TcErrors.hs 87.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 )
17
import TypeRep
batterseapower's avatar
batterseapower committed
18
import Type
19
import Kind ( isKind )
20
import Unify            ( tcMatchTys )
21
import Module
22
import FamInst
23 24 25
import Inst
import InstEnv
import TyCon
26
import DataCon
27
import TcEvidence
28
import Name
29
import RdrName ( lookupGRE_Name, GlobalRdrEnv, mkRdrUnqual )
30 31
import Class( className )
import PrelNames( typeableClassName )
32
import Id
33 34 35
import Var
import VarSet
import VarEnv
36
import NameSet
37
import Bag
38
import ErrUtils         ( ErrMsg, errDoc, pprLocErrMsg )
39
import BasicTypes
40 41 42
import Util
import FastString
import Outputable
43
import SrcLoc
44
import DynFlags
45
import StaticFlags      ( opt_PprStyle_Debug )
46
import ListSetOps       ( equivClasses )
Icelandjack's avatar
Icelandjack committed
47

48
import Control.Monad    ( when )
Icelandjack's avatar
Icelandjack committed
49
import Data.Maybe
50
import Data.List        ( partition, mapAccumL, nub, sortBy )
51

52 53 54 55 56
#if __GLASGOW_HASKELL__ < 709
import Data.Monoid      ( Monoid, mempty, mappend, mconcat )
#endif


Austin Seipp's avatar
Austin Seipp committed
57 58 59
{-
************************************************************************
*                                                                      *
60
\section{Errors and contexts}
Austin Seipp's avatar
Austin Seipp committed
61 62
*                                                                      *
************************************************************************
63 64 65 66 67

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?

68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
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
87

88 89 90 91 92 93 94 95 96 97 98 99 100 101
  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
102
and does not fail if -fdefer-type-errors is on, so that we can continue
103
compilation. The errors are turned into warnings in `reportUnsolved`.
Austin Seipp's avatar
Austin Seipp committed
104
-}
105

106 107
-- | Report unsolved goals as errors or warnings. We may also turn some into
-- deferred run-time errors if `-fdefer-type-errors` is on.
108 109
reportUnsolved :: WantedConstraints -> TcM (Bag EvBind)
reportUnsolved wanted
110 111 112 113 114 115
  = 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
116

117
       ; defer_holes <- goptM Opt_DeferTypedHoles
118 119 120 121 122 123
       ; warn_holes  <- woptM Opt_WarnTypedHoles
       ; let expr_holes | not defer_holes = HoleError
                        | warn_holes      = HoleWarn
                        | otherwise       = HoleDefer

       ; partial_sigs      <- xoptM Opt_PartialTypeSignatures
thomasw's avatar
thomasw committed
124
       ; warn_partial_sigs <- woptM Opt_WarnPartialTypeSignatures
125 126 127 128
       ; let type_holes | not partial_sigs  = HoleError
                        | warn_partial_sigs = HoleWarn
                        | otherwise         = HoleDefer

129
       ; report_unsolved (Just binds_var) False type_errors expr_holes type_holes wanted
130 131
       ; getTcEvBinds binds_var }

132
-- | Report *all* unsolved goals as errors, even if -fdefer-type-errors is on
133
-- See Note [Deferring coercion errors to runtime]
134
reportAllUnsolved :: WantedConstraints -> TcM ()
135
reportAllUnsolved wanted
136
  = report_unsolved Nothing False TypeError HoleError HoleError wanted
137

138 139 140 141 142
-- | 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
143
  = report_unsolved Nothing True TypeWarn HoleWarn HoleWarn wanted
144 145

-- | Report unsolved goals as errors or warnings.
146
report_unsolved :: Maybe EvBindsVar  -- cec_binds
147
                -> Bool              -- Errors as warnings
148
                -> TypeErrorChoice   -- Deferred type errors
149 150
                -> HoleChoice        -- Expression holes
                -> HoleChoice        -- Type holes
151
                -> WantedConstraints -> TcM ()
152
report_unsolved mb_binds_var err_as_warn type_errors expr_holes type_holes wanted
153
  | isEmptyWC wanted
154
  = return ()
155
  | otherwise
