1 use if_chain::if_chain;
2 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
3 use rustc::{declare_lint_pass, declare_tool_lint};
5 use crate::utils::{higher::if_block, match_type, paths, span_lint_and_then, usage::is_potentially_mutated};
6 use rustc::hir::intravisit::*;
8 use syntax::source_map::Span;
10 declare_clippy_lint! {
11 /// **What it does:** Checks for calls of `unwrap[_err]()` that cannot fail.
13 /// **Why is this bad?** Using `if let` or `match` is more idiomatic.
15 /// **Known problems:** None
19 /// # let option = Some(0);
20 /// # fn do_something_with(_x: usize) {}
21 /// if option.is_some() {
22 /// do_something_with(option.unwrap())
29 /// # let option = Some(0);
30 /// # fn do_something_with(_x: usize) {}
31 /// if let Some(value) = option {
32 /// do_something_with(value)
35 pub UNNECESSARY_UNWRAP,
37 "checks for calls of unwrap[_err]() that cannot fail"
40 declare_clippy_lint! {
41 /// **What it does:** Checks for calls of `unwrap[_err]()` that will always fail.
43 /// **Why is this bad?** If panicking is desired, an explicit `panic!()` should be used.
45 /// **Known problems:** This lint only checks `if` conditions not assignments.
46 /// So something like `let x: Option<()> = None; x.unwrap();` will not be recognized.
50 /// # let option = Some(0);
51 /// # fn do_something_with(_x: usize) {}
52 /// if option.is_none() {
53 /// do_something_with(option.unwrap())
57 /// This code will always panic. The if condition should probably be inverted.
60 "checks for calls of unwrap[_err]() that will always fail"
63 /// Visitor that keeps track of which variables are unwrappable.
64 struct UnwrappableVariablesVisitor<'a, 'tcx> {
65 unwrappables: Vec<UnwrapInfo<'tcx>>,
66 cx: &'a LateContext<'a, 'tcx>,
68 /// Contains information about whether a variable can be unwrapped.
69 #[derive(Copy, Clone, Debug)]
70 struct UnwrapInfo<'tcx> {
71 /// The variable that is checked
73 /// The check, like `x.is_ok()`
75 /// Whether `is_some()` or `is_ok()` was called (as opposed to `is_err()` or `is_none()`).
79 /// Collects the information about unwrappable variables from an if condition
80 /// The `invert` argument tells us whether the condition is negated.
81 fn collect_unwrap_info<'a, 'tcx>(
82 cx: &'a LateContext<'a, 'tcx>,
85 ) -> Vec<UnwrapInfo<'tcx>> {
86 if let ExprKind::Binary(op, left, right) = &expr.kind {
87 match (invert, op.node) {
88 (false, BinOpKind::And) | (false, BinOpKind::BitAnd) | (true, BinOpKind::Or) | (true, BinOpKind::BitOr) => {
89 let mut unwrap_info = collect_unwrap_info(cx, left, invert);
90 unwrap_info.append(&mut collect_unwrap_info(cx, right, invert));
95 } else if let ExprKind::Unary(UnNot, expr) = &expr.kind {
96 return collect_unwrap_info(cx, expr, !invert);
99 if let ExprKind::MethodCall(method_name, _, args) = &expr.kind;
100 if let ExprKind::Path(QPath::Resolved(None, path)) = &args[0].kind;
101 let ty = cx.tables.expr_ty(&args[0]);
102 if match_type(cx, ty, &paths::OPTION) || match_type(cx, ty, &paths::RESULT);
103 let name = method_name.ident.as_str();
104 if ["is_some", "is_none", "is_ok", "is_err"].contains(&&*name);
106 assert!(args.len() == 1);
107 let unwrappable = match name.as_ref() {
108 "is_some" | "is_ok" => true,
109 "is_err" | "is_none" => false,
112 let safe_to_unwrap = unwrappable != invert;
113 return vec![UnwrapInfo { ident: path, check: expr, safe_to_unwrap }];
120 impl<'a, 'tcx> UnwrappableVariablesVisitor<'a, 'tcx> {
121 fn visit_branch(&mut self, cond: &'tcx Expr, branch: &'tcx Expr, else_branch: bool) {
122 let prev_len = self.unwrappables.len();
123 for unwrap_info in collect_unwrap_info(self.cx, cond, else_branch) {
124 if is_potentially_mutated(unwrap_info.ident, cond, self.cx)
125 || is_potentially_mutated(unwrap_info.ident, branch, self.cx)
127 // if the variable is mutated, we don't know whether it can be unwrapped:
130 self.unwrappables.push(unwrap_info);
132 walk_expr(self, branch);
133 self.unwrappables.truncate(prev_len);
137 impl<'a, 'tcx> Visitor<'tcx> for UnwrappableVariablesVisitor<'a, 'tcx> {
138 fn visit_expr(&mut self, expr: &'tcx Expr) {
139 if let Some((cond, then, els)) = if_block(&expr) {
140 walk_expr(self, cond);
141 self.visit_branch(cond, then, false);
142 if let Some(els) = els {
143 self.visit_branch(cond, els, true);
146 // find `unwrap[_err]()` calls:
148 if let ExprKind::MethodCall(ref method_name, _, ref args) = expr.kind;
149 if let ExprKind::Path(QPath::Resolved(None, ref path)) = args[0].kind;
150 if [sym!(unwrap), sym!(unwrap_err)].contains(&method_name.ident.name);
151 let call_to_unwrap = method_name.ident.name == sym!(unwrap);
152 if let Some(unwrappable) = self.unwrappables.iter()
153 .find(|u| u.ident.res == path.res);
155 if call_to_unwrap == unwrappable.safe_to_unwrap {
160 &format!("You checked before that `{}()` cannot fail. \
161 Instead of checking and unwrapping, it's better to use `if let` or `match`.",
162 method_name.ident.name),
163 |db| { db.span_label(unwrappable.check.span, "the check is happening here"); },
170 &format!("This call to `{}()` will always panic.",
171 method_name.ident.name),
172 |db| { db.span_label(unwrappable.check.span, "because of this check"); },
177 walk_expr(self, expr);
181 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
182 NestedVisitorMap::OnlyBodies(&self.cx.tcx.hir())
186 declare_lint_pass!(Unwrap => [PANICKING_UNWRAP, UNNECESSARY_UNWRAP]);
188 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Unwrap {
191 cx: &LateContext<'a, 'tcx>,
198 if span.from_expansion() {
202 let mut v = UnwrappableVariablesVisitor {
204 unwrappables: Vec::new(),
207 walk_fn(&mut v, kind, decl, body.id(), span, fn_id);