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