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