TcErrors.lhs 59.5 KB
Newer Older
1
\begin{code}
2
{-# LANGUAGE ScopedTypeVariables #-}
Ian Lynagh's avatar
Ian Lynagh committed
3 4 5 6
{-# OPTIONS -fno-warn-tabs #-}
-- The above warning supression flag is a temporary kludge.
-- While working on this module you are encouraged to remove it and
-- detab the module (please do the detabbing in a separate patch). See
7
--     http://ghc.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
Ian Lynagh's avatar
Ian Lynagh committed
8 9
-- for details

10
module TcErrors( 
11
       reportUnsolved, reportAllUnsolved,
12
       warnDefaulting,
13 14

       solverDepthErrorTcS
15 16 17 18
  ) where

#include "HsVersions.h"

19
import TcRnTypes
20 21 22
import TcRnMonad
import TcMType
import TcType
23
import TypeRep
batterseapower's avatar
batterseapower committed
24
import Type
25
import Kind ( isKind )
26
import Unify            ( tcMatchTys )
27
import Module
28 29 30
import Inst
import InstEnv
import TyCon
31
import DataCon
32
import TcEvidence
33
import TysWiredIn       ( coercibleClass )
34
import Name
35
import RdrName          ( lookupGRE_Name )
36
import Id 
37 38 39 40
import Var
import VarSet
import VarEnv
import Bag
41
import ErrUtils         ( ErrMsg, makeIntoWarning, pprLocErrMsg )
42
import BasicTypes 
43 44 45
import Util
import FastString
import Outputable
46
import SrcLoc
47
import DynFlags
48
import ListSetOps       ( equivClasses )
Icelandjack's avatar
Icelandjack committed
49 50

import Data.Maybe
51
import Data.List        ( partition, mapAccumL, zip4 )
52 53 54 55 56 57 58 59 60 61 62 63
\end{code}

%************************************************************************
%*									*
\section{Errors and contexts}
%*									*
%************************************************************************

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?

64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
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
83

84 85 86 87 88 89 90 91 92 93 94 95 96 97
  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
98
and does not fail if -fdefer-type-errors is on, so that we can continue
99 100 101 102 103 104
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
105
       ; defer <- goptM Opt_DeferTypeErrors
106 107 108 109 110 111
       ; 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
112
reportAllUnsolved wanted = report_unsolved Nothing False wanted
113 114 115 116

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

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

138 139 140
       ; traceTc "reportUnsolved (after unflattening):" $ 
         vcat [ pprTvBndrs (varSetElems free_tvs)
              , ppr wanted ]
141

142
       ; reportWanteds err_ctxt wanted }
143

144 145 146
--------------------------------------------
--      Internal functions
--------------------------------------------
147 148 149 150

data ReportErrCtxt 
    = CEC { cec_encl :: [Implication]  -- Enclosing implications
                	       	       --   (innermost first)
151
                                       -- ic_skols and givens are tidied, rest are not
152
          , cec_tidy  :: TidyEnv
153 154 155 156 157
          , cec_binds :: Maybe EvBindsVar 
                         -- 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
158

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

168 169 170 171 172 173 174 175 176 177 178 179 180
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.
  * If there are any insolubles (eg Int~Bool), here or in a nested implication, 
    then suppress errors from the flat constraints here.  Sometimes the
    flat-constraint errors are a knock-on effect of the insolubles.


\begin{code}
181 182 183
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
184
                                 , ic_insol = ic_insoluble, ic_info = info })
185
  | BracketSkol <- info
Simon Peyton Jones's avatar
Simon Peyton Jones committed
186 187 188 189
  , 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
190 191

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

reportWanteds :: ReportErrCtxt -> WantedConstraints -> TcM ()
206 207 208 209
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)
210 211 212 213
            -- All the Derived ones have been filtered out of flats 
            -- 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]
214 215 216 217 218 219
       ; 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
220 221
    env = cec_tidy ctxt

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

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

        -- Report equalities of form (a~ty).  They are usually
241
        -- skolem-equalities, and they cause confusing knock-on
242
        -- effects in other errors; see test T4093b.
