3 use utils::{paths, method_chain_args, span_help_and_lint, match_type, snippet_opt};
5 /// **What it does:*** Checks for unnecessary `ok()` in if let.
7 /// **Why is this bad?** Calling `ok()` in if let is unnecessary, instead match on `Ok(pat)`
9 /// **Known problems:** None.
13 /// for result in iter {
14 /// if let Some(bench) = try!(result).parse().ok() {
20 pub IF_LET_SOME_RESULT,
22 "usage of `ok()` in `if let Some(pat)` statements is unnecessary, match on `Ok(pat)` instead"
25 #[derive(Copy, Clone)]
26 pub struct OkIfLetPass;
28 impl LintPass for OkIfLetPass {
29 fn get_lints(&self) -> LintArray {
30 lint_array!(IF_LET_SOME_RESULT)
34 impl LateLintPass for OkIfLetPass {
35 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
36 if_let_chain! {[ //begin checking variables
37 let ExprMatch(ref op, ref body, ref source) = expr.node, //test if expr is a match
38 let MatchSource::IfLetDesugar { .. } = *source, //test if it is an If Let
39 let ExprMethodCall(_, _, ref result_types) = op.node, //check is expr.ok() has type Result<T,E>.ok()
40 let PatKind::TupleStruct(ref x, ref y, _) = body[0].pats[0].node, //get operation
41 let Some(_) = method_chain_args(op, &["ok"]) //test to see if using ok() methoduse std::marker::Sized;
44 let is_result_type = match_type(cx, cx.tcx.expr_ty(&result_types[0]), &paths::RESULT);
45 let mut some_expr_string = String::from("");
47 if let Some(x) = snippet_opt(cx, y[0].span) {
51 if print::path_to_string(x) == "Some" && is_result_type {
52 span_help_and_lint(cx, IF_LET_SOME_RESULT, expr.span,
53 "Matching on `Some` with `ok()` is redundant",
54 &format!("Consider matching on `Ok({})` and removing the call to `ok` instead", some_expr_string));