From eef4e653f2925e4923059f4571c8433a40f2e4a0 Mon Sep 17 00:00:00 2001 From: yukang Date: Sun, 29 Oct 2023 00:29:12 +0800 Subject: [PATCH] Fix unused_parens when cast is followed LT --- compiler/rustc_lint/src/unused.rs | 34 ++++++++++++------- .../issue-117142-invalid-remove-parens.rs | 19 +++++++++++ 2 files changed, 41 insertions(+), 12 deletions(-) create mode 100644 tests/ui/lint/unused/issue-117142-invalid-remove-parens.rs diff --git a/compiler/rustc_lint/src/unused.rs b/compiler/rustc_lint/src/unused.rs index b4535c72d6c..4b99ffb4be4 100644 --- a/compiler/rustc_lint/src/unused.rs +++ b/compiler/rustc_lint/src/unused.rs @@ -1071,17 +1071,31 @@ fn check_unused_parens_pat( self.emit_unused_delims(cx, value.span, spans, "pattern", keep_space, false); } } + + fn cast_followed_by_lt(&self, expr: &ast::Expr) -> Option { + 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 { @@ -1131,17 +1145,13 @@ fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) { } 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" ); } diff --git a/tests/ui/lint/unused/issue-117142-invalid-remove-parens.rs b/tests/ui/lint/unused/issue-117142-invalid-remove-parens.rs new file mode 100644 index 00000000000..8af9e6f3d95 --- /dev/null +++ b/tests/ui/lint/unused/issue-117142-invalid-remove-parens.rs @@ -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; +}