243 244 245 246 247 248 249 250 251 252 253 254
      , ("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
255
  where
256 257 258 259
    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
260 261
    utterly_wrong _ _ = False

262 263
    is_hole ct _ = isHoleCt ct

264
    skolem_eq _ (EqPred ty1 ty2) = isRigidOrSkol ty1 && isRigidOrSkol ty2
265 266
    skolem_eq _ _ = False

267 268 269 270 271 272 273 274 275 276 277 278 279
    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


280 281
---------------
isRigid, isRigidOrSkol :: Type -> Bool
282
isRigid ty
283 284 285 286 287
  | Just (tc,_) <- tcSplitTyConApp_maybe ty = isDecomposableTyCon tc
  | Just {} <- tcSplitAppTy_maybe ty        = True
  | isForAllTy ty                           = True
  | otherwise                               = False

288
isRigidOrSkol ty
289 290 291 292 293 294 295 296
  | 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

297 298

--------------------------------------------
299
--      Reporters
300 301
--------------------------------------------

302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
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)
324 325 326

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

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

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

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

maybeAddDeferredBinding :: ReportErrCtxt -> ErrMsg -> Ct -> TcM ()
-- See Note [Deferring coercion errors to runtime]
maybeAddDeferredBinding ctxt err ct
365
  | CtWanted { ctev_pred = pred, ctev_evar = ev_id } <- ctEvidence ct
366 367
    -- Only add deferred bindings for Wanted constraints
  , isHoleCt ct || cec_defer ctxt  -- And it's a hole or we have -fdefer-type-errors
368
  , Just ev_binds_var <- cec_binds ctxt  -- We have somewhere to put the bindings
369 370 371 372 373 374 375 376 377
  = 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
378
  = return ()
379

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

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

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

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

432
type UserGiven = ([EvVar], SkolemInfo, SrcSpan)
433 434

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

443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
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
time. 

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


459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
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
        MkT :: C Int b => a -> b -> T a 
      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.)

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

  class C a b | a -> b
  g :: C a b => a -> b -> () 
  f :: C a b => a -> b -> () 
  f xa xb = 
      let loop = g xa 
      in loop xb

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


batterseapower's avatar
batterseapower committed
509 510 511 512 513 514 515
%************************************************************************
%*                  *
                Irreducible predicate errors
%*                  *
%************************************************************************

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

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

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

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


%************************************************************************
%*									*
                Equality errors
%*									*
%************************************************************************

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

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

  | otherwise   -- Wanted or derived
610
  = do { (ctxt, binds_msg) <- relevantBindings True ctxt ct
611
       ; (ctxt, tidy_orig) <- zonkTidyOrigin ctxt (ctLocOrigin loc)
612
       ; let (is_oriented, wanted_msg) = mk_wanted_extra tidy_orig
613 614
       ; dflags <- getDynFlags
       ; mkEqErr_help dflags ctxt (wanted_msg $$ binds_msg) 
615
                      ct is_oriented ty1 ty2 }
616
  where
617 618
    ev         = ctEvidence ct
    loc        = ctev_loc ev
619 620 621 622 623
    (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]
624 625
    mk_given []           = (loc, empty)
    mk_given (implic : _) = (setCtLocEnv loc (ic_env implic)
626 627
                            , hang (ptext (sLit "Inaccessible code in"))
                                 2 (ppr (ic_info implic)))
628

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

    mk_wanted_extra (KindEqOrigin cty1 cty2 sub_o)
      = (Nothing, msg1 $$ msg2)
636
      where
637 638 639 640 641 642 643 644
        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

    mk_wanted_extra _ = (Nothing, empty)
645

646 647 648 649 650 651 652
mkEqErr_help :: DynFlags -> ReportErrCtxt -> SDoc
             -> Ct          
             -> 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
653
  | otherwise                        = reportEqErr  ctxt extra ct oriented ty1 ty2
654 655
  where
    swapped = fmap flipSwap oriented
656

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

666 667
mkTyVarEqErr :: DynFlags -> ReportErrCtxt -> SDoc -> Ct 
             -> Maybe SwapFlag -> TcTyVar -> TcType -> TcM ErrMsg
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
668
-- tv1 and ty2 are already tidied
669 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
                            -- be oriented the other way round; see TcCanonical.reOrient
