From b2f8b406335310f885a0d2d21ff8472b6a5f9ce5 Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Mon, 21 Jul 2025 13:16:10 +0000 Subject: Don't ICE on non-TypeId metadata within TypeId --- compiler/rustc_const_eval/src/interpret/memory.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'compiler/rustc_const_eval/src') diff --git a/compiler/rustc_const_eval/src/interpret/memory.rs b/compiler/rustc_const_eval/src/interpret/memory.rs index 20c8e983cea..20825d2ad9b 100644 --- a/compiler/rustc_const_eval/src/interpret/memory.rs +++ b/compiler/rustc_const_eval/src/interpret/memory.rs @@ -997,7 +997,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { ptr: Pointer>, ) -> InterpResult<'tcx, (Ty<'tcx>, u64)> { let (alloc_id, offset, _meta) = self.ptr_get_alloc_id(ptr, 0)?; - let GlobalAlloc::TypeId { ty } = self.tcx.global_alloc(alloc_id) else { + let Some(GlobalAlloc::TypeId { ty }) = self.tcx.try_get_global_alloc(alloc_id) else { throw_ub_format!("invalid `TypeId` value: not all bytes carry type id metadata") }; interp_ok((ty, offset.bytes())) -- cgit 1.4.1-3-g733a5 From 9ff071219bca913e45235568defadd5ab840c50a Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Fri, 13 Oct 2023 20:20:57 +0000 Subject: Give an AllocId to ConstValue::Slice. --- compiler/rustc_codegen_cranelift/src/constant.rs | 3 +- compiler/rustc_codegen_ssa/src/mir/operand.rs | 7 +-- .../src/const_eval/eval_queries.rs | 3 +- .../rustc_const_eval/src/interpret/intrinsics.rs | 20 ++++---- compiler/rustc_const_eval/src/interpret/operand.rs | 3 +- compiler/rustc_middle/src/mir/consts.rs | 54 ++++++++++++---------- compiler/rustc_middle/src/mir/pretty.rs | 6 +-- compiler/rustc_middle/src/ty/context.rs | 8 +++- compiler/rustc_middle/src/ty/structural_impls.rs | 8 ++++ .../src/builder/expr/as_constant.rs | 41 ++++++++++------ compiler/rustc_monomorphize/src/collector.rs | 6 +-- compiler/rustc_public/src/alloc.rs | 4 +- compiler/rustc_public_bridge/src/alloc.rs | 3 +- .../building/issue_101867.main.built.after.mir | 4 ++ ...torage_live_dead_in_statics.XXX.built.after.mir | 4 ++ .../user_type_annotations.let_else.built.after.mir | 6 +++ ...e_annotations.let_else_bindless.built.after.mir | 6 +++ .../const_debuginfo.main.SingleUseConsts.diff | 2 + ..._flow_simplification.hello.GVN.panic-abort.diff | 4 ++ ...flow_simplification.hello.GVN.panic-unwind.diff | 4 ++ ..._mention.main.DeadStoreElimination-initial.diff | 8 ++++ .../gvn.duplicate_slice.GVN.panic-abort.diff | 20 +++++--- .../gvn.duplicate_slice.GVN.panic-unwind.diff | 20 +++++--- tests/mir-opt/gvn.fn_pointers.GVN.panic-abort.diff | 18 ++++---- .../mir-opt/gvn.fn_pointers.GVN.panic-unwind.diff | 18 ++++---- tests/mir-opt/gvn.rs | 19 ++++---- tests/mir-opt/gvn.slices.GVN.panic-abort.diff | 14 ++++-- tests/mir-opt/gvn.slices.GVN.panic-unwind.diff | 14 ++++-- tests/mir-opt/gvn.wrap_unwrap.GVN.panic-abort.diff | 2 + .../mir-opt/gvn.wrap_unwrap.GVN.panic-unwind.diff | 2 + .../inline_diverging.g.Inline.panic-abort.diff | 4 ++ .../inline_diverging.g.Inline.panic-unwind.diff | 4 ++ ...e_body.run2-{closure#0}.Inline.panic-abort.diff | 9 +++- ..._body.run2-{closure#0}.Inline.panic-unwind.diff | 9 +++- ..._array.strs.InstSimplify-after-simplifycfg.diff | 4 ++ ...est.SimplifyComparisonIntegral.panic-abort.diff | 6 +++ ...st.SimplifyComparisonIntegral.panic-unwind.diff | 6 +++ ...lifyCfg-pre-optimizations.after.panic-abort.mir | 4 ++ ...ifyCfg-pre-optimizations.after.panic-unwind.mir | 4 ++ ...call.main.ElaborateDrops.before.panic-abort.mir | 2 + ...all.main.ElaborateDrops.before.panic-unwind.mir | 2 + ...nvalid_constant.main.GVN.32bit.panic-abort.diff | 11 ++++- ...nvalid_constant.main.GVN.64bit.panic-abort.diff | 11 ++++- ...ts.match_const.SingleUseConsts.panic-abort.diff | 12 +++++ ...s.match_const.SingleUseConsts.panic-unwind.diff | 12 +++++ ...ch_const_debug.SingleUseConsts.panic-abort.diff | 12 +++++ ...h_const_debug.SingleUseConsts.panic-unwind.diff | 12 +++++ ...structs.flat.ScalarReplacementOfAggregates.diff | 4 ++ ...byref.UnreachableEnumBranching.panic-abort.diff | 16 +++++++ ...yref.UnreachableEnumBranching.panic-unwind.diff | 16 +++++++ ...inant.UnreachableEnumBranching.panic-abort.diff | 8 ++++ ...nant.UnreachableEnumBranching.panic-unwind.diff | 8 ++++ ...se_t1.UnreachableEnumBranching.panic-abort.diff | 12 +++++ ...e_t1.UnreachableEnumBranching.panic-unwind.diff | 12 +++++ ...se_t2.UnreachableEnumBranching.panic-abort.diff | 8 ++++ ...e_t2.UnreachableEnumBranching.panic-unwind.diff | 8 ++++ ...se_t3.UnreachableEnumBranching.panic-abort.diff | 12 +++++ ...e_t3.UnreachableEnumBranching.panic-unwind.diff | 12 +++++ ...se_t4.UnreachableEnumBranching.panic-abort.diff | 12 +++++ ...e_t4.UnreachableEnumBranching.panic-unwind.diff | 12 +++++ ...fault.UnreachableEnumBranching.panic-abort.diff | 16 +++++++ ...ault.UnreachableEnumBranching.panic-unwind.diff | 16 +++++++ ...ult_2.UnreachableEnumBranching.panic-abort.diff | 20 ++++++++ ...lt_2.UnreachableEnumBranching.panic-unwind.diff | 20 ++++++++ ...fault.UnreachableEnumBranching.panic-abort.diff | 16 +++++++ ...ault.UnreachableEnumBranching.panic-unwind.diff | 16 +++++++ ...imple.UnreachableEnumBranching.panic-abort.diff | 12 +++++ ...mple.UnreachableEnumBranching.panic-unwind.diff | 12 +++++ 68 files changed, 591 insertions(+), 132 deletions(-) (limited to 'compiler/rustc_const_eval/src') diff --git a/compiler/rustc_codegen_cranelift/src/constant.rs b/compiler/rustc_codegen_cranelift/src/constant.rs index 85adf0f3716..a7e9d7c7bae 100644 --- a/compiler/rustc_codegen_cranelift/src/constant.rs +++ b/compiler/rustc_codegen_cranelift/src/constant.rs @@ -210,8 +210,7 @@ pub(crate) fn codegen_const_value<'tcx>( .offset_i64(fx, i64::try_from(offset.bytes()).unwrap()), layout, ), - ConstValue::Slice { data, meta } => { - let alloc_id = fx.tcx.reserve_and_set_memory_alloc(data); + ConstValue::Slice { alloc_id, meta, phantom: _ } => { let ptr = pointer_for_allocation(fx, alloc_id).get_addr(fx); let len = fx.bcx.ins().iconst(fx.pointer_type, meta as i64); CValue::by_val_pair(ptr, len, layout) diff --git a/compiler/rustc_codegen_ssa/src/mir/operand.rs b/compiler/rustc_codegen_ssa/src/mir/operand.rs index 06bedaaa4a2..41cdd4dd980 100644 --- a/compiler/rustc_codegen_ssa/src/mir/operand.rs +++ b/compiler/rustc_codegen_ssa/src/mir/operand.rs @@ -154,14 +154,11 @@ impl<'a, 'tcx, V: CodegenObject> OperandRef<'tcx, V> { OperandValue::Immediate(llval) } ConstValue::ZeroSized => return OperandRef::zero_sized(layout), - ConstValue::Slice { data, meta } => { + ConstValue::Slice { alloc_id, meta, phantom: _ } => { let BackendRepr::ScalarPair(a_scalar, _) = layout.backend_repr else { bug!("from_const: invalid ScalarPair layout: {:#?}", layout); }; - let a = Scalar::from_pointer( - Pointer::new(bx.tcx().reserve_and_set_memory_alloc(data).into(), Size::ZERO), - &bx.tcx(), - ); + let a = Scalar::from_pointer(Pointer::new(alloc_id.into(), Size::ZERO), &bx.tcx()); let a_llval = bx.scalar_to_backend( a, a_scalar, diff --git a/compiler/rustc_const_eval/src/const_eval/eval_queries.rs b/compiler/rustc_const_eval/src/const_eval/eval_queries.rs index f584f6c948e..0b311d36975 100644 --- a/compiler/rustc_const_eval/src/const_eval/eval_queries.rs +++ b/compiler/rustc_const_eval/src/const_eval/eval_queries.rs @@ -241,10 +241,9 @@ pub(super) fn op_to_const<'tcx>( let (prov, offset) = ptr.into_pointer_or_addr().expect(msg).prov_and_relative_offset(); let alloc_id = prov.alloc_id(); - let data = ecx.tcx.global_alloc(alloc_id).unwrap_memory(); assert!(offset == abi::Size::ZERO, "{}", msg); let meta = b.to_target_usize(ecx).expect(msg); - ConstValue::Slice { data, meta } + ConstValue::Slice { alloc_id, meta, phantom: std::marker::PhantomData } } Immediate::Uninit => bug!("`Uninit` is not a valid value for {}", op.layout.ty), }, diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics.rs b/compiler/rustc_const_eval/src/interpret/intrinsics.rs index e24a355891d..b1e9f1e8bd2 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics.rs @@ -3,10 +3,11 @@ //! and miri. use std::assert_matches::assert_matches; +use std::marker::PhantomData; use rustc_abi::{FieldIdx, HasDataLayout, Size}; use rustc_apfloat::ieee::{Double, Half, Quad, Single}; -use rustc_middle::mir::interpret::{read_target_uint, write_target_uint}; +use rustc_middle::mir::interpret::{CTFE_ALLOC_SALT, read_target_uint, write_target_uint}; use rustc_middle::mir::{self, BinOp, ConstValue, NonDivergingIntrinsic}; use rustc_middle::ty::layout::TyAndLayout; use rustc_middle::ty::{Ty, TyCtxt}; @@ -17,17 +18,18 @@ use tracing::trace; use super::memory::MemoryKind; use super::util::ensure_monomorphic_enough; use super::{ - Allocation, CheckInAllocMsg, ConstAllocation, ImmTy, InterpCx, InterpResult, Machine, OpTy, - PlaceTy, Pointer, PointerArithmetic, Provenance, Scalar, err_ub_custom, err_unsup_format, - interp_ok, throw_inval, throw_ub_custom, throw_ub_format, + AllocId, CheckInAllocMsg, ImmTy, InterpCx, InterpResult, Machine, OpTy, PlaceTy, Pointer, + PointerArithmetic, Provenance, Scalar, err_ub_custom, err_unsup_format, interp_ok, throw_inval, + throw_ub_custom, throw_ub_format, }; use crate::fluent_generated as fluent; /// Directly returns an `Allocation` containing an absolute path representation of the given type. -pub(crate) fn alloc_type_name<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> ConstAllocation<'tcx> { +pub(crate) fn alloc_type_name<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> (AllocId, u64) { let path = crate::util::type_name(tcx, ty); - let alloc = Allocation::from_bytes_byte_aligned_immutable(path.into_bytes(), ()); - tcx.mk_const_alloc(alloc) + let bytes = path.into_bytes(); + let len = bytes.len().try_into().unwrap(); + (tcx.allocate_bytes_dedup(bytes, CTFE_ALLOC_SALT), len) } impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { /// Generates a value of `TypeId` for `ty` in-place. @@ -126,8 +128,8 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { sym::type_name => { let tp_ty = instance.args.type_at(0); ensure_monomorphic_enough(tcx, tp_ty)?; - let alloc = alloc_type_name(tcx, tp_ty); - let val = ConstValue::Slice { data: alloc, meta: alloc.inner().size().bytes() }; + let (alloc_id, meta) = alloc_type_name(tcx, tp_ty); + let val = ConstValue::Slice { alloc_id, meta, phantom: PhantomData }; let val = self.const_val_to_op(val, dest.layout.ty, Some(dest.layout))?; self.copy_op(&val, dest)?; } diff --git a/compiler/rustc_const_eval/src/interpret/operand.rs b/compiler/rustc_const_eval/src/interpret/operand.rs index 62cbbae24a8..ed48e6799e6 100644 --- a/compiler/rustc_const_eval/src/interpret/operand.rs +++ b/compiler/rustc_const_eval/src/interpret/operand.rs @@ -860,9 +860,8 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { } mir::ConstValue::Scalar(x) => adjust_scalar(x)?.into(), mir::ConstValue::ZeroSized => Immediate::Uninit, - mir::ConstValue::Slice { data, meta } => { + mir::ConstValue::Slice { alloc_id, meta, phantom: _ } => { // This is const data, no mutation allowed. - let alloc_id = self.tcx.reserve_and_set_memory_alloc(data); let ptr = Pointer::new(CtfeProvenance::from(alloc_id).as_immutable(), Size::ZERO); Immediate::new_slice(self.global_root_pointer(ptr)?.into(), meta, self) } diff --git a/compiler/rustc_middle/src/mir/consts.rs b/compiler/rustc_middle/src/mir/consts.rs index fb941977528..0be274511dc 100644 --- a/compiler/rustc_middle/src/mir/consts.rs +++ b/compiler/rustc_middle/src/mir/consts.rs @@ -9,9 +9,7 @@ use rustc_span::{DUMMY_SP, Span, Symbol}; use rustc_type_ir::TypeVisitableExt; use super::interpret::ReportedErrorInfo; -use crate::mir::interpret::{ - AllocId, AllocRange, ConstAllocation, ErrorHandled, GlobalAlloc, Scalar, alloc_range, -}; +use crate::mir::interpret::{AllocId, AllocRange, ErrorHandled, GlobalAlloc, Scalar, alloc_range}; use crate::mir::{Promoted, pretty_print_const_value}; use crate::ty::print::{pretty_print_const, with_no_trimmed_paths}; use crate::ty::{self, ConstKind, GenericArgsRef, ScalarInt, Ty, TyCtxt}; @@ -32,8 +30,8 @@ pub struct ConstAlloc<'tcx> { /// Represents a constant value in Rust. `Scalar` and `Slice` are optimizations for /// array length computations, enum discriminants and the pattern matching logic. -#[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Hash)] -#[derive(HashStable, Lift)] +#[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Lift, Hash)] +#[derive(HashStable)] pub enum ConstValue<'tcx> { /// Used for types with `layout::abi::Scalar` ABI. /// @@ -52,10 +50,11 @@ pub enum ConstValue<'tcx> { Slice { /// The allocation storing the slice contents. /// This always points to the beginning of the allocation. - data: ConstAllocation<'tcx>, + alloc_id: AllocId, /// The metadata field of the reference. /// This is a "target usize", so we use `u64` as in the interpreter. meta: u64, + phantom: std::marker::PhantomData<&'tcx ()>, }, /// A value not representable by the other variants; needs to be stored in-memory. @@ -77,7 +76,7 @@ pub enum ConstValue<'tcx> { #[cfg(target_pointer_width = "64")] rustc_data_structures::static_assert_size!(ConstValue<'_>, 24); -impl<'tcx> ConstValue<'tcx> { +impl ConstValue<'_> { #[inline] pub fn try_to_scalar(&self) -> Option { match *self { @@ -98,11 +97,11 @@ impl<'tcx> ConstValue<'tcx> { self.try_to_scalar_int()?.try_into().ok() } - pub fn try_to_target_usize(&self, tcx: TyCtxt<'tcx>) -> Option { + pub fn try_to_target_usize(&self, tcx: TyCtxt<'_>) -> Option { Some(self.try_to_scalar_int()?.to_target_usize(tcx)) } - pub fn try_to_bits_for_ty( + pub fn try_to_bits_for_ty<'tcx>( &self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>, @@ -132,12 +131,15 @@ impl<'tcx> ConstValue<'tcx> { } /// Must only be called on constants of type `&str` or `&[u8]`! - pub fn try_get_slice_bytes_for_diagnostics(&self, tcx: TyCtxt<'tcx>) -> Option<&'tcx [u8]> { - let (data, start, end) = match self { + pub fn try_get_slice_bytes_for_diagnostics<'tcx>( + &self, + tcx: TyCtxt<'tcx>, + ) -> Option<&'tcx [u8]> { + let (alloc_id, start, len) = match self { ConstValue::Scalar(_) | ConstValue::ZeroSized => { bug!("`try_get_slice_bytes` on non-slice constant") } - &ConstValue::Slice { data, meta } => (data, 0, meta), + &ConstValue::Slice { alloc_id, meta, phantom: _ } => (alloc_id, 0, meta), &ConstValue::Indirect { alloc_id, offset } => { // The reference itself is stored behind an indirection. // Load the reference, and then load the actual slice contents. @@ -170,26 +172,29 @@ impl<'tcx> ConstValue<'tcx> { // Non-empty slice, must have memory. We know this is a relative pointer. let (inner_prov, offset) = ptr.into_pointer_or_addr().ok()?.prov_and_relative_offset(); - let data = tcx.global_alloc(inner_prov.alloc_id()).unwrap_memory(); - (data, offset.bytes(), offset.bytes() + len) + (inner_prov.alloc_id(), offset.bytes(), len) } }; + let data = tcx.global_alloc(alloc_id).unwrap_memory(); + // This is for diagnostics only, so we are okay to use `inspect_with_uninit_and_ptr_outside_interpreter`. let start = start.try_into().unwrap(); - let end = end.try_into().unwrap(); + let end = start + usize::try_from(len).unwrap(); Some(data.inner().inspect_with_uninit_and_ptr_outside_interpreter(start..end)) } /// Check if a constant may contain provenance information. This is used by MIR opts. /// Can return `true` even if there is no provenance. - pub fn may_have_provenance(&self, tcx: TyCtxt<'tcx>, size: Size) -> bool { + pub fn may_have_provenance(&self, tcx: TyCtxt<'_>, size: Size) -> bool { match *self { ConstValue::ZeroSized | ConstValue::Scalar(Scalar::Int(_)) => return false, ConstValue::Scalar(Scalar::Ptr(..)) => return true, // It's hard to find out the part of the allocation we point to; // just conservatively check everything. - ConstValue::Slice { data, meta: _ } => !data.inner().provenance().ptrs().is_empty(), + ConstValue::Slice { alloc_id, meta: _, phantom: _ } => { + !tcx.global_alloc(alloc_id).unwrap_memory().inner().provenance().ptrs().is_empty() + } ConstValue::Indirect { alloc_id, offset } => !tcx .global_alloc(alloc_id) .unwrap_memory() @@ -200,7 +205,7 @@ impl<'tcx> ConstValue<'tcx> { } /// Check if a constant only contains uninitialized bytes. - pub fn all_bytes_uninit(&self, tcx: TyCtxt<'tcx>) -> bool { + pub fn all_bytes_uninit(&self, tcx: TyCtxt<'_>) -> bool { let ConstValue::Indirect { alloc_id, .. } = self else { return false; }; @@ -487,9 +492,8 @@ impl<'tcx> Const<'tcx> { /// taking into account even pointer identity tests. pub fn is_deterministic(&self) -> bool { // Some constants may generate fresh allocations for pointers they contain, - // so using the same constant twice can yield two different results: - // - valtrees purposefully generate new allocations - // - ConstValue::Slice also generate new allocations + // so using the same constant twice can yield two different results. + // Notably, valtrees purposefully generate new allocations. match self { Const::Ty(_, c) => match c.kind() { ty::ConstKind::Param(..) => true, @@ -507,11 +511,11 @@ impl<'tcx> Const<'tcx> { | ty::ConstKind::Placeholder(..) => bug!(), }, Const::Unevaluated(..) => false, - // If the same slice appears twice in the MIR, we cannot guarantee that we will - // give the same `AllocId` to the data. - Const::Val(ConstValue::Slice { .. }, _) => false, Const::Val( - ConstValue::ZeroSized | ConstValue::Scalar(_) | ConstValue::Indirect { .. }, + ConstValue::Slice { .. } + | ConstValue::ZeroSized + | ConstValue::Scalar(_) + | ConstValue::Indirect { .. }, _, ) => true, } diff --git a/compiler/rustc_middle/src/mir/pretty.rs b/compiler/rustc_middle/src/mir/pretty.rs index 8e403dfddae..045b27396f1 100644 --- a/compiler/rustc_middle/src/mir/pretty.rs +++ b/compiler/rustc_middle/src/mir/pretty.rs @@ -1567,11 +1567,7 @@ pub fn write_allocations<'tcx>( ConstValue::Scalar(interpret::Scalar::Ptr(ptr, _)) => Some(ptr.provenance.alloc_id()), ConstValue::Scalar(interpret::Scalar::Int { .. }) => None, ConstValue::ZeroSized => None, - ConstValue::Slice { .. } => { - // `u8`/`str` slices, shouldn't contain pointers that we want to print. - None - } - ConstValue::Indirect { alloc_id, .. } => { + ConstValue::Slice { alloc_id, .. } | ConstValue::Indirect { alloc_id, .. } => { // FIXME: we don't actually want to print all of these, since some are printed nicely directly as values inline in MIR. // Really we'd want `pretty_print_const_value` to decide which allocations to print, instead of having a separate visitor. Some(alloc_id) diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 51db92ecd78..aa2494a4f61 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -5,7 +5,7 @@ pub mod tls; use std::assert_matches::debug_assert_matches; -use std::borrow::Borrow; +use std::borrow::{Borrow, Cow}; use std::cmp::Ordering; use std::env::VarError; use std::ffi::OsStr; @@ -1625,7 +1625,11 @@ impl<'tcx> TyCtxt<'tcx> { /// Allocates a read-only byte or string literal for `mir::interpret` with alignment 1. /// Returns the same `AllocId` if called again with the same bytes. - pub fn allocate_bytes_dedup(self, bytes: &[u8], salt: usize) -> interpret::AllocId { + pub fn allocate_bytes_dedup<'a>( + self, + bytes: impl Into>, + salt: usize, + ) -> interpret::AllocId { // Create an allocation that just contains these bytes. let alloc = interpret::Allocation::from_bytes_byte_aligned_immutable(bytes, ()); let alloc = self.mk_const_alloc(alloc); diff --git a/compiler/rustc_middle/src/ty/structural_impls.rs b/compiler/rustc_middle/src/ty/structural_impls.rs index ab31d943408..2dfc2a2190f 100644 --- a/compiler/rustc_middle/src/ty/structural_impls.rs +++ b/compiler/rustc_middle/src/ty/structural_impls.rs @@ -4,6 +4,7 @@ //! to help with the tedium. use std::fmt::{self, Debug}; +use std::marker::PhantomData; use rustc_abi::TyAndLayout; use rustc_hir::def::Namespace; @@ -311,6 +312,13 @@ TrivialTypeTraversalAndLiftImpls! { /////////////////////////////////////////////////////////////////////////// // Lift implementations +impl<'tcx> Lift> for PhantomData<&()> { + type Lifted = PhantomData<&'tcx ()>; + fn lift_to_interner(self, _: TyCtxt<'tcx>) -> Option { + Some(PhantomData) + } +} + impl<'tcx, T: Lift>> Lift> for Option { type Lifted = Option; fn lift_to_interner(self, tcx: TyCtxt<'tcx>) -> Option { diff --git a/compiler/rustc_mir_build/src/builder/expr/as_constant.rs b/compiler/rustc_mir_build/src/builder/expr/as_constant.rs index d0d0c21463f..4a532c3bb2d 100644 --- a/compiler/rustc_mir_build/src/builder/expr/as_constant.rs +++ b/compiler/rustc_mir_build/src/builder/expr/as_constant.rs @@ -1,9 +1,11 @@ //! See docs in build/expr/mod.rs +use std::marker::PhantomData; + use rustc_abi::Size; use rustc_ast as ast; use rustc_hir::LangItem; -use rustc_middle::mir::interpret::{Allocation, CTFE_ALLOC_SALT, LitToConstInput, Scalar}; +use rustc_middle::mir::interpret::{CTFE_ALLOC_SALT, LitToConstInput, Scalar}; use rustc_middle::mir::*; use rustc_middle::thir::*; use rustc_middle::ty::{ @@ -120,17 +122,26 @@ fn lit_to_mir_constant<'tcx>(tcx: TyCtxt<'tcx>, lit_input: LitToConstInput<'tcx> let value = match (lit, lit_ty.kind()) { (ast::LitKind::Str(s, _), ty::Ref(_, inner_ty, _)) if inner_ty.is_str() => { - let s = s.as_str(); - let allocation = Allocation::from_bytes_byte_aligned_immutable(s.as_bytes(), ()); - let allocation = tcx.mk_const_alloc(allocation); - ConstValue::Slice { data: allocation, meta: allocation.inner().size().bytes() } + let s = s.as_str().as_bytes(); + let len = s.len(); + let allocation = tcx.allocate_bytes_dedup(s, CTFE_ALLOC_SALT); + ConstValue::Slice { + alloc_id: allocation, + meta: len.try_into().unwrap(), + phantom: PhantomData, + } } - (ast::LitKind::ByteStr(data, _), ty::Ref(_, inner_ty, _)) + (ast::LitKind::ByteStr(byte_sym, _), ty::Ref(_, inner_ty, _)) if matches!(inner_ty.kind(), ty::Slice(_)) => { - let allocation = Allocation::from_bytes_byte_aligned_immutable(data.as_byte_str(), ()); - let allocation = tcx.mk_const_alloc(allocation); - ConstValue::Slice { data: allocation, meta: allocation.inner().size().bytes() } + let data = byte_sym.as_byte_str(); + let len = data.len(); + let allocation = tcx.allocate_bytes_dedup(data, CTFE_ALLOC_SALT); + ConstValue::Slice { + alloc_id: allocation, + meta: len.try_into().unwrap(), + phantom: PhantomData, + } } (ast::LitKind::ByteStr(byte_sym, _), ty::Ref(_, inner_ty, _)) if inner_ty.is_array() => { let id = tcx.allocate_bytes_dedup(byte_sym.as_byte_str(), CTFE_ALLOC_SALT); @@ -138,10 +149,14 @@ fn lit_to_mir_constant<'tcx>(tcx: TyCtxt<'tcx>, lit_input: LitToConstInput<'tcx> } (ast::LitKind::CStr(byte_sym, _), ty::Ref(_, inner_ty, _)) if matches!(inner_ty.kind(), ty::Adt(def, _) if tcx.is_lang_item(def.did(), LangItem::CStr)) => { - let allocation = - Allocation::from_bytes_byte_aligned_immutable(byte_sym.as_byte_str(), ()); - let allocation = tcx.mk_const_alloc(allocation); - ConstValue::Slice { data: allocation, meta: allocation.inner().size().bytes() } + let data = byte_sym.as_byte_str(); + let len = data.len(); + let allocation = tcx.allocate_bytes_dedup(data, CTFE_ALLOC_SALT); + ConstValue::Slice { + alloc_id: allocation, + meta: len.try_into().unwrap(), + phantom: PhantomData, + } } (ast::LitKind::Byte(n), ty::Uint(ty::UintTy::U8)) => { ConstValue::Scalar(Scalar::from_uint(n, Size::from_bytes(1))) diff --git a/compiler/rustc_monomorphize/src/collector.rs b/compiler/rustc_monomorphize/src/collector.rs index 91c8e64ce9a..41457f417f2 100644 --- a/compiler/rustc_monomorphize/src/collector.rs +++ b/compiler/rustc_monomorphize/src/collector.rs @@ -1363,10 +1363,8 @@ fn collect_const_value<'tcx>( collect_alloc(tcx, ptr.provenance.alloc_id(), output) } mir::ConstValue::Indirect { alloc_id, .. } => collect_alloc(tcx, alloc_id, output), - mir::ConstValue::Slice { data, meta: _ } => { - for &prov in data.inner().provenance().ptrs().values() { - collect_alloc(tcx, prov.alloc_id(), output); - } + mir::ConstValue::Slice { alloc_id, meta: _, phantom: _ } => { + collect_alloc(tcx, alloc_id, output); } _ => {} } diff --git a/compiler/rustc_public/src/alloc.rs b/compiler/rustc_public/src/alloc.rs index 75ad31022ff..0174e2e0098 100644 --- a/compiler/rustc_public/src/alloc.rs +++ b/compiler/rustc_public/src/alloc.rs @@ -54,8 +54,8 @@ pub(crate) fn try_new_allocation<'tcx>( alloc::try_new_scalar(layout, scalar, cx).map(|alloc| alloc.stable(tables, cx)) } ConstValue::ZeroSized => Ok(new_empty_allocation(layout.align.abi)), - ConstValue::Slice { data, meta } => { - alloc::try_new_slice(layout, data, meta, cx).map(|alloc| alloc.stable(tables, cx)) + ConstValue::Slice { alloc_id, meta, phantom: _ } => { + alloc::try_new_slice(layout, alloc_id, meta, cx).map(|alloc| alloc.stable(tables, cx)) } ConstValue::Indirect { alloc_id, offset } => { let alloc = alloc::try_new_indirect(alloc_id, cx); diff --git a/compiler/rustc_public_bridge/src/alloc.rs b/compiler/rustc_public_bridge/src/alloc.rs index ecf9004562c..7e6af342546 100644 --- a/compiler/rustc_public_bridge/src/alloc.rs +++ b/compiler/rustc_public_bridge/src/alloc.rs @@ -38,11 +38,10 @@ pub fn try_new_scalar<'tcx, B: Bridge>( pub fn try_new_slice<'tcx, B: Bridge>( layout: TyAndLayout<'tcx, Ty<'tcx>>, - data: ConstAllocation<'tcx>, + alloc_id: AllocId, meta: u64, cx: &CompilerCtxt<'tcx, B>, ) -> Result { - let alloc_id = cx.tcx.reserve_and_set_memory_alloc(data); let ptr = Pointer::new(alloc_id.into(), Size::ZERO); let scalar_ptr = Scalar::from_pointer(ptr, &cx.tcx); let scalar_meta: Scalar = Scalar::from_target_usize(meta, &cx.tcx); diff --git a/tests/mir-opt/building/issue_101867.main.built.after.mir b/tests/mir-opt/building/issue_101867.main.built.after.mir index dd1d093c4db..e59b23fdd20 100644 --- a/tests/mir-opt/building/issue_101867.main.built.after.mir +++ b/tests/mir-opt/building/issue_101867.main.built.after.mir @@ -71,3 +71,7 @@ fn main() -> () { resume; } } + +ALLOC0 (size: 14, align: 1) { + 65 78 70 6c 69 63 69 74 20 70 61 6e 69 63 │ explicit panic +} diff --git a/tests/mir-opt/building/storage_live_dead_in_statics.XXX.built.after.mir b/tests/mir-opt/building/storage_live_dead_in_statics.XXX.built.after.mir index 73ead005f8c..4ec12032690 100644 --- a/tests/mir-opt/building/storage_live_dead_in_statics.XXX.built.after.mir +++ b/tests/mir-opt/building/storage_live_dead_in_statics.XXX.built.after.mir @@ -198,3 +198,7 @@ static XXX: &Foo = { return; } } + +ALLOC0 (size: 2, align: 1) { + 68 69 │ hi +} diff --git a/tests/mir-opt/building/user_type_annotations.let_else.built.after.mir b/tests/mir-opt/building/user_type_annotations.let_else.built.after.mir index 3a515787c10..6369dbec750 100644 --- a/tests/mir-opt/building/user_type_annotations.let_else.built.after.mir +++ b/tests/mir-opt/building/user_type_annotations.let_else.built.after.mir @@ -78,3 +78,9 @@ fn let_else() -> () { resume; } } + +ALLOC0 (size: 40, align: 1) { + 0x00 │ 69 6e 74 65 72 6e 61 6c 20 65 72 72 6f 72 3a 20 │ internal error: + 0x10 │ 65 6e 74 65 72 65 64 20 75 6e 72 65 61 63 68 61 │ entered unreacha + 0x20 │ 62 6c 65 20 63 6f 64 65 │ ble code +} diff --git a/tests/mir-opt/building/user_type_annotations.let_else_bindless.built.after.mir b/tests/mir-opt/building/user_type_annotations.let_else_bindless.built.after.mir index 52a6d904d45..b2a06ae53a8 100644 --- a/tests/mir-opt/building/user_type_annotations.let_else_bindless.built.after.mir +++ b/tests/mir-opt/building/user_type_annotations.let_else_bindless.built.after.mir @@ -60,3 +60,9 @@ fn let_else_bindless() -> () { resume; } } + +ALLOC0 (size: 40, align: 1) { + 0x00 │ 69 6e 74 65 72 6e 61 6c 20 65 72 72 6f 72 3a 20 │ internal error: + 0x10 │ 65 6e 74 65 72 65 64 20 75 6e 72 65 61 63 68 61 │ entered unreacha + 0x20 │ 62 6c 65 20 63 6f 64 65 │ ble code +} diff --git a/tests/mir-opt/const_debuginfo.main.SingleUseConsts.diff b/tests/mir-opt/const_debuginfo.main.SingleUseConsts.diff index 8088984bc77..9baf8439e59 100644 --- a/tests/mir-opt/const_debuginfo.main.SingleUseConsts.diff +++ b/tests/mir-opt/const_debuginfo.main.SingleUseConsts.diff @@ -123,3 +123,5 @@ ALLOC1 (size: 4, align: 2) { .. } + ALLOC2 (size: 13, align: 1) { .. } + diff --git a/tests/mir-opt/const_prop/control_flow_simplification.hello.GVN.panic-abort.diff b/tests/mir-opt/const_prop/control_flow_simplification.hello.GVN.panic-abort.diff index 417406de39b..24b10217865 100644 --- a/tests/mir-opt/const_prop/control_flow_simplification.hello.GVN.panic-abort.diff +++ b/tests/mir-opt/const_prop/control_flow_simplification.hello.GVN.panic-abort.diff @@ -24,3 +24,7 @@ } } + ALLOC0 (size: 14, align: 1) { + 65 78 70 6c 69 63 69 74 20 70 61 6e 69 63 │ explicit panic + } + diff --git a/tests/mir-opt/const_prop/control_flow_simplification.hello.GVN.panic-unwind.diff b/tests/mir-opt/const_prop/control_flow_simplification.hello.GVN.panic-unwind.diff index 63ba2c6865f..a73485e7944 100644 --- a/tests/mir-opt/const_prop/control_flow_simplification.hello.GVN.panic-unwind.diff +++ b/tests/mir-opt/const_prop/control_flow_simplification.hello.GVN.panic-unwind.diff @@ -24,3 +24,7 @@ } } + ALLOC0 (size: 14, align: 1) { + 65 78 70 6c 69 63 69 74 20 70 61 6e 69 63 │ explicit panic + } + diff --git a/tests/mir-opt/dead-store-elimination/place_mention.main.DeadStoreElimination-initial.diff b/tests/mir-opt/dead-store-elimination/place_mention.main.DeadStoreElimination-initial.diff index 5a550285871..8e224e0533a 100644 --- a/tests/mir-opt/dead-store-elimination/place_mention.main.DeadStoreElimination-initial.diff +++ b/tests/mir-opt/dead-store-elimination/place_mention.main.DeadStoreElimination-initial.diff @@ -17,3 +17,11 @@ } } + ALLOC0 (size: 5, align: 1) { + 57 6f 72 6c 64 │ World + } + + ALLOC1 (size: 5, align: 1) { + 48 65 6c 6c 6f │ Hello + } + diff --git a/tests/mir-opt/gvn.duplicate_slice.GVN.panic-abort.diff b/tests/mir-opt/gvn.duplicate_slice.GVN.panic-abort.diff index 18c2897d528..3bde339a839 100644 --- a/tests/mir-opt/gvn.duplicate_slice.GVN.panic-abort.diff +++ b/tests/mir-opt/gvn.duplicate_slice.GVN.panic-abort.diff @@ -16,23 +16,31 @@ bb0: { _7 = (const "a",); - _1 = copy (_7.0: &str) as u128 (Transmute); - _5 = identity::<&str>(copy (_7.0: &str)) -> [return: bb1, unwind unreachable]; +- _1 = copy (_7.0: &str) as u128 (Transmute); +- _5 = identity::<&str>(copy (_7.0: &str)) -> [return: bb1, unwind unreachable]; ++ _1 = const "a" as u128 (Transmute); ++ _5 = identity::<&str>(const "a") -> [return: bb1, unwind unreachable]; } bb1: { _3 = copy _5 as u128 (Transmute); _8 = const "a"; - _2 = copy _8 as u128 (Transmute); - _6 = identity::<&str>(copy _8) -> [return: bb2, unwind unreachable]; +- _2 = copy _8 as u128 (Transmute); +- _6 = identity::<&str>(copy _8) -> [return: bb2, unwind unreachable]; ++ _2 = copy _1; ++ _6 = identity::<&str>(const "a") -> [return: bb2, unwind unreachable]; } bb2: { _4 = copy _6 as u128 (Transmute); - _9 = Eq(copy _1, copy _2); +- _9 = Eq(copy _1, copy _2); ++ _9 = const true; _10 = Eq(copy _3, copy _4); - _0 = (copy _9, copy _10); +- _0 = (copy _9, copy _10); ++ _0 = (const true, copy _10); return; } } + ALLOC0 (size: 1, align: 1) { .. } + diff --git a/tests/mir-opt/gvn.duplicate_slice.GVN.panic-unwind.diff b/tests/mir-opt/gvn.duplicate_slice.GVN.panic-unwind.diff index 55f382e926e..cccfbf60585 100644 --- a/tests/mir-opt/gvn.duplicate_slice.GVN.panic-unwind.diff +++ b/tests/mir-opt/gvn.duplicate_slice.GVN.panic-unwind.diff @@ -16,23 +16,31 @@ bb0: { _7 = (const "a",); - _1 = copy (_7.0: &str) as u128 (Transmute); - _5 = identity::<&str>(copy (_7.0: &str)) -> [return: bb1, unwind continue]; +- _1 = copy (_7.0: &str) as u128 (Transmute); +- _5 = identity::<&str>(copy (_7.0: &str)) -> [return: bb1, unwind continue]; ++ _1 = const "a" as u128 (Transmute); ++ _5 = identity::<&str>(const "a") -> [return: bb1, unwind continue]; } bb1: { _3 = copy _5 as u128 (Transmute); _8 = const "a"; - _2 = copy _8 as u128 (Transmute); - _6 = identity::<&str>(copy _8) -> [return: bb2, unwind continue]; +- _2 = copy _8 as u128 (Transmute); +- _6 = identity::<&str>(copy _8) -> [return: bb2, unwind continue]; ++ _2 = copy _1; ++ _6 = identity::<&str>(const "a") -> [return: bb2, unwind continue]; } bb2: { _4 = copy _6 as u128 (Transmute); - _9 = Eq(copy _1, copy _2); +- _9 = Eq(copy _1, copy _2); ++ _9 = const true; _10 = Eq(copy _3, copy _4); - _0 = (copy _9, copy _10); +- _0 = (copy _9, copy _10); ++ _0 = (const true, copy _10); return; } } + ALLOC0 (size: 1, align: 1) { .. } + diff --git a/tests/mir-opt/gvn.fn_pointers.GVN.panic-abort.diff b/tests/mir-opt/gvn.fn_pointers.GVN.panic-abort.diff index 3cce35d34e9..f3f63195637 100644 --- a/tests/mir-opt/gvn.fn_pointers.GVN.panic-abort.diff +++ b/tests/mir-opt/gvn.fn_pointers.GVN.panic-abort.diff @@ -8,10 +8,10 @@ let mut _3: fn(u8) -> u8; let _5: (); let mut _6: fn(u8) -> u8; - let mut _9: {closure@$DIR/gvn.rs:620:19: 620:21}; + let mut _9: {closure@$DIR/gvn.rs:617:19: 617:21}; let _10: (); let mut _11: fn(); - let mut _13: {closure@$DIR/gvn.rs:620:19: 620:21}; + let mut _13: {closure@$DIR/gvn.rs:617:19: 617:21}; let _14: (); let mut _15: fn(); scope 1 { @@ -19,7 +19,7 @@ let _4: fn(u8) -> u8; scope 2 { debug g => _4; - let _7: {closure@$DIR/gvn.rs:620:19: 620:21}; + let _7: {closure@$DIR/gvn.rs:617:19: 617:21}; scope 3 { debug closure => _7; let _8: fn(); @@ -62,16 +62,16 @@ StorageDead(_6); StorageDead(_5); - StorageLive(_7); -- _7 = {closure@$DIR/gvn.rs:620:19: 620:21}; +- _7 = {closure@$DIR/gvn.rs:617:19: 617:21}; - StorageLive(_8); + nop; -+ _7 = const ZeroSized: {closure@$DIR/gvn.rs:620:19: 620:21}; ++ _7 = const ZeroSized: {closure@$DIR/gvn.rs:617:19: 617:21}; + nop; StorageLive(_9); - _9 = copy _7; - _8 = move _9 as fn() (PointerCoercion(ClosureFnPointer(Safe), AsCast)); -+ _9 = const ZeroSized: {closure@$DIR/gvn.rs:620:19: 620:21}; -+ _8 = const ZeroSized: {closure@$DIR/gvn.rs:620:19: 620:21} as fn() (PointerCoercion(ClosureFnPointer(Safe), AsCast)); ++ _9 = const ZeroSized: {closure@$DIR/gvn.rs:617:19: 617:21}; ++ _8 = const ZeroSized: {closure@$DIR/gvn.rs:617:19: 617:21} as fn() (PointerCoercion(ClosureFnPointer(Safe), AsCast)); StorageDead(_9); StorageLive(_10); StorageLive(_11); @@ -88,8 +88,8 @@ StorageLive(_13); - _13 = copy _7; - _12 = move _13 as fn() (PointerCoercion(ClosureFnPointer(Safe), AsCast)); -+ _13 = const ZeroSized: {closure@$DIR/gvn.rs:620:19: 620:21}; -+ _12 = const ZeroSized: {closure@$DIR/gvn.rs:620:19: 620:21} as fn() (PointerCoercion(ClosureFnPointer(Safe), AsCast)); ++ _13 = const ZeroSized: {closure@$DIR/gvn.rs:617:19: 617:21}; ++ _12 = const ZeroSized: {closure@$DIR/gvn.rs:617:19: 617:21} as fn() (PointerCoercion(ClosureFnPointer(Safe), AsCast)); StorageDead(_13); StorageLive(_14); StorageLive(_15); diff --git a/tests/mir-opt/gvn.fn_pointers.GVN.panic-unwind.diff b/tests/mir-opt/gvn.fn_pointers.GVN.panic-unwind.diff index d85aca040fe..029e736a979 100644 --- a/tests/mir-opt/gvn.fn_pointers.GVN.panic-unwind.diff +++ b/tests/mir-opt/gvn.fn_pointers.GVN.panic-unwind.diff @@ -8,10 +8,10 @@ let mut _3: fn(u8) -> u8; let _5: (); let mut _6: fn(u8) -> u8; - let mut _9: {closure@$DIR/gvn.rs:620:19: 620:21}; + let mut _9: {closure@$DIR/gvn.rs:617:19: 617:21}; let _10: (); let mut _11: fn(); - let mut _13: {closure@$DIR/gvn.rs:620:19: 620:21}; + let mut _13: {closure@$DIR/gvn.rs:617:19: 617:21}; let _14: (); let mut _15: fn(); scope 1 { @@ -19,7 +19,7 @@ let _4: fn(u8) -> u8; scope 2 { debug g => _4; - let _7: {closure@$DIR/gvn.rs:620:19: 620:21}; + let _7: {closure@$DIR/gvn.rs:617:19: 617:21}; scope 3 { debug closure => _7; let _8: fn(); @@ -62,16 +62,16 @@ StorageDead(_6); StorageDead(_5); - StorageLive(_7); -- _7 = {closure@$DIR/gvn.rs:620:19: 620:21}; +- _7 = {closure@$DIR/gvn.rs:617:19: 617:21}; - StorageLive(_8); + nop; -+ _7 = const ZeroSized: {closure@$DIR/gvn.rs:620:19: 620:21}; ++ _7 = const ZeroSized: {closure@$DIR/gvn.rs:617:19: 617:21}; + nop; StorageLive(_9); - _9 = copy _7; - _8 = move _9 as fn() (PointerCoercion(ClosureFnPointer(Safe), AsCast)); -+ _9 = const ZeroSized: {closure@$DIR/gvn.rs:620:19: 620:21}; -+ _8 = const ZeroSized: {closure@$DIR/gvn.rs:620:19: 620:21} as fn() (PointerCoercion(ClosureFnPointer(Safe), AsCast)); ++ _9 = const ZeroSized: {closure@$DIR/gvn.rs:617:19: 617:21}; ++ _8 = const ZeroSized: {closure@$DIR/gvn.rs:617:19: 617:21} as fn() (PointerCoercion(ClosureFnPointer(Safe), AsCast)); StorageDead(_9); StorageLive(_10); StorageLive(_11); @@ -88,8 +88,8 @@ StorageLive(_13); - _13 = copy _7; - _12 = move _13 as fn() (PointerCoercion(ClosureFnPointer(Safe), AsCast)); -+ _13 = const ZeroSized: {closure@$DIR/gvn.rs:620:19: 620:21}; -+ _12 = const ZeroSized: {closure@$DIR/gvn.rs:620:19: 620:21} as fn() (PointerCoercion(ClosureFnPointer(Safe), AsCast)); ++ _13 = const ZeroSized: {closure@$DIR/gvn.rs:617:19: 617:21}; ++ _12 = const ZeroSized: {closure@$DIR/gvn.rs:617:19: 617:21} as fn() (PointerCoercion(ClosureFnPointer(Safe), AsCast)); StorageDead(_13); StorageLive(_14); StorageLive(_15); diff --git a/tests/mir-opt/gvn.rs b/tests/mir-opt/gvn.rs index 5d348bc3c1e..407980fd0fd 100644 --- a/tests/mir-opt/gvn.rs +++ b/tests/mir-opt/gvn.rs @@ -533,10 +533,10 @@ fn dereferences(t: &mut u32, u: &impl Copy, s: &S) { fn slices() { // CHECK-LABEL: fn slices( // CHECK: {{_.*}} = const " - // CHECK-NOT: {{_.*}} = const " - let s = "my favourite slice"; // This is a `Const::Slice` in MIR. + // CHECK: {{_.*}} = const " + let s = "my favourite slice"; opaque(s); - let t = s; // This should be the same pointer, so cannot be a `Const::Slice`. + let t = s; // This should be the same pointer. opaque(t); assert_eq!(s.as_ptr(), t.as_ptr()); let u = unsafe { transmute::<&str, &[u8]>(s) }; @@ -556,12 +556,12 @@ fn duplicate_slice() -> (bool, bool) { let d: &str; { // CHECK: [[a:_.*]] = (const "a",); - // CHECK: [[au:_.*]] = copy ([[a]].0: &str) as u128 (Transmute); + // CHECK: [[au:_.*]] = const "a" as u128 (Transmute); let a = ("a",); Call(au = transmute::<_, u128>(a.0), ReturnTo(bb1), UnwindContinue()) } bb1 = { - // CHECK: [[c:_.*]] = identity::<&str>(copy ([[a]].0: &str)) + // CHECK: [[c:_.*]] = identity::<&str>(const "a") Call(c = identity(a.0), ReturnTo(bb2), UnwindContinue()) } bb2 = { @@ -569,15 +569,13 @@ fn duplicate_slice() -> (bool, bool) { Call(cu = transmute::<_, u128>(c), ReturnTo(bb3), UnwindContinue()) } bb3 = { - // This slice is different from `a.0`. Hence `bu` is not `au`. // CHECK: [[b:_.*]] = const "a"; - // CHECK: [[bu:_.*]] = copy [[b]] as u128 (Transmute); + // CHECK: [[bu:_.*]] = copy [[au]]; let b = "a"; Call(bu = transmute::<_, u128>(b), ReturnTo(bb4), UnwindContinue()) } bb4 = { - // This returns a copy of `b`, which is not `a`. - // CHECK: [[d:_.*]] = identity::<&str>(copy [[b]]) + // CHECK: [[d:_.*]] = identity::<&str>(const "a") Call(d = identity(b), ReturnTo(bb5), UnwindContinue()) } bb5 = { @@ -585,8 +583,7 @@ fn duplicate_slice() -> (bool, bool) { Call(du = transmute::<_, u128>(d), ReturnTo(bb6), UnwindContinue()) } bb6 = { - // `direct` must not fold to `true`, as `indirect` will not. - // CHECK: = Eq(copy [[au]], copy [[bu]]); + // CHECK: = const true; // CHECK: = Eq(copy [[cu]], copy [[du]]); let direct = au == bu; let indirect = cu == du; diff --git a/tests/mir-opt/gvn.slices.GVN.panic-abort.diff b/tests/mir-opt/gvn.slices.GVN.panic-abort.diff index e8e99b44e72..091c3bd5c7b 100644 --- a/tests/mir-opt/gvn.slices.GVN.panic-abort.diff +++ b/tests/mir-opt/gvn.slices.GVN.panic-abort.diff @@ -87,22 +87,24 @@ _1 = const "my favourite slice"; StorageLive(_2); StorageLive(_3); - _3 = copy _1; +- _3 = copy _1; - _2 = opaque::<&str>(move _3) -> [return: bb1, unwind unreachable]; -+ _2 = opaque::<&str>(copy _1) -> [return: bb1, unwind unreachable]; ++ _3 = const "my favourite slice"; ++ _2 = opaque::<&str>(const "my favourite slice") -> [return: bb1, unwind unreachable]; } bb1: { StorageDead(_3); StorageDead(_2); StorageLive(_4); - _4 = copy _1; +- _4 = copy _1; ++ _4 = const "my favourite slice"; StorageLive(_5); StorageLive(_6); - _6 = copy _4; - _5 = opaque::<&str>(move _6) -> [return: bb2, unwind unreachable]; -+ _6 = copy _1; -+ _5 = opaque::<&str>(copy _1) -> [return: bb2, unwind unreachable]; ++ _6 = const "my favourite slice"; ++ _5 = opaque::<&str>(const "my favourite slice") -> [return: bb2, unwind unreachable]; } bb2: { @@ -315,3 +317,5 @@ } } + ALLOC0 (size: 18, align: 1) { .. } + diff --git a/tests/mir-opt/gvn.slices.GVN.panic-unwind.diff b/tests/mir-opt/gvn.slices.GVN.panic-unwind.diff index 4296d4d4a59..9768956c9c8 100644 --- a/tests/mir-opt/gvn.slices.GVN.panic-unwind.diff +++ b/tests/mir-opt/gvn.slices.GVN.panic-unwind.diff @@ -87,22 +87,24 @@ _1 = const "my favourite slice"; StorageLive(_2); StorageLive(_3); - _3 = copy _1; +- _3 = copy _1; - _2 = opaque::<&str>(move _3) -> [return: bb1, unwind continue]; -+ _2 = opaque::<&str>(copy _1) -> [return: bb1, unwind continue]; ++ _3 = const "my favourite slice"; ++ _2 = opaque::<&str>(const "my favourite slice") -> [return: bb1, unwind continue]; } bb1: { StorageDead(_3); StorageDead(_2); StorageLive(_4); - _4 = copy _1; +- _4 = copy _1; ++ _4 = const "my favourite slice"; StorageLive(_5); StorageLive(_6); - _6 = copy _4; - _5 = opaque::<&str>(move _6) -> [return: bb2, unwind continue]; -+ _6 = copy _1; -+ _5 = opaque::<&str>(copy _1) -> [return: bb2, unwind continue]; ++ _6 = const "my favourite slice"; ++ _5 = opaque::<&str>(const "my favourite slice") -> [return: bb2, unwind continue]; } bb2: { @@ -315,3 +317,5 @@ } } + ALLOC0 (size: 18, align: 1) { .. } + diff --git a/tests/mir-opt/gvn.wrap_unwrap.GVN.panic-abort.diff b/tests/mir-opt/gvn.wrap_unwrap.GVN.panic-abort.diff index 0433152bb4f..3bbfd3a891e 100644 --- a/tests/mir-opt/gvn.wrap_unwrap.GVN.panic-abort.diff +++ b/tests/mir-opt/gvn.wrap_unwrap.GVN.panic-abort.diff @@ -47,3 +47,5 @@ } } + ALLOC0 (size: 14, align: 1) { .. } + diff --git a/tests/mir-opt/gvn.wrap_unwrap.GVN.panic-unwind.diff b/tests/mir-opt/gvn.wrap_unwrap.GVN.panic-unwind.diff index 5722c865c2f..03464f43f81 100644 --- a/tests/mir-opt/gvn.wrap_unwrap.GVN.panic-unwind.diff +++ b/tests/mir-opt/gvn.wrap_unwrap.GVN.panic-unwind.diff @@ -47,3 +47,5 @@ } } + ALLOC0 (size: 14, align: 1) { .. } + diff --git a/tests/mir-opt/inline/inline_diverging.g.Inline.panic-abort.diff b/tests/mir-opt/inline/inline_diverging.g.Inline.panic-abort.diff index bda85586515..423de59e575 100644 --- a/tests/mir-opt/inline/inline_diverging.g.Inline.panic-abort.diff +++ b/tests/mir-opt/inline/inline_diverging.g.Inline.panic-abort.diff @@ -38,5 +38,9 @@ + StorageLive(_7); + _7 = begin_panic::<&str>(const "explicit panic") -> unwind unreachable; } ++ } ++ ++ ALLOC0 (size: 14, align: 1) { ++ 65 78 70 6c 69 63 69 74 20 70 61 6e 69 63 │ explicit panic } diff --git a/tests/mir-opt/inline/inline_diverging.g.Inline.panic-unwind.diff b/tests/mir-opt/inline/inline_diverging.g.Inline.panic-unwind.diff index ecd72d2b37f..3689744dcb0 100644 --- a/tests/mir-opt/inline/inline_diverging.g.Inline.panic-unwind.diff +++ b/tests/mir-opt/inline/inline_diverging.g.Inline.panic-unwind.diff @@ -38,5 +38,9 @@ + StorageLive(_7); + _7 = begin_panic::<&str>(const "explicit panic") -> unwind continue; } ++ } ++ ++ ALLOC0 (size: 14, align: 1) { ++ 65 78 70 6c 69 63 69 74 20 70 61 6e 69 63 │ explicit panic } diff --git a/tests/mir-opt/inline_coroutine_body.run2-{closure#0}.Inline.panic-abort.diff b/tests/mir-opt/inline_coroutine_body.run2-{closure#0}.Inline.panic-abort.diff index 1e9a6dd4f5c..169a6768448 100644 --- a/tests/mir-opt/inline_coroutine_body.run2-{closure#0}.Inline.panic-abort.diff +++ b/tests/mir-opt/inline_coroutine_body.run2-{closure#0}.Inline.panic-abort.diff @@ -251,7 +251,7 @@ + StorageLive(_50); + _50 = discriminant(_43); + switchInt(move _50) -> [0: bb11, 1: bb12, otherwise: bb5]; -+ } + } + + bb5: { + unreachable; @@ -329,6 +329,11 @@ + StorageDead(_19); + _25 = discriminant(_18); + switchInt(move _25) -> [0: bb7, 1: bb6, otherwise: bb5]; - } ++ } ++ } ++ ++ ALLOC0 (size: 31, align: 1) { ++ 0x00 │ 60 52 65 61 64 79 60 20 70 6f 6c 6c 65 64 20 61 │ `Ready` polled a ++ 0x10 │ 66 74 65 72 20 63 6f 6d 70 6c 65 74 69 6f 6e │ fter completion } diff --git a/tests/mir-opt/inline_coroutine_body.run2-{closure#0}.Inline.panic-unwind.diff b/tests/mir-opt/inline_coroutine_body.run2-{closure#0}.Inline.panic-unwind.diff index 94b89a310ba..14ba3311d2d 100644 --- a/tests/mir-opt/inline_coroutine_body.run2-{closure#0}.Inline.panic-unwind.diff +++ b/tests/mir-opt/inline_coroutine_body.run2-{closure#0}.Inline.panic-unwind.diff @@ -274,7 +274,7 @@ - resume; + bb7: { + unreachable; -+ } + } + + bb8: { + _17 = const (); @@ -370,6 +370,11 @@ + StorageDead(_19); + _25 = discriminant(_18); + switchInt(move _25) -> [0: bb9, 1: bb8, otherwise: bb7]; - } ++ } ++ } ++ ++ ALLOC0 (size: 31, align: 1) { ++ 0x00 │ 60 52 65 61 64 79 60 20 70 6f 6c 6c 65 64 20 61 │ `Ready` polled a ++ 0x10 │ 66 74 65 72 20 63 6f 6d 70 6c 65 74 69 6f 6e │ fter completion } diff --git a/tests/mir-opt/instsimplify/aggregate_array.strs.InstSimplify-after-simplifycfg.diff b/tests/mir-opt/instsimplify/aggregate_array.strs.InstSimplify-after-simplifycfg.diff index f8884881756..ca5573cf97f 100644 --- a/tests/mir-opt/instsimplify/aggregate_array.strs.InstSimplify-after-simplifycfg.diff +++ b/tests/mir-opt/instsimplify/aggregate_array.strs.InstSimplify-after-simplifycfg.diff @@ -11,3 +11,7 @@ } } + ALLOC0 (size: 1, align: 1) { + 61 │ a + } + diff --git a/tests/mir-opt/issue_76432.test.SimplifyComparisonIntegral.panic-abort.diff b/tests/mir-opt/issue_76432.test.SimplifyComparisonIntegral.panic-abort.diff index c02bab3524b..08dee3697e0 100644 --- a/tests/mir-opt/issue_76432.test.SimplifyComparisonIntegral.panic-abort.diff +++ b/tests/mir-opt/issue_76432.test.SimplifyComparisonIntegral.panic-abort.diff @@ -51,3 +51,9 @@ } } + ALLOC0 (size: 40, align: 1) { + 0x00 │ 69 6e 74 65 72 6e 61 6c 20 65 72 72 6f 72 3a 20 │ internal error: + 0x10 │ 65 6e 74 65 72 65 64 20 75 6e 72 65 61 63 68 61 │ entered unreacha + 0x20 │ 62 6c 65 20 63 6f 64 65 │ ble code + } + diff --git a/tests/mir-opt/issue_76432.test.SimplifyComparisonIntegral.panic-unwind.diff b/tests/mir-opt/issue_76432.test.SimplifyComparisonIntegral.panic-unwind.diff index 49be042588c..aa44a2ad532 100644 --- a/tests/mir-opt/issue_76432.test.SimplifyComparisonIntegral.panic-unwind.diff +++ b/tests/mir-opt/issue_76432.test.SimplifyComparisonIntegral.panic-unwind.diff @@ -51,3 +51,9 @@ } } + ALLOC0 (size: 40, align: 1) { + 0x00 │ 69 6e 74 65 72 6e 61 6c 20 65 72 72 6f 72 3a 20 │ internal error: + 0x10 │ 65 6e 74 65 72 65 64 20 75 6e 72 65 61 63 68 61 │ entered unreacha + 0x20 │ 62 6c 65 20 63 6f 64 65 │ ble code + } + diff --git a/tests/mir-opt/no_drop_for_inactive_variant.unwrap.SimplifyCfg-pre-optimizations.after.panic-abort.mir b/tests/mir-opt/no_drop_for_inactive_variant.unwrap.SimplifyCfg-pre-optimizations.after.panic-abort.mir index fa6c6ce8e57..6e5f6dc9ea8 100644 --- a/tests/mir-opt/no_drop_for_inactive_variant.unwrap.SimplifyCfg-pre-optimizations.after.panic-abort.mir +++ b/tests/mir-opt/no_drop_for_inactive_variant.unwrap.SimplifyCfg-pre-optimizations.after.panic-abort.mir @@ -36,3 +36,7 @@ fn unwrap(_1: Option) -> T { return; } } + +ALLOC0 (size: 14, align: 1) { + 65 78 70 6c 69 63 69 74 20 70 61 6e 69 63 │ explicit panic +} diff --git a/tests/mir-opt/no_drop_for_inactive_variant.unwrap.SimplifyCfg-pre-optimizations.after.panic-unwind.mir b/tests/mir-opt/no_drop_for_inactive_variant.unwrap.SimplifyCfg-pre-optimizations.after.panic-unwind.mir index 54fec3c0f98..758aa45f2a2 100644 --- a/tests/mir-opt/no_drop_for_inactive_variant.unwrap.SimplifyCfg-pre-optimizations.after.panic-unwind.mir +++ b/tests/mir-opt/no_drop_for_inactive_variant.unwrap.SimplifyCfg-pre-optimizations.after.panic-unwind.mir @@ -41,3 +41,7 @@ fn unwrap(_1: Option) -> T { resume; } } + +ALLOC0 (size: 14, align: 1) { + 65 78 70 6c 69 63 69 74 20 70 61 6e 69 63 │ explicit panic +} diff --git a/tests/mir-opt/no_spurious_drop_after_call.main.ElaborateDrops.before.panic-abort.mir b/tests/mir-opt/no_spurious_drop_after_call.main.ElaborateDrops.before.panic-abort.mir index 99a7a6b6154..404de884ab5 100644 --- a/tests/mir-opt/no_spurious_drop_after_call.main.ElaborateDrops.before.panic-abort.mir +++ b/tests/mir-opt/no_spurious_drop_after_call.main.ElaborateDrops.before.panic-abort.mir @@ -38,3 +38,5 @@ fn main() -> () { resume; } } + +ALLOC0 (size: 0, align: 1) {} diff --git a/tests/mir-opt/no_spurious_drop_after_call.main.ElaborateDrops.before.panic-unwind.mir b/tests/mir-opt/no_spurious_drop_after_call.main.ElaborateDrops.before.panic-unwind.mir index 7364b329e12..47a0878ffae 100644 --- a/tests/mir-opt/no_spurious_drop_after_call.main.ElaborateDrops.before.panic-unwind.mir +++ b/tests/mir-opt/no_spurious_drop_after_call.main.ElaborateDrops.before.panic-unwind.mir @@ -38,3 +38,5 @@ fn main() -> () { resume; } } + +ALLOC0 (size: 0, align: 1) {} diff --git a/tests/mir-opt/pre-codegen/issue_117368_print_invalid_constant.main.GVN.32bit.panic-abort.diff b/tests/mir-opt/pre-codegen/issue_117368_print_invalid_constant.main.GVN.32bit.panic-abort.diff index 027c71dfaae..c2d144c98c3 100644 --- a/tests/mir-opt/pre-codegen/issue_117368_print_invalid_constant.main.GVN.32bit.panic-abort.diff +++ b/tests/mir-opt/pre-codegen/issue_117368_print_invalid_constant.main.GVN.32bit.panic-abort.diff @@ -110,9 +110,16 @@ + nop; return; } -+ } -+ + } + +- ALLOC0 (size: 43, align: 1) { + ALLOC0 (size: 8, align: 4) { + 00 00 00 00 __ __ __ __ │ ....░░░░ ++ } ++ ++ ALLOC1 (size: 43, align: 1) { + 0x00 │ 63 61 6c 6c 65 64 20 60 52 65 73 75 6c 74 3a 3a │ called `Result:: + 0x10 │ 75 6e 77 72 61 70 28 29 60 20 6f 6e 20 61 6e 20 │ unwrap()` on an + 0x20 │ 60 45 72 72 60 20 76 61 6c 75 65 │ `Err` value } diff --git a/tests/mir-opt/pre-codegen/issue_117368_print_invalid_constant.main.GVN.64bit.panic-abort.diff b/tests/mir-opt/pre-codegen/issue_117368_print_invalid_constant.main.GVN.64bit.panic-abort.diff index ebf305a6f1b..8641d2d6fa8 100644 --- a/tests/mir-opt/pre-codegen/issue_117368_print_invalid_constant.main.GVN.64bit.panic-abort.diff +++ b/tests/mir-opt/pre-codegen/issue_117368_print_invalid_constant.main.GVN.64bit.panic-abort.diff @@ -110,9 +110,16 @@ + nop; return; } -+ } -+ + } + +- ALLOC0 (size: 43, align: 1) { + ALLOC0 (size: 16, align: 8) { + 00 00 00 00 00 00 00 00 __ __ __ __ __ __ __ __ │ ........░░░░░░░░ ++ } ++ ++ ALLOC1 (size: 43, align: 1) { + 0x00 │ 63 61 6c 6c 65 64 20 60 52 65 73 75 6c 74 3a 3a │ called `Result:: + 0x10 │ 75 6e 77 72 61 70 28 29 60 20 6f 6e 20 61 6e 20 │ unwrap()` on an + 0x20 │ 60 45 72 72 60 20 76 61 6c 75 65 │ `Err` value } diff --git a/tests/mir-opt/single_use_consts.match_const.SingleUseConsts.panic-abort.diff b/tests/mir-opt/single_use_consts.match_const.SingleUseConsts.panic-abort.diff index 354e0988a00..1ba5e47b81b 100644 --- a/tests/mir-opt/single_use_consts.match_const.SingleUseConsts.panic-abort.diff +++ b/tests/mir-opt/single_use_consts.match_const.SingleUseConsts.panic-abort.diff @@ -34,3 +34,15 @@ } } + ALLOC0 (size: 5, align: 1) { + 77 6f 72 6c 64 │ world + } + + ALLOC1 (size: 5, align: 1) { + 74 6f 77 65 6c │ towel + } + + ALLOC2 (size: 5, align: 1) { + 68 65 6c 6c 6f │ hello + } + diff --git a/tests/mir-opt/single_use_consts.match_const.SingleUseConsts.panic-unwind.diff b/tests/mir-opt/single_use_consts.match_const.SingleUseConsts.panic-unwind.diff index 354e0988a00..1ba5e47b81b 100644 --- a/tests/mir-opt/single_use_consts.match_const.SingleUseConsts.panic-unwind.diff +++ b/tests/mir-opt/single_use_consts.match_const.SingleUseConsts.panic-unwind.diff @@ -34,3 +34,15 @@ } } + ALLOC0 (size: 5, align: 1) { + 77 6f 72 6c 64 │ world + } + + ALLOC1 (size: 5, align: 1) { + 74 6f 77 65 6c │ towel + } + + ALLOC2 (size: 5, align: 1) { + 68 65 6c 6c 6f │ hello + } + diff --git a/tests/mir-opt/single_use_consts.match_const_debug.SingleUseConsts.panic-abort.diff b/tests/mir-opt/single_use_consts.match_const_debug.SingleUseConsts.panic-abort.diff index 5cf37dc97cb..e0fabe5a90e 100644 --- a/tests/mir-opt/single_use_consts.match_const_debug.SingleUseConsts.panic-abort.diff +++ b/tests/mir-opt/single_use_consts.match_const_debug.SingleUseConsts.panic-abort.diff @@ -45,3 +45,15 @@ } } + ALLOC0 (size: 5, align: 1) { + 77 6f 72 6c 64 │ world + } + + ALLOC1 (size: 5, align: 1) { + 74 6f 77 65 6c │ towel + } + + ALLOC2 (size: 5, align: 1) { + 68 65 6c 6c 6f │ hello + } + diff --git a/tests/mir-opt/single_use_consts.match_const_debug.SingleUseConsts.panic-unwind.diff b/tests/mir-opt/single_use_consts.match_const_debug.SingleUseConsts.panic-unwind.diff index bdcf086e8d9..26799ae6629 100644 --- a/tests/mir-opt/single_use_consts.match_const_debug.SingleUseConsts.panic-unwind.diff +++ b/tests/mir-opt/single_use_consts.match_const_debug.SingleUseConsts.panic-unwind.diff @@ -45,3 +45,15 @@ } } + ALLOC0 (size: 5, align: 1) { + 77 6f 72 6c 64 │ world + } + + ALLOC1 (size: 5, align: 1) { + 74 6f 77 65 6c │ towel + } + + ALLOC2 (size: 5, align: 1) { + 68 65 6c 6c 6f │ hello + } + diff --git a/tests/mir-opt/sroa/structs.flat.ScalarReplacementOfAggregates.diff b/tests/mir-opt/sroa/structs.flat.ScalarReplacementOfAggregates.diff index 77c7c1a9012..ecd89d14ace 100644 --- a/tests/mir-opt/sroa/structs.flat.ScalarReplacementOfAggregates.diff +++ b/tests/mir-opt/sroa/structs.flat.ScalarReplacementOfAggregates.diff @@ -75,3 +75,7 @@ } } + ALLOC0 (size: 1, align: 1) { + 61 │ a + } + diff --git a/tests/mir-opt/unreachable_enum_branching.byref.UnreachableEnumBranching.panic-abort.diff b/tests/mir-opt/unreachable_enum_branching.byref.UnreachableEnumBranching.panic-abort.diff index ed54a38f70b..610a1a4624f 100644 --- a/tests/mir-opt/unreachable_enum_branching.byref.UnreachableEnumBranching.panic-abort.diff +++ b/tests/mir-opt/unreachable_enum_branching.byref.UnreachableEnumBranching.panic-abort.diff @@ -113,3 +113,19 @@ } } + ALLOC0 (size: 1, align: 1) { + 44 │ D + } + + ALLOC1 (size: 1, align: 1) { + 43 │ C + } + + ALLOC2 (size: 8, align: 1) { + 42 28 45 6d 70 74 79 29 │ B(Empty) + } + + ALLOC3 (size: 8, align: 1) { + 41 28 45 6d 70 74 79 29 │ A(Empty) + } + diff --git a/tests/mir-opt/unreachable_enum_branching.byref.UnreachableEnumBranching.panic-unwind.diff b/tests/mir-opt/unreachable_enum_branching.byref.UnreachableEnumBranching.panic-unwind.diff index ed54a38f70b..610a1a4624f 100644 --- a/tests/mir-opt/unreachable_enum_branching.byref.UnreachableEnumBranching.panic-unwind.diff +++ b/tests/mir-opt/unreachable_enum_branching.byref.UnreachableEnumBranching.panic-unwind.diff @@ -113,3 +113,19 @@ } } + ALLOC0 (size: 1, align: 1) { + 44 │ D + } + + ALLOC1 (size: 1, align: 1) { + 43 │ C + } + + ALLOC2 (size: 8, align: 1) { + 42 28 45 6d 70 74 79 29 │ B(Empty) + } + + ALLOC3 (size: 8, align: 1) { + 41 28 45 6d 70 74 79 29 │ A(Empty) + } + diff --git a/tests/mir-opt/unreachable_enum_branching.custom_discriminant.UnreachableEnumBranching.panic-abort.diff b/tests/mir-opt/unreachable_enum_branching.custom_discriminant.UnreachableEnumBranching.panic-abort.diff index ea6cdbfbe66..97c71762f22 100644 --- a/tests/mir-opt/unreachable_enum_branching.custom_discriminant.UnreachableEnumBranching.panic-abort.diff +++ b/tests/mir-opt/unreachable_enum_branching.custom_discriminant.UnreachableEnumBranching.panic-abort.diff @@ -41,3 +41,11 @@ } } + ALLOC0 (size: 1, align: 1) { + 45 │ E + } + + ALLOC1 (size: 1, align: 1) { + 44 │ D + } + diff --git a/tests/mir-opt/unreachable_enum_branching.custom_discriminant.UnreachableEnumBranching.panic-unwind.diff b/tests/mir-opt/unreachable_enum_branching.custom_discriminant.UnreachableEnumBranching.panic-unwind.diff index ea6cdbfbe66..97c71762f22 100644 --- a/tests/mir-opt/unreachable_enum_branching.custom_discriminant.UnreachableEnumBranching.panic-unwind.diff +++ b/tests/mir-opt/unreachable_enum_branching.custom_discriminant.UnreachableEnumBranching.panic-unwind.diff @@ -41,3 +41,11 @@ } } + ALLOC0 (size: 1, align: 1) { + 45 │ E + } + + ALLOC1 (size: 1, align: 1) { + 44 │ D + } + diff --git a/tests/mir-opt/unreachable_enum_branching.otherwise_t1.UnreachableEnumBranching.panic-abort.diff b/tests/mir-opt/unreachable_enum_branching.otherwise_t1.UnreachableEnumBranching.panic-abort.diff index be934ac688b..7e798abcd4e 100644 --- a/tests/mir-opt/unreachable_enum_branching.otherwise_t1.UnreachableEnumBranching.panic-abort.diff +++ b/tests/mir-opt/unreachable_enum_branching.otherwise_t1.UnreachableEnumBranching.panic-abort.diff @@ -51,3 +51,15 @@ } } + ALLOC0 (size: 1, align: 1) { + 43 │ C + } + + ALLOC1 (size: 8, align: 1) { + 42 28 45 6d 70 74 79 29 │ B(Empty) + } + + ALLOC2 (size: 8, align: 1) { + 41 28 45 6d 70 74 79 29 │ A(Empty) + } + diff --git a/tests/mir-opt/unreachable_enum_branching.otherwise_t1.UnreachableEnumBranching.panic-unwind.diff b/tests/mir-opt/unreachable_enum_branching.otherwise_t1.UnreachableEnumBranching.panic-unwind.diff index be934ac688b..7e798abcd4e 100644 --- a/tests/mir-opt/unreachable_enum_branching.otherwise_t1.UnreachableEnumBranching.panic-unwind.diff +++ b/tests/mir-opt/unreachable_enum_branching.otherwise_t1.UnreachableEnumBranching.panic-unwind.diff @@ -51,3 +51,15 @@ } } + ALLOC0 (size: 1, align: 1) { + 43 │ C + } + + ALLOC1 (size: 8, align: 1) { + 42 28 45 6d 70 74 79 29 │ B(Empty) + } + + ALLOC2 (size: 8, align: 1) { + 41 28 45 6d 70 74 79 29 │ A(Empty) + } + diff --git a/tests/mir-opt/unreachable_enum_branching.otherwise_t2.UnreachableEnumBranching.panic-abort.diff b/tests/mir-opt/unreachable_enum_branching.otherwise_t2.UnreachableEnumBranching.panic-abort.diff index a6d6e0861b1..ac9b047624b 100644 --- a/tests/mir-opt/unreachable_enum_branching.otherwise_t2.UnreachableEnumBranching.panic-abort.diff +++ b/tests/mir-opt/unreachable_enum_branching.otherwise_t2.UnreachableEnumBranching.panic-abort.diff @@ -42,3 +42,11 @@ } } + ALLOC0 (size: 1, align: 1) { + 45 │ E + } + + ALLOC1 (size: 1, align: 1) { + 44 │ D + } + diff --git a/tests/mir-opt/unreachable_enum_branching.otherwise_t2.UnreachableEnumBranching.panic-unwind.diff b/tests/mir-opt/unreachable_enum_branching.otherwise_t2.UnreachableEnumBranching.panic-unwind.diff index a6d6e0861b1..ac9b047624b 100644 --- a/tests/mir-opt/unreachable_enum_branching.otherwise_t2.UnreachableEnumBranching.panic-unwind.diff +++ b/tests/mir-opt/unreachable_enum_branching.otherwise_t2.UnreachableEnumBranching.panic-unwind.diff @@ -42,3 +42,11 @@ } } + ALLOC0 (size: 1, align: 1) { + 45 │ E + } + + ALLOC1 (size: 1, align: 1) { + 44 │ D + } + diff --git a/tests/mir-opt/unreachable_enum_branching.otherwise_t3.UnreachableEnumBranching.panic-abort.diff b/tests/mir-opt/unreachable_enum_branching.otherwise_t3.UnreachableEnumBranching.panic-abort.diff index 120061841a0..9e85e56c583 100644 --- a/tests/mir-opt/unreachable_enum_branching.otherwise_t3.UnreachableEnumBranching.panic-abort.diff +++ b/tests/mir-opt/unreachable_enum_branching.otherwise_t3.UnreachableEnumBranching.panic-abort.diff @@ -51,3 +51,15 @@ } } + ALLOC0 (size: 1, align: 1) { + 43 │ C + } + + ALLOC1 (size: 8, align: 1) { + 42 28 45 6d 70 74 79 29 │ B(Empty) + } + + ALLOC2 (size: 8, align: 1) { + 41 28 45 6d 70 74 79 29 │ A(Empty) + } + diff --git a/tests/mir-opt/unreachable_enum_branching.otherwise_t3.UnreachableEnumBranching.panic-unwind.diff b/tests/mir-opt/unreachable_enum_branching.otherwise_t3.UnreachableEnumBranching.panic-unwind.diff index 120061841a0..9e85e56c583 100644 --- a/tests/mir-opt/unreachable_enum_branching.otherwise_t3.UnreachableEnumBranching.panic-unwind.diff +++ b/tests/mir-opt/unreachable_enum_branching.otherwise_t3.UnreachableEnumBranching.panic-unwind.diff @@ -51,3 +51,15 @@ } } + ALLOC0 (size: 1, align: 1) { + 43 │ C + } + + ALLOC1 (size: 8, align: 1) { + 42 28 45 6d 70 74 79 29 │ B(Empty) + } + + ALLOC2 (size: 8, align: 1) { + 41 28 45 6d 70 74 79 29 │ A(Empty) + } + diff --git a/tests/mir-opt/unreachable_enum_branching.otherwise_t4.UnreachableEnumBranching.panic-abort.diff b/tests/mir-opt/unreachable_enum_branching.otherwise_t4.UnreachableEnumBranching.panic-abort.diff index b86814d6119..e83c6131fa5 100644 --- a/tests/mir-opt/unreachable_enum_branching.otherwise_t4.UnreachableEnumBranching.panic-abort.diff +++ b/tests/mir-opt/unreachable_enum_branching.otherwise_t4.UnreachableEnumBranching.panic-abort.diff @@ -46,3 +46,15 @@ } } + ALLOC0 (size: 2, align: 1) { + 43 44 │ CD + } + + ALLOC1 (size: 6, align: 1) { + 42 28 69 33 32 29 │ B(i32) + } + + ALLOC2 (size: 6, align: 1) { + 41 28 69 33 32 29 │ A(i32) + } + diff --git a/tests/mir-opt/unreachable_enum_branching.otherwise_t4.UnreachableEnumBranching.panic-unwind.diff b/tests/mir-opt/unreachable_enum_branching.otherwise_t4.UnreachableEnumBranching.panic-unwind.diff index b86814d6119..e83c6131fa5 100644 --- a/tests/mir-opt/unreachable_enum_branching.otherwise_t4.UnreachableEnumBranching.panic-unwind.diff +++ b/tests/mir-opt/unreachable_enum_branching.otherwise_t4.UnreachableEnumBranching.panic-unwind.diff @@ -46,3 +46,15 @@ } } + ALLOC0 (size: 2, align: 1) { + 43 44 │ CD + } + + ALLOC1 (size: 6, align: 1) { + 42 28 69 33 32 29 │ B(i32) + } + + ALLOC2 (size: 6, align: 1) { + 41 28 69 33 32 29 │ A(i32) + } + diff --git a/tests/mir-opt/unreachable_enum_branching.otherwise_t4_unreachable_default.UnreachableEnumBranching.panic-abort.diff b/tests/mir-opt/unreachable_enum_branching.otherwise_t4_unreachable_default.UnreachableEnumBranching.panic-abort.diff index 424ac6ba651..33e33ebddec 100644 --- a/tests/mir-opt/unreachable_enum_branching.otherwise_t4_unreachable_default.UnreachableEnumBranching.panic-abort.diff +++ b/tests/mir-opt/unreachable_enum_branching.otherwise_t4_unreachable_default.UnreachableEnumBranching.panic-abort.diff @@ -60,3 +60,19 @@ } } + ALLOC0 (size: 6, align: 1) { + 42 28 69 33 32 29 │ B(i32) + } + + ALLOC1 (size: 6, align: 1) { + 41 28 69 33 32 29 │ A(i32) + } + + ALLOC2 (size: 1, align: 1) { + 44 │ D + } + + ALLOC3 (size: 1, align: 1) { + 43 │ C + } + diff --git a/tests/mir-opt/unreachable_enum_branching.otherwise_t4_unreachable_default.UnreachableEnumBranching.panic-unwind.diff b/tests/mir-opt/unreachable_enum_branching.otherwise_t4_unreachable_default.UnreachableEnumBranching.panic-unwind.diff index 424ac6ba651..33e33ebddec 100644 --- a/tests/mir-opt/unreachable_enum_branching.otherwise_t4_unreachable_default.UnreachableEnumBranching.panic-unwind.diff +++ b/tests/mir-opt/unreachable_enum_branching.otherwise_t4_unreachable_default.UnreachableEnumBranching.panic-unwind.diff @@ -60,3 +60,19 @@ } } + ALLOC0 (size: 6, align: 1) { + 42 28 69 33 32 29 │ B(i32) + } + + ALLOC1 (size: 6, align: 1) { + 41 28 69 33 32 29 │ A(i32) + } + + ALLOC2 (size: 1, align: 1) { + 44 │ D + } + + ALLOC3 (size: 1, align: 1) { + 43 │ C + } + diff --git a/tests/mir-opt/unreachable_enum_branching.otherwise_t4_unreachable_default_2.UnreachableEnumBranching.panic-abort.diff b/tests/mir-opt/unreachable_enum_branching.otherwise_t4_unreachable_default_2.UnreachableEnumBranching.panic-abort.diff index 17e01f38f4e..d11c07c4ba3 100644 --- a/tests/mir-opt/unreachable_enum_branching.otherwise_t4_unreachable_default_2.UnreachableEnumBranching.panic-abort.diff +++ b/tests/mir-opt/unreachable_enum_branching.otherwise_t4_unreachable_default_2.UnreachableEnumBranching.panic-abort.diff @@ -73,3 +73,23 @@ } } + ALLOC0 (size: 9, align: 1) { + 41 28 6f 74 68 65 72 29 44 │ A(other)D + } + + ALLOC1 (size: 4, align: 1) { + 41 28 32 29 │ A(2) + } + + ALLOC2 (size: 4, align: 1) { + 41 28 31 29 │ A(1) + } + + ALLOC3 (size: 6, align: 1) { + 42 28 69 33 32 29 │ B(i32) + } + + ALLOC4 (size: 1, align: 1) { + 43 │ C + } + diff --git a/tests/mir-opt/unreachable_enum_branching.otherwise_t4_unreachable_default_2.UnreachableEnumBranching.panic-unwind.diff b/tests/mir-opt/unreachable_enum_branching.otherwise_t4_unreachable_default_2.UnreachableEnumBranching.panic-unwind.diff index 17e01f38f4e..d11c07c4ba3 100644 --- a/tests/mir-opt/unreachable_enum_branching.otherwise_t4_unreachable_default_2.UnreachableEnumBranching.panic-unwind.diff +++ b/tests/mir-opt/unreachable_enum_branching.otherwise_t4_unreachable_default_2.UnreachableEnumBranching.panic-unwind.diff @@ -73,3 +73,23 @@ } } + ALLOC0 (size: 9, align: 1) { + 41 28 6f 74 68 65 72 29 44 │ A(other)D + } + + ALLOC1 (size: 4, align: 1) { + 41 28 32 29 │ A(2) + } + + ALLOC2 (size: 4, align: 1) { + 41 28 31 29 │ A(1) + } + + ALLOC3 (size: 6, align: 1) { + 42 28 69 33 32 29 │ B(i32) + } + + ALLOC4 (size: 1, align: 1) { + 43 │ C + } + diff --git a/tests/mir-opt/unreachable_enum_branching.otherwise_t5_unreachable_default.UnreachableEnumBranching.panic-abort.diff b/tests/mir-opt/unreachable_enum_branching.otherwise_t5_unreachable_default.UnreachableEnumBranching.panic-abort.diff index 2de1f77eeec..ae1ca6efd43 100644 --- a/tests/mir-opt/unreachable_enum_branching.otherwise_t5_unreachable_default.UnreachableEnumBranching.panic-abort.diff +++ b/tests/mir-opt/unreachable_enum_branching.otherwise_t5_unreachable_default.UnreachableEnumBranching.panic-abort.diff @@ -64,3 +64,19 @@ } } + ALLOC0 (size: 4, align: 1) { + 42 28 54 29 │ B(T) + } + + ALLOC1 (size: 4, align: 1) { + 41 28 54 29 │ A(T) + } + + ALLOC2 (size: 1, align: 1) { + 44 │ D + } + + ALLOC3 (size: 1, align: 1) { + 43 │ C + } + diff --git a/tests/mir-opt/unreachable_enum_branching.otherwise_t5_unreachable_default.UnreachableEnumBranching.panic-unwind.diff b/tests/mir-opt/unreachable_enum_branching.otherwise_t5_unreachable_default.UnreachableEnumBranching.panic-unwind.diff index 5afb78c58a3..1e660036e46 100644 --- a/tests/mir-opt/unreachable_enum_branching.otherwise_t5_unreachable_default.UnreachableEnumBranching.panic-unwind.diff +++ b/tests/mir-opt/unreachable_enum_branching.otherwise_t5_unreachable_default.UnreachableEnumBranching.panic-unwind.diff @@ -68,3 +68,19 @@ } } + ALLOC0 (size: 4, align: 1) { + 42 28 54 29 │ B(T) + } + + ALLOC1 (size: 4, align: 1) { + 41 28 54 29 │ A(T) + } + + ALLOC2 (size: 1, align: 1) { + 44 │ D + } + + ALLOC3 (size: 1, align: 1) { + 43 │ C + } + diff --git a/tests/mir-opt/unreachable_enum_branching.simple.UnreachableEnumBranching.panic-abort.diff b/tests/mir-opt/unreachable_enum_branching.simple.UnreachableEnumBranching.panic-abort.diff index 5c08648fac3..c24bd7e7446 100644 --- a/tests/mir-opt/unreachable_enum_branching.simple.UnreachableEnumBranching.panic-abort.diff +++ b/tests/mir-opt/unreachable_enum_branching.simple.UnreachableEnumBranching.panic-abort.diff @@ -51,3 +51,15 @@ } } + ALLOC0 (size: 1, align: 1) { + 43 │ C + } + + ALLOC1 (size: 8, align: 1) { + 42 28 45 6d 70 74 79 29 │ B(Empty) + } + + ALLOC2 (size: 8, align: 1) { + 41 28 45 6d 70 74 79 29 │ A(Empty) + } + diff --git a/tests/mir-opt/unreachable_enum_branching.simple.UnreachableEnumBranching.panic-unwind.diff b/tests/mir-opt/unreachable_enum_branching.simple.UnreachableEnumBranching.panic-unwind.diff index 5c08648fac3..c24bd7e7446 100644 --- a/tests/mir-opt/unreachable_enum_branching.simple.UnreachableEnumBranching.panic-unwind.diff +++ b/tests/mir-opt/unreachable_enum_branching.simple.UnreachableEnumBranching.panic-unwind.diff @@ -51,3 +51,15 @@ } } + ALLOC0 (size: 1, align: 1) { + 43 │ C + } + + ALLOC1 (size: 8, align: 1) { + 42 28 45 6d 70 74 79 29 │ B(Empty) + } + + ALLOC2 (size: 8, align: 1) { + 41 28 45 6d 70 74 79 29 │ A(Empty) + } + -- cgit 1.4.1-3-g733a5 From 0460c92d527dbada3fde227d3f01e6d1e132a186 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Thu, 3 Jul 2025 18:41:12 +0000 Subject: Remove useless lifetime parameter. --- compiler/rustc_codegen_cranelift/src/constant.rs | 6 +++--- compiler/rustc_codegen_ssa/src/common.rs | 2 +- compiler/rustc_codegen_ssa/src/mir/constant.rs | 2 +- compiler/rustc_codegen_ssa/src/mir/operand.rs | 4 ++-- .../rustc_const_eval/src/const_eval/eval_queries.rs | 8 ++++---- compiler/rustc_const_eval/src/const_eval/mod.rs | 2 +- .../rustc_const_eval/src/const_eval/valtrees.rs | 2 +- .../rustc_const_eval/src/interpret/intrinsics.rs | 3 +-- compiler/rustc_const_eval/src/interpret/operand.rs | 4 ++-- .../rustc_const_eval/src/util/caller_location.rs | 2 +- compiler/rustc_middle/src/hooks/mod.rs | 4 ++-- compiler/rustc_middle/src/mir/consts.rs | 21 ++++++++++----------- compiler/rustc_middle/src/mir/interpret/error.rs | 2 +- compiler/rustc_middle/src/mir/pretty.rs | 12 ++++++------ compiler/rustc_middle/src/mir/query.rs | 2 +- compiler/rustc_middle/src/query/erase.rs | 6 +++--- compiler/rustc_middle/src/query/mod.rs | 2 +- compiler/rustc_middle/src/ty/structural_impls.rs | 3 ++- .../rustc_mir_build/src/builder/expr/as_constant.rs | 20 +++----------------- compiler/rustc_mir_build/src/builder/mod.rs | 6 +----- compiler/rustc_mir_transform/src/gvn.rs | 2 +- compiler/rustc_monomorphize/src/collector.rs | 13 ++++--------- compiler/rustc_public/src/alloc.rs | 6 +++--- compiler/rustc_public_bridge/src/context/impls.rs | 7 ++----- src/tools/clippy/clippy_lints/src/non_copy_const.rs | 4 ++-- 25 files changed, 59 insertions(+), 86 deletions(-) (limited to 'compiler/rustc_const_eval/src') diff --git a/compiler/rustc_codegen_cranelift/src/constant.rs b/compiler/rustc_codegen_cranelift/src/constant.rs index a7e9d7c7bae..a04cfa27237 100644 --- a/compiler/rustc_codegen_cranelift/src/constant.rs +++ b/compiler/rustc_codegen_cranelift/src/constant.rs @@ -74,7 +74,7 @@ pub(crate) fn codegen_tls_ref<'tcx>( pub(crate) fn eval_mir_constant<'tcx>( fx: &FunctionCx<'_, '_, 'tcx>, constant: &ConstOperand<'tcx>, -) -> (ConstValue<'tcx>, Ty<'tcx>) { +) -> (ConstValue, Ty<'tcx>) { let cv = fx.monomorphize(constant.const_); // This cannot fail because we checked all required_consts in advance. let val = cv @@ -93,7 +93,7 @@ pub(crate) fn codegen_constant_operand<'tcx>( pub(crate) fn codegen_const_value<'tcx>( fx: &mut FunctionCx<'_, '_, 'tcx>, - const_val: ConstValue<'tcx>, + const_val: ConstValue, ty: Ty<'tcx>, ) -> CValue<'tcx> { let layout = fx.layout_of(ty); @@ -210,7 +210,7 @@ pub(crate) fn codegen_const_value<'tcx>( .offset_i64(fx, i64::try_from(offset.bytes()).unwrap()), layout, ), - ConstValue::Slice { alloc_id, meta, phantom: _ } => { + ConstValue::Slice { alloc_id, meta } => { let ptr = pointer_for_allocation(fx, alloc_id).get_addr(fx); let len = fx.bcx.ins().iconst(fx.pointer_type, meta as i64); CValue::by_val_pair(ptr, len, layout) diff --git a/compiler/rustc_codegen_ssa/src/common.rs b/compiler/rustc_codegen_ssa/src/common.rs index 48565e0b4de..a6fd6c763ed 100644 --- a/compiler/rustc_codegen_ssa/src/common.rs +++ b/compiler/rustc_codegen_ssa/src/common.rs @@ -148,7 +148,7 @@ pub(crate) fn shift_mask_val<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( pub fn asm_const_to_str<'tcx>( tcx: TyCtxt<'tcx>, sp: Span, - const_value: mir::ConstValue<'tcx>, + const_value: mir::ConstValue, ty_and_layout: TyAndLayout<'tcx>, ) -> String { let mir::ConstValue::Scalar(scalar) = const_value else { diff --git a/compiler/rustc_codegen_ssa/src/mir/constant.rs b/compiler/rustc_codegen_ssa/src/mir/constant.rs index 68a56044a07..11b6ab3cdf1 100644 --- a/compiler/rustc_codegen_ssa/src/mir/constant.rs +++ b/compiler/rustc_codegen_ssa/src/mir/constant.rs @@ -20,7 +20,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { OperandRef::from_const(bx, val, ty) } - pub fn eval_mir_constant(&self, constant: &mir::ConstOperand<'tcx>) -> mir::ConstValue<'tcx> { + pub fn eval_mir_constant(&self, constant: &mir::ConstOperand<'tcx>) -> mir::ConstValue { // `MirUsedCollector` visited all required_consts before codegen began, so if we got here // there can be no more constants that fail to evaluate. self.monomorphize(constant.const_) diff --git a/compiler/rustc_codegen_ssa/src/mir/operand.rs b/compiler/rustc_codegen_ssa/src/mir/operand.rs index 41cdd4dd980..8e308aac769 100644 --- a/compiler/rustc_codegen_ssa/src/mir/operand.rs +++ b/compiler/rustc_codegen_ssa/src/mir/operand.rs @@ -140,7 +140,7 @@ impl<'a, 'tcx, V: CodegenObject> OperandRef<'tcx, V> { pub(crate) fn from_const>( bx: &mut Bx, - val: mir::ConstValue<'tcx>, + val: mir::ConstValue, ty: Ty<'tcx>, ) -> Self { let layout = bx.layout_of(ty); @@ -154,7 +154,7 @@ impl<'a, 'tcx, V: CodegenObject> OperandRef<'tcx, V> { OperandValue::Immediate(llval) } ConstValue::ZeroSized => return OperandRef::zero_sized(layout), - ConstValue::Slice { alloc_id, meta, phantom: _ } => { + ConstValue::Slice { alloc_id, meta } => { let BackendRepr::ScalarPair(a_scalar, _) = layout.backend_repr else { bug!("from_const: invalid ScalarPair layout: {:#?}", layout); }; diff --git a/compiler/rustc_const_eval/src/const_eval/eval_queries.rs b/compiler/rustc_const_eval/src/const_eval/eval_queries.rs index 0b311d36975..5835660e1c3 100644 --- a/compiler/rustc_const_eval/src/const_eval/eval_queries.rs +++ b/compiler/rustc_const_eval/src/const_eval/eval_queries.rs @@ -152,7 +152,7 @@ pub(crate) fn mk_eval_cx_to_read_const_val<'tcx>( pub fn mk_eval_cx_for_const_val<'tcx>( tcx: TyCtxtAt<'tcx>, typing_env: ty::TypingEnv<'tcx>, - val: mir::ConstValue<'tcx>, + val: mir::ConstValue, ty: Ty<'tcx>, ) -> Option<(CompileTimeInterpCx<'tcx>, OpTy<'tcx>)> { let ecx = mk_eval_cx_to_read_const_val(tcx.tcx, tcx.span, typing_env, CanAccessMutGlobal::No); @@ -172,7 +172,7 @@ pub(super) fn op_to_const<'tcx>( ecx: &CompileTimeInterpCx<'tcx>, op: &OpTy<'tcx>, for_diagnostics: bool, -) -> ConstValue<'tcx> { +) -> ConstValue { // Handle ZST consistently and early. if op.layout.is_zst() { return ConstValue::ZeroSized; @@ -243,7 +243,7 @@ pub(super) fn op_to_const<'tcx>( let alloc_id = prov.alloc_id(); assert!(offset == abi::Size::ZERO, "{}", msg); let meta = b.to_target_usize(ecx).expect(msg); - ConstValue::Slice { alloc_id, meta, phantom: std::marker::PhantomData } + ConstValue::Slice { alloc_id, meta } } Immediate::Uninit => bug!("`Uninit` is not a valid value for {}", op.layout.ty), }, @@ -255,7 +255,7 @@ pub(crate) fn turn_into_const_value<'tcx>( tcx: TyCtxt<'tcx>, constant: ConstAlloc<'tcx>, key: ty::PseudoCanonicalInput<'tcx, GlobalId<'tcx>>, -) -> ConstValue<'tcx> { +) -> ConstValue { let cid = key.value; let def_id = cid.instance.def.def_id(); let is_static = tcx.is_static(def_id); diff --git a/compiler/rustc_const_eval/src/const_eval/mod.rs b/compiler/rustc_const_eval/src/const_eval/mod.rs index 0082f90f3b8..624ca1dd2da 100644 --- a/compiler/rustc_const_eval/src/const_eval/mod.rs +++ b/compiler/rustc_const_eval/src/const_eval/mod.rs @@ -28,7 +28,7 @@ const VALTREE_MAX_NODES: usize = 100000; #[instrument(skip(tcx), level = "debug")] pub(crate) fn try_destructure_mir_constant_for_user_output<'tcx>( tcx: TyCtxt<'tcx>, - val: mir::ConstValue<'tcx>, + val: mir::ConstValue, ty: Ty<'tcx>, ) -> Option> { let typing_env = ty::TypingEnv::fully_monomorphized(); diff --git a/compiler/rustc_const_eval/src/const_eval/valtrees.rs b/compiler/rustc_const_eval/src/const_eval/valtrees.rs index 5ab72c853c4..37c6c4a61d8 100644 --- a/compiler/rustc_const_eval/src/const_eval/valtrees.rs +++ b/compiler/rustc_const_eval/src/const_eval/valtrees.rs @@ -259,7 +259,7 @@ pub fn valtree_to_const_value<'tcx>( tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>, cv: ty::Value<'tcx>, -) -> mir::ConstValue<'tcx> { +) -> mir::ConstValue { // Basic idea: We directly construct `Scalar` values from trivial `ValTree`s // (those for constants with type bool, int, uint, float or char). // For all other types we create an `MPlace` and fill that by walking diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics.rs b/compiler/rustc_const_eval/src/interpret/intrinsics.rs index b1e9f1e8bd2..5e3d0a15d8b 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics.rs @@ -3,7 +3,6 @@ //! and miri. use std::assert_matches::assert_matches; -use std::marker::PhantomData; use rustc_abi::{FieldIdx, HasDataLayout, Size}; use rustc_apfloat::ieee::{Double, Half, Quad, Single}; @@ -129,7 +128,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { let tp_ty = instance.args.type_at(0); ensure_monomorphic_enough(tcx, tp_ty)?; let (alloc_id, meta) = alloc_type_name(tcx, tp_ty); - let val = ConstValue::Slice { alloc_id, meta, phantom: PhantomData }; + let val = ConstValue::Slice { alloc_id, meta }; let val = self.const_val_to_op(val, dest.layout.ty, Some(dest.layout))?; self.copy_op(&val, dest)?; } diff --git a/compiler/rustc_const_eval/src/interpret/operand.rs b/compiler/rustc_const_eval/src/interpret/operand.rs index ed48e6799e6..21afd082a05 100644 --- a/compiler/rustc_const_eval/src/interpret/operand.rs +++ b/compiler/rustc_const_eval/src/interpret/operand.rs @@ -836,7 +836,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { pub(crate) fn const_val_to_op( &self, - val_val: mir::ConstValue<'tcx>, + val_val: mir::ConstValue, ty: Ty<'tcx>, layout: Option>, ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> { @@ -860,7 +860,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { } mir::ConstValue::Scalar(x) => adjust_scalar(x)?.into(), mir::ConstValue::ZeroSized => Immediate::Uninit, - mir::ConstValue::Slice { alloc_id, meta, phantom: _ } => { + mir::ConstValue::Slice { alloc_id, meta } => { // This is const data, no mutation allowed. let ptr = Pointer::new(CtfeProvenance::from(alloc_id).as_immutable(), Size::ZERO); Immediate::new_slice(self.global_root_pointer(ptr)?.into(), meta, self) diff --git a/compiler/rustc_const_eval/src/util/caller_location.rs b/compiler/rustc_const_eval/src/util/caller_location.rs index f489b05fbbd..c437934eaab 100644 --- a/compiler/rustc_const_eval/src/util/caller_location.rs +++ b/compiler/rustc_const_eval/src/util/caller_location.rs @@ -57,7 +57,7 @@ pub(crate) fn const_caller_location_provider( file: Symbol, line: u32, col: u32, -) -> mir::ConstValue<'_> { +) -> mir::ConstValue { trace!("const_caller_location: {}:{}:{}", file, line, col); let mut ecx = mk_eval_cx_to_read_const_val( tcx, diff --git a/compiler/rustc_middle/src/hooks/mod.rs b/compiler/rustc_middle/src/hooks/mod.rs index c5ce6efcb81..9d2f0a45237 100644 --- a/compiler/rustc_middle/src/hooks/mod.rs +++ b/compiler/rustc_middle/src/hooks/mod.rs @@ -50,10 +50,10 @@ macro_rules! declare_hooks { declare_hooks! { /// Tries to destructure an `mir::Const` ADT or array into its variant index /// and its field values. This should only be used for pretty printing. - hook try_destructure_mir_constant_for_user_output(val: mir::ConstValue<'tcx>, ty: Ty<'tcx>) -> Option>; + hook try_destructure_mir_constant_for_user_output(val: mir::ConstValue, ty: Ty<'tcx>) -> Option>; /// Getting a &core::panic::Location referring to a span. - hook const_caller_location(file: rustc_span::Symbol, line: u32, col: u32) -> mir::ConstValue<'tcx>; + hook const_caller_location(file: rustc_span::Symbol, line: u32, col: u32) -> mir::ConstValue; /// Returns `true` if this def is a function-like thing that is eligible for /// coverage instrumentation under `-Cinstrument-coverage`. diff --git a/compiler/rustc_middle/src/mir/consts.rs b/compiler/rustc_middle/src/mir/consts.rs index 0be274511dc..96131d47a17 100644 --- a/compiler/rustc_middle/src/mir/consts.rs +++ b/compiler/rustc_middle/src/mir/consts.rs @@ -30,9 +30,9 @@ pub struct ConstAlloc<'tcx> { /// Represents a constant value in Rust. `Scalar` and `Slice` are optimizations for /// array length computations, enum discriminants and the pattern matching logic. -#[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Lift, Hash)] +#[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Hash)] #[derive(HashStable)] -pub enum ConstValue<'tcx> { +pub enum ConstValue { /// Used for types with `layout::abi::Scalar` ABI. /// /// Not using the enum `Value` to encode that this must not be `Uninit`. @@ -54,7 +54,6 @@ pub enum ConstValue<'tcx> { /// The metadata field of the reference. /// This is a "target usize", so we use `u64` as in the interpreter. meta: u64, - phantom: std::marker::PhantomData<&'tcx ()>, }, /// A value not representable by the other variants; needs to be stored in-memory. @@ -74,9 +73,9 @@ pub enum ConstValue<'tcx> { } #[cfg(target_pointer_width = "64")] -rustc_data_structures::static_assert_size!(ConstValue<'_>, 24); +rustc_data_structures::static_assert_size!(ConstValue, 24); -impl ConstValue<'_> { +impl ConstValue { #[inline] pub fn try_to_scalar(&self) -> Option { match *self { @@ -139,7 +138,7 @@ impl ConstValue<'_> { ConstValue::Scalar(_) | ConstValue::ZeroSized => { bug!("`try_get_slice_bytes` on non-slice constant") } - &ConstValue::Slice { alloc_id, meta, phantom: _ } => (alloc_id, 0, meta), + &ConstValue::Slice { alloc_id, meta } => (alloc_id, 0, meta), &ConstValue::Indirect { alloc_id, offset } => { // The reference itself is stored behind an indirection. // Load the reference, and then load the actual slice contents. @@ -192,7 +191,7 @@ impl ConstValue<'_> { ConstValue::Scalar(Scalar::Ptr(..)) => return true, // It's hard to find out the part of the allocation we point to; // just conservatively check everything. - ConstValue::Slice { alloc_id, meta: _, phantom: _ } => { + ConstValue::Slice { alloc_id, meta: _ } => { !tcx.global_alloc(alloc_id).unwrap_memory().inner().provenance().ptrs().is_empty() } ConstValue::Indirect { alloc_id, offset } => !tcx @@ -252,7 +251,7 @@ pub enum Const<'tcx> { /// This constant cannot go back into the type system, as it represents /// something the type system cannot handle (e.g. pointers). - Val(ConstValue<'tcx>, Ty<'tcx>), + Val(ConstValue, Ty<'tcx>), } impl<'tcx> Const<'tcx> { @@ -348,7 +347,7 @@ impl<'tcx> Const<'tcx> { tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>, span: Span, - ) -> Result, ErrorHandled> { + ) -> Result { match self { Const::Ty(_, c) => { if c.has_non_region_param() { @@ -445,7 +444,7 @@ impl<'tcx> Const<'tcx> { } #[inline] - pub fn from_value(val: ConstValue<'tcx>, ty: Ty<'tcx>) -> Self { + pub fn from_value(val: ConstValue, ty: Ty<'tcx>) -> Self { Self::Val(val, ty) } @@ -578,7 +577,7 @@ impl<'tcx> Display for Const<'tcx> { /// Const-related utilities impl<'tcx> TyCtxt<'tcx> { - pub fn span_as_caller_location(self, span: Span) -> ConstValue<'tcx> { + pub fn span_as_caller_location(self, span: Span) -> ConstValue { let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span); let caller = self.sess.source_map().lookup_char_pos(topmost.lo()); self.const_caller_location( diff --git a/compiler/rustc_middle/src/mir/interpret/error.rs b/compiler/rustc_middle/src/mir/interpret/error.rs index 3e68afbfabd..2b0cfb86564 100644 --- a/compiler/rustc_middle/src/mir/interpret/error.rs +++ b/compiler/rustc_middle/src/mir/interpret/error.rs @@ -137,7 +137,7 @@ impl<'tcx> ValTreeCreationError<'tcx> { pub type EvalToAllocationRawResult<'tcx> = Result, ErrorHandled>; pub type EvalStaticInitializerRawResult<'tcx> = Result, ErrorHandled>; -pub type EvalToConstValueResult<'tcx> = Result, ErrorHandled>; +pub type EvalToConstValueResult<'tcx> = Result; pub type EvalToValTreeResult<'tcx> = Result, ValTreeCreationError<'tcx>>; #[cfg(target_pointer_width = "64")] diff --git a/compiler/rustc_middle/src/mir/pretty.rs b/compiler/rustc_middle/src/mir/pretty.rs index 045b27396f1..809cdb329f7 100644 --- a/compiler/rustc_middle/src/mir/pretty.rs +++ b/compiler/rustc_middle/src/mir/pretty.rs @@ -1465,7 +1465,7 @@ impl<'tcx> Visitor<'tcx> for ExtraComments<'tcx> { self.push(&format!("+ user_ty: {user_ty:?}")); } - let fmt_val = |val: ConstValue<'tcx>, ty: Ty<'tcx>| { + let fmt_val = |val: ConstValue, ty: Ty<'tcx>| { let tcx = self.tcx; rustc_data_structures::make_display(move |fmt| { pretty_print_const_value_tcx(tcx, val, ty, fmt) @@ -1562,7 +1562,7 @@ pub fn write_allocations<'tcx>( alloc.inner().provenance().ptrs().values().map(|p| p.alloc_id()) } - fn alloc_id_from_const_val(val: ConstValue<'_>) -> Option { + fn alloc_id_from_const_val(val: ConstValue) -> Option { match val { ConstValue::Scalar(interpret::Scalar::Ptr(ptr, _)) => Some(ptr.provenance.alloc_id()), ConstValue::Scalar(interpret::Scalar::Int { .. }) => None, @@ -1881,7 +1881,7 @@ fn pretty_print_byte_str(fmt: &mut Formatter<'_>, byte_str: &[u8]) -> fmt::Resul fn comma_sep<'tcx>( tcx: TyCtxt<'tcx>, fmt: &mut Formatter<'_>, - elems: Vec<(ConstValue<'tcx>, Ty<'tcx>)>, + elems: Vec<(ConstValue, Ty<'tcx>)>, ) -> fmt::Result { let mut first = true; for (ct, ty) in elems { @@ -1896,7 +1896,7 @@ fn comma_sep<'tcx>( fn pretty_print_const_value_tcx<'tcx>( tcx: TyCtxt<'tcx>, - ct: ConstValue<'tcx>, + ct: ConstValue, ty: Ty<'tcx>, fmt: &mut Formatter<'_>, ) -> fmt::Result { @@ -1943,7 +1943,7 @@ fn pretty_print_const_value_tcx<'tcx>( let ct = tcx.lift(ct).unwrap(); let ty = tcx.lift(ty).unwrap(); if let Some(contents) = tcx.try_destructure_mir_constant_for_user_output(ct, ty) { - let fields: Vec<(ConstValue<'_>, Ty<'_>)> = contents.fields.to_vec(); + let fields: Vec<(ConstValue, Ty<'_>)> = contents.fields.to_vec(); match *ty.kind() { ty::Array(..) => { fmt.write_str("[")?; @@ -2024,7 +2024,7 @@ fn pretty_print_const_value_tcx<'tcx>( } pub(crate) fn pretty_print_const_value<'tcx>( - ct: ConstValue<'tcx>, + ct: ConstValue, ty: Ty<'tcx>, fmt: &mut Formatter<'_>, ) -> fmt::Result { diff --git a/compiler/rustc_middle/src/mir/query.rs b/compiler/rustc_middle/src/mir/query.rs index 3fc05f2caf2..a8a95c699d8 100644 --- a/compiler/rustc_middle/src/mir/query.rs +++ b/compiler/rustc_middle/src/mir/query.rs @@ -173,5 +173,5 @@ pub enum AnnotationSource { #[derive(Copy, Clone, Debug, HashStable)] pub struct DestructuredConstant<'tcx> { pub variant: Option, - pub fields: &'tcx [(ConstValue<'tcx>, Ty<'tcx>)], + pub fields: &'tcx [(ConstValue, Ty<'tcx>)], } diff --git a/compiler/rustc_middle/src/query/erase.rs b/compiler/rustc_middle/src/query/erase.rs index f138c5ca039..dab5900b4ab 100644 --- a/compiler/rustc_middle/src/query/erase.rs +++ b/compiler/rustc_middle/src/query/erase.rs @@ -153,8 +153,8 @@ impl EraseType for Result, mir::interpret::ErrorHandled> { type Result = [u8; size_of::, mir::interpret::ErrorHandled>>()]; } -impl EraseType for Result, mir::interpret::ErrorHandled> { - type Result = [u8; size_of::, mir::interpret::ErrorHandled>>()]; +impl EraseType for Result { + type Result = [u8; size_of::>()]; } impl EraseType for EvalToValTreeResult<'_> { @@ -301,6 +301,7 @@ trivial! { rustc_middle::middle::resolve_bound_vars::ResolvedArg, rustc_middle::middle::stability::DeprecationEntry, rustc_middle::mir::ConstQualifs, + rustc_middle::mir::ConstValue, rustc_middle::mir::interpret::AllocId, rustc_middle::mir::interpret::CtfeProvenance, rustc_middle::mir::interpret::ErrorHandled, @@ -362,7 +363,6 @@ tcx_lifetime! { rustc_middle::mir::Const, rustc_middle::mir::DestructuredConstant, rustc_middle::mir::ConstAlloc, - rustc_middle::mir::ConstValue, rustc_middle::mir::interpret::GlobalId, rustc_middle::mir::interpret::LitToConstInput, rustc_middle::mir::interpret::EvalStaticInitializerRawResult, diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index ad7f4973e23..638dc2c78e4 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -1363,7 +1363,7 @@ rustc_queries! { } /// Converts a type-level constant value into a MIR constant value. - query valtree_to_const_val(key: ty::Value<'tcx>) -> mir::ConstValue<'tcx> { + query valtree_to_const_val(key: ty::Value<'tcx>) -> mir::ConstValue { desc { "converting type-level constant value to MIR constant value"} } diff --git a/compiler/rustc_middle/src/ty/structural_impls.rs b/compiler/rustc_middle/src/ty/structural_impls.rs index 2dfc2a2190f..a5fdce93e4b 100644 --- a/compiler/rustc_middle/src/ty/structural_impls.rs +++ b/compiler/rustc_middle/src/ty/structural_impls.rs @@ -235,6 +235,7 @@ TrivialLiftImpls! { rustc_abi::ExternAbi, rustc_abi::Size, rustc_hir::Safety, + rustc_middle::mir::ConstValue, rustc_type_ir::BoundConstness, rustc_type_ir::PredicatePolarity, // tidy-alphabetical-end @@ -251,7 +252,7 @@ TrivialTypeTraversalImpls! { crate::mir::BlockTailInfo, crate::mir::BorrowKind, crate::mir::CastKind, - crate::mir::ConstValue<'tcx>, + crate::mir::ConstValue, crate::mir::CoroutineSavedLocal, crate::mir::FakeReadCause, crate::mir::Local, diff --git a/compiler/rustc_mir_build/src/builder/expr/as_constant.rs b/compiler/rustc_mir_build/src/builder/expr/as_constant.rs index 4a532c3bb2d..0e0c7a7fa4f 100644 --- a/compiler/rustc_mir_build/src/builder/expr/as_constant.rs +++ b/compiler/rustc_mir_build/src/builder/expr/as_constant.rs @@ -1,7 +1,5 @@ //! See docs in build/expr/mod.rs -use std::marker::PhantomData; - use rustc_abi::Size; use rustc_ast as ast; use rustc_hir::LangItem; @@ -125,11 +123,7 @@ fn lit_to_mir_constant<'tcx>(tcx: TyCtxt<'tcx>, lit_input: LitToConstInput<'tcx> let s = s.as_str().as_bytes(); let len = s.len(); let allocation = tcx.allocate_bytes_dedup(s, CTFE_ALLOC_SALT); - ConstValue::Slice { - alloc_id: allocation, - meta: len.try_into().unwrap(), - phantom: PhantomData, - } + ConstValue::Slice { alloc_id: allocation, meta: len.try_into().unwrap() } } (ast::LitKind::ByteStr(byte_sym, _), ty::Ref(_, inner_ty, _)) if matches!(inner_ty.kind(), ty::Slice(_)) => @@ -137,11 +131,7 @@ fn lit_to_mir_constant<'tcx>(tcx: TyCtxt<'tcx>, lit_input: LitToConstInput<'tcx> let data = byte_sym.as_byte_str(); let len = data.len(); let allocation = tcx.allocate_bytes_dedup(data, CTFE_ALLOC_SALT); - ConstValue::Slice { - alloc_id: allocation, - meta: len.try_into().unwrap(), - phantom: PhantomData, - } + ConstValue::Slice { alloc_id: allocation, meta: len.try_into().unwrap() } } (ast::LitKind::ByteStr(byte_sym, _), ty::Ref(_, inner_ty, _)) if inner_ty.is_array() => { let id = tcx.allocate_bytes_dedup(byte_sym.as_byte_str(), CTFE_ALLOC_SALT); @@ -152,11 +142,7 @@ fn lit_to_mir_constant<'tcx>(tcx: TyCtxt<'tcx>, lit_input: LitToConstInput<'tcx> let data = byte_sym.as_byte_str(); let len = data.len(); let allocation = tcx.allocate_bytes_dedup(data, CTFE_ALLOC_SALT); - ConstValue::Slice { - alloc_id: allocation, - meta: len.try_into().unwrap(), - phantom: PhantomData, - } + ConstValue::Slice { alloc_id: allocation, meta: len.try_into().unwrap() } } (ast::LitKind::Byte(n), ty::Uint(ty::UintTy::U8)) => { ConstValue::Scalar(Scalar::from_uint(n, Size::from_bytes(1))) diff --git a/compiler/rustc_mir_build/src/builder/mod.rs b/compiler/rustc_mir_build/src/builder/mod.rs index 3d5f6f4cf45..855cd2f3bc0 100644 --- a/compiler/rustc_mir_build/src/builder/mod.rs +++ b/compiler/rustc_mir_build/src/builder/mod.rs @@ -1045,11 +1045,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } -fn parse_float_into_constval<'tcx>( - num: Symbol, - float_ty: ty::FloatTy, - neg: bool, -) -> Option> { +fn parse_float_into_constval(num: Symbol, float_ty: ty::FloatTy, neg: bool) -> Option { parse_float_into_scalar(num, float_ty, neg).map(|s| ConstValue::Scalar(s.into())) } diff --git a/compiler/rustc_mir_transform/src/gvn.rs b/compiler/rustc_mir_transform/src/gvn.rs index 6657f89ceb5..dc99b67a1e8 100644 --- a/compiler/rustc_mir_transform/src/gvn.rs +++ b/compiler/rustc_mir_transform/src/gvn.rs @@ -1542,7 +1542,7 @@ impl<'body, 'tcx> VnState<'body, 'tcx> { fn op_to_prop_const<'tcx>( ecx: &mut InterpCx<'tcx, DummyMachine>, op: &OpTy<'tcx>, -) -> Option> { +) -> Option { // Do not attempt to propagate unsized locals. if op.layout.is_unsized() { return None; diff --git a/compiler/rustc_monomorphize/src/collector.rs b/compiler/rustc_monomorphize/src/collector.rs index 41457f417f2..d435e4e77b9 100644 --- a/compiler/rustc_monomorphize/src/collector.rs +++ b/compiler/rustc_monomorphize/src/collector.rs @@ -659,10 +659,7 @@ impl<'a, 'tcx> MirUsedCollector<'a, 'tcx> { } /// Evaluates a *not yet monomorphized* constant. - fn eval_constant( - &mut self, - constant: &mir::ConstOperand<'tcx>, - ) -> Option> { + fn eval_constant(&mut self, constant: &mir::ConstOperand<'tcx>) -> Option { let const_ = self.monomorphize(constant.const_); // Evaluate the constant. This makes const eval failure a collection-time error (rather than // a codegen-time error). rustc stops after collection if there was an error, so this @@ -1355,17 +1352,15 @@ fn visit_mentioned_item<'tcx>( #[instrument(skip(tcx, output), level = "debug")] fn collect_const_value<'tcx>( tcx: TyCtxt<'tcx>, - value: mir::ConstValue<'tcx>, + value: mir::ConstValue, output: &mut MonoItems<'tcx>, ) { match value { mir::ConstValue::Scalar(Scalar::Ptr(ptr, _size)) => { collect_alloc(tcx, ptr.provenance.alloc_id(), output) } - mir::ConstValue::Indirect { alloc_id, .. } => collect_alloc(tcx, alloc_id, output), - mir::ConstValue::Slice { alloc_id, meta: _, phantom: _ } => { - collect_alloc(tcx, alloc_id, output); - } + mir::ConstValue::Indirect { alloc_id, .. } + | mir::ConstValue::Slice { alloc_id, meta: _ } => collect_alloc(tcx, alloc_id, output), _ => {} } } diff --git a/compiler/rustc_public/src/alloc.rs b/compiler/rustc_public/src/alloc.rs index 0174e2e0098..0c35b3b25df 100644 --- a/compiler/rustc_public/src/alloc.rs +++ b/compiler/rustc_public/src/alloc.rs @@ -33,7 +33,7 @@ fn new_empty_allocation(align: Align) -> Allocation { #[allow(rustc::usage_of_qualified_ty)] pub(crate) fn new_allocation<'tcx>( ty: rustc_middle::ty::Ty<'tcx>, - const_value: ConstValue<'tcx>, + const_value: ConstValue, tables: &mut Tables<'tcx, BridgeTys>, cx: &CompilerCtxt<'tcx, BridgeTys>, ) -> Allocation { @@ -44,7 +44,7 @@ pub(crate) fn new_allocation<'tcx>( #[allow(rustc::usage_of_qualified_ty)] pub(crate) fn try_new_allocation<'tcx>( ty: rustc_middle::ty::Ty<'tcx>, - const_value: ConstValue<'tcx>, + const_value: ConstValue, tables: &mut Tables<'tcx, BridgeTys>, cx: &CompilerCtxt<'tcx, BridgeTys>, ) -> Result { @@ -54,7 +54,7 @@ pub(crate) fn try_new_allocation<'tcx>( alloc::try_new_scalar(layout, scalar, cx).map(|alloc| alloc.stable(tables, cx)) } ConstValue::ZeroSized => Ok(new_empty_allocation(layout.align.abi)), - ConstValue::Slice { alloc_id, meta, phantom: _ } => { + ConstValue::Slice { alloc_id, meta } => { alloc::try_new_slice(layout, alloc_id, meta, cx).map(|alloc| alloc.stable(tables, cx)) } ConstValue::Indirect { alloc_id, offset } => { diff --git a/compiler/rustc_public_bridge/src/context/impls.rs b/compiler/rustc_public_bridge/src/context/impls.rs index 612e44b56b1..9b3948d232d 100644 --- a/compiler/rustc_public_bridge/src/context/impls.rs +++ b/compiler/rustc_public_bridge/src/context/impls.rs @@ -63,7 +63,7 @@ impl<'tcx, B: Bridge> CompilerCtxt<'tcx, B> { self.tcx.coroutine_movability(def_id) } - pub fn valtree_to_const_val(&self, key: ty::Value<'tcx>) -> ConstValue<'tcx> { + pub fn valtree_to_const_val(&self, key: ty::Value<'tcx>) -> ConstValue { self.tcx.valtree_to_const_val(key) } @@ -675,10 +675,7 @@ impl<'tcx, B: Bridge> CompilerCtxt<'tcx, B> { } /// Try to evaluate an instance into a constant. - pub fn eval_instance( - &self, - instance: ty::Instance<'tcx>, - ) -> Result, ErrorHandled> { + pub fn eval_instance(&self, instance: ty::Instance<'tcx>) -> Result { self.tcx.const_eval_instance( self.fully_monomorphized(), instance, diff --git a/src/tools/clippy/clippy_lints/src/non_copy_const.rs b/src/tools/clippy/clippy_lints/src/non_copy_const.rs index 5f10e1968f1..388c029c9ef 100644 --- a/src/tools/clippy/clippy_lints/src/non_copy_const.rs +++ b/src/tools/clippy/clippy_lints/src/non_copy_const.rs @@ -338,7 +338,7 @@ impl<'tcx> NonCopyConst<'tcx> { tcx: TyCtxt<'tcx>, typing_env: TypingEnv<'tcx>, ty: Ty<'tcx>, - val: ConstValue<'tcx>, + val: ConstValue, ) -> Result { let ty = tcx.try_normalize_erasing_regions(typing_env, ty).unwrap_or(ty); match self.is_ty_freeze(tcx, typing_env, ty) { @@ -477,7 +477,7 @@ impl<'tcx> NonCopyConst<'tcx> { typing_env: TypingEnv<'tcx>, typeck: &'tcx TypeckResults<'tcx>, mut src_expr: &'tcx Expr<'tcx>, - mut val: ConstValue<'tcx>, + mut val: ConstValue, ) -> Result>, ()> { let mut parents = tcx.hir_parent_iter(src_expr.hir_id); let mut ty = typeck.expr_ty(src_expr); -- cgit 1.4.1-3-g733a5 From 967ba2f93d4874f920cb8732724a045b18f525c8 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Mon, 14 Jul 2025 22:48:24 +0000 Subject: Remove const deduplication from the interpreter. --- .../rustc_const_eval/src/interpret/eval_context.rs | 8 ++-- compiler/rustc_const_eval/src/interpret/machine.rs | 22 ----------- src/tools/miri/src/machine.rs | 45 ---------------------- src/tools/miri/tests/pass/const-addrs.rs | 20 ++++------ 4 files changed, 10 insertions(+), 85 deletions(-) (limited to 'compiler/rustc_const_eval/src') diff --git a/compiler/rustc_const_eval/src/interpret/eval_context.rs b/compiler/rustc_const_eval/src/interpret/eval_context.rs index 11e7706fe60..0c888694e49 100644 --- a/compiler/rustc_const_eval/src/interpret/eval_context.rs +++ b/compiler/rustc_const_eval/src/interpret/eval_context.rs @@ -582,8 +582,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { span: Span, layout: Option>, ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> { - M::eval_mir_constant(self, *val, span, layout, |ecx, val, span, layout| { - let const_val = val.eval(*ecx.tcx, ecx.typing_env, span).map_err(|err| { + let const_val = val.eval(*self.tcx, self.typing_env, span).map_err(|err| { if M::ALL_CONSTS_ARE_PRECHECKED { match err { ErrorHandled::TooGeneric(..) => {}, @@ -599,11 +598,10 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { } } } - err.emit_note(*ecx.tcx); + err.emit_note(*self.tcx); err })?; - ecx.const_val_to_op(const_val, val.ty(), layout) - }) + self.const_val_to_op(const_val, val.ty(), layout) } #[must_use] diff --git a/compiler/rustc_const_eval/src/interpret/machine.rs b/compiler/rustc_const_eval/src/interpret/machine.rs index e981f3973ae..e22629993fb 100644 --- a/compiler/rustc_const_eval/src/interpret/machine.rs +++ b/compiler/rustc_const_eval/src/interpret/machine.rs @@ -12,7 +12,6 @@ use rustc_middle::query::TyCtxtAt; use rustc_middle::ty::Ty; use rustc_middle::ty::layout::TyAndLayout; use rustc_middle::{mir, ty}; -use rustc_span::Span; use rustc_span::def_id::DefId; use rustc_target::callconv::FnAbi; @@ -587,27 +586,6 @@ pub trait Machine<'tcx>: Sized { interp_ok(()) } - /// Evaluate the given constant. The `eval` function will do all the required evaluation, - /// but this hook has the chance to do some pre/postprocessing. - #[inline(always)] - fn eval_mir_constant( - ecx: &InterpCx<'tcx, Self>, - val: mir::Const<'tcx>, - span: Span, - layout: Option>, - eval: F, - ) -> InterpResult<'tcx, OpTy<'tcx, Self::Provenance>> - where - F: Fn( - &InterpCx<'tcx, Self>, - mir::Const<'tcx>, - Span, - Option>, - ) -> InterpResult<'tcx, OpTy<'tcx, Self::Provenance>>, - { - eval(ecx, val, span, layout) - } - /// Returns the salt to be used for a deduplicated global alloation. /// If the allocation is for a function, the instance is provided as well /// (this lets Miri ensure unique addresses for some functions). diff --git a/src/tools/miri/src/machine.rs b/src/tools/miri/src/machine.rs index ce33c870b4b..7271d3f619c 100644 --- a/src/tools/miri/src/machine.rs +++ b/src/tools/miri/src/machine.rs @@ -4,7 +4,6 @@ use std::any::Any; use std::borrow::Cow; use std::cell::{Cell, RefCell}; -use std::collections::hash_map::Entry; use std::path::Path; use std::rc::Rc; use std::{fmt, process}; @@ -70,12 +69,6 @@ pub struct FrameExtra<'tcx> { /// This is used by `MiriMachine::current_span` and `MiriMachine::caller_span` pub is_user_relevant: bool, - /// We have a cache for the mapping from [`mir::Const`] to resulting [`AllocId`]. - /// However, we don't want all frames to always get the same result, so we insert - /// an additional bit of "salt" into the cache key. This salt is fixed per-frame - /// so that within a call, a const will have a stable address. - salt: usize, - /// Data race detector per-frame data. pub data_race: Option, } @@ -88,14 +81,12 @@ impl<'tcx> std::fmt::Debug for FrameExtra<'tcx> { catch_unwind, timing: _, is_user_relevant, - salt, data_race, } = self; f.debug_struct("FrameData") .field("borrow_tracker", borrow_tracker) .field("catch_unwind", catch_unwind) .field("is_user_relevant", is_user_relevant) - .field("salt", salt) .field("data_race", data_race) .finish() } @@ -108,7 +99,6 @@ impl VisitProvenance for FrameExtra<'_> { borrow_tracker, timing: _, is_user_relevant: _, - salt: _, data_race: _, } = self; @@ -578,11 +568,6 @@ pub struct MiriMachine<'tcx> { /// diagnostics. pub(crate) allocation_spans: RefCell)>>, - /// Maps MIR consts to their evaluated result. We combine the const with a "salt" (`usize`) - /// that is fixed per stack frame; this lets us have sometimes different results for the - /// same const while ensuring consistent results within a single call. - const_cache: RefCell, usize), OpTy<'tcx>>>, - /// For each allocation, an offset inside that allocation that was deemed aligned even for /// symbolic alignment checks. This cannot be stored in `AllocExtra` since it needs to be /// tracked for vtables and function allocations as well as regular allocations. @@ -764,7 +749,6 @@ impl<'tcx> MiriMachine<'tcx> { stack_size, collect_leak_backtraces: config.collect_leak_backtraces, allocation_spans: RefCell::new(FxHashMap::default()), - const_cache: RefCell::new(FxHashMap::default()), symbolic_alignment: RefCell::new(FxHashMap::default()), union_data_ranges: FxHashMap::default(), pthread_mutex_sanity: Cell::new(false), @@ -941,7 +925,6 @@ impl VisitProvenance for MiriMachine<'_> { stack_size: _, collect_leak_backtraces: _, allocation_spans: _, - const_cache: _, symbolic_alignment: _, union_data_ranges: _, pthread_mutex_sanity: _, @@ -1578,7 +1561,6 @@ impl<'tcx> Machine<'tcx> for MiriMachine<'tcx> { catch_unwind: None, timing, is_user_relevant: ecx.machine.is_user_relevant(&frame), - salt: ecx.machine.rng.borrow_mut().random_range(0..ADDRS_PER_ANON_GLOBAL), data_race: ecx .machine .data_race @@ -1737,33 +1719,6 @@ impl<'tcx> Machine<'tcx> for MiriMachine<'tcx> { interp_ok(()) } - fn eval_mir_constant( - ecx: &InterpCx<'tcx, Self>, - val: mir::Const<'tcx>, - span: Span, - layout: Option>, - eval: F, - ) -> InterpResult<'tcx, OpTy<'tcx>> - where - F: Fn( - &InterpCx<'tcx, Self>, - mir::Const<'tcx>, - Span, - Option>, - ) -> InterpResult<'tcx, OpTy<'tcx>>, - { - let frame = ecx.active_thread_stack().last().unwrap(); - let mut cache = ecx.machine.const_cache.borrow_mut(); - match cache.entry((val, frame.extra.salt)) { - Entry::Vacant(ve) => { - let op = eval(ecx, val, span, layout)?; - ve.insert(op.clone()); - interp_ok(op) - } - Entry::Occupied(oe) => interp_ok(oe.get().clone()), - } - } - fn get_global_alloc_salt( ecx: &InterpCx<'tcx, Self>, instance: Option>, diff --git a/src/tools/miri/tests/pass/const-addrs.rs b/src/tools/miri/tests/pass/const-addrs.rs index af68b28b2b8..0d1531c73cd 100644 --- a/src/tools/miri/tests/pass/const-addrs.rs +++ b/src/tools/miri/tests/pass/const-addrs.rs @@ -1,14 +1,10 @@ -// The const fn interpreter creates a new AllocId every time it evaluates any const. -// If we do that in Miri, repeatedly evaluating a const causes unbounded memory use -// we need to keep track of the base address for that AllocId, and the allocation is never -// deallocated. -// In Miri we explicitly store previously-assigned AllocIds for each const and ensure -// that we only hand out a finite number of AllocIds per const. -// MIR inlining will put every evaluation of the const we're repeatedly evaluating into the same -// stack frame, breaking this test. +// The interpreter used to create a new AllocId every time it evaluates any const. +// This caused unbounded memory use in Miri. +// This test verifies that we only create a bounded amount of addresses for any given const. +// In practice, the interpreter always returns the same address, but we *do not guarantee* that. //@compile-flags: -Zinline-mir=no -const EVALS: usize = 256; +const EVALS: usize = 64; use std::collections::HashSet; fn main() { @@ -16,10 +12,8 @@ fn main() { for _ in 0..EVALS { addrs.insert(const_addr()); } - // Check that the const allocation has multiple base addresses - assert!(addrs.len() > 1); - // But also that we get a limited number of unique base addresses - assert!(addrs.len() < EVALS); + // Check that we always return the same base address for the const allocation. + assert_eq!(addrs.len(), 1); // Check that within a call we always produce the same address let mut prev = 0; -- cgit 1.4.1-3-g733a5 From 296586fb026539916a39b79af9a2c3440ce93976 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sun, 27 Jul 2025 16:24:48 +0200 Subject: miri: for ABI mismatch errors, say which argument is the problem --- compiler/rustc_const_eval/messages.ftl | 6 +++--- compiler/rustc_const_eval/src/errors.rs | 16 ++++++++++------ compiler/rustc_const_eval/src/interpret/call.rs | 10 +++++++--- compiler/rustc_middle/src/mir/interpret/error.rs | 7 ++++++- src/tools/miri/src/diagnostics.rs | 2 +- src/tools/miri/src/helpers.rs | 1 + .../function_pointers/abi_mismatch_array_vs_struct.rs | 2 +- .../abi_mismatch_array_vs_struct.stderr | 2 +- .../fail/function_pointers/abi_mismatch_int_vs_float.rs | 2 +- .../function_pointers/abi_mismatch_int_vs_float.stderr | 2 +- .../fail/function_pointers/abi_mismatch_raw_pointer.rs | 2 +- .../function_pointers/abi_mismatch_raw_pointer.stderr | 2 +- .../tests/fail/function_pointers/abi_mismatch_repr_C.rs | 2 +- .../fail/function_pointers/abi_mismatch_repr_C.stderr | 2 +- .../fail/function_pointers/abi_mismatch_return_type.rs | 2 +- .../function_pointers/abi_mismatch_return_type.stderr | 2 -- .../tests/fail/function_pointers/abi_mismatch_simple.rs | 2 +- .../fail/function_pointers/abi_mismatch_simple.stderr | 2 +- .../tests/fail/function_pointers/abi_mismatch_vector.rs | 2 +- .../fail/function_pointers/abi_mismatch_vector.stderr | 2 +- src/tools/miri/tests/fail/shims/input_arg_mismatch.rs | 2 +- .../miri/tests/fail/shims/input_arg_mismatch.stderr | 2 +- .../miri/tests/fail/shims/return_type_mismatch.stderr | 2 -- .../miri/tests/fail/tail_calls/signature-mismatch-arg.rs | 2 +- .../tests/fail/tail_calls/signature-mismatch-arg.stderr | 2 +- 25 files changed, 45 insertions(+), 35 deletions(-) (limited to 'compiler/rustc_const_eval/src') diff --git a/compiler/rustc_const_eval/messages.ftl b/compiler/rustc_const_eval/messages.ftl index aa0bc42d448..2985eafb63a 100644 --- a/compiler/rustc_const_eval/messages.ftl +++ b/compiler/rustc_const_eval/messages.ftl @@ -128,15 +128,15 @@ const_eval_frame_note_inner = inside {$where_ -> const_eval_frame_note_last = the failure occurred here +const_eval_incompatible_arg_types = + calling a function whose parameter #{$arg_idx} has type {$callee_ty} passing argument of type {$caller_ty} + const_eval_incompatible_calling_conventions = calling a function with calling convention "{$callee_conv}" using calling convention "{$caller_conv}" const_eval_incompatible_return_types = calling a function with return type {$callee_ty} passing return place of type {$caller_ty} -const_eval_incompatible_types = - calling a function with argument of type {$callee_ty} passing data of type {$caller_ty} - const_eval_interior_mutable_borrow_escaping = interior mutable shared borrows of temporaries that have their lifetime extended until the end of the program are not allowed .label = this borrow of an interior mutable value refers to such a temporary diff --git a/compiler/rustc_const_eval/src/errors.rs b/compiler/rustc_const_eval/src/errors.rs index b6a64035261..a4148cb145f 100644 --- a/compiler/rustc_const_eval/src/errors.rs +++ b/compiler/rustc_const_eval/src/errors.rs @@ -500,7 +500,7 @@ impl<'a> ReportErrorExt for UndefinedBehaviorInfo<'a> { InvalidNichedEnumVariantWritten { .. } => { const_eval_invalid_niched_enum_variant_written } - AbiMismatchArgument { .. } => const_eval_incompatible_types, + AbiMismatchArgument { .. } => const_eval_incompatible_arg_types, AbiMismatchReturn { .. } => const_eval_incompatible_return_types, } } @@ -625,12 +625,16 @@ impl<'a> ReportErrorExt for UndefinedBehaviorInfo<'a> { diag.arg("data_size", info.data_size); } InvalidNichedEnumVariantWritten { enum_ty } => { - diag.arg("ty", enum_ty.to_string()); + diag.arg("ty", enum_ty); } - AbiMismatchArgument { caller_ty, callee_ty } - | AbiMismatchReturn { caller_ty, callee_ty } => { - diag.arg("caller_ty", caller_ty.to_string()); - diag.arg("callee_ty", callee_ty.to_string()); + AbiMismatchArgument { arg_idx, caller_ty, callee_ty } => { + diag.arg("arg_idx", arg_idx + 1); // adjust for 1-indexed lists in output + diag.arg("caller_ty", caller_ty); + diag.arg("callee_ty", callee_ty); + } + AbiMismatchReturn { caller_ty, callee_ty } => { + diag.arg("caller_ty", caller_ty); + diag.arg("callee_ty", callee_ty); } } } diff --git a/compiler/rustc_const_eval/src/interpret/call.rs b/compiler/rustc_const_eval/src/interpret/call.rs index 1503f3bcd99..bda00ea2fb8 100644 --- a/compiler/rustc_const_eval/src/interpret/call.rs +++ b/compiler/rustc_const_eval/src/interpret/call.rs @@ -270,6 +270,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { Item = (&'x FnArg<'tcx, M::Provenance>, &'y ArgAbi<'tcx, Ty<'tcx>>), >, callee_abi: &ArgAbi<'tcx, Ty<'tcx>>, + callee_arg_idx: usize, callee_arg: &mir::Place<'tcx>, callee_ty: Ty<'tcx>, already_live: bool, @@ -298,6 +299,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { // Check compatibility if !self.check_argument_compat(caller_abi, callee_abi)? { throw_ub!(AbiMismatchArgument { + arg_idx: callee_arg_idx, caller_ty: caller_abi.layout.ty, callee_ty: callee_abi.layout.ty }); @@ -424,7 +426,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { // this is a single iterator (that handles `spread_arg`), then // `pass_argument` would be the loop body. It takes care to // not advance `caller_iter` for ignored arguments. - let mut callee_args_abis = callee_fn_abi.args.iter(); + let mut callee_args_abis = callee_fn_abi.args.iter().enumerate(); for local in body.args_iter() { // Construct the destination place for this argument. At this point all // locals are still dead, so we cannot construct a `PlaceTy`. @@ -445,10 +447,11 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { &[mir::ProjectionElem::Field(FieldIdx::from_usize(i), field_ty)], *self.tcx, ); - let callee_abi = callee_args_abis.next().unwrap(); + let (idx, callee_abi) = callee_args_abis.next().unwrap(); self.pass_argument( &mut caller_args, callee_abi, + idx, &dest, field_ty, /* already_live */ true, @@ -456,10 +459,11 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { } } else { // Normal argument. Cannot mark it as live yet, it might be unsized! - let callee_abi = callee_args_abis.next().unwrap(); + let (idx, callee_abi) = callee_args_abis.next().unwrap(); self.pass_argument( &mut caller_args, callee_abi, + idx, &dest, ty, /* already_live */ false, diff --git a/compiler/rustc_middle/src/mir/interpret/error.rs b/compiler/rustc_middle/src/mir/interpret/error.rs index 2b0cfb86564..3e895c6b280 100644 --- a/compiler/rustc_middle/src/mir/interpret/error.rs +++ b/compiler/rustc_middle/src/mir/interpret/error.rs @@ -426,7 +426,12 @@ pub enum UndefinedBehaviorInfo<'tcx> { /// Trying to set discriminant to the niched variant, but the value does not match. InvalidNichedEnumVariantWritten { enum_ty: Ty<'tcx> }, /// ABI-incompatible argument types. - AbiMismatchArgument { caller_ty: Ty<'tcx>, callee_ty: Ty<'tcx> }, + AbiMismatchArgument { + /// The index of the argument whose type is wrong. + arg_idx: usize, + caller_ty: Ty<'tcx>, + callee_ty: Ty<'tcx>, + }, /// ABI-incompatible return types. AbiMismatchReturn { caller_ty: Ty<'tcx>, callee_ty: Ty<'tcx> }, } diff --git a/src/tools/miri/src/diagnostics.rs b/src/tools/miri/src/diagnostics.rs index 9ecbd31c5b9..8fdf8d643ea 100644 --- a/src/tools/miri/src/diagnostics.rs +++ b/src/tools/miri/src/diagnostics.rs @@ -382,7 +382,7 @@ pub fn report_error<'tcx>( helps.push(note_span!(span, "{:?} was deallocated here:", alloc_id)); } } - AbiMismatchArgument { .. } | AbiMismatchReturn { .. } => { + AbiMismatchArgument { .. } => { helps.push(note!("this means these two types are not *guaranteed* to be ABI-compatible across all targets")); helps.push(note!("if you think this code should be accepted anyway, please report an issue with Miri")); } diff --git a/src/tools/miri/src/helpers.rs b/src/tools/miri/src/helpers.rs index ccfff7fa94b..15699828e00 100644 --- a/src/tools/miri/src/helpers.rs +++ b/src/tools/miri/src/helpers.rs @@ -1079,6 +1079,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { .position(|b| !b) { throw_ub!(AbiMismatchArgument { + arg_idx: index, caller_ty: caller_fn_abi.args[index].layout.ty, callee_ty: callee_fn_abi.args[index].layout.ty }); diff --git a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_array_vs_struct.rs b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_array_vs_struct.rs index 4468eb299f3..26f2e73dd75 100644 --- a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_array_vs_struct.rs +++ b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_array_vs_struct.rs @@ -17,5 +17,5 @@ fn main() { // These two types have the same size but are still not compatible. let g = unsafe { std::mem::transmute::(f) }; - g(Default::default()) //~ ERROR: calling a function with argument of type S passing data of type [i32; 4] + g(Default::default()) //~ ERROR: type S passing argument of type [i32; 4] } diff --git a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_array_vs_struct.stderr b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_array_vs_struct.stderr index cabefa8bee9..f793abb0b62 100644 --- a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_array_vs_struct.stderr +++ b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_array_vs_struct.stderr @@ -1,4 +1,4 @@ -error: Undefined Behavior: calling a function with argument of type S passing data of type [i32; 4] +error: Undefined Behavior: calling a function whose parameter #1 has type S passing argument of type [i32; 4] --> tests/fail/function_pointers/abi_mismatch_array_vs_struct.rs:LL:CC | LL | g(Default::default()) diff --git a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_int_vs_float.rs b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_int_vs_float.rs index a1fda329e8d..0cca4a13233 100644 --- a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_int_vs_float.rs +++ b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_int_vs_float.rs @@ -3,5 +3,5 @@ fn main() { let g = unsafe { std::mem::transmute::(f) }; - g(42) //~ ERROR: calling a function with argument of type f32 passing data of type i32 + g(42) //~ ERROR: type f32 passing argument of type i32 } diff --git a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_int_vs_float.stderr b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_int_vs_float.stderr index 52cc48d58ce..3651fc9b3f7 100644 --- a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_int_vs_float.stderr +++ b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_int_vs_float.stderr @@ -1,4 +1,4 @@ -error: Undefined Behavior: calling a function with argument of type f32 passing data of type i32 +error: Undefined Behavior: calling a function whose parameter #1 has type f32 passing argument of type i32 --> tests/fail/function_pointers/abi_mismatch_int_vs_float.rs:LL:CC | LL | g(42) diff --git a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_raw_pointer.rs b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_raw_pointer.rs index f0ea5ccfe0f..053a4a5f284 100644 --- a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_raw_pointer.rs +++ b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_raw_pointer.rs @@ -3,5 +3,5 @@ fn main() { let g = unsafe { std::mem::transmute::(f) }; - g(&42 as *const i32) //~ ERROR: calling a function with argument of type *const [i32] passing data of type *const i32 + g(&42 as *const i32) //~ ERROR: type *const [i32] passing argument of type *const i32 } diff --git a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_raw_pointer.stderr b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_raw_pointer.stderr index 2fbb0408c59..88345a0688c 100644 --- a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_raw_pointer.stderr +++ b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_raw_pointer.stderr @@ -1,4 +1,4 @@ -error: Undefined Behavior: calling a function with argument of type *const [i32] passing data of type *const i32 +error: Undefined Behavior: calling a function whose parameter #1 has type *const [i32] passing argument of type *const i32 --> tests/fail/function_pointers/abi_mismatch_raw_pointer.rs:LL:CC | LL | g(&42 as *const i32) diff --git a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_repr_C.rs b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_repr_C.rs index c5900489b4c..f3dffcc4e86 100644 --- a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_repr_C.rs +++ b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_repr_C.rs @@ -12,5 +12,5 @@ fn main() { let fnptr: fn(S2) = callee; let fnptr: fn(S1) = unsafe { std::mem::transmute(fnptr) }; fnptr(S1(NonZero::new(1).unwrap())); - //~^ ERROR: calling a function with argument of type S2 passing data of type S1 + //~^ ERROR: type S2 passing argument of type S1 } diff --git a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_repr_C.stderr b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_repr_C.stderr index 2c1ac0ee702..47658395132 100644 --- a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_repr_C.stderr +++ b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_repr_C.stderr @@ -1,4 +1,4 @@ -error: Undefined Behavior: calling a function with argument of type S2 passing data of type S1 +error: Undefined Behavior: calling a function whose parameter #1 has type S2 passing argument of type S1 --> tests/fail/function_pointers/abi_mismatch_repr_C.rs:LL:CC | LL | fnptr(S1(NonZero::new(1).unwrap())); diff --git a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_return_type.rs b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_return_type.rs index 0fdab49b94b..05b645cf75a 100644 --- a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_return_type.rs +++ b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_return_type.rs @@ -5,5 +5,5 @@ fn main() { let g = unsafe { std::mem::transmute:: u32, fn()>(f) }; - g() //~ ERROR: calling a function with return type u32 passing return place of type () + g() //~ ERROR: type u32 passing return place of type () } diff --git a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_return_type.stderr b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_return_type.stderr index 28c676ad482..07e6561b53e 100644 --- a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_return_type.stderr +++ b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_return_type.stderr @@ -6,8 +6,6 @@ LL | g() | = 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 - = help: this means these two types are not *guaranteed* to be ABI-compatible across all targets - = help: if you think this code should be accepted anyway, please report an issue with Miri = note: BACKTRACE: = note: inside `main` at tests/fail/function_pointers/abi_mismatch_return_type.rs:LL:CC diff --git a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_simple.rs b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_simple.rs index 20384f0965b..ca43c06008f 100644 --- a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_simple.rs +++ b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_simple.rs @@ -3,5 +3,5 @@ fn main() { let g = unsafe { std::mem::transmute::(f) }; - g(42) //~ ERROR: calling a function with argument of type (i32, i32) passing data of type i32 + g(42) //~ ERROR: type (i32, i32) passing argument of type i32 } diff --git a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_simple.stderr b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_simple.stderr index e45ad12ec05..2ed9ac2e6da 100644 --- a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_simple.stderr +++ b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_simple.stderr @@ -1,4 +1,4 @@ -error: Undefined Behavior: calling a function with argument of type (i32, i32) passing data of type i32 +error: Undefined Behavior: calling a function whose parameter #1 has type (i32, i32) passing argument of type i32 --> tests/fail/function_pointers/abi_mismatch_simple.rs:LL:CC | LL | g(42) diff --git a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_vector.rs b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_vector.rs index 80f357b61ba..dedcaac6142 100644 --- a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_vector.rs +++ b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_vector.rs @@ -7,5 +7,5 @@ fn main() { // These two vector types have the same size but are still not compatible. let g = unsafe { std::mem::transmute::(f) }; - g(Default::default()) //~ ERROR: calling a function with argument of type std::simd::Simd passing data of type std::simd::Simd + g(Default::default()) //~ ERROR: type std::simd::Simd passing argument of type std::simd::Simd } diff --git a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_vector.stderr b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_vector.stderr index bad2495cb39..b13e8d936db 100644 --- a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_vector.stderr +++ b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_vector.stderr @@ -1,4 +1,4 @@ -error: Undefined Behavior: calling a function with argument of type std::simd::Simd passing data of type std::simd::Simd +error: Undefined Behavior: calling a function whose parameter #1 has type std::simd::Simd passing argument of type std::simd::Simd --> tests/fail/function_pointers/abi_mismatch_vector.rs:LL:CC | LL | g(Default::default()) diff --git a/src/tools/miri/tests/fail/shims/input_arg_mismatch.rs b/src/tools/miri/tests/fail/shims/input_arg_mismatch.rs index eb8de04dcc4..77699776aea 100644 --- a/src/tools/miri/tests/fail/shims/input_arg_mismatch.rs +++ b/src/tools/miri/tests/fail/shims/input_arg_mismatch.rs @@ -16,6 +16,6 @@ fn main() { } as u32; let _ = unsafe { close(fd); - //~^ ERROR: calling a function with argument of type i32 passing data of type u32 + //~^ ERROR: type i32 passing argument of type u32 }; } diff --git a/src/tools/miri/tests/fail/shims/input_arg_mismatch.stderr b/src/tools/miri/tests/fail/shims/input_arg_mismatch.stderr index ce00b624a42..ec27fd5ebb8 100644 --- a/src/tools/miri/tests/fail/shims/input_arg_mismatch.stderr +++ b/src/tools/miri/tests/fail/shims/input_arg_mismatch.stderr @@ -1,4 +1,4 @@ -error: Undefined Behavior: calling a function with argument of type i32 passing data of type u32 +error: Undefined Behavior: calling a function whose parameter #1 has type i32 passing argument of type u32 --> tests/fail/shims/input_arg_mismatch.rs:LL:CC | LL | close(fd); diff --git a/src/tools/miri/tests/fail/shims/return_type_mismatch.stderr b/src/tools/miri/tests/fail/shims/return_type_mismatch.stderr index 18ff3067fa0..080ee16a2eb 100644 --- a/src/tools/miri/tests/fail/shims/return_type_mismatch.stderr +++ b/src/tools/miri/tests/fail/shims/return_type_mismatch.stderr @@ -6,8 +6,6 @@ LL | close(fd); | = 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 - = help: this means these two types are not *guaranteed* to be ABI-compatible across all targets - = help: if you think this code should be accepted anyway, please report an issue with Miri = note: BACKTRACE: = note: inside `main` at tests/fail/shims/return_type_mismatch.rs:LL:CC diff --git a/src/tools/miri/tests/fail/tail_calls/signature-mismatch-arg.rs b/src/tools/miri/tests/fail/tail_calls/signature-mismatch-arg.rs index 6df132d3255..36bd1e99cfb 100644 --- a/src/tools/miri/tests/fail/tail_calls/signature-mismatch-arg.rs +++ b/src/tools/miri/tests/fail/tail_calls/signature-mismatch-arg.rs @@ -6,7 +6,7 @@ fn main() { // the error should point to `become g(x)`, // but tail calls mess up the backtrace it seems like... f(0); - //~^ error: Undefined Behavior: calling a function with argument of type i32 passing data of type u32 + //~^ error: type i32 passing argument of type u32 } fn f(x: u32) { diff --git a/src/tools/miri/tests/fail/tail_calls/signature-mismatch-arg.stderr b/src/tools/miri/tests/fail/tail_calls/signature-mismatch-arg.stderr index fbb0d3d565d..cabea5df85d 100644 --- a/src/tools/miri/tests/fail/tail_calls/signature-mismatch-arg.stderr +++ b/src/tools/miri/tests/fail/tail_calls/signature-mismatch-arg.stderr @@ -1,4 +1,4 @@ -error: Undefined Behavior: calling a function with argument of type i32 passing data of type u32 +error: Undefined Behavior: calling a function whose parameter #1 has type i32 passing argument of type u32 --> tests/fail/tail_calls/signature-mismatch-arg.rs:LL:CC | LL | f(0); -- cgit 1.4.1-3-g733a5 From 43725ed819c57b86b32a66c40572246b1f5b8952 Mon Sep 17 00:00:00 2001 From: Kivooeo Date: Sat, 26 Jul 2025 06:21:22 +0500 Subject: use let chains in ast, borrowck, codegen, const_eval --- compiler/rustc_ast_lowering/src/index.rs | 8 +- compiler/rustc_ast_passes/src/ast_validation.rs | 20 +- compiler/rustc_ast_passes/src/feature_gate.rs | 15 +- compiler/rustc_ast_pretty/src/pprust/state.rs | 8 +- .../src/diagnostics/conflict_errors.rs | 315 ++++++++++----------- .../src/diagnostics/explain_borrow.rs | 37 ++- compiler/rustc_borrowck/src/diagnostics/mod.rs | 64 ++--- .../rustc_borrowck/src/diagnostics/move_errors.rs | 57 ++-- .../rustc_borrowck/src/diagnostics/region_name.rs | 10 +- compiler/rustc_borrowck/src/region_infer/mod.rs | 68 +++-- compiler/rustc_borrowck/src/type_check/mod.rs | 26 +- compiler/rustc_codegen_llvm/src/back/lto.rs | 8 +- compiler/rustc_codegen_llvm/src/builder.rs | 8 +- compiler/rustc_codegen_ssa/src/back/link.rs | 12 +- compiler/rustc_codegen_ssa/src/codegen_attrs.rs | 20 +- .../rustc_const_eval/src/check_consts/check.rs | 8 +- compiler/rustc_const_eval/src/check_consts/ops.rs | 27 +- .../rustc_const_eval/src/check_consts/resolver.rs | 16 +- .../rustc_const_eval/src/interpret/eval_context.rs | 8 +- .../rustc_const_eval/src/interpret/validity.rs | 8 +- compiler/rustc_errors/src/styled_buffer.rs | 11 +- compiler/rustc_hir_analysis/src/collect.rs | 11 +- .../src/hir_ty_lowering/bounds.rs | 20 +- compiler/rustc_hir_analysis/src/hir_wf_check.rs | 17 +- compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs | 8 +- .../rustc_hir_typeck/src/fn_ctxt/suggestions.rs | 48 ++-- 26 files changed, 413 insertions(+), 445 deletions(-) (limited to 'compiler/rustc_const_eval/src') diff --git a/compiler/rustc_ast_lowering/src/index.rs b/compiler/rustc_ast_lowering/src/index.rs index 1ef64f5a352..5b63206d7d6 100644 --- a/compiler/rustc_ast_lowering/src/index.rs +++ b/compiler/rustc_ast_lowering/src/index.rs @@ -164,11 +164,11 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { fn visit_item(&mut self, i: &'hir Item<'hir>) { debug_assert_eq!(i.owner_id, self.owner); self.with_parent(i.hir_id(), |this| { - if let ItemKind::Struct(_, _, struct_def) = &i.kind { + if let ItemKind::Struct(_, _, struct_def) = &i.kind // If this is a tuple or unit-like struct, register the constructor. - if let Some(ctor_hir_id) = struct_def.ctor_hir_id() { - this.insert(i.span, ctor_hir_id, Node::Ctor(struct_def)); - } + && let Some(ctor_hir_id) = struct_def.ctor_hir_id() + { + this.insert(i.span, ctor_hir_id, Node::Ctor(struct_def)); } intravisit::walk_item(this, i); }); diff --git a/compiler/rustc_ast_passes/src/ast_validation.rs b/compiler/rustc_ast_passes/src/ast_validation.rs index a08dae11153..895a457ec1d 100644 --- a/compiler/rustc_ast_passes/src/ast_validation.rs +++ b/compiler/rustc_ast_passes/src/ast_validation.rs @@ -640,16 +640,16 @@ impl<'a> AstValidator<'a> { return; } - if let Some(header) = fk.header() { - if let Const::Yes(const_span) = header.constness { - let mut spans = variadic_spans.clone(); - spans.push(const_span); - self.dcx().emit_err(errors::ConstAndCVariadic { - spans, - const_span, - variadic_spans: variadic_spans.clone(), - }); - } + if let Some(header) = fk.header() + && let Const::Yes(const_span) = header.constness + { + let mut spans = variadic_spans.clone(); + spans.push(const_span); + self.dcx().emit_err(errors::ConstAndCVariadic { + spans, + const_span, + variadic_spans: variadic_spans.clone(), + }); } match (fk.ctxt(), fk.header()) { diff --git a/compiler/rustc_ast_passes/src/feature_gate.rs b/compiler/rustc_ast_passes/src/feature_gate.rs index 8114733f406..662357ce884 100644 --- a/compiler/rustc_ast_passes/src/feature_gate.rs +++ b/compiler/rustc_ast_passes/src/feature_gate.rs @@ -630,16 +630,11 @@ fn check_incompatible_features(sess: &Session, features: &Features) { .iter() .filter(|(f1, f2)| features.enabled(*f1) && features.enabled(*f2)) { - if let Some((f1_name, f1_span)) = enabled_features.clone().find(|(name, _)| name == f1) { - if let Some((f2_name, f2_span)) = enabled_features.clone().find(|(name, _)| name == f2) - { - let spans = vec![f1_span, f2_span]; - sess.dcx().emit_err(errors::IncompatibleFeatures { - spans, - f1: f1_name, - f2: f2_name, - }); - } + if let Some((f1_name, f1_span)) = enabled_features.clone().find(|(name, _)| name == f1) + && let Some((f2_name, f2_span)) = enabled_features.clone().find(|(name, _)| name == f2) + { + let spans = vec![f1_span, f2_span]; + sess.dcx().emit_err(errors::IncompatibleFeatures { spans, f1: f1_name, f2: f2_name }); } } } diff --git a/compiler/rustc_ast_pretty/src/pprust/state.rs b/compiler/rustc_ast_pretty/src/pprust/state.rs index def0cb74d29..f0cf0c1487f 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state.rs @@ -572,10 +572,10 @@ pub trait PrintState<'a>: std::ops::Deref + std::ops::Dere } fn maybe_print_trailing_comment(&mut self, span: rustc_span::Span, next_pos: Option) { - if let Some(cmnts) = self.comments_mut() { - if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) { - self.print_comment(cmnt); - } + if let Some(cmnts) = self.comments_mut() + && let Some(cmnt) = cmnts.trailing_comment(span, next_pos) + { + self.print_comment(cmnt); } } diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index 040a0607db5..17ae671b138 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -2481,13 +2481,13 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { // Check that the parent of the closure is a method call, // with receiver matching with local's type (modulo refs) - if let hir::Node::Expr(parent) = tcx.parent_hir_node(closure_expr.hir_id) { - if let hir::ExprKind::MethodCall(_, recv, ..) = parent.kind { - let recv_ty = typeck_results.expr_ty(recv); + if let hir::Node::Expr(parent) = tcx.parent_hir_node(closure_expr.hir_id) + && let hir::ExprKind::MethodCall(_, recv, ..) = parent.kind + { + let recv_ty = typeck_results.expr_ty(recv); - if recv_ty.peel_refs() != local_ty { - return; - } + if recv_ty.peel_refs() != local_ty { + return; } } @@ -2753,16 +2753,16 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { // With the place of a union and a field access into it, we traverse the second // borrowed place and look for an access to a different field of the same union. for (place_base, elem) in second_borrowed_place.iter_projections().rev() { - if let ProjectionElem::Field(field, _) = elem { - if let Some(union_ty) = union_ty(place_base) { - if field != target_field && place_base == target_base { - return Some(( - self.describe_any_place(place_base), - self.describe_any_place(first_borrowed_place.as_ref()), - self.describe_any_place(second_borrowed_place.as_ref()), - union_ty.to_string(), - )); - } + if let ProjectionElem::Field(field, _) = elem + && let Some(union_ty) = union_ty(place_base) + { + if field != target_field && place_base == target_base { + return Some(( + self.describe_any_place(place_base), + self.describe_any_place(first_borrowed_place.as_ref()), + self.describe_any_place(second_borrowed_place.as_ref()), + union_ty.to_string(), + )); } } } @@ -2949,16 +2949,15 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { from_closure: false, .. } = explanation - { - if let Err(diag) = self.try_report_cannot_return_reference_to_local( + && let Err(diag) = self.try_report_cannot_return_reference_to_local( borrow, borrow_span, span, category, opt_place_desc.as_ref(), - ) { - return diag; - } + ) + { + return diag; } let name = format!("`{name}`"); @@ -3720,30 +3719,30 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { let loan_span = loan_spans.args_or_use(); let descr_place = self.describe_any_place(place.as_ref()); - if let BorrowKind::Fake(_) = loan.kind { - if let Some(section) = self.classify_immutable_section(loan.assigned_place) { - let mut err = self.cannot_mutate_in_immutable_section( - span, - loan_span, - &descr_place, - section, - "assign", - ); + if let BorrowKind::Fake(_) = loan.kind + && let Some(section) = self.classify_immutable_section(loan.assigned_place) + { + let mut err = self.cannot_mutate_in_immutable_section( + span, + loan_span, + &descr_place, + section, + "assign", + ); - loan_spans.var_subdiag(&mut err, Some(loan.kind), |kind, var_span| { - use crate::session_diagnostics::CaptureVarCause::*; - match kind { - hir::ClosureKind::Coroutine(_) => BorrowUseInCoroutine { var_span }, - hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => { - BorrowUseInClosure { var_span } - } + loan_spans.var_subdiag(&mut err, Some(loan.kind), |kind, var_span| { + use crate::session_diagnostics::CaptureVarCause::*; + match kind { + hir::ClosureKind::Coroutine(_) => BorrowUseInCoroutine { var_span }, + hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => { + BorrowUseInClosure { var_span } } - }); + } + }); - self.buffer_error(err); + self.buffer_error(err); - return; - } + return; } let mut err = self.cannot_assign_to_borrowed(span, loan_span, &descr_place); @@ -3996,119 +3995,116 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { "annotate_argument_and_return_for_borrow: target={:?} stmt={:?}", target, stmt ); - if let StatementKind::Assign(box (place, rvalue)) = &stmt.kind { - if let Some(assigned_to) = place.as_local() { - debug!( - "annotate_argument_and_return_for_borrow: assigned_to={:?} \ + if let StatementKind::Assign(box (place, rvalue)) = &stmt.kind + && let Some(assigned_to) = place.as_local() + { + debug!( + "annotate_argument_and_return_for_borrow: assigned_to={:?} \ rvalue={:?}", - assigned_to, rvalue - ); - // Check if our `target` was captured by a closure. - if let Rvalue::Aggregate( - box AggregateKind::Closure(def_id, args), - operands, - ) = rvalue - { - let def_id = def_id.expect_local(); - for operand in operands { - let (Operand::Copy(assigned_from) | Operand::Move(assigned_from)) = - operand - else { - continue; - }; - debug!( - "annotate_argument_and_return_for_borrow: assigned_from={:?}", - assigned_from - ); + assigned_to, rvalue + ); + // Check if our `target` was captured by a closure. + if let Rvalue::Aggregate(box AggregateKind::Closure(def_id, args), operands) = + rvalue + { + let def_id = def_id.expect_local(); + for operand in operands { + let (Operand::Copy(assigned_from) | Operand::Move(assigned_from)) = + operand + else { + continue; + }; + debug!( + "annotate_argument_and_return_for_borrow: assigned_from={:?}", + assigned_from + ); - // Find the local from the operand. - let Some(assigned_from_local) = - assigned_from.local_or_deref_local() - else { - continue; - }; + // Find the local from the operand. + let Some(assigned_from_local) = assigned_from.local_or_deref_local() + else { + continue; + }; - if assigned_from_local != target { - continue; - } + if assigned_from_local != target { + continue; + } - // If a closure captured our `target` and then assigned - // into a place then we should annotate the closure in - // case it ends up being assigned into the return place. - annotated_closure = - self.annotate_fn_sig(def_id, args.as_closure().sig()); - debug!( - "annotate_argument_and_return_for_borrow: \ + // If a closure captured our `target` and then assigned + // into a place then we should annotate the closure in + // case it ends up being assigned into the return place. + annotated_closure = + self.annotate_fn_sig(def_id, args.as_closure().sig()); + debug!( + "annotate_argument_and_return_for_borrow: \ annotated_closure={:?} assigned_from_local={:?} \ assigned_to={:?}", - annotated_closure, assigned_from_local, assigned_to - ); + annotated_closure, assigned_from_local, assigned_to + ); - if assigned_to == mir::RETURN_PLACE { - // If it was assigned directly into the return place, then - // return now. - return annotated_closure; - } else { - // Otherwise, update the target. - target = assigned_to; - } + if assigned_to == mir::RETURN_PLACE { + // If it was assigned directly into the return place, then + // return now. + return annotated_closure; + } else { + // Otherwise, update the target. + target = assigned_to; } - - // If none of our closure's operands matched, then skip to the next - // statement. - continue; } - // Otherwise, look at other types of assignment. - let assigned_from = match rvalue { - Rvalue::Ref(_, _, assigned_from) => assigned_from, - Rvalue::Use(operand) => match operand { - Operand::Copy(assigned_from) | Operand::Move(assigned_from) => { - assigned_from - } - _ => continue, - }, + // If none of our closure's operands matched, then skip to the next + // statement. + continue; + } + + // Otherwise, look at other types of assignment. + let assigned_from = match rvalue { + Rvalue::Ref(_, _, assigned_from) => assigned_from, + Rvalue::Use(operand) => match operand { + Operand::Copy(assigned_from) | Operand::Move(assigned_from) => { + assigned_from + } _ => continue, - }; - debug!( - "annotate_argument_and_return_for_borrow: \ + }, + _ => continue, + }; + debug!( + "annotate_argument_and_return_for_borrow: \ assigned_from={:?}", - assigned_from, - ); + assigned_from, + ); - // Find the local from the rvalue. - let Some(assigned_from_local) = assigned_from.local_or_deref_local() else { - continue; - }; - debug!( - "annotate_argument_and_return_for_borrow: \ + // Find the local from the rvalue. + let Some(assigned_from_local) = assigned_from.local_or_deref_local() else { + continue; + }; + debug!( + "annotate_argument_and_return_for_borrow: \ assigned_from_local={:?}", - assigned_from_local, - ); + assigned_from_local, + ); - // Check if our local matches the target - if so, we've assigned our - // borrow to a new place. - if assigned_from_local != target { - continue; - } + // Check if our local matches the target - if so, we've assigned our + // borrow to a new place. + if assigned_from_local != target { + continue; + } - // If we assigned our `target` into a new place, then we should - // check if it was the return place. - debug!( - "annotate_argument_and_return_for_borrow: \ + // If we assigned our `target` into a new place, then we should + // check if it was the return place. + debug!( + "annotate_argument_and_return_for_borrow: \ assigned_from_local={:?} assigned_to={:?}", - assigned_from_local, assigned_to - ); - if assigned_to == mir::RETURN_PLACE { - // If it was then return the annotated closure if there was one, - // else, annotate this function. - return annotated_closure.or_else(fallback); - } - - // If we didn't assign into the return place, then we just update - // the target. - target = assigned_to; + assigned_from_local, assigned_to + ); + if assigned_to == mir::RETURN_PLACE { + // If it was then return the annotated closure if there was one, + // else, annotate this function. + return annotated_closure.or_else(fallback); } + + // If we didn't assign into the return place, then we just update + // the target. + target = assigned_to; } } @@ -4120,32 +4116,31 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { ); if let TerminatorKind::Call { destination, target: Some(_), args, .. } = &terminator.kind + && let Some(assigned_to) = destination.as_local() { - if let Some(assigned_to) = destination.as_local() { + debug!( + "annotate_argument_and_return_for_borrow: assigned_to={:?} args={:?}", + assigned_to, args + ); + for operand in args { + let (Operand::Copy(assigned_from) | Operand::Move(assigned_from)) = + &operand.node + else { + continue; + }; debug!( - "annotate_argument_and_return_for_borrow: assigned_to={:?} args={:?}", - assigned_to, args + "annotate_argument_and_return_for_borrow: assigned_from={:?}", + assigned_from, ); - for operand in args { - let (Operand::Copy(assigned_from) | Operand::Move(assigned_from)) = - &operand.node - else { - continue; - }; + + if let Some(assigned_from_local) = assigned_from.local_or_deref_local() { debug!( - "annotate_argument_and_return_for_borrow: assigned_from={:?}", - assigned_from, + "annotate_argument_and_return_for_borrow: assigned_from_local={:?}", + assigned_from_local, ); - if let Some(assigned_from_local) = assigned_from.local_or_deref_local() { - debug!( - "annotate_argument_and_return_for_borrow: assigned_from_local={:?}", - assigned_from_local, - ); - - if assigned_to == mir::RETURN_PLACE && assigned_from_local == target { - return annotated_closure.or_else(fallback); - } + if assigned_to == mir::RETURN_PLACE && assigned_from_local == target { + return annotated_closure.or_else(fallback); } } } @@ -4244,10 +4239,10 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { // as the HIR doesn't have full types for closure arguments. let return_ty = sig.output().skip_binder(); let mut return_span = fn_decl.output.span(); - if let hir::FnRetTy::Return(ty) = &fn_decl.output { - if let hir::TyKind::Ref(lifetime, _) = ty.kind { - return_span = lifetime.ident.span; - } + if let hir::FnRetTy::Return(ty) = &fn_decl.output + && let hir::TyKind::Ref(lifetime, _) = ty.kind + { + return_span = lifetime.ident.span; } Some(AnnotatedBorrowFnSignature::NamedFunction { diff --git a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs index f9e52239d6f..a10da08ddf3 100644 --- a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs +++ b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs @@ -917,30 +917,29 @@ impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> { if let TerminatorKind::Call { destination, target: Some(block), args, .. } = &terminator.kind + && let Some(dest) = destination.as_local() { - if let Some(dest) = destination.as_local() { - debug!( - "was_captured_by_trait_object: target={:?} dest={:?} args={:?}", - target, dest, args - ); - // Check if one of the arguments to this function is the target place. - let found_target = args.iter().any(|arg| { - if let Operand::Move(place) = arg.node { - if let Some(potential) = place.as_local() { - potential == target - } else { - false - } + debug!( + "was_captured_by_trait_object: target={:?} dest={:?} args={:?}", + target, dest, args + ); + // Check if one of the arguments to this function is the target place. + let found_target = args.iter().any(|arg| { + if let Operand::Move(place) = arg.node { + if let Some(potential) = place.as_local() { + potential == target } else { false } - }); - - // If it is, follow this to the next block and update the target. - if found_target { - target = dest; - queue.push(block.start_location()); + } else { + false } + }); + + // If it is, follow this to the next block and update the target. + if found_target { + target = dest; + queue.push(block.start_location()); } } } diff --git a/compiler/rustc_borrowck/src/diagnostics/mod.rs b/compiler/rustc_borrowck/src/diagnostics/mod.rs index 9ad91d605a7..ed4cd52ed9c 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mod.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mod.rs @@ -266,48 +266,44 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { args, .. } = &terminator.kind + && let ty::FnDef(id, _) = *const_.ty().kind() { - if let ty::FnDef(id, _) = *const_.ty().kind() { - debug!("add_moved_or_invoked_closure_note: id={:?}", id); - if self.infcx.tcx.is_lang_item(self.infcx.tcx.parent(id), LangItem::FnOnce) { - let closure = match args.first() { - Some(Spanned { - node: Operand::Copy(place) | Operand::Move(place), .. - }) if target == place.local_or_deref_local() => { - place.local_or_deref_local().unwrap() - } - _ => return false, - }; + debug!("add_moved_or_invoked_closure_note: id={:?}", id); + if self.infcx.tcx.is_lang_item(self.infcx.tcx.parent(id), LangItem::FnOnce) { + let closure = match args.first() { + Some(Spanned { node: Operand::Copy(place) | Operand::Move(place), .. }) + if target == place.local_or_deref_local() => + { + place.local_or_deref_local().unwrap() + } + _ => return false, + }; - debug!("add_moved_or_invoked_closure_note: closure={:?}", closure); - if let ty::Closure(did, _) = self.body.local_decls[closure].ty.kind() { - let did = did.expect_local(); - if let Some((span, hir_place)) = self.infcx.tcx.closure_kind_origin(did) { - diag.subdiagnostic(OnClosureNote::InvokedTwice { - place_name: &ty::place_to_string_for_capture( - self.infcx.tcx, - hir_place, - ), - span: *span, - }); - return true; - } + debug!("add_moved_or_invoked_closure_note: closure={:?}", closure); + if let ty::Closure(did, _) = self.body.local_decls[closure].ty.kind() { + let did = did.expect_local(); + if let Some((span, hir_place)) = self.infcx.tcx.closure_kind_origin(did) { + diag.subdiagnostic(OnClosureNote::InvokedTwice { + place_name: &ty::place_to_string_for_capture(self.infcx.tcx, hir_place), + span: *span, + }); + return true; } } } } // Check if we are just moving a closure after it has been invoked. - if let Some(target) = target { - if let ty::Closure(did, _) = self.body.local_decls[target].ty.kind() { - let did = did.expect_local(); - if let Some((span, hir_place)) = self.infcx.tcx.closure_kind_origin(did) { - diag.subdiagnostic(OnClosureNote::MovedTwice { - place_name: &ty::place_to_string_for_capture(self.infcx.tcx, hir_place), - span: *span, - }); - return true; - } + if let Some(target) = target + && let ty::Closure(did, _) = self.body.local_decls[target].ty.kind() + { + let did = did.expect_local(); + if let Some((span, hir_place)) = self.infcx.tcx.closure_kind_origin(did) { + diag.subdiagnostic(OnClosureNote::MovedTwice { + place_name: &ty::place_to_string_for_capture(self.infcx.tcx, hir_place), + span: *span, + }); + return true; } } false diff --git a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs index a5661e44af8..1067f1e40ef 100644 --- a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs @@ -126,36 +126,35 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { .statements .get(location.statement_index) .map(|stmt| &stmt.kind) + && let Some(local) = place.as_local() { - if let Some(local) = place.as_local() { - let local_decl = &self.body.local_decls[local]; - // opt_match_place is the - // match_span is the span of the expression being matched on - // match *x.y { ... } match_place is Some(*x.y) - // ^^^^ match_span is the span of *x.y - // - // opt_match_place is None for let [mut] x = ... statements, - // whether or not the right-hand side is a place expression - if let LocalInfo::User(BindingForm::Var(VarBindingForm { - opt_match_place: Some((opt_match_place, match_span)), - binding_mode: _, - opt_ty_info: _, - pat_span: _, - })) = *local_decl.local_info() - { - let stmt_source_info = self.body.source_info(location); - self.append_binding_error( - grouped_errors, - kind, - original_path, - *move_from, - local, - opt_match_place, - match_span, - stmt_source_info.span, - ); - return; - } + let local_decl = &self.body.local_decls[local]; + // opt_match_place is the + // match_span is the span of the expression being matched on + // match *x.y { ... } match_place is Some(*x.y) + // ^^^^ match_span is the span of *x.y + // + // opt_match_place is None for let [mut] x = ... statements, + // whether or not the right-hand side is a place expression + if let LocalInfo::User(BindingForm::Var(VarBindingForm { + opt_match_place: Some((opt_match_place, match_span)), + binding_mode: _, + opt_ty_info: _, + pat_span: _, + })) = *local_decl.local_info() + { + let stmt_source_info = self.body.source_info(location); + self.append_binding_error( + grouped_errors, + kind, + original_path, + *move_from, + local, + opt_match_place, + match_span, + stmt_source_info.span, + ); + return; } } diff --git a/compiler/rustc_borrowck/src/diagnostics/region_name.rs b/compiler/rustc_borrowck/src/diagnostics/region_name.rs index edd14d155f6..517f9e88cd9 100644 --- a/compiler/rustc_borrowck/src/diagnostics/region_name.rs +++ b/compiler/rustc_borrowck/src/diagnostics/region_name.rs @@ -528,15 +528,15 @@ impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> { // match_adt_and_segment in this case. Res::Def(DefKind::TyAlias, _) => (), _ => { - if let Some(last_segment) = path.segments.last() { - if let Some(highlight) = self.match_adt_and_segment( + if let Some(last_segment) = path.segments.last() + && let Some(highlight) = self.match_adt_and_segment( args, needle_fr, last_segment, search_stack, - ) { - return Some(highlight); - } + ) + { + return Some(highlight); } } } diff --git a/compiler/rustc_borrowck/src/region_infer/mod.rs b/compiler/rustc_borrowck/src/region_infer/mod.rs index 5f1b655c6b6..68f1637e07e 100644 --- a/compiler/rustc_borrowck/src/region_infer/mod.rs +++ b/compiler/rustc_borrowck/src/region_infer/mod.rs @@ -822,10 +822,10 @@ impl<'tcx> RegionInferenceContext<'tcx> { continue; } - if let Some(propagated_outlives_requirements) = &mut propagated_outlives_requirements { - if self.try_promote_type_test(infcx, type_test, propagated_outlives_requirements) { - continue; - } + if let Some(propagated_outlives_requirements) = &mut propagated_outlives_requirements + && self.try_promote_type_test(infcx, type_test, propagated_outlives_requirements) + { + continue; } // Type-test failed. Report the error. @@ -1479,40 +1479,36 @@ impl<'tcx> RegionInferenceContext<'tcx> { shorter_fr: RegionVid, propagated_outlives_requirements: &mut Option<&mut Vec>>, ) -> RegionRelationCheckResult { - if let Some(propagated_outlives_requirements) = propagated_outlives_requirements { + if let Some(propagated_outlives_requirements) = propagated_outlives_requirements // Shrink `longer_fr` until we find a non-local region (if we do). // We'll call it `fr-` -- it's ever so slightly smaller than // `longer_fr`. - if let Some(fr_minus) = self.universal_region_relations.non_local_lower_bound(longer_fr) - { - debug!("try_propagate_universal_region_error: fr_minus={:?}", fr_minus); + && let Some(fr_minus) = self.universal_region_relations.non_local_lower_bound(longer_fr) + { + debug!("try_propagate_universal_region_error: fr_minus={:?}", fr_minus); - let blame_span_category = self.find_outlives_blame_span( - longer_fr, - NllRegionVariableOrigin::FreeRegion, - shorter_fr, - ); + let blame_span_category = self.find_outlives_blame_span( + longer_fr, + NllRegionVariableOrigin::FreeRegion, + shorter_fr, + ); - // Grow `shorter_fr` until we find some non-local regions. (We - // always will.) We'll call them `shorter_fr+` -- they're ever - // so slightly larger than `shorter_fr`. - let shorter_fr_plus = - self.universal_region_relations.non_local_upper_bounds(shorter_fr); - debug!( - "try_propagate_universal_region_error: shorter_fr_plus={:?}", - shorter_fr_plus - ); - for fr in shorter_fr_plus { - // Push the constraint `fr-: shorter_fr+` - propagated_outlives_requirements.push(ClosureOutlivesRequirement { - subject: ClosureOutlivesSubject::Region(fr_minus), - outlived_free_region: fr, - blame_span: blame_span_category.1.span, - category: blame_span_category.0, - }); - } - return RegionRelationCheckResult::Propagated; + // Grow `shorter_fr` until we find some non-local regions. (We + // always will.) We'll call them `shorter_fr+` -- they're ever + // so slightly larger than `shorter_fr`. + let shorter_fr_plus = + self.universal_region_relations.non_local_upper_bounds(shorter_fr); + debug!("try_propagate_universal_region_error: shorter_fr_plus={:?}", shorter_fr_plus); + for fr in shorter_fr_plus { + // Push the constraint `fr-: shorter_fr+` + propagated_outlives_requirements.push(ClosureOutlivesRequirement { + subject: ClosureOutlivesSubject::Region(fr_minus), + outlived_free_region: fr, + blame_span: blame_span_category.1.span, + category: blame_span_category.0, + }); } + return RegionRelationCheckResult::Propagated; } RegionRelationCheckResult::Error @@ -2085,11 +2081,11 @@ impl<'tcx> RegionInferenceContext<'tcx> { let locations = self.scc_values.locations_outlived_by(scc); for location in locations { let bb = &body[location.block]; - if let Some(terminator) = &bb.terminator { + if let Some(terminator) = &bb.terminator // terminator of a loop should be TerminatorKind::FalseUnwind - if let TerminatorKind::FalseUnwind { .. } = terminator.kind { - return Some(location); - } + && let TerminatorKind::FalseUnwind { .. } = terminator.kind + { + return Some(location); } } None diff --git a/compiler/rustc_borrowck/src/type_check/mod.rs b/compiler/rustc_borrowck/src/type_check/mod.rs index d500088c259..f363ef0a5a9 100644 --- a/compiler/rustc_borrowck/src/type_check/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/mod.rs @@ -669,24 +669,24 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { ); } - if let Some(annotation_index) = self.rvalue_user_ty(rv) { - if let Err(terr) = self.relate_type_and_user_type( + if let Some(annotation_index) = self.rvalue_user_ty(rv) + && let Err(terr) = self.relate_type_and_user_type( rv_ty, ty::Invariant, &UserTypeProjection { base: annotation_index, projs: vec![] }, location.to_locations(), ConstraintCategory::TypeAnnotation(AnnotationSource::GenericArg), - ) { - let annotation = &self.user_type_annotations[annotation_index]; - span_mirbug!( - self, - stmt, - "bad user type on rvalue ({:?} = {:?}): {:?}", - annotation, - rv_ty, - terr - ); - } + ) + { + let annotation = &self.user_type_annotations[annotation_index]; + span_mirbug!( + self, + stmt, + "bad user type on rvalue ({:?} = {:?}): {:?}", + annotation, + rv_ty, + terr + ); } if !self.unsized_feature_enabled() { diff --git a/compiler/rustc_codegen_llvm/src/back/lto.rs b/compiler/rustc_codegen_llvm/src/back/lto.rs index 767835c34f0..657513991ac 100644 --- a/compiler/rustc_codegen_llvm/src/back/lto.rs +++ b/compiler/rustc_codegen_llvm/src/back/lto.rs @@ -505,10 +505,10 @@ fn thin_lto( // Save the current ThinLTO import information for the next compilation // session, overwriting the previous serialized data (if any). - if let Some(path) = key_map_path { - if let Err(err) = curr_key_map.save_to_file(&path) { - return Err(write::llvm_err(dcx, LlvmError::WriteThinLtoKey { err })); - } + if let Some(path) = key_map_path + && let Err(err) = curr_key_map.save_to_file(&path) + { + return Err(write::llvm_err(dcx, LlvmError::WriteThinLtoKey { err })); } Ok((opt_jobs, copy_jobs)) diff --git a/compiler/rustc_codegen_llvm/src/builder.rs b/compiler/rustc_codegen_llvm/src/builder.rs index 0ade9edb0d2..f712b3b83fa 100644 --- a/compiler/rustc_codegen_llvm/src/builder.rs +++ b/compiler/rustc_codegen_llvm/src/builder.rs @@ -687,10 +687,10 @@ impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> { bx.nonnull_metadata(load); } - if let Some(pointee) = layout.pointee_info_at(bx, offset) { - if let Some(_) = pointee.safe { - bx.align_metadata(load, pointee.align); - } + if let Some(pointee) = layout.pointee_info_at(bx, offset) + && let Some(_) = pointee.safe + { + bx.align_metadata(load, pointee.align); } } abi::Primitive::Float(_) => {} diff --git a/compiler/rustc_codegen_ssa/src/back/link.rs b/compiler/rustc_codegen_ssa/src/back/link.rs index 5ce301c0eb9..162fbf3d6e2 100644 --- a/compiler/rustc_codegen_ssa/src/back/link.rs +++ b/compiler/rustc_codegen_ssa/src/back/link.rs @@ -3369,12 +3369,12 @@ fn warn_if_linked_with_gold(sess: &Session, path: &Path) -> Result<(), Box, did: LocalDefId) -> CodegenFnAttrs { ) .with_note("Rustc requires this item to have a specific mangled name.") .with_span_label(tcx.def_span(did), "should be the internal language item"); - if let Some(lang_item) = lang_item { - if let Some(link_name) = lang_item.link_name() { - err = err - .with_note("If you are trying to prevent mangling to ease debugging, many") - .with_note(format!( - "debuggers support a command such as `rbreak {link_name}` to" - )) - .with_note(format!( - "match `.*{link_name}.*` instead of `break {link_name}` on a specific name" - )) - } + if let Some(lang_item) = lang_item + && let Some(link_name) = lang_item.link_name() + { + err = err + .with_note("If you are trying to prevent mangling to ease debugging, many") + .with_note(format!("debuggers support a command such as `rbreak {link_name}` to")) + .with_note(format!( + "match `.*{link_name}.*` instead of `break {link_name}` on a specific name" + )) } err.emit(); } diff --git a/compiler/rustc_const_eval/src/check_consts/check.rs b/compiler/rustc_const_eval/src/check_consts/check.rs index 0eb6f28bdb3..69637cadcc9 100644 --- a/compiler/rustc_const_eval/src/check_consts/check.rs +++ b/compiler/rustc_const_eval/src/check_consts/check.rs @@ -714,10 +714,10 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { fn visit_operand(&mut self, op: &Operand<'tcx>, location: Location) { self.super_operand(op, location); - if let Operand::Constant(c) = op { - if let Some(def_id) = c.check_static_ptr(self.tcx) { - self.check_static(def_id, self.span); - } + if let Operand::Constant(c) = op + && let Some(def_id) = c.check_static_ptr(self.tcx) + { + self.check_static(def_id, self.span); } } diff --git a/compiler/rustc_const_eval/src/check_consts/ops.rs b/compiler/rustc_const_eval/src/check_consts/ops.rs index b2e0577cc82..982e640fa92 100644 --- a/compiler/rustc_const_eval/src/check_consts/ops.rs +++ b/compiler/rustc_const_eval/src/check_consts/ops.rs @@ -295,21 +295,18 @@ fn build_error_for_const_call<'tcx>( } let deref = "*".repeat(num_refs); - if let Ok(call_str) = ccx.tcx.sess.source_map().span_to_snippet(span) { - if let Some(eq_idx) = call_str.find("==") { - if let Some(rhs_idx) = - call_str[(eq_idx + 2)..].find(|c: char| !c.is_whitespace()) - { - let rhs_pos = - span.lo() + BytePos::from_usize(eq_idx + 2 + rhs_idx); - let rhs_span = span.with_lo(rhs_pos).with_hi(rhs_pos); - sugg = Some(errors::ConsiderDereferencing { - deref, - span: span.shrink_to_lo(), - rhs_span, - }); - } - } + if let Ok(call_str) = ccx.tcx.sess.source_map().span_to_snippet(span) + && let Some(eq_idx) = call_str.find("==") + && let Some(rhs_idx) = + call_str[(eq_idx + 2)..].find(|c: char| !c.is_whitespace()) + { + let rhs_pos = span.lo() + BytePos::from_usize(eq_idx + 2 + rhs_idx); + let rhs_span = span.with_lo(rhs_pos).with_hi(rhs_pos); + sugg = Some(errors::ConsiderDereferencing { + deref, + span: span.shrink_to_lo(), + rhs_span, + }); } } _ => {} diff --git a/compiler/rustc_const_eval/src/check_consts/resolver.rs b/compiler/rustc_const_eval/src/check_consts/resolver.rs index 9f7fcc509a5..d98e5027e4d 100644 --- a/compiler/rustc_const_eval/src/check_consts/resolver.rs +++ b/compiler/rustc_const_eval/src/check_consts/resolver.rs @@ -137,14 +137,14 @@ where // If a local with no projections is moved from (e.g. `x` in `y = x`), record that // it no longer needs to be dropped. - if let mir::Operand::Move(place) = operand { - if let Some(local) = place.as_local() { - // For backward compatibility with the MaybeMutBorrowedLocals used in an earlier - // implementation we retain qualif if a local had been borrowed before. This might - // not be strictly necessary since the local is no longer initialized. - if !self.state.borrow.contains(local) { - self.state.qualif.remove(local); - } + if let mir::Operand::Move(place) = operand + && let Some(local) = place.as_local() + { + // For backward compatibility with the MaybeMutBorrowedLocals used in an earlier + // implementation we retain qualif if a local had been borrowed before. This might + // not be strictly necessary since the local is no longer initialized. + if !self.state.borrow.contains(local) { + self.state.qualif.remove(local); } } } diff --git a/compiler/rustc_const_eval/src/interpret/eval_context.rs b/compiler/rustc_const_eval/src/interpret/eval_context.rs index 0c888694e49..0a8591ca140 100644 --- a/compiler/rustc_const_eval/src/interpret/eval_context.rs +++ b/compiler/rustc_const_eval/src/interpret/eval_context.rs @@ -442,10 +442,10 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { // # First compute the dynamic alignment // Packed type alignment needs to be capped. - if let ty::Adt(def, _) = layout.ty.kind() { - if let Some(packed) = def.repr().pack { - unsized_align = unsized_align.min(packed); - } + if let ty::Adt(def, _) = layout.ty.kind() + && let Some(packed) = def.repr().pack + { + unsized_align = unsized_align.min(packed); } // Choose max of two known alignments (combined value must diff --git a/compiler/rustc_const_eval/src/interpret/validity.rs b/compiler/rustc_const_eval/src/interpret/validity.rs index 693b3782960..ed48f53c310 100644 --- a/compiler/rustc_const_eval/src/interpret/validity.rs +++ b/compiler/rustc_const_eval/src/interpret/validity.rs @@ -320,10 +320,10 @@ impl<'rt, 'tcx, M: Machine<'tcx>> ValidityVisitor<'rt, 'tcx, M> { // for a coroutine). let var_hir_id = captured_place.get_root_variable(); let node = self.ecx.tcx.hir_node(var_hir_id); - if let hir::Node::Pat(pat) = node { - if let hir::PatKind::Binding(_, _, ident, _) = pat.kind { - name = Some(ident.name); - } + if let hir::Node::Pat(pat) = node + && let hir::PatKind::Binding(_, _, ident, _) = pat.kind + { + name = Some(ident.name); } } } diff --git a/compiler/rustc_errors/src/styled_buffer.rs b/compiler/rustc_errors/src/styled_buffer.rs index 790efd0286e..095502e80aa 100644 --- a/compiler/rustc_errors/src/styled_buffer.rs +++ b/compiler/rustc_errors/src/styled_buffer.rs @@ -153,12 +153,11 @@ impl StyledBuffer { /// 1. That line and column exist in `StyledBuffer` /// 2. `overwrite` is `true` or existing style is `Style::NoStyle` or `Style::Quotation` fn set_style(&mut self, line: usize, col: usize, style: Style, overwrite: bool) { - if let Some(ref mut line) = self.lines.get_mut(line) { - if let Some(StyledChar { style: s, .. }) = line.get_mut(col) { - if overwrite || matches!(s, Style::NoStyle | Style::Quotation) { - *s = style; - } - } + if let Some(ref mut line) = self.lines.get_mut(line) + && let Some(StyledChar { style: s, .. }) = line.get_mut(col) + && (overwrite || matches!(s, Style::NoStyle | Style::Quotation)) + { + *s = style; } } } diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index 0728b24eb14..afe79bed851 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -530,13 +530,12 @@ impl<'tcx> HirTyLowerer<'tcx> for ItemCtxt<'tcx> { .iter() .enumerate() .map(|(i, a)| { - if let hir::TyKind::Infer(()) = a.kind { - if let Some(suggested_ty) = + if let hir::TyKind::Infer(()) = a.kind + && let Some(suggested_ty) = self.lowerer().suggest_trait_fn_ty_for_impl_fn_infer(hir_id, Some(i)) - { - infer_replacements.push((a.span, suggested_ty.to_string())); - return Ty::new_error_with_message(tcx, a.span, suggested_ty.to_string()); - } + { + infer_replacements.push((a.span, suggested_ty.to_string())); + return Ty::new_error_with_message(tcx, a.span, suggested_ty.to_string()); } self.lowerer().lower_ty(a) 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 d7a827c649d..7760642d8fb 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs @@ -617,18 +617,14 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { }); // Provide the resolved type of the associated constant to `type_of(AnonConst)`. - if let Some(const_arg) = constraint.ct() { - if let hir::ConstArgKind::Anon(anon_const) = const_arg.kind { - let ty = alias_term - .map_bound(|alias| tcx.type_of(alias.def_id).instantiate(tcx, alias.args)); - let ty = check_assoc_const_binding_type( - self, - constraint.ident, - ty, - constraint.hir_id, - ); - tcx.feed_anon_const_type(anon_const.def_id, ty::EarlyBinder::bind(ty)); - } + if let Some(const_arg) = constraint.ct() + && let hir::ConstArgKind::Anon(anon_const) = const_arg.kind + { + let ty = alias_term + .map_bound(|alias| tcx.type_of(alias.def_id).instantiate(tcx, alias.args)); + let ty = + check_assoc_const_binding_type(self, constraint.ident, ty, constraint.hir_id); + tcx.feed_anon_const_type(anon_const.def_id, ty::EarlyBinder::bind(ty)); } alias_term diff --git a/compiler/rustc_hir_analysis/src/hir_wf_check.rs b/compiler/rustc_hir_analysis/src/hir_wf_check.rs index bf539dfab42..3fddaee8cef 100644 --- a/compiler/rustc_hir_analysis/src/hir_wf_check.rs +++ b/compiler/rustc_hir_analysis/src/hir_wf_check.rs @@ -103,16 +103,15 @@ pub(super) fn diagnostic_hir_wf_check<'tcx>( // over less-specific types (e.g. `Option>`) if self.depth >= self.cause_depth { self.cause = Some(error.obligation.cause); - if let hir::TyKind::TraitObject(..) = ty.kind { - if let DefKind::AssocTy | DefKind::AssocConst | DefKind::AssocFn = + if let hir::TyKind::TraitObject(..) = ty.kind + && let DefKind::AssocTy | DefKind::AssocConst | DefKind::AssocFn = self.tcx.def_kind(self.def_id) - { - self.cause = Some(ObligationCause::new( - ty.span, - self.def_id, - ObligationCauseCode::DynCompatible(ty.span), - )); - } + { + self.cause = Some(ObligationCause::new( + ty.span, + self.def_id, + ObligationCauseCode::DynCompatible(ty.span), + )); } self.cause_depth = self.depth } diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs index eb8d671c939..719989d5793 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs @@ -2136,10 +2136,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) }; - if let hir::ExprKind::If(_, _, Some(el)) = expr.kind { - if let Some(rslt) = check_in_progress(el) { - return rslt; - } + if let hir::ExprKind::If(_, _, Some(el)) = expr.kind + && let Some(rslt) = check_in_progress(el) + { + return rslt; } if let hir::ExprKind::Match(_, arms, _) = expr.kind { diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs index d18f4e03d2f..ede02fbf9bd 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs @@ -615,31 +615,31 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expected: Ty<'tcx>, found: Ty<'tcx>, ) -> bool { - if let (ty::FnPtr(..), ty::Closure(def_id, _)) = (expected.kind(), found.kind()) { - if let Some(upvars) = self.tcx.upvars_mentioned(*def_id) { - // Report upto four upvars being captured to reduce the amount error messages - // reported back to the user. - let spans_and_labels = upvars - .iter() - .take(4) - .map(|(var_hir_id, upvar)| { - let var_name = self.tcx.hir_name(*var_hir_id).to_string(); - let msg = format!("`{var_name}` captured here"); - (upvar.span, msg) - }) - .collect::>(); - - let mut multi_span: MultiSpan = - spans_and_labels.iter().map(|(sp, _)| *sp).collect::>().into(); - for (sp, label) in spans_and_labels { - multi_span.push_span_label(sp, label); - } - err.span_note( - multi_span, - "closures can only be coerced to `fn` types if they do not capture any variables" - ); - return true; + if let (ty::FnPtr(..), ty::Closure(def_id, _)) = (expected.kind(), found.kind()) + && let Some(upvars) = self.tcx.upvars_mentioned(*def_id) + { + // Report upto four upvars being captured to reduce the amount error messages + // reported back to the user. + let spans_and_labels = upvars + .iter() + .take(4) + .map(|(var_hir_id, upvar)| { + let var_name = self.tcx.hir_name(*var_hir_id).to_string(); + let msg = format!("`{var_name}` captured here"); + (upvar.span, msg) + }) + .collect::>(); + + let mut multi_span: MultiSpan = + spans_and_labels.iter().map(|(sp, _)| *sp).collect::>().into(); + for (sp, label) in spans_and_labels { + multi_span.push_span_label(sp, label); } + err.span_note( + multi_span, + "closures can only be coerced to `fn` types if they do not capture any variables", + ); + return true; } false } -- cgit 1.4.1-3-g733a5 From 172af038a733020ec487d57a593ddb27ce16c325 Mon Sep 17 00:00:00 2001 From: Cameron Steffen Date: Thu, 24 Jul 2025 19:05:31 -0500 Subject: Rename trait_of_item -> trait_of_assoc --- compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs | 2 +- compiler/rustc_borrowck/src/diagnostics/mod.rs | 2 +- compiler/rustc_const_eval/src/check_consts/check.rs | 2 +- compiler/rustc_const_eval/src/check_consts/qualifs.rs | 2 +- compiler/rustc_const_eval/src/interpret/call.rs | 2 +- .../rustc_hir_analysis/src/errors/wrong_number_of_generic_args.rs | 2 +- compiler/rustc_hir_typeck/src/fallback.rs | 2 +- compiler/rustc_lint/src/noop_method_call.rs | 2 +- compiler/rustc_middle/src/ty/mod.rs | 4 ++-- compiler/rustc_mir_transform/src/check_call_recursion.rs | 2 +- compiler/rustc_mir_transform/src/shim.rs | 2 +- compiler/rustc_monomorphize/src/partitioning.rs | 2 +- compiler/rustc_passes/src/dead.rs | 2 +- .../rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs | 6 +++--- .../src/error_reporting/infer/need_type_info.rs | 2 +- .../rustc_trait_selection/src/error_reporting/traits/ambiguity.rs | 2 +- .../src/error_reporting/traits/suggestions.rs | 2 +- compiler/rustc_trait_selection/src/traits/mod.rs | 2 +- compiler/rustc_trait_selection/src/traits/project.rs | 2 +- compiler/rustc_ty_utils/src/instance.rs | 2 +- src/tools/clippy/clippy_lints/src/dereference.rs | 2 +- src/tools/clippy/clippy_lints/src/loops/needless_range_loop.rs | 2 +- src/tools/clippy/clippy_lints/src/methods/clone_on_copy.rs | 2 +- .../clippy/clippy_lints/src/methods/iter_overeager_cloned.rs | 4 ++-- src/tools/clippy/clippy_lints/src/methods/manual_str_repeat.rs | 2 +- src/tools/clippy/clippy_lints/src/methods/map_clone.rs | 2 +- src/tools/clippy/clippy_lints/src/methods/open_options.rs | 2 +- src/tools/clippy/clippy_lints/src/methods/str_splitn.rs | 6 +++--- .../clippy_lints/src/methods/unnecessary_fallible_conversions.rs | 2 +- src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs | 2 +- src/tools/clippy/clippy_lints/src/methods/useless_asref.rs | 2 +- src/tools/clippy/clippy_lints/src/operators/cmp_owned.rs | 2 +- src/tools/clippy/clippy_lints/src/ranges.rs | 2 +- src/tools/clippy/clippy_lints/src/unconditional_recursion.rs | 8 ++++---- src/tools/clippy/clippy_lints/src/unused_io_amount.rs | 2 +- src/tools/clippy/clippy_utils/src/lib.rs | 4 ++-- src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs | 2 +- 37 files changed, 47 insertions(+), 47 deletions(-) (limited to 'compiler/rustc_const_eval/src') diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index bfe806e8901..be8b3f0bc1e 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -2384,7 +2384,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { if let Some(body_expr) = finder.body_expr && let Some(loop_span) = finder.loop_span && let Some(def_id) = typeck_results.type_dependent_def_id(body_expr.hir_id) - && let Some(trait_did) = tcx.trait_of_item(def_id) + && let Some(trait_did) = tcx.trait_of_assoc(def_id) && tcx.is_diagnostic_item(sym::Iterator, trait_did) { if let Some(loop_bind) = finder.loop_bind { diff --git a/compiler/rustc_borrowck/src/diagnostics/mod.rs b/compiler/rustc_borrowck/src/diagnostics/mod.rs index ed4cd52ed9c..56fdaf1c724 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mod.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mod.rs @@ -938,7 +938,7 @@ impl<'tcx> BorrowedContentSource<'tcx> { fn from_call(func: Ty<'tcx>, tcx: TyCtxt<'tcx>) -> Option { match *func.kind() { ty::FnDef(def_id, args) => { - let trait_id = tcx.trait_of_item(def_id)?; + let trait_id = tcx.trait_of_assoc(def_id)?; if tcx.is_lang_item(trait_id, LangItem::Deref) || tcx.is_lang_item(trait_id, LangItem::DerefMut) diff --git a/compiler/rustc_const_eval/src/check_consts/check.rs b/compiler/rustc_const_eval/src/check_consts/check.rs index 69637cadcc9..44e5d1d5ee7 100644 --- a/compiler/rustc_const_eval/src/check_consts/check.rs +++ b/compiler/rustc_const_eval/src/check_consts/check.rs @@ -784,7 +784,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { self.revalidate_conditional_constness(callee, fn_args, *fn_span); // Attempting to call a trait method? - if let Some(trait_did) = tcx.trait_of_item(callee) { + if let Some(trait_did) = tcx.trait_of_assoc(callee) { // We can't determine the actual callee here, so we have to do different checks // than usual. diff --git a/compiler/rustc_const_eval/src/check_consts/qualifs.rs b/compiler/rustc_const_eval/src/check_consts/qualifs.rs index 166491b47a1..faf41f1658b 100644 --- a/compiler/rustc_const_eval/src/check_consts/qualifs.rs +++ b/compiler/rustc_const_eval/src/check_consts/qualifs.rs @@ -369,7 +369,7 @@ where assert!(promoted.is_none() || Q::ALLOW_PROMOTED); // Don't peek inside trait associated constants. - if promoted.is_none() && cx.tcx.trait_of_item(def).is_none() { + if promoted.is_none() && cx.tcx.trait_of_assoc(def).is_none() { let qualifs = cx.tcx.at(constant.span).mir_const_qualif(def); if !Q::in_qualifs(&qualifs) { diff --git a/compiler/rustc_const_eval/src/interpret/call.rs b/compiler/rustc_const_eval/src/interpret/call.rs index bda00ea2fb8..5b3adba0265 100644 --- a/compiler/rustc_const_eval/src/interpret/call.rs +++ b/compiler/rustc_const_eval/src/interpret/call.rs @@ -725,7 +725,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { ) { let tcx = *self.tcx; - let trait_def_id = tcx.trait_of_item(def_id).unwrap(); + let trait_def_id = tcx.trait_of_assoc(def_id).unwrap(); let virtual_trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, virtual_instance.args); let existential_trait_ref = ty::ExistentialTraitRef::erase_self_ty(tcx, virtual_trait_ref); let concrete_trait_ref = existential_trait_ref.with_self_ty(tcx, dyn_ty); diff --git a/compiler/rustc_hir_analysis/src/errors/wrong_number_of_generic_args.rs b/compiler/rustc_hir_analysis/src/errors/wrong_number_of_generic_args.rs index 2d60c9561a9..835f8e8cdae 100644 --- a/compiler/rustc_hir_analysis/src/errors/wrong_number_of_generic_args.rs +++ b/compiler/rustc_hir_analysis/src/errors/wrong_number_of_generic_args.rs @@ -759,7 +759,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> { &self, err: &mut Diag<'_, impl EmissionGuarantee>, ) { - let trait_ = match self.tcx.trait_of_item(self.def_id) { + let trait_ = match self.tcx.trait_of_assoc(self.def_id) { Some(def_id) => def_id, None => return, }; diff --git a/compiler/rustc_hir_typeck/src/fallback.rs b/compiler/rustc_hir_typeck/src/fallback.rs index 759b5d9550c..9406697dfed 100644 --- a/compiler/rustc_hir_typeck/src/fallback.rs +++ b/compiler/rustc_hir_typeck/src/fallback.rs @@ -694,7 +694,7 @@ impl<'tcx> Visitor<'tcx> for AnnotateUnitFallbackVisitor<'_, 'tcx> { // i.e. changing `Default::default()` to `<() as Default>::default()`. if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind && let Res::Def(DefKind::AssocFn, def_id) = path.res - && self.fcx.tcx.trait_of_item(def_id).is_some() + && self.fcx.tcx.trait_of_assoc(def_id).is_some() && let Some(args) = self.fcx.typeck_results.borrow().node_args_opt(expr.hir_id) && let self_ty = args.type_at(0) && let Some(vid) = self.fcx.root_vid(self_ty) diff --git a/compiler/rustc_lint/src/noop_method_call.rs b/compiler/rustc_lint/src/noop_method_call.rs index b7835e6c36a..24682c4562a 100644 --- a/compiler/rustc_lint/src/noop_method_call.rs +++ b/compiler/rustc_lint/src/noop_method_call.rs @@ -84,7 +84,7 @@ impl<'tcx> LateLintPass<'tcx> for NoopMethodCall { return; }; - let Some(trait_id) = cx.tcx.trait_of_item(did) else { return }; + let Some(trait_id) = cx.tcx.trait_of_assoc(did) else { return }; let Some(trait_) = cx.tcx.get_diagnostic_name(trait_id) else { return }; diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 55606557770..2e4bad290d7 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -1996,7 +1996,7 @@ impl<'tcx> TyCtxt<'tcx> { /// If the given `DefId` describes an item belonging to a trait, /// returns the `DefId` of the trait that the trait item belongs to; /// otherwise, returns `None`. - pub fn trait_of_item(self, def_id: DefId) -> Option { + pub fn trait_of_assoc(self, def_id: DefId) -> Option { self.assoc_parent(def_id).filter(|id| self.def_kind(id) == DefKind::Trait) } @@ -2174,7 +2174,7 @@ impl<'tcx> TyCtxt<'tcx> { #[inline] pub fn is_const_default_method(self, def_id: DefId) -> bool { - matches!(self.trait_of_item(def_id), Some(trait_id) if self.is_const_trait(trait_id)) + matches!(self.trait_of_assoc(def_id), Some(trait_id) if self.is_const_trait(trait_id)) } pub fn impl_method_has_trait_impl_trait_tys(self, def_id: DefId) -> bool { diff --git a/compiler/rustc_mir_transform/src/check_call_recursion.rs b/compiler/rustc_mir_transform/src/check_call_recursion.rs index cace4cd6bba..dccfcc52b46 100644 --- a/compiler/rustc_mir_transform/src/check_call_recursion.rs +++ b/compiler/rustc_mir_transform/src/check_call_recursion.rs @@ -21,7 +21,7 @@ impl<'tcx> MirLint<'tcx> for CheckCallRecursion { if let DefKind::Fn | DefKind::AssocFn = tcx.def_kind(def_id) { // If this is trait/impl method, extract the trait's args. - let trait_args = match tcx.trait_of_item(def_id.to_def_id()) { + let trait_args = match tcx.trait_of_assoc(def_id.to_def_id()) { Some(trait_def_id) => { let trait_args_count = tcx.generics_of(trait_def_id).count(); &GenericArgs::identity_for_item(tcx, def_id)[..trait_args_count] diff --git a/compiler/rustc_mir_transform/src/shim.rs b/compiler/rustc_mir_transform/src/shim.rs index 6c65b072bec..c687036f544 100644 --- a/compiler/rustc_mir_transform/src/shim.rs +++ b/compiler/rustc_mir_transform/src/shim.rs @@ -75,7 +75,7 @@ fn make_shim<'tcx>(tcx: TyCtxt<'tcx>, instance: ty::InstanceKind<'tcx>) -> Body< build_call_shim(tcx, instance, Some(adjustment), CallKind::Direct(def_id)) } ty::InstanceKind::FnPtrShim(def_id, ty) => { - let trait_ = tcx.trait_of_item(def_id).unwrap(); + let trait_ = tcx.trait_of_assoc(def_id).unwrap(); // Supports `Fn` or `async Fn` traits. let adjustment = match tcx .fn_trait_kind_from_def_id(trait_) diff --git a/compiler/rustc_monomorphize/src/partitioning.rs b/compiler/rustc_monomorphize/src/partitioning.rs index f3e7d582781..9f5807070a7 100644 --- a/compiler/rustc_monomorphize/src/partitioning.rs +++ b/compiler/rustc_monomorphize/src/partitioning.rs @@ -650,7 +650,7 @@ fn characteristic_def_id_of_mono_item<'tcx>( // its self-type. If the self-type does not provide a characteristic // DefId, we use the location of the impl after all. - if tcx.trait_of_item(def_id).is_some() { + if tcx.trait_of_assoc(def_id).is_some() { let self_ty = instance.args.type_at(0); // This is a default implementation of a trait method. return characteristic_def_id_of_type(self_ty).or(Some(def_id)); diff --git a/compiler/rustc_passes/src/dead.rs b/compiler/rustc_passes/src/dead.rs index d987041fe0e..ae379d53ad1 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -429,7 +429,7 @@ impl<'tcx> MarkSymbolVisitor<'tcx> { Node::TraitItem(trait_item) => { // mark the trait live let trait_item_id = trait_item.owner_id.to_def_id(); - if let Some(trait_id) = self.tcx.trait_of_item(trait_item_id) { + if let Some(trait_id) = self.tcx.trait_of_assoc(trait_item_id) { self.check_def_id(trait_id); } intravisit::walk_trait_item(self, trait_item); 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 c69991f3fb2..6d42d954b2b 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 @@ -339,7 +339,7 @@ pub(crate) fn transform_instance<'tcx>( } else if let ty::InstanceKind::Virtual(def_id, _) = instance.def { // Transform self into a trait object of the trait that defines the method for virtual // functions to match the type erasure done below. - let upcast_ty = match tcx.trait_of_item(def_id) { + let upcast_ty = match tcx.trait_of_assoc(def_id) { Some(trait_id) => trait_object_ty( tcx, ty::Binder::dummy(ty::TraitRef::from_method(tcx, trait_id, instance.args)), @@ -364,7 +364,7 @@ pub(crate) fn transform_instance<'tcx>( }; instance.args = tcx.mk_args_trait(self_ty, instance.args.into_iter().skip(1)); } else if let ty::InstanceKind::VTableShim(def_id) = instance.def - && let Some(trait_id) = tcx.trait_of_item(def_id) + && let Some(trait_id) = tcx.trait_of_assoc(def_id) { // Adjust the type ids of VTableShims to the type id expected in the call sites for the // entry in the vtable (i.e., by using the signature of the closure passed as an argument @@ -480,7 +480,7 @@ fn implemented_method<'tcx>( // Provided method in a `trait` block trait_method = trait_method_bound; method_id = instance.def_id(); - trait_id = tcx.trait_of_item(method_id)?; + trait_id = tcx.trait_of_assoc(method_id)?; trait_ref = ty::EarlyBinder::bind(TraitRef::from_method(tcx, trait_id, instance.args)); trait_id } else { diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs index 1db05ced8d2..022d549a9df 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs @@ -1303,7 +1303,7 @@ impl<'a, 'tcx> Visitor<'tcx> for FindInferSourceVisitor<'a, 'tcx> { && let Some(args) = self.node_args_opt(expr.hir_id) && args.iter().any(|arg| self.generic_arg_contains_target(arg)) && let Some(def_id) = self.typeck_results.type_dependent_def_id(expr.hir_id) - && self.tecx.tcx.trait_of_item(def_id).is_some() + && self.tecx.tcx.trait_of_assoc(def_id).is_some() && !has_impl_trait(def_id) // FIXME(fn_delegation): In delegation item argument spans are equal to last path // segment. This leads to ICE's when emitting `multipart_suggestion`. 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 98f67257fd1..cdf1402252a 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/ambiguity.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/ambiguity.rs @@ -360,7 +360,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { }, ] = path.segments && data.trait_ref.def_id == *trait_id - && self.tcx.trait_of_item(*item_id) == Some(*trait_id) + && self.tcx.trait_of_assoc(*item_id) == Some(*trait_id) && let None = self.tainted_by_errors() { let assoc_item = self.tcx.associated_item(item_id); 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 c5248736366..c182fd99b17 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs @@ -987,7 +987,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { else { return false; }; - if self.tcx.trait_of_item(did) != Some(clone_trait) { + if self.tcx.trait_of_assoc(did) != Some(clone_trait) { return false; } Some(ident.span) diff --git a/compiler/rustc_trait_selection/src/traits/mod.rs b/compiler/rustc_trait_selection/src/traits/mod.rs index 91c41544f78..9b5e59ce0fd 100644 --- a/compiler/rustc_trait_selection/src/traits/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/mod.rs @@ -759,7 +759,7 @@ fn instantiate_and_check_impossible_predicates<'tcx>( // Specifically check trait fulfillment to avoid an error when trying to resolve // associated items. - if let Some(trait_def_id) = tcx.trait_of_item(key.0) { + if let Some(trait_def_id) = tcx.trait_of_assoc(key.0) { let trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, key.1); predicates.push(trait_ref.upcast(tcx)); } diff --git a/compiler/rustc_trait_selection/src/traits/project.rs b/compiler/rustc_trait_selection/src/traits/project.rs index 28b5b7cf391..581191b2036 100644 --- a/compiler/rustc_trait_selection/src/traits/project.rs +++ b/compiler/rustc_trait_selection/src/traits/project.rs @@ -1507,7 +1507,7 @@ fn confirm_builtin_candidate<'cx, 'tcx>( let tcx = selcx.tcx(); let self_ty = obligation.predicate.self_ty(); let item_def_id = obligation.predicate.def_id; - let trait_def_id = tcx.trait_of_item(item_def_id).unwrap(); + let trait_def_id = tcx.trait_of_assoc(item_def_id).unwrap(); let args = tcx.mk_args(&[self_ty.into()]); let (term, obligations) = if tcx.is_lang_item(trait_def_id, LangItem::DiscriminantKind) { let discriminant_def_id = diff --git a/compiler/rustc_ty_utils/src/instance.rs b/compiler/rustc_ty_utils/src/instance.rs index 166e8f19342..e6c3568620b 100644 --- a/compiler/rustc_ty_utils/src/instance.rs +++ b/compiler/rustc_ty_utils/src/instance.rs @@ -21,7 +21,7 @@ fn resolve_instance_raw<'tcx>( ) -> Result>, ErrorGuaranteed> { let PseudoCanonicalInput { typing_env, value: (def_id, args) } = key; - let result = if let Some(trait_def_id) = tcx.trait_of_item(def_id) { + let result = if let Some(trait_def_id) = tcx.trait_of_assoc(def_id) { debug!(" => associated item, attempting to find impl in typing_env {:#?}", typing_env); resolve_associated_item( tcx, diff --git a/src/tools/clippy/clippy_lints/src/dereference.rs b/src/tools/clippy/clippy_lints/src/dereference.rs index 5099df3fa02..995a1209595 100644 --- a/src/tools/clippy/clippy_lints/src/dereference.rs +++ b/src/tools/clippy/clippy_lints/src/dereference.rs @@ -364,7 +364,7 @@ impl<'tcx> LateLintPass<'tcx> for Dereferencing<'tcx> { // * `&self` methods on `&T` can have auto-borrow, but `&self` methods on `T` will take // priority. if let Some(fn_id) = typeck.type_dependent_def_id(hir_id) - && let Some(trait_id) = cx.tcx.trait_of_item(fn_id) + && let Some(trait_id) = cx.tcx.trait_of_assoc(fn_id) && let arg_ty = cx.tcx.erase_regions(adjusted_ty) && let ty::Ref(_, sub_ty, _) = *arg_ty.kind() && let args = diff --git a/src/tools/clippy/clippy_lints/src/loops/needless_range_loop.rs b/src/tools/clippy/clippy_lints/src/loops/needless_range_loop.rs index 972b0b110e0..7bb684d65bb 100644 --- a/src/tools/clippy/clippy_lints/src/loops/needless_range_loop.rs +++ b/src/tools/clippy/clippy_lints/src/loops/needless_range_loop.rs @@ -317,7 +317,7 @@ impl<'tcx> Visitor<'tcx> for VarVisitor<'_, 'tcx> { .cx .typeck_results() .type_dependent_def_id(expr.hir_id) - .and_then(|def_id| self.cx.tcx.trait_of_item(def_id)) + .and_then(|def_id| self.cx.tcx.trait_of_assoc(def_id)) && ((meth.ident.name == sym::index && self.cx.tcx.lang_items().index_trait() == Some(trait_id)) || (meth.ident.name == sym::index_mut && self.cx.tcx.lang_items().index_mut_trait() == Some(trait_id))) && !self.check(args_1, args_0, expr) diff --git a/src/tools/clippy/clippy_lints/src/methods/clone_on_copy.rs b/src/tools/clippy/clippy_lints/src/methods/clone_on_copy.rs index 2ecf3eb8979..0a456d1057a 100644 --- a/src/tools/clippy/clippy_lints/src/methods/clone_on_copy.rs +++ b/src/tools/clippy/clippy_lints/src/methods/clone_on_copy.rs @@ -28,7 +28,7 @@ pub(super) fn check( if cx .typeck_results() .type_dependent_def_id(expr.hir_id) - .and_then(|id| cx.tcx.trait_of_item(id)) + .and_then(|id| cx.tcx.trait_of_assoc(id)) .zip(cx.tcx.lang_items().clone_trait()) .is_none_or(|(x, y)| x != y) { diff --git a/src/tools/clippy/clippy_lints/src/methods/iter_overeager_cloned.rs b/src/tools/clippy/clippy_lints/src/methods/iter_overeager_cloned.rs index f5fe4316eb0..f851ebe91f3 100644 --- a/src/tools/clippy/clippy_lints/src/methods/iter_overeager_cloned.rs +++ b/src/tools/clippy/clippy_lints/src/methods/iter_overeager_cloned.rs @@ -44,9 +44,9 @@ pub(super) fn check<'tcx>( let typeck = cx.typeck_results(); if let Some(iter_id) = cx.tcx.get_diagnostic_item(sym::Iterator) && let Some(method_id) = typeck.type_dependent_def_id(expr.hir_id) - && cx.tcx.trait_of_item(method_id) == Some(iter_id) + && cx.tcx.trait_of_assoc(method_id) == Some(iter_id) && let Some(method_id) = typeck.type_dependent_def_id(cloned_call.hir_id) - && cx.tcx.trait_of_item(method_id) == Some(iter_id) + && cx.tcx.trait_of_assoc(method_id) == Some(iter_id) && let cloned_recv_ty = typeck.expr_ty_adjusted(cloned_recv) && let Some(iter_assoc_ty) = cx.get_associated_type(cloned_recv_ty, iter_id, sym::Item) && matches!(*iter_assoc_ty.kind(), ty::Ref(_, ty, _) if !is_copy(cx, ty)) diff --git a/src/tools/clippy/clippy_lints/src/methods/manual_str_repeat.rs b/src/tools/clippy/clippy_lints/src/methods/manual_str_repeat.rs index 8167e4f9605..a811dd1cee1 100644 --- a/src/tools/clippy/clippy_lints/src/methods/manual_str_repeat.rs +++ b/src/tools/clippy/clippy_lints/src/methods/manual_str_repeat.rs @@ -59,7 +59,7 @@ pub(super) fn check( && is_type_lang_item(cx, cx.typeck_results().expr_ty(collect_expr), LangItem::String) && let Some(take_id) = cx.typeck_results().type_dependent_def_id(take_expr.hir_id) && let Some(iter_trait_id) = cx.tcx.get_diagnostic_item(sym::Iterator) - && cx.tcx.trait_of_item(take_id) == Some(iter_trait_id) + && cx.tcx.trait_of_assoc(take_id) == Some(iter_trait_id) && let Some(repeat_kind) = parse_repeat_arg(cx, repeat_arg) && let ctxt = collect_expr.span.ctxt() && ctxt == take_expr.span.ctxt() diff --git a/src/tools/clippy/clippy_lints/src/methods/map_clone.rs b/src/tools/clippy/clippy_lints/src/methods/map_clone.rs index 333a33f7527..d016ace28bd 100644 --- a/src/tools/clippy/clippy_lints/src/methods/map_clone.rs +++ b/src/tools/clippy/clippy_lints/src/methods/map_clone.rs @@ -69,7 +69,7 @@ pub(super) fn check(cx: &LateContext<'_>, e: &hir::Expr<'_>, recv: &hir::Expr<'_ hir::ExprKind::MethodCall(method, obj, [], _) => { if ident_eq(name, obj) && method.ident.name == sym::clone && let Some(fn_id) = cx.typeck_results().type_dependent_def_id(closure_expr.hir_id) - && let Some(trait_id) = cx.tcx.trait_of_item(fn_id) + && let Some(trait_id) = cx.tcx.trait_of_assoc(fn_id) && cx.tcx.lang_items().clone_trait() == Some(trait_id) // no autoderefs && !cx.typeck_results().expr_adjustments(obj).iter() diff --git a/src/tools/clippy/clippy_lints/src/methods/open_options.rs b/src/tools/clippy/clippy_lints/src/methods/open_options.rs index 9b5f138295c..87e6cf02102 100644 --- a/src/tools/clippy/clippy_lints/src/methods/open_options.rs +++ b/src/tools/clippy/clippy_lints/src/methods/open_options.rs @@ -111,7 +111,7 @@ fn get_open_options( // This might be a user defined extension trait with a method like `truncate_write` // which would be a false positive if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(argument.hir_id) - && cx.tcx.trait_of_item(method_def_id).is_some() + && cx.tcx.trait_of_assoc(method_def_id).is_some() { return false; } diff --git a/src/tools/clippy/clippy_lints/src/methods/str_splitn.rs b/src/tools/clippy/clippy_lints/src/methods/str_splitn.rs index 6f78d6c6128..51dd4ac313a 100644 --- a/src/tools/clippy/clippy_lints/src/methods/str_splitn.rs +++ b/src/tools/clippy/clippy_lints/src/methods/str_splitn.rs @@ -286,7 +286,7 @@ fn parse_iter_usage<'tcx>( let iter_id = cx.tcx.get_diagnostic_item(sym::Iterator)?; match (name.ident.name, args) { - (sym::next, []) if cx.tcx.trait_of_item(did) == Some(iter_id) => (IterUsageKind::Nth(0), e.span), + (sym::next, []) if cx.tcx.trait_of_assoc(did) == Some(iter_id) => (IterUsageKind::Nth(0), e.span), (sym::next_tuple, []) => { return if paths::ITERTOOLS_NEXT_TUPLE.matches(cx, did) && let ty::Adt(adt_def, subs) = cx.typeck_results().expr_ty(e).kind() @@ -303,7 +303,7 @@ fn parse_iter_usage<'tcx>( None }; }, - (sym::nth | sym::skip, [idx_expr]) if cx.tcx.trait_of_item(did) == Some(iter_id) => { + (sym::nth | sym::skip, [idx_expr]) if cx.tcx.trait_of_assoc(did) == Some(iter_id) => { if let Some(Constant::Int(idx)) = ConstEvalCtxt::new(cx).eval(idx_expr) { let span = if name.ident.as_str() == "nth" { e.span @@ -312,7 +312,7 @@ fn parse_iter_usage<'tcx>( && next_name.ident.name == sym::next && next_expr.span.ctxt() == ctxt && let Some(next_id) = cx.typeck_results().type_dependent_def_id(next_expr.hir_id) - && cx.tcx.trait_of_item(next_id) == Some(iter_id) + && cx.tcx.trait_of_assoc(next_id) == Some(iter_id) { next_expr.span } else { diff --git a/src/tools/clippy/clippy_lints/src/methods/unnecessary_fallible_conversions.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_fallible_conversions.rs index ce81282ddfe..0ec2d8b4fc3 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_fallible_conversions.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unnecessary_fallible_conversions.rs @@ -165,7 +165,7 @@ pub(super) fn check_method(cx: &LateContext<'_>, expr: &Expr<'_>) { pub(super) fn check_function(cx: &LateContext<'_>, expr: &Expr<'_>, callee: &Expr<'_>) { if let ExprKind::Path(ref qpath) = callee.kind && let Some(item_def_id) = cx.qpath_res(qpath, callee.hir_id).opt_def_id() - && let Some(trait_def_id) = cx.tcx.trait_of_item(item_def_id) + && let Some(trait_def_id) = cx.tcx.trait_of_assoc(item_def_id) { let qpath_spans = match qpath { QPath::Resolved(_, path) => { 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 769526d131b..a8642880821 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 @@ -734,7 +734,7 @@ fn check_if_applicable_to_argument<'tcx>(cx: &LateContext<'tcx>, arg: &Expr<'tcx fn check_borrow_predicate<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'tcx>) { if let ExprKind::MethodCall(_, caller, &[arg], _) = expr.kind && let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) - && cx.tcx.trait_of_item(method_def_id).is_none() + && cx.tcx.trait_of_assoc(method_def_id).is_none() && let Some(borrow_id) = cx.tcx.get_diagnostic_item(sym::Borrow) && cx.tcx.predicates_of(method_def_id).predicates.iter().any(|(pred, _)| { if let ClauseKind::Trait(trait_pred) = pred.kind().skip_binder() diff --git a/src/tools/clippy/clippy_lints/src/methods/useless_asref.rs b/src/tools/clippy/clippy_lints/src/methods/useless_asref.rs index d30c12e0c48..d9cf8273fad 100644 --- a/src/tools/clippy/clippy_lints/src/methods/useless_asref.rs +++ b/src/tools/clippy/clippy_lints/src/methods/useless_asref.rs @@ -131,7 +131,7 @@ fn is_calling_clone(cx: &LateContext<'_>, arg: &hir::Expr<'_>) -> bool { hir::ExprKind::MethodCall(method, obj, [], _) => { if method.ident.name == sym::clone && let Some(fn_id) = cx.typeck_results().type_dependent_def_id(closure_expr.hir_id) - && let Some(trait_id) = cx.tcx.trait_of_item(fn_id) + && let Some(trait_id) = cx.tcx.trait_of_assoc(fn_id) // We check it's the `Clone` trait. && cx.tcx.lang_items().clone_trait().is_some_and(|id| id == trait_id) // no autoderefs diff --git a/src/tools/clippy/clippy_lints/src/operators/cmp_owned.rs b/src/tools/clippy/clippy_lints/src/operators/cmp_owned.rs index 9b2cfd91b85..22ec4fe60fb 100644 --- a/src/tools/clippy/clippy_lints/src/operators/cmp_owned.rs +++ b/src/tools/clippy/clippy_lints/src/operators/cmp_owned.rs @@ -41,7 +41,7 @@ fn check_op(cx: &LateContext<'_>, expr: &Expr<'_>, other: &Expr<'_>, left: bool) ExprKind::MethodCall(_, arg, [], _) if typeck .type_dependent_def_id(expr.hir_id) - .and_then(|id| cx.tcx.trait_of_item(id)) + .and_then(|id| cx.tcx.trait_of_assoc(id)) .is_some_and(|id| matches!(cx.tcx.get_diagnostic_name(id), Some(sym::ToString | sym::ToOwned))) => { (arg, arg.span) diff --git a/src/tools/clippy/clippy_lints/src/ranges.rs b/src/tools/clippy/clippy_lints/src/ranges.rs index 9281678b3d8..03d00ba849f 100644 --- a/src/tools/clippy/clippy_lints/src/ranges.rs +++ b/src/tools/clippy/clippy_lints/src/ranges.rs @@ -380,7 +380,7 @@ fn can_switch_ranges<'tcx>( if let ExprKind::MethodCall(_, receiver, _, _) = parent_expr.kind && receiver.hir_id == use_ctxt.child_id && let Some(method_did) = cx.typeck_results().type_dependent_def_id(parent_expr.hir_id) - && let Some(trait_did) = cx.tcx.trait_of_item(method_did) + && let Some(trait_did) = cx.tcx.trait_of_assoc(method_did) && matches!( cx.tcx.get_diagnostic_name(trait_did), Some(sym::Iterator | sym::IntoIterator | sym::RangeBounds) diff --git a/src/tools/clippy/clippy_lints/src/unconditional_recursion.rs b/src/tools/clippy/clippy_lints/src/unconditional_recursion.rs index d321c48f6af..dcddff557d1 100644 --- a/src/tools/clippy/clippy_lints/src/unconditional_recursion.rs +++ b/src/tools/clippy/clippy_lints/src/unconditional_recursion.rs @@ -206,7 +206,7 @@ fn check_partial_eq(cx: &LateContext<'_>, method_span: Span, method_def_id: Loca let arg_ty = cx.typeck_results().expr_ty_adjusted(arg); if let Some(fn_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) - && let Some(trait_id) = cx.tcx.trait_of_item(fn_id) + && let Some(trait_id) = cx.tcx.trait_of_assoc(fn_id) && trait_id == trait_def_id && matches_ty(receiver_ty, arg_ty, self_arg, other_arg) { @@ -250,7 +250,7 @@ fn check_to_string(cx: &LateContext<'_>, method_span: Span, method_def_id: Local let is_bad = match expr.kind { ExprKind::MethodCall(segment, _receiver, &[_arg], _) if segment.ident.name == name.name => { if let Some(fn_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) - && let Some(trait_id) = cx.tcx.trait_of_item(fn_id) + && let Some(trait_id) = cx.tcx.trait_of_assoc(fn_id) && trait_id == trait_def_id { true @@ -318,7 +318,7 @@ where && let ExprKind::Path(qpath) = f.kind && is_default_method_on_current_ty(self.cx.tcx, qpath, self.implemented_ty_id) && let Some(method_def_id) = path_def_id(self.cx, f) - && let Some(trait_def_id) = self.cx.tcx.trait_of_item(method_def_id) + && let Some(trait_def_id) = self.cx.tcx.trait_of_assoc(method_def_id) && self.cx.tcx.is_diagnostic_item(sym::Default, trait_def_id) { span_error(self.cx, self.method_span, expr); @@ -426,7 +426,7 @@ fn check_from(cx: &LateContext<'_>, method_span: Span, method_def_id: LocalDefId if let Some((fn_def_id, node_args)) = fn_def_id_with_node_args(cx, expr) && let [s1, s2] = **node_args && let (Some(s1), Some(s2)) = (s1.as_type(), s2.as_type()) - && let Some(trait_def_id) = cx.tcx.trait_of_item(fn_def_id) + && let Some(trait_def_id) = cx.tcx.trait_of_assoc(fn_def_id) && cx.tcx.is_diagnostic_item(sym::Into, trait_def_id) && get_impl_trait_def_id(cx, method_def_id) == cx.tcx.get_diagnostic_item(sym::From) && s1 == sig.inputs()[0] diff --git a/src/tools/clippy/clippy_lints/src/unused_io_amount.rs b/src/tools/clippy/clippy_lints/src/unused_io_amount.rs index 12cc1093899..bed5c0fc015 100644 --- a/src/tools/clippy/clippy_lints/src/unused_io_amount.rs +++ b/src/tools/clippy/clippy_lints/src/unused_io_amount.rs @@ -300,7 +300,7 @@ fn check_io_mode(cx: &LateContext<'_>, call: &hir::Expr<'_>) -> Option { }; if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(call.hir_id) - && let Some(trait_def_id) = cx.tcx.trait_of_item(method_def_id) + && let Some(trait_def_id) = cx.tcx.trait_of_assoc(method_def_id) { if let Some(diag_name) = cx.tcx.get_diagnostic_name(trait_def_id) { match diag_name { diff --git a/src/tools/clippy/clippy_utils/src/lib.rs b/src/tools/clippy/clippy_utils/src/lib.rs index ce5af4d2f48..211af4d5b08 100644 --- a/src/tools/clippy/clippy_utils/src/lib.rs +++ b/src/tools/clippy/clippy_utils/src/lib.rs @@ -349,7 +349,7 @@ pub fn is_ty_alias(qpath: &QPath<'_>) -> bool { /// Checks if the given method call expression calls an inherent method. pub fn is_inherent_method_call(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { if let Some(method_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) { - cx.tcx.trait_of_item(method_id).is_none() + cx.tcx.trait_of_assoc(method_id).is_none() } else { false } @@ -367,7 +367,7 @@ pub fn is_diag_item_method(cx: &LateContext<'_>, def_id: DefId, diag_item: Symbo /// Checks if a method is in a diagnostic item trait pub fn is_diag_trait_item(cx: &LateContext<'_>, def_id: DefId, diag_item: Symbol) -> bool { - if let Some(trait_did) = cx.tcx.trait_of_item(def_id) { + if let Some(trait_did) = cx.tcx.trait_of_assoc(def_id) { return cx.tcx.is_diagnostic_item(diag_item, trait_did); } false 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 b3356450d38..11c17a77b15 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 @@ -420,7 +420,7 @@ pub fn is_stable_const_fn(cx: &LateContext<'_>, def_id: DefId, msrv: Msrv) -> bo .lookup_const_stability(def_id) .or_else(|| { cx.tcx - .trait_of_item(def_id) + .trait_of_assoc(def_id) .and_then(|trait_def_id| cx.tcx.lookup_const_stability(trait_def_id)) }) .is_none_or(|const_stab| { -- cgit 1.4.1-3-g733a5