]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/unwrap.rs
Do not lint `unnecessary_unwrap` in macros
[rust.git] / clippy_lints / src / unwrap.rs
1 use crate::utils::{higher::if_block, in_macro, match_type, paths, span_lint_and_then, usage::is_potentially_mutated};
2 use if_chain::if_chain;
3 use rustc::hir::map::Map;
4 use rustc_hir::intravisit::*;
5 use rustc_hir::*;
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_session::{declare_lint_pass, declare_tool_lint};
8 use rustc_span::source_map::Span;
9
10 declare_clippy_lint! {
11     /// **What it does:** Checks for calls of `unwrap[_err]()` that cannot fail.
12     ///
13     /// **Why is this bad?** Using `if let` or `match` is more idiomatic.
14     ///
15     /// **Known problems:** None
16     ///
17     /// **Example:**
18     /// ```rust
19     /// # let option = Some(0);
20     /// # fn do_something_with(_x: usize) {}
21     /// if option.is_some() {
22     ///     do_something_with(option.unwrap())
23     /// }
24     /// ```
25     ///
26     /// Could be written:
27     ///
28     /// ```rust
29     /// # let option = Some(0);
30     /// # fn do_something_with(_x: usize) {}
31     /// if let Some(value) = option {
32     ///     do_something_with(value)
33     /// }
34     /// ```
35     pub UNNECESSARY_UNWRAP,
36     complexity,
37     "checks for calls of `unwrap[_err]()` that cannot fail"
38 }
39
40 declare_clippy_lint! {
41     /// **What it does:** Checks for calls of `unwrap[_err]()` that will always fail.
42     ///
43     /// **Why is this bad?** If panicking is desired, an explicit `panic!()` should be used.
44     ///
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.
47     ///
48     /// **Example:**
49     /// ```rust
50     /// # let option = Some(0);
51     /// # fn do_something_with(_x: usize) {}
52     /// if option.is_none() {
53     ///     do_something_with(option.unwrap())
54     /// }
55     /// ```
56     ///
57     /// This code will always panic. The if condition should probably be inverted.
58     pub PANICKING_UNWRAP,
59     correctness,
60     "checks for calls of `unwrap[_err]()` that will always fail"
61 }
62
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>,
67 }
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
72     ident: &'tcx Path<'tcx>,
73     /// The check, like `x.is_ok()`
74     check: &'tcx Expr<'tcx>,
75     /// Whether `is_some()` or `is_ok()` was called (as opposed to `is_err()` or `is_none()`).
76     safe_to_unwrap: bool,
77 }
78
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>,
83     expr: &'tcx Expr<'_>,
84     invert: bool,
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));
91                 return unwrap_info;
92             },
93             _ => (),
94         }
95     } else if let ExprKind::Unary(UnOp::UnNot, expr) = &expr.kind {
96         return collect_unwrap_info(cx, expr, !invert);
97     } else {
98         if_chain! {
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);
105             then {
106                 assert!(args.len() == 1);
107                 let unwrappable = match name.as_ref() {
108                     "is_some" | "is_ok" => true,
109                     "is_err" | "is_none" => false,
110                     _ => unreachable!(),
111                 };
112                 let safe_to_unwrap = unwrappable != invert;
113                 return vec![UnwrapInfo { ident: path, check: expr, safe_to_unwrap }];
114             }
115         }
116     }
117     Vec::new()
118 }
119
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)
126             {
127                 // if the variable is mutated, we don't know whether it can be unwrapped:
128                 continue;
129             }
130             self.unwrappables.push(unwrap_info);
131         }
132         walk_expr(self, branch);
133         self.unwrappables.truncate(prev_len);
134     }
135 }
136
137 impl<'a, 'tcx> Visitor<'tcx> for UnwrappableVariablesVisitor<'a, 'tcx> {
138     type Map = Map<'tcx>;
139
140     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
141         // Shouldn't lint when `expr` is in macro.
142         if in_macro(expr.span) {
143             return;
144         }
145         if let Some((cond, then, els)) = if_block(&expr) {
146             walk_expr(self, cond);
147             self.visit_branch(cond, then, false);
148             if let Some(els) = els {
149                 self.visit_branch(cond, els, true);
150             }
151         } else {
152             // find `unwrap[_err]()` calls:
153             if_chain! {
154                 if let ExprKind::MethodCall(ref method_name, _, ref args) = expr.kind;
155                 if let ExprKind::Path(QPath::Resolved(None, ref path)) = args[0].kind;
156                 if [sym!(unwrap), sym!(unwrap_err)].contains(&method_name.ident.name);
157                 let call_to_unwrap = method_name.ident.name == sym!(unwrap);
158                 if let Some(unwrappable) = self.unwrappables.iter()
159                     .find(|u| u.ident.res == path.res);
160                 then {
161                     if call_to_unwrap == unwrappable.safe_to_unwrap {
162                         span_lint_and_then(
163                             self.cx,
164                             UNNECESSARY_UNWRAP,
165                             expr.span,
166                             &format!("You checked before that `{}()` cannot fail. \
167                             Instead of checking and unwrapping, it's better to use `if let` or `match`.",
168                             method_name.ident.name),
169                             |db| { db.span_label(unwrappable.check.span, "the check is happening here"); },
170                         );
171                     } else {
172                         span_lint_and_then(
173                             self.cx,
174                             PANICKING_UNWRAP,
175                             expr.span,
176                             &format!("This call to `{}()` will always panic.",
177                             method_name.ident.name),
178                             |db| { db.span_label(unwrappable.check.span, "because of this check"); },
179                         );
180                     }
181                 }
182             }
183             walk_expr(self, expr);
184         }
185     }
186
187     fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
188         NestedVisitorMap::OnlyBodies(&self.cx.tcx.hir())
189     }
190 }
191
192 declare_lint_pass!(Unwrap => [PANICKING_UNWRAP, UNNECESSARY_UNWRAP]);
193
194 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Unwrap {
195     fn check_fn(
196         &mut self,
197         cx: &LateContext<'a, 'tcx>,
198         kind: FnKind<'tcx>,
199         decl: &'tcx FnDecl<'_>,
200         body: &'tcx Body<'_>,
201         span: Span,
202         fn_id: HirId,
203     ) {
204         if span.from_expansion() {
205             return;
206         }
207
208         let mut v = UnwrappableVariablesVisitor {
209             cx,
210             unwrappables: Vec::new(),
211         };
212
213         walk_fn(&mut v, kind, decl, body.id(), span, fn_id);
214     }
215 }