TcErrors.hs 127 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 13
import GhcPrelude

14
import TcRnTypes
15 16
import TcRnMonad
import TcMType
17
import TcUnify( occCheckForErrors, OccCheckResult(..) )
18
import TcEnv( tcInitTidyEnv )
19
import TcType
20
import RnUnbound ( unknownNameSuggestions )
batterseapower's avatar
batterseapower committed
21
import Type
22
import TyCoRep
23
import Unify            ( tcMatchTys )
24
import Module
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
25
import FamInst
26
import FamInstEnv       ( flattenTys )
27 28 29
import Inst
import InstEnv
import TyCon
30
import Class
31
import DataCon
32
import TcEvidence
33
import TcEvTerm
34
import HsExpr  ( UnboundVar(..) )
35
import HsBinds ( PatSynBind(..) )
36
import Name
37
import RdrName ( lookupGlobalRdrEnv, lookupGRE_Name, GlobalRdrEnv
38
               , mkRdrUnqual, isLocalGRE, greSrcSpan )
39
import PrelNames ( typeableClassName, hasKey, liftedRepDataConKey, tYPETyConKey )
40
import Id
41 42 43
import Var
import VarSet
import VarEnv
44
import NameSet
45
import Bag
46
import ErrUtils         ( ErrMsg, errDoc, pprLocErrMsg )
47
import BasicTypes
48
import ConLike          ( ConLike(..))
49 50 51
import Util
import FastString
import Outputable
52
import SrcLoc
53
import DynFlags
54
import ListSetOps       ( equivClasses )
55
import Maybes
56
import Pair
57
import qualified GHC.LanguageExtensions as LangExt
58
import FV ( fvVarList, unionFV )
Icelandjack's avatar
Icelandjack committed
59

60
import Control.Monad    ( when )
61
import Data.Foldable    ( toList )
62
import Data.List        ( partition, mapAccumL, nub, sortBy, unfoldr )
63
import qualified Data.Set as Set
64 65

import {-# SOURCE #-} TcHoleErrors ( findValidHoleFits )
66

67 68
import Data.Semigroup   ( Semigroup )
import qualified Data.Semigroup as Semigroup
69 70


Austin Seipp's avatar
Austin Seipp committed
71 72 73
{-
************************************************************************
*                                                                      *
74
\section{Errors and contexts}
Austin Seipp's avatar
Austin Seipp committed
75 76
*                                                                      *
************************************************************************
77 78 79 80 81

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?

82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
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
101

102 103 104 105 106 107 108 109 110 111 112 113 114 115
  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
116
and does not fail if -fdefer-type-errors is on, so that we can continue
117
compilation. The errors are turned into warnings in `reportUnsolved`.
Austin Seipp's avatar
Austin Seipp committed
118
-}
119

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

131
       ; defer_holes <- goptM Opt_DeferTypedHoles
132 133 134 135 136
       ; warn_holes  <- woptM Opt_WarnTypedHoles
       ; let expr_holes | not defer_holes = HoleError
                        | warn_holes      = HoleWarn
                        | otherwise       = HoleDefer

137
       ; partial_sigs      <- xoptM LangExt.PartialTypeSignatures
thomasw's avatar
thomasw committed
138
       ; warn_partial_sigs <- woptM Opt_WarnPartialTypeSignatures
139 140 141 142
       ; let type_holes | not partial_sigs  = HoleError
                        | warn_partial_sigs = HoleWarn
                        | otherwise         = HoleDefer

143 144 145 146 147 148
       ; defer_out_of_scope <- goptM Opt_DeferOutOfScopeVariables
       ; warn_out_of_scope <- woptM Opt_WarnDeferredOutOfScopeVariables
       ; let out_of_scope_holes | not defer_out_of_scope = HoleError
                                | warn_out_of_scope      = HoleWarn
                                | otherwise              = HoleDefer

149
       ; report_unsolved binds_var type_errors expr_holes
150
          type_holes out_of_scope_holes wanted
151 152 153

       ; ev_binds <- getTcEvBindsMap binds_var
       ; return (evBindMapBinds ev_binds)}
154

155
-- | Report *all* unsolved goals as errors, even if -fdefer-type-errors is on
Simon Peyton Jones's avatar
Simon Peyton Jones committed
156 157
-- However, do not make any evidence bindings, because we don't
-- have any convenient place to put them.
158
-- See Note [Deferring coercion errors to runtime]
Simon Peyton Jones's avatar
Simon Peyton Jones committed
159 160 161
-- Used by solveEqualities for kind equalities
--      (see Note [Fail fast on kind errors] in TcSimplify]
-- and for simplifyDefault.
162
reportAllUnsolved :: WantedConstraints -> TcM ()
163
reportAllUnsolved wanted
164 165
  = do { ev_binds <- newNoTcEvBinds
       ; report_unsolved ev_binds TypeError
166
                         HoleError HoleError HoleError wanted }
