Relevant Bindings no longer reports shadowed bindings (fixes #12176)
[ghc.git] / compiler / typecheck / TcErrors.hs
1 {-# LANGUAGE CPP, ScopedTypeVariables #-}
2
3 module TcErrors(
4 reportUnsolved, reportAllUnsolved, warnAllUnsolved,
5 warnDefaulting,
6
7 solverDepthErrorTcS
8 ) where
9
10 #include "HsVersions.h"
11
12 import TcRnTypes
13 import TcRnMonad
14 import TcMType
15 import TcType
16 import RnEnv( unknownNameSuggestions )
17 import Type
18 import TyCoRep
19 import Kind
20 import Unify ( tcMatchTys )
21 import Module
22 import FamInst
23 import FamInstEnv ( flattenTys )
24 import Inst
25 import InstEnv
26 import TyCon
27 import Class
28 import DataCon
29 import TcEvidence
30 import HsExpr ( UnboundVar(..) )
31 import HsBinds ( PatSynBind(..) )
32 import Name
33 import RdrName ( lookupGlobalRdrEnv, lookupGRE_Name, GlobalRdrEnv
34 , mkRdrUnqual, isLocalGRE, greSrcSpan )
35 import PrelNames ( typeableClassName, hasKey, ptrRepLiftedDataConKey
36 , ptrRepUnliftedDataConKey )
37 import Id
38 import Var
39 import VarSet
40 import VarEnv
41 import NameSet
42 import Bag
43 import ErrUtils ( ErrMsg, errDoc, pprLocErrMsg )
44 import BasicTypes
45 import ConLike ( ConLike(..) )
46 import Util
47 import FastString
48 import Outputable
49 import SrcLoc
50 import DynFlags
51 import StaticFlags ( opt_PprStyle_Debug )
52 import ListSetOps ( equivClasses )
53 import Maybes
54 import qualified GHC.LanguageExtensions as LangExt
55 import FV ( fvVarList, unionFV )
56
57 import Control.Monad ( when )
58 import Data.List ( partition, mapAccumL, nub, sortBy, unfoldr )
59 import qualified Data.Set as Set
60
61 #if __GLASGOW_HASKELL__ > 710
62 import Data.Semigroup ( Semigroup )
63 import qualified Data.Semigroup as Semigroup
64 #endif
65
66
67 {-
68 ************************************************************************
69 * *
70 \section{Errors and contexts}
71 * *
72 ************************************************************************
73
74 ToDo: for these error messages, should we note the location as coming
75 from the insts, or just whatever seems to be around in the monad just
76 now?
77
78 Note [Deferring coercion errors to runtime]
79 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
80 While developing, sometimes it is desirable to allow compilation to succeed even
81 if there are type errors in the code. Consider the following case:
82
83 module Main where
84
85 a :: Int
86 a = 'a'
87
88 main = print "b"
89
90 Even though `a` is ill-typed, it is not used in the end, so if all that we're
91 interested in is `main` it is handy to be able to ignore the problems in `a`.
92
93 Since we treat type equalities as evidence, this is relatively simple. Whenever
94 we run into a type mismatch in TcUnify, we normally just emit an error. But it
95 is always safe to defer the mismatch to the main constraint solver. If we do
96 that, `a` will get transformed into
97
98 co :: Int ~ Char
99 co = ...
100
101 a :: Int
102 a = 'a' `cast` co
103
104 The constraint solver would realize that `co` is an insoluble constraint, and
105 emit an error with `reportUnsolved`. But we can also replace the right-hand side
106 of `co` with `error "Deferred type error: Int ~ Char"`. This allows the program
107 to compile, and it will run fine unless we evaluate `a`. This is what
108 `deferErrorsToRuntime` does.
109
110 It does this by keeping track of which errors correspond to which coercion
111 in TcErrors. TcErrors.reportTidyWanteds does not print the errors
112 and does not fail if -fdefer-type-errors is on, so that we can continue
113 compilation. The errors are turned into warnings in `reportUnsolved`.
114 -}
115
116 -- | Report unsolved goals as errors or warnings. We may also turn some into
117 -- deferred run-time errors if `-fdefer-type-errors` is on.
118 reportUnsolved :: WantedConstraints -> TcM (Bag EvBind)
119 reportUnsolved wanted
120 = do { binds_var <- newTcEvBinds
121 ; defer_errors <- goptM Opt_DeferTypeErrors
122 ; warn_errors <- woptM Opt_WarnDeferredTypeErrors -- implement #10283
123 ; let type_errors | not defer_errors = TypeError
124 | warn_errors = TypeWarn
125 | otherwise = TypeDefer
126
127 ; defer_holes <- goptM Opt_DeferTypedHoles
128 ; warn_holes <- woptM Opt_WarnTypedHoles
129 ; let expr_holes | not defer_holes = HoleError
130 | warn_holes = HoleWarn
131 | otherwise = HoleDefer
132
133 ; partial_sigs <- xoptM LangExt.PartialTypeSignatures
134 ; warn_partial_sigs <- woptM Opt_WarnPartialTypeSignatures
135 ; let type_holes | not partial_sigs = HoleError
136 | warn_partial_sigs = HoleWarn
137 | otherwise = HoleDefer
138
139 ; report_unsolved (Just binds_var) False type_errors expr_holes type_holes wanted
140 ; getTcEvBinds binds_var }
141
142 -- | Report *all* unsolved goals as errors, even if -fdefer-type-errors is on
143 -- However, do not make any evidence bindings, because we don't
144 -- have any convenient place to put them.
145 -- See Note [Deferring coercion errors to runtime]
146 -- Used by solveEqualities for kind equalities
147 -- (see Note [Fail fast on kind errors] in TcSimplify]
148 -- and for simplifyDefault.
149 reportAllUnsolved :: WantedConstraints -> TcM ()
150 reportAllUnsolved wanted
151 = report_unsolved Nothing False TypeError HoleError HoleError wanted
152
153 -- | Report all unsolved goals as warnings (but without deferring any errors to
154 -- run-time). See Note [Safe Haskell Overlapping Instances Implementation] in
155 -- TcSimplify
156 warnAllUnsolved :: WantedConstraints -> TcM ()
157 warnAllUnsolved wanted
158 = report_unsolved Nothing True TypeWarn HoleWarn HoleWarn wanted
159
160 -- | Report unsolved goals as errors or warnings.
161 report_unsolved :: Maybe EvBindsVar -- cec_binds
162 -> Bool -- Errors as warnings
163 -> TypeErrorChoice -- Deferred type errors
164 -> HoleChoice -- Expression holes
165 -> HoleChoice -- Type holes
166 -> WantedConstraints -> TcM ()
167 report_unsolved mb_binds_var err_as_warn type_errors expr_holes type_holes wanted
168 | isEmptyWC wanted
169 = return ()
170 | otherwise
171 = do { traceTc "reportUnsolved (before zonking and tidying)" (ppr wanted)
172
173 ; wanted <- zonkWC wanted -- Zonk to reveal all information
174 ; env0 <- tcInitTidyEnv
175 -- If we are deferring we are going to need /all/ evidence around,
176 -- including the evidence produced by unflattening (zonkWC)
177 ; let tidy_env = tidyFreeTyCoVars env0 free_tvs
178 free_tvs = tyCoVarsOfWCList wanted
179
180 ; traceTc "reportUnsolved (after zonking and tidying):" $
181 vcat [ pprTvBndrs free_tvs
182 , ppr wanted ]
183
184 ; warn_redundant <- woptM Opt_WarnRedundantConstraints
185 ; let err_ctxt = CEC { cec_encl = []
186 , cec_tidy = tidy_env
187 , cec_defer_type_errors = type_errors
188 , cec_errors_as_warns = err_as_warn
189 , cec_expr_holes = expr_holes
190 , cec_type_holes = type_holes
191 , cec_suppress = False -- See Note [Suppressing error messages]
192 , cec_warn_redundant = warn_redundant
193 , cec_binds = mb_binds_var }
194
195 ; tc_lvl <- getTcLevel
196 ; reportWanteds err_ctxt tc_lvl wanted }
197
198 --------------------------------------------
199 -- Internal functions
200 --------------------------------------------
201
202 -- | An error Report collects messages categorised by their importance.
203 -- See Note [Error report] for details.
204 data Report
205 = Report { report_important :: [SDoc]
206 , report_relevant_bindings :: [SDoc]
207 }
208
209 {- Note [Error report]
210 The idea is that error msgs are divided into three parts: the main msg, the
211 context block (\"In the second argument of ...\"), and the relevant bindings
212 block, which are displayed in that order, with a mark to divide them. The
213 idea is that the main msg ('report_important') varies depending on the error
214 in question, but context and relevant bindings are always the same, which
215 should simplify visual parsing.
216
217 The context is added when the the Report is passed off to 'mkErrorReport'.
218 Unfortunately, unlike the context, the relevant bindings are added in
219 multiple places so they have to be in the Report.
220 -}
221
222 #if __GLASGOW_HASKELL__ > 710
223 instance Semigroup Report where
224 Report a1 b1 <> Report a2 b2 = Report (a1 ++ a2) (b1 ++ b2)
225 #endif
226
227 instance Monoid Report where
228 mempty = Report [] []
229 mappend (Report a1 b1) (Report a2 b2) = Report (a1 ++ a2) (b1 ++ b2)
230
231 -- | Put a doc into the important msgs block.
232 important :: SDoc -> Report
233 important doc = mempty { report_important = [doc] }
234
235 -- | Put a doc into the relevant bindings block.
236 relevant_bindings :: SDoc -> Report
237 relevant_bindings doc = mempty { report_relevant_bindings = [doc] }
238
239 data TypeErrorChoice -- What to do for type errors found by the type checker
240 = TypeError -- A type error aborts compilation with an error message
241 | TypeWarn -- A type error is deferred to runtime, plus a compile-time warning
242 | TypeDefer -- A type error is deferred to runtime; no error or warning at compile time
243
244 data HoleChoice
245 = HoleError -- A hole is a compile-time error
246 | HoleWarn -- Defer to runtime, emit a compile-time warning
247 | HoleDefer -- Defer to runtime, no warning
248
249 instance Outputable HoleChoice where
250 ppr HoleError = text "HoleError"
251 ppr HoleWarn = text "HoleWarn"
252 ppr HoleDefer = text "HoleDefer"
253
254 instance Outputable TypeErrorChoice where
255 ppr TypeError = text "TypeError"
256 ppr TypeWarn = text "TypeWarn"
257 ppr TypeDefer = text "TypeDefer"
258
259 data ReportErrCtxt
260 = CEC { cec_encl :: [Implication] -- Enclosing implications
261 -- (innermost first)
262 -- ic_skols and givens are tidied, rest are not
263 , cec_tidy :: TidyEnv
264
265 , cec_binds :: Maybe EvBindsVar
266 -- Nothing <=> Report all errors, including holes
267 -- Do not add any evidence bindings, because
268 -- we have no convenient place to put them
269 -- See TcErrors.reportAllUnsolved
270 -- Just ev <=> make some errors (depending on cec_defer)
271 -- into warnings, and emit evidence bindings
272 -- into 'ev' for unsolved constraints
273
274 , cec_errors_as_warns :: Bool -- Turn all errors into warnings
275 -- (except for Holes, which are
276 -- controlled by cec_type_holes and
277 -- cec_expr_holes)
278 , cec_defer_type_errors :: TypeErrorChoice -- Defer type errors until runtime
279 -- Irrelevant if cec_binds = Nothing
280
281 , cec_expr_holes :: HoleChoice -- Holes in expressions
282 , cec_type_holes :: HoleChoice -- Holes in types
283
284 , cec_warn_redundant :: Bool -- True <=> -Wredundant-constraints
285
286 , cec_suppress :: Bool -- True <=> More important errors have occurred,
287 -- so create bindings if need be, but
288 -- don't issue any more errors/warnings
289 -- See Note [Suppressing error messages]
290 }
291
292 {-
293 Note [Suppressing error messages]
294 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
295 The cec_suppress flag says "don't report any errors". Instead, just create
296 evidence bindings (as usual). It's used when more important errors have occurred.
297
298 Specifically (see reportWanteds)
299 * If there are insoluble Givens, then we are in unreachable code and all bets
300 are off. So don't report any further errors.
301 * If there are any insolubles (eg Int~Bool), here or in a nested implication,
302 then suppress errors from the simple constraints here. Sometimes the
303 simple-constraint errors are a knock-on effect of the insolubles.
304 -}
305
306 reportImplic :: ReportErrCtxt -> Implication -> TcM ()
307 reportImplic ctxt implic@(Implic { ic_skols = tvs, ic_given = given
308 , ic_wanted = wanted, ic_binds = m_evb
309 , ic_status = status, ic_info = info
310 , ic_env = tcl_env, ic_tclvl = tc_lvl })
311 | BracketSkol <- info
312 , not insoluble
313 = return () -- For Template Haskell brackets report only
314 -- definite errors. The whole thing will be re-checked
315 -- later when we plug it in, and meanwhile there may
316 -- certainly be un-satisfied constraints
317
318 | otherwise
319 = do { reportWanteds ctxt' tc_lvl wanted
320 ; traceTc "reportImplic" (ppr implic)
321 ; when (cec_warn_redundant ctxt) $
322 warnRedundantConstraints ctxt' tcl_env info' dead_givens }
323 where
324 insoluble = isInsolubleStatus status
325 (env1, tvs') = mapAccumL tidyTyCoVarBndr (cec_tidy ctxt) tvs
326 info' = tidySkolemInfo env1 info
327 implic' = implic { ic_skols = tvs'
328 , ic_given = map (tidyEvVar env1) given
329 , ic_info = info' }
330 ctxt' = ctxt { cec_tidy = env1
331 , cec_encl = implic' : cec_encl ctxt
332
333 , cec_suppress = insoluble || cec_suppress ctxt
334 -- Suppress inessential errors if there
335 -- are are insolubles anywhere in the
336 -- tree rooted here, or we've come across
337 -- a suppress-worthy constraint higher up (Trac #11541)
338
339 , cec_binds = cec_binds ctxt *> m_evb }
340 -- If cec_binds ctxt is Nothing, that means
341 -- we're reporting *all* errors. Don't change
342 -- that behavior just because we're going into
343 -- an implication.
344
345 dead_givens = case status of
346 IC_Solved { ics_dead = dead } -> dead
347 _ -> []
348
349 warnRedundantConstraints :: ReportErrCtxt -> TcLclEnv -> SkolemInfo -> [EvVar] -> TcM ()
350 warnRedundantConstraints ctxt env info ev_vars
351 | null redundant_evs
352 = return ()
353
354 | SigSkol {} <- info
355 = setLclEnv env $ -- We want to add "In the type signature for f"
356 -- to the error context, which is a bit tiresome
357 addErrCtxt (text "In" <+> ppr info) $
358 do { env <- getLclEnv
359 ; msg <- mkErrorReport ctxt env (important doc)
360 ; reportWarning (Reason Opt_WarnRedundantConstraints) msg }
361
362 | otherwise -- But for InstSkol there already *is* a surrounding
363 -- "In the instance declaration for Eq [a]" context
364 -- and we don't want to say it twice. Seems a bit ad-hoc
365 = do { msg <- mkErrorReport ctxt env (important doc)
366 ; reportWarning (Reason Opt_WarnRedundantConstraints) msg }
367 where
368 doc = text "Redundant constraint" <> plural redundant_evs <> colon
369 <+> pprEvVarTheta redundant_evs
370
371 redundant_evs = case info of -- See Note [Redundant constraints in instance decls]
372 InstSkol -> filterOut improving ev_vars
373 _ -> ev_vars
374
375 improving ev_var = any isImprovementPred $
376 transSuperClasses (idType ev_var)
377
378 {- Note [Redundant constraints in instance decls]
379 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
380 For instance declarations, we don't report unused givens if
381 they can give rise to improvement. Example (Trac #10100):
382 class Add a b ab | a b -> ab, a ab -> b
383 instance Add Zero b b
384 instance Add a b ab => Add (Succ a) b (Succ ab)
385 The context (Add a b ab) for the instance is clearly unused in terms
386 of evidence, since the dictionary has no feilds. But it is still
387 needed! With the context, a wanted constraint
388 Add (Succ Zero) beta (Succ Zero)
389 we will reduce to (Add Zero beta Zero), and thence we get beta := Zero.
390 But without the context we won't find beta := Zero.
391
392 This only matters in instance declarations..
393 -}
394
395 reportWanteds :: ReportErrCtxt -> TcLevel -> WantedConstraints -> TcM ()
396 reportWanteds ctxt tc_lvl (WC { wc_simple = simples, wc_insol = insols, wc_impl = implics })
397 = do { traceTc "reportWanteds" (vcat [ text "Simples =" <+> ppr simples
398 , text "Suppress =" <+> ppr (cec_suppress ctxt)])
399 ; let tidy_cts = bagToList (mapBag (tidyCt env) (insols `unionBags` simples))
400
401 -- First deal with things that are utterly wrong
402 -- Like Int ~ Bool (incl nullary TyCons)
403 -- or Int ~ t a (AppTy on one side)
404 -- These ones are not suppressed by the incoming context
405 ; let ctxt_for_insols = ctxt { cec_suppress = False }
406 ; (ctxt1, cts1) <- tryReporters ctxt_for_insols report1 tidy_cts
407
408 -- Now all the other constraints. We suppress errors here if
409 -- any of the first batch failed, or if the enclosing context
410 -- says to suppress
411 ; let ctxt2 = ctxt { cec_suppress = cec_suppress ctxt || cec_suppress ctxt1 }
412 ; (_, leftovers) <- tryReporters ctxt2 report2 cts1
413 ; MASSERT2( null leftovers, ppr leftovers )
414
415 -- All the Derived ones have been filtered out of simples
416 -- by the constraint solver. This is ok; we don't want
417 -- to report unsolved Derived goals as errors
418 -- See Note [Do not report derived but soluble errors]
419
420 ; mapBagM_ (reportImplic ctxt2) implics }
421 -- NB ctxt1: don't suppress inner insolubles if there's only a
422 -- wanted insoluble here; but do suppress inner insolubles
423 -- if there's a *given* insoluble here (= inaccessible code)
424 where
425 env = cec_tidy ctxt
426
427 -- report1: ones that should *not* be suppresed by
428 -- an insoluble somewhere else in the tree
429 -- It's crucial that anything that is considered insoluble
430 -- (see TcRnTypes.trulyInsoluble) is caught here, otherwise
431 -- we might suppress its error message, and proceed on past
432 -- type checking to get a Lint error later
433 report1 = [ ("custom_error", is_user_type_error,
434 True, mkUserTypeErrorReporter)
435 , ("insoluble1", is_given_eq, True, mkGroupReporter mkEqErr)
436 , ("insoluble2", utterly_wrong, True, mkGroupReporter mkEqErr)
437 , ("skolem eq1", very_wrong, True, mkSkolReporter)
438 , ("skolem eq2", skolem_eq, True, mkSkolReporter)
439 , ("non-tv eq", non_tv_eq, True, mkSkolReporter)
440 , ("Out of scope", is_out_of_scope, True, mkHoleReporter)
441 , ("Holes", is_hole, False, mkHoleReporter)
442
443 -- The only remaining equalities are alpha ~ ty,
444 -- where alpha is untouchable; and representational equalities
445 , ("Other eqs", is_equality, False, mkGroupReporter mkEqErr) ]
446
447 -- report2: we suppress these if there are insolubles elsewhere in the tree
448 report2 = [ ("Implicit params", is_ip, False, mkGroupReporter mkIPErr)
449 , ("Irreds", is_irred, False, mkGroupReporter mkIrredErr)
450 , ("Dicts", is_dict, False, mkGroupReporter mkDictErr) ]
451
452 -- rigid_nom_eq, rigid_nom_tv_eq,
453 is_hole, is_dict,
454 is_equality, is_ip, is_irred :: Ct -> PredTree -> Bool
455
456 is_given_eq ct pred
457 | EqPred {} <- pred = arisesFromGivens ct
458 | otherwise = False
459 -- I think all given residuals are equalities
460
461 -- Things like (Int ~N Bool)
462 utterly_wrong _ (EqPred NomEq ty1 ty2) = isRigidTy ty1 && isRigidTy ty2
463 utterly_wrong _ _ = False
464
465 -- Things like (a ~N Int)
466 very_wrong _ (EqPred NomEq ty1 ty2) = isSkolemTy tc_lvl ty1 && isRigidTy ty2
467 very_wrong _ _ = False
468
469 -- Things like (a ~N b) or (a ~N F Bool)
470 skolem_eq _ (EqPred NomEq ty1 _) = isSkolemTy tc_lvl ty1
471 skolem_eq _ _ = False
472
473 -- Things like (F a ~N Int)
474 non_tv_eq _ (EqPred NomEq ty1 _) = not (isTyVarTy ty1)
475 non_tv_eq _ _ = False
476
477 -- rigid_nom_eq _ pred = isRigidEqPred tc_lvl pred
478 --
479 -- rigid_nom_tv_eq _ pred
480 -- | EqPred _ ty1 _ <- pred = isRigidEqPred tc_lvl pred && isTyVarTy ty1
481 -- | otherwise = False
482
483 is_out_of_scope ct _ = isOutOfScopeCt ct
484 is_hole ct _ = isHoleCt ct
485
486 is_user_type_error ct _ = isUserTypeErrorCt ct
487
488 is_equality _ (EqPred {}) = True
489 is_equality _ _ = False
490
491 is_dict _ (ClassPred {}) = True
492 is_dict _ _ = False
493
494 is_ip _ (ClassPred cls _) = isIPClass cls
495 is_ip _ _ = False
496
497 is_irred _ (IrredPred {}) = True
498 is_irred _ _ = False
499
500
501 ---------------
502 isSkolemTy :: TcLevel -> Type -> Bool
503 -- The type is a skolem tyvar
504 isSkolemTy tc_lvl ty
505 | Just tv <- getTyVar_maybe ty
506 = isSkolemTyVar tv
507 || (isSigTyVar tv && isTouchableMetaTyVar tc_lvl tv)
508 -- The last case is for touchable SigTvs
509 -- we postpone untouchables to a latter test (too obscure)
510
511 | otherwise
512 = False
513
514 isTyFun_maybe :: Type -> Maybe TyCon
515 isTyFun_maybe ty = case tcSplitTyConApp_maybe ty of
516 Just (tc,_) | isTypeFamilyTyCon tc -> Just tc
517 _ -> Nothing
518
519 --------------------------------------------
520 -- Reporters
521 --------------------------------------------
522
523 type Reporter
524 = ReportErrCtxt -> [Ct] -> TcM ()
525 type ReporterSpec
526 = ( String -- Name
527 , Ct -> PredTree -> Bool -- Pick these ones
528 , Bool -- True <=> suppress subsequent reporters
529 , Reporter) -- The reporter itself
530
531 mkSkolReporter :: Reporter
532 -- Suppress duplicates with either the same LHS, or same location
533 mkSkolReporter ctxt cts
534 = mapM_ (reportGroup mkEqErr ctxt) (group cts)
535 where
536 group [] = []
537 group (ct:cts) = (ct : yeses) : group noes
538 where
539 (yeses, noes) = partition (group_with ct) cts
540
541 group_with ct1 ct2
542 | EQ <- cmp_loc ct1 ct2 = True
543 | eq_lhs_type ct1 ct2 = True
544 | otherwise = False
545
546 mkHoleReporter :: Reporter
547 -- Reports errors one at a time
548 mkHoleReporter ctxt
549 = mapM_ $ \ct -> do { err <- mkHoleError ctxt ct
550 ; maybeReportHoleError ctxt ct err
551 ; maybeAddDeferredHoleBinding ctxt err ct }
552
553 mkUserTypeErrorReporter :: Reporter
554 mkUserTypeErrorReporter ctxt
555 = mapM_ $ \ct -> do { err <- mkUserTypeError ctxt ct
556 ; maybeReportError ctxt err }
557
558 mkUserTypeError :: ReportErrCtxt -> Ct -> TcM ErrMsg
559 mkUserTypeError ctxt ct = mkErrorMsgFromCt ctxt ct
560 $ important
561 $ pprUserTypeErrorTy
562 $ case getUserTypeErrorMsg ct of
563 Just msg -> msg
564 Nothing -> pprPanic "mkUserTypeError" (ppr ct)
565
566
567 mkGroupReporter :: (ReportErrCtxt -> [Ct] -> TcM ErrMsg)
568 -- Make error message for a group
569 -> Reporter -- Deal with lots of constraints
570 -- Group together errors from same location,
571 -- and report only the first (to avoid a cascade)
572 mkGroupReporter mk_err ctxt cts
573 = mapM_ (reportGroup mk_err ctxt) (equivClasses cmp_loc cts)
574
575 eq_lhs_type :: Ct -> Ct -> Bool
576 eq_lhs_type ct1 ct2
577 = case (classifyPredType (ctPred ct1), classifyPredType (ctPred ct2)) of
578 (EqPred eq_rel1 ty1 _, EqPred eq_rel2 ty2 _) ->
579 (eq_rel1 == eq_rel2) && (ty1 `eqType` ty2)
580 _ -> pprPanic "mkSkolReporter" (ppr ct1 $$ ppr ct2)
581
582 cmp_loc :: Ct -> Ct -> Ordering
583 cmp_loc ct1 ct2 = ctLocSpan (ctLoc ct1) `compare` ctLocSpan (ctLoc ct2)
584
585 reportGroup :: (ReportErrCtxt -> [Ct] -> TcM ErrMsg) -> ReportErrCtxt
586 -> [Ct] -> TcM ()
587 reportGroup mk_err ctxt cts =
588 case partition isMonadFailInstanceMissing cts of
589 -- Only warn about missing MonadFail constraint when
590 -- there are no other missing contstraints!
591 (monadFailCts, []) ->
592 do { err <- mk_err ctxt monadFailCts
593 ; reportWarning (Reason Opt_WarnMissingMonadFailInstances) err }
594
595 (_, cts') -> do { err <- mk_err ctxt cts'
596 ; maybeReportError ctxt err
597 -- But see Note [Always warn with -fdefer-type-errors]
598 ; traceTc "reportGroup" (ppr cts')
599 ; mapM_ (addDeferredBinding ctxt err) cts' }
600 -- Add deferred bindings for all
601 -- Redundant if we are going to abort compilation,
602 -- but that's hard to know for sure, and if we don't
603 -- abort, we need bindings for all (e.g. Trac #12156)
604 where
605 isMonadFailInstanceMissing ct =
606 case ctLocOrigin (ctLoc ct) of
607 FailablePattern _pat -> True
608 _otherwise -> False
609
610 maybeReportHoleError :: ReportErrCtxt -> Ct -> ErrMsg -> TcM ()
611 maybeReportHoleError ctxt ct err
612 -- When -XPartialTypeSignatures is on, warnings (instead of errors) are
613 -- generated for holes in partial type signatures.
614 -- Unless -fwarn_partial_type_signatures is not on,
615 -- in which case the messages are discarded.
616 | isTypeHoleCt ct
617 = -- For partial type signatures, generate warnings only, and do that
618 -- only if -fwarn_partial_type_signatures is on
619 case cec_type_holes ctxt of
620 HoleError -> reportError err
621 HoleWarn -> reportWarning (Reason Opt_WarnPartialTypeSignatures) err
622 HoleDefer -> return ()
623
624 -- Otherwise this is a typed hole in an expression
625 | otherwise
626 = -- If deferring, report a warning only if -Wtyped-holds is on
627 case cec_expr_holes ctxt of
628 HoleError -> reportError err
629 HoleWarn -> reportWarning (Reason Opt_WarnTypedHoles) err
630 HoleDefer -> return ()
631
632 maybeReportError :: ReportErrCtxt -> ErrMsg -> TcM ()
633 -- Report the error and/or make a deferred binding for it
634 maybeReportError ctxt err
635 | cec_suppress ctxt -- Some worse error has occurred;
636 = return () -- so suppress this error/warning
637
638 | cec_errors_as_warns ctxt
639 = reportWarning NoReason err
640
641 | otherwise
642 = case cec_defer_type_errors ctxt of
643 TypeDefer -> return ()
644 TypeWarn -> reportWarning (Reason Opt_WarnDeferredTypeErrors) err
645 TypeError -> reportError err
646
647 addDeferredBinding :: ReportErrCtxt -> ErrMsg -> Ct -> TcM ()
648 -- See Note [Deferring coercion errors to runtime]
649 addDeferredBinding ctxt err ct
650 | CtWanted { ctev_pred = pred, ctev_dest = dest } <- ctEvidence ct
651 -- Only add deferred bindings for Wanted constraints
652 , Just ev_binds_var <- cec_binds ctxt -- We have somewhere to put the bindings
653 = do { dflags <- getDynFlags
654 ; let err_msg = pprLocErrMsg err
655 err_fs = mkFastString $ showSDoc dflags $
656 err_msg $$ text "(deferred type error)"
657 err_tm = EvDelayedError pred err_fs
658
659 ; case dest of
660 EvVarDest evar
661 -> addTcEvBind ev_binds_var $ mkWantedEvBind evar err_tm
662 HoleDest hole
663 -> do { -- See Note [Deferred errors for coercion holes]
664 evar <- newEvVar pred
665 ; addTcEvBind ev_binds_var $ mkWantedEvBind evar err_tm
666 ; fillCoercionHole hole (mkTcCoVarCo evar) }}
667
668 | otherwise -- Do not set any evidence for Given/Derived
669 = return ()
670
671 maybeAddDeferredHoleBinding :: ReportErrCtxt -> ErrMsg -> Ct -> TcM ()
672 maybeAddDeferredHoleBinding ctxt err ct
673 | isExprHoleCt ct
674 = addDeferredBinding ctxt err ct -- Only add bindings for holes in expressions
675 | otherwise -- not for holes in partial type signatures
676 = return ()
677
678 tryReporters :: ReportErrCtxt -> [ReporterSpec] -> [Ct] -> TcM (ReportErrCtxt, [Ct])
679 -- Use the first reporter in the list whose predicate says True
680 tryReporters ctxt reporters cts
681 = do { traceTc "tryReporters {" (ppr cts)
682 ; (ctxt', cts') <- go ctxt reporters cts
683 ; traceTc "tryReporters }" (ppr cts')
684 ; return (ctxt', cts') }
685 where
686 go ctxt [] cts
687 = return (ctxt, cts)
688
689 go ctxt (r : rs) cts
690 = do { (ctxt', cts') <- tryReporter ctxt r cts
691 ; go ctxt' rs cts' }
692 -- Carry on with the rest, because we must make
693 -- deferred bindings for them if we have -fdefer-type-errors
694 -- But suppress their error messages
695
696 tryReporter :: ReportErrCtxt -> ReporterSpec -> [Ct] -> TcM (ReportErrCtxt, [Ct])
697 tryReporter ctxt (str, keep_me, suppress_after, reporter) cts
698 | null yeses = return (ctxt, cts)
699 | otherwise = do { traceTc "tryReporter{ " (text str <+> ppr yeses)
700 ; reporter ctxt yeses
701 ; let ctxt' = ctxt { cec_suppress = suppress_after || cec_suppress ctxt }
702 ; traceTc "tryReporter end }" (text str <+> ppr (cec_suppress ctxt) <+> ppr suppress_after)
703 ; return (ctxt', nos) }
704 where
705 (yeses, nos) = partition (\ct -> keep_me ct (classifyPredType (ctPred ct))) cts
706
707
708 pprArising :: CtOrigin -> SDoc
709 -- Used for the main, top-level error message
710 -- We've done special processing for TypeEq, KindEq, Given
711 pprArising (TypeEqOrigin {}) = empty
712 pprArising (KindEqOrigin {}) = empty
713 pprArising (GivenOrigin {}) = empty
714 pprArising orig = pprCtOrigin orig
715
716 -- Add the "arising from..." part to a message about bunch of dicts
717 addArising :: CtOrigin -> SDoc -> SDoc
718 addArising orig msg = hang msg 2 (pprArising orig)
719
720 pprWithArising :: [Ct] -> (CtLoc, SDoc)
721 -- Print something like
722 -- (Eq a) arising from a use of x at y
723 -- (Show a) arising from a use of p at q
724 -- Also return a location for the error message
725 -- Works for Wanted/Derived only
726 pprWithArising []
727 = panic "pprWithArising"
728 pprWithArising (ct:cts)
729 | null cts
730 = (loc, addArising (ctLocOrigin loc)
731 (pprTheta [ctPred ct]))
732 | otherwise
733 = (loc, vcat (map ppr_one (ct:cts)))
734 where
735 loc = ctLoc ct
736 ppr_one ct' = hang (parens (pprType (ctPred ct')))
737 2 (pprCtLoc (ctLoc ct'))
738
739 mkErrorMsgFromCt :: ReportErrCtxt -> Ct -> Report -> TcM ErrMsg
740 mkErrorMsgFromCt ctxt ct report
741 = mkErrorReport ctxt (ctLocEnv (ctLoc ct)) report
742
743 mkErrorReport :: ReportErrCtxt -> TcLclEnv -> Report -> TcM ErrMsg
744 mkErrorReport ctxt tcl_env (Report important relevant_bindings)
745 = do { context <- mkErrInfo (cec_tidy ctxt) (tcl_ctxt tcl_env)
746 ; mkErrDocAt (RealSrcSpan (tcl_loc tcl_env))
747 (errDoc important [context] relevant_bindings)
748 }
749
750 type UserGiven = Implication
751
752 getUserGivens :: ReportErrCtxt -> [UserGiven]
753 -- One item for each enclosing implication
754 getUserGivens (CEC {cec_encl = implics}) = getUserGivensFromImplics implics
755
756 getUserGivensFromImplics :: [Implication] -> [UserGiven]
757 getUserGivensFromImplics implics
758 = reverse (filterOut (null . ic_given) implics)
759
760 {-
761 Note [Always warn with -fdefer-type-errors]
762 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
763 When -fdefer-type-errors is on we warn about *all* type errors, even
764 if cec_suppress is on. This can lead to a lot more warnings than you
765 would get errors without -fdefer-type-errors, but if we suppress any of
766 them you might get a runtime error that wasn't warned about at compile
767 time.
768
769 This is an easy design choice to change; just flip the order of the
770 first two equations for maybeReportError
771
772 To be consistent, we should also report multiple warnings from a single
773 location in mkGroupReporter, when -fdefer-type-errors is on. But that
774 is perhaps a bit *over*-consistent! Again, an easy choice to change.
775
776 With #10283, you can now opt out of deferred type error warnings.
777
778 Note [Deferred errors for coercion holes]
779 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
780 Suppose we need to defer a type error where the destination for the evidence
781 is a coercion hole. We can't just put the error in the hole, because we can't
782 make an erroneous coercion. (Remember that coercions are erased for runtime.)
783 Instead, we invent a new EvVar, bind it to an error and then make a coercion
784 from that EvVar, filling the hole with that coercion. Because coercions'
785 types are unlifted, the error is guaranteed to be hit before we get to the
786 coercion.
787
788 Note [Do not report derived but soluble errors]
789 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
790 The wc_simples include Derived constraints that have not been solved, but are
791 not insoluble (in that case they'd be in wc_insols). We do not want to report
792 these as errors:
793
794 * Superclass constraints. If we have an unsolved [W] Ord a, we'll also have
795 an unsolved [D] Eq a, and we do not want to report that; it's just noise.
796
797 * Functional dependencies. For givens, consider
798 class C a b | a -> b
799 data T a where
800 MkT :: C a d => [d] -> T a
801 f :: C a b => T a -> F Int
802 f (MkT xs) = length xs
803 Then we get a [D] b~d. But there *is* a legitimate call to
804 f, namely f (MkT [True]) :: T Bool, in which b=d. So we should
805 not reject the program.
806
807 For wanteds, something similar
808 data T a where
809 MkT :: C Int b => a -> b -> T a
810 g :: C Int c => c -> ()
811 f :: T a -> ()
812 f (MkT x y) = g x
813 Here we get [G] C Int b, [W] C Int a, hence [D] a~b.
814 But again f (MkT True True) is a legitimate call.
815
816 (We leave the Deriveds in wc_simple until reportErrors, so that we don't lose
817 derived superclasses between iterations of the solver.)
818
819 For functional dependencies, here is a real example,
820 stripped off from libraries/utf8-string/Codec/Binary/UTF8/Generic.hs
821
822 class C a b | a -> b
823 g :: C a b => a -> b -> ()
824 f :: C a b => a -> b -> ()
825 f xa xb =
826 let loop = g xa
827 in loop xb
828
829 We will first try to infer a type for loop, and we will succeed:
830 C a b' => b' -> ()
831 Subsequently, we will type check (loop xb) and all is good. But,
832 recall that we have to solve a final implication constraint:
833 C a b => (C a b' => .... cts from body of loop .... ))
834 And now we have a problem as we will generate an equality b ~ b' and fail to
835 solve it.
836
837
838 ************************************************************************
839 * *
840 Irreducible predicate errors
841 * *
842 ************************************************************************
843 -}
844
845 mkIrredErr :: ReportErrCtxt -> [Ct] -> TcM ErrMsg
846 mkIrredErr ctxt cts
847 = do { (ctxt, binds_msg, ct1) <- relevantBindings True ctxt ct1
848 ; let orig = ctOrigin ct1
849 msg = couldNotDeduce (getUserGivens ctxt) (map ctPred cts, orig)
850 ; mkErrorMsgFromCt ctxt ct1 $
851 important msg `mappend` relevant_bindings binds_msg }
852 where
853 (ct1:_) = cts
854
855 ----------------
856 mkHoleError :: ReportErrCtxt -> Ct -> TcM ErrMsg
857 mkHoleError _ctxt ct@(CHoleCan { cc_hole = ExprHole (OutOfScope occ rdr_env0) })
858 -- Out-of-scope variables, like 'a', where 'a' isn't bound; suggest possible
859 -- in-scope variables in the message, and note inaccessible exact matches
860 = do { dflags <- getDynFlags
861 ; imp_info <- getImports
862 ; let suggs_msg = unknownNameSuggestions dflags rdr_env0
863 (tcl_rdr lcl_env) imp_info rdr
864 ; rdr_env <- getGlobalRdrEnv
865 ; splice_locs <- getTopLevelSpliceLocs
866 ; let match_msgs = mk_match_msgs rdr_env splice_locs
867 ; mkErrDocAt (RealSrcSpan err_loc) $
868 errDoc [out_of_scope_msg] [] (match_msgs ++ [suggs_msg]) }
869
870 where
871 rdr = mkRdrUnqual occ
872 ct_loc = ctLoc ct
873 lcl_env = ctLocEnv ct_loc
874 err_loc = tcl_loc lcl_env
875 hole_ty = ctEvPred (ctEvidence ct)
876 boring_type = isTyVarTy hole_ty
877
878 out_of_scope_msg -- Print v :: ty only if the type has structure
879 | boring_type = hang herald 2 (ppr occ)
880 | otherwise = hang herald 2 (pp_with_type occ hole_ty)
881
882 herald | isDataOcc occ = text "Data constructor not in scope:"
883 | otherwise = text "Variable not in scope:"
884
885 -- Indicate if the out-of-scope variable exactly (and unambiguously) matches
886 -- a top-level binding in a later inter-splice group; see Note [OutOfScope
887 -- exact matches]
888 mk_match_msgs rdr_env splice_locs
889 = let gres = filter isLocalGRE (lookupGlobalRdrEnv rdr_env occ)
890 in case gres of
891 [gre]
892 | RealSrcSpan bind_loc <- greSrcSpan gre
893 -- Find splice between the unbound variable and the match; use
894 -- lookupLE, not lookupLT, since match could be in the splice
895 , Just th_loc <- Set.lookupLE bind_loc splice_locs
896 , err_loc < th_loc
897 -> [mk_bind_scope_msg bind_loc th_loc]
898 _ -> []
899
900 mk_bind_scope_msg bind_loc th_loc
901 | is_th_bind
902 = hang (quotes (ppr occ) <+> parens (text "splice on" <+> th_rng))
903 2 (text "is not in scope before line" <+> int th_start_ln)
904 | otherwise
905 = hang (quotes (ppr occ) <+> bind_rng <+> text "is not in scope")
906 2 (text "before the splice on" <+> th_rng)
907 where
908 bind_rng = parens (text "line" <+> int bind_ln)
909 th_rng
910 | th_start_ln == th_end_ln = single
911 | otherwise = multi
912 single = text "line" <+> int th_start_ln
913 multi = text "lines" <+> int th_start_ln <> text "-" <> int th_end_ln
914 bind_ln = srcSpanStartLine bind_loc
915 th_start_ln = srcSpanStartLine th_loc
916 th_end_ln = srcSpanEndLine th_loc
917 is_th_bind = th_loc `containsSpan` bind_loc
918
919 mkHoleError ctxt ct@(CHoleCan { cc_hole = hole })
920 -- Explicit holes, like "_" or "_f"
921 = do { (ctxt, binds_msg, ct) <- relevantBindings False ctxt ct
922 -- The 'False' means "don't filter the bindings"; see Trac #8191
923 ; mkErrorMsgFromCt ctxt ct $
924 important hole_msg `mappend` relevant_bindings binds_msg }
925
926 where
927 occ = holeOcc hole
928 hole_ty = ctEvPred (ctEvidence ct)
929 tyvars = tyCoVarsOfTypeList hole_ty
930
931 hole_msg = case hole of
932 ExprHole {} -> vcat [ hang (text "Found hole:")
933 2 (pp_with_type occ hole_ty)
934 , tyvars_msg, expr_hole_hint ]
935 TypeHole {} -> vcat [ hang (text "Found type wildcard" <+>
936 quotes (ppr occ))
937 2 (text "standing for" <+>
938 quotes (pprType hole_ty))
939 , tyvars_msg, type_hole_hint ]
940
941 tyvars_msg = ppUnless (null tyvars) $
942 text "Where:" <+> vcat (map loc_msg tyvars)
943
944 type_hole_hint
945 | HoleError <- cec_type_holes ctxt
946 = text "To use the inferred type, enable PartialTypeSignatures"
947 | otherwise
948 = empty
949
950 expr_hole_hint -- Give hint for, say, f x = _x
951 | lengthFS (occNameFS occ) > 1 -- Don't give this hint for plain "_"
952 = text "Or perhaps" <+> quotes (ppr occ)
953 <+> text "is mis-spelled, or not in scope"
954 | otherwise
955 = empty
956
957 loc_msg tv
958 | isTyVar tv
959 = case tcTyVarDetails tv of
960 SkolemTv {} -> pprSkol (cec_encl ctxt) tv
961 MetaTv {} -> quotes (ppr tv) <+> text "is an ambiguous type variable"
962 det -> pprTcTyVarDetails det
963 | otherwise
964 = sdocWithDynFlags $ \dflags ->
965 if gopt Opt_PrintExplicitCoercions dflags
966 then quotes (ppr tv) <+> text "is a coercion variable"
967 else empty
968
969 mkHoleError _ ct = pprPanic "mkHoleError" (ppr ct)
970
971 pp_with_type :: OccName -> Type -> SDoc
972 pp_with_type occ ty = hang (pprPrefixOcc occ) 2 (dcolon <+> pprType ty)
973
974 ----------------
975 mkIPErr :: ReportErrCtxt -> [Ct] -> TcM ErrMsg
976 mkIPErr ctxt cts
977 = do { (ctxt, binds_msg, ct1) <- relevantBindings True ctxt ct1
978 ; let orig = ctOrigin ct1
979 preds = map ctPred cts
980 givens = getUserGivens ctxt
981 msg | null givens
982 = addArising orig $
983 sep [ text "Unbound implicit parameter" <> plural cts
984 , nest 2 (pprTheta preds) ]
985 | otherwise
986 = couldNotDeduce givens (preds, orig)
987
988 ; mkErrorMsgFromCt ctxt ct1 $
989 important msg `mappend` relevant_bindings binds_msg }
990 where
991 (ct1:_) = cts
992
993 {-
994 Note [OutOfScope exact matches]
995 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
996 When constructing an out-of-scope error message, we not only generate a list of
997 possible in-scope alternatives but also search for an exact, unambiguous match
998 in a later inter-splice group. If we find such a match, we report its presence
999 (and indirectly, its scope) in the message. For example, if a module A contains
1000 the following declarations,
1001
1002 foo :: Int
1003 foo = x
1004
1005 $(return []) -- Empty top-level splice
1006
1007 x :: Int
1008 x = 23
1009
1010 we will issue an error similar to
1011
1012 A.hs:6:7: error:
1013 • Variable not in scope: x :: Int
1014 • ‘x’ (line 11) is not in scope before the splice on line 8
1015
1016 By providing information about the match, we hope to clarify why declaring a
1017 variable after a top-level splice but using it before the splice generates an
1018 out-of-scope error (a situation which is often confusing to Haskell newcomers).
1019
1020 Note that if we find multiple exact matches to the out-of-scope variable
1021 (hereafter referred to as x), we report nothing. Such matches can only be
1022 duplicate record fields, as the presence of any other duplicate top-level
1023 declarations would have already halted compilation. But if these record fields
1024 are declared in a later inter-splice group, then so too are their corresponding
1025 types. Thus, these types must not occur in the inter-splice group containing x
1026 (any unknown types would have already been reported), and so the matches to the
1027 record fields are most likely coincidental.
1028
1029 One oddity of the exact match portion of the error message is that we specify
1030 where the match to x is NOT in scope. Why not simply state where the match IS
1031 in scope? It most cases, this would be just as easy and perhaps a little
1032 clearer for the user. But now consider the following example:
1033
1034 {-# LANGUAGE TemplateHaskell #-}
1035
1036 module A where
1037
1038 import Language.Haskell.TH
1039 import Language.Haskell.TH.Syntax
1040
1041 foo = x
1042
1043 $(do -------------------------------------------------
1044 ds <- [d| ok1 = x
1045 |]
1046 addTopDecls ds
1047 return [])
1048
1049 bar = $(do
1050 ds <- [d| x = 23
1051 ok2 = x
1052 |]
1053 addTopDecls ds
1054 litE $ stringL "hello")
1055
1056 $(return []) -----------------------------------------
1057
1058 ok3 = x
1059
1060 Here, x is out-of-scope in the declaration of foo, and so we report
1061
1062 A.hs:8:7: error:
1063 • Variable not in scope: x
1064 • ‘x’ (line 16) is not in scope before the splice on lines 10-14
1065
1066 If we instead reported where x IS in scope, we would have to state that it is in
1067 scope after the second top-level splice as well as among all the top-level
1068 declarations added by both calls to addTopDecls. But doing so would not only
1069 add complexity to the code but also overwhelm the user with unneeded
1070 information.
1071
1072 The logic which determines where x is not in scope is straightforward: it simply
1073 finds the last top-level splice which occurs after x but before (or at) the
1074 match to x (assuming such a splice exists). In most cases, the check that the
1075 splice occurs after x acts only as a sanity check. For example, when the match
1076 to x is a non-TH top-level declaration and a splice S occurs before the match,
1077 then x must precede S; otherwise, it would be in scope. But when dealing with
1078 addTopDecls, this check serves a practical purpose. Consider the following
1079 declarations:
1080
1081 $(do
1082 ds <- [d| ok = x
1083 x = 23
1084 |]
1085 addTopDecls ds
1086 return [])
1087
1088 foo = x
1089
1090 In this case, x is not in scope in the declaration for foo. Since x occurs
1091 AFTER the splice containing the match, the logic does not find any splices after
1092 x but before or at its match, and so we report nothing about x's scope. If we
1093 had not checked whether x occurs before the splice, we would have instead
1094 reported that x is not in scope before the splice. While correct, such an error
1095 message is more likely to confuse than to enlighten.
1096 -}
1097
1098 {-
1099 ************************************************************************
1100 * *
1101 Equality errors
1102 * *
1103 ************************************************************************
1104
1105 Note [Inaccessible code]
1106 ~~~~~~~~~~~~~~~~~~~~~~~~
1107 Consider
1108 data T a where
1109 T1 :: T a
1110 T2 :: T Bool
1111
1112 f :: (a ~ Int) => T a -> Int
1113 f T1 = 3
1114 f T2 = 4 -- Unreachable code
1115
1116 Here the second equation is unreachable. The original constraint
1117 (a~Int) from the signature gets rewritten by the pattern-match to
1118 (Bool~Int), so the danger is that we report the error as coming from
1119 the *signature* (Trac #7293). So, for Given errors we replace the
1120 env (and hence src-loc) on its CtLoc with that from the immediately
1121 enclosing implication.
1122
1123 Note [Error messages for untouchables]
1124 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1125 Consider (Trac #9109)
1126 data G a where { GBool :: G Bool }
1127 foo x = case x of GBool -> True
1128
1129 Here we can't solve (t ~ Bool), where t is the untouchable result
1130 meta-var 't', because of the (a ~ Bool) from the pattern match.
1131 So we infer the type
1132 f :: forall a t. G a -> t
1133 making the meta-var 't' into a skolem. So when we come to report
1134 the unsolved (t ~ Bool), t won't look like an untouchable meta-var
1135 any more. So we don't assert that it is.
1136 -}
1137
1138 mkEqErr :: ReportErrCtxt -> [Ct] -> TcM ErrMsg
1139 -- Don't have multiple equality errors from the same location
1140 -- E.g. (Int,Bool) ~ (Bool,Int) one error will do!
1141 mkEqErr ctxt (ct:_) = mkEqErr1 ctxt ct
1142 mkEqErr _ [] = panic "mkEqErr"
1143
1144 mkEqErr1 :: ReportErrCtxt -> Ct -> TcM ErrMsg
1145 mkEqErr1 ctxt ct
1146 | arisesFromGivens ct
1147 = do { (ctxt, binds_msg, ct) <- relevantBindings True ctxt ct
1148 ; let (given_loc, given_msg) = mk_given (ctLoc ct) (cec_encl ctxt)
1149 ; dflags <- getDynFlags
1150 ; let report = important given_msg `mappend` relevant_bindings binds_msg
1151 ; mkEqErr_help dflags ctxt report
1152 (setCtLoc ct given_loc) -- Note [Inaccessible code]
1153 Nothing ty1 ty2 }
1154
1155 | otherwise -- Wanted or derived
1156 = do { (ctxt, binds_msg, ct) <- relevantBindings True ctxt ct
1157 ; rdr_env <- getGlobalRdrEnv
1158 ; fam_envs <- tcGetFamInstEnvs
1159 ; exp_syns <- goptM Opt_PrintExpandedSynonyms
1160 ; let (keep_going, is_oriented, wanted_msg)
1161 = mk_wanted_extra (ctLoc ct) exp_syns
1162 coercible_msg = case ctEqRel ct of
1163 NomEq -> empty
1164 ReprEq -> mkCoercibleExplanation rdr_env fam_envs ty1 ty2
1165 ; dflags <- getDynFlags
1166 ; traceTc "mkEqErr1" (ppr ct $$ pprCtOrigin (ctOrigin ct))
1167 ; let report = mconcat [important wanted_msg, important coercible_msg,
1168 relevant_bindings binds_msg]
1169 ; if keep_going
1170 then mkEqErr_help dflags ctxt report ct is_oriented ty1 ty2
1171 else mkErrorMsgFromCt ctxt ct report }
1172 where
1173 (ty1, ty2) = getEqPredTys (ctPred ct)
1174
1175 mk_given :: CtLoc -> [Implication] -> (CtLoc, SDoc)
1176 -- For given constraints we overwrite the env (and hence src-loc)
1177 -- with one from the implication. See Note [Inaccessible code]
1178 mk_given loc [] = (loc, empty)
1179 mk_given loc (implic : _) = (setCtLocEnv loc (ic_env implic)
1180 , hang (text "Inaccessible code in")
1181 2 (ppr (ic_info implic)))
1182
1183 -- If the types in the error message are the same as the types
1184 -- we are unifying, don't add the extra expected/actual message
1185 mk_wanted_extra :: CtLoc -> Bool -> (Bool, Maybe SwapFlag, SDoc)
1186 mk_wanted_extra loc expandSyns
1187 = case ctLocOrigin loc of
1188 orig@TypeEqOrigin {} -> mkExpectedActualMsg ty1 ty2 orig
1189 t_or_k expandSyns
1190 where
1191 t_or_k = ctLocTypeOrKind_maybe loc
1192
1193 KindEqOrigin cty1 mb_cty2 sub_o sub_t_or_k
1194 -> (True, Nothing, msg1 $$ msg2)
1195 where
1196 sub_what = case sub_t_or_k of Just KindLevel -> text "kinds"
1197 _ -> text "types"
1198 msg1 = sdocWithDynFlags $ \dflags ->
1199 case mb_cty2 of
1200 Just cty2
1201 | gopt Opt_PrintExplicitCoercions dflags
1202 || not (cty1 `pickyEqType` cty2)
1203 -> hang (text "When matching" <+> sub_what)
1204 2 (vcat [ ppr cty1 <+> dcolon <+>
1205 ppr (typeKind cty1)
1206 , ppr cty2 <+> dcolon <+>
1207 ppr (typeKind cty2) ])
1208 _ -> text "When matching the kind of" <+> quotes (ppr cty1)
1209 msg2 = case sub_o of
1210 TypeEqOrigin {}
1211 | Just cty2 <- mb_cty2 ->
1212 thdOf3 (mkExpectedActualMsg cty1 cty2 sub_o sub_t_or_k
1213 expandSyns)
1214 _ -> empty
1215 _ -> (True, Nothing, empty)
1216
1217 -- | This function tries to reconstruct why a "Coercible ty1 ty2" constraint
1218 -- is left over.
1219 mkCoercibleExplanation :: GlobalRdrEnv -> FamInstEnvs
1220 -> TcType -> TcType -> SDoc
1221 mkCoercibleExplanation rdr_env fam_envs ty1 ty2
1222 | Just (tc, tys) <- tcSplitTyConApp_maybe ty1
1223 , (rep_tc, _, _) <- tcLookupDataFamInst fam_envs tc tys
1224 , Just msg <- coercible_msg_for_tycon rep_tc
1225 = msg
1226 | Just (tc, tys) <- splitTyConApp_maybe ty2
1227 , (rep_tc, _, _) <- tcLookupDataFamInst fam_envs tc tys
1228 , Just msg <- coercible_msg_for_tycon rep_tc
1229 = msg
1230 | Just (s1, _) <- tcSplitAppTy_maybe ty1
1231 , Just (s2, _) <- tcSplitAppTy_maybe ty2
1232 , s1 `eqType` s2
1233 , has_unknown_roles s1
1234 = hang (text "NB: We cannot know what roles the parameters to" <+>
1235 quotes (ppr s1) <+> text "have;")
1236 2 (text "we must assume that the role is nominal")
1237 | otherwise
1238 = empty
1239 where
1240 coercible_msg_for_tycon tc
1241 | isAbstractTyCon tc
1242 = Just $ hsep [ text "NB: The type constructor"
1243 , quotes (pprSourceTyCon tc)
1244 , text "is abstract" ]
1245 | isNewTyCon tc
1246 , [data_con] <- tyConDataCons tc
1247 , let dc_name = dataConName data_con
1248 , isNothing (lookupGRE_Name rdr_env dc_name)
1249 = Just $ hang (text "The data constructor" <+> quotes (ppr dc_name))
1250 2 (sep [ text "of newtype" <+> quotes (pprSourceTyCon tc)
1251 , text "is not in scope" ])
1252 | otherwise = Nothing
1253
1254 has_unknown_roles ty
1255 | Just (tc, tys) <- tcSplitTyConApp_maybe ty
1256 = length tys >= tyConArity tc -- oversaturated tycon
1257 | Just (s, _) <- tcSplitAppTy_maybe ty
1258 = has_unknown_roles s
1259 | isTyVarTy ty
1260 = True
1261 | otherwise
1262 = False
1263
1264 {-
1265 -- | Make a listing of role signatures for all the parameterised tycons
1266 -- used in the provided types
1267
1268
1269 -- SLPJ Jun 15: I could not convince myself that these hints were really
1270 -- useful. Maybe they are, but I think we need more work to make them
1271 -- actually helpful.
1272 mkRoleSigs :: Type -> Type -> SDoc
1273 mkRoleSigs ty1 ty2
1274 = ppUnless (null role_sigs) $
1275 hang (text "Relevant role signatures:")
1276 2 (vcat role_sigs)
1277 where
1278 tcs = nameEnvElts $ tyConsOfType ty1 `plusNameEnv` tyConsOfType ty2
1279 role_sigs = mapMaybe ppr_role_sig tcs
1280
1281 ppr_role_sig tc
1282 | null roles -- if there are no parameters, don't bother printing
1283 = Nothing
1284 | isBuiltInSyntax (tyConName tc) -- don't print roles for (->), etc.
1285 = Nothing
1286 | otherwise
1287 = Just $ hsep $ [text "type role", ppr tc] ++ map ppr roles
1288 where
1289 roles = tyConRoles tc
1290 -}
1291
1292 mkEqErr_help :: DynFlags -> ReportErrCtxt -> Report
1293 -> Ct
1294 -> Maybe SwapFlag -- Nothing <=> not sure
1295 -> TcType -> TcType -> TcM ErrMsg
1296 mkEqErr_help dflags ctxt report ct oriented ty1 ty2
1297 | Just tv1 <- tcGetTyVar_maybe ty1 = mkTyVarEqErr dflags ctxt report ct oriented tv1 ty2
1298 | Just tv2 <- tcGetTyVar_maybe ty2 = mkTyVarEqErr dflags ctxt report ct swapped tv2 ty1
1299 | otherwise = reportEqErr ctxt report ct oriented ty1 ty2
1300 where
1301 swapped = fmap flipSwap oriented
1302
1303 reportEqErr :: ReportErrCtxt -> Report
1304 -> Ct
1305 -> Maybe SwapFlag -- Nothing <=> not sure
1306 -> TcType -> TcType -> TcM ErrMsg
1307 reportEqErr ctxt report ct oriented ty1 ty2
1308 = mkErrorMsgFromCt ctxt ct (mconcat [misMatch, report, eqInfo])
1309 where misMatch = important $ misMatchOrCND ctxt ct oriented ty1 ty2
1310 eqInfo = important $ mkEqInfoMsg ct ty1 ty2
1311
1312 mkTyVarEqErr :: DynFlags -> ReportErrCtxt -> Report -> Ct
1313 -> Maybe SwapFlag -> TcTyVar -> TcType -> TcM ErrMsg
1314 -- tv1 and ty2 are already tidied
1315 mkTyVarEqErr dflags ctxt report ct oriented tv1 ty2
1316 | isUserSkolem ctxt tv1 -- ty2 won't be a meta-tyvar, or else the thing would
1317 -- be oriented the other way round;
1318 -- see TcCanonical.canEqTyVarTyVar
1319 || isSigTyVar tv1 && not (isTyVarTy ty2)
1320 || ctEqRel ct == ReprEq && not (isTyVarUnderDatatype tv1 ty2)
1321 -- the cases below don't really apply to ReprEq (except occurs check)
1322 = mkErrorMsgFromCt ctxt ct $ mconcat
1323 [ important $ misMatchOrCND ctxt ct oriented ty1 ty2
1324 , important $ extraTyVarInfo ctxt tv1 ty2
1325 , report
1326 ]
1327
1328 -- So tv is a meta tyvar (or started that way before we
1329 -- generalised it). So presumably it is an *untouchable*
1330 -- meta tyvar or a SigTv, else it'd have been unified
1331 | OC_Occurs <- occ_check_expand
1332 , ctEqRel ct == NomEq || isTyVarUnderDatatype tv1 ty2
1333 -- See Note [Occurs check error] in TcCanonical
1334 = do { let occCheckMsg = important $ addArising (ctOrigin ct) $
1335 hang (text "Occurs check: cannot construct the infinite" <+> what <> colon)
1336 2 (sep [ppr ty1, char '~', ppr ty2])
1337 extra2 = important $ mkEqInfoMsg ct ty1 ty2
1338
1339 interesting_tyvars
1340 = filter (not . isEmptyVarSet . tyCoVarsOfType . tyVarKind) $
1341 filter isTyVar $
1342 fvVarList $
1343 tyCoFVsOfType ty1 `unionFV` tyCoFVsOfType ty2
1344 extra3 = relevant_bindings $
1345 ppWhen (not (null interesting_tyvars)) $
1346 hang (text "Type variable kinds:") 2 $
1347 vcat (map (tyvar_binding . tidyTyVarOcc (cec_tidy ctxt))
1348 interesting_tyvars)
1349
1350 tyvar_binding tv = ppr tv <+> dcolon <+> ppr (tyVarKind tv)
1351 ; mkErrorMsgFromCt ctxt ct $ mconcat [occCheckMsg, extra2, extra3, report] }
1352
1353 | OC_Forall <- occ_check_expand
1354 = do { let msg = vcat [ text "Cannot instantiate unification variable"
1355 <+> quotes (ppr tv1)
1356 , hang (text "with a" <+> what <+> text "involving foralls:") 2 (ppr ty2)
1357 , nest 2 (text "GHC doesn't yet support impredicative polymorphism") ]
1358 -- Unlike the other reports, this discards the old 'report_important'
1359 -- instead of augmenting it. This is because the details are not likely
1360 -- to be helpful since this is just an unimplemented feature.
1361 ; mkErrorMsgFromCt ctxt ct $ report { report_important = [msg] } }
1362
1363 -- If the immediately-enclosing implication has 'tv' a skolem, and
1364 -- we know by now its an InferSkol kind of skolem, then presumably
1365 -- it started life as a SigTv, else it'd have been unified, given
1366 -- that there's no occurs-check or forall problem
1367 | (implic:_) <- cec_encl ctxt
1368 , Implic { ic_skols = skols } <- implic
1369 , tv1 `elem` skols
1370 = mkErrorMsgFromCt ctxt ct $ mconcat
1371 [ important $ misMatchMsg ct oriented ty1 ty2
1372 , important $ extraTyVarInfo ctxt tv1 ty2
1373 , report
1374 ]
1375
1376 -- Check for skolem escape
1377 | (implic:_) <- cec_encl ctxt -- Get the innermost context
1378 , Implic { ic_env = env, ic_skols = skols, ic_info = skol_info } <- implic
1379 , let esc_skols = filter (`elemVarSet` (tyCoVarsOfType ty2)) skols
1380 , not (null esc_skols)
1381 = do { let msg = important $ misMatchMsg ct oriented ty1 ty2
1382 esc_doc = sep [ text "because" <+> what <+> text "variable" <> plural esc_skols
1383 <+> pprQuotedList esc_skols
1384 , text "would escape" <+>
1385 if isSingleton esc_skols then text "its scope"
1386 else text "their scope" ]
1387 tv_extra = important $
1388 vcat [ nest 2 $ esc_doc
1389 , sep [ (if isSingleton esc_skols
1390 then text "This (rigid, skolem)" <+>
1391 what <+> text "variable is"
1392 else text "These (rigid, skolem)" <+>
1393 what <+> text "variables are")
1394 <+> text "bound by"
1395 , nest 2 $ ppr skol_info
1396 , nest 2 $ text "at" <+> ppr (tcl_loc env) ] ]
1397 ; mkErrorMsgFromCt ctxt ct (mconcat [msg, tv_extra, report]) }
1398
1399 -- Nastiest case: attempt to unify an untouchable variable
1400 -- See Note [Error messages for untouchables]
1401 | (implic:_) <- cec_encl ctxt -- Get the innermost context
1402 , Implic { ic_env = env, ic_given = given
1403 , ic_tclvl = lvl, ic_info = skol_info } <- implic
1404 = ASSERT2( isTcTyVar tv1 && not (isTouchableMetaTyVar lvl tv1)
1405 , ppr tv1 ) -- See Note [Error messages for untouchables]
1406 do { let msg = important $ misMatchMsg ct oriented ty1 ty2
1407 tclvl_extra = important $
1408 nest 2 $
1409 sep [ quotes (ppr tv1) <+> text "is untouchable"
1410 , nest 2 $ text "inside the constraints:" <+> pprEvVarTheta given
1411 , nest 2 $ text "bound by" <+> ppr skol_info
1412 , nest 2 $ text "at" <+> ppr (tcl_loc env) ]
1413 tv_extra = important $ extraTyVarInfo ctxt tv1 ty2
1414 add_sig = important $ suggestAddSig ctxt ty1 ty2
1415 ; mkErrorMsgFromCt ctxt ct $ mconcat
1416 [msg, tclvl_extra, tv_extra, add_sig, report] }
1417
1418 | otherwise
1419 = reportEqErr ctxt report ct oriented (mkTyVarTy tv1) ty2
1420 -- This *can* happen (Trac #6123, and test T2627b)
1421 -- Consider an ambiguous top-level constraint (a ~ F a)
1422 -- Not an occurs check, because F is a type function.
1423 where
1424 occ_check_expand = occurCheckExpand dflags tv1 ty2
1425 ty1 = mkTyVarTy tv1
1426
1427 what = case ctLocTypeOrKind_maybe (ctLoc ct) of
1428 Just KindLevel -> text "kind"
1429 _ -> text "type"
1430
1431 mkEqInfoMsg :: Ct -> TcType -> TcType -> SDoc
1432 -- Report (a) ambiguity if either side is a type function application
1433 -- e.g. F a0 ~ Int
1434 -- (b) warning about injectivity if both sides are the same
1435 -- type function application F a ~ F b
1436 -- See Note [Non-injective type functions]
1437 -- (c) warning about -fprint-explicit-kinds if that might be helpful
1438 mkEqInfoMsg ct ty1 ty2
1439 = tyfun_msg $$ ambig_msg $$ invis_msg
1440 where
1441 mb_fun1 = isTyFun_maybe ty1
1442 mb_fun2 = isTyFun_maybe ty2
1443
1444 ambig_msg | isJust mb_fun1 || isJust mb_fun2
1445 = snd (mkAmbigMsg False ct)
1446 | otherwise = empty
1447
1448 -- better to check the exp/act types in the CtOrigin than the actual
1449 -- mismatched types for suggestion about -fprint-explicit-kinds
1450 (act_ty, exp_ty) = case ctOrigin ct of
1451 TypeEqOrigin { uo_actual = act
1452 , uo_expected = Check exp } -> (act, exp)
1453 _ -> (ty1, ty2)
1454
1455 invis_msg | Just vis <- tcEqTypeVis act_ty exp_ty
1456 , not vis
1457 = ppSuggestExplicitKinds
1458 | otherwise
1459 = empty
1460
1461 tyfun_msg | Just tc1 <- mb_fun1
1462 , Just tc2 <- mb_fun2
1463 , tc1 == tc2
1464 = text "NB:" <+> quotes (ppr tc1)
1465 <+> text "is a type function, and may not be injective"
1466 | otherwise = empty
1467
1468 isUserSkolem :: ReportErrCtxt -> TcTyVar -> Bool
1469 -- See Note [Reporting occurs-check errors]
1470 isUserSkolem ctxt tv
1471 = isSkolemTyVar tv && any is_user_skol_tv (cec_encl ctxt)
1472 where
1473 is_user_skol_tv (Implic { ic_skols = sks, ic_info = skol_info })
1474 = tv `elem` sks && is_user_skol_info skol_info
1475
1476 is_user_skol_info (InferSkol {}) = False
1477 is_user_skol_info _ = True
1478
1479 misMatchOrCND :: ReportErrCtxt -> Ct
1480 -> Maybe SwapFlag -> TcType -> TcType -> SDoc
1481 -- If oriented then ty1 is actual, ty2 is expected
1482 misMatchOrCND ctxt ct oriented ty1 ty2
1483 | null givens ||
1484 (isRigidTy ty1 && isRigidTy ty2) ||
1485 isGivenCt ct
1486 -- If the equality is unconditionally insoluble
1487 -- or there is no context, don't report the context
1488 = misMatchMsg ct oriented ty1 ty2
1489 | otherwise
1490 = couldNotDeduce givens ([eq_pred], orig)
1491 where
1492 ev = ctEvidence ct
1493 eq_pred = ctEvPred ev
1494 orig = ctEvOrigin ev
1495 givens = [ given | given <- getUserGivens ctxt, not (ic_no_eqs given)]
1496 -- Keep only UserGivens that have some equalities
1497
1498 couldNotDeduce :: [UserGiven] -> (ThetaType, CtOrigin) -> SDoc
1499 couldNotDeduce givens (wanteds, orig)
1500 = vcat [ addArising orig (text "Could not deduce:" <+> pprTheta wanteds)
1501 , vcat (pp_givens givens)]
1502
1503 pp_givens :: [UserGiven] -> [SDoc]
1504 pp_givens givens
1505 = case givens of
1506 [] -> []
1507 (g:gs) -> ppr_given (text "from the context:") g
1508 : map (ppr_given (text "or from:")) gs
1509 where
1510 ppr_given herald (Implic { ic_given = gs, ic_info = skol_info
1511 , ic_env = env })
1512 = hang (herald <+> pprEvVarTheta gs)
1513 2 (sep [ text "bound by" <+> ppr skol_info
1514 , text "at" <+> ppr (tcl_loc env) ])
1515
1516 extraTyVarInfo :: ReportErrCtxt -> TcTyVar -> TcType -> SDoc
1517 -- Add on extra info about skolem constants
1518 -- NB: The types themselves are already tidied
1519 extraTyVarInfo ctxt tv1 ty2
1520 = ASSERT2( isTcTyVar tv1, ppr tv1 )
1521 tv_extra tv1 $$ ty_extra ty2
1522 where
1523 implics = cec_encl ctxt
1524 ty_extra ty = case tcGetTyVar_maybe ty of
1525 Just tv -> tv_extra tv
1526 Nothing -> empty
1527
1528 tv_extra tv
1529 | let pp_tv = quotes (ppr tv)
1530 = case tcTyVarDetails tv of
1531 SkolemTv {} -> pprSkol implics tv
1532 FlatSkol {} -> pp_tv <+> text "is a flattening type variable"
1533 RuntimeUnk {} -> pp_tv <+> text "is an interactive-debugger skolem"
1534 MetaTv {} -> empty
1535
1536 suggestAddSig :: ReportErrCtxt -> TcType -> TcType -> SDoc
1537 -- See Note [Suggest adding a type signature]
1538 suggestAddSig ctxt ty1 ty2
1539 | null inferred_bndrs
1540 = empty
1541 | [bndr] <- inferred_bndrs
1542 = text "Possible fix: add a type signature for" <+> quotes (ppr bndr)
1543 | otherwise
1544 = text "Possible fix: add type signatures for some or all of" <+> (ppr inferred_bndrs)
1545 where
1546 inferred_bndrs = nub (get_inf ty1 ++ get_inf ty2)
1547 get_inf ty | Just tv <- tcGetTyVar_maybe ty
1548 , isSkolemTyVar tv
1549 , InferSkol prs <- ic_info (getSkolemInfo (cec_encl ctxt) tv)
1550 = map fst prs
1551 | otherwise
1552 = []
1553
1554 --------------------
1555 misMatchMsg :: Ct -> Maybe SwapFlag -> TcType -> TcType -> SDoc
1556 -- Types are already tidy
1557 -- If oriented then ty1 is actual, ty2 is expected
1558 misMatchMsg ct oriented ty1 ty2
1559 | Just NotSwapped <- oriented
1560 = misMatchMsg ct (Just IsSwapped) ty2 ty1
1561
1562 -- These next two cases are when we're about to report, e.g., that
1563 -- 'PtrRepLifted doesn't match 'VoidRep. Much better just to say
1564 -- lifted vs. unlifted
1565 | Just (tc1, []) <- splitTyConApp_maybe ty1
1566 , tc1 `hasKey` ptrRepLiftedDataConKey
1567 = lifted_vs_unlifted
1568
1569 | Just (tc2, []) <- splitTyConApp_maybe ty2
1570 , tc2 `hasKey` ptrRepLiftedDataConKey
1571 = lifted_vs_unlifted
1572
1573 | Just (tc1, []) <- splitTyConApp_maybe ty1
1574 , Just (tc2, []) <- splitTyConApp_maybe ty2
1575 , (tc1 `hasKey` ptrRepLiftedDataConKey && tc2 `hasKey` ptrRepUnliftedDataConKey)
1576 || (tc1 `hasKey` ptrRepUnliftedDataConKey && tc2 `hasKey` ptrRepLiftedDataConKey)
1577 = lifted_vs_unlifted
1578
1579 | otherwise -- So now we have Nothing or (Just IsSwapped)
1580 -- For some reason we treat Nothing like IsSwapped
1581 = addArising orig $
1582 sep [ text herald1 <+> quotes (ppr ty1)
1583 , nest padding $
1584 text herald2 <+> quotes (ppr ty2)
1585 , sameOccExtra ty2 ty1 ]
1586 where
1587 herald1 = conc [ "Couldn't match"
1588 , if is_repr then "representation of" else ""
1589 , if is_oriented then "expected" else ""
1590 , what ]
1591 herald2 = conc [ "with"
1592 , if is_repr then "that of" else ""
1593 , if is_oriented then ("actual " ++ what) else "" ]
1594 padding = length herald1 - length herald2
1595
1596 is_repr = case ctEqRel ct of { ReprEq -> True; NomEq -> False }
1597 is_oriented = isJust oriented
1598
1599 orig = ctOrigin ct
1600 what = case ctLocTypeOrKind_maybe (ctLoc ct) of
1601 Just KindLevel -> "kind"
1602 _ -> "type"
1603
1604 conc :: [String] -> String
1605 conc = foldr1 add_space
1606
1607 add_space :: String -> String -> String
1608 add_space s1 s2 | null s1 = s2
1609 | null s2 = s1
1610 | otherwise = s1 ++ (' ' : s2)
1611
1612 lifted_vs_unlifted
1613 = addArising orig $
1614 text "Couldn't match a lifted type with an unlifted type"
1615
1616 mkExpectedActualMsg :: Type -> Type -> CtOrigin -> Maybe TypeOrKind -> Bool
1617 -> (Bool, Maybe SwapFlag, SDoc)
1618 -- NotSwapped means (actual, expected), IsSwapped is the reverse
1619 -- First return val is whether or not to print a herald above this msg
1620 mkExpectedActualMsg ty1 ty2 (TypeEqOrigin { uo_actual = act
1621 , uo_expected = Check exp
1622 , uo_thing = maybe_thing })
1623 m_level printExpanded
1624 | KindLevel <- level, occurs_check_error = (True, Nothing, empty)
1625 | isUnliftedTypeKind act, isLiftedTypeKind exp = (False, Nothing, msg2)
1626 | isLiftedTypeKind act, isUnliftedTypeKind exp = (False, Nothing, msg3)
1627 | isLiftedTypeKind exp && not (isConstraintKind exp)
1628 = (False, Nothing, msg4)
1629 | Just msg <- num_args_msg = (False, Nothing, msg $$ msg1)
1630 | KindLevel <- level, Just th <- maybe_thing = (False, Nothing, msg5 th)
1631 | act `pickyEqType` ty1, exp `pickyEqType` ty2 = (True, Just NotSwapped, empty)
1632 | exp `pickyEqType` ty1, act `pickyEqType` ty2 = (True, Just IsSwapped, empty)
1633 | otherwise = (True, Nothing, msg1)
1634 where
1635 level = m_level `orElse` TypeLevel
1636
1637 occurs_check_error
1638 | Just act_tv <- tcGetTyVar_maybe act
1639 , act_tv `elemVarSet` tyCoVarsOfType exp
1640 = True
1641 | Just exp_tv <- tcGetTyVar_maybe exp
1642 , exp_tv `elemVarSet` tyCoVarsOfType act
1643 = True
1644 | otherwise
1645 = False
1646
1647 sort = case level of
1648 TypeLevel -> text "type"
1649 KindLevel -> text "kind"
1650
1651 msg1 = case level of
1652 KindLevel
1653 | Just th <- maybe_thing
1654 -> msg5 th
1655
1656 _ | not (act `pickyEqType` exp)
1657 -> vcat [ text "Expected" <+> sort <> colon <+> ppr exp
1658 , text " Actual" <+> sort <> colon <+> ppr act
1659 , if printExpanded then expandedTys else empty ]
1660
1661 | otherwise
1662 -> empty
1663
1664 thing_msg = case maybe_thing of
1665 Just thing -> \_ -> quotes (ppr thing) <+> text "is"
1666 Nothing -> \vowel -> text "got a" <>
1667 if vowel then char 'n' else empty
1668 msg2 = sep [ text "Expecting a lifted type, but"
1669 , thing_msg True, text "unlifted" ]
1670 msg3 = sep [ text "Expecting an unlifted type, but"
1671 , thing_msg False, text "lifted" ]
1672 msg4 = maybe_num_args_msg $$
1673 sep [ text "Expected a type, but"
1674 , maybe (text "found something with kind")
1675 (\thing -> quotes (ppr thing) <+> text "has kind")
1676 maybe_thing
1677 , quotes (ppr act) ]
1678
1679 msg5 th = hang (text "Expected" <+> kind_desc <> comma)
1680 2 (text "but" <+> quotes (ppr th) <+> text "has kind" <+>
1681 quotes (ppr act))
1682 where
1683 kind_desc | isConstraintKind exp = text "a constraint"
1684 | otherwise = text "kind" <+> quotes (ppr exp)
1685
1686 num_args_msg = case level of
1687 TypeLevel -> Nothing
1688 KindLevel
1689 -> let n_act = count_args act
1690 n_exp = count_args exp in
1691 case n_act - n_exp of
1692 n | n /= 0
1693 , Just thing <- maybe_thing
1694 , case errorThingNumArgs_maybe thing of
1695 Nothing -> n > 0
1696 Just num_act_args -> num_act_args >= -n
1697 -- don't report to strip off args that aren't there
1698 -> Just $ text "Expecting" <+> speakN (abs n) <+>
1699 more_or_fewer <+> quotes (ppr thing)
1700 where
1701 more_or_fewer
1702 | n < 0 = text "fewer arguments to"
1703 | n == 1 = text "more argument to"
1704 | otherwise = text "more arguments to" -- n > 1
1705 _ -> Nothing
1706
1707 maybe_num_args_msg = case num_args_msg of
1708 Nothing -> empty
1709 Just m -> m
1710
1711 count_args ty = count isVisibleBinder $ fst $ splitPiTys ty
1712
1713 expandedTys =
1714 ppUnless (expTy1 `pickyEqType` exp && expTy2 `pickyEqType` act) $ vcat
1715 [ text "Type synonyms expanded:"
1716 , text "Expected type:" <+> ppr expTy1
1717 , text " Actual type:" <+> ppr expTy2
1718 ]
1719
1720 (expTy1, expTy2) = expandSynonymsToMatch exp act
1721
1722 mkExpectedActualMsg _ _ _ _ _ = panic "mkExpectedAcutalMsg"
1723
1724 {-
1725 Note [Expanding type synonyms to make types similar]
1726 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1727
1728 In type error messages, if -fprint-expanded-types is used, we want to expand
1729 type synonyms to make expected and found types as similar as possible, but we
1730 shouldn't expand types too much to make type messages even more verbose and
1731 harder to understand. The whole point here is to make the difference in expected
1732 and found types clearer.
1733
1734 `expandSynonymsToMatch` does this, it takes two types, and expands type synonyms
1735 only as much as necessary. Given two types t1 and t2:
1736
1737 * If they're already same, it just returns the types.
1738
1739 * If they're in form `C1 t1_1 .. t1_n` and `C2 t2_1 .. t2_m` (C1 and C2 are
1740 type constructors), it expands C1 and C2 if they're different type synonyms.
1741 Then it recursively does the same thing on expanded types. If C1 and C2 are
1742 same, then it applies the same procedure to arguments of C1 and arguments of
1743 C2 to make them as similar as possible.
1744
1745 Most important thing here is to keep number of synonym expansions at
1746 minimum. For example, if t1 is `T (T3, T5, Int)` and t2 is `T (T5, T3,
1747 Bool)` where T5 = T4, T4 = T3, ..., T1 = X, it returns `T (T3, T3, Int)` and
1748 `T (T3, T3, Bool)`.
1749
1750 * Otherwise types don't have same shapes and so the difference is clearly
1751 visible. It doesn't do any expansions and show these types.
1752
1753 Note that we only expand top-layer type synonyms. Only when top-layer
1754 constructors are the same we start expanding inner type synonyms.
1755
1756 Suppose top-layer type synonyms of t1 and t2 can expand N and M times,
1757 respectively. If their type-synonym-expanded forms will meet at some point (i.e.
1758 will have same shapes according to `sameShapes` function), it's possible to find
1759 where they meet in O(N+M) top-layer type synonym expansions and O(min(N,M))
1760 comparisons. We first collect all the top-layer expansions of t1 and t2 in two
1761 lists, then drop the prefix of the longer list so that they have same lengths.
1762 Then we search through both lists in parallel, and return the first pair of
1763 types that have same shapes. Inner types of these two types with same shapes
1764 are then expanded using the same algorithm.
1765
1766 In case they don't meet, we return the last pair of types in the lists, which
1767 has top-layer type synonyms completely expanded. (in this case the inner types
1768 are not expanded at all, as the current form already shows the type error)
1769 -}
1770
1771 -- | Expand type synonyms in given types only enough to make them as similar as
1772 -- possible. Returned types are the same in terms of used type synonyms.
1773 --
1774 -- To expand all synonyms, see 'Type.expandTypeSynonyms'.
1775 --
1776 -- See `ExpandSynsFail` tests in tests testsuite/tests/typecheck/should_fail for
1777 -- some examples of how this should work.
1778 expandSynonymsToMatch :: Type -> Type -> (Type, Type)
1779 expandSynonymsToMatch ty1 ty2 = (ty1_ret, ty2_ret)
1780 where
1781 (ty1_ret, ty2_ret) = go ty1 ty2
1782
1783 -- | Returns (type synonym expanded version of first type,
1784 -- type synonym expanded version of second type)
1785 go :: Type -> Type -> (Type, Type)
1786 go t1 t2
1787 | t1 `pickyEqType` t2 =
1788 -- Types are same, nothing to do
1789 (t1, t2)
1790
1791 go (TyConApp tc1 tys1) (TyConApp tc2 tys2)
1792 | tc1 == tc2 =
1793 -- Type constructors are same. They may be synonyms, but we don't
1794 -- expand further.
1795 let (tys1', tys2') =
1796 unzip (zipWith (\ty1 ty2 -> go ty1 ty2) tys1 tys2)
1797 in (TyConApp tc1 tys1', TyConApp tc2 tys2')
1798
1799 go (AppTy t1_1 t1_2) (AppTy t2_1 t2_2) =
1800 let (t1_1', t2_1') = go t1_1 t2_1
1801 (t1_2', t2_2') = go t1_2 t2_2
1802 in (mkAppTy t1_1' t1_2', mkAppTy t2_1' t2_2')
1803
1804 go (FunTy t1_1 t1_2) (FunTy t2_1 t2_2) =
1805 let (t1_1', t2_1') = go t1_1 t2_1
1806 (t1_2', t2_2') = go t1_2 t2_2
1807 in (mkFunTy t1_1' t1_2', mkFunTy t2_1' t2_2')
1808
1809 go (ForAllTy b1 t1) (ForAllTy b2 t2) =
1810 -- NOTE: We may have a bug here, but we just can't reproduce it easily.
1811 -- See D1016 comments for details and our attempts at producing a test
1812 -- case. Short version: We probably need RnEnv2 to really get this right.
1813 let (t1', t2') = go t1 t2
1814 in (ForAllTy b1 t1', ForAllTy b2 t2')
1815
1816 go (CastTy ty1 _) ty2 = go ty1 ty2
1817 go ty1 (CastTy ty2 _) = go ty1 ty2
1818
1819 go t1 t2 =
1820 -- See Note [Expanding type synonyms to make types similar] for how this
1821 -- works
1822 let
1823 t1_exp_tys = t1 : tyExpansions t1
1824 t2_exp_tys = t2 : tyExpansions t2
1825 t1_exps = length t1_exp_tys
1826 t2_exps = length t2_exp_tys
1827 dif = abs (t1_exps - t2_exps)
1828 in
1829 followExpansions $
1830 zipEqual "expandSynonymsToMatch.go"
1831 (if t1_exps > t2_exps then drop dif t1_exp_tys else t1_exp_tys)
1832 (if t2_exps > t1_exps then drop dif t2_exp_tys else t2_exp_tys)
1833
1834 -- | Expand the top layer type synonyms repeatedly, collect expansions in a
1835 -- list. The list does not include the original type.
1836 --
1837 -- Example, if you have:
1838 --
1839 -- type T10 = T9
1840 -- type T9 = T8
1841 -- ...
1842 -- type T0 = Int
1843 --
1844 -- `tyExpansions T10` returns [T9, T8, T7, ... Int]
1845 --
1846 -- This only expands the top layer, so if you have:
1847 --
1848 -- type M a = Maybe a
1849 --
1850 -- `tyExpansions (M T10)` returns [Maybe T10] (T10 is not expanded)
1851 tyExpansions :: Type -> [Type]
1852 tyExpansions = unfoldr (\t -> (\x -> (x, x)) `fmap` coreView t)
1853
1854 -- | Drop the type pairs until types in a pair look alike (i.e. the outer
1855 -- constructors are the same).
1856 followExpansions :: [(Type, Type)] -> (Type, Type)
1857 followExpansions [] = pprPanic "followExpansions" empty
1858 followExpansions [(t1, t2)]
1859 | sameShapes t1 t2 = go t1 t2 -- expand subtrees
1860 | otherwise = (t1, t2) -- the difference is already visible
1861 followExpansions ((t1, t2) : tss)
1862 -- Traverse subtrees when the outer shapes are the same
1863 | sameShapes t1 t2 = go t1 t2
1864 -- Otherwise follow the expansions until they look alike
1865 | otherwise = followExpansions tss
1866
1867 sameShapes :: Type -> Type -> Bool
1868 sameShapes AppTy{} AppTy{} = True
1869 sameShapes (TyConApp tc1 _) (TyConApp tc2 _) = tc1 == tc2
1870 sameShapes (FunTy {}) (FunTy {}) = True
1871 sameShapes (ForAllTy {}) (ForAllTy {}) = True
1872 sameShapes (CastTy ty1 _) ty2 = sameShapes ty1 ty2
1873 sameShapes ty1 (CastTy ty2 _) = sameShapes ty1 ty2
1874 sameShapes _ _ = False
1875
1876 sameOccExtra :: TcType -> TcType -> SDoc
1877 -- See Note [Disambiguating (X ~ X) errors]
1878 sameOccExtra ty1 ty2
1879 | Just (tc1, _) <- tcSplitTyConApp_maybe ty1
1880 , Just (tc2, _) <- tcSplitTyConApp_maybe ty2
1881 , let n1 = tyConName tc1
1882 n2 = tyConName tc2
1883 same_occ = nameOccName n1 == nameOccName n2
1884 same_pkg = moduleUnitId (nameModule n1) == moduleUnitId (nameModule n2)
1885 , n1 /= n2 -- Different Names
1886 , same_occ -- but same OccName
1887 = text "NB:" <+> (ppr_from same_pkg n1 $$ ppr_from same_pkg n2)
1888 | otherwise
1889 = empty
1890 where
1891 ppr_from same_pkg nm
1892 | isGoodSrcSpan loc
1893 = hang (quotes (ppr nm) <+> text "is defined at")
1894 2 (ppr loc)
1895 | otherwise -- Imported things have an UnhelpfulSrcSpan
1896 = hang (quotes (ppr nm))
1897 2 (sep [ text "is defined in" <+> quotes (ppr (moduleName mod))
1898 , ppUnless (same_pkg || pkg == mainUnitId) $
1899 nest 4 $ text "in package" <+> quotes (ppr pkg) ])
1900 where
1901 pkg = moduleUnitId mod
1902 mod = nameModule nm
1903 loc = nameSrcSpan nm
1904
1905 {-
1906 Note [Suggest adding a type signature]
1907 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1908 The OutsideIn algorithm rejects GADT programs that don't have a principal
1909 type, and indeed some that do. Example:
1910 data T a where
1911 MkT :: Int -> T Int
1912
1913 f (MkT n) = n
1914
1915 Does this have type f :: T a -> a, or f :: T a -> Int?
1916 The error that shows up tends to be an attempt to unify an
1917 untouchable type variable. So suggestAddSig sees if the offending
1918 type variable is bound by an *inferred* signature, and suggests
1919 adding a declared signature instead.
1920
1921 This initially came up in Trac #8968, concerning pattern synonyms.
1922
1923 Note [Disambiguating (X ~ X) errors]
1924 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1925 See Trac #8278
1926
1927 Note [Reporting occurs-check errors]
1928 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1929 Given (a ~ [a]), if 'a' is a rigid type variable bound by a user-supplied
1930 type signature, then the best thing is to report that we can't unify
1931 a with [a], because a is a skolem variable. That avoids the confusing
1932 "occur-check" error message.
1933
1934 But nowadays when inferring the type of a function with no type signature,
1935 even if there are errors inside, we still generalise its signature and
1936 carry on. For example
1937 f x = x:x
1938 Here we will infer somethiing like
1939 f :: forall a. a -> [a]
1940 with a deferred error of (a ~ [a]). So in the deferred unsolved constraint
1941 'a' is now a skolem, but not one bound by the programmer in the context!
1942 Here we really should report an occurs check.
1943
1944 So isUserSkolem distinguishes the two.
1945
1946 Note [Non-injective type functions]
1947 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1948 It's very confusing to get a message like
1949 Couldn't match expected type `Depend s'
1950 against inferred type `Depend s1'
1951 so mkTyFunInfoMsg adds:
1952 NB: `Depend' is type function, and hence may not be injective
1953
1954 Warn of loopy local equalities that were dropped.
1955
1956
1957 ************************************************************************
1958 * *
1959 Type-class errors
1960 * *
1961 ************************************************************************
1962 -}
1963
1964 mkDictErr :: ReportErrCtxt -> [Ct] -> TcM ErrMsg
1965 mkDictErr ctxt cts
1966 = ASSERT( not (null cts) )
1967 do { inst_envs <- tcGetInstEnvs
1968 ; let (ct1:_) = cts -- ct1 just for its location
1969 min_cts = elim_superclasses cts
1970 lookups = map (lookup_cls_inst inst_envs) min_cts
1971 (no_inst_cts, overlap_cts) = partition is_no_inst lookups
1972
1973 -- Report definite no-instance errors,
1974 -- or (iff there are none) overlap errors
1975 -- But we report only one of them (hence 'head') because they all
1976 -- have the same source-location origin, to try avoid a cascade
1977 -- of error from one location
1978 ; (ctxt, err) <- mk_dict_err ctxt (head (no_inst_cts ++ overlap_cts))
1979 ; mkErrorMsgFromCt ctxt ct1 (important err) }
1980 where
1981 no_givens = null (getUserGivens ctxt)
1982
1983 is_no_inst (ct, (matches, unifiers, _))
1984 = no_givens
1985 && null matches
1986 && (null unifiers || all (not . isAmbiguousTyVar) (tyCoVarsOfCtList ct))
1987
1988 lookup_cls_inst inst_envs ct
1989 -- Note [Flattening in error message generation]
1990 = (ct, lookupInstEnv True inst_envs clas (flattenTys emptyInScopeSet tys))
1991 where
1992 (clas, tys) = getClassPredTys (ctPred ct)
1993
1994
1995 -- When simplifying [W] Ord (Set a), we need
1996 -- [W] Eq a, [W] Ord a
1997 -- but we really only want to report the latter
1998 elim_superclasses cts
1999 = filter (\ct -> any (eqType (ctPred ct)) min_preds) cts
2000 where
2001 min_preds = mkMinimalBySCs (map ctPred cts)
2002
2003 mk_dict_err :: ReportErrCtxt -> (Ct, ClsInstLookupResult)
2004 -> TcM (ReportErrCtxt, SDoc)
2005 -- Report an overlap error if this class constraint results
2006 -- from an overlap (returning Left clas), otherwise return (Right pred)
2007 mk_dict_err ctxt@(CEC {cec_encl = implics}) (ct, (matches, unifiers, unsafe_overlapped))
2008 | null matches -- No matches but perhaps several unifiers
2009 = do { (ctxt, binds_msg, ct) <- relevantBindings True ctxt ct
2010 ; candidate_insts <- get_candidate_instances
2011 ; return (ctxt, cannot_resolve_msg ct candidate_insts binds_msg) }
2012
2013 | null unsafe_overlapped -- Some matches => overlap errors
2014 = return (ctxt, overlap_msg)
2015
2016 | otherwise
2017 = return (ctxt, safe_haskell_msg)
2018 where
2019 orig = ctOrigin ct
2020 pred = ctPred ct
2021 (clas, tys) = getClassPredTys pred
2022 ispecs = [ispec | (ispec, _) <- matches]
2023 unsafe_ispecs = [ispec | (ispec, _) <- unsafe_overlapped]
2024 useful_givens = discardProvCtxtGivens orig (getUserGivensFromImplics implics)
2025 -- useful_givens are the enclosing implications with non-empty givens,
2026 -- modulo the horrid discardProvCtxtGivens
2027
2028 get_candidate_instances :: TcM [ClsInst]
2029 -- See Note [Report candidate instances]
2030 get_candidate_instances
2031 | [ty] <- tys -- Only try for single-parameter classes
2032 = do { instEnvs <- tcGetInstEnvs
2033 ; return (filter (is_candidate_inst ty)
2034 (classInstances instEnvs clas)) }
2035 | otherwise = return []
2036
2037 is_candidate_inst ty inst -- See Note [Report candidate instances]
2038 | [other_ty] <- is_tys inst
2039 , Just (tc1, _) <- tcSplitTyConApp_maybe ty
2040 , Just (tc2, _) <- tcSplitTyConApp_maybe other_ty
2041 = let n1 = tyConName tc1
2042 n2 = tyConName tc2
2043 different_names = n1 /= n2
2044 same_occ_names = nameOccName n1 == nameOccName n2
2045 in different_names && same_occ_names
2046 | otherwise = False
2047
2048 cannot_resolve_msg :: Ct -> [ClsInst] -> SDoc -> SDoc
2049 cannot_resolve_msg ct candidate_insts binds_msg
2050 = vcat [ no_inst_msg
2051 , nest 2 extra_note
2052 , vcat (pp_givens useful_givens)
2053 , mb_patsyn_prov `orElse` empty
2054 , ppWhen (has_ambig_tvs && not (null unifiers && null useful_givens))
2055 (vcat [ ppUnless lead_with_ambig ambig_msg, binds_msg, potential_msg ])
2056
2057 , ppWhen (isNothing mb_patsyn_prov) $
2058 -- Don't suggest fixes for the provided context of a pattern
2059 -- synonym; the right fix is to bind more in the pattern
2060 show_fixes (ctxtFixes has_ambig_tvs pred implics
2061 ++ drv_fixes)
2062 , ppWhen (not (null candidate_insts))
2063 (hang (text "There are instances for similar types:")
2064 2 (vcat (map ppr candidate_insts))) ]
2065 -- See Note [Report candidate instances]
2066 where
2067 orig = ctOrigin ct
2068 -- See Note [Highlighting ambiguous type variables]
2069 lead_with_ambig = has_ambig_tvs && not (any isRuntimeUnkSkol ambig_tvs)
2070 && not (null unifiers) && null useful_givens
2071
2072 (has_ambig_tvs, ambig_msg) = mkAmbigMsg lead_with_ambig ct
2073 ambig_tvs = uncurry (++) (getAmbigTkvs ct)
2074
2075 no_inst_msg
2076 | lead_with_ambig
2077 = ambig_msg <+> pprArising orig
2078 $$ text "prevents the constraint" <+> quotes (pprParendType pred)
2079 <+> text "from being solved."
2080
2081 | null useful_givens
2082 = addArising orig $ text "No instance for"
2083 <+> pprParendType pred
2084
2085 | otherwise
2086 = addArising orig $ text "Could not deduce"
2087 <+> pprParendType pred
2088
2089 potential_msg
2090 = ppWhen (not (null unifiers) && want_potential orig) $
2091 sdocWithDynFlags $ \dflags ->
2092 getPprStyle $ \sty ->
2093 pprPotentials dflags sty potential_hdr unifiers
2094
2095 potential_hdr
2096 = vcat [ ppWhen lead_with_ambig $
2097 text "Probable fix: use a type annotation to specify what"
2098 <+> pprQuotedList ambig_tvs <+> text "should be."
2099 , text "These potential instance" <> plural unifiers
2100 <+> text "exist:"]
2101
2102 mb_patsyn_prov :: Maybe SDoc
2103 mb_patsyn_prov
2104 | not lead_with_ambig
2105 , ProvCtxtOrigin PSB{ psb_def = L _ pat } <- orig
2106 = Just (vcat [ text "In other words, a successful match on the pattern"
2107 , nest 2 $ ppr pat
2108 , text "does not provide the constraint" <+> pprParendType pred ])
2109 | otherwise = Nothing
2110
2111 -- Report "potential instances" only when the constraint arises
2112 -- directly from the user's use of an overloaded function
2113 want_potential (TypeEqOrigin {}) = False
2114 want_potential _ = True
2115
2116 extra_note | any isFunTy (filterOutInvisibleTypes (classTyCon clas) tys)
2117 = text "(maybe you haven't applied a function to enough arguments?)"
2118 | className clas == typeableClassName -- Avoid mysterious "No instance for (Typeable T)
2119 , [_,ty] <- tys -- Look for (Typeable (k->*) (T k))
2120 , Just (tc,_) <- tcSplitTyConApp_maybe ty
2121 , not (isTypeFamilyTyCon tc)
2122 = hang (text "GHC can't yet do polykinded")
2123 2 (text "Typeable" <+>
2124 parens (ppr ty <+> dcolon <+> ppr (typeKind ty)))
2125 | otherwise
2126 = empty
2127
2128 drv_fixes = case orig of
2129 DerivOrigin -> [drv_fix]
2130 DerivOriginDC {} -> [drv_fix]
2131 DerivOriginCoerce {} -> [drv_fix]
2132 _ -> []
2133
2134 drv_fix = hang (text "use a standalone 'deriving instance' declaration,")
2135 2 (text "so you can specify the instance context yourself")
2136
2137 -- Normal overlap error
2138 overlap_msg
2139 = ASSERT( not (null matches) )
2140 vcat [ addArising orig (text "Overlapping instances for"
2141 <+> pprType (mkClassPred clas tys))
2142
2143 , ppUnless (null matching_givens) $
2144 sep [text "Matching givens (or their superclasses):"
2145 , nest 2 (vcat matching_givens)]
2146
2147 , sdocWithDynFlags $ \dflags ->
2148 getPprStyle $ \sty ->
2149 pprPotentials dflags sty (text "Matching instances:") $
2150 ispecs ++ unifiers
2151
2152 , ppWhen (null matching_givens && isSingleton matches && null unifiers) $
2153 -- Intuitively, some given matched the wanted in their
2154 -- flattened or rewritten (from given equalities) form
2155 -- but the matcher can't figure that out because the
2156 -- constraints are non-flat and non-rewritten so we
2157 -- simply report back the whole given
2158 -- context. Accelerate Smart.hs showed this problem.
2159 sep [ text "There exists a (perhaps superclass) match:"
2160 , nest 2 (vcat (pp_givens useful_givens))]
2161
2162 , ppWhen (isSingleton matches) $
2163 parens (vcat [ text "The choice depends on the instantiation of" <+>
2164 quotes (pprWithCommas ppr (tyCoVarsOfTypesList tys))
2165 , ppWhen (null (matching_givens)) $
2166 vcat [ text "To pick the first instance above, use IncoherentInstances"
2167 , text "when compiling the other instance declarations"]
2168 ])]
2169
2170 matching_givens = mapMaybe matchable useful_givens
2171
2172 matchable (Implic { ic_given = evvars, ic_info = skol_info, ic_env = env })
2173 = case ev_vars_matching of
2174 [] -> Nothing
2175 _ -> Just $ hang (pprTheta ev_vars_matching)
2176 2 (sep [ text "bound by" <+> ppr skol_info
2177 , text "at" <+> ppr (tcl_loc env) ])
2178 where ev_vars_matching = filter ev_var_matches (map evVarPred evvars)
2179 ev_var_matches ty = case getClassPredTys_maybe ty of
2180 Just (clas', tys')
2181 | clas' == clas
2182 , Just _ <- tcMatchTys tys tys'
2183 -> True
2184 | otherwise
2185 -> any ev_var_matches (immSuperClasses clas' tys')
2186 Nothing -> False
2187
2188 -- Overlap error because of Safe Haskell (first
2189 -- match should be the most specific match)
2190 safe_haskell_msg
2191 = ASSERT( length matches == 1 && not (null unsafe_ispecs) )
2192 vcat [ addArising orig (text "Unsafe overlapping instances for"
2193 <+> pprType (mkClassPred clas tys))
2194 , sep [text "The matching instance is:",
2195 nest 2 (pprInstance $ head ispecs)]
2196 , vcat [ text "It is compiled in a Safe module and as such can only"
2197 , text "overlap instances from the same module, however it"
2198 , text "overlaps the following instances from different" <+>
2199 text "modules:"
2200 , nest 2 (vcat [pprInstances $ unsafe_ispecs])
2201 ]
2202 ]
2203
2204
2205 ctxtFixes :: Bool -> PredType -> [Implication] -> [SDoc]
2206 ctxtFixes has_ambig_tvs pred implics
2207 | not has_ambig_tvs
2208 , isTyVarClassPred pred
2209 , (skol:skols) <- usefulContext implics pred
2210 , let what | null skols
2211 , SigSkol (PatSynCtxt {}) _ <- skol
2212 = text "\"required\""
2213 | otherwise
2214 = empty
2215 = [sep [ text "add" <+> pprParendType pred
2216 <+> text "to the" <+> what <+> text "context of"
2217 , nest 2 $ ppr_skol skol $$
2218 vcat [ text "or" <+> ppr_skol skol
2219 | skol <- skols ] ] ]
2220 | otherwise = []
2221 where
2222 ppr_skol (PatSkol (RealDataCon dc) _) = text "the data constructor" <+> quotes (ppr dc)
2223 ppr_skol (PatSkol (PatSynCon ps) _) = text "the pattern synonym" <+> quotes (ppr ps)
2224 ppr_skol skol_info = ppr skol_info
2225
2226 discardProvCtxtGivens :: CtOrigin -> [UserGiven] -> [UserGiven]
2227 discardProvCtxtGivens orig givens -- See Note [discardProvCtxtGivens]
2228 | ProvCtxtOrigin (PSB {psb_id = L _ name}) <- orig
2229 = filterOut (discard name) givens
2230 | otherwise
2231 = givens
2232 where
2233 discard n (Implic { ic_info = SigSkol (PatSynCtxt n') _ }) = n == n'
2234 discard _ _ = False
2235
2236 usefulContext :: [Implication] -> PredType -> [SkolemInfo]
2237 -- usefulContext picks out the implications whose context
2238 -- the programmer might plausibly augment to solve 'pred'
2239 usefulContext implics pred
2240 = go implics
2241 where
2242 pred_tvs = tyCoVarsOfType pred
2243 go [] = []
2244 go (ic : ics)
2245 | implausible ic = rest
2246 | otherwise = ic_info ic : rest
2247 where
2248 -- Stop when the context binds a variable free in the predicate
2249 rest | any (`elemVarSet` pred_tvs) (ic_skols ic) = []
2250 | otherwise = go ics
2251
2252 implausible ic
2253 | null (ic_skols ic) = True
2254 | implausible_info (ic_info ic) = True
2255 | otherwise = False
2256
2257 implausible_info (SigSkol (InfSigCtxt {}) _) = True
2258 implausible_info _ = False
2259 -- Do not suggest adding constraints to an *inferred* type signature
2260
2261 {- Note [Report candidate instances]
2262 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2263 If we have an unsolved (Num Int), where `Int` is not the Prelude Int,
2264 but comes from some other module, then it may be helpful to point out
2265 that there are some similarly named instances elsewhere. So we get
2266 something like
2267 No instance for (Num Int) arising from the literal ‘3’
2268 There are instances for similar types:
2269 instance Num GHC.Types.Int -- Defined in ‘GHC.Num’
2270 Discussion in Trac #9611.
2271
2272 Note [Highlighting ambiguous type variables]
2273 ~-------------------------------------------
2274 When we encounter ambiguous type variables (i.e. type variables
2275 that remain metavariables after type inference), we need a few more
2276 conditions before we can reason that *ambiguity* prevents constraints
2277 from being solved:
2278 - We can't have any givens, as encountering a typeclass error
2279 with given constraints just means we couldn't deduce
2280 a solution satisfying those constraints and as such couldn't
2281 bind the type variable to a known type.
2282 - If we don't have any unifiers, we don't even have potential
2283 instances from which an ambiguity could arise.
2284 - Lastly, I don't want to mess with error reporting for
2285 unknown runtime types so we just fall back to the old message there.
2286 Once these conditions are satisfied, we can safely say that ambiguity prevents
2287 the constraint from being solved.
2288
2289 Note [discardProvCtxtGivens]
2290 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
2291 In most situations we call all enclosing implications "useful". There is one
2292 exception, and that is when the constraint that causes the error is from the
2293 "provided" context of a pattern synonym declaration:
2294
2295 pattern Pat :: (Num a, Eq a) => Show a => a -> Maybe a
2296 -- required => provided => type
2297 pattern Pat x <- (Just x, 4)
2298
2299 When checking the pattern RHS we must check that it does actually bind all
2300 the claimed "provided" constraints; in this case, does the pattern (Just x, 4)
2301 bind the (Show a) constraint. Answer: no!
2302
2303 But the implication we generate for this will look like
2304 forall a. (Num a, Eq a) => [W] Show a
2305 because when checking the pattern we must make the required
2306 constraints available, since they are needed to match the pattern (in
2307 this case the literal '4' needs (Num a, Eq a)).
2308
2309 BUT we don't want to suggest adding (Show a) to the "required" constraints
2310 of the pattern synonym, thus:
2311 pattern Pat :: (Num a, Eq a, Show a) => Show a => a -> Maybe a
2312 It would then typecheck but it's silly. We want the /pattern/ to bind
2313 the alleged "provided" constraints, Show a.
2314
2315 So we suppress that Implication in discardProvCtxtGivens. It's
2316 painfully ad-hoc but the truth is that adding it to the "required"
2317 constraints would work. Suprressing it solves two problems. First,
2318 we never tell the user that we could not deduce a "provided"
2319 constraint from the "required" context. Second, we never give a
2320 possible fix that suggests to add a "provided" constraint to the
2321 "required" context.
2322
2323 For example, without this distinction the above code gives a bad error
2324 message (showing both problems):
2325
2326 error: Could not deduce (Show a) ... from the context: (Eq a)
2327 ... Possible fix: add (Show a) to the context of
2328 the signature for pattern synonym `Pat' ...
2329
2330 -}
2331
2332 show_fixes :: [SDoc] -> SDoc
2333 show_fixes [] = empty
2334 show_fixes (f:fs) = sep [ text "Possible fix:"
2335 , nest 2 (vcat (f : map (text "or" <+>) fs))]
2336
2337 pprPotentials :: DynFlags -> PprStyle -> SDoc -> [ClsInst] -> SDoc
2338 -- See Note [Displaying potential instances]
2339 pprPotentials dflags sty herald insts
2340 | null insts
2341 = empty
2342
2343 | null show_these
2344 = hang herald
2345 2 (vcat [ not_in_scope_msg empty
2346 , flag_hint ])
2347
2348 | otherwise
2349 = hang herald
2350 2 (vcat [ pprInstances show_these
2351 , ppWhen (n_in_scope_hidden > 0) $
2352 text "...plus"
2353 <+> speakNOf n_in_scope_hidden (text "other")
2354 , not_in_scope_msg (text "...plus")
2355 , flag_hint ])
2356 where
2357 n_show = 3 :: Int
2358 show_potentials = gopt Opt_PrintPotentialInstances dflags
2359
2360 (in_scope, not_in_scope) = partition inst_in_scope insts
2361 sorted = sortBy fuzzyClsInstCmp in_scope
2362 show_these | show_potentials = sorted
2363 | otherwise = take n_show sorted
2364 n_in_scope_hidden = length sorted - length show_these
2365
2366 -- "in scope" means that all the type constructors
2367 -- are lexically in scope; these instances are likely
2368 -- to be more useful
2369 inst_in_scope :: ClsInst -> Bool
2370 inst_in_scope cls_inst = nameSetAll name_in_scope $
2371 orphNamesOfTypes (is_tys cls_inst)
2372
2373 name_in_scope name
2374 | isBuiltInSyntax name
2375 = True -- E.g. (->)
2376 | Just mod <- nameModule_maybe name
2377 = qual_in_scope (qualName sty mod (nameOccName name))
2378 | otherwise
2379 = True
2380
2381 qual_in_scope :: QualifyName -> Bool
2382 qual_in_scope NameUnqual = True
2383 qual_in_scope (NameQual {}) = True
2384 qual_in_scope _ = False
2385
2386 not_in_scope_msg herald
2387 | null not_in_scope
2388 = empty
2389 | otherwise
2390 = hang (herald <+> speakNOf (length not_in_scope) (text "instance")
2391 <+> text "involving out-of-scope types")
2392 2 (ppWhen show_potentials (pprInstances not_in_scope))
2393
2394 flag_hint = ppUnless (show_potentials || length show_these == length insts) $
2395 text "(use -fprint-potential-instances to see them all)"
2396
2397 {- Note [Displaying potential instances]
2398 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2399 When showing a list of instances for
2400 - overlapping instances (show ones that match)
2401 - no such instance (show ones that could match)
2402 we want to give it a bit of structure. Here's the plan
2403
2404 * Say that an instance is "in scope" if all of the
2405 type constructors it mentions are lexically in scope.
2406 These are the ones most likely to be useful to the programmer.
2407
2408 * Show at most n_show in-scope instances,
2409 and summarise the rest ("plus 3 others")
2410
2411 * Summarise the not-in-scope instances ("plus 4 not in scope")
2412
2413 * Add the flag -fshow-potential-instances which replaces the
2414 summary with the full list
2415 -}
2416
2417 {-
2418 Note [Flattening in error message generation]
2419 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2420 Consider (C (Maybe (F x))), where F is a type function, and we have
2421 instances
2422 C (Maybe Int) and C (Maybe a)
2423 Since (F x) might turn into Int, this is an overlap situation, and
2424 indeed (because of flattening) the main solver will have refrained
2425 from solving. But by the time we get to error message generation, we've
2426 un-flattened the constraint. So we must *re*-flatten it before looking
2427 up in the instance environment, lest we only report one matching
2428 instance when in fact there are two.
2429
2430 Re-flattening is pretty easy, because we don't need to keep track of
2431 evidence. We don't re-use the code in TcCanonical because that's in
2432 the TcS monad, and we are in TcM here.
2433
2434 Note [Suggest -fprint-explicit-kinds]
2435 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2436 It can be terribly confusing to get an error message like (Trac #9171)
2437 Couldn't match expected type ‘GetParam Base (GetParam Base Int)’
2438 with actual type ‘GetParam Base (GetParam Base Int)’
2439 The reason may be that the kinds don't match up. Typically you'll get
2440 more useful information, but not when it's as a result of ambiguity.
2441 This test suggests -fprint-explicit-kinds when all the ambiguous type
2442 variables are kind variables.
2443 -}
2444
2445 mkAmbigMsg :: Bool -- True when message has to be at beginning of sentence
2446 -> Ct -> (Bool, SDoc)
2447 mkAmbigMsg prepend_msg ct
2448 | null ambig_kvs && null ambig_tvs = (False, empty)
2449 | otherwise = (True, msg)
2450 where
2451 (ambig_kvs, ambig_tvs) = getAmbigTkvs ct
2452
2453 msg | any isRuntimeUnkSkol ambig_kvs -- See Note [Runtime skolems]
2454 || any isRuntimeUnkSkol ambig_tvs
2455 = vcat [ text "Cannot resolve unknown runtime type"
2456 <> plural ambig_tvs <+> pprQuotedList ambig_tvs
2457 , text "Use :print or :force to determine these types"]
2458
2459 | not (null ambig_tvs)
2460 = pp_ambig (text "type") ambig_tvs
2461
2462 | otherwise -- All ambiguous kind variabes; suggest -fprint-explicit-kinds
2463 -- See Note [Suggest -fprint-explicit-kinds]
2464 = vcat [ pp_ambig (text "kind") ambig_kvs
2465 , ppSuggestExplicitKinds ]
2466
2467 pp_ambig what tkvs
2468 | prepend_msg -- "Ambiguous type variable 't0'"
2469 = text "Ambiguous" <+> what <+> text "variable"
2470 <> plural tkvs <+> pprQuotedList tkvs
2471
2472 | otherwise -- "The type variable 't0' is ambiguous"
2473 = text "The" <+> what <+> text "variable" <> plural tkvs
2474 <+> pprQuotedList tkvs <+> is_or_are tkvs <+> text "ambiguous"
2475
2476 is_or_are [_] = text "is"
2477 is_or_are _ = text "are"
2478
2479 pprSkol :: [Implication] -> TcTyVar -> SDoc
2480 pprSkol implics tv
2481 = case skol_info of
2482 UnkSkol -> quotes (ppr tv) <+> text "is an unknown type variable"
2483 SigSkol ctxt ty -> ppr_rigid (pprSigSkolInfo ctxt
2484 (mkSpecForAllTys skol_tvs ty))
2485 _ -> ppr_rigid (pprSkolInfo skol_info)
2486 where
2487 Implic { ic_skols = skol_tvs, ic_info = skol_info }
2488 = getSkolemInfo implics tv
2489 ppr_rigid pp_info
2490 = hang (quotes (ppr tv) <+> text "is a rigid type variable bound by")
2491 2 (sep [ pp_info
2492 , text "at" <+> ppr (getSrcSpan tv) ])
2493
2494 getAmbigTkvs :: Ct -> ([Var],[Var])
2495 getAmbigTkvs ct
2496 = partition (`elemVarSet` dep_tkv_set) ambig_tkvs
2497 where
2498 tkvs = tyCoVarsOfCtList ct
2499 ambig_tkvs = filter isAmbiguousTyVar tkvs
2500 dep_tkv_set = tyCoVarsOfTypes (map tyVarKind tkvs)
2501
2502 getSkolemInfo :: [Implication] -> TcTyVar -> Implication
2503 -- Get the skolem info for a type variable
2504 -- from the implication constraint that binds it
2505 getSkolemInfo [] tv
2506 = pprPanic "No skolem info:" (ppr tv)
2507
2508 getSkolemInfo (implic:implics) tv
2509 | tv `elem` ic_skols implic = implic
2510 | otherwise = getSkolemInfo implics tv
2511
2512 -----------------------
2513 -- relevantBindings looks at the value environment and finds values whose
2514 -- types mention any of the offending type variables. It has to be
2515 -- careful to zonk the Id's type first, so it has to be in the monad.
2516 -- We must be careful to pass it a zonked type variable, too.
2517 --
2518 -- We always remove closed top-level bindings, though,
2519 -- since they are never relevant (cf Trac #8233)
2520
2521 relevantBindings :: Bool -- True <=> filter by tyvar; False <=> no filtering
2522 -- See Trac #8191
2523 -> ReportErrCtxt -> Ct
2524 -> TcM (ReportErrCtxt, SDoc, Ct)
2525 -- Also returns the zonked and tidied CtOrigin of the constraint
2526 relevantBindings want_filtering ctxt ct
2527 = do { dflags <- getDynFlags
2528 ; (env1, tidy_orig) <- zonkTidyOrigin (cec_tidy ctxt) (ctLocOrigin loc)
2529 ; let ct_tvs = tyCoVarsOfCt ct `unionVarSet` extra_tvs
2530
2531 -- For *kind* errors, report the relevant bindings of the
2532 -- enclosing *type* equality, because that's more useful for the programmer
2533 extra_tvs = case tidy_orig of
2534 KindEqOrigin t1 m_t2 _ _ -> tyCoVarsOfTypes $
2535 t1 : maybeToList m_t2
2536 _ -> emptyVarSet
2537 ; traceTc "relevantBindings" $
2538 vcat [ ppr ct
2539 , pprCtOrigin (ctLocOrigin loc)
2540 , ppr ct_tvs
2541 , pprWithCommas id [ ppr id <+> dcolon <+> ppr (idType id)
2542 | TcIdBndr id _ <- tcl_bndrs lcl_env ]
2543 , pprWithCommas id
2544 [ ppr id | TcIdBndr_ExpType id _ _ <- tcl_bndrs lcl_env ] ]
2545
2546 ; (tidy_env', docs, discards)
2547 <- go env1 ct_tvs (maxRelevantBinds dflags)
2548 emptyVarSet [] False
2549 (remove_shadowing $ tcl_bndrs lcl_env)
2550 -- tcl_bndrs has the innermost bindings first,
2551 -- which are probably the most relevant ones
2552
2553 ; let doc = ppUnless (null docs) $
2554 hang (text "Relevant bindings include")
2555 2 (vcat docs $$ ppWhen discards discardMsg)
2556
2557 -- Put a zonked, tidied CtOrigin into the Ct
2558 loc' = setCtLocOrigin loc tidy_orig
2559 ct' = setCtLoc ct loc'
2560 ctxt' = ctxt { cec_tidy = tidy_env' }
2561
2562 ; return (ctxt', doc, ct') }
2563 where
2564 ev = ctEvidence ct
2565 loc = ctEvLoc ev
2566 lcl_env = ctLocEnv loc
2567
2568 run_out :: Maybe Int -> Bool
2569 run_out Nothing = False
2570 run_out (Just n) = n <= 0
2571
2572 dec_max :: Maybe Int -> Maybe Int
2573 dec_max = fmap (\n -> n - 1)
2574
2575 ---- fixes #12177
2576 ---- builds up a list of bindings whose OccName has not been seen before
2577 remove_shadowing :: [TcIdBinder] -> [TcIdBinder]
2578 remove_shadowing bindings = reverse $ fst $ foldl
2579 (\(bindingAcc, seenNames) binding ->
2580 if (occName binding) `elemOccSet` seenNames -- if we've seen it
2581 then (bindingAcc, seenNames) -- skip it
2582 else (binding:bindingAcc, extendOccSet seenNames (occName binding)))
2583 ([], emptyOccSet) bindings
2584
2585 go :: TidyEnv -> TcTyVarSet -> Maybe Int -> TcTyVarSet -> [SDoc]
2586 -> Bool -- True <=> some filtered out due to lack of fuel
2587 -> [TcIdBinder]
2588 -> TcM (TidyEnv, [SDoc], Bool) -- The bool says if we filtered any out
2589 -- because of lack of fuel
2590 go tidy_env _ _ _ docs discards []
2591 = return (tidy_env, reverse docs, discards)
2592 go tidy_env ct_tvs n_left tvs_seen docs discards (tc_bndr : tc_bndrs)
2593 = case tc_bndr of
2594 TcIdBndr id top_lvl -> go2 (idName id) (idType id) top_lvl
2595 TcIdBndr_ExpType name et top_lvl ->
2596 do { mb_ty <- readExpType_maybe et
2597 -- et really should be filled in by now. But there's a chance
2598 -- it hasn't, if, say, we're reporting a kind error en route to
2599 -- checking a term. See test indexed-types/should_fail/T8129
2600 ; ty <- case mb_ty of
2601 Just ty -> return ty
2602 Nothing -> do { traceTc "Defaulting an ExpType in relevantBindings"
2603 (ppr et)
2604 ; expTypeToType et }
2605 ; go2 name ty top_lvl }
2606 where
2607 go2 id_name id_type top_lvl
2608 = do { (tidy_env', tidy_ty) <- zonkTidyTcType tidy_env id_type
2609 ; traceTc "relevantBindings 1" (ppr id_name <+> dcolon <+> ppr tidy_ty)
2610 ; let id_tvs = tyCoVarsOfType tidy_ty
2611 doc = sep [ pprPrefixOcc id_name <+> dcolon <+> ppr tidy_ty
2612 , nest 2 (parens (text "bound at"
2613 <+> ppr (getSrcLoc id_name)))]
2614 new_seen = tvs_seen `unionVarSet` id_tvs
2615
2616 ; if (want_filtering && not opt_PprStyle_Debug
2617 && id_tvs `disjointVarSet` ct_tvs)
2618 -- We want to filter out this binding anyway
2619 -- so discard it silently
2620 then go tidy_env ct_tvs n_left tvs_seen docs discards tc_bndrs
2621
2622 else if isTopLevel top_lvl && not (isNothing n_left)
2623 -- It's a top-level binding and we have not specified
2624 -- -fno-max-relevant-bindings, so discard it silently
2625 then go tidy_env ct_tvs n_left tvs_seen docs discards tc_bndrs
2626
2627 else if run_out n_left && id_tvs `subVarSet` tvs_seen
2628 -- We've run out of n_left fuel and this binding only
2629 -- mentions aleady-seen type variables, so discard it
2630 then go tidy_env ct_tvs n_left tvs_seen docs True tc_bndrs
2631
2632 -- Keep this binding, decrement fuel
2633 else go tidy_env' ct_tvs (dec_max n_left) new_seen (doc:docs) discards tc_bndrs }
2634
2635 discardMsg :: SDoc
2636 discardMsg = text "(Some bindings suppressed;" <+>
2637 text "use -fmax-relevant-binds=N or -fno-max-relevant-binds)"
2638
2639 -----------------------
2640 warnDefaulting :: [Ct] -> Type -> TcM ()
2641 warnDefaulting wanteds default_ty
2642 = do { warn_default <- woptM Opt_WarnTypeDefaults
2643 ; env0 <- tcInitTidyEnv
2644 ; let tidy_env = tidyFreeTyCoVars env0 $
2645 tyCoVarsOfCtsList (listToBag wanteds)
2646 tidy_wanteds = map (tidyCt tidy_env) wanteds
2647 (loc, ppr_wanteds) = pprWithArising tidy_wanteds
2648 warn_msg =
2649 hang (hsep [ text "Defaulting the following"
2650 , text "constraint" <> plural tidy_wanteds
2651 , text "to type"
2652 , quotes (ppr default_ty) ])
2653 2
2654 ppr_wanteds
2655 ; setCtLocM loc $ warnTc (Reason Opt_WarnTypeDefaults) warn_default warn_msg }
2656
2657 {-
2658 Note [Runtime skolems]
2659 ~~~~~~~~~~~~~~~~~~~~~~
2660 We want to give a reasonably helpful error message for ambiguity
2661 arising from *runtime* skolems in the debugger. These
2662 are created by in RtClosureInspect.zonkRTTIType.
2663
2664 ************************************************************************
2665 * *
2666 Error from the canonicaliser
2667 These ones are called *during* constraint simplification
2668 * *
2669 ************************************************************************
2670 -}
2671
2672 solverDepthErrorTcS :: CtLoc -> TcType -> TcM a
2673 solverDepthErrorTcS loc ty
2674 = setCtLocM loc $
2675 do { ty <- zonkTcType ty
2676 ; env0 <- tcInitTidyEnv
2677 ; let tidy_env = tidyFreeTyCoVars env0 (tyCoVarsOfTypeList ty)
2678 tidy_ty = tidyType tidy_env ty
2679 msg
2680 = vcat [ text "Reduction stack overflow; size =" <+> ppr depth
2681 , hang (text "When simplifying the following type:")
2682 2 (ppr tidy_ty)
2683 , note ]
2684 ; failWithTcM (tidy_env, msg) }
2685 where
2686 depth = ctLocDepth loc
2687 note = vcat
2688 [ text "Use -freduction-depth=0 to disable this check"
2689 , text "(any upper bound you could choose might fail unpredictably with"
2690 , text " minor updates to GHC, so disabling the check is recommended if"
2691 , text " you're sure that type checking should terminate)" ]