TcErrors.lhs 49.8 KB
Newer Older
1
\begin{code}
2
{-# LANGUAGE ScopedTypeVariables #-}
Ian Lynagh's avatar
Ian Lynagh committed
3 4 5 6 7 8 9
{-# 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
--     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
-- for details

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

       solverDepthErrorTcS
15 16 17 18
  ) where

#include "HsVersions.h"

19
import TcCanonical( occurCheckExpand )
20
import TcRnTypes
21 22 23
import TcRnMonad
import TcMType
import TcType
24
import TypeRep
batterseapower's avatar
batterseapower committed
25
import Type
26
import Kind ( isKind )
27
import Unify            ( tcMatchTys )
28 29 30
import Inst
import InstEnv
import TyCon
31
import TcEvidence
32
import Name
33
import Id 
34 35 36 37
import Var
import VarSet
import VarEnv
import Bag
38 39
import Maybes
import ErrUtils         ( ErrMsg, makeIntoWarning, pprLocErrMsg )
40
import BasicTypes 
41 42 43
import Util
import FastString
import Outputable
44
import SrcLoc
45
import DynFlags
46
import Data.List        ( partition, mapAccumL )
47 48 49 50 51 52 53 54 55 56 57 58
\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?

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

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

\begin{code}
reportUnsolved :: WantedConstraints -> TcM (Bag EvBind)
reportUnsolved wanted
  = do { binds_var <- newTcEvBinds
       ; defer <- doptM Opt_DeferTypeErrors
       ; 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
107
reportAllUnsolved wanted = report_unsolved Nothing False wanted
108 109 110 111

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

121
       ; env0 <- tcInitTidyEnv
122 123 124
                 
            -- If we are deferring we are going to need /all/ evidence around,
            -- including the evidence produced by unflattening (zonkWC)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
125
--       ; errs_so_far <- ifErrsM (return True) (return False)
126
       ; let tidy_env = tidyFreeTyVars env0 free_tvs
127
             free_tvs = tyVarsOfWC wanted
128
             err_ctxt = CEC { cec_encl  = []
Simon Peyton Jones's avatar
Simon Peyton Jones committed
129 130
                            , cec_insol = False
                                          --errs_so_far || insolubleWC wanted
131 132 133
                                          -- Don't report ambiguity errors if
                                          -- there are any other solid errors 
                                          -- to report
134
                            , cec_tidy  = tidy_env
135 136 137
                            , cec_defer    = defer
                            , cec_suppress = False
                            , cec_binds    = mb_binds_var }
138

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

143
       ; reportWanteds err_ctxt wanted }
144

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

data ReportErrCtxt 
    = CEC { cec_encl :: [Implication]  -- Enclosing implications
                	       	       --   (innermost first)
152
                                       -- ic_skols and givens are tidied, rest are not
153
          , cec_tidy  :: TidyEnv
154 155
          , cec_insol :: Bool       -- True <=> do not report errors involving 
                                    --          ambiguous errors
156 157 158 159 160 161

          , 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
162

163 164
          , cec_defer :: Bool       -- True <=> -fdefer-type-errors
                                    -- Irrelevant if cec_binds = Nothing
165 166 167
          , cec_suppress :: Bool    -- True <=> More important errors have occurred,
                                    --          so create bindings if need be, but
                                    --          don't issue any more errors/warnings
168 169
      }

170 171 172
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
173
                                 , ic_insol = ic_insoluble, ic_info = info })
174
  | BracketSkol <- info
Simon Peyton Jones's avatar
Simon Peyton Jones committed
175 176 177 178
  , 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
179 180

  | otherwise
181
  = reportWanteds ctxt' wanted
182
  where
