]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/unwrap.rs
Auto merge of #4307 - flip1995:unnecessary_unwrap, r=oli-obk
[rust.git] / clippy_lints / src / unwrap.rs
1 use if_chain::if_chain;
2 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
3 use rustc::{declare_lint_pass, declare_tool_lint};
4
5 use crate::utils::{
6     higher::if_block, in_macro_or_desugar, match_type, paths, span_lint_and_then, usage::is_potentially_mutated,
7 };
8 use rustc::hir::intravisit::*;
9 use rustc::hir::*;
10 use syntax::source_map::Span;
11
12 declare_clippy_lint! {
13     /// **What it does:** Checks for calls of `unwrap[_err]()` that cannot fail.
14     ///
15     /// **Why is this bad?** Using `if let` or `match` is more idiomatic.
16     ///
17     /// **Known problems:** None
18     ///
19     /// **Example:**
20     /// ```rust
21     /// # let option = Some(0);
22     /// # fn do_something_with(_x: usize) {}
23     /// if option.is_some() {
24     ///     do_something_with(option.unwrap())
25     /// }
26     /// ```
27     ///
28     /// Could be written:
29     ///
30     /// ```rust
31     /// # let option = Some(0);
32     /// # fn do_something_with(_x: usize) {}
33     /// if let Some(value) = option {
34     ///     do_something_with(value)
35     /// }
36     /// ```
37     pub UNNECESSARY_UNWRAP,
38     complexity,
39     "checks for calls of unwrap[_err]() that cannot fail"
40 }
41
42 declare_clippy_lint! {
43     /// **What it does:** Checks for calls of `unwrap[_err]()` that will always fail.
44     ///
45     /// **Why is this bad?** If panicking is desired, an explicit `panic!()` should be used.
46     ///
47     /// **Known problems:** This lint only checks `if` conditions not assignments.
48     /// So something like `let x: Option<()> = None; x.unwrap();` will not be recognized.
49     ///
50     /// **Example:**
51     /// ```rust
52     /// # let option = Some(0);
53     /// # fn do_something_with(_x: usize) {}
54     /// if option.is_none() {
55     ///     do_something_with(option.unwrap())
56     /// }
57     /// ```
58     ///
59     /// This code will always panic. The if condition should probably be inverted.
60     pub PANICKING_UNWRAP,
61     correctness,
62     "checks for calls of unwrap[_err]() that will always fail"
63 }
64
65 /// Visitor that keeps track of which variables are unwrappable.
66 struct UnwrappableVariablesVisitor<'a, 'tcx> {
67     unwrappables: Vec<UnwrapInfo<'tcx>>,
68     cx: &'a LateContext<'a, 'tcx>,
69 }
70 /// Contains information about whether a variable can be unwrapped.
71 #[derive(Copy, Clone, Debug)]
72 struct UnwrapInfo<'tcx> {
73     /// The variable that is checked
74     ident: &'tcx Path,
75     /// The check, like `x.is_ok()`
76     check: &'tcx Expr,
77     /// Whether `is_some()` or `is_ok()` was called (as opposed to `is_err()` or `is_none()`).
78     safe_to_unwrap: bool,
79 }
80
81 /// Collects the information about unwrappable variables from an if condition
82 /// The `invert` argument tells us whether the condition is negated.
83 fn collect_unwrap_info<'a, 'tcx>(
84     cx: &'a LateContext<'a, 'tcx>,
85     expr: &'tcx Expr,
86     invert: bool,
87 ) -> Vec<UnwrapInfo<'tcx>> {
88     if let ExprKind::Binary(op, left, right) = &expr.node {
89         match (invert, op.node) {
90             (false, BinOpKind::And) | (false, BinOpKind::BitAnd) | (true, BinOpKind::Or) | (true, BinOpKind::BitOr) => {
91                 let mut unwrap_info = collect_unwrap_info(cx, left, invert);
92                 unwrap_info.append(&mut collect_unwrap_info(cx, right, invert));
93                 return unwrap_info;
94             },
95             _ => (),
96         }
97     } else if let ExprKind::Unary(UnNot, expr) = &expr.node {
98         return collect_unwrap_info(cx, expr, !invert);
99     } else {
100         if_chain! {
101             if let ExprKind::MethodCall(method_name, _, args) = &expr.node;
102             if let ExprKind::Path(QPath::Resolved(None, path)) = &args[0].node;
103             let ty = cx.tables.expr_ty(&args[0]);
104             if match_type(cx, ty, &paths::OPTION) || match_type(cx, ty, &paths::RESULT);
105             let name = method_name.ident.as_str();
106             if ["is_some", "is_none", "is_ok", "is_err"].contains(&&*name);
107             then {
108                 assert!(args.len() == 1);
109                 let unwrappable = match name.as_ref() {
110                     "is_some" | "is_ok" => true,
111                     "is_err" | "is_none" => false,
112                     _ => unreachable!(),
113                 };
114                 let safe_to_unwrap = unwrappable != invert;
115                 return vec![UnwrapInfo { ident: path, check: expr, safe_to_unwrap }];
116             }
117         }
118     }
119     Vec::new()
120 }
121
122 impl<'a, 'tcx> UnwrappableVariablesVisitor<'a, 'tcx> {
123     fn visit_branch(&mut self, cond: &'tcx Expr, branch: &'tcx Expr, else_branch: bool) {
124         let prev_len = self.unwrappables.len();
125         for unwrap_info in collect_unwrap_info(self.cx, cond, else_branch) {
126             if is_potentially_mutated(unwrap_info.ident, cond, self.cx)
127                 || is_potentially_mutated(unwrap_info.ident, branch, self.cx)
128             {
129                 // if the variable is mutated, we don't know whether it can be unwrapped:
130                 continue;
131             }
132             self.unwrappables.push(unwrap_info);
133         }
134         walk_expr(self, branch);
135         self.unwrappables.truncate(prev_len);
136     }
137 }
138
139 impl<'a, 'tcx> Visitor<'tcx> for UnwrappableVariablesVisitor<'a, 'tcx> {
140     fn visit_expr(&mut self, expr: &'tcx Expr) {
141         if let Some((cond, then, els)) = if_block(&expr) {
142             walk_expr(self, cond);
143             self.visit_branch(cond, then, false);
144             if let Some(els) = els {
145                 self.visit_branch(cond, els, true);
146             }
147         } else {
148             // find `unwrap[_err]()` calls:
149             if_chain! {
150                 if let ExprKind::MethodCall(ref method_name, _, ref args) = expr.node;
151                 if let ExprKind::Path(QPath::Resolved(None, ref path)) = args[0].node;
152                 if [sym!(unwrap), sym!(unwrap_err)].contains(&method_name.ident.name);
153                 let call_to_unwrap = method_name.ident.name == sym!(unwrap);
154                 if let Some(unwrappable) = self.unwrappables.iter()
155                     .find(|u| u.ident.res == path.res);
156                 then {
157                     if call_to_unwrap == unwrappable.safe_to_unwrap {
158                         span_lint_and_then(
159                             self.cx,
160                             UNNECESSARY_UNWRAP,
161                             expr.span,
162                             &format!("You checked before that `{}()` cannot fail. \
163                             Instead of checking and unwrapping, it's better to use `if let` or `match`.",
164                             method_name.ident.name),
165                             |db| { db.span_label(unwrappable.check.span, "the check is happening here"); },
166                         );
167                     } else {
168                         span_lint_and_then(
169                             self.cx,
170                             PANICKING_UNWRAP,
171                             expr.span,
172                             &format!("This call to `{}()` will always panic.",
173                             method_name.ident.name),
174                             |db| { db.span_label(unwrappable.check.span, "because of this check"); },
175                         );
176                     }
177                 }
178             }
179             walk_expr(self, expr);
180         }
181     }
182
183     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
184         NestedVisitorMap::OnlyBodies(&self.cx.tcx.hir())
185     }
186 }
187
188 declare_lint_pass!(Unwrap => [PANICKING_UNWRAP, UNNECESSARY_UNWRAP]);
189
190 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Unwrap {
191     fn check_fn(
192         &mut self,
193         cx: &LateContext<'a, 'tcx>,
194         kind: FnKind<'tcx>,
195         decl: &'tcx FnDecl,
196         body: &'tcx Body,
197         span: Span,
198         fn_id: HirId,
199     ) {
200         if in_macro_or_desugar(span) {
201             return;
202         }
203
204         let mut v = UnwrappableVariablesVisitor {
205             cx,
206             unwrappables: Vec::new(),
207         };
208
209         walk_fn(&mut v, kind, decl, body.id(), span, fn_id);
210     }
211 }