167

168 169 170 171 172
-- | 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
173
  = do { ev_binds <- newTcEvBinds
174
       ; report_unsolved ev_binds (TypeWarn NoReason)
175
                         HoleWarn HoleWarn HoleWarn wanted }
176 177

-- | Report unsolved goals as errors or warnings.
178
report_unsolved :: EvBindsVar        -- cec_binds
179
                -> TypeErrorChoice   -- Deferred type errors
180 181
                -> HoleChoice        -- Expression holes
                -> HoleChoice        -- Type holes
182
                -> HoleChoice        -- Out of scope holes
183
                -> WantedConstraints -> TcM ()
184
report_unsolved mb_binds_var type_errors expr_holes
185
    type_holes out_of_scope_holes wanted
186
  | isEmptyWC wanted
187
  = return ()
188
  | otherwise
189 190 191 192 193 194
  = do { traceTc "reportUnsolved warning/error settings:" $
           vcat [ text "type errors:" <+> ppr type_errors
                , text "expr holes:" <+> ppr expr_holes
                , text "type holes:" <+> ppr type_holes
                , text "scope holes:" <+> ppr out_of_scope_holes ]
       ; traceTc "reportUnsolved (before zonking and tidying)" (ppr wanted)
195

196
       ; wanted <- zonkWC wanted   -- Zonk to reveal all information
197
       ; env0 <- tcInitTidyEnv
198 199
            -- If we are deferring we are going to need /all/ evidence around,
            -- including the evidence produced by unflattening (zonkWC)
200
       ; let tidy_env = tidyFreeTyCoVars env0 free_tvs
niteria's avatar
niteria committed
201
             free_tvs = tyCoVarsOfWCList wanted
202

203 204
       ; traceTc "reportUnsolved (after zonking):" $
         vcat [ text "Free tyvars:" <+> pprTyVars free_tvs
205
              , text "Tidy env:" <+> ppr tidy_env
206
              , text "Wanted:" <+> ppr wanted ]
207 208 209

       ; warn_redundant <- woptM Opt_WarnRedundantConstraints
       ; let err_ctxt = CEC { cec_encl  = []
210
                            , cec_tidy  = tidy_env
211
                            , cec_defer_type_errors = type_errors
212 213
                            , cec_expr_holes = expr_holes
                            , cec_type_holes = type_holes
214
                            , cec_out_of_scope_holes = out_of_scope_holes
215
                            , cec_suppress = False -- See Note [Suppressing error messages]
216
                            , cec_warn_redundant = warn_redundant
217
                            , cec_binds    = mb_binds_var }
218

219 220
       ; tc_lvl <- getTcLevel
       ; reportWanteds err_ctxt tc_lvl wanted }
221

222 223 224
--------------------------------------------
--      Internal functions
--------------------------------------------
225

226 227 228 229 230
-- | 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]
231
           , report_valid_hole_fits :: [SDoc]
232 233
           }

234
instance Outputable Report where   -- Debugging only
235 236
  ppr (Report { report_important = imp
              , report_relevant_bindings = rel
237
              , report_valid_hole_fits = val })
238
    = vcat [ text "important:" <+> vcat imp
239 240
           , text "relevant:"  <+> vcat rel
           , text "valid:"  <+> vcat val ]
241

242 243 244 245 246 247 248 249
{- 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.

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

255
instance Semigroup Report where
256
    Report a1 b1 c1 <> Report a2 b2 c2 = Report (a1 ++ a2) (b1 ++ b2) (c1 ++ c2)
257

258
instance Monoid Report where
259
    mempty = Report [] [] []
260
    mappend = (Semigroup.<>)
261 262 263 264 265 266 267 268 269

-- | 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] }

270 271 272
-- | Put a doc into the valid hole fits block.
valid_hole_fits :: SDoc -> Report
valid_hole_fits docs = mempty { report_valid_hole_fits = [docs] }
273

274 275
data TypeErrorChoice   -- What to do for type errors found by the type checker
  = TypeError     -- A type error aborts compilation with an error message
276 277 278 279 280
  | TypeWarn WarnReason
                  -- A type error is deferred to runtime, plus a compile-time warning
                  -- The WarnReason should usually be (Reason Opt_WarnDeferredTypeErrors)
                  -- but it isn't for the Safe Haskell Overlapping Instances warnings
                  -- see warnAllUnsolved