672
  || isSigTyVar tv1 && not (isTyVarTy ty2)
673 674 675
  = mkErrorMsg ctxt ct (vcat [ misMatchOrCND ctxt ct oriented ty1 ty2
                             , extraTyVarInfo ctxt ty1 ty2
                             , extra ])
676

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

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

689 690 691 692
  | 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)
693
                        , nest 2 (ptext (sLit "Perhaps you want ImpredicativeTypes")) ]
694 695 696 697
       ; 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
698 699
  -- it started life as a SigTv, else it'd have been unified, given
  -- that there's no occurs-check or forall problem
700 701 702 703 704 705 706
  | (implic:_) <- cec_encl ctxt
  , Implic { ic_skols = skols } <- implic
  , tv1 `elem` skols
  = mkErrorMsg ctxt ct (vcat [ misMatchMsg oriented ty1 ty2
                             , extraTyVarInfo ctxt ty1 ty2
                             , extra ])

707 708
  -- Check for skolem escape
  | (implic:_) <- cec_encl ctxt   -- Get the innermost context
709 710
  , Implic { ic_env = env, ic_skols = skols, ic_info = skol_info } <- implic
  , let esc_skols = filter (`elemVarSet` (tyVarsOfType ty2)) skols
711
  , not (null esc_skols)
712
  = do { let msg = misMatchMsg oriented ty1 ty2
713 714 715 716 717
             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") ]
718 719 720 721 722 723 724 725
             tv_extra = vcat [ nest 2 $ esc_doc
                             , sep [ (if isSingleton esc_skols 
                                      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) }
726 727 728

  -- Nastiest case: attempt to unify an untouchable variable
  | (implic:_) <- cec_encl ctxt   -- Get the innermost context
729 730 731 732 733 734 735 736 737 738
  , Implic { ic_env = env, ic_given = given, ic_info = skol_info } <- implic
  = do { let msg = misMatchMsg oriented ty1 ty2
             untch_extra 
                = 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) ]
             tv_extra = extraTyVarInfo ctxt ty1 ty2
       ; mkErrorMsg ctxt ct (vcat [msg, untch_extra, tv_extra, extra]) }
739

740
  | otherwise
741
  = reportEqErr ctxt extra ct oriented (mkTyVarTy tv1) ty2
742 743
        -- 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
744
        -- Not an occurs check, because F is a type function.
745
  where         
746
    occ_check_expand = occurCheckExpand dflags tv1 ty2
747 748 749
    k1 	= tyVarKind tv1
    k2 	= typeKind ty2
    ty1 = mkTyVarTy tv1
750

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

    ambig_msg | isJust mb_fun1 || isJust mb_fun2 
              = snd (mkAmbigMsg ct)
              | otherwise = empty

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
774 775 776 777 778 779 780 781 782 783 784
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

785
misMatchOrCND :: ReportErrCtxt -> Ct -> Maybe SwapFlag -> TcType -> TcType -> SDoc
Simon Peyton Jones's avatar
Simon Peyton Jones committed
786
-- If oriented then ty1 is actual, ty2 is expected
787 788 789
misMatchOrCND ctxt ct oriented ty1 ty2
  | null givens || 
    (isRigid ty1 && isRigid ty2) || 
790
    isGivenCt ct
791 792 793 794
       -- If the equality is unconditionally insoluble
       -- or there is no context, don't report the context
  = misMatchMsg oriented ty1 ty2
  | otherwise      
795
  = couldNotDeduce givens ([mkEqPred ty1 ty2], orig)
796 797
  where
    givens = getUserGivens ctxt
Simon Peyton Jones's avatar
Simon Peyton Jones committed
798
    orig   = TypeEqOrigin { uo_actual = ty1, uo_expected = ty2 }
799

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

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

817
extraTyVarInfo :: ReportErrCtxt -> TcType -> TcType -> SDoc
818 819
-- Add on extra info about the types themselves
-- NB: The types themselves are already tidied
820 821
extraTyVarInfo ctxt ty1 ty2
  = nest 2 (extra1 $$ extra2)
822
  where
823 824
    extra1 = tyVarExtraInfoMsg (cec_encl ctxt) ty1
    extra2 = tyVarExtraInfoMsg (cec_encl ctxt) ty2
