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