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. --- .../src/builder/expr/as_constant.rs | 41 +++++++++++++++------- 1 file changed, 28 insertions(+), 13 deletions(-) (limited to 'compiler/rustc_mir_build/src') 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))) -- 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_mir_build/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 01524abb05a4a60d0015972811b8bbb9bd2a73d3 Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Wed, 23 Jul 2025 22:13:05 -0700 Subject: MIR-build: No longer emit assumes in enum-as casting This just uses the `valid_range` from the backend, so it's duplicating the range metadata that now we include on parameters and loads. --- .../rustc_mir_build/src/builder/expr/as_rvalue.rs | 80 +--------------------- tests/crashes/121097.rs | 10 --- .../mir-opt/building/enum_cast.bar.built.after.mir | 5 -- .../mir-opt/building/enum_cast.boo.built.after.mir | 5 -- .../mir-opt/building/enum_cast.far.built.after.mir | 5 -- .../building/enum_cast.offsetty.built.after.mir | 9 --- tests/mir-opt/building/enum_cast.rs | 7 ++ .../building/enum_cast.signy.built.after.mir | 9 --- tests/ui/simd/repr-simd-on-enum.rs | 15 ++++ tests/ui/simd/repr-simd-on-enum.stderr | 14 ++++ .../self-in-enum-definition.stderr | 30 -------- 11 files changed, 38 insertions(+), 151 deletions(-) delete mode 100644 tests/crashes/121097.rs create mode 100644 tests/ui/simd/repr-simd-on-enum.rs create mode 100644 tests/ui/simd/repr-simd-on-enum.stderr (limited to 'compiler/rustc_mir_build/src') diff --git a/compiler/rustc_mir_build/src/builder/expr/as_rvalue.rs b/compiler/rustc_mir_build/src/builder/expr/as_rvalue.rs index daf8fa5f19e..a4ef6e92739 100644 --- a/compiler/rustc_mir_build/src/builder/expr/as_rvalue.rs +++ b/compiler/rustc_mir_build/src/builder/expr/as_rvalue.rs @@ -1,6 +1,6 @@ //! See docs in `build/expr/mod.rs`. -use rustc_abi::{BackendRepr, FieldIdx, Primitive}; +use rustc_abi::FieldIdx; use rustc_hir::lang_items::LangItem; use rustc_index::{Idx, IndexVec}; use rustc_middle::bug; @@ -9,7 +9,6 @@ use rustc_middle::mir::interpret::Scalar; use rustc_middle::mir::*; use rustc_middle::thir::*; use rustc_middle::ty::cast::{CastTy, mir_cast_kind}; -use rustc_middle::ty::layout::IntegerExt; use rustc_middle::ty::util::IntTypeExt; use rustc_middle::ty::{self, Ty, UpvarArgs}; use rustc_span::source_map::Spanned; @@ -200,8 +199,6 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { { let discr_ty = adt_def.repr().discr_type().to_ty(this.tcx); let temp = unpack!(block = this.as_temp(block, scope, source, Mutability::Not)); - let layout = - this.tcx.layout_of(this.typing_env().as_query_input(source_expr.ty)); let discr = this.temp(discr_ty, source_expr.span); this.cfg.push_assign( block, @@ -209,80 +206,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { discr, Rvalue::Discriminant(temp.into()), ); - let (op, ty) = (Operand::Move(discr), discr_ty); - - if let BackendRepr::Scalar(scalar) = layout.unwrap().backend_repr - && !scalar.is_always_valid(&this.tcx) - && let Primitive::Int(int_width, _signed) = scalar.primitive() - { - let unsigned_ty = int_width.to_ty(this.tcx, false); - let unsigned_place = this.temp(unsigned_ty, expr_span); - this.cfg.push_assign( - block, - source_info, - unsigned_place, - Rvalue::Cast(CastKind::IntToInt, Operand::Copy(discr), unsigned_ty), - ); - - let bool_ty = this.tcx.types.bool; - let range = scalar.valid_range(&this.tcx); - let merge_op = - if range.start <= range.end { BinOp::BitAnd } else { BinOp::BitOr }; - - let mut comparer = |range: u128, bin_op: BinOp| -> Place<'tcx> { - // We can use `ty::TypingEnv::fully_monomorphized()` here - // as we only need it to compute the layout of a primitive. - let range_val = Const::from_bits( - this.tcx, - range, - ty::TypingEnv::fully_monomorphized(), - unsigned_ty, - ); - let lit_op = this.literal_operand(expr.span, range_val); - let is_bin_op = this.temp(bool_ty, expr_span); - this.cfg.push_assign( - block, - source_info, - is_bin_op, - Rvalue::BinaryOp( - bin_op, - Box::new((Operand::Copy(unsigned_place), lit_op)), - ), - ); - is_bin_op - }; - let assert_place = if range.start == 0 { - comparer(range.end, BinOp::Le) - } else { - let start_place = comparer(range.start, BinOp::Ge); - let end_place = comparer(range.end, BinOp::Le); - let merge_place = this.temp(bool_ty, expr_span); - this.cfg.push_assign( - block, - source_info, - merge_place, - Rvalue::BinaryOp( - merge_op, - Box::new(( - Operand::Move(start_place), - Operand::Move(end_place), - )), - ), - ); - merge_place - }; - this.cfg.push( - block, - Statement::new( - source_info, - StatementKind::Intrinsic(Box::new(NonDivergingIntrinsic::Assume( - Operand::Move(assert_place), - ))), - ), - ); - } - - (op, ty) + (Operand::Move(discr), discr_ty) } else { let ty = source_expr.ty; let source = unpack!( diff --git a/tests/crashes/121097.rs b/tests/crashes/121097.rs deleted file mode 100644 index 65c6028e03e..00000000000 --- a/tests/crashes/121097.rs +++ /dev/null @@ -1,10 +0,0 @@ -//@ known-bug: #121097 -#[repr(simd)] -enum Aligned { - Zero = 0, - One = 1, -} - -fn tou8(al: Aligned) -> u8 { - al as u8 -} diff --git a/tests/mir-opt/building/enum_cast.bar.built.after.mir b/tests/mir-opt/building/enum_cast.bar.built.after.mir index 72d0cf5d1e8..0dc6448ffad 100644 --- a/tests/mir-opt/building/enum_cast.bar.built.after.mir +++ b/tests/mir-opt/building/enum_cast.bar.built.after.mir @@ -5,16 +5,11 @@ fn bar(_1: Bar) -> usize { let mut _0: usize; let _2: Bar; let mut _3: isize; - let mut _4: u8; - let mut _5: bool; bb0: { StorageLive(_2); _2 = move _1; _3 = discriminant(_2); - _4 = copy _3 as u8 (IntToInt); - _5 = Le(copy _4, const 1_u8); - assume(move _5); _0 = move _3 as usize (IntToInt); StorageDead(_2); return; diff --git a/tests/mir-opt/building/enum_cast.boo.built.after.mir b/tests/mir-opt/building/enum_cast.boo.built.after.mir index 91e06dc8862..3540a2b1e2e 100644 --- a/tests/mir-opt/building/enum_cast.boo.built.after.mir +++ b/tests/mir-opt/building/enum_cast.boo.built.after.mir @@ -5,16 +5,11 @@ fn boo(_1: Boo) -> usize { let mut _0: usize; let _2: Boo; let mut _3: u8; - let mut _4: u8; - let mut _5: bool; bb0: { StorageLive(_2); _2 = move _1; _3 = discriminant(_2); - _4 = copy _3 as u8 (IntToInt); - _5 = Le(copy _4, const 1_u8); - assume(move _5); _0 = move _3 as usize (IntToInt); StorageDead(_2); return; diff --git a/tests/mir-opt/building/enum_cast.far.built.after.mir b/tests/mir-opt/building/enum_cast.far.built.after.mir index 14eaf344190..da34b7ba6c2 100644 --- a/tests/mir-opt/building/enum_cast.far.built.after.mir +++ b/tests/mir-opt/building/enum_cast.far.built.after.mir @@ -5,16 +5,11 @@ fn far(_1: Far) -> isize { let mut _0: isize; let _2: Far; let mut _3: i16; - let mut _4: u16; - let mut _5: bool; bb0: { StorageLive(_2); _2 = move _1; _3 = discriminant(_2); - _4 = copy _3 as u16 (IntToInt); - _5 = Le(copy _4, const 1_u16); - assume(move _5); _0 = move _3 as isize (IntToInt); StorageDead(_2); return; diff --git a/tests/mir-opt/building/enum_cast.offsetty.built.after.mir b/tests/mir-opt/building/enum_cast.offsetty.built.after.mir index 1c2acbe3023..b84ce0de9a0 100644 --- a/tests/mir-opt/building/enum_cast.offsetty.built.after.mir +++ b/tests/mir-opt/building/enum_cast.offsetty.built.after.mir @@ -5,20 +5,11 @@ fn offsetty(_1: NotStartingAtZero) -> u32 { let mut _0: u32; let _2: NotStartingAtZero; let mut _3: isize; - let mut _4: u8; - let mut _5: bool; - let mut _6: bool; - let mut _7: bool; bb0: { StorageLive(_2); _2 = move _1; _3 = discriminant(_2); - _4 = copy _3 as u8 (IntToInt); - _5 = Ge(copy _4, const 4_u8); - _6 = Le(copy _4, const 8_u8); - _7 = BitAnd(move _5, move _6); - assume(move _7); _0 = move _3 as u32 (IntToInt); StorageDead(_2); return; diff --git a/tests/mir-opt/building/enum_cast.rs b/tests/mir-opt/building/enum_cast.rs index 4fb9a27e309..eaf5537e0ab 100644 --- a/tests/mir-opt/building/enum_cast.rs +++ b/tests/mir-opt/building/enum_cast.rs @@ -4,6 +4,13 @@ // EMIT_MIR enum_cast.boo.built.after.mir // EMIT_MIR enum_cast.far.built.after.mir +// Previously MIR building included range `Assume`s in the MIR statements, +// which these tests demonstrated, but now that we have range metadata on +// parameters in LLVM (in addition to !range metadata on loads) the impact +// of the extra volume of MIR is worse than its value. +// Thus these are now about the discriminant type and the cast type, +// both of which might be different from the backend type of the tag. + enum Foo { A, } diff --git a/tests/mir-opt/building/enum_cast.signy.built.after.mir b/tests/mir-opt/building/enum_cast.signy.built.after.mir index 39b6dfaf005..503c506748f 100644 --- a/tests/mir-opt/building/enum_cast.signy.built.after.mir +++ b/tests/mir-opt/building/enum_cast.signy.built.after.mir @@ -5,20 +5,11 @@ fn signy(_1: SignedAroundZero) -> i16 { let mut _0: i16; let _2: SignedAroundZero; let mut _3: i16; - let mut _4: u16; - let mut _5: bool; - let mut _6: bool; - let mut _7: bool; bb0: { StorageLive(_2); _2 = move _1; _3 = discriminant(_2); - _4 = copy _3 as u16 (IntToInt); - _5 = Ge(copy _4, const 65534_u16); - _6 = Le(copy _4, const 2_u16); - _7 = BitOr(move _5, move _6); - assume(move _7); _0 = move _3 as i16 (IntToInt); StorageDead(_2); return; diff --git a/tests/ui/simd/repr-simd-on-enum.rs b/tests/ui/simd/repr-simd-on-enum.rs new file mode 100644 index 00000000000..49cf9e92d36 --- /dev/null +++ b/tests/ui/simd/repr-simd-on-enum.rs @@ -0,0 +1,15 @@ +// Used to ICE; see + +#![feature(repr_simd)] + +#[repr(simd)] //~ ERROR attribute should be applied to a struct +enum Aligned { + Zero = 0, + One = 1, +} + +fn tou8(al: Aligned) -> u8 { + al as u8 +} + +fn main() {} diff --git a/tests/ui/simd/repr-simd-on-enum.stderr b/tests/ui/simd/repr-simd-on-enum.stderr new file mode 100644 index 00000000000..6a19a16e8ea --- /dev/null +++ b/tests/ui/simd/repr-simd-on-enum.stderr @@ -0,0 +1,14 @@ +error[E0517]: attribute should be applied to a struct + --> $DIR/repr-simd-on-enum.rs:5:8 + | +LL | #[repr(simd)] + | ^^^^ +LL | / enum Aligned { +LL | | Zero = 0, +LL | | One = 1, +LL | | } + | |_- not a struct + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0517`. diff --git a/tests/ui/type-alias-enum-variants/self-in-enum-definition.stderr b/tests/ui/type-alias-enum-variants/self-in-enum-definition.stderr index 084008d8b2a..13ae6dfcaa3 100644 --- a/tests/ui/type-alias-enum-variants/self-in-enum-definition.stderr +++ b/tests/ui/type-alias-enum-variants/self-in-enum-definition.stderr @@ -7,36 +7,6 @@ LL | V3 = Self::V1 {} as u8 + 2, note: ...which requires const-evaluating + checking `Alpha::V3::{constant#0}`... --> $DIR/self-in-enum-definition.rs:5:10 | -LL | V3 = Self::V1 {} as u8 + 2, - | ^^^^^^^^^^^^^^^^^^^^^ -note: ...which requires caching mir of `Alpha::V3::{constant#0}` for CTFE... - --> $DIR/self-in-enum-definition.rs:5:10 - | -LL | V3 = Self::V1 {} as u8 + 2, - | ^^^^^^^^^^^^^^^^^^^^^ -note: ...which requires elaborating drops for `Alpha::V3::{constant#0}`... - --> $DIR/self-in-enum-definition.rs:5:10 - | -LL | V3 = Self::V1 {} as u8 + 2, - | ^^^^^^^^^^^^^^^^^^^^^ -note: ...which requires borrow-checking `Alpha::V3::{constant#0}`... - --> $DIR/self-in-enum-definition.rs:5:10 - | -LL | V3 = Self::V1 {} as u8 + 2, - | ^^^^^^^^^^^^^^^^^^^^^ -note: ...which requires promoting constants in MIR for `Alpha::V3::{constant#0}`... - --> $DIR/self-in-enum-definition.rs:5:10 - | -LL | V3 = Self::V1 {} as u8 + 2, - | ^^^^^^^^^^^^^^^^^^^^^ -note: ...which requires const checking `Alpha::V3::{constant#0}`... - --> $DIR/self-in-enum-definition.rs:5:10 - | -LL | V3 = Self::V1 {} as u8 + 2, - | ^^^^^^^^^^^^^^^^^^^^^ -note: ...which requires building MIR for `Alpha::V3::{constant#0}`... - --> $DIR/self-in-enum-definition.rs:5:10 - | LL | V3 = Self::V1 {} as u8 + 2, | ^^^^^^^^^^^^^^^^^^^^^ = note: ...which requires computing layout of `Alpha`... -- cgit 1.4.1-3-g733a5 From 730d33dd6476ebe4342da9e14c1079f277e1ee74 Mon Sep 17 00:00:00 2001 From: Folkert de Vries Date: Mon, 7 Jul 2025 14:37:50 +0200 Subject: `loop_match`: suggest extracting to a `const` item if the expression cannot be evaluated in a straightforward way --- compiler/rustc_mir_build/messages.ftl | 8 +- compiler/rustc_mir_build/src/builder/scope.rs | 29 ++++- compiler/rustc_mir_build/src/errors.rs | 32 +++++ tests/ui/loop-match/suggest-const-item.rs | 174 ++++++++++++++++++++++++++ tests/ui/loop-match/suggest-const-item.stderr | 58 +++++++++ 5 files changed, 297 insertions(+), 4 deletions(-) create mode 100644 tests/ui/loop-match/suggest-const-item.rs create mode 100644 tests/ui/loop-match/suggest-const-item.stderr (limited to 'compiler/rustc_mir_build/src') diff --git a/compiler/rustc_mir_build/messages.ftl b/compiler/rustc_mir_build/messages.ftl index e339520cd86..abfe8eb66dd 100644 --- a/compiler/rustc_mir_build/messages.ftl +++ b/compiler/rustc_mir_build/messages.ftl @@ -86,10 +86,16 @@ mir_build_confused = missing patterns are not covered because `{$variable}` is i mir_build_const_continue_bad_const = could not determine the target branch for this `#[const_continue]` .label = this value is too generic - .note = the value must be a literal or a monomorphic const mir_build_const_continue_missing_value = a `#[const_continue]` must break to a label with a value +mir_build_const_continue_not_const = could not determine the target branch for this `#[const_continue]` + .help = try extracting the expression into a `const` item + +mir_build_const_continue_not_const_const_block = `const` blocks may use generics, and are not evaluated early enough +mir_build_const_continue_not_const_const_other = this value must be a literal or a monomorphic const +mir_build_const_continue_not_const_constant_parameter = constant parameters may use generics, and are not evaluated early enough + mir_build_const_continue_unknown_jump_target = the target of this `#[const_continue]` is not statically known .label = this value must be a literal or a monomorphic const diff --git a/compiler/rustc_mir_build/src/builder/scope.rs b/compiler/rustc_mir_build/src/builder/scope.rs index 12a56d7c5ea..1240b34cf9d 100644 --- a/compiler/rustc_mir_build/src/builder/scope.rs +++ b/compiler/rustc_mir_build/src/builder/scope.rs @@ -100,7 +100,9 @@ use tracing::{debug, instrument}; use super::matches::BuiltMatchTree; use crate::builder::{BlockAnd, BlockAndExtension, BlockFrame, Builder, CFG}; -use crate::errors::{ConstContinueBadConst, ConstContinueUnknownJumpTarget}; +use crate::errors::{ + ConstContinueBadConst, ConstContinueNotMonomorphicConst, ConstContinueUnknownJumpTarget, +}; #[derive(Debug)] pub(crate) struct Scopes<'tcx> { @@ -867,7 +869,8 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { span_bug!(span, "break value must be a scope") }; - let constant = match &self.thir[value].kind { + let expr = &self.thir[value]; + let constant = match &expr.kind { ExprKind::Adt(box AdtExpr { variant_index, fields, base, .. }) => { assert!(matches!(base, AdtExprBase::None)); assert!(fields.is_empty()); @@ -887,7 +890,27 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { ), } } - _ => self.as_constant(&self.thir[value]), + + ExprKind::Literal { .. } + | ExprKind::NonHirLiteral { .. } + | ExprKind::ZstLiteral { .. } + | ExprKind::NamedConst { .. } => self.as_constant(&self.thir[value]), + + other => { + use crate::errors::ConstContinueNotMonomorphicConstReason as Reason; + + let span = expr.span; + let reason = match other { + ExprKind::ConstParam { .. } => Reason::ConstantParameter { span }, + ExprKind::ConstBlock { .. } => Reason::ConstBlock { span }, + _ => Reason::Other { span }, + }; + + self.tcx + .dcx() + .emit_err(ConstContinueNotMonomorphicConst { span: expr.span, reason }); + return block.unit(); + } }; let break_index = self diff --git a/compiler/rustc_mir_build/src/errors.rs b/compiler/rustc_mir_build/src/errors.rs index 16b49bf384c..f1fbd5c4a49 100644 --- a/compiler/rustc_mir_build/src/errors.rs +++ b/compiler/rustc_mir_build/src/errors.rs @@ -1213,6 +1213,38 @@ pub(crate) struct LoopMatchArmWithGuard { pub span: Span, } +#[derive(Diagnostic)] +#[diag(mir_build_const_continue_not_const)] +#[help] +pub(crate) struct ConstContinueNotMonomorphicConst { + #[primary_span] + pub span: Span, + + #[subdiagnostic] + pub reason: ConstContinueNotMonomorphicConstReason, +} + +#[derive(Subdiagnostic)] +pub(crate) enum ConstContinueNotMonomorphicConstReason { + #[label(mir_build_const_continue_not_const_constant_parameter)] + ConstantParameter { + #[primary_span] + span: Span, + }, + + #[label(mir_build_const_continue_not_const_const_block)] + ConstBlock { + #[primary_span] + span: Span, + }, + + #[label(mir_build_const_continue_not_const_const_other)] + Other { + #[primary_span] + span: Span, + }, +} + #[derive(Diagnostic)] #[diag(mir_build_const_continue_bad_const)] pub(crate) struct ConstContinueBadConst { diff --git a/tests/ui/loop-match/suggest-const-item.rs b/tests/ui/loop-match/suggest-const-item.rs new file mode 100644 index 00000000000..f921b430b8c --- /dev/null +++ b/tests/ui/loop-match/suggest-const-item.rs @@ -0,0 +1,174 @@ +#![allow(incomplete_features)] +#![feature(loop_match)] +#![feature(generic_const_items)] +#![crate_type = "lib"] + +const fn const_fn() -> i32 { + 1 +} + +#[unsafe(no_mangle)] +fn suggest_const_block() -> i32 { + let mut state = 0; + #[loop_match] + loop { + state = 'blk: { + match state { + 0 => { + #[const_continue] + break 'blk const_fn(); + //~^ ERROR could not determine the target branch for this `#[const_continue]` + } + 1 => { + #[const_continue] + break 'blk const { const_fn() }; + //~^ ERROR could not determine the target branch for this `#[const_continue]` + } + 2 => { + #[const_continue] + break 'blk N; + //~^ ERROR could not determine the target branch for this `#[const_continue]` + } + _ => { + #[const_continue] + break 'blk 1 + 1; + //~^ ERROR could not determine the target branch for this `#[const_continue]` + } + } + } + } + state +} + +struct S; + +impl S { + const M: usize = 42; + + fn g() { + let mut state = 0; + #[loop_match] + loop { + state = 'blk: { + match state { + 0 => { + #[const_continue] + break 'blk Self::M; + } + _ => panic!(), + } + } + } + } +} + +trait T { + const N: usize; + + fn f() { + let mut state = 0; + #[loop_match] + loop { + state = 'blk: { + match state { + 0 => { + #[const_continue] + break 'blk Self::N; + //~^ ERROR could not determine the target branch for this `#[const_continue]` + } + _ => panic!(), + } + } + } + } +} + +impl T for S { + const N: usize = 1; +} + +impl S { + fn h() { + let mut state = 0; + #[loop_match] + loop { + state = 'blk: { + match state { + 0 => { + #[const_continue] + break 'blk Self::N; + } + _ => panic!(), + } + } + } + } +} + +trait T2 { + const L: u32; + + fn p() { + let mut state = 0; + #[loop_match] + loop { + state = 'blk: { + match state { + 0 => { + #[const_continue] + break 'blk Self::L; + //~^ ERROR could not determine the target branch for this `#[const_continue]` + } + _ => panic!(), + } + } + } + } +} + +const SIZE_OF: usize = size_of::(); + +fn q() { + let mut state = 0; + #[loop_match] + loop { + state = 'blk: { + match state { + 0 => { + #[const_continue] + break 'blk SIZE_OF::; + //~^ ERROR could not determine the target branch for this `#[const_continue]` + } + _ => panic!(), + } + } + } +} + +trait Trait { + const X: usize = 9000; + const Y: usize = size_of::(); +} + +impl Trait for () {} + +fn r() { + let mut state = 0; + #[loop_match] + loop { + state = 'blk: { + match state { + 0 => { + #[const_continue] + break 'blk <() as Trait>::X; + } + 1 => { + #[const_continue] + break 'blk <() as Trait>::Y; + //~^ ERROR could not determine the target branch for this `#[const_continue]` + } + _ => panic!(), + } + } + } +} diff --git a/tests/ui/loop-match/suggest-const-item.stderr b/tests/ui/loop-match/suggest-const-item.stderr new file mode 100644 index 00000000000..787474479ad --- /dev/null +++ b/tests/ui/loop-match/suggest-const-item.stderr @@ -0,0 +1,58 @@ +error: could not determine the target branch for this `#[const_continue]` + --> $DIR/suggest-const-item.rs:19:32 + | +LL | break 'blk const_fn(); + | ^^^^^^^^^^ this value must be a literal or a monomorphic const + | + = help: try extracting the expression into a `const` item + +error: could not determine the target branch for this `#[const_continue]` + --> $DIR/suggest-const-item.rs:24:32 + | +LL | break 'blk const { const_fn() }; + | ^^^^^^^^^^^^^^^^^^^^ `const` blocks may use generics, and are not evaluated early enough + | + = help: try extracting the expression into a `const` item + +error: could not determine the target branch for this `#[const_continue]` + --> $DIR/suggest-const-item.rs:29:32 + | +LL | break 'blk N; + | ^ constant parameters may use generics, and are not evaluated early enough + | + = help: try extracting the expression into a `const` item + +error: could not determine the target branch for this `#[const_continue]` + --> $DIR/suggest-const-item.rs:34:32 + | +LL | break 'blk 1 + 1; + | ^^^^^ this value must be a literal or a monomorphic const + | + = help: try extracting the expression into a `const` item + +error: could not determine the target branch for this `#[const_continue]` + --> $DIR/suggest-const-item.rs:76:36 + | +LL | break 'blk Self::N; + | ^^^^^^^ this value is too generic + +error: could not determine the target branch for this `#[const_continue]` + --> $DIR/suggest-const-item.rs:119:36 + | +LL | break 'blk Self::L; + | ^^^^^^^ this value is too generic + +error: could not determine the target branch for this `#[const_continue]` + --> $DIR/suggest-const-item.rs:139:32 + | +LL | break 'blk SIZE_OF::; + | ^^^^^^^^^^^^ this value is too generic + +error: could not determine the target branch for this `#[const_continue]` + --> $DIR/suggest-const-item.rs:167:32 + | +LL | break 'blk <() as Trait>::Y; + | ^^^^^^^^^^^^^^^^^^^ this value is too generic + +error: aborting due to 8 previous errors + -- cgit 1.4.1-3-g733a5 From bae38bad7803be7fdf1878188da9650f82548016 Mon Sep 17 00:00:00 2001 From: Kivooeo Date: Sat, 26 Jul 2025 06:21:54 +0500 Subject: use let chains in hir, lint, mir --- .../rustc_hir_typeck/src/fn_ctxt/suggestions.rs | 12 +-- compiler/rustc_hir_typeck/src/method/confirm.rs | 10 +- compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs | 9 +- compiler/rustc_hir_typeck/src/writeback.rs | 12 +-- compiler/rustc_lint/src/builtin.rs | 48 ++++----- compiler/rustc_lint/src/internal.rs | 31 +++--- compiler/rustc_lint/src/map_unit_fn.rs | 110 ++++++++++----------- compiler/rustc_lint/src/non_fmt_panic.rs | 60 +++++------ compiler/rustc_lint/src/nonstandard_style.rs | 18 ++-- compiler/rustc_lint/src/unused.rs | 53 +++++----- compiler/rustc_metadata/src/locator.rs | 9 +- compiler/rustc_metadata/src/rmeta/encoder.rs | 8 +- compiler/rustc_middle/src/middle/region.rs | 33 +++---- compiler/rustc_middle/src/ty/adt.rs | 8 +- compiler/rustc_middle/src/ty/layout.rs | 8 +- compiler/rustc_middle/src/ty/print/pretty.rs | 8 +- compiler/rustc_mir_build/src/thir/cx/block.rs | 38 ++++--- compiler/rustc_mir_build/src/thir/cx/expr.rs | 18 ++-- .../src/thir/pattern/check_match.rs | 12 +-- .../rustc_mir_dataflow/src/drop_flag_effects.rs | 5 +- .../rustc_mir_dataflow/src/impls/initialized.rs | 13 +-- compiler/rustc_mir_dataflow/src/rustc_peek.rs | 48 +++++---- compiler/rustc_mir_dataflow/src/value_analysis.rs | 8 +- compiler/rustc_mir_transform/src/coroutine/drop.rs | 8 +- 24 files changed, 279 insertions(+), 308 deletions(-) (limited to 'compiler/rustc_mir_build/src') diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs index ede02fbf9bd..33ae4f6c45c 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs @@ -3008,13 +3008,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Returns whether the given expression is an `else if`. fn is_else_if_block(&self, expr: &hir::Expr<'_>) -> bool { - if let hir::ExprKind::If(..) = expr.kind { - if let Node::Expr(hir::Expr { - kind: hir::ExprKind::If(_, _, Some(else_expr)), .. - }) = self.tcx.parent_hir_node(expr.hir_id) - { - return else_expr.hir_id == expr.hir_id; - } + if let hir::ExprKind::If(..) = expr.kind + && let Node::Expr(hir::Expr { kind: hir::ExprKind::If(_, _, Some(else_expr)), .. }) = + self.tcx.parent_hir_node(expr.hir_id) + { + return else_expr.hir_id == expr.hir_id; } false } diff --git a/compiler/rustc_hir_typeck/src/method/confirm.rs b/compiler/rustc_hir_typeck/src/method/confirm.rs index 4c343bb7c22..8d9f7eaf177 100644 --- a/compiler/rustc_hir_typeck/src/method/confirm.rs +++ b/compiler/rustc_hir_typeck/src/method/confirm.rs @@ -669,17 +669,17 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { fn check_for_illegal_method_calls(&self, pick: &probe::Pick<'_>) { // Disallow calls to the method `drop` defined in the `Drop` trait. - if let Some(trait_def_id) = pick.item.trait_container(self.tcx) { - if let Err(e) = callee::check_legal_trait_for_method_call( + if let Some(trait_def_id) = pick.item.trait_container(self.tcx) + && let Err(e) = callee::check_legal_trait_for_method_call( self.tcx, self.span, Some(self.self_expr.span), self.call_expr.span, trait_def_id, self.body_id.to_def_id(), - ) { - self.set_tainted_by_errors(e); - } + ) + { + self.set_tainted_by_errors(e); } } diff --git a/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs b/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs index 9f4ab8ca5d4..6a985fc91e7 100644 --- a/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs +++ b/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs @@ -165,13 +165,12 @@ impl<'tcx> TypeckRootCtxt<'tcx> { if let ty::PredicateKind::Clause(ty::ClauseKind::Projection(predicate)) = obligation.predicate.kind().skip_binder() - { // If the projection predicate (Foo::Bar == X) has X as a non-TyVid, // we need to make it into one. - if let Some(vid) = predicate.term.as_type().and_then(|ty| ty.ty_vid()) { - debug!("infer_var_info: {:?}.output = true", vid); - infer_var_info.entry(vid).or_default().output = true; - } + && let Some(vid) = predicate.term.as_type().and_then(|ty| ty.ty_vid()) + { + debug!("infer_var_info: {:?}.output = true", vid); + infer_var_info.entry(vid).or_default().output = true; } } } diff --git a/compiler/rustc_hir_typeck/src/writeback.rs b/compiler/rustc_hir_typeck/src/writeback.rs index b2497cb0de1..093de950d63 100644 --- a/compiler/rustc_hir_typeck/src/writeback.rs +++ b/compiler/rustc_hir_typeck/src/writeback.rs @@ -227,21 +227,19 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { self.typeck_results.type_dependent_defs_mut().remove(e.hir_id); self.typeck_results.node_args_mut().remove(e.hir_id); - if let Some(a) = self.typeck_results.adjustments_mut().get_mut(base.hir_id) { + if let Some(a) = self.typeck_results.adjustments_mut().get_mut(base.hir_id) // Discard the need for a mutable borrow - // Extra adjustment made when indexing causes a drop // of size information - we need to get rid of it // Since this is "after" the other adjustment to be // discarded, we do an extra `pop()` - if let Some(Adjustment { + && let Some(Adjustment { kind: Adjust::Pointer(PointerCoercion::Unsize), .. }) = a.pop() - { - // So the borrow discard actually happens here - a.pop(); - } + { + // So the borrow discard actually happens here + a.pop(); } } } diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index eb4c3703dbd..c48fb286dc0 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -2446,16 +2446,16 @@ impl<'tcx> LateLintPass<'tcx> for InvalidValue { /// Determine if this expression is a "dangerous initialization". fn is_dangerous_init(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option { - if let hir::ExprKind::Call(path_expr, args) = expr.kind { + if let hir::ExprKind::Call(path_expr, args) = expr.kind // Find calls to `mem::{uninitialized,zeroed}` methods. - if let hir::ExprKind::Path(ref qpath) = path_expr.kind { - let def_id = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id()?; - match cx.tcx.get_diagnostic_name(def_id) { - Some(sym::mem_zeroed) => return Some(InitKind::Zeroed), - Some(sym::mem_uninitialized) => return Some(InitKind::Uninit), - Some(sym::transmute) if is_zero(&args[0]) => return Some(InitKind::Zeroed), - _ => {} - } + && let hir::ExprKind::Path(ref qpath) = path_expr.kind + { + let def_id = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id()?; + match cx.tcx.get_diagnostic_name(def_id) { + Some(sym::mem_zeroed) => return Some(InitKind::Zeroed), + Some(sym::mem_uninitialized) => return Some(InitKind::Uninit), + Some(sym::transmute) if is_zero(&args[0]) => return Some(InitKind::Zeroed), + _ => {} } } else if let hir::ExprKind::MethodCall(_, receiver, ..) = expr.kind { // Find problematic calls to `MaybeUninit::assume_init`. @@ -2463,14 +2463,14 @@ impl<'tcx> LateLintPass<'tcx> for InvalidValue { if cx.tcx.is_diagnostic_item(sym::assume_init, def_id) { // This is a call to *some* method named `assume_init`. // See if the `self` parameter is one of the dangerous constructors. - if let hir::ExprKind::Call(path_expr, _) = receiver.kind { - if let hir::ExprKind::Path(ref qpath) = path_expr.kind { - let def_id = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id()?; - match cx.tcx.get_diagnostic_name(def_id) { - Some(sym::maybe_uninit_zeroed) => return Some(InitKind::Zeroed), - Some(sym::maybe_uninit_uninit) => return Some(InitKind::Uninit), - _ => {} - } + if let hir::ExprKind::Call(path_expr, _) = receiver.kind + && let hir::ExprKind::Path(ref qpath) = path_expr.kind + { + let def_id = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id()?; + match cx.tcx.get_diagnostic_name(def_id) { + Some(sym::maybe_uninit_zeroed) => return Some(InitKind::Zeroed), + Some(sym::maybe_uninit_uninit) => return Some(InitKind::Uninit), + _ => {} } } } @@ -2724,13 +2724,13 @@ impl<'tcx> LateLintPass<'tcx> for DerefNullPtr { } // check for call to `core::ptr::null` or `core::ptr::null_mut` hir::ExprKind::Call(path, _) => { - if let hir::ExprKind::Path(ref qpath) = path.kind { - if let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id() { - return matches!( - cx.tcx.get_diagnostic_name(def_id), - Some(sym::ptr_null | sym::ptr_null_mut) - ); - } + if let hir::ExprKind::Path(ref qpath) = path.kind + && let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id() + { + return matches!( + cx.tcx.get_diagnostic_name(def_id), + Some(sym::ptr_null | sym::ptr_null_mut) + ); } } _ => {} diff --git a/compiler/rustc_lint/src/internal.rs b/compiler/rustc_lint/src/internal.rs index d8fc46aa9ab..7dafcc199a3 100644 --- a/compiler/rustc_lint/src/internal.rs +++ b/compiler/rustc_lint/src/internal.rs @@ -411,22 +411,21 @@ declare_lint_pass!(LintPassImpl => [LINT_PASS_IMPL_WITHOUT_MACRO]); impl EarlyLintPass for LintPassImpl { fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) { - if let ast::ItemKind::Impl(box ast::Impl { of_trait: Some(lint_pass), .. }) = &item.kind { - if let Some(last) = lint_pass.path.segments.last() { - if last.ident.name == sym::LintPass { - let expn_data = lint_pass.path.span.ctxt().outer_expn_data(); - let call_site = expn_data.call_site; - if expn_data.kind != ExpnKind::Macro(MacroKind::Bang, sym::impl_lint_pass) - && call_site.ctxt().outer_expn_data().kind - != ExpnKind::Macro(MacroKind::Bang, sym::declare_lint_pass) - { - cx.emit_span_lint( - LINT_PASS_IMPL_WITHOUT_MACRO, - lint_pass.path.span, - LintPassByHand, - ); - } - } + if let ast::ItemKind::Impl(box ast::Impl { of_trait: Some(lint_pass), .. }) = &item.kind + && let Some(last) = lint_pass.path.segments.last() + && last.ident.name == sym::LintPass + { + let expn_data = lint_pass.path.span.ctxt().outer_expn_data(); + let call_site = expn_data.call_site; + if expn_data.kind != ExpnKind::Macro(MacroKind::Bang, sym::impl_lint_pass) + && call_site.ctxt().outer_expn_data().kind + != ExpnKind::Macro(MacroKind::Bang, sym::declare_lint_pass) + { + cx.emit_span_lint( + LINT_PASS_IMPL_WITHOUT_MACRO, + lint_pass.path.span, + LintPassByHand, + ); } } } diff --git a/compiler/rustc_lint/src/map_unit_fn.rs b/compiler/rustc_lint/src/map_unit_fn.rs index af509cb786d..a8803158889 100644 --- a/compiler/rustc_lint/src/map_unit_fn.rs +++ b/compiler/rustc_lint/src/map_unit_fn.rs @@ -43,56 +43,50 @@ impl<'tcx> LateLintPass<'tcx> for MapUnitFn { return; } - if let StmtKind::Semi(expr) = stmt.kind { - if let ExprKind::MethodCall(path, receiver, args, span) = expr.kind { - if path.ident.name.as_str() == "map" { - if receiver.span.from_expansion() - || args.iter().any(|e| e.span.from_expansion()) - || !is_impl_slice(cx, receiver) - || !is_diagnostic_name(cx, expr.hir_id, "IteratorMap") - { - return; + if let StmtKind::Semi(expr) = stmt.kind + && let ExprKind::MethodCall(path, receiver, args, span) = expr.kind + { + if path.ident.name.as_str() == "map" { + if receiver.span.from_expansion() + || args.iter().any(|e| e.span.from_expansion()) + || !is_impl_slice(cx, receiver) + || !is_diagnostic_name(cx, expr.hir_id, "IteratorMap") + { + return; + } + let arg_ty = cx.typeck_results().expr_ty(&args[0]); + let default_span = args[0].span; + if let ty::FnDef(id, _) = arg_ty.kind() { + let fn_ty = cx.tcx.fn_sig(id).skip_binder(); + let ret_ty = fn_ty.output().skip_binder(); + if is_unit_type(ret_ty) { + cx.emit_span_lint( + MAP_UNIT_FN, + span, + MappingToUnit { + function_label: cx.tcx.span_of_impl(*id).unwrap_or(default_span), + argument_label: args[0].span, + map_label: span, + suggestion: path.ident.span, + replace: "for_each".to_string(), + }, + ) } - let arg_ty = cx.typeck_results().expr_ty(&args[0]); - let default_span = args[0].span; - if let ty::FnDef(id, _) = arg_ty.kind() { - let fn_ty = cx.tcx.fn_sig(id).skip_binder(); - let ret_ty = fn_ty.output().skip_binder(); - if is_unit_type(ret_ty) { - cx.emit_span_lint( - MAP_UNIT_FN, - span, - MappingToUnit { - function_label: cx - .tcx - .span_of_impl(*id) - .unwrap_or(default_span), - argument_label: args[0].span, - map_label: span, - suggestion: path.ident.span, - replace: "for_each".to_string(), - }, - ) - } - } else if let ty::Closure(id, subs) = arg_ty.kind() { - let cl_ty = subs.as_closure().sig(); - let ret_ty = cl_ty.output().skip_binder(); - if is_unit_type(ret_ty) { - cx.emit_span_lint( - MAP_UNIT_FN, - span, - MappingToUnit { - function_label: cx - .tcx - .span_of_impl(*id) - .unwrap_or(default_span), - argument_label: args[0].span, - map_label: span, - suggestion: path.ident.span, - replace: "for_each".to_string(), - }, - ) - } + } else if let ty::Closure(id, subs) = arg_ty.kind() { + let cl_ty = subs.as_closure().sig(); + let ret_ty = cl_ty.output().skip_binder(); + if is_unit_type(ret_ty) { + cx.emit_span_lint( + MAP_UNIT_FN, + span, + MappingToUnit { + function_label: cx.tcx.span_of_impl(*id).unwrap_or(default_span), + argument_label: args[0].span, + map_label: span, + suggestion: path.ident.span, + replace: "for_each".to_string(), + }, + ) } } } @@ -101,10 +95,10 @@ impl<'tcx> LateLintPass<'tcx> for MapUnitFn { } fn is_impl_slice(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { - if let Some(method_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) { - if let Some(impl_id) = cx.tcx.impl_of_method(method_id) { - return cx.tcx.type_of(impl_id).skip_binder().is_slice(); - } + if let Some(method_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) + && let Some(impl_id) = cx.tcx.impl_of_method(method_id) + { + return cx.tcx.type_of(impl_id).skip_binder().is_slice(); } false } @@ -114,11 +108,11 @@ fn is_unit_type(ty: Ty<'_>) -> bool { } fn is_diagnostic_name(cx: &LateContext<'_>, id: HirId, name: &str) -> bool { - if let Some(def_id) = cx.typeck_results().type_dependent_def_id(id) { - if let Some(item) = cx.tcx.get_diagnostic_name(def_id) { - if item.as_str() == name { - return true; - } + if let Some(def_id) = cx.typeck_results().type_dependent_def_id(id) + && let Some(item) = cx.tcx.get_diagnostic_name(def_id) + { + if item.as_str() == name { + return true; } } false diff --git a/compiler/rustc_lint/src/non_fmt_panic.rs b/compiler/rustc_lint/src/non_fmt_panic.rs index 16c06100808..2eabeeaa88f 100644 --- a/compiler/rustc_lint/src/non_fmt_panic.rs +++ b/compiler/rustc_lint/src/non_fmt_panic.rs @@ -48,39 +48,39 @@ declare_lint_pass!(NonPanicFmt => [NON_FMT_PANICS]); impl<'tcx> LateLintPass<'tcx> for NonPanicFmt { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) { - if let hir::ExprKind::Call(f, [arg]) = &expr.kind { - if let &ty::FnDef(def_id, _) = cx.typeck_results().expr_ty(f).kind() { - let f_diagnostic_name = cx.tcx.get_diagnostic_name(def_id); + if let hir::ExprKind::Call(f, [arg]) = &expr.kind + && let &ty::FnDef(def_id, _) = cx.typeck_results().expr_ty(f).kind() + { + let f_diagnostic_name = cx.tcx.get_diagnostic_name(def_id); - if cx.tcx.is_lang_item(def_id, LangItem::BeginPanic) - || cx.tcx.is_lang_item(def_id, LangItem::Panic) - || f_diagnostic_name == Some(sym::panic_str_2015) - { - if let Some(id) = f.span.ctxt().outer_expn_data().macro_def_id { - if matches!( - cx.tcx.get_diagnostic_name(id), - Some(sym::core_panic_2015_macro | sym::std_panic_2015_macro) - ) { - check_panic(cx, f, arg); - } - } - } else if f_diagnostic_name == Some(sym::unreachable_display) { - if let Some(id) = f.span.ctxt().outer_expn_data().macro_def_id { - if cx.tcx.is_diagnostic_item(sym::unreachable_2015_macro, id) { - check_panic( - cx, - f, - // This is safe because we checked above that the callee is indeed - // unreachable_display - match &arg.kind { - // Get the borrowed arg not the borrow - hir::ExprKind::AddrOf(ast::BorrowKind::Ref, _, arg) => arg, - _ => bug!("call to unreachable_display without borrow"), - }, - ); - } + if cx.tcx.is_lang_item(def_id, LangItem::BeginPanic) + || cx.tcx.is_lang_item(def_id, LangItem::Panic) + || f_diagnostic_name == Some(sym::panic_str_2015) + { + if let Some(id) = f.span.ctxt().outer_expn_data().macro_def_id { + if matches!( + cx.tcx.get_diagnostic_name(id), + Some(sym::core_panic_2015_macro | sym::std_panic_2015_macro) + ) { + check_panic(cx, f, arg); } } + } else if f_diagnostic_name == Some(sym::unreachable_display) { + if let Some(id) = f.span.ctxt().outer_expn_data().macro_def_id + && cx.tcx.is_diagnostic_item(sym::unreachable_2015_macro, id) + { + check_panic( + cx, + f, + // This is safe because we checked above that the callee is indeed + // unreachable_display + match &arg.kind { + // Get the borrowed arg not the borrow + hir::ExprKind::AddrOf(ast::BorrowKind::Ref, _, arg) => arg, + _ => bug!("call to unreachable_display without borrow"), + }, + ); + } } } } diff --git a/compiler/rustc_lint/src/nonstandard_style.rs b/compiler/rustc_lint/src/nonstandard_style.rs index db89396d1dc..76e374deef6 100644 --- a/compiler/rustc_lint/src/nonstandard_style.rs +++ b/compiler/rustc_lint/src/nonstandard_style.rs @@ -623,15 +623,15 @@ impl<'tcx> LateLintPass<'tcx> for NonUpperCaseGlobals { .. }) = p.kind { - if let Res::Def(DefKind::Const, _) = path.res { - if let [segment] = path.segments { - NonUpperCaseGlobals::check_upper_case( - cx, - "constant in pattern", - None, - &segment.ident, - ); - } + if let Res::Def(DefKind::Const, _) = path.res + && let [segment] = path.segments + { + NonUpperCaseGlobals::check_upper_case( + cx, + "constant in pattern", + None, + &segment.ident, + ); } } } diff --git a/compiler/rustc_lint/src/unused.rs b/compiler/rustc_lint/src/unused.rs index a9eb1739f7f..13dd6cb1661 100644 --- a/compiler/rustc_lint/src/unused.rs +++ b/compiler/rustc_lint/src/unused.rs @@ -562,20 +562,19 @@ declare_lint_pass!(PathStatements => [PATH_STATEMENTS]); impl<'tcx> LateLintPass<'tcx> for PathStatements { fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) { - if let hir::StmtKind::Semi(expr) = s.kind { - if let hir::ExprKind::Path(_) = expr.kind { - let ty = cx.typeck_results().expr_ty(expr); - if ty.needs_drop(cx.tcx, cx.typing_env()) { - let sub = if let Ok(snippet) = cx.sess().source_map().span_to_snippet(expr.span) - { - PathStatementDropSub::Suggestion { span: s.span, snippet } - } else { - PathStatementDropSub::Help { span: s.span } - }; - cx.emit_span_lint(PATH_STATEMENTS, s.span, PathStatementDrop { sub }) + if let hir::StmtKind::Semi(expr) = s.kind + && let hir::ExprKind::Path(_) = expr.kind + { + let ty = cx.typeck_results().expr_ty(expr); + if ty.needs_drop(cx.tcx, cx.typing_env()) { + let sub = if let Ok(snippet) = cx.sess().source_map().span_to_snippet(expr.span) { + PathStatementDropSub::Suggestion { span: s.span, snippet } } else { - cx.emit_span_lint(PATH_STATEMENTS, s.span, PathStatementNoEffect); - } + PathStatementDropSub::Help { span: s.span } + }; + cx.emit_span_lint(PATH_STATEMENTS, s.span, PathStatementDrop { sub }) + } else { + cx.emit_span_lint(PATH_STATEMENTS, s.span, PathStatementNoEffect); } } } @@ -1509,21 +1508,19 @@ impl UnusedDelimLint for UnusedBraces { // let _: A<{produces_literal!()}>; // ``` // FIXME(const_generics): handle paths when #67075 is fixed. - if let [stmt] = inner.stmts.as_slice() { - if let ast::StmtKind::Expr(ref expr) = stmt.kind { - if !Self::is_expr_delims_necessary(expr, ctx, followed_by_block) - && (ctx != UnusedDelimsCtx::AnonConst - || (matches!(expr.kind, ast::ExprKind::Lit(_)) - && !expr.span.from_expansion())) - && ctx != UnusedDelimsCtx::ClosureBody - && !cx.sess().source_map().is_multiline(value.span) - && value.attrs.is_empty() - && !value.span.from_expansion() - && !inner.span.from_expansion() - { - self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos, is_kw) - } - } + if let [stmt] = inner.stmts.as_slice() + && let ast::StmtKind::Expr(ref expr) = stmt.kind + && !Self::is_expr_delims_necessary(expr, ctx, followed_by_block) + && (ctx != UnusedDelimsCtx::AnonConst + || (matches!(expr.kind, ast::ExprKind::Lit(_)) + && !expr.span.from_expansion())) + && ctx != UnusedDelimsCtx::ClosureBody + && !cx.sess().source_map().is_multiline(value.span) + && value.attrs.is_empty() + && !value.span.from_expansion() + && !inner.span.from_expansion() + { + self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos, is_kw) } } ast::ExprKind::Let(_, ref expr, _, _) => { diff --git a/compiler/rustc_metadata/src/locator.rs b/compiler/rustc_metadata/src/locator.rs index c30cfd1fcf7..9fef22f9558 100644 --- a/compiler/rustc_metadata/src/locator.rs +++ b/compiler/rustc_metadata/src/locator.rs @@ -370,12 +370,11 @@ impl<'a> CrateLocator<'a> { return self.find_commandline_library(crate_rejections); } let mut seen_paths = FxHashSet::default(); - if let Some(extra_filename) = self.extra_filename { - if let library @ Some(_) = + if let Some(extra_filename) = self.extra_filename + && let library @ Some(_) = self.find_library_crate(crate_rejections, extra_filename, &mut seen_paths)? - { - return Ok(library); - } + { + return Ok(library); } self.find_library_crate(crate_rejections, "", &mut seen_paths) } diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 5cd98038fc6..8a8ce2a789a 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -2141,10 +2141,10 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { .push((id.owner_id.def_id.local_def_index, simplified_self_ty)); let trait_def = tcx.trait_def(trait_ref.def_id); - if let Ok(mut an) = trait_def.ancestors(tcx, def_id) { - if let Some(specialization_graph::Node::Impl(parent)) = an.nth(1) { - self.tables.impl_parent.set_some(def_id.index, parent.into()); - } + if let Ok(mut an) = trait_def.ancestors(tcx, def_id) + && let Some(specialization_graph::Node::Impl(parent)) = an.nth(1) + { + self.tables.impl_parent.set_some(def_id.index, parent.into()); } // if this is an impl of `CoerceUnsized`, create its diff --git a/compiler/rustc_middle/src/middle/region.rs b/compiler/rustc_middle/src/middle/region.rs index 0f5b63f5c1d..800c1af660a 100644 --- a/compiler/rustc_middle/src/middle/region.rs +++ b/compiler/rustc_middle/src/middle/region.rs @@ -175,23 +175,22 @@ impl Scope { return DUMMY_SP; }; let span = tcx.hir_span(hir_id); - if let ScopeData::Remainder(first_statement_index) = self.data { - if let Node::Block(blk) = tcx.hir_node(hir_id) { - // Want span for scope starting after the - // indexed statement and ending at end of - // `blk`; reuse span of `blk` and shift `lo` - // forward to end of indexed statement. - // - // (This is the special case alluded to in the - // doc-comment for this method) - - let stmt_span = blk.stmts[first_statement_index.index()].span; - - // To avoid issues with macro-generated spans, the span - // of the statement must be nested in that of the block. - if span.lo() <= stmt_span.lo() && stmt_span.lo() <= span.hi() { - return span.with_lo(stmt_span.lo()); - } + if let ScopeData::Remainder(first_statement_index) = self.data + // Want span for scope starting after the + // indexed statement and ending at end of + // `blk`; reuse span of `blk` and shift `lo` + // forward to end of indexed statement. + // + // (This is the special case alluded to in the + // doc-comment for this method) + && let Node::Block(blk) = tcx.hir_node(hir_id) + { + let stmt_span = blk.stmts[first_statement_index.index()].span; + + // To avoid issues with macro-generated spans, the span + // of the statement must be nested in that of the block. + if span.lo() <= stmt_span.lo() && stmt_span.lo() <= span.hi() { + return span.with_lo(stmt_span.lo()); } } span diff --git a/compiler/rustc_middle/src/ty/adt.rs b/compiler/rustc_middle/src/ty/adt.rs index 275458fc85f..3bf80d37e65 100644 --- a/compiler/rustc_middle/src/ty/adt.rs +++ b/compiler/rustc_middle/src/ty/adt.rs @@ -566,10 +566,10 @@ impl<'tcx> AdtDef<'tcx> { let mut prev_discr = None::>; self.variants().iter_enumerated().map(move |(i, v)| { let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx)); - if let VariantDiscr::Explicit(expr_did) = v.discr { - if let Ok(new_discr) = self.eval_explicit_discr(tcx, expr_did) { - discr = new_discr; - } + if let VariantDiscr::Explicit(expr_did) = v.discr + && let Ok(new_discr) = self.eval_explicit_discr(tcx, expr_did) + { + discr = new_discr; } prev_discr = Some(discr); diff --git a/compiler/rustc_middle/src/ty/layout.rs b/compiler/rustc_middle/src/ty/layout.rs index 809717513c7..a5123576fc6 100644 --- a/compiler/rustc_middle/src/ty/layout.rs +++ b/compiler/rustc_middle/src/ty/layout.rs @@ -1055,11 +1055,11 @@ where _ => Some(this), }; - if let Some(variant) = data_variant { + if let Some(variant) = data_variant // We're not interested in any unions. - if let FieldsShape::Union(_) = variant.fields { - data_variant = None; - } + && let FieldsShape::Union(_) = variant.fields + { + data_variant = None; } let mut result = None; diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index 9ee64df0ad0..d1cc75699d2 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -225,10 +225,10 @@ impl<'tcx> RegionHighlightMode<'tcx> { region: Option>, number: Option, ) { - if let Some(k) = region { - if let Some(n) = number { - self.highlighting_region(k, n); - } + if let Some(k) = region + && let Some(n) = number + { + self.highlighting_region(k, n); } } diff --git a/compiler/rustc_mir_build/src/thir/cx/block.rs b/compiler/rustc_mir_build/src/thir/cx/block.rs index e858b629ab1..57ddb8eddb8 100644 --- a/compiler/rustc_mir_build/src/thir/cx/block.rs +++ b/compiler/rustc_mir_build/src/thir/cx/block.rs @@ -76,28 +76,24 @@ impl<'tcx> ThirBuildCx<'tcx> { let mut pattern = self.pattern_from_hir(local.pat); debug!(?pattern); - if let Some(ty) = &local.ty { - if let Some(&user_ty) = + if let Some(ty) = &local.ty + && let Some(&user_ty) = self.typeck_results.user_provided_types().get(ty.hir_id) - { - debug!("mirror_stmts: user_ty={:?}", user_ty); - let annotation = CanonicalUserTypeAnnotation { - user_ty: Box::new(user_ty), - span: ty.span, - inferred_ty: self.typeck_results.node_type(ty.hir_id), - }; - pattern = Box::new(Pat { - ty: pattern.ty, - span: pattern.span, - kind: PatKind::AscribeUserType { - ascription: Ascription { - annotation, - variance: ty::Covariant, - }, - subpattern: pattern, - }, - }); - } + { + debug!("mirror_stmts: user_ty={:?}", user_ty); + let annotation = CanonicalUserTypeAnnotation { + user_ty: Box::new(user_ty), + span: ty.span, + inferred_ty: self.typeck_results.node_type(ty.hir_id), + }; + pattern = Box::new(Pat { + ty: pattern.ty, + span: pattern.span, + kind: PatKind::AscribeUserType { + ascription: Ascription { annotation, variance: ty::Covariant }, + subpattern: pattern, + }, + }); } let span = match local.init { diff --git a/compiler/rustc_mir_build/src/thir/cx/expr.rs b/compiler/rustc_mir_build/src/thir/cx/expr.rs index b694409f327..33bf4e3e29f 100644 --- a/compiler/rustc_mir_build/src/thir/cx/expr.rs +++ b/compiler/rustc_mir_build/src/thir/cx/expr.rs @@ -105,11 +105,11 @@ impl<'tcx> ThirBuildCx<'tcx> { // // ^ error message points at this expression. // } let mut adjust_span = |expr: &mut Expr<'tcx>| { - if let ExprKind::Block { block } = expr.kind { - if let Some(last_expr) = self.thir[block].expr { - span = self.thir[last_expr].span; - expr.span = span; - } + if let ExprKind::Block { block } = expr.kind + && let Some(last_expr) = self.thir[block].expr + { + span = self.thir[last_expr].span; + expr.span = span; } }; @@ -956,10 +956,10 @@ impl<'tcx> ThirBuildCx<'tcx> { }; fn local(expr: &rustc_hir::Expr<'_>) -> Option { - if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = expr.kind { - if let Res::Local(hir_id) = path.res { - return Some(hir_id); - } + if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = expr.kind + && let Res::Local(hir_id) = path.res + { + return Some(hir_id); } None diff --git a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs index 7f47754f6bc..ae67bb5075e 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs @@ -1155,14 +1155,12 @@ fn find_fallback_pattern_typo<'tcx>( } hir::Node::Block(hir::Block { stmts, .. }) => { for stmt in *stmts { - if let hir::StmtKind::Let(let_stmt) = stmt.kind { - if let hir::PatKind::Binding(_, _, binding_name, _) = + if let hir::StmtKind::Let(let_stmt) = stmt.kind + && let hir::PatKind::Binding(_, _, binding_name, _) = let_stmt.pat.kind - { - if name == binding_name.name { - lint.pattern_let_binding = Some(binding_name.span); - } - } + && name == binding_name.name + { + lint.pattern_let_binding = Some(binding_name.span); } } } diff --git a/compiler/rustc_mir_dataflow/src/drop_flag_effects.rs b/compiler/rustc_mir_dataflow/src/drop_flag_effects.rs index c9c7fddae5a..1402a1a8b91 100644 --- a/compiler/rustc_mir_dataflow/src/drop_flag_effects.rs +++ b/compiler/rustc_mir_dataflow/src/drop_flag_effects.rs @@ -124,10 +124,9 @@ pub fn drop_flag_effects_for_location<'tcx, F>( // Drop does not count as a move but we should still consider the variable uninitialized. if let Some(Terminator { kind: TerminatorKind::Drop { place, .. }, .. }) = body.stmt_at(loc).right() + && let LookupResult::Exact(mpi) = move_data.rev_lookup.find(place.as_ref()) { - if let LookupResult::Exact(mpi) = move_data.rev_lookup.find(place.as_ref()) { - on_all_children_bits(move_data, mpi, |mpi| callback(mpi, DropFlagState::Absent)) - } + on_all_children_bits(move_data, mpi, |mpi| callback(mpi, DropFlagState::Absent)) } debug!("drop_flag_effects: assignment for location({:?})", loc); diff --git a/compiler/rustc_mir_dataflow/src/impls/initialized.rs b/compiler/rustc_mir_dataflow/src/impls/initialized.rs index 085757f0fb6..117525eb777 100644 --- a/compiler/rustc_mir_dataflow/src/impls/initialized.rs +++ b/compiler/rustc_mir_dataflow/src/impls/initialized.rs @@ -637,16 +637,13 @@ impl<'tcx> Analysis<'tcx> for EverInitializedPlaces<'_, 'tcx> { debug!("initializes move_indexes {:?}", init_loc_map[location]); state.gen_all(init_loc_map[location].iter().copied()); - if let mir::StatementKind::StorageDead(local) = stmt.kind { + if let mir::StatementKind::StorageDead(local) = stmt.kind // End inits for StorageDead, so that an immutable variable can // be reinitialized on the next iteration of the loop. - if let Some(move_path_index) = rev_lookup.find_local(local) { - debug!( - "clears the ever initialized status of {:?}", - init_path_map[move_path_index] - ); - state.kill_all(init_path_map[move_path_index].iter().copied()); - } + && let Some(move_path_index) = rev_lookup.find_local(local) + { + debug!("clears the ever initialized status of {:?}", init_path_map[move_path_index]); + state.kill_all(init_path_map[move_path_index].iter().copied()); } } diff --git a/compiler/rustc_mir_dataflow/src/rustc_peek.rs b/compiler/rustc_mir_dataflow/src/rustc_peek.rs index 303fc767b9a..1682f332857 100644 --- a/compiler/rustc_mir_dataflow/src/rustc_peek.rs +++ b/compiler/rustc_mir_dataflow/src/rustc_peek.rs @@ -135,12 +135,11 @@ fn value_assigned_to_local<'a, 'tcx>( stmt: &'a mir::Statement<'tcx>, local: Local, ) -> Option<&'a mir::Rvalue<'tcx>> { - if let mir::StatementKind::Assign(box (place, rvalue)) = &stmt.kind { - if let Some(l) = place.as_local() { - if local == l { - return Some(&*rvalue); - } - } + if let mir::StatementKind::Assign(box (place, rvalue)) = &stmt.kind + && let Some(l) = place.as_local() + && local == l + { + return Some(&*rvalue); } None @@ -178,31 +177,30 @@ impl PeekCall { let span = terminator.source_info.span; if let mir::TerminatorKind::Call { func: Operand::Constant(func), args, .. } = &terminator.kind + && let ty::FnDef(def_id, fn_args) = *func.const_.ty().kind() { - if let ty::FnDef(def_id, fn_args) = *func.const_.ty().kind() { - if tcx.intrinsic(def_id)?.name != sym::rustc_peek { - return None; - } + if tcx.intrinsic(def_id)?.name != sym::rustc_peek { + return None; + } - assert_eq!(fn_args.len(), 1); - let kind = PeekCallKind::from_arg_ty(fn_args.type_at(0)); - let arg = match &args[0].node { - Operand::Copy(place) | Operand::Move(place) => { - if let Some(local) = place.as_local() { - local - } else { - tcx.dcx().emit_err(PeekMustBeNotTemporary { span }); - return None; - } - } - _ => { + assert_eq!(fn_args.len(), 1); + let kind = PeekCallKind::from_arg_ty(fn_args.type_at(0)); + let arg = match &args[0].node { + Operand::Copy(place) | Operand::Move(place) => { + if let Some(local) = place.as_local() { + local + } else { tcx.dcx().emit_err(PeekMustBeNotTemporary { span }); return None; } - }; + } + _ => { + tcx.dcx().emit_err(PeekMustBeNotTemporary { span }); + return None; + } + }; - return Some(PeekCall { arg, kind, span }); - } + return Some(PeekCall { arg, kind, span }); } None diff --git a/compiler/rustc_mir_dataflow/src/value_analysis.rs b/compiler/rustc_mir_dataflow/src/value_analysis.rs index 83fd8ccba60..005e7973130 100644 --- a/compiler/rustc_mir_dataflow/src/value_analysis.rs +++ b/compiler/rustc_mir_dataflow/src/value_analysis.rs @@ -215,10 +215,10 @@ impl State { // If both places are tracked, we copy the value to the target. // If the target is tracked, but the source is not, we do nothing, as invalidation has // already been performed. - if let Some(target_value) = map.places[target].value_index { - if let Some(source_value) = map.places[source].value_index { - values.insert(target_value, values.get(source_value).clone()); - } + if let Some(target_value) = map.places[target].value_index + && let Some(source_value) = map.places[source].value_index + { + values.insert(target_value, values.get(source_value).clone()); } for target_child in map.children(target) { // Try to find corresponding child and recurse. Reasoning is similar as above. diff --git a/compiler/rustc_mir_transform/src/coroutine/drop.rs b/compiler/rustc_mir_transform/src/coroutine/drop.rs index 406575c4f43..1a314e029f4 100644 --- a/compiler/rustc_mir_transform/src/coroutine/drop.rs +++ b/compiler/rustc_mir_transform/src/coroutine/drop.rs @@ -23,10 +23,10 @@ impl<'tcx> MutVisitor<'tcx> for FixReturnPendingVisitor<'tcx> { } // Converting `_0 = Poll::::Pending` to `_0 = Poll::<()>::Pending` - if let Rvalue::Aggregate(kind, _) = rvalue { - if let AggregateKind::Adt(_, _, ref mut args, _, _) = **kind { - *args = self.tcx.mk_args(&[self.tcx.types.unit.into()]); - } + if let Rvalue::Aggregate(kind, _) = rvalue + && let AggregateKind::Adt(_, _, ref mut args, _, _) = **kind + { + *args = self.tcx.mk_args(&[self.tcx.types.unit.into()]); } } } -- cgit 1.4.1-3-g733a5 From d87b4f2c77add3404f7469ea72f1d7c51e2a29dc Mon Sep 17 00:00:00 2001 From: Shoyu Vanilla Date: Fri, 25 Jul 2025 23:07:13 +0900 Subject: fix: Reject upvar scrutinees for `loop_match` --- compiler/rustc_mir_build/src/thir/cx/expr.rs | 21 +++++--- tests/ui/loop-match/upvar-scrutinee.rs | 81 ++++++++++++++++++++++++++++ tests/ui/loop-match/upvar-scrutinee.stderr | 18 +++++++ 3 files changed, 113 insertions(+), 7 deletions(-) create mode 100644 tests/ui/loop-match/upvar-scrutinee.rs create mode 100644 tests/ui/loop-match/upvar-scrutinee.stderr (limited to 'compiler/rustc_mir_build/src') diff --git a/compiler/rustc_mir_build/src/thir/cx/expr.rs b/compiler/rustc_mir_build/src/thir/cx/expr.rs index 33bf4e3e29f..16df58cd76d 100644 --- a/compiler/rustc_mir_build/src/thir/cx/expr.rs +++ b/compiler/rustc_mir_build/src/thir/cx/expr.rs @@ -955,9 +955,13 @@ impl<'tcx> ThirBuildCx<'tcx> { dcx.emit_fatal(LoopMatchBadRhs { span: block_body_expr.span }) }; - fn local(expr: &rustc_hir::Expr<'_>) -> Option { + fn local( + cx: &mut ThirBuildCx<'_>, + expr: &rustc_hir::Expr<'_>, + ) -> Option { if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = expr.kind && let Res::Local(hir_id) = path.res + && !cx.is_upvar(hir_id) { return Some(hir_id); } @@ -965,11 +969,11 @@ impl<'tcx> ThirBuildCx<'tcx> { None } - let Some(scrutinee_hir_id) = local(scrutinee) else { + let Some(scrutinee_hir_id) = local(self, scrutinee) else { dcx.emit_fatal(LoopMatchInvalidMatch { span: scrutinee.span }) }; - if local(state) != Some(scrutinee_hir_id) { + if local(self, state) != Some(scrutinee_hir_id) { dcx.emit_fatal(LoopMatchInvalidUpdate { scrutinee: scrutinee.span, lhs: state.span, @@ -1260,10 +1264,7 @@ impl<'tcx> ThirBuildCx<'tcx> { fn convert_var(&mut self, var_hir_id: hir::HirId) -> ExprKind<'tcx> { // We want upvars here not captures. // Captures will be handled in MIR. - let is_upvar = self - .tcx - .upvars_mentioned(self.body_owner) - .is_some_and(|upvars| upvars.contains_key(&var_hir_id)); + let is_upvar = self.is_upvar(var_hir_id); debug!( "convert_var({:?}): is_upvar={}, body_owner={:?}", @@ -1443,6 +1444,12 @@ impl<'tcx> ThirBuildCx<'tcx> { } } + fn is_upvar(&mut self, var_hir_id: hir::HirId) -> bool { + self.tcx + .upvars_mentioned(self.body_owner) + .is_some_and(|upvars| upvars.contains_key(&var_hir_id)) + } + /// Converts a list of named fields (i.e., for struct-like struct/enum ADTs) into FieldExpr. fn field_refs(&mut self, fields: &'tcx [hir::ExprField<'tcx>]) -> Box<[FieldExpr]> { fields diff --git a/tests/ui/loop-match/upvar-scrutinee.rs b/tests/ui/loop-match/upvar-scrutinee.rs new file mode 100644 index 00000000000..a93e3a0e59a --- /dev/null +++ b/tests/ui/loop-match/upvar-scrutinee.rs @@ -0,0 +1,81 @@ +#![allow(incomplete_features)] +#![feature(loop_match)] + +#[derive(Clone, Copy)] +enum State { + A, + B, +} + +fn main() { + let mut state = State::A; + + #[loop_match] + loop { + state = 'blk: { + match state { + State::A => { + #[const_continue] + break 'blk State::B; + } + State::B => { + return; + } + } + } + } + + || { + #[loop_match] + loop { + state = 'blk: { + match state { + //~^ ERROR invalid match on `#[loop_match]` state + State::A => { + #[const_continue] + break 'blk State::B; + } + State::B => { + return; + } + } + } + } + }; + + || { + let mut state = state; + #[loop_match] + loop { + state = 'blk: { + match state { + State::A => { + #[const_continue] + break 'blk State::B; + } + State::B => { + return; + } + } + } + } + }; + + move || { + #[loop_match] + loop { + state = 'blk: { + match state { + //~^ ERROR invalid match on `#[loop_match]` state + State::A => { + #[const_continue] + break 'blk State::B; + } + State::B => { + return; + } + } + } + } + }; +} diff --git a/tests/ui/loop-match/upvar-scrutinee.stderr b/tests/ui/loop-match/upvar-scrutinee.stderr new file mode 100644 index 00000000000..b7a0a90193d --- /dev/null +++ b/tests/ui/loop-match/upvar-scrutinee.stderr @@ -0,0 +1,18 @@ +error: invalid match on `#[loop_match]` state + --> $DIR/upvar-scrutinee.rs:32:23 + | +LL | match state { + | ^^^^^ + | + = note: a local variable must be the scrutinee within a `#[loop_match]` + +error: invalid match on `#[loop_match]` state + --> $DIR/upvar-scrutinee.rs:68:23 + | +LL | match state { + | ^^^^^ + | + = note: a local variable must be the scrutinee within a `#[loop_match]` + +error: aborting due to 2 previous errors + -- cgit 1.4.1-3-g733a5