156
  = do { traceTc "reportUnsolved (before zonking and tidying)" (ppr wanted)
157

158
       ; wanted <- zonkWC wanted   -- Zonk to reveal all information
159
       ; env0 <- tcInitTidyEnv
160 161
            -- If we are deferring we are going to need /all/ evidence around,
            -- including the evidence produced by unflattening (zonkWC)
162
       ; let tidy_env = tidyFreeTyVars env0 free_tvs
163
             free_tvs = tyVarsOfWC wanted
164 165 166 167 168 169 170

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

       ; warn_redundant <- woptM Opt_WarnRedundantConstraints
       ; let err_ctxt = CEC { cec_encl  = []
171
                            , cec_tidy  = tidy_env
172
                            , cec_defer_type_errors = type_errors
173
                            , cec_errors_as_warns = err_as_warn
174 175
                            , cec_expr_holes = expr_holes
                            , cec_type_holes = type_holes
176
                            , cec_suppress = False -- See Note [Suppressing error messages]
177
                            , cec_warn_redundant = warn_redundant
178
                            , cec_binds    = mb_binds_var }
179

180 181
       ; tc_lvl <- getTcLevel
       ; reportWanteds err_ctxt tc_lvl wanted }
182

183 184 185
--------------------------------------------
--      Internal functions
--------------------------------------------
186

187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
-- | 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.
-}

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

219 220 221 222 223
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

224 225 226 227 228
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

229
data ReportErrCtxt
230
    = CEC { cec_encl :: [Implication]  -- Enclosing implications
231
                                       --   (innermost first)
232
                                       -- ic_skols and givens are tidied, rest are not
233
          , cec_tidy  :: TidyEnv
234
          , cec_binds :: Maybe EvBindsVar
235 236 237 238
                         -- 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
239

240 241 242 243
          , cec_errors_as_warns :: Bool   -- Turn all errors into warnings
                                          -- (except for Holes, which are
                                          -- controlled by cec_type_holes and
                                          -- cec_expr_holes)
244 245
          , cec_defer_type_errors :: TypeErrorChoice -- Defer type errors until runtime
                                                     -- Irrelevant if cec_binds = Nothing
246

247 248
          , cec_expr_holes :: HoleChoice  -- Holes in expressions
          , cec_type_holes :: HoleChoice  -- Holes in types
249

250 251
          , cec_warn_redundant :: Bool    -- True <=> -fwarn-redundant-constraints

252 253 254
          , cec_suppress :: Bool    -- True <=> More important errors have occurred,
                                    --          so create bindings if need be, but
                                    --          don't issue any more errors/warnings
255
                                    -- See Note [Suppressing error messages]
256 257
      }

Austin Seipp's avatar
Austin Seipp committed
258
{-
259 260
Note [Suppressing error messages]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
261
The cec_suppress flag says "don't report any errors".  Instead, just create
262
evidence bindings (as usual).  It's used when more important errors have occurred.
263

264 265 266
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.
267
  * If there are any insolubles (eg Int~Bool), here or in a nested implication,
268 269
    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
270
-}
271

272 273 274
reportImplic :: ReportErrCtxt -> Implication -> TcM ()
reportImplic ctxt implic@(Implic { ic_skols = tvs, ic_given = given
                                 , ic_wanted = wanted, ic_binds = evb
275
                                 , ic_status = status, ic_info = info
276
                                 , ic_env = tcl_env, ic_tclvl = tc_lvl })
277
  | BracketSkol <- info
278
  , not insoluble
279 280
  = return ()        -- For Template Haskell brackets report only
                     -- definite errors. The whole thing will be re-checked
281 282
                     -- later when we plug it in, and meanwhile there may
                     -- certainly be un-satisfied constraints
283 284

  | otherwise
285
  = do { reportWanteds ctxt' tc_lvl wanted
286 287 288
       ; traceTc "reportImplic" (ppr implic)
       ; when (cec_warn_redundant ctxt) $
         warnRedundantConstraints ctxt' tcl_env info' dead_givens }
289
  where
290
    insoluble    = isInsolubleStatus status
291
    (env1, tvs') = mapAccumL tidyTyVarBndr (cec_tidy ctxt) tvs
292
    (env2, info') = tidySkolemInfo env1 info
293
    implic' = implic { ic_skols = tvs'
294 295
                     , ic_given = map (tidyEvVar env2) given
                     , ic_info  = info' }
296 297 298 299 300 301 302 303
    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
                 , cec_binds    = case cec_binds ctxt of
                                     Nothing -> Nothing
                                     Just {} -> Just evb }
304 305 306 307 308 309
    dead_givens = case status of
                    IC_Solved { ics_dead = dead } -> dead
                    _                             -> []

warnRedundantConstraints :: ReportErrCtxt -> TcLclEnv -> SkolemInfo -> [EvVar] -> TcM ()
warnRedundantConstraints ctxt env info ev_vars
310
 | null redundant_evs
311 312 313 314 315 316 317
 = 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
318
      ; msg <- mkErrorReport ctxt env (important doc)
319 320 321 322 323
      ; 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
324
 = do { msg <- mkErrorReport ctxt env (important doc)
325 326
      ; reportWarning msg }
 where
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
   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 $
                      transSuperClassesPred (idType ev_var)

{- 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..
-}
353

354 355
reportWanteds :: ReportErrCtxt -> TcLevel -> WantedConstraints -> TcM ()
reportWanteds ctxt tc_lvl (WC { wc_simple = simples, wc_insol = insols, wc_impl = implics })
356 357
  = do { traceTc "reportWanteds" (vcat [ ptext (sLit "Simples =") <+> ppr simples
                                       , ptext (sLit "Suppress =") <+> ppr (cec_suppress ctxt)])
358
       ; let tidy_cts = bagToList (mapBag (tidyCt env) (insols `unionBags` simples))
359 360 361 362

         -- First deal with things that are utterly wrong
         -- Like Int ~ Bool (incl nullary TyCons)
         -- or  Int ~ t a   (AppTy on one side)
363 364 365 366 367 368 369 370 371
         -- 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
372 373
       ; MASSERT2( null leftovers, ppr leftovers )

374
            -- All the Derived ones have been filtered out of simples
375 376 377
            -- 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]
378

379
     ; mapBagM_ (reportImplic ctxt2) implics }