183
    (env1, tvs') = mapAccumL tidyTyVarBndr (cec_tidy ctxt) tvs
184
    (env2, info') = tidySkolemInfo env1 info
185
    implic' = implic { ic_skols = tvs'
186 187
                     , ic_given = map (tidyEvVar env2) given
                     , ic_info  = info' }
Simon Peyton Jones's avatar
Simon Peyton Jones committed
188 189 190
    insoluble' = case info of
                   InferSkol {} -> ic_insoluble
                   _            -> cec_insol ctxt    
191
    ctxt' = ctxt { cec_tidy  = env2
192
                 , cec_encl  = implic' : cec_encl ctxt
Simon Peyton Jones's avatar
Simon Peyton Jones committed
193
                 , cec_insol = insoluble'
194
                 , cec_binds = case cec_binds ctxt of
195 196 197 198 199
                                 Nothing -> Nothing
                                 Just {} -> Just evb }

reportWanteds :: ReportErrCtxt -> WantedConstraints -> TcM ()
reportWanteds ctxt (WC { wc_flat = flats, wc_insol = insols, wc_impl = implics })
200
  = do { reportFlats ctxt tidy_cts
201
       ; mapBagM_ (reportImplic ctxt) implics }
202
  where
203
    env = cec_tidy ctxt
204
    tidy_cts = mapBag (tidyCt env) (insols `unionBags` flats)
205 206 207
                  -- All the Derived ones have been filtered out alrady
                  -- by the constraint solver. This is ok; we don't want
                  -- to report unsolved Derived goals as error
208
                  -- See Note [Do not report derived but soluble errors]
209

210 211
reportFlats :: ReportErrCtxt -> Cts -> TcM ()
reportFlats ctxt flats    -- Here 'flats' includes insolble goals
Simon Peyton Jones's avatar
Simon Peyton Jones committed
212 213
  = traceTc "reportFlats" (ppr flats) >>
    tryReporters 
214 215 216
      [ -- First deal with things that are utterly wrong
        -- Like Int ~ Bool (incl nullary TyCons)
        -- or  Int ~ t a   (AppTy on one side)
217 218
        ("Utterly wrong",  utterly_wrong,   mkGroupReporter mkEqErr)
      , ("Holes",          is_hole,         mkUniReporter mkHoleError)
219 220 221 222

        -- Report equalities of form (a~ty).  They are usually
        -- skolem-equalities, and they cause confusing knock-on 
        -- effects in other errors; see test T4093b.
Simon Peyton Jones's avatar
Simon Peyton Jones committed
223 224 225
      , ("Skolem equalities",    skolem_eq,   mkUniReporter mkEqErr1) ]
--      , ("Unambiguous",          unambiguous, reportFlatErrs) ]
      reportFlatErrs
226
      ctxt (bagToList flats)
227
  where
Simon Peyton Jones's avatar
Simon Peyton Jones committed
228
    utterly_wrong, skolem_eq :: Ct -> PredTree -> Bool
229 230 231
    utterly_wrong _ (EqPred ty1 ty2) = isRigid ty1 && isRigid ty2 
    utterly_wrong _ _ = False

232 233
    is_hole ct _ = isHoleCt ct

234 235 236
    skolem_eq _ (EqPred ty1 ty2) = isRigidOrSkol ty1 && isRigidOrSkol ty2 
    skolem_eq _ _ = False

Simon Peyton Jones's avatar
Simon Peyton Jones committed
237 238
{-
    unambiguous :: Ct -> PredTree -> Bool
239 240 241 242 243 244 245
    unambiguous ct pred 
      | not (any isAmbiguousTyVar (varSetElems (tyVarsOfCt ct)))
      = True
      | otherwise 
      = case pred of
          EqPred ty1 ty2 -> isNothing (isTyFun_maybe ty1) && isNothing (isTyFun_maybe ty2)
          _              -> False
Simon Peyton Jones's avatar
Simon Peyton Jones committed
246
-}
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265

---------------
isRigid, isRigidOrSkol :: Type -> Bool
isRigid ty 
  | Just (tc,_) <- tcSplitTyConApp_maybe ty = isDecomposableTyCon tc
  | Just {} <- tcSplitAppTy_maybe ty        = True
  | isForAllTy ty                           = True
  | otherwise                               = False

isRigidOrSkol ty 
  | 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

-----------------
Simon Peyton Jones's avatar
Simon Peyton Jones committed
266
{-
267
reportAmbigErrs :: Reporter
268 269 270 271 272
reportAmbigErrs ctxt cts
  | cec_insol ctxt = return ()
  | otherwise      = reportFlatErrs ctxt cts
          -- Only report ambiguity if no other errors (at all) happened
          -- See Note [Avoiding spurious errors] in TcSimplify
Simon Peyton Jones's avatar
Simon Peyton Jones committed
273
-}
274
reportFlatErrs :: Reporter
275 276 277 278
-- Called once for non-ambigs, once for ambigs
-- Report equality errors, and others only if we've done all 
-- the equalities.  The equality errors are more basic, and
-- can lead to knock on type-class errors
279
reportFlatErrs
280
  = tryReporters
281
      [ ("Equalities", is_equality, mkGroupReporter mkEqErr) ]
