From 1af79e9922dac50fac7740507d6e26f3ddb77068 Mon Sep 17 00:00:00 2001 From: Folkert de Vries Date: Sun, 15 Nov 2026 23:10:57 +0100 Subject: [PATCH 1/9] test `ReturnsVisitor` with weird, nested returns --- tests/ui/error-codes/E0746.rs | 44 +++++++++- tests/ui/error-codes/E0746.stderr | 136 ++++++++++++++++++++++++++---- 2 files changed, 161 insertions(+), 19 deletions(-) diff --git a/tests/ui/error-codes/E0746.rs b/tests/ui/error-codes/E0746.rs index 86b5b7444d18e..9686870547aaf 100644 --- a/tests/ui/error-codes/E0746.rs +++ b/tests/ui/error-codes/E0746.rs @@ -1,18 +1,54 @@ #![allow(dead_code)] +fn main() {} + struct Struct; trait Trait {} impl Trait for Struct {} impl Trait for u32 {} +impl Trait for () {} -fn foo() -> dyn Trait { Struct } -//~^ ERROR E0746 +fn implicit_return() -> dyn Trait { + //~^ ERROR E0746 + Struct +} -fn bar() -> dyn Trait { //~ ERROR E0746 +fn return_in_branch() -> dyn Trait { + //~^ ERROR E0746 if true { return 0; } 42 } -fn main() {} +// The examples below are mostly here to test the diagnostic output, +// in particular whether the suggestion is valid. + +fn return_in_tail_loop(c: bool) -> dyn Trait { + //~^ ERROR E0746 + loop { + if c { + return 1u32; + } + } +} + +fn return_nested_in_leaf(c: bool) -> dyn Trait { + //~^ ERROR E0746 + let identity = |x| x; + identity(if c { return 1u32 } else { 2u32 }) +} + +fn labeled_block_break() -> dyn Trait { + //~^ ERROR E0746 + 'a: { + break 'a 1u32; //~ ERROR mismatched types + } +} + +fn loop_break_value() -> dyn Trait { + //~^ ERROR E0746 + loop { + break 1u32; //~ ERROR mismatched types + } +} diff --git a/tests/ui/error-codes/E0746.stderr b/tests/ui/error-codes/E0746.stderr index 07d6b285f764a..aaab3d105f948 100644 --- a/tests/ui/error-codes/E0746.stderr +++ b/tests/ui/error-codes/E0746.stderr @@ -1,39 +1,145 @@ error[E0746]: return type cannot be a trait object without pointer indirection - --> $DIR/E0746.rs:8:13 + --> $DIR/E0746.rs:11:25 | -LL | fn foo() -> dyn Trait { Struct } - | ^^^^^^^^^ doesn't have a size known at compile-time +LL | fn implicit_return() -> dyn Trait { + | ^^^^^^^^^ doesn't have a size known at compile-time | help: consider returning an `impl Trait` instead of a `dyn Trait` | -LL - fn foo() -> dyn Trait { Struct } -LL + fn foo() -> impl Trait { Struct } +LL - fn implicit_return() -> dyn Trait { +LL + fn implicit_return() -> impl Trait { | help: alternatively, box the return type, and wrap all of the returned values in `Box::new` | -LL | fn foo() -> Box { Box::new(Struct) } - | ++++ + +++++++++ + +LL ~ fn implicit_return() -> Box { +LL | +LL ~ Box::new(Struct) + | error[E0746]: return type cannot be a trait object without pointer indirection - --> $DIR/E0746.rs:11:13 + --> $DIR/E0746.rs:16:26 | -LL | fn bar() -> dyn Trait { - | ^^^^^^^^^ doesn't have a size known at compile-time +LL | fn return_in_branch() -> dyn Trait { + | ^^^^^^^^^ doesn't have a size known at compile-time | help: consider returning an `impl Trait` instead of a `dyn Trait` | -LL - fn bar() -> dyn Trait { -LL + fn bar() -> impl Trait { +LL - fn return_in_branch() -> dyn Trait { +LL + fn return_in_branch() -> impl Trait { | help: alternatively, box the return type, and wrap all of the returned values in `Box::new` | -LL ~ fn bar() -> Box { +LL ~ fn return_in_branch() -> Box { +LL | LL | if true { LL ~ return Box::new(0); LL | } LL ~ Box::new(42) | -error: aborting due to 2 previous errors +error[E0746]: return type cannot be a trait object without pointer indirection + --> $DIR/E0746.rs:27:36 + | +LL | fn return_in_tail_loop(c: bool) -> dyn Trait { + | ^^^^^^^^^ doesn't have a size known at compile-time + | +help: consider returning an `impl Trait` instead of a `dyn Trait` + | +LL - fn return_in_tail_loop(c: bool) -> dyn Trait { +LL + fn return_in_tail_loop(c: bool) -> impl Trait { + | +help: alternatively, box the return type, and wrap all of the returned values in `Box::new` + | +LL ~ fn return_in_tail_loop(c: bool) -> Box { +LL | +LL ~ Box::new(loop { +LL | if c { +LL | return 1u32; +LL | } +LL ~ }) + | + +error[E0746]: return type cannot be a trait object without pointer indirection + --> $DIR/E0746.rs:36:38 + | +LL | fn return_nested_in_leaf(c: bool) -> dyn Trait { + | ^^^^^^^^^ doesn't have a size known at compile-time + | +help: consider returning an `impl Trait` instead of a `dyn Trait` + | +LL - fn return_nested_in_leaf(c: bool) -> dyn Trait { +LL + fn return_nested_in_leaf(c: bool) -> impl Trait { + | +help: alternatively, box the return type, and wrap all of the returned values in `Box::new` + | +LL ~ fn return_nested_in_leaf(c: bool) -> Box { +LL | +LL | let identity = |x| x; +LL ~ Box::new(identity(if c { return 1u32 } else { 2u32 })) + | + +error[E0746]: return type cannot be a trait object without pointer indirection + --> $DIR/E0746.rs:42:29 + | +LL | fn labeled_block_break() -> dyn Trait { + | ^^^^^^^^^ doesn't have a size known at compile-time + | +help: consider returning an `impl Trait` instead of a `dyn Trait` + | +LL - fn labeled_block_break() -> dyn Trait { +LL + fn labeled_block_break() -> impl Trait { + | +help: alternatively, box the return type, and wrap all of the returned values in `Box::new` + | +LL | fn labeled_block_break() -> Box { + | ++++ + + +error[E0746]: return type cannot be a trait object without pointer indirection + --> $DIR/E0746.rs:49:26 + | +LL | fn loop_break_value() -> dyn Trait { + | ^^^^^^^^^ doesn't have a size known at compile-time + | +help: consider returning an `impl Trait` instead of a `dyn Trait` + | +LL - fn loop_break_value() -> dyn Trait { +LL + fn loop_break_value() -> impl Trait { + | +help: alternatively, box the return type, and wrap all of the returned values in `Box::new` + | +LL ~ fn loop_break_value() -> Box { +LL | +LL ~ Box::new(loop { +LL | break 1u32; +LL ~ }) + | + +error[E0308]: mismatched types + --> $DIR/E0746.rs:45:18 + | +LL | break 'a 1u32; + | ^^^^ expected `dyn Trait`, found `u32` + | + = note: expected trait object `(dyn Trait + 'static)` + found type `u32` + = help: `u32` implements `Trait` so you could box the found value and coerce it to the trait object `Box`, you will have to change the expected type as well + +error[E0308]: mismatched types + --> $DIR/E0746.rs:52:15 + | +LL | fn loop_break_value() -> dyn Trait { + | --------- expected `dyn Trait` because of this return type +LL | +LL | loop { + | ---- this loop is expected to be of type `(dyn Trait + 'static)` +LL | break 1u32; + | ^^^^ expected `dyn Trait`, found `u32` + | + = note: expected trait object `(dyn Trait + 'static)` + found type `u32` + = help: `u32` implements `Trait` so you could box the found value and coerce it to the trait object `Box`, you will have to change the expected type as well + +error: aborting due to 8 previous errors -For more information about this error, try `rustc --explain E0746`. +Some errors have detailed explanations: E0308, E0746. +For more information about an error, try `rustc --explain E0308`. From 44568ecd7bbc317e74bf071305a94140d6f64e0b Mon Sep 17 00:00:00 2001 From: Folkert de Vries Date: Sun, 15 Nov 2026 23:57:29 +0100 Subject: [PATCH 2/9] make `ReturnsVisitor` more accurate - keep doing when finding a return expression; there might be nested early returns. - keep track of blocks/loops in tail position: a break to them is effectively a return --- .../src/error_reporting/traits/suggestions.rs | 83 +++++++++++++------ tests/ui/error-codes/E0746.stderr | 20 ++--- 2 files changed, 66 insertions(+), 37 deletions(-) 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 8751d884725a9..aaae018cc37d3 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs @@ -6915,51 +6915,80 @@ impl<'v> Visitor<'v> for SelfVisitor<'v> { #[derive(Default)] pub struct ReturnsVisitor<'v> { pub returns: Vec<&'v hir::Expr<'v>>, - in_block_tail: bool, + /// The set of items in tail position that can be targeted with a break (loops and blocks). + /// A break to such an item is a return. + break_targets_in_tail_position: FxHashSet, } impl<'v> Visitor<'v> for ReturnsVisitor<'v> { fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) { - // Visit every expression to detect `return` paths, either through the function's tail - // expression or `return` statements. We walk all nodes to find `return` statements, but - // we only care about tail expressions when `in_block_tail` is `true`, which means that - // they're in the return path of the function body. match ex.kind { - hir::ExprKind::Ret(Some(ex)) => { - self.returns.push(ex); + hir::ExprKind::Ret(Some(val)) => self.returns.push(val), + hir::ExprKind::Break(dest, Some(val)) if let Ok(id) = dest.target_id => { + // If this is a break to a block/loop in tail position, this is a return. + if self.break_targets_in_tail_position.contains(&id) { + self.returns.push(val) + } + } + hir::ExprKind::Become(_) => { + // A become is like a return, but for diagnostics it is not useful to treat it as + // one. Often suggestions will break the tail call. } - hir::ExprKind::Block(block, _) if self.in_block_tail => { - self.in_block_tail = false; + _ => {} + } + + // Continue the walk, there might be further nested return expressions. + hir::intravisit::walk_expr(self, ex); + } + + fn visit_body(&mut self, body: &hir::Body<'v>) { + self.visit_tail(body.value); + } +} + +impl<'v> ReturnsVisitor<'v> { + fn visit_tail(&mut self, ex: &'v hir::Expr<'v>) { + match ex.kind { + hir::ExprKind::Block(block, _) => { + if block.targeted_by_break { + self.break_targets_in_tail_position.insert(block.hir_id); + } for stmt in block.stmts { hir::intravisit::walk_stmt(self, stmt); } - self.in_block_tail = true; - if let Some(expr) = block.expr { - self.visit_expr(expr); + if let Some(tail) = block.expr { + self.visit_tail(tail); } } - hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => { - self.visit_expr(then); - if let Some(el) = else_opt { - self.visit_expr(el); + hir::ExprKind::If(cond, then, els) => { + self.visit_expr(cond); + self.visit_tail(then); + if let Some(els) = els { + self.visit_tail(els); } } - hir::ExprKind::Match(_, arms, _) if self.in_block_tail => { + hir::ExprKind::Match(scrutinee, arms, _) => { + self.visit_expr(scrutinee); for arm in arms { - self.visit_expr(arm.body); + if let Some(guard) = arm.guard { + self.visit_expr(guard); + } + self.visit_tail(arm.body); } } - // We need to walk to find `return`s in the entire body. - _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex), - _ => self.returns.push(ex), + hir::ExprKind::Loop(block, ..) => { + self.break_targets_in_tail_position.insert(ex.hir_id); + self.visit_block(block); + } + hir::ExprKind::Ret(_) | hir::ExprKind::Become(_) | hir::ExprKind::Break(..) => { + self.visit_expr(ex); + } + _ => { + self.returns.push(ex); + self.visit_expr(ex); + } } } - - fn visit_body(&mut self, body: &hir::Body<'v>) { - assert!(!self.in_block_tail); - self.in_block_tail = true; - hir::intravisit::walk_body(self, body); - } } /// Collect all the awaited expressions within the input expression. diff --git a/tests/ui/error-codes/E0746.stderr b/tests/ui/error-codes/E0746.stderr index aaab3d105f948..e533feccc21d7 100644 --- a/tests/ui/error-codes/E0746.stderr +++ b/tests/ui/error-codes/E0746.stderr @@ -52,11 +52,9 @@ help: alternatively, box the return type, and wrap all of the returned values in | LL ~ fn return_in_tail_loop(c: bool) -> Box { LL | -LL ~ Box::new(loop { +LL | loop { LL | if c { -LL | return 1u32; -LL | } -LL ~ }) +LL ~ return Box::new(1u32); | error[E0746]: return type cannot be a trait object without pointer indirection @@ -75,7 +73,7 @@ help: alternatively, box the return type, and wrap all of the returned values in LL ~ fn return_nested_in_leaf(c: bool) -> Box { LL | LL | let identity = |x| x; -LL ~ Box::new(identity(if c { return 1u32 } else { 2u32 })) +LL ~ Box::new(identity(if c { return Box::new(1u32) } else { 2u32 })) | error[E0746]: return type cannot be a trait object without pointer indirection @@ -91,8 +89,11 @@ LL + fn labeled_block_break() -> impl Trait { | help: alternatively, box the return type, and wrap all of the returned values in `Box::new` | -LL | fn labeled_block_break() -> Box { - | ++++ + +LL ~ fn labeled_block_break() -> Box { +LL | +LL | 'a: { +LL ~ break 'a Box::new(1u32); + | error[E0746]: return type cannot be a trait object without pointer indirection --> $DIR/E0746.rs:49:26 @@ -109,9 +110,8 @@ help: alternatively, box the return type, and wrap all of the returned values in | LL ~ fn loop_break_value() -> Box { LL | -LL ~ Box::new(loop { -LL | break 1u32; -LL ~ }) +LL | loop { +LL ~ break Box::new(1u32); | error[E0308]: mismatched types From 8778c7d36a9854264ba67b460d5d2e5369849834 Mon Sep 17 00:00:00 2001 From: Yilin Chen <1479826151@qq.com> Date: Tue, 24 Nov 2026 10:17:32 +0800 Subject: [PATCH 3/9] Add safety section for intrinsic volatile operations --- library/core/src/intrinsics/mod.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/library/core/src/intrinsics/mod.rs b/library/core/src/intrinsics/mod.rs index 2f5585bfe40dc..c96548d2ee207 100644 --- a/library/core/src/intrinsics/mod.rs +++ b/library/core/src/intrinsics/mod.rs @@ -1260,12 +1260,20 @@ pub const unsafe fn volatile_set_memory(dst: *mut T, val: u8, count: usize); /// Performs a volatile load from the `src` pointer. /// /// The stabilized version of this intrinsic is [`core::ptr::read_volatile`]. +/// +/// # Safety +/// +/// See [`crate::ptr::read_volatile`] for safety conditions. #[rustc_intrinsic] #[rustc_nounwind] pub const unsafe fn volatile_load(src: *const T) -> T; /// Performs a volatile store to the `dst` pointer. /// /// The stabilized version of this intrinsic is [`core::ptr::write_volatile`]. +/// +/// # Safety +/// +/// See [`crate::ptr::write_volatile`] for safety conditions. #[rustc_intrinsic] #[rustc_nounwind] pub const unsafe fn volatile_store(dst: *mut T, val: T); @@ -1274,6 +1282,10 @@ pub const unsafe fn volatile_store(dst: *mut T, val: T); /// The pointer is not required to be aligned. /// /// This intrinsic does not have a stable counterpart. +/// +/// # Safety +/// See [`crate::ptr::read_volatile`] for safety conditions, +/// but note that `src` does not need to be aligned. #[rustc_intrinsic] #[rustc_nounwind] #[rustc_diagnostic_item = "intrinsics_unaligned_volatile_load"] @@ -1282,6 +1294,10 @@ pub unsafe fn unaligned_volatile_load(src: *const T) -> T; /// The pointer is not required to be aligned. /// /// This intrinsic does not have a stable counterpart. +/// +/// # Safety +/// See [`crate::ptr::write_volatile`] for safety conditions, +/// but note that `dst` does not need to be aligned. #[rustc_intrinsic] #[rustc_nounwind] #[rustc_diagnostic_item = "intrinsics_unaligned_volatile_store"] From 966f1814b494f4af2c041f84cf861a2ad4640ed5 Mon Sep 17 00:00:00 2001 From: Adwin White Date: Fri, 13 Nov 2026 18:19:01 +0800 Subject: [PATCH 4/9] move span out of leaf region constraint --- .../rustc_hir_analysis/src/check/wfcheck.rs | 25 ++- compiler/rustc_hir_analysis/src/collect.rs | 23 +- .../src/infer/outlives/obligations.rs | 10 +- .../eval_ctxt/solver_region_constraints.rs | 8 +- .../rustc_next_trait_solver/src/solve/mod.rs | 2 +- .../rustc_type_ir/src/region_constraint.rs | 206 +++++++----------- .../src/relate/solver_relating.rs | 2 +- 7 files changed, 116 insertions(+), 160 deletions(-) diff --git a/compiler/rustc_hir_analysis/src/check/wfcheck.rs b/compiler/rustc_hir_analysis/src/check/wfcheck.rs index ba5975e447db3..bf6fb87841e53 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -2477,12 +2477,12 @@ impl<'tcx> WfCheckingCtxt<'_, 'tcx> { let mut r = Ok(()); let mut validate_and = |and: &And, _>| { - for c in and.iter() { + for (c, span) in and.iter() { match c { - LeafRegionConstraint::Ambiguity(_) + LeafRegionConstraint::Ambiguity | LeafRegionConstraint::RegionOutlives(..) | LeafRegionConstraint::AliasTyOutlivesViaEnv(..) => (), // OK - LeafRegionConstraint::PlaceholderTyOutlives(ty, _, span) => { + LeafRegionConstraint::PlaceholderTyOutlives(ty, _) => { // we can't check this during lowering, because the ty is a ty::Bound that gets // instantiated with a placeholder when entering the containing forall. if let ty::Placeholder(_) | ty::Param(_) = ty.kind() { @@ -2606,18 +2606,19 @@ impl<'tcx> WfCheckingCtxt<'_, 'tcx> { expected: &SolverRegionConstraint<'tcx>, actual: &SolverRegionConstraint<'tcx>, ) { - let span_of_and = - |c: &And<_, _>| c.iter().map(|leaf| leaf.span()).reduce(|span: Span, acc| acc.to(span)); + let span_of_and = |c: &And<_, _>| { + c.iter().map(|(_, span)| *span).reduce(|span: Span, acc: Span| acc.to(span)) + }; let span_of_or = |c: &Or<_, _>| { - c.iter().flat_map(|and| span_of_and(and)).reduce(|span, acc| acc.to(span)) + c.iter().flat_map(|and| span_of_and(and)).reduce(|span, acc: Span| acc.to(span)) }; let check_leaf_constraint = - |expected: &LeafRegionConstraint<_, _>, actual: &LeafRegionConstraint<_, _>| { - if let LeafRegionConstraint::AliasTyOutlivesViaEnv(expected, expected_span) = - expected - && let LeafRegionConstraint::AliasTyOutlivesViaEnv(actual, actual_span) = actual + |(expected, expected_span): &(LeafRegionConstraint<_>, Span), + (actual, actual_span): &(LeafRegionConstraint<_>, Span)| { + if let LeafRegionConstraint::AliasTyOutlivesViaEnv(expected) = expected + && let LeafRegionConstraint::AliasTyOutlivesViaEnv(actual) = actual { let expected_anon = self.tcx().anonymize_bound_vars(expected.clone()); let actual_anon = self.tcx().anonymize_bound_vars(actual.clone()); @@ -2627,10 +2628,10 @@ impl<'tcx> WfCheckingCtxt<'_, 'tcx> { Err((Some(*expected_span), Some(*actual_span))) } } else { - if expected.clone().without_span() == actual.clone().without_span() { + if expected == actual { Ok(()) } else { - Err((Some(expected.span()), Some(actual.span()))) + Err((Some(*expected_span), Some(*actual_span))) } } }; diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index 62b0e4d23dc43..39ef49dae5654 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -469,9 +469,10 @@ impl<'tcx> ItemCtxt<'tcx> { let span = lhs.ident.span.to(rhs.ident.span); let lhs = self.lowerer().lower_lifetime(lhs, RegionInferReason::RegionPredicate); let rhs = self.lowerer().lower_lifetime(rhs, RegionInferReason::RegionPredicate); - SolverRegionConstraint::new_leaf(LeafRegionConstraint::RegionOutlives( - lhs, rhs, span, - )) + SolverRegionConstraint::new_leaf( + LeafRegionConstraint::RegionOutlives(lhs, rhs), + span, + ) } hir::TestBinderConstraint::PlaceholderOutlives { lhs, rhs } => { let span = lhs.span.to(rhs.ident.span); @@ -480,9 +481,10 @@ impl<'tcx> ItemCtxt<'tcx> { // note that we cannot check that lhs is a placeholder at this moment, as at this // point it is a bound variable that is not yet instantiated with a placeholder. // instead, we check it when we emit the region constraint. - SolverRegionConstraint::new_leaf(LeafRegionConstraint::PlaceholderTyOutlives( - lhs, rhs, span, - )) + SolverRegionConstraint::new_leaf( + LeafRegionConstraint::PlaceholderTyOutlives(lhs, rhs), + span, + ) } hir::TestBinderConstraint::AliasOutlives { bound_type_constraint: @@ -494,10 +496,13 @@ impl<'tcx> ItemCtxt<'tcx> { return SolverRegionConstraint::new_true(); }; let rhs = self.lowerer().lower_lifetime(rhs, RegionInferReason::RegionPredicate); - SolverRegionConstraint::new_leaf(LeafRegionConstraint::AliasTyOutlivesViaEnv( - ty::Binder::bind_with_vars((lhs, rhs), bound_vars), + SolverRegionConstraint::new_leaf( + LeafRegionConstraint::AliasTyOutlivesViaEnv(ty::Binder::bind_with_vars( + (lhs, rhs), + bound_vars, + )), *span, - )) + ) } } } diff --git a/compiler/rustc_infer/src/infer/outlives/obligations.rs b/compiler/rustc_infer/src/infer/outlives/obligations.rs index 784f9042ff528..6068fe98981d6 100644 --- a/compiler/rustc_infer/src/infer/outlives/obligations.rs +++ b/compiler/rustc_infer/src/infer/outlives/obligations.rs @@ -280,7 +280,7 @@ impl<'tcx> InferCtxt<'tcx> { if constraint.is_false() { match failing_leafs.first() { - Some(PlaceholderTyOutlives(_a, _b, span)) => { + Some((PlaceholderTyOutlives(_a, _b), span)) => { self.dcx() .struct_span_err( *span, @@ -288,7 +288,7 @@ impl<'tcx> InferCtxt<'tcx> { ) .emit(); } - Some(AliasTyOutlivesViaEnv(_, span)) => { + Some((AliasTyOutlivesViaEnv(_), span)) => { self.dcx() .struct_span_err( *span, @@ -303,14 +303,14 @@ impl<'tcx> InferCtxt<'tcx> { } // FIXME(-Zassumptions-on-binders): actually implement OR as an OR - for c in constraint.and_constraint.into_iter().chain( + for (c, span) in constraint.and_constraint.into_iter().chain( constraint .or_constraint .into_iter() .flat_map(|and_constraint| and_constraint.into_iter()), ) { match c { - Ambiguity(span) => { + Ambiguity => { self.dcx() .struct_span_err( span, @@ -318,7 +318,7 @@ impl<'tcx> InferCtxt<'tcx> { ) .emit(); } - RegionOutlives(a, b, span) => { + RegionOutlives(a, b) => { let origin = SubregionOrigin::SolverRegionConstraint(span); let category = origin.to_constraint_category(); conversion.push_sub_region_constraint( diff --git a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/solver_region_constraints.rs b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/solver_region_constraints.rs index 84fb63d6311ac..fc94eeff9510e 100644 --- a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/solver_region_constraints.rs +++ b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/solver_region_constraints.rs @@ -168,9 +168,9 @@ where use Component::*; use LeafRegionConstraint::*; match c { - Region(c_r) => Or::new_leaf(RegionOutlives(*c_r, r, NoSpan)), + Region(c_r) => Or::new_leaf(RegionOutlives(*c_r, r), NoSpan), Placeholder(p) => { - Or::new_leaf(PlaceholderTyOutlives(Ty::new_placeholder(self.cx(), *p), r, NoSpan)) + Or::new_leaf(PlaceholderTyOutlives(Ty::new_placeholder(self.cx(), *p), r), NoSpan) } Alias(_, alias) => self.destructure_alias_outlives(*alias, r), UnresolvedInferenceVariable(_) => { @@ -194,11 +194,11 @@ where let item_bounds = rustc_type_ir::outlives::declared_bounds_from_definition(self.cx(), alias) - .map(|bound| And::new([RegionOutlives(bound, r, NoSpan)])); + .map(|bound| And::new([(RegionOutlives(bound, r), NoSpan)])); let item_bound_outlives = Or::new(item_bounds); let where_clause_outlives = - Or::new_leaf(AliasTyOutlivesViaEnv(Binder::dummy((alias, r)), NoSpan)); + Or::new_leaf(AliasTyOutlivesViaEnv(Binder::dummy((alias, r))), NoSpan); let mut components = Default::default(); rustc_type_ir::outlives::compute_alias_components_recursive( diff --git a/compiler/rustc_next_trait_solver/src/solve/mod.rs b/compiler/rustc_next_trait_solver/src/solve/mod.rs index 5e449db8d8a94..8b19a6a7d7a2a 100644 --- a/compiler/rustc_next_trait_solver/src/solve/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/mod.rs @@ -131,7 +131,7 @@ where }; let constraint = - RegionConstraint::new_leaf(LeafRegionConstraint::RegionOutlives(a, b, NoSpan)); + RegionConstraint::new_leaf(LeafRegionConstraint::RegionOutlives(a, b), NoSpan); self.register_solver_region_constraint(constraint); } else { self.register_region_outlives(a, b, VisibleForLeakCheck::Yes); diff --git a/compiler/rustc_type_ir/src/region_constraint.rs b/compiler/rustc_type_ir/src/region_constraint.rs index ea3eeb31b73a4..7ae8bf23c1d11 100644 --- a/compiler/rustc_type_ir/src/region_constraint.rs +++ b/compiler/rustc_type_ir/src/region_constraint.rs @@ -187,12 +187,12 @@ impl ConstraintSpan for NoSpan {} #[cfg(feature = "nightly")] impl ConstraintSpan for rustc_span::Span {} -#[derive_where(Clone, Hash, PartialEq, Eq; I: Interner, S)] +#[derive_where(Clone, Hash, PartialEq, Eq; I: Interner)] #[derive(TypeVisitable_Generic, GenericTypeVisitable, TypeFoldable_Generic)] #[cfg_attr(feature = "nightly", derive(StableHash_NoContext))] -pub enum LeafRegionConstraint { - Ambiguity(S), - RegionOutlives(Region, Region, S), +pub enum LeafRegionConstraint { + Ambiguity, + RegionOutlives(Region, Region), /// Requirement that a (potentially higher ranked) alias outlives some (potentially higher ranked) /// region due to an assumption in the environment. This cannot be satisfied via component outlives /// or item bounds. @@ -202,7 +202,7 @@ pub enum LeafRegionConstraint { /// /// We eagerly destructure alias outlives requirements into region outlives requirements corresponding to /// component outlives & item bound outlives rules, leaving only param env candidates. - AliasTyOutlivesViaEnv(Binder, Region)>, S), + AliasTyOutlivesViaEnv(Binder, Region)>), /// This is an `I::Ty` for two reasons: /// 1. We need the type visitable impl to be able to `visit_ty` on this so canonicalization /// knows about the placeholder @@ -212,19 +212,19 @@ pub enum LeafRegionConstraint { /// /// We cannot eagerly look at assumptions as we are usually working with an incomplete set of assumptions /// and there may wind up being assumptions we can use to prove this when we're in a smaller universe. - PlaceholderTyOutlives(I::Ty, Region, S), + PlaceholderTyOutlives(I::Ty, Region), } -impl std::fmt::Debug for LeafRegionConstraint { +impl std::fmt::Debug for LeafRegionConstraint { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { match self { - Self::Ambiguity(_span) => f.write_str("ambiguity"), - Self::RegionOutlives(r1, r2, _span) => { + Self::Ambiguity => f.write_str("ambiguity"), + Self::RegionOutlives(r1, r2) => { r1.fmt(f)?; f.write_str(": ")?; r2.fmt(f) } - Self::AliasTyOutlivesViaEnv(bound_outlives, _span) => { + Self::AliasTyOutlivesViaEnv(bound_outlives) => { f.write_str("for<")?; bound_outlives.bound_vars().fmt(f)?; f.write_str(">")?; @@ -233,7 +233,7 @@ impl std::fmt::Debug for LeafRegionConstraint { f.write_str(": ")?; r.fmt(f) } - Self::PlaceholderTyOutlives(ty, r, _span) => { + Self::PlaceholderTyOutlives(ty, r) => { ty.fmt(f)?; f.write_str(": ")?; r.fmt(f) @@ -242,46 +242,6 @@ impl std::fmt::Debug for LeafRegionConstraint { } } -impl LeafRegionConstraint { - pub fn with_span(self, span: S) -> LeafRegionConstraint { - use LeafRegionConstraint::*; - - match self { - Ambiguity(NoSpan) => Ambiguity(span), - RegionOutlives(r1, r2, NoSpan) => RegionOutlives(r1, r2, span), - AliasTyOutlivesViaEnv(bound_outlives, NoSpan) => { - AliasTyOutlivesViaEnv(bound_outlives, span) - } - PlaceholderTyOutlives(ty, r, NoSpan) => PlaceholderTyOutlives(ty, r, span), - } - } -} - -impl LeafRegionConstraint { - pub fn without_span(self) -> LeafRegionConstraint { - use LeafRegionConstraint::*; - - match self { - Ambiguity(_) => Ambiguity(NoSpan), - RegionOutlives(r1, r2, _) => RegionOutlives(r1, r2, NoSpan), - AliasTyOutlivesViaEnv(bound_outlives, _) => { - AliasTyOutlivesViaEnv(bound_outlives, NoSpan) - } - PlaceholderTyOutlives(ty, r, _) => PlaceholderTyOutlives(ty, r, NoSpan), - } - } - - pub fn span(&self) -> S { - use LeafRegionConstraint::*; - - let (Ambiguity(s) - | RegionOutlives(_, _, s) - | AliasTyOutlivesViaEnv(_, s) - | PlaceholderTyOutlives(_, _, s)) = self; - s.clone() - } -} - #[derive_where(Clone, Hash, PartialEq, Eq; I: Interner, S)] #[derive(TypeVisitable_Generic, GenericTypeVisitable, TypeFoldable_Generic)] #[cfg_attr(feature = "nightly", derive(StableHash_NoContext))] @@ -376,11 +336,11 @@ impl Or { } pub fn new_ambig(s: S) -> Self { - Or::new_leaf(LeafRegionConstraint::Ambiguity(s)) + Or::new_leaf(LeafRegionConstraint::Ambiguity, s) } - pub fn new_leaf(l: LeafRegionConstraint) -> Self { - Or::new([And::new([l])]) + pub fn new_leaf(l: LeafRegionConstraint, s: S) -> Self { + Or::new([And::new([(l, s)])]) } pub fn build_and(a: Or, b: Or) -> Self { @@ -455,11 +415,11 @@ impl Deref for Or { // FIXME(-Zassumptions-on-binders): move to a separate module to avoid accidental // mutation in this module? pub struct And( - SmallVec<[LeafRegionConstraint; 1]>, + SmallVec<[(LeafRegionConstraint, S); 1]>, ); impl And { pub fn with_spans(self, span: S) -> And { - And(self.0.into_iter().map(|leaf| leaf.with_span(span.clone())).collect()) + And(self.0.into_iter().map(|(leaf, _)| (leaf, span.clone())).collect()) } } impl And { @@ -467,24 +427,24 @@ impl And { Self(SmallVec::new()) } - pub fn new(i: impl IntoIterator>) -> Self { + pub fn new(i: impl IntoIterator, S)>) -> Self { let mut seen = IndexSet::new(); And(i .into_iter() - .filter(|leaf| { + .filter(|(leaf, _)| { // Outlives is reflexive so a `'a: 'a` leaf is always true and carries no // information. Dropping it here keeps the rest of the code from having to special // case it, and is what lets an OR with a reflexive candidate be recognized as true. - if let LeafRegionConstraint::RegionOutlives(r1, r2, _) = leaf + if let LeafRegionConstraint::RegionOutlives(r1, r2) = leaf && r1 == r2 { return false; } - if seen.contains(&leaf.clone().without_span()) { + if seen.contains(leaf) { false } else { - seen.insert(leaf.clone().without_span()); + seen.insert(leaf.clone()); true } }) @@ -497,25 +457,19 @@ impl And { // if newcome is superset // In particular, the equivalent case is also classified under the subset branch - if this - .iter() - .all(|c1| other.iter().any(|c2| c1.clone().without_span() == c2.clone().without_span())) - { + if this.iter().all(|(c1, _)| other.iter().any(|(c2, _)| c1 == c2)) { return AndRelation::Subset; } // if newcome is subset - if other - .iter() - .all(|c2| this.iter().any(|c1| c1.clone().without_span() == c2.clone().without_span())) - { + if other.iter().all(|(c2, _)| this.iter().any(|(c1, _)| c1 == c2)) { return AndRelation::Superset; } return AndRelation::Incomparable; } pub fn without_spans(self) -> And { - And(self.0.into_iter().map(|leaf| leaf.without_span()).collect()) + And(self.0.into_iter().map(|(leaf, _)| (leaf, NoSpan)).collect()) } } @@ -523,18 +477,18 @@ impl std::fmt::Debug for And { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { if self.0.is_empty() { f.write_str("true") - } else if let [single] = &*self.0 { + } else if let [(single, _span)] = &*self.0 { single.fmt(f) } else { f.write_str("and ")?; - f.debug_set().entries(&self.0).finish() + f.debug_set().entries(self.iter().map(|(l, _)| l)).finish() } } } impl IntoIterator for And { - type Item = LeafRegionConstraint; - type IntoIter = ; 1]> as IntoIterator>::IntoIter; + type Item = (LeafRegionConstraint, S); + type IntoIter = , S); 1]> as IntoIterator>::IntoIter; fn into_iter(self) -> Self::IntoIter { self.0.into_iter() @@ -542,8 +496,8 @@ impl IntoIterator for And { } impl<'a, I: Interner, S: Clone + std::fmt::Debug> IntoIterator for &'a And { - type Item = &'a LeafRegionConstraint; - type IntoIter = <&'a SmallVec<[LeafRegionConstraint; 1]> as IntoIterator>::IntoIter; + type Item = &'a (LeafRegionConstraint, S); + type IntoIter = <&'a SmallVec<[(LeafRegionConstraint, S); 1]> as IntoIterator>::IntoIter; fn into_iter(self) -> Self::IntoIter { (&self.0).into_iter() @@ -551,7 +505,7 @@ impl<'a, I: Interner, S: Clone + std::fmt::Debug> IntoIterator for &'a And } impl Deref for And { - type Target = SmallVec<[LeafRegionConstraint; 1]>; + type Target = SmallVec<[(LeafRegionConstraint, S); 1]>; fn deref(&self) -> &Self::Target { &self.0 @@ -591,19 +545,14 @@ impl RegionConstraint { let mut and_constraint = fst.0.to_vec(); for and in or.0.split_first().unwrap().1 { - and_constraint.retain(|c| { - and.0.iter().any(|c2| c.clone().without_span() == c2.clone().without_span()) - }); + and_constraint.retain(|(c, _)| and.0.iter().any(|(c2, _)| c == c2)); } let and_constraint = And::new(and_constraint); let or_constraint = Or::new(or.0.into_iter().map(|and| { - And::new(and.0.into_iter().filter(|c| { - and_constraint - .0 - .iter() - .all(|s_c| c.clone().without_span() != s_c.clone().without_span()) - })) + And::new( + and.0.into_iter().filter(|(c, _)| and_constraint.0.iter().all(|(s_c, _)| c != s_c)), + ) })); Self { @@ -650,13 +599,13 @@ impl RegionConstraint { pub fn new_ambig(span: S) -> Self { Self { - and_constraint: And::new([LeafRegionConstraint::Ambiguity(span)]), + and_constraint: And::new([(LeafRegionConstraint::Ambiguity, span)]), or_constraint: Or::new_true(), } } pub fn is_ambig(&self) -> bool { - if let [c] = &*self.and_constraint.0 + if let [(c, _)] = &*self.and_constraint.0 && c.is_ambig() && self.or_constraint.is_true() { @@ -673,8 +622,8 @@ impl RegionConstraint { } } - pub fn new_leaf(l: LeafRegionConstraint) -> Self { - RegionConstraint { and_constraint: And::new([l]), or_constraint: Or::new_true() } + pub fn new_leaf(l: LeafRegionConstraint, s: S) -> Self { + RegionConstraint { and_constraint: And::new([(l, s)]), or_constraint: Or::new_true() } } } @@ -693,9 +642,9 @@ impl std::fmt::Debug for RegionConstrai } } -impl LeafRegionConstraint { +impl LeafRegionConstraint { pub fn is_ambig(&self) -> bool { - matches!(self, Self::Ambiguity(_)) + matches!(self, Self::Ambiguity) } } @@ -766,12 +715,12 @@ fn compute_new_region_constraints, I: Interne regions: &mut IndexSet<_>, constraints: &mut Vec<_>, and: &And| { - for c in &and.0 { + for (c, NoSpan) in &and.0 { match c { - Ambiguity(NoSpan) | PlaceholderTyOutlives(..) | AliasTyOutlivesViaEnv(..) => { - constraints.push(c.clone()) + Ambiguity | PlaceholderTyOutlives(..) | AliasTyOutlivesViaEnv(..) => { + constraints.push((c.clone(), NoSpan)) } - RegionOutlives(r1, r2, NoSpan) => { + RegionOutlives(r1, r2) => { regions.insert(*r1); regions.insert(*r2); builder.add(*r2, *r1); @@ -813,7 +762,7 @@ fn compute_new_region_constraints, I: Interne }; if is_placeholder_like(r) && is_placeholder_like(ub) { - constraints.push(RegionOutlives(ub, r, NoSpan)); + constraints.push((RegionOutlives(ub, r), NoSpan)); } } } @@ -870,18 +819,18 @@ fn pull_region_outlives_constraints_out_of_universe< let pull_and = |and: And| { let mut pulled_constraints = Vec::new(); - for c in and.0 { + for (c, span) in and.0 { match c { - Ambiguity(NoSpan) | PlaceholderTyOutlives(..) | AliasTyOutlivesViaEnv(..) => { + Ambiguity | PlaceholderTyOutlives(..) | AliasTyOutlivesViaEnv(..) => { assert!(max_universe(infcx, c.clone()) < u); - pulled_constraints.push(Or::new_leaf(c.clone())); + pulled_constraints.push(Or::new_leaf(c, span)); } - RegionOutlives(region_1, region_2, NoSpan) => { + RegionOutlives(region_1, region_2) => { let region_1_u = max_universe(infcx, region_1); let region_2_u = max_universe(infcx, region_2); if region_1_u != u && region_2_u != u { - pulled_constraints.push(Or::new_leaf(c)); + pulled_constraints.push(Or::new_leaf(c, span)); continue; } @@ -907,7 +856,7 @@ fn pull_region_outlives_constraints_out_of_universe< // As long as any region outlived by `region_1` outlives any region region which // `region_2` outlives, we know that `region_1: region_2` holds. In other words, // there exists some set of 4 regions for which `'r1: 'i1` `'i1: 'i2` `'i2: 'r2` - candidates.push(RegionOutlives(ub, lb, NoSpan)); + candidates.push((RegionOutlives(ub, lb), NoSpan)); } } @@ -931,7 +880,7 @@ fn pull_region_outlives_constraints_out_of_universe< #[derive_where(Debug; I: Interner, S)] pub struct RootDestructuredConstraints { pub constraint: RegionConstraint, - pub failing_leafs: Vec>, + pub failing_leafs: Vec<(LeafRegionConstraint, S)>, } /// Converts type outlives constraints into region outlives constraints. This assumes the *complete* set of @@ -950,28 +899,28 @@ pub fn destructure_type_outlives_constraints_in_root< ) -> RootDestructuredConstraints { use LeafRegionConstraint::*; - let mut failing_leafs: Vec> = vec![]; + let mut failing_leafs: Vec<(LeafRegionConstraint, S)> = vec![]; let mut destructure_and = |and: &And| { debug!("rewriting and: {:?}", and); let mut destructured_constraints = Vec::new(); - for c in &and.0 { + for (c, span) in &and.0 { match c { - Ambiguity(_) | RegionOutlives(..) => { - destructured_constraints.push(Or::new_leaf(c.clone())) + Ambiguity | RegionOutlives(..) => { + destructured_constraints.push(Or::new_leaf(c.clone(), span.clone())) } - PlaceholderTyOutlives(ty, r, span) => { + PlaceholderTyOutlives(ty, r) => { let contents = Or::new(regions_outlived_by_placeholder(*ty, assumptions, infcx.cx()).map( move |assumption_r| { - And::new([RegionOutlives(assumption_r, *r, span.clone())]) + And::new([(RegionOutlives(assumption_r, *r), span.clone())]) }, )); if contents.is_false() { - failing_leafs.push(c.clone()); + failing_leafs.push((c.clone(), span.clone())); } destructured_constraints.push(contents) } - AliasTyOutlivesViaEnv(bound_outlives, span) => { + AliasTyOutlivesViaEnv(bound_outlives) => { let content = alias_outlives_candidates_from_assumptions( infcx, *bound_outlives, @@ -979,7 +928,7 @@ pub fn destructure_type_outlives_constraints_in_root< ) .with_spans(span.clone()); if content.is_false() { - failing_leafs.push(c.clone()); + failing_leafs.push((c.clone(), span.clone())); } destructured_constraints.push(content); } @@ -1037,15 +986,15 @@ fn rewrite_type_outlives_constraints_in_universe_for_eager_placeholder_handling< let rewrite_and = |and: And| { let mut rewritten_constraints = Vec::new(); - for c in and.0 { + for (c, NoSpan) in and.0 { match c { - Ambiguity(NoSpan) | RegionOutlives(..) => { - rewritten_constraints.push(Or::new_leaf(c)) + Ambiguity | RegionOutlives(..) => { + rewritten_constraints.push(Or::new_leaf(c, NoSpan)) } - PlaceholderTyOutlives(ty, region, NoSpan) => { + PlaceholderTyOutlives(ty, region) => { rewritten_constraints.push(rewrite_placeholder_ty_outlives_constraints_in_universe_for_eager_placeholder_handling(infcx, ty, region, u, assumptions)); } - AliasTyOutlivesViaEnv(bound_outlives, NoSpan) => { + AliasTyOutlivesViaEnv(bound_outlives) => { rewritten_constraints.push(rewrite_alias_ty_outlives_constraints_in_universe_for_eager_placeholder_handling(infcx, bound_outlives, u, assumptions)); } } @@ -1080,7 +1029,7 @@ fn rewrite_placeholder_ty_outlives_constraints_in_universe_for_eager_placeholder let region_u = max_universe(infcx, region); if region_u != u && ty_u != u { - return Or::new_leaf(PlaceholderTyOutlives(ty, region, NoSpan)); + return Or::new_leaf(PlaceholderTyOutlives(ty, region), NoSpan); } let mut candidates = vec![]; @@ -1089,7 +1038,7 @@ fn rewrite_placeholder_ty_outlives_constraints_in_universe_for_eager_placeholder // smaller universe candidates.extend( regions_outlived_by_placeholder(ty, assumptions, infcx.cx()) - .map(move |assumption_r| RegionOutlives(assumption_r, region, NoSpan)), + .map(move |assumption_r| RegionOutlives(assumption_r, region)), ); // We can express `!T: 'region` as `!T: 'r` where `'r: 'region`. This is only necessary @@ -1099,11 +1048,11 @@ fn rewrite_placeholder_ty_outlives_constraints_in_universe_for_eager_placeholder candidates.extend( regions_outliving::(region, assumptions, infcx.cx()) .filter(|r| max_universe(infcx, *r) < u) - .map(|r| PlaceholderTyOutlives(ty, r, NoSpan)), + .map(|r| PlaceholderTyOutlives(ty, r)), ); } - Or::new(candidates.into_iter().map(|c| And::new([c]))) + Or::new(candidates.into_iter().map(|c| And::new([(c, NoSpan)]))) } #[instrument(level = "debug", skip(infcx), ret)] @@ -1119,7 +1068,7 @@ fn rewrite_alias_ty_outlives_constraints_in_universe_for_eager_placeholder_handl use LeafRegionConstraint::*; if max_universe(infcx, bound_outlives) != u { - return Or::new_leaf(AliasTyOutlivesViaEnv(bound_outlives, NoSpan)); + return Or::new_leaf(AliasTyOutlivesViaEnv(bound_outlives), NoSpan); } let mut candidates = Vec::new(); @@ -1166,7 +1115,7 @@ fn rewrite_alias_ty_outlives_constraints_in_universe_for_eager_placeholder_handl } debug!("higher ranked candidate: {bound_outlives:?}"); - Or::new_leaf(AliasTyOutlivesViaEnv(bound_outlives, NoSpan)) + Or::new_leaf(AliasTyOutlivesViaEnv(bound_outlives), NoSpan) }; // We elaborate something like `Alias<'a_u2>: 'b_u2` into alias outlives involving each @@ -1333,7 +1282,7 @@ fn alias_outlives_candidates_from_assumptions let mut relation = HigherRankedAliasMatcher { infcx, - region_constraints: vec![LeafRegionConstraint::RegionOutlives(r2, r, NoSpan)], + region_constraints: vec![LeafRegionConstraint::RegionOutlives(r2, r)], }; // FIXME(#155345): Both sides should be rigid in the future. @@ -1343,7 +1292,8 @@ fn alias_outlives_candidates_from_assumptions .skip_norm_wip(), set_aliases_to_non_rigid(infcx.cx(), alias2).skip_norm_wip(), ) { - candidates.push(And::new(relation.region_constraints)); + candidates + .push(And::new(relation.region_constraints.into_iter().map(|c| (c, NoSpan)))); } } }); @@ -1406,8 +1356,8 @@ impl<'a, Infcx: InferCtxtLike, I: Interner> TypeRelation fn regions(&mut self, a: Region, b: Region) -> RelateResult> { if a != b { - self.region_constraints.push(LeafRegionConstraint::RegionOutlives(a, b, NoSpan)); - self.region_constraints.push(LeafRegionConstraint::RegionOutlives(b, a, NoSpan)); + self.region_constraints.push(LeafRegionConstraint::RegionOutlives(a, b)); + self.region_constraints.push(LeafRegionConstraint::RegionOutlives(b, a)); } Ok(a) } diff --git a/compiler/rustc_type_ir/src/relate/solver_relating.rs b/compiler/rustc_type_ir/src/relate/solver_relating.rs index e411d79e44dd4..71ddd75e927b7 100644 --- a/compiler/rustc_type_ir/src/relate/solver_relating.rs +++ b/compiler/rustc_type_ir/src/relate/solver_relating.rs @@ -242,7 +242,7 @@ where fn regions(&mut self, a: Region, b: Region) -> RelateResult> { if self.cx().assumptions_on_binders() { let region_outlives = |a, b| { - RegionConstraint::new_leaf(LeafRegionConstraint::RegionOutlives(a, b, NoSpan)) + RegionConstraint::new_leaf(LeafRegionConstraint::RegionOutlives(a, b), NoSpan) }; match self.ambient_variance { From 7cd93b0a75ce45b15940499551dc6f5d96c7e8bd Mon Sep 17 00:00:00 2001 From: Mark Rousskov Date: Sun, 22 Nov 2026 14:10:35 -0500 Subject: [PATCH 5/9] Drop references to codebuild We no longer use AWS CodeBuild for our jobs, so delete or rephrase code that referred to it. --- .github/workflows/ci.yml | 11 ---- .github/workflows/ghcr.yml | 2 +- src/ci/citool/src/jobs.rs | 11 +--- src/ci/citool/src/jobs/tests.rs | 67 ------------------------- src/ci/scripts/free-disk-space-linux.sh | 2 +- 5 files changed, 4 insertions(+), 89 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2ad4bba147184..cb8d5974af09f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -103,17 +103,6 @@ jobs: # Check the `calculate_matrix` job to see how is the matrix defined. include: ${{ fromJSON(needs.calculate_matrix.outputs.jobs) }} steps: - - name: Install cargo in AWS CodeBuild - if: matrix.codebuild - run: | - # Check if cargo is installed - if ! command -v cargo &> /dev/null; then - echo "Cargo not found, installing Rust..." - curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile=minimal - # Make cargo available in PATH - echo "$HOME/.cargo/bin" >> $GITHUB_PATH - fi - - name: disable git crlf conversion run: git config --global core.autocrlf false diff --git a/.github/workflows/ghcr.yml b/.github/workflows/ghcr.yml index f0f0ece750b9f..a1ac3306f3aaf 100644 --- a/.github/workflows/ghcr.yml +++ b/.github/workflows/ghcr.yml @@ -6,7 +6,7 @@ # Those images are pushed to ghcr.io by this job. # # While Docker Hub rate limit *shouldn't* be an issue on GitHub Actions, -# it certainly is for AWS codebuild. +# it may be for external self-hosted runners (e.g., EC2 runners). # # Note that authenticating to DockerHub or other registries isn't possible # for PR jobs, because forks can't access secrets. diff --git a/src/ci/citool/src/jobs.rs b/src/ci/citool/src/jobs.rs index b94f12a37cc77..6ca6cd10815ba 100644 --- a/src/ci/citool/src/jobs.rs +++ b/src/ci/citool/src/jobs.rs @@ -29,8 +29,6 @@ pub struct Job { pub free_disk: Option, /// Documentation link to a resource that could help people debug this CI job. pub doc_url: Option, - /// Whether the job is executed on AWS CodeBuild. - pub codebuild: Option, /// Which Python version (if any) is required. On Windows, this is typically required to run /// LLDB. #[serde(default)] @@ -170,7 +168,6 @@ fn validate_job_database(db: &JobDatabase) -> anyhow::Result<()> { only_on_channel, free_disk, doc_url, - codebuild, required_python_version, // Carve-out configs allowed to be different. @@ -183,7 +180,6 @@ fn validate_job_database(db: &JobDatabase) -> anyhow::Result<()> { && *only_on_channel == auto_job.only_on_channel && *free_disk == auto_job.free_disk && *doc_url == auto_job.doc_url - && *codebuild == auto_job.codebuild && *required_python_version == auto_job.required_python_version { Ok(()) @@ -249,14 +245,12 @@ struct GithubActionsJob { #[serde(skip_serializing_if = "Option::is_none")] doc_url: Option, #[serde(skip_serializing_if = "Option::is_none")] - codebuild: Option, - #[serde(skip_serializing_if = "Option::is_none")] required_python_version: Option, } /// Replace GitHub context variables with environment variables in job configs. -/// Used for codebuild jobs like -/// `codebuild-ubuntu-22-8c-$github.run_id-$github.run_attempt` +/// +/// This is used for self-hosted runner jobs to loosely tie an instance to a particular GHA job. fn substitute_github_vars(jobs: Vec) -> anyhow::Result> { let run_id = load_env_var("GITHUB_RUN_ID")?; let run_attempt = load_env_var("GITHUB_RUN_ATTEMPT")?; @@ -382,7 +376,6 @@ fn calculate_jobs( continue_on_error: job.continue_on_error, free_disk: job.free_disk, doc_url: job.doc_url, - codebuild: job.codebuild, required_python_version: job.required_python_version, } }) diff --git a/src/ci/citool/src/jobs/tests.rs b/src/ci/citool/src/jobs/tests.rs index 65990d35d61b1..0179157d85c58 100644 --- a/src/ci/citool/src/jobs/tests.rs +++ b/src/ci/citool/src/jobs/tests.rs @@ -81,73 +81,6 @@ fn check_pattern(db: &JobDatabase, pattern: &str, expected: &[&str]) { assert_eq!(jobs, expected); } -/// Validate that CodeBuild jobs use Docker images from ghcr.io registry. -/// This is needed because otherwise from CodeBuild we get rate limited by Docker Hub. -fn validate_codebuild_image(job: &Job) -> anyhow::Result<()> { - let is_job_on_codebuild = job.codebuild.unwrap_or(false); - if !is_job_on_codebuild { - // Jobs in GitHub Actions don't get rate limited by Docker Hub. - return Ok(()); - } - - let image_name = job.image(); - // we hardcode host-x86_64 here, because in codebuild we only run jobs for this architecture. - let dockerfile_path = - Path::new(DOCKER_DIRECTORY).join("host-x86_64").join(&image_name).join("Dockerfile"); - - if !dockerfile_path.exists() { - return Err(anyhow::anyhow!( - "Dockerfile not found for CodeBuild job '{}' at path: {}", - job.name, - dockerfile_path.display() - )); - } - - let dockerfile_content = utils::read_to_string(&dockerfile_path)?; - - // Check if all FROM statement uses ghcr.io registry - let has_ghcr_from = dockerfile_content - .lines() - .filter(|line| line.trim_start().to_lowercase().starts_with("from ")) - .all(|line| line.contains("ghcr.io")); - - if !has_ghcr_from { - return Err(anyhow::anyhow!( - "CodeBuild job '{}' must use ghcr.io registry in its Dockerfile FROM statement. \ - Dockerfile path: {dockerfile_path:?}", - job.name, - )); - } - - Ok(()) -} - -#[test] -fn validate_jobs() { - let db = { - let default_jobs_file = Path::new(JOBS_YML_PATH); - let db_str = utils::read_to_string(default_jobs_file).unwrap(); - load_job_db(&db_str).expect("Failed to load job database") - }; - - let all_jobs = db - .pr_jobs - .iter() - .chain(db.try_jobs.iter()) - .chain(db.auto_jobs.iter()) - .chain(db.optional_jobs.iter()) - .collect::>(); - - let errors: Vec = - all_jobs.into_iter().filter_map(|job| validate_codebuild_image(job).err()).collect(); - - if !errors.is_empty() { - let error_messages = - errors.into_iter().map(|e| format!("- {e}")).collect::>().join("\n"); - panic!("Job validation failed:\n{error_messages}"); - } -} - #[test] fn pr_job_implies_auto_job() { let db = load_job_db( diff --git a/src/ci/scripts/free-disk-space-linux.sh b/src/ci/scripts/free-disk-space-linux.sh index 1498bc0a24f2c..36c9505327157 100755 --- a/src/ci/scripts/free-disk-space-linux.sh +++ b/src/ci/scripts/free-disk-space-linux.sh @@ -21,7 +21,7 @@ isX86() { } # Check if we're on a GitHub hosted runner. -# In aws codebuild, the variable RUNNER_ENVIRONMENT is "self-hosted". +# In self hosted runners, the variable RUNNER_ENVIRONMENT is "self-hosted". isGitHubRunner() { # `:-` means "use the value of RUNNER_ENVIRONMENT if it exists, otherwise use an empty string". if [[ "${RUNNER_ENVIRONMENT:-}" == "github-hosted" ]]; then From 3fcb5e1d5c210d7080e6d32a111d49629744d1dc Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Tue, 24 Nov 2026 08:37:51 +0100 Subject: [PATCH 6/9] remove some incorrect docs from volatile intrinsics --- library/core/src/intrinsics/mod.rs | 19 +++---------------- 1 file changed, 3 insertions(+), 16 deletions(-) diff --git a/library/core/src/intrinsics/mod.rs b/library/core/src/intrinsics/mod.rs index 2f5585bfe40dc..9df7338788255 100644 --- a/library/core/src/intrinsics/mod.rs +++ b/library/core/src/intrinsics/mod.rs @@ -1222,14 +1222,7 @@ pub fn ptr_mask(ptr: *const T, mask: usize) -> *const T; /// Equivalent to the appropriate `llvm.memcpy.p0i8.0i8.*` intrinsic, with /// a size of `count` * `size_of::()` and an alignment of `align_of::()`. /// -/// This intrinsic does not have a stable counterpart. -/// # Safety -/// -/// The safety requirements are consistent with [`copy_nonoverlapping`] -/// while the read and write behaviors are volatile, -/// which means it will not be optimized out unless `_count` or `size_of::()` is equal to zero. -/// -/// [`copy_nonoverlapping`]: ptr::copy_nonoverlapping +/// This intrinsic does not have a public counterpart. #[rustc_intrinsic] #[rustc_nounwind] pub unsafe fn volatile_copy_nonoverlapping_memory(dst: *mut T, src: *const T, count: usize); @@ -1239,20 +1232,14 @@ pub unsafe fn volatile_copy_nonoverlapping_memory(dst: *mut T, src: *const T, /// The volatile parameter is set to `true`, so it will not be optimized out /// unless size is equal to zero. /// -/// This intrinsic does not have a stable counterpart. +/// This intrinsic does not have a public counterpart. #[rustc_intrinsic] #[rustc_nounwind] pub unsafe fn volatile_copy_memory(dst: *mut T, src: *const T, count: usize); /// Equivalent to the appropriate `llvm.memset.p0i8.*` intrinsic, with a /// size of `count * size_of::()` and an alignment of `align_of::()`. /// -/// This intrinsic does not have a stable counterpart. -/// # Safety -/// -/// The safety requirements are consistent with [`write_bytes`] while the write behavior is volatile, -/// which means it will not be optimized out unless `_count` or `size_of::()` is equal to zero. -/// -/// [`write_bytes`]: ptr::write_bytes +/// This intrinsic does not have a public counterpart. #[rustc_intrinsic] #[rustc_nounwind] pub const unsafe fn volatile_set_memory(dst: *mut T, val: u8, count: usize); From 5a701ad02db26fae189a18171ecba3a5f79b868a Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Tue, 24 Nov 2026 08:00:39 +0000 Subject: [PATCH 7/9] Make rigid alias invalidation explicit when transitioning to PostAnalysis * Add post-analysis `TypingEnv` constructors explicit about rigid aliases * Use `post_analysis_no_rigid_aliases` at the existing `post_analysis` call sites * Rename interner `TypingEnv::post_analysis` to `post_analysis_no_rigid_aliases` * Use `post_analysis_invalidating_rigid_aliases` for drop shims * Remove `TypingEnv::post_analysis` --- .../rustc_middle/src/mir/interpret/queries.rs | 4 +-- compiler/rustc_middle/src/mir/mod.rs | 4 +-- compiler/rustc_middle/src/ty/adt.rs | 2 +- compiler/rustc_middle/src/ty/mod.rs | 25 ++++++++++++++++--- .../rustc_mir_transform/src/inline/cycle.rs | 2 +- compiler/rustc_mir_transform/src/liveness.rs | 4 ++- compiler/rustc_mir_transform/src/shim.rs | 9 +++++-- .../src/solve/eval_ctxt/mod.rs | 2 +- compiler/rustc_passes/src/abi_test.rs | 4 +-- .../cfi/typeid/itanium_cxx_abi/transform.rs | 3 ++- compiler/rustc_symbol_mangling/src/legacy.rs | 2 +- compiler/rustc_symbol_mangling/src/v0.rs | 2 +- .../rustc_trait_selection/src/traits/mod.rs | 5 ++-- compiler/rustc_type_ir/src/inherent.rs | 2 +- src/librustdoc/clean/mod.rs | 2 +- src/librustdoc/html/render/mod.rs | 2 +- src/librustdoc/html/render/type_layout.rs | 2 +- .../clippy_utils/src/qualify_min_const_fn.rs | 2 +- tests/ui-fulldeps/polymorphic-drop-glue.rs | 2 +- 19 files changed, 54 insertions(+), 26 deletions(-) diff --git a/compiler/rustc_middle/src/mir/interpret/queries.rs b/compiler/rustc_middle/src/mir/interpret/queries.rs index 264c826109af9..1c722a3b7d23c 100644 --- a/compiler/rustc_middle/src/mir/interpret/queries.rs +++ b/compiler/rustc_middle/src/mir/interpret/queries.rs @@ -24,7 +24,7 @@ impl<'tcx> TyCtxt<'tcx> { let args = GenericArgs::identity_for_item(self, def_id); let instance = ty::Instance::new_raw(def_id, args); let cid = GlobalId { instance, promoted: None }; - let typing_env = ty::TypingEnv::post_analysis(self, def_id); + let typing_env = ty::TypingEnv::post_analysis_no_rigid_aliases(self, def_id); self.const_eval_global_id(typing_env, cid, DUMMY_SP) } @@ -40,7 +40,7 @@ impl<'tcx> TyCtxt<'tcx> { let args = GenericArgs::identity_for_item(self, def_id); let instance = ty::Instance::new_raw(def_id, args); let cid = GlobalId { instance, promoted: None }; - let typing_env = ty::TypingEnv::post_analysis(self, def_id); + let typing_env = ty::TypingEnv::post_analysis_no_rigid_aliases(self, def_id); let inputs = self.erase_and_anonymize_regions(typing_env.as_query_input(cid)); self.eval_to_allocation_raw(inputs) } diff --git a/compiler/rustc_middle/src/mir/mod.rs b/compiler/rustc_middle/src/mir/mod.rs index 786563805832f..acf12f1f5b503 100644 --- a/compiler/rustc_middle/src/mir/mod.rs +++ b/compiler/rustc_middle/src/mir/mod.rs @@ -428,7 +428,7 @@ impl<'tcx> Body<'tcx> { ) } MirPhase::Analysis(AnalysisPhase::PostCleanup) | MirPhase::Runtime(_) => { - TypingEnv::post_analysis(tcx, self.source.def_id()) + TypingEnv::post_analysis_no_rigid_aliases(tcx, self.source.def_id()) } } } else { @@ -438,7 +438,7 @@ impl<'tcx> Body<'tcx> { ty::TypingMode::non_body_analysis(), ), MirPhase::Analysis(AnalysisPhase::PostCleanup) | MirPhase::Runtime(_) => { - TypingEnv::post_analysis(tcx, self.source.def_id()) + TypingEnv::post_analysis_no_rigid_aliases(tcx, self.source.def_id()) } } } diff --git a/compiler/rustc_middle/src/ty/adt.rs b/compiler/rustc_middle/src/ty/adt.rs index e93059f5216c2..c252e2aaa043e 100644 --- a/compiler/rustc_middle/src/ty/adt.rs +++ b/compiler/rustc_middle/src/ty/adt.rs @@ -649,7 +649,7 @@ impl<'tcx> AdtDef<'tcx> { let repr_type = self.repr().discr_type(); match tcx.const_eval_poly(expr_did) { Ok(val) => { - let typing_env = ty::TypingEnv::post_analysis(tcx, expr_did); + let typing_env = ty::TypingEnv::post_analysis_no_rigid_aliases(tcx, expr_did); let ty = repr_type.to_ty(tcx); if let Some(b) = val.try_to_bits_for_ty(tcx, typing_env, ty) { trace!("discriminants: {} ({:?})", b, repr_type); diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 8de81ccd1e2fb..9392b2acdf9e2 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -1130,8 +1130,8 @@ impl<'tcx> rustc_type_ir::inherent::TypingEnv> for TypingEnv<'tcx> .size } - fn post_analysis(tcx: TyCtxt<'tcx>, def_id: DefId) -> TypingEnv<'tcx> { - Self::post_analysis(tcx, def_id) + fn post_analysis_no_rigid_aliases(tcx: TyCtxt<'tcx>, def_id: DefId) -> TypingEnv<'tcx> { + Self::post_analysis_no_rigid_aliases(tcx, def_id) } } @@ -1192,10 +1192,29 @@ impl<'tcx> TypingEnv<'tcx> { } } - pub fn post_analysis(tcx: TyCtxt<'tcx>, def_id: impl IntoQueryKey) -> TypingEnv<'tcx> { + /// Use this when you don't have types/consts from an earlier typing env. + /// See [`Self::with_post_analysis_normalized_invalidating_rigid_aliases`]. + pub fn post_analysis_no_rigid_aliases( + tcx: TyCtxt<'tcx>, + def_id: impl IntoQueryKey, + ) -> TypingEnv<'tcx> { TypingEnv::new(tcx.param_env_normalized_for_post_analysis(def_id), TypingMode::PostAnalysis) } + /// Use this when you have types/consts from an earlier typing env. + /// See [`Self::with_post_analysis_normalized_invalidating_rigid_aliases`]. + pub fn post_analysis_invalidating_rigid_aliases( + tcx: TyCtxt<'tcx>, + def_id: impl IntoQueryKey, + value: T, + ) -> PseudoCanonicalInput<'tcx, Unnormalized<'tcx, T>> + where + T: TypeFoldable>, + { + let typing_env = TypingEnv::post_analysis_no_rigid_aliases(tcx, def_id); + typing_env.as_query_input(ty::set_aliases_to_non_rigid(tcx, value)) + } + pub fn codegen(tcx: TyCtxt<'tcx>, def_id: impl IntoQueryKey) -> TypingEnv<'tcx> { TypingEnv::new(tcx.param_env_normalized_for_post_analysis(def_id), TypingMode::Codegen) } diff --git a/compiler/rustc_mir_transform/src/inline/cycle.rs b/compiler/rustc_mir_transform/src/inline/cycle.rs index 77ddecabc291f..d04d44464945e 100644 --- a/compiler/rustc_mir_transform/src/inline/cycle.rs +++ b/compiler/rustc_mir_transform/src/inline/cycle.rs @@ -167,7 +167,7 @@ pub(crate) fn mir_callgraph_cyclic<'tcx>( // into the call graph, we're probably not going to find any useful MIR inlining. let recursion_limit = tcx.recursion_limit() / 8; let mut involved = FxHashSet::default(); - let typing_env = ty::TypingEnv::post_analysis(tcx, root); + let typing_env = ty::TypingEnv::post_analysis_no_rigid_aliases(tcx, root); let root_instance = ty::Instance::new_raw(root.to_def_id(), ty::GenericArgs::identity_for_item(tcx, root)); if !should_recurse(tcx, root_instance) { diff --git a/compiler/rustc_mir_transform/src/liveness.rs b/compiler/rustc_mir_transform/src/liveness.rs index 887e5179f5c4b..e107a80fc25f5 100644 --- a/compiler/rustc_mir_transform/src/liveness.rs +++ b/compiler/rustc_mir_transform/src/liveness.rs @@ -141,7 +141,9 @@ pub(crate) fn check_liveness<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Den .iterate_to_fixpoint(tcx, body, None) .into_results_cursor(body); - let typing_env = ty::TypingEnv::post_analysis(tcx, body.source.def_id()); + // FIXME: We could use the rigid alias invalidating variant here, since + // we reset rigidness later, but doing so caused a perf regression. + let typing_env = ty::TypingEnv::post_analysis_no_rigid_aliases(tcx, body.source.def_id()); let mut assignments = AssignmentResult::find_dead_assignments(tcx, typing_env, &checked_places, &mut live, body); diff --git a/compiler/rustc_mir_transform/src/shim.rs b/compiler/rustc_mir_transform/src/shim.rs index 3296d1ca87f33..767587d18cf7b 100644 --- a/compiler/rustc_mir_transform/src/shim.rs +++ b/compiler/rustc_mir_transform/src/shim.rs @@ -122,7 +122,12 @@ fn make_shim<'tcx>(tcx: TyCtxt<'tcx>, shim: ty::ShimKind<'tcx>) -> Body<'tcx> { return body; } - build_drop_shim(tcx, def_id, ty, ty::TypingEnv::post_analysis(tcx, def_id)) + let ty::PseudoCanonicalInput { typing_env, value: ty } = + ty::TypingEnv::post_analysis_invalidating_rigid_aliases(tcx, def_id, ty); + // We intentionally don't normalize ty here. Any generic parameters it mentions + // belong to the caller, not to drop_glue, so typing_env cannot normalize its + // aliases. The caller normalizes the shim body in its own env instead. + build_drop_shim(tcx, def_id, ty.skip_normalization(), typing_env) } ty::ShimKind::ThreadLocal(..) => build_thread_local_shim(tcx, shim), ty::ShimKind::Clone(def_id, ty) => build_clone_shim(tcx, def_id, ty), @@ -1011,7 +1016,7 @@ fn build_call_shim<'tcx>( pub(super) fn build_adt_ctor(tcx: TyCtxt<'_>, ctor_id: DefId) -> Body<'_> { debug_assert!(tcx.is_constructor(ctor_id)); - let typing_env = ty::TypingEnv::post_analysis(tcx, ctor_id); + let typing_env = ty::TypingEnv::post_analysis_no_rigid_aliases(tcx, ctor_id); // Normalize the sig. let sig = tcx 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 71c4ae1f57e3a..fbe33846dc389 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 @@ -1607,7 +1607,7 @@ where // To prevent this we discard all the generic arguments and evalaute with identity args // and in its own environment instead of the current environment we are normalizing in. let args = GenericArgs::identity_for_item(cx, def_id.into()); - let typing_env = TypingEnv::post_analysis(cx, def_id.into()); + let typing_env = TypingEnv::post_analysis_no_rigid_aliases(cx, def_id.into()); Ok((typing_env, args)) } diff --git a/compiler/rustc_passes/src/abi_test.rs b/compiler/rustc_passes/src/abi_test.rs index 1a2ccc75d0bcf..7bed36a365666 100644 --- a/compiler/rustc_passes/src/abi_test.rs +++ b/compiler/rustc_passes/src/abi_test.rs @@ -53,7 +53,7 @@ fn dump_abi_of_fn_item( attr_span: Span, attr_kind: RustcAbiAttrKind, ) { - let typing_env = ty::TypingEnv::post_analysis(tcx, item_def_id); + let typing_env = ty::TypingEnv::post_analysis_no_rigid_aliases(tcx, item_def_id); let args = GenericArgs::identity_for_item(tcx, item_def_id); let instance = match Instance::try_resolve(tcx, typing_env, item_def_id.into(), args) { Ok(Some(instance)) => instance, @@ -110,7 +110,7 @@ fn dump_abi_of_fn_type( attr_span: Span, attr_kind: RustcAbiAttrKind, ) { - let typing_env = ty::TypingEnv::post_analysis(tcx, item_def_id); + let typing_env = ty::TypingEnv::post_analysis_no_rigid_aliases(tcx, item_def_id); let ty = tcx.type_of(item_def_id).instantiate_identity().skip_norm_wip(); let span = tcx.def_span(item_def_id); if !ensure_wf(tcx, typing_env, ty, item_def_id, span) { 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 69258a21cff03..9ad5a0026ff69 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 @@ -145,7 +145,8 @@ impl<'tcx> TypeFolder> for TransformTy<'tcx> { return t; } let variant = adt_def.non_enum_variant(); - let typing_env = ty::TypingEnv::post_analysis(self.tcx, variant.def_id); + let typing_env = + ty::TypingEnv::post_analysis_no_rigid_aliases(self.tcx, variant.def_id); let field = variant.fields.iter().find(|field| { let ty = self.tcx.type_of(field.did).instantiate_identity().skip_norm_wip(); let is_zst = self diff --git a/compiler/rustc_symbol_mangling/src/legacy.rs b/compiler/rustc_symbol_mangling/src/legacy.rs index 6d9c44dcd05cc..a3ce11937a223 100644 --- a/compiler/rustc_symbol_mangling/src/legacy.rs +++ b/compiler/rustc_symbol_mangling/src/legacy.rs @@ -460,7 +460,7 @@ impl<'tcx> Printer<'tcx> for LegacySymbolMangler<'tcx> { .as_slice() { ( - ty::TypingEnv::post_analysis(self.tcx, impl_def_id), + ty::TypingEnv::post_analysis_no_rigid_aliases(self.tcx, impl_def_id), self_ty.instantiate_identity().skip_norm_wip(), impl_trait_ref .map(|impl_trait_ref| impl_trait_ref.instantiate_identity().skip_norm_wip()), diff --git a/compiler/rustc_symbol_mangling/src/v0.rs b/compiler/rustc_symbol_mangling/src/v0.rs index e53c598952df9..d14308bb6545b 100644 --- a/compiler/rustc_symbol_mangling/src/v0.rs +++ b/compiler/rustc_symbol_mangling/src/v0.rs @@ -419,7 +419,7 @@ impl<'tcx> Printer<'tcx> for V0SymbolMangler<'tcx> { .as_slice() { ( - ty::TypingEnv::post_analysis(self.tcx, impl_def_id), + ty::TypingEnv::post_analysis_no_rigid_aliases(self.tcx, impl_def_id), self_ty.instantiate_identity().skip_norm_wip(), impl_trait_ref .map(|impl_trait_ref| impl_trait_ref.instantiate_identity().skip_norm_wip()), diff --git a/compiler/rustc_trait_selection/src/traits/mod.rs b/compiler/rustc_trait_selection/src/traits/mod.rs index 613a685aeb846..e5afaed106c80 100644 --- a/compiler/rustc_trait_selection/src/traits/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/mod.rs @@ -705,7 +705,8 @@ pub fn try_evaluate_const<'tcx, E: Debug>( } Err(_) | Ok(None) => { let args = GenericArgs::identity_for_item(tcx, def_id); - let typing_env = ty::TypingEnv::post_analysis(tcx, def_id); + let typing_env = + ty::TypingEnv::post_analysis_no_rigid_aliases(tcx, def_id); (args, typing_env) } } @@ -737,7 +738,7 @@ pub fn try_evaluate_const<'tcx, E: Debug>( // To prevent this we discard all the generic arguments and evalaute with identity args // and in its own environment instead of the current environment we are normalizing in. let args = GenericArgs::identity_for_item(tcx, def_id); - let typing_env = ty::TypingEnv::post_analysis(tcx, def_id); + let typing_env = ty::TypingEnv::post_analysis_no_rigid_aliases(tcx, def_id); (args, typing_env) } diff --git a/compiler/rustc_type_ir/src/inherent.rs b/compiler/rustc_type_ir/src/inherent.rs index fb57a57883030..ee22b9884b434 100644 --- a/compiler/rustc_type_ir/src/inherent.rs +++ b/compiler/rustc_type_ir/src/inherent.rs @@ -764,5 +764,5 @@ pub trait ScalarInt: Copy + Debug + Hash + Eq { pub trait TypingEnv: Copy + Clone + Debug + PartialEq + Eq + Hash { fn fully_monomorphized() -> Self; fn layout_size(self, interner: I, ty: I::Ty) -> Size; - fn post_analysis(interner: I, def_id: I::DefId) -> Self; + fn post_analysis_no_rigid_aliases(interner: I, def_id: I::DefId) -> Self; } diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index ff5aeb1097799..8d5616c8929ee 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1915,7 +1915,7 @@ pub(crate) fn clean_ty<'tcx>(ty: &hir::Ty<'_>, cx: &mut DocContext<'tcx>) -> Typ hir::ConstArgKind::Anon(hir::AnonConst { def_id, .. }) => { // FIXME: Avoid re-HIR-ty-lowering. let ct = lower_const_arg_for_rustdoc(cx.tcx, const_arg, cx.tcx.types.usize); - let typing_env = ty::TypingEnv::post_analysis(cx.tcx, *def_id); + let typing_env = ty::TypingEnv::post_analysis_no_rigid_aliases(cx.tcx, *def_id); let ct = cx.tcx.normalize_erasing_regions(typing_env, Unnormalized::new_wip(ct)); print_const(cx.tcx, ct) diff --git a/src/librustdoc/html/render/mod.rs b/src/librustdoc/html/render/mod.rs index 71ec9d11bd174..a090be3b20376 100644 --- a/src/librustdoc/html/render/mod.rs +++ b/src/librustdoc/html/render/mod.rs @@ -3083,7 +3083,7 @@ fn repr_attribute<'tcx>( // Side note: There can only ever be one or zero non-1-ZST fields. let non_1zst_field = var.fields.iter().find(|field| { - let ty = ty::TypingEnv::post_analysis(tcx, field.did) + let ty = ty::TypingEnv::post_analysis_no_rigid_aliases(tcx, field.did) .as_query_input(tcx.type_of(field.did).instantiate_identity().skip_norm_wip()); tcx.layout_of(ty).is_ok_and(|layout| !layout.is_1zst()) }); diff --git a/src/librustdoc/html/render/type_layout.rs b/src/librustdoc/html/render/type_layout.rs index 346de6c0cfb1c..71270a9f1a64c 100644 --- a/src/librustdoc/html/render/type_layout.rs +++ b/src/librustdoc/html/render/type_layout.rs @@ -32,7 +32,7 @@ pub(crate) fn document_type_layout(cx: &Context<'_>, ty_def_id: DefId) -> impl f } let tcx = cx.tcx(); - let typing_env = ty::TypingEnv::post_analysis(tcx, ty_def_id); + let typing_env = ty::TypingEnv::post_analysis_no_rigid_aliases(tcx, ty_def_id); let ty = tcx.type_of(ty_def_id).instantiate_identity().skip_norm_wip(); let type_layout = tcx.layout_of(typing_env.as_query_input(ty)); diff --git a/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs b/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs index 50b7cd9bb5c8c..f699dc6a25d79 100644 --- a/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs +++ b/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs @@ -182,7 +182,7 @@ fn check_rvalue<'tcx>( }; let unsized_ty = cx .tcx - .struct_tail_for_codegen(pointee_ty, ty::TypingEnv::post_analysis(cx.tcx, def_id)); + .struct_tail_for_codegen(pointee_ty, ty::TypingEnv::post_analysis_no_rigid_aliases(cx.tcx, def_id)); if let ty::Slice(_) | ty::Str = unsized_ty.kind() { check_operand(cx, op, span, body, msrv)?; // Casting/coercing things to slices is fine. diff --git a/tests/ui-fulldeps/polymorphic-drop-glue.rs b/tests/ui-fulldeps/polymorphic-drop-glue.rs index a3ad05ef228e3..f44fe04d04c8a 100644 --- a/tests/ui-fulldeps/polymorphic-drop-glue.rs +++ b/tests/ui-fulldeps/polymorphic-drop-glue.rs @@ -68,7 +68,7 @@ impl rustc_driver::Callbacks for CompilerCalls { // Regression test for ICE due to the drop glue code not correctly handling generic // contexts. let ty = tcx.type_of(contains_array).instantiate_identity().skip_norm_wip(); - let typing_env = ty::TypingEnv::post_analysis(tcx, contains_array); + let typing_env = ty::TypingEnv::post_analysis_no_rigid_aliases(tcx, contains_array); rustc_mir_transform::build_drop_shim(tcx, drop_glue, Some(ty), typing_env); Compilation::Stop From f9b362bda480b5b1dcd912f578c717b4fb0e7be9 Mon Sep 17 00:00:00 2001 From: "Eddy (Eduard) Stefes" Date: Tue, 24 Nov 2026 09:10:28 +0100 Subject: [PATCH 8/9] fix test enum-repr-abi some architectures abi require 32 bit types to be extended to 64 bit. --- tests/codegen-llvm/enum/enum-repr-abi.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/codegen-llvm/enum/enum-repr-abi.rs b/tests/codegen-llvm/enum/enum-repr-abi.rs index 0add3533593ed..1b210e41b6cec 100644 --- a/tests/codegen-llvm/enum/enum-repr-abi.rs +++ b/tests/codegen-llvm/enum/enum-repr-abi.rs @@ -74,7 +74,7 @@ pub extern "C" fn enum_u16(value: ReprU16) -> ReprU16 { value } -// CHECK: {{(noundef)?}}{{( range\(i32 0, 2\))?}} i32 @enum_i32(i32{{( noundef)?}}{{( range\(i32 0, 2\))?}} %value) +// CHECK: {{(noundef)?}}{{( signext)?}}{{( range\(i32 0, 2\))?}} i32 @enum_i32(i32{{( noundef)?}}{{( signext)?}}{{( range\(i32 0, 2\))?}} %value) #[unsafe(no_mangle)] pub extern "C" fn enum_i32(value: ReprI32) -> ReprI32 { // CHECK: start: From f099c5f4cd45eedc61d8fead3306c7562dc82c45 Mon Sep 17 00:00:00 2001 From: Jonathan Brouwer Date: Mon, 23 Nov 2026 12:15:08 +0100 Subject: [PATCH 9/9] Inline some attribute parsing code --- compiler/rustc_attr_parsing/src/interface.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/compiler/rustc_attr_parsing/src/interface.rs b/compiler/rustc_attr_parsing/src/interface.rs index c4193f5db6100..1aa54ab42c668 100644 --- a/compiler/rustc_attr_parsing/src/interface.rs +++ b/compiler/rustc_attr_parsing/src/interface.rs @@ -69,6 +69,7 @@ impl<'sess> AttributeParser<'sess> { /// with `parse_limited` to be reparsed later during ast lowering where we *do* emit the errors /// /// Due to this function not taking in `RegisteredTools`, *do not* use this for parsing any lint attributes + #[inline] pub fn parse_limited( sess: &'sess Session, attrs: &[ast::Attribute], @@ -87,6 +88,7 @@ impl<'sess> AttributeParser<'sess> { /// This does the same as `parse_limited`, except that it takes a fixed symbol instead of a /// filter. + #[inline] pub fn parse_limited_sym( sess: &'sess Session, attrs: &[ast::Attribute], @@ -99,6 +101,7 @@ impl<'sess> AttributeParser<'sess> { /// Usually you want `parse_limited`, which emits no errors. /// /// Due to this function not taking in `RegisteredTools`, *do not* use this for parsing any lint attributes + #[inline] pub fn parse_limited_should_emit( sess: &'sess Session, attrs: &[ast::Attribute], @@ -125,6 +128,7 @@ impl<'sess> AttributeParser<'sess> { /// This does the same as `parse_limited_should_emit`, except that it takes a fixed symbol /// instead of a filter. + #[inline] pub fn parse_limited_sym_should_emit( sess: &'sess Session, attrs: &[ast::Attribute], @@ -148,6 +152,7 @@ impl<'sess> AttributeParser<'sess> { /// /// Try to use this as little as possible. Attributes *should* be lowered during /// `rustc_ast_lowering`. + #[inline] pub fn parse_limited_all( sess: &'sess Session, attrs: &[ast::Attribute], @@ -160,6 +165,10 @@ impl<'sess> AttributeParser<'sess> { attr_tools: Option<&'sess RegisteredTools>, lint_tools: Option<&'sess RegisteredTools>, ) -> Vec { + if attrs.len() == 0 { + return vec![]; + } + // Some attributes require access to features to parse. // Therefore, if `parse_filter` is None, then features *must* be provided. assert!(parse_filter.is_some() || features.is_some()); @@ -179,6 +188,7 @@ impl<'sess> AttributeParser<'sess> { /// This method parses a single attribute, using `parse_fn`. /// This is useful if you already know what exact attribute this is, and want to parse it. + #[inline] pub fn parse_single( sess: &'sess Session, attr: &ast::Attribute, @@ -225,6 +235,7 @@ impl<'sess> AttributeParser<'sess> { /// This method is equivalent to `parse_single`, but parses arguments using `parse_fn` using manually created `args`. /// This is useful when you want to parse other things than attributes using attribute parsers. + #[inline] pub fn parse_single_args( sess: &'sess Session, attr_span: Span,