TcErrors.lhs 63.3 KB
Newer Older
1
\begin{code}
2
{-# LANGUAGE CPP, ScopedTypeVariables #-}
3 4

module TcErrors(
5
       reportUnsolved, reportAllUnsolved,
6
       warnDefaulting,
7 8

       solverDepthErrorTcS
9 10 11 12
  ) where

#include "HsVersions.h"

13
import TcRnTypes
14 15 16
import TcRnMonad
import TcMType
import TcType
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          ( FamInstEnvs, tcGetFamInstEnvs, tcLookupDataFamInst )
23 24 25
import Inst
import InstEnv
import TyCon
26
import DataCon
27
import TcEvidence
28
import TysWiredIn       ( coercibleClass )
29
import Name
30
import RdrName          ( lookupGRE_Name )
31
import Id
32 33 34 35
import Var
import VarSet
import VarEnv
import Bag
36
import ErrUtils         ( ErrMsg, makeIntoWarning, pprLocErrMsg )
37
import BasicTypes
38 39 40
import Util
import FastString
import Outputable
41
import SrcLoc
42
import DynFlags
43
import StaticFlags      ( opt_PprStyle_Debug )
44
import ListSetOps       ( equivClasses )
Icelandjack's avatar
Icelandjack committed
45 46

import Data.Maybe
47
import Data.List        ( partition, mapAccumL, zip4, nub )
48 49 50
\end{code}

%************************************************************************
51
%*                                                                      *
52
\section{Errors and contexts}
53
%*                                                                      *
54 55 56 57 58 59
%************************************************************************

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?

60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
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
79

80 81 82 83 84 85 86 87 88 89 90 91 92 93
  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
94
and does not fail if -fdefer-type-errors is on, so that we can continue
95 96 97 98 99 100
compilation. The errors are turned into warnings in `reportUnsolved`.

\begin{code}
reportUnsolved :: WantedConstraints -> TcM (Bag EvBind)
reportUnsolved wanted
  = do { binds_var <- newTcEvBinds
ian@well-typed.com's avatar
ian@well-typed.com committed
101
       ; defer <- goptM Opt_DeferTypeErrors
102 103 104 105 106 107
       ; report_unsolved (Just binds_var) defer wanted
       ; getTcEvBinds binds_var }

reportAllUnsolved :: WantedConstraints -> TcM ()
-- Report all unsolved goals, even if -fdefer-type-errors is on
-- See Note [Deferring coercion errors to runtime]
Simon Peyton Jones's avatar
Simon Peyton Jones committed
108
reportAllUnsolved wanted = report_unsolved Nothing False wanted
109 110 111 112

report_unsolved :: Maybe EvBindsVar  -- cec_binds
                -> Bool              -- cec_defer
                -> WantedConstraints -> TcM ()
113 114 115
-- Important precondition:
-- WantedConstraints are fully zonked and unflattened, that is,
-- zonkWC has already been applied to these constraints.
116
report_unsolved mb_binds_var defer wanted
117
  | isEmptyWC wanted
118
  = return ()
119
  | otherwise
120
  = do { traceTc "reportUnsolved (before unflattening)" (ppr wanted)
121

122
       ; env0 <- tcInitTidyEnv
123

124 125
            -- If we are deferring we are going to need /all/ evidence around,
            -- including the evidence produced by unflattening (zonkWC)
126
       ; let tidy_env = tidyFreeTyVars env0 free_tvs
127
             free_tvs = tyVarsOfWC wanted
128
             err_ctxt = CEC { cec_encl  = []
129
                            , cec_tidy  = tidy_env
130
                            , cec_defer    = defer
131
                            , cec_suppress = False -- See Note [Suppressing error messages]
132
                            , cec_binds    = mb_binds_var }
133

134
       ; traceTc "reportUnsolved (after unflattening):" $
135 136
         vcat [ pprTvBndrs (varSetElems free_tvs)
              , ppr wanted ]
137

138
       ; reportWanteds err_ctxt wanted }
139

140 141 142
--------------------------------------------
--      Internal functions
--------------------------------------------
143

144
data ReportErrCtxt
145
    = CEC { cec_encl :: [Implication]  -- Enclosing implications
146
                                       --   (innermost first)
147
                                       -- ic_skols and givens are tidied, rest are not
148
          , cec_tidy  :: TidyEnv
149
          , cec_binds :: Maybe EvBindsVar
150 151 152 153
                         -- 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
154

155 156
          , cec_defer :: Bool       -- True <=> -fdefer-type-errors
                                    -- Irrelevant if cec_binds = Nothing
157 158 159
          , cec_suppress :: Bool    -- True <=> More important errors have occurred,
                                    --          so create bindings if need be, but
                                    --          don't issue any more errors/warnings
160
                                    -- See Note [Suppressing error messages]
161
      }
162
\end{code}
163

164 165 166 167 168 169 170
Note [Suppressing error messages]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The cec_suppress flag says "don't report any errors.  Instead, just create
evidence bindings (as usual).  It's used when more important errors have occurred.
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.
171
  * If there are any insolubles (eg Int~Bool), here or in a nested implication,
172 173 174 175 176
    then suppress errors from the flat constraints here.  Sometimes the
    flat-constraint errors are a knock-on effect of the insolubles.


\begin{code}
177 178 179
reportImplic :: ReportErrCtxt -> Implication -> TcM ()
reportImplic ctxt implic@(Implic { ic_skols = tvs, ic_given = given
                                 , ic_wanted = wanted, ic_binds = evb
Simon Peyton Jones's avatar
Simon Peyton Jones committed
180
                                 , ic_insol = ic_insoluble, ic_info = info })
181
  | BracketSkol <- info
Simon Peyton Jones's avatar
Simon Peyton Jones committed
182 183 184 185
  , not ic_insoluble -- For Template Haskell brackets report only
  = return ()        -- definite errors. The whole thing will be re-checked
                     -- later when we plug it in, and meanwhile there may
                     -- certainly be un-satisfied constraints
186 187

  | otherwise
188
  = reportWanteds ctxt' wanted
189
  where
190
    (env1, tvs') = mapAccumL tidyTyVarBndr (cec_tidy ctxt) tvs
191
    (env2, info') = tidySkolemInfo env1 info
192
    implic' = implic { ic_skols = tvs'
193 194 195
                     , ic_given = map (tidyEvVar env2) given
                     , ic_info  = info' }
    ctxt' = ctxt { cec_tidy  = env2
196
                 , cec_encl  = implic' : cec_encl ctxt
197
                 , cec_binds = case cec_binds ctxt of
198 199 200 201
                                 Nothing -> Nothing
                                 Just {} -> Just evb }

reportWanteds :: ReportErrCtxt -> WantedConstraints -> TcM ()
202 203 204 205
reportWanteds ctxt wanted@(WC { wc_flat = flats, wc_insol = insols, wc_impl = implics })
  = do { reportFlats ctxt  (mapBag (tidyCt env) insol_given)
       ; reportFlats ctxt1 (mapBag (tidyCt env) insol_wanted)
       ; reportFlats ctxt2 (mapBag (tidyCt env) flats)
206
            -- All the Derived ones have been filtered out of flats
207 208 209
            -- 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]
210 211 212 213 214 215
       ; mapBagM_ (reportImplic ctxt1) implics }
            -- NB ctxt1: don't suppress inner insolubles if there's only a
            -- wanted insoluble here; but do suppress inner insolubles
            -- if there's a given insoluble here (= inaccessible code)
 where
    (insol_given, insol_wanted) = partitionBag isGivenCt insols
216 217
    env = cec_tidy ctxt

218 219 220 221 222 223 224
      -- See Note [Suppressing error messages]
    suppress0 = cec_suppress ctxt
    suppress1 = suppress0 || not (isEmptyBag insol_given)
    suppress2 = suppress0 || insolubleWC wanted
    ctxt1     = ctxt { cec_suppress = suppress1 }
    ctxt2     = ctxt { cec_suppress = suppress2 }

225 226
reportFlats :: ReportErrCtxt -> Cts -> TcM ()
reportFlats ctxt flats    -- Here 'flats' includes insolble goals
227 228 229
  =  traceTc "reportFlats" (vcat [ ptext (sLit "Flats =") <+> ppr flats
                                 , ptext (sLit "Suppress =") <+> ppr (cec_suppress ctxt)])
  >> tryReporters
230 231 232
      [ -- First deal with things that are utterly wrong
        -- Like Int ~ Bool (incl nullary TyCons)
        -- or  Int ~ t a   (AppTy on one side)
233 234
        ("Utterly wrong",  utterly_wrong,   True, mkGroupReporter mkEqErr)
      , ("Holes",          is_hole,         True, mkUniReporter mkHoleError)
235 236

        -- Report equalities of form (a~ty).  They are usually
237
        -- skolem-equalities, and they cause confusing knock-on
238
        -- effects in other errors; see test T4093b.
239 240 241 242 243 244 245 246 247 248 249 250
      , ("Skolem equalities", skolem_eq,  True,  mkSkolReporter)

        -- Other equalities; also confusing knock on effects
      , ("Equalities",      is_equality, True,  mkGroupReporter mkEqErr)

      , ("Implicit params", is_ip,       False, mkGroupReporter mkIPErr)
      , ("Irreds",          is_irred,    False, mkGroupReporter mkIrredErr)
      , ("Dicts",           is_dict,     False, mkGroupReporter mkDictErr)
      ]
      panicReporter ctxt (bagToList flats)
          -- TuplePreds should have been expanded away by the constraint
          -- simplifier, so they shouldn't show up at this point
251
  where
252 253 254 255
    utterly_wrong, skolem_eq, is_hole, is_dict,
      is_equality, is_ip, is_irred :: Ct -> PredTree -> Bool

    utterly_wrong _ (EqPred ty1 ty2) = isRigid ty1 && isRigid ty2
256 257
    utterly_wrong _ _ = False

258 259
    is_hole ct _ = isHoleCt ct

260
    skolem_eq _ (EqPred ty1 ty2) = isRigidOrSkol ty1 && isRigidOrSkol ty2
261 262
    skolem_eq _ _ = False

263 264 265 266 267 268 269 270 271 272 273 274 275
    is_equality _ (EqPred {}) = True
    is_equality _ _           = False

    is_dict _ (ClassPred {}) = True
    is_dict _ _              = False

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

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


276 277
---------------
isRigid, isRigidOrSkol :: Type -> Bool
278
isRigid ty
279 280 281 282 283
  | Just (tc,_) <- tcSplitTyConApp_maybe ty = isDecomposableTyCon tc
  | Just {} <- tcSplitAppTy_maybe ty        = True
  | isForAllTy ty                           = True
  | otherwise                               = False

284
isRigidOrSkol ty
285 286 287 288 289 290 291 292
  | Just tv <- getTyVar_maybe ty = isSkolemTyVar tv
  | otherwise                    = isRigid ty

isTyFun_maybe :: Type -> Maybe TyCon
isTyFun_maybe ty = case tcSplitTyConApp_maybe ty of
                      Just (tc,_) | isSynFamilyTyCon tc -> Just tc
                      _ -> Nothing

293 294

--------------------------------------------
295
--      Reporters
296 297
--------------------------------------------

298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
type Reporter
  = ReportErrCtxt -> [Ct] -> TcM ()
type ReporterSpec
  = ( String                     -- Name
    , Ct -> PredTree -> Bool     -- Pick these ones
    , Bool                       -- True <=> suppress subsequent reporters
    , Reporter)                  -- The reporter itself

panicReporter :: Reporter
panicReporter _ cts
  | null cts  = return ()
  | otherwise =  pprPanic "reportFlats" (ppr cts)

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
           (EqPred ty1 _, EqPred ty2 _) -> ty1 `cmpType` ty2
           _ -> pprPanic "mkSkolReporter" (ppr ct1 $$ ppr ct2)
320 321 322

mkUniReporter :: (ReportErrCtxt -> Ct -> TcM ErrMsg) -> Reporter
-- Reports errors one at a time
323 324
mkUniReporter mk_err ctxt
  = mapM_ $ \ct ->
325
    do { err <- mk_err ctxt ct
326
       ; maybeReportError ctxt err
327
       ; maybeAddDeferredBinding ctxt err ct }
328 329 330 331

mkGroupReporter :: (ReportErrCtxt -> [Ct] -> TcM ErrMsg)
                             -- Make error message for a group
                -> Reporter  -- Deal with lots of constraints
332 333 334 335 336
-- 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
337
    cmp_loc ct1 ct2 = ctLocSpan (ctLoc ct1) `compare` ctLocSpan (ctLoc ct2)
338

339 340 341 342
reportGroup :: (ReportErrCtxt -> [Ct] -> TcM ErrMsg) -> ReportErrCtxt
            -> [Ct] -> TcM ()
reportGroup mk_err ctxt cts
  = do { err <- mk_err ctxt cts
343
       ; maybeReportError ctxt err
344
       ; mapM_ (maybeAddDeferredBinding ctxt err) cts }
345
               -- Add deferred bindings for all
346
               -- But see Note [Always warn with -fdefer-type-errors]
347

348
maybeReportError :: ReportErrCtxt -> ErrMsg -> TcM ()
349
-- Report the error and/or make a deferred binding for it
350
maybeReportError ctxt err
351
  | cec_defer ctxt  -- See Note [Always warn with -fdefer-type-errors]
352
  = reportWarning (makeIntoWarning err)
353 354 355 356 357 358 359 360
  | cec_suppress ctxt
  = return ()
  | otherwise
  = reportError err

maybeAddDeferredBinding :: ReportErrCtxt -> ErrMsg -> Ct -> TcM ()
-- See Note [Deferring coercion errors to runtime]
maybeAddDeferredBinding ctxt err ct
361
  | CtWanted { ctev_pred = pred, ctev_evar = ev_id } <- ctEvidence ct
362 363
    -- Only add deferred bindings for Wanted constraints
  , isHoleCt ct || cec_defer ctxt  -- And it's a hole or we have -fdefer-type-errors
364
  , Just ev_binds_var <- cec_binds ctxt  -- We have somewhere to put the bindings
365 366 367 368 369 370 371 372 373
  = do { dflags <- getDynFlags
       ; let err_msg = pprLocErrMsg err
             err_fs  = mkFastString $ showSDoc dflags $
                       err_msg $$ text "(deferred type error)"

         -- Create the binding
       ; addTcEvBind ev_binds_var ev_id (EvDelayedError pred err_fs) }

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

376
tryReporters :: [ReporterSpec] -> Reporter -> Reporter
377 378
-- Use the first reporter in the list whose predicate says True
tryReporters reporters deflt ctxt cts
379
  = do { traceTc "tryReporters {" (ppr cts)
380
       ; go ctxt reporters cts
381 382
       ; traceTc "tryReporters }" empty }
  where
383 384
    go ctxt [] cts = deflt ctxt cts
    go ctxt ((str, pred, suppress_after, reporter) : rs) cts
385 386 387 388
      | null yeses  = do { traceTc "tryReporters: no" (text str)
                         ; go ctxt rs cts }
      | otherwise   = do { traceTc "tryReporters: yes" (text str <+> ppr yeses)
                         ; reporter ctxt yeses :: TcM ()
389 390
                         ; let ctxt' = ctxt { cec_suppress = suppress_after || cec_suppress ctxt }
                         ; go ctxt' rs nos }
391
                         -- Carry on with the rest, because we must make
392
                         -- deferred bindings for them if we have
393
                         -- -fdefer-type-errors
Simon Peyton Jones's avatar
Simon Peyton Jones committed
394
                         -- But suppress their error messages
395
      where
396
       (yeses, nos) = partition keep_me cts
397
       keep_me ct = pred ct (classifyPredType (ctPred ct))
398 399

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

403
pprWithArising :: [Ct] -> (CtLoc, SDoc)
404 405
-- Print something like
--    (Eq a) arising from a use of x at y
406 407
--    (Show a) arising from a use of p at q
-- Also return a location for the error message
408
-- Works for Wanted/Derived only
409
pprWithArising []
410
  = panic "pprWithArising"
411 412
pprWithArising (ct:cts)
  | null cts
413
  = (loc, addArising (ctLocOrigin loc)
dimitris's avatar
dimitris committed
414
                     (pprTheta [ctPred ct]))
415 416
  | otherwise
  = (loc, vcat (map ppr_one (ct:cts)))
417
  where
418
    loc = ctLoc ct
419
    ppr_one ct' = hang (parens (pprType (ctPred ct')))