281 282
  | TypeDefer     -- A type error is deferred to runtime; no error or warning at compile time

283 284 285 286 287
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

288 289 290 291 292 293
instance Outputable HoleChoice where
  ppr HoleError = text "HoleError"
  ppr HoleWarn  = text "HoleWarn"
  ppr HoleDefer = text "HoleDefer"

instance Outputable TypeErrorChoice  where
294 295 296
  ppr TypeError         = text "TypeError"
  ppr (TypeWarn reason) = text "TypeWarn" <+> ppr reason
  ppr TypeDefer         = text "TypeDefer"
297

298
data ReportErrCtxt
299
    = CEC { cec_encl :: [Implication]  -- Enclosing implications
300
                                       --   (innermost first)
301
                                       -- ic_skols and givens are tidied, rest are not
302
          , cec_tidy  :: TidyEnv
Simon Peyton Jones's avatar
Simon Peyton Jones committed
303

304 305 306
          , cec_binds :: EvBindsVar    -- Make some errors (depending on cec_defer)
                                       -- into warnings, and emit evidence bindings
                                       -- into 'cec_binds' for unsolved constraints
307

308
          , cec_defer_type_errors :: TypeErrorChoice -- Defer type errors until runtime
309

310 311 312 313 314 315 316
          -- cec_expr_holes is a union of:
          --   cec_type_holes - a set of typed holes: '_', '_a', '_foo'
          --   cec_out_of_scope_holes - a set of variables which are
          --                            out of scope: 'x', 'y', 'bar'
          , cec_expr_holes :: HoleChoice           -- Holes in expressions
          , cec_type_holes :: HoleChoice           -- Holes in types
          , cec_out_of_scope_holes :: HoleChoice   -- Out of scope holes
317

318
          , cec_warn_redundant :: Bool    -- True <=> -Wredundant-constraints
319

320 321 322
          , cec_suppress :: Bool    -- True <=> More important errors have occurred,
                                    --          so create bindings if need be, but
                                    --          don't issue any more errors/warnings
323
                                    -- See Note [Suppressing error messages]
324 325
      }

326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
instance Outputable ReportErrCtxt where
  ppr (CEC { cec_binds              = bvar
           , cec_defer_type_errors  = dte
           , cec_expr_holes         = eh
           , cec_type_holes         = th
           , cec_out_of_scope_holes = osh
           , cec_warn_redundant     = wr
           , cec_suppress           = sup })
    = text "CEC" <+> braces (vcat
         [ text "cec_binds"              <+> equals <+> ppr bvar
         , text "cec_defer_type_errors"  <+> equals <+> ppr dte
         , text "cec_expr_holes"         <+> equals <+> ppr eh
         , text "cec_type_holes"         <+> equals <+> ppr th
         , text "cec_out_of_scope_holes" <+> equals <+> ppr osh
         , text "cec_warn_redundant"     <+> equals <+> ppr wr
         , text "cec_suppress"           <+> equals <+> ppr sup ])

343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
-- | Returns True <=> the ReportErrCtxt indicates that something is deferred
deferringAnyBindings :: ReportErrCtxt -> Bool
  -- Don't check cec_type_holes, as these don't cause bindings to be deferred
deferringAnyBindings (CEC { cec_defer_type_errors  = TypeError
                          , cec_expr_holes         = HoleError
                          , cec_out_of_scope_holes = HoleError }) = False
deferringAnyBindings _                                            = True

-- | Transforms a 'ReportErrCtxt' into one that does not defer any bindings
-- at all.
noDeferredBindings :: ReportErrCtxt -> ReportErrCtxt
noDeferredBindings ctxt = ctxt { cec_defer_type_errors  = TypeError
                               , cec_expr_holes         = HoleError
                               , cec_out_of_scope_holes = HoleError }

Simon Peyton Jones's avatar
Simon Peyton Jones committed
358 359
{- Note [Suppressing error messages]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
360
The cec_suppress flag says "don't report any errors".  Instead, just create
361
evidence bindings (as usual).  It's used when more important errors have occurred.
362

363 364 365
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.
366
  * If there are any insolubles (eg Int~Bool), here or in a nested implication,
367 368
    then suppress errors from the simple constraints here.  Sometimes the
    simple-constraint errors are a knock-on effect of the insolubles.
Simon Peyton Jones's avatar
Simon Peyton Jones committed
369 370 371 372 373 374 375 376 377 378 379 380 381

This suppression behaviour is controlled by the Bool flag in
ReportErrorSpec, as used in reportWanteds.

But we need to take care: flags can turn errors into warnings, and we
don't want those warnings to suppress subsequent errors (including
suppressing the essential addTcEvBind for them: Trac #15152). So in
tryReporter we use askNoErrs to see if any error messages were
/actually/ produced; if not, we don't switch on suppression.

A consequence is that warnings never suppress warnings, so turning an
error into a warning may allow subsequent warnings to appear that were
previously suppressed.   (e.g. partial-sigs/should_fail/T14584)
Austin Seipp's avatar
Austin Seipp committed
382
-}
383