825

826
tyVarExtraInfoMsg :: [Implication] -> Type -> SDoc
827
-- Shows a bit of extra info about skolem constants
828
tyVarExtraInfoMsg implics ty
829
  | Just tv <- tcGetTyVar_maybe ty
Simon Peyton Jones's avatar
Simon Peyton Jones committed
830 831 832
  , isTcTyVar tv, isSkolemTyVar tv
  , let pp_tv = quotes (ppr tv)
 = case tcTyVarDetails tv of
833
    SkolemTv {}   -> pp_tv <+> pprSkol (getSkolemInfo implics tv) (getSrcLoc tv)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
834 835 836 837 838 839 840
    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
 
841 842 843 844 845 846 847 848 849
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

850
--------------------
851
misMatchMsg :: Maybe SwapFlag -> TcType -> TcType -> SDoc	   -- Types are already tidy
852
-- If oriented then ty1 is actual, ty2 is expected
853
misMatchMsg oriented ty1 ty2
854 855 856
  | Just IsSwapped <- oriented
  = misMatchMsg (Just NotSwapped) ty2 ty1
  | Just NotSwapped <- oriented
857
  = sep [ ptext (sLit "Couldn't match expected") <+> what <+> quotes (ppr ty2)
858 859
        , nest 12 $   ptext (sLit "with actual") <+> what <+> quotes (ppr ty1)
        , sameOccExtra ty2 ty1 ]
860 861
  | otherwise
  = sep [ ptext (sLit "Couldn't match") <+> what <+> quotes (ppr ty1)
862 863 864
        , nest 14 $ ptext (sLit "with") <+> quotes (ppr ty2)
        , sameOccExtra ty1 ty2 ]
  where
865 866
    what | isKind ty1 = ptext (sLit "kind")
         | otherwise  = ptext (sLit "type")
867

868
mkExpectedActualMsg :: Type -> Type -> CtOrigin -> (Maybe SwapFlag, SDoc)
869
-- NotSwapped means (actual, expected), IsSwapped is the reverse
870
mkExpectedActualMsg ty1 ty2 (TypeEqOrigin { uo_actual = act, uo_expected = exp })
871 872
  | act `pickyEqType` ty1, exp `pickyEqType` ty2 = (Just NotSwapped,  empty)
  | exp `pickyEqType` ty1, act `pickyEqType` ty2 = (Just IsSwapped, empty)
873 874 875 876 877 878
  | otherwise                                    = (Nothing, msg)
  where
    msg = vcat [ text "Expected type:" <+> ppr exp
               , text "  Actual type:" <+> ppr act ]

mkExpectedActualMsg _ _ _ = panic "mkExprectedAcutalMsg"
879 880

sameOccExtra :: TcType -> TcType -> SDoc
881
-- See Note [Disambiguating (X ~ X) errors]
882 883 884 885 886 887 888 889 890 891 892 893 894 895
sameOccExtra ty1 ty2
  | Just (tc1, _) <- tcSplitTyConApp_maybe ty1
  , Just (tc2, _) <- tcSplitTyConApp_maybe ty2
  , let n1 = tyConName tc1
        n2 = tyConName tc2
        same_occ = nameOccName n1                  == nameOccName n2
        same_pkg = modulePackageId (nameModule n1) == modulePackageId (nameModule n2)
  , n1 /= n2   -- Different Names
  , same_occ   -- but same OccName
  = ptext (sLit "NB:") <+> (ppr_from same_pkg n1 $$ ppr_from same_pkg n2)
  | otherwise
  = empty
  where
    ppr_from same_pkg nm
896 897 898 899
      | isGoodSrcSpan loc
      = hang (quotes (ppr nm) <+> ptext (sLit "is defined at"))
           2 (ppr loc)
      | otherwise  -- Imported things have an UnhelpfulSrcSpan
900 901 902 903 904 905 906
      = hang (quotes (ppr nm))
           2 (sep [ ptext (sLit "is defined in") <+> quotes (ppr (moduleName mod))
                  , ppUnless (same_pkg || pkg == mainPackageId) $
                    nest 4 $ ptext (sLit "in package") <+> quotes (ppr pkg) ])
       where
         pkg = modulePackageId mod
         mod = nameModule nm
