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