384
reportImplic :: ReportErrCtxt -> Implication -> TcM ()
385 386
reportImplic ctxt implic@(Implic { ic_skols = tvs, ic_telescope = m_telescope
                                 , ic_given = given
387
                                 , ic_wanted = wanted, ic_binds = evb
388
                                 , ic_status = status, ic_info = info
389
                                 , ic_tclvl = tc_lvl })
390
  | BracketSkol <- info
391
  , not insoluble
392 393
  = 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
394 395
                     -- later when we plug it in, and meanwhile there may
                     -- certainly be un-satisfied constraints
396 397

  | otherwise
398 399
  = do { traceTc "reportImplic" (ppr implic')
       ; reportWanteds ctxt' tc_lvl wanted
400
       ; when (cec_warn_redundant ctxt) $
401 402
         warnRedundantConstraints ctxt' tcl_env info' dead_givens
       ; when bad_telescope $ reportBadTelescope ctxt tcl_env m_telescope tvs }
403
  where
404
    tcl_env      = implicLclEnv implic
405
    insoluble    = isInsolubleStatus status
406
    (env1, tvs') = mapAccumL tidyTyCoVarBndr (cec_tidy ctxt) tvs
Simon Peyton Jones's avatar
Simon Peyton Jones committed
407
    info'        = tidySkolemInfo env1 info
408
    implic' = implic { ic_skols = tvs'
Simon Peyton Jones's avatar
Simon Peyton Jones committed
409
                     , ic_given = map (tidyEvVar env1) given
410
                     , ic_info  = info' }
Simon Peyton Jones's avatar
Simon Peyton Jones committed
411
    ctxt1 | CoEvBindsVar{} <- evb    = noDeferredBindings ctxt
412
          | otherwise                = ctxt
413
          -- If we go inside an implication that has no term
414
          -- evidence (e.g. unifying under a forall), we can't defer
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
          -- type errors.  You could imagine using the /enclosing/
          -- bindings (in cec_binds), but that may not have enough stuff
          -- in scope for the bindings to be well typed.  So we just
          -- switch off deferred type errors altogether.  See Trac #14605.

    ctxt' = ctxt1 { cec_tidy     = env1
                  , cec_encl     = implic' : cec_encl ctxt

                  , cec_suppress = insoluble || cec_suppress ctxt
                        -- Suppress inessential errors if there
                        -- are insolubles anywhere in the
                        -- tree rooted here, or we've come across
                        -- a suppress-worthy constraint higher up (Trac #11541)

                  , cec_binds    = evb }
430

431 432 433 434
    dead_givens = case status of
                    IC_Solved { ics_dead = dead } -> dead
                    _                             -> []

435 436 437 438
    bad_telescope = case status of
              IC_BadTelescope -> True
              _               -> False

439
warnRedundantConstraints :: ReportErrCtxt -> TcLclEnv -> SkolemInfo -> [EvVar] -> TcM ()
440
-- See Note [Tracking redundant constraints] in TcSimplify
441
warnRedundantConstraints ctxt env info ev_vars
442
 | null redundant_evs
443 444 445 446 447
 = return ()

 | SigSkol {} <- info
 = setLclEnv env $  -- We want to add "In the type signature for f"
                    -- to the error context, which is a bit tiresome
448
   addErrCtxt (text "In" <+> ppr info) $
449
   do { env <- getLclEnv
450
      ; msg <- mkErrorReport ctxt env (important doc)
451
      ; reportWarning (Reason Opt_WarnRedundantConstraints) msg }
452 453 454 455

 | 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
456
 = do { msg <- mkErrorReport ctxt env (important doc)
457
      ; reportWarning (Reason Opt_WarnRedundantConstraints) msg }
458
 where
459
   doc = text "Redundant constraint" <> plural redundant_evs <> colon
460 461
         <+> pprEvVarTheta redundant_evs

462 463 464 465 466 467 468 469
   redundant_evs =
       filterOut is_type_error $
       case info of -- See Note [Redundant constraints in instance decls]
         InstSkol -> filterOut improving ev_vars
         _        -> ev_vars

   -- See #15232
   is_type_error = isJust . userTypeError_maybe . idType
470 471

   improving ev_var = any isImprovementPred $
472
                      transSuperClasses (idType ev_var)
473

474 475 476 477 478 479 480 481 482 483 484 485 486 487
reportBadTelescope :: ReportErrCtxt -> TcLclEnv -> Maybe SDoc -> [TcTyVar] -> TcM ()
reportBadTelescope ctxt env (Just telescope) skols
  = do { msg <- mkErrorReport ctxt env (important doc)
       ; reportError msg }
  where
    doc = hang (text "These kind and type variables:" <+> telescope $$
                text "are out of dependency order. Perhaps try this ordering:")
             2 (pprTyVars sorted_tvs)

    sorted_tvs = toposortTyVars skols

reportBadTelescope _ _ Nothing skols
  = pprPanic "reportBadTelescope" (ppr skols)

488 489 490 491 492 493 494 495
{- 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
496
of evidence, since the dictionary has no fields.  But it is still
497 498 499 500 501 502 503
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..
-}
504

505
reportWanteds :: ReportErrCtxt -> TcLevel -> WantedConstraints -> TcM ()
506
reportWanteds ctxt tc_lvl (WC { wc_simple = simples, wc_impl = implics })
507 508
  = do { traceTc "reportWanteds" (vcat [ text "Simples =" <+> ppr simples
                                       , text "Suppress =" <+> ppr (cec_suppress ctxt)])
509
       ; traceTc "rw2" (ppr tidy_cts)
510 511 512 513

         -- First deal with things that are utterly wrong
         -- Like Int ~ Bool (incl nullary TyCons)
         -- or  Int ~ t a   (AppTy on one side)
514
         -- These /ones/ are not suppressed by the incoming context
515 516 517 518 519 520 521 522
       ; 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
523 524
       ; MASSERT2( null leftovers, ppr leftovers )

525
            -- All the Derived ones have been filtered out of simples
526 527 528
            -- 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]
529

530
     ; mapBagM_ (reportImplic ctxt2) implics }
531
            -- NB ctxt1: don't suppress inner insolubles if there's only a
532
            -- wanted insoluble here; but do suppress inner insolubles
533
            -- if there's a *given* insoluble here (= inaccessible code)
534
 where
535
    env = cec_tidy ctxt
536
    tidy_cts = bagToList (mapBag (tidyCt env) simples)
537

538 539 540
    -- report1: ones that should *not* be suppresed by
    --          an insoluble somewhere else in the tree
    -- It's crucial that anything that is considered insoluble
541
    -- (see TcRnTypes.insolubleWantedCt) is caught here, otherwise
542 543
    -- we might suppress its error message, and proceed on past
    -- type checking to get a Lint error later
Simon Peyton Jones's avatar
Simon Peyton Jones committed
544
    report1 = [ ("Out of scope", is_out_of_scope,    True,  mkHoleReporter tidy_cts)
545
              , ("Holes",        is_hole,            False, mkHoleReporter tidy_cts)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
546
              , ("custom_error", is_user_type_error, True,  mkUserTypeErrorReporter)
547

548
              , given_eq_spec
549 550 551 552
              , ("insoluble2",   utterly_wrong,  True, mkGroupReporter mkEqErr)
              , ("skolem eq1",   very_wrong,     True, mkSkolReporter)
              , ("skolem eq2",   skolem_eq,      True, mkSkolReporter)
              , ("non-tv eq",    non_tv_eq,      True, mkSkolReporter)
553 554 555

                  -- The only remaining equalities are alpha ~ ty,
                  -- where alpha is untouchable; and representational equalities
556 557 558 559 560
                  -- Prefer homogeneous equalities over hetero, because the
                  -- former might be holding up the latter.
                  -- See Note [Equalities with incompatible kinds] in TcCanonical
              , ("Homo eqs",      is_homo_equality, True,  mkGroupReporter mkEqErr)
              , ("Other eqs",     is_equality,      False, mkGroupReporter mkEqErr) ]
561 562 563 564 565 566

    -- 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) ]

