]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/unwrap.rs
Auto merge of #5040 - JohnTitor:rustup-0111, r=flip1995
[rust.git] / clippy_lints / src / unwrap.rs
1 use crate::utils::{higher::if_block, match_type, paths, span_lint_and_then, usage::is_potentially_mutated};
2 use if_chain::if_chain;
3 use rustc::hir::map::Map;
4 use rustc::lint::{LateContext, LateLintPass};
5 use rustc_hir::intravisit::*;
6 use rustc_hir::*;
7 use rustc_session::{declare_lint_pass, declare_tool_lint};
8 use rustc_span::source_map::Span;
9
10 declare_clippy_lint! {
11     /// **What it does:** Checks for calls of `unwrap[_err]()` that cannot fail.
12     ///
13     /// **Why is this bad?** Using `if let` or `match` is more idiomatic.
14     ///
15     /// **Known problems:** None
16     ///
17     /// **Example:**
18     /// ```rust
19     /// # let option = Some(0);
20     /// # fn do_something_with(_x: usize) {}
21     /// if option.is_some() {
22     ///     do_something_with(option.unwrap())
23     /// }
24     /// ```
25     ///
26     /// Could be written:
27     ///
28     /// ```rust
29     /// # let option = Some(0);
30     /// # fn do_something_with(_x: usize) {}
31     /// if let Some(value) = option {
32     ///     do_something_with(value)
33     /// }
34     /// ```
35     pub UNNECESSARY_UNWRAP,
36     complexity,
37     "checks for calls of `unwrap[_err]()` that cannot fail"
38 }
39
40 declare_clippy_lint! {
41     /// **What it does:** Checks for calls of `unwrap[_err]()` that will always fail.
42     ///
43     /// **Why is this bad?** If panicking is desired, an explicit `panic!()` should be used.
44     ///
45     /// **Known problems:** This lint only checks `if` conditions not assignments.
46     /// So something like `let x: Option<()> = None; x.unwrap();` will not be recognized.
47     ///
48     /// **Example:**
49     /// ```rust
50     /// # let option = Some(0);
51     /// # fn do_something_with(_x: usize) {}
52     /// if option.is_none() {
53     ///     do_something_with(option.unwrap())
54     /// }
55     /// ```
56     ///
57     /// This code will always panic. The if condition should probably be inverted.
58     pub PANICKING_UNWRAP,
59     correctness,
60     "checks for calls of `unwrap[_err]()` that will always fail"
61 }
62
63 /// Visitor that keeps track of which variables are unwrappable.
64 struct UnwrappableVariablesVisitor<'a, 'tcx> {
65     unwrappables: Vec<UnwrapInfo<'tcx>>,
66     cx: &'a LateContext<'a, 'tcx>,
67 }
68 /// Contains information about whether a variable can be unwrapped.
69 #[derive(Copy, Clone, Debug)]
70 struct UnwrapInfo<'tcx> {
71     /// The variable that is checked
72     ident: &'tcx Path<'tcx>,
73     /// The check, like `x.is_ok()`
74     check: &'tcx Expr<'tcx>,
75     /// Whether `is_some()` or `is_ok()` was called (as opposed to `is_err()` or `is_none()`).
76     safe_to_unwrap: bool,
77 }
78
79 /// Collects the information about unwrappable variables from an if condition
80 /// The `invert` argument tells us whether the condition is negated.
81 fn collect_unwrap_info<'a, 'tcx>(
82     cx: &'a LateContext<'a, 'tcx>,
83     expr: &'tcx Expr<'_>,
84     invert: bool,
85 ) -> Vec<UnwrapInfo<'tcx>> {
86     if let ExprKind::Binary(op, left, right) = &expr.kind {
87         match (invert, op.node) {
88             (false, BinOpKind::And) | (false, BinOpKind::BitAnd) | (true, BinOpKind::Or) | (true, BinOpKind::BitOr) => {
89                 let mut unwrap_info = collect_unwrap_info(cx, left, invert);
90                 unwrap_info.append(&mut collect_unwrap_info(cx, right, invert));
91                 return unwrap_info;
92             },
93             _ => (),
94         }
95     } else if let ExprKind::Unary(UnOp::UnNot, expr) = &expr.kind {
96         return collect_unwrap_info(cx, expr, !invert);
97     } else {
98         if_chain! {
99             if let ExprKind::MethodCall(method_name, _, args) = &expr.kind;
100             if let ExprKind::Path(QPath::Resolved(None, path)) = &args[0].kind;
101             let ty = cx.tables.expr_ty(&args[0]);
102             if match_type(cx, ty, &paths::OPTION) || match_type(cx, ty, &paths::RESULT);
103             let name = method_name.ident.as_str();
104             if ["is_some", "is_none", "is_ok", "is_err"].contains(&&*name);
105             then {
106                 assert!(args.len() == 1);
107                 let unwrappable = match name.as_ref() {
108                     "is_some" | "is_ok" => true,
109                     "is_err" | "is_none" => false,
110                     _ => unreachable!(),
111                 };
112                 let safe_to_unwrap = unwrappable != invert;
113                 return vec![UnwrapInfo { ident: path, check: expr, safe_to_unwrap }];
114             }
115         }
116     }
117     Vec::new()
118 }
119
120 impl<'a, 'tcx> UnwrappableVariablesVisitor<'a, 'tcx> {
121     fn visit_branch(&mut self, cond: &'tcx Expr<'_>, branch: &'tcx Expr<'_>, else_branch: bool) {
122         let prev_len = self.unwrappables.len();
123         for unwrap_info in collect_unwrap_info(self.cx, cond, else_branch) {
124             if is_potentially_mutated(unwrap_info.ident, cond, self.cx)
125                 || is_potentially_mutated(unwrap_info.ident, branch, self.cx)
126             {
127                 // if the variable is mutated, we don't know whether it can be unwrapped:
128                 continue;
129             }
130             self.unwrappables.push(unwrap_info);
131         }
132         walk_expr(self, branch);
133         self.unwrappables.truncate(prev_len);
134     }
135 }
136
137 impl<'a, 'tcx> Visitor<'tcx> for UnwrappableVariablesVisitor<'a, 'tcx> {
138     type Map = Map<'tcx>;
139
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.kind;
151                 if let ExprKind::Path(QPath::Resolved(None, ref path)) = args[0].kind;
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(&mut self) -> NestedVisitorMap<'_, Self::Map> {
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 span.from_expansion() {
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 }