Skip to content

Commit 7bf7921

Browse files
lint on tail expr drop order change in Edition 2024
1 parent ab1527f commit 7bf7921

File tree

5 files changed

+272
-0
lines changed

5 files changed

+272
-0
lines changed

compiler/rustc_lint/messages.ftl

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -758,6 +758,9 @@ lint_suspicious_double_ref_clone =
758758
lint_suspicious_double_ref_deref =
759759
using `.deref()` on a double reference, which returns `{$ty}` instead of dereferencing the inner type
760760
761+
lint_tail_expr_drop_order = these values and local bindings have significant drop implementation that will have a different drop order from that of Edition 2021
762+
.label = these values have significant drop implementation and will observe changes in drop order under Edition 2024
763+
761764
lint_trailing_semi_macro = trailing semicolon in macro used in expression position
762765
.note1 = macro invocations at the end of a block are treated as expressions
763766
.note2 = to ignore the value produced by the macro, add a semicolon after the invocation of `{$name}`

compiler/rustc_lint/src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ mod ptr_nulls;
7878
mod redundant_semicolon;
7979
mod reference_casting;
8080
mod shadowed_into_iter;
81+
mod tail_expr_drop_order;
8182
mod traits;
8283
mod types;
8384
mod unit_bindings;
@@ -115,6 +116,7 @@ use rustc_middle::query::Providers;
115116
use rustc_middle::ty::TyCtxt;
116117
use shadowed_into_iter::ShadowedIntoIter;
117118
pub use shadowed_into_iter::{ARRAY_INTO_ITER, BOXED_SLICE_INTO_ITER};
119+
use tail_expr_drop_order::TailExprDropOrder;
118120
use traits::*;
119121
use types::*;
120122
use unit_bindings::*;
@@ -238,6 +240,7 @@ late_lint_methods!(
238240
AsyncFnInTrait: AsyncFnInTrait,
239241
NonLocalDefinitions: NonLocalDefinitions::default(),
240242
ImplTraitOvercaptures: ImplTraitOvercaptures,
243+
TailExprDropOrder: TailExprDropOrder,
241244
]
242245
]
243246
);
Lines changed: 217 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,217 @@
1+
use std::mem::swap;
2+
3+
use rustc_ast::UnOp;
4+
use rustc_hir::def::Res;
5+
use rustc_hir::intravisit::{self, Visitor};
6+
use rustc_hir::{Block, Expr, ExprKind, LetStmt, Pat, PatKind, QPath, StmtKind};
7+
use rustc_macros::LintDiagnostic;
8+
use rustc_session::{declare_lint, declare_lint_pass};
9+
use rustc_span::Span;
10+
use tracing::debug;
11+
12+
use crate::{LateContext, LateLintPass};
13+
14+
declare_lint! {
15+
/// ### What it does
16+
/// Edition 2024 introduces a new rule with drop orders for values generated in tail expressions
17+
/// of blocks.
18+
/// Now the values will be dropped first, before the local variable bindings were dropped.
19+
///
20+
/// This lint looks for those values generated at the tail expression location, that of type
21+
/// with a significant `Drop` implementation, such as locks.
22+
/// In case there are also local variables of type with significant `Drop` implementation as well,
23+
/// this lint warns you of a potential transposition in the drop order.
24+
/// Your discretion on the new drop order introduced by Edition 2024 is required.
25+
///
26+
/// ### Why is this bad?
27+
/// Values of type with significant `Drop` implementation has an ill-specified drop order that
28+
/// come after those of local variables.
29+
/// Edition 2024 moves them, so that they are dropped first before dropping local variables.
30+
///
31+
/// ### Example
32+
/// ```compile_fail,E0597
33+
/// fn edition_2024() -> i32 {
34+
/// let mutex = std::sync::Mutex::new(vec![0]);
35+
/// mutex.lock().unwrap()[0]
36+
/// }
37+
/// ```
38+
/// This lint only points out the issue with `mutex.lock()`, which will be dropped before `mutex` does.
39+
/// No fix will be proposed.
40+
/// However, the most probable fix is to hoist `mutex.lock()` into its own local variable binding.
41+
/// ```no_run
42+
/// fn edition_2024() -> i32 {
43+
/// let mutex = std::sync::Mutex::new(vec![0]);
44+
/// let guard = mutex.lock().unwrap();
45+
/// guard[0]
46+
/// }
47+
/// ```
48+
pub TAIL_EXPR_DROP_ORDER,
49+
Allow,
50+
"Detect and warn on significant change in drop order in tail expression location",
51+
@feature_gate = shorter_tail_lifetimes;
52+
}
53+
54+
declare_lint_pass!(TailExprDropOrder => [TAIL_EXPR_DROP_ORDER]);
55+
56+
impl<'tcx> LateLintPass<'tcx> for TailExprDropOrder {
57+
fn check_block(&mut self, cx: &LateContext<'tcx>, block: &'tcx Block<'tcx>) {
58+
LintVisitor { cx, locals: <_>::default() }.check_block_inner(block);
59+
}
60+
}
61+
62+
struct LintVisitor<'tcx, 'a> {
63+
cx: &'a LateContext<'tcx>,
64+
locals: Vec<Span>,
65+
}
66+
67+
struct LocalCollector<'tcx, 'a> {
68+
cx: &'a LateContext<'tcx>,
69+
locals: &'a mut Vec<Span>,
70+
}
71+
72+
impl<'tcx, 'a> Visitor<'tcx> for LocalCollector<'tcx, 'a> {
73+
type Result = ();
74+
fn visit_pat(&mut self, pat: &'tcx Pat<'tcx>) {
75+
if let PatKind::Binding(_binding_mode, id, ident, pat) = pat.kind {
76+
let ty = self.cx.typeck_results().node_type(id);
77+
if ty.has_significant_drop(self.cx.tcx, self.cx.param_env) {
78+
self.locals.push(ident.span);
79+
}
80+
if let Some(pat) = pat {
81+
self.visit_pat(pat);
82+
}
83+
} else {
84+
intravisit::walk_pat(self, pat);
85+
}
86+
}
87+
}
88+
89+
impl<'tcx, 'a> Visitor<'tcx> for LintVisitor<'tcx, 'a> {
90+
fn visit_block(&mut self, block: &'tcx Block<'tcx>) {
91+
let mut locals = <_>::default();
92+
swap(&mut locals, &mut self.locals);
93+
self.check_block_inner(block);
94+
swap(&mut locals, &mut self.locals);
95+
}
96+
fn visit_local(&mut self, local: &'tcx LetStmt<'tcx>) {
97+
LocalCollector { cx: self.cx, locals: &mut self.locals }.visit_local(local);
98+
}
99+
}
100+
101+
impl<'tcx, 'a> LintVisitor<'tcx, 'a> {
102+
fn check_block_inner(&mut self, block: &Block<'tcx>) {
103+
if !block.span.at_least_rust_2024() {
104+
// We only lint for Edition 2024 onwards
105+
return;
106+
}
107+
let Some(tail_expr) = block.expr else { return };
108+
for stmt in block.stmts {
109+
match stmt.kind {
110+
StmtKind::Let(let_stmt) => self.visit_local(let_stmt),
111+
StmtKind::Item(_) => {}
112+
StmtKind::Expr(e) | StmtKind::Semi(e) => self.visit_expr(e),
113+
}
114+
}
115+
if self.locals.is_empty() {
116+
return;
117+
}
118+
debug!(?self.locals, "dxf");
119+
LintTailExpr { cx: self.cx, locals: &self.locals }.visit_expr(tail_expr);
120+
}
121+
}
122+
123+
struct LintTailExpr<'tcx, 'a> {
124+
cx: &'a LateContext<'tcx>,
125+
locals: &'a [Span],
126+
}
127+
128+
impl<'tcx, 'a> LintTailExpr<'tcx, 'a> {
129+
fn expr_eventually_point_into_local(mut expr: &Expr<'tcx>) -> bool {
130+
loop {
131+
match expr.kind {
132+
ExprKind::Index(access, _, _) | ExprKind::Field(access, _) => expr = access,
133+
ExprKind::AddrOf(_, _, referee) | ExprKind::Unary(UnOp::Deref, referee) => {
134+
expr = referee
135+
}
136+
ExprKind::Path(_)
137+
if let ExprKind::Path(QPath::Resolved(_, path)) = expr.kind
138+
&& let [local, ..] = path.segments
139+
&& let Res::Local(_) = local.res =>
140+
{
141+
return true;
142+
}
143+
_ => return false,
144+
}
145+
}
146+
}
147+
148+
fn expr_generates_nonlocal_droppy_value(&self, expr: &Expr<'tcx>) -> bool {
149+
if Self::expr_eventually_point_into_local(expr) {
150+
return false;
151+
}
152+
self.cx.typeck_results().expr_ty(expr).has_significant_drop(self.cx.tcx, self.cx.param_env)
153+
}
154+
}
155+
156+
impl<'tcx, 'a> Visitor<'tcx> for LintTailExpr<'tcx, 'a> {
157+
fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
158+
if self.expr_generates_nonlocal_droppy_value(expr) {
159+
self.cx.tcx.emit_node_span_lint(
160+
TAIL_EXPR_DROP_ORDER,
161+
expr.hir_id,
162+
expr.span,
163+
TailExprDropOrderLint { spans: self.locals.to_vec() },
164+
);
165+
return;
166+
}
167+
match expr.kind {
168+
ExprKind::ConstBlock(_)
169+
| ExprKind::Array(_)
170+
| ExprKind::Break(_, _)
171+
| ExprKind::Continue(_)
172+
| ExprKind::Ret(_)
173+
| ExprKind::Become(_)
174+
| ExprKind::Yield(_, _)
175+
| ExprKind::InlineAsm(_)
176+
| ExprKind::If(_, _, _)
177+
| ExprKind::Loop(_, _, _, _)
178+
| ExprKind::Match(_, _, _)
179+
| ExprKind::Closure(_)
180+
| ExprKind::DropTemps(_)
181+
| ExprKind::OffsetOf(_, _)
182+
| ExprKind::Assign(_, _, _)
183+
| ExprKind::AssignOp(_, _, _)
184+
| ExprKind::Lit(_)
185+
| ExprKind::Err(_) => {}
186+
187+
ExprKind::MethodCall(_, _, _, _)
188+
| ExprKind::Call(_, _)
189+
| ExprKind::Type(_, _)
190+
| ExprKind::Tup(_)
191+
| ExprKind::Binary(_, _, _)
192+
| ExprKind::Unary(_, _)
193+
| ExprKind::Path(_)
194+
| ExprKind::Let(_)
195+
| ExprKind::Cast(_, _)
196+
| ExprKind::Field(_, _)
197+
| ExprKind::Index(_, _, _)
198+
| ExprKind::AddrOf(_, _, _)
199+
| ExprKind::Struct(_, _, _)
200+
| ExprKind::Repeat(_, _) => intravisit::walk_expr(self, expr),
201+
202+
ExprKind::Block(block, _) => {
203+
LintVisitor { cx: self.cx, locals: <_>::default() }.check_block_inner(block)
204+
}
205+
}
206+
}
207+
fn visit_block(&mut self, block: &'tcx Block<'tcx>) {
208+
LintVisitor { cx: self.cx, locals: <_>::default() }.check_block_inner(block);
209+
}
210+
}
211+
212+
#[derive(LintDiagnostic)]
213+
#[diag(lint_tail_expr_drop_order)]
214+
struct TailExprDropOrderLint {
215+
#[label]
216+
pub spans: Vec<Span>,
217+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
//@compile-flags: -Z unstable-options
2+
//@edition:2024
3+
4+
#![deny(tail_expr_drop_order)]
5+
#![feature(shorter_tail_lifetimes)]
6+
7+
struct LoudDropper;
8+
impl Drop for LoudDropper {
9+
fn drop(&mut self) {
10+
println!("loud drop")
11+
}
12+
}
13+
impl LoudDropper {
14+
fn get(&self) -> i32 {
15+
0
16+
}
17+
}
18+
19+
fn should_lint() -> i32 {
20+
let x = LoudDropper;
21+
// Should lint
22+
x.get() + LoudDropper.get()
23+
//~^ ERROR: these values and local bindings have significant drop implementation that will have a different drop order from that of Edition 2021
24+
}
25+
26+
fn should_not_lint() -> i32 {
27+
let x = LoudDropper;
28+
// Should not lint
29+
x.get()
30+
}
31+
32+
fn main() {}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
error: these values and local bindings have significant drop implementation that will have a different drop order from that of Edition 2021
2+
--> $DIR/lint-tail-expr-drop-order.rs:22:15
3+
|
4+
LL | let x = LoudDropper;
5+
| - these values have significant drop implementation and will observe changes in drop order under Edition 2024
6+
LL | // Should lint
7+
LL | x.get() + LoudDropper.get()
8+
| ^^^^^^^^^^^
9+
|
10+
note: the lint level is defined here
11+
--> $DIR/lint-tail-expr-drop-order.rs:4:9
12+
|
13+
LL | #![deny(tail_expr_drop_order)]
14+
| ^^^^^^^^^^^^^^^^^^^^
15+
16+
error: aborting due to 1 previous error
17+

0 commit comments

Comments
 (0)