Simon Peyton Jones's avatar
Simon Peyton Jones committed
282 283 284 285 286 287
      (\ctxt cts -> do { let ctxt' | cec_insol ctxt = ctxt { cec_suppress = True }
                                   | otherwise      = ctxt
                       ; let (dicts, ips, irreds) = go cts [] [] []
                       ; mkGroupReporter mkIPErr    ctxt' ips   
                       ; mkGroupReporter mkIrredErr ctxt' irreds
                       ; mkGroupReporter mkDictErr  ctxt' dicts })
288
  where
289 290 291 292 293 294
    is_equality _ (EqPred {}) = True
    is_equality _ _           = False

    go [] dicts ips irreds
      = (dicts, ips, irreds)
    go (ct:cts) dicts ips irreds
Simon Peyton Jones's avatar
Simon Peyton Jones committed
295 296
      | isIPPred (ctPred ct) 
      = go cts dicts (ct:ips) irreds
297
      | otherwise
298 299 300
      = case classifyPredType (ctPred ct) of
          ClassPred {}  -> go cts (ct:dicts) ips irreds
          IrredPred {}  -> go cts dicts ips (ct:irreds)
301
          _             -> panic "reportFlatErrs"
batterseapower's avatar
batterseapower committed
302 303
    -- TuplePreds should have been expanded away by the constraint
    -- simplifier, so they shouldn't show up at this point
304 305
    -- And EqPreds are dealt with by the is_equality test

306 307

--------------------------------------------
308
--      Reporters
309 310
--------------------------------------------

311 312 313 314 315 316
type Reporter = ReportErrCtxt -> [Ct] -> TcM ()

mkUniReporter :: (ReportErrCtxt -> Ct -> TcM ErrMsg) -> Reporter
-- Reports errors one at a time
mkUniReporter mk_err ctxt 
  = mapM_ $ \ct -> 
317 318 319
    do { err <- mk_err ctxt ct
       ; maybeReportError ctxt err ct
       ; maybeAddDeferredBinding ctxt err ct }
320 321 322 323

mkGroupReporter :: (ReportErrCtxt -> [Ct] -> TcM ErrMsg)
                             -- Make error message for a group
                -> Reporter  -- Deal with lots of constraints
324
-- Group together insts from same location
325 326
-- We want to report them together in error messages

327
mkGroupReporter _ _ [] 
328
  = return ()
329
mkGroupReporter mk_err ctxt (ct1 : rest)
330 331 332 333
  = do { err <- mk_err ctxt cts
       ; maybeReportError ctxt err ct1
       ; mapM_ (maybeAddDeferredBinding ctxt err) (ct1:rest)
               -- Add deferred bindings for all
334
       ; mkGroupReporter mk_err ctxt others }
335
  where
336
   loc               = cc_loc ct1
337 338
   cts               = ct1 : friends
   (friends, others) = partition is_friend rest
339
   is_friend friend  = cc_loc friend `same_loc` loc
340

341
   same_loc :: CtLoc -> CtLoc -> Bool
342 343
   same_loc l1 l2 = ctLocSpan l1 == ctLocSpan l2

344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
maybeReportError :: ReportErrCtxt -> ErrMsg -> Ct -> TcM ()
-- Report the error and/or make a deferred binding for it
maybeReportError ctxt err ct
  | cec_suppress ctxt
  = return ()
  | isHoleCt ct || cec_defer ctxt  -- And it's a hole or we have -fdefer-type-errors
  = reportWarning (makeIntoWarning err)
  | otherwise
  = reportError err

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

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

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

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

418 419 420 421 422
mkErrorMsg :: ReportErrCtxt -> Ct -> SDoc -> TcM ErrMsg
mkErrorMsg ctxt ct msg 
  = do { let tcl_env = ctLocEnv (cc_loc ct)
       ; err_info <- mkErrInfo (cec_tidy ctxt) (tcl_ctxt tcl_env)
       ; mkLongErrAt (tcl_loc tcl_env) msg err_info }
423

424
type UserGiven = ([EvVar], SkolemInfo, SrcSpan)
425 426

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

435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 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
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
485 486 487 488 489 490 491
%************************************************************************
%*                  *
                Irreducible predicate errors
%*                  *
%************************************************************************

\begin{code}
492 493
mkIrredErr :: ReportErrCtxt -> [Ct] -> TcM ErrMsg
mkIrredErr ctxt cts 
494 495
  = do { (ctxt, binds_msg) <- relevantBindings ctxt ct1
       ; mkErrorMsg ctxt ct1 (msg $$ binds_msg) }
batterseapower's avatar
batterseapower committed
496
  where
497
    (ct1:_) = cts
498
    orig    = ctLocOrigin (cc_loc ct1)
499 500
    givens  = getUserGivens ctxt
    msg = couldNotDeduce givens (map ctPred cts, orig)
batterseapower's avatar
batterseapower committed
501

502
----------------
503 504
mkHoleError :: ReportErrCtxt -> Ct -> TcM ErrMsg
mkHoleError ctxt ct@(CHoleCan {})
505 506 507
  = do { let tyvars = varSetElems (tyVarsOfCt ct)
             tyvars_msg = map loc_msg tyvars
             msg = (text "Found hole" <+> quotes (text "_") 
508
                    <+> text "with type") <+> pprType (ctEvPred (cc_ev ct))
509
                   $$ (if null tyvars_msg then empty else text "Where:" <+> vcat tyvars_msg)
510 511
       ; (ctxt, binds_doc) <- relevantBindings ctxt ct
       ; mkErrorMsg ctxt ct (msg $$ binds_doc) }
512
  where
513 514 515 516 517 518 519
    loc_msg tv 
       = case tcTyVarDetails tv of
          SkolemTv {} -> quotes (ppr tv) <+> skol_msg
          MetaTv {}   -> quotes (ppr tv) <+> text "is a free type variable"
          det -> pprTcTyVarDetails det
       where 
          skol_msg = pprSkol (getSkolemInfo (cec_encl ctxt) tv) (getSrcLoc tv)
520 521

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

523
----------------
524 525
mkIPErr :: ReportErrCtxt -> [Ct] -> TcM ErrMsg
mkIPErr ctxt cts
526 527 528
  = do { (ctxt, _, ambig_err) <- mkAmbigMsg ctxt cts
       ; (ctxt, bind_msg) <- relevantBindings ctxt ct1
       ; mkErrorMsg ctxt ct1 (msg $$ ambig_err $$ bind_msg) }
529
  where
530
    (ct1:_) = cts
531
    orig    = ctLocOrigin (cc_loc ct1)
532 533
    preds   = map ctPred cts
    givens  = getUserGivens ctxt
534 535
    msg | null givens
        = addArising orig $
536 537
          sep [ ptext (sLit "Unbound implicit parameter") <> plural cts
              , nest 2 (pprTheta preds) ] 
538
        | otherwise
539
        = couldNotDeduce givens (preds, orig)
540 541 542 543 544 545 546 547 548 549
\end{code}


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

\begin{code}
550 551 552 553 554 555 556 557 558
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
559 560 561 562 563 564
  = do { (ctxt, binds_msg) <- relevantBindings ctxt ct
       ; (ctxt, orig) <- zonkTidyOrigin ctxt orig
       ; if isGiven ev then 
           mkEqErr_help ctxt (inaccessible_msg orig $$ binds_msg) ct False ty1 ty2
         else
           mk_err binds_msg orig }
565
  where
566 567
    ev         = cc_ev ct
    orig       = ctLocOrigin (cc_loc ct)
dimitris's avatar
dimitris committed
568
    (ty1, ty2) = getEqPredTys (ctPred ct)
569

570 571 572
    inaccessible_msg orig = hang (ptext (sLit "Inaccessible code in"))
                               2 (ppr orig)

573 574
       -- If the types in the error message are the same as the types
       -- we are unifying, don't add the extra expected/actual message
575
    mk_err extra (TypeEqOrigin (UnifyOrigin { uo_actual = act, uo_expected = exp })) 
576
      | act `pickyEqType` ty1
577
      , exp `pickyEqType` ty2 = mkEqErr_help ctxt extra  ct True  ty2 ty1
578
      | exp `pickyEqType` ty1
579 580
      , act `pickyEqType` ty2 = mkEqErr_help ctxt extra  ct True  ty1 ty2
      | otherwise             = mkEqErr_help ctxt extra1 ct False ty1 ty2
581
      where
582 583 584
        extra1 = msg $$ extra
        msg    = mkExpectedActualMsg exp act
    mk_err extra _ = mkEqErr_help ctxt extra ct False ty1 ty2
585

586
mkEqErr_help, reportEqErr 
587
   :: ReportErrCtxt -> SDoc
588 589 590 591 592 593
   -> Ct
   -> Bool     -- True  <=> Types are correct way round;
               --           report "expected ty1, actual ty2"
               -- False <=> Just report a mismatch without orientation
               --           The ReportErrCtxt has expected/actual 
   -> TcType -> TcType -> TcM ErrMsg
594 595 596 597
mkEqErr_help ctxt extra ct oriented ty1 ty2
  | Just tv1 <- tcGetTyVar_maybe ty1 = mkTyVarEqErr ctxt extra ct oriented tv1 ty2
  | Just tv2 <- tcGetTyVar_maybe ty2 = mkTyVarEqErr ctxt extra ct oriented tv2 ty1
  | otherwise                        = reportEqErr  ctxt extra ct oriented ty1 ty2
598

599 600 601 602
reportEqErr ctxt extra1 ct oriented ty1 ty2
  = do { (ctxt', extra2) <- mkEqInfoMsg ctxt ct ty1 ty2
       ; mkErrorMsg ctxt' ct (vcat [ misMatchOrCND ctxt' ct oriented ty1 ty2
                                   , extra2, extra1]) }
603

604
mkTyVarEqErr :: ReportErrCtxt -> SDoc -> Ct -> Bool -> TcTyVar -> TcType -> TcM ErrMsg
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
605
-- tv1 and ty2 are already tidied
606
mkTyVarEqErr ctxt extra ct oriented tv1 ty2
607
  -- Occurs check
Simon Peyton Jones's avatar
Simon Peyton Jones committed
608 609
  |  isUserSkolem ctxt tv1   -- ty2 won't be a meta-tyvar, or else the thing would
     		   	     -- be oriented the other way round; see TcCanonical.reOrient
610
  || isSigTyVar tv1 && not (isTyVarTy ty2)
611 612 613
  = mkErrorMsg ctxt ct (vcat [ misMatchOrCND ctxt ct oriented ty1 ty2
                             , extraTyVarInfo ctxt ty1 ty2
                             , extra ])
614 615 616

  -- So tv is a meta tyvar, and presumably it is
  -- an *untouchable* meta tyvar, else it'd have been unified
617
  | not (k2 `tcIsSubKind` k1)   	 -- Kind error
618
  = mkErrorMsg ctxt ct $ (kindErrorMsg (mkTyVarTy tv1) ty2 $$ extra)
619

Simon Peyton Jones's avatar
Simon Peyton Jones committed
620 621 622 623 624
  | isNothing (occurCheckExpand tv1 ty2)
  = let occCheckMsg = hang (text "Occurs check: cannot construct the infinite type:") 2
                           (sep [ppr ty1, char '~', ppr ty2])
    in mkErrorMsg ctxt ct (occCheckMsg $$ extra)

625 626
  -- Check for skolem escape
  | (implic:_) <- cec_encl ctxt   -- Get the innermost context
627 628
  , Implic { ic_env = env, ic_skols = skols, ic_info = skol_info } <- implic
  , let esc_skols = filter (`elemVarSet` (tyVarsOfType ty2)) skols
629
  , not (null esc_skols)
630
  = do { let msg = misMatchMsg oriented ty1 ty2
631 632 633 634 635
             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") ]
636 637 638 639 640 641 642 643
             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) }
