1 use if_chain::if_chain;
2 use rustc::declare_lint_pass;
3 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
4 use rustc_session::declare_tool_lint;
6 use crate::utils::{higher::if_block, match_type, paths, span_lint_and_then, usage::is_potentially_mutated};
7 use rustc::hir::intravisit::*;
9 use syntax::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
74 /// The check, like `x.is_ok()`
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(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 match_type(cx, ty, &paths::OPTION) || match_type(cx, ty, &paths::RESULT);
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 fn visit_expr(&mut self, expr: &'tcx Expr) {
140 if let Some((cond, then, els)) = if_block(&expr) {
141 walk_expr(self, cond);
142 self.visit_branch(cond, then, false);
143 if let Some(els) = els {
144 self.visit_branch(cond, els, true);
147 // find `unwrap[_err]()` calls:
149 if let ExprKind::MethodCall(ref method_name, _, ref args) = expr.kind;
150 if let ExprKind::Path(QPath::Resolved(None, ref path)) = args[0].kind;
151 if [sym!(unwrap), sym!(unwrap_err)].contains(&method_name.ident.name);
152 let call_to_unwrap = method_name.ident.name == sym!(unwrap);
153 if let Some(unwrappable) = self.unwrappables.iter()
154 .find(|u| u.ident.res == path.res);
156 if call_to_unwrap == unwrappable.safe_to_unwrap {
161 &format!("You checked before that `{}()` cannot fail. \
162 Instead of checking and unwrapping, it's better to use `if let` or `match`.",
163 method_name.ident.name),
164 |db| { db.span_label(unwrappable.check.span, "the check is happening here"); },
171 &format!("This call to `{}()` will always panic.",
172 method_name.ident.name),
173 |db| { db.span_label(unwrappable.check.span, "because of this check"); },
178 walk_expr(self, expr);
182 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
183 NestedVisitorMap::OnlyBodies(&self.cx.tcx.hir())
187 declare_lint_pass!(Unwrap => [PANICKING_UNWRAP, UNNECESSARY_UNWRAP]);
189 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Unwrap {
192 cx: &LateContext<'a, 'tcx>,
199 if span.from_expansion() {
203 let mut v = UnwrappableVariablesVisitor {
205 unwrappables: Vec::new(),
208 walk_fn(&mut v, kind, decl, body.id(), span, fn_id);