]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/ok_if_let.rs
fixed array bounds checking
[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_opt};
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 /// ```rustc
13 /// for result in iter {
14 ///     if let Some(bench) = try!(result).parse().ok() {
15 ///         vec.push(bench)
16 ///     }
17 /// }
18 /// ```
19 declare_lint! {
20     pub IF_LET_SOME_RESULT,
21     Warn,
22     "usage of `ok()` in `if let Some(pat)` statements is unnecessary, match on `Ok(pat)` instead"
23 }
24
25 #[derive(Copy, Clone)]
26 pub struct OkIfLetPass;
27
28 impl LintPass for OkIfLetPass {
29     fn get_lints(&self) -> LintArray {
30         lint_array!(IF_LET_SOME_RESULT)
31     }
32 }
33
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;
42
43         ], {
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("");
46             if y.len() > 0 {
47                 if let Some(x) = snippet_opt(cx, y[0].span) {
48                     some_expr_string = x;
49                 }
50             }
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)); 
55             }
56         }}
57     }
58 }