1 use crate::utils::{higher::if_block, is_type_diagnostic_item, span_lint_and_then, usage::is_potentially_mutated};
2 use if_chain::if_chain;
3 use rustc_hir::intravisit::{walk_expr, walk_fn, FnKind, NestedVisitorMap, Visitor};
4 use rustc_hir::{BinOpKind, Body, Expr, ExprKind, FnDecl, HirId, Path, QPath, UnOp};
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_middle::hir::map::Map;
7 use rustc_middle::lint::in_external_macro;
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9 use rustc_span::source_map::Span;
11 declare_clippy_lint! {
12 /// **What it does:** Checks for calls of `unwrap[_err]()` that cannot fail.
14 /// **Why is this bad?** Using `if let` or `match` is more idiomatic.
16 /// **Known problems:** None
20 /// # let option = Some(0);
21 /// # fn do_something_with(_x: usize) {}
22 /// if option.is_some() {
23 /// do_something_with(option.unwrap())
30 /// # let option = Some(0);
31 /// # fn do_something_with(_x: usize) {}
32 /// if let Some(value) = option {
33 /// do_something_with(value)
36 pub UNNECESSARY_UNWRAP,
38 "checks for calls of `unwrap[_err]()` that cannot fail"
41 declare_clippy_lint! {
42 /// **What it does:** Checks for calls of `unwrap[_err]()` that will always fail.
44 /// **Why is this bad?** If panicking is desired, an explicit `panic!()` should be used.
46 /// **Known problems:** This lint only checks `if` conditions not assignments.
47 /// So something like `let x: Option<()> = None; x.unwrap();` will not be recognized.
51 /// # let option = Some(0);
52 /// # fn do_something_with(_x: usize) {}
53 /// if option.is_none() {
54 /// do_something_with(option.unwrap())
58 /// This code will always panic. The if condition should probably be inverted.
61 "checks for calls of `unwrap[_err]()` that will always fail"
64 /// Visitor that keeps track of which variables are unwrappable.
65 struct UnwrappableVariablesVisitor<'a, 'tcx> {
66 unwrappables: Vec<UnwrapInfo<'tcx>>,
67 cx: &'a LateContext<'a, 'tcx>,
69 /// Contains information about whether a variable can be unwrapped.
70 #[derive(Copy, Clone, Debug)]
71 struct UnwrapInfo<'tcx> {
72 /// The variable that is checked
73 ident: &'tcx Path<'tcx>,
74 /// The check, like `x.is_ok()`
75 check: &'tcx Expr<'tcx>,
76 /// Whether `is_some()` or `is_ok()` was called (as opposed to `is_err()` or `is_none()`).
80 /// Collects the information about unwrappable variables from an if condition
81 /// The `invert` argument tells us whether the condition is negated.
82 fn collect_unwrap_info<'a, 'tcx>(
83 cx: &'a LateContext<'a, 'tcx>,
86 ) -> Vec<UnwrapInfo<'tcx>> {
87 if let ExprKind::Binary(op, left, right) = &expr.kind {
88 match (invert, op.node) {
89 (false, BinOpKind::And) | (false, BinOpKind::BitAnd) | (true, BinOpKind::Or) | (true, BinOpKind::BitOr) => {
90 let mut unwrap_info = collect_unwrap_info(cx, left, invert);
91 unwrap_info.append(&mut collect_unwrap_info(cx, right, invert));
96 } else if let ExprKind::Unary(UnOp::UnNot, expr) = &expr.kind {
97 return collect_unwrap_info(cx, expr, !invert);
100 if let ExprKind::MethodCall(method_name, _, args) = &expr.kind;
101 if let ExprKind::Path(QPath::Resolved(None, path)) = &args[0].kind;
102 let ty = cx.tables.expr_ty(&args[0]);
103 if is_type_diagnostic_item(cx, ty, sym!(option_type)) || is_type_diagnostic_item(cx, ty, sym!(result_type));
104 let name = method_name.ident.as_str();
105 if ["is_some", "is_none", "is_ok", "is_err"].contains(&&*name);
107 assert!(args.len() == 1);
108 let unwrappable = match name.as_ref() {
109 "is_some" | "is_ok" => true,
110 "is_err" | "is_none" => false,
113 let safe_to_unwrap = unwrappable != invert;
114 return vec![UnwrapInfo { ident: path, check: expr, safe_to_unwrap }];
121 impl<'a, 'tcx> UnwrappableVariablesVisitor<'a, 'tcx> {
122 fn visit_branch(&mut self, cond: &'tcx Expr<'_>, branch: &'tcx Expr<'_>, else_branch: bool) {
123 let prev_len = self.unwrappables.len();
124 for unwrap_info in collect_unwrap_info(self.cx, cond, else_branch) {
125 if is_potentially_mutated(unwrap_info.ident, cond, self.cx)
126 || is_potentially_mutated(unwrap_info.ident, branch, self.cx)
128 // if the variable is mutated, we don't know whether it can be unwrapped:
131 self.unwrappables.push(unwrap_info);
133 walk_expr(self, branch);
134 self.unwrappables.truncate(prev_len);
138 impl<'a, 'tcx> Visitor<'tcx> for UnwrappableVariablesVisitor<'a, 'tcx> {
139 type Map = Map<'tcx>;
141 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
142 // Shouldn't lint when `expr` is in macro.
143 if in_external_macro(self.cx.tcx.sess, expr.span) {
146 if let Some((cond, then, els)) = if_block(&expr) {
147 walk_expr(self, cond);
148 self.visit_branch(cond, then, false);
149 if let Some(els) = els {
150 self.visit_branch(cond, els, true);
153 // find `unwrap[_err]()` calls:
155 if let ExprKind::MethodCall(ref method_name, _, ref args) = expr.kind;
156 if let ExprKind::Path(QPath::Resolved(None, ref path)) = args[0].kind;
157 if [sym!(unwrap), sym!(unwrap_err)].contains(&method_name.ident.name);
158 let call_to_unwrap = method_name.ident.name == sym!(unwrap);
159 if let Some(unwrappable) = self.unwrappables.iter()
160 .find(|u| u.ident.res == path.res);
162 if call_to_unwrap == unwrappable.safe_to_unwrap {
167 &format!("You checked before that `{}()` cannot fail. \
168 Instead of checking and unwrapping, it's better to use `if let` or `match`.",
169 method_name.ident.name),
170 |diag| { diag.span_label(unwrappable.check.span, "the check is happening here"); },
177 &format!("This call to `{}()` will always panic.",
178 method_name.ident.name),
179 |diag| { diag.span_label(unwrappable.check.span, "because of this check"); },
184 walk_expr(self, expr);
188 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
189 NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
193 declare_lint_pass!(Unwrap => [PANICKING_UNWRAP, UNNECESSARY_UNWRAP]);
195 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Unwrap {
198 cx: &LateContext<'a, 'tcx>,
200 decl: &'tcx FnDecl<'_>,
201 body: &'tcx Body<'_>,
205 if span.from_expansion() {
209 let mut v = UnwrappableVariablesVisitor {
211 unwrappables: Vec::new(),
214 walk_fn(&mut v, kind, decl, body.id(), span, fn_id);