380
            -- NB ctxt1: don't suppress inner insolubles if there's only a
381
            -- wanted insoluble here; but do suppress inner insolubles
382
            -- if there's a *given* insoluble here (= inaccessible code)
383
 where
384
    env = cec_tidy ctxt
385

386 387 388 389 390 391
    -- 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
392 393 394
    report1 = [ ("custom_error", is_user_type_error,
                                                  True, mkUserTypeErrorReporter)
              , ("insoluble1",   is_given,        True, mkGroupReporter mkEqErr)
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
              , ("insoluble2",   utterly_wrong,   True, mkGroupReporter mkEqErr)
              , ("insoluble3",   rigid_nom_tv_eq, True, mkSkolReporter)
              , ("insoluble4",   rigid_nom_eq,    True, mkGroupReporter mkEqErr)
              , ("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) ]

    rigid_nom_eq, rigid_nom_tv_eq, is_hole, is_dict,
411
      is_equality, is_ip, is_irred :: Ct -> PredTree -> Bool
412

413
    utterly_wrong _ (EqPred NomEq ty1 ty2) = isRigidTy ty1 && isRigidTy ty2
414 415
    utterly_wrong _ _                      = False

416 417
    is_out_of_scope ct _ = isOutOfScopeCt ct
    is_hole         ct _ = isHoleCt ct
418
    is_user_type_error ct _ = isUserTypeErrorCt ct
419
    is_given  ct _ = not (isWantedCt ct)  -- The Derived ones are actually all from Givens
420

421 422 423 424 425 426 427
    -- Skolem (i.e. non-meta) type variable on the left
    rigid_nom_eq _ pred = isRigidEqPred tc_lvl pred

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

428 429 430
    is_equality _ (EqPred {}) = True
    is_equality _ _           = False

431 432 433 434 435 436 437 438 439 440
    is_dict _ (ClassPred {}) = True
    is_dict _ _              = False

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

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


441 442 443
---------------
isTyFun_maybe :: Type -> Maybe TyCon
isTyFun_maybe ty = case tcSplitTyConApp_maybe ty of
444
                      Just (tc,_) | isTypeFamilyTyCon tc -> Just tc
445 446
                      _ -> Nothing

447 448

--------------------------------------------
449
--      Reporters
450 451
--------------------------------------------

452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
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
-- Suppress duplicates with the same LHS
mkSkolReporter ctxt cts
  = mapM_ (reportGroup mkEqErr ctxt) (equivClasses cmp_lhs_type cts)
  where
    cmp_lhs_type ct1 ct2
      = case (classifyPredType (ctPred ct1), classifyPredType (ctPred ct2)) of
467 468
           (EqPred eq_rel1 ty1 _, EqPred eq_rel2 ty2 _) ->
             (eq_rel1 `compare` eq_rel2) `thenCmp` (ty1 `cmpType` ty2)
469
           _ -> pprPanic "mkSkolReporter" (ppr ct1 $$ ppr ct2)
470

471
mkHoleReporter :: Reporter
472
-- Reports errors one at a time
473
mkHoleReporter ctxt
474
  = mapM_ $ \ct ->
475 476
    do { err <- mkHoleError ctxt ct
       ; maybeReportHoleError ctxt ct err
477
       ; maybeAddDeferredHoleBinding ctxt err ct }
478

479 480 481 482 483 484
mkUserTypeErrorReporter :: Reporter
mkUserTypeErrorReporter ctxt
  = mapM_ $ \ct -> maybeReportError ctxt =<< mkUserTypeError ctxt ct

mkUserTypeError :: ReportErrCtxt -> Ct -> TcM ErrMsg
mkUserTypeError ctxt ct = mkErrorMsgFromCt ctxt ct
485
                        $ important
486 487 488 489 490 491
                        $ pprUserTypeErrorTy
                        $ case getUserTypeErrorMsg ct of
                            Just (_,msg) -> msg
                            Nothing      -> pprPanic "mkUserTypeError" (ppr ct)


492 493 494
mkGroupReporter :: (ReportErrCtxt -> [Ct] -> TcM ErrMsg)
                             -- Make error message for a group
                -> Reporter  -- Deal with lots of constraints
495 496 497 498 499
-- 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
500
    cmp_loc ct1 ct2 = ctLocSpan (ctLoc ct1) `compare` ctLocSpan (ctLoc ct2)
501

502 503
reportGroup :: (ReportErrCtxt -> [Ct] -> TcM ErrMsg) -> ReportErrCtxt
            -> [Ct] -> TcM ()
quchen's avatar
quchen committed
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
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
521

522 523
maybeReportHoleError :: ReportErrCtxt -> Ct -> ErrMsg -> TcM ()
maybeReportHoleError ctxt ct err
thomasw's avatar
thomasw committed
524 525 526 527
  -- When -XPartialTypeSignatures is on, warnings (instead of errors) are
  -- generated for holes in partial type signatures. Unless
  -- -fwarn_partial_type_signatures is not on, in which case the messages are
  -- discarded.
528 529 530 531 532
  | 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
533
       HoleWarn  -> reportWarning err
534 535 536
       HoleDefer -> return ()

  -- Otherwise this is a typed hole in an expression
537
  | otherwise
538 539 540
  = -- If deferring, report a warning only if -fwarn-typed-holds is on
    case cec_expr_holes ctxt of
       HoleError -> reportError err
541
       HoleWarn  -> reportWarning err
542
       HoleDefer -> return ()
543

544
maybeReportError :: ReportErrCtxt -> ErrMsg -> TcM ()
545
-- Report the error and/or make a deferred binding for it
546
maybeReportError ctxt err
547
  | cec_errors_as_warns ctxt
548
  = reportWarning err
549
  | otherwise
550 551 552 553 554
  = case cec_defer_type_errors ctxt of
    TypeDefer -> return ()
    TypeWarn -> reportWarning err
    -- handle case when suppress is on like in the original code
    TypeError -> if cec_suppress ctxt then return () else reportError err
555

556
addDeferredBinding :: ReportErrCtxt -> ErrMsg -> Ct -> TcM ()
557
-- See Note [Deferring coercion errors to runtime]
558
addDeferredBinding ctxt err ct
559
  | CtWanted { ctev_pred = pred, ctev_evar = ev_id } <- ctEvidence ct
560
    -- Only add deferred bindings for Wanted constraints
561
  , Just ev_binds_var <- cec_binds ctxt  -- We have somewhere to put the bindings
562 563 564 565 566 567
  = do { dflags <- getDynFlags
       ; let err_msg = pprLocErrMsg err
             err_fs  = mkFastString $ showSDoc dflags $
                       err_msg $$ text "(deferred type error)"

         -- Create the binding
568
       ; addTcEvBind ev_binds_var (mkWantedEvBind ev_id (EvDelayedError pred err_fs)) }
569 570

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

573 574
maybeAddDeferredHoleBinding :: ReportErrCtxt -> ErrMsg -> Ct -> TcM ()
maybeAddDeferredHoleBinding ctxt err ct
575 576 577 578 579 580 581
    | 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
582 583 584
    = return ()

maybeAddDeferredBinding :: ReportErrCtxt -> ErrMsg -> Ct -> TcM ()
585 586 587 588 589 590 591
maybeAddDeferredBinding ctxt err ct =
  case cec_defer_type_errors ctxt of
        TypeDefer -> deferred
        TypeWarn -> deferred
        TypeError -> return ()
  where
    deferred = addDeferredBinding ctxt err ct
592

593
tryReporters :: ReportErrCtxt -> [ReporterSpec] -> [Ct] -> TcM (ReportErrCtxt, [Ct])
594
-- Use the first reporter in the list whose predicate says True
595
tryReporters ctxt reporters cts
596
  = do { traceTc "tryReporters {" (ppr cts)
597 598 599
       ; (ctxt', cts') <- go ctxt reporters cts
       ; traceTc "tryReporters }" (ppr cts')
       ; return (ctxt', cts') }
600
  where
601
    go ctxt [] cts
602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
      = 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
620

621 622 623 624 625 626 627 628 629

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

630
-- Add the "arising from..." part to a message about bunch of dicts
631
addArising :: CtOrigin -> SDoc -> SDoc
632
addArising orig msg = hang msg 2 (pprArising orig)
633

634
pprWithArising :: [Ct] -> (CtLoc, SDoc)
635 636
-- Print something like
--    (Eq a) arising from a use of x at y
637 638
--    (Show a) arising from a use of p at q
-- Also return a location for the error message
639
-- Works for Wanted/Derived only
640
pprWithArising []
641
  = panic "pprWithArising"
642 643
pprWithArising (ct:cts)
  | null cts
644
  = (loc, addArising (ctLocOrigin loc)
dimitris's avatar
dimitris committed
645
                     (pprTheta [ctPred ct]))
646 647
  | otherwise
  = (loc, vcat (map ppr_one (ct:cts)))
648
  where
649
    loc = ctLoc ct
650
    ppr_one ct' = hang (parens (pprType (ctPred ct')))
