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