420
                     2 (pprArisingAt (ctLoc ct'))
421

422
mkErrorMsg :: ReportErrCtxt -> Ct -> SDoc -> TcM ErrMsg
423
mkErrorMsg ctxt ct msg
424
  = do { let tcl_env = ctLocEnv (ctLoc ct)
425 426
       ; err_info <- mkErrInfo (cec_tidy ctxt) (tcl_ctxt tcl_env)
       ; mkLongErrAt (tcl_loc tcl_env) msg err_info }
427

428
type UserGiven = ([EvVar], SkolemInfo, Bool, SrcSpan)
429 430

getUserGivens :: ReportErrCtxt -> [UserGiven]
431
-- One item for each enclosing implication
432
getUserGivens (CEC {cec_encl = ctxt})
433
  = reverse $
434 435 436
    [ (givens, info, no_eqs, tcl_loc env)
    | Implic { ic_given = givens, ic_env = env
             , ic_no_eqs = no_eqs, ic_info = info } <- ctxt
437
    , not (null givens) ]
438 439
\end{code}

440 441 442 443 444 445
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
446
time.
447 448 449 450 451

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


456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
Note [Do not report derived but soluble errors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The wc_flats include Derived constraints that have not been solved, but are
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
477
        MkT :: C Int b => a -> b -> T a
478 479 480 481 482 483 484 485 486
      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.

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

487
For functional dependencies, here is a real example,
488 489 490
stripped off from libraries/utf8-string/Codec/Binary/UTF8/Generic.hs

  class C a b | a -> b
491 492 493 494
  g :: C a b => a -> b -> ()
  f :: C a b => a -> b -> ()
  f xa xb =
      let loop = g xa
495 496 497 498
      in loop xb

We will first try to infer a type for loop, and we will succeed:
    C a b' => b' -> ()
499 500 501 502 503
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.
504 505


batterseapower's avatar
batterseapower committed
506 507 508 509 510 511 512
%************************************************************************
%*                  *
                Irreducible predicate errors
%*                  *
%************************************************************************

\begin{code}
513
mkIrredErr :: ReportErrCtxt -> [Ct] -> TcM ErrMsg
514
mkIrredErr ctxt cts
515
  = do { (ctxt, binds_msg) <- relevantBindings True ctxt ct1
516
       ; mkErrorMsg ctxt ct1 (msg $$ binds_msg) }
batterseapower's avatar
batterseapower committed
517
  where
518
    (ct1:_) = cts
519
    orig    = ctLocOrigin (ctLoc ct1)
520 521
    givens  = getUserGivens ctxt
    msg = couldNotDeduce givens (map ctPred cts, orig)
batterseapower's avatar
batterseapower committed
522

523
----------------
524
mkHoleError :: ReportErrCtxt -> Ct -> TcM ErrMsg
525
mkHoleError ctxt ct@(CHoleCan { cc_occ = occ })
526 527
  = do { let tyvars = varSetElems (tyVarsOfCt ct)
             tyvars_msg = map loc_msg tyvars
528
             msg = vcat [ hang (ptext (sLit "Found hole") <+> quotes (ppr occ))
529
                             2 (ptext (sLit "with type:") <+> pprType (ctEvPred (ctEvidence ct)))
530
                        , ppUnless (null tyvars_msg) (ptext (sLit "Where:") <+> vcat tyvars_msg) ]
531 532
       ; (ctxt, binds_doc) <- relevantBindings False ctxt ct
               -- The 'False' means "don't filter the bindings; see Trac #8191
533
       ; mkErrorMsg ctxt ct (msg $$ binds_doc) }
534
  where
535
    loc_msg tv
536 537
       = case tcTyVarDetails tv of
          SkolemTv {} -> quotes (ppr tv) <+> skol_msg
538
          MetaTv {}   -> quotes (ppr tv) <+> ptext (sLit "is an ambiguous type variable")
539
          det -> pprTcTyVarDetails det
540
       where
541
          skol_msg = pprSkol (getSkolemInfo (cec_encl ctxt) tv) (getSrcLoc tv)
542 543

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

545
----------------
546 547
mkIPErr :: ReportErrCtxt -> [Ct] -> TcM ErrMsg
mkIPErr ctxt cts
548
  = do { (ctxt, bind_msg) <- relevantBindings True ctxt ct1
549
       ; mkErrorMsg ctxt ct1 (msg $$ bind_msg) }
550
  where
551
    (ct1:_) = cts
552
    orig    = ctLocOrigin (ctLoc ct1)
553 554
    preds   = map ctPred cts
    givens  = getUserGivens ctxt
555 556
    msg | null givens
        = addArising orig $
557
          sep [ ptext (sLit "Unbound implicit parameter") <> plural cts
558
              , nest 2 (pprTheta preds) ]
559
        | otherwise
560
        = couldNotDeduce givens (preds, orig)
561 562 563 564
\end{code}


%************************************************************************
565
%*                                                                      *
566
                Equality errors
567
%*                                                                      *
568 569
%************************************************************************

570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
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.

588
\begin{code}
589 590 591 592 593 594 595 596 597
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
598
  | isGiven ev
599
  = do { (ctxt, binds_msg) <- relevantBindings True ctxt ct
600
       ; let (given_loc, given_msg) = mk_given (cec_encl ctxt)
601
       ; dflags <- getDynFlags
602
       ; mkEqErr_help dflags ctxt (given_msg $$ binds_msg)
603
                      (ct { cc_ev = ev {ctev_loc = given_loc}}) -- Note [Inaccessible code]
604 605 606
                      Nothing ty1 ty2 }

  | otherwise   -- Wanted or derived
607
  = do { (ctxt, binds_msg) <- relevantBindings True ctxt ct
608
       ; (env1, tidy_orig) <- zonkTidyOrigin (cec_tidy ctxt) (ctLocOrigin loc)
609
       ; let (is_oriented, wanted_msg) = mk_wanted_extra tidy_orig
610
       ; dflags <- getDynFlags
611
       ; traceTc "mkEqErr1" (ppr ct $$ pprCtOrigin (ctLocOrigin loc) $$ pprCtOrigin tidy_orig) 
612 613
       ; mkEqErr_help dflags (ctxt {cec_tidy = env1})
                      (wanted_msg $$ binds_msg)
614
                      ct is_oriented ty1 ty2 }
615
  where
616 617
    ev         = ctEvidence ct
    loc        = ctev_loc ev
618 619 620 621 622
    (ty1, ty2) = getEqPredTys (ctEvPred ev)

    mk_given :: [Implication] -> (CtLoc, SDoc)
    -- For given constraints we overwrite the env (and hence src-loc)
    -- with one from the implication.  See Note [Inaccessible code]
623 624
    mk_given []           = (loc, empty)
    mk_given (implic : _) = (setCtLocEnv loc (ic_env implic)
625 626
                            , hang (ptext (sLit "Inaccessible code in"))
                                 2 (ppr (ic_info implic)))
627

628 629
       -- If the types in the error message are the same as the types
       -- we are unifying, don't add the extra expected/actual message
630 631 632 633 634
    mk_wanted_extra orig@(TypeEqOrigin {})
      = mkExpectedActualMsg ty1 ty2 orig

    mk_wanted_extra (KindEqOrigin cty1 cty2 sub_o)
      = (Nothing, msg1 $$ msg2)
635
      where
636 637 638 639 640 641 642
        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
                 TypeEqOrigin {} -> snd (mkExpectedActualMsg cty1 cty2 sub_o)
                 _ -> empty

643 644 645
    mk_wanted_extra orig@(FunDepOrigin1 {}) = (Nothing, pprArising orig)
    mk_wanted_extra orig@(FunDepOrigin2 {}) = (Nothing, pprArising orig)
    mk_wanted_extra _                       = (Nothing, empty)
646

647
mkEqErr_help :: DynFlags -> ReportErrCtxt -> SDoc
648
             -> Ct
649 650 651 652 653
             -> Maybe SwapFlag   -- Nothing <=> not sure
             -> TcType -> TcType -> TcM ErrMsg
mkEqErr_help dflags ctxt extra ct oriented ty1 ty2
  | Just tv1 <- tcGetTyVar_maybe ty1 = mkTyVarEqErr dflags ctxt extra ct oriented tv1 ty2
  | Just tv2 <- tcGetTyVar_maybe ty2 = mkTyVarEqErr dflags ctxt extra ct swapped  tv2 ty1
654
  | otherwise                        = reportEqErr  ctxt extra ct oriented ty1 ty2
655 656
  where
    swapped = fmap flipSwap oriented
657

658
reportEqErr :: ReportErrCtxt -> SDoc
659
            -> Ct
660 661
            -> Maybe SwapFlag   -- Nothing <=> not sure
            -> TcType -> TcType -> TcM ErrMsg
662
reportEqErr ctxt extra1 ct oriented ty1 ty2
663 664
  = do { let extra2 = mkEqInfoMsg ct ty1 ty2
       ; mkErrorMsg ctxt ct (vcat [ misMatchOrCND ctxt ct oriented ty1 ty2
665
                                   , extra2, extra1]) }
666

667
mkTyVarEqErr :: DynFlags -> ReportErrCtxt -> SDoc -> Ct
668
             -> Maybe SwapFlag -> TcTyVar -> TcType -> TcM ErrMsg
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
669
-- tv1 and ty2 are already tidied
670 671
mkTyVarEqErr dflags ctxt extra ct oriented tv1 ty2
  | isUserSkolem ctxt tv1   -- ty2 won't be a meta-tyvar, or else the thing would
672 673
                            -- be oriented the other way round;
                            -- see TcCanonical.canEqTyVarTyVar
674
  || isSigTyVar tv1 && not (isTyVarTy ty2)
675
  = mkErrorMsg ctxt ct (vcat [ misMatchOrCND ctxt ct oriented ty1 ty2
676
                             , extraTyVarInfo ctxt tv1 ty2
677
                             , extra ])
678

679 680
  -- So tv is a meta tyvar (or started that way before we
  -- generalised it).  So presumably it is an *untouchable*
681
  -- meta tyvar or a SigTv, else it'd have been unified
682
  | not (k2 `tcIsSubKind` k1)            -- Kind error
683
  = mkErrorMsg ctxt ct $ (kindErrorMsg (mkTyVarTy tv1) ty2 $$ extra)
684

685
  | OC_Occurs <- occ_check_expand
686 687
  = do { let occCheckMsg = hang (text "Occurs check: cannot construct the infinite type:")
                              2 (sep [ppr ty1, char '~', ppr ty2])
688 689
             extra2 = mkEqInfoMsg ct ty1 ty2
       ; mkErrorMsg ctxt ct (occCheckMsg $$ extra2 $$ extra) }
Simon Peyton Jones's avatar
Simon Peyton Jones committed
690

691 692 693 694
  | OC_Forall <- occ_check_expand
  = do { let msg = vcat [ ptext (sLit "Cannot instantiate unification variable")
                          <+> quotes (ppr tv1)
                        , hang (ptext (sLit "with a type involving foralls:")) 2 (ppr ty2)
695
                        , nest 2 (ptext (sLit "Perhaps you want ImpredicativeTypes")) ]
696 697 698 699
       ; mkErrorMsg ctxt ct msg }

  -- If the immediately-enclosing implication has 'tv' a skolem, and
  -- we know by now its an InferSkol kind of skolem, then presumably
700 701
  -- it started life as a SigTv, else it'd have been unified, given
  -- that there's no occurs-check or forall problem
702 703 704 705
  | (implic:_) <- cec_encl ctxt
  , Implic { ic_skols = skols } <- implic
  , tv1 `elem` skols
  = mkErrorMsg ctxt ct (vcat [ misMatchMsg oriented ty1 ty2
706
                             , extraTyVarInfo ctxt tv1 ty2
707 708
                             , extra ])

709 710
  -- Check for skolem escape
  | (implic:_) <- cec_encl ctxt   -- Get the innermost context
711 712
  , Implic { ic_env = env, ic_skols = skols, ic_info = skol_info } <- implic
  , let esc_skols = filter (`elemVarSet` (tyVarsOfType ty2)) skols
713
  , not (null esc_skols)
714
  = do { let msg = misMatchMsg oriented ty1 ty2
715 716 717 718 719
             esc_doc = sep [ ptext (sLit "because type variable") <> plural esc_skols
                             <+> pprQuotedList esc_skols
                           , ptext (sLit "would escape") <+>
                             if isSingleton esc_skols then ptext (sLit "its scope")
                                                      else ptext (sLit "their scope") ]
720
             tv_extra = vcat [ nest 2 $ esc_doc
721
                             , sep [ (if isSingleton esc_skols
722 723 724 725 726 727
                                      then ptext (sLit "This (rigid, skolem) type variable is")
                                      else ptext (sLit "These (rigid, skolem) type variables are"))
                               <+> ptext (sLit "bound by")
                             , nest 2 $ ppr skol_info
                             , nest 2 $ ptext (sLit "at") <+> ppr (tcl_loc env) ] ]
       ; mkErrorMsg ctxt ct (msg $$ tv_extra $$ extra) }
728 729 730

  -- Nastiest case: attempt to unify an untouchable variable
  | (implic:_) <- cec_encl ctxt   -- Get the innermost context
731 732
  , Implic { ic_env = env, ic_given = given, ic_info = skol_info } <- implic
  = do { let msg = misMatchMsg oriented ty1 ty2
733
             untch_extra
734 735 736 737 738
                = nest 2 $
                  sep [ quotes (ppr tv1) <+> ptext (sLit "is untouchable")
                      , nest 2 $ ptext (sLit "inside the constraints") <+> pprEvVarTheta given
                      , nest 2 $ ptext (sLit "bound by") <+> ppr skol_info
                      , nest 2 $ ptext (sLit "at") <+> ppr (tcl_loc env) ]
739
             tv_extra = extraTyVarInfo ctxt tv1 ty2
740 741
             add_sig  = suggestAddSig ctxt ty1 ty2
       ; mkErrorMsg ctxt ct (vcat [msg, untch_extra, tv_extra, add_sig, extra]) }
742

743
  | otherwise
744
  = reportEqErr ctxt extra ct oriented (mkTyVarTy tv1) ty2
745 746
        -- This *can* happen (Trac #6123, and test T2627b)
        -- Consider an ambiguous top-level constraint (a ~ F a)
Gabor Greif's avatar
typos  
Gabor Greif committed
747
        -- Not an occurs check, because F is a type function.
748
  where
749
    occ_check_expand = occurCheckExpand dflags tv1 ty2
750 751
    k1  = tyVarKind tv1
    k2  = typeKind ty2
752
    ty1 = mkTyVarTy tv1
753

754
mkEqInfoMsg :: Ct -> TcType -> TcType -> SDoc
755
-- Report (a) ambiguity if either side is a type function application
756
--            e.g. F a0 ~ Int
757 758 759
--        (b) warning about injectivity if both sides are the same
--            type function application   F a ~ F b
--            See Note [Non-injective type functions]
760 761
mkEqInfoMsg ct ty1 ty2
  = tyfun_msg $$ ambig_msg
762 763 764
  where
    mb_fun1 = isTyFun_maybe ty1
    mb_fun2 = isTyFun_maybe ty2
765

766
    ambig_msg | isJust mb_fun1 || isJust mb_fun2
767 768 769
              = snd (mkAmbigMsg ct)
              | otherwise = empty

770 771
    tyfun_msg | Just tc1 <- mb_fun1
              , Just tc2 <- mb_fun2
772 773
              , tc1 == tc2
              = ptext (sLit "NB:") <+> quotes (ppr tc1)
774 775 776
                <+> ptext (sLit "is a type function, and may not be injective")
              | otherwise = empty

Simon Peyton Jones's avatar
Simon Peyton Jones committed
777 778 779 780 781 782 783 784 785 786 787
isUserSkolem :: ReportErrCtxt -> TcTyVar -> Bool
-- See Note [Reporting occurs-check errors]
isUserSkolem ctxt tv
  = isSkolemTyVar tv && any is_user_skol_tv (cec_encl ctxt)
  where
    is_user_skol_tv (Implic { ic_skols = sks, ic_info = skol_info })
      = tv `elem` sks && is_user_skol_info skol_info

    is_user_skol_info (InferSkol {}) = False
    is_user_skol_info _ = True

788
misMatchOrCND :: ReportErrCtxt -> Ct -> Maybe SwapFlag -> TcType -> TcType -> SDoc
Simon Peyton Jones's avatar
Simon Peyton Jones committed
789
-- If oriented then ty1 is actual, ty2 is expected
790
misMatchOrCND ctxt ct oriented ty1 ty2
791 792
  | null givens ||
    (isRigid ty1 && isRigid ty2) ||
793
    isGivenCt ct
794 795 796
       -- If the equality is unconditionally insoluble
       -- or there is no context, don't report the context
  = misMatchMsg oriented ty1 ty2
797
  | otherwise
798
  = couldNotDeduce givens ([mkTcEqPred ty1 ty2], orig)
799
  where
800 801
    givens = [ given | given@(_, _, no_eqs, _) <- getUserGivens ctxt, not no_eqs]
             -- Keep only UserGivens that have some equalities
Simon Peyton Jones's avatar
Simon Peyton Jones committed
802
    orig   = TypeEqOrigin { uo_actual = ty1, uo_expected = ty2 }
803

804
couldNotDeduce :: [UserGiven] -> (ThetaType, CtOrigin) -> SDoc
805
couldNotDeduce givens (wanteds, orig)
806
  = vcat [ addArising orig (ptext (sLit "Could not deduce") <+> pprTheta wanteds)
dimitris's avatar
dimitris committed
807 808
         , vcat (pp_givens givens)]

809
pp_givens :: [UserGiven] -> [SDoc]
810
pp_givens givens
dimitris's avatar
dimitris committed
811
   = case givens of
812 813 814
         []     -> []
         (g:gs) ->      ppr_given (ptext (sLit "from the context")) g
                 : map (ppr_given (ptext (sLit "or from"))) gs
815
    where
816
       ppr_given herald (gs, skol_info, _, loc)
dimitris's avatar
dimitris committed
817
           = hang (herald <+> pprEvVarTheta gs)
818 819
                2 (sep [ ptext (sLit "bound by") <+> ppr skol_info
                       , ptext (sLit "at") <+> ppr loc])
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
820

821
extraTyVarInfo :: ReportErrCtxt -> TcTyVar -> TcType -> SDoc
822
-- Add on extra info about skolem constants
823
-- NB: The types themselves are already tidied
824 825
extraTyVarInfo ctxt tv1 ty2
  = nest 2 (tv_extra tv1 $$ ty_extra ty2)
826
  where
827
    implics = cec_encl ctxt
828 829 830 831 832
    ty_extra ty = case tcGetTyVar_maybe ty of
                    Just tv -> tv_extra tv
                    Nothing -> empty

    tv_extra tv | isTcTyVar tv, isSkolemTyVar tv
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860
                , let pp_tv = quotes (ppr tv)
                = case tcTyVarDetails tv of
                    SkolemTv {}   -> pp_tv <+> pprSkol (getSkolemInfo implics tv) (getSrcLoc tv)
                    FlatSkol {}   -> pp_tv <+> ptext (sLit "is a flattening type variable")
                    RuntimeUnk {} -> pp_tv <+> ptext (sLit "is an interactive-debugger skolem")
                    MetaTv {}     -> empty

                | otherwise             -- Normal case
                = empty

suggestAddSig :: ReportErrCtxt -> TcType -> TcType -> SDoc
-- See Note [Suggest adding a type signature]
suggestAddSig ctxt ty1 ty2
  | null inferred_bndrs
  = empty
  | [bndr] <- inferred_bndrs
  = ptext (sLit "Possible fix: add a type signature for") <+> quotes (ppr bndr)
  | otherwise
  = ptext (sLit "Possible fix: add type signatures for some or all of") <+> (ppr inferred_bndrs)
  where
    inferred_bndrs = nub (get_inf ty1 ++ get_inf ty2)
    get_inf ty | Just tv <- tcGetTyVar_maybe ty
               , isTcTyVar tv, isSkolemTyVar tv
               , InferSkol prs <- getSkolemInfo (cec_encl ctxt) tv
               = map fst prs
               | otherwise
               = []

861 862 863 864 865 866 867 868 869
kindErrorMsg :: TcType -> TcType -> SDoc   -- Types are already tidy
kindErrorMsg ty1 ty2
  = vcat [ ptext (sLit "Kind incompatibility when matching types:")
         , nest 2 (vcat [ ppr ty1 <+> dcolon <+> ppr k1
                        , ppr ty2 <+> dcolon <+> ppr k2 ]) ]
  where
    k1 = typeKind ty1
    k2 = typeKind ty2

870
--------------------
871
misMatchMsg :: Maybe SwapFlag -> TcType -> TcType -> SDoc          -- Types are already tidy
872
-- If oriented then ty1 is actual, ty2 is expected
873
misMatchMsg oriented ty1 ty2
874 875 876
  | Just IsSwapped <- oriented
  = misMatchMsg (Just NotSwapped) ty2 ty1
  | Just NotSwapped <- oriented
877
  = sep [ ptext (sLit "Couldn't match expected") <+> what <+> quotes (ppr ty2)
878 879
        , nest 12 $   ptext (sLit "with actual") <+> what <+> quotes (ppr ty1)
        , sameOccExtra ty2 ty1 ]
880 881
  | otherwise
  = sep [ ptext (sLit "Couldn't match") <+> what <+> quotes (ppr ty1)
882 883 884
        , nest 14 $ ptext (sLit "with") <+> quotes (ppr ty2)
        , sameOccExtra ty1 ty2 ]
  where
885 886
    what | isKind ty1 = ptext (sLit "kind")
         | otherwise  = ptext (sLit "type")
887

888
mkExpectedActualMsg :: Type -> Type -> CtOrigin -> (Maybe SwapFlag, SDoc)
889
-- NotSwapped means (actual, expected), IsSwapped is the reverse