651
                     2 (pprCtLoc (ctLoc ct'))
652

653 654 655
mkErrorMsgFromCt :: ReportErrCtxt -> Ct -> Report -> TcM ErrMsg
mkErrorMsgFromCt ctxt ct report
  = mkErrorReport ctxt (ctLocEnv (ctLoc ct)) report
656

657 658 659 660 661 662
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)
       }
663

664
type UserGiven = ([EvVar], SkolemInfo, Bool, RealSrcSpan)
665 666

getUserGivens :: ReportErrCtxt -> [UserGiven]
667
-- One item for each enclosing implication
668
getUserGivens (CEC {cec_encl = ctxt})
669
  = reverse $
670 671 672
    [ (givens, info, no_eqs, tcl_loc env)
    | Implic { ic_given = givens, ic_env = env
             , ic_no_eqs = no_eqs, ic_info = info } <- ctxt
673
    , not (null givens) ]
674

Austin Seipp's avatar
Austin Seipp committed
675
{-
676 677 678 679 680 681
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
682
time.
683 684 685 686 687

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
688
location in mkGroupReporter, when -fdefer-type-errors is on.  But that
689 690
is perhaps a bit *over*-consistent! Again, an easy choice to change.

691 692
With #10283, you can now opt out of deferred type error warnings.

693

694 695
Note [Do not report derived but soluble errors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
696
The wc_simples include Derived constraints that have not been solved, but are
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
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
715
        MkT :: C Int b => a -> b -> T a
716 717 718 719 720 721
      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.

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

725
For functional dependencies, here is a real example,
726 727 728
stripped off from libraries/utf8-string/Codec/Binary/UTF8/Generic.hs

  class C a b | a -> b
729 730 731 732
  g :: C a b => a -> b -> ()
  f :: C a b => a -> b -> ()
  f xa xb =
      let loop = g xa
733 734 735 736
      in loop xb

We will first try to infer a type for loop, and we will succeed:
    C a b' => b' -> ()
737 738 739 740 741
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.
742 743


Austin Seipp's avatar
Austin Seipp committed
744
************************************************************************
745
*                                                                      *
batterseapower's avatar
batterseapower committed
746
                Irreducible predicate errors
747
*                                                                      *
Austin Seipp's avatar
Austin Seipp committed
748 749
************************************************************************
-}
batterseapower's avatar
batterseapower committed
750

751
mkIrredErr :: ReportErrCtxt -> [Ct] -> TcM ErrMsg
752
mkIrredErr ctxt cts
753 754 755
  = do { (ctxt, binds_msg, ct1) <- relevantBindings True ctxt ct1
       ; let orig = ctOrigin ct1
             msg  = couldNotDeduce (getUserGivens ctxt) (map ctPred cts, orig)
756 757
       ; mkErrorMsgFromCt ctxt ct1 $
            important msg `mappend` relevant_bindings binds_msg }
batterseapower's avatar
batterseapower committed
758
  where
759
    (ct1:_) = cts
batterseapower's avatar
batterseapower committed
760

761
----------------
762
mkHoleError :: ReportErrCtxt -> Ct -> TcM ErrMsg
763
mkHoleError ctxt ct@(CHoleCan { cc_occ = occ, cc_hole = hole_sort })
Simon Peyton Jones's avatar
Simon Peyton Jones committed
764 765
  | isOutOfScopeCt ct  -- Out of scope variables, like 'a', where 'a' isn't bound
                       -- Suggest possible in-scope variables in the message
766 767
  = do { dflags  <- getDynFlags
       ; rdr_env <- getGlobalRdrEnv
Joachim Breitner's avatar
Joachim Breitner committed
768
       ; impInfo <- getImports
769 770 771 772
       ; mkErrDocAt (RealSrcSpan (tcl_loc lcl_env)) $
                    errDoc [out_of_scope_msg] []
                           [unknownNameSuggestions dflags rdr_env
                            (tcl_rdr lcl_env) impInfo (mkRdrUnqual occ)] }
773

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

780
  where
781 782 783
    ct_loc      = ctLoc ct
    lcl_env     = ctLocEnv ct_loc
    hole_ty     = ctEvPred (ctEvidence ct)
784
    tyvars      = tyVarsOfTypeList hole_ty
785
    boring_type = isTyVarTy hole_ty
786

787 788 789
    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
790 791 792 793 794

    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:")

795 796 797 798 799 800 801 802
    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 ]

