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