Skip to content

Commit 214d5c9

Browse files
committed
Auto merge of rust-lang#134523 - dingxiangfei2009:issue-130836-attempt-2, r=<try>
Run borrowck tests on BIDs and emit tail-expr-drop-order lints for violations Fix rust-lang#132861 r? `@nikomatsakis` cc `@compiler-errors` This patch enlarges the scope where the `tail-expr-drop-order` lint applies, so that all locals involved in tail expressions are inspected. This is necessary to run borrow-checking to capture the cases where it used to compile under Edition 2021 but is not going to pass borrow-checking from Edition 2024 onwards. The way it works is to inspect each BID against the set of borrows that are still live. If the local involved in BID has a borrow index which happens to be live as well at the location of this BID statement, in the future this will be a borrow-checking violation. The lint will fire in this case.
2 parents dcfa38f + 4749325 commit 214d5c9

12 files changed

+252
-37
lines changed

Diff for: compiler/rustc_borrowck/messages.ftl

+3
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,9 @@ borrowck_suggest_create_fresh_reborrow =
213213
borrowck_suggest_iterate_over_slice =
214214
consider iterating over a slice of the `{$ty}`'s content to avoid moving into the `for` loop
215215
216+
borrowck_tail_expr_drop_order = a temporary value will be dropped here before the execution exits the block in Edition 2024, which will raise borrow checking error
217+
.label = consider using a `let` binding to create a longer lived value; or replacing the `{"{"} .. {"}"}` block with curly brackets `( .. )`; or folding the rest of the expression into the surrounding `unsafe {"{"} .. {"}"}`
218+
216219
borrowck_ty_no_impl_copy =
217220
{$is_partial_move ->
218221
[true] partial move

Diff for: compiler/rustc_borrowck/src/lib.rs

+73-15
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
#![warn(unreachable_pub)]
1616
// tidy-alphabetical-end
1717

18+
use std::borrow::Cow;
1819
use std::cell::RefCell;
1920
use std::marker::PhantomData;
2021
use std::ops::Deref;
@@ -23,6 +24,7 @@ use rustc_abi::FieldIdx;
2324
use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
2425
use rustc_data_structures::graph::dominators::Dominators;
2526
use rustc_hir as hir;
27+
use rustc_hir::CRATE_HIR_ID;
2628
use rustc_hir::def_id::LocalDefId;
2729
use rustc_index::bit_set::{BitSet, MixedBitSet};
2830
use rustc_index::{IndexSlice, IndexVec};
@@ -42,7 +44,7 @@ use rustc_mir_dataflow::move_paths::{
4244
InitIndex, InitLocation, LookupResult, MoveData, MovePathIndex,
4345
};
4446
use rustc_mir_dataflow::{Analysis, EntryStates, Results, ResultsVisitor, visit_results};
45-
use rustc_session::lint::builtin::UNUSED_MUT;
47+
use rustc_session::lint::builtin::{TAIL_EXPR_DROP_ORDER, UNUSED_MUT};
4648
use rustc_span::{Span, Symbol};
4749
use smallvec::SmallVec;
4850
use tracing::{debug, instrument};
@@ -636,9 +638,11 @@ impl<'a, 'tcx> ResultsVisitor<'a, 'tcx, Borrowck<'a, 'tcx>> for MirBorrowckCtxt<
636638
| StatementKind::Coverage(..)
637639
// These do not actually affect borrowck
638640
| StatementKind::ConstEvalCounter
639-
// This do not affect borrowck
640-
| StatementKind::BackwardIncompatibleDropHint { .. }
641641
| StatementKind::StorageLive(..) => {}
642+
// This does not affect borrowck
643+
StatementKind::BackwardIncompatibleDropHint { place, reason: BackwardIncompatibleDropReason::Edition2024 } => {
644+
self.check_backward_incompatible_drop(location, (**place, span), state);
645+
}
642646
StatementKind::StorageDead(local) => {
643647
self.access_place(
644648
location,
@@ -1007,6 +1011,24 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
10071011
}
10081012
}
10091013

1014+
fn borrows_in_scope<'s>(
1015+
&self,
1016+
location: Location,
1017+
state: &'s BorrowckDomain,
1018+
) -> Cow<'s, BitSet<BorrowIndex>> {
1019+
if let Some(polonius) = &self.polonius_output {
1020+
// Use polonius output if it has been enabled.
1021+
let location = self.location_table.start_index(location);
1022+
let mut polonius_output = BitSet::new_empty(self.borrow_set.len());
1023+
for &idx in polonius.errors_at(location) {
1024+
polonius_output.insert(idx);
1025+
}
1026+
Cow::Owned(polonius_output)
1027+
} else {
1028+
Cow::Borrowed(&state.borrows)
1029+
}
1030+
}
1031+
10101032
#[instrument(level = "debug", skip(self, state))]
10111033
fn check_access_for_conflict(
10121034
&mut self,
@@ -1018,18 +1040,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
10181040
) -> bool {
10191041
let mut error_reported = false;
10201042

1021-
// Use polonius output if it has been enabled.
1022-
let mut polonius_output;
1023-
let borrows_in_scope = if let Some(polonius) = &self.polonius_output {
1024-
let location = self.location_table.start_index(location);
1025-
polonius_output = BitSet::new_empty(self.borrow_set.len());
1026-
for &idx in polonius.errors_at(location) {
1027-
polonius_output.insert(idx);
1028-
}
1029-
&polonius_output
1030-
} else {
1031-
&state.borrows
1032-
};
1043+
let borrows_in_scope = self.borrows_in_scope(location, state);
10331044

10341045
each_borrow_involving_path(
10351046
self,
@@ -1149,6 +1160,53 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
11491160
error_reported
11501161
}
11511162

1163+
/// Through #123739, backward incompatible drops (BIDs) are introduced.
1164+
/// We would like to emit lints whether borrow checking fails at these future drop locations.
1165+
#[instrument(level = "debug", skip(self, state))]
1166+
fn check_backward_incompatible_drop(
1167+
&mut self,
1168+
location: Location,
1169+
(place, place_span): (Place<'tcx>, Span),
1170+
state: &BorrowckDomain,
1171+
) {
1172+
let tcx = self.infcx.tcx;
1173+
// If this type does not need `Drop`, then treat it like a `StorageDead`.
1174+
// This is needed because we track the borrows of refs to thread locals,
1175+
// and we'll ICE because we don't track borrows behind shared references.
1176+
let sd = if place.ty(self.body, tcx).ty.needs_drop(tcx, self.body.typing_env(tcx)) {
1177+
AccessDepth::Drop
1178+
} else {
1179+
AccessDepth::Shallow(None)
1180+
};
1181+
1182+
let borrows_in_scope = self.borrows_in_scope(location, state);
1183+
1184+
// This is a very simplified version of `Self::check_access_for_conflict`.
1185+
// We are here checking on BIDs and specifically still-live borrows of data involving the BIDs.
1186+
each_borrow_involving_path(
1187+
self,
1188+
self.infcx.tcx,
1189+
self.body,
1190+
(sd, place),
1191+
self.borrow_set,
1192+
|borrow_index| borrows_in_scope.contains(borrow_index),
1193+
|this, _borrow_index, borrow| {
1194+
if matches!(borrow.kind, BorrowKind::Fake(_)) {
1195+
return Control::Continue;
1196+
}
1197+
let borrowed = this.retrieve_borrow_spans(borrow).var_or_use_path_span();
1198+
this.infcx.tcx.emit_node_span_lint(
1199+
TAIL_EXPR_DROP_ORDER,
1200+
CRATE_HIR_ID,
1201+
place_span,
1202+
session_diagnostics::TailExprDropOrder { borrowed },
1203+
);
1204+
// We may stop at the first case
1205+
Control::Break
1206+
},
1207+
);
1208+
}
1209+
11521210
fn mutate_place(
11531211
&mut self,
11541212
location: Location,

Diff for: compiler/rustc_borrowck/src/session_diagnostics.rs

+7
Original file line numberDiff line numberDiff line change
@@ -480,3 +480,10 @@ pub(crate) struct SimdIntrinsicArgConst {
480480
pub arg: usize,
481481
pub intrinsic: String,
482482
}
483+
484+
#[derive(LintDiagnostic)]
485+
#[diag(borrowck_tail_expr_drop_order)]
486+
pub(crate) struct TailExprDropOrder {
487+
#[label]
488+
pub borrowed: Span,
489+
}

Diff for: compiler/rustc_mir_build/src/builder/scope.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -1131,15 +1131,15 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
11311131

11321132
/// Schedule emission of a backwards incompatible drop lint hint.
11331133
/// Applicable only to temporary values for now.
1134+
#[instrument(level = "debug", skip(self))]
11341135
pub(crate) fn schedule_backwards_incompatible_drop(
11351136
&mut self,
11361137
span: Span,
11371138
region_scope: region::Scope,
11381139
local: Local,
11391140
) {
1140-
if !self.local_decls[local].ty.has_significant_drop(self.tcx, self.typing_env()) {
1141-
return;
1142-
}
1141+
// Note that we are *not* gating BIDs here on whether they have significant destructor.
1142+
// We need to know all of them so that we can capture potential borrow-checking errors.
11431143
for scope in self.scopes.scopes.iter_mut().rev() {
11441144
// Since we are inserting linting MIR statement, we have to invalidate the caches
11451145
scope.invalidate_cache();

Diff for: compiler/rustc_mir_transform/src/lint_tail_expr_drop_order.rs

+6-1
Original file line numberDiff line numberDiff line change
@@ -351,14 +351,19 @@ pub(crate) fn run_lint<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId, body: &Body<
351351
{
352352
return;
353353
}
354+
355+
// FIXME(typing_env): This should be able to reveal the opaques local to the
356+
// body using the typeck results.
357+
let typing_env = ty::TypingEnv::non_body_analysis(tcx, def_id);
358+
354359
// ## About BIDs in blocks ##
355360
// Track the set of blocks that contain a backwards-incompatible drop (BID)
356361
// and, for each block, the vector of locations.
357362
//
358363
// We group them per-block because they tend to scheduled in the same drop ladder block.
359364
let mut bid_per_block = IndexMap::default();
360365
let mut bid_places = UnordSet::new();
361-
let typing_env = ty::TypingEnv::post_analysis(tcx, def_id);
366+
362367
let mut ty_dropped_components = UnordMap::default();
363368
for (block, data) in body.basic_blocks.iter_enumerated() {
364369
for (statement_index, stmt) in data.statements.iter().enumerate() {

Diff for: tests/ui/drop/lint-tail-expr-drop-order-borrowck.rs

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// Edition 2024 lint for change in drop order at tail expression
2+
// This lint is to capture potential borrow-checking errors
3+
// due to implementation of RFC 3606 <https://github.com/rust-lang/rfcs/pull/3606>
4+
//@ edition: 2021
5+
6+
#![deny(tail_expr_drop_order)] //~ NOTE: the lint level is defined here
7+
8+
fn should_lint_with_potential_borrowck_err() {
9+
let _ = { String::new().as_str() }.len();
10+
//~^ ERROR: a temporary value will be dropped here
11+
//~| WARN: this changes meaning in Rust 2024
12+
//~| NOTE: consider using a `let` binding
13+
//~| NOTE: for more information, see
14+
}
15+
16+
fn should_lint_with_unsafe_block() {
17+
fn f(_: usize) {}
18+
f(unsafe { String::new().as_str() }.len());
19+
//~^ ERROR: a temporary value will be dropped here
20+
//~| WARN: this changes meaning in Rust 2024
21+
//~| NOTE: consider using a `let` binding
22+
//~| NOTE: for more information, see
23+
}
24+
25+
#[rustfmt::skip]
26+
fn should_lint_with_big_block() {
27+
fn f<T>(_: T) {}
28+
f({
29+
&mut || 0
30+
//~^ ERROR: a temporary value will be dropped here
31+
//~| WARN: this changes meaning in Rust 2024
32+
//~| NOTE: consider using a `let` binding
33+
//~| NOTE: for more information, see
34+
})
35+
}
36+
37+
fn main() {}
+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
error: a temporary value will be dropped here before the execution exits the block in Edition 2024, which will raise borrow checking error
2+
--> $DIR/lint-tail-expr-drop-order-borrowck.rs:9:36
3+
|
4+
LL | let _ = { String::new().as_str() }.len();
5+
| ------------- ^
6+
| |
7+
| consider using a `let` binding to create a longer lived value; or replacing the `{ .. }` block with curly brackets `( .. )`; or folding the rest of the expression into the surrounding `unsafe { .. }`
8+
|
9+
= warning: this changes meaning in Rust 2024
10+
= note: for more information, see <https://doc.rust-lang.org/nightly/edition-guide/rust-2024/temporary-tail-expr-scope.html>
11+
note: the lint level is defined here
12+
--> $DIR/lint-tail-expr-drop-order-borrowck.rs:6:9
13+
|
14+
LL | #![deny(tail_expr_drop_order)]
15+
| ^^^^^^^^^^^^^^^^^^^^
16+
17+
error: a temporary value will be dropped here before the execution exits the block in Edition 2024, which will raise borrow checking error
18+
--> $DIR/lint-tail-expr-drop-order-borrowck.rs:18:37
19+
|
20+
LL | f(unsafe { String::new().as_str() }.len());
21+
| ------------- ^
22+
| |
23+
| consider using a `let` binding to create a longer lived value; or replacing the `{ .. }` block with curly brackets `( .. )`; or folding the rest of the expression into the surrounding `unsafe { .. }`
24+
|
25+
= warning: this changes meaning in Rust 2024
26+
= note: for more information, see <https://doc.rust-lang.org/nightly/edition-guide/rust-2024/temporary-tail-expr-scope.html>
27+
28+
error: a temporary value will be dropped here before the execution exits the block in Edition 2024, which will raise borrow checking error
29+
--> $DIR/lint-tail-expr-drop-order-borrowck.rs:29:17
30+
|
31+
LL | &mut || 0
32+
| --------^
33+
| |
34+
| consider using a `let` binding to create a longer lived value; or replacing the `{ .. }` block with curly brackets `( .. )`; or folding the rest of the expression into the surrounding `unsafe { .. }`
35+
|
36+
= warning: this changes meaning in Rust 2024
37+
= note: for more information, see <https://doc.rust-lang.org/nightly/edition-guide/rust-2024/temporary-tail-expr-scope.html>
38+
39+
error: aborting due to 3 previous errors
40+

Diff for: tests/ui/drop/lint-tail-expr-drop-order.rs

-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ impl Drop for LoudDropper {
1717
//~| NOTE: `#1` invokes this custom destructor
1818
//~| NOTE: `x` invokes this custom destructor
1919
//~| NOTE: `#1` invokes this custom destructor
20-
//~| NOTE: `future` invokes this custom destructor
2120
//~| NOTE: `_x` invokes this custom destructor
2221
//~| NOTE: `#1` invokes this custom destructor
2322
fn drop(&mut self) {

Diff for: tests/ui/drop/lint-tail-expr-drop-order.stderr

+10-17
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
error: relative drop order changing in Rust 2024
2-
--> $DIR/lint-tail-expr-drop-order.rs:41:15
2+
--> $DIR/lint-tail-expr-drop-order.rs:40:15
33
|
44
LL | let x = LoudDropper;
55
| -
@@ -40,7 +40,7 @@ LL | #![deny(tail_expr_drop_order)]
4040
| ^^^^^^^^^^^^^^^^^^^^
4141

4242
error: relative drop order changing in Rust 2024
43-
--> $DIR/lint-tail-expr-drop-order.rs:66:19
43+
--> $DIR/lint-tail-expr-drop-order.rs:65:19
4444
|
4545
LL | let x = LoudDropper;
4646
| -
@@ -76,7 +76,7 @@ LL | | }
7676
= note: most of the time, changing drop order is harmless; inspect the `impl Drop`s for side effects like releasing locks or sending messages
7777

7878
error: relative drop order changing in Rust 2024
79-
--> $DIR/lint-tail-expr-drop-order.rs:93:7
79+
--> $DIR/lint-tail-expr-drop-order.rs:92:7
8080
|
8181
LL | let x = LoudDropper;
8282
| -
@@ -112,7 +112,7 @@ LL | | }
112112
= note: most of the time, changing drop order is harmless; inspect the `impl Drop`s for side effects like releasing locks or sending messages
113113

114114
error: relative drop order changing in Rust 2024
115-
--> $DIR/lint-tail-expr-drop-order.rs:146:5
115+
--> $DIR/lint-tail-expr-drop-order.rs:145:5
116116
|
117117
LL | let future = f();
118118
| ------
@@ -136,19 +136,12 @@ note: `#1` invokes this custom destructor
136136
|
137137
LL | / impl Drop for LoudDropper {
138138
... |
139-
LL | | }
140-
| |_^
141-
note: `future` invokes this custom destructor
142-
--> $DIR/lint-tail-expr-drop-order.rs:10:1
143-
|
144-
LL | / impl Drop for LoudDropper {
145-
... |
146139
LL | | }
147140
| |_^
148141
= note: most of the time, changing drop order is harmless; inspect the `impl Drop`s for side effects like releasing locks or sending messages
149142

150143
error: relative drop order changing in Rust 2024
151-
--> $DIR/lint-tail-expr-drop-order.rs:163:14
144+
--> $DIR/lint-tail-expr-drop-order.rs:162:14
152145
|
153146
LL | let x = T::default();
154147
| -
@@ -170,7 +163,7 @@ LL | }
170163
= note: most of the time, changing drop order is harmless; inspect the `impl Drop`s for side effects like releasing locks or sending messages
171164

172165
error: relative drop order changing in Rust 2024
173-
--> $DIR/lint-tail-expr-drop-order.rs:177:5
166+
--> $DIR/lint-tail-expr-drop-order.rs:176:5
174167
|
175168
LL | let x: Result<LoudDropper, ()> = Ok(LoudDropper);
176169
| -
@@ -206,7 +199,7 @@ LL | | }
206199
= note: most of the time, changing drop order is harmless; inspect the `impl Drop`s for side effects like releasing locks or sending messages
207200

208201
error: relative drop order changing in Rust 2024
209-
--> $DIR/lint-tail-expr-drop-order.rs:221:5
202+
--> $DIR/lint-tail-expr-drop-order.rs:220:5
210203
|
211204
LL | let x = LoudDropper2;
212205
| -
@@ -226,7 +219,7 @@ LL | }
226219
= warning: this changes meaning in Rust 2024
227220
= note: for more information, see <https://doc.rust-lang.org/nightly/edition-guide/rust-2024/temporary-tail-expr-scope.html>
228221
note: `#1` invokes this custom destructor
229-
--> $DIR/lint-tail-expr-drop-order.rs:194:5
222+
--> $DIR/lint-tail-expr-drop-order.rs:193:5
230223
|
231224
LL | / impl Drop for LoudDropper3 {
232225
LL | |
@@ -236,7 +229,7 @@ LL | | }
236229
LL | | }
237230
| |_____^
238231
note: `x` invokes this custom destructor
239-
--> $DIR/lint-tail-expr-drop-order.rs:206:5
232+
--> $DIR/lint-tail-expr-drop-order.rs:205:5
240233
|
241234
LL | / impl Drop for LoudDropper2 {
242235
LL | |
@@ -248,7 +241,7 @@ LL | | }
248241
= note: most of the time, changing drop order is harmless; inspect the `impl Drop`s for side effects like releasing locks or sending messages
249242

250243
error: relative drop order changing in Rust 2024
251-
--> $DIR/lint-tail-expr-drop-order.rs:234:13
244+
--> $DIR/lint-tail-expr-drop-order.rs:233:13
252245
|
253246
LL | LoudDropper.get()
254247
| ^^^^^^^^^^^

0 commit comments

Comments
 (0)