803 804 805
    tyvars_msg = ppUnless (null tyvars) $
                 ptext (sLit "Where:") <+> vcat (map loc_msg tyvars)

806 807
    type_hole_hint
         | HoleError <- cec_type_holes ctxt
808
         = ptext (sLit "To use the inferred type, enable PartialTypeSignatures")
809 810
         | otherwise
         = empty
811

812 813
    expr_hole_hint                       -- Give hint for, say,   f x = _x
         | lengthFS (occNameFS occ) > 1  -- Don't give this hint for plain "_"
814 815 816 817
         = ptext (sLit "Or perhaps") <+> quotes (ppr occ)
           <+> ptext (sLit "is mis-spelled, or not in scope")
         | otherwise
         = empty
818

819
    loc_msg tv
820 821
       = case tcTyVarDetails tv of
          SkolemTv {} -> quotes (ppr tv) <+> skol_msg
822
          MetaTv {}   -> quotes (ppr tv) <+> ptext (sLit "is an ambiguous type variable")
823
          det -> pprTcTyVarDetails det
824
       where
825
          skol_msg = pprSkol (getSkolemInfo (cec_encl ctxt) tv) (getSrcLoc tv)
826 827

mkHoleError _ ct = pprPanic "mkHoleError" (ppr ct)
828

