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;
15 declare_clippy_lint! {
17 /// Checks for calls of `unwrap[_err]()` that cannot fail.
19 /// ### Why is this bad?
20 /// Using `if let` or `match` is more idiomatic.
24 /// # let option = Some(0);
25 /// # fn do_something_with(_x: usize) {}
26 /// if option.is_some() {
27 /// do_something_with(option.unwrap())
34 /// # let option = Some(0);
35 /// # fn do_something_with(_x: usize) {}
36 /// if let Some(value) = option {
37 /// do_something_with(value)
40 pub UNNECESSARY_UNWRAP,
42 "checks for calls of `unwrap[_err]()` that cannot fail"
45 declare_clippy_lint! {
47 /// Checks for calls of `unwrap[_err]()` that will always fail.
49 /// ### Why is this bad?
50 /// If panicking is desired, an explicit `panic!()` should be used.
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.
58 /// # let option = Some(0);
59 /// # fn do_something_with(_x: usize) {}
60 /// if option.is_none() {
61 /// do_something_with(option.unwrap())
65 /// This code will always panic. The if condition should probably be inverted.
68 "checks for calls of `unwrap[_err]()` that will always fail"
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>,
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()`).
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>,
94 branch: &'tcx Expr<'_>,
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)
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)
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));
114 } else if let ExprKind::Unary(UnOp::Not, expr) = &expr.kind {
115 return collect_unwrap_info(cx, expr, branch, !invert);
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);
124 assert!(args.len() == 1);
125 let unwrappable = match name.as_ref() {
126 "is_some" | "is_ok" => true,
127 "is_err" | "is_none" => false,
130 let safe_to_unwrap = unwrappable != invert;
131 return vec![UnwrapInfo { ident: path, check: expr, branch, safe_to_unwrap }];
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)
145 // if the variable is mutated, we don't know whether it can be unwrapped:
148 self.unwrappables.push(unwrap_info);
150 walk_expr(self, branch);
151 self.unwrappables.truncate(prev_len);
155 impl<'a, 'tcx> Visitor<'tcx> for UnwrappableVariablesVisitor<'a, 'tcx> {
156 type Map = Map<'tcx>;
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) {
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);
170 // find `unwrap[_err]()` calls:
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);
182 if call_to_unwrap == unwrappable.safe_to_unwrap {
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"); },
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"); },
204 walk_expr(self, expr);
208 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
209 NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
213 declare_lint_pass!(Unwrap => [PANICKING_UNWRAP, UNNECESSARY_UNWRAP]);
215 impl<'tcx> LateLintPass<'tcx> for Unwrap {
218 cx: &LateContext<'tcx>,
220 decl: &'tcx FnDecl<'_>,
221 body: &'tcx Body<'_>,
225 if span.from_expansion() {
229 let mut v = UnwrappableVariablesVisitor {
231 unwrappables: Vec::new(),
234 walk_fn(&mut v, kind, decl, body.id(), span, fn_id);