1 use crate::utils::{differing_macro_contexts, span_lint_and_then, usage::is_potentially_mutated};
2 use clippy_utils::ty::is_type_diagnostic_item;
3 use if_chain::if_chain;
4 use rustc_hir::intravisit::{walk_expr, walk_fn, FnKind, NestedVisitorMap, Visitor};
5 use rustc_hir::{BinOpKind, Body, Expr, ExprKind, FnDecl, HirId, Path, QPath, UnOp};
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_middle::hir::map::Map;
8 use rustc_middle::lint::in_external_macro;
9 use rustc_middle::ty::Ty;
10 use rustc_session::{declare_lint_pass, declare_tool_lint};
11 use rustc_span::source_map::Span;
14 declare_clippy_lint! {
15 /// **What it does:** Checks for calls of `unwrap[_err]()` that cannot fail.
17 /// **Why is this bad?** Using `if let` or `match` is more idiomatic.
19 /// **Known problems:** None
23 /// # let option = Some(0);
24 /// # fn do_something_with(_x: usize) {}
25 /// if option.is_some() {
26 /// do_something_with(option.unwrap())
33 /// # let option = Some(0);
34 /// # fn do_something_with(_x: usize) {}
35 /// if let Some(value) = option {
36 /// do_something_with(value)
39 pub UNNECESSARY_UNWRAP,
41 "checks for calls of `unwrap[_err]()` that cannot fail"
44 declare_clippy_lint! {
45 /// **What it does:** Checks for calls of `unwrap[_err]()` that will always fail.
47 /// **Why is this bad?** If panicking is desired, an explicit `panic!()` should be used.
49 /// **Known problems:** This lint only checks `if` conditions not assignments.
50 /// So something like `let x: Option<()> = None; x.unwrap();` will not be recognized.
54 /// # let option = Some(0);
55 /// # fn do_something_with(_x: usize) {}
56 /// if option.is_none() {
57 /// do_something_with(option.unwrap())
61 /// This code will always panic. The if condition should probably be inverted.
64 "checks for calls of `unwrap[_err]()` that will always fail"
67 /// Visitor that keeps track of which variables are unwrappable.
68 struct UnwrappableVariablesVisitor<'a, 'tcx> {
69 unwrappables: Vec<UnwrapInfo<'tcx>>,
70 cx: &'a LateContext<'tcx>,
72 /// Contains information about whether a variable can be unwrapped.
73 #[derive(Copy, Clone, Debug)]
74 struct UnwrapInfo<'tcx> {
75 /// The variable that is checked
76 ident: &'tcx Path<'tcx>,
77 /// The check, like `x.is_ok()`
78 check: &'tcx Expr<'tcx>,
79 /// The branch where the check takes place, like `if x.is_ok() { .. }`
80 branch: &'tcx Expr<'tcx>,
81 /// Whether `is_some()` or `is_ok()` was called (as opposed to `is_err()` or `is_none()`).
85 /// Collects the information about unwrappable variables from an if condition
86 /// The `invert` argument tells us whether the condition is negated.
87 fn collect_unwrap_info<'tcx>(
88 cx: &LateContext<'tcx>,
90 branch: &'tcx Expr<'_>,
92 ) -> Vec<UnwrapInfo<'tcx>> {
93 fn is_relevant_option_call(cx: &LateContext<'_>, ty: Ty<'_>, method_name: &str) -> bool {
94 is_type_diagnostic_item(cx, ty, sym::option_type) && ["is_some", "is_none"].contains(&method_name)
97 fn is_relevant_result_call(cx: &LateContext<'_>, ty: Ty<'_>, method_name: &str) -> bool {
98 is_type_diagnostic_item(cx, ty, sym::result_type) && ["is_ok", "is_err"].contains(&method_name)
101 if let ExprKind::Binary(op, left, right) = &expr.kind {
102 match (invert, op.node) {
103 (false, BinOpKind::And | BinOpKind::BitAnd) | (true, BinOpKind::Or | BinOpKind::BitOr) => {
104 let mut unwrap_info = collect_unwrap_info(cx, left, branch, invert);
105 unwrap_info.append(&mut collect_unwrap_info(cx, right, branch, invert));
110 } else if let ExprKind::Unary(UnOp::Not, expr) = &expr.kind {
111 return collect_unwrap_info(cx, expr, branch, !invert);
114 if let ExprKind::MethodCall(method_name, _, args, _) = &expr.kind;
115 if let ExprKind::Path(QPath::Resolved(None, path)) = &args[0].kind;
116 let ty = cx.typeck_results().expr_ty(&args[0]);
117 let name = method_name.ident.as_str();
118 if is_relevant_option_call(cx, ty, &name) || is_relevant_result_call(cx, ty, &name);
120 assert!(args.len() == 1);
121 let unwrappable = match name.as_ref() {
122 "is_some" | "is_ok" => true,
123 "is_err" | "is_none" => false,
126 let safe_to_unwrap = unwrappable != invert;
127 return vec![UnwrapInfo { ident: path, check: expr, branch, safe_to_unwrap }];
134 impl<'a, 'tcx> UnwrappableVariablesVisitor<'a, 'tcx> {
135 fn visit_branch(&mut self, cond: &'tcx Expr<'_>, branch: &'tcx Expr<'_>, else_branch: bool) {
136 let prev_len = self.unwrappables.len();
137 for unwrap_info in collect_unwrap_info(self.cx, cond, branch, else_branch) {
138 if is_potentially_mutated(unwrap_info.ident, cond, self.cx)
139 || is_potentially_mutated(unwrap_info.ident, branch, self.cx)
141 // if the variable is mutated, we don't know whether it can be unwrapped:
144 self.unwrappables.push(unwrap_info);
146 walk_expr(self, branch);
147 self.unwrappables.truncate(prev_len);
151 impl<'a, 'tcx> Visitor<'tcx> for UnwrappableVariablesVisitor<'a, 'tcx> {
152 type Map = Map<'tcx>;
154 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
155 // Shouldn't lint when `expr` is in macro.
156 if in_external_macro(self.cx.tcx.sess, expr.span) {
159 if let ExprKind::If(cond, then, els) = &expr.kind {
160 walk_expr(self, cond);
161 self.visit_branch(cond, then, false);
162 if let Some(els) = els {
163 self.visit_branch(cond, els, true);
166 // find `unwrap[_err]()` calls:
168 if let ExprKind::MethodCall(ref method_name, _, ref args, _) = expr.kind;
169 if let ExprKind::Path(QPath::Resolved(None, ref path)) = args[0].kind;
170 if [sym::unwrap, sym!(unwrap_err)].contains(&method_name.ident.name);
171 let call_to_unwrap = method_name.ident.name == sym::unwrap;
172 if let Some(unwrappable) = self.unwrappables.iter()
173 .find(|u| u.ident.res == path.res);
174 // Span contexts should not differ with the conditional branch
175 if !differing_macro_contexts(unwrappable.branch.span, expr.span);
176 if !differing_macro_contexts(unwrappable.branch.span, unwrappable.check.span);
178 if call_to_unwrap == unwrappable.safe_to_unwrap {
183 &format!("you checked before that `{}()` cannot fail, \
184 instead of checking and unwrapping, it's better to use `if let` or `match`",
185 method_name.ident.name),
186 |diag| { diag.span_label(unwrappable.check.span, "the check is happening here"); },
193 &format!("this call to `{}()` will always panic",
194 method_name.ident.name),
195 |diag| { diag.span_label(unwrappable.check.span, "because of this check"); },
200 walk_expr(self, expr);
204 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
205 NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
209 declare_lint_pass!(Unwrap => [PANICKING_UNWRAP, UNNECESSARY_UNWRAP]);
211 impl<'tcx> LateLintPass<'tcx> for Unwrap {
214 cx: &LateContext<'tcx>,
216 decl: &'tcx FnDecl<'_>,
217 body: &'tcx Body<'_>,
221 if span.from_expansion() {
225 let mut v = UnwrappableVariablesVisitor {
227 unwrappables: Vec::new(),
230 walk_fn(&mut v, kind, decl, body.id(), span, fn_id);