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.
11 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
12 use crate::rustc::{declare_tool_lint, lint_array};
13 use if_chain::if_chain;
15 use crate::utils::{in_macro, match_type, paths, span_lint_and_then, usage::is_potentially_mutated};
16 use crate::rustc::hir::intravisit::*;
17 use crate::rustc::hir::*;
18 use crate::syntax::ast::NodeId;
19 use crate::syntax::source_map::Span;
21 /// **What it does:** Checks for calls of `unwrap[_err]()` that cannot fail.
23 /// **Why is this bad?** Using `if let` or `match` is more idiomatic.
25 /// **Known problems:** Limitations of the borrow checker might make unwrap() necessary sometimes?
29 /// if option.is_some() {
30 /// do_something_with(option.unwrap())
37 /// if let Some(value) = option {
38 /// do_something_with(value)
41 declare_clippy_lint! {
42 pub UNNECESSARY_UNWRAP,
44 "checks for calls of unwrap[_err]() that cannot fail"
47 /// **What it does:** Checks for calls of `unwrap[_err]()` that will always fail.
49 /// **Why is this bad?** If panicking is desired, an explicit `panic!()` should be used.
51 /// **Known problems:** This lint only checks `if` conditions not assignments.
52 /// So something like `let x: Option<()> = None; x.unwrap();` will not be recognized.
56 /// if option.is_none() {
57 /// do_something_with(option.unwrap())
61 /// This code will always panic. The if condition should probably be inverted.
62 declare_clippy_lint! {
65 "checks for calls of unwrap[_err]() that will always fail"
70 /// Visitor that keeps track of which variables are unwrappable.
71 struct UnwrappableVariablesVisitor<'a, 'tcx: 'a> {
72 unwrappables: Vec<UnwrapInfo<'tcx>>,
73 cx: &'a LateContext<'a, 'tcx>,
75 /// Contains information about whether a variable can be unwrapped.
76 #[derive(Copy, Clone, Debug)]
77 struct UnwrapInfo<'tcx> {
78 /// The variable that is checked
80 /// The check, like `x.is_ok()`
82 /// Whether `is_some()` or `is_ok()` was called (as opposed to `is_err()` or `is_none()`).
86 /// Collects the information about unwrappable variables from an if condition
87 /// The `invert` argument tells us whether the condition is negated.
88 fn collect_unwrap_info<'a, 'tcx: 'a>(
89 cx: &'a LateContext<'a, 'tcx>,
92 ) -> Vec<UnwrapInfo<'tcx>> {
93 if let ExprKind::Binary(op, left, right) = &expr.node {
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, invert);
97 unwrap_info.append(&mut collect_unwrap_info(cx, right, invert));
102 } else if let ExprKind::Unary(UnNot, expr) = &expr.node {
103 return collect_unwrap_info(cx, expr, !invert);
106 if let ExprKind::MethodCall(method_name, _, args) = &expr.node;
107 if let ExprKind::Path(QPath::Resolved(None, path)) = &args[0].node;
108 let ty = cx.tables.expr_ty(&args[0]);
109 if match_type(cx, ty, &paths::OPTION) || match_type(cx, ty, &paths::RESULT);
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, safe_to_unwrap }];
127 impl<'a, 'tcx: 'a> 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, 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: 'a> Visitor<'tcx> for UnwrappableVariablesVisitor<'a, 'tcx> {
145 fn visit_expr(&mut self, expr: &'tcx Expr) {
146 if let ExprKind::If(cond, then, els) = &expr.node {
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.node;
156 if let ExprKind::Path(QPath::Resolved(None, ref path)) = args[0].node;
157 if ["unwrap", "unwrap_err"].contains(&&*method_name.ident.as_str());
158 let call_to_unwrap = method_name.ident.name == "unwrap";
159 if let Some(unwrappable) = self.unwrappables.iter()
160 .find(|u| u.ident.def == path.def);
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 |db| { db.span_label(unwrappable.check.span, "the check is happening here"); },
177 &format!("This call to `{}()` will always panic.",
178 method_name.ident.name),
179 |db| { db.span_label(unwrappable.check.span, "because of this check"); },
184 walk_expr(self, expr);
188 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
189 NestedVisitorMap::OnlyBodies(&self.cx.tcx.hir)
193 impl<'a> LintPass for Pass {
194 fn get_lints(&self) -> LintArray {
195 lint_array!(PANICKING_UNWRAP, UNNECESSARY_UNWRAP)
199 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
202 cx: &LateContext<'a, 'tcx>,
213 let mut v = UnwrappableVariablesVisitor {
215 unwrappables: Vec::new(),
218 walk_fn(&mut v, kind, decl, body.id(), span, fn_id);