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