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, path_to_local, usage::is_potentially_mutated};
5 use if_chain::if_chain;
6 use rustc_errors::Applicability;
7 use rustc_hir::intravisit::{walk_expr, walk_fn, FnKind, NestedVisitorMap, Visitor};
8 use rustc_hir::{BinOpKind, Body, Expr, ExprKind, FnDecl, HirId, PathSegment, UnOp};
9 use rustc_lint::{LateContext, LateLintPass};
10 use rustc_middle::hir::map::Map;
11 use rustc_middle::lint::in_external_macro;
12 use rustc_middle::ty::Ty;
13 use rustc_session::{declare_lint_pass, declare_tool_lint};
14 use rustc_span::source_map::Span;
17 declare_clippy_lint! {
19 /// Checks for calls of `unwrap[_err]()` that cannot fail.
21 /// ### Why is this bad?
22 /// Using `if let` or `match` is more idiomatic.
26 /// # let option = Some(0);
27 /// # fn do_something_with(_x: usize) {}
28 /// if option.is_some() {
29 /// do_something_with(option.unwrap())
36 /// # let option = Some(0);
37 /// # fn do_something_with(_x: usize) {}
38 /// if let Some(value) = option {
39 /// do_something_with(value)
42 pub UNNECESSARY_UNWRAP,
44 "checks for calls of `unwrap[_err]()` that cannot fail"
47 declare_clippy_lint! {
49 /// Checks for calls of `unwrap[_err]()` that will always fail.
51 /// ### Why is this bad?
52 /// If panicking is desired, an explicit `panic!()` should be used.
54 /// ### Known problems
55 /// This lint only checks `if` conditions not assignments.
56 /// So something like `let x: Option<()> = None; x.unwrap();` will not be recognized.
60 /// # let option = Some(0);
61 /// # fn do_something_with(_x: usize) {}
62 /// if option.is_none() {
63 /// do_something_with(option.unwrap())
67 /// This code will always panic. The if condition should probably be inverted.
70 "checks for calls of `unwrap[_err]()` that will always fail"
73 /// Visitor that keeps track of which variables are unwrappable.
74 struct UnwrappableVariablesVisitor<'a, 'tcx> {
75 unwrappables: Vec<UnwrapInfo<'tcx>>,
76 cx: &'a LateContext<'tcx>,
79 /// What kind of unwrappable this is.
80 #[derive(Copy, Clone, Debug)]
81 enum UnwrappableKind {
86 impl UnwrappableKind {
87 fn success_variant_pattern(self) -> &'static str {
89 UnwrappableKind::Option => "Some(..)",
90 UnwrappableKind::Result => "Ok(..)",
94 fn error_variant_pattern(self) -> &'static str {
96 UnwrappableKind::Option => "None",
97 UnwrappableKind::Result => "Err(..)",
102 /// Contains information about whether a variable can be unwrapped.
103 #[derive(Copy, Clone, Debug)]
104 struct UnwrapInfo<'tcx> {
105 /// The variable that is checked
108 if_expr: &'tcx Expr<'tcx>,
109 /// The check, like `x.is_ok()`
110 check: &'tcx Expr<'tcx>,
111 /// The check's name, like `is_ok`
112 check_name: &'tcx PathSegment<'tcx>,
113 /// The branch where the check takes place, like `if x.is_ok() { .. }`
114 branch: &'tcx Expr<'tcx>,
115 /// Whether `is_some()` or `is_ok()` was called (as opposed to `is_err()` or `is_none()`).
116 safe_to_unwrap: bool,
117 /// What kind of unwrappable this is.
118 kind: UnwrappableKind,
119 /// If the check is the entire condition (`if x.is_ok()`) or only a part of it (`foo() &&
121 is_entire_condition: bool,
124 /// Collects the information about unwrappable variables from an if condition
125 /// The `invert` argument tells us whether the condition is negated.
126 fn collect_unwrap_info<'tcx>(
127 cx: &LateContext<'tcx>,
128 if_expr: &'tcx Expr<'_>,
129 expr: &'tcx Expr<'_>,
130 branch: &'tcx Expr<'_>,
132 is_entire_condition: bool,
133 ) -> Vec<UnwrapInfo<'tcx>> {
134 fn is_relevant_option_call(cx: &LateContext<'_>, ty: Ty<'_>, method_name: &str) -> bool {
135 is_type_diagnostic_item(cx, ty, sym::Option) && ["is_some", "is_none"].contains(&method_name)
138 fn is_relevant_result_call(cx: &LateContext<'_>, ty: Ty<'_>, method_name: &str) -> bool {
139 is_type_diagnostic_item(cx, ty, sym::Result) && ["is_ok", "is_err"].contains(&method_name)
142 if let ExprKind::Binary(op, left, right) = &expr.kind {
143 match (invert, op.node) {
144 (false, BinOpKind::And | BinOpKind::BitAnd) | (true, BinOpKind::Or | BinOpKind::BitOr) => {
145 let mut unwrap_info = collect_unwrap_info(cx, if_expr, left, branch, invert, false);
146 unwrap_info.append(&mut collect_unwrap_info(cx, if_expr, right, branch, invert, false));
151 } else if let ExprKind::Unary(UnOp::Not, expr) = &expr.kind {
152 return collect_unwrap_info(cx, if_expr, expr, branch, !invert, false);
155 if let ExprKind::MethodCall(method_name, _, args, _) = &expr.kind;
156 if let Some(local_id) = path_to_local(&args[0]);
157 let ty = cx.typeck_results().expr_ty(&args[0]);
158 let name = method_name.ident.as_str();
159 if is_relevant_option_call(cx, ty, &name) || is_relevant_result_call(cx, ty, &name);
161 assert!(args.len() == 1);
162 let unwrappable = match name.as_ref() {
163 "is_some" | "is_ok" => true,
164 "is_err" | "is_none" => false,
167 let safe_to_unwrap = unwrappable != invert;
168 let kind = if is_type_diagnostic_item(cx, ty, sym::Option) {
169 UnwrappableKind::Option
171 UnwrappableKind::Result
179 check_name: method_name,
192 impl<'a, 'tcx> UnwrappableVariablesVisitor<'a, 'tcx> {
195 if_expr: &'tcx Expr<'_>,
196 cond: &'tcx Expr<'_>,
197 branch: &'tcx Expr<'_>,
200 let prev_len = self.unwrappables.len();
201 for unwrap_info in collect_unwrap_info(self.cx, if_expr, cond, branch, else_branch, true) {
202 if is_potentially_mutated(unwrap_info.local_id, cond, self.cx)
203 || is_potentially_mutated(unwrap_info.local_id, branch, self.cx)
205 // if the variable is mutated, we don't know whether it can be unwrapped:
208 self.unwrappables.push(unwrap_info);
210 walk_expr(self, branch);
211 self.unwrappables.truncate(prev_len);
215 impl<'a, 'tcx> Visitor<'tcx> for UnwrappableVariablesVisitor<'a, 'tcx> {
216 type Map = Map<'tcx>;
218 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
219 // Shouldn't lint when `expr` is in macro.
220 if in_external_macro(self.cx.tcx.sess, expr.span) {
223 if let Some(higher::If { cond, then, r#else }) = higher::If::hir(expr) {
224 walk_expr(self, cond);
225 self.visit_branch(expr, cond, then, false);
226 if let Some(else_inner) = r#else {
227 self.visit_branch(expr, cond, else_inner, true);
230 // find `unwrap[_err]()` calls:
232 if let ExprKind::MethodCall(method_name, _, args, _) = expr.kind;
233 if let Some(id) = path_to_local(&args[0]);
234 if [sym::unwrap, sym::expect, sym!(unwrap_err)].contains(&method_name.ident.name);
235 let call_to_unwrap = [sym::unwrap, sym::expect].contains(&method_name.ident.name);
236 if let Some(unwrappable) = self.unwrappables.iter()
237 .find(|u| u.local_id == id);
238 // Span contexts should not differ with the conditional branch
239 if !differing_macro_contexts(unwrappable.branch.span, expr.span);
240 if !differing_macro_contexts(unwrappable.branch.span, unwrappable.check.span);
242 if call_to_unwrap == unwrappable.safe_to_unwrap {
243 let is_entire_condition = unwrappable.is_entire_condition;
244 let unwrappable_variable_name = self.cx.tcx.hir().name(unwrappable.local_id);
245 let suggested_pattern = if call_to_unwrap {
246 unwrappable.kind.success_variant_pattern()
248 unwrappable.kind.error_variant_pattern()
256 "called `{}` on `{}` after checking its variant with `{}`",
257 method_name.ident.name,
258 unwrappable_variable_name,
259 unwrappable.check_name.ident.as_str(),
262 if is_entire_condition {
263 diag.span_suggestion(
264 unwrappable.check.span.with_lo(unwrappable.if_expr.span.lo()),
269 unwrappable_variable_name,
271 // We don't track how the unwrapped value is used inside the
272 // block or suggest deleting the unwrap, so we can't offer a
274 Applicability::Unspecified,
277 diag.span_label(unwrappable.check.span, "the check is happening here");
278 diag.help("try using `if let` or `match`");
287 &format!("this call to `{}()` will always panic",
288 method_name.ident.name),
289 |diag| { diag.span_label(unwrappable.check.span, "because of this check"); },
294 walk_expr(self, expr);
298 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
299 NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
303 declare_lint_pass!(Unwrap => [PANICKING_UNWRAP, UNNECESSARY_UNWRAP]);
305 impl<'tcx> LateLintPass<'tcx> for Unwrap {
308 cx: &LateContext<'tcx>,
310 decl: &'tcx FnDecl<'_>,
311 body: &'tcx Body<'_>,
315 if span.from_expansion() {
319 let mut v = UnwrappableVariablesVisitor {
321 unwrappables: Vec::new(),
324 walk_fn(&mut v, kind, decl, body.id(), span, fn_id);