rust-lang/rust · #166586

abby test dsl: one binder to rule them all

khyperia · merged Nov 27, 202623 files · 360 + / 235 −
compiler/rustc_ast/src/ast.rs0 + / 2 −
@@ -4255,7 +4255,6 @@ pub struct TestBinderRegionEquality { #[derive(Clone, Encodable, Decodable, Debug, Walkable)] pub struct TestBinderForall {     pub span: Span,-    pub node_id: NodeId,     pub generics: Generics,     pub body: TestBinderBody,     pub assert_on_exit: Option<ThinVec<TestBinderConstraint>>,@@ -4264,7 +4263,6 @@ pub struct TestBinderForall { #[derive(Clone, Encodable, Decodable, Debug, Walkable)] pub struct TestBinderExists {     pub span: Span,-    pub node_id: NodeId,     pub params: ThinVec<GenericParam>,     pub body: TestBinderBody, }
compiler/rustc_ast_lowering/src/index.rs0 + / 10 −
@@ -437,16 +437,6 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> {         intravisit::walk_precise_capturing_arg(self, arg);     } -    fn visit_test_binder_forall(&mut self, forall: &'hir TestBinderForall<'hir>) {-        self.insert(forall.span, forall.hir_id, Node::TestBinderForall(forall));-        self.with_parent(forall.hir_id, |this| intravisit::walk_test_binder_forall(this, forall))-    }--    fn visit_test_binder_exists(&mut self, exists: &'hir TestBinderExists<'hir>) {-        self.insert(exists.span, exists.hir_id, Node::TestBinderExists(exists));-        self.with_parent(exists.hir_id, |this| intravisit::walk_test_binder_exists(this, exists))-    }-     fn visit_test_binder_bound_type_constraint(         &mut self,         bound_type: &'hir TestBinderBoundTypeConstraint<'hir>,
compiler/rustc_ast_lowering/src/item.rs0 + / 2 −
@@ -2065,7 +2065,6 @@ impl<'hir> LoweringContext<'_, 'hir> {         });         hir::TestBinderForall {             span: self.lower_span(forall.span),-            hir_id: self.lower_node_id(forall.node_id),             generics,             body: self.arena.alloc(body),             assert_on_exit,@@ -2088,7 +2087,6 @@ impl<'hir> LoweringContext<'_, 'hir> {         let params = generics.params;         hir::TestBinderExists {             span: self.lower_span(exists.span),-            hir_id: self.lower_node_id(exists.node_id),             params,             body: self.arena.alloc(body),         }
compiler/rustc_hir/src/hir.rs0 + / 6 −
@@ -4637,7 +4637,6 @@ pub enum TestBinderItem<'hir> { #[derive(Debug, Clone, Copy, StableHash)] pub struct TestBinderForall<'hir> {     pub span: Span,-    pub hir_id: HirId,     pub generics: &'hir Generics<'hir>,     pub body: &'hir TestBinderBody<'hir>,     pub assert_on_exit: Option<&'hir TestBinderConstraint<'hir>>,@@ -4646,7 +4645,6 @@ pub struct TestBinderForall<'hir> { #[derive(Debug, Clone, Copy, StableHash)] pub struct TestBinderExists<'hir> {     pub span: Span,-    pub hir_id: HirId,     pub params: &'hir [GenericParam<'hir>],     pub body: &'hir TestBinderBody<'hir>, }@@ -5079,8 +5077,6 @@ pub enum Node<'hir> {     Infer(&'hir InferArg),     WherePredicate(&'hir WherePredicate<'hir>),     PreciseCapturingNonLifetimeArg(&'hir PreciseCapturingNonLifetimeArg),-    TestBinderForall(&'hir TestBinderForall<'hir>),-    TestBinderExists(&'hir TestBinderExists<'hir>),     TestBinderBoundTypeConstraint(&'hir TestBinderBoundTypeConstraint<'hir>),     // Created by query feeding     Synthetic,@@ -5139,8 +5135,6 @@ impl<'hir> Node<'hir> {             | Node::NestedUseTree(_)             | Node::Infer(..)             | Node::WherePredicate(..)-            | Node::TestBinderForall(..)-            | Node::TestBinderExists(..)             | Node::TestBinderBoundTypeConstraint(..)             | Node::Synthetic             | Node::Err(..) => None,
compiler/rustc_hir/src/intravisit.rs2 + / 4 −
@@ -1612,8 +1612,7 @@ pub fn walk_test_binder_forall<'v, V: Visitor<'v>>(     visitor: &mut V,     forall: &'v TestBinderForall<'v>, ) -> V::Result {-    let TestBinderForall { span: _, hir_id, generics, body, assert_on_exit } = forall;-    try_visit!(visitor.visit_id(*hir_id));+    let TestBinderForall { span: _, generics, body, assert_on_exit } = forall;     try_visit!(visitor.visit_generics(generics));     try_visit!(visitor.visit_test_binder_body(body));     if let Some(assert_on_exit) = &assert_on_exit {@@ -1651,8 +1650,7 @@ pub fn walk_test_binder_exists<'v, V: Visitor<'v>>(     visitor: &mut V,     exists: &'v TestBinderExists<'v>, ) -> V::Result {-    let TestBinderExists { span: _, hir_id, params, body } = exists;-    try_visit!(visitor.visit_id(*hir_id));+    let TestBinderExists { span: _, params, body } = exists;     walk_list!(visitor, visit_generic_param, *params);     try_visit!(visitor.visit_test_binder_body(body));     V::Result::output()
compiler/rustc_hir_analysis/src/check/check.rs2 + / 2 −
@@ -1189,9 +1189,9 @@ pub(crate) fn check_item_type(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(),             let (_, body) =                 tcx.hir_node_by_def_id(def_id).expect_item().expect_test_binder_constraints();             let icx = ItemCtxt::new(tcx, def_id);-            let lowered = icx.lower_test_binder_body(body);+            let lowered = icx.lower_test_binder_constraints(def_id, body);             res = res.and(enter_wf_checking_ctxt(tcx, def_id, |wfcx| {-                wfcx.check_test_binder_body(lowered);+                wfcx.check_test_binder_constraints(lowered);                 Ok(())             }));             return res;
compiler/rustc_hir_analysis/src/check/wfcheck.rs175 + / 58 −
@@ -17,7 +17,10 @@ use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::{AmbigArg, ItemKind}; use rustc_infer::infer::outlives::env::OutlivesEnvironment;-use rustc_infer::infer::{BoundRegionConversionTime, SolverRegionConstraint, TyCtxtInferExt};+use rustc_infer::infer::{+    BoundRegionConversionTime, InferCtxt, RegionVariableOrigin, SolverRegionConstraint,+    TyCtxtInferExt,+}; use rustc_infer::traits::{PredicateObligations, TraitErrors}; use rustc_lint_defs::builtin::{     REDUNDANT_LIFETIMES, SHADOWING_SUPERTRAIT_ITEMS, UNEVALUATED_DEFAULT_FIELD_VALUE,@@ -2423,8 +2426,138 @@ impl<'tcx> WfCheckingCtxt<'_, 'tcx> {         }     } +    // The binder here is not a normal binder. Consider the following:+    //+    // core::test_binder_constraints! {+    //     impl {+    //         forall<'a> { exists<'b> { 'b: 'a } },+    //         forall<'c> { },+    //         'a: 'b,+    //     }+    // }+    //+    // To allow testing uses of leaked variables, this is lowered to something like the following:+    //+    // core::test_binder_constraints! {+    //     impl {+    //         for<'a, 'b, 'c> {+    //             forall { exists { 'b: 'a } },+    //             forall { },+    //             'a: 'b,+    //         }+    //     }+    // }+    //+    // but we remember where 'a, 'b, and 'c came from. This outer binder is then instantiated with a+    // bit of a cursed set of arguments, with potentially different universes used for each arg:+    //+    // 'a => placeholder in universe 1+    // 'b => existential in universe 1+    // 'c => placeholder in universe 2+    #[instrument(level = "debug", skip(self))]+    pub(super) fn check_test_binder_constraints(+        &self,+        mut body: ty::Binder<'tcx, TestBinderBody<'tcx>>,+    ) {+        // Create a new universe for each forall. This corresponds to the universes that+        // `infcx.enter_forall` would create for each forall. Also, figure out which kind of arg we+        // should use for each binder parameter.+        fn create_universes<'tcx>(+            infcx: &InferCtxt<'tcx>,+            args: &mut Vec<Arg<'tcx>>,+            body: &mut TestBinderBody<'tcx>,+        ) {+            for item in &mut body.items {+                match item {+                    TestBinderItem::Forall(item) => {+                        let u = infcx.create_next_universe();+                        item.universe = Some(u);+                        args.extend(item.params.iter().map(|_| Arg::Universal(u)));+                        create_universes(infcx, args, &mut item.body);+                    }+                    TestBinderItem::Exists(item) => {+                        let u = infcx.universe();+                        args.extend(item.params.iter().map(|sp| Arg::Existential(u, *sp, None)));+                        create_universes(infcx, args, &mut item.body);+                    }+                    TestBinderItem::RegionEquality(..)+                    | TestBinderItem::Constraint(..)+                    | TestBinderItem::Predicate { .. } => (),+                }+            }+        }+        let mut args = vec![];+        create_universes(self.infcx, &mut args, body.as_mut().skip_binder());+        debug_assert_eq!(args.len(), body.bound_vars().len());++        enum Arg<'tcx> {+            // Instantiate as if `infcx.instantiate_binder_with_fresh_vars` was used+            Existential(ty::UniverseIndex, Span, Option<ty::GenericArg<'tcx>>),+            // Instantiate as if `infcx.enter_forall` was used+            Universal(ty::UniverseIndex),+        }+        struct TestBinderDelegate<'a, 'tcx> {+            infcx: &'a InferCtxt<'tcx>,+            args: Vec<Arg<'tcx>>,+        }++        impl<'a, 'tcx> ty::BoundVarReplacerDelegate<TyCtxt<'tcx>> for TestBinderDelegate<'a, 'tcx> {+            fn replace_region(&mut self, br: ty::BoundRegion<'tcx>) -> ty::Region<'tcx> {+                // We could eagerly create the existential variables beforehand, but that requires+                // knowing the kind up front, so just lazily create them when requested.+                match &mut self.args[br.var.index()] {+                    Arg::Existential(u, span, e) => e+                        .get_or_insert_with(|| {+                            self.infcx+                                .next_region_var_in_universe(+                                    RegionVariableOrigin::BoundRegion(+                                        *span,+                                        br.kind,+                                        BoundRegionConversionTime::HigherRankedType,+                                    ),+                                    *u,+                                )+                                .into()+                        })+                        .expect_region(),+                    Arg::Universal(u) => ty::Region::new_placeholder(+                        self.infcx.tcx,+                        ty::PlaceholderRegion::new(*u, br),+                    ),+                }+            }+            fn replace_ty(&mut self, bt: ty::BoundTy<'tcx>) -> Ty<'tcx> {+                match &mut self.args[bt.var.index()] {+                    Arg::Existential(u, span, e) => e+                        .get_or_insert_with(|| self.infcx.next_ty_var_in_universe(*span, *u).into())+                        .expect_ty(),+                    Arg::Universal(u) => {+                        Ty::new_placeholder(self.infcx.tcx, ty::PlaceholderType::new(*u, bt))+                    }+                }+            }+            fn replace_const(&mut self, bc: ty::BoundConst<'tcx>) -> ty::Const<'tcx> {+                match &mut self.args[bc.var.index()] {+                    Arg::Existential(u, span, e) => e+                        .get_or_insert_with(|| {+                            self.infcx.next_const_var_in_universe(*span, *u).into()+                        })+                        .expect_const(),+                    Arg::Universal(u) => ty::Const::new_placeholder(+                        self.infcx.tcx,+                        ty::PlaceholderConst::new(*u, bc),+                    ),+                }+            }+        }++        let delegate = TestBinderDelegate { infcx: self.infcx, args };+        let body = self.tcx().replace_bound_vars_uncached(body, delegate);+        self.check_test_binder_body(body);+    }+     #[instrument(level = "debug", skip(self))]-    pub(super) fn check_test_binder_body(&self, body: TestBinderBody<'tcx>) {+    fn check_test_binder_body(&self, body: TestBinderBody<'tcx>) {         let TestBinderBody { span, items } = body;         for item in items {             match item {@@ -2512,45 +2645,32 @@ impl<'tcx> WfCheckingCtxt<'_, 'tcx> {      #[instrument(level = "debug", skip(self))]     fn check_test_binder_forall(&self, forall: TestBinderForall<'tcx>) {-        let prev_u = self.infcx.universe();-        self.infcx.enter_forall(forall.binder, |body| {-            let u = if prev_u == self.infcx.universe() {-                // `enter_forall` has some special cases to avoid creating universes-                // in some cases for perf reasons. Not creating the universe unconditionally-                // breaks calling `eagerly_handle_placeholders` later on in this function.-                //-                // See `test_infra_empty_forall.rs`.-                self.infcx.create_next_universe()-            } else {-                self.infcx.universe()-            };--            let assumptions = self.build_test_binder_assumptions(-                forall.span,-                body.type_outlives,-                body.region_outlives,+        let u = forall.universe.unwrap();+        let assumptions = self.build_test_binder_assumptions(+            forall.span,+            forall.type_outlives,+            forall.region_outlives,+        );+        self.infcx.insert_placeholder_assumptions(u, assumptions);+        self.check_test_binder_body(forall.body);+        let solver_region_constraint = self.infcx.get_solver_region_constraint();+        let constraint = ty::region_constraint::eagerly_handle_placeholders_in_universe(+            self.infcx,+            solver_region_constraint.without_spans(),+            u,+        )+        .with_spans(forall.span);+        if constraint.is_false() {+            self.tcx().dcx().span_err(forall.span, "forall evaluated to false");+            self.infcx.overwrite_solver_region_constraint(+                ty::region_constraint::RegionConstraint::new_true(),             );-            self.infcx.insert_placeholder_assumptions(u, assumptions);-            self.check_test_binder_body(body.value);-            let solver_region_constraint = self.infcx.get_solver_region_constraint();-            let constraint = ty::region_constraint::eagerly_handle_placeholders_in_universe(-                self.infcx,-                solver_region_constraint.without_spans(),-                u,-            )-            .with_spans(forall.span);-            if constraint.is_false() {-                self.tcx().dcx().span_err(forall.span, "forall evaluated to false");-                self.infcx.overwrite_solver_region_constraint(-                    ty::region_constraint::RegionConstraint::new_true(),-                );-                return;-            }-            if let Some(assert_on_exit) = &forall.assert_on_exit {-                self.check_test_binder_region_constraints(forall.span, assert_on_exit, &constraint);-            }-            self.infcx.overwrite_solver_region_constraint(constraint);-        });+            return;+        }+        if let Some(assert_on_exit) = &forall.assert_on_exit {+            self.check_test_binder_region_constraints(forall.span, assert_on_exit, &constraint);+        }+        self.infcx.overwrite_solver_region_constraint(constraint);     }      fn build_test_binder_assumptions(@@ -2680,12 +2800,7 @@ impl<'tcx> WfCheckingCtxt<'_, 'tcx> {      #[instrument(level = "debug", skip(self))]     fn check_test_binder_exists(&self, exists: TestBinderExists<'tcx>) {-        let body = self.infcx.instantiate_binder_with_fresh_vars(-            exists.span,-            BoundRegionConversionTime::HigherRankedType,-            exists.binder,-        );-        self.check_test_binder_body(body);+        self.check_test_binder_body(exists.body);     } } @@ -2879,22 +2994,24 @@ pub(crate) enum TestBinderItem<'tcx> { #[derive(Clone, Debug, TypeFoldable, TypeVisitable)] pub(crate) struct TestBinderForall<'tcx> {     pub span: Span,-    pub binder: ty::Binder<'tcx, WithWhereClauses<'tcx, TestBinderBody<'tcx>>>,++    // HACK(khyperia): This universe index is specific to a particular infcx, and becomes invalid+    // after that infcx is done. However, this struct is dropped before the infcx that fills in this+    // field is finished, so the universe index is never observed by anyone else.+    pub universe: Option<ty::UniverseIndex>,+    pub params: Vec<Span>,++    pub type_outlives: Vec<ty::PolyTypeOutlivesClause<'tcx>>,+    pub region_outlives: Vec<ty::RegionOutlivesClause<'tcx>>,++    pub body: TestBinderBody<'tcx>,+     pub assert_on_exit: Option<SolverRegionConstraint<'tcx>>, }  #[derive(Clone, Debug, TypeFoldable, TypeVisitable)] pub(crate) struct TestBinderExists<'tcx> {     pub span: Span,-    pub binder: ty::Binder<'tcx, TestBinderBody<'tcx>>,-}--#[derive(Clone, Debug, TypeFoldable, TypeVisitable)]-pub(crate) struct WithWhereClauses<'tcx, T> {-    pub value: T,--    // The where clauses on the forall. These eventually will probably get stored inside-    // `ty::Binder` but they're here for now.-    pub type_outlives: Vec<ty::PolyTypeOutlivesClause<'tcx>>,-    pub region_outlives: Vec<ty::RegionOutlivesClause<'tcx>>,+    pub params: Vec<Span>,+    pub body: TestBinderBody<'tcx>, }
compiler/rustc_hir_analysis/src/collect.rs25 + / 11 −
@@ -323,11 +323,21 @@ impl<'tcx> ItemCtxt<'tcx> {         diag.emit_err()     } +    // The return value of this is not a normal binder. See docs on `check_test_binder_constraints`.     #[instrument(level = "debug", skip(self), ret)]-    pub(super) fn lower_test_binder_body(+    pub(super) fn lower_test_binder_constraints(         &self,+        def_id: LocalDefId,         body: &hir::TestBinderBody<'tcx>,-    ) -> TestBinderBody<'tcx> {+    ) -> ty::Binder<'tcx, TestBinderBody<'tcx>> {+        let hir_id = self.tcx.local_def_id_to_hir_id(def_id);+        let bound_vars = self.tcx.late_bound_vars(hir_id);+        let body = self.lower_test_binder_body(body);+        ty::Binder::bind_with_vars(body, bound_vars)+    }++    #[instrument(level = "debug", skip(self), ret)]+    fn lower_test_binder_body(&self, body: &hir::TestBinderBody<'tcx>) -> TestBinderBody<'tcx> {         let hir::TestBinderBody { span, items: hir_items } = body;         let mut items: Vec<TestBinderItem<'_>> = vec![];         for hir_item in *hir_items {@@ -371,31 +381,35 @@ impl<'tcx> ItemCtxt<'tcx> {         &self,         forall: &hir::TestBinderForall<'tcx>,     ) -> TestBinderForall<'tcx> {-        let bound_vars = self.tcx.late_bound_vars(forall.hir_id);-        let value = self.lower_test_binder_body(forall.body);+        let params = forall.generics.params.iter().map(|p| p.span).collect();+        let body = self.lower_test_binder_body(forall.body);         let mut type_outlives = vec![];         let mut region_outlives = vec![];         for predicate in forall.generics.predicates {             self.lower_test_binder_assumptions(predicate, &mut type_outlives, &mut region_outlives);         }-        let body =-            crate::check::wfcheck::WithWhereClauses { value, type_outlives, region_outlives };-        let binder = ty::Binder::bind_with_vars(body, bound_vars);         let assert_on_exit = forall             .assert_on_exit             .map(|assert_on_exit| self.lower_test_binder_constraint(assert_on_exit));-        TestBinderForall { span: forall.span, binder, assert_on_exit }+        TestBinderForall {+            span: forall.span,+            universe: None,+            params,+            type_outlives,+            region_outlives,+            body,+            assert_on_exit,+        }     }      #[instrument(level = "debug", skip(self), ret)]     pub(super) fn lower_test_binder_exists(         &self,         exists: &hir::TestBinderExists<'tcx>,     ) -> TestBinderExists<'tcx> {-        let bound_vars = self.tcx.late_bound_vars(exists.hir_id);+        let params = exists.params.iter().map(|p| p.span).collect();         let body = self.lower_test_binder_body(exists.body);-        let binder = ty::Binder::bind_with_vars(body, bound_vars);-        TestBinderExists { span: exists.span, binder }+        TestBinderExists { span: exists.span, params, body }     }      fn lower_test_binder_assumptions(
compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs68 + / 67 −
@@ -648,11 +648,13 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> {             | hir::ItemKind::Union(_, generics, _)             | hir::ItemKind::Trait { generics, .. }             | hir::ItemKind::TraitAlias(_, _, generics, ..)-            | hir::ItemKind::Impl(hir::Impl { generics, .. })-            | hir::ItemKind::TestBinderConstraints { generics, .. } => {+            | hir::ItemKind::Impl(hir::Impl { generics, .. }) => {                 // These kinds of items have only early-bound lifetime parameters.                 self.visit_early(item.hir_id(), generics, |this| intravisit::walk_item(this, item));             }+            hir::ItemKind::TestBinderConstraints { generics, body } => {+                self.visit_test_binder_constraints(item.hir_id(), generics, body)+            }         }     } @@ -1084,71 +1086,6 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> {         }     } -    fn visit_test_binder_forall(-        &mut self,-        forall: &'tcx hir::TestBinderForall<'tcx>,-    ) -> Self::Result {-        let (bound_vars, binders): (FxIndexMap<LocalDefId, ResolvedArg>, Vec<_>) = forall-            .generics-            .params-            .iter()-            .enumerate()-            .map(|(late_bound_idx, param)| {-                (-                    (param.def_id, ResolvedArg::late(late_bound_idx as u32, param)),-                    late_arg_as_bound_arg(param),-                )-            })-            .unzip();-        self.record_late_bound_vars(forall.hir_id, binders);-        let scope = Scope::Binder {-            hir_id: forall.hir_id,-            bound_vars,-            s: self.scope,-            scope_type: BinderScopeType::Normal,-            where_bound_origin: None,-        };-        self.with(scope, |this| {-            this.visit_generics(forall.generics);-            this.visit_test_binder_body(forall.body);-        });-        // exit assertions don't have the bound vars in scope-        if let Some(assert_on_exit) = forall.assert_on_exit {-            self.visit_test_binder_constraint(assert_on_exit);-        }-    }--    fn visit_test_binder_exists(-        &mut self,-        exists: &'tcx hir::TestBinderExists<'tcx>,-    ) -> Self::Result {-        let (bound_vars, binders): (FxIndexMap<LocalDefId, ResolvedArg>, Vec<_>) = exists-            .params-            .iter()-            .enumerate()-            .map(|(late_bound_idx, param)| {-                (-                    (param.def_id, ResolvedArg::late(late_bound_idx as u32, param)),-                    late_arg_as_bound_arg(param),-                )-            })-            .unzip();-        self.record_late_bound_vars(exists.hir_id, binders);-        let scope = Scope::Binder {-            hir_id: exists.hir_id,-            bound_vars,-            s: self.scope,-            scope_type: BinderScopeType::Normal,-            where_bound_origin: None,-        };-        self.with(scope, |this| {-            for param in exists.params {-                this.visit_generic_param(param);-            }-            this.visit_test_binder_body(exists.body);-        });-    }-     fn visit_test_binder_bound_type_constraint(         &mut self,         bound_type: &'tcx hir::TestBinderBoundTypeConstraint<'tcx>,@@ -2572,6 +2509,70 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> {             }         }     }++    fn visit_test_binder_constraints(+        &mut self,+        hir_id: HirId,+        generics: &'tcx hir::Generics<'tcx>,+        body: &'tcx hir::TestBinderBody<'tcx>,+    ) {+        fn collect_params<'a>(body: &hir::TestBinderBody<'a>, params: &mut Vec<GenericParam<'a>>) {+            for item in body.items {+                match item {+                    hir::TestBinderItem::Forall(item) => {+                        params.extend(item.generics.params);+                        collect_params(&item.body, params);+                    }+                    hir::TestBinderItem::Exists(item) => {+                        params.extend(item.params);+                        collect_params(&item.body, params);+                    }+                    hir::TestBinderItem::RegionEquality { .. }+                    | hir::TestBinderItem::Constraint(..)+                    | hir::TestBinderItem::Predicate(..) => (),+                }+            }+        }++        let mut params = vec![];+        collect_params(body, &mut params);++        let early_bound_vars =+            generics.params.iter().map(|param| (param.def_id, ResolvedArg::early(param))).collect();++        let (late_bound_vars, binders): (FxIndexMap<LocalDefId, ResolvedArg>, Vec<_>) = params+            .iter()+            .enumerate()+            .map(|(late_bound_idx, param)| {+                (+                    (param.def_id, ResolvedArg::late(late_bound_idx as u32, param)),+                    late_arg_as_bound_arg(param),+                )+            })+            .unzip();+        self.record_late_bound_vars(hir_id, binders);++        let early_scope = Scope::Binder {+            hir_id,+            bound_vars: early_bound_vars,+            s: self.scope,+            scope_type: BinderScopeType::Normal,+            where_bound_origin: None,+        };+        self.with(early_scope, |this| {+            this.with(Scope::TraitRefBoundary { s: this.scope }, |this| {+                this.visit_generics(generics);+                let late_scope = Scope::Binder {+                    hir_id,+                    bound_vars: late_bound_vars,+                    s: this.scope,+                    scope_type: BinderScopeType::Normal,+                    where_bound_origin: None,+                };+                this.with(late_scope, |this| this.visit_test_binder_body(body))+            })+        })+    } }  /// Detects late-bound lifetimes and inserts them into
compiler/rustc_hir_pretty/src/lib.rs0 + / 2 −
@@ -220,8 +220,6 @@ impl<'a> State<'a> {             Node::Crate(..) => panic!("cannot print Crate"),             Node::WherePredicate(pred) => self.print_where_predicate(pred),             Node::NestedUseTree(tree) => self.print_use_tree(tree),-            Node::TestBinderForall(_) => panic!("cannot print Node::TestBinderForall"),-            Node::TestBinderExists(_) => panic!("cannot print Node::TestBinderExists"),             Node::TestBinderBoundTypeConstraint(_) => {                 panic!("cannot print Node::TestBinderBoundTypeConstraint")             }
compiler/rustc_middle/src/hir/map.rs0 + / 4 −
@@ -800,8 +800,6 @@ impl<'tcx> TyCtxt<'tcx> {             Node::WherePredicate(_) => node_str("where predicate"),             Node::NestedUseTree(_) => node_str("use"),             Node::PreciseCapturingNonLifetimeArg(_param) => node_str("parameter"),-            Node::TestBinderForall(_) => node_str("forall"),-            Node::TestBinderExists(_) => node_str("exists"),             Node::TestBinderBoundTypeConstraint(_) => node_str("test bound type constraint"),             Node::Synthetic => unreachable!(),             Node::Err(_) => node_str("error"),@@ -1095,8 +1093,6 @@ impl<'tcx> TyCtxt<'tcx> {             Node::WherePredicate(pred) => pred.span,             Node::PreciseCapturingNonLifetimeArg(param) => param.ident.span,             Node::NestedUseTree(tree) => tree.prefix.span,-            Node::TestBinderForall(forall) => forall.span,-            Node::TestBinderExists(exists) => exists.span,             Node::TestBinderBoundTypeConstraint(bound_type) => bound_type.span,             Node::Synthetic => unreachable!(),             Node::Err(span) => span,
compiler/rustc_middle/src/hir/mod.rs0 + / 2 −
@@ -353,8 +353,6 @@ impl<'tcx> TyCtxt<'tcx> {             | Node::PreciseCapturingNonLifetimeArg(_)             | Node::ConstArgExprField(_)             | Node::OpaqueTy(_)-            | Node::TestBinderForall(_)-            | Node::TestBinderExists(_)             | Node::TestBinderBoundTypeConstraint(_) => {                 unreachable!("no sub-expr expected for {parent_node:?}")             }
compiler/rustc_parse/src/parser/item.rs2 + / 2 −
@@ -2790,15 +2790,15 @@ impl<'a> Parser<'a> {             None         }; -        Ok(TestBinderForall { span, node_id: DUMMY_NODE_ID, generics, body, assert_on_exit })+        Ok(TestBinderForall { span, generics, body, assert_on_exit })     }      pub fn parse_test_binder_exists(&mut self) -> PResult<'a, TestBinderExists> {         let span = self.token.span;         self.bump();         let params = self.parse_generics()?.params;         let body = self.parse_test_binder_body()?;-        Ok(TestBinderExists { span, node_id: DUMMY_NODE_ID, params, body })+        Ok(TestBinderExists { span, params, body })     }      pub fn parse_test_binder_constraint(&mut self) -> PResult<'a, TestBinderConstraint> {
compiler/rustc_resolve/src/late.rs34 + / 38 −
@@ -1585,37 +1585,6 @@ impl<'ast, 'ra, 'tcx> Visitor<'ast> for LateResolutionVisitor<'_, 'ast, 'ra, 'tc         }     } -    fn visit_test_binder_forall(&mut self, forall: &'ast TestBinderForall) {-        self.with_generic_param_rib(-            &forall.generics.params,-            RibKind::Normal,-            forall.node_id,-            LifetimeBinderKind::WhereBound,-            forall.span,-            |this| {-                this.visit_generics(&forall.generics);-                this.visit_test_binder_body(&forall.body)-            },-        );-        // exit assertions don't have the bound vars in scope-        if let Some(assert_on_exit) = &forall.assert_on_exit {-            for constraint in assert_on_exit {-                self.visit_test_binder_constraint(constraint);-            }-        }-    }--    fn visit_test_binder_exists(&mut self, exists: &'ast TestBinderExists) {-        self.with_generic_param_rib(-            &exists.params,-            RibKind::Normal,-            exists.node_id,-            LifetimeBinderKind::WhereBound,-            exists.span,-            |this| visit::walk_test_binder_exists(this, exists),-        );-    }-     fn visit_test_binder_bound_type_constraint(         &mut self,         bound_type: &'ast TestBinderBoundTypeConstraint,@@ -3824,21 +3793,48 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {         constraints: &'ast TestBinderConstraints,         item_id: NodeId,     ) {-        let generics = &constraints.generics;+        fn collect_params(body: &TestBinderBody, params: &mut Vec<GenericParam>) {+            for item in &body.items {+                match item {+                    TestBinderItem::Forall(item) => {+                        params.extend(item.generics.params.iter().cloned());+                        collect_params(&item.body, params);+                    }+                    TestBinderItem::Exists(item) => {+                        params.extend(item.params.iter().cloned());+                        collect_params(&item.body, params);+                    }+                    TestBinderItem::RegionEquality { .. }+                    | TestBinderItem::Constraint(..)+                    | TestBinderItem::Predicate(..) => (),+                }+            }+        }++        let mut params = vec![];+        collect_params(&constraints.body, &mut params);+         self.with_generic_param_rib(-            &generics.params,+            &constraints.generics.params,             RibKind::Item(-                HasGenericParams::Yes(generics.span),+                HasGenericParams::Yes(constraints.generics.span),                 self.r.tcx.def_kind(self.r.current_owner.def_id),             ),             item_id,             LifetimeBinderKind::ImplBlock,-            generics.span,+            constraints.generics.span,             |this| {-                this.visit_generics(generics);-                this.visit_test_binder_body(&constraints.body);+                this.visit_generics(&constraints.generics);+                this.with_generic_param_rib(+                    &params,+                    RibKind::Normal,+                    item_id,+                    LifetimeBinderKind::WhereBound,+                    constraints.generics.span,+                    |this| this.visit_test_binder_body(&constraints.body),+                )             },-        );+        )     }      fn resolve_impl_item(
compiler/rustc_type_ir/src/binder.rs4 + / 0 −
@@ -123,6 +123,10 @@ impl<I: Interner, T> Binder<I, T> {         Binder { value: &self.value, bound_vars: self.bound_vars }     } +    pub fn as_mut(&mut self) -> Binder<I, &mut T> {+        Binder { value: &mut self.value, bound_vars: self.bound_vars }+    }+     pub fn as_deref(&self) -> Binder<I, &T::Target>     where         T: Deref,
src/tools/clippy/clippy_utils/src/lib.rs0 + / 2 −
@@ -2809,8 +2809,6 @@ pub fn expr_use_sites<'tcx>(                 | Node::TyPat(_)                 | Node::NestedUseTree(_)                 | Node::WherePredicate(_)-                | Node::TestBinderForall(_)-                | Node::TestBinderExists(_)                 | Node::TestBinderBoundTypeConstraint(_) => {                     // This shouldn't be possible to hit; the inner iterator should have                     // been moved to the end before we hit any of these nodes.
tests/ui/assumptions_on_binders/alias_outlives_with_repeated_placeholder.rs3 + / 3 −
@@ -14,11 +14,11 @@ core::test_binder_constraints! {         for<'a> T: Trait<'a>,         for<'a> <T as Trait<'a>>::Assoc: 'a     {-        forall<'a, 'b>+        forall<'c, 'd>         where-            'a: 'b,+            'c: 'd,         {-            for<> <T as Trait<'a>>::Assoc: 'b+            for<> <T as Trait<'c>>::Assoc: 'd         } expect {             or {                 // this first candidate is the important one!
tests/ui/assumptions_on_binders/relating-region-equality.rs6 + / 6 −
@@ -35,16 +35,16 @@ core::test_binder_constraints! { core::test_binder_constraints! {     impl<'c, T>     where-        for<'a, 'b> T: Trait<'a, 'b>,+        for<'a, 'd> T: Trait<'a, 'd>,     {         forall<'a>         where-            for<'b> <T as Trait<'a, 'b>>::Assoc: 'c,+            for<'d> <T as Trait<'a, 'd>>::Assoc: 'c,         {             forall<'b> {                 predicates Carrier<T>: Require<'a, 'b, 'c, T>             } expect {-                for<'b> <T as Trait<'a, 'b>>::Assoc: 'c+                for<'d> <T as Trait<'a, 'd>>::Assoc: 'c             }         } expect {}     }@@ -53,18 +53,18 @@ core::test_binder_constraints! { core::test_binder_constraints! {     impl<'c, T>     where-        for<'a, 'b> T: Trait<'a, 'b>,+        for<'a, 'd> T: Trait<'a, 'd>,     {         forall<'a>         where-            for<'b> <T as Trait<'a, 'b>>::Assoc: 'c,+            for<'d> <T as Trait<'a, 'd>>::Assoc: 'c,         {             forall<'b> {                 exists<X> {                     predicates Carrier<X>: Require<'a, 'b, 'c, T>                 }             } expect {-                for<'b> <T as Trait<'a, 'b>>::Assoc: 'c+                for<'d> <T as Trait<'a, 'd>>::Assoc: 'c             }         } expect {}     }
tests/ui/assumptions_on_binders/replace_region_vars_with_placeholders.rs2 + / 2 −
@@ -21,8 +21,8 @@ core::test_binder_constraints! {             for<'a> <T as Trait<'a>>::Assoc: 'b         {             forall<> {-                exists<'a> {-                    for<> <T as Trait<'a>>::Assoc: 'b+                exists<'c> {+                    for<> <T as Trait<'c>>::Assoc: 'b                 }             } expect {                 for<'a> <T as Trait<'a>>::Assoc: 'b
tests/ui/assumptions_on_binders/resolve-region-vars.rs8 + / 8 −
@@ -16,8 +16,8 @@ core::test_binder_constraints! {         where             for<'b> <T as Trait<'a, 'b>>::Assoc: 'c,         {-            forall<'b> {-                predicates <T as Trait<'a, 'b>>::Assoc: 'c+            forall<'d> {+                predicates <T as Trait<'a, 'd>>::Assoc: 'c             } expect {                 for<'b> <T as Trait<'a, 'b>>::Assoc: 'c             }@@ -28,11 +28,11 @@ core::test_binder_constraints! { core::test_binder_constraints! {     impl<'c, T>     where-        for<'a, 'b> T: Trait<'a, 'b>,+        for<'a, 'd> T: Trait<'a, 'd>,     {         forall<'a>         where-            for<'b> <T as Trait<'a, 'b>>::Assoc: 'c,+            for<'d> <T as Trait<'a, 'd>>::Assoc: 'c,         {             forall<'b> {                 exists<'a2, 'b2, 'c2> {@@ -45,7 +45,7 @@ core::test_binder_constraints! {                     }                 }             } expect {-                for<'b> <T as Trait<'a, 'b>>::Assoc: 'c+                for<'d> <T as Trait<'a, 'd>>::Assoc: 'c             }         } expect { }     }@@ -54,11 +54,11 @@ core::test_binder_constraints! { core::test_binder_constraints! {     impl<'c, T>     where-        for<'a, 'b> T: Trait<'a, 'b>,+        for<'a, 'd> T: Trait<'a, 'd>,     {         forall<'a>         where-            for<'b> <T as Trait<'a, 'b>>::Assoc: 'c,+            for<'d> <T as Trait<'a, 'd>>::Assoc: 'c,         {             forall<'b> {                 exists<'a2, 'b2, 'c2> {@@ -73,7 +73,7 @@ core::test_binder_constraints! {                     }                 }             } expect {-                for<'b> <T as Trait<'a, 'b>>::Assoc: 'c+                for<'d> <T as Trait<'a, 'd>>::Assoc: 'c             }         } expect { }     }
tests/ui/assumptions_on_binders/test-infra-fails-properly.rs8 + / 0 −
@@ -116,4 +116,12 @@ core::test_binder_constraints! {     } } +core::test_binder_constraints! {+    impl {+        forall<'a> {},+        forall<'a> {},+        //~^ ERROR the name `'a` is already used for a generic parameter in this item's generic parameters+    }+}+ fn main() {}
tests/ui/assumptions_on_binders/test-infra-fails-properly.stderr11 + / 2 −
@@ -16,6 +16,14 @@ error: expected lifetime, found keyword `for` LL |         T: for<'b> Trait<'b>,    |            ^^^ expected lifetime +error[E0403]: the name `'a` is already used for a generic parameter in this item's generic parameters+  --> $DIR/test-infra-fails-properly.rs:122:16+   |+LL |         forall<'a> {},+   |                -- first use of `'a`+LL |         forall<'a> {},+   |                ^^ already used+ error[E0658]: only lifetime parameters can be used in this context   --> $DIR/test-infra-fails-properly.rs:48:16    |@@ -135,6 +143,7 @@ error: unable to satisfy constraints involving placeholders due to unknown impli LL |         forall<'a> where 'a: 'static {    |         ^^^^^^ -error: aborting due to 16 previous errors+error: aborting due to 17 previous errors -For more information about this error, try `rustc --explain E0658`.+Some errors have detailed explanations: E0403, E0658.+For more information about an error, try `rustc --explain E0403`.
tests/ui/assumptions_on_binders/test-infra-works.rs10 + / 2 −
@@ -86,8 +86,16 @@ core::test_binder_constraints! { core::test_binder_constraints! {     impl<TParam: Trait> {         forall<'a> where TParam: 'a { },-        forall<'a> where TParam::Assoc: 'a { },-        forall<'a, T> where T: 'a { },+        forall<'b> where TParam::Assoc: 'b { },+        forall<'c, T> where T: 'c { },+    }+}++core::test_binder_constraints! {+    impl {+        forall<'a> {},+        // leaking 'a+        'static: 'a,     } }