1 use if_chain::if_chain;
2 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
3 use rustc::{declare_lint_pass, declare_tool_lint};
6 higher::if_block, in_macro_or_desugar, match_type, paths, span_lint_and_then, usage::is_potentially_mutated,
8 use rustc::hir::intravisit::*;
10 use syntax::source_map::Span;
12 declare_clippy_lint! {
13 /// **What it does:** Checks for calls of `unwrap[_err]()` that cannot fail.
15 /// **Why is this bad?** Using `if let` or `match` is more idiomatic.
17 /// **Known problems:** Limitations of the borrow checker might make unwrap() necessary sometimes?
21 /// if option.is_some() {
22 /// do_something_with(option.unwrap())
29 /// if let Some(value) = option {
30 /// do_something_with(value)
33 pub UNNECESSARY_UNWRAP,
35 "checks for calls of unwrap[_err]() that cannot fail"
38 declare_clippy_lint! {
39 /// **What it does:** Checks for calls of `unwrap[_err]()` that will always fail.
41 /// **Why is this bad?** If panicking is desired, an explicit `panic!()` should be used.
43 /// **Known problems:** This lint only checks `if` conditions not assignments.
44 /// So something like `let x: Option<()> = None; x.unwrap();` will not be recognized.
48 /// if option.is_none() {
49 /// do_something_with(option.unwrap())
53 /// This code will always panic. The if condition should probably be inverted.
56 "checks for calls of unwrap[_err]() that will always fail"
59 /// Visitor that keeps track of which variables are unwrappable.
60 struct UnwrappableVariablesVisitor<'a, 'tcx: 'a> {
61 unwrappables: Vec<UnwrapInfo<'tcx>>,
62 cx: &'a LateContext<'a, 'tcx>,
64 /// Contains information about whether a variable can be unwrapped.
65 #[derive(Copy, Clone, Debug)]
66 struct UnwrapInfo<'tcx> {
67 /// The variable that is checked
69 /// The check, like `x.is_ok()`
71 /// Whether `is_some()` or `is_ok()` was called (as opposed to `is_err()` or `is_none()`).
75 /// Collects the information about unwrappable variables from an if condition
76 /// The `invert` argument tells us whether the condition is negated.
77 fn collect_unwrap_info<'a, 'tcx: 'a>(
78 cx: &'a LateContext<'a, 'tcx>,
81 ) -> Vec<UnwrapInfo<'tcx>> {
82 if let ExprKind::Binary(op, left, right) = &expr.node {
83 match (invert, op.node) {
84 (false, BinOpKind::And) | (false, BinOpKind::BitAnd) | (true, BinOpKind::Or) | (true, BinOpKind::BitOr) => {
85 let mut unwrap_info = collect_unwrap_info(cx, left, invert);
86 unwrap_info.append(&mut collect_unwrap_info(cx, right, invert));
91 } else if let ExprKind::Unary(UnNot, expr) = &expr.node {
92 return collect_unwrap_info(cx, expr, !invert);
95 if let ExprKind::MethodCall(method_name, _, args) = &expr.node;
96 if let ExprKind::Path(QPath::Resolved(None, path)) = &args[0].node;
97 let ty = cx.tables.expr_ty(&args[0]);
98 if match_type(cx, ty, &paths::OPTION) || match_type(cx, ty, &paths::RESULT);
99 let name = method_name.ident.as_str();
100 if ["is_some", "is_none", "is_ok", "is_err"].contains(&&*name);
102 assert!(args.len() == 1);
103 let unwrappable = match name.as_ref() {
104 "is_some" | "is_ok" => true,
105 "is_err" | "is_none" => false,
108 let safe_to_unwrap = unwrappable != invert;
109 return vec![UnwrapInfo { ident: path, check: expr, safe_to_unwrap }];
116 impl<'a, 'tcx: 'a> UnwrappableVariablesVisitor<'a, 'tcx> {
117 fn visit_branch(&mut self, cond: &'tcx Expr, branch: &'tcx Expr, else_branch: bool) {
118 let prev_len = self.unwrappables.len();
119 for unwrap_info in collect_unwrap_info(self.cx, cond, else_branch) {
120 if is_potentially_mutated(unwrap_info.ident, cond, self.cx)
121 || is_potentially_mutated(unwrap_info.ident, branch, self.cx)
123 // if the variable is mutated, we don't know whether it can be unwrapped:
126 self.unwrappables.push(unwrap_info);
128 walk_expr(self, branch);
129 self.unwrappables.truncate(prev_len);
133 impl<'a, 'tcx: 'a> Visitor<'tcx> for UnwrappableVariablesVisitor<'a, 'tcx> {
134 fn visit_expr(&mut self, expr: &'tcx Expr) {
135 if let Some((cond, then, els)) = if_block(&expr) {
136 walk_expr(self, cond);
137 self.visit_branch(cond, then, false);
138 if let Some(els) = els {
139 self.visit_branch(cond, els, true);
142 // find `unwrap[_err]()` calls:
144 if let ExprKind::MethodCall(ref method_name, _, ref args) = expr.node;
145 if let ExprKind::Path(QPath::Resolved(None, ref path)) = args[0].node;
146 if [sym!(unwrap), sym!(unwrap_err)].contains(&method_name.ident.name);
147 let call_to_unwrap = method_name.ident.name == sym!(unwrap);
148 if let Some(unwrappable) = self.unwrappables.iter()
149 .find(|u| u.ident.res == path.res);
151 if call_to_unwrap == unwrappable.safe_to_unwrap {
156 &format!("You checked before that `{}()` cannot fail. \
157 Instead of checking and unwrapping, it's better to use `if let` or `match`.",
158 method_name.ident.name),
159 |db| { db.span_label(unwrappable.check.span, "the check is happening here"); },
166 &format!("This call to `{}()` will always panic.",
167 method_name.ident.name),
168 |db| { db.span_label(unwrappable.check.span, "because of this check"); },
173 walk_expr(self, expr);
177 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
178 NestedVisitorMap::OnlyBodies(&self.cx.tcx.hir())
182 declare_lint_pass!(Unwrap => [PANICKING_UNWRAP, UNNECESSARY_UNWRAP]);
184 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Unwrap {
187 cx: &LateContext<'a, 'tcx>,
194 if in_macro_or_desugar(span) {
198 let mut v = UnwrappableVariablesVisitor {
200 unwrappables: Vec::new(),
203 walk_fn(&mut v, kind, decl, body.id(), span, fn_id);