]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/ok_if_let.rs
also run rustfmt on clippy-lints
[rust.git] / clippy_lints / src / ok_if_let.rs
1 use rustc::lint::*;
2 use rustc::hir::*;
3 use utils::{paths, method_chain_args, span_help_and_lint, match_type, snippet};
4
5 /// **What it does:*** Checks for unnecessary `ok()` in if let.
6 ///
7 /// **Why is this bad?** Calling `ok()` in if let is unnecessary, instead match on `Ok(pat)`
8 ///
9 /// **Known problems:** None.
10 ///
11 /// **Example:**
12 /// ```rust
13 /// for result in iter {
14 ///     if let Some(bench) = try!(result).parse().ok() {
15 ///         vec.push(bench)
16 ///     }
17 /// }
18 /// ```
19 /// Could be written:
20 ///
21 /// ```rust
22 /// for result in iter {
23 ///     if let Ok(bench) = try!(result).parse() {
24 ///         vec.push(bench)
25 ///     }
26 /// }
27 /// ```
28 declare_lint! {
29     pub IF_LET_SOME_RESULT,
30     Warn,
31     "usage of `ok()` in `if let Some(pat)` statements is unnecessary, match on `Ok(pat)` instead"
32 }
33
34 #[derive(Copy, Clone)]
35 pub struct Pass;
36
37 impl LintPass for Pass {
38     fn get_lints(&self) -> LintArray {
39         lint_array!(IF_LET_SOME_RESULT)
40     }
41 }
42
43 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
44     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
45         if_let_chain! {[ //begin checking variables
46             let ExprMatch(ref op, ref body, ref source) = expr.node, //test if expr is a match
47             let MatchSource::IfLetDesugar { .. } = *source, //test if it is an If Let
48             let ExprMethodCall(_, _, ref result_types) = op.node, //check is expr.ok() has type Result<T,E>.ok()
49             let PatKind::TupleStruct(QPath::Resolved(_, ref x), ref y, _)  = body[0].pats[0].node, //get operation
50             method_chain_args(op, &["ok"]).is_some() //test to see if using ok() methoduse std::marker::Sized;
51
52         ], {
53             let is_result_type = match_type(cx, cx.tcx.tables().expr_ty(&result_types[0]), &paths::RESULT);
54             let some_expr_string = snippet(cx, y[0].span, "");
55             if print::path_to_string(x) == "Some" && is_result_type {
56                 span_help_and_lint(cx, IF_LET_SOME_RESULT, expr.span,
57                 "Matching on `Some` with `ok()` is redundant",
58                 &format!("Consider matching on `Ok({})` and removing the call to `ok` instead", some_expr_string));
59             }
60         }}
61     }
62 }