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