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