644 645 646

  -- Nastiest case: attempt to unify an untouchable variable
  | (implic:_) <- cec_encl ctxt   -- Get the innermost context
647 648 649 650 651 652 653 654 655 656
  , 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]) }
657

658
  | otherwise
659
  = reportEqErr ctxt extra ct oriented (mkTyVarTy tv1) ty2
660 661 662
        -- This *can* happen (Trac #6123, and test T2627b)
        -- Consider an ambiguous top-level constraint (a ~ F a)
        -- Not an occurs check, becuase F is a type function.
663
  where         
664 665 666
    k1 	= tyVarKind tv1
    k2 	= typeKind ty2
    ty1 = mkTyVarTy tv1
667

668
mkEqInfoMsg :: ReportErrCtxt -> Ct -> TcType -> TcType -> TcM (ReportErrCtxt, SDoc)
669 670 671 672 673 674 675 676 677
-- 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]
mkEqInfoMsg ctxt ct ty1 ty2
  = do { (ctxt', _, ambig_msg) <- if isJust mb_fun1 || isJust mb_fun2
                                  then mkAmbigMsg ctxt [ct]
                                  else return (ctxt, False, empty)
678
       ; return (ctxt', tyfun_msg $$ ambig_msg) }
679 680 681 682 683 684 685 686 687 688
  where
    mb_fun1 = isTyFun_maybe ty1
    mb_fun2 = isTyFun_maybe ty2
    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
689 690 691 692 693 694 695 696 697 698 699
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

700 701 702 703 704
misMatchOrCND :: ReportErrCtxt -> Ct -> Bool -> TcType -> TcType -> SDoc
-- If oriented then ty1 is expected, ty2 is actual
misMatchOrCND ctxt ct oriented ty1 ty2
  | null givens || 
    (isRigid ty1 && isRigid ty2) || 
705
    isGivenCt ct
706 707 708 709
       -- If the equality is unconditionally insoluble
       -- or there is no context, don't report the context
  = misMatchMsg oriented ty1 ty2
  | otherwise      
710
  = couldNotDeduce givens ([mkEqPred ty1 ty2], orig)
711 712 713 714
  where
    givens = getUserGivens ctxt
    orig   = TypeEqOrigin (UnifyOrigin ty1 ty2)

715
couldNotDeduce :: [UserGiven] -> (ThetaType, CtOrigin) -> SDoc
716
couldNotDeduce givens (wanteds, orig)
717
  = vcat [ addArising orig (ptext (sLit "Could not deduce") <+> pprTheta wanteds)
dimitris's avatar
dimitris committed
718 719
         , vcat (pp_givens givens)]

720
pp_givens :: [UserGiven] -> [SDoc]
dimitris's avatar
dimitris committed
721 722
pp_givens givens 
   = case givens of
723 724 725
         []     -> []
         (g:gs) ->      ppr_given (ptext (sLit "from the context")) g
                 : map (ppr_given (ptext (sLit "or from"))) gs
726 727
    where 
       ppr_given herald (gs, skol_info, loc)
dimitris's avatar
dimitris committed
728
           = hang (herald <+> pprEvVarTheta gs)
729 730
                2 (sep [ ptext (sLit "bound by") <+> ppr skol_info
                       , ptext (sLit "at") <+> ppr loc])
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
731

732
extraTyVarInfo :: ReportErrCtxt -> TcType -> TcType -> SDoc
733 734
-- Add on extra info about the types themselves
-- NB: The types themselves are already tidied
735 736
extraTyVarInfo ctxt ty1 ty2
  = nest 2 (extra1 $$ extra2)
737
  where
738 739
    extra1 = tyVarExtraInfoMsg (cec_encl ctxt) ty1
    extra2 = tyVarExtraInfoMsg (cec_encl ctxt) ty2
740

741
tyVarExtraInfoMsg :: [Implication] -> Type -> SDoc
742
-- Shows a bit of extra info about skolem constants
743
tyVarExtraInfoMsg implics ty
744
  | Just tv <- tcGetTyVar_maybe ty
Simon Peyton Jones's avatar
Simon Peyton Jones committed
745 746 747
  , isTcTyVar tv, isSkolemTyVar tv
  , let pp_tv = quotes (ppr tv)
 = case tcTyVarDetails tv of
748
    SkolemTv {}   -> pp_tv <+> pprSkol (getSkolemInfo implics tv) (getSrcLoc tv)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
749 750 751 752 753 754 755
    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
 
756 757 758 759 760 761 762 763 764
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

765
--------------------
766 767 768 769 770 771 772 773 774 775 776 777
misMatchMsg :: Bool -> TcType -> TcType -> SDoc	   -- Types are already tidy
-- If oriented then ty1 is expected, ty2 is actual
misMatchMsg oriented ty1 ty2 
  | oriented
  = sep [ ptext (sLit "Couldn't match expected") <+> what <+> quotes (ppr ty1)
        , nest 12 $   ptext (sLit "with actual") <+> what <+> quotes (ppr ty2) ]
  | otherwise
  = sep [ ptext (sLit "Couldn't match") <+> what <+> quotes (ppr ty1)
        , nest 14 $ ptext (sLit "with") <+> quotes (ppr ty2) ]
  where 
    what | isKind ty1 = ptext (sLit "kind")
         | otherwise  = ptext (sLit "type")
778 779

mkExpectedActualMsg :: Type -> Type -> SDoc
780
mkExpectedActualMsg exp_ty act_ty
781 782
  = vcat [ text "Expected type:" <+> ppr exp_ty
         , text "  Actual type:" <+> ppr act_ty ]
783 784
\end{code}

Simon Peyton Jones's avatar
Simon Peyton Jones committed
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
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.

803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
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}
821 822
mkDictErr :: ReportErrCtxt -> [Ct] -> TcM ErrMsg
mkDictErr ctxt cts 
823 824 825 826 827 828 829
  = 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
830 831 832
       -- But we report only one of them (hence 'head') becuase they all
       -- have the same source-location origin, to try avoid a cascade
       -- of error from one location
833
       ; (ctxt, err) <- mk_dict_err ctxt (head (no_inst_cts ++ overlap_cts))
834
       ; mkErrorMsg ctxt ct1 err }
835
  where
836
    ct1:_ = cts
837 838 839 840 841 842 843 844 845 846
    no_givens = null (getUserGivens ctxt)
    is_no_inst (ct, (matches, unifiers, _))
      =  no_givens 
      && null matches 
      && (null unifiers || all (not . isAmbiguousTyVar) (varSetElems (tyVarsOfCt ct)))
           
    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) }
