Skip to content

Commit

Permalink
Auto merge of rust-lang#117321 - chenyukang:yukang-fix-117142, r=petr…
Browse files Browse the repository at this point in the history
…ochenkov

Fix unused_parens issue when cast is followed LT

Fixes rust-lang#117142

The original check only checks `a as (i32) < 0`, this fix extends it to handle `b + a as (i32) < 0`.

A better way is maybe we suggest `(a as i32) < 0` instead of suppressing the warning, maybe following PR could improve it.
  • Loading branch information
bors committed Jan 12, 2024
2 parents 2319be8 + eef4e65 commit 3071aef
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 12 deletions.
34 changes: 22 additions & 12 deletions compiler/rustc_lint/src/unused.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1071,17 +1071,31 @@ impl UnusedParens {
self.emit_unused_delims(cx, value.span, spans, "pattern", keep_space, false);
}
}

fn cast_followed_by_lt(&self, expr: &ast::Expr) -> Option<ast::NodeId> {
if let ExprKind::Binary(op, lhs, _rhs) = &expr.kind
&& (op.node == ast::BinOpKind::Lt || op.node == ast::BinOpKind::Shl)
{
let mut cur = lhs;
while let ExprKind::Binary(_, _, rhs) = &cur.kind {
cur = rhs;
}

if let ExprKind::Cast(_, ty) = &cur.kind
&& let ast::TyKind::Paren(_) = &ty.kind
{
return Some(ty.id);
}
}
None
}
}

impl EarlyLintPass for UnusedParens {
#[inline]
fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
if let ExprKind::Binary(op, lhs, _rhs) = &e.kind
&& (op.node == ast::BinOpKind::Lt || op.node == ast::BinOpKind::Shl)
&& let ExprKind::Cast(_expr, ty) = &lhs.kind
&& let ast::TyKind::Paren(_) = &ty.kind
{
self.parens_in_cast_in_lt.push(ty.id);
if let Some(ty_id) = self.cast_followed_by_lt(e) {
self.parens_in_cast_in_lt.push(ty_id);
}

match e.kind {
Expand Down Expand Up @@ -1133,17 +1147,13 @@ impl EarlyLintPass for UnusedParens {
}

fn check_expr_post(&mut self, _cx: &EarlyContext<'_>, e: &ast::Expr) {
if let ExprKind::Binary(op, lhs, _rhs) = &e.kind
&& (op.node == ast::BinOpKind::Lt || op.node == ast::BinOpKind::Shl)
&& let ExprKind::Cast(_expr, ty) = &lhs.kind
&& let ast::TyKind::Paren(_) = &ty.kind
{
if let Some(ty_id) = self.cast_followed_by_lt(e) {
let id = self
.parens_in_cast_in_lt
.pop()
.expect("check_expr and check_expr_post must balance");
assert_eq!(
id, ty.id,
id, ty_id,
"check_expr, check_ty, and check_expr_post are called, in that order, by the visitor"
);
}
Expand Down
19 changes: 19 additions & 0 deletions tests/ui/lint/unused/issue-117142-invalid-remove-parens.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// check-pass
#![warn(unused_parens)]

fn main() {
let a: i32 = 1;
let b: i64 = 1;

if b + a as (i64) < 0 {
println!(":D");
}
if b + b + a as (i64) < 0 {
println!(":D");
}
let c = a + b as (i32) < 0;
let mut x = false;
x |= false || (b as (i32) < 0);

let d = 1 + 2 + 3 * 4 as (i32) < 10;
}

0 comments on commit 3071aef

Please sign in to comment.