Simon Peyton Jones pushed to branch wip/26805 at Glasgow Haskell Compiler / GHC

Commits:

16 changed files:

Changes:

  • compiler/GHC/Core/TyCo/Rep.hs
    ... ... @@ -1688,11 +1688,9 @@ holes `HoleCo`, which get filled in later.
    1688 1688
     
    
    1689 1689
     -- | A coercion to be filled in by the type-checker. See Note [Coercion holes]
    
    1690 1690
     data CoercionHole
    
    1691
    -  = CoercionHole { ch_co_var  :: CoVar
    
    1692
    -                       -- See Note [Coercion holes] wrinkle (COH2)
    
    1693
    -
    
    1694
    -                 , ch_ref :: IORef (Maybe CoercionPlusHoles)
    
    1695
    -                 }
    
    1691
    +  = CH { ch_co_var  :: CoVar  -- See Note [Coercion holes] wrinkle (COH2)
    
    1692
    +       , ch_ref :: IORef (Maybe CoercionPlusHoles)
    
    1693
    +       }
    
    1696 1694
     
    
    1697 1695
     data CoercionPlusHoles
    
    1698 1696
       = CPH { cph_co    :: Coercion
    
    ... ... @@ -1714,7 +1712,7 @@ instance Data.Data CoercionHole where
    1714 1712
       dataTypeOf _ = mkNoRepType "CoercionHole"
    
    1715 1713
     
    
    1716 1714
     instance Outputable CoercionHole where
    
    1717
    -  ppr (CoercionHole { ch_co_var = cv }) = braces (ppr cv)
    
    1715
    +  ppr (CH { ch_co_var = cv }) = braces (ppr cv)
    
    1718 1716
     
    
    1719 1717
     instance Outputable CoercionPlusHoles where
    
    1720 1718
       ppr (CPH { cph_co = co, cph_holes = holes })
    
    ... ... @@ -1723,7 +1721,7 @@ instance Outputable CoercionPlusHoles where
    1723 1721
                            , text "cph_holes =" <+> ppr holes ])
    
    1724 1722
     
    
    1725 1723
     instance Uniquable CoercionHole where
    
    1726
    -  getUnique (CoercionHole { ch_co_var = cv }) = getUnique cv
    
    1724
    +  getUnique (CH { ch_co_var = cv }) = getUnique cv
    
    1727 1725
     
    
    1728 1726
     
    
    1729 1727
     -- | A CoHoleSet stores a set of CoercionHoles that have been used to rewrite
    

  • compiler/GHC/Core/TyCo/Subst.hs
    ... ... @@ -892,8 +892,7 @@ subst_co subst co
    892 892
                      in cos' `seqList` cos'
    
    893 893
     
    
    894 894
         -- See Note [Substituting in a coercion hole]
    
    895
    -    go_hole h@(CoercionHole { ch_co_var = cv })
    
    896
    -      = h { ch_co_var = updateVarType go_ty cv }
    
    895
    +    go_hole h@(CH { ch_co_var = cv }) = h { ch_co_var = updateVarType go_ty cv }
    
    897 896
     
    
    898 897
     -- | Perform a substitution within a 'DVarSet' of free variables,
    
    899 898
     -- returning the shallow free coercion variables.
    

  • compiler/GHC/Core/TyCo/Tidy.hs
    ... ... @@ -357,7 +357,7 @@ tidyCo env co
    357 357
     
    
    358 358
         go_cv cv = tidyTyCoVarOcc env cv
    
    359 359
     
    
    360
    -    go_hole (CoercionHole cv r) = (CoercionHole $! go_cv cv) r
    
    360
    +    go_hole (CH cv r) = (CH $! go_cv cv) r
    
    361 361
         -- Tidy even the holes; tidied types should have tidied kinds
    
    362 362
     
    
    363 363
     tidyCos :: TidyEnv -> [Coercion] -> [Coercion]
    

  • compiler/GHC/Tc/Gen/Expr.hs
    ... ... @@ -199,6 +199,9 @@ tcPolyExprCheck expr res_ty
    199 199
                         -> TcM (HsExpr GhcTc)
    
    200 200
         outer_skolemise (Left ty) thing_inside
    
    201 201
           = do { (wrap, expr') <- tcSkolemiseExpectedType ty thing_inside
    
    202
    +           ; traceTc "outer_skol" (vcat [ text "wrap" <+> ppr wrap
    
    203
    +                                        , text "expr'" <+> ppr expr'
    
    204
    +                                        , text "wrapped" <+> ppr (mkHsWrap wrap expr') ])
    
    202 205
                ; return (mkHsWrap wrap expr') }
    
    203 206
         outer_skolemise (Right sig) thing_inside
    
    204 207
           = do { (wrap, expr') <- tcSkolemiseCompleteSig sig thing_inside
    

  • compiler/GHC/Tc/Solver/Default.hs
    ... ... @@ -272,10 +272,9 @@ unsatisfiableEv_maybe v = (v,) <$> isUnsatisfiableCt_maybe (idType v)
    272 272
     -- solve all the other Wanted constraints, including those nested within
    
    273 273
     -- deeper implications.
    
    274 274
     solveImplicationUsingUnsatGiven :: (EvVar, Type) -> Implication -> TcS Implication
    
    275
    -solveImplicationUsingUnsatGiven
    
    276
    -  unsat_given@(given_ev,_)
    
    275
    +solveImplicationUsingUnsatGiven unsat_given
    
    277 276
       impl@(Implic { ic_wanted = wtd, ic_tclvl = tclvl, ic_binds = ev_binds_var
    
    278
    -               , ic_need_implic = inner, ic_info = skol_info })
    
    277
    +               , ic_info = skol_info })
    
    279 278
       | isCoEvBindsVar ev_binds_var
    
    280 279
       -- We can't use Unsatisfiable evidence in kinds.
    
    281 280
       -- See Note [Coercion evidence only] in GHC.Tc.Types.Evidence.
    
    ... ... @@ -283,9 +282,7 @@ solveImplicationUsingUnsatGiven
    283 282
       | otherwise
    
    284 283
       = do { wcs <- nestImplicTcS skol_info ev_binds_var tclvl $ go_wc wtd
    
    285 284
            ; setImplicationStatus $
    
    286
    -         impl { ic_wanted = wcs
    
    287
    -              , ic_need_implic = inner `extendEvNeedSet` given_ev } }
    
    288
    -                -- Record that the Given is needed; I'm not certain why
    
    285
    +         impl { ic_wanted = wcs } }
    
    289 286
       where
    
    290 287
         go_wc :: WantedConstraints -> TcS WantedConstraints
    
    291 288
         go_wc wc@(WC { wc_simple = wtds, wc_impl = impls })
    

  • compiler/GHC/Tc/Solver/Equality.hs
    ... ... @@ -601,7 +601,7 @@ can_eq_nc_forall ev eq_rel s1 s2
    601 601
                        -- they are kept alive by `neededEvVars`. Admittedly they are free in `all_co`,
    
    602 602
                        -- but only if we zonk it, which `neededEvVars` does not do (see test T7196).
    
    603 603
                       ev_binds_var <- getTcEvBindsVar
    
    604
    -                ; updTcEvBinds ev_binds_var nested_ev_binds_var
    
    604
    +                ; combineTcEvBinds ev_binds_var nested_ev_binds_var
    
    605 605
     
    
    606 606
                     ; setWantedEq orig_dest (CPH { cph_co = all_co, cph_holes = emptyCoHoleSet })
    
    607 607
                          -- emptyCoHoleSet: fully solved, so all_co has no holes
    

  • compiler/GHC/Tc/Solver/Monad.hs
    ... ... @@ -15,7 +15,7 @@ module GHC.Tc.Solver.Monad (
    15 15
         failTcS, warnTcS, addErrTcS, wrapTcS, ctLocWarnTcS,
    
    16 16
         runTcSEqualities,
    
    17 17
         nestTcS, nestImplicTcS, tryShortCutTcS, nestFunDepsTcS,
    
    18
    -    setEvBindsTcS, setTcLevelTcS, updTcEvBinds,
    
    18
    +    setEvBindsTcS, setTcLevelTcS,
    
    19 19
     
    
    20 20
         selectNextWorkItem,
    
    21 21
         getWorkList,
    
    ... ... @@ -58,7 +58,7 @@ module GHC.Tc.Solver.Monad (
    58 58
         getInstEnvs, getFamInstEnvs,                -- Getting the environments
    
    59 59
         getTopEnv, getGblEnv, getLclEnv, setSrcSpan,
    
    60 60
         getTcEvBindsVar, getTcLevel,
    
    61
    -    getTcEvTyCoVars, getTcEvBindsMap, setTcEvBindsMap,
    
    61
    +    getTcEvBindsMap, setTcEvBindsMap, getTcEvBindsState, combineTcEvBinds,
    
    62 62
         tcLookupClass, tcLookupId, tcLookupTyCon,
    
    63 63
     
    
    64 64
         -- Inerts
    
    ... ... @@ -1140,7 +1140,7 @@ csTraceTcM mk_doc
    1140 1140
     {-# INLINE csTraceTcM #-}  -- see Note [INLINE conditional tracing utilities]
    
    1141 1141
     
    
    1142 1142
     runTcS :: TcS a                -- What to run
    
    1143
    -       -> TcM (a, EvBindMap)
    
    1143
    +       -> TcM (a, EvBindsMap)
    
    1144 1144
     runTcS tcs
    
    1145 1145
       = do { ev_binds_var <- TcM.newTcEvBinds
    
    1146 1146
            ; res <- runTcSWithEvBinds ev_binds_var tcs
    
    ... ... @@ -1222,7 +1222,7 @@ runTcSWithEvBinds' mode ev_binds_var thing_inside
    1222 1222
     
    
    1223 1223
     ----------------------------
    
    1224 1224
     #if defined(DEBUG)
    
    1225
    -checkForCyclicBinds :: EvBindMap -> TcM ()
    
    1225
    +checkForCyclicBinds :: EvBindsMap -> TcM ()
    
    1226 1226
     checkForCyclicBinds ev_binds_map
    
    1227 1227
       | null cycles
    
    1228 1228
       = return ()
    
    ... ... @@ -1380,18 +1380,24 @@ tryShortCutTcS (TcS thing_inside)
    1380 1380
                                 , tcs_inerts   = new_inert_var
    
    1381 1381
                                 , tcs_worklist = new_wl_var }
    
    1382 1382
     
    
    1383
    -       ; TcM.traceTc "tryTcS {" $
    
    1383
    +       ; TcM.traceTc "tryShortCutTcS {" $
    
    1384 1384
              vcat [ text "old_ev_binds:" <+> ppr old_ev_binds_var
    
    1385 1385
                   , text "new_ev_binds:" <+> ppr new_ev_binds_var
    
    1386 1386
                   , ppr old_inerts ]
    
    1387 1387
            ; solved <- thing_inside nest_env
    
    1388
    -       ; TcM.traceTc "tryTcS }" (ppr solved)
    
    1388
    +       ; TcM.traceTc "tryShortCutTcS }" (ppr solved)
    
    1389 1389
     
    
    1390 1390
            ; if not solved
    
    1391 1391
              then return False
    
    1392 1392
              else do {  -- Successfully solved
    
    1393 1393
                        -- Add the new bindings to the existing ones
    
    1394
    -                 ; TcM.updTcEvBinds old_ev_binds_var new_ev_binds_var
    
    1394
    +                 ; old_ebvs <- TcM.readTcRef (ebv_binds old_ev_binds_var)
    
    1395
    +
    
    1396
    +                 ; TcM.combineTcEvBinds old_ev_binds_var new_ev_binds_var
    
    1397
    +
    
    1398
    +                 ; final_ebvs <- TcM.readTcRef (ebv_binds old_ev_binds_var)
    
    1399
    +                 ; TcM.traceTc "update" (text "old" <+> ppr old_ebvs $$
    
    1400
    +                                         text "new" <+> ppr final_ebvs)
    
    1395 1401
     
    
    1396 1402
                      -- Update the existing inert set
    
    1397 1403
                      ; new_inerts <- TcM.readTcRef new_inert_var
    
    ... ... @@ -1465,21 +1471,21 @@ getTcEvBindsVar = TcS (return . tcs_ev_binds)
    1465 1471
     getTcLevel :: TcS TcLevel
    
    1466 1472
     getTcLevel = wrapTcS TcM.getTcLevel
    
    1467 1473
     
    
    1468
    -getTcEvTyCoVars :: EvBindsVar -> TcS [TcCoercion]
    
    1469
    -getTcEvTyCoVars ev_binds_var
    
    1470
    -  = wrapTcS $ TcM.getTcEvTyCoVars ev_binds_var
    
    1474
    +getTcEvBindsState :: EvBindsVar -> TcS EvBindsState
    
    1475
    +getTcEvBindsState ev_binds_var
    
    1476
    +  = wrapTcS $ TcM.getTcEvBindsState ev_binds_var
    
    1471 1477
     
    
    1472
    -getTcEvBindsMap :: EvBindsVar -> TcS EvBindMap
    
    1478
    +getTcEvBindsMap :: EvBindsVar -> TcS EvBindsMap
    
    1473 1479
     getTcEvBindsMap ev_binds_var
    
    1474 1480
       = wrapTcS $ TcM.getTcEvBindsMap ev_binds_var
    
    1475 1481
     
    
    1476
    -setTcEvBindsMap :: EvBindsVar -> EvBindMap -> TcS ()
    
    1482
    +setTcEvBindsMap :: EvBindsVar -> EvBindsMap -> TcS ()
    
    1477 1483
     setTcEvBindsMap ev_binds_var binds
    
    1478 1484
       = wrapTcS $ TcM.setTcEvBindsMap ev_binds_var binds
    
    1479 1485
     
    
    1480
    -updTcEvBinds :: EvBindsVar -> EvBindsVar -> TcS ()
    
    1481
    -updTcEvBinds evb nested_evb
    
    1482
    -  = wrapTcS $ TcM.updTcEvBinds evb nested_evb
    
    1486
    +combineTcEvBinds :: EvBindsVar -> EvBindsVar -> TcS ()
    
    1487
    +combineTcEvBinds evb nested_evb
    
    1488
    +  = wrapTcS $ TcM.combineTcEvBinds evb nested_evb
    
    1483 1489
     
    
    1484 1490
     getDefaultInfo ::  TcS (DefaultEnv, Bool)
    
    1485 1491
     getDefaultInfo = wrapTcS TcM.tcGetDefaultTys
    
    ... ... @@ -2029,12 +2035,9 @@ setWantedDict dest canonical tm
    2029 2035
           HoleDest h      -> pprPanic "setWantedEq: HoleDest" (ppr h)
    
    2030 2036
     
    
    2031 2037
     fillCoercionHole :: CoercionHole -> CoercionPlusHoles -> TcS ()
    
    2032
    -fillCoercionHole hole co_plus_holes@(CPH { cph_co = co })
    
    2038
    +fillCoercionHole hole co_plus_holes
    
    2033 2039
       = do { ev_binds_var <- getTcEvBindsVar
    
    2034
    -       ; wrapTcS $ do { -- Record usage of the free vars of this coercion
    
    2035
    -                        TcM.updTcRef (ebv_tcvs ev_binds_var) (co :)
    
    2036
    -                      ; -- Fill the hole
    
    2037
    -                        TcM.fillCoercionHole hole co_plus_holes }
    
    2040
    +       ; wrapTcS $ TcM.addTcEvCoBind ev_binds_var hole co_plus_holes
    
    2038 2041
            ; kickOutAfterFillingCoercionHole hole co_plus_holes }
    
    2039 2042
     
    
    2040 2043
     newTcEvBinds :: TcS EvBindsVar
    

  • compiler/GHC/Tc/Solver/Solve.hs
    ... ... @@ -33,7 +33,6 @@ import qualified GHC.Tc.Zonk.TcType as TcM
    33 33
     import GHC.Core.Predicate
    
    34 34
     import GHC.Core.Reduction
    
    35 35
     import GHC.Core.Coercion
    
    36
    -import GHC.Core.TyCo.FVs( coVarsOfCos )
    
    37 36
     import GHC.Core.Class( classHasSCs )
    
    38 37
     
    
    39 38
     import GHC.Types.Id(  idType )
    
    ... ... @@ -432,12 +431,10 @@ solveImplication imp@(Implic { ic_tclvl = tclvl
    432 431
                                                      , ic_wanted = final_wanted })
    
    433 432
     
    
    434 433
            ; evbinds <- TcS.getTcEvBindsMap ev_binds_var
    
    435
    -       ; tcvs    <- TcS.getTcEvTyCoVars ev_binds_var
    
    436 434
            ; traceTcS "solveImplication end }" $ vcat
    
    437 435
                  [ text "has_given_eqs =" <+> ppr has_given_eqs
    
    438 436
                  , text "res_implic =" <+> ppr res_implic
    
    439
    -             , text "implication evbinds =" <+> ppr (evBindMapBinds evbinds)
    
    440
    -             , text "implication tvcs =" <+> ppr tcvs ]
    
    437
    +             , text "evbinds =" <+> ppr evbinds ]
    
    441 438
     
    
    442 439
            ; return res_implic }
    
    443 440
     
    
    ... ... @@ -460,30 +457,27 @@ setImplicationStatus :: Implication -> TcS Implication
    460 457
     --   * Prune unnecessary evidence bindings
    
    461 458
     --   * Prune unnecessary child implications
    
    462 459
     -- Precondition: the ic_status field is not already IC_Solved
    
    463
    -setImplicationStatus implic@(Implic { ic_status = old_status
    
    464
    -                                    , ic_info   = info
    
    465
    -                                    , ic_wanted = wc })
    
    466
    - = assertPpr (not (isSolvedStatus old_status)) (ppr info) $
    
    467
    -   -- Precondition: we only set the status if it is not already solved
    
    468
    -   do { traceTcS "setImplicationStatus {" (ppr implic)
    
    469
    -
    
    470
    -      ; let solved = isSolvedWC wc
    
    471
    -      ; new_implic    <- neededEvVars implic
    
    472
    -      ; bad_telescope <- if solved then checkBadTelescope implic
    
    473
    -                                   else return False
    
    474
    -
    
    475
    -      ; let new_status | insolubleWC wc = IC_Insoluble
    
    476
    -                       | not solved     = IC_Unsolved
    
    477
    -                       | bad_telescope  = IC_BadTelescope
    
    478
    -                       | otherwise      = IC_Solved { ics_dead = dead_givens }
    
    479
    -            dead_givens = findRedundantGivens new_implic
    
    480
    -            new_wc      = pruneImplications wc
    
    481
    -
    
    482
    -            final_implic = new_implic { ic_status = new_status
    
    483
    -                                      , ic_wanted = new_wc }
    
    484
    -
    
    485
    -      ; traceTcS "setImplicationStatus }" (ppr final_implic)
    
    486
    -      ; return final_implic }
    
    460
    +setImplicationStatus implic@(Implic { ic_wanted = wc })
    
    461
    + | insolubleWC wc
    
    462
    + = do { traceTcS "setImplicationStatus:insoluble {" (ppr implic)
    
    463
    +      ; return (implic { ic_status = IC_Insoluble }) }
    
    464
    +
    
    465
    + | not (isSolvedWC wc)
    
    466
    + = -- Precondition: we only set the status if it is not /already/ solved
    
    467
    +   do { traceTcS "setImplicationStatus:in progress {" (ppr implic)
    
    468
    +      ; return (implic { ic_status = IC_Unsolved }) }
    
    469
    +
    
    470
    + | otherwise  -- The Wanteds are all solved
    
    471
    + = do { traceTcS "setImplicationStatus:solved {" (ppr implic)
    
    472
    +      ; bad_telescope <- checkBadTelescope implic
    
    473
    +      ; if bad_telescope
    
    474
    +        then return (implic { ic_status = IC_BadTelescope })
    
    475
    +        else
    
    476
    +
    
    477
    +   do { solved_status <- computeSolvedStatus implic
    
    478
    +      ; let pruned_wc = pruneImplications wc
    
    479
    +      ; return (implic { ic_status = solved_status
    
    480
    +                       , ic_wanted = pruned_wc }) } }
    
    487 481
     
    
    488 482
     pruneImplications :: WantedConstraints -> WantedConstraints
    
    489 483
     -- We have now recorded the `ic_need` variables of the child
    
    ... ... @@ -502,8 +496,8 @@ pruneImplications wc@(WC { wc_impl = implics })
    502 496
           | otherwise
    
    503 497
           = True        -- Otherwise, keep it
    
    504 498
     
    
    505
    -findRedundantGivens :: Implication -> [EvVar]
    
    506
    -findRedundantGivens (Implic { ic_info = info, ic_need = need, ic_given = givens })
    
    499
    +findRedundantGivens :: SkolemInfoAnon -> NeededEvIds -> [EvVar] -> [EvVar]
    
    500
    +findRedundantGivens info need givens
    
    507 501
       | not (warnRedundantGivens info)   -- Don't report redundant constraints at all
    
    508 502
       = []                    -- See (TRC4) of Note [Tracking redundant constraints]
    
    509 503
     
    
    ... ... @@ -520,9 +514,8 @@ findRedundantGivens (Implic { ic_info = info, ic_need = need, ic_given = givens
    520 514
     
    
    521 515
         unused_givens = filterOut is_used givens
    
    522 516
     
    
    523
    -    needed_givens_ignoring_default_methods = ens_fvs need
    
    524 517
         is_used given =  is_type_error given
    
    525
    -                  || given `elemVarSet` needed_givens_ignoring_default_methods
    
    518
    +                  || given `elemVarSet` need
    
    526 519
                       || (in_instance_decl && is_improving (idType given))
    
    527 520
     
    
    528 521
         minimal_givens = mkMinimalBySCs evVarPred givens  -- See (TRC2)
    
    ... ... @@ -611,113 +604,105 @@ checkBadTelescope (Implic { ic_info = info
    611 604
           | otherwise
    
    612 605
           = go (later_skols `extendVarSet` one_skol) earlier_skols
    
    613 606
     
    
    614
    -neededEvVars :: Implication -> TcS Implication
    
    615
    --- Find all the evidence variables that are "needed",
    
    616
    --- /and/ delete dead evidence bindings
    
    607
    +computeSolvedStatus :: Implication -> TcS ImplicStatus
    
    608
    +-- Given a fully-solved implication,
    
    609
    +--    - Figure out the right IC_Solved fields
    
    610
    +--    - Delete unused evidence bindings
    
    617 611
     --
    
    618 612
     --   See Note [Tracking redundant constraints]
    
    619 613
     --   See Note [Delete dead Given evidence bindings]
    
    620
    ---
    
    621
    ---   - Start from initial_seeds (from nested implications)
    
    622
    ---
    
    623
    ---   - Add free vars of RHS of all Wanted evidence bindings
    
    624
    ---     and coercion variables accumulated in tcvs (all Wanted)
    
    625
    ---
    
    626
    ---   - Generate 'needed', the needed set of EvVars, by doing transitive
    
    627
    ---     closure through Given bindings
    
    628
    ---     e.g.   Needed {a,b}
    
    629
    ---            Given  a = sc_sel a2
    
    630
    ---            Then a2 is needed too
    
    631
    ---
    
    632
    ---   - Prune out all Given bindings that are not needed
    
    633
    -
    
    634
    -neededEvVars implic@(Implic { ic_info        = info
    
    614
    +computeSolvedStatus (Implic { ic_info        = info
    
    635 615
                                 , ic_binds       = ev_binds_var
    
    636
    -                            , ic_wanted      = WC { wc_impl = implics }
    
    637
    -                            , ic_need_implic = old_need_implic    -- See (TRC1)
    
    638
    -                    })
    
    639
    - = do { ev_binds <- TcS.getTcEvBindsMap ev_binds_var
    
    640
    -      ; used_cos <- TcS.getTcEvTyCoVars ev_binds_var
    
    641
    -
    
    642
    -      ; let -- Find the variables needed by `implics`
    
    643
    -            new_need_implic@(ENS { ens_dms = dm_seeds, ens_fvs = other_seeds })
    
    644
    -                = foldr add_implic old_need_implic implics
    
    645
    -                  -- Start from old_need_implic!  See (TRC1)
    
    646
    -
    
    647
    -            -- Get the variables needed by the solved bindings
    
    648
    -            -- (It's OK to use a non-deterministic fold here
    
    649
    -            --  because add_wanted is commutative.)
    
    650
    -            used_covars = coVarsOfCos used_cos
    
    651
    -            seeds_w = nonDetStrictFoldEvBindMap add_wanted used_covars ev_binds
    
    652
    -
    
    653
    -            need_ignoring_dms = findNeededGivenEvVars ev_binds (other_seeds `unionVarSet` seeds_w)
    
    654
    -            need_from_dms     = findNeededGivenEvVars ev_binds dm_seeds
    
    655
    -            need_full         = need_ignoring_dms `unionVarSet` need_from_dms
    
    656
    -
    
    657
    -            -- `need`: the Givens from outer scopes that are used in this implication
    
    658
    -            -- is_dm_skol: see (TRC5)
    
    659
    -            need | is_dm_skol info = ENS { ens_dms = trim ev_binds need_full
    
    660
    -                                         , ens_fvs = emptyVarSet }
    
    661
    -                 | otherwise       = ENS { ens_dms = trim ev_binds need_from_dms
    
    662
    -                                         , ens_fvs = trim ev_binds need_ignoring_dms }
    
    663
    -
    
    664
    -      -- Delete dead Given evidence bindings
    
    616
    +                            , ic_given       = givens
    
    617
    +                            , ic_wanted      = WC { wc_impl = implics } })
    
    618
    + = do { ev_binds_state <- TcS.getTcEvBindsState ev_binds_var
    
    619
    +
    
    620
    +      ; let EBS { ebs_binds = ev_binds, ebs_needs = local_needs } = ev_binds_state
    
    621
    +
    
    622
    +            -- Gather the raw needed EvIds, from the
    
    623
    +            -- current evidence bindings `local_needs`, and the `implics`
    
    624
    +            (need_dm, need_non_dm) = foldr add_implic (emptyVarSet, local_needs) implics
    
    625
    +
    
    626
    +            -- Do transitive closure through the evidence bindings
    
    627
    +            -- and delete all EvIds bound by the bindings
    
    628
    +            need_dm1     = findNeededGivenEvVars ev_binds need_dm
    
    629
    +            need_non_dm1 = findNeededGivenEvVars ev_binds need_non_dm
    
    630
    +
    
    631
    +            -- Compute the redundant Givens
    
    632
    +            dead_givens = findRedundantGivens info need_non_dm1 givens
    
    633
    +
    
    634
    +            -- Delete variables bound by ev_binds or by givens
    
    635
    +            need_dm2     = trim_needs need_dm1
    
    636
    +            need_non_dm2 = trim_needs need_non_dm1
    
    637
    +
    
    638
    +            trim_needs :: NeededEvIds -> NeededEvIds
    
    639
    +            trim_needs needs = (needs `varSetMinusEvBindsMap` ev_binds)
    
    640
    +                               `delVarSetList` givens
    
    641
    +
    
    642
    +      -- Prune dead Given evidence bindings
    
    665 643
           -- See Note [Delete dead Given evidence bindings]
    
    666
    -      ; let live_ev_binds = filterEvBindMap (needed_ev_bind need_full) ev_binds
    
    667
    -      ; TcS.setTcEvBindsMap ev_binds_var live_ev_binds
    
    668
    -
    
    669
    -      ; traceTcS "neededEvVars" $
    
    670
    -        vcat [ text "old_need_implic:" <+> ppr old_need_implic
    
    671
    -             , text "new_need_implic:" <+> ppr new_need_implic
    
    672
    -             , text "used_covars:" <+> ppr used_covars
    
    673
    -             , text "need_ignoring_dms:" <+> ppr need_ignoring_dms
    
    674
    -             , text "need_from_dms:"     <+> ppr need_from_dms
    
    675
    -             , text "need:" <+> ppr need
    
    644
    +      ; let need_full       = need_dm1 `unionVarSet` need_non_dm1
    
    645
    +            pruned_ev_binds = filterEvBindsMap (keep_ev_bind need_full) ev_binds
    
    646
    +      ; TcS.setTcEvBindsMap ev_binds_var pruned_ev_binds
    
    647
    +
    
    648
    +      ; traceTcS "computeSolvedStatus" $
    
    649
    +        vcat [ text "local_needs:" <+> ppr local_needs
    
    650
    +             , text "need_dm:" <+> ppr need_dm
    
    651
    +             , text "need_non_dm:" <+> ppr need_non_dm
    
    652
    +             , text "need_dm1:" <+> ppr need_dm1
    
    653
    +             , text "need_non_dm1:" <+> ppr need_non_dm1
    
    654
    +             , text "need_dm2:" <+> ppr need_dm2
    
    655
    +             , text "need_non_dm2:" <+> ppr need_non_dm2
    
    676 656
                  , text "ev_binds:" <+> ppr ev_binds
    
    677
    -             , text "live_ev_binds:" <+> ppr live_ev_binds ]
    
    678
    -      ; return (implic { ic_need        = need
    
    679
    -                       , ic_need_implic = new_need_implic }) }
    
    680
    - where
    
    681
    -    trim :: EvBindMap -> VarSet -> VarSet
    
    682
    -    -- Delete variables bound by Givens or bindings
    
    683
    -    trim ev_binds needs = needs `varSetMinusEvBindMap` ev_binds
    
    657
    +             , text "deleted ev_binds:"
    
    658
    +               <+> ppr (filterEvBindsMap (not . keep_ev_bind need_full) ev_binds) ]
    
    684 659
     
    
    685
    -    add_implic :: Implication -> EvNeedSet -> EvNeedSet
    
    686
    -    add_implic (Implic { ic_given = givens, ic_need = need }) acc
    
    687
    -       = (need `delGivensFromEvNeedSet` givens) `unionEvNeedSet` acc
    
    660
    +      ; if is_dm_skol info
    
    661
    +        then return (IC_Solved { ics_dead   = dead_givens
    
    662
    +                               , ics_dm     = need_dm2 `unionVarSet` need_non_dm2
    
    663
    +                               , ics_non_dm = emptyVarSet })
    
    688 664
     
    
    689
    -    needed_ev_bind needed (EvBind { eb_lhs = ev_var, eb_info = info })
    
    665
    +        else return (IC_Solved { ics_dead   = dead_givens
    
    666
    +                               , ics_dm     = need_dm2
    
    667
    +                               , ics_non_dm = need_non_dm2 }) }
    
    668
    + where
    
    669
    +    add_implic :: Implication -> (NeededEvIds, NeededEvIds) -> (NeededEvIds, NeededEvIds)
    
    670
    +    add_implic (Implic { ic_status = status}) (dm2, non_dm2)
    
    671
    +       | IC_Solved { ics_dm = dm1, ics_non_dm = non_dm1 } <- status
    
    672
    +       = (dm1 `unionVarSet` dm2, non_dm1 `unionVarSet` non_dm2)
    
    673
    +       | otherwise
    
    674
    +       = pprPanic "computeSolvedStatus" (ppr implics)
    
    675
    +
    
    676
    +    keep_ev_bind :: NeededEvIds -> EvBind -> Bool
    
    677
    +    -- False => we can discard this unused Given evidence binding
    
    678
    +    -- We always keep all the Wanted bindings
    
    679
    +    keep_ev_bind needed (EvBind { eb_lhs = ev_var, eb_info = info })
    
    690 680
           | EvBindGiven{} <- info = ev_var `elemVarSet` needed
    
    691 681
           | otherwise             = True   -- Keep all wanted bindings
    
    692 682
     
    
    693
    -    add_wanted :: EvBind -> VarSet -> VarSet
    
    694
    -    add_wanted (EvBind { eb_info = info, eb_rhs = rhs }) needs
    
    695
    -      | EvBindGiven{} <- info = needs  -- Add the rhs vars of the Wanted bindings only
    
    696
    -      | otherwise = nestedEvIdsOfTerm rhs `unionVarSet` needs
    
    697
    -
    
    698 683
         is_dm_skol :: SkolemInfoAnon -> Bool
    
    699 684
         is_dm_skol (MethSkol _ is_dm) = is_dm
    
    700 685
         is_dm_skol _                  = False
    
    701 686
     
    
    702
    -findNeededGivenEvVars :: EvBindMap -> VarSet -> VarSet
    
    687
    +findNeededGivenEvVars :: EvBindsMap -> NeededEvIds -> NeededEvIds
    
    703 688
     -- Find all the Given evidence needed by seeds,
    
    704 689
     -- looking transitively through bindings for Givens (only)
    
    705 690
     findNeededGivenEvVars ev_binds seeds
    
    706 691
       = transCloVarSet also_needs seeds
    
    707 692
       where
    
    708
    -   also_needs :: VarSet -> VarSet
    
    709
    -   also_needs needs = nonDetStrictFoldUniqSet add emptyVarSet needs
    
    710
    -     -- It's OK to use a non-deterministic fold here because we immediately
    
    711
    -     -- forget about the ordering by creating a set
    
    712
    -
    
    713
    -   add :: Var -> VarSet -> VarSet
    
    714
    -   add v needs
    
    715
    -     | Just ev_bind <- lookupEvBind ev_binds v
    
    716
    -     , EvBind { eb_info = EvBindGiven, eb_rhs = rhs } <- ev_bind
    
    717
    -       -- Look at Given bindings only
    
    718
    -     = nestedEvIdsOfTerm rhs `unionVarSet` needs
    
    719
    -     | otherwise
    
    720
    -     = needs
    
    693
    +    also_needs :: VarSet -> VarSet
    
    694
    +    also_needs needs = nonDetStrictFoldUniqSet add emptyVarSet needs
    
    695
    +      -- It's OK to use a non-deterministic fold here because we immediately
    
    696
    +      -- forget about the ordering by creating a set
    
    697
    +
    
    698
    +    add :: Var -> VarSet -> VarSet
    
    699
    +    add v needs
    
    700
    +      | Just ev_bind <- lookupEvBind ev_binds v
    
    701
    +      , EvBind { eb_info = EvBindGiven, eb_rhs = rhs } <- ev_bind
    
    702
    +        -- Look at Given bindings only
    
    703
    +      = nestedEvIdsOfTerm rhs `unionVarSet` needs
    
    704
    +      | otherwise
    
    705
    +      = needs
    
    721 706
     
    
    722 707
     -------------------------------------------------
    
    723 708
     simplifyDelayedErrors :: Bag DelayedError -> TcS (Bag DelayedError)
    
    ... ... @@ -949,7 +934,7 @@ Wrinkles:
    949 934
          and because of the degnerate instance for `Show (T a)`, we don't need the `Eq a`
    
    950 935
          constraint.  But we don't want to report it as redundant!
    
    951 936
     
    
    952
    -(TRC5) Consider this (#25992), where `op2` has a default method
    
    937
    +(TRC5) Default methods.  Consider this (#25992), where `op2` has a default method
    
    953 938
             class C a where { op1, op2 :: a -> a
    
    954 939
                             ; op2 = op1 . op1 }
    
    955 940
             instance C a => C [a] where
    
    ... ... @@ -960,10 +945,12 @@ Wrinkles:
    960 945
             $dmop2 = op1 . op1
    
    961 946
     
    
    962 947
             $fCList :: forall a. C a => C [a]
    
    963
    -        $fCList @a (d::C a) = MkC (\(x:a).x) ($dmop2 @a d)
    
    948
    +        $fCList @a (d::C a) = MkC (\(x:a).x)
    
    949
    +                                  ($dmop2 @[a] ($fCList @a d))
    
    964 950
     
    
    965
    -   Notice that `d` gets passed to `$dmop`: it is "needed".  But it's only
    
    966
    -   /really/ needed if some /other/ method (in this case `op1`) uses it.
    
    951
    +   Notice that `d` gets passed, indirectly to `$dmop`: it appears to be
    
    952
    +   "needed".  But it's only /really/ needed if some /other/ method or
    
    953
    +   superclass (in this case `op1`) uses it.
    
    967 954
     
    
    968 955
        So, rather than one set of "needed Givens" we use `EvNeedSet` to track
    
    969 956
        a /pair/ of sets:
    
    ... ... @@ -1645,10 +1632,12 @@ solveWantedQCI mode ct@(CQuantCan (QCI { qci_ev = ev, qci_tvs = tvs
    1645 1632
                   --     carrying a record of which evidence variables are used
    
    1646 1633
                   --     See Note [Free vars of EvFun] in GHC.Tc.Types.Evidence
    
    1647 1634
                  do { setWantedDict dest EvCanonical $
    
    1648
    -                  EvFun { et_tvs = skol_tvs, et_given = given_ev_vars
    
    1635
    +                  EvFun { et_tvs   = skol_tvs
    
    1636
    +                        , et_given = given_ev_vars
    
    1649 1637
                             , et_binds = TcEvBinds ev_binds_var
    
    1650
    -                        , et_body = wantedCtEvEvId wanted_ev }
    
    1638
    +                        , et_body  = wantedCtEvEvId wanted_ev }
    
    1651 1639
     
    
    1640
    +                ; traceTcS "solveWantedQCI" (ppr imp')
    
    1652 1641
                     ; return (Right imp') }
    
    1653 1642
         }
    
    1654 1643
     
    

  • compiler/GHC/Tc/Types/Constraint.hs
    ... ... @@ -65,7 +65,6 @@ module GHC.Tc.Types.Constraint (
    65 65
             ImplicStatus(..), isInsolubleStatus, isSolvedStatus,
    
    66 66
             UserGiven, getGivensFromImplics,
    
    67 67
             HasGivenEqs(..), checkImplicationInvariants,
    
    68
    -        EvNeedSet(..), emptyEvNeedSet, unionEvNeedSet, extendEvNeedSet, delGivensFromEvNeedSet,
    
    69 68
     
    
    70 69
             -- CtLocEnv
    
    71 70
             CtLocEnv(..), setCtLocEnvLoc, setCtLocEnvLvl, getCtLocEnvLoc, getCtLocEnvLvl, ctLocEnvInGeneratedCode,
    
    ... ... @@ -1564,45 +1563,9 @@ data Implication
    1564 1563
           ic_binds  :: EvBindsVar,    -- Points to the place to fill in the
    
    1565 1564
                                       -- abstraction and bindings.
    
    1566 1565
     
    
    1567
    -      -- The ic_need fields keep track of which Given evidence
    
    1568
    -      -- is used by this implication or its children
    
    1569
    -      -- See Note [Tracking redundant constraints]
    
    1570
    -      -- NB: these sets include stuff used by fully-solved nested implications
    
    1571
    -      --     that have since been discarded
    
    1572
    -      ic_need  :: EvNeedSet,        -- All needed Given evidence, from this implication
    
    1573
    -                                    --   or outer ones
    
    1574
    -                                    -- That is, /after/ deleting the binders of ic_binds,
    
    1575
    -                                    --   but /before/ deleting ic_givens
    
    1576
    -
    
    1577
    -      ic_need_implic :: EvNeedSet,  -- Union of of the ic_need of all implications in ic_wanted
    
    1578
    -                                    -- /including/ any fully-solved implications that have been
    
    1579
    -                                    -- discarded by `pruneImplications`.  This discarding is why
    
    1580
    -                                    -- we need to keep this field in the first place.
    
    1581
    -
    
    1582 1566
           ic_status   :: ImplicStatus
    
    1583 1567
         }
    
    1584 1568
     
    
    1585
    -data EvNeedSet = ENS { ens_dms :: VarSet   -- Needed only by default methods
    
    1586
    -                     , ens_fvs :: VarSet   -- Needed by things /other than/ default methods
    
    1587
    -                       -- See (TRC5) in Note [Tracking redundant constraints]
    
    1588
    -                 }
    
    1589
    -
    
    1590
    -emptyEvNeedSet :: EvNeedSet
    
    1591
    -emptyEvNeedSet = ENS { ens_dms = emptyVarSet, ens_fvs = emptyVarSet }
    
    1592
    -
    
    1593
    -unionEvNeedSet :: EvNeedSet -> EvNeedSet -> EvNeedSet
    
    1594
    -unionEvNeedSet (ENS { ens_dms = dm1, ens_fvs = fv1 })
    
    1595
    -               (ENS { ens_dms = dm2, ens_fvs = fv2 })
    
    1596
    -  = ENS { ens_dms = dm1 `unionVarSet` dm2, ens_fvs = fv1 `unionVarSet` fv2 }
    
    1597
    -
    
    1598
    -extendEvNeedSet :: EvNeedSet -> Var -> EvNeedSet
    
    1599
    -extendEvNeedSet ens@(ENS { ens_fvs = fvs }) v = ens { ens_fvs = fvs `extendVarSet` v }
    
    1600
    -
    
    1601
    -delGivensFromEvNeedSet :: EvNeedSet -> [Var] -> EvNeedSet
    
    1602
    -delGivensFromEvNeedSet (ENS { ens_dms = dms, ens_fvs = fvs }) givens
    
    1603
    -  = ENS { ens_dms = dms `delVarSetList` givens
    
    1604
    -        , ens_fvs = fvs `delVarSetList` givens }
    
    1605
    -
    
    1606 1569
     implicationPrototype :: CtLocEnv -> Implication
    
    1607 1570
     implicationPrototype ct_loc_env
    
    1608 1571
        = Implic { -- These fields must be initialised
    
    ... ... @@ -1619,14 +1582,21 @@ implicationPrototype ct_loc_env
    1619 1582
                 , ic_given       = []
    
    1620 1583
                 , ic_wanted      = emptyWC
    
    1621 1584
                 , ic_given_eqs   = MaybeGivenEqs
    
    1622
    -            , ic_status      = IC_Unsolved
    
    1623
    -            , ic_need        = emptyEvNeedSet
    
    1624
    -            , ic_need_implic = emptyEvNeedSet }
    
    1585
    +            , ic_status      = IC_Unsolved }
    
    1625 1586
     
    
    1626 1587
     data ImplicStatus
    
    1627 1588
       = IC_Solved     -- All wanteds in the tree are solved, all the way down
    
    1628
    -       { ics_dead :: [EvVar] }  -- Subset of ic_given that are not needed
    
    1629
    -         -- See Note [Tracking redundant constraints] in GHC.Tc.Solver
    
    1589
    +       { ics_dead   :: [EvVar]     -- Subset of ic_given that are not needed
    
    1590
    +
    
    1591
    +       , ics_dm     :: NeededEvIds -- Enclosing Given EvIds that are needed by
    
    1592
    +                                   -- calls to default methods (typically empty)
    
    1593
    +
    
    1594
    +       , ics_non_dm :: NeededEvIds -- Enclosing Given EvIds that are needed, other than
    
    1595
    +                                   -- calls to default methods
    
    1596
    +       }
    
    1597
    +      -- Reporting redundant givens: use ics_non_dm
    
    1598
    +      -- Pruning evidence bindings:  use ics_dm `union` ics_non_dm
    
    1599
    +      -- See Note [Tracking redundant constraints] in GHC.Tc.Solver
    
    1630 1600
     
    
    1631 1601
       | IC_Insoluble  -- At least one insoluble Wanted constraint in the tree
    
    1632 1602
     
    
    ... ... @@ -1715,7 +1685,6 @@ instance Outputable Implication where
    1715 1685
                   , ic_given = given, ic_given_eqs = given_eqs
    
    1716 1686
                   , ic_wanted = wanted, ic_status = status
    
    1717 1687
                   , ic_binds = binds
    
    1718
    -              , ic_need = need, ic_need_implic = need_implic
    
    1719 1688
                   , ic_info = info })
    
    1720 1689
        = hang (text "Implic" <+> lbrace)
    
    1721 1690
             2 (sep [ text "TcLevel =" <+> ppr tclvl
    
    ... ... @@ -1725,21 +1694,17 @@ instance Outputable Implication where
    1725 1694
                    , hang (text "Given =")  2 (pprEvVars given)
    
    1726 1695
                    , hang (text "Wanted =") 2 (ppr wanted)
    
    1727 1696
                    , text "Binds =" <+> ppr binds
    
    1728
    -               , text "need =" <+> ppr need
    
    1729
    -               , text "need_implic =" <+> ppr need_implic
    
    1730 1697
                    , pprSkolInfo info ] <+> rbrace)
    
    1731 1698
     
    
    1732
    -instance Outputable EvNeedSet where
    
    1733
    -  ppr (ENS { ens_dms = dms, ens_fvs = fvs })
    
    1734
    -    = text "ENS" <> braces (sep [text "ens_dms =" <+> ppr dms
    
    1735
    -                                , text "ens_fvs =" <+> ppr fvs])
    
    1736
    -
    
    1737 1699
     instance Outputable ImplicStatus where
    
    1738 1700
       ppr IC_Insoluble    = text "Insoluble"
    
    1739 1701
       ppr IC_BadTelescope = text "Bad telescope"
    
    1740 1702
       ppr IC_Unsolved     = text "Unsolved"
    
    1741
    -  ppr (IC_Solved { ics_dead = dead })
    
    1742
    -    = text "Solved" <+> (braces (text "Dead givens =" <+> ppr dead))
    
    1703
    +  ppr (IC_Solved { ics_dead = dead, ics_dm = dm, ics_non_dm = non_dm })
    
    1704
    +    = text "Solved" <> (braces $
    
    1705
    +      vcat [ text "Dead givens =" <+> ppr dead
    
    1706
    +           , text "need_dm =" <+> ppr dm
    
    1707
    +           , text "need_non_dm =" <+> ppr non_dm ])
    
    1743 1708
     
    
    1744 1709
     checkTelescopeSkol :: SkolemInfoAnon -> Bool
    
    1745 1710
     -- See Note [Checking telescopes]
    

  • compiler/GHC/Tc/Types/Evidence.hs
    ... ... @@ -14,14 +14,15 @@ module GHC.Tc.Types.Evidence (
    14 14
       optSubTypeHsWrapper,
    
    15 15
     
    
    16 16
       -- * Evidence bindings
    
    17
    -  TcEvBinds(..), EvBindsVar(..),
    
    18
    -  EvBindMap(..), emptyEvBindMap, extendEvBinds, unionEvBindMap,
    
    17
    +  TcEvBinds(..), EvBindsVar(..), NeededEvIds,
    
    18
    +  EvBindsState(..), emptyEvBindsState, unionEvBindsState, addCoVarsEBS,
    
    19
    +  EvBindsMap(..), emptyEvBindsMap, extendEvBinds, unionEvBindsMap,
    
    19 20
       lookupEvBind, evBindMapBinds,
    
    20
    -  foldEvBindMap, nonDetStrictFoldEvBindMap,
    
    21
    -  filterEvBindMap,
    
    22
    -  isEmptyEvBindMap,
    
    21
    +  foldEvBindsMap, nonDetStrictFoldEvBindsMap,
    
    22
    +  filterEvBindsMap,
    
    23
    +  isEmptyEvBindsMap,
    
    23 24
       evBindMapToVarSet,
    
    24
    -  varSetMinusEvBindMap,
    
    25
    +  varSetMinusEvBindsMap,
    
    25 26
       EvBindInfo(..), EvBind(..), emptyTcEvBinds, isEmptyTcEvBinds, mkGivenEvBind, mkWantedEvBind,
    
    26 27
       evBindVar, isCoEvBindsVar,
    
    27 28
     
    
    ... ... @@ -725,12 +726,12 @@ data EvBindsVar
    725 726
           ebv_uniq :: Unique,
    
    726 727
              -- The Unique is for debug printing only
    
    727 728
     
    
    728
    -      ebv_binds :: IORef EvBindMap,
    
    729
    +      ebv_binds :: IORef EvBindsState
    
    729 730
           -- The main payload: the value-level evidence bindings
    
    730 731
           --     (dictionaries etc)
    
    731 732
           -- Some Given, some Wanted
    
    732 733
     
    
    733
    -      ebv_tcvs :: IORef [TcCoercion]
    
    734
    +--      ebv_needs :: IORef VarSet
    
    734 735
           -- When we solve a Wanted by filling in a CoercionHole, it is as
    
    735 736
           -- if we were adding an evidence binding
    
    736 737
           --       co_hole := coercion
    
    ... ... @@ -745,10 +746,35 @@ data EvBindsVar
    745 746
       | CoEvBindsVar {  -- See Note [Coercion evidence only]
    
    746 747
     
    
    747 748
           -- See above for comments on ebv_uniq, ebv_tcvs
    
    748
    -      ebv_uniq :: Unique,
    
    749
    -      ebv_tcvs :: IORef [TcCoercion]
    
    749
    +      ebv_uniq  :: Unique,
    
    750
    +      ebv_needs :: IORef NeededEvIds
    
    750 751
         }
    
    751 752
     
    
    753
    +type NeededEvIds = VarSet
    
    754
    +
    
    755
    +data EvBindsState = EBS { ebs_binds :: EvBindsMap
    
    756
    +                        , ebs_needs :: NeededEvIds }
    
    757
    +
    
    758
    +emptyEvBindsState :: EvBindsState
    
    759
    +emptyEvBindsState = EBS { ebs_binds = emptyEvBindsMap
    
    760
    +                        , ebs_needs = emptyVarSet }
    
    761
    +
    
    762
    +unionEvBindsState :: EvBindsState -> EvBindsState -> EvBindsState
    
    763
    +unionEvBindsState (EBS { ebs_binds = bs1, ebs_needs = n1 })
    
    764
    +                  (EBS { ebs_binds = bs2, ebs_needs = n2 })
    
    765
    +  = EBS { ebs_binds = bs1 `unionEvBindsMap` bs2
    
    766
    +        , ebs_needs = n1  `unionVarSet`    n2 }
    
    767
    +
    
    768
    +addCoVarsEBS :: VarSet -> EvBindsState -> EvBindsState
    
    769
    +addCoVarsEBS n1 ebs@(EBS { ebs_needs = n2 })
    
    770
    +  = ebs { ebs_needs = n1 `unionVarSet` n2 }
    
    771
    +
    
    772
    +instance Outputable EvBindsState where
    
    773
    +  ppr (EBS { ebs_binds = bs, ebs_needs = needs })
    
    774
    +    = text "EBS" <> (braces $
    
    775
    +        sep [ text "needs =" <+> ppr needs
    
    776
    +            , text "binds =" <+> ppr bs ])
    
    777
    +
    
    752 778
     instance Data.Data TcEvBinds where
    
    753 779
       -- Placeholder; we can't traverse into TcEvBinds
    
    754 780
       toConstr _   = abstractConstr "TcEvBinds"
    
    ... ... @@ -778,8 +804,8 @@ isCoEvBindsVar (CoEvBindsVar {}) = True
    778 804
     isCoEvBindsVar (EvBindsVar {})   = False
    
    779 805
     
    
    780 806
     -----------------
    
    781
    -newtype EvBindMap
    
    782
    -  = EvBindMap {
    
    807
    +newtype EvBindsMap
    
    808
    +  = EvBindsMap {
    
    783 809
            ev_bind_varenv :: DVarEnv EvBind
    
    784 810
         }       -- Map from evidence variables to evidence terms
    
    785 811
                 -- We use @DVarEnv@ here to get deterministic ordering when we
    
    ... ... @@ -801,50 +827,50 @@ newtype EvBindMap
    801 827
                 -- See Note [Deterministic UniqFM] in GHC.Types.Unique.DFM for explanation why
    
    802 828
                 -- @UniqFM@ can lead to nondeterministic order.
    
    803 829
     
    
    804
    -emptyEvBindMap :: EvBindMap
    
    805
    -emptyEvBindMap = EvBindMap { ev_bind_varenv = emptyDVarEnv }
    
    830
    +emptyEvBindsMap :: EvBindsMap
    
    831
    +emptyEvBindsMap = EvBindsMap { ev_bind_varenv = emptyDVarEnv }
    
    806 832
     
    
    807
    -extendEvBinds :: EvBindMap -> EvBind -> EvBindMap
    
    833
    +extendEvBinds :: EvBindsMap -> EvBind -> EvBindsMap
    
    808 834
     extendEvBinds bs ev_bind
    
    809
    -  = EvBindMap { ev_bind_varenv = extendDVarEnv (ev_bind_varenv bs)
    
    835
    +  = EvBindsMap { ev_bind_varenv = extendDVarEnv (ev_bind_varenv bs)
    
    810 836
                                                    (eb_lhs ev_bind)
    
    811 837
                                                    ev_bind }
    
    812 838
     
    
    813 839
     -- | Union two evidence binding maps
    
    814
    -unionEvBindMap :: EvBindMap -> EvBindMap -> EvBindMap
    
    815
    -unionEvBindMap (EvBindMap env1) (EvBindMap env2) =
    
    816
    -  EvBindMap { ev_bind_varenv = plusDVarEnv env1 env2 }
    
    840
    +unionEvBindsMap :: EvBindsMap -> EvBindsMap -> EvBindsMap
    
    841
    +unionEvBindsMap (EvBindsMap env1) (EvBindsMap env2) =
    
    842
    +  EvBindsMap { ev_bind_varenv = plusDVarEnv env1 env2 }
    
    817 843
     
    
    818
    -isEmptyEvBindMap :: EvBindMap -> Bool
    
    819
    -isEmptyEvBindMap (EvBindMap m) = isEmptyDVarEnv m
    
    844
    +isEmptyEvBindsMap :: EvBindsMap -> Bool
    
    845
    +isEmptyEvBindsMap (EvBindsMap m) = isEmptyDVarEnv m
    
    820 846
     
    
    821
    -lookupEvBind :: EvBindMap -> EvVar -> Maybe EvBind
    
    847
    +lookupEvBind :: EvBindsMap -> EvVar -> Maybe EvBind
    
    822 848
     lookupEvBind bs = lookupDVarEnv (ev_bind_varenv bs)
    
    823 849
     
    
    824
    -evBindMapBinds :: EvBindMap -> Bag EvBind
    
    825
    -evBindMapBinds = foldEvBindMap consBag emptyBag
    
    850
    +evBindMapBinds :: EvBindsMap -> Bag EvBind
    
    851
    +evBindMapBinds = foldEvBindsMap consBag emptyBag
    
    826 852
     
    
    827
    -foldEvBindMap :: (EvBind -> a -> a) -> a -> EvBindMap -> a
    
    828
    -foldEvBindMap k z bs = foldDVarEnv k z (ev_bind_varenv bs)
    
    853
    +foldEvBindsMap :: (EvBind -> a -> a) -> a -> EvBindsMap -> a
    
    854
    +foldEvBindsMap k z bs = foldDVarEnv k z (ev_bind_varenv bs)
    
    829 855
     
    
    830 856
     -- See Note [Deterministic UniqFM] to learn about nondeterminism.
    
    831 857
     -- If you use this please provide a justification why it doesn't introduce
    
    832 858
     -- nondeterminism.
    
    833
    -nonDetStrictFoldEvBindMap :: (EvBind -> a -> a) -> a -> EvBindMap -> a
    
    834
    -nonDetStrictFoldEvBindMap k z bs = nonDetStrictFoldDVarEnv k z (ev_bind_varenv bs)
    
    859
    +nonDetStrictFoldEvBindsMap :: (EvBind -> a -> a) -> a -> EvBindsMap -> a
    
    860
    +nonDetStrictFoldEvBindsMap k z bs = nonDetStrictFoldDVarEnv k z (ev_bind_varenv bs)
    
    835 861
     
    
    836
    -filterEvBindMap :: (EvBind -> Bool) -> EvBindMap -> EvBindMap
    
    837
    -filterEvBindMap k (EvBindMap { ev_bind_varenv = env })
    
    838
    -  = EvBindMap { ev_bind_varenv = filterDVarEnv k env }
    
    862
    +filterEvBindsMap :: (EvBind -> Bool) -> EvBindsMap -> EvBindsMap
    
    863
    +filterEvBindsMap k (EvBindsMap { ev_bind_varenv = env })
    
    864
    +  = EvBindsMap { ev_bind_varenv = filterDVarEnv k env }
    
    839 865
     
    
    840
    -evBindMapToVarSet :: EvBindMap -> VarSet
    
    841
    -evBindMapToVarSet (EvBindMap dve) = unsafeUFMToUniqSet (mapUFM evBindVar (udfmToUfm dve))
    
    866
    +evBindMapToVarSet :: EvBindsMap -> VarSet
    
    867
    +evBindMapToVarSet (EvBindsMap dve) = unsafeUFMToUniqSet (mapUFM evBindVar (udfmToUfm dve))
    
    842 868
     
    
    843
    -varSetMinusEvBindMap :: VarSet -> EvBindMap -> VarSet
    
    844
    -varSetMinusEvBindMap vs (EvBindMap dve) = vs `uniqSetMinusUDFM` dve
    
    869
    +varSetMinusEvBindsMap :: VarSet -> EvBindsMap -> VarSet
    
    870
    +varSetMinusEvBindsMap vs (EvBindsMap dve) = vs `uniqSetMinusUDFM` dve
    
    845 871
     
    
    846
    -instance Outputable EvBindMap where
    
    847
    -  ppr (EvBindMap m) = ppr m
    
    872
    +instance Outputable EvBindsMap where
    
    873
    +  ppr (EvBindsMap m) = ppr m
    
    848 874
     
    
    849 875
     data EvBindInfo
    
    850 876
       = EvBindGiven { -- See Note [Tracking redundant constraints] in GHC.Tc.Solver
    

  • compiler/GHC/Tc/Utils/Monad.hs
    ... ... @@ -104,9 +104,10 @@ module GHC.Tc.Utils.Monad(
    104 104
     
    
    105 105
       -- * Type constraints
    
    106 106
       newTcEvBinds, newNoTcEvBinds, cloneEvBindsVar,
    
    107
    -  addTcEvBind, addTcEvBinds, addTopEvBinds,
    
    108
    -  getTcEvBindsMap, setTcEvBindsMap, updTcEvBinds,
    
    109
    -  getTcEvTyCoVars, chooseUniqueOccTc,
    
    107
    +  addTcEvCoBind, addTcEvBind, addTopEvBinds,
    
    108
    +  getTcEvBindsMap, getTcEvBindsState,
    
    109
    +  setTcEvBindsMap, combineTcEvBinds,
    
    110
    +  chooseUniqueOccTc,
    
    110 111
       getConstraintVar, setConstraintVar,
    
    111 112
       emitConstraints, emitSimple, emitSimples,
    
    112 113
       emitImplication, emitImplications, ensureReflMultiplicityCo,
    
    ... ... @@ -118,6 +119,7 @@ module GHC.Tc.Utils.Monad(
    118 119
       getLclTypeEnv, setLclTypeEnv,
    
    119 120
       traceTcConstraints,
    
    120 121
       emitNamedTypeHole, IsExtraConstraint(..), emitAnonTypeHole,
    
    122
    +  fillCoercionHole,
    
    121 123
     
    
    122 124
       -- * Template Haskell context
    
    123 125
       recordThUse, recordThNeededRuntimeDeps,
    
    ... ... @@ -187,12 +189,13 @@ import GHC.Unit.Module.Warnings
    187 189
     import GHC.Unit.Home.PackageTable
    
    188 190
     
    
    189 191
     import GHC.Core.UsageEnv
    
    190
    -
    
    191 192
     import GHC.Core.Coercion ( isReflCo )
    
    192 193
     import GHC.Core.Multiplicity
    
    193 194
     import GHC.Core.InstEnv
    
    194 195
     import GHC.Core.FamInstEnv
    
    195 196
     import GHC.Core.Type( mkNumLitTy )
    
    197
    +import GHC.Core.TyCo.Rep( CoercionHole(..) )
    
    198
    +import GHC.Core.TyCo.FVs( coVarsOfCo )
    
    196 199
     import GHC.Core.TyCon ( TyCon )
    
    197 200
     
    
    198 201
     import GHC.Driver.Env
    
    ... ... @@ -230,6 +233,7 @@ import GHC.Types.SafeHaskell
    230 233
     import GHC.Types.Id
    
    231 234
     import GHC.Types.TypeEnv
    
    232 235
     import GHC.Types.Var.Env
    
    236
    +import GHC.Types.Var.Set
    
    233 237
     import GHC.Types.SrcLoc
    
    234 238
     import GHC.Types.Name.Env
    
    235 239
     import GHC.Types.Name.Set
    
    ... ... @@ -1660,6 +1664,105 @@ tryTcDiscardingErrs' validate recover_invalid recover_error thing_inside
    1660 1664
                      recover_error
    
    1661 1665
             }
    
    1662 1666
     
    
    1667
    +{- Note [Constraints and errors]
    
    1668
    +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    1669
    +Consider this (#12124):
    
    1670
    +
    
    1671
    +  foo :: Maybe Int
    
    1672
    +  foo = return (case Left 3 of
    
    1673
    +                  Left -> 1  -- Hard error here!
    
    1674
    +                  _    -> 0)
    
    1675
    +
    
    1676
    +The call to 'return' will generate a (Monad m) wanted constraint; but
    
    1677
    +then there'll be "hard error" (i.e. an exception in the TcM monad), from
    
    1678
    +the unsaturated Left constructor pattern.
    
    1679
    +
    
    1680
    +We'll recover in tcPolyBinds, using recoverM.  But then the final
    
    1681
    +tcSimplifyTop will see that (Monad m) constraint, with 'm' utterly
    
    1682
    +un-filled-in, and will emit a misleading error message.
    
    1683
    +
    
    1684
    +The underlying problem is that an exception interrupts the constraint
    
    1685
    +gathering process. Bottom line: if we have an exception, it's best
    
    1686
    +simply to discard any gathered constraints.  Hence in 'attemptM' we
    
    1687
    +capture the constraints in a fresh variable, and only emit them into
    
    1688
    +the surrounding context if we exit normally.  If an exception is
    
    1689
    +raised, simply discard the collected constraints... we have a hard
    
    1690
    +error to report.  So this capture-the-emit dance isn't as stupid as it
    
    1691
    +looks :-).
    
    1692
    +
    
    1693
    +However suppose we throw an exception inside an invocation of
    
    1694
    +captureConstraints, and discard all the constraints. Some of those
    
    1695
    +constraints might be "variable out of scope" Hole constraints, and that
    
    1696
    +might have been the actual original cause of the exception!  For
    
    1697
    +example (#12529):
    
    1698
    +   f = p @ Int
    
    1699
    +Here 'p' is out of scope, so we get an insoluble Hole constraint. But
    
    1700
    +the visible type application fails in the monad (throws an exception).
    
    1701
    +We must not discard the out-of-scope error.
    
    1702
    +
    
    1703
    +It's distressingly delicate though:
    
    1704
    +
    
    1705
    +* If we discard too /many/ constraints we may fail to report the error
    
    1706
    +  that led us to interrupt the constraint gathering process.
    
    1707
    +
    
    1708
    +  One particular example "variable out of scope" Hole constraints. For
    
    1709
    +  example (#12529):
    
    1710
    +   f = p @ Int
    
    1711
    +  Here 'p' is out of scope, so we get an insoluble Hole constraint. But
    
    1712
    +  the visible type application fails in the monad (throws an exception).
    
    1713
    +  We must not discard the out-of-scope error.
    
    1714
    +
    
    1715
    +  Also GHC.Tc.Solver.simplifyAndEmitFlatConstraints may fail having
    
    1716
    +  emitted some constraints with skolem-escape problems.
    
    1717
    +
    
    1718
    +* If we discard too /few/ constraints, we may get the misleading
    
    1719
    +  class constraints mentioned above.
    
    1720
    +
    
    1721
    +  We may /also/ end up taking constraints built at some inner level, and
    
    1722
    +  emitting them (via the exception catching in `tryCaptureConstraints`) at some
    
    1723
    +  outer level, and then breaking the TcLevel invariants See Note [TcLevel
    
    1724
    +  invariants] in GHC.Tc.Utils.TcType
    
    1725
    +
    
    1726
    +So `dropMisleading` has a horridly ad-hoc structure:
    
    1727
    +
    
    1728
    +* It keeps only /insoluble/ flat constraints (which are unlikely to very visibly
    
    1729
    +  trip up on the TcLevel invariant)
    
    1730
    +
    
    1731
    +* But it keeps all /implication/ constraints (except the class constraints
    
    1732
    +  inside them).  The implication constraints are OK because they set the ambient
    
    1733
    +  level before attempting to solve any inner constraints.
    
    1734
    +
    
    1735
    +Ugh! I hate this. But it seems to work.
    
    1736
    +
    
    1737
    +Other wrinkles
    
    1738
    +
    
    1739
    +(CERR1) Note that freshly-generated constraints like (Int ~ Bool), or
    
    1740
    +    ((a -> b) ~ Int) are all CNonCanonical, and hence won't be flagged as
    
    1741
    +    insoluble.  The constraint solver does that.  So they'll be discarded.
    
    1742
    +    That's probably ok; but see th/5358 as a not-so-good example:
    
    1743
    +       t1 :: Int
    
    1744
    +       t1 x = x   -- Manifestly wrong
    
    1745
    +
    
    1746
    +       foo = $(...raises exception...)
    
    1747
    +    We report the exception, but not the bug in t1.  Oh well.  Possible
    
    1748
    +    solution: make GHC.Tc.Utils.Unify.uType spot manifestly-insoluble constraints.
    
    1749
    +
    
    1750
    +(CERR2) In #26015 I found that from the constraints
    
    1751
    +           [W] alpha ~ Int      -- A class constraint
    
    1752
    +           [W] F alpha ~# Bool  -- An equality constraint
    
    1753
    +  we were dropping the first (becuase it's a class constraint) but not the
    
    1754
    +  second, and then getting a misleading error message from the second.  As
    
    1755
    +  #25607 shows, we can get not just one but a zillion bogus messages, which
    
    1756
    +  conceal the one genuine error.  Boo.
    
    1757
    +
    
    1758
    +  For now I have added an even more ad-hoc "drop class constraints except
    
    1759
    +  equality classes (~) and (~~)"; see `dropMisleading`.  That just kicks the can
    
    1760
    +  down the road; but this problem seems somewhat rare anyway.  The code in
    
    1761
    +  `dropMisleading` hasn't changed for years.
    
    1762
    +
    
    1763
    +It would be great to have a more systematic solution to this entire mess.
    
    1764
    +-}
    
    1765
    +
    
    1663 1766
     {-
    
    1664 1767
     ************************************************************************
    
    1665 1768
     *                                                                      *
    
    ... ... @@ -1854,108 +1957,112 @@ debugTc thing
    1854 1957
     
    
    1855 1958
     addTopEvBinds :: Bag EvBind -> TcM a -> TcM a
    
    1856 1959
     addTopEvBinds new_ev_binds thing_inside
    
    1857
    -  =updGblEnv upd_env thing_inside
    
    1960
    +  = updGblEnv upd_env thing_inside
    
    1858 1961
       where
    
    1859 1962
         upd_env tcg_env = tcg_env { tcg_ev_binds = tcg_ev_binds tcg_env
    
    1860 1963
                                                    `unionBags` new_ev_binds }
    
    1861 1964
     
    
    1862 1965
     newTcEvBinds :: TcM EvBindsVar
    
    1863
    -newTcEvBinds = do { binds_ref <- newTcRef emptyEvBindMap
    
    1864
    -                  ; tcvs_ref  <- newTcRef []
    
    1966
    +newTcEvBinds = do { binds_ref <- newTcRef emptyEvBindsState
    
    1865 1967
                       ; uniq <- newUnique
    
    1866 1968
                       ; traceTc "newTcEvBinds" (text "unique =" <+> ppr uniq)
    
    1867 1969
                       ; return (EvBindsVar { ebv_binds = binds_ref
    
    1868
    -                                       , ebv_tcvs = tcvs_ref
    
    1869 1970
                                            , ebv_uniq = uniq }) }
    
    1870 1971
     
    
    1871 1972
     -- | Creates an EvBindsVar incapable of holding any bindings. It still
    
    1872
    --- tracks covar usages (see comments on ebv_tcvs in "GHC.Tc.Types.Evidence"), thus
    
    1973
    +-- tracks covar usages (see comments on ebv_needs in "GHC.Tc.Types.Evidence"), thus
    
    1873 1974
     -- must be made monadically
    
    1874 1975
     newNoTcEvBinds :: TcM EvBindsVar
    
    1875 1976
     newNoTcEvBinds
    
    1876
    -  = do { tcvs_ref  <- newTcRef []
    
    1977
    +  = do { tcvs_ref  <- newTcRef emptyVarSet
    
    1877 1978
            ; uniq <- newUnique
    
    1878 1979
            ; traceTc "newNoTcEvBinds" (text "unique =" <+> ppr uniq)
    
    1879
    -       ; return (CoEvBindsVar { ebv_tcvs = tcvs_ref
    
    1880
    -                              , ebv_uniq = uniq }) }
    
    1980
    +       ; return (CoEvBindsVar { ebv_needs = tcvs_ref
    
    1981
    +                              , ebv_uniq  = uniq }) }
    
    1881 1982
     
    
    1882 1983
     cloneEvBindsVar :: EvBindsVar -> TcM EvBindsVar
    
    1883 1984
     -- Clone the refs, so that any binding created when
    
    1884 1985
     -- solving don't pollute the original
    
    1885 1986
     cloneEvBindsVar ebv@(EvBindsVar {})
    
    1886
    -  = do { binds_ref <- newTcRef emptyEvBindMap
    
    1887
    -       ; tcvs_ref  <- newTcRef []
    
    1888
    -       ; return (ebv { ebv_binds = binds_ref
    
    1889
    -                     , ebv_tcvs = tcvs_ref }) }
    
    1987
    +  = do { binds_ref <- newTcRef emptyEvBindsState
    
    1988
    +       ; uniq <- newUnique
    
    1989
    +       ; return (ebv { ebv_uniq = uniq
    
    1990
    +                     , ebv_binds = binds_ref }) }
    
    1890 1991
     cloneEvBindsVar ebv@(CoEvBindsVar {})
    
    1891
    -  = do { tcvs_ref  <- newTcRef []
    
    1892
    -       ; return (ebv { ebv_tcvs = tcvs_ref }) }
    
    1992
    +  = do { tcvs_ref  <- newTcRef emptyVarSet
    
    1993
    +       ; return (ebv { ebv_needs = tcvs_ref }) }
    
    1893 1994
     
    
    1894
    -getTcEvTyCoVars :: EvBindsVar -> TcM [TcCoercion]
    
    1895
    -getTcEvTyCoVars ev_binds_var
    
    1896
    -  = readTcRef (ebv_tcvs ev_binds_var)
    
    1995
    +getTcEvBindsMap :: EvBindsVar -> TcM EvBindsMap
    
    1996
    +getTcEvBindsMap ebv = do { EBS { ebs_binds = bs } <- getTcEvBindsState ebv
    
    1997
    +                         ; return bs }
    
    1897 1998
     
    
    1898
    -getTcEvBindsMap :: EvBindsVar -> TcM EvBindMap
    
    1899
    -getTcEvBindsMap (EvBindsVar { ebv_binds = ev_ref })
    
    1999
    +getTcEvBindsState :: EvBindsVar -> TcM EvBindsState
    
    2000
    +getTcEvBindsState (EvBindsVar { ebv_binds = ev_ref })
    
    1900 2001
       = readTcRef ev_ref
    
    1901
    -getTcEvBindsMap (CoEvBindsVar {})
    
    1902
    -  = return emptyEvBindMap
    
    1903
    -
    
    1904
    -setTcEvBindsMap :: EvBindsVar -> EvBindMap -> TcM ()
    
    1905
    -setTcEvBindsMap (EvBindsVar { ebv_binds = ev_ref }) binds
    
    1906
    -  = writeTcRef ev_ref binds
    
    1907
    -setTcEvBindsMap v@(CoEvBindsVar {}) ev_binds
    
    1908
    -  | isEmptyEvBindMap ev_binds
    
    1909
    -  = return ()
    
    1910
    -  | otherwise
    
    1911
    -  = pprPanic "setTcEvBindsMap" (ppr v $$ ppr ev_binds)
    
    1912
    -
    
    1913
    -updTcEvBinds :: EvBindsVar -> EvBindsVar -> TcM ()
    
    1914
    -updTcEvBinds (EvBindsVar { ebv_binds = old_ebv_ref, ebv_tcvs = old_tcv_ref })
    
    1915
    -             (EvBindsVar { ebv_binds = new_ebv_ref, ebv_tcvs = new_tcv_ref })
    
    2002
    +getTcEvBindsState (CoEvBindsVar { ebv_needs = needs_ref })
    
    2003
    +  = do { needs <- readTcRef needs_ref
    
    2004
    +       ; return (EBS { ebs_binds = emptyEvBindsMap, ebs_needs = needs }) }
    
    2005
    +
    
    2006
    +setTcEvBindsMap :: EvBindsVar -> EvBindsMap -> TcM ()
    
    2007
    +setTcEvBindsMap (EvBindsVar { ebv_binds = ev_ref }) ev_binds
    
    2008
    +  = updTcRef ev_ref (\ebs -> ebs { ebs_binds = ev_binds })
    
    2009
    +setTcEvBindsMap (CoEvBindsVar {}) ev_binds
    
    2010
    +  = assertPpr (isEmptyEvBindsMap ev_binds) (ppr ev_binds) $
    
    2011
    +    return ()
    
    2012
    +
    
    2013
    +combineTcEvBinds :: EvBindsVar -> EvBindsVar -> TcM ()
    
    2014
    +combineTcEvBinds (EvBindsVar { ebv_binds = old_ebv_ref })
    
    2015
    +                 (EvBindsVar { ebv_binds = new_ebv_ref })
    
    1916 2016
       = do { new_ebvs <- readTcRef new_ebv_ref
    
    1917
    -       ; updTcRef old_ebv_ref (`unionEvBindMap` new_ebvs)
    
    1918
    -       ; new_tcvs <- readTcRef new_tcv_ref
    
    1919
    -       ; updTcRef old_tcv_ref (new_tcvs ++) }
    
    1920
    -updTcEvBinds (EvBindsVar { ebv_tcvs = old_tcv_ref })
    
    1921
    -             (CoEvBindsVar { ebv_tcvs = new_tcv_ref })
    
    2017
    +       ; updTcRef old_ebv_ref (`unionEvBindsState` new_ebvs) }
    
    2018
    +combineTcEvBinds (EvBindsVar { ebv_binds = old_tcv_ref })
    
    2019
    +                 (CoEvBindsVar { ebv_needs = new_tcv_ref })
    
    1922 2020
       = do { new_tcvs <- readTcRef new_tcv_ref
    
    1923
    -       ; updTcRef old_tcv_ref (new_tcvs ++) }
    
    1924
    -updTcEvBinds (CoEvBindsVar { ebv_tcvs = old_tcv_ref })
    
    1925
    -             (CoEvBindsVar { ebv_tcvs = new_tcv_ref })
    
    2021
    +       ; updTcRef old_tcv_ref (addCoVarsEBS new_tcvs) }
    
    2022
    +combineTcEvBinds (CoEvBindsVar { ebv_needs = old_tcv_ref })
    
    2023
    +                 (CoEvBindsVar { ebv_needs = new_tcv_ref })
    
    1926 2024
       = do { new_tcvs <- readTcRef new_tcv_ref
    
    1927
    -       ; updTcRef old_tcv_ref (new_tcvs ++) }
    
    1928
    -updTcEvBinds old_var new_var
    
    1929
    -  = pprPanic "updTcEvBinds" (ppr old_var $$ ppr new_var)
    
    2025
    +       ; updTcRef old_tcv_ref (unionVarSet new_tcvs) }
    
    2026
    +combineTcEvBinds old_var new_var
    
    2027
    +  = pprPanic "combineTcEvBinds" (ppr old_var $$ ppr new_var)
    
    1930 2028
         -- Terms inside types, no good
    
    1931 2029
     
    
    2030
    +addTcEvCoBind :: EvBindsVar -> CoercionHole -> CoercionPlusHoles -> TcM ()
    
    2031
    +addTcEvCoBind ebv hole co_plus_holes@(CPH { cph_co = co })
    
    2032
    +  = do { fillCoercionHole hole co_plus_holes
    
    2033
    +         -- Record usage of the free vars of this coercion
    
    2034
    +       ; let fvs = coVarsOfCo co
    
    2035
    +       ; case ebv of
    
    2036
    +           EvBindsVar { ebv_binds = bs_ref }
    
    2037
    +              -> updTcRef bs_ref (addCoVarsEBS fvs)
    
    2038
    +           CoEvBindsVar { ebv_needs = need_ref }
    
    2039
    +              -> updTcRef need_ref (unionVarSet fvs) }
    
    2040
    +
    
    1932 2041
     addTcEvBind :: EvBindsVar -> EvBind -> TcM ()
    
    1933 2042
     -- Add a binding to the TcEvBinds by side effect
    
    1934
    -addTcEvBind (EvBindsVar { ebv_binds = ev_ref, ebv_uniq = u }) ev_bind
    
    1935
    -  = do { bnds <- readTcRef ev_ref
    
    1936
    -       ; let bnds' = extendEvBinds bnds ev_bind
    
    2043
    +addTcEvBind (EvBindsVar { ebv_binds = ev_ref, ebv_uniq = u })
    
    2044
    +            ev_bind@(EvBind { eb_info = info, eb_rhs = rhs })
    
    2045
    +  = do { EBS { ebs_binds = bnds, ebs_needs = needs } <- readTcRef ev_ref
    
    2046
    +       ; let bnds'  = extendEvBinds bnds ev_bind
    
    2047
    +             needs' = case info of
    
    2048
    +                        EvBindWanted {} -> nestedEvIdsOfTerm rhs
    
    2049
    +                                           `unionVarSet` needs
    
    2050
    +                        EvBindGiven {} -> needs
    
    2051
    +
    
    1937 2052
            ; traceTc "addTcEvBind" $
    
    1938 2053
              vcat [ text "EvBindsVar:" <+> ppr u
    
    1939 2054
                   , text "ev_bind:" <+> ppr ev_bind
    
    1940 2055
                   , text "bnds:" <+> ppr bnds
    
    1941
    -              , text "bnds':" <+> ppr bnds' ]
    
    1942
    -       ; writeTcRef ev_ref bnds' }
    
    2056
    +              , text "bnds':" <+> ppr bnds'
    
    2057
    +              , text "needs" <+> ppr needs
    
    2058
    +              , text "needs'" <+> ppr needs' ]
    
    2059
    +
    
    2060
    +       ; writeTcRef ev_ref $
    
    2061
    +         EBS { ebs_binds = bnds', ebs_needs = needs' } }
    
    2062
    +
    
    1943 2063
     addTcEvBind (CoEvBindsVar { ebv_uniq = u }) ev_bind
    
    1944 2064
       = pprPanic "addTcEvBind CoEvBindsVar" (ppr ev_bind $$ ppr u)
    
    1945 2065
     
    
    1946
    -addTcEvBinds :: EvBindsVar -> EvBindMap -> TcM ()
    
    1947
    --- ^ Add a collection of binding to the TcEvBinds by side effect
    
    1948
    -addTcEvBinds _ new_ev_binds
    
    1949
    -  | isEmptyEvBindMap new_ev_binds
    
    1950
    -  = return ()
    
    1951
    -addTcEvBinds (EvBindsVar { ebv_binds = ev_ref, ebv_uniq = u }) new_ev_binds
    
    1952
    -  = do { traceTc "addTcEvBinds" $ ppr u $$
    
    1953
    -                                  ppr new_ev_binds
    
    1954
    -       ; old_bnds <- readTcRef ev_ref
    
    1955
    -       ; writeTcRef ev_ref (old_bnds `unionEvBindMap` new_ev_binds) }
    
    1956
    -addTcEvBinds (CoEvBindsVar { ebv_uniq = u }) new_ev_binds
    
    1957
    -  = pprPanic "addTcEvBinds CoEvBindsVar" (ppr new_ev_binds $$ ppr u)
    
    1958
    -
    
    1959 2066
     chooseUniqueOccTc :: (OccSet -> OccName) -> TcM OccName
    
    1960 2067
     chooseUniqueOccTc fn =
    
    1961 2068
       do { env <- getGblEnv
    
    ... ... @@ -2137,111 +2244,22 @@ emitNamedTypeHole (name, tv)
    2137 2244
       where
    
    2138 2245
         occ       = nameOccName name
    
    2139 2246
     
    
    2140
    -{- Note [Constraints and errors]
    
    2141
    -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    2142
    -Consider this (#12124):
    
    2143
    -
    
    2144
    -  foo :: Maybe Int
    
    2145
    -  foo = return (case Left 3 of
    
    2146
    -                  Left -> 1  -- Hard error here!
    
    2147
    -                  _    -> 0)
    
    2148
    -
    
    2149
    -The call to 'return' will generate a (Monad m) wanted constraint; but
    
    2150
    -then there'll be "hard error" (i.e. an exception in the TcM monad), from
    
    2151
    -the unsaturated Left constructor pattern.
    
    2152
    -
    
    2153
    -We'll recover in tcPolyBinds, using recoverM.  But then the final
    
    2154
    -tcSimplifyTop will see that (Monad m) constraint, with 'm' utterly
    
    2155
    -un-filled-in, and will emit a misleading error message.
    
    2156
    -
    
    2157
    -The underlying problem is that an exception interrupts the constraint
    
    2158
    -gathering process. Bottom line: if we have an exception, it's best
    
    2159
    -simply to discard any gathered constraints.  Hence in 'attemptM' we
    
    2160
    -capture the constraints in a fresh variable, and only emit them into
    
    2161
    -the surrounding context if we exit normally.  If an exception is
    
    2162
    -raised, simply discard the collected constraints... we have a hard
    
    2163
    -error to report.  So this capture-the-emit dance isn't as stupid as it
    
    2164
    -looks :-).
    
    2165
    -
    
    2166
    -However suppose we throw an exception inside an invocation of
    
    2167
    -captureConstraints, and discard all the constraints. Some of those
    
    2168
    -constraints might be "variable out of scope" Hole constraints, and that
    
    2169
    -might have been the actual original cause of the exception!  For
    
    2170
    -example (#12529):
    
    2171
    -   f = p @ Int
    
    2172
    -Here 'p' is out of scope, so we get an insoluble Hole constraint. But
    
    2173
    -the visible type application fails in the monad (throws an exception).
    
    2174
    -We must not discard the out-of-scope error.
    
    2175
    -
    
    2176
    -It's distressingly delicate though:
    
    2177
    -
    
    2178
    -* If we discard too /many/ constraints we may fail to report the error
    
    2179
    -  that led us to interrupt the constraint gathering process.
    
    2180
    -
    
    2181
    -  One particular example "variable out of scope" Hole constraints. For
    
    2182
    -  example (#12529):
    
    2183
    -   f = p @ Int
    
    2184
    -  Here 'p' is out of scope, so we get an insoluble Hole constraint. But
    
    2185
    -  the visible type application fails in the monad (throws an exception).
    
    2186
    -  We must not discard the out-of-scope error.
    
    2187
    -
    
    2188
    -  Also GHC.Tc.Solver.simplifyAndEmitFlatConstraints may fail having
    
    2189
    -  emitted some constraints with skolem-escape problems.
    
    2190
    -
    
    2191
    -* If we discard too /few/ constraints, we may get the misleading
    
    2192
    -  class constraints mentioned above.
    
    2193
    -
    
    2194
    -  We may /also/ end up taking constraints built at some inner level, and
    
    2195
    -  emitting them (via the exception catching in `tryCaptureConstraints` at some
    
    2196
    -  outer level, and then breaking the TcLevel invariants See Note [TcLevel
    
    2197
    -  invariants] in GHC.Tc.Utils.TcType
    
    2198
    -
    
    2199
    -So `dropMisleading` has a horridly ad-hoc structure:
    
    2200
    -
    
    2201
    -* It keeps only /insoluble/ flat constraints (which are unlikely to very visibly
    
    2202
    -  trip up on the TcLevel invariant
    
    2203
    -
    
    2204
    -* But it keeps all /implication/ constraints (except the class constraints
    
    2205
    -  inside them).  The implication constraints are OK because they set the ambient
    
    2206
    -  level before attempting to solve any inner constraints.
    
    2207
    -
    
    2208
    -Ugh! I hate this. But it seems to work.
    
    2209
    -
    
    2210
    -Other wrinkles
    
    2211
    -
    
    2212
    -(CERR1) Note that freshly-generated constraints like (Int ~ Bool), or
    
    2213
    -    ((a -> b) ~ Int) are all CNonCanonical, and hence won't be flagged as
    
    2214
    -    insoluble.  The constraint solver does that.  So they'll be discarded.
    
    2215
    -    That's probably ok; but see th/5358 as a not-so-good example:
    
    2216
    -       t1 :: Int
    
    2217
    -       t1 x = x   -- Manifestly wrong
    
    2218
    -
    
    2219
    -       foo = $(...raises exception...)
    
    2220
    -    We report the exception, but not the bug in t1.  Oh well.  Possible
    
    2221
    -    solution: make GHC.Tc.Utils.Unify.uType spot manifestly-insoluble constraints.
    
    2222
    -
    
    2223
    -(CERR2) In #26015 I found that from the constraints
    
    2224
    -           [W] alpha ~ Int      -- A class constraint
    
    2225
    -           [W] F alpha ~# Bool  -- An equality constraint
    
    2226
    -  we were dropping the first (becuase it's a class constraint) but not the
    
    2227
    -  second, and then getting a misleading error message from the second.  As
    
    2228
    -  #25607 shows, we can get not just one but a zillion bogus messages, which
    
    2229
    -  conceal the one genuine error.  Boo.
    
    2247
    +-- | Put a value in a coercion hole
    
    2248
    +fillCoercionHole :: CoercionHole -> CoercionPlusHoles -> TcM ()
    
    2249
    +fillCoercionHole (CH { ch_ref = ref, ch_co_var = cv }) co
    
    2250
    +  = do { when debugIsOn $
    
    2251
    +         do { cts <- readTcRef ref
    
    2252
    +            ; whenIsJust cts $ \old_co ->
    
    2253
    +              pprPanic "Filling a filled coercion hole" (ppr cv $$ ppr co $$ ppr old_co) }
    
    2254
    +       ; traceTc "Filling coercion hole" (ppr cv <+> text ":=" <+> ppr co)
    
    2255
    +       ; writeTcRef ref (Just co) }
    
    2230 2256
     
    
    2231
    -  For now I have added an even more ad-hoc "drop class constraints except
    
    2232
    -  equality classes (~) and (~~)"; see `dropMisleading`.  That just kicks the can
    
    2233
    -  down the road; but this problem seems somewhat rare anyway.  The code in
    
    2234
    -  `dropMisleading` hasn't changed for years.
    
    2235
    -
    
    2236
    -It would be great to have a more systematic solution to this entire mess.
    
    2237 2257
     
    
    2238
    -
    
    2239
    -************************************************************************
    
    2258
    +{- *********************************************************************
    
    2240 2259
     *                                                                      *
    
    2241 2260
                  Template Haskell context
    
    2242 2261
     *                                                                      *
    
    2243
    -************************************************************************
    
    2244
    --}
    
    2262
    +********************************************************************* -}
    
    2245 2263
     
    
    2246 2264
     recordThUse :: TcM ()
    
    2247 2265
     recordThUse = do { env <- getGblEnv; writeTcRef (tcg_th_used env) True }
    

  • compiler/GHC/Tc/Utils/TcMType.hs
    ... ... @@ -341,31 +341,13 @@ newImplication
    341 341
              (implicationPrototype (mkCtLocEnv env))
    
    342 342
                { ic_warn_inaccessible = warn_inaccessible && not in_gen_code }
    
    343 343
     
    
    344
    -{-
    
    345
    -************************************************************************
    
    346
    -*                                                                      *
    
    347
    -        Coercion holes
    
    348
    -*                                                                      *
    
    349
    -************************************************************************
    
    350
    --}
    
    351
    -
    
    352 344
     newCoercionHole :: TcPredType -> TcM CoercionHole
    
    353 345
     -- For the Bool, see (EIK2) in Note [Equalities with heterogeneous kinds]
    
    354 346
     newCoercionHole pred_ty
    
    355 347
       = do { co_var <- newEvVar pred_ty
    
    356 348
            ; traceTc "New coercion hole:" (ppr co_var <+> dcolon <+> ppr pred_ty)
    
    357 349
            ; ref <- newMutVar Nothing
    
    358
    -       ; return $ CoercionHole { ch_co_var = co_var, ch_ref = ref } }
    
    359
    -
    
    360
    --- | Put a value in a coercion hole
    
    361
    -fillCoercionHole :: CoercionHole -> CoercionPlusHoles -> TcM ()
    
    362
    -fillCoercionHole (CoercionHole { ch_ref = ref, ch_co_var = cv }) co
    
    363
    -  = do { when debugIsOn $
    
    364
    -         do { cts <- readTcRef ref
    
    365
    -            ; whenIsJust cts $ \old_co ->
    
    366
    -              pprPanic "Filling a filled coercion hole" (ppr cv $$ ppr co $$ ppr old_co) }
    
    367
    -       ; traceTc "Filling coercion hole" (ppr cv <+> text ":=" <+> ppr co)
    
    368
    -       ; writeTcRef ref (Just co) }
    
    350
    +       ; return $ CH { ch_co_var = co_var, ch_ref = ref } }
    
    369 351
     
    
    370 352
     {- **********************************************************************
    
    371 353
     *
    

  • compiler/GHC/Tc/Utils/Unify.hs
    ... ... @@ -418,7 +418,8 @@ Some examples:
    418 418
     -}
    
    419 419
     
    
    420 420
     tcSkolemiseGeneral
    
    421
    -  :: DeepSubsumptionFlag
    
    421
    +  :: HasDebugCallStack
    
    422
    +  => DeepSubsumptionFlag
    
    422 423
       -> UserTypeCtxt
    
    423 424
       -> TcType -> TcType   -- top_ty and expected_ty
    
    424 425
             -- Here, top_ty      is the type we started to skolemise; used only in SigSkol
    
    ... ... @@ -446,15 +447,16 @@ tcSkolemiseGeneral ds_flag ctxt top_ty expected_ty thing_inside
    446 447
                  ; skol_info <- mkSkolemInfo sig_skol }
    
    447 448
     
    
    448 449
            ; let skol_tvs = map (binderVar . snd) tv_prs
    
    449
    -       ; traceTc "tcSkolemiseGeneral" (pprUserTypeCtxt ctxt <+> ppr skol_tvs <+> ppr given)
    
    450
    +       ; traceTc "tcSkolemiseGeneral {" (pprUserTypeCtxt ctxt <+> ppr skol_tvs <+> ppr given)
    
    450 451
            ; (ev_binds, result) <- checkConstraints sig_skol skol_tvs given $
    
    451 452
                                    thing_inside tv_prs rho_ty
    
    452 453
     
    
    454
    +       ; traceTc "tcSkolemiseGeneral }" (ppr ev_binds $$ traceCallStackDoc)
    
    453 455
            ; return (wrap <.> mkWpLet ev_binds, result) }
    
    454 456
              -- The ev_binds returned by checkConstraints is very
    
    455 457
              -- often empty, in which case mkWpLet is a no-op
    
    456 458
     
    
    457
    -tcSkolemiseCompleteSig :: TcCompleteSig
    
    459
    +tcSkolemiseCompleteSig :: HasDebugCallStack => TcCompleteSig
    
    458 460
                            -> ([ExpPatType] -> TcRhoType -> TcM result)
    
    459 461
                            -> TcM (HsWrapper, result)
    
    460 462
     -- ^ The wrapper has type: spec_ty ~~> expected_ty
    
    ... ... @@ -471,7 +473,7 @@ tcSkolemiseCompleteSig (CSig { sig_bndr = poly_id, sig_ctxt = ctxt, sig_loc = lo
    471 473
              tcExtendNameTyVarEnv (map (fmap binderVar) tv_prs) $
    
    472 474
              thing_inside (map (mkInvisExpPatType . snd) tv_prs) rho_ty }
    
    473 475
     
    
    474
    -tcSkolemiseExpectedType :: TcSigmaType
    
    476
    +tcSkolemiseExpectedType :: HasDebugCallStack => TcSigmaType
    
    475 477
                             -> ([ExpPatType] -> TcRhoType -> TcM result)
    
    476 478
                             -> TcM (HsWrapper, result)
    
    477 479
     -- Just like tcSkolemiseCompleteSig, except that we don't have a user-written
    
    ... ... @@ -483,14 +485,15 @@ tcSkolemiseExpectedType exp_ty thing_inside
    483 485
       = tcSkolemiseGeneral Shallow GenSigCtxt exp_ty exp_ty $ \tv_prs rho_ty ->
    
    484 486
         thing_inside (map (mkInvisExpPatType . snd) tv_prs) rho_ty
    
    485 487
     
    
    486
    -tcSkolemise :: DeepSubsumptionFlag -> UserTypeCtxt -> TcSigmaType
    
    488
    +tcSkolemise :: HasDebugCallStack => DeepSubsumptionFlag -> UserTypeCtxt -> TcSigmaType
    
    487 489
                 -> (TcRhoType -> TcM result)
    
    488 490
                 -> TcM (HsWrapper, result)
    
    489 491
     tcSkolemise ds_flag ctxt expected_ty thing_inside
    
    490 492
       = tcSkolemiseGeneral ds_flag ctxt expected_ty expected_ty $ \_ rho_ty ->
    
    491 493
         thing_inside rho_ty
    
    492 494
     
    
    493
    -checkConstraints :: SkolemInfoAnon
    
    495
    +checkConstraints :: HasDebugCallStack
    
    496
    +                 => SkolemInfoAnon
    
    494 497
                      -> [TcTyVar]           -- Skolems
    
    495 498
                      -> [EvVar]             -- Given
    
    496 499
                      -> TcM result
    
    ... ... @@ -504,14 +507,16 @@ checkConstraints skol_info skol_tvs given thing_inside
    504 507
            ; if implication_needed
    
    505 508
              then do { (tclvl, wanted, result) <- pushLevelAndCaptureConstraints thing_inside
    
    506 509
                      ; (implics, ev_binds) <- buildImplicationFor tclvl skol_info skol_tvs given wanted
    
    507
    -                 ; traceTc "checkConstraints" (ppr tclvl $$ ppr skol_tvs)
    
    510
    +                 ; traceTc "checkConstraints A" (ppr tclvl $$ ppr skol_tvs $$ traceCallStackDoc)
    
    508 511
                      ; emitImplications implics
    
    509 512
                      ; return (ev_binds, result) }
    
    510 513
     
    
    511 514
              else -- Fast path.  We check every function argument with tcCheckPolyExpr,
    
    512 515
                   -- which uses tcTopSkolemise and hence checkConstraints.
    
    513 516
                   -- So this fast path is well-exercised
    
    514
    -              do { res <- thing_inside
    
    517
    +              do { traceTc "checkConstraints B" (ppr skol_tvs $$ ppr given $$ ppr skol_info $$
    
    518
    +                                                 traceCallStackDoc)
    
    519
    +                 ; res <- thing_inside
    
    515 520
                      ; return (emptyTcEvBinds, res) } }
    
    516 521
     
    
    517 522
     checkTvConstraints :: SkolemInfo
    

  • compiler/GHC/Tc/Zonk/TcType.hs
    ... ... @@ -236,7 +236,7 @@ zonkCo :: Coercion -> ZonkM Coercion
    236 236
           , tcm_tycon      = zonkTcTyCon }
    
    237 237
           where
    
    238 238
             hole :: () -> CoercionHole -> ZonkM Coercion
    
    239
    -        hole _ hole@(CoercionHole { ch_ref = ref, ch_co_var = cv })
    
    239
    +        hole _ hole@(CH { ch_ref = ref, ch_co_var = cv })
    
    240 240
               = do { contents <- readTcRef ref
    
    241 241
                    ; case contents of
    
    242 242
                        Just (CPH { cph_co = co })
    
    ... ... @@ -617,7 +617,7 @@ instance Monoid UnfilledCoercionHoleMonoid where
    617 617
     
    
    618 618
     -- | Is a coercion hole filled in?
    
    619 619
     isFilledCoercionHole :: CoercionHole -> ZonkM Bool
    
    620
    -isFilledCoercionHole (CoercionHole { ch_ref = ref })
    
    620
    +isFilledCoercionHole (CH { ch_ref = ref })
    
    621 621
       = isJust <$> readTcRef ref
    
    622 622
     
    
    623 623
     -- | Retrieve the contents of a coercion hole. Panics if the hole
    
    ... ... @@ -631,7 +631,7 @@ unpackCoercionHole hole
    631 631
     
    
    632 632
     -- | Retrieve the contents of a coercion hole, if it is filled
    
    633 633
     unpackCoercionHole_maybe :: CoercionHole -> ZonkM (Maybe CoercionPlusHoles)
    
    634
    -unpackCoercionHole_maybe (CoercionHole { ch_ref = ref }) = readTcRef ref
    
    634
    +unpackCoercionHole_maybe (CH { ch_ref = ref }) = readTcRef ref
    
    635 635
     
    
    636 636
     
    
    637 637
     {-
    

  • compiler/GHC/Tc/Zonk/Type.hs
    ... ... @@ -485,7 +485,7 @@ zonkCoVarOcc cv
    485 485
               _        -> mkCoVarCo <$> (lift $ liftZonkM $ zonkCoVar cv) }
    
    486 486
     
    
    487 487
     zonkCoHole :: CoercionHole -> ZonkTcM Coercion
    
    488
    -zonkCoHole hole@(CoercionHole { ch_ref = ref, ch_co_var = cv })
    
    488
    +zonkCoHole hole@(CH { ch_ref = ref, ch_co_var = cv })
    
    489 489
       = do { contents <- readTcRef ref
    
    490 490
            ; case contents of
    
    491 491
                Just (CPH { cph_co = co })
    
    ... ... @@ -1910,8 +1910,9 @@ zonk_tc_ev_binds (EvBinds bs) = zonkEvBinds bs
    1910 1910
     
    
    1911 1911
     zonkEvBindsVar :: EvBindsVar -> ZonkBndrTcM (Bag EvBind)
    
    1912 1912
     zonkEvBindsVar (EvBindsVar { ebv_binds = ref })
    
    1913
    -  = do { bs <- readTcRef ref
    
    1913
    +  = do { EBS { ebs_binds = bs }  <- readTcRef ref
    
    1914 1914
            ; zonkEvBinds (evBindMapBinds bs) }
    
    1915
    +
    
    1915 1916
     zonkEvBindsVar (CoEvBindsVar {}) = return emptyBag
    
    1916 1917
     
    
    1917 1918
     zonkEvBinds :: Bag EvBind -> ZonkBndrTcM (Bag EvBind)
    

  • compiler/GHC/Utils/Trace.hs
    ... ... @@ -11,6 +11,7 @@ module GHC.Utils.Trace
    11 11
       , warnPprTraceM
    
    12 12
       , pprTraceUserWarning
    
    13 13
       , trace
    
    14
    +  , traceCallStackDoc
    
    14 15
       )
    
    15 16
     where
    
    16 17