567 568
    -- rigid_nom_eq, rigid_nom_tv_eq,
    is_hole, is_dict,
569
      is_equality, is_ip, is_irred :: Ct -> PredTree -> Bool
570

571 572 573 574 575
    is_given_eq ct pred
       | EqPred {} <- pred = arisesFromGivens ct
       | otherwise         = False
       -- I think all given residuals are equalities

576 577 578 579 580 581 582
    -- 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
583

584
    -- Things like (a ~N b) or (a  ~N  F Bool)
585
    skolem_eq _ (EqPred NomEq ty1 _) = isSkolemTy tc_lvl ty1
586
    skolem_eq _ _                    = False
587

588 589 590 591 592 593 594 595
    -- Things like (F a  ~N  Int)
    non_tv_eq _ (EqPred NomEq ty1 _) = not (isTyVarTy ty1)
    non_tv_eq _ _                    = False

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

    is_user_type_error ct _ = isUserTypeErrorCt ct
596

597 598 599
    is_homo_equality _ (EqPred _ ty1 ty2) = typeKind ty1 `tcEqType` typeKind ty2
    is_homo_equality _ _                  = False

600 601 602
    is_equality _ (EqPred {}) = True
    is_equality _ _           = False

603 604 605 606 607 608 609 610 611
    is_dict _ (ClassPred {}) = True
    is_dict _ _              = False

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

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

