rust-clippy/clippy_lints/src/if_let_redundant_pattern_matching.rs

91 lines
2.9 KiB
Rust
Raw Normal View History

use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
use crate::rustc::{declare_tool_lint, lint_array};
use crate::rustc::hir::*;
2018-05-30 08:15:50 +00:00
use crate::utils::{match_qpath, paths, snippet, span_lint_and_then};
2018-06-15 07:19:19 +00:00
/// **What it does:** Lint for redundant pattern matching over `Result` or
2017-08-09 07:30:56 +00:00
/// `Option`
///
2017-08-09 07:30:56 +00:00
/// **Why is this bad?** It's more concise and clear to just use the proper
/// utility function
///
/// **Known problems:** None.
///
/// **Example:**
///
/// ```rust
/// if let Ok(_) = Ok::<i32, i32>(42) {}
/// if let Err(_) = Err::<i32, i32>(42) {}
/// if let None = None::<()> {}
/// if let Some(_) = Some(42) {}
/// ```
///
/// The more idiomatic use would be:
///
/// ```rust
/// if Ok::<i32, i32>(42).is_ok() {}
/// if Err::<i32, i32>(42).is_err() {}
/// if None::<()>.is_none() {}
/// if Some(42).is_some() {}
/// ```
///
2018-03-28 13:24:26 +00:00
declare_clippy_lint! {
pub IF_LET_REDUNDANT_PATTERN_MATCHING,
2018-03-28 13:24:26 +00:00
style,
"use the proper utility function avoiding an `if let`"
}
#[derive(Copy, Clone)]
pub struct Pass;
impl LintPass for Pass {
fn get_lints(&self) -> LintArray {
lint_array!(IF_LET_REDUNDANT_PATTERN_MATCHING)
}
}
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
2018-07-12 07:30:57 +00:00
if let ExprKind::Match(ref op, ref arms, MatchSource::IfLetDesugar { .. }) = expr.node {
if arms[0].pats.len() == 1 {
let good_method = match arms[0].pats[0].node {
PatKind::TupleStruct(ref path, ref pats, _) if pats.len() == 1 => {
if let PatKind::Wild = pats[0].node {
if match_qpath(path, &paths::RESULT_OK) {
"is_ok()"
} else if match_qpath(path, &paths::RESULT_ERR) {
"is_err()"
} else if match_qpath(path, &paths::OPTION_SOME) {
"is_some()"
} else {
return;
}
} else {
2016-12-20 17:21:30 +00:00
return;
}
2016-12-20 17:21:30 +00:00
},
PatKind::Path(ref path) if match_qpath(path, &paths::OPTION_NONE) => "is_none()",
2016-12-20 17:21:30 +00:00
_ => return,
};
2017-09-05 09:33:04 +00:00
span_lint_and_then(
cx,
IF_LET_REDUNDANT_PATTERN_MATCHING,
arms[0].pats[0].span,
&format!("redundant pattern matching, consider using `{}`", good_method),
|db| {
let span = expr.span.with_hi(op.span.hi());
db.span_suggestion(
span,
"try this",
format!("if {}.{}", snippet(cx, op.span, "_"), good_method),
);
},
);
}
}
}
}