907
         loc = nameSrcSpan nm
908 909
\end{code}

910 911 912 913
Note [Disambiguating (X ~ X) errors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
See Trac #8278

Simon Peyton Jones's avatar
Simon Peyton Jones committed
914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931
Note [Reporting occurs-check errors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Given (a ~ [a]), if 'a' is a rigid type variable bound by a user-supplied
type signature, then the best thing is to report that we can't unify
a with [a], because a is a skolem variable.  That avoids the confusing
"occur-check" error message.

But nowadays when inferring the type of a function with no type signature,
even if there are errors inside, we still generalise its signature and
carry on. For example
   f x = x:x
Here we will infer somethiing like
   f :: forall a. a -> [a]
with a suspended error of (a ~ [a]).  So 'a' is now a skolem, but not
one bound by the programmer!  Here we really should report an occurs check.

So isUserSkolem distinguishes the two.

932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
Note [Non-injective type functions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It's very confusing to get a message like
     Couldn't match expected type `Depend s'
            against inferred type `Depend s1'
so mkTyFunInfoMsg adds:
       NB: `Depend' is type function, and hence may not be injective

Warn of loopy local equalities that were dropped.


%************************************************************************
%*									*
                 Type-class errors
%*									*
%************************************************************************

\begin{code}
950 951
mkDictErr :: ReportErrCtxt -> [Ct] -> TcM ErrMsg
mkDictErr ctxt cts 
952 953 954 955 956 957 958
  = ASSERT( not (null cts) )
    do { inst_envs <- tcGetInstEnvs
       ; lookups   <- mapM (lookup_cls_inst inst_envs) cts
       ; let (no_inst_cts, overlap_cts) = partition is_no_inst lookups

       -- Report definite no-instance errors, 
       -- or (iff there are none) overlap errors
Gabor Greif's avatar
typos  
Gabor Greif committed
959
       -- But we report only one of them (hence 'head') because they all
960 961
       -- have the same source-location origin, to try avoid a cascade
       -- of error from one location
962
       ; (ctxt, err) <- mk_dict_err ctxt (head (no_inst_cts ++ overlap_cts))
963
       ; mkErrorMsg ctxt ct1 err }
964
  where
965 966
    ct1:_ = elim_superclasses cts

967
    no_givens = null (getUserGivens ctxt)
968

969
    is_no_inst (ct, (matches, unifiers, _))
970 971
      =  no_givens
      && null matches
972
      && (null unifiers || all (not . isAmbiguousTyVar) (varSetElems (tyVarsOfCt ct)))
973

974 975 976 977
    lookup_cls_inst inst_envs ct
      = do { tys_flat <- mapM quickFlattenTy tys
                -- Note [Flattening in error message generation]
           ; return (ct, lookupInstEnv inst_envs clas tys_flat) }
978
      where
979
        (clas, tys) = getClassPredTys (ctPred ct)
980

981 982 983 984 985 986 987 988 989

    -- When simplifying [W] Ord (Set a), we need
    --    [W] Eq a, [W] Ord a
    -- but we really only want to report the latter
    elim_superclasses cts
      = filter (\ct -> any (eqPred (ctPred ct)) min_preds) cts
      where
        min_preds = mkMinimalBySCs (map ctPred cts)

990
mk_dict_err :: ReportErrCtxt -> (Ct, ClsInstLookupResult)
991
            -> TcM (ReportErrCtxt, SDoc)
992 993 994 995
-- Report an overlap error if this class constraint results
-- from an overlap (returning Left clas), otherwise return (Right pred)
mk_dict_err ctxt (ct, (matches, unifiers, safe_haskell)) 
  | null matches  -- No matches but perhaps several unifiers
996
  = do { let (is_ambig, ambig_msg) = mkAmbigMsg ct
997
       ; (ctxt, binds_msg) <- relevantBindings True ctxt ct
Simon Peyton Jones's avatar
Simon Peyton Jones committed
998
       ; traceTc "mk_dict_err" (ppr ct $$ ppr is_ambig $$ ambig_msg)
999 1000 1001