Skip to content

Commit 22fedd1

Browse files
authored
Rollup merge of rust-lang#71910 - mibac138:necessary-paren, r=cuviper
Fix unused_parens false positive when using binary operations Fixes rust-lang#71290 r? @cuviper who provided instructions
2 parents e114d60 + 4b7a928 commit 22fedd1

File tree

2 files changed

+43
-4
lines changed

2 files changed

+43
-4
lines changed

src/librustc_lint/unused.rs

+20-4
Original file line numberDiff line numberDiff line change
@@ -380,11 +380,27 @@ trait UnusedDelimLint {
380380
);
381381

382382
fn is_expr_delims_necessary(inner: &ast::Expr, followed_by_block: bool) -> bool {
383-
followed_by_block
384-
&& match inner.kind {
385-
ExprKind::Ret(_) | ExprKind::Break(..) => true,
386-
_ => parser::contains_exterior_struct_lit(&inner),
383+
// Prevent false-positives in cases like `fn x() -> u8 { ({ 0 } + 1) }`
384+
let lhs_needs_parens = {
385+
let mut innermost = inner;
386+
loop {
387+
if let ExprKind::Binary(_, lhs, _rhs) = &innermost.kind {
388+
innermost = lhs;
389+
if !rustc_ast::util::classify::expr_requires_semi_to_be_stmt(innermost) {
390+
break true;
391+
}
392+
} else {
393+
break false;
394+
}
387395
}
396+
};
397+
398+
lhs_needs_parens
399+
|| (followed_by_block
400+
&& match inner.kind {
401+
ExprKind::Ret(_) | ExprKind::Break(..) => true,
402+
_ => parser::contains_exterior_struct_lit(&inner),
403+
})
388404
}
389405

390406
fn emit_unused_delims_expr(
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// check-pass
2+
// Make sure unused parens lint doesn't emit a false positive.
3+
// See https://github.com/rust-lang/rust/issues/71290 for details.
4+
#![deny(unused_parens)]
5+
6+
fn x() -> u8 {
7+
({ 0 }) + 1
8+
}
9+
10+
fn y() -> u8 {
11+
({ 0 } + 1)
12+
}
13+
14+
pub fn foo(a: bool, b: bool) -> u8 {
15+
(if a { 1 } else { 0 } + if b { 1 } else { 0 })
16+
}
17+
18+
pub fn bar() -> u8 {
19+
// Make sure nested expressions are handled correctly as well
20+
({ 0 } + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9)
21+
}
22+
23+
fn main() {}

0 commit comments

Comments
 (0)