|
| 1 | +use clippy_utils::diagnostics::span_lint_and_help; |
| 2 | +use rustc_ast::ast::{Expr, ExprKind, Path}; |
| 3 | +use rustc_ast::ast_traits::AstDeref; |
| 4 | +use rustc_ast::ptr::P; |
| 5 | +use rustc_lint::{EarlyContext, EarlyLintPass}; |
| 6 | +use rustc_session::{declare_lint_pass, declare_tool_lint}; |
| 7 | + |
| 8 | +declare_clippy_lint! { |
| 9 | + /// ### What it does |
| 10 | + /// Checks for cast which argument is parenthesized variable. |
| 11 | + /// |
| 12 | + /// ### Why is this bad? |
| 13 | + /// It's same effect as `variable as Type`, thus you don't need parentheses. |
| 14 | + /// |
| 15 | + /// ### Example |
| 16 | + /// ```rust |
| 17 | + /// fn no_op(arg_1: f64) {} |
| 18 | + /// |
| 19 | + /// let x = (1.0f32) as f64; |
| 20 | + /// let y = (2.0f32) as f64; |
| 21 | + /// no_op(y); |
| 22 | + /// ``` |
| 23 | + /// Use instead: |
| 24 | + /// ```rust |
| 25 | + /// fn no_op(arg_1: f64) {} |
| 26 | + /// |
| 27 | + /// let x = 1.0f32 as f64; |
| 28 | + /// let y = 2.0f32 as f64; |
| 29 | + /// no_op(y); |
| 30 | + /// ``` |
| 31 | + #[clippy::version = "1.70.0"] |
| 32 | + pub UNARY_PARENTHESIS_FOLLOWED_BY_CAST, |
| 33 | + complexity, |
| 34 | + "default lint description" |
| 35 | +} |
| 36 | +declare_lint_pass!(UnaryParenthesisFollowedByCast => [UNARY_PARENTHESIS_FOLLOWED_BY_CAST]); |
| 37 | + |
| 38 | +impl EarlyLintPass for UnaryParenthesisFollowedByCast { |
| 39 | + fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) { |
| 40 | + if let ExprKind::Cast(ref expr, _) = expr.kind |
| 41 | + && let ExprKind::Paren(ref parenthesized) = expr.kind |
| 42 | + && is_item_path_is_local_and_not_qualified(parenthesized) |
| 43 | + { |
| 44 | + span_lint_and_help( |
| 45 | + cx, |
| 46 | + UNARY_PARENTHESIS_FOLLOWED_BY_CAST, |
| 47 | + expr.span, |
| 48 | + "unnecessary parenthesis", |
| 49 | + None, |
| 50 | + "consider remove parenthesis" |
| 51 | + ); |
| 52 | + } |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +fn is_item_path_is_local_and_not_qualified(parenthesized: &P<Expr>) -> bool { |
| 57 | + if let ExprKind::Path(ref impl_qualifier, ref item_path) = parenthesized.ast_deref().kind |
| 58 | + && impl_qualifier.is_none() |
| 59 | + // is item_path local variable? |
| 60 | + && !item_path.is_global() |
| 61 | + && let Path { segments, .. } = item_path |
| 62 | + && segments.len() == 1 { |
| 63 | + true |
| 64 | + } else { |
| 65 | + false |
| 66 | + } |
| 67 | +} |
0 commit comments