Marge Bot pushed to branch master at Glasgow Haskell Compiler / GHC

Commits:

28 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/Errors.hs
    ... ... @@ -405,7 +405,7 @@ reportImplic ctxt implic@(Implic { ic_skols = tvs
    405 405
                   _               -> False
    
    406 406
     
    
    407 407
     warnRedundantConstraints :: SolverReportErrCtxt -> CtLocEnv -> SkolemInfoAnon -> [EvVar] -> TcM ()
    
    408
    --- See Note [Tracking redundant constraints] in GHC.Tc.Solver
    
    408
    +-- See Note [Tracking needed EvIds] in GHC.Tc.Solver
    
    409 409
     warnRedundantConstraints ctxt env info redundant_evs
    
    410 410
      | not (cec_warn_redundant ctxt)
    
    411 411
      = return ()
    

  • compiler/GHC/Tc/Gen/Default.hs
    ... ... @@ -22,7 +22,7 @@ import GHC.Tc.Errors.Types
    22 22
     import GHC.Tc.Gen.HsType
    
    23 23
     import GHC.Tc.Solver.Monad  ( runTcS )
    
    24 24
     import GHC.Tc.Solver.Solve  ( solveWanteds )
    
    25
    -import GHC.Tc.Types.Constraint ( isEmptyWC, andWC, mkSimpleWC )
    
    25
    +import GHC.Tc.Types.Constraint ( isSolvedWC, andWC, mkSimpleWC )
    
    26 26
     import GHC.Tc.Types.Origin  ( CtOrigin(DefaultOrigin) )
    
    27 27
     import GHC.Tc.Utils.Env
    
    28 28
     import GHC.Tc.Utils.Monad
    
    ... ... @@ -296,7 +296,7 @@ simplifyDefault cls dflt_ty@(L l _)
    296 296
                     , text "inst_pred:" <+> ppr inst_pred
    
    297 297
                     , text "all_wanteds " <+> ppr all_wanteds
    
    298 298
                     , text "unsolved:" <+> ppr unsolved ]
    
    299
    -       ; let is_instance = isEmptyWC unsolved
    
    299
    +       ; let is_instance = isSolvedWC unsolved
    
    300 300
            ; return $
    
    301 301
                if | is_instance
    
    302 302
                   , ClassPred _ tys <- classifyPredType inst_pred
    

  • 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/Dict.hs
    ... ... @@ -663,6 +663,12 @@ Some wrinkles:
    663 663
         of the caller (#15164).  You might worry about having a solved-dict that uses
    
    664 664
         a Given -- but that too will have been subject to short-cut solving so it's fine.
    
    665 665
     
    
    666
    +(SCS4) In `tryShortCutSolver`, when deciding if we have "completely solved" the
    
    667
    +   constraint, we must use `isSolvedWC` not `isEmptyWC`.  The latter says "False"
    
    668
    +   if the residual constraint has any implications, even solved ones; and we
    
    669
    +   don't want to reject short-cut solving just because we have some leftover
    
    670
    +   /solved/ implications.  #26805 was a case in point.
    
    671
    +
    
    666 672
     Note [Shortcut solving: incoherence]
    
    667 673
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    668 674
     This optimization relies on coherence of dictionaries to be correct. When we
    
    ... ... @@ -742,7 +748,8 @@ try_inert_dicts inerts dict_w@(DictCt { di_ev = ev_w, di_cls = cls, di_tys = tys
    742 748
       = -- There is a matching dictionary in the inert set
    
    743 749
         do { -- For a Wanted, first to try to solve it /completely/ from top level instances
    
    744 750
              -- See Note [Shortcut solving]
    
    745
    -       ; short_cut_worked <- tryShortCutSolver (isGiven ev_i) dict_w
    
    751
    +       ; dflags <- getDynFlags
    
    752
    +       ; short_cut_worked <- tryShortCutSolver dflags (isGiven ev_i) dict_w
    
    746 753
     
    
    747 754
            ; if | short_cut_worked
    
    748 755
                 -> stopWith ev_w "shortCutSolver worked(1)"
    
    ... ... @@ -770,7 +777,8 @@ try_inert_dicts inerts dict_w@(DictCt { di_ev = ev_w, di_cls = cls, di_tys = tys
    770 777
            ; continueWith () }
    
    771 778
     
    
    772 779
     -- See Note [Shortcut solving]
    
    773
    -tryShortCutSolver :: Bool       -- True <=> try the short-cut solver; False <=> don't
    
    780
    +tryShortCutSolver :: DynFlags
    
    781
    +                  -> Bool       -- True <=> try the short-cut solver; False <=> don't
    
    774 782
                       -> DictCt     -- Work item
    
    775 783
                       -> TcS Bool   -- True <=> success
    
    776 784
     -- We are about to solve a [W] constraint from a [G] constraint. We take
    
    ... ... @@ -778,30 +786,25 @@ tryShortCutSolver :: Bool -- True <=> try the short-cut solver; False <=>
    778 786
     -- Note that we only do this for the sake of performance. Exactly the same
    
    779 787
     -- programs should typecheck regardless of whether we take this step or
    
    780 788
     -- not. See Note [Shortcut solving]
    
    781
    -tryShortCutSolver try_short_cut dict_w@(DictCt { di_ev = ev_w })
    
    782
    -  | not try_short_cut
    
    783
    -  = return False
    
    784
    -  | otherwise
    
    785
    -  = do { dflags <- getDynFlags
    
    786
    -       ; if | CtWanted (WantedCt { ctev_pred = pred_w }) <- ev_w
    
    787
    -
    
    788
    -            , not (couldBeIPLike pred_w)   -- Not for implicit parameters (#18627)
    
    789
    +tryShortCutSolver dflags try_short_cut dict_w
    
    790
    +  | try_short_cut
    
    791
    +  , DictCt { di_ev = ev_w } <- dict_w
    
    792
    +  , CtWanted (WantedCt { ctev_pred = pred_w }) <- ev_w
    
    793
    +  , not (couldBeIPLike pred_w)   -- Not for implicit parameters (#18627)
    
    789 794
     
    
    790
    -            , not (xopt LangExt.IncoherentInstances dflags)
    
    795
    +  , not (xopt LangExt.IncoherentInstances dflags)
    
    791 796
                   -- If IncoherentInstances is on then we cannot rely on coherence of proofs
    
    792 797
                   -- in order to justify this optimization: The proof provided by the
    
    793 798
                   -- [G] constraint's superclass may be different from the top-level proof.
    
    794 799
                   -- See Note [Shortcut solving: incoherence]
    
    795
    -
    
    796
    -            , gopt Opt_SolveConstantDicts dflags
    
    800
    +  , gopt Opt_SolveConstantDicts dflags
    
    797 801
                   -- Enabled by the -fsolve-constant-dicts flag
    
    798 802
     
    
    799
    -            -> tryShortCutTcS $  -- tryTcS tries to completely solve some contraints
    
    800
    -               do { residual <- solveSimpleWanteds (unitBag (CDictCan dict_w))
    
    801
    -                  ; return (isEmptyWC residual) }
    
    803
    +  = tryShortCutTcS $  -- tryTcS tries to completely solve some contraints
    
    804
    +    solveSimpleWanteds (unitBag (CDictCan dict_w))
    
    802 805
     
    
    803
    -            | otherwise
    
    804
    -            -> return False }
    
    806
    +  | otherwise
    
    807
    +  = return False
    
    805 808
     
    
    806 809
     
    
    807 810
     {- *******************************************************************
    
    ... ... @@ -836,7 +839,7 @@ try_instances inerts work_item@(DictCt { di_ev = ev@(CtWanted wev), di_cls = cls
    836 839
             ; case lkup_res of
    
    837 840
                    OneInst { cir_what = what }
    
    838 841
                       -> do { let is_local_given = case what of { LocalInstance -> True; _ -> False }
    
    839
    -                        ; take_shortcut <- tryShortCutSolver is_local_given work_item
    
    842
    +                        ; take_shortcut <- tryShortCutSolver dflags is_local_given work_item
    
    840 843
                             ; if take_shortcut
    
    841 844
                               then stopWith ev "shortCutSolver worked(2)"
    
    842 845
                               else do { insertSafeOverlapFailureTcS what work_item
    

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

  • compiler/GHC/Tc/Solver/InertSet.hs
    ... ... @@ -2127,7 +2127,7 @@ solveOneFromTheOther.
    2127 2127
     
    
    2128 2128
           - For everything else, we want to keep the outermost one.  Reason: that
    
    2129 2129
             makes it more likely that the inner one will turn out to be unused,
    
    2130
    -        and can be reported as redundant.  See Note [Tracking redundant constraints]
    
    2130
    +        and can be reported as redundant.  See Note [Tracking needed EvIds]
    
    2131 2131
             in GHC.Tc.Solver.
    
    2132 2132
     
    
    2133 2133
             It transpires that using the outermost one is responsible for an
    
    ... ... @@ -2140,7 +2140,7 @@ solveOneFromTheOther.
    2140 2140
                according to Note [Solving superclass constraints] in GHC.Tc.TyCl.Instance.
    
    2141 2141
     
    
    2142 2142
            (b) Prefer constraints that are not superclass selections. See
    
    2143
    -           (TRC3) in Note [Tracking redundant constraints] in GHC.Tc.Solver.
    
    2143
    +           (TRC3) in Note [Tracking needed EvIds] in GHC.Tc.Solver.
    
    2144 2144
     
    
    2145 2145
            (c) If both are GivenSCOrigin, chooose the one with the shallower
    
    2146 2146
                superclass-selection depth, in the hope of identifying more correct
    

  • 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 ()
    
    ... ... @@ -1351,7 +1351,7 @@ nestTcS (TcS thing_inside)
    1351 1351
     
    
    1352 1352
            ; return res }
    
    1353 1353
     
    
    1354
    -tryShortCutTcS :: TcS Bool -> TcS Bool
    
    1354
    +tryShortCutTcS :: TcS WantedConstraints -> TcS Bool
    
    1355 1355
     -- Like nestTcS, but
    
    1356 1356
     --   (a) be a no-op if the nested computation returns False
    
    1357 1357
     --   (b) if (but only if) success, propagate nested bindings to the caller
    
    ... ... @@ -1380,26 +1380,43 @@ 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
    -       ; solved <- thing_inside nest_env
    
    1388
    -       ; TcM.traceTc "tryTcS }" (ppr solved)
    
    1389
    -
    
    1390
    -       ; if not solved
    
    1391
    -         then return False
    
    1392
    -         else do {  -- Successfully solved
    
    1393
    -                   -- Add the new bindings to the existing ones
    
    1394
    -                 ; TcM.updTcEvBinds old_ev_binds_var new_ev_binds_var
    
    1395
    -
    
    1396
    -                 -- Update the existing inert set
    
    1397
    -                 ; new_inerts <- TcM.readTcRef new_inert_var
    
    1398
    -                 ; TcM.updTcRef inerts_var (`updateInertsWith` new_inerts)
    
    1399
    -
    
    1400
    -                 ; TcM.traceTc "tryTcS update" (ppr (inert_solved_dicts new_inerts))
    
    1401
    -
    
    1402
    -                 ; return True } }
    
    1387
    +       ; residual <- thing_inside nest_env
    
    1388
    +       ; let solved = isSolvedWC residual
    
    1389
    +              -- NB: isSolvedWC, not isEmptyWC (#26805). We might succeed
    
    1390
    +              --     in fully-solving the constraint but still leave some
    
    1391
    +              --     /solved/ implications in the residual.
    
    1392
    +              --     See (SCS4) in Note [Shortcut solving]
    
    1393
    +       ; TcM.traceTc "tryShortCutTcS }" (ppr solved)
    
    1394
    +
    
    1395
    +       ; when solved $    -- Successfully solved
    
    1396
    +         do {  -- Add the new bindings to the existing ones
    
    1397
    +            ; TcM.combineTcEvBinds old_ev_binds_var new_ev_binds_var
    
    1398
    +
    
    1399
    +            -- We are discarding some implications; we must add their
    
    1400
    +            -- NeededEvIds to the current bindings, lest we fail to record
    
    1401
    +            -- some needed givens, and then wrongly prune away their bindings
    
    1402
    +            ; TcM.addNeededEvIds old_ev_binds_var $
    
    1403
    +              foldr add_implic emptyVarSet $
    
    1404
    +              wc_impl residual
    
    1405
    +
    
    1406
    +            -- Update the existing inert set
    
    1407
    +            ; new_inerts <- TcM.readTcRef new_inert_var
    
    1408
    +            ; TcM.updTcRef inerts_var (`updateInertsWith` new_inerts) }
    
    1409
    +
    
    1410
    +
    
    1411
    +       ; return solved
    
    1412
    +       }
    
    1413
    +  where
    
    1414
    +    add_implic :: Implication -> NeededEvIds -> NeededEvIds
    
    1415
    +    add_implic implic@(Implic { ic_status = status }) needs
    
    1416
    +      | IC_Solved { ics_dm = dm, ics_non_dm = non_dm } <- status
    
    1417
    +      = needs `unionVarSet` dm `unionVarSet` non_dm
    
    1418
    +      | otherwise
    
    1419
    +      = pprPanic "tryShortCutTcS" (ppr implic)
    
    1403 1420
     
    
    1404 1421
     updateInertsWith :: InertSet -> InertSet -> InertSet
    
    1405 1422
     -- Update the current inert set with bits from a nested solve,
    
    ... ... @@ -1465,21 +1482,21 @@ getTcEvBindsVar = TcS (return . tcs_ev_binds)
    1465 1482
     getTcLevel :: TcS TcLevel
    
    1466 1483
     getTcLevel = wrapTcS TcM.getTcLevel
    
    1467 1484
     
    
    1468
    -getTcEvTyCoVars :: EvBindsVar -> TcS [TcCoercion]
    
    1469
    -getTcEvTyCoVars ev_binds_var
    
    1470
    -  = wrapTcS $ TcM.getTcEvTyCoVars ev_binds_var
    
    1485
    +getTcEvBindsState :: EvBindsVar -> TcS EvBindsState
    
    1486
    +getTcEvBindsState ev_binds_var
    
    1487
    +  = wrapTcS $ TcM.getTcEvBindsState ev_binds_var
    
    1471 1488
     
    
    1472
    -getTcEvBindsMap :: EvBindsVar -> TcS EvBindMap
    
    1489
    +getTcEvBindsMap :: EvBindsVar -> TcS EvBindsMap
    
    1473 1490
     getTcEvBindsMap ev_binds_var
    
    1474 1491
       = wrapTcS $ TcM.getTcEvBindsMap ev_binds_var
    
    1475 1492
     
    
    1476
    -setTcEvBindsMap :: EvBindsVar -> EvBindMap -> TcS ()
    
    1493
    +setTcEvBindsMap :: EvBindsVar -> EvBindsMap -> TcS ()
    
    1477 1494
     setTcEvBindsMap ev_binds_var binds
    
    1478 1495
       = wrapTcS $ TcM.setTcEvBindsMap ev_binds_var binds
    
    1479 1496
     
    
    1480
    -updTcEvBinds :: EvBindsVar -> EvBindsVar -> TcS ()
    
    1481
    -updTcEvBinds evb nested_evb
    
    1482
    -  = wrapTcS $ TcM.updTcEvBinds evb nested_evb
    
    1497
    +combineTcEvBinds :: EvBindsVar -> EvBindsVar -> TcS ()
    
    1498
    +combineTcEvBinds evb nested_evb
    
    1499
    +  = wrapTcS $ TcM.combineTcEvBinds evb nested_evb
    
    1483 1500
     
    
    1484 1501
     getDefaultInfo ::  TcS (DefaultEnv, Bool)
    
    1485 1502
     getDefaultInfo = wrapTcS TcM.tcGetDefaultTys
    
    ... ... @@ -2029,12 +2046,9 @@ setWantedDict dest canonical tm
    2029 2046
           HoleDest h      -> pprPanic "setWantedEq: HoleDest" (ppr h)
    
    2030 2047
     
    
    2031 2048
     fillCoercionHole :: CoercionHole -> CoercionPlusHoles -> TcS ()
    
    2032
    -fillCoercionHole hole co_plus_holes@(CPH { cph_co = co })
    
    2049
    +fillCoercionHole hole co_plus_holes
    
    2033 2050
       = 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 }
    
    2051
    +       ; wrapTcS $ TcM.addTcEvCoBind ev_binds_var hole co_plus_holes
    
    2038 2052
            ; kickOutAfterFillingCoercionHole hole co_plus_holes }
    
    2039 2053
     
    
    2040 2054
     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,44 +496,6 @@ 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 })
    
    507
    -  | not (warnRedundantGivens info)   -- Don't report redundant constraints at all
    
    508
    -  = []                    -- See (TRC4) of Note [Tracking redundant constraints]
    
    509
    -
    
    510
    -  | not (null unused_givens)         -- Some givens are literally unused
    
    511
    -  = unused_givens
    
    512
    -
    
    513
    -  -- Only try this if unused_givens is empty: see (TRC2a)
    
    514
    -  | otherwise                       -- All givens are used, but some might
    
    515
    -  = redundant_givens                -- still be redundant e.g. (Eq a, Ord a)
    
    516
    -
    
    517
    -  where
    
    518
    -    in_instance_decl = case info of { InstSkol {} -> True; _ -> False }
    
    519
    -                       -- See Note [Redundant constraints in instance decls]
    
    520
    -
    
    521
    -    unused_givens = filterOut is_used givens
    
    522
    -
    
    523
    -    needed_givens_ignoring_default_methods = ens_fvs need
    
    524
    -    is_used given =  is_type_error given
    
    525
    -                  || given `elemVarSet` needed_givens_ignoring_default_methods
    
    526
    -                  || (in_instance_decl && is_improving (idType given))
    
    527
    -
    
    528
    -    minimal_givens = mkMinimalBySCs evVarPred givens  -- See (TRC2)
    
    529
    -
    
    530
    -    is_minimal = (`elemVarSet` mkVarSet minimal_givens)
    
    531
    -    redundant_givens
    
    532
    -      | in_instance_decl = []
    
    533
    -      | otherwise        = filterOut is_minimal givens
    
    534
    -
    
    535
    -    -- See #15232
    
    536
    -    is_type_error id = containsUserTypeError False (idType id)
    
    537
    -      -- False <=> do not look under ty-fam apps, AppTy etc.
    
    538
    -      -- See (UTE1) in Note [Custom type errors in constraints].
    
    539
    -
    
    540
    -    is_improving pred -- (transSuperClasses p) does not include p
    
    541
    -      = any isImprovementPred (pred : transSuperClasses pred)
    
    542
    -
    
    543 499
     warnRedundantGivens :: SkolemInfoAnon -> Bool
    
    544 500
     warnRedundantGivens (SigSkol ctxt _ _)
    
    545 501
       = case ctxt of
    
    ... ... @@ -549,7 +505,7 @@ warnRedundantGivens (SigSkol ctxt _ _)
    549 505
     
    
    550 506
     warnRedundantGivens (InstSkol from _)
    
    551 507
      -- Do not report redundant constraints for quantified constraints
    
    552
    - -- See (TRC4) in Note [Tracking redundant constraints]
    
    508
    + -- See (TRC4) in Note [Tracking needed EvIds]
    
    553 509
      -- Fortunately it is easy to spot implications constraints that arise
    
    554 510
      -- from quantified constraints, from their SkolInfo
    
    555 511
      = case from of
    
    ... ... @@ -611,113 +567,142 @@ checkBadTelescope (Implic { ic_info = info
    611 567
           | otherwise
    
    612 568
           = go (later_skols `extendVarSet` one_skol) earlier_skols
    
    613 569
     
    
    614
    -neededEvVars :: Implication -> TcS Implication
    
    615
    --- Find all the evidence variables that are "needed",
    
    616
    --- /and/ delete dead evidence bindings
    
    570
    +computeSolvedStatus :: Implication -> TcS ImplicStatus
    
    571
    +-- Given a fully-solved implication,
    
    572
    +--    - Figure out the right IC_Solved fields
    
    573
    +--    - Delete unused evidence bindings
    
    617 574
     --
    
    618
    ---   See Note [Tracking redundant constraints]
    
    575
    +--   See Note [Tracking needed EvIds]
    
    619 576
     --   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
    
    577
    +computeSolvedStatus (Implic { ic_info        = info
    
    635 578
                                 , 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
    
    579
    +                            , ic_given       = givens
    
    580
    +                            , ic_wanted      = WC { wc_impl = implics } })
    
    581
    + = do { ev_binds_state <- TcS.getTcEvBindsState ev_binds_var
    
    582
    +
    
    583
    +      ; let EBS { ebs_binds = ev_binds, ebs_needs = local_needs } = ev_binds_state
    
    584
    +
    
    585
    +            -- Gather the raw needed EvIds, from the
    
    586
    +            -- current evidence bindings `local_needs`, and the `implics`
    
    587
    +            (need_dm, need_non_dm) = foldr add_implic (emptyVarSet, local_needs) implics
    
    588
    +
    
    589
    +            -- Do transitive closure through the evidence bindings
    
    590
    +            -- and delete all EvIds bound by the bindings
    
    591
    +            need_dm1     = findNeededGivenEvVars ev_binds need_dm
    
    592
    +            need_non_dm1 = findNeededGivenEvVars ev_binds need_non_dm
    
    593
    +
    
    594
    +            -- Compute the redundant Givens
    
    595
    +            dead_givens = findRedundantGivens info need_non_dm1 givens
    
    596
    +
    
    597
    +            -- Delete variables bound by ev_binds or by givens
    
    598
    +            need_dm2     = trim_needs need_dm1
    
    599
    +            need_non_dm2 = trim_needs need_non_dm1
    
    600
    +
    
    601
    +            trim_needs :: NeededEvIds -> NeededEvIds
    
    602
    +            trim_needs needs = (needs `varSetMinusEvBindsMap` ev_binds)
    
    603
    +                               `delVarSetList` givens
    
    604
    +
    
    605
    +      -- Prune dead Given evidence bindings
    
    665 606
           -- 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
    
    607
    +      ; let need_full       = need_dm1 `unionVarSet` need_non_dm1
    
    608
    +            pruned_ev_binds = filterEvBindsMap (keep_ev_bind need_full) ev_binds
    
    609
    +      ; TcS.setTcEvBindsMap ev_binds_var pruned_ev_binds
    
    610
    +
    
    611
    +      ; traceTcS "computeSolvedStatus" $
    
    612
    +        vcat [ text "local_needs:" <+> ppr local_needs
    
    613
    +             , text "need_dm:" <+> ppr need_dm
    
    614
    +             , text "need_non_dm:" <+> ppr need_non_dm
    
    615
    +             , text "need_dm1:" <+> ppr need_dm1
    
    616
    +             , text "need_non_dm1:" <+> ppr need_non_dm1
    
    617
    +             , text "need_dm2:" <+> ppr need_dm2
    
    618
    +             , text "need_non_dm2:" <+> ppr need_non_dm2
    
    676 619
                  , 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
    
    620
    +             , text "deleted ev_binds:"
    
    621
    +               <+> ppr (filterEvBindsMap (not . keep_ev_bind need_full) ev_binds) ]
    
    622
    +
    
    623
    +      ; if is_dm_skol info
    
    624
    +        then return (IC_Solved { ics_dead   = dead_givens
    
    625
    +                               , ics_dm     = need_dm2 `unionVarSet` need_non_dm2
    
    626
    +                               , ics_non_dm = emptyVarSet })
    
    684 627
     
    
    685
    -    add_implic :: Implication -> EvNeedSet -> EvNeedSet
    
    686
    -    add_implic (Implic { ic_given = givens, ic_need = need }) acc
    
    687
    -       = (need `delGivensFromEvNeedSet` givens) `unionEvNeedSet` acc
    
    628
    +        else return (IC_Solved { ics_dead   = dead_givens
    
    629
    +                               , ics_dm     = need_dm2
    
    630
    +                               , ics_non_dm = need_non_dm2 }) }
    
    631
    + where
    
    632
    +    add_implic :: Implication -> (NeededEvIds, NeededEvIds) -> (NeededEvIds, NeededEvIds)
    
    633
    +    add_implic (Implic { ic_status = status}) (dm2, non_dm2)
    
    634
    +       | IC_Solved { ics_dm = dm1, ics_non_dm = non_dm1 } <- status
    
    635
    +       = (dm1 `unionVarSet` dm2, non_dm1 `unionVarSet` non_dm2)
    
    636
    +       | otherwise
    
    637
    +       = pprPanic "computeSolvedStatus" (ppr implics)
    
    688 638
     
    
    689
    -    needed_ev_bind needed (EvBind { eb_lhs = ev_var, eb_info = info })
    
    639
    +    keep_ev_bind :: NeededEvIds -> EvBind -> Bool
    
    640
    +    -- False => we can discard this unused Given evidence binding
    
    641
    +    -- We always keep all the Wanted bindings
    
    642
    +    keep_ev_bind needed (EvBind { eb_lhs = ev_var, eb_info = info })
    
    690 643
           | EvBindGiven{} <- info = ev_var `elemVarSet` needed
    
    691 644
           | otherwise             = True   -- Keep all wanted bindings
    
    692 645
     
    
    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 646
         is_dm_skol :: SkolemInfoAnon -> Bool
    
    699 647
         is_dm_skol (MethSkol _ is_dm) = is_dm
    
    700 648
         is_dm_skol _                  = False
    
    701 649
     
    
    702
    -findNeededGivenEvVars :: EvBindMap -> VarSet -> VarSet
    
    650
    +findRedundantGivens :: SkolemInfoAnon -> NeededEvIds -> [EvVar] -> [EvVar]
    
    651
    +findRedundantGivens info need givens
    
    652
    +  | not (warnRedundantGivens info)   -- Don't report redundant constraints at all
    
    653
    +  = []                    -- See (TRC4) of Note [Tracking needed EvIds]
    
    654
    +
    
    655
    +  | not (null unused_givens)         -- Some givens are literally unused
    
    656
    +  = unused_givens
    
    657
    +
    
    658
    +  -- Only try this if unused_givens is empty: see (TRC2a)
    
    659
    +  | otherwise                       -- All givens are used, but some might
    
    660
    +  = redundant_givens                -- still be redundant e.g. (Eq a, Ord a)
    
    661
    +
    
    662
    +  where
    
    663
    +    in_instance_decl = case info of { InstSkol {} -> True; _ -> False }
    
    664
    +                       -- See Note [Redundant constraints in instance decls]
    
    665
    +
    
    666
    +    unused_givens = filterOut is_used givens
    
    667
    +
    
    668
    +    is_used given =  is_type_error given
    
    669
    +                  || given `elemVarSet` need
    
    670
    +                  || (in_instance_decl && is_improving (idType given))
    
    671
    +
    
    672
    +    minimal_givens = mkMinimalBySCs evVarPred givens  -- See (TRC2)
    
    673
    +
    
    674
    +    is_minimal = (`elemVarSet` mkVarSet minimal_givens)
    
    675
    +    redundant_givens
    
    676
    +      | in_instance_decl = []
    
    677
    +      | otherwise        = filterOut is_minimal givens
    
    678
    +
    
    679
    +    -- See #15232
    
    680
    +    is_type_error id = containsUserTypeError False (idType id)
    
    681
    +      -- False <=> do not look under ty-fam apps, AppTy etc.
    
    682
    +      -- See (UTE1) in Note [Custom type errors in constraints].
    
    683
    +
    
    684
    +    is_improving pred -- (transSuperClasses p) does not include p
    
    685
    +      = any isImprovementPred (pred : transSuperClasses pred)
    
    686
    +
    
    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)
    
    ... ... @@ -837,26 +822,80 @@ from TypeHole in HoleSort.
    837 822
     See also Note [Extra-constraint holes in partial type signatures]
    
    838 823
     in GHC.Tc.Gen.HsType.
    
    839 824
     
    
    840
    -Note [Tracking redundant constraints]
    
    841
    -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    842
    -With Opt_WarnRedundantConstraints, GHC can report which constraints of a type
    
    843
    -signature (or instance declaration) are redundant, and can be omitted.  Here is
    
    844
    -an overview of how it works.
    
    825
    +Note [Tracking needed EvIds]
    
    826
    +~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    827
    +The solver has some careful footwork to track:
    
    828
    +
    
    829
    +    Which Given EvIds are in fact needed
    
    830
    +
    
    831
    +The relevant type is NeededEvIds, which is just a VarSet; it may be a mixture
    
    832
    +of DictIds and CoVars.
    
    833
    +
    
    834
    +The NeededEvIds are used for two related purposes:
    
    845 835
     
    
    846
    -This is all tested in typecheck/should_compile/T20602 (among others).
    
    836
    +* Redundant Givens. With Opt_WarnRedundantConstraints, GHC can report which
    
    837
    +  constraints of a type signature (or instance declaration) are redundant, and
    
    838
    +  can be omitted.  We report this by computing which of the Implication's
    
    839
    +  `ic_givens` are not in the `NeededIds` for that Implication.
    
    847 840
     
    
    848
    -How tracking works:
    
    841
    +  See `findRedundantGivens`
    
    849 842
     
    
    850
    -* We maintain the `ic_need` field in an implication:
    
    851
    -     ic_need: the set of Given evidence variables that are needed somewhere
    
    852
    -              inside this implication; and are bound either by this implication
    
    853
    -              or by an enclosing one.
    
    843
    +* Pruning useless evidence bindings. The solver creates lots of superclass
    
    844
    +  bindings, in the EvBinds of an Implication, just in case they are needed.  So
    
    845
    +  we might get
    
    846
    +      \ (d::Ord a).  let d2:Eq a = sc_sel d in ...
    
    847
    +  That `d2` binding may or may not be needed.  For fully-solved implications,
    
    848
    +  GHC prunes away the un-needed bindings simply to reduce clutter; less to zonk,
    
    849
    +  less to desugar etc.
    
    854 850
     
    
    855
    -* `setImplicationStatus` does all the work:
    
    856
    -  - When the constraint solver finishes solving all the wanteds in
    
    857
    -    an implication, it sets its status to IC_Solved
    
    851
    +  See Note [Delete dead Given evidence bindings]
    
    852
    +  and the pruning code in `computeSolvedStatus`
    
    853
    +
    
    854
    +The tracking works like this:
    
    855
    +
    
    856
    +* An `Implication` has `ic_binds :: EvBindVar`.
    
    857
    +
    
    858
    +* That EvBindsVar holds a mutable reference to an `EvBindsState`.
    
    859
    +
    
    860
    +* That `EvBindsState` is a  pair of
    
    861
    +  * ebs_binds :: EvBindsMap    The evidence bindings themselves
    
    862
    +  * ebs_needs :: NeededEvIds   The free EvIds of the Wanted `ebs_binds`
    
    863
    +                               NB: only the Wanted ones!
    
    864
    +
    
    865
    +  When we add a new binding to `ebs_binds` we also add to `ebs_needs` the free
    
    866
    +  EvIds of the RHS, iff the binding is Wanted. Why Wanted only?  Each Wanted
    
    867
    +  binding solves a Wanted constraint, so we want them all. But Given bindings
    
    868
    +  are speculative; we work them out in `findNeededGivenEvVars`.
    
    869
    +
    
    870
    +  See `GHC.Tc.Utils.Monad.addTcEvBind` and `addTcCoBind`
    
    871
    +
    
    872
    +* When an implication is fully Solved, we give it an `ic_status` of IC_Solved,
    
    873
    +  in `setImplicationStatus`:
    
    874
    +     data ImplicStatus
    
    875
    +       = ...
    
    876
    +       | IC_Solved { ics_dead   :: [EvVar]
    
    877
    +                   , ics_dm     :: NeededEvIds
    
    878
    +                   , ics_non_dm :: NeededEvIds }
    
    879
    +   The `ics_dead` field records the `ic_given` EvVars that are unused.
    
    880
    +   The other two fields record the NeededEvIds bound by /enclosing/ Implications;
    
    881
    +   that is, the `ic_given` from /this/ implication have been removed.
    
    882
    +
    
    883
    +   Why two fields?  See (TRC5) below.
    
    884
    +
    
    885
    +* `computeSolvedStatus` does all the work of computing these fields.
    
    886
    +
    
    887
    +  - It combines the NeededEvIds from the sub-implications, plus
    
    888
    +    those from the bindings.
    
    889
    +
    
    890
    +  - It uses a transitive closure algorithm across the Given bindings
    
    891
    +    so find the transitive needs.  E.g. suppose the bindings are
    
    892
    +       [G] d2 = sc_sel d1
    
    893
    +       [G] d3 = sc_sel d2
    
    894
    +       [W] w1 = d3
    
    895
    +    The `ebs_needs` for these bindings will be {d3} (free var of the RHS
    
    896
    +    of the Wanted bindings). But needing d3 needs d2 and needing d2 needs
    
    897
    +    d1.   Hence the transitive closure in `findNeededGivenEvVars`.
    
    858 898
     
    
    859
    -  - `neededEvVars`: computes which evidence variables are needed by an
    
    860 899
         implication in `setImplicationStatus`.  A variable is needed if
    
    861 900
     
    
    862 901
           a) It is in the ic_need field of this implication, computed in
    
    ... ... @@ -884,15 +923,13 @@ How tracking works:
    884 923
     
    
    885 924
     Wrinkles:
    
    886 925
     
    
    887
    -(TRC1) `pruneImplications` drops any sub-implications of an Implication
    
    888
    -  that are irrelevant for error reporting:
    
    889
    -      - no unsolved wanteds
    
    890
    -      - no sub-implications
    
    891
    -      - no redundant givens to report
    
    892
    -  But in doing so we must not lose track of the variables that those implications
    
    893
    -  needed!  So we track the ic_needs of all child implications in `ic_need_implics`.
    
    894
    -  Crucially, this set includes things need by child implications that have been
    
    895
    -  discarded by `pruneImplications`.
    
    926
    +(TRC1) In `setImplicationStatus`, for a fully-solved Implication, we take
    
    927
    +  the opportunity to discard any fully-solved child implications, using
    
    928
    +  `pruneImplications`.  We can't drop /all/ fully-solved children; we can
    
    929
    +  drop a sub-implication  only if:
    
    930
    +     - it has empty `ics_dead` (if not, keep the Implication so we can report the
    
    931
    +       redundant givens later
    
    932
    +     - it itself has no sub-implications (presumably with redundant givens)
    
    896 933
     
    
    897 934
     (TRC2) A Given can be redundant because it is implied by other Givens
    
    898 935
              f :: (Eq a, Ord a)     => blah   -- Eq a unnecessary
    
    ... ... @@ -914,6 +951,7 @@ Wrinkles:
    914 951
       the one from the user-written Eq a, not the superclass selection. This means
    
    915 952
       we report the Ord a as redundant with -Wredundant-constraints, not the Eq a.
    
    916 953
       Getting this wrong was #20602.
    
    954
    +  See Note [Replacement vs keeping] in GHC.Tc.Solver.InertSet
    
    917 955
     
    
    918 956
     (TRC4) We don't compute redundant givens for *every* implication; only
    
    919 957
       for those which reply True to `warnRedundantGivens`:
    
    ... ... @@ -949,7 +987,7 @@ Wrinkles:
    949 987
          and because of the degnerate instance for `Show (T a)`, we don't need the `Eq a`
    
    950 988
          constraint.  But we don't want to report it as redundant!
    
    951 989
     
    
    952
    -(TRC5) Consider this (#25992), where `op2` has a default method
    
    990
    +(TRC5) Default methods.  Consider this (#25992), where `op2` has a default method
    
    953 991
             class C a where { op1, op2 :: a -> a
    
    954 992
                             ; op2 = op1 . op1 }
    
    955 993
             instance C a => C [a] where
    
    ... ... @@ -960,17 +998,22 @@ Wrinkles:
    960 998
             $dmop2 = op1 . op1
    
    961 999
     
    
    962 1000
             $fCList :: forall a. C a => C [a]
    
    963
    -        $fCList @a (d::C a) = MkC (\(x:a).x) ($dmop2 @a d)
    
    1001
    +        $fCList @a (d::C a) = MkC (\(x:a).x)
    
    1002
    +                                  ($dmop2 @[a] ($fCList @a d))
    
    1003
    +
    
    1004
    +   Notice that `d` gets passed (indirectly) to `$dmop`: it appears to be
    
    1005
    +   "needed".  But it's only /really/ needed if some /other/ method or
    
    1006
    +   superclass (in this case `op1`) uses it.
    
    964 1007
     
    
    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.
    
    1008
    +   So, in IC_Solved rather than one set of NeededEvIds we have /two/:
    
    1009
    +      ics_dm:     needed /only/ by default-method calls
    
    1010
    +      ics_non_dm: needed by something other than a default-method call
    
    1011
    +   Then:
    
    1012
    +      - For tracking redundant Givens we use only ics_non_dm
    
    1013
    +      - For pruning evidence bindings we use the union of the two
    
    967 1014
     
    
    968
    -   So, rather than one set of "needed Givens" we use `EvNeedSet` to track
    
    969
    -   a /pair/ of sets:
    
    970
    -      ens_dms: needed /only/ by default-method calls
    
    971
    -      ens_fvs: needed by something other than a default-method call
    
    972 1015
        It's a bit of a palaver, but not really difficult.
    
    973
    -   All the logic is localised in `neededEvVars`.
    
    1016
    +   All the logic is localised in `computeSolvedStatus`.
    
    974 1017
     
    
    975 1018
        But NOTE that this only applies to /vanilla/ default methods.
    
    976 1019
        For /generic/ default methods, like
    
    ... ... @@ -979,26 +1022,26 @@ Wrinkles:
    979 1022
        the (Eq a) constraint really is needed (e.g. class NFData and #25992).
    
    980 1023
        Hence the `Bool` field of `MethSkol` indicates a /vanilla/ default method.
    
    981 1024
     
    
    982
    ------ Examples
    
    1025
    +----- Examples of reporting redundant Givens
    
    983 1026
     
    
    984 1027
         f, g, h :: (Eq a, Ord a) => a -> Bool
    
    985 1028
         f x = x == x
    
    986 1029
         g x = x > x
    
    987 1030
         h x = x == x && x > x
    
    988 1031
     
    
    989
    -    All of f,g,h will discover that they have two [G] Eq a constraints: one as
    
    990
    -    given and one extracted from the Ord a constraint. They will both discard
    
    991
    -    the latter; see (TRC3).
    
    1032
    +All of f,g,h will discover that they have two [G] Eq a constraints: one as
    
    1033
    +given and one extracted from the Ord a constraint. They will both discard
    
    1034
    +the latter; see (TRC3).
    
    992 1035
     
    
    993
    -    The body of f uses the [G] Eq a, but not the [G] Ord a. It will report a
    
    994
    -    redundant Ord a.
    
    1036
    +* The body of f uses the [G] Eq a, but not the [G] Ord a. It will report a
    
    1037
    +  redundant Ord a.
    
    995 1038
     
    
    996
    -    The body of g uses the [G] Ord a, but not the [G] Eq a. It will report a
    
    997
    -    redundant Eq a.
    
    1039
    +* The body of g uses the [G] Ord a, but not the [G] Eq a. It will report a
    
    1040
    +  redundant Eq a.
    
    998 1041
     
    
    999
    -    The body of h uses both [G] Ord a and [G] Eq a; each is used in a solved
    
    1000
    -    Wanted evidence binding.  But (TRC2) kicks in and discovers the Eq a
    
    1001
    -    is redundant.
    
    1042
    +* The body of h uses both [G] Ord a and [G] Eq a; each is used in a solved
    
    1043
    +  Wanted evidence binding.  But (TRC2) kicks in and discovers the Eq a
    
    1044
    +  is redundant.
    
    1002 1045
     
    
    1003 1046
     ----- Shortcomings
    
    1004 1047
     
    
    ... ... @@ -1010,10 +1053,10 @@ Shortcoming 1. Consider
    1010 1053
       k :: (Eq a, b ~ a) => a -> Bool
    
    1011 1054
       k x = x == x
    
    1012 1055
     
    
    1013
    -Currently (Nov 2021), j issues no warning, while k says that b ~ a
    
    1014
    -is redundant. This is because j uses the a ~ b constraint to rewrite
    
    1015
    -everything to be in terms of b, while k does none of that. This is
    
    1016
    -ridiculous, but I (Richard E) don't see a good fix.
    
    1056
    +Currently (Nov 2021), j issues no warning, while k says that b ~ a is
    
    1057
    +redundant. This is because j uses the a ~ b constraint to rewrite everything to
    
    1058
    +be in terms of b, while k does none of that. This is ridiculous, but I (Richard
    
    1059
    +E) don't see a good fix.
    
    1017 1060
     
    
    1018 1061
     Shortcoming 2.  Removing a redundant constraint can cause clients to fail to
    
    1019 1062
     compile, by making the function more polymorphic. Consider (#16154)
    
    ... ... @@ -1645,10 +1688,12 @@ solveWantedQCI mode ct@(CQuantCan (QCI { qci_ev = ev, qci_tvs = tvs
    1645 1688
                   --     carrying a record of which evidence variables are used
    
    1646 1689
                   --     See Note [Free vars of EvFun] in GHC.Tc.Types.Evidence
    
    1647 1690
                  do { setWantedDict dest EvCanonical $
    
    1648
    -                  EvFun { et_tvs = skol_tvs, et_given = given_ev_vars
    
    1691
    +                  EvFun { et_tvs   = skol_tvs
    
    1692
    +                        , et_given = given_ev_vars
    
    1649 1693
                             , et_binds = TcEvBinds ev_binds_var
    
    1650
    -                        , et_body = wantedCtEvEvId wanted_ev }
    
    1694
    +                        , et_body  = wantedCtEvEvId wanted_ev }
    
    1651 1695
     
    
    1696
    +                ; traceTcS "solveWantedQCI" (ppr imp')
    
    1652 1697
                     ; return (Right imp') }
    
    1653 1698
         }
    
    1654 1699
     
    

  • compiler/GHC/Tc/TyCl/Instance.hs
    ... ... @@ -1481,8 +1481,7 @@ Notice that
    1481 1481
        implication for the whole instance declaration, with the expected
    
    1482 1482
        skolems and givens.  We need this to get the correct "redundant
    
    1483 1483
        constraint" warnings, gathering all the uses from all the methods
    
    1484
    -   and superclasses.  See GHC.Tc.Solver Note [Tracking redundant
    
    1485
    -   constraints]
    
    1484
    +   and superclasses.  See GHC.Tc.SolverSolve Note [Tracking needed EvIds]
    
    1486 1485
     
    
    1487 1486
      * The given constraints in the outer implication may generate
    
    1488 1487
        evidence, notably by superclass selection.  Since the method and
    
    ... ... @@ -1947,7 +1946,7 @@ tcMethods _skol_info dfun_id clas tyvars dfun_ev_vars inst_tys
    1947 1946
             mismatched_meths = bind_nms `minusList` cls_meth_nms
    
    1948 1947
     
    
    1949 1948
         is_vanilla_dm :: DefMethSpec ty -> Bool
    
    1950
    -    -- See (TRC5) in Note [Tracking redundant constraints]
    
    1949
    +    -- See (TRC5) in Note [Tracking needed EvIds]
    
    1951 1950
         --            in GHC.Tc.Solver.Solve
    
    1952 1951
         is_vanilla_dm VanillaDM      = True
    
    1953 1952
         is_vanilla_dm (GenericDM {}) = False
    
    ... ... @@ -2022,7 +2021,7 @@ Instead, we take the following approach:
    2022 2021
     
    
    2023 2022
     ------------------------
    
    2024 2023
     tcMethodBody :: Bool   -- True <=> This is a vanilla default method
    
    2025
    -                       -- See (TRC5) in Note [Tracking redundant constraints]
    
    2024
    +                       -- See (TRC5) in Note [Tracking needed EvIds]
    
    2026 2025
                            --            in GHC.Tc.Solver.Solve
    
    2027 2026
                  -> Class -> [TcTyVar] -> [EvVar] -> [TcType]
    
    2028 2027
                  -> TcEvBinds -> Bool
    

  • 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,
    
    ... ... @@ -1061,6 +1060,13 @@ mkImplicWC :: Bag Implication -> WantedConstraints
    1061 1060
     mkImplicWC implic
    
    1062 1061
       = emptyWC { wc_impl = implic }
    
    1063 1062
     
    
    1063
    +-- | `isEmptyWC` sees if a `WantedConstraints` is truly empty, including
    
    1064
    +-- having no implications.
    
    1065
    +--
    
    1066
    +-- It's possible that it might have /solved/ implications, which are left around
    
    1067
    +-- just so we can report unreachable code.  So:
    
    1068
    +--    isEmptyWC implies isSolvedWC
    
    1069
    +-- but not vice versa
    
    1064 1070
     isEmptyWC :: WantedConstraints -> Bool
    
    1065 1071
     isEmptyWC (WC { wc_simple = f, wc_impl = i, wc_errors = errors })
    
    1066 1072
       = isEmptyBag f && isEmptyBag i && isEmptyBag errors
    
    ... ... @@ -1563,45 +1569,9 @@ data Implication
    1563 1569
           ic_binds  :: EvBindsVar,    -- Points to the place to fill in the
    
    1564 1570
                                       -- abstraction and bindings.
    
    1565 1571
     
    
    1566
    -      -- The ic_need fields keep track of which Given evidence
    
    1567
    -      -- is used by this implication or its children
    
    1568
    -      -- See Note [Tracking redundant constraints]
    
    1569
    -      -- NB: these sets include stuff used by fully-solved nested implications
    
    1570
    -      --     that have since been discarded
    
    1571
    -      ic_need  :: EvNeedSet,        -- All needed Given evidence, from this implication
    
    1572
    -                                    --   or outer ones
    
    1573
    -                                    -- That is, /after/ deleting the binders of ic_binds,
    
    1574
    -                                    --   but /before/ deleting ic_givens
    
    1575
    -
    
    1576
    -      ic_need_implic :: EvNeedSet,  -- Union of of the ic_need of all implications in ic_wanted
    
    1577
    -                                    -- /including/ any fully-solved implications that have been
    
    1578
    -                                    -- discarded by `pruneImplications`.  This discarding is why
    
    1579
    -                                    -- we need to keep this field in the first place.
    
    1580
    -
    
    1581 1572
           ic_status   :: ImplicStatus
    
    1582 1573
         }
    
    1583 1574
     
    
    1584
    -data EvNeedSet = ENS { ens_dms :: VarSet   -- Needed only by default methods
    
    1585
    -                     , ens_fvs :: VarSet   -- Needed by things /other than/ default methods
    
    1586
    -                       -- See (TRC5) in Note [Tracking redundant constraints]
    
    1587
    -                 }
    
    1588
    -
    
    1589
    -emptyEvNeedSet :: EvNeedSet
    
    1590
    -emptyEvNeedSet = ENS { ens_dms = emptyVarSet, ens_fvs = emptyVarSet }
    
    1591
    -
    
    1592
    -unionEvNeedSet :: EvNeedSet -> EvNeedSet -> EvNeedSet
    
    1593
    -unionEvNeedSet (ENS { ens_dms = dm1, ens_fvs = fv1 })
    
    1594
    -               (ENS { ens_dms = dm2, ens_fvs = fv2 })
    
    1595
    -  = ENS { ens_dms = dm1 `unionVarSet` dm2, ens_fvs = fv1 `unionVarSet` fv2 }
    
    1596
    -
    
    1597
    -extendEvNeedSet :: EvNeedSet -> Var -> EvNeedSet
    
    1598
    -extendEvNeedSet ens@(ENS { ens_fvs = fvs }) v = ens { ens_fvs = fvs `extendVarSet` v }
    
    1599
    -
    
    1600
    -delGivensFromEvNeedSet :: EvNeedSet -> [Var] -> EvNeedSet
    
    1601
    -delGivensFromEvNeedSet (ENS { ens_dms = dms, ens_fvs = fvs }) givens
    
    1602
    -  = ENS { ens_dms = dms `delVarSetList` givens
    
    1603
    -        , ens_fvs = fvs `delVarSetList` givens }
    
    1604
    -
    
    1605 1575
     implicationPrototype :: CtLocEnv -> Implication
    
    1606 1576
     implicationPrototype ct_loc_env
    
    1607 1577
        = Implic { -- These fields must be initialised
    
    ... ... @@ -1618,14 +1588,21 @@ implicationPrototype ct_loc_env
    1618 1588
                 , ic_given       = []
    
    1619 1589
                 , ic_wanted      = emptyWC
    
    1620 1590
                 , ic_given_eqs   = MaybeGivenEqs
    
    1621
    -            , ic_status      = IC_Unsolved
    
    1622
    -            , ic_need        = emptyEvNeedSet
    
    1623
    -            , ic_need_implic = emptyEvNeedSet }
    
    1591
    +            , ic_status      = IC_Unsolved }
    
    1624 1592
     
    
    1625 1593
     data ImplicStatus
    
    1626 1594
       = IC_Solved     -- All wanteds in the tree are solved, all the way down
    
    1627
    -       { ics_dead :: [EvVar] }  -- Subset of ic_given that are not needed
    
    1628
    -         -- See Note [Tracking redundant constraints] in GHC.Tc.Solver
    
    1595
    +       { ics_dead   :: [EvVar]     -- Subset of ic_given that are not needed
    
    1596
    +
    
    1597
    +       , ics_dm     :: NeededEvIds -- Enclosing Given EvIds that are needed by
    
    1598
    +                                   -- calls to default methods (typically empty)
    
    1599
    +
    
    1600
    +       , ics_non_dm :: NeededEvIds -- Enclosing Given EvIds that are needed, other than
    
    1601
    +                                   -- calls to default methods
    
    1602
    +       }
    
    1603
    +      -- Reporting redundant givens: use ics_non_dm
    
    1604
    +      -- Pruning evidence bindings:  use ics_dm `union` ics_non_dm
    
    1605
    +      -- See Note [Tracking needed EvIds] in GHC.Tc.Solver.Solve
    
    1629 1606
     
    
    1630 1607
       | IC_Insoluble  -- At least one insoluble Wanted constraint in the tree
    
    1631 1608
     
    
    ... ... @@ -1714,7 +1691,6 @@ instance Outputable Implication where
    1714 1691
                   , ic_given = given, ic_given_eqs = given_eqs
    
    1715 1692
                   , ic_wanted = wanted, ic_status = status
    
    1716 1693
                   , ic_binds = binds
    
    1717
    -              , ic_need = need, ic_need_implic = need_implic
    
    1718 1694
                   , ic_info = info })
    
    1719 1695
        = hang (text "Implic" <+> lbrace)
    
    1720 1696
             2 (sep [ text "TcLevel =" <+> ppr tclvl
    
    ... ... @@ -1724,21 +1700,17 @@ instance Outputable Implication where
    1724 1700
                    , hang (text "Given =")  2 (pprEvVars given)
    
    1725 1701
                    , hang (text "Wanted =") 2 (ppr wanted)
    
    1726 1702
                    , text "Binds =" <+> ppr binds
    
    1727
    -               , text "need =" <+> ppr need
    
    1728
    -               , text "need_implic =" <+> ppr need_implic
    
    1729 1703
                    , pprSkolInfo info ] <+> rbrace)
    
    1730 1704
     
    
    1731
    -instance Outputable EvNeedSet where
    
    1732
    -  ppr (ENS { ens_dms = dms, ens_fvs = fvs })
    
    1733
    -    = text "ENS" <> braces (sep [text "ens_dms =" <+> ppr dms
    
    1734
    -                                , text "ens_fvs =" <+> ppr fvs])
    
    1735
    -
    
    1736 1705
     instance Outputable ImplicStatus where
    
    1737 1706
       ppr IC_Insoluble    = text "Insoluble"
    
    1738 1707
       ppr IC_BadTelescope = text "Bad telescope"
    
    1739 1708
       ppr IC_Unsolved     = text "Unsolved"
    
    1740
    -  ppr (IC_Solved { ics_dead = dead })
    
    1741
    -    = text "Solved" <+> (braces (text "Dead givens =" <+> ppr dead))
    
    1709
    +  ppr (IC_Solved { ics_dead = dead, ics_dm = dm, ics_non_dm = non_dm })
    
    1710
    +    = text "Solved" <> (braces $
    
    1711
    +      vcat [ text "Dead givens =" <+> ppr dead
    
    1712
    +           , text "need_dm =" <+> ppr dm
    
    1713
    +           , text "need_non_dm =" <+> ppr non_dm ])
    
    1742 1714
     
    
    1743 1715
     checkTelescopeSkol :: SkolemInfoAnon -> Bool
    
    1744 1716
     -- 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, addNeededEvIdsEBS,
    
    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,30 +726,45 @@ 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
    -      -- Some Given, some Wanted
    
    732
    -
    
    733
    -      ebv_tcvs :: IORef [TcCoercion]
    
    734
    -      -- When we solve a Wanted by filling in a CoercionHole, it is as
    
    735
    -      -- if we were adding an evidence binding
    
    736
    -      --       co_hole := coercion
    
    737
    -      -- We keep all these RHS coercions in a list, alongside `ebv_binds`,
    
    738
    -      --  so that we can report unused given constraints,
    
    739
    -      --  in GHC.Tc.Solver.neededEvVars
    
    740
    -      -- See Note [Tracking redundant constraints] in GHC.Tc.Solver
    
    741
    -      -- Also: we garbage-collect unused bindings in `neededEvVars`,
    
    742
    -      --       so this matters for correctness too.
    
    732
    +      -- Some Given, some Wanted; this is tracked in the `eb_info`
    
    733
    +      -- field of the `EvBind`.
    
    743 734
         }
    
    744 735
     
    
    745 736
       | CoEvBindsVar {  -- See Note [Coercion evidence only]
    
    746 737
     
    
    747 738
           -- See above for comments on ebv_uniq, ebv_tcvs
    
    748
    -      ebv_uniq :: Unique,
    
    749
    -      ebv_tcvs :: IORef [TcCoercion]
    
    739
    +      ebv_uniq  :: Unique,
    
    740
    +      ebv_needs :: IORef NeededEvIds
    
    750 741
         }
    
    751 742
     
    
    743
    +type NeededEvIds = VarSet
    
    744
    +
    
    745
    +data EvBindsState = EBS { ebs_binds :: EvBindsMap
    
    746
    +                        , ebs_needs :: NeededEvIds }
    
    747
    +
    
    748
    +emptyEvBindsState :: EvBindsState
    
    749
    +emptyEvBindsState = EBS { ebs_binds = emptyEvBindsMap
    
    750
    +                        , ebs_needs = emptyVarSet }
    
    751
    +
    
    752
    +unionEvBindsState :: EvBindsState -> EvBindsState -> EvBindsState
    
    753
    +unionEvBindsState (EBS { ebs_binds = bs1, ebs_needs = n1 })
    
    754
    +                  (EBS { ebs_binds = bs2, ebs_needs = n2 })
    
    755
    +  = EBS { ebs_binds = bs1 `unionEvBindsMap` bs2
    
    756
    +        , ebs_needs = n1  `unionVarSet`    n2 }
    
    757
    +
    
    758
    +addNeededEvIdsEBS :: NeededEvIds -> EvBindsState -> EvBindsState
    
    759
    +addNeededEvIdsEBS n1 ebs@(EBS { ebs_needs = n2 })
    
    760
    +  = ebs { ebs_needs = n1 `unionVarSet` n2 }
    
    761
    +
    
    762
    +instance Outputable EvBindsState where
    
    763
    +  ppr (EBS { ebs_binds = bs, ebs_needs = needs })
    
    764
    +    = text "EBS" <> (braces $
    
    765
    +        sep [ text "needs =" <+> ppr needs
    
    766
    +            , text "binds =" <+> ppr bs ])
    
    767
    +
    
    752 768
     instance Data.Data TcEvBinds where
    
    753 769
       -- Placeholder; we can't traverse into TcEvBinds
    
    754 770
       toConstr _   = abstractConstr "TcEvBinds"
    
    ... ... @@ -778,8 +794,8 @@ isCoEvBindsVar (CoEvBindsVar {}) = True
    778 794
     isCoEvBindsVar (EvBindsVar {})   = False
    
    779 795
     
    
    780 796
     -----------------
    
    781
    -newtype EvBindMap
    
    782
    -  = EvBindMap {
    
    797
    +newtype EvBindsMap
    
    798
    +  = EvBindsMap {
    
    783 799
            ev_bind_varenv :: DVarEnv EvBind
    
    784 800
         }       -- Map from evidence variables to evidence terms
    
    785 801
                 -- We use @DVarEnv@ here to get deterministic ordering when we
    
    ... ... @@ -801,56 +817,56 @@ newtype EvBindMap
    801 817
                 -- See Note [Deterministic UniqFM] in GHC.Types.Unique.DFM for explanation why
    
    802 818
                 -- @UniqFM@ can lead to nondeterministic order.
    
    803 819
     
    
    804
    -emptyEvBindMap :: EvBindMap
    
    805
    -emptyEvBindMap = EvBindMap { ev_bind_varenv = emptyDVarEnv }
    
    820
    +emptyEvBindsMap :: EvBindsMap
    
    821
    +emptyEvBindsMap = EvBindsMap { ev_bind_varenv = emptyDVarEnv }
    
    806 822
     
    
    807
    -extendEvBinds :: EvBindMap -> EvBind -> EvBindMap
    
    823
    +extendEvBinds :: EvBindsMap -> EvBind -> EvBindsMap
    
    808 824
     extendEvBinds bs ev_bind
    
    809
    -  = EvBindMap { ev_bind_varenv = extendDVarEnv (ev_bind_varenv bs)
    
    825
    +  = EvBindsMap { ev_bind_varenv = extendDVarEnv (ev_bind_varenv bs)
    
    810 826
                                                    (eb_lhs ev_bind)
    
    811 827
                                                    ev_bind }
    
    812 828
     
    
    813 829
     -- | Union two evidence binding maps
    
    814
    -unionEvBindMap :: EvBindMap -> EvBindMap -> EvBindMap
    
    815
    -unionEvBindMap (EvBindMap env1) (EvBindMap env2) =
    
    816
    -  EvBindMap { ev_bind_varenv = plusDVarEnv env1 env2 }
    
    830
    +unionEvBindsMap :: EvBindsMap -> EvBindsMap -> EvBindsMap
    
    831
    +unionEvBindsMap (EvBindsMap env1) (EvBindsMap env2) =
    
    832
    +  EvBindsMap { ev_bind_varenv = plusDVarEnv env1 env2 }
    
    817 833
     
    
    818
    -isEmptyEvBindMap :: EvBindMap -> Bool
    
    819
    -isEmptyEvBindMap (EvBindMap m) = isEmptyDVarEnv m
    
    834
    +isEmptyEvBindsMap :: EvBindsMap -> Bool
    
    835
    +isEmptyEvBindsMap (EvBindsMap m) = isEmptyDVarEnv m
    
    820 836
     
    
    821
    -lookupEvBind :: EvBindMap -> EvVar -> Maybe EvBind
    
    837
    +lookupEvBind :: EvBindsMap -> EvVar -> Maybe EvBind
    
    822 838
     lookupEvBind bs = lookupDVarEnv (ev_bind_varenv bs)
    
    823 839
     
    
    824
    -evBindMapBinds :: EvBindMap -> Bag EvBind
    
    825
    -evBindMapBinds = foldEvBindMap consBag emptyBag
    
    840
    +evBindMapBinds :: EvBindsMap -> Bag EvBind
    
    841
    +evBindMapBinds = foldEvBindsMap consBag emptyBag
    
    826 842
     
    
    827
    -foldEvBindMap :: (EvBind -> a -> a) -> a -> EvBindMap -> a
    
    828
    -foldEvBindMap k z bs = foldDVarEnv k z (ev_bind_varenv bs)
    
    843
    +foldEvBindsMap :: (EvBind -> a -> a) -> a -> EvBindsMap -> a
    
    844
    +foldEvBindsMap k z bs = foldDVarEnv k z (ev_bind_varenv bs)
    
    829 845
     
    
    830 846
     -- See Note [Deterministic UniqFM] to learn about nondeterminism.
    
    831 847
     -- If you use this please provide a justification why it doesn't introduce
    
    832 848
     -- nondeterminism.
    
    833
    -nonDetStrictFoldEvBindMap :: (EvBind -> a -> a) -> a -> EvBindMap -> a
    
    834
    -nonDetStrictFoldEvBindMap k z bs = nonDetStrictFoldDVarEnv k z (ev_bind_varenv bs)
    
    849
    +nonDetStrictFoldEvBindsMap :: (EvBind -> a -> a) -> a -> EvBindsMap -> a
    
    850
    +nonDetStrictFoldEvBindsMap k z bs = nonDetStrictFoldDVarEnv k z (ev_bind_varenv bs)
    
    835 851
     
    
    836
    -filterEvBindMap :: (EvBind -> Bool) -> EvBindMap -> EvBindMap
    
    837
    -filterEvBindMap k (EvBindMap { ev_bind_varenv = env })
    
    838
    -  = EvBindMap { ev_bind_varenv = filterDVarEnv k env }
    
    852
    +filterEvBindsMap :: (EvBind -> Bool) -> EvBindsMap -> EvBindsMap
    
    853
    +filterEvBindsMap k (EvBindsMap { ev_bind_varenv = env })
    
    854
    +  = EvBindsMap { ev_bind_varenv = filterDVarEnv k env }
    
    839 855
     
    
    840
    -evBindMapToVarSet :: EvBindMap -> VarSet
    
    841
    -evBindMapToVarSet (EvBindMap dve) = unsafeUFMToUniqSet (mapUFM evBindVar (udfmToUfm dve))
    
    856
    +evBindMapToVarSet :: EvBindsMap -> VarSet
    
    857
    +evBindMapToVarSet (EvBindsMap dve) = unsafeUFMToUniqSet (mapUFM evBindVar (udfmToUfm dve))
    
    842 858
     
    
    843
    -varSetMinusEvBindMap :: VarSet -> EvBindMap -> VarSet
    
    844
    -varSetMinusEvBindMap vs (EvBindMap dve) = vs `uniqSetMinusUDFM` dve
    
    859
    +varSetMinusEvBindsMap :: VarSet -> EvBindsMap -> VarSet
    
    860
    +varSetMinusEvBindsMap vs (EvBindsMap dve) = vs `uniqSetMinusUDFM` dve
    
    845 861
     
    
    846
    -instance Outputable EvBindMap where
    
    847
    -  ppr (EvBindMap m) = ppr m
    
    862
    +instance Outputable EvBindsMap where
    
    863
    +  ppr (EvBindsMap m) = ppr m
    
    848 864
     
    
    849
    -data EvBindInfo
    
    850
    -  = EvBindGiven { -- See Note [Tracking redundant constraints] in GHC.Tc.Solver
    
    851
    -    }
    
    852
    -  | EvBindWanted { ebi_canonical :: CanonicalEvidence -- See Note [Desugaring non-canonical evidence]
    
    853
    -    }
    
    865
    +data EvBindInfo    -- See Note [Tracking needed EvIds] in GHC.Tc.Solver.Solve
    
    866
    +  = EvBindGiven
    
    867
    +  | EvBindWanted
    
    868
    +      { ebi_canonical :: CanonicalEvidence }
    
    869
    +        -- See Note [Desugaring non-canonical evidence]
    
    854 870
     
    
    855 871
     -----------------
    
    856 872
     -- All evidence is bound by EvBinds; no side effects
    
    ... ... @@ -1334,7 +1350,7 @@ can just squeeze by. Here's how.
    1334 1350
       * Each EvBindsVar in an et_binds field of an EvFun is /also/ in the
    
    1335 1351
         ic_binds field of an Implication
    
    1336 1352
       * So we can track usage via the processing for that implication,
    
    1337
    -    (see Note [Tracking redundant constraints] in GHC.Tc.Solver).
    
    1353
    +    (see Note [Tracking needed EvIds] in GHC.Tc.Solver).
    
    1338 1354
         We can ignore usage from the EvFun altogether.
    
    1339 1355
     
    
    1340 1356
     * /After/ typechecking `evTermFVs` is used by `GHC.Iface.Ext.Ast`, but by
    

  • compiler/GHC/Tc/Types/Origin.hs
    ... ... @@ -94,7 +94,7 @@ data UserTypeCtxt
    94 94
                         -- Also used for types in SPECIALISE pragmas
    
    95 95
            Name              -- Name of the function
    
    96 96
            ReportRedundantConstraints
    
    97
    -         -- See Note [Tracking redundant constraints] in GHC.Tc.Solver
    
    97
    +         -- See Note [Tracking needed EvIds] in GHC.Tc.Solver
    
    98 98
              -- This field is usually 'WantRCC', but 'NoRCC' for
    
    99 99
              --   * Record selectors (not important here)
    
    100 100
              --   * Class and instance methods.  Here the code may legitimately
    
    ... ... @@ -285,7 +285,7 @@ data SkolemInfoAnon
    285 285
       | MethSkol Name Bool  -- Bound by the type of class method op
    
    286 286
                             -- True  <=> it's a vanilla default method
    
    287 287
                             -- False <=> it's a user-written, or generic-default, method
    
    288
    -                        -- See (TRC5) in Note [Tracking redundant constraints]
    
    288
    +                        -- See (TRC5) in Note [Tracking needed EvIds]
    
    289 289
                             --            in GHC.Tc.Solver.Solve
    
    290 290
     
    
    291 291
       | FamInstSkol         -- Bound at a family instance decl
    

  • 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, addNeededEvIds,
    
    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
    
    ... ... @@ -1661,6 +1665,105 @@ tryTcDiscardingErrs' validate recover_invalid recover_error thing_inside
    1661 1665
                      recover_error
    
    1662 1666
             }
    
    1663 1667
     
    
    1668
    +{- Note [Constraints and errors]
    
    1669
    +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    1670
    +Consider this (#12124):
    
    1671
    +
    
    1672
    +  foo :: Maybe Int
    
    1673
    +  foo = return (case Left 3 of
    
    1674
    +                  Left -> 1  -- Hard error here!
    
    1675
    +                  _    -> 0)
    
    1676
    +
    
    1677
    +The call to 'return' will generate a (Monad m) wanted constraint; but
    
    1678
    +then there'll be "hard error" (i.e. an exception in the TcM monad), from
    
    1679
    +the unsaturated Left constructor pattern.
    
    1680
    +
    
    1681
    +We'll recover in tcPolyBinds, using recoverM.  But then the final
    
    1682
    +tcSimplifyTop will see that (Monad m) constraint, with 'm' utterly
    
    1683
    +un-filled-in, and will emit a misleading error message.
    
    1684
    +
    
    1685
    +The underlying problem is that an exception interrupts the constraint
    
    1686
    +gathering process. Bottom line: if we have an exception, it's best
    
    1687
    +simply to discard any gathered constraints.  Hence in 'attemptM' we
    
    1688
    +capture the constraints in a fresh variable, and only emit them into
    
    1689
    +the surrounding context if we exit normally.  If an exception is
    
    1690
    +raised, simply discard the collected constraints... we have a hard
    
    1691
    +error to report.  So this capture-the-emit dance isn't as stupid as it
    
    1692
    +looks :-).
    
    1693
    +
    
    1694
    +However suppose we throw an exception inside an invocation of
    
    1695
    +captureConstraints, and discard all the constraints. Some of those
    
    1696
    +constraints might be "variable out of scope" Hole constraints, and that
    
    1697
    +might have been the actual original cause of the exception!  For
    
    1698
    +example (#12529):
    
    1699
    +   f = p @ Int
    
    1700
    +Here 'p' is out of scope, so we get an insoluble Hole constraint. But
    
    1701
    +the visible type application fails in the monad (throws an exception).
    
    1702
    +We must not discard the out-of-scope error.
    
    1703
    +
    
    1704
    +It's distressingly delicate though:
    
    1705
    +
    
    1706
    +* If we discard too /many/ constraints we may fail to report the error
    
    1707
    +  that led us to interrupt the constraint gathering process.
    
    1708
    +
    
    1709
    +  One particular example "variable out of scope" Hole constraints. For
    
    1710
    +  example (#12529):
    
    1711
    +   f = p @ Int
    
    1712
    +  Here 'p' is out of scope, so we get an insoluble Hole constraint. But
    
    1713
    +  the visible type application fails in the monad (throws an exception).
    
    1714
    +  We must not discard the out-of-scope error.
    
    1715
    +
    
    1716
    +  Also GHC.Tc.Solver.simplifyAndEmitFlatConstraints may fail having
    
    1717
    +  emitted some constraints with skolem-escape problems.
    
    1718
    +
    
    1719
    +* If we discard too /few/ constraints, we may get the misleading
    
    1720
    +  class constraints mentioned above.
    
    1721
    +
    
    1722
    +  We may /also/ end up taking constraints built at some inner level, and
    
    1723
    +  emitting them (via the exception catching in `tryCaptureConstraints`) at some
    
    1724
    +  outer level, and then breaking the TcLevel invariants See Note [TcLevel
    
    1725
    +  invariants] in GHC.Tc.Utils.TcType
    
    1726
    +
    
    1727
    +So `dropMisleading` has a horridly ad-hoc structure:
    
    1728
    +
    
    1729
    +* It keeps only /insoluble/ flat constraints (which are unlikely to very visibly
    
    1730
    +  trip up on the TcLevel invariant)
    
    1731
    +
    
    1732
    +* But it keeps all /implication/ constraints (except the class constraints
    
    1733
    +  inside them).  The implication constraints are OK because they set the ambient
    
    1734
    +  level before attempting to solve any inner constraints.
    
    1735
    +
    
    1736
    +Ugh! I hate this. But it seems to work.
    
    1737
    +
    
    1738
    +Other wrinkles
    
    1739
    +
    
    1740
    +(CERR1) Note that freshly-generated constraints like (Int ~ Bool), or
    
    1741
    +    ((a -> b) ~ Int) are all CNonCanonical, and hence won't be flagged as
    
    1742
    +    insoluble.  The constraint solver does that.  So they'll be discarded.
    
    1743
    +    That's probably ok; but see th/5358 as a not-so-good example:
    
    1744
    +       t1 :: Int
    
    1745
    +       t1 x = x   -- Manifestly wrong
    
    1746
    +
    
    1747
    +       foo = $(...raises exception...)
    
    1748
    +    We report the exception, but not the bug in t1.  Oh well.  Possible
    
    1749
    +    solution: make GHC.Tc.Utils.Unify.uType spot manifestly-insoluble constraints.
    
    1750
    +
    
    1751
    +(CERR2) In #26015 I found that from the constraints
    
    1752
    +           [W] alpha ~ Int      -- A class constraint
    
    1753
    +           [W] F alpha ~# Bool  -- An equality constraint
    
    1754
    +  we were dropping the first (because it's a class constraint) but not the
    
    1755
    +  second, and then getting a misleading error message from the second.  As
    
    1756
    +  #25607 shows, we can get not just one but a zillion bogus messages, which
    
    1757
    +  conceal the one genuine error.  Boo.
    
    1758
    +
    
    1759
    +  For now I have added an even more ad-hoc "drop class constraints except
    
    1760
    +  equality classes (~) and (~~)"; see `dropMisleading`.  That just kicks the can
    
    1761
    +  down the road; but this problem seems somewhat rare anyway.  The code in
    
    1762
    +  `dropMisleading` hasn't changed for years.
    
    1763
    +
    
    1764
    +It would be great to have a more systematic solution to this entire mess.
    
    1765
    +-}
    
    1766
    +
    
    1664 1767
     {-
    
    1665 1768
     ************************************************************************
    
    1666 1769
     *                                                                      *
    
    ... ... @@ -1855,108 +1958,113 @@ debugTc thing
    1855 1958
     
    
    1856 1959
     addTopEvBinds :: Bag EvBind -> TcM a -> TcM a
    
    1857 1960
     addTopEvBinds new_ev_binds thing_inside
    
    1858
    -  =updGblEnv upd_env thing_inside
    
    1961
    +  = updGblEnv upd_env thing_inside
    
    1859 1962
       where
    
    1860 1963
         upd_env tcg_env = tcg_env { tcg_ev_binds = tcg_ev_binds tcg_env
    
    1861 1964
                                                    `unionBags` new_ev_binds }
    
    1862 1965
     
    
    1863 1966
     newTcEvBinds :: TcM EvBindsVar
    
    1864
    -newTcEvBinds = do { binds_ref <- newTcRef emptyEvBindMap
    
    1865
    -                  ; tcvs_ref  <- newTcRef []
    
    1967
    +newTcEvBinds = do { binds_ref <- newTcRef emptyEvBindsState
    
    1866 1968
                       ; uniq <- newUnique
    
    1867 1969
                       ; traceTc "newTcEvBinds" (text "unique =" <+> ppr uniq)
    
    1868 1970
                       ; return (EvBindsVar { ebv_binds = binds_ref
    
    1869
    -                                       , ebv_tcvs = tcvs_ref
    
    1870 1971
                                            , ebv_uniq = uniq }) }
    
    1871 1972
     
    
    1872 1973
     -- | Creates an EvBindsVar incapable of holding any bindings. It still
    
    1873
    --- tracks covar usages (see comments on ebv_tcvs in "GHC.Tc.Types.Evidence"), thus
    
    1974
    +-- tracks covar usages (see comments on ebv_needs in "GHC.Tc.Types.Evidence"), thus
    
    1874 1975
     -- must be made monadically
    
    1875 1976
     newNoTcEvBinds :: TcM EvBindsVar
    
    1876 1977
     newNoTcEvBinds
    
    1877
    -  = do { tcvs_ref  <- newTcRef []
    
    1978
    +  = do { tcvs_ref  <- newTcRef emptyVarSet
    
    1878 1979
            ; uniq <- newUnique
    
    1879 1980
            ; traceTc "newNoTcEvBinds" (text "unique =" <+> ppr uniq)
    
    1880
    -       ; return (CoEvBindsVar { ebv_tcvs = tcvs_ref
    
    1881
    -                              , ebv_uniq = uniq }) }
    
    1981
    +       ; return (CoEvBindsVar { ebv_needs = tcvs_ref
    
    1982
    +                              , ebv_uniq  = uniq }) }
    
    1882 1983
     
    
    1883 1984
     cloneEvBindsVar :: EvBindsVar -> TcM EvBindsVar
    
    1884 1985
     -- Clone the refs, so that any binding created when
    
    1885 1986
     -- solving don't pollute the original
    
    1886 1987
     cloneEvBindsVar ebv@(EvBindsVar {})
    
    1887
    -  = do { binds_ref <- newTcRef emptyEvBindMap
    
    1888
    -       ; tcvs_ref  <- newTcRef []
    
    1889
    -       ; return (ebv { ebv_binds = binds_ref
    
    1890
    -                     , ebv_tcvs = tcvs_ref }) }
    
    1988
    +  = do { binds_ref <- newTcRef emptyEvBindsState
    
    1989
    +       ; uniq <- newUnique
    
    1990
    +       ; return (ebv { ebv_uniq = uniq
    
    1991
    +                     , ebv_binds = binds_ref }) }
    
    1891 1992
     cloneEvBindsVar ebv@(CoEvBindsVar {})
    
    1892
    -  = do { tcvs_ref  <- newTcRef []
    
    1893
    -       ; return (ebv { ebv_tcvs = tcvs_ref }) }
    
    1993
    +  = do { tcvs_ref  <- newTcRef emptyVarSet
    
    1994
    +       ; return (ebv { ebv_needs = tcvs_ref }) }
    
    1894 1995
     
    
    1895
    -getTcEvTyCoVars :: EvBindsVar -> TcM [TcCoercion]
    
    1896
    -getTcEvTyCoVars ev_binds_var
    
    1897
    -  = readTcRef (ebv_tcvs ev_binds_var)
    
    1996
    +getTcEvBindsMap :: EvBindsVar -> TcM EvBindsMap
    
    1997
    +getTcEvBindsMap ebv = do { EBS { ebs_binds = bs } <- getTcEvBindsState ebv
    
    1998
    +                         ; return bs }
    
    1898 1999
     
    
    1899
    -getTcEvBindsMap :: EvBindsVar -> TcM EvBindMap
    
    1900
    -getTcEvBindsMap (EvBindsVar { ebv_binds = ev_ref })
    
    2000
    +getTcEvBindsState :: EvBindsVar -> TcM EvBindsState
    
    2001
    +getTcEvBindsState (EvBindsVar { ebv_binds = ev_ref })
    
    1901 2002
       = readTcRef ev_ref
    
    1902
    -getTcEvBindsMap (CoEvBindsVar {})
    
    1903
    -  = return emptyEvBindMap
    
    1904
    -
    
    1905
    -setTcEvBindsMap :: EvBindsVar -> EvBindMap -> TcM ()
    
    1906
    -setTcEvBindsMap (EvBindsVar { ebv_binds = ev_ref }) binds
    
    1907
    -  = writeTcRef ev_ref binds
    
    1908
    -setTcEvBindsMap v@(CoEvBindsVar {}) ev_binds
    
    1909
    -  | isEmptyEvBindMap ev_binds
    
    1910
    -  = return ()
    
    1911
    -  | otherwise
    
    1912
    -  = pprPanic "setTcEvBindsMap" (ppr v $$ ppr ev_binds)
    
    1913
    -
    
    1914
    -updTcEvBinds :: EvBindsVar -> EvBindsVar -> TcM ()
    
    1915
    -updTcEvBinds (EvBindsVar { ebv_binds = old_ebv_ref, ebv_tcvs = old_tcv_ref })
    
    1916
    -             (EvBindsVar { ebv_binds = new_ebv_ref, ebv_tcvs = new_tcv_ref })
    
    2003
    +getTcEvBindsState (CoEvBindsVar { ebv_needs = needs_ref })
    
    2004
    +  = do { needs <- readTcRef needs_ref
    
    2005
    +       ; return (EBS { ebs_binds = emptyEvBindsMap, ebs_needs = needs }) }
    
    2006
    +
    
    2007
    +setTcEvBindsMap :: EvBindsVar -> EvBindsMap -> TcM ()
    
    2008
    +setTcEvBindsMap (EvBindsVar { ebv_binds = ev_ref }) ev_binds
    
    2009
    +  = updTcRef ev_ref (\ebs -> ebs { ebs_binds = ev_binds })
    
    2010
    +setTcEvBindsMap (CoEvBindsVar {}) ev_binds
    
    2011
    +  = assertPpr (isEmptyEvBindsMap ev_binds) (ppr ev_binds) $
    
    2012
    +    return ()
    
    2013
    +
    
    2014
    +combineTcEvBinds :: EvBindsVar -> EvBindsVar -> TcM ()
    
    2015
    +combineTcEvBinds (EvBindsVar { ebv_binds = old_ebv_ref })
    
    2016
    +                 (EvBindsVar { ebv_binds = new_ebv_ref })
    
    1917 2017
       = do { new_ebvs <- readTcRef new_ebv_ref
    
    1918
    -       ; updTcRef old_ebv_ref (`unionEvBindMap` new_ebvs)
    
    1919
    -       ; new_tcvs <- readTcRef new_tcv_ref
    
    1920
    -       ; updTcRef old_tcv_ref (new_tcvs ++) }
    
    1921
    -updTcEvBinds (EvBindsVar { ebv_tcvs = old_tcv_ref })
    
    1922
    -             (CoEvBindsVar { ebv_tcvs = new_tcv_ref })
    
    2018
    +       ; updTcRef old_ebv_ref (`unionEvBindsState` new_ebvs) }
    
    2019
    +combineTcEvBinds (EvBindsVar { ebv_binds = old_tcv_ref })
    
    2020
    +                 (CoEvBindsVar { ebv_needs = new_tcv_ref })
    
    1923 2021
       = do { new_tcvs <- readTcRef new_tcv_ref
    
    1924
    -       ; updTcRef old_tcv_ref (new_tcvs ++) }
    
    1925
    -updTcEvBinds (CoEvBindsVar { ebv_tcvs = old_tcv_ref })
    
    1926
    -             (CoEvBindsVar { ebv_tcvs = new_tcv_ref })
    
    2022
    +       ; updTcRef old_tcv_ref (addNeededEvIdsEBS new_tcvs) }
    
    2023
    +combineTcEvBinds (CoEvBindsVar { ebv_needs = old_tcv_ref })
    
    2024
    +                 (CoEvBindsVar { ebv_needs = new_tcv_ref })
    
    1927 2025
       = do { new_tcvs <- readTcRef new_tcv_ref
    
    1928
    -       ; updTcRef old_tcv_ref (new_tcvs ++) }
    
    1929
    -updTcEvBinds old_var new_var
    
    1930
    -  = pprPanic "updTcEvBinds" (ppr old_var $$ ppr new_var)
    
    2026
    +       ; updTcRef old_tcv_ref (unionVarSet new_tcvs) }
    
    2027
    +combineTcEvBinds old_var new_var
    
    2028
    +  = pprPanic "combineTcEvBinds" (ppr old_var $$ ppr new_var)
    
    1931 2029
         -- Terms inside types, no good
    
    1932 2030
     
    
    2031
    +addNeededEvIds :: EvBindsVar -> NeededEvIds -> TcM ()
    
    2032
    +addNeededEvIds (EvBindsVar { ebv_binds = bs_ref }) needed
    
    2033
    +  = updTcRef bs_ref (addNeededEvIdsEBS needed)
    
    2034
    +addNeededEvIds (CoEvBindsVar { ebv_needs = need_ref }) needed
    
    2035
    +  = updTcRef need_ref (unionVarSet needed)
    
    2036
    +
    
    2037
    +addTcEvCoBind :: EvBindsVar -> CoercionHole -> CoercionPlusHoles -> TcM ()
    
    2038
    +addTcEvCoBind ebv hole co_plus_holes@(CPH { cph_co = co })
    
    2039
    +  = do { fillCoercionHole hole co_plus_holes
    
    2040
    +         -- Record usage of the free vars of this coercion
    
    2041
    +       ; addNeededEvIds ebv (coVarsOfCo co) }
    
    2042
    +
    
    1933 2043
     addTcEvBind :: EvBindsVar -> EvBind -> TcM ()
    
    1934 2044
     -- Add a binding to the TcEvBinds by side effect
    
    1935
    -addTcEvBind (EvBindsVar { ebv_binds = ev_ref, ebv_uniq = u }) ev_bind
    
    1936
    -  = do { bnds <- readTcRef ev_ref
    
    1937
    -       ; let bnds' = extendEvBinds bnds ev_bind
    
    2045
    +addTcEvBind (EvBindsVar { ebv_binds = ev_ref, ebv_uniq = u })
    
    2046
    +            ev_bind@(EvBind { eb_info = info, eb_rhs = rhs })
    
    2047
    +  = do { EBS { ebs_binds = bnds, ebs_needs = needs } <- readTcRef ev_ref
    
    2048
    +       ; let bnds'  = extendEvBinds bnds ev_bind
    
    2049
    +             needs' = case info of
    
    2050
    +                        EvBindWanted {} -> nestedEvIdsOfTerm rhs
    
    2051
    +                                           `unionVarSet` needs
    
    2052
    +                        EvBindGiven {} -> needs
    
    2053
    +
    
    1938 2054
            ; traceTc "addTcEvBind" $
    
    1939 2055
              vcat [ text "EvBindsVar:" <+> ppr u
    
    1940 2056
                   , text "ev_bind:" <+> ppr ev_bind
    
    1941 2057
                   , text "bnds:" <+> ppr bnds
    
    1942
    -              , text "bnds':" <+> ppr bnds' ]
    
    1943
    -       ; writeTcRef ev_ref bnds' }
    
    2058
    +              , text "bnds':" <+> ppr bnds'
    
    2059
    +              , text "needs" <+> ppr needs
    
    2060
    +              , text "needs'" <+> ppr needs' ]
    
    2061
    +
    
    2062
    +       ; writeTcRef ev_ref $
    
    2063
    +         EBS { ebs_binds = bnds', ebs_needs = needs' } }
    
    2064
    +
    
    1944 2065
     addTcEvBind (CoEvBindsVar { ebv_uniq = u }) ev_bind
    
    1945 2066
       = pprPanic "addTcEvBind CoEvBindsVar" (ppr ev_bind $$ ppr u)
    
    1946 2067
     
    
    1947
    -addTcEvBinds :: EvBindsVar -> EvBindMap -> TcM ()
    
    1948
    --- ^ Add a collection of binding to the TcEvBinds by side effect
    
    1949
    -addTcEvBinds _ new_ev_binds
    
    1950
    -  | isEmptyEvBindMap new_ev_binds
    
    1951
    -  = return ()
    
    1952
    -addTcEvBinds (EvBindsVar { ebv_binds = ev_ref, ebv_uniq = u }) new_ev_binds
    
    1953
    -  = do { traceTc "addTcEvBinds" $ ppr u $$
    
    1954
    -                                  ppr new_ev_binds
    
    1955
    -       ; old_bnds <- readTcRef ev_ref
    
    1956
    -       ; writeTcRef ev_ref (old_bnds `unionEvBindMap` new_ev_binds) }
    
    1957
    -addTcEvBinds (CoEvBindsVar { ebv_uniq = u }) new_ev_binds
    
    1958
    -  = pprPanic "addTcEvBinds CoEvBindsVar" (ppr new_ev_binds $$ ppr u)
    
    1959
    -
    
    1960 2068
     chooseUniqueOccTc :: (OccSet -> OccName) -> TcM OccName
    
    1961 2069
     chooseUniqueOccTc fn =
    
    1962 2070
       do { env <- getGblEnv
    
    ... ... @@ -2138,111 +2246,22 @@ emitNamedTypeHole (name, tv)
    2138 2246
       where
    
    2139 2247
         occ       = nameOccName name
    
    2140 2248
     
    
    2141
    -{- Note [Constraints and errors]
    
    2142
    -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    2143
    -Consider this (#12124):
    
    2144
    -
    
    2145
    -  foo :: Maybe Int
    
    2146
    -  foo = return (case Left 3 of
    
    2147
    -                  Left -> 1  -- Hard error here!
    
    2148
    -                  _    -> 0)
    
    2149
    -
    
    2150
    -The call to 'return' will generate a (Monad m) wanted constraint; but
    
    2151
    -then there'll be "hard error" (i.e. an exception in the TcM monad), from
    
    2152
    -the unsaturated Left constructor pattern.
    
    2153
    -
    
    2154
    -We'll recover in tcPolyBinds, using recoverM.  But then the final
    
    2155
    -tcSimplifyTop will see that (Monad m) constraint, with 'm' utterly
    
    2156
    -un-filled-in, and will emit a misleading error message.
    
    2157
    -
    
    2158
    -The underlying problem is that an exception interrupts the constraint
    
    2159
    -gathering process. Bottom line: if we have an exception, it's best
    
    2160
    -simply to discard any gathered constraints.  Hence in 'attemptM' we
    
    2161
    -capture the constraints in a fresh variable, and only emit them into
    
    2162
    -the surrounding context if we exit normally.  If an exception is
    
    2163
    -raised, simply discard the collected constraints... we have a hard
    
    2164
    -error to report.  So this capture-the-emit dance isn't as stupid as it
    
    2165
    -looks :-).
    
    2166
    -
    
    2167
    -However suppose we throw an exception inside an invocation of
    
    2168
    -captureConstraints, and discard all the constraints. Some of those
    
    2169
    -constraints might be "variable out of scope" Hole constraints, and that
    
    2170
    -might have been the actual original cause of the exception!  For
    
    2171
    -example (#12529):
    
    2172
    -   f = p @ Int
    
    2173
    -Here 'p' is out of scope, so we get an insoluble Hole constraint. But
    
    2174
    -the visible type application fails in the monad (throws an exception).
    
    2175
    -We must not discard the out-of-scope error.
    
    2176
    -
    
    2177
    -It's distressingly delicate though:
    
    2249
    +-- | Put a value in a coercion hole
    
    2250
    +fillCoercionHole :: CoercionHole -> CoercionPlusHoles -> TcM ()
    
    2251
    +fillCoercionHole (CH { ch_ref = ref, ch_co_var = cv }) co
    
    2252
    +  = do { when debugIsOn $
    
    2253
    +         do { cts <- readTcRef ref
    
    2254
    +            ; whenIsJust cts $ \old_co ->
    
    2255
    +              pprPanic "Filling a filled coercion hole" (ppr cv $$ ppr co $$ ppr old_co) }
    
    2256
    +       ; traceTc "Filling coercion hole" (ppr cv <+> text ":=" <+> ppr co)
    
    2257
    +       ; writeTcRef ref (Just co) }
    
    2178 2258
     
    
    2179
    -* If we discard too /many/ constraints we may fail to report the error
    
    2180
    -  that led us to interrupt the constraint gathering process.
    
    2181 2259
     
    
    2182
    -  One particular example "variable out of scope" Hole constraints. For
    
    2183
    -  example (#12529):
    
    2184
    -   f = p @ Int
    
    2185
    -  Here 'p' is out of scope, so we get an insoluble Hole constraint. But
    
    2186
    -  the visible type application fails in the monad (throws an exception).
    
    2187
    -  We must not discard the out-of-scope error.
    
    2188
    -
    
    2189
    -  Also GHC.Tc.Solver.simplifyAndEmitFlatConstraints may fail having
    
    2190
    -  emitted some constraints with skolem-escape problems.
    
    2191
    -
    
    2192
    -* If we discard too /few/ constraints, we may get the misleading
    
    2193
    -  class constraints mentioned above.
    
    2194
    -
    
    2195
    -  We may /also/ end up taking constraints built at some inner level, and
    
    2196
    -  emitting them (via the exception catching in `tryCaptureConstraints` at some
    
    2197
    -  outer level, and then breaking the TcLevel invariants See Note [TcLevel
    
    2198
    -  invariants] in GHC.Tc.Utils.TcType
    
    2199
    -
    
    2200
    -So `dropMisleading` has a horridly ad-hoc structure:
    
    2201
    -
    
    2202
    -* It keeps only /insoluble/ flat constraints (which are unlikely to very visibly
    
    2203
    -  trip up on the TcLevel invariant
    
    2204
    -
    
    2205
    -* But it keeps all /implication/ constraints (except the class constraints
    
    2206
    -  inside them).  The implication constraints are OK because they set the ambient
    
    2207
    -  level before attempting to solve any inner constraints.
    
    2208
    -
    
    2209
    -Ugh! I hate this. But it seems to work.
    
    2210
    -
    
    2211
    -Other wrinkles
    
    2212
    -
    
    2213
    -(CERR1) Note that freshly-generated constraints like (Int ~ Bool), or
    
    2214
    -    ((a -> b) ~ Int) are all CNonCanonical, and hence won't be flagged as
    
    2215
    -    insoluble.  The constraint solver does that.  So they'll be discarded.
    
    2216
    -    That's probably ok; but see th/5358 as a not-so-good example:
    
    2217
    -       t1 :: Int
    
    2218
    -       t1 x = x   -- Manifestly wrong
    
    2219
    -
    
    2220
    -       foo = $(...raises exception...)
    
    2221
    -    We report the exception, but not the bug in t1.  Oh well.  Possible
    
    2222
    -    solution: make GHC.Tc.Utils.Unify.uType spot manifestly-insoluble constraints.
    
    2223
    -
    
    2224
    -(CERR2) In #26015 I found that from the constraints
    
    2225
    -           [W] alpha ~ Int      -- A class constraint
    
    2226
    -           [W] F alpha ~# Bool  -- An equality constraint
    
    2227
    -  we were dropping the first (becuase it's a class constraint) but not the
    
    2228
    -  second, and then getting a misleading error message from the second.  As
    
    2229
    -  #25607 shows, we can get not just one but a zillion bogus messages, which
    
    2230
    -  conceal the one genuine error.  Boo.
    
    2231
    -
    
    2232
    -  For now I have added an even more ad-hoc "drop class constraints except
    
    2233
    -  equality classes (~) and (~~)"; see `dropMisleading`.  That just kicks the can
    
    2234
    -  down the road; but this problem seems somewhat rare anyway.  The code in
    
    2235
    -  `dropMisleading` hasn't changed for years.
    
    2236
    -
    
    2237
    -It would be great to have a more systematic solution to this entire mess.
    
    2238
    -
    
    2239
    -
    
    2240
    -************************************************************************
    
    2260
    +{- *********************************************************************
    
    2241 2261
     *                                                                      *
    
    2242 2262
                  Template Haskell context
    
    2243 2263
     *                                                                      *
    
    2244
    -************************************************************************
    
    2245
    --}
    
    2264
    +********************************************************************* -}
    
    2246 2265
     
    
    2247 2266
     recordThUse :: TcM ()
    
    2248 2267
     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
    ... ... @@ -422,7 +422,8 @@ Some examples:
    422 422
     -}
    
    423 423
     
    
    424 424
     tcSkolemiseGeneral
    
    425
    -  :: DeepSubsumptionFlag
    
    425
    +  :: HasDebugCallStack
    
    426
    +  => DeepSubsumptionFlag
    
    426 427
       -> UserTypeCtxt
    
    427 428
       -> TcType -> TcType   -- top_ty and expected_ty
    
    428 429
             -- Here, top_ty      is the type we started to skolemise; used only in SigSkol
    
    ... ... @@ -450,15 +451,16 @@ tcSkolemiseGeneral ds_flag ctxt top_ty expected_ty thing_inside
    450 451
                  ; skol_info <- mkSkolemInfo sig_skol }
    
    451 452
     
    
    452 453
            ; let skol_tvs = map (binderVar . snd) tv_prs
    
    453
    -       ; traceTc "tcSkolemiseGeneral" (pprUserTypeCtxt ctxt <+> ppr skol_tvs <+> ppr given)
    
    454
    +       ; traceTc "tcSkolemiseGeneral {" (pprUserTypeCtxt ctxt <+> ppr skol_tvs <+> ppr given)
    
    454 455
            ; (ev_binds, result) <- checkConstraints sig_skol skol_tvs given $
    
    455 456
                                    thing_inside tv_prs rho_ty
    
    456 457
     
    
    458
    +       ; traceTc "tcSkolemiseGeneral }" (ppr ev_binds $$ traceCallStackDoc)
    
    457 459
            ; return (wrap <.> mkWpLet ev_binds, result) }
    
    458 460
              -- The ev_binds returned by checkConstraints is very
    
    459 461
              -- often empty, in which case mkWpLet is a no-op
    
    460 462
     
    
    461
    -tcSkolemiseCompleteSig :: TcCompleteSig
    
    463
    +tcSkolemiseCompleteSig :: HasDebugCallStack => TcCompleteSig
    
    462 464
                            -> ([ExpPatType] -> TcRhoType -> TcM result)
    
    463 465
                            -> TcM (HsWrapper, result)
    
    464 466
     -- ^ The wrapper has type: spec_ty ~~> expected_ty
    
    ... ... @@ -475,7 +477,7 @@ tcSkolemiseCompleteSig (CSig { sig_bndr = poly_id, sig_ctxt = ctxt, sig_loc = lo
    475 477
              tcExtendNameTyVarEnv (map (fmap binderVar) tv_prs) $
    
    476 478
              thing_inside (map (mkInvisExpPatType . snd) tv_prs) rho_ty }
    
    477 479
     
    
    478
    -tcSkolemiseExpectedType :: TcSigmaType
    
    480
    +tcSkolemiseExpectedType :: HasDebugCallStack => TcSigmaType
    
    479 481
                             -> ([ExpPatType] -> TcRhoType -> TcM result)
    
    480 482
                             -> TcM (HsWrapper, result)
    
    481 483
     -- Just like tcSkolemiseCompleteSig, except that we don't have a user-written
    
    ... ... @@ -487,14 +489,15 @@ tcSkolemiseExpectedType exp_ty thing_inside
    487 489
       = tcSkolemiseGeneral Shallow GenSigCtxt exp_ty exp_ty $ \tv_prs rho_ty ->
    
    488 490
         thing_inside (map (mkInvisExpPatType . snd) tv_prs) rho_ty
    
    489 491
     
    
    490
    -tcSkolemise :: DeepSubsumptionFlag -> UserTypeCtxt -> TcSigmaType
    
    492
    +tcSkolemise :: HasDebugCallStack => DeepSubsumptionFlag -> UserTypeCtxt -> TcSigmaType
    
    491 493
                 -> (TcRhoType -> TcM result)
    
    492 494
                 -> TcM (HsWrapper, result)
    
    493 495
     tcSkolemise ds_flag ctxt expected_ty thing_inside
    
    494 496
       = tcSkolemiseGeneral ds_flag ctxt expected_ty expected_ty $ \_ rho_ty ->
    
    495 497
         thing_inside rho_ty
    
    496 498
     
    
    497
    -checkConstraints :: SkolemInfoAnon
    
    499
    +checkConstraints :: HasDebugCallStack
    
    500
    +                 => SkolemInfoAnon
    
    498 501
                      -> [TcTyVar]           -- Skolems
    
    499 502
                      -> [EvVar]             -- Given
    
    500 503
                      -> TcM result
    
    ... ... @@ -508,14 +511,16 @@ checkConstraints skol_info skol_tvs given thing_inside
    508 511
            ; if implication_needed
    
    509 512
              then do { (tclvl, wanted, result) <- pushLevelAndCaptureConstraints thing_inside
    
    510 513
                      ; (implics, ev_binds) <- buildImplicationFor tclvl skol_info skol_tvs given wanted
    
    511
    -                 ; traceTc "checkConstraints" (ppr tclvl $$ ppr skol_tvs)
    
    514
    +                 ; traceTc "checkConstraints A" (ppr tclvl $$ ppr skol_tvs $$ traceCallStackDoc)
    
    512 515
                      ; emitImplications implics
    
    513 516
                      ; return (ev_binds, result) }
    
    514 517
     
    
    515 518
              else -- Fast path.  We check every function argument with tcCheckPolyExpr,
    
    516 519
                   -- which uses tcTopSkolemise and hence checkConstraints.
    
    517 520
                   -- So this fast path is well-exercised
    
    518
    -              do { res <- thing_inside
    
    521
    +              do { traceTc "checkConstraints B" (ppr skol_tvs $$ ppr given $$ ppr skol_info $$
    
    522
    +                                                 traceCallStackDoc)
    
    523
    +                 ; res <- thing_inside
    
    519 524
                      ; return (emptyTcEvBinds, res) } }
    
    520 525
     
    
    521 526
     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/Types/Var.hs
    ... ... @@ -176,7 +176,7 @@ type KindVar = Var -- Definitely a kind variable
    176 176
     
    
    177 177
     -- See Note [Evidence: EvIds and CoVars]
    
    178 178
     -- | Evidence Identifier
    
    179
    -type EvId   = Id        -- Term-level evidence: DictId, IpId, or EqVar
    
    179
    +type EvId   = Id        -- Term-level evidence: DictId, IpId, or CoVar
    
    180 180
     
    
    181 181
     -- | Evidence Variable
    
    182 182
     type EvVar  = EvId      -- ...historical name for EvId
    

  • 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
     
    

  • testsuite/tests/simplCore/should_compile/T26805.hs
    1
    +{-# LANGUAGE GADTs              #-}
    
    2
    +{-# LANGUAGE ImpredicativeTypes #-}
    
    3
    +{-# LANGUAGE TypeData           #-}
    
    4
    +module T26805( interpret )  where
    
    5
    +
    
    6
    +import Data.Kind (Type)
    
    7
    +
    
    8
    +data Phantom (sh :: Type) = Phantom  -- newtype fails to specialise as well
    
    9
    +
    
    10
    +instance Show (Phantom sh) where
    
    11
    +  show Phantom = "show"
    
    12
    +
    
    13
    +type Foo r = (forall sh. Show (Phantom sh), Num r)
    
    14
    +-- this specialises fine:
    
    15
    +-- type Foo r = (Num r)
    
    16
    +
    
    17
    +type data TK = TKScalar Type
    
    18
    +
    
    19
    +data AstTensor :: TK -> Type where
    
    20
    +  AstInt :: Int -> AstTensor (TKScalar Int)
    
    21
    +  AstPlus :: Foo r => AstTensor (TKScalar r) -> AstTensor (TKScalar r)
    
    22
    +
    
    23
    +plusConcrete :: Foo r => r -> r
    
    24
    +plusConcrete = (+ 1)
    
    25
    +
    
    26
    +interpret :: AstTensor (TKScalar Int) -> Int
    
    27
    +interpret v0 = case v0 of
    
    28
    +  AstInt n  -> n
    
    29
    +  AstPlus u -> plusConcrete (interpret u)

  • testsuite/tests/simplCore/should_compile/T26805.stderr
    1
    + 
    \ No newline at end of file

  • testsuite/tests/simplCore/should_compile/all.T
    ... ... @@ -578,3 +578,4 @@ test('T26615', [grep_errmsg(r'fEqList')], multimod_compile, ['T26615', '-O -fsp
    578 578
     
    
    579 579
     # T26722: there should be no reboxing in $wg
    
    580 580
     test('T26722', [grep_errmsg(r'SPEC')], compile, ['-O -dno-typeable-binds'])
    
    581
    +test('T26805', [grep_errmsg(r'fromInteger')], compile, ['-O -dno-typeable-binds -ddump-simpl -dsuppress-uniques'])

  • testsuite/tests/typecheck/should_compile/T26805a.hs
    1
    +{-# LANGUAGE ScopedTypeVariables #-}
    
    2
    +{-# LANGUAGE UndecidableSuperClasses #-}
    
    3
    +{-# LANGUAGE QuantifiedConstraints #-}
    
    4
    +{-# LANGUAGE TypeApplications #-}
    
    5
    +{-# LANGUAGE RoleAnnotations #-}
    
    6
    +
    
    7
    +-- This is a cut-down version of the failure found in !15389
    
    8
    +-- when compiling the `constraints` package.
    
    9
    +-- We got a Lint error because the NeededEvIds stuff in the
    
    10
    +-- constraint solver forgot some needed variables.
    
    11
    +
    
    12
    +module T26805a where
    
    13
    +
    
    14
    +import GHC.Exts (Constraint)
    
    15
    +import Data.Kind
    
    16
    +
    
    17
    +data Dict :: Constraint -> Type where
    
    18
    +  Dict :: a => Dict a
    
    19
    +
    
    20
    +newtype a :- b = Sub (a => Dict b)
    
    21
    +type role (:-) nominal nominal
    
    22
    +
    
    23
    +-- | Instantiate a quantified @'ForallF' p f@ constraint at type @a@.
    
    24
    +instF :: forall p f a . ForallF p f :- p (f a)
    
    25
    +instF = Sub @(ForallF p f) @(p (f a))
    
    26
    +            (case inst :: Forall (ComposeC p f) :- ComposeC p f a of
    
    27
    +                Sub Dict -> Dict)
    
    28
    +
    
    29
    +class Forall (ComposeC p f) => ForallF (p :: k2 -> Constraint) (f :: k1 -> k2)
    
    30
    +
    
    31
    +class p (f a) => ComposeC (p :: k2 -> Constraint) (f :: k1 -> k2) (a :: k1)
    
    32
    +
    
    33
    +class (forall a. p a) => Forall (p :: k -> Constraint)
    
    34
    +instance (forall a. p a) => Forall (p :: k -> Constraint)
    
    35
    +
    
    36
    +inst :: forall p a. Forall p :- p a
    
    37
    +inst = Sub Dict
    
    38
    +

  • testsuite/tests/typecheck/should_compile/all.T
    ... ... @@ -959,3 +959,5 @@ test('T26451', normal, compile, [''])
    959 959
     test('T26582', normal, compile, [''])
    
    960 960
     test('T26746', normal, compile, [''])
    
    961 961
     test('T26737', normal, compile, [''])
    
    962
    +test('T26805a', normal, compile, [''])
    
    963
    +