847
      where
848
        (clas, tys) = getClassPredTys (ctPred ct)
849

850
mk_dict_err :: ReportErrCtxt -> (Ct, ClsInstLookupResult)
851
            -> TcM (ReportErrCtxt, SDoc)
852 853 854 855
-- 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
856 857
  = do { (ctxt, is_ambig, ambig_msg) <- mkAmbigMsg ctxt [ct]
       ; (ctxt, binds_msg) <- relevantBindings ctxt ct
Simon Peyton Jones's avatar
Simon Peyton Jones committed
858
       ; traceTc "mk_dict_err" (ppr ct $$ ppr is_ambig $$ ambig_msg)
859
       ; return (ctxt, cannot_resolve_msg is_ambig binds_msg ambig_msg) }
860

861 862
  | not safe_haskell   -- Some matches => overlap errors
  = return (ctxt, overlap_msg)
863

864 865 866
  | otherwise
  = return (ctxt, safe_haskell_msg)
  where
867
    orig        = ctLocOrigin (cc_loc ct)
868 869 870 871 872 873
    pred        = ctPred ct
    (clas, tys) = getClassPredTys pred
    ispecs      = [ispec | (ispec, _) <- matches]
    givens      = getUserGivens ctxt
    all_tyvars  = all isTyVarTy tys