829
----------------
830 831
mkIPErr :: ReportErrCtxt -> [Ct] -> TcM ErrMsg
mkIPErr ctxt cts
832
  = do { (ctxt, binds_msg, ct1) <- relevantBindings True ctxt ct1
833 834 835 836 837 838 839 840 841 842
       ; let orig    = ctOrigin ct1
             preds   = map ctPred cts
             givens  = getUserGivens ctxt
             msg | null givens
                 = addArising orig $
                   sep [ ptext (sLit "Unbound implicit parameter") <> plural cts
                       , nest 2 (pprTheta preds) ]
                 | otherwise
                 = couldNotDeduce givens (preds, orig)

843 844
       ; mkErrorMsgFromCt ctxt ct1 $
            important msg `mappend` relevant_bindings binds_msg }
845
  where
846
    (ct1:_) = cts
847

Austin Seipp's avatar
Austin Seipp committed
848 849 850
{-
************************************************************************
*                                                                      *
851
                Equality errors
Austin Seipp's avatar
Austin Seipp committed
852 853
*                                                                      *
************************************************************************
854

855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
Note [Inaccessible code]
~~~~~~~~~~~~~~~~~~~~~~~~
Consider
   data T a where
     T1 :: T a
     T2 :: T Bool

   f :: (a ~ Int) => T a -> Int
   f T1 = 3
   f T2 = 4   -- Unreachable code

Here the second equation is unreachable. The original constraint
(a~Int) from the signature gets rewritten by the pattern-match to
(Bool~Int), so the danger is that we report the error as coming from
the *signature* (Trac #7293).  So, for Given errors we replace the
env (and hence src-loc) on its CtLoc with that from the immediately
enclosing implication.
Austin Seipp's avatar
Austin Seipp committed
872
-}
873

874 875 876 877 878 879 880 881 882
mkEqErr :: ReportErrCtxt -> [Ct] -> TcM ErrMsg
-- Don't have multiple equality errors from the same location
-- E.g.   (Int,Bool) ~ (Bool,Int)   one error will do!
mkEqErr ctxt (ct:_) = mkEqErr1 ctxt ct
mkEqErr _ [] = panic "mkEqErr"

mkEqErr1 :: ReportErrCtxt -> Ct -> TcM ErrMsg
-- Wanted constraints only!
mkEqErr1 ctxt ct
883 884 885
  | isGivenCt ct
  = do { (ctxt, binds_msg, ct) <- relevantBindings True ctxt ct
       ; let (given_loc, given_msg) = mk_given (ctLoc ct) (cec_encl ctxt)
886
       ; dflags <- getDynFlags
887 888
       ; let report = important given_msg `mappend` relevant_bindings binds_msg
       ; mkEqErr_help dflags ctxt report
889
                      (setCtLoc ct given_loc) -- Note [Inaccessible code]
890 891 892
                      Nothing ty1 ty2 }

  | otherwise   -- Wanted or derived
893
  = do { (ctxt, binds_msg, ct) <- relevantBindings True ctxt ct
894 895
       ; rdr_env <- getGlobalRdrEnv
       ; fam_envs <- tcGetFamInstEnvs
896 897
       ; exp_syns <- goptM Opt_PrintExpandedSynonyms
       ; let (is_oriented, wanted_msg) = mk_wanted_extra (ctOrigin ct) exp_syns
898
             coercible_msg = case ctEqRel ct of
899 900
               NomEq  -> empty
               ReprEq -> mkCoercibleExplanation rdr_env fam_envs ty1 ty2
901
       ; dflags <- getDynFlags
902
       ; traceTc "mkEqErr1" (ppr ct $$ pprCtOrigin (ctOrigin ct))
903 904 905
       ; let report = mconcat [important wanted_msg, important coercible_msg,
                               relevant_bindings binds_msg]
       ; mkEqErr_help dflags ctxt report ct is_oriented ty1 ty2 }
906
  where
907
    (ty1, ty2) = getEqPredTys (ctPred ct)
908

909
    mk_given :: CtLoc -> [Implication] -> (CtLoc, SDoc)
910 911
    -- For given constraints we overwrite the env (and hence src-loc)
    -- with one from the implication.  See Note [Inaccessible code]
912 913 914 915
    mk_given loc []           = (loc, empty)
    mk_given loc (implic : _) = (setCtLocEnv loc (ic_env implic)
                                , hang (ptext (sLit "Inaccessible code in"))
                                     2 (ppr (ic_info implic)))
916

917 918
       -- If the types in the error message are the same as the types
       -- we are unifying, don't add the extra expected/actual message
919 920 921
    mk_wanted_extra :: CtOrigin -> Bool -> (Maybe SwapFlag, SDoc)
    mk_wanted_extra orig@(TypeEqOrigin {}) expandSyns
      = mkExpectedActualMsg ty1 ty2 orig expandSyns
922

923
    mk_wanted_extra (KindEqOrigin cty1 cty2 sub_o) expandSyns
924
      = (Nothing, msg1 $$ msg2)
925
      where
926 927 928 929
        msg1 = hang (ptext (sLit "When matching types"))
                  2 (vcat [ ppr cty1 <+> dcolon <+> ppr (typeKind cty1)
                          , ppr cty2 <+> dcolon <+> ppr (typeKind cty2) ])
        msg2 = case sub_o of
930 931 932 933
                 TypeEqOrigin {} ->
                   snd (mkExpectedActualMsg cty1 cty2 sub_o expandSyns)
                 _ ->
                   empty
934

935
    mk_wanted_extra _ _ = (Nothing, empty)
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983

-- | This function tries to reconstruct why a "Coercible ty1 ty2" constraint
-- is left over.
mkCoercibleExplanation :: GlobalRdrEnv -> FamInstEnvs
                       -> TcType -> TcType -> SDoc
mkCoercibleExplanation rdr_env fam_envs ty1 ty2
  | Just (tc, tys) <- tcSplitTyConApp_maybe ty1
  , (rep_tc, _, _) <- tcLookupDataFamInst fam_envs tc tys
  , Just msg <- coercible_msg_for_tycon rep_tc
  = msg
  | Just (tc, tys) <- splitTyConApp_maybe ty2
  , (rep_tc, _, _) <- tcLookupDataFamInst fam_envs tc tys
  , Just msg <- coercible_msg_for_tycon rep_tc
  = msg
  | Just (s1, _) <- tcSplitAppTy_maybe ty1
  , Just (s2, _) <- tcSplitAppTy_maybe ty2
  , s1 `eqType` s2
  , has_unknown_roles s1
  = hang (text "NB: We cannot know what roles the parameters to" <+>
          quotes (ppr s1) <+> text "have;")
       2 (text "we must assume that the role is nominal")
  | otherwise
  = empty
  where
    coercible_msg_for_tycon tc
        | isAbstractTyCon tc
        = Just $ hsep [ text "NB: The type constructor"
                      , quotes (pprSourceTyCon tc)
                      , text "is abstract" ]
        | isNewTyCon tc
        , [data_con] <- tyConDataCons tc
        , let dc_name = dataConName data_con
        , null (lookupGRE_Name rdr_env dc_name)
        = Just $ hang (text "The data constructor" <+> quotes (ppr dc_name))
                    2 (sep [ text "of newtype" <+> quotes (pprSourceTyCon tc)
                           , text "is not in scope" ])
        | otherwise = Nothing

    has_unknown_roles ty
      | Just (tc, tys) <- tcSplitTyConApp_maybe ty
      = length tys >= tyConArity tc  -- oversaturated tycon
      | Just (s, _) <- tcSplitAppTy_maybe ty
      = has_unknown_roles s
      | isTyVarTy ty
      = True
      | otherwise
      = False

984
{-
985 986
-- | Make a listing of role signatures for all the parameterised tycons
-- used in the provided types
987 988 989 990 991


-- SLPJ Jun 15: I could not convince myself that these hints were really
-- useful.  Maybe they are, but I think we need more work to make them
-- actually helpful.
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
mkRoleSigs :: Type -> Type -> SDoc
mkRoleSigs ty1 ty2
  = ppUnless (null role_sigs) $
    hang (text "Relevant role signatures:")
       2 (vcat role_sigs)
  where
    tcs = nameEnvElts $ tyConsOfType ty1 `plusNameEnv` tyConsOfType ty2
    role_sigs = mapMaybe ppr_role_sig tcs

    ppr_role_sig tc
      | null roles  -- if there are no parameters, don't bother printing
      = Nothing
      | otherwise
      = Just $ hsep $ [text "type role", ppr tc] ++ map ppr roles
      where
        roles = tyConRoles tc
1008
-}
1009

1010
mkEqErr_help :: DynFlags -> ReportErrCtxt -> Report
1011
             -> Ct
1012 1013
             -> Maybe SwapFlag   -- Nothing <=> not sure
             -> TcType -> TcType -> TcM ErrMsg
1014 1015 1016 1017
mkEqErr_help dflags ctxt report ct oriented ty1 ty2
  | Just tv1 <- tcGetTyVar_maybe ty1 = mkTyVarEqErr dflags ctxt report ct oriented tv1 ty2
  | Just tv2 <- tcGetTyVar_maybe ty2 = mkTyVarEqErr dflags ctxt report ct swapped  tv2 ty1
  | otherwise                        = reportEqErr ctxt report ct oriented ty1 ty2
1018 1019
  where
    swapped = fmap flipSwap oriented
1020

1021
reportEqErr :: ReportErrCtxt -> Report
1022
            -> Ct
1023 1024
            -> Maybe SwapFlag   -- Nothing <=> not sure
            -> TcType -> TcType -> TcM ErrMsg
1025 1026 1027 1028
reportEqErr ctxt report ct oriented ty1 ty2
  = mkErrorMsgFromCt ctxt ct (mconcat [misMatch, eqInfo, report])
  where misMatch = important $ misMatchOrCND ctxt ct oriented ty1 ty2
        eqInfo = important $ mkEqInfoMsg ct ty1 ty2
1029

1030
mkTyVarEqErr :: DynFlags -> ReportErrCtxt -> Report -> Ct
1031
             -> Maybe SwapFlag -> TcTyVar -> TcType -> TcM ErrMsg
1032
-- tv1 and ty2 are already tidied
1033
mkTyVarEqErr dflags ctxt report ct oriented tv1 ty2
1034
  | isUserSkolem ctxt tv1   -- ty2 won't be a meta-tyvar, or else the thing would
1035 1036
                            -- be oriented the other way round;
                            -- see TcCanonical.canEqTyVarTyVar
1037
  || isSigTyVar tv1 && not (isTyVarTy ty2)
1038
  || ctEqRel ct == ReprEq && not (isTyVarUnderDatatype tv1 ty2)
1039
     -- the cases below don't really apply to ReprEq (except occurs check)
1040 1041 1042 1043 1044
  = mkErrorMsgFromCt ctxt ct $ mconcat
        [ important $ misMatchOrCND ctxt ct oriented ty1 ty2
        , important $ extraTyVarInfo ctxt tv1 ty2
        , report
        ]
1045

1046 1047
  -- So tv is a meta tyvar (or started that way before we
  -- generalised it).  So presumably it is an *untouchable*
1048
  -- meta tyvar or a SigTv, else it'd have been unified
1049
  | not (k2 `tcIsSubKind` k1)            -- Kind error
1050 1051
  = mkErrorMsgFromCt ctxt ct $
        (important $ kindErrorMsg (mkTyVarTy tv1) ty2) `mappend` report
1052

1053
  | OC_Occurs <- occ_check_expand
1054 1055
  , ctEqRel ct == NomEq || isTyVarUnderDatatype tv1 ty2
         -- See Note [Occurs check error] in TcCanonical
1056
  = do { let occCheckMsg = important $ addArising (ctOrigin ct) $
1057
                           hang (text "Occurs check: cannot construct the infinite type:")
1058
                              2 (sep [ppr ty1, char '~', ppr ty2])
1059 1060
             extra2 = important $ mkEqInfoMsg ct ty1 ty2
       ; mkErrorMsgFromCt ctxt ct $ mconcat [occCheckMsg, extra2, report] }
1061