1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
10 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
11 use crate::rustc::{declare_tool_lint, lint_array};
12 use if_chain::if_chain;
14 use crate::rustc::hir::intravisit::*;
15 use crate::rustc::hir::*;
16 use crate::syntax::ast::NodeId;
17 use crate::syntax::source_map::Span;
18 use crate::utils::{in_macro, match_type, paths, span_lint_and_then, usage::is_potentially_mutated};
20 /// **What it does:** Checks for calls of `unwrap[_err]()` that cannot fail.
22 /// **Why is this bad?** Using `if let` or `match` is more idiomatic.
24 /// **Known problems:** Limitations of the borrow checker might make unwrap() necessary sometimes?
28 /// if option.is_some() {
29 /// do_something_with(option.unwrap())
36 /// if let Some(value) = option {
37 /// do_something_with(value)
40 declare_clippy_lint! {
41 pub UNNECESSARY_UNWRAP,
43 "checks for calls of unwrap[_err]() that cannot fail"
46 /// **What it does:** Checks for calls of `unwrap[_err]()` that will always fail.
48 /// **Why is this bad?** If panicking is desired, an explicit `panic!()` should be used.
50 /// **Known problems:** This lint only checks `if` conditions not assignments.
51 /// So something like `let x: Option<()> = None; x.unwrap();` will not be recognized.
55 /// if option.is_none() {
56 /// do_something_with(option.unwrap())
60 /// This code will always panic. The if condition should probably be inverted.
61 declare_clippy_lint! {
64 "checks for calls of unwrap[_err]() that will always fail"
69 /// Visitor that keeps track of which variables are unwrappable.
70 struct UnwrappableVariablesVisitor<'a, 'tcx: 'a> {
71 unwrappables: Vec<UnwrapInfo<'tcx>>,
72 cx: &'a LateContext<'a, 'tcx>,
74 /// Contains information about whether a variable can be unwrapped.
75 #[derive(Copy, Clone, Debug)]
76 struct UnwrapInfo<'tcx> {
77 /// The variable that is checked
79 /// The check, like `x.is_ok()`
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: 'a>(
88 cx: &'a LateContext<'a, 'tcx>,
91 ) -> Vec<UnwrapInfo<'tcx>> {
92 if let ExprKind::Binary(op, left, right) = &expr.node {
93 match (invert, op.node) {
94 (false, BinOpKind::And) | (false, BinOpKind::BitAnd) | (true, BinOpKind::Or) | (true, BinOpKind::BitOr) => {
95 let mut unwrap_info = collect_unwrap_info(cx, left, invert);
96 unwrap_info.append(&mut collect_unwrap_info(cx, right, invert));
101 } else if let ExprKind::Unary(UnNot, expr) = &expr.node {
102 return collect_unwrap_info(cx, expr, !invert);
105 if let ExprKind::MethodCall(method_name, _, args) = &expr.node;
106 if let ExprKind::Path(QPath::Resolved(None, path)) = &args[0].node;
107 let ty = cx.tables.expr_ty(&args[0]);
108 if match_type(cx, ty, &paths::OPTION) || match_type(cx, ty, &paths::RESULT);
109 let name = method_name.ident.as_str();
110 if ["is_some", "is_none", "is_ok", "is_err"].contains(&&*name);
112 assert!(args.len() == 1);
113 let unwrappable = match name.as_ref() {
114 "is_some" | "is_ok" => true,
115 "is_err" | "is_none" => false,
118 let safe_to_unwrap = unwrappable != invert;
119 return vec![UnwrapInfo { ident: path, check: expr, safe_to_unwrap }];
126 impl<'a, 'tcx: 'a> UnwrappableVariablesVisitor<'a, 'tcx> {
127 fn visit_branch(&mut self, cond: &'tcx Expr, branch: &'tcx Expr, else_branch: bool) {
128 let prev_len = self.unwrappables.len();
129 for unwrap_info in collect_unwrap_info(self.cx, cond, else_branch) {
130 if is_potentially_mutated(unwrap_info.ident, cond, self.cx)
131 || is_potentially_mutated(unwrap_info.ident, branch, self.cx)
133 // if the variable is mutated, we don't know whether it can be unwrapped:
136 self.unwrappables.push(unwrap_info);
138 walk_expr(self, branch);
139 self.unwrappables.truncate(prev_len);
143 impl<'a, 'tcx: 'a> Visitor<'tcx> for UnwrappableVariablesVisitor<'a, 'tcx> {
144 fn visit_expr(&mut self, expr: &'tcx Expr) {
145 if let ExprKind::If(cond, then, els) = &expr.node {
146 walk_expr(self, cond);
147 self.visit_branch(cond, then, false);
148 if let Some(els) = els {
149 self.visit_branch(cond, els, true);
152 // find `unwrap[_err]()` calls:
154 if let ExprKind::MethodCall(ref method_name, _, ref args) = expr.node;
155 if let ExprKind::Path(QPath::Resolved(None, ref path)) = args[0].node;
156 if ["unwrap", "unwrap_err"].contains(&&*method_name.ident.as_str());
157 let call_to_unwrap = method_name.ident.name == "unwrap";
158 if let Some(unwrappable) = self.unwrappables.iter()
159 .find(|u| u.ident.def == path.def);
161 if call_to_unwrap == unwrappable.safe_to_unwrap {
166 &format!("You checked before that `{}()` cannot fail. \
167 Instead of checking and unwrapping, it's better to use `if let` or `match`.",
168 method_name.ident.name),
169 |db| { db.span_label(unwrappable.check.span, "the check is happening here"); },
176 &format!("This call to `{}()` will always panic.",
177 method_name.ident.name),
178 |db| { db.span_label(unwrappable.check.span, "because of this check"); },
183 walk_expr(self, expr);
187 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
188 NestedVisitorMap::OnlyBodies(&self.cx.tcx.hir())
192 impl<'a> LintPass for Pass {
193 fn get_lints(&self) -> LintArray {
194 lint_array!(PANICKING_UNWRAP, UNNECESSARY_UNWRAP)
198 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
201 cx: &LateContext<'a, 'tcx>,
212 let mut v = UnwrappableVariablesVisitor {
214 unwrappables: Vec::new(),
217 walk_fn(&mut v, kind, decl, body.id(), span, fn_id);