874
    cannot_resolve_msg has_ambig_tvs binds_msg ambig_msg
875 876
      = vcat [ addArising orig (no_inst_herald <+> pprParendType pred)
             , vcat (pp_givens givens)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
877 878
             , if (has_ambig_tvs && all_tyvars)
               then vcat [ ambig_msg, binds_msg, potential_msg ]
879
               else empty
880
             , show_fixes (add_to_ctxt_fixes has_ambig_tvs ++ drv_fixes) ]
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901

    potential_msg
      | null unifiers = empty
      | otherwise 
      = hang (if isSingleton unifiers 
              then ptext (sLit "Note: there is a potential instance available:")
              else ptext (sLit "Note: there are several potential instances:"))
    	   2 (ppr_insts unifiers)

    add_to_ctxt_fixes has_ambig_tvs
      | not has_ambig_tvs && all_tyvars
      , (orig:origs) <- mapCatMaybes get_good_orig (cec_encl ctxt)
      = [sep [ ptext (sLit "add") <+> pprParendType pred
               <+> ptext (sLit "to the context of")
	     , nest 2 $ ppr_skol orig $$ 
                        vcat [ ptext (sLit "or") <+> ppr_skol orig 
                             | orig <- origs ] ] ]
      | otherwise = []

    ppr_skol (PatSkol dc _) = ptext (sLit "the data constructor") <+> quotes (ppr dc)
    ppr_skol skol_info      = ppr skol_info
