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