]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/unwrap.rs
Rollup merge of #4102 - Urriel:fix/4096_match_same_arms, r=flip1995
[rust.git] / clippy_lints / src / unwrap.rs
1 use if_chain::if_chain;
2 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
3 use rustc::{declare_lint_pass, declare_tool_lint};
4
5 use crate::utils::{
6     higher::if_block, in_macro_or_desugar, match_type, paths, span_lint_and_then, usage::is_potentially_mutated,
7 };
8 use rustc::hir::intravisit::*;
9 use rustc::hir::*;
10 use syntax::source_map::Span;
11
12 declare_clippy_lint! {
13     /// **What it does:** Checks for calls of `unwrap[_err]()` that cannot fail.
14     ///
15     /// **Why is this bad?** Using `if let` or `match` is more idiomatic.
16     ///
17     /// **Known problems:** Limitations of the borrow checker might make unwrap() necessary sometimes?
18     ///
19     /// **Example:**
20     /// ```rust
21     /// if option.is_some() {
22     ///     do_something_with(option.unwrap())
23     /// }
24     /// ```
25     ///
26     /// Could be written:
27     ///
28     /// ```rust
29     /// if let Some(value) = option {
30     ///     do_something_with(value)
31     /// }
32     /// ```
33     pub UNNECESSARY_UNWRAP,
34     nursery,
35     "checks for calls of unwrap[_err]() that cannot fail"
36 }
37
38 declare_clippy_lint! {
39     /// **What it does:** Checks for calls of `unwrap[_err]()` that will always fail.
40     ///
41     /// **Why is this bad?** If panicking is desired, an explicit `panic!()` should be used.
42     ///
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.
45     ///
46     /// **Example:**
47     /// ```rust
48     /// if option.is_none() {
49     ///     do_something_with(option.unwrap())
50     /// }
51     /// ```
52     ///
53     /// This code will always panic. The if condition should probably be inverted.
54     pub PANICKING_UNWRAP,
55     nursery,
56     "checks for calls of unwrap[_err]() that will always fail"
57 }
58
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>,
63 }
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
68     ident: &'tcx Path,
69     /// The check, like `x.is_ok()`
70     check: &'tcx Expr,
71     /// Whether `is_some()` or `is_ok()` was called (as opposed to `is_err()` or `is_none()`).
72     safe_to_unwrap: bool,
73 }
74
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>,
79     expr: &'tcx Expr,
80     invert: bool,
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));
87                 return unwrap_info;
88             },
89             _ => (),
90         }
91     } else if let ExprKind::Unary(UnNot, expr) = &expr.node {
92         return collect_unwrap_info(cx, expr, !invert);
93     } else {
94         if_chain! {
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);
101             then {
102                 assert!(args.len() == 1);
103                 let unwrappable = match name.as_ref() {
104                     "is_some" | "is_ok" => true,
105                     "is_err" | "is_none" => false,
106                     _ => unreachable!(),
107                 };
108                 let safe_to_unwrap = unwrappable != invert;
109                 return vec![UnwrapInfo { ident: path, check: expr, safe_to_unwrap }];
110             }
111         }
112     }
113     Vec::new()
114 }
115
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)
122             {
123                 // if the variable is mutated, we don't know whether it can be unwrapped:
124                 continue;
125             }
126             self.unwrappables.push(unwrap_info);
127         }
128         walk_expr(self, branch);
129         self.unwrappables.truncate(prev_len);
130     }
131 }
132
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);
140             }
141         } else {
142             // find `unwrap[_err]()` calls:
143             if_chain! {
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);
150                 then {
151                     if call_to_unwrap == unwrappable.safe_to_unwrap {
152                         span_lint_and_then(
153                             self.cx,
154                             UNNECESSARY_UNWRAP,
155                             expr.span,
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"); },
160                         );
161                     } else {
162                         span_lint_and_then(
163                             self.cx,
164                             PANICKING_UNWRAP,
165                             expr.span,
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"); },
169                         );
170                     }
171                 }
172             }
173             walk_expr(self, expr);
174         }
175     }
176
177     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
178         NestedVisitorMap::OnlyBodies(&self.cx.tcx.hir())
179     }
180 }
181
182 declare_lint_pass!(Unwrap => [PANICKING_UNWRAP, UNNECESSARY_UNWRAP]);
183
184 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Unwrap {
185     fn check_fn(
186         &mut self,
187         cx: &LateContext<'a, 'tcx>,
188         kind: FnKind<'tcx>,
189         decl: &'tcx FnDecl,
190         body: &'tcx Body,
191         span: Span,
192         fn_id: HirId,
193     ) {
194         if in_macro_or_desugar(span) {
195             return;
196         }
197
198         let mut v = UnwrappableVariablesVisitor {
199             cx,
200             unwrappables: Vec::new(),
201         };
202
203         walk_fn(&mut v, kind, decl, body.id(), span, fn_id);
204     }
205 }