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:** None
21 /// # let option = Some(0);
22 /// # fn do_something_with(_x: usize) {}
23 /// if option.is_some() {
24 /// do_something_with(option.unwrap())
31 /// # let option = Some(0);
32 /// # fn do_something_with(_x: usize) {}
33 /// if let Some(value) = option {
34 /// do_something_with(value)
37 pub UNNECESSARY_UNWRAP,
39 "checks for calls of unwrap[_err]() that cannot fail"
42 declare_clippy_lint! {
43 /// **What it does:** Checks for calls of `unwrap[_err]()` that will always fail.
45 /// **Why is this bad?** If panicking is desired, an explicit `panic!()` should be used.
47 /// **Known problems:** This lint only checks `if` conditions not assignments.
48 /// So something like `let x: Option<()> = None; x.unwrap();` will not be recognized.
52 /// # let option = Some(0);
53 /// # fn do_something_with(_x: usize) {}
54 /// if option.is_none() {
55 /// do_something_with(option.unwrap())
59 /// This code will always panic. The if condition should probably be inverted.
62 "checks for calls of unwrap[_err]() that will always fail"
65 /// Visitor that keeps track of which variables are unwrappable.
66 struct UnwrappableVariablesVisitor<'a, 'tcx> {
67 unwrappables: Vec<UnwrapInfo<'tcx>>,
68 cx: &'a LateContext<'a, 'tcx>,
70 /// Contains information about whether a variable can be unwrapped.
71 #[derive(Copy, Clone, Debug)]
72 struct UnwrapInfo<'tcx> {
73 /// The variable that is checked
75 /// The check, like `x.is_ok()`
77 /// Whether `is_some()` or `is_ok()` was called (as opposed to `is_err()` or `is_none()`).
81 /// Collects the information about unwrappable variables from an if condition
82 /// The `invert` argument tells us whether the condition is negated.
83 fn collect_unwrap_info<'a, 'tcx>(
84 cx: &'a LateContext<'a, 'tcx>,
87 ) -> Vec<UnwrapInfo<'tcx>> {
88 if let ExprKind::Binary(op, left, right) = &expr.node {
89 match (invert, op.node) {
90 (false, BinOpKind::And) | (false, BinOpKind::BitAnd) | (true, BinOpKind::Or) | (true, BinOpKind::BitOr) => {
91 let mut unwrap_info = collect_unwrap_info(cx, left, invert);
92 unwrap_info.append(&mut collect_unwrap_info(cx, right, invert));
97 } else if let ExprKind::Unary(UnNot, expr) = &expr.node {
98 return collect_unwrap_info(cx, expr, !invert);
101 if let ExprKind::MethodCall(method_name, _, args) = &expr.node;
102 if let ExprKind::Path(QPath::Resolved(None, path)) = &args[0].node;
103 let ty = cx.tables.expr_ty(&args[0]);
104 if match_type(cx, ty, &paths::OPTION) || match_type(cx, ty, &paths::RESULT);
105 let name = method_name.ident.as_str();
106 if ["is_some", "is_none", "is_ok", "is_err"].contains(&&*name);
108 assert!(args.len() == 1);
109 let unwrappable = match name.as_ref() {
110 "is_some" | "is_ok" => true,
111 "is_err" | "is_none" => false,
114 let safe_to_unwrap = unwrappable != invert;
115 return vec![UnwrapInfo { ident: path, check: expr, safe_to_unwrap }];
122 impl<'a, 'tcx> UnwrappableVariablesVisitor<'a, 'tcx> {
123 fn visit_branch(&mut self, cond: &'tcx Expr, branch: &'tcx Expr, else_branch: bool) {
124 let prev_len = self.unwrappables.len();
125 for unwrap_info in collect_unwrap_info(self.cx, cond, else_branch) {
126 if is_potentially_mutated(unwrap_info.ident, cond, self.cx)
127 || is_potentially_mutated(unwrap_info.ident, branch, self.cx)
129 // if the variable is mutated, we don't know whether it can be unwrapped:
132 self.unwrappables.push(unwrap_info);
134 walk_expr(self, branch);
135 self.unwrappables.truncate(prev_len);
139 impl<'a, 'tcx> Visitor<'tcx> for UnwrappableVariablesVisitor<'a, 'tcx> {
140 fn visit_expr(&mut self, expr: &'tcx Expr) {
141 if let Some((cond, then, els)) = if_block(&expr) {
142 walk_expr(self, cond);
143 self.visit_branch(cond, then, false);
144 if let Some(els) = els {
145 self.visit_branch(cond, els, true);
148 // find `unwrap[_err]()` calls:
150 if let ExprKind::MethodCall(ref method_name, _, ref args) = expr.node;
151 if let ExprKind::Path(QPath::Resolved(None, ref path)) = args[0].node;
152 if [sym!(unwrap), sym!(unwrap_err)].contains(&method_name.ident.name);
153 let call_to_unwrap = method_name.ident.name == sym!(unwrap);
154 if let Some(unwrappable) = self.unwrappables.iter()
155 .find(|u| u.ident.res == path.res);
157 if call_to_unwrap == unwrappable.safe_to_unwrap {
162 &format!("You checked before that `{}()` cannot fail. \
163 Instead of checking and unwrapping, it's better to use `if let` or `match`.",
164 method_name.ident.name),
165 |db| { db.span_label(unwrappable.check.span, "the check is happening here"); },
172 &format!("This call to `{}()` will always panic.",
173 method_name.ident.name),
174 |db| { db.span_label(unwrappable.check.span, "because of this check"); },
179 walk_expr(self, expr);
183 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
184 NestedVisitorMap::OnlyBodies(&self.cx.tcx.hir())
188 declare_lint_pass!(Unwrap => [PANICKING_UNWRAP, UNNECESSARY_UNWRAP]);
190 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Unwrap {
193 cx: &LateContext<'a, 'tcx>,
200 if in_macro_or_desugar(span) {
204 let mut v = UnwrappableVariablesVisitor {
206 unwrappables: Vec::new(),
209 walk_fn(&mut v, kind, decl, body.id(), span, fn_id);