rust/clippy_lints/src/double_parens.rs

69 lines
1.8 KiB
Rust
Raw Normal View History

use clippy_utils::diagnostics::span_lint;
2020-02-29 21:23:33 -06:00
use rustc_ast::ast::{Expr, ExprKind};
2020-01-12 00:08:41 -06:00
use rustc_lint::{EarlyContext, EarlyLintPass};
use rustc_session::declare_lint_pass;
2018-03-28 08:24:26 -05:00
declare_clippy_lint! {
/// ### What it does
/// Checks for unnecessary double parentheses.
///
/// ### Why is this bad?
/// This makes code harder to read and might indicate a
/// mistake.
///
/// ### Example
2023-10-23 08:49:18 -05:00
/// ```no_run
/// fn simple_double_parens() -> i32 {
/// ((0))
/// }
///
/// # fn foo(bar: usize) {}
/// foo((0));
/// ```
///
/// Use instead:
2023-10-23 08:49:18 -05:00
/// ```no_run
/// fn simple_no_parens() -> i32 {
/// 0
/// }
///
/// # fn foo(bar: usize) {}
/// foo(0);
/// ```
#[clippy::version = "pre 1.29.0"]
2018-03-28 08:24:26 -05:00
pub DOUBLE_PARENS,
complexity,
2016-12-28 12:54:23 -06:00
"Warn on unnecessary double parentheses"
}
2019-04-08 15:43:55 -05:00
declare_lint_pass!(DoubleParens => [DOUBLE_PARENS]);
2016-12-28 12:54:23 -06:00
impl EarlyLintPass for DoubleParens {
2018-07-23 06:01:12 -05:00
fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
let span = match &expr.kind {
ExprKind::Paren(in_paren) if matches!(in_paren.kind, ExprKind::Paren(_) | ExprKind::Tup(_)) => expr.span,
ExprKind::Call(_, params)
if let [param] = &**params
&& let ExprKind::Paren(_) = param.kind =>
{
param.span
2016-12-28 14:03:49 -06:00
},
ExprKind::MethodCall(call)
if let [arg] = &*call.args
&& let ExprKind::Paren(_) = arg.kind =>
{
arg.span
2016-12-28 14:03:49 -06:00
},
_ => return,
};
if !expr.span.from_expansion() {
span_lint(
cx,
DOUBLE_PARENS,
span,
"consider removing unnecessary double parentheses",
);
2016-12-28 14:03:49 -06:00
}
2016-12-28 12:54:23 -06:00
}
}