TcErrors.hs 93.7 KB
Newer Older
1
{-# LANGUAGE CPP, ScopedTypeVariables #-}
2 3

module TcErrors(
4
       reportUnsolved, reportAllUnsolved, warnAllUnsolved,
5
       warnDefaulting,
6 7

       solverDepthErrorTcS
8 9 10 11
  ) where

#include "HsVersions.h"

12
import TcRnTypes
13 14 15
import TcRnMonad
import TcMType
import TcType
16
import RnEnv( unknownNameSuggestions )
batterseapower's avatar
batterseapower committed
17
import Type
18 19
import TyCoRep
import Kind
20
import Unify            ( tcMatchTys )
21
import Module
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
22
import FamInst
23
import FamInstEnv       ( flattenTys )
24 25 26
import Inst
import InstEnv
import TyCon
27
import Class
28
import DataCon
29
import TcEvidence
30
import Name
31
import RdrName ( lookupGRE_Name, GlobalRdrEnv, mkRdrUnqual )
32 33
import PrelNames ( typeableClassName, hasKey
                 , liftedDataConKey, unliftedDataConKey )
34
import Id
35 36 37
import Var
import VarSet
import VarEnv
38
import NameSet
39
import Bag
40
import ErrUtils         ( ErrMsg, errDoc, pprLocErrMsg )
41
import BasicTypes
42 43 44
import Util
import FastString
import Outputable
45
import SrcLoc
46
import DynFlags
47
import StaticFlags      ( opt_PprStyle_Debug )
48
import ListSetOps       ( equivClasses )
49
import Maybes
50
import qualified GHC.LanguageExtensions as LangExt
Icelandjack's avatar
Icelandjack committed
51

52
import Control.Monad    ( when )
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
53
import Data.List        ( partition, mapAccumL, nub, sortBy )
54

55 56 57
#if __GLASGOW_HASKELL__ < 709
import Data.Monoid      ( Monoid, mempty, mappend, mconcat )
#endif
58 59 60 61
#if __GLASGOW_HASKELL__ > 710
import Data.Semigroup   ( Semigroup )
import qualified Data.Semigroup as Semigroup
#endif
62 63


Austin Seipp's avatar
Austin Seipp committed
64 65 66
{-
************************************************************************
*                                                                      *
67
\section{Errors and contexts}
Austin Seipp's avatar
Austin Seipp committed
68 69
*                                                                      *
************************************************************************
70 71 72 73 74

ToDo: for these error messages, should we note the location as coming
from the insts, or just whatever seems to be around in the monad just
now?

75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
Note [Deferring coercion errors to runtime]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
While developing, sometimes it is desirable to allow compilation to succeed even
if there are type errors in the code. Consider the following case:

  module Main where

  a :: Int
  a = 'a'

  main = print "b"

Even though `a` is ill-typed, it is not used in the end, so if all that we're
interested in is `main` it is handy to be able to ignore the problems in `a`.

Since we treat type equalities as evidence, this is relatively simple. Whenever
we run into a type mismatch in TcUnify, we normally just emit an error. But it
is always safe to defer the mismatch to the main constraint solver. If we do
that, `a` will get transformed into
94

95 96 97 98 99 100 101 102 103 104 105 106 107 108
  co :: Int ~ Char
  co = ...

  a :: Int
  a = 'a' `cast` co

The constraint solver would realize that `co` is an insoluble constraint, and
emit an error with `reportUnsolved`. But we can also replace the right-hand side
of `co` with `error "Deferred type error: Int ~ Char"`. This allows the program
to compile, and it will run fine unless we evaluate `a`. This is what
`deferErrorsToRuntime` does.

It does this by keeping track of which errors correspond to which coercion
in TcErrors. TcErrors.reportTidyWanteds does not print the errors
109
and does not fail if -fdefer-type-errors is on, so that we can continue
110
compilation. The errors are turned into warnings in `reportUnsolved`.
Austin Seipp's avatar
Austin Seipp committed
111
-}
112

113 114
-- | Report unsolved goals as errors or warnings. We may also turn some into
-- deferred run-time errors if `-fdefer-type-errors` is on.
115 116
reportUnsolved :: WantedConstraints -> TcM (Bag EvBind)
reportUnsolved wanted
117 118 119 120 121 122
  = do { binds_var <- newTcEvBinds
       ; defer_errors <- goptM Opt_DeferTypeErrors
       ; warn_errors <- woptM Opt_WarnDeferredTypeErrors -- implement #10283
       ; let type_errors | not defer_errors = TypeError
                         | warn_errors      = TypeWarn
                         | otherwise        = TypeDefer
123

124
       ; defer_holes <- goptM Opt_DeferTypedHoles
125 126 127 128 129
       ; warn_holes  <- woptM Opt_WarnTypedHoles
       ; let expr_holes | not defer_holes = HoleError
                        | warn_holes      = HoleWarn
                        | otherwise       = HoleDefer

130
       ; partial_sigs      <- xoptM LangExt.PartialTypeSignatures
thomasw's avatar
thomasw committed
131
       ; warn_partial_sigs <- woptM Opt_WarnPartialTypeSignatures
132 133 134 135
       ; let type_holes | not partial_sigs  = HoleError
                        | warn_partial_sigs = HoleWarn
                        | otherwise         = HoleDefer

136
       ; report_unsolved (Just binds_var) False type_errors expr_holes type_holes wanted
137 138
       ; getTcEvBinds binds_var }

139
-- | Report *all* unsolved goals as errors, even if -fdefer-type-errors is on
140
-- See Note [Deferring coercion errors to runtime]
141
reportAllUnsolved :: WantedConstraints -> TcM ()
142
reportAllUnsolved wanted
143
  = report_unsolved Nothing False TypeError HoleError HoleError wanted
144

145 146 147 148 149
-- | Report all unsolved goals as warnings (but without deferring any errors to
-- run-time). See Note [Safe Haskell Overlapping Instances Implementation] in
-- TcSimplify
warnAllUnsolved :: WantedConstraints -> TcM ()
warnAllUnsolved wanted
150
  = report_unsolved Nothing True TypeWarn HoleWarn HoleWarn wanted
151 152

-- | Report unsolved goals as errors or warnings.
153
report_unsolved :: Maybe EvBindsVar  -- cec_binds
154
                -> Bool              -- Errors as warnings
155
                -> TypeErrorChoice   -- Deferred type errors
156 157
                -> HoleChoice        -- Expression holes
                -> HoleChoice        -- Type holes
158
                -> WantedConstraints -> TcM ()
159
report_unsolved mb_binds_var err_as_warn type_errors expr_holes type_holes wanted
160
  | isEmptyWC wanted
161
  = return ()
162
  | otherwise
163
  = do { traceTc "reportUnsolved (before zonking and tidying)" (ppr wanted)
164

165
       ; wanted <- zonkWC wanted   -- Zonk to reveal all information
166
       ; env0 <- tcInitTidyEnv
167 168
            -- If we are deferring we are going to need /all/ evidence around,
            -- including the evidence produced by unflattening (zonkWC)
169 170
       ; let tidy_env = tidyFreeTyCoVars env0 free_tvs
             free_tvs = tyCoVarsOfWC wanted
171 172 173 174 175 176 177

       ; traceTc "reportUnsolved (after zonking and tidying):" $
         vcat [ pprTvBndrs (varSetElems free_tvs)
              , ppr wanted ]

       ; warn_redundant <- woptM Opt_WarnRedundantConstraints
       ; let err_ctxt = CEC { cec_encl  = []
178
                            , cec_tidy  = tidy_env
179
                            , cec_defer_type_errors = type_errors
180
                            , cec_errors_as_warns = err_as_warn
181 182
                            , cec_expr_holes = expr_holes
                            , cec_type_holes = type_holes
183
                            , cec_suppress = False -- See Note [Suppressing error messages]
184
                            , cec_warn_redundant = warn_redundant
185
                            , cec_binds    = mb_binds_var }
186

187 188
       ; tc_lvl <- getTcLevel
       ; reportWanteds err_ctxt tc_lvl wanted }
189

190 191 192
--------------------------------------------
--      Internal functions
--------------------------------------------
193

194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
-- | An error Report collects messages categorised by their importance.
-- See Note [Error report] for details.
data Report
  = Report { report_important :: [SDoc]
           , report_relevant_bindings :: [SDoc]
           }

{- Note [Error report]
The idea is that error msgs are divided into three parts: the main msg, the
context block (\"In the second argument of ...\"), and the relevant bindings
block, which are displayed in that order, with a mark to divide them.  The
idea is that the main msg ('report_important') varies depending on the error
in question, but context and relevant bindings are always the same, which
should simplify visual parsing.

The context is added when the the Report is passed off to 'mkErrorReport'.
Unfortunately, unlike the context, the relevant bindings are added in
multiple places so they have to be in the Report.
-}

214 215 216 217 218
#if __GLASGOW_HASKELL__ > 710
instance Semigroup Report where
    Report a1 b1 <> Report a2 b2 = Report (a1 ++ a2) (b1 ++ b2)
#endif

219 220 221 222 223 224 225 226 227 228 229 230
instance Monoid Report where
    mempty = Report [] []
    mappend (Report a1 b1) (Report a2 b2) = Report (a1 ++ a2) (b1 ++ b2)

-- | Put a doc into the important msgs block.
important :: SDoc -> Report
important doc = mempty { report_important = [doc] }

-- | Put a doc into the relevant bindings block.
relevant_bindings :: SDoc -> Report
relevant_bindings doc = mempty { report_relevant_bindings = [doc] }

231 232 233 234 235
data TypeErrorChoice   -- What to do for type errors found by the type checker
  = TypeError     -- A type error aborts compilation with an error message
  | TypeWarn      -- A type error is deferred to runtime, plus a compile-time warning
  | TypeDefer     -- A type error is deferred to runtime; no error or warning at compile time

236 237 238 239 240
data HoleChoice
  = HoleError     -- A hole is a compile-time error
  | HoleWarn      -- Defer to runtime, emit a compile-time warning
  | HoleDefer     -- Defer to runtime, no warning

241
data ReportErrCtxt
242
    = CEC { cec_encl :: [Implication]  -- Enclosing implications
243
                                       --   (innermost first)
244
                                       -- ic_skols and givens are tidied, rest are not
245
          , cec_tidy  :: TidyEnv
246
          , cec_binds :: Maybe EvBindsVar
247 248 249 250
                         -- Nothinng <=> Report all errors, including holes; no bindings
                         -- Just ev  <=> make some errors (depending on cec_defer)
                         --              into warnings, and emit evidence bindings
                         --              into 'ev' for unsolved constraints
251

252 253 254 255
          , cec_errors_as_warns :: Bool   -- Turn all errors into warnings
                                          -- (except for Holes, which are
                                          -- controlled by cec_type_holes and
                                          -- cec_expr_holes)
256 257
          , cec_defer_type_errors :: TypeErrorChoice -- Defer type errors until runtime
                                                     -- Irrelevant if cec_binds = Nothing
258

259 260
          , cec_expr_holes :: HoleChoice  -- Holes in expressions
          , cec_type_holes :: HoleChoice  -- Holes in types
261

262
          , cec_warn_redundant :: Bool    -- True <=> -Wredundant-constraints
263

264 265 266
          , cec_suppress :: Bool    -- True <=> More important errors have occurred,
                                    --          so create bindings if need be, but
                                    --          don't issue any more errors/warnings
267
                                    -- See Note [Suppressing error messages]
268 269
      }

Austin Seipp's avatar
Austin Seipp committed
270
{-
271 272
Note [Suppressing error messages]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
273
The cec_suppress flag says "don't report any errors".  Instead, just create
274
evidence bindings (as usual).  It's used when more important errors have occurred.
275

276 277 278
Specifically (see reportWanteds)
  * If there are insoluble Givens, then we are in unreachable code and all bets
    are off.  So don't report any further errors.
279
  * If there are any insolubles (eg Int~Bool), here or in a nested implication,
280 281
    then suppress errors from the simple constraints here.  Sometimes the
    simple-constraint errors are a knock-on effect of the insolubles.
Austin Seipp's avatar
Austin Seipp committed
282
-}
283

284 285
reportImplic :: ReportErrCtxt -> Implication -> TcM ()
reportImplic ctxt implic@(Implic { ic_skols = tvs, ic_given = given
286
                                 , ic_wanted = wanted, ic_binds = m_evb
287
                                 , ic_status = status, ic_info = info
288
                                 , ic_env = tcl_env, ic_tclvl = tc_lvl })
289
  | BracketSkol <- info
290
  , not insoluble
291 292
  = return ()        -- For Template Haskell brackets report only
                     -- definite errors. The whole thing will be re-checked
Simon Peyton Jones's avatar
Simon Peyton Jones committed
293 294
                     -- later when we plug it in, and meanwhile there may
                     -- certainly be un-satisfied constraints
295 296

  | otherwise
297
  = do { reportWanteds ctxt' tc_lvl wanted
298 299 300
       ; traceTc "reportImplic" (ppr implic)
       ; when (cec_warn_redundant ctxt) $
         warnRedundantConstraints ctxt' tcl_env info' dead_givens }
301
  where
302
    insoluble    = isInsolubleStatus status
303
    (env1, tvs') = mapAccumL tidyTyCoVarBndr (cec_tidy ctxt) tvs
304
    (env2, info') = tidySkolemInfo env1 info
305
    implic' = implic { ic_skols = tvs'
306 307
                     , ic_given = map (tidyEvVar env2) given
                     , ic_info  = info' }
308 309 310 311 312
    ctxt' = ctxt { cec_tidy     = env2
                 , cec_encl     = implic' : cec_encl ctxt
                 , cec_suppress = insoluble  -- Suppress inessential errors if there
                                             -- are are insolubles anywhere in the
                                             -- tree rooted here
313 314 315 316 317
                 , cec_binds    = cec_binds ctxt *> m_evb }
                                  -- if cec_binds ctxt is Nothing, that means
                                  -- we're reporting *all* errors. Don't change
                                  -- that behavior just because we're going into
                                  -- an implication.
318 319 320 321 322 323
    dead_givens = case status of
                    IC_Solved { ics_dead = dead } -> dead
                    _                             -> []

warnRedundantConstraints :: ReportErrCtxt -> TcLclEnv -> SkolemInfo -> [EvVar] -> TcM ()
warnRedundantConstraints ctxt env info ev_vars
324
 | null redundant_evs
325 326 327 328 329 330 331
 = return ()

 | SigSkol {} <- info
 = setLclEnv env $  -- We want to add "In the type signature for f"
                    -- to the error context, which is a bit tiresome
   addErrCtxt (ptext (sLit "In") <+> ppr info) $
   do { env <- getLclEnv
332
      ; msg <- mkErrorReport ctxt env (important doc)
333 334 335 336 337
      ; reportWarning msg }

 | otherwise  -- But for InstSkol there already *is* a surrounding
              -- "In the instance declaration for Eq [a]" context
              -- and we don't want to say it twice. Seems a bit ad-hoc
338
 = do { msg <- mkErrorReport ctxt env (important doc)
339 340
      ; reportWarning msg }
 where
341 342 343 344 345 346 347 348
   doc = ptext (sLit "Redundant constraint") <> plural redundant_evs <> colon
         <+> pprEvVarTheta redundant_evs

   redundant_evs = case info of -- See Note [Redundant constraints in instance decls]
                     InstSkol -> filterOut improving ev_vars
                     _        -> ev_vars

   improving ev_var = any isImprovementPred $
349
                      transSuperClasses (idType ev_var)
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366

{- Note [Redundant constraints in instance decls]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For instance declarations, we don't report unused givens if
they can give rise to improvement.  Example (Trac #10100):
    class Add a b ab | a b -> ab, a ab -> b
    instance Add Zero b b
    instance Add a b ab => Add (Succ a) b (Succ ab)
The context (Add a b ab) for the instance is clearly unused in terms
of evidence, since the dictionary has no feilds.  But it is still
needed!  With the context, a wanted constraint
   Add (Succ Zero) beta (Succ Zero)
we will reduce to (Add Zero beta Zero), and thence we get beta := Zero.
But without the context we won't find beta := Zero.

This only matters in instance declarations..
-}
367

368 369
reportWanteds :: ReportErrCtxt -> TcLevel -> WantedConstraints -> TcM ()
reportWanteds ctxt tc_lvl (WC { wc_simple = simples, wc_insol = insols, wc_impl = implics })
370 371
  = do { traceTc "reportWanteds" (vcat [ ptext (sLit "Simples =") <+> ppr simples
                                       , ptext (sLit "Suppress =") <+> ppr (cec_suppress ctxt)])
372
       ; let tidy_cts = bagToList (mapBag (tidyCt env) (insols `unionBags` simples))
373 374 375 376

         -- First deal with things that are utterly wrong
         -- Like Int ~ Bool (incl nullary TyCons)
         -- or  Int ~ t a   (AppTy on one side)
377 378 379 380 381 382 383 384 385
         -- These ones are not suppressed by the incoming context
       ; let ctxt_for_insols = ctxt { cec_suppress = False }
       ; (ctxt1, cts1) <- tryReporters ctxt_for_insols report1 tidy_cts

         -- Now all the other constraints.  We suppress errors here if
         -- any of the first batch failed, or if the enclosing context
         -- says to suppress
       ; let ctxt2 = ctxt { cec_suppress = cec_suppress ctxt || cec_suppress ctxt1 }
       ; (_, leftovers) <- tryReporters ctxt2 report2 cts1
386 387
       ; MASSERT2( null leftovers, ppr leftovers )

388
            -- All the Derived ones have been filtered out of simples
389 390 391
            -- by the constraint solver. This is ok; we don't want
            -- to report unsolved Derived goals as errors
            -- See Note [Do not report derived but soluble errors]
392

393
     ; mapBagM_ (reportImplic ctxt2) implics }
394
            -- NB ctxt1: don't suppress inner insolubles if there's only a
395
            -- wanted insoluble here; but do suppress inner insolubles
396
            -- if there's a *given* insoluble here (= inaccessible code)
397
 where
398
    env = cec_tidy ctxt
399

400 401 402 403 404 405
    -- report1: ones that should *not* be suppresed by
    --          an insoluble somewhere else in the tree
    -- It's crucial that anything that is considered insoluble
    -- (see TcRnTypes.trulyInsoluble) is caught here, otherwise
    -- we might suppress its error message, and proceed on past
    -- type checking to get a Lint error later
406 407
    report1 = [ ("custom_error", is_user_type_error,
                                                  True, mkUserTypeErrorReporter)
408
              , ("insoluble1",   is_given_eq,     True, mkGroupReporter mkEqErr)
409
              , ("insoluble2",   utterly_wrong,   True, mkGroupReporter mkEqErr)
410 411 412
              , ("skolem eq1",   very_wrong,      True, mkSkolReporter)
              , ("skolem eq2",   skolem_eq,       True, mkSkolReporter)
              , ("non-tv eq",    non_tv_eq,       True, mkSkolReporter)
413 414 415 416 417 418 419 420 421 422 423 424
              , ("Out of scope", is_out_of_scope, True,  mkHoleReporter)
              , ("Holes",        is_hole,         False, mkHoleReporter)

                  -- The only remaining equalities are alpha ~ ty,
                  -- where alpha is untouchable; and representational equalities
              , ("Other eqs",    is_equality,     False, mkGroupReporter mkEqErr) ]

    -- report2: we suppress these if there are insolubles elsewhere in the tree
    report2 = [ ("Implicit params", is_ip,           False, mkGroupReporter mkIPErr)
              , ("Irreds",          is_irred,        False, mkGroupReporter mkIrredErr)
              , ("Dicts",           is_dict,         False, mkGroupReporter mkDictErr) ]

425 426
    -- rigid_nom_eq, rigid_nom_tv_eq,
    is_hole, is_dict,
427
      is_equality, is_ip, is_irred :: Ct -> PredTree -> Bool
428

429 430 431 432 433
    is_given_eq ct pred
       | EqPred {} <- pred = arisesFromGivens ct
       | otherwise         = False
       -- I think all given residuals are equalities

434 435 436 437 438 439 440
    -- Things like (Int ~N Bool)
    utterly_wrong _ (EqPred NomEq ty1 ty2) = isRigidTy ty1 && isRigidTy ty2
    utterly_wrong _ _                      = False

    -- Things like (a ~N Int)
    very_wrong _ (EqPred NomEq ty1 ty2) = isSkolemTy tc_lvl ty1 && isRigidTy ty2
    very_wrong _ _                      = False
441

442 443 444
    -- Things like (a ~N b) or (a  ~N  F Bool)
    skolem_eq _ (EqPred NomEq ty1 _) =  isSkolemTy tc_lvl ty1
    skolem_eq _ _                    = False
445

446 447 448 449 450 451 452 453 454 455 456 457 458 459
    -- Things like (F a  ~N  Int)
    non_tv_eq _ (EqPred NomEq ty1 _) = not (isTyVarTy ty1)
    non_tv_eq _ _                    = False

--    rigid_nom_eq _ pred = isRigidEqPred tc_lvl pred
--
--    rigid_nom_tv_eq _ pred
--      | EqPred _ ty1 _ <- pred = isRigidEqPred tc_lvl pred && isTyVarTy ty1
--      | otherwise              = False

    is_out_of_scope ct _ = isOutOfScopeCt ct
    is_hole         ct _ = isHoleCt ct

    is_user_type_error ct _ = isUserTypeErrorCt ct
460

461 462 463
    is_equality _ (EqPred {}) = True
    is_equality _ _           = False

464 465 466 467 468 469 470 471 472 473
    is_dict _ (ClassPred {}) = True
    is_dict _ _              = False

    is_ip _ (ClassPred cls _) = isIPClass cls
    is_ip _ _                 = False

    is_irred _ (IrredPred {}) = True
    is_irred _ _              = False


474
---------------
475 476 477 478 479 480 481 482 483
isSkolemTy :: TcLevel -> Type -> Bool
isSkolemTy tc_lvl ty
  = case getTyVar_maybe ty of
      Nothing -> False
      Just tv -> isSkolemTyVar tv
              || (isSigTyVar tv && isTouchableMetaTyVar tc_lvl tv)
         -- The latter case is for touchable SigTvs
         -- we postpone untouchables to a latter test (too obscure)

484 485
isTyFun_maybe :: Type -> Maybe TyCon
isTyFun_maybe ty = case tcSplitTyConApp_maybe ty of
486
                      Just (tc,_) | isTypeFamilyTyCon tc -> Just tc
487 488
                      _ -> Nothing

489 490

--------------------------------------------
491
--      Reporters
492 493
--------------------------------------------

494 495 496 497 498 499 500 501 502
type Reporter
  = ReportErrCtxt -> [Ct] -> TcM ()
type ReporterSpec
  = ( String                     -- Name
    , Ct -> PredTree -> Bool     -- Pick these ones
    , Bool                       -- True <=> suppress subsequent reporters
    , Reporter)                  -- The reporter itself

mkSkolReporter :: Reporter
503
-- Suppress duplicates with either the same LHS, or same location
504
mkSkolReporter ctxt cts
505
  = mapM_ (reportGroup mkEqErr ctxt) (group cts)
506
  where
507 508 509 510 511 512 513 514 515
     group [] = []
     group (ct:cts) = (ct : yeses) : group noes
        where
          (yeses, noes) = partition (group_with ct) cts

     group_with ct1 ct2
       | EQ <- cmp_loc      ct1 ct2 = True
       | EQ <- cmp_lhs_type ct1 ct2 = True
       | otherwise                  = False
516

517
mkHoleReporter :: Reporter
518
-- Reports errors one at a time
519
mkHoleReporter ctxt
520
  = mapM_ $ \ct ->
521 522
    do { err <- mkHoleError ctxt ct
       ; maybeReportHoleError ctxt ct err
523
       ; maybeAddDeferredHoleBinding ctxt err ct }
524

525 526 527 528 529 530
mkUserTypeErrorReporter :: Reporter
mkUserTypeErrorReporter ctxt
  = mapM_ $ \ct -> maybeReportError ctxt =<< mkUserTypeError ctxt ct

mkUserTypeError :: ReportErrCtxt -> Ct -> TcM ErrMsg
mkUserTypeError ctxt ct = mkErrorMsgFromCt ctxt ct
531
                        $ important
532 533
                        $ pprUserTypeErrorTy
                        $ case getUserTypeErrorMsg ct of
534 535
                            Just msg -> msg
                            Nothing  -> pprPanic "mkUserTypeError" (ppr ct)
536 537


538 539 540
mkGroupReporter :: (ReportErrCtxt -> [Ct] -> TcM ErrMsg)
                             -- Make error message for a group
                -> Reporter  -- Deal with lots of constraints
541 542 543 544 545
-- Group together errors from same location,
-- and report only the first (to avoid a cascade)
mkGroupReporter mk_err ctxt cts
  = mapM_ (reportGroup mk_err ctxt) (equivClasses cmp_loc cts)
  where
546 547 548 549 550 551 552 553 554 555

cmp_lhs_type :: Ct -> Ct -> Ordering
cmp_lhs_type ct1 ct2
  = case (classifyPredType (ctPred ct1), classifyPredType (ctPred ct2)) of
       (EqPred eq_rel1 ty1 _, EqPred eq_rel2 ty2 _) ->
         (eq_rel1 `compare` eq_rel2) `thenCmp` (ty1 `cmpType` ty2)
       _ -> pprPanic "mkSkolReporter" (ppr ct1 $$ ppr ct2)

cmp_loc :: Ct -> Ct -> Ordering
cmp_loc ct1 ct2 = ctLocSpan (ctLoc ct1) `compare` ctLocSpan (ctLoc ct2)
556

557 558
reportGroup :: (ReportErrCtxt -> [Ct] -> TcM ErrMsg) -> ReportErrCtxt
            -> [Ct] -> TcM ()
quchen's avatar
quchen committed
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
reportGroup mk_err ctxt cts =
  case partition isMonadFailInstanceMissing cts of
        -- Only warn about missing MonadFail constraint when
        -- there are no other missing contstraints!
        (monadFailCts, []) -> do { err <- mk_err ctxt monadFailCts
                                 ; reportWarning err }

        (_, cts') -> do { err <- mk_err ctxt cts'
                        ; maybeReportError ctxt err
                        ; mapM_ (maybeAddDeferredBinding ctxt err) cts' }
                                -- Add deferred bindings for all
                                -- But see Note [Always warn with -fdefer-type-errors]
  where
    isMonadFailInstanceMissing ct =
        case ctLocOrigin (ctLoc ct) of
            FailablePattern _pat -> True
            _otherwise           -> False
576

577 578
maybeReportHoleError :: ReportErrCtxt -> Ct -> ErrMsg -> TcM ()
maybeReportHoleError ctxt ct err
thomasw's avatar
thomasw committed
579
  -- When -XPartialTypeSignatures is on, warnings (instead of errors) are
580 581 582
  -- generated for holes in partial type signatures.
  -- Unless -fwarn_partial_type_signatures is not on,
  -- in which case the messages are discarded.
583 584 585 586 587
  | isTypeHoleCt ct
  = -- For partial type signatures, generate warnings only, and do that
    -- only if -fwarn_partial_type_signatures is on
    case cec_type_holes ctxt of
       HoleError -> reportError err
588
       HoleWarn  -> reportWarning err
589 590 591
       HoleDefer -> return ()

  -- Otherwise this is a typed hole in an expression
592
  | otherwise
593
  = -- If deferring, report a warning only if -Wtyped-holds is on
594 595
    case cec_expr_holes ctxt of
       HoleError -> reportError err
596
       HoleWarn  -> reportWarning err
597
       HoleDefer -> return ()
598

599
maybeReportError :: ReportErrCtxt -> ErrMsg -> TcM ()
600
-- Report the error and/or make a deferred binding for it
601
maybeReportError ctxt err
602 603 604
  | cec_suppress ctxt    -- Some worse error has occurred;
  = return ()            -- so suppress this error/warning

605
  | cec_errors_as_warns ctxt
606
  = reportWarning err
607

608
  | otherwise
609
  = case cec_defer_type_errors ctxt of
610 611 612
      TypeDefer -> return ()
      TypeWarn  -> reportWarning err
      TypeError -> reportError err
613

614
addDeferredBinding :: ReportErrCtxt -> ErrMsg -> Ct -> TcM ()
615
-- See Note [Deferring coercion errors to runtime]
616
addDeferredBinding ctxt err ct
617
  | CtWanted { ctev_pred = pred, ctev_dest = dest } <- ctEvidence ct
618
    -- Only add deferred bindings for Wanted constraints
619
  , Just ev_binds_var <- cec_binds ctxt  -- We have somewhere to put the bindings
620 621 622 623
  = do { dflags <- getDynFlags
       ; let err_msg = pprLocErrMsg err
             err_fs  = mkFastString $ showSDoc dflags $
                       err_msg $$ text "(deferred type error)"
624
             err_tm  = EvDelayedError pred err_fs
625

626 627 628 629 630 631 632 633
       ; case dest of
           EvVarDest evar
             -> addTcEvBind ev_binds_var $ mkWantedEvBind evar err_tm
           HoleDest hole
             -> do { -- See Note [Deferred errors for coercion holes]
                     evar <- newEvVar pred
                   ; addTcEvBind ev_binds_var $ mkWantedEvBind evar err_tm
                   ; fillCoercionHole hole (mkTcCoVarCo evar) }}
634 635

  | otherwise   -- Do not set any evidence for Given/Derived
636
  = return ()
637

638 639
maybeAddDeferredHoleBinding :: ReportErrCtxt -> ErrMsg -> Ct -> TcM ()
maybeAddDeferredHoleBinding ctxt err ct
640 641 642 643 644 645 646
    | isExprHoleCt ct
    , case cec_expr_holes ctxt of
        HoleDefer -> True
        HoleWarn  -> True
        HoleError -> False
    = addDeferredBinding ctxt err ct  -- Only add bindings for holes in expressions
    | otherwise                       -- not for holes in partial type signatures
647 648 649
    = return ()

maybeAddDeferredBinding :: ReportErrCtxt -> ErrMsg -> Ct -> TcM ()
650 651 652 653 654 655 656
maybeAddDeferredBinding ctxt err ct =
  case cec_defer_type_errors ctxt of
        TypeDefer -> deferred
        TypeWarn -> deferred
        TypeError -> return ()
  where
    deferred = addDeferredBinding ctxt err ct
657

658
tryReporters :: ReportErrCtxt -> [ReporterSpec] -> [Ct] -> TcM (ReportErrCtxt, [Ct])
659
-- Use the first reporter in the list whose predicate says True
660
tryReporters ctxt reporters cts
661
  = do { traceTc "tryReporters {" (ppr cts)
662 663 664
       ; (ctxt', cts') <- go ctxt reporters cts
       ; traceTc "tryReporters }" (ppr cts')
       ; return (ctxt', cts') }
665
  where
666
    go ctxt [] cts
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
      = return (ctxt, cts)

    go ctxt (r : rs) cts
      = do { (ctxt', cts') <- tryReporter ctxt r cts
           ; go ctxt' rs cts' }
                -- Carry on with the rest, because we must make
                -- deferred bindings for them if we have -fdefer-type-errors
                -- But suppress their error messages

tryReporter :: ReportErrCtxt -> ReporterSpec -> [Ct] -> TcM (ReportErrCtxt, [Ct])
tryReporter ctxt (str, keep_me,  suppress_after, reporter) cts
  | null yeses = return (ctxt, cts)
  | otherwise  = do { traceTc "tryReporter:" (text str <+> ppr yeses)
                    ; reporter ctxt yeses
                    ; let ctxt' = ctxt { cec_suppress = suppress_after || cec_suppress ctxt }
                    ; return (ctxt', nos) }
  where
    (yeses, nos) = partition (\ct -> keep_me ct (classifyPredType (ctPred ct))) cts
685

686 687 688 689 690 691 692 693 694

pprArising :: CtOrigin -> SDoc
-- Used for the main, top-level error message
-- We've done special processing for TypeEq, KindEq, Given
pprArising (TypeEqOrigin {}) = empty
pprArising (KindEqOrigin {}) = empty
pprArising (GivenOrigin {})  = empty
pprArising orig              = pprCtOrigin orig

695
-- Add the "arising from..." part to a message about bunch of dicts
696
addArising :: CtOrigin -> SDoc -> SDoc
697
addArising orig msg = hang msg 2 (pprArising orig)
698

699
pprWithArising :: [Ct] -> (CtLoc, SDoc)
700 701
-- Print something like
--    (Eq a) arising from a use of x at y
702 703
--    (Show a) arising from a use of p at q
-- Also return a location for the error message
704
-- Works for Wanted/Derived only
705
pprWithArising []
706
  = panic "pprWithArising"
707 708
pprWithArising (ct:cts)
  | null cts
709
  = (loc, addArising (ctLocOrigin loc)
dimitris's avatar
dimitris committed
710
                     (pprTheta [ctPred ct]))
711 712
  | otherwise
  = (loc, vcat (map ppr_one (ct:cts)))
713
  where
714
    loc = ctLoc ct
715
    ppr_one ct' = hang (parens (pprType (ctPred ct')))
716
                     2 (pprCtLoc (ctLoc ct'))
717

718 719 720
mkErrorMsgFromCt :: ReportErrCtxt -> Ct -> Report -> TcM ErrMsg
mkErrorMsgFromCt ctxt ct report
  = mkErrorReport ctxt (ctLocEnv (ctLoc ct)) report
721

722 723 724 725 726 727
mkErrorReport :: ReportErrCtxt -> TcLclEnv -> Report -> TcM ErrMsg
mkErrorReport ctxt tcl_env (Report important relevant_bindings)
  = do { context <- mkErrInfo (cec_tidy ctxt) (tcl_ctxt tcl_env)
       ; mkErrDocAt (RealSrcSpan (tcl_loc tcl_env))
            (errDoc important [context] relevant_bindings)
       }
728

729
type UserGiven = ([EvVar], SkolemInfo, Bool, RealSrcSpan)
730 731

getUserGivens :: ReportErrCtxt -> [UserGiven]
732
-- One item for each enclosing implication
733
getUserGivens (CEC {cec_encl = ctxt})
734
  = reverse $
735 736 737
    [ (givens, info, no_eqs, tcl_loc env)
    | Implic { ic_given = givens, ic_env = env
             , ic_no_eqs = no_eqs, ic_info = info } <- ctxt
738
    , not (null givens) ]
739

Austin Seipp's avatar
Austin Seipp committed
740
{-
741 742 743 744 745 746
Note [Always warn with -fdefer-type-errors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When -fdefer-type-errors is on we warn about *all* type errors, even
if cec_suppress is on.  This can lead to a lot more warnings than you
would get errors without -fdefer-type-errors, but if we suppress any of
them you might get a runtime error that wasn't warned about at compile
747
time.
748 749 750 751 752

This is an easy design choice to change; just flip the order of the
first two equations for maybeReportError

To be consistent, we should also report multiple warnings from a single
753
location in mkGroupReporter, when -fdefer-type-errors is on.  But that
754 755
is perhaps a bit *over*-consistent! Again, an easy choice to change.

756 757
With #10283, you can now opt out of deferred type error warnings.

758 759 760 761 762 763 764 765 766
Note [Deferred errors for coercion holes]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we need to defer a type error where the destination for the evidence
is a coercion hole. We can't just put the error in the hole, because we can't
make an erroneous coercion. (Remember that coercions are erased for runtime.)
Instead, we invent a new EvVar, bind it to an error and then make a coercion
from that EvVar, filling the hole with that coercion. Because coercions'
types are unlifted, the error is guaranteed to be hit before we get to the
coercion.
767

768 769
Note [Do not report derived but soluble errors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
770
The wc_simples include Derived constraints that have not been solved, but are
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
not insoluble (in that case they'd be in wc_insols).  We do not want to report
these as errors:

* Superclass constraints. If we have an unsolved [W] Ord a, we'll also have
  an unsolved [D] Eq a, and we do not want to report that; it's just noise.

* Functional dependencies.  For givens, consider
      class C a b | a -> b
      data T a where
         MkT :: C a d => [d] -> T a
      f :: C a b => T a -> F Int
      f (MkT xs) = length xs
  Then we get a [D] b~d.  But there *is* a legitimate call to
  f, namely   f (MkT [True]) :: T Bool, in which b=d.  So we should
  not reject the program.

  For wanteds, something similar
      data T a where
789
        MkT :: C Int b => a -> b -> T a
790 791 792 793 794 795
      g :: C Int c => c -> ()
      f :: T a -> ()
      f (MkT x y) = g x
  Here we get [G] C Int b, [W] C Int a, hence [D] a~b.
  But again f (MkT True True) is a legitimate call.

796
(We leave the Deriveds in wc_simple until reportErrors, so that we don't lose
797 798
derived superclasses between iterations of the solver.)

799
For functional dependencies, here is a real example,
800 801 802
stripped off from libraries/utf8-string/Codec/Binary/UTF8/Generic.hs

  class C a b | a -> b
803 804 805 806
  g :: C a b => a -> b -> ()
  f :: C a b => a -> b -> ()
  f xa xb =
      let loop = g xa
807 808 809 810
      in loop xb

We will first try to infer a type for loop, and we will succeed:
    C a b' => b' -> ()
811 812 813 814 815
Subsequently, we will type check (loop xb) and all is good. But,
recall that we have to solve a final implication constraint:
    C a b => (C a b' => .... cts from body of loop .... ))
And now we have a problem as we will generate an equality b ~ b' and fail to
solve it.
816 817


Austin Seipp's avatar
Austin Seipp committed
818
************************************************************************
819
*                                                                      *
batterseapower's avatar
batterseapower committed
820
                Irreducible predicate errors
821
*                                                                      *
Austin Seipp's avatar
Austin Seipp committed
822 823
************************************************************************
-}
batterseapower's avatar
batterseapower committed
824

825
mkIrredErr :: ReportErrCtxt -> [Ct] -> TcM ErrMsg
826
mkIrredErr ctxt cts
827 828 829
  = do { (ctxt, binds_msg, ct1) <- relevantBindings True ctxt ct1
       ; let orig = ctOrigin ct1
             msg  = couldNotDeduce (getUserGivens ctxt) (map ctPred cts, orig)
830 831
       ; mkErrorMsgFromCt ctxt ct1 $
            important msg `mappend` relevant_bindings binds_msg }
batterseapower's avatar
batterseapower committed
832
  where
833
    (ct1:_) = cts
batterseapower's avatar
batterseapower committed
834

835
----------------
836
mkHoleError :: ReportErrCtxt -> Ct -> TcM ErrMsg
837
mkHoleError ctxt ct@(CHoleCan { cc_occ = occ, cc_hole = hole_sort })
Simon Peyton Jones's avatar
Simon Peyton Jones committed
838 839
  | isOutOfScopeCt ct  -- Out of scope variables, like 'a', where 'a' isn't bound
                       -- Suggest possible in-scope variables in the message
840 841
  = do { dflags  <- getDynFlags
       ; rdr_env <- getGlobalRdrEnv
Joachim Breitner's avatar
Joachim Breitner committed
842
       ; impInfo <- getImports
843 844 845 846
       ; mkErrDocAt (RealSrcSpan (tcl_loc lcl_env)) $
                    errDoc [out_of_scope_msg] []
                           [unknownNameSuggestions dflags rdr_env
                            (tcl_rdr lcl_env) impInfo (mkRdrUnqual occ)] }
847

Simon Peyton Jones's avatar
Simon Peyton Jones committed
848
  | otherwise  -- Explicit holes, like "_" or "_f"
849
  = do { (ctxt, binds_msg, ct) <- relevantBindings False ctxt ct
850
               -- The 'False' means "don't filter the bindings"; see Trac #8191
851 852
       ; mkErrorMsgFromCt ctxt ct $
            important hole_msg `mappend` relevant_bindings binds_msg }
853

854
  where
855 856 857
    ct_loc      = ctLoc ct
    lcl_env     = ctLocEnv ct_loc
    hole_ty     = ctEvPred (ctEvidence ct)
858
    tyvars      = tyCoVarsOfTypeList hole_ty
859
    boring_type = isTyVarTy hole_ty
860

861 862 863
    out_of_scope_msg -- Print v :: ty only if the type has structure
      | boring_type = hang herald 2 (ppr occ)
      | otherwise   = hang herald 2 pp_with_type
864 865 866 867 868

    pp_with_type = hang (pprPrefixOcc occ) 2 (dcolon <+> pprType hole_ty)
    herald | isDataOcc occ = ptext (sLit "Data constructor not in scope:")
           | otherwise     = ptext (sLit "Variable not in scope:")

869 870 871 872 873 874 875 876
    hole_msg = case hole_sort of
      ExprHole -> vcat [ hang (ptext (sLit "Found hole:"))
                            2 pp_with_type
                       , tyvars_msg, expr_hole_hint ]
      TypeHole -> vcat [ hang (ptext (sLit "Found type wildcard") <+> quotes (ppr occ))
                            2 (ptext (sLit "standing for") <+> quotes (pprType hole_ty))
                       , tyvars_msg, type_hole_hint ]

877 878 879
    tyvars_msg = ppUnless (null tyvars) $
                 ptext (sLit "Where:") <+> vcat (map loc_msg tyvars)

880 881
    type_hole_hint
         | HoleError <- cec_type_holes ctxt
882
         = ptext (sLit "To use the inferred type, enable PartialTypeSignatures")
883 884
         | otherwise
         = empty
885

886 887
    expr_hole_hint                       -- Give hint for, say,   f x = _x
         | lengthFS (occNameFS occ)<