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