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