From 63c15e4bd5762307e6e72a74e328024fa5c4b029 Mon Sep 17 00:00:00 2001 From: Embers-of-the-Fire Date: Sun, 22 Mar 2026 19:14:07 +0800 Subject: [PATCH 01/26] test: cover current if let closure capture behavior --- .../if-let-patterns-capture-analysis.rs | 54 +++++++++++ .../if-let-patterns-capture-analysis.stderr | 90 +++++++++++++++++++ 2 files changed, 144 insertions(+) create mode 100644 tests/ui/closures/2229_closure_analysis/if-let-patterns-capture-analysis.rs create mode 100644 tests/ui/closures/2229_closure_analysis/if-let-patterns-capture-analysis.stderr diff --git a/tests/ui/closures/2229_closure_analysis/if-let-patterns-capture-analysis.rs b/tests/ui/closures/2229_closure_analysis/if-let-patterns-capture-analysis.rs new file mode 100644 index 0000000000000..10b01d456d7bd --- /dev/null +++ b/tests/ui/closures/2229_closure_analysis/if-let-patterns-capture-analysis.rs @@ -0,0 +1,54 @@ +//@ edition:2021 + +#![feature(rustc_attrs)] +#![feature(stmt_expr_attributes)] +#![allow(irrefutable_let_patterns)] + +enum SingleVariant { + Pair(i32, String), +} + +fn if_let_closure() { + let variant = SingleVariant::Pair(1, "hello".into()); + + let c = #[rustc_capture_analysis] + || { + //~^ ERROR First Pass analysis includes: + //~| ERROR Min Capture analysis includes: + if let SingleVariant::Pair(ref n, s) = variant { + //~^ NOTE: Capturing variant[] -> Immutable + //~| NOTE: Capturing variant[(0, 0)] -> Immutable + //~| NOTE: Capturing variant[(1, 0)] -> ByValue + //~| NOTE: Min Capture variant[] -> ByValue + let _ = (n, s); + } + }; + + c(); +} + +fn match_closure() { + let variant = SingleVariant::Pair(1, "hello".into()); + + let c = #[rustc_capture_analysis] + || { + //~^ ERROR First Pass analysis includes: + //~| ERROR Min Capture analysis includes: + match variant { + //~^ NOTE: Capturing variant[(0, 0)] -> Immutable + //~| NOTE: Capturing variant[(1, 0)] -> ByValue + //~| NOTE: Min Capture variant[(0, 0)] -> Immutable + //~| NOTE: Min Capture variant[(1, 0)] -> ByValue + SingleVariant::Pair(ref n, s) => { + let _ = (n, s); + } + } + }; + + c(); +} + +fn main() { + if_let_closure(); + match_closure(); +} diff --git a/tests/ui/closures/2229_closure_analysis/if-let-patterns-capture-analysis.stderr b/tests/ui/closures/2229_closure_analysis/if-let-patterns-capture-analysis.stderr new file mode 100644 index 0000000000000..d93f333a5ef0c --- /dev/null +++ b/tests/ui/closures/2229_closure_analysis/if-let-patterns-capture-analysis.stderr @@ -0,0 +1,90 @@ +error: First Pass analysis includes: + --> $DIR/if-let-patterns-capture-analysis.rs:15:5 + | +LL | / || { +LL | | +LL | | +LL | | if let SingleVariant::Pair(ref n, s) = variant { +... | +LL | | }; + | |_____^ + | +note: Capturing variant[] -> Immutable + --> $DIR/if-let-patterns-capture-analysis.rs:18:48 + | +LL | if let SingleVariant::Pair(ref n, s) = variant { + | ^^^^^^^ +note: Capturing variant[(0, 0)] -> Immutable + --> $DIR/if-let-patterns-capture-analysis.rs:18:48 + | +LL | if let SingleVariant::Pair(ref n, s) = variant { + | ^^^^^^^ +note: Capturing variant[(1, 0)] -> ByValue + --> $DIR/if-let-patterns-capture-analysis.rs:18:48 + | +LL | if let SingleVariant::Pair(ref n, s) = variant { + | ^^^^^^^ + +error: Min Capture analysis includes: + --> $DIR/if-let-patterns-capture-analysis.rs:15:5 + | +LL | / || { +LL | | +LL | | +LL | | if let SingleVariant::Pair(ref n, s) = variant { +... | +LL | | }; + | |_____^ + | +note: Min Capture variant[] -> ByValue + --> $DIR/if-let-patterns-capture-analysis.rs:18:48 + | +LL | if let SingleVariant::Pair(ref n, s) = variant { + | ^^^^^^^ + +error: First Pass analysis includes: + --> $DIR/if-let-patterns-capture-analysis.rs:34:5 + | +LL | / || { +LL | | +LL | | +LL | | match variant { +... | +LL | | }; + | |_____^ + | +note: Capturing variant[(0, 0)] -> Immutable + --> $DIR/if-let-patterns-capture-analysis.rs:37:15 + | +LL | match variant { + | ^^^^^^^ +note: Capturing variant[(1, 0)] -> ByValue + --> $DIR/if-let-patterns-capture-analysis.rs:37:15 + | +LL | match variant { + | ^^^^^^^ + +error: Min Capture analysis includes: + --> $DIR/if-let-patterns-capture-analysis.rs:34:5 + | +LL | / || { +LL | | +LL | | +LL | | match variant { +... | +LL | | }; + | |_____^ + | +note: Min Capture variant[(0, 0)] -> Immutable + --> $DIR/if-let-patterns-capture-analysis.rs:37:15 + | +LL | match variant { + | ^^^^^^^ +note: Min Capture variant[(1, 0)] -> ByValue + --> $DIR/if-let-patterns-capture-analysis.rs:37:15 + | +LL | match variant { + | ^^^^^^^ + +error: aborting due to 4 previous errors + From 923ef1fdbafd2144c69704a774df49dc172fddb1 Mon Sep 17 00:00:00 2001 From: Embers-of-the-Fire Date: Sun, 22 Mar 2026 19:20:24 +0800 Subject: [PATCH 02/26] fix: drop eager if let scrutinee borrow during capture analysis --- .../rustc_hir_typeck/src/expr_use_visitor.rs | 2 +- .../2229_closure_analysis/capture-enums.rs | 2 -- .../capture-enums.stderr | 24 ++++++------------- .../if-let-patterns-capture-analysis.rs | 6 ++--- .../if-let-patterns-capture-analysis.stderr | 12 +++++----- 5 files changed, 17 insertions(+), 29 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/expr_use_visitor.rs b/compiler/rustc_hir_typeck/src/expr_use_visitor.rs index a924a81f89b0d..acf3112bd8fba 100644 --- a/compiler/rustc_hir_typeck/src/expr_use_visitor.rs +++ b/compiler/rustc_hir_typeck/src/expr_use_visitor.rs @@ -451,7 +451,7 @@ impl<'tcx, Cx: TypeInformationCtxt<'tcx>, D: Delegate<'tcx>> ExprUseVisitor<'tcx } hir::ExprKind::Let(hir::LetExpr { pat, init, .. }) => { - self.walk_local(init, pat, None, || self.borrow_expr(init, BorrowKind::Immutable))?; + self.walk_local(init, pat, None, || Ok(()))?; } hir::ExprKind::Match(discr, arms, _) => { diff --git a/tests/ui/closures/2229_closure_analysis/capture-enums.rs b/tests/ui/closures/2229_closure_analysis/capture-enums.rs index 36b98351854bf..b0f0b4fcfb5f0 100644 --- a/tests/ui/closures/2229_closure_analysis/capture-enums.rs +++ b/tests/ui/closures/2229_closure_analysis/capture-enums.rs @@ -20,7 +20,6 @@ fn multi_variant_enum() { //~| ERROR Min Capture analysis includes: if let Info::Point(_, _, str) = point { //~^ NOTE: Capturing point[] -> Immutable - //~| NOTE: Capturing point[] -> Immutable //~| NOTE: Capturing point[(2, 0)] -> ByValue //~| NOTE: Min Capture point[] -> ByValue println!("{}", str); @@ -28,7 +27,6 @@ fn multi_variant_enum() { if let Info::Meta(_, v) = meta { //~^ NOTE: Capturing meta[] -> Immutable - //~| NOTE: Capturing meta[] -> Immutable //~| NOTE: Capturing meta[(1, 1)] -> ByValue //~| NOTE: Min Capture meta[] -> ByValue println!("{:?}", v); diff --git a/tests/ui/closures/2229_closure_analysis/capture-enums.stderr b/tests/ui/closures/2229_closure_analysis/capture-enums.stderr index 2f49c8668f85c..2165c3bd828f1 100644 --- a/tests/ui/closures/2229_closure_analysis/capture-enums.stderr +++ b/tests/ui/closures/2229_closure_analysis/capture-enums.stderr @@ -14,28 +14,18 @@ note: Capturing point[] -> Immutable | LL | if let Info::Point(_, _, str) = point { | ^^^^^ -note: Capturing point[] -> Immutable - --> $DIR/capture-enums.rs:21:41 - | -LL | if let Info::Point(_, _, str) = point { - | ^^^^^ note: Capturing point[(2, 0)] -> ByValue --> $DIR/capture-enums.rs:21:41 | LL | if let Info::Point(_, _, str) = point { | ^^^^^ note: Capturing meta[] -> Immutable - --> $DIR/capture-enums.rs:29:35 - | -LL | if let Info::Meta(_, v) = meta { - | ^^^^ -note: Capturing meta[] -> Immutable - --> $DIR/capture-enums.rs:29:35 + --> $DIR/capture-enums.rs:28:35 | LL | if let Info::Meta(_, v) = meta { | ^^^^ note: Capturing meta[(1, 1)] -> ByValue - --> $DIR/capture-enums.rs:29:35 + --> $DIR/capture-enums.rs:28:35 | LL | if let Info::Meta(_, v) = meta { | ^^^^ @@ -57,13 +47,13 @@ note: Min Capture point[] -> ByValue LL | if let Info::Point(_, _, str) = point { | ^^^^^ note: Min Capture meta[] -> ByValue - --> $DIR/capture-enums.rs:29:35 + --> $DIR/capture-enums.rs:28:35 | LL | if let Info::Meta(_, v) = meta { | ^^^^ error: First Pass analysis includes: - --> $DIR/capture-enums.rs:49:5 + --> $DIR/capture-enums.rs:47:5 | LL | / || { LL | | @@ -75,13 +65,13 @@ LL | | }; | |_____^ | note: Capturing point[(2, 0)] -> ByValue - --> $DIR/capture-enums.rs:52:47 + --> $DIR/capture-enums.rs:50:47 | LL | let SingleVariant::Point(_, _, str) = point; | ^^^^^ error: Min Capture analysis includes: - --> $DIR/capture-enums.rs:49:5 + --> $DIR/capture-enums.rs:47:5 | LL | / || { LL | | @@ -93,7 +83,7 @@ LL | | }; | |_____^ | note: Min Capture point[(2, 0)] -> ByValue - --> $DIR/capture-enums.rs:52:47 + --> $DIR/capture-enums.rs:50:47 | LL | let SingleVariant::Point(_, _, str) = point; | ^^^^^ diff --git a/tests/ui/closures/2229_closure_analysis/if-let-patterns-capture-analysis.rs b/tests/ui/closures/2229_closure_analysis/if-let-patterns-capture-analysis.rs index 10b01d456d7bd..e5f6e940c1c42 100644 --- a/tests/ui/closures/2229_closure_analysis/if-let-patterns-capture-analysis.rs +++ b/tests/ui/closures/2229_closure_analysis/if-let-patterns-capture-analysis.rs @@ -16,10 +16,10 @@ fn if_let_closure() { //~^ ERROR First Pass analysis includes: //~| ERROR Min Capture analysis includes: if let SingleVariant::Pair(ref n, s) = variant { - //~^ NOTE: Capturing variant[] -> Immutable - //~| NOTE: Capturing variant[(0, 0)] -> Immutable + //~^ NOTE: Capturing variant[(0, 0)] -> Immutable //~| NOTE: Capturing variant[(1, 0)] -> ByValue - //~| NOTE: Min Capture variant[] -> ByValue + //~| NOTE: Min Capture variant[(0, 0)] -> Immutable + //~| NOTE: Min Capture variant[(1, 0)] -> ByValue let _ = (n, s); } }; diff --git a/tests/ui/closures/2229_closure_analysis/if-let-patterns-capture-analysis.stderr b/tests/ui/closures/2229_closure_analysis/if-let-patterns-capture-analysis.stderr index d93f333a5ef0c..eee008aace344 100644 --- a/tests/ui/closures/2229_closure_analysis/if-let-patterns-capture-analysis.stderr +++ b/tests/ui/closures/2229_closure_analysis/if-let-patterns-capture-analysis.stderr @@ -9,11 +9,6 @@ LL | | if let SingleVariant::Pair(ref n, s) = variant { LL | | }; | |_____^ | -note: Capturing variant[] -> Immutable - --> $DIR/if-let-patterns-capture-analysis.rs:18:48 - | -LL | if let SingleVariant::Pair(ref n, s) = variant { - | ^^^^^^^ note: Capturing variant[(0, 0)] -> Immutable --> $DIR/if-let-patterns-capture-analysis.rs:18:48 | @@ -36,7 +31,12 @@ LL | | if let SingleVariant::Pair(ref n, s) = variant { LL | | }; | |_____^ | -note: Min Capture variant[] -> ByValue +note: Min Capture variant[(0, 0)] -> Immutable + --> $DIR/if-let-patterns-capture-analysis.rs:18:48 + | +LL | if let SingleVariant::Pair(ref n, s) = variant { + | ^^^^^^^ +note: Min Capture variant[(1, 0)] -> ByValue --> $DIR/if-let-patterns-capture-analysis.rs:18:48 | LL | if let SingleVariant::Pair(ref n, s) = variant { From 665416dcb036a5dd807c0a115fb46ff937288fe3 Mon Sep 17 00:00:00 2001 From: Embers-of-the-Fire Date: Sun, 22 Mar 2026 20:56:07 +0800 Subject: [PATCH 03/26] test(ui): add regression for if-let closure capture size --- .../run_pass/if-let-capture.rs | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 tests/ui/closures/2229_closure_analysis/run_pass/if-let-capture.rs diff --git a/tests/ui/closures/2229_closure_analysis/run_pass/if-let-capture.rs b/tests/ui/closures/2229_closure_analysis/run_pass/if-let-capture.rs new file mode 100644 index 0000000000000..2e78e856cef57 --- /dev/null +++ b/tests/ui/closures/2229_closure_analysis/run_pass/if-let-capture.rs @@ -0,0 +1,51 @@ +//@ edition:2021 +//@ run-pass + +// Regression test for #153982: `if let` in a closure should capture only the +// moved field, matching `match` and plain `let` destructuring. + +#![allow(dead_code, irrefutable_let_patterns)] + +use std::mem::{size_of, size_of_val}; + +struct Thing(String, String); + +fn if_let_capture_size(x: Thing) -> usize { + let closure = || { + if let Thing(_a, _) = x {} + }; + + size_of_val(&closure) +} + +fn match_capture_size(x: Thing) -> usize { + let closure = || { + match x { + Thing(_a, _) => {} + } + }; + + size_of_val(&closure) +} + +fn let_capture_size(x: Thing) -> usize { + let closure = || { + let Thing(_a, _) = x; + }; + + size_of_val(&closure) +} + +fn main() { + let if_let_size = if_let_capture_size(Thing(String::from("a"), String::from("b"))); + let match_size = match_capture_size(Thing(String::from("a"), String::from("b"))); + let let_size = let_capture_size(Thing(String::from("a"), String::from("b"))); + + assert_eq!(if_let_size, size_of::()); + assert_eq!(match_size, size_of::()); + assert_eq!(let_size, size_of::()); + + assert_eq!(if_let_size, match_size); + assert_eq!(if_let_size, let_size); + assert_ne!(if_let_size, size_of::()); +} From 2aadcee180e76fdf93d2f1dd3eaaa0f30c5d2112 Mon Sep 17 00:00:00 2001 From: Embers-of-the-Fire Date: Sun, 22 Mar 2026 21:07:12 +0800 Subject: [PATCH 04/26] feat: remove callback param for walk_local method --- compiler/rustc_hir_typeck/src/expr_use_visitor.rs | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/expr_use_visitor.rs b/compiler/rustc_hir_typeck/src/expr_use_visitor.rs index acf3112bd8fba..6d36464dd282b 100644 --- a/compiler/rustc_hir_typeck/src/expr_use_visitor.rs +++ b/compiler/rustc_hir_typeck/src/expr_use_visitor.rs @@ -451,7 +451,7 @@ impl<'tcx, Cx: TypeInformationCtxt<'tcx>, D: Delegate<'tcx>> ExprUseVisitor<'tcx } hir::ExprKind::Let(hir::LetExpr { pat, init, .. }) => { - self.walk_local(init, pat, None, || Ok(()))?; + self.walk_local(init, pat, None)?; } hir::ExprKind::Match(discr, arms, _) => { @@ -577,7 +577,7 @@ impl<'tcx, Cx: TypeInformationCtxt<'tcx>, D: Delegate<'tcx>> ExprUseVisitor<'tcx fn walk_stmt(&self, stmt: &hir::Stmt<'_>) -> Result<(), Cx::Error> { match stmt.kind { hir::StmtKind::Let(hir::LetStmt { pat, init: Some(expr), els, .. }) => { - self.walk_local(expr, pat, *els, || Ok(()))?; + self.walk_local(expr, pat, *els)?; } hir::StmtKind::Let(_) => {} @@ -617,19 +617,14 @@ impl<'tcx, Cx: TypeInformationCtxt<'tcx>, D: Delegate<'tcx>> ExprUseVisitor<'tcx Ok(()) } - fn walk_local( + fn walk_local( &self, expr: &hir::Expr<'_>, pat: &hir::Pat<'_>, els: Option<&hir::Block<'_>>, - mut f: F, - ) -> Result<(), Cx::Error> - where - F: FnMut() -> Result<(), Cx::Error>, - { + ) -> Result<(), Cx::Error> { self.walk_expr(expr)?; let expr_place = self.cat_expr(expr)?; - f()?; self.fake_read_scrutinee(&expr_place, els.is_some())?; self.walk_pat(&expr_place, pat, false)?; if let Some(els) = els { From 1f81a55b1801273054e0184be4bb354eee3c4ba1 Mon Sep 17 00:00:00 2001 From: Embers-of-the-Fire Date: Sat, 18 Apr 2026 13:01:10 +0800 Subject: [PATCH 05/26] test: add if let test for partial capture Signed-off-by: Embers-of-the-Fire --- .../2229_closure_analysis/run_pass/if-let-capture.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/tests/ui/closures/2229_closure_analysis/run_pass/if-let-capture.rs b/tests/ui/closures/2229_closure_analysis/run_pass/if-let-capture.rs index 2e78e856cef57..98986577c08e2 100644 --- a/tests/ui/closures/2229_closure_analysis/run_pass/if-let-capture.rs +++ b/tests/ui/closures/2229_closure_analysis/run_pass/if-let-capture.rs @@ -47,5 +47,9 @@ fn main() { assert_eq!(if_let_size, match_size); assert_eq!(if_let_size, let_size); - assert_ne!(if_let_size, size_of::()); + + // The closure should capture only the moved field, so its size should be + // less than the size of `Thing`, which would indicate that it captures the + // entire struct. + assert!(if_let_size <= size_of::()); } From f491a6c0ad5e73269181789425b510ec11d84d9e Mon Sep 17 00:00:00 2001 From: Embers-of-the-Fire Date: Thu, 21 May 2026 12:49:44 +0800 Subject: [PATCH 06/26] test(miri): add if-let closure capture UB smoke tests Add focused Miri coverage for the if-let closure capture change, demonstrating UB at closure construction when partial pattern capture reborrows dangling references. Assisted-by: OpenAI:gpt-5.5 Signed-off-by: Embers-of-the-Fire --- .../match/closures/if-let-deref-in-pattern.rs | 25 ++++++++++++++ .../closures/if-let-deref-in-pattern.stderr | 16 +++++++++ .../match/closures/if-let-partial-pattern.rs | 33 +++++++++++++++++++ .../closures/if-let-partial-pattern.stderr | 16 +++++++++ 4 files changed, 90 insertions(+) create mode 100644 src/tools/miri/tests/fail/match/closures/if-let-deref-in-pattern.rs create mode 100644 src/tools/miri/tests/fail/match/closures/if-let-deref-in-pattern.stderr create mode 100644 src/tools/miri/tests/fail/match/closures/if-let-partial-pattern.rs create mode 100644 src/tools/miri/tests/fail/match/closures/if-let-partial-pattern.stderr diff --git a/src/tools/miri/tests/fail/match/closures/if-let-deref-in-pattern.rs b/src/tools/miri/tests/fail/match/closures/if-let-deref-in-pattern.rs new file mode 100644 index 0000000000000..5303a09237d30 --- /dev/null +++ b/src/tools/miri/tests/fail/match/closures/if-let-deref-in-pattern.rs @@ -0,0 +1,25 @@ +// This test serves to document the change in semantics introduced by +// rust-lang/rust#138961, extended to `if let` closure captures. +// +// A corollary of partial-pattern.rs: while the tuple access testcase makes +// it clear why these semantics are useful, it is actually the dereference +// being performed by the pattern that matters. +// +// Before rust-lang/rust#154210, `if let` in closures captured all of `x`, so +// this test did not fail because the closure is never called. +//@normalize-stderr-test: "constructing invalid value of type [^:]+:" -> "constructing invalid value:" + +#![allow(irrefutable_let_patterns)] + +fn main() { + // the inner reference is dangling + let x: &&u32 = unsafe { + let x: u32 = 42; + &&*&raw const x + }; + + //~v ERROR: encountered a dangling reference + let _ = || { + if let &&_y = x {} + }; +} diff --git a/src/tools/miri/tests/fail/match/closures/if-let-deref-in-pattern.stderr b/src/tools/miri/tests/fail/match/closures/if-let-deref-in-pattern.stderr new file mode 100644 index 0000000000000..77b85ee39e358 --- /dev/null +++ b/src/tools/miri/tests/fail/match/closures/if-let-deref-in-pattern.stderr @@ -0,0 +1,16 @@ +error: Undefined Behavior: constructing invalid value: encountered a dangling reference (use-after-free) + --> tests/fail/match/closures/if-let-deref-in-pattern.rs:LL:CC + | +LL | let _ = || { + | _____________^ +LL | | if let &&_y = x {} +LL | | }; + | |_____^ Undefined Behavior occurred here + | + = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior + = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information + +note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace + +error: aborting due to 1 previous error + diff --git a/src/tools/miri/tests/fail/match/closures/if-let-partial-pattern.rs b/src/tools/miri/tests/fail/match/closures/if-let-partial-pattern.rs new file mode 100644 index 0000000000000..197564366e0f8 --- /dev/null +++ b/src/tools/miri/tests/fail/match/closures/if-let-partial-pattern.rs @@ -0,0 +1,33 @@ +// This test serves to document the change in semantics introduced by +// rust-lang/rust#138961, extended to `if let` closure captures. +// +// Previously, the closure would capture the entirety of x, and access *(*x).0 +// when called. Now, the closure only captures *(*x).0, which means that +// a &*(*x).0 reborrow happens when the closure is constructed. +// +// Hence, if one of the references is dangling, this constitutes newly introduced UB +// in the case where the closure doesn't get called. This isn't a big deal, +// because while opsem only now considers this to be UB, the unsafe code +// guidelines have long recommended against any handling of dangling references. +// +// Before rust-lang/rust#154210, `if let` in closures captured all of `x`, so +// this test did not fail because the closure is never called. +//@normalize-stderr-test: "constructing invalid value of type [^:]+:" -> "constructing invalid value:" + +#![allow(irrefutable_let_patterns)] + +fn main() { + // the inner references are dangling + let x: &(&u32, &u32) = unsafe { + let a = 21; + let b = 37; + let ra = &*&raw const a; + let rb = &*&raw const b; + &(ra, rb) + }; + + //~v ERROR: encountered a dangling reference + let _ = || { + if let &(&_y, _) = x {} + }; +} diff --git a/src/tools/miri/tests/fail/match/closures/if-let-partial-pattern.stderr b/src/tools/miri/tests/fail/match/closures/if-let-partial-pattern.stderr new file mode 100644 index 0000000000000..93f3a00563c39 --- /dev/null +++ b/src/tools/miri/tests/fail/match/closures/if-let-partial-pattern.stderr @@ -0,0 +1,16 @@ +error: Undefined Behavior: constructing invalid value: encountered a dangling reference (use-after-free) + --> tests/fail/match/closures/if-let-partial-pattern.rs:LL:CC + | +LL | let _ = || { + | _____________^ +LL | | if let &(&_y, _) = x {} +LL | | }; + | |_____^ Undefined Behavior occurred here + | + = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior + = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information + +note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace + +error: aborting due to 1 previous error + From 0e87c7665f9d79887ecfdb0108daa859896ec8fe Mon Sep 17 00:00:00 2001 From: Mahdi Ali-Raihan Date: Tue, 4 Aug 2026 03:49:16 -0400 Subject: [PATCH 07/26] Adding diagnostic markers for multiple fs functions --- library/std/src/fs.rs | 24 ++++++++++++++++++++++++ library/std/src/os/unix/fs.rs | 1 + library/std/src/os/wasi/fs.rs | 1 + library/std/src/os/windows/fs.rs | 2 ++ 4 files changed, 28 insertions(+) diff --git a/library/std/src/fs.rs b/library/std/src/fs.rs index 4c5cd0e0c9e6a..e266612c19e74 100644 --- a/library/std/src/fs.rs +++ b/library/std/src/fs.rs @@ -184,6 +184,7 @@ pub enum TryLockError { /// /// [TOCTOU]: self#time-of-check-to-time-of-use-toctou #[unstable(feature = "dirfd", issue = "120426")] +#[cfg_attr(not(test), rustc_diagnostic_item = "FsDir")] pub struct Dir { inner: fs_imp::Dir, } @@ -196,6 +197,7 @@ pub struct Dir { /// times, etc. #[stable(feature = "rust1", since = "1.0.0")] #[derive(Clone)] +#[cfg_attr(not(test), rustc_diagnostic_item = "FsMetadata")] pub struct Metadata(fs_imp::FileAttr); /// Iterator over the entries in a directory. @@ -213,6 +215,7 @@ pub struct Metadata(fs_imp::FileAttr); /// the next entry from the OS. #[stable(feature = "rust1", since = "1.0.0")] #[derive(Debug)] +#[cfg_attr(not(test), rustc_diagnostic_item = "FsReadDir")] pub struct ReadDir(fs_imp::ReadDir); /// Entries returned by the [`ReadDir`] iterator. @@ -231,6 +234,7 @@ pub struct ReadDir(fs_imp::ReadDir); /// /// [changes]: io#platform-specific-behavior #[stable(feature = "rust1", since = "1.0.0")] +#[cfg_attr(not(test), rustc_diagnostic_item = "FsDirEntry")] pub struct DirEntry(fs_imp::DirEntry); /// Options and flags which can be used to configure how a file is opened. @@ -337,6 +341,7 @@ pub struct DirBuilder { /// } /// ``` #[stable(feature = "fs_read_write_bytes", since = "1.26.0")] +#[cfg_attr(not(test), rustc_diagnostic_item = "fs_read")] pub fn read>(path: P) -> io::Result> { fn inner(path: &Path) -> io::Result> { let mut file = File::open(path)?; @@ -379,6 +384,7 @@ pub fn read>(path: P) -> io::Result> { /// } /// ``` #[stable(feature = "fs_read_write", since = "1.26.0")] +#[cfg_attr(not(test), rustc_diagnostic_item = "fs_read_to_string")] pub fn read_to_string>(path: P) -> io::Result { fn inner(path: &Path) -> io::Result { let mut file = File::open(path)?; @@ -416,6 +422,7 @@ pub fn read_to_string>(path: P) -> io::Result { /// } /// ``` #[stable(feature = "fs_read_write_bytes", since = "1.26.0")] +#[cfg_attr(not(test), rustc_diagnostic_item = "fs_write")] pub fn write, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result<()> { fn inner(path: &Path, contents: &[u8]) -> io::Result<()> { File::create(path)?.write_all(contents) @@ -459,6 +466,7 @@ pub fn write, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result #[doc(alias = "utimens")] #[doc(alias = "utimes")] #[doc(alias = "utime")] +#[cfg_attr(not(test), rustc_diagnostic_item = "fs_set_times")] pub fn set_times>(path: P, times: FileTimes) -> io::Result<()> { fs_imp::set_times(path.as_ref(), times.0) } @@ -500,6 +508,7 @@ pub fn set_times>(path: P, times: FileTimes) -> io::Result<()> { #[doc(alias = "utimensat")] #[doc(alias = "lutimens")] #[doc(alias = "lutimes")] +#[cfg_attr(not(test), rustc_diagnostic_item = "fs_set_times_nofollow")] pub fn set_times_nofollow>(path: P, times: FileTimes) -> io::Result<()> { fs_imp::set_times_nofollow(path.as_ref(), times.0) } @@ -2761,6 +2770,7 @@ impl AsInner for DirEntry { /// ``` #[doc(alias = "rm", alias = "unlink", alias = "DeleteFile")] #[stable(feature = "rust1", since = "1.0.0")] +#[cfg_attr(not(test), rustc_diagnostic_item = "fs_remove_file")] pub fn remove_file>(path: P) -> io::Result<()> { fs_imp::remove_file(path.as_ref()) } @@ -2802,6 +2812,7 @@ pub fn remove_file>(path: P) -> io::Result<()> { /// ``` #[doc(alias = "stat")] #[stable(feature = "rust1", since = "1.0.0")] +#[cfg_attr(not(test), rustc_diagnostic_item = "fs_metadata")] pub fn metadata>(path: P) -> io::Result { fs_imp::metadata(path.as_ref()).map(Metadata) } @@ -2842,6 +2853,7 @@ pub fn metadata>(path: P) -> io::Result { /// ``` #[doc(alias = "lstat")] #[stable(feature = "symlink_metadata", since = "1.1.0")] +#[cfg_attr(not(test), rustc_diagnostic_item = "fs_symlink_metadata")] pub fn symlink_metadata>(path: P) -> io::Result { fs_imp::symlink_metadata(path.as_ref()).map(Metadata) } @@ -2890,6 +2902,7 @@ pub fn symlink_metadata>(path: P) -> io::Result { /// ``` #[doc(alias = "mv", alias = "MoveFile", alias = "MoveFileEx")] #[stable(feature = "rust1", since = "1.0.0")] +#[cfg_attr(not(test), rustc_diagnostic_item = "fs_rename")] pub fn rename, Q: AsRef>(from: P, to: Q) -> io::Result<()> { fs_imp::rename(from.as_ref(), to.as_ref()) } @@ -2953,6 +2966,7 @@ pub fn rename, Q: AsRef>(from: P, to: Q) -> io::Result<()> #[doc(alias = "CopyFile", alias = "CopyFileEx")] #[doc(alias = "fclonefileat", alias = "fcopyfile")] #[stable(feature = "rust1", since = "1.0.0")] +#[cfg_attr(not(test), rustc_diagnostic_item = "fs_copy")] pub fn copy, Q: AsRef>(from: P, to: Q) -> io::Result { fs_imp::copy(from.as_ref(), to.as_ref()) } @@ -2999,6 +3013,7 @@ pub fn copy, Q: AsRef>(from: P, to: Q) -> io::Result { /// ``` #[doc(alias = "CreateHardLink", alias = "linkat")] #[stable(feature = "rust1", since = "1.0.0")] +#[cfg_attr(not(test), rustc_diagnostic_item = "fs_hard_link")] pub fn hard_link, Q: AsRef>(original: P, link: Q) -> io::Result<()> { fs_imp::hard_link(original.as_ref(), link.as_ref()) } @@ -3065,6 +3080,7 @@ pub fn soft_link, Q: AsRef>(original: P, link: Q) -> io::Re /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] +#[cfg_attr(not(test), rustc_diagnostic_item = "fs_read_link")] pub fn read_link>(path: P) -> io::Result { fs_imp::read_link(path.as_ref()) } @@ -3108,6 +3124,7 @@ pub fn read_link>(path: P) -> io::Result { #[doc(alias = "realpath")] #[doc(alias = "GetFinalPathNameByHandle")] #[stable(feature = "fs_canonicalize", since = "1.5.0")] +#[cfg_attr(not(test), rustc_diagnostic_item = "fs_canonicalize")] pub fn canonicalize>(path: P) -> io::Result { fs_imp::canonicalize(path.as_ref()) } @@ -3196,6 +3213,7 @@ pub fn create_dir>(path: P) -> io::Result<()> { /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] +#[cfg_attr(not(test), rustc_diagnostic_item = "fs_create_dir_all")] pub fn create_dir_all>(path: P) -> io::Result<()> { DirBuilder::new().recursive(true).create(path.as_ref()) } @@ -3241,6 +3259,7 @@ pub fn create_dir_all>(path: P) -> io::Result<()> { /// ``` #[doc(alias = "rmdir", alias = "RemoveDirectory")] #[stable(feature = "rust1", since = "1.0.0")] +#[cfg_attr(not(test), rustc_diagnostic_item = "fs_remove_dir")] pub fn remove_dir>(path: P) -> io::Result<()> { fs_imp::remove_dir(path.as_ref()) } @@ -3305,6 +3324,7 @@ pub fn remove_dir>(path: P) -> io::Result<()> { /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] +#[cfg_attr(not(test), rustc_diagnostic_item = "fs_remove_dir_all")] pub fn remove_dir_all>(path: P) -> io::Result<()> { fs_imp::remove_dir_all(path.as_ref()) } @@ -3384,6 +3404,7 @@ pub fn remove_dir_all>(path: P) -> io::Result<()> { /// ``` #[doc(alias = "ls", alias = "opendir", alias = "FindFirstFile", alias = "FindNextFile")] #[stable(feature = "rust1", since = "1.0.0")] +#[cfg_attr(not(test), rustc_diagnostic_item = "fs_read_dir")] pub fn read_dir>(path: P) -> io::Result { fs_imp::read_dir(path.as_ref()).map(ReadDir) } @@ -3435,6 +3456,7 @@ pub fn read_dir>(path: P) -> io::Result { /// ``` #[doc(alias = "chmod", alias = "SetFileAttributes")] #[stable(feature = "set_permissions", since = "1.1.0")] +#[cfg_attr(not(test), rustc_diagnostic_item = "fs_set_permissions")] pub fn set_permissions>(path: P, perm: Permissions) -> io::Result<()> { fs_imp::set_permissions(path.as_ref(), perm.0) } @@ -3496,6 +3518,7 @@ pub fn set_permissions>(path: P, perm: Permissions) -> io::Result /// ``` #[doc(alias = "fchmodat", alias = "SetFileInformationByHandle")] #[unstable(feature = "set_permissions_nofollow", issue = "141607")] +#[cfg_attr(not(test), rustc_diagnostic_item = "fs_set_permissions_nofollow")] pub fn set_permissions_nofollow>(path: P, perm: Permissions) -> io::Result<()> { fs_imp::set_permissions_nofollow(path.as_ref(), perm.0) } @@ -3643,6 +3666,7 @@ impl AsInnerMut for DirBuilder { /// [`Path::exists`]: crate::path::Path::exists /// [TOCTOU]: self#time-of-check-to-time-of-use-toctou #[stable(feature = "fs_try_exists", since = "1.81.0")] +#[cfg_attr(not(test), rustc_diagnostic_item = "fs_exists")] #[inline] pub fn exists>(path: P) -> io::Result { fs_imp::exists(path.as_ref()) diff --git a/library/std/src/os/unix/fs.rs b/library/std/src/os/unix/fs.rs index c119912c3b022..2d2e782c0671a 100644 --- a/library/std/src/os/unix/fs.rs +++ b/library/std/src/os/unix/fs.rs @@ -1060,6 +1060,7 @@ impl DirEntryExt2 for fs::DirEntry { /// } /// ``` #[stable(feature = "symlink", since = "1.1.0")] +#[cfg_attr(not(test), rustc_diagnostic_item = "fs_symlink")] pub fn symlink, Q: AsRef>(original: P, link: Q) -> io::Result<()> { sys::fs::symlink(original.as_ref(), link.as_ref()) } diff --git a/library/std/src/os/wasi/fs.rs b/library/std/src/os/wasi/fs.rs index fc9e6c925f0bd..369e5d4b0fb9d 100644 --- a/library/std/src/os/wasi/fs.rs +++ b/library/std/src/os/wasi/fs.rs @@ -451,6 +451,7 @@ pub fn symlink, U: AsRef>( /// /// This is a convenience API similar to `std::os::unix::fs::symlink` and /// `std::os::windows::fs::symlink_file` and `std::os::windows::fs::symlink_dir`. +#[cfg_attr(not(test), rustc_diagnostic_item = "fs_symlink_path")] pub fn symlink_path, U: AsRef>(old_path: P, new_path: U) -> io::Result<()> { crate::sys::fs::symlink(old_path.as_ref(), new_path.as_ref()) } diff --git a/library/std/src/os/windows/fs.rs b/library/std/src/os/windows/fs.rs index dfa9236a7e428..7d8602762530a 100644 --- a/library/std/src/os/windows/fs.rs +++ b/library/std/src/os/windows/fs.rs @@ -719,6 +719,7 @@ impl FileTimesExt for fs::FileTimes { /// /// [symlink-security]: https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/create-symbolic-links #[stable(feature = "symlink", since = "1.1.0")] +#[cfg_attr(not(test), rustc_diagnostic_item = "fs_symlink_file")] pub fn symlink_file, Q: AsRef>(original: P, link: Q) -> io::Result<()> { sys::fs::symlink_inner(original.as_ref(), link.as_ref(), false) } @@ -758,6 +759,7 @@ pub fn symlink_file, Q: AsRef>(original: P, link: Q) -> io: /// /// [symlink-security]: https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/create-symbolic-links #[stable(feature = "symlink", since = "1.1.0")] +#[cfg_attr(not(test), rustc_diagnostic_item = "fs_symlink_dir")] pub fn symlink_dir, Q: AsRef>(original: P, link: Q) -> io::Result<()> { sys::fs::symlink_inner(original.as_ref(), link.as_ref(), true) } From e6b20c877bb5fc60e7e54a64af6e5789caa64aab Mon Sep 17 00:00:00 2001 From: Omar1H1 Date: Sat, 8 Aug 2026 18:08:59 +0200 Subject: [PATCH 08/26] diagnostics: unify foreign-trait label for ADT and primitive types in orphan check `emit_orphan_check_error` already special-cases non-local types that appear in a foreign trait's own parameter position (as opposed to Self): for Slice, Array, and Tuple, the label reads "this is not defined in the current crate because this is a foreign trait" instead of naming the type. The Adt arm and the primitive/catch-all arm never checked this and always named the type instead, even in the same non-Self position. This produced a confusing diagnostic for impls like impl PartialEq for u32 {} where Rhs defaults to Self (u32), so both the Self label and the Rhs label read `u32` is not defined in the current crate, with the second one visually landing under PartialEq since the defaulted Rhs has no span of its own. Extend the existing is_foreign check to the Adt and catch-all arms so all four cases behave consistently. Addresses #160648 --- .../src/coherence/orphan.rs | 18 ++++-- ...coherence-orphan-foreign-adt-diagnostic.rs | 43 +++++++++++++++ ...rence-orphan-foreign-adt-diagnostic.stderr | 55 +++++++++++++++++++ tests/ui/coherence/coherence-orphan.stderr | 2 +- .../coherence-pair-covered-uncovered-1.stderr | 2 +- .../impl-foreign-for-foreign[foreign].stderr | 6 +- .../impl-foreign[foreign]-for-foreign.stderr | 2 +- ...n[fundemental[foreign]]-for-foreign.stderr | 6 +- ...orphan-check-error-reporting-ty-var.stderr | 2 +- .../const-and-non-const-impl.stderr | 2 +- 10 files changed, 122 insertions(+), 16 deletions(-) create mode 100644 tests/ui/coherence/coherence-orphan-foreign-adt-diagnostic.rs create mode 100644 tests/ui/coherence/coherence-orphan-foreign-adt-diagnostic.stderr diff --git a/compiler/rustc_hir_analysis/src/coherence/orphan.rs b/compiler/rustc_hir_analysis/src/coherence/orphan.rs index 1cf5da0522c2c..88c621047e497 100644 --- a/compiler/rustc_hir_analysis/src/coherence/orphan.rs +++ b/compiler/rustc_hir_analysis/src/coherence/orphan.rs @@ -465,13 +465,21 @@ fn emit_orphan_check_error<'tcx>( }); } ty::Adt(adt_def, _) => { - diag.subdiagnostic(diagnostics::OnlyCurrentTraitsAdt { - span, - name: tcx.def_path_str(adt_def.did()), - }); + if is_foreign { + diag.subdiagnostic(diagnostics::OnlyCurrentTraitsForeign { span }); + } else { + diag.subdiagnostic(diagnostics::OnlyCurrentTraitsAdt { + span, + name: tcx.def_path_str(adt_def.did()), + }); + } } _ => { - diag.subdiagnostic(diagnostics::OnlyCurrentTraitsTy { span, ty }); + if is_foreign { + diag.subdiagnostic(diagnostics::OnlyCurrentTraitsForeign { span }); + } else { + diag.subdiagnostic(diagnostics::OnlyCurrentTraitsTy { span, ty }); + } } } } diff --git a/tests/ui/coherence/coherence-orphan-foreign-adt-diagnostic.rs b/tests/ui/coherence/coherence-orphan-foreign-adt-diagnostic.rs new file mode 100644 index 0000000000000..c027043ce5d45 --- /dev/null +++ b/tests/ui/coherence/coherence-orphan-foreign-adt-diagnostic.rs @@ -0,0 +1,43 @@ +//@ compile-flags: --crate-type=lib + +// Test diagnostic output for E0117 when implementing foreign traits +// with defaulted parameters (like `PartialEq` and `Add`) on foreign types. +// addresses https://github.com/rust-lang/rust/issues/160648 + +use std::ops::Add; + +// Case 1: Foreign trait, foreign type in Self position, defaulted Rhs (PartialEq) +impl PartialEq for Option { + //~^ ERROR only traits defined in the current crate can be implemented for types defined outside of the crate + fn eq(&self, _other: &Self) -> bool { + true + } +} + +// Case 2: Foreign trait, foreign primitive in Self position, defaulted Rhs (Add) +impl Add for u32 { + //~^ ERROR only traits defined in the current crate can be implemented for primitive types + type Output = u32; + fn add(self, _rhs: u32) -> u32 { + self + } +} + +// Case 3: Foreign trait with explicit foreign Rhs type on a foreign Self type +impl PartialEq for Option { + //~^ ERROR only traits defined in the current crate can be implemented for types defined outside of the crate + fn eq(&self, _other: &String) -> bool { + false + } +} + +// Case 4: Foreign trait with explicit foreign array Rhs type on a foreign Self type +// (control case: Array already used the foreign-trait label before this fix, +// via the pre-existing `Slice`/`Array`/`Tuple` arms. included here so that +// behavior is also pinned down as a regression test.) +impl PartialEq<[i32; 3]> for Option { + //~^ ERROR only traits defined in the current crate can be implemented for types defined outside of the crate + fn eq(&self, _other: &[i32; 3]) -> bool { + false + } +} diff --git a/tests/ui/coherence/coherence-orphan-foreign-adt-diagnostic.stderr b/tests/ui/coherence/coherence-orphan-foreign-adt-diagnostic.stderr new file mode 100644 index 0000000000000..65030aefb08ed --- /dev/null +++ b/tests/ui/coherence/coherence-orphan-foreign-adt-diagnostic.stderr @@ -0,0 +1,55 @@ +error[E0117]: only traits defined in the current crate can be implemented for types defined outside of the crate + --> $DIR/coherence-orphan-foreign-adt-diagnostic.rs:10:1 + | +LL | impl PartialEq for Option { + | ^^^^^---------^^^^^----------- + | | | + | | `Option` is not defined in the current crate + | this is not defined in the current crate because this is a foreign trait + | + = note: impl doesn't have any local type before any uncovered type parameters + = note: for more information see https://doc.rust-lang.org/reference/items/implementations.html#orphan-rules + = note: define and implement a trait or new type instead + +error[E0117]: only traits defined in the current crate can be implemented for types defined outside of the crate + --> $DIR/coherence-orphan-foreign-adt-diagnostic.rs:27:1 + | +LL | impl PartialEq for Option { + | ^^^^^-----------------^^^^^----------- + | | | + | | `Option` is not defined in the current crate + | this is not defined in the current crate because this is a foreign trait + | + = note: impl doesn't have any local type before any uncovered type parameters + = note: for more information see https://doc.rust-lang.org/reference/items/implementations.html#orphan-rules + = note: define and implement a trait or new type instead + +error[E0117]: only traits defined in the current crate can be implemented for types defined outside of the crate + --> $DIR/coherence-orphan-foreign-adt-diagnostic.rs:38:1 + | +LL | impl PartialEq<[i32; 3]> for Option { + | ^^^^^-------------------^^^^^----------- + | | | + | | `Option` is not defined in the current crate + | this is not defined in the current crate because this is a foreign trait + | + = note: impl doesn't have any local type before any uncovered type parameters + = note: for more information see https://doc.rust-lang.org/reference/items/implementations.html#orphan-rules + = note: define and implement a trait or new type instead + +error[E0117]: only traits defined in the current crate can be implemented for primitive types + --> $DIR/coherence-orphan-foreign-adt-diagnostic.rs:18:1 + | +LL | impl Add for u32 { + | ^^^^^---^^^^^--- + | | | + | | `u32` is not defined in the current crate + | this is not defined in the current crate because this is a foreign trait + | + = note: impl doesn't have any local type before any uncovered type parameters + = note: for more information see https://doc.rust-lang.org/reference/items/implementations.html#orphan-rules + = note: define and implement a trait or new type instead + +error: aborting due to 4 previous errors + +For more information about this error, try `rustc --explain E0117`. diff --git a/tests/ui/coherence/coherence-orphan.stderr b/tests/ui/coherence/coherence-orphan.stderr index dcf423e24eedb..a8de82e23a98c 100644 --- a/tests/ui/coherence/coherence-orphan.stderr +++ b/tests/ui/coherence/coherence-orphan.stderr @@ -5,7 +5,7 @@ LL | impl TheTrait for isize {} | ^^^^^---------------^^^^^----- | | | | | `isize` is not defined in the current crate - | `usize` is not defined in the current crate + | this is not defined in the current crate because this is a foreign trait | = note: impl doesn't have any local type before any uncovered type parameters = note: for more information see https://doc.rust-lang.org/reference/items/implementations.html#orphan-rules diff --git a/tests/ui/coherence/coherence-pair-covered-uncovered-1.stderr b/tests/ui/coherence/coherence-pair-covered-uncovered-1.stderr index d7890d156cae9..016cd0a4a866a 100644 --- a/tests/ui/coherence/coherence-pair-covered-uncovered-1.stderr +++ b/tests/ui/coherence/coherence-pair-covered-uncovered-1.stderr @@ -5,7 +5,7 @@ LL | impl Remote1>> for i32 { } | ^^^^^^^^^^^--------------------------^^^^^--- | | | | | `i32` is not defined in the current crate - | `Pair` is not defined in the current crate + | this is not defined in the current crate because this is a foreign trait | = note: impl doesn't have any local type before any uncovered type parameters = note: for more information see https://doc.rust-lang.org/reference/items/implementations.html#orphan-rules diff --git a/tests/ui/coherence/impl-foreign-for-foreign[foreign].stderr b/tests/ui/coherence/impl-foreign-for-foreign[foreign].stderr index ce5376f98cb72..8f64d8ae1b2fd 100644 --- a/tests/ui/coherence/impl-foreign-for-foreign[foreign].stderr +++ b/tests/ui/coherence/impl-foreign-for-foreign[foreign].stderr @@ -5,7 +5,7 @@ LL | impl Remote1> for i32 { | ^^^^^----------------^^^^^--- | | | | | `i32` is not defined in the current crate - | `Rc` is not defined in the current crate + | this is not defined in the current crate because this is a foreign trait | = note: impl doesn't have any local type before any uncovered type parameters = note: for more information see https://doc.rust-lang.org/reference/items/implementations.html#orphan-rules @@ -18,7 +18,7 @@ LL | impl Remote1> for f64 { | ^^^^^------------------^^^^^--- | | | | | `f64` is not defined in the current crate - | `Rc` is not defined in the current crate + | this is not defined in the current crate because this is a foreign trait | = note: impl doesn't have any local type before any uncovered type parameters = note: for more information see https://doc.rust-lang.org/reference/items/implementations.html#orphan-rules @@ -31,7 +31,7 @@ LL | impl Remote1> for f32 { | ^^^^^^^^--------------^^^^^--- | | | | | `f32` is not defined in the current crate - | `Rc` is not defined in the current crate + | this is not defined in the current crate because this is a foreign trait | = note: impl doesn't have any local type before any uncovered type parameters = note: for more information see https://doc.rust-lang.org/reference/items/implementations.html#orphan-rules diff --git a/tests/ui/coherence/impl-foreign[foreign]-for-foreign.stderr b/tests/ui/coherence/impl-foreign[foreign]-for-foreign.stderr index d9dd2b8a8c625..0d84c643fca0e 100644 --- a/tests/ui/coherence/impl-foreign[foreign]-for-foreign.stderr +++ b/tests/ui/coherence/impl-foreign[foreign]-for-foreign.stderr @@ -5,7 +5,7 @@ LL | impl Remote1 for f64 { | ^^^^^------------^^^^^--- | | | | | `f64` is not defined in the current crate - | `u32` is not defined in the current crate + | this is not defined in the current crate because this is a foreign trait | = note: impl doesn't have any local type before any uncovered type parameters = note: for more information see https://doc.rust-lang.org/reference/items/implementations.html#orphan-rules diff --git a/tests/ui/coherence/impl-foreign[fundemental[foreign]]-for-foreign.stderr b/tests/ui/coherence/impl-foreign[fundemental[foreign]]-for-foreign.stderr index af661faa4ea50..cdc686ad09707 100644 --- a/tests/ui/coherence/impl-foreign[fundemental[foreign]]-for-foreign.stderr +++ b/tests/ui/coherence/impl-foreign[fundemental[foreign]]-for-foreign.stderr @@ -5,7 +5,7 @@ LL | impl Remote1> for i32 { | ^^^^^--------------------^^^^^--- | | | | | `i32` is not defined in the current crate - | `String` is not defined in the current crate + | this is not defined in the current crate because this is a foreign trait | = note: impl doesn't have any local type before any uncovered type parameters = note: for more information see https://doc.rust-lang.org/reference/items/implementations.html#orphan-rules @@ -18,7 +18,7 @@ LL | impl Remote1>> for f64 { | ^^^^^---------------------^^^^^--- | | | | | `f64` is not defined in the current crate - | `Rc` is not defined in the current crate + | this is not defined in the current crate because this is a foreign trait | = note: impl doesn't have any local type before any uncovered type parameters = note: for more information see https://doc.rust-lang.org/reference/items/implementations.html#orphan-rules @@ -31,7 +31,7 @@ LL | impl Remote1>> for f32 { | ^^^^^^^^-------------------^^^^^--- | | | | | `f32` is not defined in the current crate - | `Rc` is not defined in the current crate + | this is not defined in the current crate because this is a foreign trait | = note: impl doesn't have any local type before any uncovered type parameters = note: for more information see https://doc.rust-lang.org/reference/items/implementations.html#orphan-rules diff --git a/tests/ui/coherence/orphan-check-error-reporting-ty-var.stderr b/tests/ui/coherence/orphan-check-error-reporting-ty-var.stderr index f229f8b2e385e..113632c0eecbc 100644 --- a/tests/ui/coherence/orphan-check-error-reporting-ty-var.stderr +++ b/tests/ui/coherence/orphan-check-error-reporting-ty-var.stderr @@ -5,7 +5,7 @@ LL | impl From> for as MyTrait>::Item {} | ^^^^^^^^^-------------^^^^^-------------------------- | | | | | `Vec` is not defined in the current crate - | `Vec` is not defined in the current crate + | this is not defined in the current crate because this is a foreign trait | = note: impl doesn't have any local type before any uncovered type parameters = note: for more information see https://doc.rust-lang.org/reference/items/implementations.html#orphan-rules diff --git a/tests/ui/traits/const-traits/const-and-non-const-impl.stderr b/tests/ui/traits/const-traits/const-and-non-const-impl.stderr index 71bcad0e2bf4d..d4cde4ede8b7c 100644 --- a/tests/ui/traits/const-traits/const-and-non-const-impl.stderr +++ b/tests/ui/traits/const-traits/const-and-non-const-impl.stderr @@ -14,7 +14,7 @@ LL | const impl std::ops::Add for i32 { | ^^^^^^^^^^^-------------^^^^^--- | | | | | `i32` is not defined in the current crate - | `i32` is not defined in the current crate + | this is not defined in the current crate because this is a foreign trait | = note: impl doesn't have any local type before any uncovered type parameters = note: for more information see https://doc.rust-lang.org/reference/items/implementations.html#orphan-rules From f3381d223795afbb4d5818331085471a1420a432 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Mon, 17 Aug 2026 17:58:27 +1000 Subject: [PATCH 09/26] Allow `Subcommand::Fix` to have fields --- src/bootstrap/src/core/build_steps/check.rs | 3 +-- src/bootstrap/src/core/builder/mod.rs | 2 +- src/bootstrap/src/core/config/config.rs | 7 +++---- src/bootstrap/src/core/config/flags.rs | 6 ++++-- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/check.rs b/src/bootstrap/src/core/build_steps/check.rs index b8918ec12fd9f..265999711eb87 100644 --- a/src/bootstrap/src/core/build_steps/check.rs +++ b/src/bootstrap/src/core/build_steps/check.rs @@ -20,7 +20,6 @@ use crate::core::builder::{ }; use crate::core::compiler::Compiler; use crate::core::config::TargetSelection; -use crate::core::config::flags::Subcommand; use crate::utils::build_stamp::{self, BuildStamp}; use crate::utils::helpers::t; @@ -113,7 +112,7 @@ impl CommandLineStep for Std { ); std_cargo(builder, target, &mut cargo, &self.crates); - if matches!(builder.config.cmd, Subcommand::Fix) { + if matches!(builder.kind, Kind::Fix) { // By default, cargo tries to fix all targets. Tell it not to fix tests until we've added `test` to the sysroot. cargo.arg("--lib"); } diff --git a/src/bootstrap/src/core/builder/mod.rs b/src/bootstrap/src/core/builder/mod.rs index 6871dea3e80e8..9bd865924635b 100644 --- a/src/bootstrap/src/core/builder/mod.rs +++ b/src/bootstrap/src/core/builder/mod.rs @@ -1077,7 +1077,7 @@ impl<'a> Builder<'a> { Subcommand::Build { .. } => (Kind::Build, &paths[..]), Subcommand::Check { .. } => (Kind::Check, &paths[..]), Subcommand::Clippy { .. } => (Kind::Clippy, &paths[..]), - Subcommand::Fix => (Kind::Fix, &paths[..]), + Subcommand::Fix { .. } => (Kind::Fix, &paths[..]), Subcommand::Doc { .. } => (Kind::Doc, &paths[..]), Subcommand::Test { .. } => (Kind::Test, &paths[..]), Subcommand::Miri { .. } => (Kind::Miri, &paths[..]), diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 071515ea78f1e..6e86283b6d97f 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -1189,8 +1189,7 @@ impl Config { let download_rustc = download_rustc_commit.is_some(); let stage = match flags_cmd { - Subcommand::Check { .. } => flags_stage.or(build_check_stage).unwrap_or(1), - Subcommand::Clippy { .. } | Subcommand::Fix => { + Subcommand::Check { .. } | Subcommand::Clippy { .. } | Subcommand::Fix { .. } => { flags_stage.or(build_check_stage).unwrap_or(1) } // `download-rustc` only has a speed-up for stage2 builds. Default to stage2 unless explicitly overridden. @@ -1263,7 +1262,7 @@ impl Config { helpers::exit_process(1); } - if matches!(flags_cmd, Subcommand::Fix) { + if matches!(flags_cmd, Subcommand::Fix { .. }) { eprintln!( "WARNING: `x fix` is provided on a best-effort basis and does not support all `cargo fix` options correctly." ); @@ -1289,7 +1288,7 @@ NOTE: Please add `--stage 2` to your command line, or if you're sure you want to Subcommand::Clean { .. } | Subcommand::Check { .. } | Subcommand::Clippy { .. } - | Subcommand::Fix + | Subcommand::Fix { .. } | Subcommand::Run { .. } | Subcommand::Setup { .. } | Subcommand::Format { .. } diff --git a/src/bootstrap/src/core/config/flags.rs b/src/bootstrap/src/core/config/flags.rs index c8dbf8d4c4edf..5a0358e360189 100644 --- a/src/bootstrap/src/core/config/flags.rs +++ b/src/bootstrap/src/core/config/flags.rs @@ -313,6 +313,7 @@ pub enum Subcommand { #[arg(global = true, short = 'F', action = clap::ArgAction::Append, value_name = "LINT")] forbid: Vec, }, + /// Run cargo fix #[command(long_about = "\n Arguments: @@ -320,7 +321,9 @@ pub enum Subcommand { and/or artifacts to run `cargo fix` against. For example: ./x.py fix library/core ./x.py fix library/core library/proc_macro")] - Fix, + Fix {}, + + /// Run rustfmt #[command( name = "fmt", long_about = "\n @@ -330,7 +333,6 @@ pub enum Subcommand { ./x.py fmt ./x.py fmt --check" )] - /// Run rustfmt Format { /// check formatting instead of applying #[arg(long)] From e9963a8be7b0b0882ff8d3c07b2919d70be52c07 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Mon, 17 Aug 2026 18:04:01 +1000 Subject: [PATCH 10/26] Allow `./x fix --allow-dirty` This was already possible via `./x fix -- --allow-dirty`, but forwarding the argument from bootstrap is more user-friendly. --- src/bootstrap/src/core/builder/cargo.rs | 10 +++++++++- src/bootstrap/src/core/config/flags.rs | 7 ++++++- src/etc/completions/x.fish | 1 + src/etc/completions/x.ps1 | 1 + src/etc/completions/x.py.fish | 1 + src/etc/completions/x.py.ps1 | 1 + src/etc/completions/x.py.sh | 2 +- src/etc/completions/x.py.zsh | 1 + src/etc/completions/x.sh | 2 +- src/etc/completions/x.zsh | 1 + 10 files changed, 23 insertions(+), 4 deletions(-) diff --git a/src/bootstrap/src/core/builder/cargo.rs b/src/bootstrap/src/core/builder/cargo.rs index 7bd7c261f8067..e70a718b26fe4 100644 --- a/src/bootstrap/src/core/builder/cargo.rs +++ b/src/bootstrap/src/core/builder/cargo.rs @@ -8,7 +8,7 @@ use crate::core::build_steps::llvm::prebuilt_llvm_output; use crate::core::build_steps::test; use crate::core::build_steps::tool::SourceType; use crate::core::compiler::Compiler; -use crate::core::config::flags::Color; +use crate::core::config::flags::{Color, Subcommand}; use crate::core::config::toml::pgo::PgoConfig; use crate::core::config::{CompressDebuginfo, Config, DryRun, SplitDebuginfo, TargetSelection}; use crate::utils::build_stamp; @@ -720,6 +720,14 @@ impl Builder<'_> { } } + // Forward `./x fix --allow-dirty` from bootstrap to cargo. + if matches!(cmd_kind, Kind::Fix) + && let Subcommand::Fix { allow_dirty } = self.config.cmd + && allow_dirty + { + cargo.arg("--allow-dirty"); + } + let build_compiler_stage = if compiler.stage == 0 && self.local_rebuild { // Assume the local-rebuild rustc already has stage1 features. 1 diff --git a/src/bootstrap/src/core/config/flags.rs b/src/bootstrap/src/core/config/flags.rs index 5a0358e360189..56c2541161cec 100644 --- a/src/bootstrap/src/core/config/flags.rs +++ b/src/bootstrap/src/core/config/flags.rs @@ -321,7 +321,12 @@ pub enum Subcommand { and/or artifacts to run `cargo fix` against. For example: ./x.py fix library/core ./x.py fix library/core library/proc_macro")] - Fix {}, + Fix { + /// Pass `--allow-dirty` to `cargo fix`, allowing it to run even if the + /// current git checkout has uncommitted changes. + #[arg(long)] + allow_dirty: bool, + }, /// Run rustfmt #[command( diff --git a/src/etc/completions/x.fish b/src/etc/completions/x.fish index 4d40b28414677..3afa7032b3697 100644 --- a/src/etc/completions/x.fish +++ b/src/etc/completions/x.fish @@ -296,6 +296,7 @@ complete -c x -n "__fish_x_using_subcommand fix" -l llvm-profile-use -d 'use PGO complete -c x -n "__fish_x_using_subcommand fix" -l reproducible-artifact -d 'Additional reproducible artifacts that should be added to the reproducible artifacts archive' -r complete -c x -n "__fish_x_using_subcommand fix" -l set -d 'override options in bootstrap.toml' -r -f complete -c x -n "__fish_x_using_subcommand fix" -l ci -d 'Make bootstrap to behave as it\'s running on the CI environment or not' -r -f -a "{true\t'',false\t''}" +complete -c x -n "__fish_x_using_subcommand fix" -l allow-dirty -d 'Pass `--allow-dirty` to `cargo fix`, allowing it to run even if the current git checkout has uncommitted changes' complete -c x -n "__fish_x_using_subcommand fix" -s v -l verbose -d 'use verbose output (-vv for very verbose)' complete -c x -n "__fish_x_using_subcommand fix" -s q -l quiet -d 'use quiet output' complete -c x -n "__fish_x_using_subcommand fix" -s i -l incremental -d 'use incremental compilation' diff --git a/src/etc/completions/x.ps1 b/src/etc/completions/x.ps1 index f9bebb22b916f..fce6898dd0069 100644 --- a/src/etc/completions/x.ps1 +++ b/src/etc/completions/x.ps1 @@ -342,6 +342,7 @@ Register-ArgumentCompleter -Native -CommandName 'x' -ScriptBlock { [CompletionResult]::new('--reproducible-artifact', '--reproducible-artifact', [CompletionResultType]::ParameterName, 'Additional reproducible artifacts that should be added to the reproducible artifacts archive') [CompletionResult]::new('--set', '--set', [CompletionResultType]::ParameterName, 'override options in bootstrap.toml') [CompletionResult]::new('--ci', '--ci', [CompletionResultType]::ParameterName, 'Make bootstrap to behave as it''s running on the CI environment or not') + [CompletionResult]::new('--allow-dirty', '--allow-dirty', [CompletionResultType]::ParameterName, 'Pass `--allow-dirty` to `cargo fix`, allowing it to run even if the current git checkout has uncommitted changes') [CompletionResult]::new('-v', '-v', [CompletionResultType]::ParameterName, 'use verbose output (-vv for very verbose)') [CompletionResult]::new('--verbose', '--verbose', [CompletionResultType]::ParameterName, 'use verbose output (-vv for very verbose)') [CompletionResult]::new('-q', '-q', [CompletionResultType]::ParameterName, 'use quiet output') diff --git a/src/etc/completions/x.py.fish b/src/etc/completions/x.py.fish index b098de6e7daff..6474cecae92a1 100644 --- a/src/etc/completions/x.py.fish +++ b/src/etc/completions/x.py.fish @@ -296,6 +296,7 @@ complete -c x.py -n "__fish_x.py_using_subcommand fix" -l llvm-profile-use -d 'u complete -c x.py -n "__fish_x.py_using_subcommand fix" -l reproducible-artifact -d 'Additional reproducible artifacts that should be added to the reproducible artifacts archive' -r complete -c x.py -n "__fish_x.py_using_subcommand fix" -l set -d 'override options in bootstrap.toml' -r -f complete -c x.py -n "__fish_x.py_using_subcommand fix" -l ci -d 'Make bootstrap to behave as it\'s running on the CI environment or not' -r -f -a "{true\t'',false\t''}" +complete -c x.py -n "__fish_x.py_using_subcommand fix" -l allow-dirty -d 'Pass `--allow-dirty` to `cargo fix`, allowing it to run even if the current git checkout has uncommitted changes' complete -c x.py -n "__fish_x.py_using_subcommand fix" -s v -l verbose -d 'use verbose output (-vv for very verbose)' complete -c x.py -n "__fish_x.py_using_subcommand fix" -s q -l quiet -d 'use quiet output' complete -c x.py -n "__fish_x.py_using_subcommand fix" -s i -l incremental -d 'use incremental compilation' diff --git a/src/etc/completions/x.py.ps1 b/src/etc/completions/x.py.ps1 index 6c952de7eaac9..e50edbb800ec4 100644 --- a/src/etc/completions/x.py.ps1 +++ b/src/etc/completions/x.py.ps1 @@ -342,6 +342,7 @@ Register-ArgumentCompleter -Native -CommandName 'x.py' -ScriptBlock { [CompletionResult]::new('--reproducible-artifact', '--reproducible-artifact', [CompletionResultType]::ParameterName, 'Additional reproducible artifacts that should be added to the reproducible artifacts archive') [CompletionResult]::new('--set', '--set', [CompletionResultType]::ParameterName, 'override options in bootstrap.toml') [CompletionResult]::new('--ci', '--ci', [CompletionResultType]::ParameterName, 'Make bootstrap to behave as it''s running on the CI environment or not') + [CompletionResult]::new('--allow-dirty', '--allow-dirty', [CompletionResultType]::ParameterName, 'Pass `--allow-dirty` to `cargo fix`, allowing it to run even if the current git checkout has uncommitted changes') [CompletionResult]::new('-v', '-v', [CompletionResultType]::ParameterName, 'use verbose output (-vv for very verbose)') [CompletionResult]::new('--verbose', '--verbose', [CompletionResultType]::ParameterName, 'use verbose output (-vv for very verbose)') [CompletionResult]::new('-q', '-q', [CompletionResultType]::ParameterName, 'use quiet output') diff --git a/src/etc/completions/x.py.sh b/src/etc/completions/x.py.sh index b2542b94b9468..1266f85addd8d 100644 --- a/src/etc/completions/x.py.sh +++ b/src/etc/completions/x.py.sh @@ -2160,7 +2160,7 @@ _x.py() { return 0 ;; x.py__fix) - opts="-v -q -i -j -h --verbose --quiet --incremental --config --build-dir --build --host --target --exclude --skip --include-default-paths --rustc-error-format --on-fail --dry-run --dump-bootstrap-shims --stage --keep-stage --keep-stage-std --src --jobs --warnings --json-output --compile-time-deps --color --bypass-bootstrap-lock --rust-profile-generate --rust-profile-use --llvm-profile-use --llvm-profile-generate --enable-bolt-settings --skip-stage0-validation --reproducible-artifact --set --ci --skip-std-check-if-no-download-rustc --help [PATHS]... [ARGS]..." + opts="-v -q -i -j -h --allow-dirty --verbose --quiet --incremental --config --build-dir --build --host --target --exclude --skip --include-default-paths --rustc-error-format --on-fail --dry-run --dump-bootstrap-shims --stage --keep-stage --keep-stage-std --src --jobs --warnings --json-output --compile-time-deps --color --bypass-bootstrap-lock --rust-profile-generate --rust-profile-use --llvm-profile-use --llvm-profile-generate --enable-bolt-settings --skip-stage0-validation --reproducible-artifact --set --ci --skip-std-check-if-no-download-rustc --help [PATHS]... [ARGS]..." if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") ) return 0 diff --git a/src/etc/completions/x.py.zsh b/src/etc/completions/x.py.zsh index 5199c6cbaf350..57c8080fa369f 100644 --- a/src/etc/completions/x.py.zsh +++ b/src/etc/completions/x.py.zsh @@ -335,6 +335,7 @@ _arguments "${_arguments_options[@]}" : \ '*--reproducible-artifact=[Additional reproducible artifacts that should be added to the reproducible artifacts archive]:REPRODUCIBLE_ARTIFACT:_default' \ '*--set=[override options in bootstrap.toml]:section.option=value:' \ '--ci=[Make bootstrap to behave as it'\''s running on the CI environment or not]:bool:(true false)' \ +'--allow-dirty[Pass \`--allow-dirty\` to \`cargo fix\`, allowing it to run even if the current git checkout has uncommitted changes]' \ '(-q --quiet)*-v[use verbose output (-vv for very verbose)]' \ '(-q --quiet)*--verbose[use verbose output (-vv for very verbose)]' \ '(-v --verbose)-q[use quiet output]' \ diff --git a/src/etc/completions/x.sh b/src/etc/completions/x.sh index 5740459a414d2..644c656514f6c 100644 --- a/src/etc/completions/x.sh +++ b/src/etc/completions/x.sh @@ -2160,7 +2160,7 @@ _x() { return 0 ;; x__fix) - opts="-v -q -i -j -h --verbose --quiet --incremental --config --build-dir --build --host --target --exclude --skip --include-default-paths --rustc-error-format --on-fail --dry-run --dump-bootstrap-shims --stage --keep-stage --keep-stage-std --src --jobs --warnings --json-output --compile-time-deps --color --bypass-bootstrap-lock --rust-profile-generate --rust-profile-use --llvm-profile-use --llvm-profile-generate --enable-bolt-settings --skip-stage0-validation --reproducible-artifact --set --ci --skip-std-check-if-no-download-rustc --help [PATHS]... [ARGS]..." + opts="-v -q -i -j -h --allow-dirty --verbose --quiet --incremental --config --build-dir --build --host --target --exclude --skip --include-default-paths --rustc-error-format --on-fail --dry-run --dump-bootstrap-shims --stage --keep-stage --keep-stage-std --src --jobs --warnings --json-output --compile-time-deps --color --bypass-bootstrap-lock --rust-profile-generate --rust-profile-use --llvm-profile-use --llvm-profile-generate --enable-bolt-settings --skip-stage0-validation --reproducible-artifact --set --ci --skip-std-check-if-no-download-rustc --help [PATHS]... [ARGS]..." if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") ) return 0 diff --git a/src/etc/completions/x.zsh b/src/etc/completions/x.zsh index 31d9e43ef8e89..66d41a91118f3 100644 --- a/src/etc/completions/x.zsh +++ b/src/etc/completions/x.zsh @@ -335,6 +335,7 @@ _arguments "${_arguments_options[@]}" : \ '*--reproducible-artifact=[Additional reproducible artifacts that should be added to the reproducible artifacts archive]:REPRODUCIBLE_ARTIFACT:_default' \ '*--set=[override options in bootstrap.toml]:section.option=value:' \ '--ci=[Make bootstrap to behave as it'\''s running on the CI environment or not]:bool:(true false)' \ +'--allow-dirty[Pass \`--allow-dirty\` to \`cargo fix\`, allowing it to run even if the current git checkout has uncommitted changes]' \ '(-q --quiet)*-v[use verbose output (-vv for very verbose)]' \ '(-q --quiet)*--verbose[use verbose output (-vv for very verbose)]' \ '(-v --verbose)-q[use quiet output]' \ From 5898a3974ab889e372fcab8d6cbedd0a3cb66e22 Mon Sep 17 00:00:00 2001 From: carbotaniuman <41451839+carbotaniuman@users.noreply.github.com> Date: Mon, 17 Aug 2026 20:19:59 -0500 Subject: [PATCH 11/26] Initial implementation of `FnPtr` trait This commit is an initial implementation of the `FnPtr` trait as described in the `fn_static` tracking issue, which consists of moving the internally unstable `core::marker::FnPtr` to `core::ops::FnPtr`, as well as changing the API. Because `NonNull` is used in the new `as_ptr` signature, it was also turned into a proper lang item. --- compiler/rustc_attr_ir/src/lang_items.rs | 7 +- .../src/attributes/rustc_internal.rs | 6 +- .../rustc_const_eval/src/interpret/call.rs | 3 +- compiler/rustc_feature/src/unstable.rs | 2 + .../rustc_hir_analysis/src/check/wfcheck.rs | 24 +++-- compiler/rustc_lint/src/types.rs | 2 +- compiler/rustc_middle/src/mir/visit.rs | 3 +- compiler/rustc_middle/src/mono.rs | 3 +- compiler/rustc_middle/src/ty/instance.rs | 22 +++-- compiler/rustc_middle/src/ty/print/mod.rs | 3 +- compiler/rustc_mir_transform/src/inline.rs | 3 +- .../rustc_mir_transform/src/inline/cycle.rs | 2 +- compiler/rustc_mir_transform/src/shim.rs | 89 +++++++++++++++---- compiler/rustc_monomorphize/src/collector.rs | 3 +- .../rustc_monomorphize/src/partitioning.rs | 6 +- compiler/rustc_span/src/symbol.rs | 7 +- compiler/rustc_ty_utils/src/diagnostics.rs | 7 -- compiler/rustc_ty_utils/src/instance.rs | 26 +++--- library/core/src/marker.rs | 19 ---- library/core/src/ops/function.rs | 39 +++++++- library/core/src/ops/mod.rs | 2 + library/core/src/ptr/mod.rs | 9 +- library/core/src/ptr/non_null.rs | 2 +- library/std/src/lib.rs | 2 +- library/std/src/sys/pal/unix/weak/dlsym.rs | 3 +- .../clippy_lints/src/methods/zst_offset.rs | 4 +- .../src/non_send_fields_in_send_ty.rs | 3 +- .../src/nonnull_unchecked_on_box_ptr.rs | 2 +- .../clippy_lints/src/volatile_composites.rs | 3 +- .../crates/hir-def/src/lang_item.rs | 5 +- .../crates/intern/src/symbol/symbols.rs | 5 +- .../feature-gates/feature-gate-fn_static.rs | 4 + .../feature-gate-fn_static.stderr | 13 +++ tests/ui/fn/fn-ptr-trait-run.rs | 15 ++++ tests/ui/fn/fn-ptr-trait.rs | 4 +- .../dont-pick-fnptr-bound-as-leaf.rs | 4 +- 36 files changed, 255 insertions(+), 101 deletions(-) create mode 100644 tests/ui/feature-gates/feature-gate-fn_static.rs create mode 100644 tests/ui/feature-gates/feature-gate-fn_static.stderr create mode 100644 tests/ui/fn/fn-ptr-trait-run.rs diff --git a/compiler/rustc_attr_ir/src/lang_items.rs b/compiler/rustc_attr_ir/src/lang_items.rs index e45621689558e..fe631b5ea9859 100644 --- a/compiler/rustc_attr_ir/src/lang_items.rs +++ b/compiler/rustc_attr_ir/src/lang_items.rs @@ -180,11 +180,15 @@ language_item_table! { Metadata, sym::metadata_type, metadata_type, Target::AssocTy, GenericRequirement::None; DynMetadata, sym::dyn_metadata, dyn_metadata, Target::Struct, GenericRequirement::None; + NonNull, sym::non_null, non_null_trait, Target::Struct, GenericRequirement::Exact(1); + Freeze, sym::freeze, freeze_trait, Target::Trait, GenericRequirement::Exact(0); UnsafeUnpin, sym::unsafe_unpin, unsafe_unpin_trait, Target::Trait, GenericRequirement::Exact(0); FnPtrTrait, sym::fn_ptr_trait, fn_ptr_trait, Target::Trait, GenericRequirement::Exact(0); - FnPtrAddr, sym::fn_ptr_addr, fn_ptr_addr, Target::Method(MethodKind::Trait { body: false }), GenericRequirement::None; + FnPtrAsPtr, sym::fn_ptr_as_ptr, fn_ptr_as_ptr, Target::Method(MethodKind::Trait { body: false }), GenericRequirement::None; + FnPtrFromPtr, sym::fn_ptr_from_ptr, fn_ptr_from_ptr, Target::Method(MethodKind::Trait { body: false }), GenericRequirement::None; + Code, sym::code, code, Target::ForeignTy, GenericRequirement::None; Drop, sym::drop, drop_trait, Target::Trait, GenericRequirement::None; Destruct, sym::destruct, destruct_trait, Target::Trait, GenericRequirement::None; @@ -245,6 +249,7 @@ language_item_table! { Fn, kw::Fn, fn_trait, Target::Trait, GenericRequirement::Exact(1); FnMut, sym::fn_mut, fn_mut_trait, Target::Trait, GenericRequirement::Exact(1); FnOnce, sym::fn_once, fn_once_trait, Target::Trait, GenericRequirement::Exact(1); + FnStatic, sym::fn_static, fn_static_trait, Target::Trait, GenericRequirement::Exact(1); AsyncFn, sym::async_fn, async_fn_trait, Target::Trait, GenericRequirement::Exact(1); AsyncFnMut, sym::async_fn_mut, async_fn_mut_trait, Target::Trait, GenericRequirement::Exact(1); diff --git a/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs b/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs index 94d7d70d07afc..dddd61e9f0ba0 100644 --- a/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs +++ b/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs @@ -607,9 +607,9 @@ impl SingleAttributeParser for LangParser { return None; }; - // Only weak lang items may be applied to foreign items - if [Target::ForeignFn, Target::ForeignStatic, Target::ForeignTy, Target::ForeignMod] - .contains(&cx.target) + // Only weak lang items may be applied to foreign items, + // except for `ForeignTy` which can be a normal lang item. + if [Target::ForeignFn, Target::ForeignStatic, Target::ForeignMod].contains(&cx.target) && !lang_item.is_weak() { cx.emit_err(UnknownExternLangItem { span: cx.attr_span, lang_item: lang_item.name() }); diff --git a/compiler/rustc_const_eval/src/interpret/call.rs b/compiler/rustc_const_eval/src/interpret/call.rs index 3afeb3b9c46a0..bc793fcc7f4e2 100644 --- a/compiler/rustc_const_eval/src/interpret/call.rs +++ b/compiler/rustc_const_eval/src/interpret/call.rs @@ -743,7 +743,8 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { | ty::InstanceKind::Shim(ty::ShimKind::FnPtr(..)) | ty::InstanceKind::Shim(ty::ShimKind::DropGlue(..)) | ty::InstanceKind::Shim(ty::ShimKind::Clone(..)) - | ty::InstanceKind::Shim(ty::ShimKind::FnPtrAddr(..)) + | ty::InstanceKind::Shim(ty::ShimKind::FnPtrAsPtr(..)) + | ty::InstanceKind::Shim(ty::ShimKind::FnPtrFromPtr(..)) | ty::InstanceKind::Shim(ty::ShimKind::ThreadLocal(..)) | ty::InstanceKind::Shim(ty::ShimKind::AsyncDropGlueCtor(..)) | ty::InstanceKind::Shim(ty::ShimKind::AsyncDropGlue(..)) diff --git a/compiler/rustc_feature/src/unstable.rs b/compiler/rustc_feature/src/unstable.rs index 665661f43006e..8ba571df5d5a5 100644 --- a/compiler/rustc_feature/src/unstable.rs +++ b/compiler/rustc_feature/src/unstable.rs @@ -561,6 +561,8 @@ declare_features! ( (unstable, fn_align, "1.53.0", Some(82232)), /// Support delegating implementation of functions to other already implemented functions. (incomplete, fn_delegation, "1.76.0", Some(118212)), + /// Traits for function pointers and items + (unstable, fn_static, "CURRENT_RUSTC_VERSION", Some(148768)), /// Allows impls for the Freeze trait. (internal, freeze_impls, "1.78.0", Some(121675)), /// Frontmatter `---` blocks for use by external tools. diff --git a/compiler/rustc_hir_analysis/src/check/wfcheck.rs b/compiler/rustc_hir_analysis/src/check/wfcheck.rs index 9a498837b1f4d..d1c011d22a6b1 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -1800,14 +1800,22 @@ fn check_method_receiver<'tcx>( { match receiver_validity_err { ReceiverValidityError::DoesNotDeref if arbitrary_self_types_level.is_some() => { - let hint = match receiver_ty - .builtin_deref(false) - .unwrap_or(receiver_ty) - .ty_adt_def() - .and_then(|adt_def| tcx.get_diagnostic_name(adt_def.did())) - { - Some(sym::RcWeak | sym::ArcWeak) => Some(InvalidReceiverTyHint::Weak), - Some(sym::NonNull) => Some(InvalidReceiverTyHint::NonNull), + let adt_def = + receiver_ty.builtin_deref(false).unwrap_or(receiver_ty).ty_adt_def(); + + let hint = match adt_def { + Some(adt) => { + if tcx.is_lang_item(adt.did(), LangItem::NonNull) { + Some(InvalidReceiverTyHint::NonNull) + } else { + match tcx.get_diagnostic_name(adt.did()) { + Some(sym::RcWeak | sym::ArcWeak) => { + Some(InvalidReceiverTyHint::Weak) + } + _ => None, + } + } + } _ => None, }; diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs index 49a14c2676c10..6212cb2253cd0 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -318,7 +318,7 @@ fn lint_wide_pointer<'tcx>( let mut modifiers = String::new(); ty = match ty.kind() { ty::RawPtr(ty, _) => *ty, - ty::Adt(def, args) if cx.tcx.is_diagnostic_item(sym::NonNull, def.did()) => { + ty::Adt(def, args) if cx.tcx.is_lang_item(def.did(), LangItem::NonNull) => { modifiers.push_str(".as_ptr()"); args.type_at(0) } diff --git a/compiler/rustc_middle/src/mir/visit.rs b/compiler/rustc_middle/src/mir/visit.rs index 0ae59e99c2b5a..0fc31c17caaf9 100644 --- a/compiler/rustc_middle/src/mir/visit.rs +++ b/compiler/rustc_middle/src/mir/visit.rs @@ -362,7 +362,8 @@ macro_rules! make_mir_visitor { ty::InstanceKind::Shim(ty::ShimKind::FnPtr(_def_id, ty)) | ty::InstanceKind::Shim(ty::ShimKind::DropGlue(_def_id, Some(ty))) | ty::InstanceKind::Shim(ty::ShimKind::Clone(_def_id, ty)) - | ty::InstanceKind::Shim(ty::ShimKind::FnPtrAddr(_def_id, ty)) + | ty::InstanceKind::Shim(ty::ShimKind::FnPtrAsPtr(_def_id, ty)) + | ty::InstanceKind::Shim(ty::ShimKind::FnPtrFromPtr(_def_id, ty)) | ty::InstanceKind::Shim(ty::ShimKind::AsyncDropGlue(_def_id, ty)) | ty::InstanceKind::Shim(ty::ShimKind::AsyncDropGlueCtor(_def_id, ty)) => { // FIXME(eddyb) use a better `TyContext` here. diff --git a/compiler/rustc_middle/src/mono.rs b/compiler/rustc_middle/src/mono.rs index dc9a94f79aa0f..76828cbee60f1 100644 --- a/compiler/rustc_middle/src/mono.rs +++ b/compiler/rustc_middle/src/mono.rs @@ -548,7 +548,8 @@ impl<'tcx> CodegenUnit<'tcx> { | InstanceKind::Shim(ShimKind::DropGlue(..)) | InstanceKind::Shim(ShimKind::Clone(..)) | InstanceKind::Shim(ShimKind::ThreadLocal(..)) - | InstanceKind::Shim(ShimKind::FnPtrAddr(..)) + | InstanceKind::Shim(ShimKind::FnPtrAsPtr(..)) + | InstanceKind::Shim(ShimKind::FnPtrFromPtr(..)) | InstanceKind::Shim(ShimKind::AsyncDropGlue(..)) | InstanceKind::Shim(ShimKind::FutureDropPoll(..)) | InstanceKind::Shim(ShimKind::AsyncDropGlueCtor(..)) => None, diff --git a/compiler/rustc_middle/src/ty/instance.rs b/compiler/rustc_middle/src/ty/instance.rs index dcd0ee601aa9d..49f930c21afb2 100644 --- a/compiler/rustc_middle/src/ty/instance.rs +++ b/compiler/rustc_middle/src/ty/instance.rs @@ -177,12 +177,19 @@ pub enum ShimKind<'tcx> { /// The `DefId` is for `Clone::clone`, the `Ty` is the type `T` with the builtin `Clone` impl. Clone(DefId, Ty<'tcx>), - /// Compiler-generated `::addr` implementation. + /// Compiler-generated `::as_ptr` implementation. /// /// Automatically generated for all potentially higher-ranked `fn(I) -> R` types. /// - /// The `DefId` is for `FnPtr::addr`, the `Ty` is the type `T`. - FnPtrAddr(DefId, Ty<'tcx>), + /// The `DefId` is for `FnPtr::as_ptr`, the `Ty` is the type `T`. + FnPtrAsPtr(DefId, Ty<'tcx>), + + /// Compiler-generated `::from_ptr` implementation. + /// + /// Automatically generated for all potentially higher-ranked `fn(I) -> R` types. + /// + /// The `DefId` is for `FnPtr::from_ptr`, the `Ty` is the type `T`. + FnPtrFromPtr(DefId, Ty<'tcx>), /// `core::future::async_drop::async_drop_in_place::<'_, T>`. /// @@ -344,7 +351,8 @@ impl<'tcx> ShimKind<'tcx> { } | ShimKind::DropGlue(def_id, _) | ShimKind::Clone(def_id, _) - | ShimKind::FnPtrAddr(def_id, _) + | ShimKind::FnPtrAsPtr(def_id, _) + | ShimKind::FnPtrFromPtr(def_id, _) | ShimKind::FutureDropPoll(def_id, _, _) | ShimKind::AsyncDropGlue(def_id, _) | ShimKind::AsyncDropGlueCtor(def_id, _) => def_id, @@ -366,7 +374,8 @@ impl<'tcx> ShimKind<'tcx> { | ShimKind::ConstructCoroutineInClosure { .. } | ShimKind::DropGlue(..) | ShimKind::Clone(..) - | ShimKind::FnPtrAddr(..) => None, + | ShimKind::FnPtrAsPtr(..) + | ShimKind::FnPtrFromPtr(..) => None, } } @@ -385,8 +394,9 @@ impl<'tcx> ShimKind<'tcx> { match *self { ShimKind::Clone(..) | ShimKind::ThreadLocal(..) - | ShimKind::FnPtrAddr(..) | ShimKind::FnPtr(..) + | ShimKind::FnPtrAsPtr(..) + | ShimKind::FnPtrFromPtr(..) | ShimKind::DropGlue(_, Some(_)) | ShimKind::FutureDropPoll(..) | ShimKind::AsyncDropGlue(_, _) => false, diff --git a/compiler/rustc_middle/src/ty/print/mod.rs b/compiler/rustc_middle/src/ty/print/mod.rs index ccdac57cc8dcd..451a75e52d2d9 100644 --- a/compiler/rustc_middle/src/ty/print/mod.rs +++ b/compiler/rustc_middle/src/ty/print/mod.rs @@ -397,7 +397,8 @@ impl<'tcx, P: Printer<'tcx> + std::fmt::Write> Print

for ty::ShimKind<'tcx> { ty::ShimKind::DropGlue(_, None) => cx.write_str("shim(None)"), ty::ShimKind::DropGlue(_, Some(ty)) => cx.write_str(&format!("shim(Some({ty}))")), ty::ShimKind::Clone(_, ty) => cx.write_str(&format!("shim({ty})")), - ty::ShimKind::FnPtrAddr(_, ty) => cx.write_str(&format!("shim({ty})")), + ty::ShimKind::FnPtrAsPtr(_, ty) => cx.write_str(&format!("shim({ty})")), + ty::ShimKind::FnPtrFromPtr(_, ty) => cx.write_str(&format!("shim({ty})")), ty::ShimKind::FutureDropPoll(_, proxy_ty, impl_ty) => { cx.write_str(&format!("dropshim({proxy_ty}-{impl_ty})")) } diff --git a/compiler/rustc_mir_transform/src/inline.rs b/compiler/rustc_mir_transform/src/inline.rs index 47df95a37a60f..ae20d21ea665f 100644 --- a/compiler/rustc_mir_transform/src/inline.rs +++ b/compiler/rustc_mir_transform/src/inline.rs @@ -765,7 +765,8 @@ fn check_mir_is_available<'tcx, I: Inliner<'tcx>>( | InstanceKind::Shim(ShimKind::DropGlue(..)) | InstanceKind::Shim(ShimKind::Clone(..)) | InstanceKind::Shim(ShimKind::ThreadLocal(..)) - | InstanceKind::Shim(ShimKind::FnPtrAddr(..)) => return Ok(()), + | InstanceKind::Shim(ShimKind::FnPtrAsPtr(..)) + | InstanceKind::Shim(ShimKind::FnPtrFromPtr(..)) => return Ok(()), } if inliner.tcx().is_constructor(callee_def_id) { diff --git a/compiler/rustc_mir_transform/src/inline/cycle.rs b/compiler/rustc_mir_transform/src/inline/cycle.rs index dc9cc38fcb733..b974cb656379d 100644 --- a/compiler/rustc_mir_transform/src/inline/cycle.rs +++ b/compiler/rustc_mir_transform/src/inline/cycle.rs @@ -36,7 +36,7 @@ fn should_recurse<'tcx>(tcx: TyCtxt<'tcx>, callee: ty::Instance<'tcx>) -> bool { | InstanceKind::Shim(ShimKind::Clone(..)) => {} // This shim does not call any other functions, thus there can be no recursion. - InstanceKind::Shim(ShimKind::FnPtrAddr(..)) => return false, + InstanceKind::Shim(ShimKind::FnPtrAsPtr(..) | ShimKind::FnPtrFromPtr(..)) => return false, // FIXME: A not fully instantiated drop shim can cause ICEs if one attempts to // have its MIR built. Likely oli-obk just screwed up the `ParamEnv`s, so this diff --git a/compiler/rustc_mir_transform/src/shim.rs b/compiler/rustc_mir_transform/src/shim.rs index 0561c04bc1db3..426c6cd955fc6 100644 --- a/compiler/rustc_mir_transform/src/shim.rs +++ b/compiler/rustc_mir_transform/src/shim.rs @@ -128,7 +128,8 @@ fn make_shim<'tcx>(tcx: TyCtxt<'tcx>, shim: ty::ShimKind<'tcx>) -> Body<'tcx> { } ty::ShimKind::ThreadLocal(..) => build_thread_local_shim(tcx, shim), ty::ShimKind::Clone(def_id, ty) => build_clone_shim(tcx, def_id, ty), - ty::ShimKind::FnPtrAddr(def_id, ty) => build_fn_ptr_addr_shim(tcx, def_id, ty), + ty::ShimKind::FnPtrAsPtr(def_id, ty) => build_fn_ptr_as_ptr_shim(tcx, def_id, ty), + ty::ShimKind::FnPtrFromPtr(def_id, ty) => build_fn_ptr_from_ptr_shim(tcx, def_id, ty), ty::ShimKind::FutureDropPoll(def_id, proxy_ty, impl_ty) => { let mut body = async_destructor_ctor::build_future_drop_poll_shim(tcx, def_id, proxy_ty, impl_ty); @@ -1080,40 +1081,98 @@ pub(super) fn build_adt_ctor(tcx: TyCtxt<'_>, ctor_id: DefId) -> Body<'_> { /// ```ignore (pseudo-impl) /// impl FnPtr for fn(u32) { -/// fn addr(self) -> usize { -/// self as usize +/// fn addr(self) -> NonNull { +/// unsafe { transmute(self as *const Code)} /// } /// } /// ``` -fn build_fn_ptr_addr_shim<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, self_ty: Ty<'tcx>) -> Body<'tcx> { +fn build_fn_ptr_as_ptr_shim<'tcx>( + tcx: TyCtxt<'tcx>, + def_id: DefId, + self_ty: Ty<'tcx>, +) -> Body<'tcx> { assert_matches!(self_ty.kind(), ty::FnPtr(..), "expected fn ptr, found {self_ty}"); + let span = tcx.def_span(def_id); + let nonnull_did = tcx.require_lang_item(LangItem::NonNull, span); + let code_did = tcx.require_lang_item(LangItem::Code, span); + let nonnull_ty = tcx + .type_of(nonnull_did) + .instantiate( + tcx, + &[ty::GenericArg::from(tcx.type_of(code_did).instantiate_identity().skip_norm_wip())], + ) + .skip_norm_wip(); + let Some(sig) = tcx.fn_sig(def_id).instantiate(tcx, &[self_ty.into()]).skip_norm_wip().no_bound_vars() else { - span_bug!(span, "FnPtr::addr with bound vars for `{self_ty}`"); + span_bug!(span, "FnPtr::as_ptr with bound vars for `{self_ty}`"); }; - let locals = local_decls_for_sig(&sig, span); + let mut locals = local_decls_for_sig(&sig, span); let source_info = SourceInfo::outermost(span); + + let mut statements = vec![]; // FIXME: use `expose_provenance` once we figure out whether function pointers have meaningful // provenance. - let rvalue = Rvalue::Cast( - CastKind::FnPtrToPtr, - Operand::Move(Place::from(Local::arg(0))), - Ty::new_imm_ptr(tcx, tcx.types.unit), - ); - let stmt = Statement::new( + let raw_unit_ptr = Ty::new_imm_ptr(tcx, tcx.types.unit); + let cast_to_raw_rvalue = + Rvalue::Cast(CastKind::FnPtrToPtr, Operand::Move(Place::from(Local::arg(0))), raw_unit_ptr); + let raw_ptr = locals.push(LocalDecl::with_source_info(raw_unit_ptr, source_info)).into(); + statements.push(Statement::new( source_info, - StatementKind::Assign(Box::new((Place::return_place(), rvalue))), + StatementKind::Assign(Box::new((raw_ptr, cast_to_raw_rvalue))), + )); + + let transmute_to_nonnull = + Rvalue::Cast(CastKind::Transmute, Operand::Move(Place::from(raw_ptr)), nonnull_ty); + statements.push(Statement::new( + source_info, + StatementKind::Assign(Box::new((Place::return_place(), transmute_to_nonnull))), + )); + + let start_block = BasicBlockData::new_stmts( + statements, + Some(Terminator { source_info, kind: TerminatorKind::Return, attributes: ThinVec::new() }), + false, ); - let statements = vec![stmt]; + let source = MirSource::from_shim(ty::ShimKind::FnPtrAsPtr(def_id, self_ty)); + new_body(source, IndexVec::from_elem_n(start_block, 1), locals, sig.inputs().len(), span) +} + +fn build_fn_ptr_from_ptr_shim<'tcx>( + tcx: TyCtxt<'tcx>, + def_id: DefId, + self_ty: Ty<'tcx>, +) -> Body<'tcx> { + assert_matches!(self_ty.kind(), ty::FnPtr(..), "expected fn ptr, found {self_ty}"); + + let span = tcx.def_span(def_id); + + let Some(sig) = + tcx.fn_sig(def_id).instantiate(tcx, &[self_ty.into()]).skip_norm_wip().no_bound_vars() + else { + span_bug!(span, "FnPtr::as_ptr with bound vars for `{self_ty}`"); + }; + let locals = local_decls_for_sig(&sig, span); + + let source_info = SourceInfo::outermost(span); + + let mut statements = vec![]; + let transmute_to_self = + Rvalue::Cast(CastKind::Transmute, Operand::Move(Place::from(Local::arg(0))), self_ty); + statements.push(Statement::new( + source_info, + StatementKind::Assign(Box::new((Place::return_place(), transmute_to_self))), + )); + let start_block = BasicBlockData::new_stmts( statements, Some(Terminator { source_info, kind: TerminatorKind::Return, attributes: ThinVec::new() }), false, ); - let source = MirSource::from_shim(ty::ShimKind::FnPtrAddr(def_id, self_ty)); + let source = MirSource::from_shim(ty::ShimKind::FnPtrFromPtr(def_id, self_ty)); new_body(source, IndexVec::from_elem_n(start_block, 1), locals, sig.inputs().len(), span) } diff --git a/compiler/rustc_monomorphize/src/collector.rs b/compiler/rustc_monomorphize/src/collector.rs index 5d7820df622b7..62519ee4f13ee 100644 --- a/compiler/rustc_monomorphize/src/collector.rs +++ b/compiler/rustc_monomorphize/src/collector.rs @@ -1064,7 +1064,8 @@ fn visit_instance_use<'tcx>( | ty::InstanceKind::Shim(ty::ShimKind::ConstructCoroutineInClosure { .. }) | ty::InstanceKind::Shim(ty::ShimKind::FnPtr(..)) | ty::InstanceKind::Shim(ty::ShimKind::Clone(..)) - | ty::InstanceKind::Shim(ty::ShimKind::FnPtrAddr(..)) => { + | ty::InstanceKind::Shim(ty::ShimKind::FnPtrAsPtr(..)) + | ty::InstanceKind::Shim(ty::ShimKind::FnPtrFromPtr(..)) => { output.push(create_fn_mono_item(tcx, instance, source)); } } diff --git a/compiler/rustc_monomorphize/src/partitioning.rs b/compiler/rustc_monomorphize/src/partitioning.rs index 1b3e411312ca6..29b624afd0614 100644 --- a/compiler/rustc_monomorphize/src/partitioning.rs +++ b/compiler/rustc_monomorphize/src/partitioning.rs @@ -655,7 +655,8 @@ fn characteristic_def_id_of_mono_item<'tcx>( | ty::InstanceKind::Shim(ty::ShimKind::DropGlue(..)) | ty::InstanceKind::Shim(ty::ShimKind::Clone(..)) | ty::InstanceKind::Shim(ty::ShimKind::ThreadLocal(..)) - | ty::InstanceKind::Shim(ty::ShimKind::FnPtrAddr(..)) + | ty::InstanceKind::Shim(ty::ShimKind::FnPtrAsPtr(..)) + | ty::InstanceKind::Shim(ty::ShimKind::FnPtrFromPtr(..)) | ty::InstanceKind::Shim(ty::ShimKind::FutureDropPoll(..)) | ty::InstanceKind::Shim(ty::ShimKind::AsyncDropGlue(..)) | ty::InstanceKind::Shim(ty::ShimKind::AsyncDropGlueCtor(..)) => return None, @@ -841,7 +842,8 @@ fn mono_item_visibility<'tcx>( | InstanceKind::Shim(ShimKind::ConstructCoroutineInClosure { .. }) | InstanceKind::Shim(ShimKind::DropGlue(..)) | InstanceKind::Shim(ShimKind::Clone(..)) - | InstanceKind::Shim(ShimKind::FnPtrAddr(..)) => return Visibility::Hidden, + | InstanceKind::Shim(ShimKind::FnPtrAsPtr(..)) + | InstanceKind::Shim(ShimKind::FnPtrFromPtr(..)) => return Visibility::Hidden, }; let attrs = tcx.codegen_fn_attrs(def_id); diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index a07cd26f0cbc5..fcdd3d93b0748 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -257,7 +257,6 @@ symbols! { Mutex, MutexGuard, Named, - NonNull, NonZero, None, Normal, @@ -635,6 +634,7 @@ symbols! { cmp_partialord_lt, cmpxchg16b_target_feature, cmse_nonsecure_entry, + code, coerce_pointee_validated, coerce_shared, coerce_shared_target, @@ -1005,8 +1005,10 @@ symbols! { fn_mut, fn_once, fn_once_output, - fn_ptr_addr, + fn_ptr_as_ptr, + fn_ptr_from_ptr, fn_ptr_trait, + fn_static, forbid, force_target_feature, forget, @@ -1449,6 +1451,7 @@ symbols! { non_exhaustive_omitted_patterns_lint, non_lifetime_binders, non_modrs_mods, + non_null, nonblocking, none, nontemporal_store, diff --git a/compiler/rustc_ty_utils/src/diagnostics.rs b/compiler/rustc_ty_utils/src/diagnostics.rs index 07a2c844a717e..9eb4e0b9686b1 100644 --- a/compiler/rustc_ty_utils/src/diagnostics.rs +++ b/compiler/rustc_ty_utils/src/diagnostics.rs @@ -71,13 +71,6 @@ pub(crate) enum GenericConstantTooComplexSub { OperationNotSupported(#[primary_span] Span), } -#[derive(Diagnostic)] -#[diag("`FnPtr` trait with unexpected associated item")] -pub(crate) struct UnexpectedFnPtrAssociatedItem { - #[primary_span] - pub span: Span, -} - #[derive(Diagnostic)] #[diag( "monomorphising SIMD type `{$ty}` with a non-primitive-scalar (integer/float/pointer) element type `{$e_ty}`" diff --git a/compiler/rustc_ty_utils/src/instance.rs b/compiler/rustc_ty_utils/src/instance.rs index c0f476a7feaca..94ce0c2a533d2 100644 --- a/compiler/rustc_ty_utils/src/instance.rs +++ b/compiler/rustc_ty_utils/src/instance.rs @@ -15,8 +15,6 @@ use rustc_trait_selection::traits; use tracing::debug; use traits::translate_args; -use crate::diagnostics::UnexpectedFnPtrAssociatedItem; - fn resolve_instance_raw<'tcx>( tcx: TyCtxt<'tcx>, key: ty::PseudoCanonicalInput<'tcx, (DefId, GenericArgsRef<'tcx>)>, @@ -297,22 +295,28 @@ fn resolve_associated_item<'tcx>( Some(ty::Instance::new_raw(trait_item_id, args)) } } else if tcx.is_lang_item(trait_ref.def_id, LangItem::FnPtrTrait) { - if tcx.is_lang_item(trait_item_id, LangItem::FnPtrAddr) { - let self_ty = trait_ref.self_ty(); - if !matches!(self_ty.kind(), ty::FnPtr(..)) { - return Ok(None); - } + let self_ty = trait_ref.self_ty(); + if !matches!(self_ty.kind(), ty::FnPtr(..)) { + return Ok(None); + } + if tcx.is_lang_item(trait_item_id, LangItem::FnPtrAsPtr) { Some(Instance { - def: ty::InstanceKind::Shim(ty::ShimKind::FnPtrAddr( + def: ty::InstanceKind::Shim(ty::ShimKind::FnPtrAsPtr( trait_item_id, self_ty, )), args: rcvr_args, }) - } else { - tcx.dcx().emit_fatal(UnexpectedFnPtrAssociatedItem { - span: tcx.def_span(trait_item_id), + } else if tcx.is_lang_item(trait_item_id, LangItem::FnPtrFromPtr) { + Some(Instance { + def: ty::InstanceKind::Shim(ty::ShimKind::FnPtrFromPtr( + trait_item_id, + self_ty, + )), + args: rcvr_args, }) + } else { + Some(Instance { def: ty::InstanceKind::Item(trait_item_id), args: rcvr_args }) } } else if let Some(target_kind) = tcx.fn_trait_kind_from_def_id(trait_ref.def_id) { // FIXME: This doesn't check for malformed libcore that defines, e.g., diff --git a/library/core/src/marker.rs b/library/core/src/marker.rs index 1eea7adf1a6d5..c83972d6eae58 100644 --- a/library/core/src/marker.rs +++ b/library/core/src/marker.rs @@ -1136,25 +1136,6 @@ marker_impls! { {T: ConstParamTy_ + ?Sized} &T, } -/// A common trait implemented by all function pointers. -// -// Note that while the trait is internal and unstable it is nevertheless -// exposed as a public bound of the stable `core::ptr::fn_addr_eq` function. -#[unstable( - feature = "fn_ptr_trait", - issue = "none", - reason = "internal trait for implementing various traits for all function pointers" -)] -#[lang = "fn_ptr_trait"] -#[fundamental] -#[rustc_deny_explicit_impl] -#[rustc_dyn_incompatible_trait] -pub trait FnPtr: Copy + Clone { - /// Returns the address of the function pointer. - #[lang = "fn_ptr_addr"] - fn addr(self) -> *const (); -} - /// Derive macro that makes a smart pointer usable with trait objects. /// /// # What this macro does diff --git a/library/core/src/ops/function.rs b/library/core/src/ops/function.rs index 15b54243c1eed..d40603e15bb1b 100644 --- a/library/core/src/ops/function.rs +++ b/library/core/src/ops/function.rs @@ -1,5 +1,5 @@ use crate::marker::Tuple; - +use crate::ptr::NonNull; /// The version of the call operator that takes an immutable receiver. /// /// Instances of `Fn` can be called repeatedly without mutating state. @@ -311,3 +311,40 @@ mod impls { } } } + +unsafe extern "C" { + /// A type representing a pointer to a function pointer. + #[unstable(feature = "fn_static", issue = "148768")] + #[lang = "code"] + pub type Code; +} + +/// A common trait implemented by all function pointers. +#[unstable(feature = "fn_static", issue = "148768")] +#[lang = "fn_ptr_trait"] +#[fundamental] +#[rustc_deny_explicit_impl] +#[rustc_dyn_incompatible_trait] +pub trait FnPtr: Copy { + /// Returns the address of the function pointer. + #[unstable(feature = "fn_static", issue = "148768")] + fn addr(self) -> usize { + self.as_ptr().addr().get() + } + + /// Returns the function pointer as a [`NonNull`]. + #[unstable(feature = "fn_static", issue = "148768")] + #[lang = "fn_ptr_as_ptr"] + fn as_ptr(self) -> NonNull; + + /// Constructs a function pointer from a `NonNull` pointer. + /// + /// # Safety + /// + /// The function pointer must have been obtained + /// from an [`FnPtr::as_ptr`] call from a function + /// pointer type that is ABI compatible. + #[unstable(feature = "fn_static", issue = "148768")] + #[lang = "fn_ptr_from_ptr"] + unsafe fn from_ptr(ptr: NonNull) -> Self; +} diff --git a/library/core/src/ops/mod.rs b/library/core/src/ops/mod.rs index 87dd873fdb57d..6fa96c242fa76 100644 --- a/library/core/src/ops/mod.rs +++ b/library/core/src/ops/mod.rs @@ -176,6 +176,8 @@ pub use self::deref::Receiver; pub use self::deref::{Deref, DerefMut}; #[stable(feature = "rust1", since = "1.0.0")] pub use self::drop::Drop; +#[unstable(feature = "fn_static", issue = "148768")] +pub use self::function::{Code, FnPtr}; #[stable(feature = "rust1", since = "1.0.0")] pub use self::function::{Fn, FnMut, FnOnce}; #[stable(feature = "rust1", since = "1.0.0")] diff --git a/library/core/src/ptr/mod.rs b/library/core/src/ptr/mod.rs index 8b8a65d630189..2bdb12485dd68 100644 --- a/library/core/src/ptr/mod.rs +++ b/library/core/src/ptr/mod.rs @@ -428,9 +428,10 @@ use crate::cmp::Ordering; use crate::intrinsics::const_eval_select; -use crate::marker::{Destruct, FnPtr, PointeeSized}; +use crate::marker::{Destruct, PointeeSized}; use crate::mem::{self, MaybeUninit, SizedTypeProperties}; use crate::num::NonZero; +use crate::ops::FnPtr; use crate::{fmt, hash, intrinsics, ub_checks}; #[unstable(feature = "ptr_alignment_type", issue = "102070")] @@ -2660,21 +2661,21 @@ impl Ord for F { #[stable(feature = "fnptr_impls", since = "1.4.0")] impl hash::Hash for F { fn hash(&self, state: &mut HH) { - state.write_usize(self.addr().addr()) + state.write_usize(self.addr()) } } #[stable(feature = "fnptr_impls", since = "1.4.0")] impl fmt::Pointer for F { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt::pointer_fmt_inner(self.addr().addr(), f) + fmt::pointer_fmt_inner(self.addr(), f) } } #[stable(feature = "fnptr_impls", since = "1.4.0")] impl fmt::Debug for F { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt::pointer_fmt_inner(self.addr().addr(), f) + fmt::pointer_fmt_inner(self.addr(), f) } } diff --git a/library/core/src/ptr/non_null.rs b/library/core/src/ptr/non_null.rs index bf5355ffc141d..5ec875cf47868 100644 --- a/library/core/src/ptr/non_null.rs +++ b/library/core/src/ptr/non_null.rs @@ -75,7 +75,7 @@ use crate::{fmt, hash, intrinsics, mem, ptr}; #[stable(feature = "nonnull", since = "1.25.0")] #[repr(transparent)] #[rustc_nonnull_optimization_guaranteed] -#[rustc_diagnostic_item = "NonNull"] +#[lang = "non_null"] pub struct NonNull { pointer: crate::pattern_type!(*const T is !null), } diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index d3bbb7c2353cd..1b63d94b65bef 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -348,7 +348,7 @@ #![feature(float_gamma)] #![feature(float_minimum_maximum)] #![feature(fmt_internals)] -#![feature(fn_ptr_trait)] +#![feature(fn_static)] #![feature(formatting_options)] #![feature(funnel_shifts)] #![feature(generic_atomic)] diff --git a/library/std/src/sys/pal/unix/weak/dlsym.rs b/library/std/src/sys/pal/unix/weak/dlsym.rs index 4967b93cc52b5..170e356dbc72f 100644 --- a/library/std/src/sys/pal/unix/weak/dlsym.rs +++ b/library/std/src/sys/pal/unix/weak/dlsym.rs @@ -1,5 +1,6 @@ use crate::ffi::{CStr, c_char, c_void}; -use crate::marker::{FnPtr, PhantomData}; +use crate::marker::PhantomData; +use crate::ops::FnPtr; use crate::sync::atomic::{Atomic, AtomicPtr, Ordering}; use crate::{mem, ptr}; diff --git a/src/tools/clippy/clippy_lints/src/methods/zst_offset.rs b/src/tools/clippy/clippy_lints/src/methods/zst_offset.rs index 3efb267328984..4d3882089a2fc 100644 --- a/src/tools/clippy/clippy_lints/src/methods/zst_offset.rs +++ b/src/tools/clippy/clippy_lints/src/methods/zst_offset.rs @@ -1,9 +1,9 @@ use clippy_utils::diagnostics::span_lint; use clippy_utils::res::MaybeDef as _; use rustc_hir as hir; +use rustc_hir::attrs::LangItem; use rustc_lint::LateContext; use rustc_middle::ty; -use rustc_span::sym; use super::ZST_OFFSET; @@ -11,7 +11,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, recv: &hir::Expr let recv_ty = cx.typeck_results().expr_ty(recv); let pointee_ty = match recv_ty.kind() { ty::RawPtr(ty, _) => *ty, - ty::Adt(_, args) if recv_ty.is_diag_item(cx, sym::NonNull) => args.type_at(0), + ty::Adt(_, args) if recv_ty.is_lang_item(cx, LangItem::NonNull) => args.type_at(0), _ => return, }; if let Ok(layout) = cx.tcx.layout_of(cx.typing_env().as_query_input(pointee_ty)) diff --git a/src/tools/clippy/clippy_lints/src/non_send_fields_in_send_ty.rs b/src/tools/clippy/clippy_lints/src/non_send_fields_in_send_ty.rs index dc8111a51f1ee..77a772d3363bc 100644 --- a/src/tools/clippy/clippy_lints/src/non_send_fields_in_send_ty.rs +++ b/src/tools/clippy/clippy_lints/src/non_send_fields_in_send_ty.rs @@ -4,6 +4,7 @@ use clippy_utils::is_lint_allowed; use clippy_utils::source::snippet; use clippy_utils::ty::{implements_trait, is_copy}; use rustc_ast::ImplPolarity; +use rustc_hir::attrs::LangItem; use rustc_hir::def_id::DefId; use rustc_hir::{FieldDef, Item, ItemKind, Node}; use rustc_lint::{LateContext, LateLintPass}; @@ -227,7 +228,7 @@ fn contains_pointer_like<'tcx>(cx: &LateContext<'tcx>, target_ty: Ty<'tcx>) -> b ty::RawPtr(_, _) => { return true; }, - ty::Adt(adt_def, _) if cx.tcx.is_diagnostic_item(sym::NonNull, adt_def.did()) => { + ty::Adt(adt_def, _) if cx.tcx.is_lang_item(adt_def.did(), LangItem::NonNull) => { return true; }, _ => (), diff --git a/src/tools/clippy/clippy_lints/src/nonnull_unchecked_on_box_ptr.rs b/src/tools/clippy/clippy_lints/src/nonnull_unchecked_on_box_ptr.rs index dd72f8339d329..4339dc427d5a3 100644 --- a/src/tools/clippy/clippy_lints/src/nonnull_unchecked_on_box_ptr.rs +++ b/src/tools/clippy/clippy_lints/src/nonnull_unchecked_on_box_ptr.rs @@ -57,7 +57,7 @@ impl<'tcx> LateLintPass<'tcx> for NonnullUncheckedOnBoxPtr { .ty_rel_def_if_named(cx, sym::new_unchecked) .opt_parent(cx) .opt_impl_ty(cx) - .is_diag_item(cx, sym::NonNull) + .is_lang_item(cx, LangItem::NonNull) && box_into_raw .ty_rel_def_if_named(cx, sym::into_raw) .opt_parent(cx) diff --git a/src/tools/clippy/clippy_lints/src/volatile_composites.rs b/src/tools/clippy/clippy_lints/src/volatile_composites.rs index e7eeade451724..7600fab1048c9 100644 --- a/src/tools/clippy/clippy_lints/src/volatile_composites.rs +++ b/src/tools/clippy/clippy_lints/src/volatile_composites.rs @@ -1,6 +1,7 @@ use clippy_utils::diagnostics::span_lint; use clippy_utils::res::MaybeDef as _; use clippy_utils::sym; +use rustc_hir::attrs::LangItem; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::layout::LayoutOf as _; @@ -155,7 +156,7 @@ impl<'tcx> LateLintPass<'tcx> for VolatileComposites { // Raw pointers ty::RawPtr(innerty, _) => report_volatile_safe(cx, expr, *innerty), // std::ptr::NonNull - ty::Adt(_, args) if self_ty.is_diag_item(cx, sym::NonNull) => { + ty::Adt(_, args) if self_ty.is_lang_item(cx, LangItem::NonNull) => { report_volatile_safe(cx, expr, args.type_at(0)); }, _ => (), diff --git a/src/tools/rust-analyzer/crates/hir-def/src/lang_item.rs b/src/tools/rust-analyzer/crates/hir-def/src/lang_item.rs index 511305c4f372e..8aeb54b509cac 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/lang_item.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/lang_item.rs @@ -462,8 +462,11 @@ language_item_table! { LangItems => Freeze, sym::freeze, TraitId; + NonNull, sym::non_null, StructId; + FnPtrTrait, sym::fn_ptr_trait, TraitId; - FnPtrAddr, sym::fn_ptr_addr, FunctionId; + FnPtrAsPtr, sym::fn_ptr_as_ptr, FunctionId; + FnPtrFromPtr, sym::fn_ptr_from_ptr, FunctionId; Drop, sym::drop, TraitId; Destruct, sym::destruct, TraitId; diff --git a/src/tools/rust-analyzer/crates/intern/src/symbol/symbols.rs b/src/tools/rust-analyzer/crates/intern/src/symbol/symbols.rs index 915cc5e389286..45b4c274a5254 100644 --- a/src/tools/rust-analyzer/crates/intern/src/symbol/symbols.rs +++ b/src/tools/rust-analyzer/crates/intern/src/symbol/symbols.rs @@ -250,6 +250,7 @@ define_symbols! { clone, trivial_clone, Clone, + code, coerce_shared, coerce_unsized, column, @@ -328,7 +329,8 @@ define_symbols! { async_fn_kind_upvars, call_ref_future, call_once_future, - fn_ptr_addr, + fn_ptr_as_ptr, + fn_ptr_from_ptr, fn_ptr_trait, format_alignment, format_args_nl, @@ -439,6 +441,7 @@ define_symbols! { no_mangle, no_std, non_exhaustive, + non_null, none, None, not, diff --git a/tests/ui/feature-gates/feature-gate-fn_static.rs b/tests/ui/feature-gates/feature-gate-fn_static.rs new file mode 100644 index 0000000000000..5111c7ab6e785 --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-fn_static.rs @@ -0,0 +1,4 @@ +use std::ops::FnPtr; +//~^ ERROR: use of unstable library feature `fn_static` [E0658] + +fn main() {} diff --git a/tests/ui/feature-gates/feature-gate-fn_static.stderr b/tests/ui/feature-gates/feature-gate-fn_static.stderr new file mode 100644 index 0000000000000..1b4bfd835d617 --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-fn_static.stderr @@ -0,0 +1,13 @@ +error[E0658]: use of unstable library feature `fn_static` + --> $DIR/feature-gate-fn_static.rs:1:5 + | +LL | use std::ops::FnPtr; + | ^^^^^^^^^^^^^^^ + | + = note: see issue #148768 for more information + = help: add `#![feature(fn_static)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/fn/fn-ptr-trait-run.rs b/tests/ui/fn/fn-ptr-trait-run.rs new file mode 100644 index 0000000000000..529deb9be1e0a --- /dev/null +++ b/tests/ui/fn/fn-ptr-trait-run.rs @@ -0,0 +1,15 @@ +#![feature(fn_static)] +//@ run-pass + +use std::ops::FnPtr; + +fn bar(a: u64) -> u64 { + a +} + +fn main() { + type F = fn(u64) -> u64; + let b: F = bar; + assert_eq!(b.addr(), bar as *const () as usize); + assert_eq!(b(42), unsafe { F::from_ptr(b.as_ptr())(42) }); +} diff --git a/tests/ui/fn/fn-ptr-trait.rs b/tests/ui/fn/fn-ptr-trait.rs index b9096d5f303f5..dcd1b38d56047 100644 --- a/tests/ui/fn/fn-ptr-trait.rs +++ b/tests/ui/fn/fn-ptr-trait.rs @@ -1,7 +1,7 @@ -#![feature(fn_ptr_trait)] +#![feature(fn_static)] //@ check-pass -use std::marker::FnPtr; +use std::ops::FnPtr; trait Foo {} impl Foo for T where T: FnPtr {} diff --git a/tests/ui/traits/next-solver/diagnostics/dont-pick-fnptr-bound-as-leaf.rs b/tests/ui/traits/next-solver/diagnostics/dont-pick-fnptr-bound-as-leaf.rs index 0da7bb17a58a2..b7a4c911746de 100644 --- a/tests/ui/traits/next-solver/diagnostics/dont-pick-fnptr-bound-as-leaf.rs +++ b/tests/ui/traits/next-solver/diagnostics/dont-pick-fnptr-bound-as-leaf.rs @@ -6,9 +6,9 @@ // to give as the reason why the bound does not hold. This test checks that we do not // try to tell the user that `Foo: FnPtr` is unimplemented as that would be confusing. -#![feature(fn_ptr_trait)] +#![feature(fn_static)] -use std::marker::FnPtr; +use std::ops::FnPtr; trait Trait {} From 6064370f7977cc0b09f87bbdab455b2f6e26ed60 Mon Sep 17 00:00:00 2001 From: Ada Alakbarova Date: Tue, 18 Aug 2026 12:12:30 +0200 Subject: [PATCH 12/26] rename `ProjectionPredicate` to `ProjectionClause` --- .../src/check/compare_impl_item.rs | 2 +- .../src/hir_ty_lowering/bounds.rs | 2 +- .../src/hir_ty_lowering/dyn_trait.rs | 2 +- .../src/impl_wf_check/min_specialization.rs | 2 +- .../rustc_hir_analysis/src/variance/mod.rs | 2 +- compiler/rustc_hir_typeck/src/closure.rs | 8 ++--- .../rustc_infer/src/infer/opaque_types/mod.rs | 2 +- compiler/rustc_infer/src/infer/projection.rs | 2 +- .../src/infer/relate/generalize.rs | 2 +- compiler/rustc_middle/src/ty/mod.rs | 4 +-- compiler/rustc_middle/src/ty/predicate.rs | 24 ++++++------- compiler/rustc_middle/src/ty/print/pretty.rs | 2 +- compiler/rustc_middle/src/ty/util.rs | 2 +- .../src/solve/assembly/structural_traits.rs | 4 +-- .../src/solve/eval_ctxt/mod.rs | 2 +- .../rustc_next_trait_solver/src/solve/mod.rs | 2 +- .../src/solve/normalizes_to.rs | 10 +++--- .../src/solve/project_goals/anon_const.rs | 2 +- .../src/solve/project_goals/free_alias.rs | 2 +- .../src/solve/project_goals/inherent.rs | 2 +- .../src/solve/project_goals/mod.rs | 8 ++--- .../src/solve/project_goals/opaque_types.rs | 2 +- compiler/rustc_privacy/src/lib.rs | 2 +- compiler/rustc_public/src/ty/tys.rs | 7 ++-- .../src/unstable/convert/stable/ty.rs | 8 ++--- .../cfi/typeid/itanium_cxx_abi/transform.rs | 2 +- .../traits/fulfillment_errors.rs | 4 +-- .../src/error_reporting/traits/suggestions.rs | 2 +- .../src/solve/fulfill/derive_errors.rs | 2 +- .../src/solve/normalize.rs | 4 +-- .../src/traits/auto_trait.rs | 2 +- .../rustc_trait_selection/src/traits/mod.rs | 2 +- .../src/traits/project.rs | 34 +++++++++---------- .../src/traits/select/mod.rs | 6 ++-- .../src/traits/structural_normalize.rs | 2 +- .../rustc_trait_selection/src/traits/util.rs | 2 +- compiler/rustc_ty_utils/src/ty.rs | 2 +- compiler/rustc_type_ir/src/flags.rs | 2 +- compiler/rustc_type_ir/src/inherent.rs | 8 ++--- compiler/rustc_type_ir/src/interner.rs | 2 +- compiler/rustc_type_ir/src/ir_print.rs | 4 +-- compiler/rustc_type_ir/src/predicate.rs | 26 +++++++------- compiler/rustc_type_ir/src/predicate_kind.rs | 4 +-- compiler/rustc_type_ir/src/relate/combine.rs | 4 +-- .../src/relate/solver_relating.rs | 4 +-- src/librustdoc/clean/mod.rs | 2 +- .../src/methods/unnecessary_to_owned.rs | 6 ++-- .../src/needless_borrows_for_generic_args.rs | 6 ++-- .../src/unit_return_expecting_ord.rs | 4 +-- tests/ui/attributes/dump-clauses.stderr | 2 +- .../assoc-type-clauses.stderr | 6 ++-- 51 files changed, 127 insertions(+), 124 deletions(-) diff --git a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs index 2f65b443dd5ec..8c2896e78289a 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs @@ -2726,7 +2726,7 @@ fn param_env_with_gat_bounds<'tcx>( } _ => clauses.push( ty::Binder::bind_with_vars( - ty::ProjectionPredicate { + ty::ProjectionClause { projection_term: ty::AliasTerm::new_from_def_id( tcx, trait_ty.def_id, diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs index 613202ef35345..8102708550292 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs @@ -547,7 +547,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { | PredicateFilter::SelfOnly | PredicateFilter::SelfAndAssociatedTypeBounds => { let bound = projection_term.map_bound(|projection_term| { - ty::ClauseKind::Projection(ty::ProjectionPredicate { + ty::ClauseKind::Projection(ty::ProjectionClause { projection_term, term, }) diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_trait.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_trait.rs index 3d8c23ebdf8d3..db6a348b8ff9e 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_trait.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_trait.rs @@ -476,7 +476,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { /// `elaborated-predicates-unconstrained-late-bound.rs` for a test. fn check_elaborated_projection_mentions_input_lifetimes( &self, - pred: ty::PolyProjectionPredicate<'tcx>, + pred: ty::PolyProjectionClause<'tcx>, span: Span, supertrait_span: Span, ) { diff --git a/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs b/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs index 5788983811f03..42d9b4cdbf8c5 100644 --- a/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs +++ b/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs @@ -433,7 +433,7 @@ fn check_specialization_on<'tcx>( .emit()) } } - ty::ClauseKind::Projection(ty::ProjectionPredicate { projection_term, term }) => Err(tcx + ty::ClauseKind::Projection(ty::ProjectionClause { projection_term, term }) => Err(tcx .dcx() .struct_span_err( span, diff --git a/compiler/rustc_hir_analysis/src/variance/mod.rs b/compiler/rustc_hir_analysis/src/variance/mod.rs index c733292df7d98..e595ccab47058 100644 --- a/compiler/rustc_hir_analysis/src/variance/mod.rs +++ b/compiler/rustc_hir_analysis/src/variance/mod.rs @@ -206,7 +206,7 @@ fn variance_of_opaque( arg.visit_with(&mut collector); } } - ty::ClauseKind::Projection(ty::ProjectionPredicate { + ty::ClauseKind::Projection(ty::ProjectionClause { projection_term: ty::AliasTerm { args, .. }, term, }) => { diff --git a/compiler/rustc_hir_typeck/src/closure.rs b/compiler/rustc_hir_typeck/src/closure.rs index a9ce46b68527f..de2f152011dbe 100644 --- a/compiler/rustc_hir_typeck/src/closure.rs +++ b/compiler/rustc_hir_typeck/src/closure.rs @@ -483,7 +483,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { &self, cause_span: Option, closure_kind: hir::ClosureKind, - projection: ty::PolyProjectionPredicate<'tcx>, + projection: ty::PolyProjectionClause<'tcx>, ) -> Option> { let def_id = projection.item_def_id(); @@ -515,7 +515,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fn extract_sig_from_projection( &self, cause_span: Option, - projection: ty::PolyProjectionPredicate<'tcx>, + projection: ty::PolyProjectionClause<'tcx>, ) -> Option> { let projection = self.resolve_vars_if_possible(projection); @@ -560,7 +560,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fn extract_sig_from_projection_and_future_bound( &self, cause_span: Option, - projection: ty::PolyProjectionPredicate<'tcx>, + projection: ty::PolyProjectionClause<'tcx>, ) -> Option> { let projection = self.resolve_vars_if_possible(projection); @@ -1031,7 +1031,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fn deduce_future_output_from_projection( &self, cause_span: Span, - predicate: ty::PolyProjectionPredicate<'tcx>, + predicate: ty::PolyProjectionClause<'tcx>, ) -> Option> { debug!("deduce_future_output_from_projection(predicate={:?})", predicate); diff --git a/compiler/rustc_infer/src/infer/opaque_types/mod.rs b/compiler/rustc_infer/src/infer/opaque_types/mod.rs index 08c7c49417124..70423ca7da1be 100644 --- a/compiler/rustc_infer/src/infer/opaque_types/mod.rs +++ b/compiler/rustc_infer/src/infer/opaque_types/mod.rs @@ -335,7 +335,7 @@ impl<'tcx> InferCtxt<'tcx> { goals.push(Goal::new( self.tcx, param_env, - ty::ProjectionPredicate { + ty::ProjectionClause { projection_term: projection_ty.into(), term: ty_var.into(), }, diff --git a/compiler/rustc_infer/src/infer/projection.rs b/compiler/rustc_infer/src/infer/projection.rs index 43870ccbdd39b..5736b0a24eff3 100644 --- a/compiler/rustc_infer/src/infer/projection.rs +++ b/compiler/rustc_infer/src/infer/projection.rs @@ -29,7 +29,7 @@ impl<'tcx> InferCtxt<'tcx> { self.next_const_var(span).into() }; - let projection = ty::ProjectionPredicate { projection_term: alias_term, term: infer_var }; + let projection = ty::ProjectionClause { projection_term: alias_term, term: infer_var }; let obligation = Obligation::with_depth(self.tcx, cause, recursion_depth, param_env, projection); obligations.push(obligation); diff --git a/compiler/rustc_infer/src/infer/relate/generalize.rs b/compiler/rustc_infer/src/infer/relate/generalize.rs index 0e4ebdfb90085..afdabb38c3b20 100644 --- a/compiler/rustc_infer/src/infer/relate/generalize.rs +++ b/compiler/rustc_infer/src/infer/relate/generalize.rs @@ -171,7 +171,7 @@ impl<'tcx> InferCtxt<'tcx> { // instead create a new inference variable `?normalized_source`, emitting // `Projection(normalized_source, ?ty_normalized)` and // `?normalized_source <: generalized_term`. - relation.register_predicates([ty::ProjectionPredicate { + relation.register_predicates([ty::ProjectionClause { projection_term: source_alias, term: generalized_term, }]); diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index cd9e5f6903478..b7feb28d61414 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -89,8 +89,8 @@ pub use self::predicate::{ ExistentialPredicate, ExistentialPredicateStableCmpExt, ExistentialProjection, ExistentialTraitRef, HostEffectClause, NormalizesTo, OutlivesClause, PolyCoercePredicate, PolyExistentialPredicate, PolyExistentialProjection, PolyExistentialTraitRef, - PolyProjectionPredicate, PolyRegionOutlivesClause, PolySubtypePredicate, PolyTraitPredicate, - PolyTraitRef, PolyTypeOutlivesClause, Predicate, PredicateKind, ProjectionPredicate, + PolyProjectionClause, PolyRegionOutlivesClause, PolySubtypePredicate, PolyTraitPredicate, + PolyTraitRef, PolyTypeOutlivesClause, Predicate, PredicateKind, ProjectionClause, RegionConstraint, RegionEqPredicate, RegionOutlivesClause, SubtypePredicate, TraitPredicate, TraitRef, TypeOutlivesClause, }; diff --git a/compiler/rustc_middle/src/ty/predicate.rs b/compiler/rustc_middle/src/ty/predicate.rs index 990a424289e9b..d2834ab9ce226 100644 --- a/compiler/rustc_middle/src/ty/predicate.rs +++ b/compiler/rustc_middle/src/ty/predicate.rs @@ -10,7 +10,7 @@ use crate::ty::{self, EarlyBinder, Ty, TyCtxt, TypeFlags, Upcast, UpcastFrom, Wi pub type TraitRef<'tcx> = ir::TraitRef>; pub type AliasTerm<'tcx> = ir::AliasTerm>; pub type AliasTermKind<'tcx> = ir::AliasTermKind>; -pub type ProjectionPredicate<'tcx> = ir::ProjectionPredicate>; +pub type ProjectionClause<'tcx> = ir::ProjectionClause>; pub type ExistentialPredicate<'tcx> = ir::ExistentialPredicate>; pub type ExistentialTraitRef<'tcx> = ir::ExistentialTraitRef>; pub type ExistentialProjection<'tcx> = ir::ExistentialProjection>; @@ -32,7 +32,7 @@ pub type PolyRegionOutlivesClause<'tcx> = ty::Binder<'tcx, RegionOutlivesClause< pub type PolyTypeOutlivesClause<'tcx> = ty::Binder<'tcx, TypeOutlivesClause<'tcx>>; pub type PolySubtypePredicate<'tcx> = ty::Binder<'tcx, SubtypePredicate<'tcx>>; pub type PolyCoercePredicate<'tcx> = ty::Binder<'tcx, CoercePredicate<'tcx>>; -pub type PolyProjectionPredicate<'tcx> = ty::Binder<'tcx, ProjectionPredicate<'tcx>>; +pub type PolyProjectionClause<'tcx> = ty::Binder<'tcx, ProjectionClause<'tcx>>; /// A statement that can be proven by a trait solver. This includes things that may /// show up in where clauses, such as trait predicates and projection predicates, @@ -186,7 +186,7 @@ impl<'tcx> Clause<'tcx> { } } - pub fn as_projection_clause(self) -> Option>> { + pub fn as_projection_clause(self) -> Option>> { let clause = self.kind(); if let ty::ClauseKind::Projection(projection_clause) = clause.skip_binder() { Some(clause.rebind(projection_clause)) @@ -556,27 +556,27 @@ impl<'tcx> UpcastFrom, TypeOutlivesClause<'tcx>> for Predicate<'tcx } } -impl<'tcx> UpcastFrom, ProjectionPredicate<'tcx>> for Predicate<'tcx> { - fn upcast_from(from: ProjectionPredicate<'tcx>, tcx: TyCtxt<'tcx>) -> Self { +impl<'tcx> UpcastFrom, ProjectionClause<'tcx>> for Predicate<'tcx> { + fn upcast_from(from: ProjectionClause<'tcx>, tcx: TyCtxt<'tcx>) -> Self { ty::Binder::dummy(PredicateKind::Clause(ClauseKind::Projection(from))).upcast(tcx) } } -impl<'tcx> UpcastFrom, PolyProjectionPredicate<'tcx>> for Predicate<'tcx> { - fn upcast_from(from: PolyProjectionPredicate<'tcx>, tcx: TyCtxt<'tcx>) -> Self { +impl<'tcx> UpcastFrom, PolyProjectionClause<'tcx>> for Predicate<'tcx> { + fn upcast_from(from: PolyProjectionClause<'tcx>, tcx: TyCtxt<'tcx>) -> Self { from.map_bound(|p| PredicateKind::Clause(ClauseKind::Projection(p))).upcast(tcx) } } -impl<'tcx> UpcastFrom, ProjectionPredicate<'tcx>> for Clause<'tcx> { - fn upcast_from(from: ProjectionPredicate<'tcx>, tcx: TyCtxt<'tcx>) -> Self { +impl<'tcx> UpcastFrom, ProjectionClause<'tcx>> for Clause<'tcx> { + fn upcast_from(from: ProjectionClause<'tcx>, tcx: TyCtxt<'tcx>) -> Self { let p: Predicate<'tcx> = from.upcast(tcx); p.expect_clause() } } -impl<'tcx> UpcastFrom, PolyProjectionPredicate<'tcx>> for Clause<'tcx> { - fn upcast_from(from: PolyProjectionPredicate<'tcx>, tcx: TyCtxt<'tcx>) -> Self { +impl<'tcx> UpcastFrom, PolyProjectionClause<'tcx>> for Clause<'tcx> { + fn upcast_from(from: PolyProjectionClause<'tcx>, tcx: TyCtxt<'tcx>) -> Self { let p: Predicate<'tcx> = from.upcast(tcx); p.expect_clause() } @@ -611,7 +611,7 @@ impl<'tcx> Predicate<'tcx> { } } - pub fn as_projection_clause(self) -> Option> { + pub fn as_projection_clause(self) -> Option> { let predicate = self.kind(); match predicate.skip_binder() { PredicateKind::Clause(ClauseKind::Projection(t)) => Some(predicate.rebind(t)), diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index 4ab474fd89fe6..b64435a8591a7 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -3314,7 +3314,7 @@ define_print! { self.term.print(p)?; } - ty::ProjectionPredicate<'tcx> { + ty::ProjectionClause<'tcx> { self.projection_term.print(p)?; write!(p, " == ")?; p.reset_type_limit(); diff --git a/compiler/rustc_middle/src/ty/util.rs b/compiler/rustc_middle/src/ty/util.rs index adf153b68dae6..2e31e666f8f48 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -1040,7 +1040,7 @@ impl<'tcx> TypeFolder> for OpaqueTypeExpander<'tcx> { && let ty::ClauseKind::Projection(projection_pred) = clause { p.kind() - .rebind(ty::ProjectionPredicate { + .rebind(ty::ProjectionClause { projection_term: projection_pred.projection_term.fold_with(self), // Don't fold the term on the RHS of the projection predicate. // This is because for default trait methods with RPITITs, we diff --git a/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs b/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs index aa26a122817bb..17172c5333502 100644 --- a/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs +++ b/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs @@ -964,7 +964,7 @@ struct ReplaceProjectionWith<'a, 'b, I: Interner, D: SolverDelegate, param_env: I::ParamEnv, self_ty: I::Ty, - mapping: &'a HashMap>>>, + mapping: &'a HashMap>>>, nested: Vec>, } @@ -975,7 +975,7 @@ where { fn projection_may_match( &mut self, - source_projection: ty::Binder>, + source_projection: ty::Binder>, target_projection: ty::AliasTerm, ) -> Result { if source_projection.item_def_id() != target_projection.expect_projection_def_id() { diff --git a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs index 559ca0a98c58e..17bb87b8e17a9 100644 --- a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs @@ -1709,7 +1709,7 @@ where let infcx = self.delegate.deref(); let mut folder = NormalizationFolder::new(infcx, vec![], |alias_term| { let infer_term = self.next_term_infer_of_alias_kind(alias_term); - let pred = ty::ProjectionPredicate { projection_term: alias_term, term: infer_term }; + let pred = ty::ProjectionClause { projection_term: alias_term, term: infer_term }; let goal = Goal::new(self.cx(), param_env, pred); self.inspect.add_goal(self.delegate, self.max_input_universe, source, goal); let GoalEvaluation { goal, certainty, has_changed: _, stalled_on } = diff --git a/compiler/rustc_next_trait_solver/src/solve/mod.rs b/compiler/rustc_next_trait_solver/src/solve/mod.rs index 3504882834268..84c128ad0f45f 100644 --- a/compiler/rustc_next_trait_solver/src/solve/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/mod.rs @@ -394,7 +394,7 @@ where let projection_goal = Goal::new( self.cx(), param_env, - ty::ProjectionPredicate { projection_term: alias, term: normalized_term }, + ty::ProjectionClause { projection_term: alias, term: normalized_term }, ); // We normalize the self type to be able to relate it with // types from candidates. diff --git a/compiler/rustc_next_trait_solver/src/solve/normalizes_to.rs b/compiler/rustc_next_trait_solver/src/solve/normalizes_to.rs index 08c634620300a..23cd22fab6e3f 100644 --- a/compiler/rustc_next_trait_solver/src/solve/normalizes_to.rs +++ b/compiler/rustc_next_trait_solver/src/solve/normalizes_to.rs @@ -536,7 +536,7 @@ where let output_is_sized_pred = ty::TraitRef::new(cx, cx.require_trait_lang_item(SolverTraitLangItem::Sized), [output]); - let pred = ty::ProjectionPredicate { + let pred = ty::ProjectionClause { projection_term: ty::AliasTerm::new( cx, goal.predicate.alias.kind, @@ -625,7 +625,7 @@ where } else { panic!("no such associated type in `AsyncFn*`: {:?}", def_id) }; - let pred = ty::ProjectionPredicate { projection_term, term }.upcast(cx); + let pred = ty::ProjectionClause { projection_term, term }.upcast(cx); Self::probe_and_consider_implied_clause( ecx, @@ -821,7 +821,7 @@ where ecx, CandidateSource::BuiltinImpl(BuiltinImplSource::Misc), goal, - ty::ProjectionPredicate { + ty::ProjectionClause { projection_term: ty::AliasTerm::new( ecx.cx(), cx.alias_term_kind_from_def_id( @@ -859,7 +859,7 @@ where ecx, CandidateSource::BuiltinImpl(BuiltinImplSource::Misc), goal, - ty::ProjectionPredicate { + ty::ProjectionClause { projection_term: ty::AliasTerm::new( ecx.cx(), cx.alias_term_kind_from_def_id( @@ -950,7 +950,7 @@ where ecx, CandidateSource::BuiltinImpl(BuiltinImplSource::Misc), goal, - ty::ProjectionPredicate { + ty::ProjectionClause { projection_term: ty::AliasTerm::new( ecx.cx(), goal.predicate.alias.kind, diff --git a/compiler/rustc_next_trait_solver/src/solve/project_goals/anon_const.rs b/compiler/rustc_next_trait_solver/src/solve/project_goals/anon_const.rs index fc0c34e63e187..5c6e9cc2045c2 100644 --- a/compiler/rustc_next_trait_solver/src/solve/project_goals/anon_const.rs +++ b/compiler/rustc_next_trait_solver/src/solve/project_goals/anon_const.rs @@ -13,7 +13,7 @@ where #[instrument(level = "trace", skip(self), ret)] pub(super) fn normalize_anon_const( &mut self, - goal: Goal>, + goal: Goal>, ) -> QueryResultOrRerunNonErased { let alias_const = goal.predicate.projection_term.expect_ct(); self.evaluate_const_and_instantiate_projection_term( diff --git a/compiler/rustc_next_trait_solver/src/solve/project_goals/free_alias.rs b/compiler/rustc_next_trait_solver/src/solve/project_goals/free_alias.rs index 7f5d258ccc706..efc630a106ee3 100644 --- a/compiler/rustc_next_trait_solver/src/solve/project_goals/free_alias.rs +++ b/compiler/rustc_next_trait_solver/src/solve/project_goals/free_alias.rs @@ -17,7 +17,7 @@ where { pub(super) fn normalize_free_alias( &mut self, - goal: Goal>, + goal: Goal>, ) -> QueryResultOrRerunNonErased { let cx = self.cx(); let free_alias = goal.predicate.projection_term; diff --git a/compiler/rustc_next_trait_solver/src/solve/project_goals/inherent.rs b/compiler/rustc_next_trait_solver/src/solve/project_goals/inherent.rs index afdc0c20a7132..a7480cded0514 100644 --- a/compiler/rustc_next_trait_solver/src/solve/project_goals/inherent.rs +++ b/compiler/rustc_next_trait_solver/src/solve/project_goals/inherent.rs @@ -18,7 +18,7 @@ where { pub(super) fn normalize_inherent_associated_term( &mut self, - goal: Goal>, + goal: Goal>, ) -> QueryResultOrRerunNonErased { let cx = self.cx(); let inherent = goal.predicate.projection_term; diff --git a/compiler/rustc_next_trait_solver/src/solve/project_goals/mod.rs b/compiler/rustc_next_trait_solver/src/solve/project_goals/mod.rs index 41fe4105cb745..6ec82aefb523f 100644 --- a/compiler/rustc_next_trait_solver/src/solve/project_goals/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/project_goals/mod.rs @@ -5,7 +5,7 @@ mod opaque_types; use rustc_type_ir::search_graph::LowerAvailableDepth; use rustc_type_ir::solve::QueryResultOrRerunNonErased; -use rustc_type_ir::{self as ty, Interner, ProjectionPredicate}; +use rustc_type_ir::{self as ty, Interner, ProjectionClause}; use tracing::{instrument, trace}; use crate::delegate::SolverDelegate; @@ -21,7 +21,7 @@ where #[instrument(level = "trace", skip(self), ret)] pub(super) fn compute_projection_goal( &mut self, - goal: Goal>, + goal: Goal>, ) -> QueryResultOrRerunNonErased { match goal.predicate.projection_term.kind { ty::AliasTermKind::ProjectionTy { .. } | ty::AliasTermKind::ProjectionConst { .. } => { @@ -42,9 +42,9 @@ where fn normalize_associated_term( &mut self, - goal: Goal>, + goal: Goal>, ) -> QueryResultOrRerunNonErased { - let ty::ProjectionPredicate { projection_term: alias, term } = goal.predicate; + let ty::ProjectionClause { projection_term: alias, term } = goal.predicate; let unconstrained_term = self.next_term_infer_of_alias_kind(alias); let normalizes_to = goal.with(self.cx(), ty::NormalizesTo { alias, term: unconstrained_term }); diff --git a/compiler/rustc_next_trait_solver/src/solve/project_goals/opaque_types.rs b/compiler/rustc_next_trait_solver/src/solve/project_goals/opaque_types.rs index 3387c8599b911..126bffb720dbc 100644 --- a/compiler/rustc_next_trait_solver/src/solve/project_goals/opaque_types.rs +++ b/compiler/rustc_next_trait_solver/src/solve/project_goals/opaque_types.rs @@ -16,7 +16,7 @@ where #[tracing::instrument(skip(self))] pub(super) fn normalize_opaque_type( &mut self, - goal: Goal>, + goal: Goal>, ) -> QueryResultOrRerunNonErased { let cx = self.cx(); let opaque_ty = goal.predicate.projection_term; diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index 879b239047fdc..069dfe428be30 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -137,7 +137,7 @@ where try_visit!(self.visit_trait(clause.trait_ref)); clause.constness.visit_with(self) } - ty::ClauseKind::Projection(ty::ProjectionPredicate { + ty::ClauseKind::Projection(ty::ProjectionClause { projection_term: projection_ty, term, }) => { diff --git a/compiler/rustc_public/src/ty/tys.rs b/compiler/rustc_public/src/ty/tys.rs index 35792ce2fcc23..3bd8764c909e8 100644 --- a/compiler/rustc_public/src/ty/tys.rs +++ b/compiler/rustc_public/src/ty/tys.rs @@ -1234,7 +1234,7 @@ pub enum ClauseKind { Trait(TraitPredicate), RegionOutlives(RegionOutlivesClause), TypeOutlives(TypeOutlivesClause), - Projection(ProjectionPredicate), + Projection(ProjectionClause), ConstArgHasType(TyConst, Ty), WellFormed(TermKind), ConstEvaluatable(TyConst), @@ -1279,11 +1279,14 @@ pub type RegionOutlivesPredicate = RegionOutlivesClause; pub type TypeOutlivesPredicate = TypeOutlivesClause; #[derive(Clone, Debug, Eq, PartialEq, Serialize)] -pub struct ProjectionPredicate { +pub struct ProjectionClause { pub projection_term: AliasTerm, pub term: TermKind, } +#[deprecated = "renamed to [`ProjectionClause`]"] +pub type ProjectionPredicate = ProjectionClause; + #[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub enum ImplPolarity { Positive, diff --git a/compiler/rustc_public/src/unstable/convert/stable/ty.rs b/compiler/rustc_public/src/unstable/convert/stable/ty.rs index 160487400c38c..8cefed4dd243d 100644 --- a/compiler/rustc_public/src/unstable/convert/stable/ty.rs +++ b/compiler/rustc_public/src/unstable/convert/stable/ty.rs @@ -872,16 +872,16 @@ where } } -impl<'tcx> Stable<'tcx> for ty::ProjectionPredicate<'tcx> { - type T = crate::ty::ProjectionPredicate; +impl<'tcx> Stable<'tcx> for ty::ProjectionClause<'tcx> { + type T = crate::ty::ProjectionClause; fn stable<'cx>( &self, tables: &mut Tables<'cx, BridgeTys>, cx: &CompilerCtxt<'cx, BridgeTys>, ) -> Self::T { - let ty::ProjectionPredicate { projection_term, term } = self; - crate::ty::ProjectionPredicate { + let ty::ProjectionClause { projection_term, term } = self; + crate::ty::ProjectionClause { projection_term: projection_term.stable(tables, cx), term: term.kind().stable(tables, cx), } diff --git a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs index 1d4accd8ad3b6..8a44589f5052c 100644 --- a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs +++ b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs @@ -262,7 +262,7 @@ fn trait_object_ty<'tcx>(tcx: TyCtxt<'tcx>, poly_trait_ref: ty::PolyTraitRef<'tc ty::ExistentialPredicate::Projection( ty::ExistentialProjection::erase_self_ty( tcx, - ty::ProjectionPredicate { projection_term, term }, + ty::ProjectionClause { projection_term, term }, ), ) }) diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs index 1897ed8fc84eb..3734b8b4f6946 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs @@ -1537,8 +1537,8 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { fn can_match_projection( &self, param_env: ty::ParamEnv<'tcx>, - goal: ty::ProjectionPredicate<'tcx>, - assumption: ty::PolyProjectionPredicate<'tcx>, + goal: ty::ProjectionClause<'tcx>, + assumption: ty::PolyProjectionClause<'tcx>, ) -> bool { let assumption = self.instantiate_binder_with_fresh_vars( DUMMY_SP, diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs index 35bedea6c565e..c87a75c4b9f1f 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs @@ -5529,7 +5529,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { let ty = self.infcx.next_ty_var(span); // This corresponds to `::Item = _`. let projection = ty::Binder::dummy(ty::PredicateKind::Clause( - ty::ClauseKind::Projection(ty::ProjectionPredicate { + ty::ClauseKind::Projection(ty::ProjectionClause { projection_term: ty::AliasTerm::new_from_args(self.tcx, kind.into(), args), term: ty.into(), }), diff --git a/compiler/rustc_trait_selection/src/solve/fulfill/derive_errors.rs b/compiler/rustc_trait_selection/src/solve/fulfill/derive_errors.rs index bb75ae6247e38..ae7967ae6f277 100644 --- a/compiler/rustc_trait_selection/src/solve/fulfill/derive_errors.rs +++ b/compiler/rustc_trait_selection/src/solve/fulfill/derive_errors.rs @@ -302,7 +302,7 @@ impl<'tcx> BestObligation<'tcx> { if let ty::Alias(_, alias) = *self_ty.kind() { let infer_term = goal.infcx().next_ty_var(self.obligation.cause.span); let pred = - ty::ProjectionPredicate { projection_term: alias.into(), term: infer_term.into() }; + ty::ProjectionClause { projection_term: alias.into(), term: infer_term.into() }; let obligation = Obligation::new(tcx, self.obligation.cause.clone(), goal.goal().param_env, pred); self.with_derived_obligation(obligation, |this| { diff --git a/compiler/rustc_trait_selection/src/solve/normalize.rs b/compiler/rustc_trait_selection/src/solve/normalize.rs index 4e718ed896add..bff35154ed10d 100644 --- a/compiler/rustc_trait_selection/src/solve/normalize.rs +++ b/compiler/rustc_trait_selection/src/solve/normalize.rs @@ -53,7 +53,7 @@ where let mut folder = NormalizationFolder::new(infcx, universes.clone(), |alias_term| { let delegate = <&SolverDelegate<'tcx>>::from(infcx); let infer_term = delegate.next_term_var_of_alias_kind(alias_term, at.cause.span); - let predicate = ty::ProjectionPredicate { projection_term: alias_term, term: infer_term }; + let predicate = ty::ProjectionClause { projection_term: alias_term, term: infer_term }; let goal = Goal::new(infcx.tcx, at.param_env, predicate); let result = match delegate.evaluate_root_goal(goal, at.cause.span, None) { Ok(result) => result, @@ -98,7 +98,7 @@ impl<'me, 'tcx> ReplaceAliasWithInfer<'me, 'tcx> { infcx.tcx, self.at.cause.clone(), self.at.param_env, - ty::ProjectionPredicate { projection_term: alias_term, term: infer_term }, + ty::ProjectionClause { projection_term: alias_term, term: infer_term }, ); self.obligations.push(obligation); infer_term diff --git a/compiler/rustc_trait_selection/src/traits/auto_trait.rs b/compiler/rustc_trait_selection/src/traits/auto_trait.rs index c885406f6dcfb..10f9c5ffca163 100644 --- a/compiler/rustc_trait_selection/src/traits/auto_trait.rs +++ b/compiler/rustc_trait_selection/src/traits/auto_trait.rs @@ -637,7 +637,7 @@ impl<'tcx> AutoTraitFinder<'tcx> { } } - fn is_self_referential_projection(&self, p: ty::PolyProjectionPredicate<'tcx>) -> bool { + fn is_self_referential_projection(&self, p: ty::PolyProjectionClause<'tcx>) -> bool { if let Some(ty) = p.term().skip_binder().as_type() { matches!(ty.kind(), ty::Alias(_, proj @ ty::AliasTy { kind: ty::Projection { .. }, .. }) if proj == &p.skip_binder().projection_term.expect_ty()) } else { diff --git a/compiler/rustc_trait_selection/src/traits/mod.rs b/compiler/rustc_trait_selection/src/traits/mod.rs index eda63e09b1189..af09c1b942d1b 100644 --- a/compiler/rustc_trait_selection/src/traits/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/mod.rs @@ -257,7 +257,7 @@ fn set_projection_term_to_non_rigid<'tcx>( if let ty::ClauseKind::Projection(projection_pred) = clause.kind().skip_binder() { clause .kind() - .rebind(ty::ProjectionPredicate { + .rebind(ty::ProjectionClause { projection_term: projection_pred.projection_term, term: ty::set_aliases_to_non_rigid(tcx, projection_pred.term).skip_norm_wip(), }) diff --git a/compiler/rustc_trait_selection/src/traits/project.rs b/compiler/rustc_trait_selection/src/traits/project.rs index 7da8c68ff894a..3a870efd2e274 100644 --- a/compiler/rustc_trait_selection/src/traits/project.rs +++ b/compiler/rustc_trait_selection/src/traits/project.rs @@ -31,9 +31,9 @@ use crate::traits::normalize::{normalize_with_depth, normalize_with_depth_to}; use crate::traits::query::evaluate_obligation::InferCtxtExt as _; use crate::traits::select::ProjectionMatchesProjection; -pub type PolyProjectionObligation<'tcx> = Obligation<'tcx, ty::PolyProjectionPredicate<'tcx>>; +pub type PolyProjectionObligation<'tcx> = Obligation<'tcx, ty::PolyProjectionClause<'tcx>>; -pub type ProjectionObligation<'tcx> = Obligation<'tcx, ty::ProjectionPredicate<'tcx>>; +pub type ProjectionObligation<'tcx> = Obligation<'tcx, ty::ProjectionClause<'tcx>>; pub type ProjectionTermObligation<'tcx> = Obligation<'tcx, ty::AliasTerm<'tcx>>; @@ -52,14 +52,14 @@ pub enum ProjectionError<'tcx> { #[derive(PartialEq, Eq, Debug)] enum ProjectionCandidate<'tcx> { /// From a where-clause in the env or object type - ParamEnv(ty::PolyProjectionPredicate<'tcx>), + ParamEnv(ty::PolyProjectionClause<'tcx>), /// From the definition of `Trait` when you have something like /// `<::B as Trait2>::C`. - TraitDef(ty::PolyProjectionPredicate<'tcx>), + TraitDef(ty::PolyProjectionClause<'tcx>), /// Bounds specified on an object type - Object(ty::PolyProjectionPredicate<'tcx>), + Object(ty::PolyProjectionClause<'tcx>), /// From an "impl" (or a "pseudo-impl" returned by select) Select(Selection<'tcx>), @@ -868,7 +868,7 @@ fn assemble_candidates_from_clauses<'cx, 'tcx>( selcx: &mut SelectionContext<'cx, 'tcx>, obligation: &ProjectionTermObligation<'tcx>, candidate_set: &mut ProjectionCandidateSet<'tcx>, - ctor: fn(ty::PolyProjectionPredicate<'tcx>) -> ProjectionCandidate<'tcx>, + ctor: fn(ty::PolyProjectionClause<'tcx>) -> ProjectionCandidate<'tcx>, env_clauses: impl Iterator>, potentially_unnormalized_candidates: bool, ) { @@ -1371,7 +1371,7 @@ fn confirm_coroutine_candidate<'cx, 'tcx>( ); }; - let predicate = ty::ProjectionPredicate { + let predicate = ty::ProjectionClause { projection_term: obligation.predicate.with_args(tcx, trait_ref.args), term: ty.into(), }; @@ -1418,7 +1418,7 @@ fn confirm_future_candidate<'cx, 'tcx>( sym::Output ); - let predicate = ty::ProjectionPredicate { + let predicate = ty::ProjectionClause { projection_term: obligation.predicate.with_args(tcx, trait_ref.args), term: return_ty.into(), }; @@ -1463,7 +1463,7 @@ fn confirm_iterator_candidate<'cx, 'tcx>( sym::Item ); - let predicate = ty::ProjectionPredicate { + let predicate = ty::ProjectionClause { projection_term: obligation.predicate.with_args(tcx, trait_ref.args), term: yield_ty.into(), }; @@ -1516,7 +1516,7 @@ fn confirm_async_iterator_candidate<'cx, 'tcx>( }; let item_ty = args.type_at(0); - let predicate = ty::ProjectionPredicate { + let predicate = ty::ProjectionClause { projection_term: obligation.predicate.with_args(tcx, trait_ref.args), term: item_ty.into(), }; @@ -1595,7 +1595,7 @@ fn confirm_builtin_candidate<'cx, 'tcx>( bug!("unexpected builtin trait with associated type: {:?}", obligation.predicate); }; - let predicate = ty::ProjectionPredicate { + let predicate = ty::ProjectionClause { projection_term: ty::AliasTerm::new_from_args( tcx, ty::AliasTermKind::ProjectionTy { def_id: item_def_id }, @@ -1699,7 +1699,7 @@ fn confirm_callable_candidate<'cx, 'tcx>( fn_sig, flag, ) - .map_bound(|(trait_ref, ret_type)| ty::ProjectionPredicate { + .map_bound(|(trait_ref, ret_type)| ty::ProjectionClause { projection_term: ty::AliasTerm::new_from_args( tcx, ty::AliasTermKind::ProjectionTy { def_id: fn_once_output_def_id }, @@ -1754,7 +1754,7 @@ fn confirm_async_closure_candidate<'cx, 'tcx>( }; args.coroutine_closure_sig() - .rebind(ty::ProjectionPredicate { projection_term, term: term.into() }) + .rebind(ty::ProjectionClause { projection_term, term: term.into() }) } ty::FnDef(..) | ty::FnPtr(..) => { let bound_sig = self_ty.fn_sig(tcx); @@ -1787,7 +1787,7 @@ fn confirm_async_closure_candidate<'cx, 'tcx>( name => bug!("no such associated type: {name}"), }; - bound_sig.rebind(ty::ProjectionPredicate { projection_term, term: term.into() }) + bound_sig.rebind(ty::ProjectionClause { projection_term, term: term.into() }) } ty::Closure(_, args) => { let args = args.as_closure(); @@ -1815,7 +1815,7 @@ fn confirm_async_closure_candidate<'cx, 'tcx>( name => bug!("no such associated type: {name}"), }; - bound_sig.rebind(ty::ProjectionPredicate { projection_term, term: term.into() }) + bound_sig.rebind(ty::ProjectionClause { projection_term, term: term.into() }) } _ => bug!("expected callable type for AsyncFn candidate"), }; @@ -1908,7 +1908,7 @@ fn confirm_async_fn_kind_helper_candidate<'cx, 'tcx>( bug!(); }; - let predicate = ty::ProjectionPredicate { + let predicate = ty::ProjectionClause { projection_term: obligation.predicate.with_args(selcx.tcx(), obligation.predicate.args), term: ty::CoroutineClosureSignature::tupled_upvars_by_closure_kind( selcx.tcx(), @@ -1929,7 +1929,7 @@ fn confirm_async_fn_kind_helper_candidate<'cx, 'tcx>( fn confirm_param_env_candidate<'cx, 'tcx>( selcx: &mut SelectionContext<'cx, 'tcx>, obligation: &ProjectionTermObligation<'tcx>, - poly_cache_entry: ty::PolyProjectionPredicate<'tcx>, + poly_cache_entry: ty::PolyProjectionClause<'tcx>, potentially_unnormalized_candidate: bool, ) -> Progress<'tcx> { let infcx = selcx.infcx; diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index 9b4ee13bf1b63..88962e0d37471 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -27,8 +27,8 @@ use rustc_middle::ty::error::TypeErrorToStringExt; use rustc_middle::ty::print::{PrintTraitRefExt as _, with_no_trimmed_paths}; use rustc_middle::ty::{ self, CandidatePreferenceMode, CantBeErased, DeepRejectCtxt, GenericArgsRef, - PolyProjectionPredicate, SizedTraitKind, Ty, TyCtxt, TypeFoldable, TypeVisitableExt, - TypingMode, Unnormalized, Upcast, elaborate, may_use_unstable_feature, + PolyProjectionClause, SizedTraitKind, Ty, TyCtxt, TypeFoldable, TypeVisitableExt, TypingMode, + Unnormalized, Upcast, elaborate, may_use_unstable_feature, }; use rustc_next_trait_solver::solve::AliasBoundKind; use rustc_span::Symbol; @@ -1761,7 +1761,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { pub(super) fn match_projection_projections( &mut self, obligation: &ProjectionTermObligation<'tcx>, - env_predicate: PolyProjectionPredicate<'tcx>, + env_predicate: PolyProjectionClause<'tcx>, potentially_unnormalized_candidates: bool, ) -> ProjectionMatchesProjection { let def_id = obligation.predicate.expect_projection_def_id(); diff --git a/compiler/rustc_trait_selection/src/traits/structural_normalize.rs b/compiler/rustc_trait_selection/src/traits/structural_normalize.rs index 2556c2baffada..e5fff1eb0fd04 100644 --- a/compiler/rustc_trait_selection/src/traits/structural_normalize.rs +++ b/compiler/rustc_trait_selection/src/traits/structural_normalize.rs @@ -60,7 +60,7 @@ impl<'tcx> At<'_, 'tcx> { self.infcx.tcx, self.cause.clone(), self.param_env, - ty::ProjectionPredicate { projection_term: alias, term: new_infer }, + ty::ProjectionClause { projection_term: alias, term: new_infer }, ); fulfill_cx.register_predicate_obligation(self.infcx, obligation); diff --git a/compiler/rustc_trait_selection/src/traits/util.rs b/compiler/rustc_trait_selection/src/traits/util.rs index e611b4fc6b6ac..d4d6b9c9c47b6 100644 --- a/compiler/rustc_trait_selection/src/traits/util.rs +++ b/compiler/rustc_trait_selection/src/traits/util.rs @@ -36,7 +36,7 @@ pub fn expand_trait_aliases<'tcx>( clauses: impl IntoIterator, Span)>, ) -> ( Vec<(ty::PolyTraitPredicate<'tcx>, SmallVec<[Span; 1]>)>, - Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>, + Vec<(ty::PolyProjectionClause<'tcx>, Span)>, ) { let mut trait_preds = vec![]; let mut projection_preds = vec![]; diff --git a/compiler/rustc_ty_utils/src/ty.rs b/compiler/rustc_ty_utils/src/ty.rs index 39f0da47942e4..898197438f12b 100644 --- a/compiler/rustc_ty_utils/src/ty.rs +++ b/compiler/rustc_ty_utils/src/ty.rs @@ -262,7 +262,7 @@ impl<'tcx> TypeVisitor> for ImplTraitInTraitFinder<'_, 'tcx> { self.clauses.push( ty::Binder::bind_with_vars( - ty::ProjectionPredicate { + ty::ProjectionClause { projection_term: shifted_alias_ty.projection_to_alias_ty().into(), term: default_ty.into(), }, diff --git a/compiler/rustc_type_ir/src/flags.rs b/compiler/rustc_type_ir/src/flags.rs index 2db0c83098b54..7b0a098ad1948 100644 --- a/compiler/rustc_type_ir/src/flags.rs +++ b/compiler/rustc_type_ir/src/flags.rs @@ -418,7 +418,7 @@ impl FlagComputation { self.add_ty(a); self.add_ty(b); } - ty::PredicateKind::Clause(ty::ClauseKind::Projection(ty::ProjectionPredicate { + ty::PredicateKind::Clause(ty::ClauseKind::Projection(ty::ProjectionClause { projection_term, term, })) => { diff --git a/compiler/rustc_type_ir/src/inherent.rs b/compiler/rustc_type_ir/src/inherent.rs index 859996d67eb64..d2a26205bac72 100644 --- a/compiler/rustc_type_ir/src/inherent.rs +++ b/compiler/rustc_type_ir/src/inherent.rs @@ -462,7 +462,7 @@ pub trait Predicate>: + UpcastFrom> + UpcastFrom>> + UpcastFrom> - + UpcastFrom> + + UpcastFrom> + UpcastFrom> + UpcastFrom>> + IntoKind>> @@ -504,8 +504,8 @@ pub trait Clause>: + UpcastFrom>> + UpcastFrom> + UpcastFrom>> - + UpcastFrom> - + UpcastFrom>> + + UpcastFrom> + + UpcastFrom>> + IntoKind>> + Elaboratable { @@ -537,7 +537,7 @@ pub trait Clause>: .transpose() } - fn as_projection_clause(self) -> Option>> { + fn as_projection_clause(self) -> Option>> { self.kind() .map_bound( |clause| { diff --git a/compiler/rustc_type_ir/src/interner.rs b/compiler/rustc_type_ir/src/interner.rs index 037e02d345fa8..0cfa9574e4131 100644 --- a/compiler/rustc_type_ir/src/interner.rs +++ b/compiler/rustc_type_ir/src/interner.rs @@ -35,7 +35,7 @@ pub trait Interner: + IrPrint> + IrPrint> + IrPrint> - + IrPrint> + + IrPrint> + IrPrint> + IrPrint> + IrPrint> diff --git a/compiler/rustc_type_ir/src/ir_print.rs b/compiler/rustc_type_ir/src/ir_print.rs index 1b11665e1f574..5fd8f65c1a95c 100644 --- a/compiler/rustc_type_ir/src/ir_print.rs +++ b/compiler/rustc_type_ir/src/ir_print.rs @@ -5,7 +5,7 @@ use crate::{AliasConst, ClosureKind}; use crate::{ AliasTerm, AliasTy, Binder, CoercePredicate, ExistentialProjection, ExistentialTraitRef, FnSig, HostEffectClause, Interner, NormalizesTo, OutlivesClause, PatternKind, Placeholder, - ProjectionPredicate, Region, SubtypePredicate, TraitPredicate, TraitRef, + ProjectionClause, Region, SubtypePredicate, TraitPredicate, TraitRef, }; pub trait IrPrint { @@ -42,7 +42,7 @@ define_display_via_print!( TraitPredicate, ExistentialTraitRef, ExistentialProjection, - ProjectionPredicate, + ProjectionClause, NormalizesTo, SubtypePredicate, CoercePredicate, diff --git a/compiler/rustc_type_ir/src/predicate.rs b/compiler/rustc_type_ir/src/predicate.rs index 7907149e25fef..3520c049fea40 100644 --- a/compiler/rustc_type_ir/src/predicate.rs +++ b/compiler/rustc_type_ir/src/predicate.rs @@ -452,7 +452,7 @@ impl ty::Binder> { } } -/// A `ProjectionPredicate` for an `ExistentialTraitRef`. +/// A `ProjectionClause` for an `ExistentialTraitRef`. #[derive_where(Clone, Copy, Hash, PartialEq, Debug; I: Interner)] #[derive(TypeVisitable_Generic, GenericTypeVisitable, TypeFoldable_Generic, Lift_Generic)] #[cfg_attr( @@ -505,11 +505,11 @@ impl ExistentialProjection { ExistentialTraitRef::new_from_args(interner, def_id, args) } - pub fn with_self_ty(&self, interner: I, self_ty: I::Ty) -> ProjectionPredicate { + pub fn with_self_ty(&self, interner: I, self_ty: I::Ty) -> ProjectionClause { // otherwise the escaping regions would be captured by the binders debug_assert!(!self_ty.has_escaping_bound_vars()); - ProjectionPredicate { + ProjectionClause { projection_term: ty::AliasTerm::new( interner, interner.alias_term_kind_from_def_id(self.def_id.into()), @@ -519,7 +519,7 @@ impl ExistentialProjection { } } - pub fn erase_self_ty(interner: I, projection_predicate: ProjectionPredicate) -> Self { + pub fn erase_self_ty(interner: I, projection_predicate: ProjectionClause) -> Self { // Assert there is a Self. projection_predicate.projection_term.args.type_at(0); @@ -533,7 +533,7 @@ impl ExistentialProjection { } impl ty::Binder> { - pub fn with_self_ty(&self, cx: I, self_ty: I::Ty) -> ty::Binder> { + pub fn with_self_ty(&self, cx: I, self_ty: I::Ty) -> ty::Binder> { self.map_bound(|p| p.with_self_ty(cx, self_ty)) } @@ -552,7 +552,7 @@ impl ty::Binder> { /// normal trait predicate (`T: TraitRef<...>`) and one of these /// predicates. Form #2 is a broader form in that it also permits /// equality between arbitrary types. Processing an instance of -/// Form #2 eventually yields one of these `ProjectionPredicate` +/// Form #2 eventually yields one of these `ProjectionClause` /// instances to normalize the LHS. #[derive_where(Clone, Copy, Hash, PartialEq; I: Interner)] #[derive(TypeVisitable_Generic, GenericTypeVisitable, TypeFoldable_Generic, Lift_Generic)] @@ -560,19 +560,19 @@ impl ty::Binder> { feature = "nightly", derive(Decodable_NoContext, Encodable_NoContext, StableHash_NoContext) )] -pub struct ProjectionPredicate { +pub struct ProjectionClause { pub projection_term: ty::AliasTerm, pub term: I::Term, } -impl Eq for ProjectionPredicate {} +impl Eq for ProjectionClause {} -impl ProjectionPredicate { +impl ProjectionClause { pub fn self_ty(self) -> I::Ty { self.projection_term.self_ty() } - pub fn with_replaced_self_ty(self, interner: I, self_ty: I::Ty) -> ProjectionPredicate { + pub fn with_replaced_self_ty(self, interner: I, self_ty: I::Ty) -> ProjectionClause { Self { projection_term: self.projection_term.with_replaced_self_ty(interner, self_ty), ..self @@ -588,7 +588,7 @@ impl ProjectionPredicate { } } -impl ty::Binder> { +impl ty::Binder> { /// Returns the `DefId` of the trait of the associated item being projected. #[inline] pub fn trait_def_id(&self, cx: I) -> I::TraitId { @@ -609,9 +609,9 @@ impl ty::Binder> { } } -impl fmt::Debug for ProjectionPredicate { +impl fmt::Debug for ProjectionClause { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "ProjectionPredicate({:?}, {:?})", self.projection_term, self.term) + write!(f, "ProjectionClause({:?}, {:?})", self.projection_term, self.term) } } diff --git a/compiler/rustc_type_ir/src/predicate_kind.rs b/compiler/rustc_type_ir/src/predicate_kind.rs index e57f0f1e0cd8d..7b4e91f7410aa 100644 --- a/compiler/rustc_type_ir/src/predicate_kind.rs +++ b/compiler/rustc_type_ir/src/predicate_kind.rs @@ -28,8 +28,8 @@ pub enum ClauseKind { TypeOutlives(ty::OutlivesClause), /// `where ::Name == X`, approximately. - /// See the `ProjectionPredicate` struct for details. - Projection(ty::ProjectionPredicate), + /// See the `ProjectionClause` struct for details. + Projection(ty::ProjectionClause), /// Ensures that a const generic argument to a parameter `const N: u8` /// is of type `u8`. diff --git a/compiler/rustc_type_ir/src/relate/combine.rs b/compiler/rustc_type_ir/src/relate/combine.rs index 4c0fe9cd25724..29193f40959d3 100644 --- a/compiler/rustc_type_ir/src/relate/combine.rs +++ b/compiler/rustc_type_ir/src/relate/combine.rs @@ -180,14 +180,14 @@ where } (ty::ConstKind::Alias(ty::IsRigid::No, alias), _) if infcx.next_trait_solver() => { - relation.register_predicates([ty::ProjectionPredicate { + relation.register_predicates([ty::ProjectionClause { projection_term: alias.into(), term: b.into(), }]); Ok(b) } (_, ty::ConstKind::Alias(ty::IsRigid::No, alias)) if infcx.next_trait_solver() => { - relation.register_predicates([ty::ProjectionPredicate { + relation.register_predicates([ty::ProjectionClause { projection_term: alias.into(), term: a.into(), }]); diff --git a/compiler/rustc_type_ir/src/relate/solver_relating.rs b/compiler/rustc_type_ir/src/relate/solver_relating.rs index 849dcf4c5732b..1e8ff77e4d395 100644 --- a/compiler/rustc_type_ir/src/relate/solver_relating.rs +++ b/compiler/rustc_type_ir/src/relate/solver_relating.rs @@ -199,7 +199,7 @@ where self.goals.push(Goal::new( self.cx(), self.param_env, - ty::ProjectionPredicate { projection_term: alias.into(), term: new_var.into() }, + ty::ProjectionClause { projection_term: alias.into(), term: new_var.into() }, )); self.tys(new_var, b)?; } @@ -208,7 +208,7 @@ where self.goals.push(Goal::new( self.cx(), self.param_env, - ty::ProjectionPredicate { projection_term: alias.into(), term: new_var.into() }, + ty::ProjectionClause { projection_term: alias.into(), term: new_var.into() }, )); self.tys(a, new_var)?; } diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 9f972376c11ac..b7046744b2895 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -524,7 +524,7 @@ fn clean_hir_term<'tcx>( } fn clean_projection_predicate<'tcx>( - pred: ty::Binder<'tcx, ty::ProjectionPredicate<'tcx>>, + pred: ty::Binder<'tcx, ty::ProjectionClause<'tcx>>, cx: &mut DocContext<'tcx>, ) -> WherePredicate { WherePredicate::ProjectionPredicate { diff --git a/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs index 8ae27b2342d18..b9070f39296ad 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs @@ -17,7 +17,7 @@ use rustc_lint::LateContext; use rustc_middle::mir::Mutability; use rustc_middle::ty::adjustment::{Adjust, Adjustment, DerefAdjustKind, OverloadedDeref}; use rustc_middle::ty::{ - self, ClauseKind, GenericArg, GenericArgKind, GenericArgsRef, ParamTy, ProjectionPredicate, TraitPredicate, Ty, + self, ClauseKind, GenericArg, GenericArgKind, GenericArgsRef, ParamTy, ProjectionClause, TraitPredicate, Ty, }; use rustc_span::Symbol; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _; @@ -473,12 +473,12 @@ fn get_callee_generic_args_and_args<'tcx>( None } -/// Returns the `TraitPredicate`s and `ProjectionPredicate`s for a function's input type. +/// Returns the `TraitPredicate`s and `ProjectionClause`s for a function's input type. fn get_input_traits_and_projections<'tcx>( cx: &LateContext<'tcx>, callee_def_id: DefId, input: Ty<'tcx>, -) -> (Vec>, Vec>) { +) -> (Vec>, Vec>) { let mut trait_predicates = Vec::new(); let mut projection_predicates = Vec::new(); for clause in cx.tcx.param_env(callee_def_id).caller_bounds() { diff --git a/src/tools/clippy/clippy_lints/src/needless_borrows_for_generic_args.rs b/src/tools/clippy/clippy_lints/src/needless_borrows_for_generic_args.rs index 7b5635f8555a0..1ae9d8791954d 100644 --- a/src/tools/clippy/clippy_lints/src/needless_borrows_for_generic_args.rs +++ b/src/tools/clippy/clippy_lints/src/needless_borrows_for_generic_args.rs @@ -14,7 +14,7 @@ use rustc_infer::infer::TyCtxtInferExt as _; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::mir::{Rvalue, StatementKind}; use rustc_middle::ty::{ - self, ClauseKind, EarlyBinder, FnSig, GenericArg, GenericArgKind, ParamTy, ProjectionPredicate, Ty, Unnormalized, + self, ClauseKind, EarlyBinder, FnSig, GenericArg, GenericArgKind, ParamTy, ProjectionClause, Ty, Unnormalized, }; use rustc_session::impl_lint_pass; use rustc_span::SyntaxContext; @@ -328,7 +328,7 @@ fn has_ref_mut_self_method(cx: &LateContext<'_>, trait_def_id: DefId) -> bool { fn is_mixed_projection_predicate<'tcx>( cx: &LateContext<'tcx>, callee_def_id: DefId, - projection_predicate: &ProjectionPredicate<'tcx>, + projection_predicate: &ProjectionClause<'tcx>, ) -> bool { let generics = cx.tcx.generics_of(callee_def_id); // The predicate requires the projected type to equal a type parameter from the parent context. @@ -402,7 +402,7 @@ fn replace_types<'tcx>( new_ty: Ty<'tcx>, fn_sig: FnSig<'tcx>, arg_index: usize, - projection_predicates: &[ProjectionPredicate<'tcx>], + projection_predicates: &[ProjectionClause<'tcx>], args: &mut [GenericArg<'tcx>], ) -> bool { let mut replaced = DenseBitSet::new_empty(args.len()); diff --git a/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs b/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs index 49488c9da34a5..60f21b87f63cd 100644 --- a/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs +++ b/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs @@ -3,7 +3,7 @@ use rustc_hir::def_id::DefId; use rustc_hir::{Closure, Expr, ExprKind, StmtKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty; -use rustc_middle::ty::{ClauseKind, GenericClauses, ProjectionPredicate, TraitPredicate}; +use rustc_middle::ty::{ClauseKind, GenericClauses, ProjectionClause, TraitPredicate}; use rustc_session::declare_lint_pass; use rustc_span::{BytePos, Span, Symbol, sym}; @@ -64,7 +64,7 @@ fn get_projection_pred<'tcx>( cx: &LateContext<'tcx>, generics: GenericClauses<'tcx>, trait_pred: TraitPredicate<'tcx>, -) -> Option> { +) -> Option> { generics.clauses.iter().find_map(|(clause, _)| { if let ClauseKind::Projection(pred) = clause.kind().skip_binder() { let projection_pred = cx.tcx.instantiate_bound_regions_with_erased(clause.kind().rebind(pred)); diff --git a/tests/ui/attributes/dump-clauses.stderr b/tests/ui/attributes/dump-clauses.stderr index 0a91751c59ba2..d5726fe60e602 100644 --- a/tests/ui/attributes/dump-clauses.stderr +++ b/tests/ui/attributes/dump-clauses.stderr @@ -33,7 +33,7 @@ error: rustc_dump_item_bounds LL | type Assoc: std::ops::Deref | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | - = note: Binder { value: ProjectionPredicate(Alias { kind: ProjectionTy { def_id: DefId(..) }, args: [Alias(No, Alias { kind: Projection { def_id: DefId(..) }, args: [Self/#0, T/#1, P/#2], .. })], .. }, Term::Ty(())), bound_vars: [] } + = note: Binder { value: ProjectionClause(Alias { kind: ProjectionTy { def_id: DefId(..) }, args: [Alias(No, Alias { kind: Projection { def_id: DefId(..) }, args: [Self/#0, T/#1, P/#2], .. })], .. }, Term::Ty(())), bound_vars: [] } = note: Binder { value: TraitPredicate(<>::Assoc

as std::ops::Deref>, polarity:Positive), bound_vars: [] } = note: Binder { value: TraitPredicate(<>::Assoc

as std::marker::Sized>, polarity:Positive), bound_vars: [] } diff --git a/tests/ui/supertrait-shadowing/assoc-type-clauses.stderr b/tests/ui/supertrait-shadowing/assoc-type-clauses.stderr index 3a42da43f3ba1..f2e8347e17fb4 100644 --- a/tests/ui/supertrait-shadowing/assoc-type-clauses.stderr +++ b/tests/ui/supertrait-shadowing/assoc-type-clauses.stderr @@ -6,7 +6,7 @@ LL | fn a_bound>() {} | = note: Binder { value: TraitPredicate(, polarity:Positive), bound_vars: [] } = note: Binder { value: TraitPredicate(, polarity:Positive), bound_vars: [] } - = note: Binder { value: ProjectionPredicate(Alias { kind: ProjectionTy { def_id: DefId(0:4 ~ assoc_type_clauses[HASH]::A::Assoc) }, args: [T/#0], .. }, Term::Ty(i8)), bound_vars: [] } + = note: Binder { value: ProjectionClause(Alias { kind: ProjectionTy { def_id: DefId(0:4 ~ assoc_type_clauses[HASH]::A::Assoc) }, args: [T/#0], .. }, Term::Ty(i8)), bound_vars: [] } error: rustc_dump_clauses --> $DIR/assoc-type-clauses.rs:32:1 @@ -16,7 +16,7 @@ LL | fn b_bound>() {} | = note: Binder { value: TraitPredicate(, polarity:Positive), bound_vars: [] } = note: Binder { value: TraitPredicate(, polarity:Positive), bound_vars: [] } - = note: Binder { value: ProjectionPredicate(Alias { kind: ProjectionTy { def_id: DefId(0:9 ~ assoc_type_clauses[HASH]::B::Assoc) }, args: [T/#0], .. }, Term::Ty(i16)), bound_vars: [] } + = note: Binder { value: ProjectionClause(Alias { kind: ProjectionTy { def_id: DefId(0:9 ~ assoc_type_clauses[HASH]::B::Assoc) }, args: [T/#0], .. }, Term::Ty(i16)), bound_vars: [] } error: rustc_dump_clauses --> $DIR/assoc-type-clauses.rs:39:1 @@ -26,7 +26,7 @@ LL | fn c_bound>() {} | = note: Binder { value: TraitPredicate(, polarity:Positive), bound_vars: [] } = note: Binder { value: TraitPredicate(, polarity:Positive), bound_vars: [] } - = note: Binder { value: ProjectionPredicate(Alias { kind: ProjectionTy { def_id: DefId(0:9 ~ assoc_type_clauses[HASH]::B::Assoc) }, args: [T/#0], .. }, Term::Ty(i16)), bound_vars: [] } + = note: Binder { value: ProjectionClause(Alias { kind: ProjectionTy { def_id: DefId(0:9 ~ assoc_type_clauses[HASH]::B::Assoc) }, args: [T/#0], .. }, Term::Ty(i16)), bound_vars: [] } error: aborting due to 3 previous errors From 169bd22aeae344bd7ff3d5d2720e11174182e343 Mon Sep 17 00:00:00 2001 From: Ada Alakbarova Date: Wed, 12 Aug 2026 09:53:15 +0200 Subject: [PATCH 13/26] rename `TraitPredicate` to `TraitClause` --- .../src/diagnostics/conflict_errors.rs | 2 +- .../src/diagnostics/mutability_errors.rs | 2 +- .../src/type_check/canonical.rs | 4 +- .../src/obligation_forest/graphviz.rs | 4 +- .../rustc_hir_analysis/src/check/wfcheck.rs | 2 +- .../src/coherence/builtin.rs | 4 +- .../src/collect/clauses_of.rs | 4 +- .../src/hir_ty_lowering/dyn_trait.rs | 6 +- .../src/hir_ty_lowering/errors.rs | 2 +- .../src/hir_ty_lowering/mod.rs | 12 +-- .../src/impl_wf_check/min_specialization.rs | 4 +- .../rustc_hir_analysis/src/variance/mod.rs | 2 +- compiler/rustc_hir_typeck/src/expr.rs | 4 +- .../src/fn_ctxt/inspect_obligations.rs | 6 +- compiler/rustc_hir_typeck/src/method/probe.rs | 2 +- .../rustc_hir_typeck/src/method/suggest.rs | 14 ++-- compiler/rustc_infer/src/traits/mod.rs | 6 +- compiler/rustc_infer/src/traits/util.rs | 4 +- compiler/rustc_lint/src/builtin.rs | 2 +- compiler/rustc_lint/src/internal.rs | 4 +- .../src/opaque_hidden_inferred_bound.rs | 4 +- compiler/rustc_middle/src/traits/mod.rs | 8 +- compiler/rustc_middle/src/traits/select.rs | 10 +-- compiler/rustc_middle/src/ty/context.rs | 12 +-- compiler/rustc_middle/src/ty/diagnostics.rs | 6 +- .../rustc_middle/src/ty/elaborate_impl.rs | 8 +- compiler/rustc_middle/src/ty/mod.rs | 4 +- compiler/rustc_middle/src/ty/predicate.rs | 41 +++++----- compiler/rustc_middle/src/ty/print/pretty.rs | 64 ++++++++-------- .../rustc_middle/src/ty/structural_impls.rs | 2 +- .../src/impossible_clauses.rs | 2 +- .../src/solve/effect_goals.rs | 2 +- .../src/solve/normalizes_to.rs | 2 +- .../src/solve/trait_goals.rs | 76 +++++++++---------- compiler/rustc_privacy/src/lib.rs | 2 +- compiler/rustc_public/src/ty/tys.rs | 14 +++- .../src/unstable/convert/stable/ty.rs | 18 ++--- .../error_reporting/infer/note_and_explain.rs | 5 +- .../src/error_reporting/traits/ambiguity.rs | 10 +-- .../traits/fulfillment_errors.rs | 62 +++++++-------- .../traits/on_unimplemented.rs | 6 +- .../src/error_reporting/traits/suggestions.rs | 70 ++++++++--------- .../src/solve/delegate.rs | 2 +- .../src/solve/fulfill/derive_errors.rs | 8 +- .../src/traits/auto_trait.rs | 14 ++-- .../src/traits/dyn_compatibility.rs | 4 +- .../src/traits/select/candidate_assembly.rs | 2 +- .../src/traits/select/confirmation.rs | 4 +- .../src/traits/select/mod.rs | 30 ++++---- .../rustc_trait_selection/src/traits/util.rs | 20 ++--- .../rustc_trait_selection/src/traits/wf.rs | 6 +- compiler/rustc_type_ir/src/elaborate.rs | 6 +- compiler/rustc_type_ir/src/error.rs | 2 +- compiler/rustc_type_ir/src/generic_visit.rs | 2 +- compiler/rustc_type_ir/src/inherent.rs | 8 +- compiler/rustc_type_ir/src/interner.rs | 2 +- compiler/rustc_type_ir/src/ir_print.rs | 4 +- compiler/rustc_type_ir/src/macros.rs | 2 +- compiler/rustc_type_ir/src/predicate.rs | 43 +++++------ compiler/rustc_type_ir/src/predicate_kind.rs | 2 +- compiler/rustc_type_ir/src/relate.rs | 10 +-- compiler/rustc_type_ir/src/serialize.rs | 2 +- compiler/rustc_type_ir/src/unnormalized.rs | 10 +-- src/librustdoc/clean/mod.rs | 2 +- .../derive/derive_partial_eq_without_eq.rs | 6 +- .../clippy/clippy_lints/src/eta_reduction.rs | 2 +- .../src/methods/unnecessary_to_owned.rs | 8 +- .../clippy_lints/src/needless_maybe_sized.rs | 4 +- src/tools/clippy/clippy_lints/src/ranges.rs | 4 +- .../src/unit_return_expecting_ord.rs | 6 +- tests/ui/associated-types/issue-65774-1.rs | 2 +- tests/ui/associated-types/issue-65774-2.rs | 2 +- tests/ui/attributes/dump-clauses.stderr | 34 ++++----- .../byte-string-u8-validation.rs | 2 +- .../byte-string-u8-validation.stderr | 2 +- .../assoc-type-clauses.rs | 12 +-- .../assoc-type-clauses.stderr | 12 +-- tests/ui/traits/cache-reached-depth-ice.rs | 2 +- .../ui/traits/cache-reached-depth-ice.stderr | 2 +- .../issue-83538-tainted-cache-after-cycle.rs | 8 +- ...sue-83538-tainted-cache-after-cycle.stderr | 8 +- .../traits/issue-85360-eval-obligation-ice.rs | 4 +- .../issue-85360-eval-obligation-ice.stderr | 4 +- tests/ui/traits/project-modulo-regions.rs | 4 +- .../project-modulo-regions.with_clause.stderr | 2 +- ...oject-modulo-regions.without_clause.stderr | 2 +- .../in-where-clause.stderr | 2 +- 87 files changed, 416 insertions(+), 421 deletions(-) diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index 7267ae113de3e..0e2024f822b96 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -691,7 +691,7 @@ impl<'diag, 'tcx> MirBorrowckCtxt<'_, 'diag, 'tcx> { if !clauses.instantiate_identity(tcx).clauses.iter().any(|clause| { clause.as_trait_clause().is_some_and(|tc| { tc.self_ty().skip_binder().is_param(param.index) - && tc.polarity() == ty::PredicatePolarity::Positive + && tc.polarity() == ty::ClausePolarity::Positive && supertrait_def_ids(tcx, tc.def_id()) .flat_map(|trait_did| tcx.associated_items(trait_did).in_definition_order()) .any(|item| item.is_method()) diff --git a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs index 49e6dc334ff80..62cad6a874866 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs @@ -1228,7 +1228,7 @@ impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> { tcx.clauses_of(callee_def_id).instantiate(tcx, generic_args).clauses.iter().any( |clause| { clause.as_trait_clause().is_some_and(|trait_pred| { - trait_pred.polarity() == ty::PredicatePolarity::Positive + trait_pred.polarity() == ty::ClausePolarity::Positive && tcx.fn_trait_kind_from_def_id(trait_pred.def_id()) == Some(ty::ClosureKind::Fn) && trait_pred.self_ty().skip_binder().peel_refs() diff --git a/compiler/rustc_borrowck/src/type_check/canonical.rs b/compiler/rustc_borrowck/src/type_check/canonical.rs index bc2c75f0c01a4..e4307e0481e5c 100644 --- a/compiler/rustc_borrowck/src/type_check/canonical.rs +++ b/compiler/rustc_borrowck/src/type_check/canonical.rs @@ -131,9 +131,9 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { category: ConstraintCategory<'tcx>, ) { self.prove_clause( - ty::ClauseKind::Trait(ty::TraitPredicate { + ty::ClauseKind::Trait(ty::TraitClause { trait_ref, - polarity: ty::PredicatePolarity::Positive, + polarity: ty::ClausePolarity::Positive, }), locations, category, diff --git a/compiler/rustc_data_structures/src/obligation_forest/graphviz.rs b/compiler/rustc_data_structures/src/obligation_forest/graphviz.rs index 65a24366db837..9def3d98fe09d 100644 --- a/compiler/rustc_data_structures/src/obligation_forest/graphviz.rs +++ b/compiler/rustc_data_structures/src/obligation_forest/graphviz.rs @@ -18,8 +18,8 @@ impl ObligationForest { /// A few post-processing that you might want to do make the forest easier to visualize: /// /// * `sed 's,std::[a-z]*::,,g'` — Deletes the `std::::` prefix of paths. - /// * `sed 's,"Binder(TraitPredicate(<\(.*\)>)) (\([^)]*\))","\1 (\2)",'` — Transforms - /// `Binder(TraitPredicate())` into just ``. + /// * `sed 's,"Binder(TraitClause(<\(.*\)>)) (\([^)]*\))","\1 (\2)",'` — Transforms + /// `Binder(TraitClause())` into just ``. #[allow(dead_code)] pub fn dump_graphviz>(&self, dir: P, description: &str) { static COUNTER: AtomicUsize = AtomicUsize::new(0); diff --git a/compiler/rustc_hir_analysis/src/check/wfcheck.rs b/compiler/rustc_hir_analysis/src/check/wfcheck.rs index 9a498837b1f4d..12b69768c63df 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -1323,7 +1323,7 @@ fn check_impl<'tcx>( trait_ref, ); let trait_pred = - ty::TraitPredicate { trait_ref, polarity: ty::PredicatePolarity::Positive }; + ty::TraitClause { trait_ref, polarity: ty::ClausePolarity::Positive }; let mut obligations = traits::wf::trait_obligations( wfcx.infcx, wfcx.param_env, diff --git a/compiler/rustc_hir_analysis/src/coherence/builtin.rs b/compiler/rustc_hir_analysis/src/coherence/builtin.rs index 3b57f45e684f7..06d336298a42c 100644 --- a/compiler/rustc_hir_analysis/src/coherence/builtin.rs +++ b/compiler/rustc_hir_analysis/src/coherence/builtin.rs @@ -924,9 +924,9 @@ fn infringing_fields_error<'tcx>( .or_default() .push(error.obligation.cause.span); } - if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(ty::TraitPredicate { + if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(ty::TraitClause { trait_ref, - polarity: ty::PredicatePolarity::Positive, + polarity: ty::ClausePolarity::Positive, .. })) = error_predicate.kind().skip_binder() { diff --git a/compiler/rustc_hir_analysis/src/collect/clauses_of.rs b/compiler/rustc_hir_analysis/src/collect/clauses_of.rs index 1ee647fd61a33..488b9a09e6106 100644 --- a/compiler/rustc_hir_analysis/src/collect/clauses_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/clauses_of.rs @@ -720,7 +720,7 @@ pub(super) fn implied_clauses_with_filter<'tcx>( for &(clause, span) in implied_bounds { debug!("superbound: {:?}", clause); if let ty::ClauseKind::Trait(bound) = clause.kind().skip_binder() - && bound.polarity == ty::PredicatePolarity::Positive + && bound.polarity == ty::ClausePolarity::Positive { tcx.at(span).explicit_super_clauses_of(bound.def_id()); } @@ -730,7 +730,7 @@ pub(super) fn implied_clauses_with_filter<'tcx>( for &(clause, span) in implied_bounds { debug!("superbound: {:?}", clause); if let ty::ClauseKind::Trait(bound) = clause.kind().skip_binder() - && bound.polarity == ty::PredicatePolarity::Positive + && bound.polarity == ty::ClausePolarity::Positive { tcx.at(span).explicit_implied_clauses_of(bound.def_id()); } diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_trait.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_trait.rs index db6a348b8ff9e..ca0d47f38d0a1 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_trait.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_trait.rs @@ -207,7 +207,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { if let Some((principal_trait, ref spans)) = principal_trait { let principal_trait = principal_trait.map_bound(|trait_pred| { - assert_eq!(trait_pred.polarity, ty::PredicatePolarity::Positive); + assert_eq!(trait_pred.polarity, ty::ClausePolarity::Positive); trait_pred.trait_ref }); @@ -350,7 +350,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { let principal_trait_ref = principal_trait.map(|(trait_pred, spans)| { trait_pred.map_bound(|trait_pred| { let trait_ref = trait_pred.trait_ref; - assert_eq!(trait_pred.polarity, ty::PredicatePolarity::Positive); + assert_eq!(trait_pred.polarity, ty::ClausePolarity::Positive); assert_eq!(trait_ref.self_ty(), dummy_self); let span = *spans.first().unwrap(); @@ -423,7 +423,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { let mut auto_trait_predicates: Vec<_> = auto_traits .into_iter() .map(|(trait_pred, _)| { - assert_eq!(trait_pred.polarity(), ty::PredicatePolarity::Positive); + assert_eq!(trait_pred.polarity(), ty::ClausePolarity::Positive); assert_eq!(trait_pred.self_ty().skip_binder(), dummy_self); ty::Binder::dummy(ty::ExistentialPredicate::AutoTrait(trait_pred.def_id())) diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs index e5dbae16d07d4..6207b3fdea6a9 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs @@ -1485,7 +1485,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { pub fn report_trait_object_addition_traits( &self, - regular_traits: &Vec<(ty::PolyTraitPredicate<'tcx>, SmallVec<[Span; 1]>)>, + regular_traits: &Vec<(ty::PolyTraitClause<'tcx>, SmallVec<[Span; 1]>)>, ) -> ErrorGuaranteed { // we use the last span to point at the traits themselves, // and all other preceding spans are trait alias expansions. diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs index c65e9bdbd211e..1f7821d0b500e 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs @@ -996,9 +996,9 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { let polarity = match polarity { hir::BoundPolarity::Positive | hir::BoundPolarity::Maybe(_) => { - ty::PredicatePolarity::Positive + ty::ClausePolarity::Positive } - hir::BoundPolarity::Negative(_) => ty::PredicatePolarity::Negative, + hir::BoundPolarity::Negative(_) => ty::ClausePolarity::Negative, }; let [leading_segments @ .., segment] = trait_ref.path.segments else { bug!() }; @@ -1047,7 +1047,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { | PredicateFilter::SelfTraitThatDefines(..) | PredicateFilter::SelfAndAssociatedTypeBounds => { let bound = poly_trait_ref.map_bound(|trait_ref| { - ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, polarity }) + ty::ClauseKind::Trait(ty::TraitClause { trait_ref, polarity }) }); let bound = (bound.upcast(tcx), span); // FIXME(-Znext-solver): We can likely remove this hack once the @@ -1102,7 +1102,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { | PredicateFilter::SelfAndAssociatedTypeBounds => { match constness { hir::BoundConstness::Always(_) => { - if polarity == ty::PredicatePolarity::Positive { + if polarity == ty::ClausePolarity::Positive { bounds.push(( poly_trait_ref .to_host_effect_clause(tcx, ty::BoundConstness::Const), @@ -1128,7 +1128,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => { match constness { hir::BoundConstness::Maybe(_) => { - if polarity == ty::PredicatePolarity::Positive { + if polarity == ty::ClausePolarity::Positive { bounds.push(( poly_trait_ref .to_host_effect_clause(tcx, ty::BoundConstness::Maybe), @@ -1150,7 +1150,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { // Don't register any associated item constraints for negative bounds, // since we should have emitted an error for them earlier, and they // would not be well-formed! - if polarity == ty::PredicatePolarity::Negative { + if polarity == ty::ClausePolarity::Negative { self.dcx().span_delayed_bug( constraint.span, "negative trait bounds should not have assoc item constraints", diff --git a/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs b/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs index 42d9b4cdbf8c5..cec65615111a7 100644 --- a/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs +++ b/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs @@ -414,7 +414,7 @@ fn check_specialization_on<'tcx>( _ if clause.is_global() => Ok(()), // We allow specializing on explicitly marked traits with no associated // items. - ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, polarity: _ }) => { + ty::ClauseKind::Trait(ty::TraitClause { trait_ref, polarity: _ }) => { if matches!( trait_specialization_kind(tcx, clause), Some(TraitSpecializationKind::Marker) @@ -463,7 +463,7 @@ fn trait_specialization_kind<'tcx>( clause: ty::Clause<'tcx>, ) -> Option { match clause.kind().skip_binder() { - ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, polarity: _ }) => { + ty::ClauseKind::Trait(ty::TraitClause { trait_ref, polarity: _ }) => { Some(tcx.trait_def(trait_ref.def_id).specialization_kind) } ty::ClauseKind::RegionOutlives(_) diff --git a/compiler/rustc_hir_analysis/src/variance/mod.rs b/compiler/rustc_hir_analysis/src/variance/mod.rs index e595ccab47058..163cd5ab5bfbc 100644 --- a/compiler/rustc_hir_analysis/src/variance/mod.rs +++ b/compiler/rustc_hir_analysis/src/variance/mod.rs @@ -194,7 +194,7 @@ fn variance_of_opaque( // which thus mentions `'a` and should thus accept hidden types that borrow 'a // instead of requiring an additional `+ 'a`. match clause.kind().skip_binder() { - ty::ClauseKind::Trait(ty::TraitPredicate { + ty::ClauseKind::Trait(ty::TraitClause { trait_ref: ty::TraitRef { def_id: _, args, .. }, polarity: _, }) diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index cbbd66f648eb8..6ebf382083f25 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -3575,9 +3575,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ocx.register_obligations(traits::predicates_for_generics( |idx, span| { cause.clone().derived_cause( - ty::Binder::dummy(ty::TraitPredicate { + ty::Binder::dummy(ty::TraitClause { trait_ref: impl_trait_ref, - polarity: ty::PredicatePolarity::Positive, + polarity: ty::ClausePolarity::Positive, }), |derived| { ObligationCauseCode::ImplDerived(Box::new(traits::ImplDerivedCause { diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/inspect_obligations.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/inspect_obligations.rs index e6de8b55ef2f9..8b76a5eb44db7 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/inspect_obligations.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/inspect_obligations.rs @@ -171,11 +171,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { predicate: ty::Predicate<'tcx>, ) -> Option { // The predicates we are looking for look like - // `TraitPredicate(>, polarity:Positive)`. + // `TraitClause(>, polarity:Positive)`. // They will have no bound variables. match predicate.kind().no_bound_vars() { - Some(ty::PredicateKind::Clause(ty::ClauseKind::Trait(ty::TraitPredicate { - polarity: ty::PredicatePolarity::Positive, + Some(ty::PredicateKind::Clause(ty::ClauseKind::Trait(ty::TraitClause { + polarity: ty::ClausePolarity::Positive, trait_ref, }))) if trait_ref.def_id == from_trait && self.shallow_resolve(trait_ref.self_ty()).kind() diff --git a/compiler/rustc_hir_typeck/src/method/probe.rs b/compiler/rustc_hir_typeck/src/method/probe.rs index b2e0a3bd7a195..8cf6cfbc8fffa 100644 --- a/compiler/rustc_hir_typeck/src/method/probe.rs +++ b/compiler/rustc_hir_typeck/src/method/probe.rs @@ -1139,7 +1139,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { for (bound_trait_pred, _) in traits::expand_trait_aliases(self.tcx, [(trait_ref.upcast(self.tcx), self.span)]).0 { - assert_eq!(bound_trait_pred.polarity(), ty::PredicatePolarity::Positive); + assert_eq!(bound_trait_pred.polarity(), ty::ClausePolarity::Positive); let bound_trait_ref = bound_trait_pred.map_bound(|pred| pred.trait_ref); for item in self.impl_or_trait_item(bound_trait_ref.def_id()) { if !self.has_applicable_self(&item) { diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index a22b6f746a952..05062155915d6 100644 --- a/compiler/rustc_hir_typeck/src/method/suggest.rs +++ b/compiler/rustc_hir_typeck/src/method/suggest.rs @@ -121,7 +121,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred)) = predicate.kind().as_ref().skip_binder() { - let ty::TraitPredicate { trait_ref: ty::TraitRef { args, .. }, .. } = trait_pred; + let ty::TraitClause { trait_ref: ty::TraitRef { args, .. }, .. } = trait_pred; if args.is_empty() { return false; } @@ -1949,7 +1949,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { match pred.kind().skip_binder() { ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => { self.tcx.is_lang_item(pred.def_id(), LangItem::Sized) - && pred.polarity == ty::PredicatePolarity::Positive + && pred.polarity == ty::ClausePolarity::Positive } _ => false, } @@ -3543,7 +3543,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } foreign_preds - .sort_by_key(|(_, pred): &(_, ty::TraitPredicate<'_>)| pred.trait_ref.to_string()); + .sort_by_key(|(_, pred): &(_, ty::TraitClause<'_>)| pred.trait_ref.to_string()); for (_, pred) in &foreign_preds { let ty = pred.self_ty(); @@ -3587,7 +3587,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Returns Some(list_of_derives) if possible, or None if not. fn consider_suggesting_derives_for_ty( &self, - trait_pred: ty::TraitPredicate<'tcx>, + trait_pred: ty::TraitClause<'tcx>, adt: ty::AdtDef<'tcx>, ) -> Option> { let diagnostic_name = self.tcx.get_diagnostic_name(trait_pred.def_id())?; @@ -4848,9 +4848,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } }), ); - let trait_pred = ty::Binder::dummy(ty::TraitPredicate { + let trait_pred = ty::Binder::dummy(ty::TraitClause { trait_ref, - polarity: ty::PredicatePolarity::Positive, + polarity: ty::ClausePolarity::Positive, }); let obligation = Obligation::new(self.tcx, self.misc(rcvr.span), self.param_env, trait_ref); self.err_ctxt().note_different_trait_with_same_name(err, &obligation, trait_pred) @@ -4947,7 +4947,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fn suggest_hashmap_on_unsatisfied_hashset_buildhasher( &self, err: &mut Diag<'_>, - pred: &ty::TraitPredicate<'_>, + pred: &ty::TraitClause<'_>, adt: ty::AdtDef<'_>, ) -> bool { if self.tcx.is_diagnostic_item(sym::HashSet, adt.did()) diff --git a/compiler/rustc_infer/src/traits/mod.rs b/compiler/rustc_infer/src/traits/mod.rs index 86aae77adcf8e..b3552bc68d517 100644 --- a/compiler/rustc_infer/src/traits/mod.rs +++ b/compiler/rustc_infer/src/traits/mod.rs @@ -87,8 +87,8 @@ impl Hash for Obligation<'_, T> { } pub type PredicateObligation<'tcx> = Obligation<'tcx, ty::Predicate<'tcx>>; -pub type TraitObligation<'tcx> = Obligation<'tcx, ty::TraitPredicate<'tcx>>; -pub type PolyTraitObligation<'tcx> = Obligation<'tcx, ty::PolyTraitPredicate<'tcx>>; +pub type TraitObligation<'tcx> = Obligation<'tcx, ty::TraitClause<'tcx>>; +pub type PolyTraitObligation<'tcx> = Obligation<'tcx, ty::PolyTraitClause<'tcx>>; pub type PredicateObligations<'tcx> = ThinVec>; @@ -175,7 +175,7 @@ impl<'tcx, O> Obligation<'tcx, O> { } impl<'tcx> PolyTraitObligation<'tcx> { - pub fn polarity(&self) -> ty::PredicatePolarity { + pub fn polarity(&self) -> ty::ClausePolarity { self.predicate.skip_binder().polarity } diff --git a/compiler/rustc_infer/src/traits/util.rs b/compiler/rustc_infer/src/traits/util.rs index 2630c8b125418..cc29546adb880 100644 --- a/compiler/rustc_infer/src/traits/util.rs +++ b/compiler/rustc_infer/src/traits/util.rs @@ -81,7 +81,7 @@ impl<'tcx> Elaboratable> for PredicateObligation<'tcx> { &self, clause: ty::Clause<'tcx>, span: Span, - parent_trait_pred: ty::PolyTraitPredicate<'tcx>, + parent_trait_pred: ty::PolyTraitClause<'tcx>, index: usize, ) -> Self { let cause = self.cause.clone().derived_cause(parent_trait_pred, |derived| { @@ -126,7 +126,7 @@ pub fn transitive_bounds_that_define_assoc_item<'tcx>( .map(Unnormalized::skip_norm_wip) .map(|(clause, _)| clause.instantiate_supertrait(tcx, trait_ref)) .filter_map(|clause| clause.as_trait_clause()) - .filter(|clause| clause.polarity() == ty::PredicatePolarity::Positive) + .filter(|clause| clause.polarity() == ty::ClausePolarity::Positive) .map(|clause| clause.map_bound(|clause| clause.trait_ref)), ); diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index 627fb962d5dbf..370614d5d8ebc 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -557,7 +557,7 @@ fn type_implements_negative_copy_modulo_regions<'tcx>( ) -> bool { let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env); let trait_ref = ty::TraitRef::new(tcx, tcx.require_lang_item(LangItem::Copy, DUMMY_SP), [ty]); - let pred = ty::TraitPredicate { trait_ref, polarity: ty::PredicatePolarity::Negative }; + let pred = ty::TraitClause { trait_ref, polarity: ty::ClausePolarity::Negative }; let obligation = traits::Obligation { cause: traits::ObligationCause::dummy(), param_env, diff --git a/compiler/rustc_lint/src/internal.rs b/compiler/rustc_lint/src/internal.rs index 454e99f2d29e0..2cac8551f1bfb 100644 --- a/compiler/rustc_lint/src/internal.rs +++ b/compiler/rustc_lint/src/internal.rs @@ -7,7 +7,7 @@ use rustc_hir as hir; use rustc_hir::def::Res; use rustc_hir::def_id::DefId; use rustc_hir::{Expr, ExprKind, HirId, find_attr}; -use rustc_middle::ty::{self, GenericArgsRef, PredicatePolarity}; +use rustc_middle::ty::{self, ClausePolarity, GenericArgsRef}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::hygiene::{ExpnKind, MacroKind}; use rustc_span::{Span, sym}; @@ -135,7 +135,7 @@ fn has_unstable_into_iter_predicate<'tcx>( continue; }; if trait_clause.def_id() != into_iterator_def_id - || trait_clause.polarity() != PredicatePolarity::Positive + || trait_clause.polarity() != ClausePolarity::Positive { continue; } diff --git a/compiler/rustc_lint/src/opaque_hidden_inferred_bound.rs b/compiler/rustc_lint/src/opaque_hidden_inferred_bound.rs index d9dfe5fa7de0c..78030e9b17b1b 100644 --- a/compiler/rustc_lint/src/opaque_hidden_inferred_bound.rs +++ b/compiler/rustc_lint/src/opaque_hidden_inferred_bound.rs @@ -1,7 +1,7 @@ use rustc_hir::{self as hir, AmbigArg}; use rustc_infer::infer::TyCtxtInferExt; use rustc_macros::{Diagnostic, Subdiagnostic}; -use rustc_middle::ty::print::{PrintTraitPredicateExt as _, TraitPredPrintModifiersAndPath}; +use rustc_middle::ty::print::{PrintTraitClauseExt as _, TraitClausePrintModifiersAndPath}; use rustc_middle::ty::{self, BottomUpFolder, Ty, TypeFoldable, Unnormalized}; use rustc_session::{declare_lint, declare_lint_pass}; use rustc_span::{Span, kw}; @@ -229,5 +229,5 @@ struct OpaqueHiddenInferredBoundLint<'tcx> { struct AddBound<'tcx> { #[primary_span] suggest_span: Span, - trait_ref: TraitPredPrintModifiersAndPath<'tcx>, + trait_ref: TraitClausePrintModifiersAndPath<'tcx>, } diff --git a/compiler/rustc_middle/src/traits/mod.rs b/compiler/rustc_middle/src/traits/mod.rs index b8cd0791a783e..47b248f26c300 100644 --- a/compiler/rustc_middle/src/traits/mod.rs +++ b/compiler/rustc_middle/src/traits/mod.rs @@ -105,7 +105,7 @@ impl<'tcx> ObligationCause<'tcx> { pub fn derived_cause( mut self, - parent_trait_pred: ty::PolyTraitPredicate<'tcx>, + parent_trait_pred: ty::PolyTraitClause<'tcx>, variant: impl FnOnce(DerivedCause<'tcx>) -> ObligationCauseCode<'tcx>, ) -> ObligationCause<'tcx> { /*! @@ -491,7 +491,7 @@ impl<'tcx> ObligationCauseCode<'tcx> { /// Returns the base obligation and the base trait predicate, if any, ignoring /// derived obligations. - pub fn peel_derives_with_predicate(&self) -> (&Self, Option>) { + pub fn peel_derives_with_predicate(&self) -> (&Self, Option>) { let mut base_cause = self; let mut base_trait_pred = None; while let Some((parent_code, parent_pred)) = base_cause.parent_with_predicate() { @@ -504,7 +504,7 @@ impl<'tcx> ObligationCauseCode<'tcx> { (base_cause, base_trait_pred) } - pub fn parent_with_predicate(&self) -> Option<(&Self, Option>)> { + pub fn parent_with_predicate(&self) -> Option<(&Self, Option>)> { match self { ObligationCauseCode::FunctionArg { parent_code, .. } => Some((parent_code, None)), ObligationCauseCode::BuiltinDerived(derived) @@ -577,7 +577,7 @@ pub struct DerivedCause<'tcx> { /// current obligation. Note that only trait obligations lead to /// derived obligations, so we just store the trait predicate here /// directly. - pub parent_trait_pred: ty::PolyTraitPredicate<'tcx>, + pub parent_trait_pred: ty::PolyTraitClause<'tcx>, /// The parent trait had this cause. pub parent_code: ObligationCauseCodeHandle<'tcx>, diff --git a/compiler/rustc_middle/src/traits/select.rs b/compiler/rustc_middle/src/traits/select.rs index a2eecebcc3501..e56dbb4ec3020 100644 --- a/compiler/rustc_middle/src/traits/select.rs +++ b/compiler/rustc_middle/src/traits/select.rs @@ -12,13 +12,11 @@ use super::{SelectionError, SelectionResult}; use crate::traits::cache::WithDepNodeCache; use crate::ty; -pub type SelectionCache<'tcx, ENV> = WithDepNodeCache< - (ENV, ty::TraitPredicate<'tcx>), - SelectionResult<'tcx, SelectionCandidate<'tcx>>, ->; +pub type SelectionCache<'tcx, ENV> = + WithDepNodeCache<(ENV, ty::TraitClause<'tcx>), SelectionResult<'tcx, SelectionCandidate<'tcx>>>; pub type EvaluationCache<'tcx, ENV> = - WithDepNodeCache<(ENV, ty::PolyTraitPredicate<'tcx>), EvaluationResult>; + WithDepNodeCache<(ENV, ty::PolyTraitClause<'tcx>), EvaluationResult>; /// The selection process begins by considering all impls, where /// clauses, and so forth that might resolve an obligation. Sometimes @@ -114,7 +112,7 @@ pub enum SelectionCandidate<'tcx> { /// Implementation of transmutability trait. TransmutabilityCandidate, - ParamCandidate(ty::PolyTraitPredicate<'tcx>), + ParamCandidate(ty::PolyTraitClause<'tcx>), ImplCandidate(DefId), AutoImplCandidate, diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 75aa5aaaa4352..9a8e7df6fb568 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -66,11 +66,11 @@ use crate::traits::solve::{ExternalConstraints, ExternalConstraintsData, Predefi use crate::ty::predicate::ExistentialPredicateStableCmpExt as _; use crate::ty::region::RegionExt; use crate::ty::{ - self, AdtDef, AdtDefData, AdtKind, Binder, Clause, Clauses, Const, FnSigKind, GenericArg, - GenericArgs, GenericArgsRef, GenericParamDefKind, List, ListWithCachedTypeInfo, ParamConst, - Pattern, PatternKind, PolyExistentialPredicate, PolyFnSig, Predicate, PredicateKind, - PredicatePolarity, Region, RegionKind, ReprOptions, TraitObjectVisitor, Ty, TyKind, TyVid, - ValTree, ValTreeKind, Visibility, + self, AdtDef, AdtDefData, AdtKind, Binder, Clause, ClausePolarity, Clauses, Const, FnSigKind, + GenericArg, GenericArgs, GenericArgsRef, GenericParamDefKind, List, ListWithCachedTypeInfo, + ParamConst, Pattern, PatternKind, PolyExistentialPredicate, PolyFnSig, Predicate, + PredicateKind, Region, RegionKind, ReprOptions, TraitObjectVisitor, Ty, TyKind, TyVid, ValTree, + ValTreeKind, Visibility, }; impl<'tcx> rustc_type_ir::inherent::DefId> for DefId { @@ -2073,7 +2073,7 @@ impl<'tcx> TyCtxt<'tcx> { return false; }; trait_predicate.trait_ref.def_id == future_trait - && trait_predicate.polarity == PredicatePolarity::Positive + && trait_predicate.polarity == ClausePolarity::Positive }) } diff --git a/compiler/rustc_middle/src/ty/diagnostics.rs b/compiler/rustc_middle/src/ty/diagnostics.rs index 94a6ae918a703..1f2a9aca60142 100644 --- a/compiler/rustc_middle/src/ty/diagnostics.rs +++ b/compiler/rustc_middle/src/ty/diagnostics.rs @@ -14,8 +14,8 @@ use rustc_type_ir::TyKind::*; use crate::ty::{ self, AliasTy, Const, ConstKind, FallibleTypeFolder, InferConst, InferTy, Instance, Opaque, - PolyTraitPredicate, Projection, Ty, TyCtxt, TypeFoldable, TypeSuperFoldable, - TypeSuperVisitable, TypeVisitable, TypeVisitor, + PolyTraitClause, Projection, Ty, TyCtxt, TypeFoldable, TypeSuperFoldable, TypeSuperVisitable, + TypeVisitable, TypeVisitor, }; impl IntoDiagArg for Ty<'_> { @@ -133,7 +133,7 @@ pub fn suggest_arbitrary_trait_bound<'tcx>( tcx: TyCtxt<'tcx>, generics: &hir::Generics<'_>, err: &mut Diag<'_>, - trait_pred: PolyTraitPredicate<'tcx>, + trait_pred: PolyTraitClause<'tcx>, associated_ty: Option<(&'static str, Ty<'tcx>)>, ) -> bool { if !trait_pred.is_suggestable(tcx, false) { diff --git a/compiler/rustc_middle/src/ty/elaborate_impl.rs b/compiler/rustc_middle/src/ty/elaborate_impl.rs index 8c89a2d884b30..cd76d49cefecb 100644 --- a/compiler/rustc_middle/src/ty/elaborate_impl.rs +++ b/compiler/rustc_middle/src/ty/elaborate_impl.rs @@ -16,7 +16,7 @@ impl<'tcx> Elaboratable> for ty::Clause<'tcx> { &self, clause: ty::Clause<'tcx>, _span: Span, - _parent_trait_pred: ty::PolyTraitPredicate<'tcx>, + _parent_trait_pred: ty::PolyTraitClause<'tcx>, _index: usize, ) -> Self { clause @@ -36,7 +36,7 @@ impl<'tcx> Elaboratable> for ty::Predicate<'tcx> { &self, clause: ty::Clause<'tcx>, _span: Span, - _parent_trait_pred: ty::PolyTraitPredicate<'tcx>, + _parent_trait_pred: ty::PolyTraitClause<'tcx>, _index: usize, ) -> Self { clause.as_predicate() @@ -56,7 +56,7 @@ impl<'tcx> Elaboratable> for (ty::Predicate<'tcx>, Span) { &self, clause: ty::Clause<'tcx>, _span: Span, - _parent_trait_pred: ty::PolyTraitPredicate<'tcx>, + _parent_trait_pred: ty::PolyTraitClause<'tcx>, _index: usize, ) -> Self { (clause.as_predicate(), self.1) @@ -76,7 +76,7 @@ impl<'tcx> Elaboratable> for (ty::Clause<'tcx>, Span) { &self, clause: ty::Clause<'tcx>, _span: Span, - _parent_trait_pred: ty::PolyTraitPredicate<'tcx>, + _parent_trait_pred: ty::PolyTraitClause<'tcx>, _index: usize, ) -> Self { (clause, self.1) diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index b7feb28d61414..36631861e8108 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -89,9 +89,9 @@ pub use self::predicate::{ ExistentialPredicate, ExistentialPredicateStableCmpExt, ExistentialProjection, ExistentialTraitRef, HostEffectClause, NormalizesTo, OutlivesClause, PolyCoercePredicate, PolyExistentialPredicate, PolyExistentialProjection, PolyExistentialTraitRef, - PolyProjectionClause, PolyRegionOutlivesClause, PolySubtypePredicate, PolyTraitPredicate, + PolyProjectionClause, PolyRegionOutlivesClause, PolySubtypePredicate, PolyTraitClause, PolyTraitRef, PolyTypeOutlivesClause, Predicate, PredicateKind, ProjectionClause, - RegionConstraint, RegionEqPredicate, RegionOutlivesClause, SubtypePredicate, TraitPredicate, + RegionConstraint, RegionEqPredicate, RegionOutlivesClause, SubtypePredicate, TraitClause, TraitRef, TypeOutlivesClause, }; pub use self::region::{ diff --git a/compiler/rustc_middle/src/ty/predicate.rs b/compiler/rustc_middle/src/ty/predicate.rs index d2834ab9ce226..3ccf185405209 100644 --- a/compiler/rustc_middle/src/ty/predicate.rs +++ b/compiler/rustc_middle/src/ty/predicate.rs @@ -14,7 +14,7 @@ pub type ProjectionClause<'tcx> = ir::ProjectionClause>; pub type ExistentialPredicate<'tcx> = ir::ExistentialPredicate>; pub type ExistentialTraitRef<'tcx> = ir::ExistentialTraitRef>; pub type ExistentialProjection<'tcx> = ir::ExistentialProjection>; -pub type TraitPredicate<'tcx> = ir::TraitPredicate>; +pub type TraitClause<'tcx> = ir::TraitClause>; pub type HostEffectClause<'tcx> = ir::HostEffectClause>; pub type ClauseKind<'tcx> = ir::ClauseKind>; pub type PredicateKind<'tcx> = ir::PredicateKind>; @@ -27,7 +27,7 @@ pub type TypeOutlivesClause<'tcx> = OutlivesClause<'tcx, Ty<'tcx>>; pub type ArgOutlivesClause<'tcx> = OutlivesClause<'tcx, ty::GenericArg<'tcx>>; pub type RegionEqPredicate<'tcx> = ir::RegionEqPredicate>; pub type RegionConstraint<'tcx> = ir::RegionConstraint>; -pub type PolyTraitPredicate<'tcx> = ty::Binder<'tcx, TraitPredicate<'tcx>>; +pub type PolyTraitClause<'tcx> = ty::Binder<'tcx, TraitClause<'tcx>>; pub type PolyRegionOutlivesClause<'tcx> = ty::Binder<'tcx, RegionOutlivesClause<'tcx>>; pub type PolyTypeOutlivesClause<'tcx> = ty::Binder<'tcx, TypeOutlivesClause<'tcx>>; pub type PolySubtypePredicate<'tcx> = ty::Binder<'tcx, SubtypePredicate<'tcx>>; @@ -84,13 +84,12 @@ impl<'tcx> Predicate<'tcx> { let kind = self .kind() .map_bound(|kind| match kind { - PredicateKind::Clause(ClauseKind::Trait(TraitPredicate { - trait_ref, - polarity, - })) => Some(PredicateKind::Clause(ClauseKind::Trait(TraitPredicate { - trait_ref, - polarity: polarity.flip(), - }))), + PredicateKind::Clause(ClauseKind::Trait(TraitClause { trait_ref, polarity })) => { + Some(PredicateKind::Clause(ClauseKind::Trait(TraitClause { + trait_ref, + polarity: polarity.flip(), + }))) + } _ => None, }) @@ -177,7 +176,7 @@ impl<'tcx> Clause<'tcx> { }) } - pub fn as_trait_clause(self) -> Option>> { + pub fn as_trait_clause(self) -> Option>> { let clause = self.kind(); if let ty::ClauseKind::Trait(trait_clause) = clause.skip_binder() { Some(clause.rebind(trait_clause)) @@ -500,39 +499,39 @@ impl<'tcx> UpcastFrom, TraitRef<'tcx>> for Clause<'tcx> { impl<'tcx> UpcastFrom, ty::Binder<'tcx, TraitRef<'tcx>>> for Predicate<'tcx> { fn upcast_from(from: ty::Binder<'tcx, TraitRef<'tcx>>, tcx: TyCtxt<'tcx>) -> Self { - let pred: PolyTraitPredicate<'tcx> = from.upcast(tcx); + let pred: PolyTraitClause<'tcx> = from.upcast(tcx); pred.upcast(tcx) } } impl<'tcx> UpcastFrom, ty::Binder<'tcx, TraitRef<'tcx>>> for Clause<'tcx> { fn upcast_from(from: ty::Binder<'tcx, TraitRef<'tcx>>, tcx: TyCtxt<'tcx>) -> Self { - let pred: PolyTraitPredicate<'tcx> = from.upcast(tcx); + let pred: PolyTraitClause<'tcx> = from.upcast(tcx); pred.upcast(tcx) } } -impl<'tcx> UpcastFrom, TraitPredicate<'tcx>> for Predicate<'tcx> { - fn upcast_from(from: TraitPredicate<'tcx>, tcx: TyCtxt<'tcx>) -> Self { +impl<'tcx> UpcastFrom, TraitClause<'tcx>> for Predicate<'tcx> { + fn upcast_from(from: TraitClause<'tcx>, tcx: TyCtxt<'tcx>) -> Self { PredicateKind::Clause(ClauseKind::Trait(from)).upcast(tcx) } } -impl<'tcx> UpcastFrom, PolyTraitPredicate<'tcx>> for Predicate<'tcx> { - fn upcast_from(from: PolyTraitPredicate<'tcx>, tcx: TyCtxt<'tcx>) -> Self { +impl<'tcx> UpcastFrom, PolyTraitClause<'tcx>> for Predicate<'tcx> { + fn upcast_from(from: PolyTraitClause<'tcx>, tcx: TyCtxt<'tcx>) -> Self { from.map_bound(|p| PredicateKind::Clause(ClauseKind::Trait(p))).upcast(tcx) } } -impl<'tcx> UpcastFrom, TraitPredicate<'tcx>> for Clause<'tcx> { - fn upcast_from(from: TraitPredicate<'tcx>, tcx: TyCtxt<'tcx>) -> Self { +impl<'tcx> UpcastFrom, TraitClause<'tcx>> for Clause<'tcx> { + fn upcast_from(from: TraitClause<'tcx>, tcx: TyCtxt<'tcx>) -> Self { let p: Predicate<'tcx> = from.upcast(tcx); p.expect_clause() } } -impl<'tcx> UpcastFrom, PolyTraitPredicate<'tcx>> for Clause<'tcx> { - fn upcast_from(from: PolyTraitPredicate<'tcx>, tcx: TyCtxt<'tcx>) -> Self { +impl<'tcx> UpcastFrom, PolyTraitClause<'tcx>> for Clause<'tcx> { + fn upcast_from(from: PolyTraitClause<'tcx>, tcx: TyCtxt<'tcx>) -> Self { let p: Predicate<'tcx> = from.upcast(tcx); p.expect_clause() } @@ -603,7 +602,7 @@ impl<'tcx> UpcastFrom, NormalizesTo<'tcx>> for Predicate<'tcx> { } impl<'tcx> Predicate<'tcx> { - pub fn as_trait_clause(self) -> Option> { + pub fn as_trait_clause(self) -> Option> { let predicate = self.kind(); match predicate.skip_binder() { PredicateKind::Clause(ClauseKind::Trait(t)) => Some(predicate.rebind(t)), diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index b64435a8591a7..84437a237c28a 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -26,7 +26,7 @@ use crate::mir::interpret::{AllocRange, GlobalAlloc, Pointer, Provenance, Scalar use crate::query::{IntoQueryKey, Providers}; use crate::ty::region::RegionExt; use crate::ty::{ - ConstInt, Expr, GenericArgKind, ParamConst, ScalarInt, Term, TermKind, TraitPredicate, + ConstInt, Expr, GenericArgKind, ParamConst, ScalarInt, Term, TermKind, TraitClause, TypeFoldable, TypeSuperFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, }; @@ -1060,11 +1060,11 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { // `MetaSized`, and skip sizedness bounds to be added at the end. match tcx.as_lang_item(pred.def_id()) { Some(LangItem::Sized) => match pred.polarity { - ty::PredicatePolarity::Positive => { + ty::ClausePolarity::Positive => { has_sized_bound = true; continue; } - ty::PredicatePolarity::Negative => has_negative_sized_bound = true, + ty::ClausePolarity::Negative => has_negative_sized_bound = true, }, Some(LangItem::MetaSized) => { has_meta_sized_bound = true; @@ -1085,9 +1085,9 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } ty::ClauseKind::Projection(pred) => { let proj = bound_predicate.rebind(pred); - let trait_ref = proj.map_bound(|proj| TraitPredicate { + let trait_ref = proj.map_bound(|proj| TraitClause { trait_ref: proj.projection_term.trait_ref(tcx), - polarity: ty::PredicatePolarity::Positive, + polarity: ty::ClausePolarity::Positive, }); self.insert_trait_and_projection( @@ -1151,8 +1151,8 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } else { // Otherwise, render this like a regular trait. traits.insert( - bound_args_and_self_ty.map_bound(|(args, self_ty)| ty::TraitPredicate { - polarity: ty::PredicatePolarity::Positive, + bound_args_and_self_ty.map_bound(|(args, self_ty)| ty::TraitClause { + polarity: ty::ClausePolarity::Positive, trait_ref: ty::TraitRef::new( tcx, trait_def_id, @@ -1169,7 +1169,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { write!(self, "{}", if first { "" } else { " + " })?; self.wrap_binder(&trait_pred, WrapBinderMode::ForAll, |trait_pred, p| { - if trait_pred.polarity == ty::PredicatePolarity::Negative { + if trait_pred.polarity == ty::ClausePolarity::Negative { write!(p, "!")?; } trait_pred.trait_ref.print_only_trait_name().print(p)?; @@ -1257,10 +1257,10 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { /// traits map or fn_traits map, depending on if the trait is in the Fn* family of traits. fn insert_trait_and_projection( &mut self, - trait_pred: ty::PolyTraitPredicate<'tcx>, + trait_pred: ty::PolyTraitClause<'tcx>, proj_ty: Option<(DefId, ty::Binder<'tcx, Term<'tcx>>)>, traits: &mut FxIndexMap< - ty::PolyTraitPredicate<'tcx>, + ty::PolyTraitClause<'tcx>, FxIndexMap>>, >, fn_traits: &mut FxIndexMap< @@ -1279,7 +1279,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { None }; - if trait_pred.polarity() == ty::PredicatePolarity::Positive + if trait_pred.polarity() == ty::ClausePolarity::Positive && let Some((kind, is_async)) = fn_trait_and_async && let ty::Tuple(types) = *trait_pred.skip_binder().trait_ref.args.type_at(1).kind() { @@ -3076,46 +3076,46 @@ impl<'tcx> ty::Binder<'tcx, ty::TraitRef<'tcx>> { } #[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift, Hash)] -pub struct TraitPredPrintModifiersAndPath<'tcx>(ty::TraitPredicate<'tcx>); +pub struct TraitClausePrintModifiersAndPath<'tcx>(ty::TraitClause<'tcx>); -impl<'tcx> fmt::Debug for TraitPredPrintModifiersAndPath<'tcx> { +impl<'tcx> fmt::Debug for TraitClausePrintModifiersAndPath<'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(self, f) } } -#[extension(pub trait PrintTraitPredicateExt<'tcx>)] -impl<'tcx> ty::TraitPredicate<'tcx> { - fn print_modifiers_and_trait_path(self) -> TraitPredPrintModifiersAndPath<'tcx> { - TraitPredPrintModifiersAndPath(self) +#[extension(pub trait PrintTraitClauseExt<'tcx>)] +impl<'tcx> ty::TraitClause<'tcx> { + fn print_modifiers_and_trait_path(self) -> TraitClausePrintModifiersAndPath<'tcx> { + TraitClausePrintModifiersAndPath(self) } } #[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift, Hash)] -pub struct TraitPredPrintWithBoundConstness<'tcx>( - ty::TraitPredicate<'tcx>, +pub struct TraitClausePrintWithBoundConstness<'tcx>( + ty::TraitClause<'tcx>, Option, ); -impl<'tcx> fmt::Debug for TraitPredPrintWithBoundConstness<'tcx> { +impl<'tcx> fmt::Debug for TraitClausePrintWithBoundConstness<'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(self, f) } } -#[extension(pub trait PrintPolyTraitPredicateExt<'tcx>)] -impl<'tcx> ty::PolyTraitPredicate<'tcx> { +#[extension(pub trait PrintPolyTraitClauseExt<'tcx>)] +impl<'tcx> ty::PolyTraitClause<'tcx> { fn print_modifiers_and_trait_path( self, - ) -> ty::Binder<'tcx, TraitPredPrintModifiersAndPath<'tcx>> { - self.map_bound(TraitPredPrintModifiersAndPath) + ) -> ty::Binder<'tcx, TraitClausePrintModifiersAndPath<'tcx>> { + self.map_bound(TraitClausePrintModifiersAndPath) } fn print_with_bound_constness( self, constness: Option, - ) -> ty::Binder<'tcx, TraitPredPrintWithBoundConstness<'tcx>> { - self.map_bound(|trait_pred| TraitPredPrintWithBoundConstness(trait_pred, constness)) + ) -> ty::Binder<'tcx, TraitClausePrintWithBoundConstness<'tcx>> { + self.map_bound(|trait_pred| TraitClausePrintWithBoundConstness(trait_pred, constness)) } } @@ -3214,10 +3214,10 @@ define_print! { } } - ty::TraitPredicate<'tcx> { + ty::TraitClause<'tcx> { self.trait_ref.self_ty().print(p)?; write!(p, ": ")?; - if let ty::PredicatePolarity::Negative = self.polarity { + if let ty::ClausePolarity::Negative = self.polarity { write!(p, "!")?; } self.trait_ref.print_trait_sugared().print(p)?; @@ -3389,20 +3389,20 @@ define_print_and_forward_display! { p.print_def_path(self.0.def_id, &[])?; } - TraitPredPrintModifiersAndPath<'tcx> { - if let ty::PredicatePolarity::Negative = self.0.polarity { + TraitClausePrintModifiersAndPath<'tcx> { + if let ty::ClausePolarity::Negative = self.0.polarity { write!(p, "!")?; } self.0.trait_ref.print_trait_sugared().print(p)?; } - TraitPredPrintWithBoundConstness<'tcx> { + TraitClausePrintWithBoundConstness<'tcx> { self.0.trait_ref.self_ty().print(p)?; write!(p, ": ")?; if let Some(constness) = self.1 { p.pretty_print_bound_constness(constness)?; } - if let ty::PredicatePolarity::Negative = self.0.polarity { + if let ty::ClausePolarity::Negative = self.0.polarity { write!(p, "!")?; } self.0.trait_ref.print_trait_sugared().print(p)?; diff --git a/compiler/rustc_middle/src/ty/structural_impls.rs b/compiler/rustc_middle/src/ty/structural_impls.rs index 7dc717649dc1c..d40c5dfab7c14 100644 --- a/compiler/rustc_middle/src/ty/structural_impls.rs +++ b/compiler/rustc_middle/src/ty/structural_impls.rs @@ -186,7 +186,7 @@ TrivialLiftImpls! { rustc_middle::mir::ConstValue, rustc_span::Symbol, rustc_type_ir::BoundConstness, - rustc_type_ir::PredicatePolarity, + rustc_type_ir::ClausePolarity, // tidy-alphabetical-end } diff --git a/compiler/rustc_mir_transform/src/impossible_clauses.rs b/compiler/rustc_mir_transform/src/impossible_clauses.rs index 39f864d8a8219..bb6644716bf05 100644 --- a/compiler/rustc_mir_transform/src/impossible_clauses.rs +++ b/compiler/rustc_mir_transform/src/impossible_clauses.rs @@ -58,7 +58,7 @@ fn has_structurally_impossible_sized_clause<'tcx>( }; let trait_predicate = trait_predicate.skip_binder(); - trait_predicate.polarity == ty::PredicatePolarity::Positive + trait_predicate.polarity == ty::ClausePolarity::Positive && trait_predicate.def_id() == sized_trait && is_structurally_unsized(tcx, trait_predicate.self_ty()) } diff --git a/compiler/rustc_next_trait_solver/src/solve/effect_goals.rs b/compiler/rustc_next_trait_solver/src/solve/effect_goals.rs index 488d1b9215016..2fe983afc25ef 100644 --- a/compiler/rustc_next_trait_solver/src/solve/effect_goals.rs +++ b/compiler/rustc_next_trait_solver/src/solve/effect_goals.rs @@ -485,7 +485,7 @@ where goal: Goal>, ) -> QueryResultOrRerunNonErased { let (_, proven_via) = self.probe(|_| ProbeKind::ShadowedEnvProbing).enter(|ecx| { - let trait_goal: Goal> = + let trait_goal: Goal> = goal.with(ecx.cx(), goal.predicate.trait_ref); ecx.compute_trait_goal(trait_goal).map_err(Into::into) })?; diff --git a/compiler/rustc_next_trait_solver/src/solve/normalizes_to.rs b/compiler/rustc_next_trait_solver/src/solve/normalizes_to.rs index 23cd22fab6e3f..20986813668d3 100644 --- a/compiler/rustc_next_trait_solver/src/solve/normalizes_to.rs +++ b/compiler/rustc_next_trait_solver/src/solve/normalizes_to.rs @@ -41,7 +41,7 @@ where let trait_ref = goal.predicate.alias.trait_ref(cx); let (_, proven_via) = self.probe(|_| ProbeKind::ShadowedEnvProbing).enter(|ecx| { - let trait_goal: Goal> = goal.with(cx, trait_ref); + let trait_goal: Goal> = goal.with(cx, trait_ref); ecx.compute_trait_goal(trait_goal) })?; self.assemble_and_merge_candidates( diff --git a/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs b/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs index 07a87d1194d13..335263b1d169d 100644 --- a/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs +++ b/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs @@ -10,9 +10,9 @@ use rustc_type_ir::solve::{ RerunReason, RerunResultExt, SizedTraitKind, }; use rustc_type_ir::{ - self as ty, ExistentialPredicate, FieldInfo, Interner, MayBeErased, Movability, - PredicatePolarity, Region, TraitPredicate, TraitRef, TypeVisitableExt as _, TypingMode, - Unnormalized, Upcast as _, elaborate, + self as ty, ClausePolarity, ExistentialPredicate, FieldInfo, Interner, MayBeErased, Movability, + Region, TraitClause, TraitRef, TypeVisitableExt as _, TypingMode, Unnormalized, Upcast as _, + elaborate, }; use tracing::{debug, instrument, trace, warn}; @@ -28,7 +28,7 @@ use crate::solve::{ has_only_region_constraints, }; -impl assembly::GoalKind for TraitPredicate +impl assembly::GoalKind for TraitClause where D: SolverDelegate, I: Interner, @@ -59,7 +59,7 @@ where fn consider_impl_candidate( ecx: &mut EvalCtxt<'_, D>, - goal: Goal>, + goal: Goal>, goal_trait_ref: TraitRef, impl_def_id: I::ImplId, then: impl FnOnce(&mut EvalCtxt<'_, D>, Certainty) -> QueryResultOrRerunNonErased, @@ -87,8 +87,8 @@ where } // Impl matches polarity - (ty::ImplPolarity::Positive, ty::PredicatePolarity::Positive) - | (ty::ImplPolarity::Negative, ty::PredicatePolarity::Negative) => { + (ty::ImplPolarity::Positive, ty::ClausePolarity::Positive) + | (ty::ImplPolarity::Negative, ty::ClausePolarity::Negative) => { if ecx.typing_mode().is_reflection() && !cx.is_fully_generic_for_reflection(impl_def_id) { @@ -99,8 +99,8 @@ where } // Impl doesn't match polarity - (ty::ImplPolarity::Positive, ty::PredicatePolarity::Negative) - | (ty::ImplPolarity::Negative, ty::PredicatePolarity::Positive) => { + (ty::ImplPolarity::Positive, ty::ClausePolarity::Negative) + | (ty::ImplPolarity::Negative, ty::ClausePolarity::Positive) => { return Err(NoSolution.into()); } }; @@ -151,14 +151,14 @@ where cx: I, clause_def_id: I::TraitId, goal_def_id: I::TraitId, - polarity: PredicatePolarity, + polarity: ClausePolarity, ) -> bool { clause_def_id == goal_def_id // PERF(sized-hierarchy): Sizedness supertraits aren't elaborated to improve perf, so // check for a `MetaSized` supertrait being matched against a `Sized` assumption. // // `PointeeSized` bounds are syntactic sugar for a lack of bounds so don't need this. - || (polarity == PredicatePolarity::Positive + || (polarity == ClausePolarity::Positive && cx.is_trait_lang_item(clause_def_id, SolverTraitLangItem::Sized) && cx.is_trait_lang_item(goal_def_id, SolverTraitLangItem::MetaSized)) } @@ -214,7 +214,7 @@ where goal: Goal, ) -> Result, NoSolutionOrRerunNonErased> { let cx = ecx.cx(); - if goal.predicate.polarity != ty::PredicatePolarity::Positive { + if goal.predicate.polarity != ty::ClausePolarity::Positive { return Err(NoSolution.into()); } @@ -280,7 +280,7 @@ where ecx: &mut EvalCtxt<'_, D>, goal: Goal, ) -> Result, NoSolutionOrRerunNonErased> { - if goal.predicate.polarity != ty::PredicatePolarity::Positive { + if goal.predicate.polarity != ty::ClausePolarity::Positive { return Err(NoSolution.into()); } @@ -307,7 +307,7 @@ where goal: Goal, sizedness: SizedTraitKind, ) -> Result, NoSolutionOrRerunNonErased> { - if goal.predicate.polarity != ty::PredicatePolarity::Positive { + if goal.predicate.polarity != ty::ClausePolarity::Positive { return Err(NoSolution.into()); } @@ -326,7 +326,7 @@ where ecx: &mut EvalCtxt<'_, D>, goal: Goal, ) -> Result, NoSolutionOrRerunNonErased> { - if goal.predicate.polarity != ty::PredicatePolarity::Positive { + if goal.predicate.polarity != ty::ClausePolarity::Positive { return Err(NoSolution.into()); } @@ -349,7 +349,7 @@ where let self_ty = goal.predicate.self_ty(); match goal.predicate.polarity { // impl FnPtr for FnPtr {} - ty::PredicatePolarity::Positive => { + ty::ClausePolarity::Positive => { if self_ty.is_fn_ptr() { ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| { ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes) @@ -359,7 +359,7 @@ where } } // impl !FnPtr for T where T != FnPtr && T is rigid {} - ty::PredicatePolarity::Negative => { + ty::ClausePolarity::Negative => { // If a type is rigid and not a fn ptr, then we know for certain // that it does *not* implement `FnPtr`. if !self_ty.is_fn_ptr() && self_ty.is_known_rigid() { @@ -378,7 +378,7 @@ where goal: Goal, goal_kind: ty::ClosureKind, ) -> Result, NoSolutionOrRerunNonErased> { - if goal.predicate.polarity != ty::PredicatePolarity::Positive { + if goal.predicate.polarity != ty::ClausePolarity::Positive { return Err(NoSolution.into()); } @@ -416,7 +416,7 @@ where goal: Goal, goal_kind: ty::ClosureKind, ) -> Result, NoSolutionOrRerunNonErased> { - if goal.predicate.polarity != ty::PredicatePolarity::Positive { + if goal.predicate.polarity != ty::ClausePolarity::Positive { return Err(NoSolution.into()); } @@ -492,7 +492,7 @@ where ecx: &mut EvalCtxt<'_, D>, goal: Goal, ) -> Result, NoSolutionOrRerunNonErased> { - if goal.predicate.polarity != ty::PredicatePolarity::Positive { + if goal.predicate.polarity != ty::ClausePolarity::Positive { return Err(NoSolution.into()); } @@ -508,7 +508,7 @@ where ecx: &mut EvalCtxt<'_, D>, goal: Goal, ) -> Result, NoSolutionOrRerunNonErased> { - if goal.predicate.polarity != ty::PredicatePolarity::Positive { + if goal.predicate.polarity != ty::ClausePolarity::Positive { return Err(NoSolution.into()); } @@ -520,7 +520,7 @@ where ecx: &mut EvalCtxt<'_, D>, goal: Goal, ) -> Result, NoSolutionOrRerunNonErased> { - if goal.predicate.polarity != ty::PredicatePolarity::Positive { + if goal.predicate.polarity != ty::ClausePolarity::Positive { return Err(NoSolution.into()); } @@ -545,7 +545,7 @@ where ecx: &mut EvalCtxt<'_, D>, goal: Goal, ) -> Result, NoSolutionOrRerunNonErased> { - if goal.predicate.polarity != ty::PredicatePolarity::Positive { + if goal.predicate.polarity != ty::ClausePolarity::Positive { return Err(NoSolution.into()); } @@ -570,7 +570,7 @@ where ecx: &mut EvalCtxt<'_, D>, goal: Goal, ) -> Result, NoSolutionOrRerunNonErased> { - if goal.predicate.polarity != ty::PredicatePolarity::Positive { + if goal.predicate.polarity != ty::ClausePolarity::Positive { return Err(NoSolution.into()); } @@ -593,7 +593,7 @@ where ecx: &mut EvalCtxt<'_, D>, goal: Goal, ) -> Result, NoSolutionOrRerunNonErased> { - if goal.predicate.polarity != ty::PredicatePolarity::Positive { + if goal.predicate.polarity != ty::ClausePolarity::Positive { return Err(NoSolution.into()); } @@ -618,7 +618,7 @@ where ecx: &mut EvalCtxt<'_, D>, goal: Goal, ) -> Result, NoSolutionOrRerunNonErased> { - if goal.predicate.polarity != ty::PredicatePolarity::Positive { + if goal.predicate.polarity != ty::ClausePolarity::Positive { return Err(NoSolution.into()); } @@ -650,7 +650,7 @@ where ecx: &mut EvalCtxt<'_, D>, goal: Goal, ) -> Result, NoSolutionOrRerunNonErased> { - if goal.predicate.polarity != ty::PredicatePolarity::Positive { + if goal.predicate.polarity != ty::ClausePolarity::Positive { return Err(NoSolution.into()); } @@ -663,7 +663,7 @@ where ecx: &mut EvalCtxt<'_, D>, goal: Goal, ) -> Result, NoSolutionOrRerunNonErased> { - if goal.predicate.polarity != ty::PredicatePolarity::Positive { + if goal.predicate.polarity != ty::ClausePolarity::Positive { return Err(NoSolution.into()); } @@ -677,7 +677,7 @@ where ecx: &mut EvalCtxt<'_, D>, goal: Goal, ) -> Result, NoSolutionOrRerunNonErased> { - if goal.predicate.polarity != ty::PredicatePolarity::Positive { + if goal.predicate.polarity != ty::ClausePolarity::Positive { return Err(NoSolution.into()); } @@ -725,7 +725,7 @@ where ecx: &mut EvalCtxt<'_, D>, goal: Goal, ) -> Result, NoSolutionOrRerunNonErased> { - if goal.predicate.polarity != ty::PredicatePolarity::Positive { + if goal.predicate.polarity != ty::ClausePolarity::Positive { return Err(NoSolution.into()); } @@ -818,7 +818,7 @@ where ecx: &mut EvalCtxt<'_, D>, goal: Goal, ) -> Result>, RerunNonErased> { - if goal.predicate.polarity != ty::PredicatePolarity::Positive { + if goal.predicate.polarity != ty::ClausePolarity::Positive { return Ok(vec![]); } @@ -878,7 +878,7 @@ where ecx: &mut EvalCtxt<'_, D>, goal: Goal, ) -> Result, NoSolutionOrRerunNonErased> { - if goal.predicate.polarity != ty::PredicatePolarity::Positive { + if goal.predicate.polarity != ty::ClausePolarity::Positive { return Err(NoSolution.into()); } let cx = ecx.cx(); @@ -921,7 +921,7 @@ where ecx: &mut EvalCtxt<'_, D>, goal: Goal, ) -> Result, NoSolutionOrRerunNonErased> { - if goal.predicate.polarity != ty::PredicatePolarity::Positive { + if goal.predicate.polarity != ty::ClausePolarity::Positive { return Err(NoSolution.into()); } if let ty::Adt(def, args) = goal.predicate.self_ty().kind() @@ -976,11 +976,11 @@ where #[inline(always)] fn trait_predicate_with_def_id( cx: I, - clause: ty::Binder>, + clause: ty::Binder>, did: I::TraitId, ) -> I::Clause { clause - .map_bound(|c| TraitPredicate { + .map_bound(|c| TraitClause { trait_ref: TraitRef::new_from_args(cx, did, c.trait_ref.args), polarity: c.polarity, }) @@ -1305,7 +1305,7 @@ where // the type's constituent types. fn disqualify_auto_trait_candidate_due_to_possible_impl( &mut self, - goal: Goal>, + goal: Goal>, ) -> Option, NoSolutionOrRerunNonErased>> { let self_ty = goal.predicate.self_ty(); let check_impls = || { @@ -1417,7 +1417,7 @@ where fn probe_and_evaluate_goal_for_constituent_tys( &mut self, source: CandidateSource, - goal: Goal>, + goal: Goal>, constituent_tys: impl Fn( &EvalCtxt<'_, D>, I::Ty, @@ -1633,7 +1633,7 @@ where #[instrument(level = "trace", skip(self))] pub(super) fn compute_trait_goal( &mut self, - goal: Goal>, + goal: Goal>, ) -> Result<(CanonicalResponse, Option), NoSolutionOrRerunNonErased> { let (candidates, failed_candidate_info) = diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index 069dfe428be30..c11a4b162971f 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -130,7 +130,7 @@ where fn visit_clause(&mut self, clause: ty::Clause<'tcx>) -> V::Result { match clause.kind().skip_binder() { - ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, polarity: _ }) => { + ty::ClauseKind::Trait(ty::TraitClause { trait_ref, polarity: _ }) => { self.visit_trait(trait_ref) } ty::ClauseKind::HostEffect(clause) => { diff --git a/compiler/rustc_public/src/ty/tys.rs b/compiler/rustc_public/src/ty/tys.rs index 3bd8764c909e8..75e4272ead57a 100644 --- a/compiler/rustc_public/src/ty/tys.rs +++ b/compiler/rustc_public/src/ty/tys.rs @@ -1231,7 +1231,7 @@ pub enum PredicateKind { #[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub enum ClauseKind { - Trait(TraitPredicate), + Trait(TraitClause), RegionOutlives(RegionOutlivesClause), TypeOutlives(TypeOutlivesClause), Projection(ProjectionClause), @@ -1260,11 +1260,14 @@ pub struct CoercePredicate { } #[derive(Clone, Debug, Eq, PartialEq, Serialize)] -pub struct TraitPredicate { +pub struct TraitClause { pub trait_ref: TraitRef, - pub polarity: PredicatePolarity, + pub polarity: ClausePolarity, } +#[deprecated = "renamed to [`TraitClause`]"] +pub type TraitPredicate = TraitClause; + #[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct OutlivesClause(pub A, pub B); @@ -1295,11 +1298,14 @@ pub enum ImplPolarity { } #[derive(Clone, Debug, Eq, PartialEq, Serialize)] -pub enum PredicatePolarity { +pub enum ClausePolarity { Positive, Negative, } +#[deprecated = "renamed to [`ClausePolarity`]"] +pub type PredicatePolarity = ClausePolarity; + macro_rules! index_impl { ($name:ident) => { impl crate::IndexedVal for $name { diff --git a/compiler/rustc_public/src/unstable/convert/stable/ty.rs b/compiler/rustc_public/src/unstable/convert/stable/ty.rs index 8cefed4dd243d..9eed22dc15d05 100644 --- a/compiler/rustc_public/src/unstable/convert/stable/ty.rs +++ b/compiler/rustc_public/src/unstable/convert/stable/ty.rs @@ -840,16 +840,16 @@ impl<'tcx> Stable<'tcx> for ty::CoercePredicate<'tcx> { } } -impl<'tcx> Stable<'tcx> for ty::TraitPredicate<'tcx> { - type T = crate::ty::TraitPredicate; +impl<'tcx> Stable<'tcx> for ty::TraitClause<'tcx> { + type T = crate::ty::TraitClause; fn stable<'cx>( &self, tables: &mut Tables<'cx, BridgeTys>, cx: &CompilerCtxt<'cx, BridgeTys>, ) -> Self::T { - let ty::TraitPredicate { trait_ref, polarity } = self; - crate::ty::TraitPredicate { + let ty::TraitClause { trait_ref, polarity } = self; + crate::ty::TraitClause { trait_ref: trait_ref.stable(tables, cx), polarity: polarity.stable(tables, cx), } @@ -901,14 +901,14 @@ impl<'tcx> Stable<'tcx> for ty::ImplPolarity { } } -impl<'tcx> Stable<'tcx> for ty::PredicatePolarity { - type T = crate::ty::PredicatePolarity; +impl<'tcx> Stable<'tcx> for ty::ClausePolarity { + type T = crate::ty::ClausePolarity; fn stable(&self, _: &mut Tables<'_, BridgeTys>, _: &CompilerCtxt<'_, BridgeTys>) -> Self::T { - use rustc_middle::ty::PredicatePolarity::*; + use rustc_middle::ty::ClausePolarity::*; match self { - Positive => crate::ty::PredicatePolarity::Positive, - Negative => crate::ty::PredicatePolarity::Negative, + Positive => crate::ty::ClausePolarity::Positive, + Negative => crate::ty::ClausePolarity::Negative, } } } diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs index c28970829f0a4..45ae86b39f35e 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs @@ -386,8 +386,7 @@ impl Trait for X { .iter() .any(|(pred, _span)| match pred.kind().skip_binder() { ty::ClauseKind::Trait(trait_predicate) - if trait_predicate.polarity - == ty::PredicatePolarity::Positive => + if trait_predicate.polarity == ty::ClausePolarity::Positive => { trait_predicate.def_id() == def_id } @@ -524,7 +523,7 @@ impl Trait for X { else { continue; }; - if trait_predicate.polarity != ty::PredicatePolarity::Positive { + if trait_predicate.polarity != ty::ClausePolarity::Positive { continue; } let def_id = trait_predicate.def_id(); diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/ambiguity.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/ambiguity.rs index 06d882a309489..2e0fc64c5445f 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/ambiguity.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/ambiguity.rs @@ -11,7 +11,7 @@ use rustc_infer::traits::util::elaborate; use rustc_infer::traits::{ Obligation, ObligationCause, ObligationCauseCode, PolyTraitObligation, PredicateObligation, }; -use rustc_middle::ty::print::PrintPolyTraitPredicateExt; +use rustc_middle::ty::print::PrintPolyTraitClauseExt; use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitable as _, TypeVisitableExt as _, Unnormalized}; use rustc_session::diagnostics::feature_err_unstable_feature_bound; use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span}; @@ -67,8 +67,8 @@ pub fn compute_applicable_impls_for_diagnostics<'tcx>( let impl_polarity = impl_trait_header.polarity; match (impl_polarity, predicate_polarity) { - (ty::ImplPolarity::Positive, ty::PredicatePolarity::Positive) - | (ty::ImplPolarity::Negative, ty::PredicatePolarity::Negative) => {} + (ty::ImplPolarity::Positive, ty::ClausePolarity::Positive) + | (ty::ImplPolarity::Negative, ty::ClausePolarity::Negative) => {} _ => return false, } @@ -99,7 +99,7 @@ pub fn compute_applicable_impls_for_diagnostics<'tcx>( }) }; - let param_env_candidate_may_apply = |poly_trait_predicate: ty::PolyTraitPredicate<'tcx>| { + let param_env_candidate_may_apply = |poly_trait_predicate: ty::PolyTraitClause<'tcx>| { let ocx = ObligationCtxt::new(infcx); infcx.enter_forall(obligation.predicate, |placeholder_obligation| { let obligation_trait_ref = ocx.normalize( @@ -791,7 +791,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { fn applicable_impls_to_mention( &self, obligation: &PredicateObligation<'tcx>, - trait_pred: ty::PolyTraitPredicate<'tcx>, + trait_pred: ty::PolyTraitClause<'tcx>, ) -> Option> { let mut ambiguities = compute_applicable_impls_for_diagnostics( self.infcx, diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs index 3734b8b4f6946..380c3bc63285a 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs @@ -26,7 +26,7 @@ use rustc_middle::traits::select::OverflowError; use rustc_middle::ty::abstract_const::NotConstEvaluatable; use rustc_middle::ty::error::{ExpectedFound, TypeError}; use rustc_middle::ty::print::{ - PrintPolyTraitPredicateExt, PrintPolyTraitRefExt as _, PrintTraitPredicateExt as _, + PrintPolyTraitClauseExt, PrintPolyTraitRefExt as _, PrintTraitClauseExt as _, PrintTraitRefExt as _, with_forced_trimmed_paths, }; use rustc_middle::ty::{ @@ -865,9 +865,9 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { // FIXME(const_trait_impl): We should recompute the clause with `[const]` // if it's `const`, and if it holds, explain that this bound only // *conditionally* holds. - let trait_ref = clause.map_bound(|clause| ty::TraitPredicate { + let trait_ref = clause.map_bound(|clause| ty::TraitClause { trait_ref: clause.trait_ref, - polarity: ty::PredicatePolarity::Positive, + polarity: ty::ClausePolarity::Positive, }); let mut file = None; @@ -980,7 +980,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { fn emit_specialized_closure_kind_error( &self, obligation: &PredicateObligation<'tcx>, - mut trait_pred: ty::PolyTraitPredicate<'tcx>, + mut trait_pred: ty::PolyTraitClause<'tcx>, ) -> Option { // If we end up on an `AsyncFnKindHelper` goal, try to unwrap the parent // `AsyncFn*` goal. @@ -1097,7 +1097,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { fn detect_negative_literal( &self, obligation: &PredicateObligation<'tcx>, - trait_pred: ty::PolyTraitPredicate<'tcx>, + trait_pred: ty::PolyTraitClause<'tcx>, err: &mut Diag<'_>, ) -> bool { if let ObligationCauseCode::UnOp { hir_id, .. } = obligation.cause.code() @@ -1132,7 +1132,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { fn try_conversion_context( &self, obligation: &PredicateObligation<'tcx>, - trait_pred: ty::PolyTraitPredicate<'tcx>, + trait_pred: ty::PolyTraitClause<'tcx>, err: &mut Diag<'_>, ) -> (bool, bool) { let span = obligation.cause.span; @@ -1343,7 +1343,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { err: &mut Diag<'_>, self_ty: Ty<'_>, found_ty: Option>, - trait_pred: ty::PolyTraitPredicate<'tcx>, + trait_pred: ty::PolyTraitClause<'tcx>, ) -> bool { match (self_ty.kind(), found_ty) { (ty::Adt(def, _), Some(ty)) @@ -1492,8 +1492,8 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { fn can_match_trait( &self, param_env: ty::ParamEnv<'tcx>, - goal: ty::TraitPredicate<'tcx>, - assumption: ty::PolyTraitPredicate<'tcx>, + goal: ty::TraitClause<'tcx>, + assumption: ty::PolyTraitClause<'tcx>, ) -> bool { // Fast path if goal.polarity != assumption.polarity() { @@ -2048,7 +2048,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { pub(super) fn find_similar_impl_candidates( &self, - trait_pred: ty::PolyTraitPredicate<'tcx>, + trait_pred: ty::PolyTraitClause<'tcx>, ) -> Vec> { let mut candidates: Vec<_> = self .tcx @@ -2080,7 +2080,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { &self, impl_candidates: &[ImplCandidate<'tcx>], obligation: &PredicateObligation<'tcx>, - trait_pred: ty::PolyTraitPredicate<'tcx>, + trait_pred: ty::PolyTraitClause<'tcx>, body_def_id: LocalDefId, err: &mut Diag<'_>, other: bool, @@ -2665,7 +2665,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { fn report_similar_impl_candidates_for_root_obligation( &self, obligation: &PredicateObligation<'tcx>, - trait_predicate: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>, + trait_predicate: ty::Binder<'tcx, ty::TraitClause<'tcx>>, body_def_id: LocalDefId, err: &mut Diag<'_>, ) { @@ -2733,7 +2733,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { fn check_same_trait_different_version( &self, err: &mut Diag<'_>, - trait_pred: ty::PolyTraitPredicate<'tcx>, + trait_pred: ty::PolyTraitClause<'tcx>, ) -> bool { let get_trait_impls = |trait_def_id| { let mut trait_impls = vec![]; @@ -2770,11 +2770,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { err.span_note(sp, crate_msg); } - fn note_adt_version_mismatch( - &self, - err: &mut Diag<'_>, - trait_pred: ty::PolyTraitPredicate<'tcx>, - ) { + fn note_adt_version_mismatch(&self, err: &mut Diag<'_>, trait_pred: ty::PolyTraitClause<'tcx>) { let ty::Adt(impl_self_def, _) = trait_pred.self_ty().skip_binder().peel_refs().kind() else { return; @@ -2836,7 +2832,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { &self, err: &mut Diag<'_>, obligation: &PredicateObligation<'tcx>, - trait_pred: ty::PolyTraitPredicate<'tcx>, + trait_pred: ty::PolyTraitClause<'tcx>, ) -> bool { let mut suggested = false; let trait_def_id = trait_pred.def_id(); @@ -2873,7 +2869,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { self.tcx, obligation.cause.clone(), obligation.param_env, - trait_pred.map_bound(|tr| ty::TraitPredicate { + trait_pred.map_bound(|tr| ty::TraitClause { trait_ref: ty::TraitRef::new(self.tcx, def_id, tr.trait_ref.args), ..tr }), @@ -2898,7 +2894,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { &self, err: &mut Diag<'_>, obligation: &PredicateObligation<'tcx>, - trait_pred: ty::PolyTraitPredicate<'tcx>, + trait_pred: ty::PolyTraitClause<'tcx>, ) -> bool { if self.check_same_trait_different_version(err, trait_pred) { return true; @@ -2919,7 +2915,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { pub(super) fn mk_trait_obligation_with_new_self_ty( &self, param_env: ty::ParamEnv<'tcx>, - trait_ref_and_ty: ty::Binder<'tcx, (ty::TraitPredicate<'tcx>, Ty<'tcx>)>, + trait_ref_and_ty: ty::Binder<'tcx, (ty::TraitClause<'tcx>, Ty<'tcx>)>, ) -> PredicateObligation<'tcx> { let trait_pred = trait_ref_and_ty .map_bound(|(tr, new_self_ty)| tr.with_replaced_self_ty(self.tcx, new_self_ty)); @@ -3050,7 +3046,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { fn get_standard_error_message( &self, - trait_predicate: ty::PolyTraitPredicate<'tcx>, + trait_predicate: ty::PolyTraitClause<'tcx>, predicate_constness: Option, post_message: String, long_ty_path: &mut Option, @@ -3067,9 +3063,9 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { fn select_transmute_obligation_for_reporting( &self, obligation: &PredicateObligation<'tcx>, - trait_predicate: ty::PolyTraitPredicate<'tcx>, + trait_predicate: ty::PolyTraitClause<'tcx>, root_obligation: &PredicateObligation<'tcx>, - ) -> (PredicateObligation<'tcx>, ty::PolyTraitPredicate<'tcx>) { + ) -> (PredicateObligation<'tcx>, ty::PolyTraitClause<'tcx>) { if obligation.predicate.has_non_region_param() || obligation.has_non_region_infer() { return (obligation.clone(), trait_predicate); } @@ -3114,7 +3110,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { fn get_safe_transmute_error_and_reason( &self, obligation: PredicateObligation<'tcx>, - trait_pred: ty::PolyTraitPredicate<'tcx>, + trait_pred: ty::PolyTraitClause<'tcx>, span: Span, ) -> GetSafeTransmuteErrorAndReason { use rustc_transmute::Answer; @@ -3299,7 +3295,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { self.tcx, ObligationCause::dummy(), param_env, - ty::TraitPredicate { trait_ref, polarity: ty::PredicatePolarity::Positive }, + ty::TraitClause { trait_ref, polarity: ty::ClausePolarity::Positive }, ); self.predicate_must_hold_modulo_regions(&obligation) @@ -3329,7 +3325,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { &self, root_obligation: &PredicateObligation<'tcx>, obligation: &PredicateObligation<'tcx>, - trait_predicate: ty::PolyTraitPredicate<'tcx>, + trait_predicate: ty::PolyTraitClause<'tcx>, err: &mut Diag<'_>, span: Span, is_fn_trait: bool, @@ -3372,13 +3368,13 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { && self.tcx.trait_impls_of(trait_def_id).is_empty() && !self.tcx.trait_is_auto(trait_def_id) && !self.tcx.trait_is_alias(trait_def_id) - && trait_predicate.polarity() == ty::PredicatePolarity::Positive + && trait_predicate.polarity() == ty::ClausePolarity::Positive { err.span_help( self.tcx.def_span(trait_def_id), msg!("this trait has no implementations, consider adding one"), ); - } else if !suggested && trait_predicate.polarity() == ty::PredicatePolarity::Positive { + } else if !suggested && trait_predicate.polarity() == ty::ClausePolarity::Positive { // Can't show anything else useful, try to find similar impls. let impl_candidates = self.find_similar_impl_candidates(trait_predicate); if !self.report_similar_impl_candidates( @@ -3413,7 +3409,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { fn add_help_message_for_fn_trait( &self, - trait_pred: ty::PolyTraitPredicate<'tcx>, + trait_pred: ty::PolyTraitClause<'tcx>, err: &mut Diag<'_>, implemented_kind: ty::ClosureKind, params: ty::Binder<'tcx, Ty<'tcx>>, @@ -3845,7 +3841,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { &self, param_env: ty::ParamEnv<'tcx>, ty: ty::Binder<'tcx, Ty<'tcx>>, - polarity: ty::PredicatePolarity, + polarity: ty::ClausePolarity, ) -> Result<(ty::ClosureKind, ty::Binder<'tcx, Ty<'tcx>>), ()> { self.commit_if_ok(|_| { for trait_def_id in [ @@ -3863,7 +3859,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { self.tcx, ObligationCause::dummy(), param_env, - ty.rebind(ty::TraitPredicate { trait_ref, polarity }), + ty.rebind(ty::TraitClause { trait_ref, polarity }), ); let ocx = ObligationCtxt::new(self); ocx.register_obligation(obligation); diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs index f7e4ec6164c99..ed22d4f4ef246 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs @@ -33,11 +33,11 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { pub fn on_unimplemented_note( &self, - trait_pred: ty::PolyTraitPredicate<'tcx>, + trait_pred: ty::PolyTraitClause<'tcx>, obligation: &PredicateObligation<'tcx>, long_ty_path: &mut Option, ) -> CustomDiagnostic { - if trait_pred.polarity() != ty::PredicatePolarity::Positive { + if trait_pred.polarity() != ty::ClausePolarity::Positive { return CustomDiagnostic::default(); } // This is needed as `on_unimplemented` is currently not allowed on trait aliases, @@ -59,7 +59,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { pub(crate) fn on_unimplemented_components( &self, - trait_pred: ty::PolyTraitPredicate<'tcx>, + trait_pred: ty::PolyTraitClause<'tcx>, obligation: &PredicateObligation<'tcx>, long_ty_path: &mut Option, print_infer_ty_var: bool, diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs index c87a75c4b9f1f..01b3026ff4e5b 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs @@ -27,7 +27,7 @@ use rustc_middle::traits::IsConstable; use rustc_middle::ty::adjustment::{Adjust, DerefAdjustKind}; use rustc_middle::ty::error::TypeError; use rustc_middle::ty::print::{ - PrintPolyTraitPredicateExt as _, PrintPolyTraitRefExt, PrintTraitPredicateExt as _, + PrintPolyTraitClauseExt as _, PrintPolyTraitRefExt, PrintTraitClauseExt as _, PrintTraitRefExt as _, with_forced_trimmed_paths, with_no_trimmed_paths, with_types_for_suggestion, }; @@ -128,7 +128,7 @@ pub fn suggest_restriction<'tcx, G: EmissionGuarantee>( err: &mut Diag<'_, G>, fn_sig: Option<&hir::FnSig<'_>>, projection: Option>, - trait_pred: ty::PolyTraitPredicate<'tcx>, + trait_pred: ty::PolyTraitClause<'tcx>, // When we are dealing with a trait, `super_traits` will be `Some`: // Given `trait T: A + B + C {}` // - ^^^^^^^^^ GenericBounds @@ -464,11 +464,11 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { pub fn suggest_restricting_param_bound( &self, err: &mut Diag<'_>, - trait_pred: ty::PolyTraitPredicate<'tcx>, + trait_pred: ty::PolyTraitClause<'tcx>, associated_ty: Option<(&'static str, Ty<'tcx>)>, mut body_def_id: LocalDefId, ) { - if trait_pred.skip_binder().polarity != ty::PredicatePolarity::Positive { + if trait_pred.skip_binder().polarity != ty::ClausePolarity::Positive { return; } @@ -703,7 +703,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { &self, obligation: &PredicateObligation<'tcx>, err: &mut Diag<'_>, - trait_pred: ty::PolyTraitPredicate<'tcx>, + trait_pred: ty::PolyTraitClause<'tcx>, ) -> bool { let mut code = obligation.cause.code(); if let ObligationCauseCode::FunctionArg { arg_hir_id, call_hir_id, .. } = code @@ -853,7 +853,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { // one at a time to account for cases such as &Box == &&T let trait_pred_and_ty = trait_pred.map_bound(|inner| { ( - ty::TraitPredicate { + ty::TraitClause { trait_ref: ty::TraitRef::new_from_args( self.tcx, inner.trait_ref.def_id, @@ -1007,7 +1007,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { &self, obligation: &PredicateObligation<'tcx>, err: &mut Diag<'_>, - trait_pred: ty::PolyTraitPredicate<'tcx>, + trait_pred: ty::PolyTraitClause<'tcx>, ) -> bool { // It doesn't make sense to make this suggestion outside of typeck... // (also autoderef will ICE...) @@ -1213,8 +1213,8 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { &self, obligation: &PredicateObligation<'tcx>, err: &mut Diag<'_>, - leaf_trait_predicate: ty::PolyTraitPredicate<'tcx>, - main_trait_predicate: ty::PolyTraitPredicate<'tcx>, + leaf_trait_predicate: ty::PolyTraitClause<'tcx>, + main_trait_predicate: ty::PolyTraitClause<'tcx>, span: Span, ) -> bool { let &[candidate] = &self.find_similar_impl_candidates(leaf_trait_predicate)[..] else { @@ -1269,7 +1269,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { &self, obligation: &PredicateObligation<'tcx>, err: &mut Diag<'_>, - trait_pred: ty::PolyTraitPredicate<'tcx>, + trait_pred: ty::PolyTraitClause<'tcx>, ) { let mut span = obligation.cause.span; while span.from_expansion() { @@ -1352,7 +1352,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { &self, obligation: &PredicateObligation<'tcx>, err: &mut Diag<'_>, - trait_pred: ty::PolyTraitPredicate<'tcx>, + trait_pred: ty::PolyTraitClause<'tcx>, ) -> bool { let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty()); self.enter_forall(self_ty, |ty: Ty<'_>| { @@ -1630,7 +1630,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { &self, obligation: &PredicateObligation<'tcx>, err: &mut Diag<'_>, - poly_trait_pred: ty::PolyTraitPredicate<'tcx>, + poly_trait_pred: ty::PolyTraitClause<'tcx>, has_custom_message: bool, ) -> bool { let span = obligation.cause.span; @@ -1862,7 +1862,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } // Try to apply the original trait bound by borrowing. - let mut try_borrowing = |old_pred: ty::PolyTraitPredicate<'tcx>, + let mut try_borrowing = |old_pred: ty::PolyTraitClause<'tcx>, blacklist: &[DefId]| -> bool { if blacklist.contains(&old_pred.def_id()) { @@ -2192,7 +2192,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { &self, obligation: &PredicateObligation<'tcx>, err: &mut Diag<'_>, - trait_pred: ty::PolyTraitPredicate<'tcx>, + trait_pred: ty::PolyTraitClause<'tcx>, ) -> bool { let mut span = obligation.cause.span; let mut trait_pred = trait_pred; @@ -2457,7 +2457,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { &self, obligation: &PredicateObligation<'tcx>, err: &mut Diag<'_>, - trait_pred: ty::PolyTraitPredicate<'tcx>, + trait_pred: ty::PolyTraitClause<'tcx>, ) { let points_at_arg = matches!(obligation.cause.code(), ObligationCauseCode::FunctionArg { .. },); @@ -2534,7 +2534,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { obligation: &PredicateObligation<'tcx>, err: &mut Diag<'_>, span: Span, - trait_pred: ty::PolyTraitPredicate<'tcx>, + trait_pred: ty::PolyTraitClause<'tcx>, ) -> bool { let node = self.tcx.hir_node_by_def_id(obligation.cause.body_def_id); if let hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn {sig, body: body_id, .. }, .. }) = node @@ -2641,7 +2641,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { &self, err: &mut Diag<'_>, obligation: &PredicateObligation<'tcx>, - trait_pred: ty::PolyTraitPredicate<'tcx>, + trait_pred: ty::PolyTraitClause<'tcx>, ) -> bool { let ObligationCauseCode::SizedReturnType = obligation.cause.code() else { return false; @@ -3353,7 +3353,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { interior_or_upvar_span: CoroutineInteriorOrUpvar, is_async: bool, outer_coroutine: Option, - trait_pred: ty::TraitPredicate<'tcx>, + trait_pred: ty::TraitClause<'tcx>, target_ty: Ty<'tcx>, obligation: &PredicateObligation<'tcx>, next_code: Option<&ObligationCauseCode<'tcx>>, @@ -4668,7 +4668,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { &self, err: &mut Diag<'_>, obligation: &PredicateObligation<'tcx>, - trait_pred: ty::PolyTraitPredicate<'tcx>, + trait_pred: ty::PolyTraitClause<'tcx>, span: Span, ) { let future_trait = self.tcx.require_lang_item(LangItem::Future, span); @@ -4739,7 +4739,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { &self, obligation: &PredicateObligation<'tcx>, err: &mut Diag<'_>, - trait_pred: ty::PolyTraitPredicate<'tcx>, + trait_pred: ty::PolyTraitClause<'tcx>, ) { let rhs_span = match obligation.cause.code() { ObligationCauseCode::BinOp { rhs_span, rhs_is_lit, .. } if *rhs_is_lit => rhs_span, @@ -4761,9 +4761,9 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { pub fn can_suggest_derive( &self, obligation: &PredicateObligation<'tcx>, - trait_pred: ty::PolyTraitPredicate<'tcx>, + trait_pred: ty::PolyTraitClause<'tcx>, ) -> bool { - if trait_pred.polarity() == ty::PredicatePolarity::Negative { + if trait_pred.polarity() == ty::ClausePolarity::Negative { return false; } let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else { @@ -4793,7 +4793,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } _ => None, }; - let trait_pred = trait_pred.map_bound_ref(|tr| ty::TraitPredicate { + let trait_pred = trait_pred.map_bound_ref(|tr| ty::TraitClause { trait_ref: ty::TraitRef::new(self.tcx, trait_pred.def_id(), [field_ty].into_iter().chain(trait_args), @@ -4814,7 +4814,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { &self, obligation: &PredicateObligation<'tcx>, err: &mut Diag<'_>, - trait_pred: ty::PolyTraitPredicate<'tcx>, + trait_pred: ty::PolyTraitClause<'tcx>, ) { let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else { return; @@ -4842,7 +4842,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { &self, obligation: &PredicateObligation<'tcx>, err: &mut Diag<'_>, - trait_pred: ty::PolyTraitPredicate<'tcx>, + trait_pred: ty::PolyTraitClause<'tcx>, ) { if let ObligationCauseCode::ImplDerived(_) = obligation.cause.code() && self @@ -5121,7 +5121,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { // Given the predicate `fn(&T): FnOnce<(U,)>`, extract `fn(&T)` and `(U,)`, // then suggest `Option::as_deref(_mut)` if `U` can deref to `T` - if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, .. })) + if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(ty::TraitClause { trait_ref, .. })) = failed_pred.kind().skip_binder() && tcx.is_fn_trait(trait_ref.def_id) && let [self_ty, found_ty] = trait_ref.args.as_slice() @@ -5293,13 +5293,13 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { let node = tcx.hir_node_by_def_id(tcx.hir_get_parent_item(expr.hir_id).def_id); - let pred = ty::Binder::dummy(ty::TraitPredicate { + let pred = ty::Binder::dummy(ty::TraitClause { trait_ref: ty::TraitRef::new( tcx, tcx.require_lang_item(LangItem::Clone, span), [*ty], ), - polarity: ty::PredicatePolarity::Positive, + polarity: ty::ClausePolarity::Positive, }); let Some(generics) = node.generics() else { continue; @@ -5671,7 +5671,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { &self, err: &mut Diag<'_>, obligation: &PredicateObligation<'tcx>, - trait_pred: ty::PolyTraitPredicate<'tcx>, + trait_pred: ty::PolyTraitClause<'tcx>, candidate_impls: &[ImplCandidate<'tcx>], span: Span, ) { @@ -5783,7 +5783,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { &self, err: &mut Diag<'_>, obligation: &PredicateObligation<'tcx>, - trait_predicate: ty::PolyTraitPredicate<'tcx>, + trait_predicate: ty::PolyTraitClause<'tcx>, ) { let ObligationCauseCode::FunctionArg { call_hir_id, .. } = obligation.cause.code() else { return; @@ -5855,7 +5855,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { pub(super) fn explain_hrtb_projection( &self, diag: &mut Diag<'_>, - pred: ty::PolyTraitPredicate<'tcx>, + pred: ty::PolyTraitClause<'tcx>, param_env: ty::ParamEnv<'tcx>, cause: &ObligationCause<'tcx>, ) { @@ -5925,7 +5925,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { pub(super) fn suggest_desugaring_async_fn_in_trait( &self, err: &mut Diag<'_>, - trait_pred: ty::PolyTraitPredicate<'tcx>, + trait_pred: ty::PolyTraitClause<'tcx>, ) { // Don't suggest if RTN is active -- we should prefer a where-clause bound instead. if self.tcx.features().return_type_notation() { @@ -6081,7 +6081,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { &self, obligation: &PredicateObligation<'tcx>, err: &mut Diag<'_>, - trait_pred: ty::PolyTraitPredicate<'tcx>, + trait_pred: ty::PolyTraitClause<'tcx>, ) { if ObligationCauseCode::QuestionMark != *obligation.cause.code().peel_derives() { return; @@ -6556,7 +6556,7 @@ impl<'a, 'hir> hir::intravisit::Visitor<'hir> for ReplaceImplTraitVisitor<'a> { pub(super) fn get_explanation_based_on_obligation<'tcx>( tcx: TyCtxt<'tcx>, obligation: &PredicateObligation<'tcx>, - trait_predicate: ty::PolyTraitPredicate<'tcx>, + trait_predicate: ty::PolyTraitClause<'tcx>, pre_message: String, long_ty_path: &mut Option, ) -> String { @@ -6573,7 +6573,7 @@ pub(super) fn get_explanation_based_on_obligation<'tcx>( Some(desc) => format!(" {desc}"), None => String::new(), }; - if let ty::PredicatePolarity::Positive = trait_predicate.polarity() { + if let ty::ClausePolarity::Positive = trait_predicate.polarity() { // If the trait in question is unstable, mention that fact in the diagnostic. // But if we're building with `-Zforce-unstable-if-unmarked` then _any_ trait // not explicitly marked stable is considered unstable, so the extra text is diff --git a/compiler/rustc_trait_selection/src/solve/delegate.rs b/compiler/rustc_trait_selection/src/solve/delegate.rs index 071c62d0b5ee0..6995cea23de52 100644 --- a/compiler/rustc_trait_selection/src/solve/delegate.rs +++ b/compiler/rustc_trait_selection/src/solve/delegate.rs @@ -165,7 +165,7 @@ impl<'tcx> rustc_next_trait_solver::delegate::SolverDelegate for SolverDelegate< && self.known_no_opaque_types_in_storage() { goal_stalled_on_args_or_nonempty_opaques(thin_vec![TyOrConstInferVar::Ty(vid)]) - } else if trait_pred.polarity() == ty::PredicatePolarity::Positive { + } else if trait_pred.polarity() == ty::ClausePolarity::Positive { match self.0.tcx.as_lang_item(trait_pred.def_id()) { Some(LangItem::Sized) | Some(LangItem::MetaSized) => { let predicate = self.resolve_vars_if_possible(goal.predicate); diff --git a/compiler/rustc_trait_selection/src/solve/fulfill/derive_errors.rs b/compiler/rustc_trait_selection/src/solve/fulfill/derive_errors.rs index ae7967ae6f277..27be427d28102 100644 --- a/compiler/rustc_trait_selection/src/solve/fulfill/derive_errors.rs +++ b/compiler/rustc_trait_selection/src/solve/fulfill/derive_errors.rs @@ -459,9 +459,9 @@ impl<'tcx> ProofTreeVisitor<'tcx> for BestObligation<'tcx> { ty::PredicateKind::Clause(ty::ClauseKind::Projection(projection)) if projection.projection_term.kind.is_trait_projection() => { - ChildMode::Trait(pred.kind().rebind(ty::TraitPredicate { + ChildMode::Trait(pred.kind().rebind(ty::TraitClause { trait_ref: projection.projection_term.trait_ref(tcx), - polarity: ty::PredicatePolarity::Positive, + polarity: ty::ClausePolarity::Positive, })) } ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(term)) => { @@ -552,7 +552,7 @@ enum ChildMode<'tcx> { // Try to derive an `ObligationCause::{ImplDerived,BuiltinDerived}`, // and skip all `GoalSource::Misc`, which represent useless obligations // such as alias-eq which may not hold. - Trait(ty::PolyTraitPredicate<'tcx>), + Trait(ty::PolyTraitClause<'tcx>), // Try to derive an `ObligationCause::{ImplDerived,BuiltinDerived}`, // and skip all `GoalSource::Misc`, which represent useless obligations // such as alias-eq which may not hold. @@ -568,7 +568,7 @@ fn derive_cause<'tcx>( candidate_kind: inspect::ProbeKind>, mut cause: ObligationCause<'tcx>, idx: usize, - parent_trait_pred: ty::PolyTraitPredicate<'tcx>, + parent_trait_pred: ty::PolyTraitClause<'tcx>, ) -> ObligationCause<'tcx> { match candidate_kind { inspect::ProbeKind::TraitCandidate { diff --git a/compiler/rustc_trait_selection/src/traits/auto_trait.rs b/compiler/rustc_trait_selection/src/traits/auto_trait.rs index 10f9c5ffca163..84cfddbb0dd33 100644 --- a/compiler/rustc_trait_selection/src/traits/auto_trait.rs +++ b/compiler/rustc_trait_selection/src/traits/auto_trait.rs @@ -94,12 +94,12 @@ impl<'tcx> AutoTraitFinder<'tcx> { let (infcx, orig_env) = tcx.infer_ctxt().build_with_typing_env(typing_env); let mut selcx = SelectionContext::new(&infcx); - for polarity in [ty::PredicatePolarity::Positive, ty::PredicatePolarity::Negative] { + for polarity in [ty::ClausePolarity::Positive, ty::ClausePolarity::Negative] { let result = selcx.select(&Obligation::new( tcx, ObligationCause::dummy(), orig_env, - ty::TraitPredicate { trait_ref, polarity }, + ty::TraitClause { trait_ref, polarity }, )); if let Ok(Some(ImplSource::UserDefined(_))) = result { debug!("find_auto_trait_generics({trait_ref:?}): manual impl found, bailing out"); @@ -229,9 +229,9 @@ impl<'tcx> AutoTraitFinder<'tcx> { .map(|field| field.ty(tcx, args).skip_norm_wip()) .filter(|field_ty| field_ty.has_non_region_param()) .map(|field_ty| { - ty::TraitPredicate { + ty::TraitClause { trait_ref: ty::TraitRef::new(tcx, trait_did, [field_ty]), - polarity: ty::PredicatePolarity::Positive, + polarity: ty::ClausePolarity::Positive, } .upcast(tcx) }) @@ -318,11 +318,11 @@ impl<'tcx> AutoTraitFinder<'tcx> { let mut already_visited = UnordSet::new(); let mut predicates = VecDeque::new(); - predicates.push_back(ty::Binder::dummy(ty::TraitPredicate { + predicates.push_back(ty::Binder::dummy(ty::TraitClause { trait_ref: ty::TraitRef::new(infcx.tcx, trait_did, [ty]), // Auto traits are positive - polarity: ty::PredicatePolarity::Positive, + polarity: ty::ClausePolarity::Positive, })); let computed_clauses = param_env.caller_bounds().iter(); @@ -651,7 +651,7 @@ impl<'tcx> AutoTraitFinder<'tcx> { nested: impl Iterator>, computed_clauses: &mut FxIndexSet>, fresh_preds: &mut FxIndexSet>, - predicates: &mut VecDeque>, + predicates: &mut VecDeque>, selcx: &mut SelectionContext<'_, 'tcx>, ) -> bool { let dummy_cause = ObligationCause::dummy(); diff --git a/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs b/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs index 6d86a2cce6400..dfed9b5309ae2 100644 --- a/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs +++ b/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs @@ -564,9 +564,9 @@ fn virtual_call_violations_for_method<'tcx>( // only if the autotrait is one of the trait object's trait bounds, like // in `dyn Trait + AutoTrait`. This guarantees that trait objects only // implement auto traits if the underlying type does as well. - if let ty::ClauseKind::Trait(ty::TraitPredicate { + if let ty::ClauseKind::Trait(ty::TraitClause { trait_ref: pred_trait_ref, - polarity: ty::PredicatePolarity::Positive, + polarity: ty::ClausePolarity::Positive, }) = clause.kind().skip_binder() && pred_trait_ref.self_ty() == tcx.types.self_param && tcx.trait_is_auto(pred_trait_ref.def_id) diff --git a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs index db863cb42f63e..63aabaec1c883 100644 --- a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs +++ b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs @@ -58,7 +58,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { let mut candidates = SelectionCandidateSet { vec: Vec::new(), ambiguous: false }; // Negative trait predicates have different rules than positive trait predicates. - if obligation.polarity() == ty::PredicatePolarity::Negative { + if obligation.polarity() == ty::ClausePolarity::Negative { self.assemble_candidates_for_trait_alias(obligation, &mut candidates); self.assemble_candidates_from_impls(obligation, &mut candidates); self.assemble_candidates_from_caller_bounds(stack, &mut candidates)?; diff --git a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs index 203ed5a62a8b9..3e84404e0dab9 100644 --- a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs +++ b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs @@ -385,7 +385,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { &mut self, obligation: &PolyTraitObligation<'tcx>, ) -> Result, SelectionError<'tcx>> { - assert_eq!(obligation.predicate.polarity(), ty::PredicatePolarity::Positive); + assert_eq!(obligation.predicate.polarity(), ty::ClausePolarity::Positive); let self_ty = obligation.predicate.self_ty().map_bound(|ty| self.infcx.shallow_resolve(ty)); let self_ty = self.infcx.enter_forall_and_leak_universe(self_ty); @@ -454,7 +454,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { cause: &ObligationCause<'tcx>, recursion_depth: usize, param_env: ty::ParamEnv<'tcx>, - parent_trait_pred: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>, + parent_trait_pred: ty::Binder<'tcx, ty::TraitClause<'tcx>>, ) -> ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>> { debug!(?impl_def_id, ?args, ?recursion_depth, "vtable_impl"); diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index 88962e0d37471..5e472d855ce94 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -129,7 +129,7 @@ struct TraitObligationStack<'prev, 'tcx> { /// The trait predicate from `obligation` but "freshened" with the /// selection-context's freshener. Used to check for recursion. - fresh_trait_pred: ty::PolyTraitPredicate<'tcx>, + fresh_trait_pred: ty::PolyTraitClause<'tcx>, /// Starts out equal to `depth` -- if, during evaluation, we /// encounter a cycle, then we will set this flag to the minimum @@ -1315,7 +1315,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { fn check_evaluation_cache( &self, param_env: ty::ParamEnv<'tcx>, - trait_pred: ty::PolyTraitPredicate<'tcx>, + trait_pred: ty::PolyTraitClause<'tcx>, ) -> Option { let infcx = self.infcx; let tcx = infcx.tcx; @@ -1335,7 +1335,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { fn insert_evaluation_cache( &mut self, param_env: ty::ParamEnv<'tcx>, - trait_pred: ty::PolyTraitPredicate<'tcx>, + trait_pred: ty::PolyTraitClause<'tcx>, dep_node: DepNodeIndex, result: EvaluationResult, ) { @@ -1425,8 +1425,8 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { if let ImplCandidate(def_id) = candidate { match (tcx.impl_polarity(def_id), obligation.polarity()) { (ty::ImplPolarity::Reservation, _) - | (ty::ImplPolarity::Positive, ty::PredicatePolarity::Positive) - | (ty::ImplPolarity::Negative, ty::PredicatePolarity::Negative) => { + | (ty::ImplPolarity::Positive, ty::ClausePolarity::Positive) + | (ty::ImplPolarity::Negative, ty::ClausePolarity::Negative) => { result.push(candidate); } _ => {} @@ -1496,7 +1496,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { fn can_use_global_caches( &self, param_env: ty::ParamEnv<'tcx>, - pred: ty::PolyTraitPredicate<'tcx>, + pred: ty::PolyTraitClause<'tcx>, ) -> bool { // If there are any inference variables in the `ParamEnv`, then we // always use a cache local to this particular scope. Otherwise, we @@ -1544,7 +1544,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { fn check_candidate_cache( &mut self, param_env: ty::ParamEnv<'tcx>, - cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>, + cache_fresh_trait_pred: ty::PolyTraitClause<'tcx>, ) -> Option>> { let infcx = self.infcx; let tcx = infcx.tcx; @@ -1597,7 +1597,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { fn insert_candidate_cache( &mut self, param_env: ty::ParamEnv<'tcx>, - cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>, + cache_fresh_trait_pred: ty::PolyTraitClause<'tcx>, dep_node: DepNodeIndex, candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>, ) { @@ -1927,7 +1927,7 @@ impl<'tcx> SelectionContext<'_, 'tcx> { // // Our handling of where-bounds is generally fairly messy but necessary for backwards // compatibility, see #50825 for why we need to handle global where-bounds like this. - let is_global = |c: ty::PolyTraitPredicate<'tcx>| c.is_global() && !c.has_bound_vars(); + let is_global = |c: ty::PolyTraitClause<'tcx>| c.is_global() && !c.has_bound_vars(); let param_candidates = candidates .iter() .filter_map(|c| if let ParamCandidate(p) = c.candidate { Some(p) } else { None }); @@ -2777,8 +2777,8 @@ impl<'tcx> SelectionContext<'_, 'tcx> { fn match_fresh_trait_preds( &self, - previous: ty::PolyTraitPredicate<'tcx>, - current: ty::PolyTraitPredicate<'tcx>, + previous: ty::PolyTraitClause<'tcx>, + current: ty::PolyTraitClause<'tcx>, ) -> bool { let mut matcher = _match::MatchAgainstFreshVars::new(self.tcx()); matcher.relate(previous, current).is_ok() @@ -2836,7 +2836,7 @@ impl<'tcx> SelectionContext<'_, 'tcx> { param_env: ty::ParamEnv<'tcx>, def_id: DefId, // of impl or trait args: GenericArgsRef<'tcx>, // for impl or trait - parent_trait_pred: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>, + parent_trait_pred: ty::Binder<'tcx, ty::TraitClause<'tcx>>, ) -> PredicateObligations<'tcx> { let tcx = self.tcx(); @@ -3030,7 +3030,7 @@ struct ProvisionalEvaluationCache<'tcx> { /// - then we determine that `E` is in error -- we will then clear /// all cache values whose DFN is >= 4 -- in this case, that /// means the cached value for `F`. - map: RefCell, ProvisionalEvaluation>>, + map: RefCell, ProvisionalEvaluation>>, /// The stack of terms that we assume to be well-formed because a `WF(term)` predicate /// is on the stack above (and because of wellformedness is coinductive). @@ -3071,7 +3071,7 @@ impl<'tcx> ProvisionalEvaluationCache<'tcx> { /// `reached_depth` (from the returned value). fn get_provisional( &self, - fresh_trait_pred: ty::PolyTraitPredicate<'tcx>, + fresh_trait_pred: ty::PolyTraitClause<'tcx>, ) -> Option { debug!( ?fresh_trait_pred, @@ -3089,7 +3089,7 @@ impl<'tcx> ProvisionalEvaluationCache<'tcx> { &self, from_dfn: usize, reached_depth: usize, - fresh_trait_pred: ty::PolyTraitPredicate<'tcx>, + fresh_trait_pred: ty::PolyTraitClause<'tcx>, result: EvaluationResult, ) { debug!(?from_dfn, ?fresh_trait_pred, ?result, "insert_provisional"); diff --git a/compiler/rustc_trait_selection/src/traits/util.rs b/compiler/rustc_trait_selection/src/traits/util.rs index d4d6b9c9c47b6..5685bd8ef55f8 100644 --- a/compiler/rustc_trait_selection/src/traits/util.rs +++ b/compiler/rustc_trait_selection/src/traits/util.rs @@ -8,8 +8,8 @@ use rustc_infer::traits::PolyTraitObligation; pub use rustc_infer::traits::util::*; use rustc_middle::ty::fast_reject::DeepRejectCtxt; use rustc_middle::ty::{ - self, PolyTraitPredicate, PredicatePolarity, SizedTraitKind, TraitPredicate, TraitRef, Ty, - TyCtxt, TypeFoldable, TypeVisitableExt, Unnormalized, + self, ClausePolarity, PolyTraitClause, SizedTraitKind, TraitClause, TraitRef, Ty, TyCtxt, + TypeFoldable, TypeVisitableExt, Unnormalized, }; pub use rustc_next_trait_solver::placeholder::{BoundVarReplacer, PlaceholderReplacer}; use rustc_span::Span; @@ -35,7 +35,7 @@ pub fn expand_trait_aliases<'tcx>( tcx: TyCtxt<'tcx>, clauses: impl IntoIterator, Span)>, ) -> ( - Vec<(ty::PolyTraitPredicate<'tcx>, SmallVec<[Span; 1]>)>, + Vec<(ty::PolyTraitClause<'tcx>, SmallVec<[Span; 1]>)>, Vec<(ty::PolyProjectionClause<'tcx>, Span)>, ) { let mut trait_preds = vec![]; @@ -227,7 +227,7 @@ pub fn sizedness_fast_path<'tcx>( // canonicalize and all that for such cases. if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred)) = predicate.kind().skip_binder() - && trait_pred.polarity == ty::PredicatePolarity::Positive + && trait_pred.polarity == ty::ClausePolarity::Positive { let sizedness = match tcx.as_lang_item(trait_pred.def_id()) { Some(LangItem::Sized) => SizedTraitKind::Sized, @@ -243,7 +243,7 @@ pub fn sizedness_fast_path<'tcx>( if matches!(trait_pred.self_ty().kind(), ty::Param(_) | ty::Placeholder(_)) { for clause in param_env.caller_bounds() { if let ty::ClauseKind::Trait(clause_pred) = clause.kind().skip_binder() - && clause_pred.polarity == ty::PredicatePolarity::Positive + && clause_pred.polarity == ty::ClausePolarity::Positive && clause_pred.self_ty() == trait_pred.self_ty() && (clause_pred.def_id() == trait_pred.def_id() || (sizedness == SizedTraitKind::MetaSized @@ -264,16 +264,16 @@ pub fn sizedness_fast_path<'tcx>( pub(crate) fn lazily_elaborate_sizedness_candidate<'tcx>( infcx: &InferCtxt<'tcx>, obligation: &PolyTraitObligation<'tcx>, - candidate: PolyTraitPredicate<'tcx>, -) -> PolyTraitPredicate<'tcx> { + candidate: PolyTraitClause<'tcx>, +) -> PolyTraitClause<'tcx> { if !infcx.tcx.is_lang_item(obligation.predicate.def_id(), LangItem::MetaSized) || !infcx.tcx.is_lang_item(candidate.def_id(), LangItem::Sized) { return candidate; } - if obligation.predicate.polarity() != PredicatePolarity::Positive - || candidate.polarity() != PredicatePolarity::Positive + if obligation.predicate.polarity() != ClausePolarity::Positive + || candidate.polarity() != ClausePolarity::Positive { return candidate; } @@ -286,7 +286,7 @@ pub(crate) fn lazily_elaborate_sizedness_candidate<'tcx>( return candidate; } - candidate.map_bound(|c| TraitPredicate { + candidate.map_bound(|c| TraitClause { trait_ref: TraitRef::new_from_args( infcx.tcx, obligation.predicate.def_id(), diff --git a/compiler/rustc_trait_selection/src/traits/wf.rs b/compiler/rustc_trait_selection/src/traits/wf.rs index 41d2d9adfea74..7bb93d342b639 100644 --- a/compiler/rustc_trait_selection/src/traits/wf.rs +++ b/compiler/rustc_trait_selection/src/traits/wf.rs @@ -127,7 +127,7 @@ pub fn trait_obligations<'tcx>( infcx: &InferCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, body_def_id: LocalDefId, - trait_pred: ty::TraitPredicate<'tcx>, + trait_pred: ty::TraitClause<'tcx>, span: Span, item: &'tcx hir::Item<'tcx>, ) -> PredicateObligations<'tcx> { @@ -374,7 +374,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { /// Pushes the obligations required for `trait_ref` to be WF into `self.out`. fn add_wf_preds_for_trait_pred( &mut self, - trait_pred: ty::TraitPredicate<'tcx>, + trait_pred: ty::TraitClause<'tcx>, elaborate: Elaborate, ) { let tcx = self.tcx(); @@ -382,7 +382,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { // Negative trait predicates don't require supertraits to hold, just // that their args are WF. - if trait_pred.polarity == ty::PredicatePolarity::Negative { + if trait_pred.polarity == ty::ClausePolarity::Negative { self.add_wf_preds_for_negative_trait_pred(trait_ref); return; } diff --git a/compiler/rustc_type_ir/src/elaborate.rs b/compiler/rustc_type_ir/src/elaborate.rs index 828bd107f5b34..912a5ac90f632 100644 --- a/compiler/rustc_type_ir/src/elaborate.rs +++ b/compiler/rustc_type_ir/src/elaborate.rs @@ -46,7 +46,7 @@ pub trait Elaboratable { &self, clause: I::Clause, span: I::Span, - parent_trait_pred: ty::Binder>, + parent_trait_pred: ty::Binder>, index: usize, ) -> Self; } @@ -76,7 +76,7 @@ impl Elaboratable for ClauseWithSupertraitSpan { &self, clause: ::Clause, supertrait_span: ::Span, - _parent_trait_pred: crate::Binder>, + _parent_trait_pred: crate::Binder>, _index: usize, ) -> Self { ClauseWithSupertraitSpan { clause, supertrait_span } @@ -151,7 +151,7 @@ impl> Elaborator { match bound_clause.skip_binder() { ty::ClauseKind::Trait(data) => { // Negative trait bounds do not imply any supertrait bounds - if data.polarity != ty::PredicatePolarity::Positive { + if data.polarity != ty::ClausePolarity::Positive { return; } diff --git a/compiler/rustc_type_ir/src/error.rs b/compiler/rustc_type_ir/src/error.rs index 4d16fb365e10d..59ceb4bd1e327 100644 --- a/compiler/rustc_type_ir/src/error.rs +++ b/compiler/rustc_type_ir/src/error.rs @@ -24,7 +24,7 @@ impl ExpectedFound { #[cfg_attr(feature = "nightly", rustc_pass_by_value)] pub enum TypeError { Mismatch, - PolarityMismatch(#[type_visitable(ignore)] ExpectedFound), + PolarityMismatch(#[type_visitable(ignore)] ExpectedFound), SafetyMismatch(#[type_visitable(ignore)] ExpectedFound), AbiMismatch(#[type_visitable(ignore)] ExpectedFound), Mutability, diff --git a/compiler/rustc_type_ir/src/generic_visit.rs b/compiler/rustc_type_ir/src/generic_visit.rs index 4010ac3da5ece..6f4b461575075 100644 --- a/compiler/rustc_type_ir/src/generic_visit.rs +++ b/compiler/rustc_type_ir/src/generic_visit.rs @@ -196,7 +196,7 @@ trivial_impls!( u64, u128, usize, - crate::PredicatePolarity, + crate::ClausePolarity, crate::BoundConstness, crate::DebruijnIndex, crate::solve::Certainty, diff --git a/compiler/rustc_type_ir/src/inherent.rs b/compiler/rustc_type_ir/src/inherent.rs index d2a26205bac72..333f01bca968d 100644 --- a/compiler/rustc_type_ir/src/inherent.rs +++ b/compiler/rustc_type_ir/src/inherent.rs @@ -461,7 +461,7 @@ pub trait Predicate>: + UpcastFrom> + UpcastFrom> + UpcastFrom>> - + UpcastFrom> + + UpcastFrom> + UpcastFrom> + UpcastFrom> + UpcastFrom>> @@ -502,8 +502,8 @@ pub trait Clause>: + UpcastFrom>> + UpcastFrom> + UpcastFrom>> - + UpcastFrom> - + UpcastFrom>> + + UpcastFrom> + + UpcastFrom>> + UpcastFrom> + UpcastFrom>> + IntoKind>> @@ -523,7 +523,7 @@ pub trait Clause>: .transpose() } - fn as_trait_clause(self) -> Option>> { + fn as_trait_clause(self) -> Option>> { self.kind() .map_bound(|clause| if let ty::ClauseKind::Trait(t) = clause { Some(t) } else { None }) .transpose() diff --git a/compiler/rustc_type_ir/src/interner.rs b/compiler/rustc_type_ir/src/interner.rs index 0cfa9574e4131..49899147d5747 100644 --- a/compiler/rustc_type_ir/src/interner.rs +++ b/compiler/rustc_type_ir/src/interner.rs @@ -31,7 +31,7 @@ pub trait Interner: + IrPrint> + IrPrint> + IrPrint> - + IrPrint> + + IrPrint> + IrPrint> + IrPrint> + IrPrint> diff --git a/compiler/rustc_type_ir/src/ir_print.rs b/compiler/rustc_type_ir/src/ir_print.rs index 5fd8f65c1a95c..8133862e1bf1a 100644 --- a/compiler/rustc_type_ir/src/ir_print.rs +++ b/compiler/rustc_type_ir/src/ir_print.rs @@ -5,7 +5,7 @@ use crate::{AliasConst, ClosureKind}; use crate::{ AliasTerm, AliasTy, Binder, CoercePredicate, ExistentialProjection, ExistentialTraitRef, FnSig, HostEffectClause, Interner, NormalizesTo, OutlivesClause, PatternKind, Placeholder, - ProjectionClause, Region, SubtypePredicate, TraitPredicate, TraitRef, + ProjectionClause, Region, SubtypePredicate, TraitClause, TraitRef, }; pub trait IrPrint { @@ -39,7 +39,7 @@ macro_rules! define_debug_via_print { define_display_via_print!( TraitRef, - TraitPredicate, + TraitClause, ExistentialTraitRef, ExistentialProjection, ProjectionClause, diff --git a/compiler/rustc_type_ir/src/macros.rs b/compiler/rustc_type_ir/src/macros.rs index 3c07b14df06f5..3741c80d0eb14 100644 --- a/compiler/rustc_type_ir/src/macros.rs +++ b/compiler/rustc_type_ir/src/macros.rs @@ -51,8 +51,8 @@ TrivialTypeTraversalImpls! { u64, // tidy-alphabetical-start crate::BoundConstness, + crate::ClausePolarity, crate::DebruijnIndex, - crate::PredicatePolarity, crate::UniverseIndex, crate::Variance, crate::solve::BuiltinImplSource, diff --git a/compiler/rustc_type_ir/src/predicate.rs b/compiler/rustc_type_ir/src/predicate.rs index 3520c049fea40..a819530485ccd 100644 --- a/compiler/rustc_type_ir/src/predicate.rs +++ b/compiler/rustc_type_ir/src/predicate.rs @@ -193,21 +193,21 @@ impl ty::Binder> { feature = "nightly", derive(Decodable_NoContext, Encodable_NoContext, StableHash_NoContext) )] -pub struct TraitPredicate { +pub struct TraitClause { pub trait_ref: TraitRef, /// If polarity is Positive: we are proving that the trait is implemented. /// /// If polarity is Negative: we are proving that a negative impl of this trait /// exists. (Note that coherence also checks whether negative impls of supertraits - /// exist via a series of predicates.) + /// exist via a series of clauses.) #[lift(identity)] - pub polarity: PredicatePolarity, + pub polarity: ClausePolarity, } -impl Eq for TraitPredicate {} +impl Eq for TraitClause {} -impl TraitPredicate { +impl TraitClause { pub fn with_replaced_self_ty(self, interner: I, self_ty: I::Ty) -> Self { Self { trait_ref: self.trait_ref.with_replaced_self_ty(interner, self_ty), @@ -224,7 +224,7 @@ impl TraitPredicate { } } -impl ty::Binder> { +impl ty::Binder> { pub fn def_id(self) -> I::TraitId { // Ok to skip binder since trait `DefId` does not care about regions. self.skip_binder().def_id() @@ -235,29 +235,26 @@ impl ty::Binder> { } #[inline] - pub fn polarity(self) -> PredicatePolarity { + pub fn polarity(self) -> ClausePolarity { self.skip_binder().polarity } } -impl UpcastFrom> for TraitPredicate { +impl UpcastFrom> for TraitClause { fn upcast_from(from: TraitRef, _tcx: I) -> Self { - TraitPredicate { trait_ref: from, polarity: PredicatePolarity::Positive } + TraitClause { trait_ref: from, polarity: ClausePolarity::Positive } } } -impl UpcastFrom>> for ty::Binder> { +impl UpcastFrom>> for ty::Binder> { fn upcast_from(from: ty::Binder>, _tcx: I) -> Self { - from.map_bound(|trait_ref| TraitPredicate { - trait_ref, - polarity: PredicatePolarity::Positive, - }) + from.map_bound(|trait_ref| TraitClause { trait_ref, polarity: ClausePolarity::Positive }) } } -impl fmt::Debug for TraitPredicate { +impl fmt::Debug for TraitClause { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "TraitPredicate({:?}, polarity:{:?})", self.trait_ref, self.polarity) + write!(f, "TraitClause({:?}, polarity:{:?})", self.trait_ref, self.polarity) } } @@ -296,31 +293,31 @@ impl ImplPolarity { } } -/// Polarity for a trait predicate. +/// Polarity for a trait clause. /// /// May either be negative or positive. /// Distinguished from [`ImplPolarity`] since we never compute goals with /// "reservation" level. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] #[cfg_attr(feature = "nightly", derive(Decodable_NoContext, Encodable_NoContext, StableHash))] -pub enum PredicatePolarity { +pub enum ClausePolarity { /// `Type: Trait` Positive, /// `Type: !Trait` Negative, } -impl PredicatePolarity { +impl ClausePolarity { /// Flips polarity by turning `Positive` into `Negative` and `Negative` into `Positive`. - pub fn flip(&self) -> PredicatePolarity { + pub fn flip(&self) -> ClausePolarity { match self { - PredicatePolarity::Positive => PredicatePolarity::Negative, - PredicatePolarity::Negative => PredicatePolarity::Positive, + ClausePolarity::Positive => ClausePolarity::Negative, + ClausePolarity::Negative => ClausePolarity::Positive, } } } -impl fmt::Display for PredicatePolarity { +impl fmt::Display for ClausePolarity { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Positive => f.write_str("positive"), diff --git a/compiler/rustc_type_ir/src/predicate_kind.rs b/compiler/rustc_type_ir/src/predicate_kind.rs index 7b4e91f7410aa..d6276ea0062bd 100644 --- a/compiler/rustc_type_ir/src/predicate_kind.rs +++ b/compiler/rustc_type_ir/src/predicate_kind.rs @@ -19,7 +19,7 @@ pub enum ClauseKind { /// Corresponds to `where Foo: Bar`. `Foo` here would be /// the `Self` type of the trait reference and `A`, `B`, and `C` /// would be the type parameters. - Trait(ty::TraitPredicate), + Trait(ty::TraitClause), /// `where 'a: 'r` RegionOutlives(ty::OutlivesClause>), diff --git a/compiler/rustc_type_ir/src/relate.rs b/compiler/rustc_type_ir/src/relate.rs index ccaf1550a6d31..98d251c6f1d64 100644 --- a/compiler/rustc_type_ir/src/relate.rs +++ b/compiler/rustc_type_ir/src/relate.rs @@ -639,16 +639,16 @@ impl> Relate for ty::Binder { } } -impl Relate for ty::TraitPredicate { +impl Relate for ty::TraitClause { fn relate>( relation: &mut R, - a: ty::TraitPredicate, - b: ty::TraitPredicate, - ) -> RelateResult> { + a: ty::TraitClause, + b: ty::TraitClause, + ) -> RelateResult> { let trait_ref = relation.relate(a.trait_ref, b.trait_ref)?; if a.polarity != b.polarity { return Err(TypeError::PolarityMismatch(ExpectedFound::new(a.polarity, b.polarity))); } - Ok(ty::TraitPredicate { trait_ref, polarity: a.polarity }) + Ok(ty::TraitClause { trait_ref, polarity: a.polarity }) } } diff --git a/compiler/rustc_type_ir/src/serialize.rs b/compiler/rustc_type_ir/src/serialize.rs index 7996fd9d32aae..835383b101136 100644 --- a/compiler/rustc_type_ir/src/serialize.rs +++ b/compiler/rustc_type_ir/src/serialize.rs @@ -47,7 +47,7 @@ macro_rules! impl_binder_encode_decode { impl_binder_encode_decode! { ty::FnSig, ty::FnSigTys, - ty::TraitPredicate, + ty::TraitClause, ty::ExistentialPredicate, ty::TraitRef, ty::ExistentialTraitRef, diff --git a/compiler/rustc_type_ir/src/unnormalized.rs b/compiler/rustc_type_ir/src/unnormalized.rs index e62f2763069ce..17a8e0e75fa78 100644 --- a/compiler/rustc_type_ir/src/unnormalized.rs +++ b/compiler/rustc_type_ir/src/unnormalized.rs @@ -9,8 +9,8 @@ use crate::fold::{FallibleTypeFolder, TypeFoldable, TypeFolder}; use crate::inherent::*; use crate::upcast::Upcast; use crate::{ - Binder, BoundConstness, ClauseKind, HostEffectClause, Interner, PredicatePolarity, - TraitPredicate, TraitRef, + Binder, BoundConstness, ClauseKind, ClausePolarity, HostEffectClause, Interner, TraitClause, + TraitRef, }; /// A wrapper for values that need normalization. @@ -114,7 +114,7 @@ impl Unnormalized> { } impl Unnormalized { - pub fn as_trait_clause(self) -> Option>>> { + pub fn as_trait_clause(self) -> Option>>> { self.value.as_trait_clause().map(|v| Unnormalized::new(v)) } @@ -123,7 +123,7 @@ impl Unnormalized { } } -impl Unnormalized>> { +impl Unnormalized>> { pub fn self_ty(self) -> Unnormalized> { self.map(|pred| pred.self_ty()) } @@ -133,7 +133,7 @@ impl Unnormalized>> { } #[inline] - pub fn polarity(self) -> PredicatePolarity { + pub fn polarity(self) -> ClausePolarity { self.value.skip_binder().polarity } } diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index b7046744b2895..b0134bfa307d3 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -451,7 +451,7 @@ pub(crate) fn clean_clause<'tcx>( } fn clean_poly_trait_predicate<'tcx>( - pred: ty::PolyTraitPredicate<'tcx>, + pred: ty::PolyTraitClause<'tcx>, cx: &mut DocContext<'tcx>, ) -> Option { // `T: [const] Destruct` is hidden because `T: Destruct` is a no-op. diff --git a/src/tools/clippy/clippy_lints/src/derive/derive_partial_eq_without_eq.rs b/src/tools/clippy/clippy_lints/src/derive/derive_partial_eq_without_eq.rs index 51412cd1d8a6e..65a305d361af8 100644 --- a/src/tools/clippy/clippy_lints/src/derive/derive_partial_eq_without_eq.rs +++ b/src/tools/clippy/clippy_lints/src/derive/derive_partial_eq_without_eq.rs @@ -5,7 +5,7 @@ use rustc_errors::Applicability; use rustc_hir::def_id::DefId; use rustc_hir::{self as hir, HirId}; use rustc_lint::LateContext; -use rustc_middle::ty::{self, ClauseKind, GenericParamDefKind, ParamEnv, TraitPredicate, Ty, TyCtxt, Upcast as _}; +use rustc_middle::ty::{self, ClauseKind, GenericParamDefKind, ParamEnv, TraitClause, Ty, TyCtxt, Upcast as _}; use rustc_span::{Span, sym}; use super::DERIVE_PARTIAL_EQ_WITHOUT_EQ; @@ -78,9 +78,9 @@ fn typing_env_for_derived_eq(tcx: TyCtxt<'_>, did: DefId, eq_trait_id: DefId) -> let param_env = ParamEnv::new(tcx.mk_clauses_from_iter(ty_clauses.iter().map(|&(c, _)| c).chain( params.iter().filter(|&&(_, needs_eq)| needs_eq).map(|&(param, _)| { - ClauseKind::Trait(TraitPredicate { + ClauseKind::Trait(TraitClause { trait_ref: ty::TraitRef::new(tcx, eq_trait_id, [tcx.mk_param_from_def(param)]), - polarity: ty::PredicatePolarity::Positive, + polarity: ty::ClausePolarity::Positive, }) .upcast(tcx) }), diff --git a/src/tools/clippy/clippy_lints/src/eta_reduction.rs b/src/tools/clippy/clippy_lints/src/eta_reduction.rs index e1ad4649a5e3e..d84166766aa4e 100644 --- a/src/tools/clippy/clippy_lints/src/eta_reduction.rs +++ b/src/tools/clippy/clippy_lints/src/eta_reduction.rs @@ -207,7 +207,7 @@ fn check_closure<'tcx>(cx: &LateContext<'tcx>, outer_receiver: Option<&Expr<'tcx .type_implements_fn_trait( cx.param_env, Binder::bind_with_vars(callee_ty_adjusted, List::empty()), - ty::PredicatePolarity::Positive, + ty::ClausePolarity::Positive, ) { span_lint_hir_and_then( diff --git a/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs index b9070f39296ad..cd0bc5a67f0c3 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs @@ -17,7 +17,7 @@ use rustc_lint::LateContext; use rustc_middle::mir::Mutability; use rustc_middle::ty::adjustment::{Adjust, Adjustment, DerefAdjustKind, OverloadedDeref}; use rustc_middle::ty::{ - self, ClauseKind, GenericArg, GenericArgKind, GenericArgsRef, ParamTy, ProjectionClause, TraitPredicate, Ty, + self, ClauseKind, GenericArg, GenericArgKind, GenericArgsRef, ParamTy, ProjectionClause, TraitClause, Ty, }; use rustc_span::Symbol; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _; @@ -473,12 +473,12 @@ fn get_callee_generic_args_and_args<'tcx>( None } -/// Returns the `TraitPredicate`s and `ProjectionClause`s for a function's input type. +/// Returns the `TraitClause`s and `ProjectionClause`s for a function's input type. fn get_input_traits_and_projections<'tcx>( cx: &LateContext<'tcx>, callee_def_id: DefId, input: Ty<'tcx>, -) -> (Vec>, Vec>) { +) -> (Vec>, Vec>) { let mut trait_predicates = Vec::new(); let mut projection_predicates = Vec::new(); for clause in cx.tcx.param_env(callee_def_id).caller_bounds() { @@ -740,7 +740,7 @@ fn check_borrow_predicate<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'tcx>) { && let Some(borrow_id) = cx.tcx.get_diagnostic_item(sym::Borrow) && cx.tcx.clauses_of(method_def_id).clauses.iter().any(|(clause, _)| { if let ClauseKind::Trait(trait_pred) = clause.kind().skip_binder() - && trait_pred.polarity == ty::PredicatePolarity::Positive + && trait_pred.polarity == ty::ClausePolarity::Positive && trait_pred.trait_ref.def_id == borrow_id { true diff --git a/src/tools/clippy/clippy_lints/src/needless_maybe_sized.rs b/src/tools/clippy/clippy_lints/src/needless_maybe_sized.rs index 079f5a4929dc7..79db70d7f97f0 100644 --- a/src/tools/clippy/clippy_lints/src/needless_maybe_sized.rs +++ b/src/tools/clippy/clippy_lints/src/needless_maybe_sized.rs @@ -4,7 +4,7 @@ use rustc_errors::Applicability; use rustc_hir::def_id::{DefId, DefIdMap}; use rustc_hir::{BoundPolarity, GenericBound, Generics, PolyTraitRef, TraitBoundModifiers, WherePredicateKind}; use rustc_lint::{LateContext, LateLintPass}; -use rustc_middle::ty::{ClauseKind, PredicatePolarity, Unnormalized}; +use rustc_middle::ty::{ClauseKind, ClausePolarity, Unnormalized}; use rustc_session::declare_lint_pass; use rustc_span::symbol::Ident; @@ -99,7 +99,7 @@ fn path_to_sized_bound(cx: &LateContext<'_>, trait_bound: &PolyTraitRef<'_>) -> .map(Unnormalized::skip_norm_wip) { if let ClauseKind::Trait(trait_predicate) = clause.kind().skip_binder() - && trait_predicate.polarity == PredicatePolarity::Positive + && trait_predicate.polarity == ClausePolarity::Positive && !path.contains(&trait_predicate.def_id()) { path.push(trait_predicate.def_id()); diff --git a/src/tools/clippy/clippy_lints/src/ranges.rs b/src/tools/clippy/clippy_lints/src/ranges.rs index 18b3ecb474bba..164d08c9a2fc3 100644 --- a/src/tools/clippy/clippy_lints/src/ranges.rs +++ b/src/tools/clippy/clippy_lints/src/ranges.rs @@ -15,7 +15,7 @@ use rustc_errors::Applicability; use rustc_hir::attrs::lang_items::LangItem; use rustc_hir::{BinOpKind, Expr, ExprKind, HirId, Node}; use rustc_lint::{LateContext, LateLintPass, Lint}; -use rustc_middle::ty::{self, ClauseKind, GenericArgKind, PredicatePolarity, Ty}; +use rustc_middle::ty::{self, ClauseKind, GenericArgKind, ClausePolarity, Ty}; use rustc_session::impl_lint_pass; use rustc_span::{DesugaringKind, Span, Spanned, SyntaxContext}; use std::cmp::Ordering; @@ -436,7 +436,7 @@ fn can_switch_ranges<'tcx>( .into_iter() .any(|c| { if let ClauseKind::Trait(t) = c.kind().skip_binder() - && t.polarity == PredicatePolarity::Positive + && t.polarity == ClausePolarity::Positive && matches!( cx.tcx.get_diagnostic_name(t.trait_ref.def_id), Some(sym::Iterator | sym::IntoIterator | sym::RangeBounds) diff --git a/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs b/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs index 60f21b87f63cd..193be59be6a6c 100644 --- a/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs +++ b/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs @@ -3,7 +3,7 @@ use rustc_hir::def_id::DefId; use rustc_hir::{Closure, Expr, ExprKind, StmtKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty; -use rustc_middle::ty::{ClauseKind, GenericClauses, ProjectionClause, TraitPredicate}; +use rustc_middle::ty::{ClauseKind, GenericClauses, ProjectionClause, TraitClause}; use rustc_session::declare_lint_pass; use rustc_span::{BytePos, Span, Symbol, sym}; @@ -40,7 +40,7 @@ fn get_trait_predicates_for_trait_ids<'tcx>( cx: &LateContext<'tcx>, generics: GenericClauses<'tcx>, trait_ids: &[Option], // At least 2 ids -) -> [Vec>; 3] { +) -> [Vec>; 3] { debug_assert!(trait_ids.len() >= 2); let mut preds = [Vec::new(), Vec::new(), Vec::new()]; for (clause, _) in generics.clauses { @@ -63,7 +63,7 @@ fn get_trait_predicates_for_trait_ids<'tcx>( fn get_projection_pred<'tcx>( cx: &LateContext<'tcx>, generics: GenericClauses<'tcx>, - trait_pred: TraitPredicate<'tcx>, + trait_pred: TraitClause<'tcx>, ) -> Option> { generics.clauses.iter().find_map(|(clause, _)| { if let ClauseKind::Projection(pred) = clause.kind().skip_binder() { diff --git a/tests/ui/associated-types/issue-65774-1.rs b/tests/ui/associated-types/issue-65774-1.rs index 9345140558b07..93b24471d7b7c 100644 --- a/tests/ui/associated-types/issue-65774-1.rs +++ b/tests/ui/associated-types/issue-65774-1.rs @@ -39,7 +39,7 @@ impl ProcessType for Process { // writer.my_write(valref) // This one causes the ICE: - // FulfillmentError(Obligation(predicate=Binder(TraitPredicate()), + // FulfillmentError(Obligation(predicate=Binder(TraitClause()), // depth=1),Unimplemented) let closure = |config: &mut ::MpuConfig| writer.my_write(&config); //~^ ERROR the trait bound `T: MyDisplay` is not satisfied diff --git a/tests/ui/associated-types/issue-65774-2.rs b/tests/ui/associated-types/issue-65774-2.rs index 171e0893b4719..accc349758cea 100644 --- a/tests/ui/associated-types/issue-65774-2.rs +++ b/tests/ui/associated-types/issue-65774-2.rs @@ -40,7 +40,7 @@ impl ProcessType for Process { //~^ ERROR the trait bound `T: MyDisplay` is not satisfied // This one causes the ICE: - // FulfillmentError(Obligation(predicate=Binder(TraitPredicate()), + // FulfillmentError(Obligation(predicate=Binder(TraitClause()), // depth=1),Unimplemented) /*let closure = |config: &mut ::MpuConfig| writer.my_write(&config); closure(valref);*/ diff --git a/tests/ui/attributes/dump-clauses.stderr b/tests/ui/attributes/dump-clauses.stderr index d5726fe60e602..93d2057d88cd5 100644 --- a/tests/ui/attributes/dump-clauses.stderr +++ b/tests/ui/attributes/dump-clauses.stderr @@ -4,12 +4,12 @@ error: rustc_dump_clauses LL | trait Trait: Iterator | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | - = note: Binder { value: TraitPredicate(, polarity:Positive), bound_vars: [] } - = note: Binder { value: TraitPredicate(, polarity:Positive), bound_vars: [] } - = note: Binder { value: TraitPredicate(<::Item as std::marker::Copy>, polarity:Positive), bound_vars: [] } - = note: Binder { value: TraitPredicate(, polarity:Positive), bound_vars: [] } - = note: Binder { value: TraitPredicate(>, polarity:Positive), bound_vars: [] } - = note: Binder { value: TraitPredicate(>, polarity:Positive), bound_vars: [] } + = note: Binder { value: TraitClause(, polarity:Positive), bound_vars: [] } + = note: Binder { value: TraitClause(, polarity:Positive), bound_vars: [] } + = note: Binder { value: TraitClause(<::Item as std::marker::Copy>, polarity:Positive), bound_vars: [] } + = note: Binder { value: TraitClause(, polarity:Positive), bound_vars: [] } + = note: Binder { value: TraitClause(>, polarity:Positive), bound_vars: [] } + = note: Binder { value: TraitClause(>, polarity:Positive), bound_vars: [] } error: rustc_dump_clauses --> $DIR/dump-clauses.rs:13:5 @@ -17,15 +17,15 @@ error: rustc_dump_clauses LL | type Assoc: std::ops::Deref | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | - = note: Binder { value: TraitPredicate(, polarity:Positive), bound_vars: [] } - = note: Binder { value: TraitPredicate(, polarity:Positive), bound_vars: [] } - = note: Binder { value: TraitPredicate(<::Item as std::marker::Copy>, polarity:Positive), bound_vars: [] } - = note: Binder { value: TraitPredicate(, polarity:Positive), bound_vars: [] } - = note: Binder { value: TraitPredicate(>, polarity:Positive), bound_vars: [] } - = note: Binder { value: TraitPredicate(>, polarity:Positive), bound_vars: [] } - = note: Binder { value: TraitPredicate(

, polarity:Positive), bound_vars: [] } - = note: Binder { value: TraitPredicate(

, polarity:Positive), bound_vars: [] } - = note: Binder { value: TraitPredicate(<>::Assoc<()> as std::marker::Copy>, polarity:Positive), bound_vars: [] } + = note: Binder { value: TraitClause(, polarity:Positive), bound_vars: [] } + = note: Binder { value: TraitClause(, polarity:Positive), bound_vars: [] } + = note: Binder { value: TraitClause(<::Item as std::marker::Copy>, polarity:Positive), bound_vars: [] } + = note: Binder { value: TraitClause(, polarity:Positive), bound_vars: [] } + = note: Binder { value: TraitClause(>, polarity:Positive), bound_vars: [] } + = note: Binder { value: TraitClause(>, polarity:Positive), bound_vars: [] } + = note: Binder { value: TraitClause(

, polarity:Positive), bound_vars: [] } + = note: Binder { value: TraitClause(

, polarity:Positive), bound_vars: [] } + = note: Binder { value: TraitClause(<>::Assoc<()> as std::marker::Copy>, polarity:Positive), bound_vars: [] } error: rustc_dump_item_bounds --> $DIR/dump-clauses.rs:13:5 @@ -34,8 +34,8 @@ LL | type Assoc: std::ops::Deref | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: Binder { value: ProjectionClause(Alias { kind: ProjectionTy { def_id: DefId(..) }, args: [Alias(No, Alias { kind: Projection { def_id: DefId(..) }, args: [Self/#0, T/#1, P/#2], .. })], .. }, Term::Ty(())), bound_vars: [] } - = note: Binder { value: TraitPredicate(<>::Assoc

as std::ops::Deref>, polarity:Positive), bound_vars: [] } - = note: Binder { value: TraitPredicate(<>::Assoc

as std::marker::Sized>, polarity:Positive), bound_vars: [] } + = note: Binder { value: TraitClause(<>::Assoc

as std::ops::Deref>, polarity:Positive), bound_vars: [] } + = note: Binder { value: TraitClause(<>::Assoc

as std::marker::Sized>, polarity:Positive), bound_vars: [] } error: aborting due to 3 previous errors diff --git a/tests/ui/const-generics/adt_const_params/byte-string-u8-validation.rs b/tests/ui/const-generics/adt_const_params/byte-string-u8-validation.rs index 1ba509cb9ed43..5bb893719de30 100644 --- a/tests/ui/const-generics/adt_const_params/byte-string-u8-validation.rs +++ b/tests/ui/const-generics/adt_const_params/byte-string-u8-validation.rs @@ -8,7 +8,7 @@ struct ConstBytes //~^ ERROR rustc_dump_clauses //~| NOTE Binder { value: ConstArgHasType(T/#0, &'static [*mut u8; 3_usize]), bound_vars: [] } -//~| NOTE Binder { value: TraitPredicate( as std::marker::Sized>, polarity:Positive), bound_vars: [] } +//~| NOTE Binder { value: TraitClause( as std::marker::Sized>, polarity:Positive), bound_vars: [] } //~| NOTE expected because of the type of the const parameter where ConstBytes: Sized; diff --git a/tests/ui/const-generics/adt_const_params/byte-string-u8-validation.stderr b/tests/ui/const-generics/adt_const_params/byte-string-u8-validation.stderr index 5626c6f04eb7a..bb7e4e253f907 100644 --- a/tests/ui/const-generics/adt_const_params/byte-string-u8-validation.stderr +++ b/tests/ui/const-generics/adt_const_params/byte-string-u8-validation.stderr @@ -19,7 +19,7 @@ LL | struct ConstBytes | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: Binder { value: ConstArgHasType(T/#0, &'static [*mut u8; 3_usize]), bound_vars: [] } - = note: Binder { value: TraitPredicate( as std::marker::Sized>, polarity:Positive), bound_vars: [] } + = note: Binder { value: TraitClause( as std::marker::Sized>, polarity:Positive), bound_vars: [] } error: aborting due to 2 previous errors diff --git a/tests/ui/supertrait-shadowing/assoc-type-clauses.rs b/tests/ui/supertrait-shadowing/assoc-type-clauses.rs index ebd9bc15ef282..e4092f53d8ac8 100644 --- a/tests/ui/supertrait-shadowing/assoc-type-clauses.rs +++ b/tests/ui/supertrait-shadowing/assoc-type-clauses.rs @@ -24,22 +24,22 @@ impl C for T {} #[rustc_dump_clauses] fn a_bound>() {} //~^ ERROR rustc_dump_clauses -//~| NOTE TraitPredicate( -//~| NOTE TraitPredicate( +//~| NOTE TraitClause( +//~| NOTE TraitClause( //~| NOTE A::Assoc #[rustc_dump_clauses] fn b_bound>() {} //~^ ERROR rustc_dump_clauses -//~| NOTE TraitPredicate( -//~| NOTE TraitPredicate( +//~| NOTE TraitClause( +//~| NOTE TraitClause( //~| NOTE B::Assoc #[rustc_dump_clauses] fn c_bound>() {} //~^ ERROR rustc_dump_clauses -//~| NOTE TraitPredicate( -//~| NOTE TraitPredicate( +//~| NOTE TraitClause( +//~| NOTE TraitClause( //~| NOTE B::Assoc fn main() {} diff --git a/tests/ui/supertrait-shadowing/assoc-type-clauses.stderr b/tests/ui/supertrait-shadowing/assoc-type-clauses.stderr index f2e8347e17fb4..50649b1c1fe3b 100644 --- a/tests/ui/supertrait-shadowing/assoc-type-clauses.stderr +++ b/tests/ui/supertrait-shadowing/assoc-type-clauses.stderr @@ -4,8 +4,8 @@ error: rustc_dump_clauses LL | fn a_bound>() {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | - = note: Binder { value: TraitPredicate(, polarity:Positive), bound_vars: [] } - = note: Binder { value: TraitPredicate(, polarity:Positive), bound_vars: [] } + = note: Binder { value: TraitClause(, polarity:Positive), bound_vars: [] } + = note: Binder { value: TraitClause(, polarity:Positive), bound_vars: [] } = note: Binder { value: ProjectionClause(Alias { kind: ProjectionTy { def_id: DefId(0:4 ~ assoc_type_clauses[HASH]::A::Assoc) }, args: [T/#0], .. }, Term::Ty(i8)), bound_vars: [] } error: rustc_dump_clauses @@ -14,8 +14,8 @@ error: rustc_dump_clauses LL | fn b_bound>() {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | - = note: Binder { value: TraitPredicate(, polarity:Positive), bound_vars: [] } - = note: Binder { value: TraitPredicate(, polarity:Positive), bound_vars: [] } + = note: Binder { value: TraitClause(, polarity:Positive), bound_vars: [] } + = note: Binder { value: TraitClause(, polarity:Positive), bound_vars: [] } = note: Binder { value: ProjectionClause(Alias { kind: ProjectionTy { def_id: DefId(0:9 ~ assoc_type_clauses[HASH]::B::Assoc) }, args: [T/#0], .. }, Term::Ty(i16)), bound_vars: [] } error: rustc_dump_clauses @@ -24,8 +24,8 @@ error: rustc_dump_clauses LL | fn c_bound>() {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | - = note: Binder { value: TraitPredicate(, polarity:Positive), bound_vars: [] } - = note: Binder { value: TraitPredicate(, polarity:Positive), bound_vars: [] } + = note: Binder { value: TraitClause(, polarity:Positive), bound_vars: [] } + = note: Binder { value: TraitClause(, polarity:Positive), bound_vars: [] } = note: Binder { value: ProjectionClause(Alias { kind: ProjectionTy { def_id: DefId(0:9 ~ assoc_type_clauses[HASH]::B::Assoc) }, args: [T/#0], .. }, Term::Ty(i16)), bound_vars: [] } error: aborting due to 3 previous errors diff --git a/tests/ui/traits/cache-reached-depth-ice.rs b/tests/ui/traits/cache-reached-depth-ice.rs index bc62adf4842d3..921e557bba4af 100644 --- a/tests/ui/traits/cache-reached-depth-ice.rs +++ b/tests/ui/traits/cache-reached-depth-ice.rs @@ -42,5 +42,5 @@ fn test() {} fn main() { test::(); - //~^ ERROR evaluate(Binder { value: TraitPredicate(, polarity:Positive), bound_vars: [] }) = Ok(EvaluatedToOk) + //~^ ERROR evaluate(Binder { value: TraitClause(, polarity:Positive), bound_vars: [] }) = Ok(EvaluatedToOk) } diff --git a/tests/ui/traits/cache-reached-depth-ice.stderr b/tests/ui/traits/cache-reached-depth-ice.stderr index fd76dc92dfbd7..5cff962008e04 100644 --- a/tests/ui/traits/cache-reached-depth-ice.stderr +++ b/tests/ui/traits/cache-reached-depth-ice.stderr @@ -1,4 +1,4 @@ -error: evaluate(Binder { value: TraitPredicate(, polarity:Positive), bound_vars: [] }) = Ok(EvaluatedToOk) +error: evaluate(Binder { value: TraitClause(, polarity:Positive), bound_vars: [] }) = Ok(EvaluatedToOk) --> $DIR/cache-reached-depth-ice.rs:44:5 | LL | fn test() {} diff --git a/tests/ui/traits/issue-83538-tainted-cache-after-cycle.rs b/tests/ui/traits/issue-83538-tainted-cache-after-cycle.rs index 5136aef4f7aa7..5cb3e255580e3 100644 --- a/tests/ui/traits/issue-83538-tainted-cache-after-cycle.rs +++ b/tests/ui/traits/issue-83538-tainted-cache-after-cycle.rs @@ -57,10 +57,10 @@ fn main() { // Key is that Vec is "ok" and Third<'_, Ty> is "ok modulo regions": forward(); - //~^ ERROR evaluate(Binder { value: TraitPredicate( as std::marker::Unpin>, polarity:Positive), bound_vars: [] }) = Ok(EvaluatedToOk) - //~| ERROR evaluate(Binder { value: TraitPredicate( as std::marker::Unpin>, polarity:Positive), bound_vars: [] }) = Ok(EvaluatedToOkModuloRegions) + //~^ ERROR evaluate(Binder { value: TraitClause( as std::marker::Unpin>, polarity:Positive), bound_vars: [] }) = Ok(EvaluatedToOk) + //~| ERROR evaluate(Binder { value: TraitClause( as std::marker::Unpin>, polarity:Positive), bound_vars: [] }) = Ok(EvaluatedToOkModuloRegions) reverse(); - //~^ ERROR evaluate(Binder { value: TraitPredicate( as std::marker::Unpin>, polarity:Positive), bound_vars: [] }) = Ok(EvaluatedToOk) - //~| ERROR evaluate(Binder { value: TraitPredicate( as std::marker::Unpin>, polarity:Positive), bound_vars: [] }) = Ok(EvaluatedToOkModuloRegions) + //~^ ERROR evaluate(Binder { value: TraitClause( as std::marker::Unpin>, polarity:Positive), bound_vars: [] }) = Ok(EvaluatedToOk) + //~| ERROR evaluate(Binder { value: TraitClause( as std::marker::Unpin>, polarity:Positive), bound_vars: [] }) = Ok(EvaluatedToOkModuloRegions) } diff --git a/tests/ui/traits/issue-83538-tainted-cache-after-cycle.stderr b/tests/ui/traits/issue-83538-tainted-cache-after-cycle.stderr index 96baec76a17ec..f61d09a3fb737 100644 --- a/tests/ui/traits/issue-83538-tainted-cache-after-cycle.stderr +++ b/tests/ui/traits/issue-83538-tainted-cache-after-cycle.stderr @@ -1,4 +1,4 @@ -error: evaluate(Binder { value: TraitPredicate( as std::marker::Unpin>, polarity:Positive), bound_vars: [] }) = Ok(EvaluatedToOk) +error: evaluate(Binder { value: TraitClause( as std::marker::Unpin>, polarity:Positive), bound_vars: [] }) = Ok(EvaluatedToOk) --> $DIR/issue-83538-tainted-cache-after-cycle.rs:59:5 | LL | Vec: Unpin, @@ -7,7 +7,7 @@ LL | Vec: Unpin, LL | forward(); | ^^^^^^^ -error: evaluate(Binder { value: TraitPredicate( as std::marker::Unpin>, polarity:Positive), bound_vars: [] }) = Ok(EvaluatedToOkModuloRegions) +error: evaluate(Binder { value: TraitClause( as std::marker::Unpin>, polarity:Positive), bound_vars: [] }) = Ok(EvaluatedToOkModuloRegions) --> $DIR/issue-83538-tainted-cache-after-cycle.rs:59:5 | LL | Third<'a, Ty>: Unpin, @@ -16,7 +16,7 @@ LL | Third<'a, Ty>: Unpin, LL | forward(); | ^^^^^^^ -error: evaluate(Binder { value: TraitPredicate( as std::marker::Unpin>, polarity:Positive), bound_vars: [] }) = Ok(EvaluatedToOkModuloRegions) +error: evaluate(Binder { value: TraitClause( as std::marker::Unpin>, polarity:Positive), bound_vars: [] }) = Ok(EvaluatedToOkModuloRegions) --> $DIR/issue-83538-tainted-cache-after-cycle.rs:63:5 | LL | Third<'a, Ty>: Unpin, @@ -25,7 +25,7 @@ LL | Third<'a, Ty>: Unpin, LL | reverse(); | ^^^^^^^ -error: evaluate(Binder { value: TraitPredicate( as std::marker::Unpin>, polarity:Positive), bound_vars: [] }) = Ok(EvaluatedToOk) +error: evaluate(Binder { value: TraitClause( as std::marker::Unpin>, polarity:Positive), bound_vars: [] }) = Ok(EvaluatedToOk) --> $DIR/issue-83538-tainted-cache-after-cycle.rs:63:5 | LL | Vec: Unpin, diff --git a/tests/ui/traits/issue-85360-eval-obligation-ice.rs b/tests/ui/traits/issue-85360-eval-obligation-ice.rs index f7c49049e2d33..fd77c729a248c 100644 --- a/tests/ui/traits/issue-85360-eval-obligation-ice.rs +++ b/tests/ui/traits/issue-85360-eval-obligation-ice.rs @@ -7,10 +7,10 @@ use core::marker::PhantomData; fn main() { test::>>(make()); - //~^ ERROR evaluate(Binder { value: TraitPredicate(> as std::marker::Sized>, polarity:Positive), bound_vars: [] }) = Ok(EvaluatedToOk) + //~^ ERROR evaluate(Binder { value: TraitClause(> as std::marker::Sized>, polarity:Positive), bound_vars: [] }) = Ok(EvaluatedToOk) test::>>(make()); - //~^ ERROR evaluate(Binder { value: TraitPredicate(> as std::marker::Sized>, polarity:Positive), bound_vars: [] }) = Ok(EvaluatedToOkModuloRegions) + //~^ ERROR evaluate(Binder { value: TraitClause(> as std::marker::Sized>, polarity:Positive), bound_vars: [] }) = Ok(EvaluatedToOkModuloRegions) } #[rustc_evaluate_where_clauses] diff --git a/tests/ui/traits/issue-85360-eval-obligation-ice.stderr b/tests/ui/traits/issue-85360-eval-obligation-ice.stderr index d2b00a45a4f15..d7861984411de 100644 --- a/tests/ui/traits/issue-85360-eval-obligation-ice.stderr +++ b/tests/ui/traits/issue-85360-eval-obligation-ice.stderr @@ -1,4 +1,4 @@ -error: evaluate(Binder { value: TraitPredicate(> as std::marker::Sized>, polarity:Positive), bound_vars: [] }) = Ok(EvaluatedToOk) +error: evaluate(Binder { value: TraitClause(> as std::marker::Sized>, polarity:Positive), bound_vars: [] }) = Ok(EvaluatedToOk) --> $DIR/issue-85360-eval-obligation-ice.rs:9:5 | LL | test::>>(make()); @@ -7,7 +7,7 @@ LL | test::>>(make()); LL | fn test(_: T) {} | ----- predicate -error: evaluate(Binder { value: TraitPredicate(> as std::marker::Sized>, polarity:Positive), bound_vars: [] }) = Ok(EvaluatedToOkModuloRegions) +error: evaluate(Binder { value: TraitClause(> as std::marker::Sized>, polarity:Positive), bound_vars: [] }) = Ok(EvaluatedToOkModuloRegions) --> $DIR/issue-85360-eval-obligation-ice.rs:12:5 | LL | test::>>(make()); diff --git a/tests/ui/traits/project-modulo-regions.rs b/tests/ui/traits/project-modulo-regions.rs index 3af5fbc7ea76d..42e188aba70db 100644 --- a/tests/ui/traits/project-modulo-regions.rs +++ b/tests/ui/traits/project-modulo-regions.rs @@ -48,8 +48,8 @@ fn test(val: MyStruct) where Helper: HelperTrait { fn foo(val: MyStruct) { test(val); - //[with_clause]~^ ERROR evaluate(Binder { value: TraitPredicate(, polarity:Positive), bound_vars: [] }) = Ok(EvaluatedToOkModuloRegions) - //[without_clause]~^^ ERROR evaluate(Binder { value: TraitPredicate(, polarity:Positive), bound_vars: [] }) = Ok(EvaluatedToOk) + //[with_clause]~^ ERROR evaluate(Binder { value: TraitClause(, polarity:Positive), bound_vars: [] }) = Ok(EvaluatedToOkModuloRegions) + //[without_clause]~^^ ERROR evaluate(Binder { value: TraitClause(, polarity:Positive), bound_vars: [] }) = Ok(EvaluatedToOk) } fn main() {} diff --git a/tests/ui/traits/project-modulo-regions.with_clause.stderr b/tests/ui/traits/project-modulo-regions.with_clause.stderr index 0e3081ddfdfeb..398116153bc3d 100644 --- a/tests/ui/traits/project-modulo-regions.with_clause.stderr +++ b/tests/ui/traits/project-modulo-regions.with_clause.stderr @@ -1,4 +1,4 @@ -error: evaluate(Binder { value: TraitPredicate(, polarity:Positive), bound_vars: [] }) = Ok(EvaluatedToOkModuloRegions) +error: evaluate(Binder { value: TraitClause(, polarity:Positive), bound_vars: [] }) = Ok(EvaluatedToOkModuloRegions) --> $DIR/project-modulo-regions.rs:50:5 | LL | fn test(val: MyStruct) where Helper: HelperTrait { diff --git a/tests/ui/traits/project-modulo-regions.without_clause.stderr b/tests/ui/traits/project-modulo-regions.without_clause.stderr index 830a07c4f5f79..283da7f136f8c 100644 --- a/tests/ui/traits/project-modulo-regions.without_clause.stderr +++ b/tests/ui/traits/project-modulo-regions.without_clause.stderr @@ -1,4 +1,4 @@ -error: evaluate(Binder { value: TraitPredicate(, polarity:Positive), bound_vars: [] }) = Ok(EvaluatedToOk) +error: evaluate(Binder { value: TraitClause(, polarity:Positive), bound_vars: [] }) = Ok(EvaluatedToOk) --> $DIR/project-modulo-regions.rs:50:5 | LL | fn test(val: MyStruct) where Helper: HelperTrait { diff --git a/tests/ui/type-alias-impl-trait/in-where-clause.stderr b/tests/ui/type-alias-impl-trait/in-where-clause.stderr index 122cfdcabadd5..97b63a8ad3e32 100644 --- a/tests/ui/type-alias-impl-trait/in-where-clause.stderr +++ b/tests/ui/type-alias-impl-trait/in-where-clause.stderr @@ -21,7 +21,7 @@ note: ...which requires computing revealed normalized predicates of `foo::{const | LL | [0; 1 + 2] | ^^^^^ - = note: ...which requires revealing opaque types in `[Binder { value: TraitPredicate(, polarity:Positive), bound_vars: [] }]`... + = note: ...which requires revealing opaque types in `[Binder { value: TraitClause(, polarity:Positive), bound_vars: [] }]`... note: ...which requires computing type of `Bar::{opaque#0}`... --> $DIR/in-where-clause.rs:5:12 | From 00d78026aee7a6cf313a450a522aa339dce1ae95 Mon Sep 17 00:00:00 2001 From: mejrs <59372212+mejrs@users.noreply.github.com> Date: Tue, 18 Aug 2026 14:57:00 +0200 Subject: [PATCH 14/26] remove rustc_error_messages dependency --- Cargo.lock | 1 - compiler/rustc_middle/Cargo.toml | 1 - compiler/rustc_middle/src/ty/consts.rs | 6 +++--- 3 files changed, 3 insertions(+), 5 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a00c6c397962a..0b9856570621e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4385,7 +4385,6 @@ dependencies = [ "rustc_ast_ir", "rustc_crate_store", "rustc_data_structures", - "rustc_error_messages", "rustc_errors", "rustc_feature", "rustc_graphviz", diff --git a/compiler/rustc_middle/Cargo.toml b/compiler/rustc_middle/Cargo.toml index 2d4b3ced37fd1..96506291735ba 100644 --- a/compiler/rustc_middle/Cargo.toml +++ b/compiler/rustc_middle/Cargo.toml @@ -17,7 +17,6 @@ rustc_ast = { path = "../rustc_ast" } rustc_ast_ir = { path = "../rustc_ast_ir" } rustc_crate_store = { path = "../rustc_crate_store" } rustc_data_structures = { path = "../rustc_data_structures" } -rustc_error_messages = { path = "../rustc_error_messages" } # Used for intra-doc links rustc_errors = { path = "../rustc_errors" } rustc_feature = { path = "../rustc_feature" } rustc_graphviz = { path = "../rustc_graphviz" } diff --git a/compiler/rustc_middle/src/ty/consts.rs b/compiler/rustc_middle/src/ty/consts.rs index df25b08168609..d2f761a1c5d7f 100644 --- a/compiler/rustc_middle/src/ty/consts.rs +++ b/compiler/rustc_middle/src/ty/consts.rs @@ -1,8 +1,8 @@ use std::borrow::Cow; use rustc_data_structures::intern::Interned; -use rustc_error_messages::MultiSpan; use rustc_macros::StableHash; +use rustc_span::Span; use rustc_type_ir::walk::TypeWalker; use rustc_type_ir::{self as ir, TypeFlags, WithCachedTypeInfo}; @@ -142,9 +142,9 @@ impl<'tcx> Const<'tcx> { /// Like [Ty::new_error_with_message] but for constants. #[track_caller] - pub fn new_error_with_message>( + pub fn new_error_with_message( tcx: TyCtxt<'tcx>, - span: S, + span: Span, msg: impl Into>, ) -> Const<'tcx> { let reported = tcx.dcx().span_delayed_bug(span, msg); From 951f07a7d6f1e24b4cc5bc617f0ea6dd7c55eb76 Mon Sep 17 00:00:00 2001 From: aerooneqq Date: Tue, 18 Aug 2026 17:16:10 +0300 Subject: [PATCH 15/26] Rename test so it matches the issue --- .../{fn-sig-cycle-ice-154560.rs => fn-sig-cycle-ice-154056.rs} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename tests/ui/parallel-rustc/{fn-sig-cycle-ice-154560.rs => fn-sig-cycle-ice-154056.rs} (100%) diff --git a/tests/ui/parallel-rustc/fn-sig-cycle-ice-154560.rs b/tests/ui/parallel-rustc/fn-sig-cycle-ice-154056.rs similarity index 100% rename from tests/ui/parallel-rustc/fn-sig-cycle-ice-154560.rs rename to tests/ui/parallel-rustc/fn-sig-cycle-ice-154056.rs From 3bf400306f61e33002372759caf693a2afa5c6ca Mon Sep 17 00:00:00 2001 From: Scott Mabin Date: Thu, 6 Aug 2026 13:18:02 +0100 Subject: [PATCH 16/26] Require windowed (and exception) for Xtensa ABI Rust only supports the windowed Xtensa calling convention on all upstream targets (esp32 family). Mark windowed and exception as ABI-required features so a mismatched -Ctarget-cpu cannot silently change the ABI. Discussion: https://github.com/rust-lang/rust/pull/160530#discussion_r3720972977 --- compiler/rustc_target/src/target_features.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/compiler/rustc_target/src/target_features.rs b/compiler/rustc_target/src/target_features.rs index 0500c1619f301..f891608b37b53 100644 --- a/compiler/rustc_target/src/target_features.rs +++ b/compiler/rustc_target/src/target_features.rs @@ -1467,6 +1467,17 @@ impl Target { // No ABI-relevant target features have been identified thus far. NOTHING } + Arch::Xtensa => { + // All Rust-supported Xtensa targets use the windowed register ABI + // (esp32 and later). Non-windowed (historical esp8266 / CALL0) is not + // a supported Rust ABI. Requiring `windowed` here means selecting a + // -Ctarget-cpu that does not provide windowed produces an ABI mismatch + // warning rather than silent UB when mixed with windowed code. + // + // `windowed` implies `exception` in XTENSA_FEATURES, so exception is + // always enabled for this ABI; list it explicitly for complete constraints. + FeatureConstraints { required: &["windowed", "exception"], incompatible: &[] } + } _ => NOTHING, } } From 8a446b5e12c45a99cbfa842b19f3e0e5589c1fbf Mon Sep 17 00:00:00 2001 From: Scott Mabin Date: Mon, 17 Aug 2026 18:21:38 +0100 Subject: [PATCH 17/26] Add Xtensa to the ABI flag consistency match Rust currently supports a single Xtensa ABI, so apply the same spec checks as wasm: unspecified llvm_abiname, no floatabi, no rustc_abi, and unspecified or other cfg_abi. --- compiler/rustc_target/src/spec/consistency.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/compiler/rustc_target/src/spec/consistency.rs b/compiler/rustc_target/src/spec/consistency.rs index 5bbce71316009..ab6b8cf6af6d6 100644 --- a/compiler/rustc_target/src/spec/consistency.rs +++ b/compiler/rustc_target/src/spec/consistency.rs @@ -616,6 +616,19 @@ impl Target { "invalid `target_abi` for wasm" ); } + Arch::Xtensa => { + check!( + self.llvm_abiname == LlvmAbi::Unspecified, + "`llvm_abiname` is unused on Xtensa" + ); + check!(self.llvm_floatabi.is_none(), "`llvm_floatabi` is unused on Xtensa"); + check!(self.rustc_abi.is_none(), "`rustc_abi` is unused on Xtensa"); + check_matches!( + self.cfg_abi, + CfgAbi::Unspecified | CfgAbi::Other(_), + "invalid `target_abi` for Xtensa" + ); + } ref arch => { check!(self.rustc_abi.is_none(), "`rustc_abi` is unused on {arch}"); // Ensure consistency among built-in targets, but give JSON targets the opportunity From 840899306463b92d4b24e6ea04b84e0ba0b3ba72 Mon Sep 17 00:00:00 2001 From: aerooneqq Date: Tue, 18 Aug 2026 18:43:49 +0300 Subject: [PATCH 18/26] Enable overflow checks in `rustc_thread_pool` --- Cargo.toml | 7 ------- 1 file changed, 7 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 0d36c3f242d82..63d96ff2a62ac 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -60,13 +60,6 @@ exclude = [ "obj", ] -[profile.release.package.rustc_thread_pool] -# The rustc fork of Rayon has deadlock detection code which intermittently -# causes overflows in the CI (see https://github.com/rust-lang/rust/issues/90227) -# so we turn overflow checks off for now. -# FIXME: This workaround should be removed once #90227 is fixed. -overflow-checks = false - # These are very thin wrappers around executing lld with the right binary name. # Basically nothing within them can go wrong without having been explicitly logged anyway. # We ship these in every rustc tarball and even after compression they add up From 30a47c4fb2fe23b398cb255a7341f55719268505 Mon Sep 17 00:00:00 2001 From: Tim Neumann Date: Tue, 18 Aug 2026 19:44:43 +0200 Subject: [PATCH 19/26] Relax codgen test variable regex --- tests/codegen-llvm/try_question_mark_nop.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/codegen-llvm/try_question_mark_nop.rs b/tests/codegen-llvm/try_question_mark_nop.rs index a09fa0a49019d..af8274ec9b5c1 100644 --- a/tests/codegen-llvm/try_question_mark_nop.rs +++ b/tests/codegen-llvm/try_question_mark_nop.rs @@ -105,7 +105,7 @@ pub fn option_nop_match_64(x: Option) -> Option { pub fn option_nop_traits_64(x: Option) -> Option { // CHECK: start: // CHECK-NEXT: %[[TRUNC:[0-9]+]] = trunc nuw i64 %0 to i1 - // CHECK-NEXT: %[[SEL:\.[0-9]+]] = select i1 %[[TRUNC]], i64 %1, i64 undef + // CHECK-NEXT: %[[SEL:\.[0-9]*]] = select i1 %[[TRUNC]], i64 %1, i64 undef // CHECK-NEXT: insertvalue { i64, i64 } // CHECK-NEXT: insertvalue { i64, i64 } // CHECK-NEXT: ret { i64, i64 } From 57d455b6c871703181aba388a614c5f5adb22230 Mon Sep 17 00:00:00 2001 From: xizheyin Date: Wed, 19 Aug 2026 02:46:54 +0800 Subject: [PATCH 20/26] Doc: clarify how `Read::bytes` handling Interrupted errors --- library/alloc/src/io/read.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/library/alloc/src/io/read.rs b/library/alloc/src/io/read.rs index e3d26218c09a0..2f4e891aa4429 100644 --- a/library/alloc/src/io/read.rs +++ b/library/alloc/src/io/read.rs @@ -488,6 +488,14 @@ pub trait Read { /// which can be very inefficient for data that's not in memory, /// such as `File`. Consider using a `BufReader` in such cases. /// + /// # Errors + /// + /// When the returned iterator calls [`Iterator::next`], + /// if it encounters an error of the kind [`ErrorKind::Interrupted`] + /// then the error is ignored and it will try to read the byte again. + /// + /// [`ErrorKind::Interrupted`]: crate::io::ErrorKind::Interrupted + /// /// # Examples /// /// `File`s implement `Read`: From 1724501193e9611f2ac05941d2557d43f59be900 Mon Sep 17 00:00:00 2001 From: Nia Deckers Date: Fri, 14 Aug 2026 23:15:12 +0200 Subject: [PATCH 21/26] allocator: wording & grammar nitpicks ref mut const unstable matching ref vec, vecdeque: rename alloc to allocator staticallocator on ref mut as well wording will be the death of me words order words random word words random good eeeeeeeeeeeee oh yeah these need the bound --- .../alloc/src/collections/vec_deque/mod.rs | 2 +- library/alloc/src/rc.rs | 6 +- library/alloc/src/sync.rs | 4 +- library/alloc/src/vec/mod.rs | 16 ++-- library/core/src/alloc/mod.rs | 79 +++++++++++-------- tests/ui/allocator/157089-box-pin-in.stderr | 3 + .../ui/allocator/159445-unsize-pin-box.stderr | 3 + 7 files changed, 67 insertions(+), 46 deletions(-) diff --git a/library/alloc/src/collections/vec_deque/mod.rs b/library/alloc/src/collections/vec_deque/mod.rs index 940fce7377938..5f1fd39bbbc3b 100644 --- a/library/alloc/src/collections/vec_deque/mod.rs +++ b/library/alloc/src/collections/vec_deque/mod.rs @@ -3991,7 +3991,7 @@ impl From> for VecDeque { /// any additional memory. #[inline] fn from(other: Vec) -> Self { - let (ptr, len, cap, alloc) = other.into_raw_parts_with_alloc(); + let (ptr, len, cap, alloc) = other.into_raw_parts_with_allocator(); Self { head: WrappedIndex::zero(), len, diff --git a/library/alloc/src/rc.rs b/library/alloc/src/rc.rs index e639a32370703..689f015d586b0 100644 --- a/library/alloc/src/rc.rs +++ b/library/alloc/src/rc.rs @@ -2983,7 +2983,7 @@ impl From for Rc { #[cfg(not(no_global_oom_handling))] #[stable(feature = "shared_from_slice", since = "1.21.0")] -impl From> for Rc { +impl From> for Rc { /// Move a boxed object to a new, reference counted, allocation. /// /// # Example @@ -3002,7 +3002,7 @@ impl From> for Rc { #[cfg(not(no_global_oom_handling))] #[stable(feature = "shared_from_slice", since = "1.21.0")] -impl From> for Rc<[T], A> { +impl From> for Rc<[T], A> { /// Allocates a reference-counted slice and moves `v`'s items into it. /// /// # Example @@ -3016,7 +3016,7 @@ impl From> for Rc<[T], A> { #[inline] fn from(v: Vec) -> Rc<[T], A> { unsafe { - let (vec_ptr, len, cap, alloc) = v.into_raw_parts_with_alloc(); + let (vec_ptr, len, cap, alloc) = v.into_raw_parts_with_allocator(); let rc_ptr = Self::allocate_for_slice_in(len, &alloc); ptr::copy_nonoverlapping(vec_ptr, (&raw mut (*rc_ptr).value) as *mut T, len); diff --git a/library/alloc/src/sync.rs b/library/alloc/src/sync.rs index 5ea0fd3a394d4..fd4a630422011 100644 --- a/library/alloc/src/sync.rs +++ b/library/alloc/src/sync.rs @@ -4050,7 +4050,7 @@ impl From for Arc { #[cfg(not(no_global_oom_handling))] #[stable(feature = "shared_from_slice", since = "1.21.0")] -impl From> for Arc { +impl From> for Arc { /// Move a boxed object to a new, reference-counted allocation. /// /// # Example @@ -4083,7 +4083,7 @@ impl From> for Arc<[T], A> { #[inline] fn from(v: Vec) -> Arc<[T], A> { unsafe { - let (vec_ptr, len, cap, alloc) = v.into_raw_parts_with_alloc(); + let (vec_ptr, len, cap, alloc) = v.into_raw_parts_with_allocator(); let rc_ptr = Self::allocate_for_slice_in(len, &alloc); ptr::copy_nonoverlapping(vec_ptr, (&raw mut (*rc_ptr).data) as *mut T, len); diff --git a/library/alloc/src/vec/mod.rs b/library/alloc/src/vec/mod.rs index a619aa6e5427b..698379b96a696 100644 --- a/library/alloc/src/vec/mod.rs +++ b/library/alloc/src/vec/mod.rs @@ -1140,7 +1140,7 @@ impl Vec { /// v.push(3); /// /// // Deconstruct the vector into parts. - /// let (p, len, cap, alloc) = v.into_raw_parts_with_alloc(); + /// let (p, len, cap, alloc) = v.into_raw_parts_with_allocator(); /// /// unsafe { /// // Overwrite memory with 4, 5, 6 @@ -1337,7 +1337,7 @@ impl Vec { /// v.push(0); /// v.push(1); /// - /// let (ptr, len, cap, alloc) = v.into_raw_parts_with_alloc(); + /// let (ptr, len, cap, alloc) = v.into_raw_parts_with_allocator(); /// /// let rebuilt = unsafe { /// // We can now make changes to the components, such as @@ -1351,7 +1351,7 @@ impl Vec { #[must_use = "losing the pointer will leak memory"] #[unstable(feature = "allocator_api", issue = "32838")] #[rustc_const_unstable(feature = "allocator_api", issue = "32838")] - pub const fn into_raw_parts_with_alloc(self) -> (*mut T, usize, usize, A) { + pub const fn into_raw_parts_with_allocator(self) -> (*mut T, usize, usize, A) { let mut me = ManuallyDrop::new(self); let len = me.len(); let capacity = me.capacity(); @@ -1402,7 +1402,7 @@ impl Vec { #[unstable(feature = "allocator_api", issue = "32838")] #[rustc_const_unstable(feature = "allocator_api", issue = "32838")] pub const fn into_parts_with_alloc(self) -> (NonNull, usize, usize, A) { - let (ptr, len, capacity, alloc) = self.into_raw_parts_with_alloc(); + let (ptr, len, capacity, alloc) = self.into_raw_parts_with_allocator(); // SAFETY: A `Vec` always has a non-null pointer. (unsafe { NonNull::new_unchecked(ptr) }, len, capacity, alloc) } @@ -3439,10 +3439,10 @@ impl Vec { self.buf.shrink_to_fit(cap - cap_remainder); } - let (ptr, _, _, alloc) = self.into_raw_parts_with_alloc(); + let (ptr, _, _, alloc) = self.into_raw_parts_with_allocator(); // SAFETY: - // - `ptr` and `alloc` were just returned from `self.into_raw_parts_with_alloc()` + // - `ptr` and `alloc` were just returned from `self.into_raw_parts_with_allocator()` // - `[T; N]` has the same alignment as `T` // - `size_of::<[T; N]>() * cap / N == size_of::() * cap` // - `len / N <= cap / N` because `len <= cap` @@ -3515,7 +3515,7 @@ impl Vec { let (ptr, length, capacity, alloc) = self.into_parts_with_alloc(); debug_assert_eq!(length, 0); // SAFETY: - // - `ptr` and `alloc` were just returned from `self.into_raw_parts_with_alloc()` + // - `ptr` and `alloc` were just returned from `self.into_raw_parts_with_allocator()` // - `T` & `U` have the same layout, so `capacity` does not need to be changed and we can safely use `alloc.dealloc` later // - the original vector was cleared, so there is no problem with "transmuting" the stored values unsafe { Vec::from_parts_in(ptr.cast::(), length, capacity, alloc) } @@ -3686,7 +3686,7 @@ impl Vec<[T; N], A> { /// ``` #[stable(feature = "slice_flatten", since = "1.80.0")] pub fn into_flattened(self) -> Vec { - let (ptr, len, cap, alloc) = self.into_raw_parts_with_alloc(); + let (ptr, len, cap, alloc) = self.into_raw_parts_with_allocator(); let (new_len, new_cap) = if T::IS_ZST { (len.checked_mul(N).expect("vec len overflow"), usize::MAX) } else { diff --git a/library/core/src/alloc/mod.rs b/library/core/src/alloc/mod.rs index 7816709ac4663..5fed1fae2a2d2 100644 --- a/library/core/src/alloc/mod.rs +++ b/library/core/src/alloc/mod.rs @@ -49,21 +49,27 @@ impl fmt::Display for AllocError { /// An implementation of `Allocator` can allocate, grow, shrink, and deallocate arbitrary blocks of /// data described via [`Layout`][]. /// -/// `Allocator` is designed to be implemented on ZSTs, references, or smart pointers. -/// An allocator for `MyAlloc([u8; N])` cannot be moved, without updating the pointers to the -/// allocated memory. +/// `Allocator` is mostly designed to be implemented on ZSTs, references, or smart pointers, +/// but can also be implemented directly on the underlying memory-owning type so long as it +/// upholds the necessary guarantees. In general, an allocator for `MyAlloc([u8; N])` cannot be +/// moved, without updating the pointers to the allocated memory. /// /// In contrast to [`GlobalAlloc`][], `Allocator` allows zero-sized allocations. If an underlying /// allocator does not support this (like jemalloc) or responds by returning a null pointer /// (such as `libc::malloc`), this must be caught by the implementation. /// +/// In order to be usable in a flexible manner while still being sound, implementors of the trait +/// must uphold very detailed semantics as explained below; the following terms are thus provided +/// as vocabulary for allocator safety and implementation requirements: +/// /// ### Equivalent allocators /// /// Multiple allocator values can sometimes be interchangeable with each other. /// When this is the case, we refer to those allocators as being *equivalent* to /// each other. /// -/// The following conditions are sufficient conditions for allocators to be equivalent. +/// Users of allocators may assume the following are true of equivalent allocators, +/// and implementors must ensure these rules are upheld: /// * An allocator is equivalent to itself. (Equivalence is reflexive.) /// * If an allocator is equivalent to a second allocator, then /// the second allocator is also equivalent to the first. (Equivalence is symmetric.) @@ -73,9 +79,8 @@ impl fmt::Display for AllocError { /// (Equivalence is transitive.) /// * Moving, subtyping, unsize-coercing, or trait-upcasting an allocator does not change /// what the allocator is equivalent to. -/// * Copying or cloning allocator results in an allocator that's -/// equivalent to the initial allocator, should the [`AllocatorClone`] trait -/// be implemented. +/// * Copying or cloning an allocator creates an equivalent one, should the +/// [`AllocatorClone`] trait be implemented. /// /// Additionally, implementors of `Allocator` may specify additional equivalences /// between allocators. It is the responsibility of such implementors to make sure @@ -104,14 +109,14 @@ impl fmt::Display for AllocError { /// * The memory block is deallocated. This occurs when the memory block /// is passed as an argument to a [`deallocate`] call, or when it is passed /// as an argument to a [`grow`], [`grow_zeroed`] or [`shrink`] call that returns `Ok`. -/// * All (equivalent) allocators that this memory block is allocated with, -/// each has one of the following happen to them: +/// * For all (equivalent) allocators that this memory block is currently allocated by, at +/// least one of the following has occurred: /// * The allocator's destructor runs. -/// * The allocator is mutated through public API taking `&mut` access. +/// * The allocator is mutated through a public or otherwise untrusted API taking `&mut` access. /// * One of the borrow-checker lifetimes in the allocator's type expires. /// /// Note that these conditions imply that a collection may ensure that -/// any specific currently allocated memory block won't be invalidated, by: +/// any specific currently allocated memory block won't be invalidated by: /// * not deallocating that memory block, /// * owning an allocator that memory block is allocated with, and /// * not publicly exposing `&mut` access to that allocator. @@ -120,11 +125,11 @@ impl fmt::Display for AllocError { /// allowed to invalidate its memory blocks. Furthermore, unsafe public API /// of an allocator with `&` access must document that they invalidate /// memory blocks (e.g., by calling `deallocate`) if they do. Therefore, -/// collections may safely expose `&` access to its allocator. +/// a collection may safely expose `&` access to its allocator. /// -/// Also note that, even in cases where are other "alive" allocators known to be -/// equivalent to a given collection's allocator, most collections still should -/// not publicly expose `&mut` access to its allocator. The fact that there are +/// Also note that, even in cases where there are other "alive" allocators known +/// to be equivalent to a given collection's allocator, most collections still should +/// not publicly expose `&mut` access to their allocators. The fact that there are /// other "alive" allocators would prevent this `&mut` access from invalidating /// the collection's memory block, but public `&mut` access is still likely to /// be unsound, since a user could replace the collection's allocator with @@ -140,8 +145,8 @@ impl fmt::Display for AllocError { /// /// ### Memory fitting /// -/// Some of the methods require that a `layout` *fit* a memory block or vice versa. This means that the -/// following conditions must hold: +/// Some of the methods require that a `layout` *fits* a memory block or vice versa. This means +/// that the following conditions must hold: /// * the memory block must be *currently allocated* with alignment of [`layout.align()`], and /// * [`layout.size()`] must fall in the range `min ..= max`, where: /// - `min` is the size of the layout used to allocate the block, and @@ -154,28 +159,33 @@ impl fmt::Display for AllocError { /// # Safety /// /// Implementors of `Allocator` must ensure that a memory block that -/// is [*currently allocated*] by the allocator points to valid memory, +/// is [*currently allocated*] by the allocator points to valid memory /// until that memory block is [*invalidated*]. The implementor must also /// not violate this invariant of `Allocator` via allocator equivalences -/// that are in the implementor's control (e.g., via an incorrect `unsafe -/// impl AllocatorClone for MyAllocator`). +/// that are in the implementor's control, and generally ensure that equivalence +/// is respected. /// /// Additionally, any memory block returned by the allocator must /// satisfy the allocation invariants described in `core::ptr`. /// In particular, if a block has base address `p` and size `n`, -/// then `p as usize + n <= usize::MAX` must hold. +/// then `p as usize + n <= usize::MAX` must hold. These blocks must also +/// be wholly disjoint. /// /// This ensures that pointer arithmetic within the allocation -/// (for example, `ptr.add(len)`) cannot overflow the address space. +/// (for example, `ptr.add(len)`) cannot overflow the address space, and +/// that it is possible to perform nonoverlapping copies between allocations. /// /// None of the allocating or deallocating methods may unwind. This restriction /// may be lifted in the future by ensuring unwinding out of an allocating function always /// aborts. If an implementor of `Allocator` also has drop glue or directly implements `Drop`, /// dropping the allocator must not result in an unwind. /// -/// Lastly, the methods on this trait must be *correct*; i.e. the layout requested +/// It is undefined behavior for the allocator to read, write, or deallocate any memory that +/// is currently allocated. This memory is owned by the user; the allocator must not touch it. +/// +/// Lastly, the methods on this trait must be *correct*; in particular, the layout requested /// must be respected, calls must zero out memory if the documentation so requires, -/// and returning an `AllocError` from a reallocating method must indeed ensure that +/// returning an `AllocError` from a reallocating method must indeed ensure that /// the old pointer was not invalidated, and de/reallocating calls must accept layouts /// in the ranges defined by their documentation. /// @@ -203,7 +213,7 @@ pub const unsafe trait Allocator { /// Note that the returned block of memory is considered [*currently allocated*] /// with this allocator (and equivalent allocators). /// Therefore, it is the responsibility of implementors of `Allocator` to make sure that - /// this block of memory points to valid memory until the block is [*invalidated*] + /// this block of memory remains valid until it is [*invalidated*]. /// /// [*currently allocated*]: #currently-allocated-memory /// [*invalidated*]: #invalidating-memory-blocks @@ -539,14 +549,15 @@ pub unsafe trait AllocatorClone: Allocator + Clone {} /// /// # Safety /// -/// Implementors must ensure that memory cannot be freed except via a call to -/// `Allocator::deallocate`, and that subtype coercion preserves this invariant. +/// Implementors must ensure that memory blocks are *only, ever* invalidated by a +/// call to a de/reallocating method on `Allocator`, and that this holds true for all +/// possible instances of all subtypes of the implementor as well. /// /// These requirements trivially apply to allocators that always maintain global state, such as /// `System` or `Global`. However, due to subtype coercion, it is *not* sound to implement -/// for an arbitrary `Allocator + 'static` due to [edge-case interactions][unsound] with -/// `Pin::clone`. Namely, an impl of `StaticAllocator for MyAllocator + 'long` guarantees that an -/// impl of `StaticAllocator for MyAllocator + 'short` would be sound to write. +/// for an arbitrary `Allocator + 'static` due to [edge-case interactions][unsound] with e.g. +/// `Pin::clone`. Namely, an impl of `StaticAllocator for MyAllocator + 'long` guarantees that any +/// value of `MyAllocator + 'short` also fulfills the requirements of `StaticAllocator`. /// /// The following must thus be guaranteed: /// - the `Drop` impl of the allocator does not invalidate any allocations; @@ -617,9 +628,10 @@ where } #[unstable(feature = "allocator_api", issue = "32838")] -unsafe impl Allocator for &mut A +#[rustc_const_unstable(feature = "const_heap", issue = "79597")] +const unsafe impl Allocator for &mut A where - A: Allocator + ?Sized, + A: [const] Allocator + ?Sized, { #[inline] fn allocate(&self, layout: Layout) -> Result, AllocError> { @@ -678,3 +690,6 @@ unsafe impl AllocatorClone for &A {} // its semantics, and references are equivalent to the allocator they reference. #[unstable(feature = "allocator_api", issue = "32838")] unsafe impl StaticAllocator for &A {} + +#[unstable(feature = "allocator_api", issue = "32838")] +unsafe impl StaticAllocator for &mut A {} diff --git a/tests/ui/allocator/157089-box-pin-in.stderr b/tests/ui/allocator/157089-box-pin-in.stderr index f25736d819a1f..e919eb8e3286e 100644 --- a/tests/ui/allocator/157089-box-pin-in.stderr +++ b/tests/ui/allocator/157089-box-pin-in.stderr @@ -15,6 +15,9 @@ help: the following other types implement trait `StaticAllocator` --> $SRC_DIR/core/src/alloc/mod.rs:LL:COL | = note: `&A` + ::: $SRC_DIR/core/src/alloc/mod.rs:LL:COL + | + = note: `&mut A` --> $SRC_DIR/std/src/alloc.rs:LL:COL | = note: `System` diff --git a/tests/ui/allocator/159445-unsize-pin-box.stderr b/tests/ui/allocator/159445-unsize-pin-box.stderr index 0fb3d0f176eb2..c17019be03799 100644 --- a/tests/ui/allocator/159445-unsize-pin-box.stderr +++ b/tests/ui/allocator/159445-unsize-pin-box.stderr @@ -13,6 +13,9 @@ help: the following other types implement trait `StaticAllocator` --> $SRC_DIR/core/src/alloc/mod.rs:LL:COL | = note: `&A` + ::: $SRC_DIR/core/src/alloc/mod.rs:LL:COL + | + = note: `&mut A` --> $SRC_DIR/std/src/alloc.rs:LL:COL | = note: `System` From c132f36b30a03f11adcd3f6ef61d2f6515ec14ab Mon Sep 17 00:00:00 2001 From: Nia Deckers Date: Tue, 18 Aug 2026 20:49:13 +0200 Subject: [PATCH 22/26] okay max sure --- library/core/src/alloc/mod.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/library/core/src/alloc/mod.rs b/library/core/src/alloc/mod.rs index 5fed1fae2a2d2..430da3e7142d6 100644 --- a/library/core/src/alloc/mod.rs +++ b/library/core/src/alloc/mod.rs @@ -162,8 +162,7 @@ impl fmt::Display for AllocError { /// is [*currently allocated*] by the allocator points to valid memory /// until that memory block is [*invalidated*]. The implementor must also /// not violate this invariant of `Allocator` via allocator equivalences -/// that are in the implementor's control, and generally ensure that equivalence -/// is respected. +/// that are in the implementor's control. /// /// Additionally, any memory block returned by the allocator must /// satisfy the allocation invariants described in `core::ptr`. From 2ee54ff4e93d3ff4eaed85d2386ab70fc79b3701 Mon Sep 17 00:00:00 2001 From: Nia Deckers Date: Tue, 18 Aug 2026 21:05:35 +0200 Subject: [PATCH 23/26] undo rc and arc thing --- library/alloc/src/rc.rs | 2 +- library/alloc/src/sync.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/library/alloc/src/rc.rs b/library/alloc/src/rc.rs index 689f015d586b0..12ab0b6fe5437 100644 --- a/library/alloc/src/rc.rs +++ b/library/alloc/src/rc.rs @@ -2983,7 +2983,7 @@ impl From for Rc { #[cfg(not(no_global_oom_handling))] #[stable(feature = "shared_from_slice", since = "1.21.0")] -impl From> for Rc { +impl From> for Rc { /// Move a boxed object to a new, reference counted, allocation. /// /// # Example diff --git a/library/alloc/src/sync.rs b/library/alloc/src/sync.rs index fd4a630422011..bb98788ca7b3a 100644 --- a/library/alloc/src/sync.rs +++ b/library/alloc/src/sync.rs @@ -4050,7 +4050,7 @@ impl From for Arc { #[cfg(not(no_global_oom_handling))] #[stable(feature = "shared_from_slice", since = "1.21.0")] -impl From> for Arc { +impl From> for Arc { /// Move a boxed object to a new, reference-counted allocation. /// /// # Example From 4f2bbfd897e31a139ed020862df9d721b68cf835 Mon Sep 17 00:00:00 2001 From: Nia Deckers Date: Tue, 18 Aug 2026 21:16:43 +0200 Subject: [PATCH 24/26] tighten send so bad rc can't be used --- library/alloc/src/sync.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/library/alloc/src/sync.rs b/library/alloc/src/sync.rs index bb98788ca7b3a..0ae099cccbbe7 100644 --- a/library/alloc/src/sync.rs +++ b/library/alloc/src/sync.rs @@ -281,7 +281,7 @@ pub struct Arc< } #[stable(feature = "rust1", since = "1.0.0")] -unsafe impl Send for Arc {} +unsafe impl Send for Arc {} #[stable(feature = "rust1", since = "1.0.0")] unsafe impl Sync for Arc {} @@ -364,7 +364,7 @@ pub struct Weak< } #[stable(feature = "arc_weak", since = "1.4.0")] -unsafe impl Send for Weak {} +unsafe impl Send for Weak {} #[stable(feature = "arc_weak", since = "1.4.0")] unsafe impl Sync for Weak {} @@ -4423,7 +4423,7 @@ pub struct UniqueArc< } #[unstable(feature = "unique_rc_arc", issue = "112566")] -unsafe impl Send for UniqueArc {} +unsafe impl Send for UniqueArc {} #[unstable(feature = "unique_rc_arc", issue = "112566")] unsafe impl Sync for UniqueArc {} From 31d172e735acb8d768360b481d8ea6fb1a664419 Mon Sep 17 00:00:00 2001 From: Nia Deckers Date: Tue, 18 Aug 2026 21:19:36 +0200 Subject: [PATCH 25/26] this too --- library/alloc/src/rc.rs | 7 +++++-- library/alloc/src/sync.rs | 5 ++++- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/library/alloc/src/rc.rs b/library/alloc/src/rc.rs index 12ab0b6fe5437..30e4e1aa504bf 100644 --- a/library/alloc/src/rc.rs +++ b/library/alloc/src/rc.rs @@ -342,9 +342,12 @@ impl !Send for Rc {} impl !Sync for Rc {} #[stable(feature = "catch_unwind", since = "1.9.0")] -impl UnwindSafe for Rc {} +impl UnwindSafe for Rc {} #[stable(feature = "rc_ref_unwind_safe", since = "1.58.0")] -impl RefUnwindSafe for Rc {} +impl RefUnwindSafe + for Rc +{ +} #[unstable(feature = "coerce_unsized", issue = "18598")] impl, U: ?Sized, A: Allocator> CoerceUnsized> for Rc {} diff --git a/library/alloc/src/sync.rs b/library/alloc/src/sync.rs index 0ae099cccbbe7..706eba3aab8e5 100644 --- a/library/alloc/src/sync.rs +++ b/library/alloc/src/sync.rs @@ -286,7 +286,10 @@ unsafe impl Send for Arc Sync for Arc {} #[stable(feature = "catch_unwind", since = "1.9.0")] -impl UnwindSafe for Arc {} +impl UnwindSafe + for Arc +{ +} #[unstable(feature = "coerce_unsized", issue = "18598")] impl, U: ?Sized, A: Allocator> CoerceUnsized> for Arc {} From 7d40fdb67d7aec852f7a5aa60f53eff192f9b94a Mon Sep 17 00:00:00 2001 From: Nia Deckers Date: Tue, 18 Aug 2026 21:46:37 +0200 Subject: [PATCH 26/26] there u go --- library/core/src/alloc/mod.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/library/core/src/alloc/mod.rs b/library/core/src/alloc/mod.rs index 430da3e7142d6..6069c468f96e4 100644 --- a/library/core/src/alloc/mod.rs +++ b/library/core/src/alloc/mod.rs @@ -51,8 +51,9 @@ impl fmt::Display for AllocError { /// /// `Allocator` is mostly designed to be implemented on ZSTs, references, or smart pointers, /// but can also be implemented directly on the underlying memory-owning type so long as it -/// upholds the necessary guarantees. In general, an allocator for `MyAlloc([u8; N])` cannot be -/// moved, without updating the pointers to the allocated memory. +/// upholds the necessary guarantees. In general, an allocator of the type `MyAlloc([u8; N])` +/// cannot be soundly created without being pinned or otherwise immovable in order to be +/// correct. /// /// In contrast to [`GlobalAlloc`][], `Allocator` allows zero-sized allocations. If an underlying /// allocator does not support this (like jemalloc) or responds by returning a null pointer