Skip to content

Commit a7c38d1

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

File tree

5 files changed

+275
-0
lines changed

5 files changed

+275
-0
lines changed

compiler/rustc_lint/messages.ftl

+3
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

+3
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
);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,220 @@
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::lint::FutureIncompatibilityReason;
9+
use rustc_session::{declare_lint, declare_lint_pass};
10+
use rustc_span::edition::Edition;
11+
use rustc_span::Span;
12+
13+
use crate::{LateContext, LateLintPass};
14+
15+
declare_lint! {
16+
/// The `tail_expr_drop_order` lint looks for those values generated at the tail expression location, that of type
17+
/// with a significant `Drop` implementation, such as locks.
18+
/// In case there are also local variables of type with significant `Drop` implementation as well,
19+
/// this lint warns you of a potential transposition in the drop order.
20+
/// Your discretion on the new drop order introduced by Edition 2024 is required.
21+
///
22+
/// ### Example
23+
/// ```compile_fail,E0597
24+
/// fn edition_2024() -> i32 {
25+
/// let mutex = std::sync::Mutex::new(vec![0]);
26+
/// mutex.lock().unwrap()[0]
27+
/// }
28+
/// ```
29+
///
30+
/// {{produces}}
31+
///
32+
/// ### Explanation
33+
///
34+
/// In tail expression of blocks or function bodies,
35+
/// values of type with significant `Drop` implementation has an ill-specified drop order before Edition 2024
36+
/// so that they are dropped only after dropping local variables.
37+
/// Edition 2024 introduces a new rule with drop orders for them, so that they are dropped first before dropping local variables.
38+
///
39+
/// This lint only points out the issue with `mutex.lock()`, which will be dropped before `mutex` does.
40+
/// No fix will be proposed.
41+
/// However, the most probable fix is to hoist `mutex.lock()` into its own local variable binding.
42+
/// ```no_run
43+
/// fn edition_2024() -> i32 {
44+
/// let mutex = std::sync::Mutex::new(vec![0]);
45+
/// let guard = mutex.lock().unwrap();
46+
/// guard[0]
47+
/// }
48+
/// ```
49+
pub TAIL_EXPR_DROP_ORDER,
50+
Allow,
51+
"Detect and warn on significant change in drop order in tail expression location",
52+
@future_incompatible = FutureIncompatibleInfo {
53+
reason: FutureIncompatibilityReason::EditionError(Edition::Edition2024),
54+
reference: "issue #123739 <https://github.com/rust-lang/rust/issues/123739>",
55+
};
56+
}
57+
58+
declare_lint_pass!(TailExprDropOrder => [TAIL_EXPR_DROP_ORDER]);
59+
60+
impl<'tcx> LateLintPass<'tcx> for TailExprDropOrder {
61+
fn check_block(&mut self, cx: &LateContext<'tcx>, block: &'tcx Block<'tcx>) {
62+
LintVisitor { cx, locals: <_>::default() }.check_block_inner(block);
63+
}
64+
}
65+
66+
struct LintVisitor<'tcx, 'a> {
67+
cx: &'a LateContext<'tcx>,
68+
locals: Vec<Span>,
69+
}
70+
71+
struct LocalCollector<'tcx, 'a> {
72+
cx: &'a LateContext<'tcx>,
73+
locals: &'a mut Vec<Span>,
74+
}
75+
76+
impl<'tcx, 'a> Visitor<'tcx> for LocalCollector<'tcx, 'a> {
77+
type Result = ();
78+
fn visit_pat(&mut self, pat: &'tcx Pat<'tcx>) {
79+
if let PatKind::Binding(_binding_mode, id, ident, pat) = pat.kind {
80+
let ty = self.cx.typeck_results().node_type(id);
81+
if ty.has_significant_drop(self.cx.tcx, self.cx.param_env) {
82+
self.locals.push(ident.span);
83+
}
84+
if let Some(pat) = pat {
85+
self.visit_pat(pat);
86+
}
87+
} else {
88+
intravisit::walk_pat(self, pat);
89+
}
90+
}
91+
}
92+
93+
impl<'tcx, 'a> Visitor<'tcx> for LintVisitor<'tcx, 'a> {
94+
fn visit_block(&mut self, block: &'tcx Block<'tcx>) {
95+
let mut locals = <_>::default();
96+
swap(&mut locals, &mut self.locals);
97+
self.check_block_inner(block);
98+
swap(&mut locals, &mut self.locals);
99+
}
100+
fn visit_local(&mut self, local: &'tcx LetStmt<'tcx>) {
101+
LocalCollector { cx: self.cx, locals: &mut self.locals }.visit_local(local);
102+
}
103+
}
104+
105+
impl<'tcx, 'a> LintVisitor<'tcx, 'a> {
106+
fn check_block_inner(&mut self, block: &Block<'tcx>) {
107+
if !block.span.at_least_rust_2024() {
108+
// We only lint for Edition 2024 onwards
109+
return;
110+
}
111+
let Some(tail_expr) = block.expr else { return };
112+
for stmt in block.stmts {
113+
match stmt.kind {
114+
StmtKind::Let(let_stmt) => self.visit_local(let_stmt),
115+
StmtKind::Item(_) => {}
116+
StmtKind::Expr(e) | StmtKind::Semi(e) => self.visit_expr(e),
117+
}
118+
}
119+
if self.locals.is_empty() {
120+
return;
121+
}
122+
LintTailExpr { cx: self.cx, locals: &self.locals }.visit_expr(tail_expr);
123+
}
124+
}
125+
126+
struct LintTailExpr<'tcx, 'a> {
127+
cx: &'a LateContext<'tcx>,
128+
locals: &'a [Span],
129+
}
130+
131+
impl<'tcx, 'a> LintTailExpr<'tcx, 'a> {
132+
fn expr_eventually_point_into_local(mut expr: &Expr<'tcx>) -> bool {
133+
loop {
134+
match expr.kind {
135+
ExprKind::Index(access, _, _) | ExprKind::Field(access, _) => expr = access,
136+
ExprKind::AddrOf(_, _, referee) | ExprKind::Unary(UnOp::Deref, referee) => {
137+
expr = referee
138+
}
139+
ExprKind::Path(_)
140+
if let ExprKind::Path(QPath::Resolved(_, path)) = expr.kind
141+
&& let [local, ..] = path.segments
142+
&& let Res::Local(_) = local.res =>
143+
{
144+
return true;
145+
}
146+
_ => return false,
147+
}
148+
}
149+
}
150+
151+
fn expr_generates_nonlocal_droppy_value(&self, expr: &Expr<'tcx>) -> bool {
152+
if Self::expr_eventually_point_into_local(expr) {
153+
return false;
154+
}
155+
self.cx.typeck_results().expr_ty(expr).has_significant_drop(self.cx.tcx, self.cx.param_env)
156+
}
157+
}
158+
159+
impl<'tcx, 'a> Visitor<'tcx> for LintTailExpr<'tcx, 'a> {
160+
fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
161+
if self.expr_generates_nonlocal_droppy_value(expr) {
162+
self.cx.tcx.emit_node_span_lint(
163+
TAIL_EXPR_DROP_ORDER,
164+
expr.hir_id,
165+
expr.span,
166+
TailExprDropOrderLint { spans: self.locals.to_vec() },
167+
);
168+
return;
169+
}
170+
match expr.kind {
171+
ExprKind::ConstBlock(_)
172+
| ExprKind::Array(_)
173+
| ExprKind::Break(_, _)
174+
| ExprKind::Continue(_)
175+
| ExprKind::Ret(_)
176+
| ExprKind::Become(_)
177+
| ExprKind::Yield(_, _)
178+
| ExprKind::InlineAsm(_)
179+
| ExprKind::If(_, _, _)
180+
| ExprKind::Loop(_, _, _, _)
181+
| ExprKind::Match(_, _, _)
182+
| ExprKind::Closure(_)
183+
| ExprKind::DropTemps(_)
184+
| ExprKind::OffsetOf(_, _)
185+
| ExprKind::Assign(_, _, _)
186+
| ExprKind::AssignOp(_, _, _)
187+
| ExprKind::Lit(_)
188+
| ExprKind::Err(_) => {}
189+
190+
ExprKind::MethodCall(_, _, _, _)
191+
| ExprKind::Call(_, _)
192+
| ExprKind::Type(_, _)
193+
| ExprKind::Tup(_)
194+
| ExprKind::Binary(_, _, _)
195+
| ExprKind::Unary(_, _)
196+
| ExprKind::Path(_)
197+
| ExprKind::Let(_)
198+
| ExprKind::Cast(_, _)
199+
| ExprKind::Field(_, _)
200+
| ExprKind::Index(_, _, _)
201+
| ExprKind::AddrOf(_, _, _)
202+
| ExprKind::Struct(_, _, _)
203+
| ExprKind::Repeat(_, _) => intravisit::walk_expr(self, expr),
204+
205+
ExprKind::Block(block, _) => {
206+
LintVisitor { cx: self.cx, locals: <_>::default() }.check_block_inner(block)
207+
}
208+
}
209+
}
210+
fn visit_block(&mut self, block: &'tcx Block<'tcx>) {
211+
LintVisitor { cx: self.cx, locals: <_>::default() }.check_block_inner(block);
212+
}
213+
}
214+
215+
#[derive(LintDiagnostic)]
216+
#[diag(lint_tail_expr_drop_order)]
217+
struct TailExprDropOrderLint {
218+
#[label]
219+
pub spans: Vec<Span>,
220+
}
+32
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() {}
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)