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