]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/unwrap.rs
Merge commit '43a1777b89cf6791f9e20878b4e5e3ae907867a5' into clippyup
[rust.git] / src / tools / clippy / clippy_lints / src / unwrap.rs
1 use crate::utils::{
2     differing_macro_contexts, higher::if_block, is_type_diagnostic_item, span_lint_and_then,
3     usage::is_potentially_mutated,
4 };
5 use if_chain::if_chain;
6 use rustc_hir::intravisit::{walk_expr, walk_fn, FnKind, NestedVisitorMap, Visitor};
7 use rustc_hir::{BinOpKind, Body, Expr, ExprKind, FnDecl, HirId, Path, QPath, UnOp};
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_middle::hir::map::Map;
10 use rustc_middle::lint::in_external_macro;
11 use rustc_session::{declare_lint_pass, declare_tool_lint};
12 use rustc_span::source_map::Span;
13
14 declare_clippy_lint! {
15     /// **What it does:** Checks for calls of `unwrap[_err]()` that cannot fail.
16     ///
17     /// **Why is this bad?** Using `if let` or `match` is more idiomatic.
18     ///
19     /// **Known problems:** None
20     ///
21     /// **Example:**
22     /// ```rust
23     /// # let option = Some(0);
24     /// # fn do_something_with(_x: usize) {}
25     /// if option.is_some() {
26     ///     do_something_with(option.unwrap())
27     /// }
28     /// ```
29     ///
30     /// Could be written:
31     ///
32     /// ```rust
33     /// # let option = Some(0);
34     /// # fn do_something_with(_x: usize) {}
35     /// if let Some(value) = option {
36     ///     do_something_with(value)
37     /// }
38     /// ```
39     pub UNNECESSARY_UNWRAP,
40     complexity,
41     "checks for calls of `unwrap[_err]()` that cannot fail"
42 }
43
44 declare_clippy_lint! {
45     /// **What it does:** Checks for calls of `unwrap[_err]()` that will always fail.
46     ///
47     /// **Why is this bad?** If panicking is desired, an explicit `panic!()` should be used.
48     ///
49     /// **Known problems:** This lint only checks `if` conditions not assignments.
50     /// So something like `let x: Option<()> = None; x.unwrap();` will not be recognized.
51     ///
52     /// **Example:**
53     /// ```rust
54     /// # let option = Some(0);
55     /// # fn do_something_with(_x: usize) {}
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     pub PANICKING_UNWRAP,
63     correctness,
64     "checks for calls of `unwrap[_err]()` that will always fail"
65 }
66
67 /// Visitor that keeps track of which variables are unwrappable.
68 struct UnwrappableVariablesVisitor<'a, 'tcx> {
69     unwrappables: Vec<UnwrapInfo<'tcx>>,
70     cx: &'a LateContext<'a, 'tcx>,
71 }
72 /// Contains information about whether a variable can be unwrapped.
73 #[derive(Copy, Clone, Debug)]
74 struct UnwrapInfo<'tcx> {
75     /// The variable that is checked
76     ident: &'tcx Path<'tcx>,
77     /// The check, like `x.is_ok()`
78     check: &'tcx Expr<'tcx>,
79     /// The branch where the check takes place, like `if x.is_ok() { .. }`
80     branch: &'tcx Expr<'tcx>,
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>(
88     cx: &'a LateContext<'a, 'tcx>,
89     expr: &'tcx Expr<'_>,
90     branch: &'tcx Expr<'_>,
91     invert: bool,
92 ) -> Vec<UnwrapInfo<'tcx>> {
93     if let ExprKind::Binary(op, left, right) = &expr.kind {
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, branch, invert);
97                 unwrap_info.append(&mut collect_unwrap_info(cx, right, branch, invert));
98                 return unwrap_info;
99             },
100             _ => (),
101         }
102     } else if let ExprKind::Unary(UnOp::UnNot, expr) = &expr.kind {
103         return collect_unwrap_info(cx, expr, branch, !invert);
104     } else {
105         if_chain! {
106             if let ExprKind::MethodCall(method_name, _, args) = &expr.kind;
107             if let ExprKind::Path(QPath::Resolved(None, path)) = &args[0].kind;
108             let ty = cx.tables.expr_ty(&args[0]);
109             if is_type_diagnostic_item(cx, ty, sym!(option_type)) || is_type_diagnostic_item(cx, ty, sym!(result_type));
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, branch, safe_to_unwrap }];
121             }
122         }
123     }
124     Vec::new()
125 }
126
127 impl<'a, 'tcx> 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, branch, 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> Visitor<'tcx> for UnwrappableVariablesVisitor<'a, 'tcx> {
145     type Map = Map<'tcx>;
146
147     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
148         // Shouldn't lint when `expr` is in macro.
149         if in_external_macro(self.cx.tcx.sess, expr.span) {
150             return;
151         }
152         if let Some((cond, then, els)) = if_block(&expr) {
153             walk_expr(self, cond);
154             self.visit_branch(cond, then, false);
155             if let Some(els) = els {
156                 self.visit_branch(cond, els, true);
157             }
158         } else {
159             // find `unwrap[_err]()` calls:
160             if_chain! {
161                 if let ExprKind::MethodCall(ref method_name, _, ref args) = expr.kind;
162                 if let ExprKind::Path(QPath::Resolved(None, ref path)) = args[0].kind;
163                 if [sym!(unwrap), sym!(unwrap_err)].contains(&method_name.ident.name);
164                 let call_to_unwrap = method_name.ident.name == sym!(unwrap);
165                 if let Some(unwrappable) = self.unwrappables.iter()
166                     .find(|u| u.ident.res == path.res);
167                 // Span contexts should not differ with the conditional branch
168                 if !differing_macro_contexts(unwrappable.branch.span, expr.span);
169                 if !differing_macro_contexts(unwrappable.branch.span, unwrappable.check.span);
170                 then {
171                     if call_to_unwrap == unwrappable.safe_to_unwrap {
172                         span_lint_and_then(
173                             self.cx,
174                             UNNECESSARY_UNWRAP,
175                             expr.span,
176                             &format!("You checked before that `{}()` cannot fail. \
177                             Instead of checking and unwrapping, it's better to use `if let` or `match`.",
178                             method_name.ident.name),
179                             |diag| { diag.span_label(unwrappable.check.span, "the check is happening here"); },
180                         );
181                     } else {
182                         span_lint_and_then(
183                             self.cx,
184                             PANICKING_UNWRAP,
185                             expr.span,
186                             &format!("This call to `{}()` will always panic.",
187                             method_name.ident.name),
188                             |diag| { diag.span_label(unwrappable.check.span, "because of this check"); },
189                         );
190                     }
191                 }
192             }
193             walk_expr(self, expr);
194         }
195     }
196
197     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
198         NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
199     }
200 }
201
202 declare_lint_pass!(Unwrap => [PANICKING_UNWRAP, UNNECESSARY_UNWRAP]);
203
204 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Unwrap {
205     fn check_fn(
206         &mut self,
207         cx: &LateContext<'a, 'tcx>,
208         kind: FnKind<'tcx>,
209         decl: &'tcx FnDecl<'_>,
210         body: &'tcx Body<'_>,
211         span: Span,
212         fn_id: HirId,
213     ) {
214         if span.from_expansion() {
215             return;
216         }
217
218         let mut v = UnwrappableVariablesVisitor {
219             cx,
220             unwrappables: Vec::new(),
221         };
222
223         walk_fn(&mut v, kind, decl, body.id(), span, fn_id);
224     }
225 }