]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/unwrap.rs
Auto merge of #5345 - Toxyxer:add-lint-for-float-in-array-comparison, r=flip1995
[rust.git] / clippy_lints / src / unwrap.rs
1 use crate::utils::{higher::if_block, is_type_diagnostic_item, span_lint_and_then, usage::is_potentially_mutated};
2 use if_chain::if_chain;
3 use rustc_hir::intravisit::{walk_expr, walk_fn, FnKind, NestedVisitorMap, Visitor};
4 use rustc_hir::{BinOpKind, Body, Expr, ExprKind, FnDecl, HirId, Path, QPath, UnOp};
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_middle::hir::map::Map;
7 use rustc_middle::lint::in_external_macro;
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9 use rustc_span::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<'tcx>,
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(UnOp::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 is_type_diagnostic_item(cx, ty, sym!(option_type)) || is_type_diagnostic_item(cx, ty, sym!(result_type));
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     type Map = Map<'tcx>;
140
141     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
142         // Shouldn't lint when `expr` is in macro.
143         if in_external_macro(self.cx.tcx.sess, expr.span) {
144             return;
145         }
146         if let Some((cond, then, els)) = if_block(&expr) {
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.kind;
156                 if let ExprKind::Path(QPath::Resolved(None, ref path)) = args[0].kind;
157                 if [sym!(unwrap), sym!(unwrap_err)].contains(&method_name.ident.name);
158                 let call_to_unwrap = method_name.ident.name == sym!(unwrap);
159                 if let Some(unwrappable) = self.unwrappables.iter()
160                     .find(|u| u.ident.res == path.res);
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(&mut self) -> NestedVisitorMap<Self::Map> {
189         NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
190     }
191 }
192
193 declare_lint_pass!(Unwrap => [PANICKING_UNWRAP, UNNECESSARY_UNWRAP]);
194
195 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Unwrap {
196     fn check_fn(
197         &mut self,
198         cx: &LateContext<'a, 'tcx>,
199         kind: FnKind<'tcx>,
200         decl: &'tcx FnDecl<'_>,
201         body: &'tcx Body<'_>,
202         span: Span,
203         fn_id: HirId,
204     ) {
205         if span.from_expansion() {
206             return;
207         }
208
209         let mut v = UnwrappableVariablesVisitor {
210             cx,
211             unwrappables: Vec::new(),
212         };
213
214         walk_fn(&mut v, kind, decl, body.id(), span, fn_id);
215     }
216 }