902 903

	-- Do not suggest adding constraints to an *inferred* type signature!
904 905 906
    get_good_orig ic = case ic_info ic of 
                         SigSkol (InfSigCtxt {}) _ -> Nothing
                         origin                    -> Just origin
907

908 909 910
    no_inst_herald
      | null givens && null matches = ptext (sLit "No instance for")
      | otherwise                   = ptext (sLit "Could not deduce")
911

912 913 914
    drv_fixes = case orig of
                   DerivOrigin -> [drv_fix]
                   _           -> []
915

916 917
    drv_fix = hang (ptext (sLit "use a standalone 'deriving instance' declaration,"))
                 2 (ptext (sLit "so you can specify the instance context yourself"))
918

919
    -- Normal overlap error
920
    overlap_msg
921 922
      = ASSERT( not (null matches) )
        vcat [	addArising orig (ptext (sLit "Overlapping instances for") 
batterseapower's avatar
batterseapower committed
923
				<+> pprType (mkClassPred clas tys))
dimitris's avatar
dimitris committed
924

925
             ,  if not (null matching_givens) then 
926
                  sep [ptext (sLit "Matching givens (or their superclasses):") 
927
                      , nest 2 (vcat matching_givens)]
dimitris's avatar
dimitris committed
928 929
                else empty

930 931 932
    	     ,	sep [ptext (sLit "Matching instances:"),
    		     nest 2 (vcat [pprInstances ispecs, pprInstances unifiers])]

933 934 935 936 937 938 939
             ,  if null matching_givens && isSingleton matches && null unifiers then
                -- Intuitively, some given matched the wanted in their
                -- flattened or rewritten (from given equalities) form
                -- but the matcher can't figure that out because the
                -- constraints are non-flat and non-rewritten so we
                -- simply report back the whole given
                -- context. Accelerate Smart.hs showed this problem.
940
                  sep [ ptext (sLit "There exists a (perhaps superclass) match:") 
941
                      , nest 2 (vcat (pp_givens givens))]
dimitris's avatar
dimitris committed
942 943
                else empty 

944 945 946
	     ,	if not (isSingleton matches)
    		then 	-- Two or more matches
		     empty
Simon Peyton Jones's avatar
Simon Peyton Jones committed
947
    		else 	-- One match
948
		parens (vcat [ptext (sLit "The choice depends on the instantiation of") <+>
batterseapower's avatar
batterseapower committed
949
	    		         quotes (pprWithCommas ppr (varSetElems (tyVarsOfTypes tys))),
950
			      if null (matching_givens) then
dimitris's avatar
dimitris committed
951 952 953
                                   vcat [ ptext (sLit "To pick the first instance above, use -XIncoherentInstances"),
			                  ptext (sLit "when compiling the other instance declarations")]
                              else empty])]
