diff options
Diffstat (limited to 'compiler/rustc_mir_build')
| -rw-r--r-- | compiler/rustc_mir_build/messages.ftl | 2 | ||||
| -rw-r--r-- | compiler/rustc_mir_build/src/builder/block.rs (renamed from compiler/rustc_mir_build/src/build/block.rs) | 6 | ||||
| -rw-r--r-- | compiler/rustc_mir_build/src/builder/cfg.rs (renamed from compiler/rustc_mir_build/src/build/cfg.rs) | 4 | ||||
| -rw-r--r-- | compiler/rustc_mir_build/src/builder/coverageinfo.rs (renamed from compiler/rustc_mir_build/src/build/coverageinfo.rs) | 4 | ||||
| -rw-r--r-- | compiler/rustc_mir_build/src/builder/coverageinfo/mcdc.rs (renamed from compiler/rustc_mir_build/src/build/coverageinfo/mcdc.rs) | 2 | ||||
| -rw-r--r-- | compiler/rustc_mir_build/src/builder/custom/mod.rs (renamed from compiler/rustc_mir_build/src/build/custom/mod.rs) | 5 | ||||
| -rw-r--r-- | compiler/rustc_mir_build/src/builder/custom/parse.rs (renamed from compiler/rustc_mir_build/src/build/custom/parse.rs) | 13 | ||||
| -rw-r--r-- | compiler/rustc_mir_build/src/builder/custom/parse/instruction.rs (renamed from compiler/rustc_mir_build/src/build/custom/parse/instruction.rs) | 4 | ||||
| -rw-r--r-- | compiler/rustc_mir_build/src/builder/expr/as_constant.rs (renamed from compiler/rustc_mir_build/src/build/expr/as_constant.rs) | 2 | ||||
| -rw-r--r-- | compiler/rustc_mir_build/src/builder/expr/as_operand.rs (renamed from compiler/rustc_mir_build/src/build/expr/as_operand.rs) | 4 | ||||
| -rw-r--r-- | compiler/rustc_mir_build/src/builder/expr/as_place.rs (renamed from compiler/rustc_mir_build/src/build/expr/as_place.rs) | 46 | ||||
| -rw-r--r-- | compiler/rustc_mir_build/src/builder/expr/as_rvalue.rs (renamed from compiler/rustc_mir_build/src/build/expr/as_rvalue.rs) | 6 | ||||
| -rw-r--r-- | compiler/rustc_mir_build/src/builder/expr/as_temp.rs (renamed from compiler/rustc_mir_build/src/build/expr/as_temp.rs) | 8 | ||||
| -rw-r--r-- | compiler/rustc_mir_build/src/builder/expr/category.rs (renamed from compiler/rustc_mir_build/src/build/expr/category.rs) | 0 | ||||
| -rw-r--r-- | compiler/rustc_mir_build/src/builder/expr/into.rs (renamed from compiler/rustc_mir_build/src/build/expr/into.rs) | 22 | ||||
| -rw-r--r-- | compiler/rustc_mir_build/src/builder/expr/mod.rs (renamed from compiler/rustc_mir_build/src/build/expr/mod.rs) | 0 | ||||
| -rw-r--r-- | compiler/rustc_mir_build/src/builder/expr/stmt.rs (renamed from compiler/rustc_mir_build/src/build/expr/stmt.rs) | 4 | ||||
| -rw-r--r-- | compiler/rustc_mir_build/src/builder/matches/match_pair.rs (renamed from compiler/rustc_mir_build/src/build/matches/match_pair.rs) | 8 | ||||
| -rw-r--r-- | compiler/rustc_mir_build/src/builder/matches/mod.rs (renamed from compiler/rustc_mir_build/src/build/matches/mod.rs) | 11 | ||||
| -rw-r--r-- | compiler/rustc_mir_build/src/builder/matches/simplify.rs (renamed from compiler/rustc_mir_build/src/build/matches/simplify.rs) | 4 | ||||
| -rw-r--r-- | compiler/rustc_mir_build/src/builder/matches/test.rs (renamed from compiler/rustc_mir_build/src/build/matches/test.rs) | 7 | ||||
| -rw-r--r-- | compiler/rustc_mir_build/src/builder/matches/util.rs (renamed from compiler/rustc_mir_build/src/build/matches/util.rs) | 6 | ||||
| -rw-r--r-- | compiler/rustc_mir_build/src/builder/misc.rs (renamed from compiler/rustc_mir_build/src/build/misc.rs) | 8 | ||||
| -rw-r--r-- | compiler/rustc_mir_build/src/builder/mod.rs (renamed from compiler/rustc_mir_build/src/build/mod.rs) | 16 | ||||
| -rw-r--r-- | compiler/rustc_mir_build/src/builder/scope.rs (renamed from compiler/rustc_mir_build/src/build/scope.rs) | 157 | ||||
| -rw-r--r-- | compiler/rustc_mir_build/src/check_unsafety.rs | 21 | ||||
| -rw-r--r-- | compiler/rustc_mir_build/src/errors.rs | 31 | ||||
| -rw-r--r-- | compiler/rustc_mir_build/src/lib.rs | 9 | ||||
| -rw-r--r-- | compiler/rustc_mir_build/src/thir/constant.rs | 2 | ||||
| -rw-r--r-- | compiler/rustc_mir_build/src/thir/cx/block.rs | 8 | ||||
| -rw-r--r-- | compiler/rustc_mir_build/src/thir/cx/expr.rs | 26 | ||||
| -rw-r--r-- | compiler/rustc_mir_build/src/thir/pattern/mod.rs | 29 |
32 files changed, 301 insertions, 174 deletions
diff --git a/compiler/rustc_mir_build/messages.ftl b/compiler/rustc_mir_build/messages.ftl index f647486f62a..edba247c7b0 100644 --- a/compiler/rustc_mir_build/messages.ftl +++ b/compiler/rustc_mir_build/messages.ftl @@ -285,7 +285,7 @@ mir_build_pointer_pattern = function pointers and raw pointers not derived from mir_build_privately_uninhabited = pattern `{$witness_1}` is currently uninhabited, but this variant contains private fields which may become inhabited in the future -mir_build_rust_2024_incompatible_pat = patterns are not allowed to reset the default binding mode in edition 2024 +mir_build_rust_2024_incompatible_pat = this pattern relies on behavior which may change in edition 2024 mir_build_rustc_box_attribute_error = `#[rustc_box]` attribute used incorrectly .attributes = no other attributes may be applied diff --git a/compiler/rustc_mir_build/src/build/block.rs b/compiler/rustc_mir_build/src/builder/block.rs index 89e64015bc4..ba63a97de89 100644 --- a/compiler/rustc_mir_build/src/build/block.rs +++ b/compiler/rustc_mir_build/src/builder/block.rs @@ -5,9 +5,9 @@ use rustc_middle::{span_bug, ty}; use rustc_span::Span; use tracing::debug; -use crate::build::ForGuard::OutsideGuard; -use crate::build::matches::{DeclareLetBindings, EmitStorageLive, ScheduleDrops}; -use crate::build::{BlockAnd, BlockAndExtension, BlockFrame, Builder}; +use crate::builder::ForGuard::OutsideGuard; +use crate::builder::matches::{DeclareLetBindings, EmitStorageLive, ScheduleDrops}; +use crate::builder::{BlockAnd, BlockAndExtension, BlockFrame, Builder}; impl<'a, 'tcx> Builder<'a, 'tcx> { pub(crate) fn ast_block( diff --git a/compiler/rustc_mir_build/src/build/cfg.rs b/compiler/rustc_mir_build/src/builder/cfg.rs index 9c5ee5b0996..42212f2518b 100644 --- a/compiler/rustc_mir_build/src/build/cfg.rs +++ b/compiler/rustc_mir_build/src/builder/cfg.rs @@ -4,7 +4,7 @@ use rustc_middle::mir::*; use rustc_middle::ty::TyCtxt; use tracing::debug; -use crate::build::CFG; +use crate::builder::CFG; impl<'tcx> CFG<'tcx> { pub(crate) fn block_data(&self, blk: BasicBlock) -> &BasicBlockData<'tcx> { @@ -19,7 +19,7 @@ impl<'tcx> CFG<'tcx> { // it as #[inline(never)] to keep rustc's stack use in check. #[inline(never)] pub(crate) fn start_new_block(&mut self) -> BasicBlock { - self.basic_blocks.push(BasicBlockData::new(None)) + self.basic_blocks.push(BasicBlockData::new(None, false)) } pub(crate) fn start_new_cleanup_block(&mut self) -> BasicBlock { diff --git a/compiler/rustc_mir_build/src/build/coverageinfo.rs b/compiler/rustc_mir_build/src/builder/coverageinfo.rs index 52a4a4b4b51..a80bd4f3c80 100644 --- a/compiler/rustc_mir_build/src/build/coverageinfo.rs +++ b/compiler/rustc_mir_build/src/builder/coverageinfo.rs @@ -8,8 +8,8 @@ use rustc_middle::thir::{ExprId, ExprKind, Pat, Thir}; use rustc_middle::ty::TyCtxt; use rustc_span::def_id::LocalDefId; -use crate::build::coverageinfo::mcdc::MCDCInfoBuilder; -use crate::build::{Builder, CFG}; +use crate::builder::coverageinfo::mcdc::MCDCInfoBuilder; +use crate::builder::{Builder, CFG}; mod mcdc; diff --git a/compiler/rustc_mir_build/src/build/coverageinfo/mcdc.rs b/compiler/rustc_mir_build/src/builder/coverageinfo/mcdc.rs index 343d4000043..6b4871dc1fc 100644 --- a/compiler/rustc_mir_build/src/build/coverageinfo/mcdc.rs +++ b/compiler/rustc_mir_build/src/builder/coverageinfo/mcdc.rs @@ -9,7 +9,7 @@ use rustc_middle::thir::LogicalOp; use rustc_middle::ty::TyCtxt; use rustc_span::Span; -use crate::build::Builder; +use crate::builder::Builder; use crate::errors::MCDCExceedsConditionLimit; /// LLVM uses `i16` to represent condition id. Hence `i16::MAX` is the hard limit for number of diff --git a/compiler/rustc_mir_build/src/build/custom/mod.rs b/compiler/rustc_mir_build/src/builder/custom/mod.rs index e809c9a23f3..ca2e1dd7a1a 100644 --- a/compiler/rustc_mir_build/src/build/custom/mod.rs +++ b/compiler/rustc_mir_build/src/builder/custom/mod.rs @@ -17,10 +17,9 @@ //! terminators, and everything below can be found in the `parse::instruction` submodule. //! -use rustc_ast::Attribute; use rustc_data_structures::fx::FxHashMap; -use rustc_hir::HirId; use rustc_hir::def_id::DefId; +use rustc_hir::{Attribute, HirId}; use rustc_index::{IndexSlice, IndexVec}; use rustc_middle::mir::*; use rustc_middle::span_bug; @@ -65,7 +64,7 @@ pub(super) fn build_custom_mir<'tcx>( }; body.local_decls.push(LocalDecl::new(return_ty, return_ty_span)); - body.basic_blocks_mut().push(BasicBlockData::new(None)); + body.basic_blocks_mut().push(BasicBlockData::new(None, false)); body.source_scopes.push(SourceScopeData { span, parent_scope: None, diff --git a/compiler/rustc_mir_build/src/build/custom/parse.rs b/compiler/rustc_mir_build/src/builder/custom/parse.rs index 538068e1fac..91e284604b6 100644 --- a/compiler/rustc_mir_build/src/build/custom/parse.rs +++ b/compiler/rustc_mir_build/src/builder/custom/parse.rs @@ -199,10 +199,12 @@ impl<'a, 'tcx> ParseCtxt<'a, 'tcx> { match &self.thir[stmt].kind { StmtKind::Let { pattern, initializer: Some(initializer), .. } => { let (var, ..) = self.parse_var(pattern)?; - let mut data = BasicBlockData::new(None); - data.is_cleanup = parse_by_kind!(self, *initializer, _, "basic block declaration", - @variant(mir_basic_block, Normal) => false, - @variant(mir_basic_block, Cleanup) => true, + let data = BasicBlockData::new( + None, + parse_by_kind!(self, *initializer, _, "basic block declaration", + @variant(mir_basic_block, Normal) => false, + @variant(mir_basic_block, Cleanup) => true, + ), ); let block = self.body.basic_blocks_mut().push(data); self.block_map.insert(var, block); @@ -308,8 +310,7 @@ impl<'a, 'tcx> ParseCtxt<'a, 'tcx> { ExprKind::Block { block } => &self.thir[*block], ); - let mut data = BasicBlockData::new(None); - data.is_cleanup = is_cleanup; + let mut data = BasicBlockData::new(None, is_cleanup); for stmt_id in &*block.stmts { let stmt = self.statement_as_expr(*stmt_id)?; let span = self.thir[stmt].span; diff --git a/compiler/rustc_mir_build/src/build/custom/parse/instruction.rs b/compiler/rustc_mir_build/src/builder/custom/parse/instruction.rs index 67114efdff5..59f440432eb 100644 --- a/compiler/rustc_mir_build/src/build/custom/parse/instruction.rs +++ b/compiler/rustc_mir_build/src/builder/custom/parse/instruction.rs @@ -9,8 +9,8 @@ use rustc_span::Span; use rustc_span::source_map::Spanned; use super::{PResult, ParseCtxt, parse_by_kind}; -use crate::build::custom::ParseError; -use crate::build::expr::as_constant::as_constant_inner; +use crate::builder::custom::ParseError; +use crate::builder::expr::as_constant::as_constant_inner; impl<'a, 'tcx> ParseCtxt<'a, 'tcx> { pub(crate) fn parse_statement(&self, expr_id: ExprId) -> PResult<StatementKind<'tcx>> { diff --git a/compiler/rustc_mir_build/src/build/expr/as_constant.rs b/compiler/rustc_mir_build/src/builder/expr/as_constant.rs index 640408cb9c8..177c1e33a83 100644 --- a/compiler/rustc_mir_build/src/build/expr/as_constant.rs +++ b/compiler/rustc_mir_build/src/builder/expr/as_constant.rs @@ -14,7 +14,7 @@ use rustc_middle::ty::{ use rustc_middle::{bug, mir, span_bug}; use tracing::{instrument, trace}; -use crate::build::{Builder, parse_float_into_constval}; +use crate::builder::{Builder, parse_float_into_constval}; impl<'a, 'tcx> Builder<'a, 'tcx> { /// Compile `expr`, yielding a compile-time constant. Assumes that diff --git a/compiler/rustc_mir_build/src/build/expr/as_operand.rs b/compiler/rustc_mir_build/src/builder/expr/as_operand.rs index 777ff9e68f0..63e9b1dc6cd 100644 --- a/compiler/rustc_mir_build/src/build/expr/as_operand.rs +++ b/compiler/rustc_mir_build/src/builder/expr/as_operand.rs @@ -4,8 +4,8 @@ use rustc_middle::mir::*; use rustc_middle::thir::*; use tracing::{debug, instrument}; -use crate::build::expr::category::Category; -use crate::build::{BlockAnd, BlockAndExtension, Builder, NeedsTemporary}; +use crate::builder::expr::category::Category; +use crate::builder::{BlockAnd, BlockAndExtension, Builder, NeedsTemporary}; impl<'a, 'tcx> Builder<'a, 'tcx> { /// Construct a temporary lifetime restricted to just the local scope diff --git a/compiler/rustc_mir_build/src/build/expr/as_place.rs b/compiler/rustc_mir_build/src/builder/expr/as_place.rs index 70a74910a68..01aec70f437 100644 --- a/compiler/rustc_mir_build/src/build/expr/as_place.rs +++ b/compiler/rustc_mir_build/src/builder/expr/as_place.rs @@ -14,9 +14,9 @@ use rustc_middle::{bug, span_bug}; use rustc_span::{DesugaringKind, Span}; use tracing::{debug, instrument, trace}; -use crate::build::ForGuard::{OutsideGuard, RefWithinGuard}; -use crate::build::expr::category::Category; -use crate::build::{BlockAnd, BlockAndExtension, Builder, Capture, CaptureMap}; +use crate::builder::ForGuard::{OutsideGuard, RefWithinGuard}; +use crate::builder::expr::category::Category; +use crate::builder::{BlockAnd, BlockAndExtension, Builder, Capture, CaptureMap}; /// The "outermost" place that holds this value. #[derive(Copy, Clone, Debug, PartialEq)] @@ -68,7 +68,7 @@ pub(crate) enum PlaceBase { /// This is used internally when building a place for an expression like `a.b.c`. The fields `b` /// and `c` can be progressively pushed onto the place builder that is created when converting `a`. #[derive(Clone, Debug, PartialEq)] -pub(in crate::build) struct PlaceBuilder<'tcx> { +pub(in crate::builder) struct PlaceBuilder<'tcx> { base: PlaceBase, projection: Vec<PlaceElem<'tcx>>, } @@ -249,7 +249,7 @@ fn strip_prefix<'a, 'tcx>( } impl<'tcx> PlaceBuilder<'tcx> { - pub(in crate::build) fn to_place(&self, cx: &Builder<'_, 'tcx>) -> Place<'tcx> { + pub(in crate::builder) fn to_place(&self, cx: &Builder<'_, 'tcx>) -> Place<'tcx> { self.try_to_place(cx).unwrap_or_else(|| match self.base { PlaceBase::Local(local) => span_bug!( cx.local_decls[local].source_info.span, @@ -265,7 +265,7 @@ impl<'tcx> PlaceBuilder<'tcx> { } /// Creates a `Place` or returns `None` if an upvar cannot be resolved - pub(in crate::build) fn try_to_place(&self, cx: &Builder<'_, 'tcx>) -> Option<Place<'tcx>> { + pub(in crate::builder) fn try_to_place(&self, cx: &Builder<'_, 'tcx>) -> Option<Place<'tcx>> { let resolved = self.resolve_upvar(cx); let builder = resolved.as_ref().unwrap_or(self); let PlaceBase::Local(local) = builder.base else { return None }; @@ -283,7 +283,7 @@ impl<'tcx> PlaceBuilder<'tcx> { /// not captured. This can happen because the final mir that will be /// generated doesn't require a read for this place. Failures will only /// happen inside closures. - pub(in crate::build) fn resolve_upvar( + pub(in crate::builder) fn resolve_upvar( &self, cx: &Builder<'_, 'tcx>, ) -> Option<PlaceBuilder<'tcx>> { @@ -647,13 +647,31 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { match place_ty.kind() { ty::Array(_elem_ty, len_const) => { - // We know how long an array is, so just use that as a constant - // directly -- no locals needed. We do need one statement so - // that borrow- and initialization-checking consider it used, - // though. FIXME: Do we really *need* to count this as a use? - // Could partial array tracking work off something else instead? - self.cfg.push_fake_read(block, source_info, FakeReadCause::ForIndex, place); - let const_ = Const::from_ty_const(*len_const, usize_ty, self.tcx); + let ty_const = if let Some((_, len_ty)) = len_const.try_to_valtree() + && len_ty != self.tcx.types.usize + { + // Bad const generics can give us a constant from the type that's + // not actually a `usize`, so in that case give an error instead. + // FIXME: It'd be nice if the type checker made sure this wasn't + // possible, instead. + let err = self.tcx.dcx().span_delayed_bug( + span, + format!( + "Array length should have already been a type error, as it's {len_ty:?}" + ), + ); + ty::Const::new_error(self.tcx, err) + } else { + // We know how long an array is, so just use that as a constant + // directly -- no locals needed. We do need one statement so + // that borrow- and initialization-checking consider it used, + // though. FIXME: Do we really *need* to count this as a use? + // Could partial array tracking work off something else instead? + self.cfg.push_fake_read(block, source_info, FakeReadCause::ForIndex, place); + *len_const + }; + + let const_ = Const::from_ty_const(ty_const, usize_ty, self.tcx); Operand::Constant(Box::new(ConstOperand { span, user_ty: None, const_ })) } ty::Slice(_elem_ty) => { diff --git a/compiler/rustc_mir_build/src/build/expr/as_rvalue.rs b/compiler/rustc_mir_build/src/builder/expr/as_rvalue.rs index c66af118453..9961c2488ef 100644 --- a/compiler/rustc_mir_build/src/build/expr/as_rvalue.rs +++ b/compiler/rustc_mir_build/src/builder/expr/as_rvalue.rs @@ -16,9 +16,9 @@ use rustc_span::source_map::Spanned; use rustc_span::{DUMMY_SP, Span}; use tracing::debug; -use crate::build::expr::as_place::PlaceBase; -use crate::build::expr::category::{Category, RvalueFunc}; -use crate::build::{BlockAnd, BlockAndExtension, Builder, NeedsTemporary}; +use crate::builder::expr::as_place::PlaceBase; +use crate::builder::expr::category::{Category, RvalueFunc}; +use crate::builder::{BlockAnd, BlockAndExtension, Builder, NeedsTemporary}; impl<'a, 'tcx> Builder<'a, 'tcx> { /// Returns an rvalue suitable for use until the end of the current diff --git a/compiler/rustc_mir_build/src/build/expr/as_temp.rs b/compiler/rustc_mir_build/src/builder/expr/as_temp.rs index 466f67b1ba4..2927f5b0c45 100644 --- a/compiler/rustc_mir_build/src/build/expr/as_temp.rs +++ b/compiler/rustc_mir_build/src/builder/expr/as_temp.rs @@ -7,8 +7,8 @@ use rustc_middle::mir::*; use rustc_middle::thir::*; use tracing::{debug, instrument}; -use crate::build::scope::DropKind; -use crate::build::{BlockAnd, BlockAndExtension, Builder}; +use crate::builder::scope::DropKind; +use crate::builder::{BlockAnd, BlockAndExtension, Builder}; impl<'a, 'tcx> Builder<'a, 'tcx> { /// Compile `expr` into a fresh temporary. This is used when building @@ -75,11 +75,11 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { LocalInfo::BlockTailTemp(tail_info) } - _ if let Some(Scope { data: ScopeData::IfThenRescope, id }) = + _ if let Some(Scope { data: ScopeData::IfThenRescope, local_id }) = temp_lifetime.temp_lifetime => { LocalInfo::IfThenRescopeTemp { - if_then: HirId { owner: this.hir_id.owner, local_id: id }, + if_then: HirId { owner: this.hir_id.owner, local_id }, } } diff --git a/compiler/rustc_mir_build/src/build/expr/category.rs b/compiler/rustc_mir_build/src/builder/expr/category.rs index e0349e3e3f6..e0349e3e3f6 100644 --- a/compiler/rustc_mir_build/src/build/expr/category.rs +++ b/compiler/rustc_mir_build/src/builder/expr/category.rs diff --git a/compiler/rustc_mir_build/src/build/expr/into.rs b/compiler/rustc_mir_build/src/builder/expr/into.rs index a3d5376dcd4..88f63d4e22c 100644 --- a/compiler/rustc_mir_build/src/build/expr/into.rs +++ b/compiler/rustc_mir_build/src/builder/expr/into.rs @@ -11,9 +11,9 @@ use rustc_middle::ty::CanonicalUserTypeAnnotation; use rustc_span::source_map::Spanned; use tracing::{debug, instrument}; -use crate::build::expr::category::{Category, RvalueFunc}; -use crate::build::matches::DeclareLetBindings; -use crate::build::{BlockAnd, BlockAndExtension, BlockFrame, Builder, NeedsTemporary}; +use crate::builder::expr::category::{Category, RvalueFunc}; +use crate::builder::matches::DeclareLetBindings; +use crate::builder::{BlockAnd, BlockAndExtension, BlockFrame, Builder, NeedsTemporary}; impl<'a, 'tcx> Builder<'a, 'tcx> { /// Compile `expr`, storing the result into `destination`, which @@ -367,14 +367,20 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { .collect() } AdtExprBase::DefaultFields(field_types) => { - itertools::zip_eq(field_names, &**field_types) - .map(|(n, ty)| match fields_map.get(&n) { + itertools::zip_eq(field_names, field_types) + .map(|(n, &ty)| match fields_map.get(&n) { Some(v) => v.clone(), None => match variant.fields[n].value { Some(def) => { - let value = Const::from_unevaluated(this.tcx, def) - .instantiate(this.tcx, args); - this.literal_operand(expr_span, value) + let value = Const::Unevaluated( + UnevaluatedConst::new(def, args), + ty, + ); + Operand::Constant(Box::new(ConstOperand { + span: expr_span, + user_ty: None, + const_: value, + })) } None => { let name = variant.fields[n].name; diff --git a/compiler/rustc_mir_build/src/build/expr/mod.rs b/compiler/rustc_mir_build/src/builder/expr/mod.rs index 3de43a3370f..3de43a3370f 100644 --- a/compiler/rustc_mir_build/src/build/expr/mod.rs +++ b/compiler/rustc_mir_build/src/builder/expr/mod.rs diff --git a/compiler/rustc_mir_build/src/build/expr/stmt.rs b/compiler/rustc_mir_build/src/builder/expr/stmt.rs index 15ee6dd014c..4ae3536d9c2 100644 --- a/compiler/rustc_mir_build/src/build/expr/stmt.rs +++ b/compiler/rustc_mir_build/src/builder/expr/stmt.rs @@ -5,8 +5,8 @@ use rustc_middle::thir::*; use rustc_span::source_map::Spanned; use tracing::debug; -use crate::build::scope::BreakableTarget; -use crate::build::{BlockAnd, BlockAndExtension, BlockFrame, Builder}; +use crate::builder::scope::BreakableTarget; +use crate::builder::{BlockAnd, BlockAndExtension, BlockFrame, Builder}; impl<'a, 'tcx> Builder<'a, 'tcx> { /// Builds a block of MIR statements to evaluate the THIR `expr`. diff --git a/compiler/rustc_mir_build/src/build/matches/match_pair.rs b/compiler/rustc_mir_build/src/builder/matches/match_pair.rs index 33fbd7b1a3f..9d59ffc88ba 100644 --- a/compiler/rustc_mir_build/src/build/matches/match_pair.rs +++ b/compiler/rustc_mir_build/src/builder/matches/match_pair.rs @@ -2,9 +2,9 @@ use rustc_middle::mir::*; use rustc_middle::thir::{self, *}; use rustc_middle::ty::{self, Ty, TypeVisitableExt}; -use crate::build::Builder; -use crate::build::expr::as_place::{PlaceBase, PlaceBuilder}; -use crate::build::matches::{FlatPat, MatchPairTree, TestCase}; +use crate::builder::Builder; +use crate::builder::expr::as_place::{PlaceBase, PlaceBuilder}; +use crate::builder::matches::{FlatPat, MatchPairTree, TestCase}; impl<'a, 'tcx> Builder<'a, 'tcx> { /// Builds and returns [`MatchPairTree`] subtrees, one for each pattern in @@ -86,7 +86,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { impl<'pat, 'tcx> MatchPairTree<'pat, 'tcx> { /// Recursively builds a match pair tree for the given pattern and its /// subpatterns. - pub(in crate::build) fn for_pattern( + pub(in crate::builder) fn for_pattern( mut place_builder: PlaceBuilder<'tcx>, pattern: &'pat Pat<'tcx>, cx: &mut Builder<'_, 'tcx>, diff --git a/compiler/rustc_mir_build/src/build/matches/mod.rs b/compiler/rustc_mir_build/src/builder/matches/mod.rs index 5791460a6b1..b944d13fb0d 100644 --- a/compiler/rustc_mir_build/src/build/matches/mod.rs +++ b/compiler/rustc_mir_build/src/builder/matches/mod.rs @@ -14,14 +14,13 @@ use rustc_middle::middle::region; use rustc_middle::mir::{self, *}; use rustc_middle::thir::{self, *}; use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Ty}; -use rustc_span::symbol::Symbol; -use rustc_span::{BytePos, Pos, Span}; +use rustc_span::{BytePos, Pos, Span, Symbol}; use tracing::{debug, instrument}; -use crate::build::ForGuard::{self, OutsideGuard, RefWithinGuard}; -use crate::build::expr::as_place::PlaceBuilder; -use crate::build::scope::DropKind; -use crate::build::{ +use crate::builder::ForGuard::{self, OutsideGuard, RefWithinGuard}; +use crate::builder::expr::as_place::PlaceBuilder; +use crate::builder::scope::DropKind; +use crate::builder::{ BlockAnd, BlockAndExtension, Builder, GuardFrame, GuardFrameLocal, LocalsForNode, }; diff --git a/compiler/rustc_mir_build/src/build/matches/simplify.rs b/compiler/rustc_mir_build/src/builder/matches/simplify.rs index 5b402604395..ebaed1e431b 100644 --- a/compiler/rustc_mir_build/src/build/matches/simplify.rs +++ b/compiler/rustc_mir_build/src/builder/matches/simplify.rs @@ -16,8 +16,8 @@ use std::mem; use tracing::{debug, instrument}; -use crate::build::Builder; -use crate::build::matches::{MatchPairTree, PatternExtraData, TestCase}; +use crate::builder::Builder; +use crate::builder::matches::{MatchPairTree, PatternExtraData, TestCase}; impl<'a, 'tcx> Builder<'a, 'tcx> { /// Simplify a list of match pairs so they all require a test. Stores relevant bindings and diff --git a/compiler/rustc_mir_build/src/build/matches/test.rs b/compiler/rustc_mir_build/src/builder/matches/test.rs index 4f7bbc4ce3e..8cca84d7fcc 100644 --- a/compiler/rustc_mir_build/src/build/matches/test.rs +++ b/compiler/rustc_mir_build/src/builder/matches/test.rs @@ -16,12 +16,11 @@ use rustc_middle::ty::{self, GenericArg, Ty, TyCtxt}; use rustc_middle::{bug, span_bug}; use rustc_span::def_id::DefId; use rustc_span::source_map::Spanned; -use rustc_span::symbol::{Symbol, sym}; -use rustc_span::{DUMMY_SP, Span}; +use rustc_span::{DUMMY_SP, Span, Symbol, sym}; use tracing::{debug, instrument}; -use crate::build::Builder; -use crate::build::matches::{Candidate, MatchPairTree, Test, TestBranch, TestCase, TestKind}; +use crate::builder::Builder; +use crate::builder::matches::{Candidate, MatchPairTree, Test, TestBranch, TestCase, TestKind}; impl<'a, 'tcx> Builder<'a, 'tcx> { /// Identifies what test is needed to decide if `match_pair` is applicable. diff --git a/compiler/rustc_mir_build/src/build/matches/util.rs b/compiler/rustc_mir_build/src/builder/matches/util.rs index 555684ded81..1bd399e511b 100644 --- a/compiler/rustc_mir_build/src/build/matches/util.rs +++ b/compiler/rustc_mir_build/src/builder/matches/util.rs @@ -4,9 +4,9 @@ use rustc_middle::ty::Ty; use rustc_span::Span; use tracing::debug; -use crate::build::Builder; -use crate::build::expr::as_place::PlaceBase; -use crate::build::matches::{Binding, Candidate, FlatPat, MatchPairTree, TestCase}; +use crate::builder::Builder; +use crate::builder::expr::as_place::PlaceBase; +use crate::builder::matches::{Binding, Candidate, FlatPat, MatchPairTree, TestCase}; impl<'a, 'tcx> Builder<'a, 'tcx> { /// Creates a false edge to `imaginary_target` and a real edge to diff --git a/compiler/rustc_mir_build/src/build/misc.rs b/compiler/rustc_mir_build/src/builder/misc.rs index a14dcad6573..9ea56a9574f 100644 --- a/compiler/rustc_mir_build/src/build/misc.rs +++ b/compiler/rustc_mir_build/src/builder/misc.rs @@ -7,7 +7,7 @@ use rustc_span::Span; use rustc_trait_selection::infer::InferCtxtExt; use tracing::debug; -use crate::build::Builder; +use crate::builder::Builder; impl<'a, 'tcx> Builder<'a, 'tcx> { /// Adds a new temporary value of type `ty` storing the result of @@ -56,10 +56,10 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { pub(crate) fn consume_by_copy_or_move(&self, place: Place<'tcx>) -> Operand<'tcx> { let tcx = self.tcx; let ty = place.ty(&self.local_decls, tcx).ty; - if !self.infcx.type_is_copy_modulo_regions(self.param_env, ty) { - Operand::Move(place) - } else { + if self.infcx.type_is_copy_modulo_regions(self.param_env, ty) { Operand::Copy(place) + } else { + Operand::Move(place) } } } diff --git a/compiler/rustc_mir_build/src/build/mod.rs b/compiler/rustc_mir_build/src/builder/mod.rs index f43c29d8f5d..0a60899248a 100644 --- a/compiler/rustc_mir_build/src/build/mod.rs +++ b/compiler/rustc_mir_build/src/builder/mod.rs @@ -1,3 +1,8 @@ +//! This module used to be named `build`, but that was causing GitHub's +//! "Go to file" feature to silently ignore all files in the module, probably +//! because it assumes that "build" is a build-output directory. +//! See <https://github.com/rust-lang/rust/pull/134365>. + use itertools::Itertools; use rustc_abi::{ExternAbi, FieldIdx}; use rustc_apfloat::Float; @@ -19,12 +24,11 @@ use rustc_middle::query::TyCtxtAt; use rustc_middle::thir::{self, ExprId, LintLevel, LocalVarId, Param, ParamId, PatKind, Thir}; use rustc_middle::ty::{self, ScalarInt, Ty, TyCtxt, TypeVisitableExt, TypingMode}; use rustc_middle::{bug, span_bug}; -use rustc_span::symbol::sym; -use rustc_span::{Span, Symbol}; +use rustc_span::{Span, Symbol, sym}; use super::lints; -use crate::build::expr::as_place::PlaceBuilder; -use crate::build::scope::DropKind; +use crate::builder::expr::as_place::PlaceBuilder; +use crate::builder::scope::DropKind; pub(crate) fn closure_saved_names_of_captured_variables<'tcx>( tcx: TyCtxt<'tcx>, @@ -527,9 +531,9 @@ fn construct_fn<'tcx>( ); let call_site_scope = - region::Scope { id: body.id().hir_id.local_id, data: region::ScopeData::CallSite }; + region::Scope { local_id: body.id().hir_id.local_id, data: region::ScopeData::CallSite }; let arg_scope = - region::Scope { id: body.id().hir_id.local_id, data: region::ScopeData::Arguments }; + region::Scope { local_id: body.id().hir_id.local_id, data: region::ScopeData::Arguments }; let source_info = builder.source_info(span); let call_site_s = (call_site_scope, source_info); let _: BlockAnd<()> = builder.in_scope(call_site_s, LintLevel::Inherited, |builder| { diff --git a/compiler/rustc_mir_build/src/build/scope.rs b/compiler/rustc_mir_build/src/builder/scope.rs index 636e47b7ad2..35c98037827 100644 --- a/compiler/rustc_mir_build/src/build/scope.rs +++ b/compiler/rustc_mir_build/src/builder/scope.rs @@ -89,13 +89,13 @@ use rustc_index::{IndexSlice, IndexVec}; use rustc_middle::middle::region; use rustc_middle::mir::*; use rustc_middle::thir::{ExprId, LintLevel}; -use rustc_middle::{bug, span_bug, ty}; +use rustc_middle::{bug, span_bug}; use rustc_session::lint::Level; use rustc_span::source_map::Spanned; use rustc_span::{DUMMY_SP, Span}; use tracing::{debug, instrument}; -use crate::build::{BlockAnd, BlockAndExtension, BlockFrame, Builder, CFG}; +use crate::builder::{BlockAnd, BlockAndExtension, BlockFrame, Builder, CFG}; #[derive(Debug)] pub(crate) struct Scopes<'tcx> { @@ -151,15 +151,13 @@ struct DropData { /// Whether this is a value Drop or a StorageDead. kind: DropKind, - - /// Whether this is a backwards-incompatible drop lint - backwards_incompatible_lint: bool, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub(crate) enum DropKind { Value, Storage, + ForLint, } #[derive(Debug)] @@ -248,7 +246,7 @@ impl Scope { /// use of optimizations in the MIR coroutine transform. fn needs_cleanup(&self) -> bool { self.drops.iter().any(|drop| match drop.kind { - DropKind::Value => true, + DropKind::Value | DropKind::ForLint => true, DropKind::Storage => false, }) } @@ -277,12 +275,8 @@ impl DropTree { // represents the block in the tree that should be jumped to once all // of the required drops have been performed. let fake_source_info = SourceInfo::outermost(DUMMY_SP); - let fake_data = DropData { - source_info: fake_source_info, - local: Local::MAX, - kind: DropKind::Storage, - backwards_incompatible_lint: false, - }; + let fake_data = + DropData { source_info: fake_source_info, local: Local::MAX, kind: DropKind::Storage }; let drops = IndexVec::from_raw(vec![DropNode { data: fake_data, next: DropIdx::MAX }]); Self { drops, entry_points: Vec::new(), existing_drops_map: FxHashMap::default() } } @@ -411,6 +405,27 @@ impl DropTree { }; cfg.terminate(block, drop_node.data.source_info, terminator); } + DropKind::ForLint => { + let stmt = Statement { + source_info: drop_node.data.source_info, + kind: StatementKind::BackwardIncompatibleDropHint { + place: Box::new(drop_node.data.local.into()), + reason: BackwardIncompatibleDropReason::Edition2024, + }, + }; + cfg.push(block, stmt); + let target = blocks[drop_node.next].unwrap(); + if target != block { + // Diagnostics don't use this `Span` but debuginfo + // might. Since we don't want breakpoints to be placed + // here, especially when this is on an unwind path, we + // use `DUMMY_SP`. + let source_info = + SourceInfo { span: DUMMY_SP, ..drop_node.data.source_info }; + let terminator = TerminatorKind::Goto { target }; + cfg.terminate(block, source_info, terminator); + } + } // Root nodes don't correspond to a drop. DropKind::Storage if drop_idx == ROOT_NODE => {} DropKind::Storage => { @@ -770,12 +785,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let local = place.as_local().unwrap_or_else(|| bug!("projection in tail call args")); - Some(DropData { - source_info, - local, - kind: DropKind::Value, - backwards_incompatible_lint: false, - }) + Some(DropData { source_info, local, kind: DropKind::Value }) } Operand::Constant(_) => None, }) @@ -822,6 +832,15 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { }); block = next; } + DropKind::ForLint => { + self.cfg.push(block, Statement { + source_info, + kind: StatementKind::BackwardIncompatibleDropHint { + place: Box::new(local.into()), + reason: BackwardIncompatibleDropReason::Edition2024, + }, + }); + } DropKind::Storage => { // Only temps and vars need their storage dead. assert!(local.index() > self.arg_count); @@ -1021,7 +1040,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { drop_kind: DropKind, ) { let needs_drop = match drop_kind { - DropKind::Value => { + DropKind::Value | DropKind::ForLint => { if !self.local_decls[local].ty.needs_drop(self.tcx, self.typing_env()) { return; } @@ -1101,7 +1120,6 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { source_info: SourceInfo { span: scope_end, scope: scope.source_scope }, local, kind: drop_kind, - backwards_incompatible_lint: false, }); return; @@ -1119,10 +1137,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { region_scope: region::Scope, local: Local, ) { - if !self.local_decls[local].ty.has_significant_drop(self.tcx, ty::TypingEnv { - typing_mode: ty::TypingMode::non_body_analysis(), - param_env: self.param_env, - }) { + if !self.local_decls[local].ty.has_significant_drop(self.tcx, self.typing_env()) { return; } for scope in self.scopes.scopes.iter_mut().rev() { @@ -1135,8 +1150,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { scope.drops.push(DropData { source_info: SourceInfo { span: scope_end, scope: scope.source_scope }, local, - kind: DropKind::Value, - backwards_incompatible_lint: true, + kind: DropKind::ForLint, }); return; @@ -1379,12 +1393,23 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } /// Builds drops for `pop_scope` and `leave_top_scope`. +/// +/// # Parameters +/// +/// * `unwind_drops`, the drop tree data structure storing what needs to be cleaned up if unwind occurs +/// * `scope`, describes the drops that will occur on exiting the scope in regular execution +/// * `block`, the block to branch to once drops are complete (assuming no unwind occurs) +/// * `unwind_to`, describes the drops that would occur at this point in the code if a +/// panic occurred (a subset of the drops in `scope`, since we sometimes elide StorageDead and other +/// instructions on unwinding) +/// * `storage_dead_on_unwind`, if true, then we should emit `StorageDead` even when unwinding +/// * `arg_count`, number of MIR local variables corresponding to fn arguments (used to assert that we don't drop those) fn build_scope_drops<'tcx>( cfg: &mut CFG<'tcx>, unwind_drops: &mut DropTree, scope: &Scope, - mut block: BasicBlock, - mut unwind_to: DropIdx, + block: BasicBlock, + unwind_to: DropIdx, storage_dead_on_unwind: bool, arg_count: usize, ) -> BlockAnd<()> { @@ -1409,6 +1434,18 @@ fn build_scope_drops<'tcx>( // drops for the unwind path should have already been generated by // `diverge_cleanup_gen`. + // `unwind_to` indicates what needs to be dropped should unwinding occur. + // This is a subset of what needs to be dropped when exiting the scope. + // As we unwind the scope, we will also move `unwind_to` backwards to match, + // so that we can use it should a destructor panic. + let mut unwind_to = unwind_to; + + // The block that we should jump to after drops complete. We start by building the final drop (`drops[n]` + // in the diagram above) and then build the drops (e.g., `drop[1]`, `drop[0]`) that come before it. + // block begins as the successor of `drops[n]` and then becomes `drops[n]` so that `drops[n-1]` + // will branch to `drops[n]`. + let mut block = block; + for drop_data in scope.drops.iter().rev() { let source_info = drop_data.source_info; let local = drop_data.local; @@ -1418,6 +1455,9 @@ fn build_scope_drops<'tcx>( // `unwind_to` should drop the value that we're about to // schedule. If dropping this value panics, then we continue // with the *next* value on the unwind path. + // + // We adjust this BEFORE we create the drop (e.g., `drops[n]`) + // because `drops[n]` should unwind to `drops[n-1]`. debug_assert_eq!(unwind_drops.drops[unwind_to].data.local, drop_data.local); debug_assert_eq!(unwind_drops.drops[unwind_to].data.kind, drop_data.kind); unwind_to = unwind_drops.drops[unwind_to].next; @@ -1430,27 +1470,50 @@ fn build_scope_drops<'tcx>( continue; } - if drop_data.backwards_incompatible_lint { - cfg.push(block, Statement { - source_info, - kind: StatementKind::BackwardIncompatibleDropHint { - place: Box::new(local.into()), - reason: BackwardIncompatibleDropReason::Edition2024, - }, - }); - } else { - unwind_drops.add_entry_point(block, unwind_to); - let next = cfg.start_new_block(); - cfg.terminate(block, source_info, TerminatorKind::Drop { - place: local.into(), - target: next, - unwind: UnwindAction::Continue, - replace: false, - }); - block = next; + unwind_drops.add_entry_point(block, unwind_to); + let next = cfg.start_new_block(); + cfg.terminate(block, source_info, TerminatorKind::Drop { + place: local.into(), + target: next, + unwind: UnwindAction::Continue, + replace: false, + }); + block = next; + } + DropKind::ForLint => { + // As in the `DropKind::Storage` case below: + // normally lint-related drops are not emitted for unwind, + // so we can just leave `unwind_to` unmodified, but in some + // cases we emit things ALSO on the unwind path, so we need to adjust + // `unwind_to` in that case. + if storage_dead_on_unwind { + debug_assert_eq!(unwind_drops.drops[unwind_to].data.local, drop_data.local); + debug_assert_eq!(unwind_drops.drops[unwind_to].data.kind, drop_data.kind); + unwind_to = unwind_drops.drops[unwind_to].next; } + + // If the operand has been moved, and we are not on an unwind + // path, then don't generate the drop. (We only take this into + // account for non-unwind paths so as not to disturb the + // caching mechanism.) + if scope.moved_locals.iter().any(|&o| o == local) { + continue; + } + + cfg.push(block, Statement { + source_info, + kind: StatementKind::BackwardIncompatibleDropHint { + place: Box::new(local.into()), + reason: BackwardIncompatibleDropReason::Edition2024, + }, + }); } DropKind::Storage => { + // Ordinarily, storage-dead nodes are not emitted on unwind, so we don't + // need to adjust `unwind_to` on this path. However, in some specific cases + // we *do* emit storage-dead nodes on the unwind path, and in that case now that + // the storage-dead has completed, we need to adjust the `unwind_to` pointer + // so that any future drops we emit will not register storage-dead. if storage_dead_on_unwind { debug_assert_eq!(unwind_drops.drops[unwind_to].data.local, drop_data.local); debug_assert_eq!(unwind_drops.drops[unwind_to].data.kind, drop_data.kind); @@ -1489,7 +1552,7 @@ impl<'a, 'tcx: 'a> Builder<'a, 'tcx> { let mut unwind_indices = IndexVec::from_elem_n(unwind_target, 1); for (drop_idx, drop_node) in drops.drops.iter_enumerated().skip(1) { match drop_node.data.kind { - DropKind::Storage => { + DropKind::Storage | DropKind::ForLint => { if is_coroutine { let unwind_drop = self .scopes diff --git a/compiler/rustc_mir_build/src/check_unsafety.rs b/compiler/rustc_mir_build/src/check_unsafety.rs index f37b3f977fa..f7071eb139f 100644 --- a/compiler/rustc_mir_build/src/check_unsafety.rs +++ b/compiler/rustc_mir_build/src/check_unsafety.rs @@ -4,7 +4,7 @@ use std::ops::Bound; use rustc_errors::DiagArgValue; use rustc_hir::def::DefKind; -use rustc_hir::{self as hir, BindingMode, ByRef, HirId, Mutability, Safety}; +use rustc_hir::{self as hir, BindingMode, ByRef, HirId, Mutability}; use rustc_middle::middle::codegen_fn_attrs::TargetFeature; use rustc_middle::mir::BorrowKind; use rustc_middle::span_bug; @@ -15,10 +15,9 @@ use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_session::lint::Level; use rustc_session::lint::builtin::{DEPRECATED_SAFE_2024, UNSAFE_OP_IN_UNSAFE_FN, UNUSED_UNSAFE}; use rustc_span::def_id::{DefId, LocalDefId}; -use rustc_span::symbol::Symbol; -use rustc_span::{Span, sym}; +use rustc_span::{Span, Symbol, sym}; -use crate::build::ExprCategory; +use crate::builder::ExprCategory; use crate::errors::*; struct UnsafetyVisitor<'a, 'tcx> { @@ -342,7 +341,7 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> { PatKind::Leaf { subpatterns, .. } => { if let ty::Adt(adt_def, ..) = pat.ty.kind() { for pat in subpatterns { - if adt_def.non_enum_variant().fields[pat.field].safety == Safety::Unsafe { + if adt_def.non_enum_variant().fields[pat.field].safety.is_unsafe() { self.requires_unsafe(pat.pattern.span, UseOfUnsafeField); } } @@ -367,7 +366,7 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> { PatKind::Variant { adt_def, args: _, variant_index, subpatterns } => { for pat in subpatterns { let field = &pat.field; - if adt_def.variant(*variant_index).fields[*field].safety == Safety::Unsafe { + if adt_def.variant(*variant_index).fields[*field].safety.is_unsafe() { self.requires_unsafe(pat.pattern.span, UseOfUnsafeField); } } @@ -479,7 +478,7 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> { return; // don't visit the whole expression } ExprKind::Call { fun, ty: _, args: _, from_hir_call: _, fn_span: _ } => { - if self.thir[fun].ty.fn_sig(self.tcx).safety() == hir::Safety::Unsafe { + if self.thir[fun].ty.fn_sig(self.tcx).safety().is_unsafe() { let func_id = if let ty::FnDef(func_id, _) = self.thir[fun].ty.kind() { Some(*func_id) } else { @@ -623,7 +622,7 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> { ExprKind::Field { lhs, variant_index, name } => { let lhs = &self.thir[lhs]; if let ty::Adt(adt_def, _) = lhs.ty.kind() { - if adt_def.variant(variant_index).fields[name].safety == Safety::Unsafe { + if adt_def.variant(variant_index).fields[name].safety.is_unsafe() { self.requires_unsafe(expr.span, UseOfUnsafeField); } else if adt_def.is_union() { if let Some(assigned_ty) = self.assignment_info { @@ -1112,11 +1111,7 @@ pub(crate) fn check_unsafety(tcx: TyCtxt<'_>, def: LocalDefId) { let hir_id = tcx.local_def_id_to_hir_id(def); let safety_context = tcx.hir().fn_sig_by_hir_id(hir_id).map_or(SafetyContext::Safe, |fn_sig| { - if fn_sig.header.safety == hir::Safety::Unsafe { - SafetyContext::UnsafeFn - } else { - SafetyContext::Safe - } + if fn_sig.header.safety.is_unsafe() { SafetyContext::UnsafeFn } else { SafetyContext::Safe } }); let body_target_features = &tcx.body_codegen_attrs(def.to_def_id()).target_features; let mut warnings = Vec::new(); diff --git a/compiler/rustc_mir_build/src/errors.rs b/compiler/rustc_mir_build/src/errors.rs index 3632da943e1..be5f8bdffb5 100644 --- a/compiler/rustc_mir_build/src/errors.rs +++ b/compiler/rustc_mir_build/src/errors.rs @@ -1,14 +1,13 @@ use rustc_errors::codes::*; use rustc_errors::{ Applicability, Diag, DiagArgValue, DiagCtxtHandle, Diagnostic, EmissionGuarantee, Level, - MultiSpan, SubdiagMessageOp, Subdiagnostic, + MultiSpan, SubdiagMessageOp, Subdiagnostic, pluralize, }; use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; use rustc_middle::ty::{self, Ty}; use rustc_pattern_analysis::errors::Uncovered; use rustc_pattern_analysis::rustc::RustcPatCtxt; -use rustc_span::Span; -use rustc_span::symbol::Symbol; +use rustc_span::{Span, Symbol}; use crate::fluent_generated as fluent; @@ -1089,18 +1088,20 @@ pub(crate) enum RustcBoxAttrReason { #[derive(LintDiagnostic)] #[diag(mir_build_rust_2024_incompatible_pat)] -pub(crate) struct Rust2024IncompatiblePat { +pub(crate) struct Rust2024IncompatiblePat<'a> { #[subdiagnostic] - pub(crate) sugg: Rust2024IncompatiblePatSugg, + pub(crate) sugg: Rust2024IncompatiblePatSugg<'a>, } -pub(crate) struct Rust2024IncompatiblePatSugg { +pub(crate) struct Rust2024IncompatiblePatSugg<'a> { pub(crate) suggestion: Vec<(Span, String)>, - /// Whether the incompatibility is a hard error because a relevant span is in edition 2024. - pub(crate) is_hard_error: bool, + pub(crate) ref_pattern_count: usize, + pub(crate) binding_mode_count: usize, + /// Labeled spans for subpatterns invalid in Rust 2024. + pub(crate) labels: &'a [(Span, String)], } -impl Subdiagnostic for Rust2024IncompatiblePatSugg { +impl<'a> Subdiagnostic for Rust2024IncompatiblePatSugg<'a> { fn add_to_diag_with<G: EmissionGuarantee, F: SubdiagMessageOp<G>>( self, diag: &mut Diag<'_, G>, @@ -1112,6 +1113,16 @@ impl Subdiagnostic for Rust2024IncompatiblePatSugg { } else { Applicability::MaybeIncorrect }; - diag.multipart_suggestion("desugar the match ergonomics", self.suggestion, applicability); + let plural_derefs = pluralize!(self.ref_pattern_count); + let and_modes = if self.binding_mode_count > 0 { + format!(" and variable binding mode{}", pluralize!(self.binding_mode_count)) + } else { + String::new() + }; + diag.multipart_suggestion_verbose( + format!("make the implied reference pattern{plural_derefs}{and_modes} explicit"), + self.suggestion, + applicability, + ); } } diff --git a/compiler/rustc_mir_build/src/lib.rs b/compiler/rustc_mir_build/src/lib.rs index 833e5019865..467725841dc 100644 --- a/compiler/rustc_mir_build/src/lib.rs +++ b/compiler/rustc_mir_build/src/lib.rs @@ -11,7 +11,10 @@ #![warn(unreachable_pub)] // tidy-alphabetical-end -mod build; +// The `builder` module used to be named `build`, but that was causing GitHub's +// "Go to file" feature to silently ignore all files in the module, probably +// because it assumes that "build" is a build-output directory. See #134365. +mod builder; mod check_tail_calls; mod check_unsafety; mod errors; @@ -25,9 +28,9 @@ rustc_fluent_macro::fluent_messages! { "../messages.ftl" } pub fn provide(providers: &mut Providers) { providers.check_match = thir::pattern::check_match; providers.lit_to_const = thir::constant::lit_to_const; - providers.hooks.build_mir = build::mir_build; + providers.hooks.build_mir = builder::mir_build; providers.closure_saved_names_of_captured_variables = - build::closure_saved_names_of_captured_variables; + builder::closure_saved_names_of_captured_variables; providers.check_unsafety = check_unsafety::check_unsafety; providers.check_tail_calls = check_tail_calls::check_tail_calls; providers.thir_body = thir::cx::thir_body; diff --git a/compiler/rustc_mir_build/src/thir/constant.rs b/compiler/rustc_mir_build/src/thir/constant.rs index 30b6718683b..ce1c635d1b9 100644 --- a/compiler/rustc_mir_build/src/thir/constant.rs +++ b/compiler/rustc_mir_build/src/thir/constant.rs @@ -5,7 +5,7 @@ use rustc_middle::mir::interpret::{LitToConstError, LitToConstInput}; use rustc_middle::ty::{self, ScalarInt, TyCtxt, TypeVisitableExt as _}; use tracing::trace; -use crate::build::parse_float_into_scalar; +use crate::builder::parse_float_into_scalar; pub(crate) fn lit_to_const<'tcx>( tcx: TyCtxt<'tcx>, diff --git a/compiler/rustc_mir_build/src/thir/cx/block.rs b/compiler/rustc_mir_build/src/thir/cx/block.rs index 069c2e7881e..c9df027687a 100644 --- a/compiler/rustc_mir_build/src/thir/cx/block.rs +++ b/compiler/rustc_mir_build/src/thir/cx/block.rs @@ -16,7 +16,7 @@ impl<'tcx> Cx<'tcx> { let block = Block { targeted_by_break: block.targeted_by_break, region_scope: region::Scope { - id: block.hir_id.local_id, + local_id: block.hir_id.local_id, data: region::ScopeData::Node, }, span: block.span, @@ -51,7 +51,7 @@ impl<'tcx> Cx<'tcx> { let stmt = Stmt { kind: StmtKind::Expr { scope: region::Scope { - id: hir_id.local_id, + local_id: hir_id.local_id, data: region::ScopeData::Node, }, expr: self.mirror_expr(expr), @@ -65,7 +65,7 @@ impl<'tcx> Cx<'tcx> { } hir::StmtKind::Let(local) => { let remainder_scope = region::Scope { - id: block_id, + local_id: block_id, data: region::ScopeData::Remainder(region::FirstStatementIndex::new( index, )), @@ -108,7 +108,7 @@ impl<'tcx> Cx<'tcx> { kind: StmtKind::Let { remainder_scope, init_scope: region::Scope { - id: hir_id.local_id, + local_id: hir_id.local_id, data: region::ScopeData::Node, }, pattern, diff --git a/compiler/rustc_mir_build/src/thir/cx/expr.rs b/compiler/rustc_mir_build/src/thir/cx/expr.rs index 6770e562d50..0338ac674e5 100644 --- a/compiler/rustc_mir_build/src/thir/cx/expr.rs +++ b/compiler/rustc_mir_build/src/thir/cx/expr.rs @@ -25,6 +25,14 @@ use crate::thir::cx::Cx; use crate::thir::util::UserAnnotatedTyHelpers; impl<'tcx> Cx<'tcx> { + /// Create a THIR expression for the given HIR expression. This expands all + /// adjustments and directly adds the type information from the + /// `typeck_results`. See the [dev-guide] for more details. + /// + /// (The term "mirror" in this case does not refer to "flipped" or + /// "reversed".) + /// + /// [dev-guide]: https://rustc-dev-guide.rust-lang.org/thir.html pub(crate) fn mirror_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) -> ExprId { // `mirror_expr` is recursing very deep. Make sure the stack doesn't overflow. ensure_sufficient_stack(|| self.mirror_expr_inner(expr)) @@ -37,7 +45,7 @@ impl<'tcx> Cx<'tcx> { #[instrument(level = "trace", skip(self, hir_expr))] pub(super) fn mirror_expr_inner(&mut self, hir_expr: &'tcx hir::Expr<'tcx>) -> ExprId { let expr_scope = - region::Scope { id: hir_expr.hir_id.local_id, data: region::ScopeData::Node }; + region::Scope { local_id: hir_expr.hir_id.local_id, data: region::ScopeData::Node }; trace!(?hir_expr.hir_id, ?hir_expr.span); @@ -806,14 +814,20 @@ impl<'tcx> Cx<'tcx> { hir::ExprKind::Become(call) => ExprKind::Become { value: self.mirror_expr(call) }, hir::ExprKind::Break(dest, ref value) => match dest.target_id { Ok(target_id) => ExprKind::Break { - label: region::Scope { id: target_id.local_id, data: region::ScopeData::Node }, + label: region::Scope { + local_id: target_id.local_id, + data: region::ScopeData::Node, + }, value: value.map(|value| self.mirror_expr(value)), }, Err(err) => bug!("invalid loop id for break: {}", err), }, hir::ExprKind::Continue(dest) => match dest.target_id { Ok(loop_id) => ExprKind::Continue { - label: region::Scope { id: loop_id.local_id, data: region::ScopeData::Node }, + label: region::Scope { + local_id: loop_id.local_id, + data: region::ScopeData::Node, + }, }, Err(err) => bug!("invalid loop id for continue: {}", err), }, @@ -823,7 +837,7 @@ impl<'tcx> Cx<'tcx> { }, hir::ExprKind::If(cond, then, else_opt) => ExprKind::If { if_then_scope: region::Scope { - id: then.hir_id.local_id, + local_id: then.hir_id.local_id, data: { if expr.span.at_least_rust_2024() { region::ScopeData::IfThenRescope @@ -1013,7 +1027,7 @@ impl<'tcx> Cx<'tcx> { guard: arm.guard.as_ref().map(|g| self.mirror_expr(g)), body: self.mirror_expr(arm.body), lint_level: LintLevel::Explicit(arm.hir_id), - scope: region::Scope { id: arm.hir_id.local_id, data: region::ScopeData::Node }, + scope: region::Scope { local_id: arm.hir_id.local_id, data: region::ScopeData::Node }, span: arm.span, }; self.thir.arms.push(arm) @@ -1189,7 +1203,7 @@ impl<'tcx> Cx<'tcx> { .temporary_scope(self.region_scope_tree, closure_expr.hir_id.local_id); let var_ty = place.base_ty; - // The result of capture analysis in `rustc_hir_analysis/check/upvar.rs`represents a captured path + // The result of capture analysis in `rustc_hir_typeck/src/upvar.rs` represents a captured path // as it's seen for use within the closure and not at the time of closure creation. // // That is we see expect to see it start from a captured upvar and not something that is local diff --git a/compiler/rustc_mir_build/src/thir/pattern/mod.rs b/compiler/rustc_mir_build/src/thir/pattern/mod.rs index 2dbc8b7b573..bdf243c87b6 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/mod.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/mod.rs @@ -6,6 +6,7 @@ mod const_to_pat; use std::cmp::Ordering; use rustc_abi::{FieldIdx, Integer}; +use rustc_errors::MultiSpan; use rustc_errors::codes::*; use rustc_hir::def::{CtorOf, DefKind, Res}; use rustc_hir::pat_util::EnumerateAndAdjustIterator; @@ -34,7 +35,7 @@ struct PatCtxt<'a, 'tcx> { typeck_results: &'a ty::TypeckResults<'tcx>, /// Used by the Rust 2024 migration lint. - rust_2024_migration_suggestion: Option<Rust2024IncompatiblePatSugg>, + rust_2024_migration_suggestion: Option<Rust2024IncompatiblePatSugg<'a>>, } pub(super) fn pat_from_hir<'a, 'tcx>( @@ -50,24 +51,36 @@ pub(super) fn pat_from_hir<'a, 'tcx>( rust_2024_migration_suggestion: typeck_results .rust_2024_migration_desugared_pats() .get(pat.hir_id) - .map(|&is_hard_error| Rust2024IncompatiblePatSugg { + .map(|labels| Rust2024IncompatiblePatSugg { suggestion: Vec::new(), - is_hard_error, + ref_pattern_count: 0, + binding_mode_count: 0, + labels: labels.as_slice(), }), }; let result = pcx.lower_pattern(pat); debug!("pat_from_hir({:?}) = {:?}", pat, result); if let Some(sugg) = pcx.rust_2024_migration_suggestion { - if sugg.is_hard_error { + let mut spans = MultiSpan::from_spans(sugg.labels.iter().map(|(span, _)| *span).collect()); + for (span, label) in sugg.labels { + spans.push_span_label(*span, label.clone()); + } + // If a relevant span is from at least edition 2024, this is a hard error. + let is_hard_error = spans.primary_spans().iter().any(|span| span.at_least_rust_2024()); + if is_hard_error { let mut err = - tcx.dcx().struct_span_err(pat.span, fluent::mir_build_rust_2024_incompatible_pat); + tcx.dcx().struct_span_err(spans, fluent::mir_build_rust_2024_incompatible_pat); + if let Some(info) = lint::builtin::RUST_2024_INCOMPATIBLE_PAT.future_incompatible { + // provide the same reference link as the lint + err.note(format!("for more information, see {}", info.reference)); + } err.subdiagnostic(sugg); err.emit(); } else { tcx.emit_node_span_lint( lint::builtin::RUST_2024_INCOMPATIBLE_PAT, pat.hir_id, - pat.span, + spans, Rust2024IncompatiblePat { sugg }, ); } @@ -133,6 +146,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { }) .collect(); s.suggestion.push((pat.span.shrink_to_lo(), suggestion_str)); + s.ref_pattern_count += adjustments.len(); }; adjusted_pat @@ -371,7 +385,8 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { s.suggestion.push(( pat.span.with_lo(ident.span.lo()).shrink_to_lo(), sugg_str.to_owned(), - )) + )); + s.binding_mode_count += 1; } // A ref x pattern is the same node used for x, and as such it has |