612 613 614 615 616 617 618 619 620 621 622 623 624
    given_eq_spec = case find_gadt_match (cec_encl ctxt) of
       Just imp -> ("insoluble1a", is_given_eq, True,  mkGivenErrorReporter imp)
       Nothing  -> ("insoluble1b", is_given_eq, False, ignoreErrorReporter)
                  -- False means don't suppress subsequent errors
                  -- Reason: we don't report all given errors
                  --         (see mkGivenErrorReporter), and we should only suppress
                  --         subsequent errors if we actually report this one!
                  --         Trac #13446 is an example

    find_gadt_match [] = Nothing
    find_gadt_match (implic : implics)
      | PatSkol {} <- ic_info implic
      , not (ic_no_eqs implic)
625 626 627
      , wopt Opt_WarnInaccessibleCode (implicDynFlags implic)
          -- Don't bother doing this if -Winaccessible-code isn't enabled.
          -- See Note [Avoid -Winaccessible-code when deriving] in TcInstDcls.
628 629 630
      = Just implic
      | otherwise
      = find_gadt_match implics
631

632
---------------
633
isSkolemTy :: TcLevel -> Type -> Bool
634
-- The type is a skolem tyvar
635
isSkolemTy tc_lvl ty
636 637 638 639 640 641 642 643
  | Just tv <- getTyVar_maybe ty
  =  isSkolemTyVar tv
  || (isSigTyVar tv && isTouchableMetaTyVar tc_lvl tv)
     -- The last case is for touchable SigTvs
     -- we postpone untouchables to a latter test (too obscure)

  | otherwise
  = False
644

645 646
isTyFun_maybe :: Type -> Maybe TyCon
isTyFun_maybe ty = case tcSplitTyConApp_maybe ty of
647
                      Just (tc,_) | isTypeFamilyTyCon tc -> Just tc
648 649
                      _ -> Nothing

650
--------------------------------------------
651
--      Reporters
652 653
--------------------------------------------

654 655 656 657 658 659 660 661 662
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
663
-- Suppress duplicates with either the same LHS, or same location
664
mkSkolReporter ctxt cts
665
  = mapM_ (reportGroup mkEqErr ctxt) (group cts)
666
  where
667 668 669 670 671 672
     group [] = []
     group (ct:cts) = (ct : yeses) : group noes
        where
          (yeses, noes) = partition (group_with ct) cts

     group_with ct1 ct2
673 674 675
       | EQ <- cmp_loc ct1 ct2 = True
       | eq_lhs_type   ct1 ct2 = True
       | otherwise             = False
676

677
mkHoleReporter :: [Ct] -> Reporter
678
-- Reports errors one at a time
679 680
mkHoleReporter tidy_simples ctxt
  = mapM_ $ \ct -> do { err <- mkHoleError tidy_simples ctxt ct
681 682
                      ; maybeReportHoleError ctxt ct err
                      ; maybeAddDeferredHoleBinding ctxt err ct }
683

684 685
mkUserTypeErrorReporter :: Reporter
mkUserTypeErrorReporter ctxt
686
  = mapM_ $ \ct -> do { err <- mkUserTypeError ctxt ct
687 688
                      ; maybeReportError ctxt err
                      ; addDeferredBinding ctxt err ct }
689 690 691

mkUserTypeError :: ReportErrCtxt -> Ct -> TcM ErrMsg
mkUserTypeError ctxt ct = mkErrorMsgFromCt ctxt ct
692
                        $ important
693 694
                        $ pprUserTypeErrorTy
                        $ case getUserTypeErrorMsg ct of
695 696
                            Just msg -> msg
                            Nothing  -> pprPanic "mkUserTypeError" (ppr ct)
697 698