954 955 956 957
        where
            ispecs = [ispec | (ispec, _) <- matches]

            givens = getUserGivens ctxt
958 959
            matching_givens = mapCatMaybes matchable givens

960
            matchable (evvars,skol_info,loc) 
961 962 963
              = case ev_vars_matching of
                     [] -> Nothing
                     _  -> Just $ hang (pprTheta ev_vars_matching)
964 965
                                    2 (sep [ ptext (sLit "bound by") <+> ppr skol_info
                                           , ptext (sLit "at") <+> ppr loc])
966
                where ev_vars_matching = filter ev_var_matches (map evVarPred evvars)
batterseapower's avatar
batterseapower committed
967 968 969 970 971 972 973 974
                      ev_var_matches ty = case getClassPredTys_maybe ty of
                         Just (clas', tys')
                           | clas' == clas
                           , Just _ <- tcMatchTys (tyVarsOfTypes tys) tys tys'
                           -> True 
                           | otherwise
                           -> any ev_var_matches (immSuperClasses clas' tys')
                         Nothing -> False
975

976 977 978
    -- Overlap error because of Safe Haskell (first 
    -- match should be the most specific match)
    safe_haskell_msg
979 980
      = ASSERT( length matches > 1 )
        vcat [ addArising orig (ptext (sLit "Unsafe overlapping instances for") 
batterseapower's avatar
batterseapower committed
981
                        <+> pprType (mkClassPred clas tys))
982
             , sep [ptext (sLit "The matching instance is:"),
983 984 985 986 987 988 989
                    nest 2 (pprInstance $ head ispecs)]
             , vcat [ ptext $ sLit "It is compiled in a Safe module and as such can only"
                    , ptext $ sLit "overlap instances from the same module, however it"
                    , ptext $ sLit "overlaps the following instances from different modules:"
                    , nest 2 (vcat [pprInstances $ tail ispecs])
                    ]
             ]
990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004

show_fixes :: [SDoc] -> SDoc
show_fixes []     = empty
show_fixes (f:fs) = sep [ ptext (sLit "Possible fix:")
                        , nest 2 (vcat (f : map (ptext (sLit "or") <+>) fs))]

ppr_insts :: [ClsInst] -> SDoc
ppr_insts insts
  = pprInstances (take 3 insts) $$ dot_dot_message
  where
    n_extra = length insts - 3
    dot_dot_message 
       | n_extra <= 0 = empty
       | otherwise    = ptext (sLit "...plus") 
                        <+> speakNOf n_extra (ptext (sLit "other"))
dimitris's avatar
dimitris committed
1005

1006 1007 1008 1009 1010 1011
----------------------
quickFlattenTy :: TcType -> TcM TcType
-- See Note [Flattening in error message generation]
quickFlattenTy ty | Just ty' <- tcView ty = quickFlattenTy ty'
quickFlattenTy ty@(TyVarTy {})  = return ty
quickFlattenTy ty@(ForAllTy {}) = return ty     -- See
1012
quickFlattenTy ty@(LitTy {})    = return ty
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
  -- Don't flatten because of the danger or removing a bound variable
quickFlattenTy (AppTy ty1 ty2) = do { fy1 <- quickFlattenTy ty1
                                    ; fy2 <- quickFlattenTy ty2
                                    ; return (AppTy fy1 fy2) }
quickFlattenTy (FunTy ty1 ty2) = do { fy1 <- quickFlattenTy ty1
                                    ; fy2 <- quickFlattenTy ty2
                                    ; return (FunTy fy1 fy2) }
quickFlattenTy (TyConApp tc tys)
    | not (isSynFamilyTyCon tc)
    = do { fys <- mapM quickFlattenTy tys 
         ; return (TyConApp tc fys) }
    | otherwise
    = do { let (funtys,resttys) = splitAt (tyConArity tc) tys
                -- Ignore the arguments of the type family funtys
         ; v <- newMetaTyVar TauTv (typeKind (TyConApp tc funtys))
         ; flat_resttys <- mapM quickFlattenTy resttys
         ; return (foldl AppTy (mkTyVarTy v) flat_resttys) }
\end{code