Skip to content

Commit 65b0d13

Browse files
authored
Rollup merge of rust-lang#75056 - Veykril:path_statements_lint, r=oli-obk
Lint path statements to suggest using drop when the type needs drop Fixes rust-lang#48852. With this change the current lint description doesn't really fit entirely anymore I think.
2 parents f7b7fa5 + 35d6a2e commit 65b0d13

File tree

3 files changed

+44
-5
lines changed

3 files changed

+44
-5
lines changed

src/librustc_lint/unused.rs

+18-2
Original file line numberDiff line numberDiff line change
@@ -275,10 +275,26 @@ declare_lint_pass!(PathStatements => [PATH_STATEMENTS]);
275275

276276
impl<'tcx> LateLintPass<'tcx> for PathStatements {
277277
fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) {
278-
if let hir::StmtKind::Semi(ref expr) = s.kind {
278+
if let hir::StmtKind::Semi(expr) = s.kind {
279279
if let hir::ExprKind::Path(_) = expr.kind {
280280
cx.struct_span_lint(PATH_STATEMENTS, s.span, |lint| {
281-
lint.build("path statement with no effect").emit()
281+
let ty = cx.typeck_results().expr_ty(expr);
282+
if ty.needs_drop(cx.tcx, cx.param_env) {
283+
let mut lint = lint.build("path statement drops value");
284+
if let Ok(snippet) = cx.sess().source_map().span_to_snippet(expr.span) {
285+
lint.span_suggestion(
286+
s.span,
287+
"use `drop` to clarify the intent",
288+
format!("drop({});", snippet),
289+
Applicability::MachineApplicable,
290+
);
291+
} else {
292+
lint.span_help(s.span, "use `drop` to clarify the intent");
293+
}
294+
lint.emit()
295+
} else {
296+
lint.build("path statement with no effect").emit()
297+
}
282298
});
283299
}
284300
}

src/test/ui/warn-path-statement.rs

+12-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,17 @@
11
// compile-flags: -D path-statements
2-
fn main() {
2+
struct Droppy;
3+
4+
impl Drop for Droppy {
5+
fn drop(&mut self) {}
6+
}
37

8+
fn main() {
49
let x = 10;
510
x; //~ ERROR path statement with no effect
11+
12+
let y = Droppy;
13+
y; //~ ERROR path statement drops value
14+
15+
let z = (Droppy,);
16+
z; //~ ERROR path statement drops value
617
}
+14-2
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,22 @@
11
error: path statement with no effect
2-
--> $DIR/warn-path-statement.rs:5:5
2+
--> $DIR/warn-path-statement.rs:10:5
33
|
44
LL | x;
55
| ^^
66
|
77
= note: requested on the command line with `-D path-statements`
88

9-
error: aborting due to previous error
9+
error: path statement drops value
10+
--> $DIR/warn-path-statement.rs:13:5
11+
|
12+
LL | y;
13+
| ^^ help: use `drop` to clarify the intent: `drop(y);`
14+
15+
error: path statement drops value
16+
--> $DIR/warn-path-statement.rs:16:5
17+
|
18+
LL | z;
19+
| ^^ help: use `drop` to clarify the intent: `drop(z);`
20+
21+
error: aborting due to 3 previous errors
1022

0 commit comments

Comments
 (0)