699
mkGivenErrorReporter :: Implication -> Reporter
700
-- See Note [Given errors]
701
mkGivenErrorReporter implic ctxt cts
702 703
  = do { (ctxt, binds_msg, ct) <- relevantBindings True ctxt ct
       ; dflags <- getDynFlags
704
       ; let ct' = setCtLoc ct (setCtLocEnv (ctLoc ct) (implicLclEnv implic))
705 706 707 708 709 710 711 712 713 714 715
                   -- For given constraints we overwrite the env (and hence src-loc)
                  -- with one from the implication.  See Note [Inaccessible code]

             inaccessible_msg = hang (text "Inaccessible code in")
                                   2 (ppr (ic_info implic))
             report = important inaccessible_msg `mappend`
                      relevant_bindings binds_msg

       ; err <- mkEqErr_help dflags ctxt report ct'
                             Nothing ty1 ty2

Simon Peyton Jones's avatar
Simon Peyton Jones committed
716
       ; traceTc "mkGivenErrorReporter" (ppr ct)
717
       ; reportWarning (Reason Opt_WarnInaccessibleCode) err }
718 719 720 721
  where
    (ct : _ )  = cts    -- Never empty
    (ty1, ty2) = getEqPredTys (ctPred ct)

722 723
ignoreErrorReporter :: Reporter
-- Discard Given errors that don't come from
Simon Peyton Jones's avatar
Simon Peyton Jones committed
724
-- a pattern match; maybe we should warn instead?
725
ignoreErrorReporter ctxt cts
Simon Peyton Jones's avatar
Simon Peyton Jones committed
726
  = do { traceTc "mkGivenErrorReporter no" (ppr cts $$ ppr (cec_encl ctxt))
727 728
       ; return () }

729 730 731

{- Note [Given errors]
~~~~~~~~~~~~~~~~~~~~~~
Gabor Greif's avatar
Gabor Greif committed
732
Given constraints represent things for which we have (or will have)
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
evidence, so they aren't errors.  But if a Given constraint is
insoluble, this code is inaccessible, and we might want to at least
warn about that.  A classic case is

   data T a where
     T1 :: T Int
     T2 :: T a
     T3 :: T Bool

   f :: T Int -> Bool
   f T1 = ...
   f T2 = ...
   f T3 = ...  -- We want to report this case as inaccessible

We'd like to point out that the T3 match is inaccessible. It
will have a Given constraint [G] Int ~ Bool.

But we don't want to report ALL insoluble Given constraints.  See Trac
Simon Peyton Jones's avatar
Simon Peyton Jones committed
751
#12466 for a long discussion.  For example, if we aren't careful
752 753 754 755
we'll complain about
   f :: ((Int ~ Bool) => a -> a) -> Int
which arguably is OK.  It's more debatable for
   g :: (Int ~ Bool) => Int -> Int
756
but it's tricky to distinguish these cases so we don't report
757 758
either.

Simon Peyton Jones's avatar
Simon Peyton Jones committed
759
The bottom line is this: find_gadt_match looks for an enclosing
760 761 762 763
pattern match which binds some equality constraints.  If we
find one, we report the insoluble Given.
-}

764 765 766
mkGroupReporter :: (ReportErrCtxt -> [Ct] -> TcM ErrMsg)
                             -- Make error message for a group
                -> Reporter  -- Deal with lots of constraints
767 768 769
-- Group together errors from same location,
-- and report only the first (to avoid a cascade)
mkGroupReporter mk_err ctxt cts
770
  = mapM_ (reportGroup mk_err ctxt . toList) (equivClasses cmp_loc cts)
771

772 773
eq_lhs_type :: Ct -> Ct -> Bool
eq_lhs_type ct1 ct2
774 775
  = case (classifyPredType (ctPred ct1), classifyPredType (ctPred ct2)) of
       (EqPred eq_rel1 ty1 _, EqPred eq_rel2 ty2 _) ->
776
         (eq_rel1 == eq_rel2) && (ty1 `eqType` ty2)
777 778 779 780
       _ -> pprPanic "mkSkolReporter" (ppr ct1 $$ ppr ct2)

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

782 783
reportGroup :: (ReportErrCtxt -> [Ct] -> TcM ErrMsg) -> ReportErrCtxt
            -> [Ct] -> TcM ()
quchen's avatar
quchen committed
784 785 786
reportGroup mk_err ctxt cts =
  case partition isMonadFailInstanceMissing cts of
        -- Only warn about missing MonadFail constraint when
Gabor Greif's avatar
Gabor Greif committed
787
        -- there are no other missing constraints!
788 789 790
        (monadFailCts, []) ->
            do { err <- mk_err ctxt monadFailCts
               ; reportWarning (Reason Opt_WarnMissingMonadFailInstances) err }
