2 differing_macro_contexts, higher::if_block, is_type_diagnostic_item, span_lint_and_then,
3 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_session::{declare_lint_pass, declare_tool_lint};
12 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<'a, '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<'a, 'tcx>(
88 cx: &'a LateContext<'a, 'tcx>,
90 branch: &'tcx Expr<'_>,
92 ) -> Vec<UnwrapInfo<'tcx>> {
93 if let ExprKind::Binary(op, left, right) = &expr.kind {
94 match (invert, op.node) {
95 (false, BinOpKind::And) | (false, BinOpKind::BitAnd) | (true, BinOpKind::Or) | (true, BinOpKind::BitOr) => {
96 let mut unwrap_info = collect_unwrap_info(cx, left, branch, invert);
97 unwrap_info.append(&mut collect_unwrap_info(cx, right, branch, invert));
102 } else if let ExprKind::Unary(UnOp::UnNot, expr) = &expr.kind {
103 return collect_unwrap_info(cx, expr, branch, !invert);
106 if let ExprKind::MethodCall(method_name, _, args) = &expr.kind;
107 if let ExprKind::Path(QPath::Resolved(None, path)) = &args[0].kind;
108 let ty = cx.tables.expr_ty(&args[0]);
109 if is_type_diagnostic_item(cx, ty, sym!(option_type)) || is_type_diagnostic_item(cx, ty, sym!(result_type));
110 let name = method_name.ident.as_str();
111 if ["is_some", "is_none", "is_ok", "is_err"].contains(&&*name);
113 assert!(args.len() == 1);
114 let unwrappable = match name.as_ref() {
115 "is_some" | "is_ok" => true,
116 "is_err" | "is_none" => false,
119 let safe_to_unwrap = unwrappable != invert;
120 return vec![UnwrapInfo { ident: path, check: expr, branch, safe_to_unwrap }];
127 impl<'a, 'tcx> UnwrappableVariablesVisitor<'a, 'tcx> {
128 fn visit_branch(&mut self, cond: &'tcx Expr<'_>, branch: &'tcx Expr<'_>, else_branch: bool) {
129 let prev_len = self.unwrappables.len();
130 for unwrap_info in collect_unwrap_info(self.cx, cond, branch, else_branch) {
131 if is_potentially_mutated(unwrap_info.ident, cond, self.cx)
132 || is_potentially_mutated(unwrap_info.ident, branch, self.cx)
134 // if the variable is mutated, we don't know whether it can be unwrapped:
137 self.unwrappables.push(unwrap_info);
139 walk_expr(self, branch);
140 self.unwrappables.truncate(prev_len);
144 impl<'a, 'tcx> Visitor<'tcx> for UnwrappableVariablesVisitor<'a, 'tcx> {
145 type Map = Map<'tcx>;
147 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
148 // Shouldn't lint when `expr` is in macro.
149 if in_external_macro(self.cx.tcx.sess, expr.span) {
152 if let Some((cond, then, els)) = if_block(&expr) {
153 walk_expr(self, cond);
154 self.visit_branch(cond, then, false);
155 if let Some(els) = els {
156 self.visit_branch(cond, els, true);
159 // find `unwrap[_err]()` calls:
161 if let ExprKind::MethodCall(ref method_name, _, ref args) = expr.kind;
162 if let ExprKind::Path(QPath::Resolved(None, ref path)) = args[0].kind;
163 if [sym!(unwrap), sym!(unwrap_err)].contains(&method_name.ident.name);
164 let call_to_unwrap = method_name.ident.name == sym!(unwrap);
165 if let Some(unwrappable) = self.unwrappables.iter()
166 .find(|u| u.ident.res == path.res);
167 // Span contexts should not differ with the conditional branch
168 if !differing_macro_contexts(unwrappable.branch.span, expr.span);
169 if !differing_macro_contexts(unwrappable.branch.span, unwrappable.check.span);
171 if call_to_unwrap == unwrappable.safe_to_unwrap {
176 &format!("You checked before that `{}()` cannot fail. \
177 Instead of checking and unwrapping, it's better to use `if let` or `match`.",
178 method_name.ident.name),
179 |diag| { diag.span_label(unwrappable.check.span, "the check is happening here"); },
186 &format!("This call to `{}()` will always panic.",
187 method_name.ident.name),
188 |diag| { diag.span_label(unwrappable.check.span, "because of this check"); },
193 walk_expr(self, expr);
197 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
198 NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
202 declare_lint_pass!(Unwrap => [PANICKING_UNWRAP, UNNECESSARY_UNWRAP]);
204 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Unwrap {
207 cx: &LateContext<'a, 'tcx>,
209 decl: &'tcx FnDecl<'_>,
210 body: &'tcx Body<'_>,
214 if span.from_expansion() {
218 let mut v = UnwrappableVariablesVisitor {
220 unwrappables: Vec::new(),
223 walk_fn(&mut v, kind, decl, body.id(), span, fn_id);