TcErrors.hs 121 KB
Newer Older
1
{-# LANGUAGE CPP, ScopedTypeVariables #-}
2
3

module TcErrors(
4
       reportUnsolved, reportAllUnsolved, warnAllUnsolved,
5
       warnDefaulting,
6
7

       solverDepthErrorTcS
8
9
10
11
  ) where

#include "HsVersions.h"

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

59
import Control.Monad    ( when )
60
import Data.List        ( partition, mapAccumL, nub, sortBy, unfoldr )
61
import qualified Data.Set as Set
62

63
64
65
66
#if __GLASGOW_HASKELL__ > 710
import Data.Semigroup   ( Semigroup )
import qualified Data.Semigroup as Semigroup
#endif
67
68


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

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?

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

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

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

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

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

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

147
       ; report_unsolved binds_var False type_errors expr_holes
148
          type_holes out_of_scope_holes wanted
149
150
151

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

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

166
167
168
169
170
-- | Report all unsolved goals as warnings (but without deferring any errors to
-- run-time). See Note [Safe Haskell Overlapping Instances Implementation] in
-- TcSimplify
warnAllUnsolved :: WantedConstraints -> TcM ()
warnAllUnsolved wanted
171
172
173
  = do { ev_binds <- newTcEvBinds
       ; report_unsolved ev_binds True TypeWarn
                         HoleWarn HoleWarn HoleWarn wanted }
174
175

-- | Report unsolved goals as errors or warnings.
176
report_unsolved :: EvBindsVar        -- cec_binds
177
                -> Bool              -- Errors as warnings
178
                -> TypeErrorChoice   -- Deferred type errors
179
180
                -> HoleChoice        -- Expression holes
                -> HoleChoice        -- Type holes
181
                -> HoleChoice        -- Out of scope holes
182
                -> WantedConstraints -> TcM ()
183
184
report_unsolved mb_binds_var err_as_warn type_errors expr_holes
    type_holes out_of_scope_holes wanted
185
  | isEmptyWC wanted
186
  = return ()
187
  | otherwise
188
  = do { traceTc "reportUnsolved (before zonking and tidying)" (ppr wanted)
189

190
       ; wanted <- zonkWC wanted   -- Zonk to reveal all information
191
       ; env0 <- tcInitTidyEnv
192
193
            -- If we are deferring we are going to need /all/ evidence around,
            -- including the evidence produced by unflattening (zonkWC)
194
       ; let tidy_env = tidyFreeTyCoVars env0 free_tvs
niteria's avatar
niteria committed
195
             free_tvs = tyCoVarsOfWCList wanted
196

197
198
199
       ; traceTc "reportUnsolved (after zonking):" $
         vcat [ text "Free tyvars:" <+> pprTyVars free_tvs
              , text "Wanted:" <+> ppr wanted ]
200
201
202

       ; warn_redundant <- woptM Opt_WarnRedundantConstraints
       ; let err_ctxt = CEC { cec_encl  = []
203
                            , cec_tidy  = tidy_env
204
                            , cec_defer_type_errors = type_errors
205
                            , cec_errors_as_warns = err_as_warn
206
207
                            , cec_expr_holes = expr_holes
                            , cec_type_holes = type_holes
208
                            , cec_out_of_scope_holes = out_of_scope_holes
209
                            , cec_suppress = False -- See Note [Suppressing error messages]
210
                            , cec_warn_redundant = warn_redundant
211
                            , cec_binds    = mb_binds_var }
212

213
214
       ; tc_lvl <- getTcLevel
       ; reportWanteds err_ctxt tc_lvl wanted }
215

216
217
218
--------------------------------------------
--      Internal functions
--------------------------------------------
219

220
221
222
223
224
-- | An error Report collects messages categorised by their importance.
-- See Note [Error report] for details.
data Report
  = Report { report_important :: [SDoc]
           , report_relevant_bindings :: [SDoc]
225
           , report_valid_substitutions :: [SDoc]
226
227
           }

228
instance Outputable Report where   -- Debugging only
229
230
231
  ppr (Report { report_important = imp
              , report_relevant_bindings = rel
              , report_valid_substitutions = val })
232
    = vcat [ text "important:" <+> vcat imp
233
234
           , text "relevant:"  <+> vcat rel
           , text "valid:"  <+> vcat val ]
235

236
237
238
239
240
241
242
243
244
245
246
247
248
{- Note [Error report]
The idea is that error msgs are divided into three parts: the main msg, the
context block (\"In the second argument of ...\"), and the relevant bindings
block, which are displayed in that order, with a mark to divide them.  The
idea is that the main msg ('report_important') varies depending on the error
in question, but context and relevant bindings are always the same, which
should simplify visual parsing.

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

249
250
#if __GLASGOW_HASKELL__ > 710
instance Semigroup Report where
251
    Report a1 b1 c1 <> Report a2 b2 c2 = Report (a1 ++ a2) (b1 ++ b2) (c1 ++ c2)
252
253
#endif

254
instance Monoid Report where
255
256
257
    mempty = Report [] [] []
    mappend (Report a1 b1 c1) (Report a2 b2 c2)
      = Report (a1 ++ a2) (b1 ++ b2) (c1 ++ c2)
258
259
260
261
262
263
264
265
266

-- | Put a doc into the important msgs block.
important :: SDoc -> Report
important doc = mempty { report_important = [doc] }

-- | Put a doc into the relevant bindings block.
relevant_bindings :: SDoc -> Report
relevant_bindings doc = mempty { report_relevant_bindings = [doc] }

267
268
269
270
-- | Put a doc into the valid substitutions block.
valid_substitutions :: SDoc -> Report
valid_substitutions docs = mempty { report_valid_substitutions = [docs] }

271
272
273
274
275
data TypeErrorChoice   -- What to do for type errors found by the type checker
  = TypeError     -- A type error aborts compilation with an error message
  | TypeWarn      -- A type error is deferred to runtime, plus a compile-time warning
  | TypeDefer     -- A type error is deferred to runtime; no error or warning at compile time

276
277
278
279
280
data HoleChoice
  = HoleError     -- A hole is a compile-time error
  | HoleWarn      -- Defer to runtime, emit a compile-time warning
  | HoleDefer     -- Defer to runtime, no warning

281
282
283
284
285
286
287
288
289
290
instance Outputable HoleChoice where
  ppr HoleError = text "HoleError"
  ppr HoleWarn  = text "HoleWarn"
  ppr HoleDefer = text "HoleDefer"

instance Outputable TypeErrorChoice  where
  ppr TypeError = text "TypeError"
  ppr TypeWarn  = text "TypeWarn"
  ppr TypeDefer = text "TypeDefer"

291
data ReportErrCtxt
292
    = CEC { cec_encl :: [Implication]  -- Enclosing implications
293
                                       --   (innermost first)
294
                                       -- ic_skols and givens are tidied, rest are not
295
          , cec_tidy  :: TidyEnv
Simon Peyton Jones's avatar
Simon Peyton Jones committed
296

297
298
299
          , cec_binds :: EvBindsVar    -- Make some errors (depending on cec_defer)
                                       -- into warnings, and emit evidence bindings
                                       -- into 'cec_binds' for unsolved constraints
300

301
302
303
304
          , cec_errors_as_warns :: Bool   -- Turn all errors into warnings
                                          -- (except for Holes, which are
                                          -- controlled by cec_type_holes and
                                          -- cec_expr_holes)
305
          , cec_defer_type_errors :: TypeErrorChoice -- Defer type errors until runtime
306

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

315
          , cec_warn_redundant :: Bool    -- True <=> -Wredundant-constraints
316

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

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

Austin Seipp's avatar
Austin Seipp committed
342
{-
343
344
Note [Suppressing error messages]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
345
The cec_suppress flag says "don't report any errors".  Instead, just create
346
evidence bindings (as usual).  It's used when more important errors have occurred.
347

348
349
350
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.
351
  * If there are any insolubles (eg Int~Bool), here or in a nested implication,
352
353
    then suppress errors from the simple constraints here.  Sometimes the
    simple-constraint errors are a knock-on effect of the insolubles.
Austin Seipp's avatar
Austin Seipp committed
354
-}
355

356
357
reportImplic :: ReportErrCtxt -> Implication -> TcM ()
reportImplic ctxt implic@(Implic { ic_skols = tvs, ic_given = given
358
                                 , ic_wanted = wanted, ic_binds = evb
359
                                 , ic_status = status, ic_info = info
360
                                 , ic_env = tcl_env, ic_tclvl = tc_lvl })
361
  | BracketSkol <- info
362
  , not insoluble
363
364
  = return ()        -- For Template Haskell brackets report only
                     -- definite errors. The whole thing will be re-checked
Simon Peyton Jones's avatar
Simon Peyton Jones committed
365
366
                     -- later when we plug it in, and meanwhile there may
                     -- certainly be un-satisfied constraints
367
368

  | otherwise
369
370
  = do { traceTc "reportImplic" (ppr implic')
       ; reportWanteds ctxt' tc_lvl wanted
371
372
       ; when (cec_warn_redundant ctxt) $
         warnRedundantConstraints ctxt' tcl_env info' dead_givens }
373
  where
374
    insoluble    = isInsolubleStatus status
375
    (env1, tvs') = mapAccumL tidyTyCoVarBndr (cec_tidy ctxt) tvs
Simon Peyton Jones's avatar
Simon Peyton Jones committed
376
    info'        = tidySkolemInfo env1 info
377
    implic' = implic { ic_skols = tvs'
Simon Peyton Jones's avatar
Simon Peyton Jones committed
378
                     , ic_given = map (tidyEvVar env1) given
379
                     , ic_info  = info' }
Simon Peyton Jones's avatar
Simon Peyton Jones committed
380
    ctxt' = ctxt { cec_tidy     = env1
381
                 , cec_encl     = implic' : cec_encl ctxt
382
383
384
385
386
387
388

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

389
                 , cec_binds    = evb }
390

391
392
393
394
395
    dead_givens = case status of
                    IC_Solved { ics_dead = dead } -> dead
                    _                             -> []

warnRedundantConstraints :: ReportErrCtxt -> TcLclEnv -> SkolemInfo -> [EvVar] -> TcM ()
396
-- See Note [Tracking redundant constraints] in TcSimplify
397
warnRedundantConstraints ctxt env info ev_vars
398
 | null redundant_evs
399
400
401
402
403
 = return ()

 | SigSkol {} <- info
 = setLclEnv env $  -- We want to add "In the type signature for f"
                    -- to the error context, which is a bit tiresome
404
   addErrCtxt (text "In" <+> ppr info) $
405
   do { env <- getLclEnv
406
      ; msg <- mkErrorReport ctxt env (important doc)
407
      ; reportWarning (Reason Opt_WarnRedundantConstraints) msg }
408
409
410
411

 | otherwise  -- But for InstSkol there already *is* a surrounding
              -- "In the instance declaration for Eq [a]" context
              -- and we don't want to say it twice. Seems a bit ad-hoc
412
 = do { msg <- mkErrorReport ctxt env (important doc)
413
      ; reportWarning (Reason Opt_WarnRedundantConstraints) msg }
414
 where
415
   doc = text "Redundant constraint" <> plural redundant_evs <> colon
416
417
418
419
420
421
422
         <+> pprEvVarTheta redundant_evs

   redundant_evs = case info of -- See Note [Redundant constraints in instance decls]
                     InstSkol -> filterOut improving ev_vars
                     _        -> ev_vars

   improving ev_var = any isImprovementPred $
423
                      transSuperClasses (idType ev_var)
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440

{- Note [Redundant constraints in instance decls]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For instance declarations, we don't report unused givens if
they can give rise to improvement.  Example (Trac #10100):
    class Add a b ab | a b -> ab, a ab -> b
    instance Add Zero b b
    instance Add a b ab => Add (Succ a) b (Succ ab)
The context (Add a b ab) for the instance is clearly unused in terms
of evidence, since the dictionary has no feilds.  But it is still
needed!  With the context, a wanted constraint
   Add (Succ Zero) beta (Succ Zero)
we will reduce to (Add Zero beta Zero), and thence we get beta := Zero.
But without the context we won't find beta := Zero.

This only matters in instance declarations..
-}
441

442
443
reportWanteds :: ReportErrCtxt -> TcLevel -> WantedConstraints -> TcM ()
reportWanteds ctxt tc_lvl (WC { wc_simple = simples, wc_insol = insols, wc_impl = implics })
444
  = do { traceTc "reportWanteds" (vcat [ text "Simples =" <+> ppr simples
445
                                       , text "Insols =" <+> ppr insols
446
                                       , text "Suppress =" <+> ppr (cec_suppress ctxt)])
447
       ; let tidy_cts = bagToList (mapBag (tidyCt env) (insols `unionBags` simples))
448
449
450
451

         -- First deal with things that are utterly wrong
         -- Like Int ~ Bool (incl nullary TyCons)
         -- or  Int ~ t a   (AppTy on one side)
452
         -- These /ones/ are not suppressed by the incoming context
453
454
455
456
457
458
459
460
       ; let ctxt_for_insols = ctxt { cec_suppress = False }
       ; (ctxt1, cts1) <- tryReporters ctxt_for_insols report1 tidy_cts

         -- Now all the other constraints.  We suppress errors here if
         -- any of the first batch failed, or if the enclosing context
         -- says to suppress
       ; let ctxt2 = ctxt { cec_suppress = cec_suppress ctxt || cec_suppress ctxt1 }
       ; (_, leftovers) <- tryReporters ctxt2 report2 cts1
461
462
       ; MASSERT2( null leftovers, ppr leftovers )

463
            -- All the Derived ones have been filtered out of simples
464
465
466
            -- 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]
467

468
     ; mapBagM_ (reportImplic ctxt2) implics }
469
            -- NB ctxt1: don't suppress inner insolubles if there's only a
470
            -- wanted insoluble here; but do suppress inner insolubles
471
            -- if there's a *given* insoluble here (= inaccessible code)
472
 where
473
    env = cec_tidy ctxt
474

475
476
477
478
479
480
    -- report1: ones that should *not* be suppresed by
    --          an insoluble somewhere else in the tree
    -- It's crucial that anything that is considered insoluble
    -- (see TcRnTypes.trulyInsoluble) is caught here, otherwise
    -- we might suppress its error message, and proceed on past
    -- type checking to get a Lint error later
481
482
    report1 = [ ("custom_error", is_user_type_error,
                                                  True, mkUserTypeErrorReporter)
483
              , given_eq_spec
484
              , ("insoluble2",   utterly_wrong,   True, mkGroupReporter mkEqErr)
485
486
487
              , ("skolem eq1",   very_wrong,      True, mkSkolReporter)
              , ("skolem eq2",   skolem_eq,       True, mkSkolReporter)
              , ("non-tv eq",    non_tv_eq,       True, mkSkolReporter)
488
              , ("Out of scope", is_out_of_scope, True, mkHoleReporter)
489
490
491
492
493
494
495
496
497
498
499
              , ("Holes",        is_hole,         False, mkHoleReporter)

                  -- The only remaining equalities are alpha ~ ty,
                  -- where alpha is untouchable; and representational equalities
              , ("Other eqs",    is_equality,     False, mkGroupReporter mkEqErr) ]

    -- report2: we suppress these if there are insolubles elsewhere in the tree
    report2 = [ ("Implicit params", is_ip,           False, mkGroupReporter mkIPErr)
              , ("Irreds",          is_irred,        False, mkGroupReporter mkIrredErr)
              , ("Dicts",           is_dict,         False, mkGroupReporter mkDictErr) ]

500
501
    -- rigid_nom_eq, rigid_nom_tv_eq,
    is_hole, is_dict,
502
      is_equality, is_ip, is_irred :: Ct -> PredTree -> Bool
503

504
505
506
507
508
    is_given_eq ct pred
       | EqPred {} <- pred = arisesFromGivens ct
       | otherwise         = False
       -- I think all given residuals are equalities

509
510
511
512
513
514
515
    -- Things like (Int ~N Bool)
    utterly_wrong _ (EqPred NomEq ty1 ty2) = isRigidTy ty1 && isRigidTy ty2
    utterly_wrong _ _                      = False

    -- Things like (a ~N Int)
    very_wrong _ (EqPred NomEq ty1 ty2) = isSkolemTy tc_lvl ty1 && isRigidTy ty2
    very_wrong _ _                      = False
516

517
    -- Things like (a ~N b) or (a  ~N  F Bool)
518
    skolem_eq _ (EqPred NomEq ty1 _) = isSkolemTy tc_lvl ty1
519
    skolem_eq _ _                    = False
520

521
522
523
524
525
526
527
528
    -- Things like (F a  ~N  Int)
    non_tv_eq _ (EqPred NomEq ty1 _) = not (isTyVarTy ty1)
    non_tv_eq _ _                    = False

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

    is_user_type_error ct _ = isUserTypeErrorCt ct
529

530
531
532
    is_equality _ (EqPred {}) = True
    is_equality _ _           = False

533
534
535
536
537
538
539
540
541
    is_dict _ (ClassPred {}) = True
    is_dict _ _              = False

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

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

542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
    given_eq_spec = case find_gadt_match (cec_encl ctxt) of
       Just imp -> ("insoluble1a", is_given_eq, True,  mkGivenErrorReporter imp)
       Nothing  -> ("insoluble1b", is_given_eq, False, ignoreErrorReporter)
                  -- False means don't suppress subsequent errors
                  -- Reason: we don't report all given errors
                  --         (see mkGivenErrorReporter), and we should only suppress
                  --         subsequent errors if we actually report this one!
                  --         Trac #13446 is an example

    find_gadt_match [] = Nothing
    find_gadt_match (implic : implics)
      | PatSkol {} <- ic_info implic
      , not (ic_no_eqs implic)
      = Just implic
      | otherwise
      = find_gadt_match implics
558

559
---------------
560
isSkolemTy :: TcLevel -> Type -> Bool
561
-- The type is a skolem tyvar
562
isSkolemTy tc_lvl ty
563
564
565
566
567
568
569
570
  | Just tv <- getTyVar_maybe ty
  =  isSkolemTyVar tv
  || (isSigTyVar tv && isTouchableMetaTyVar tc_lvl tv)
     -- The last case is for touchable SigTvs
     -- we postpone untouchables to a latter test (too obscure)

  | otherwise
  = False
571

572
573
isTyFun_maybe :: Type -> Maybe TyCon
isTyFun_maybe ty = case tcSplitTyConApp_maybe ty of
574
                      Just (tc,_) | isTypeFamilyTyCon tc -> Just tc
575
576
                      _ -> Nothing

577
--------------------------------------------
578
--      Reporters
579
580
--------------------------------------------

581
582
583
584
585
586
587
588
589
type Reporter
  = ReportErrCtxt -> [Ct] -> TcM ()
type ReporterSpec
  = ( String                     -- Name
    , Ct -> PredTree -> Bool     -- Pick these ones
    , Bool                       -- True <=> suppress subsequent reporters
    , Reporter)                  -- The reporter itself

mkSkolReporter :: Reporter
590
-- Suppress duplicates with either the same LHS, or same location
591
mkSkolReporter ctxt cts
592
  = mapM_ (reportGroup mkEqErr ctxt) (group cts)
593
  where
594
595
596
597
598
599
     group [] = []
     group (ct:cts) = (ct : yeses) : group noes
        where
          (yeses, noes) = partition (group_with ct) cts

     group_with ct1 ct2
600
601
602
       | EQ <- cmp_loc ct1 ct2 = True
       | eq_lhs_type   ct1 ct2 = True
       | otherwise             = False
603

604
mkHoleReporter :: Reporter
605
-- Reports errors one at a time
606
mkHoleReporter ctxt
607
608
609
  = mapM_ $ \ct -> do { err <- mkHoleError ctxt ct
                      ; maybeReportHoleError ctxt ct err
                      ; maybeAddDeferredHoleBinding ctxt err ct }
610

611
612
mkUserTypeErrorReporter :: Reporter
mkUserTypeErrorReporter ctxt
613
  = mapM_ $ \ct -> do { err <- mkUserTypeError ctxt ct
614
615
                      ; maybeReportError ctxt err
                      ; addDeferredBinding ctxt err ct }
616
617
618

mkUserTypeError :: ReportErrCtxt -> Ct -> TcM ErrMsg
mkUserTypeError ctxt ct = mkErrorMsgFromCt ctxt ct
619
                        $ important
620
621
                        $ pprUserTypeErrorTy
                        $ case getUserTypeErrorMsg ct of
622
623
                            Just msg -> msg
                            Nothing  -> pprPanic "mkUserTypeError" (ppr ct)
624
625


626
mkGivenErrorReporter :: Implication -> Reporter
627
-- See Note [Given errors]
628
mkGivenErrorReporter implic ctxt cts
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
  = do { (ctxt, binds_msg, ct) <- relevantBindings True ctxt ct
       ; dflags <- getDynFlags
       ; let ct' = setCtLoc ct (setCtLocEnv (ctLoc ct) (ic_env implic))
                   -- For given constraints we overwrite the env (and hence src-loc)
                  -- with one from the implication.  See Note [Inaccessible code]

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

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

       ; traceTc "mkGivenErrorRporter" (ppr ct)
       ; maybeReportError ctxt err }
  where
    (ct : _ )  = cts    -- Never empty
    (ty1, ty2) = getEqPredTys (ctPred ct)

649
650
651
652
653
654
655
ignoreErrorReporter :: Reporter
-- Discard Given errors that don't come from
-- a pattern match; maybe we should warn instead?ignoreErrorReporter ctxt cts
ignoreErrorReporter ctxt cts
  = do { traceTc "mkGivenErrorRporter no" (ppr cts $$ ppr (cec_encl ctxt))
       ; return () }

656
657
658

{- Note [Given errors]
~~~~~~~~~~~~~~~~~~~~~~
Gabor Greif's avatar
Gabor Greif committed
659
Given constraints represent things for which we have (or will have)
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
evidence, so they aren't errors.  But if a Given constraint is
insoluble, this code is inaccessible, and we might want to at least
warn about that.  A classic case is

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

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

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

But we don't want to report ALL insoluble Given constraints.  See Trac
#12466 for a long discussion on.  For example, if we aren't careful
we'll complain about
   f :: ((Int ~ Bool) => a -> a) -> Int
which arguably is OK.  It's more debatable for
   g :: (Int ~ Bool) => Int -> Int
but it's tricky to distinguish these cases to we don't report
either.

The bottom line is this: find_gadt_match looks for an encosing
pattern match which binds some equality constraints.  If we
find one, we report the insoluble Given.
-}

691
692
693
mkGroupReporter :: (ReportErrCtxt -> [Ct] -> TcM ErrMsg)
                             -- Make error message for a group
                -> Reporter  -- Deal with lots of constraints
694
695
696
697
-- 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)
698

699
700
eq_lhs_type :: Ct -> Ct -> Bool
eq_lhs_type ct1 ct2
701
702
  = case (classifyPredType (ctPred ct1), classifyPredType (ctPred ct2)) of
       (EqPred eq_rel1 ty1 _, EqPred eq_rel2 ty2 _) ->
703
         (eq_rel1 == eq_rel2) && (ty1 `eqType` ty2)
704
705
706
707
       _ -> pprPanic "mkSkolReporter" (ppr ct1 $$ ppr ct2)

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

709
710
reportGroup :: (ReportErrCtxt -> [Ct] -> TcM ErrMsg) -> ReportErrCtxt
            -> [Ct] -> TcM ()
quchen's avatar
quchen committed
711
712
713
reportGroup mk_err ctxt cts =
  case partition isMonadFailInstanceMissing cts of
        -- Only warn about missing MonadFail constraint when
Gabor Greif's avatar
Gabor Greif committed
714
        -- there are no other missing constraints!
715
716
717
        (monadFailCts, []) ->
            do { err <- mk_err ctxt monadFailCts
               ; reportWarning (Reason Opt_WarnMissingMonadFailInstances) err }
quchen's avatar
quchen committed
718
719
720

        (_, cts') -> do { err <- mk_err ctxt cts'
                        ; maybeReportError ctxt err
721
722
723
724
725
726
727
                            -- But see Note [Always warn with -fdefer-type-errors]
                        ; traceTc "reportGroup" (ppr cts')
                        ; mapM_ (addDeferredBinding ctxt err) cts' }
                            -- Add deferred bindings for all
                            -- Redundant if we are going to abort compilation,
                            -- but that's hard to know for sure, and if we don't
                            -- abort, we need bindings for all (e.g. Trac #12156)
quchen's avatar
quchen committed
728
729
730
731
732
  where
    isMonadFailInstanceMissing ct =
        case ctLocOrigin (ctLoc ct) of
            FailablePattern _pat -> True
            _otherwise           -> False
733

734
735
maybeReportHoleError :: ReportErrCtxt -> Ct -> ErrMsg -> TcM ()
maybeReportHoleError ctxt ct err
thomasw's avatar
thomasw committed
736
  -- When -XPartialTypeSignatures is on, warnings (instead of errors) are
737
738
739
  -- generated for holes in partial type signatures.
  -- Unless -fwarn_partial_type_signatures is not on,
  -- in which case the messages are discarded.
740
741
742
743
744
  | isTypeHoleCt ct
  = -- For partial type signatures, generate warnings only, and do that
    -- only if -fwarn_partial_type_signatures is on
    case cec_type_holes ctxt of
       HoleError -> reportError err
745
       HoleWarn  -> reportWarning (Reason Opt_WarnPartialTypeSignatures) err
746
747
       HoleDefer -> return ()

748
749
750
751
  -- Always report an error for out-of-scope variables
  -- Unless -fdefer-out-of-scope-variables is on,
  -- in which case the messages are discarded.
  -- See Trac #12170, #12406
752
  | isOutOfScopeCt ct
753
754
755
756
757
758
  = -- If deferring, report a warning only if -Wout-of-scope-variables is on
    case cec_out_of_scope_holes ctxt of
      HoleError -> reportError err
      HoleWarn  ->
        reportWarning (Reason Opt_WarnDeferredOutOfScopeVariables) err
      HoleDefer -> return ()
759
760
761

  -- Otherwise this is a typed hole in an expression,
  -- but not for an out-of-scope variable
762
  | otherwise
763
  = -- If deferring, report a warning only if -Wtyped-holes is on
764
765
    case cec_expr_holes ctxt of
       HoleError -> reportError err
766
       HoleWarn  -> reportWarning (Reason Opt_WarnTypedHoles) err
767
       HoleDefer -> return ()
768

769
maybeReportError :: ReportErrCtxt -> ErrMsg -> TcM ()
770
-- Report the error and/or make a deferred binding for it
771
maybeReportError ctxt err
772
773
774
  | cec_suppress ctxt    -- Some worse error has occurred;
  = return ()            -- so suppress this error/warning

775
  | cec_errors_as_warns ctxt
776
  = reportWarning NoReason err
777

778
  | otherwise
779
  = case cec_defer_type_errors ctxt of
780
      TypeDefer -> return ()
781
      TypeWarn  -> reportWarning (Reason Opt_WarnDeferredTypeErrors) err
782
      TypeError -> reportError err
783

784
addDeferredBinding :: ReportErrCtxt -> ErrMsg -> Ct -> TcM ()
785
-- See Note [Deferring coercion errors to runtime]
786
addDeferredBinding ctxt err ct
787
  | CtWanted { ctev_pred = pred, ctev_dest = dest } <- ctEvidence ct
788
789
790
791
792
    -- Only add deferred bindings for Wanted constraints
  = do { dflags <- getDynFlags
       ; let err_msg = pprLocErrMsg err
             err_fs  = mkFastString $ showSDoc dflags $
                       err_msg $$ text "(deferred type error)"
793
             err_tm  = EvDelayedError pred err_fs
794
             ev_binds_var = cec_binds ctxt
795

796
797
798
799
800
801
802
803
       ; case dest of
           EvVarDest evar
             -> addTcEvBind ev_binds_var $ mkWantedEvBind evar err_tm
           HoleDest hole
             -> do { -- See Note [Deferred errors for coercion holes]
                     evar <- newEvVar pred
                   ; addTcEvBind ev_binds_var $ mkWantedEvBind evar err_tm
                   ; fillCoercionHole hole (mkTcCoVarCo evar) }}
804
805

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

808
809
maybeAddDeferredHoleBinding :: ReportErrCtxt -> ErrMsg -> Ct -> TcM ()
maybeAddDeferredHoleBinding ctxt err ct
810
811
812
813
  | isExprHoleCt ct
  = addDeferredBinding ctxt err ct  -- Only add bindings for holes in expressions
  | otherwise                       -- not for holes in partial type signatures
  = return ()
814

815
tryReporters :: ReportErrCtxt -> [ReporterSpec] -> [Ct] -> TcM (ReportErrCtxt, [Ct])
816
-- Use the first reporter in the list whose predicate says True
817
tryReporters ctxt reporters cts
818
  = do { traceTc "tryReporters {" (ppr cts)
819
820
821
       ; (ctxt', cts') <- go ctxt reporters cts
       ; traceTc "tryReporters }" (ppr cts')
       ; return (ctxt', cts') }
822
  where
823
    go ctxt [] cts
824
825
826
827
828
829
830
831
832
833
834
835
      = return (ctxt, cts)

    go ctxt (r : rs) cts
      = do { (ctxt', cts') <- tryReporter ctxt r cts
           ; go ctxt' rs cts' }
                -- Carry on with the rest, because we must make
                -- deferred bindings for them if we have -fdefer-type-errors
                -- But suppress their error messages

tryReporter :: ReportErrCtxt -> ReporterSpec -> [Ct] -> TcM (ReportErrCtxt, [Ct])
tryReporter ctxt (str, keep_me,  suppress_after, reporter) cts
  | null yeses = return (ctxt, cts)
836
  | otherwise  = do { traceTc "tryReporter{ " (text str <+> ppr yeses)
837
838
                    ; reporter ctxt yeses
                    ; let ctxt' = ctxt { cec_suppress = suppress_after || cec_suppress ctxt }
839
                    ; traceTc "tryReporter end }" (text str <+> ppr (cec_suppress ctxt) <+> ppr suppress_after)
840
841
842
                    ; return (ctxt', nos) }
  where
    (yeses, nos) = partition (\ct -> keep_me ct (classifyPredType (ctPred ct))) cts
843

844
845
846
847
848
849
850
851
852

pprArising :: CtOrigin -> SDoc
-- Used for the main, top-level error message
-- We've done special processing for TypeEq, KindEq, Given
pprArising (TypeEqOrigin {}) = empty
pprArising (KindEqOrigin {}) = empty
pprArising (GivenOrigin {})  = empty
pprArising orig              = pprCtOrigin orig

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

857
pprWithArising :: [Ct] -> (CtLoc, SDoc)
858
859
-- Print something like
--    (Eq a) arising from a use of x at y
860
861
--    (Show a) arising from a use of p at q
-- Also return a location for the error message
862
-- Works for Wanted/Derived only
863
pprWithArising []
864
  = panic "pprWithArising"
865
866
pprWithArising (ct:cts)
  | null cts
867
  = (loc, addArising (ctLocOrigin loc)
dimitris's avatar
dimitris committed
868
                     (pprTheta [ctPred ct]))
869
870
  | otherwise
  = (loc, vcat (map ppr_one (ct:cts)))
871
  where
872
    loc = ctLoc ct
873
    ppr_one ct' = hang (parens (pprType (ctPred ct')))
874
                     2 (pprCtLoc (ctLoc ct'))
875

876
877
878
mkErrorMsgFromCt :: ReportErrCtxt -> Ct -> Report -> TcM ErrMsg
mkErrorMsgFromCt ctxt ct report
  = mkErrorReport ctxt (ctLocEnv (ctLoc ct)) report
879

880
mkErrorReport :: ReportErrCtxt -> TcLclEnv -> Report -> TcM ErrMsg
881
mkErrorReport ctxt tcl_env (Report important relevant_bindings valid_subs)
882
883
  = do { context <- mkErrInfo (cec_tidy ctxt) (tcl_ctxt tcl_env)
       ; mkErrDocAt (RealSrcSpan (tcl_loc tcl_env))
884
            (errDoc important [context] (relevant_bindings ++ valid_subs))
885
       }
886

887
type UserGiven = Implication
888
889

getUserGivens :: ReportErrCtxt -> [UserGiven]
890
-- One item for each enclosing implication
891
892
893
894
getUserGivens (CEC {cec_encl = implics}) = getUserGivensFromImplics implics

getUserGivensFromImplics :: [Implication] -> [UserGiven]
getUserGivensFromImplics implics
895
  = reverse (filterOut (null . ic_given) implics)
896

Austin Seipp's avatar
Austin Seipp committed
897
{-
898
899
900
901
902
903
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
904
time.
905
906
907
908
909

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

913
914
With #10283, you can now opt out of deferred type error warnings.

915
916
917
918
919
920
921
922
923
Note [Deferred errors for coercion holes]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we need to defer a type error where the destination for the evidence
is a coercion hole. We can't just put the error in the hole, because we can't
make an erroneous coercion. (Remember that coercions are erased for runtime.)
Instead, we invent a new EvVar, bind it to an error and then make a coercion
from that EvVar, filling the hole with that coercion. Because coercions'
types are unlifted, the error is guaranteed to be hit before we get to the
coercion.
924

925
926
Note [Do not report derived but soluble errors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
927
The wc_simples include Derived constraints that have not been solved, but are
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
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
946
        MkT :: C Int b => a -> b -> T a
947
948
949
950
951
952
      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.

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

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

  class C a b | a -> b
960
961
962
963
  g :: C a b => a -> b -> ()
  f :: C a b => a -> b -> ()
  f xa xb =
      let loop = g xa
964
965
966
967
      in loop xb

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


Austin Seipp's avatar
Austin Seipp committed
975
************************************************************************
976
*                                                                      *
batterseapower's avatar
batterseapower committed
977
                Irreducible predicate errors
978
*                                                                      *
Austin Seipp's avatar
Austin Seipp committed
979
980
************************************************************************
-}
batterseapower's avatar
batterseapower committed
981

982
mkIrredErr :: ReportErrCtxt -> [Ct] -> TcM ErrMsg
983
mkIrredErr ctxt cts
984
985
986
  = do { (ctxt, binds_msg, ct1) <- relevantBindings True ctxt ct1
       ; let orig = ctOrigin ct1
             msg  = couldNotDeduce (getUserGivens ctxt) (map ctPred cts, orig)
987
988
       ; mkErrorMsgFromCt ctxt ct1 $
            important msg `mappend` relevant_bindings binds_msg }
batterseapower's avatar
batterseapower committed
989
  where
990
    (ct1:_) = cts
batterseapower's avatar
batterseapower committed
991

992
----------------
993
mkHoleError :: ReportErrCtxt -> Ct -> TcM ErrMsg
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
mkHoleError _ctxt ct@(CHoleCan { cc_hole = ExprHole (OutOfScope occ rdr_env0) })
  -- Out-of-scope variables, like 'a', where 'a' isn't bound; suggest possible
  -- in-scope variables in the message, and note inaccessible exact matches
  = do { dflags   <- getDynFlags
       ; imp_info <- getImports
       ; let suggs_msg = unknownNameSuggestions dflags rdr_env0
                                                (tcl_rdr lcl_env) imp_info rdr
       ; rdr_env     <- getGlobalRdrEnv
       ; splice_locs <- getTopLevelSpliceLocs
       ; let match_msgs = mk_match_msgs rdr_env splice_locs
       ; mkErrDocAt (RealSrcSpan err_loc) $
                    errDoc [out_of_scope_msg] [] (match_msgs ++ [suggs_msg]) }
1006

1007
  where
1008
    rdr         = mkRdrUnqual occ
1009
1010
    ct_loc      = ctLoc ct
    lcl_env     = ctLocEnv ct_loc
1011
    err_loc     = tcl_loc lcl_env
1012
1013
    hole_ty     = ctEvPred (ctEvidence ct)
    boring_type = isTyVarTy hole_ty