quchen's avatar
quchen committed
791 792

        (_, cts') -> do { err <- mk_err ctxt cts'
Simon Peyton Jones's avatar
Simon Peyton Jones committed
793 794 795 796
                        ; traceTc "About to maybeReportErr" $
                          vcat [ text "Constraint:"             <+> ppr cts'
                               , text "cec_suppress ="          <+> ppr (cec_suppress ctxt)
                               , text "cec_defer_type_errors =" <+> ppr (cec_defer_type_errors ctxt) ]
quchen's avatar
quchen committed
797
                        ; maybeReportError ctxt err
798 799 800 801 802 803 804
                            -- But see Note [Always warn with -fdefer-type-errors]
                        ; traceTc "reportGroup" (ppr cts')
                        ; mapM_ (addDeferredBinding ctxt err) cts' }
                            -- Add deferred bindings for all
                            -- Redundant if we are going to abort compilation,
                            -- but that's hard to know for sure, and if we don't
                            -- abort, we need bindings for all (e.g. Trac #12156)
quchen's avatar
quchen committed
805 806 807 808 809
  where
    isMonadFailInstanceMissing ct =
        case ctLocOrigin (ctLoc ct) of
            FailablePattern _pat -> True
            _otherwise           -> False
810

811
maybeReportHoleError :: ReportErrCtxt -> Ct -> ErrMsg -> TcM ()
812 813
-- Unlike maybeReportError, these "hole" errors are
-- /not/ suppressed by cec_suppress.  We want to see them!
814
maybeReportHoleError ctxt ct err
thomasw's avatar
thomasw committed
815
  -- When -XPartialTypeSignatures is on, warnings (instead of errors) are
816 817 818
  -- generated for holes in partial type signatures.
  -- Unless -fwarn_partial_type_signatures is not on,
  -- in which case the messages are discarded.
819 820 821 822 823
  | 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
824
       HoleWarn  -> reportWarning (Reason Opt_WarnPartialTypeSignatures) err
825 826
       HoleDefer -> return ()

827 828 829 830
  -- Always report an error for out-of-scope variables
  -- Unless -fdefer-out-of-scope-variables is on,
  -- in which case the messages are discarded.
  -- See Trac #12170, #12406
831
  | isOutOfScopeCt ct
832 833 834 835 836 837
  = -- If deferring, report a warning only if -Wout-of-scope-variables is on
    case cec_out_of_scope_holes ctxt of
      HoleError -> reportError err
      HoleWarn  ->
        reportWarning (Reason Opt_WarnDeferredOutOfScopeVariables) err
      HoleDefer -> return ()
838 839 840

  -- Otherwise this is a typed hole in an expression,
  -- but not for an out-of-scope variable
841
  | otherwise
842
  = -- If deferring, report a warning only if -Wtyped-holes is on
843 844
    case cec_expr_holes ctxt of
       HoleError -> reportError err
845
       HoleWarn  -> reportWarning (Reason Opt_WarnTypedHoles) err
846
       HoleDefer -> return ()
847

848
maybeReportError :: ReportErrCtxt -> ErrMsg -> TcM ()
849
-- Report the error and/or make a deferred binding for it
850
maybeReportError ctxt err
851 852 853
  | cec_suppress ctxt    -- Some worse error has occurred;
  = return ()            -- so suppress this error/warning

854
  | otherwise
855
  = case cec_defer_type_errors ctxt of
856 857 858
      TypeDefer       -> return ()
      TypeWarn reason -> reportWarning reason err
      TypeError       -> reportError err
859

860
addDeferredBinding :: ReportErrCtxt -> ErrMsg -> Ct -> TcM ()
861
-- See Note [Deferring coercion errors to runtime]
862
addDeferredBinding ctxt err ct
863 864
  | deferringAnyBindings ctxt
  , CtWanted { ctev_pred = pred, ctev_dest = dest } <- ctEvidence ct
865 866 867 868 869
    -- Only add deferred bindings for Wanted constraints
  = do { dflags <- getDynFlags
       ; let err_msg = pprLocErrMsg err
             err_fs  = mkFastString $ showSDoc dflags $
                       err_msg $$ text "(deferred type error)"
870
             err_tm  = evDelayedError pred err_fs
871
             ev_binds_var = cec_binds ctxt
872

873 874
       ; case dest of
           EvVarDest evar
875
             -> addTcEvBind ev_binds_var $ mkWantedEvBind evar err_tm
876 877
           HoleDest hole
             -> do { -- See Note [Deferred errors for coercion holes]
Simon Peyton Jones's avatar
Simon Peyton Jones committed
878
                     let co_var = coHoleCoVar hole