]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/unwrap.rs
Auto merge of #6828 - mgacek8:issue_6758_enhance_wrong_self_convention, r=flip1995
[rust.git] / clippy_lints / src / unwrap.rs
1 use crate::utils::{differing_macro_contexts, span_lint_and_then, usage::is_potentially_mutated};
2 use clippy_utils::ty::is_type_diagnostic_item;
3 use if_chain::if_chain;
4 use rustc_hir::intravisit::{walk_expr, walk_fn, FnKind, NestedVisitorMap, Visitor};
5 use rustc_hir::{BinOpKind, Body, Expr, ExprKind, FnDecl, HirId, Path, QPath, UnOp};
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_middle::hir::map::Map;
8 use rustc_middle::lint::in_external_macro;
9 use rustc_middle::ty::Ty;
10 use rustc_session::{declare_lint_pass, declare_tool_lint};
11 use rustc_span::source_map::Span;
12 use rustc_span::sym;
13
14 declare_clippy_lint! {
15     /// **What it does:** Checks for calls of `unwrap[_err]()` that cannot fail.
16     ///
17     /// **Why is this bad?** Using `if let` or `match` is more idiomatic.
18     ///
19     /// **Known problems:** None
20     ///
21     /// **Example:**
22     /// ```rust
23     /// # let option = Some(0);
24     /// # fn do_something_with(_x: usize) {}
25     /// if option.is_some() {
26     ///     do_something_with(option.unwrap())
27     /// }
28     /// ```
29     ///
30     /// Could be written:
31     ///
32     /// ```rust
33     /// # let option = Some(0);
34     /// # fn do_something_with(_x: usize) {}
35     /// if let Some(value) = option {
36     ///     do_something_with(value)
37     /// }
38     /// ```
39     pub UNNECESSARY_UNWRAP,
40     complexity,
41     "checks for calls of `unwrap[_err]()` that cannot fail"
42 }
43
44 declare_clippy_lint! {
45     /// **What it does:** Checks for calls of `unwrap[_err]()` that will always fail.
46     ///
47     /// **Why is this bad?** If panicking is desired, an explicit `panic!()` should be used.
48     ///
49     /// **Known problems:** This lint only checks `if` conditions not assignments.
50     /// So something like `let x: Option<()> = None; x.unwrap();` will not be recognized.
51     ///
52     /// **Example:**
53     /// ```rust
54     /// # let option = Some(0);
55     /// # fn do_something_with(_x: usize) {}
56     /// if option.is_none() {
57     ///     do_something_with(option.unwrap())
58     /// }
59     /// ```
60     ///
61     /// This code will always panic. The if condition should probably be inverted.
62     pub PANICKING_UNWRAP,
63     correctness,
64     "checks for calls of `unwrap[_err]()` that will always fail"
65 }
66
67 /// Visitor that keeps track of which variables are unwrappable.
68 struct UnwrappableVariablesVisitor<'a, 'tcx> {
69     unwrappables: Vec<UnwrapInfo<'tcx>>,
70     cx: &'a LateContext<'tcx>,
71 }
72 /// Contains information about whether a variable can be unwrapped.
73 #[derive(Copy, Clone, Debug)]
74 struct UnwrapInfo<'tcx> {
75     /// The variable that is checked
76     ident: &'tcx Path<'tcx>,
77     /// The check, like `x.is_ok()`
78     check: &'tcx Expr<'tcx>,
79     /// The branch where the check takes place, like `if x.is_ok() { .. }`
80     branch: &'tcx Expr<'tcx>,
81     /// Whether `is_some()` or `is_ok()` was called (as opposed to `is_err()` or `is_none()`).
82     safe_to_unwrap: bool,
83 }
84
85 /// Collects the information about unwrappable variables from an if condition
86 /// The `invert` argument tells us whether the condition is negated.
87 fn collect_unwrap_info<'tcx>(
88     cx: &LateContext<'tcx>,
89     expr: &'tcx Expr<'_>,
90     branch: &'tcx Expr<'_>,
91     invert: bool,
92 ) -> Vec<UnwrapInfo<'tcx>> {
93     fn is_relevant_option_call(cx: &LateContext<'_>, ty: Ty<'_>, method_name: &str) -> bool {
94         is_type_diagnostic_item(cx, ty, sym::option_type) && ["is_some", "is_none"].contains(&method_name)
95     }
96
97     fn is_relevant_result_call(cx: &LateContext<'_>, ty: Ty<'_>, method_name: &str) -> bool {
98         is_type_diagnostic_item(cx, ty, sym::result_type) && ["is_ok", "is_err"].contains(&method_name)
99     }
100
101     if let ExprKind::Binary(op, left, right) = &expr.kind {
102         match (invert, op.node) {
103             (false, BinOpKind::And | BinOpKind::BitAnd) | (true, BinOpKind::Or | BinOpKind::BitOr) => {
104                 let mut unwrap_info = collect_unwrap_info(cx, left, branch, invert);
105                 unwrap_info.append(&mut collect_unwrap_info(cx, right, branch, invert));
106                 return unwrap_info;
107             },
108             _ => (),
109         }
110     } else if let ExprKind::Unary(UnOp::Not, expr) = &expr.kind {
111         return collect_unwrap_info(cx, expr, branch, !invert);
112     } else {
113         if_chain! {
114             if let ExprKind::MethodCall(method_name, _, args, _) = &expr.kind;
115             if let ExprKind::Path(QPath::Resolved(None, path)) = &args[0].kind;
116             let ty = cx.typeck_results().expr_ty(&args[0]);
117             let name = method_name.ident.as_str();
118             if is_relevant_option_call(cx, ty, &name) || is_relevant_result_call(cx, ty, &name);
119             then {
120                 assert!(args.len() == 1);
121                 let unwrappable = match name.as_ref() {
122                     "is_some" | "is_ok" => true,
123                     "is_err" | "is_none" => false,
124                     _ => unreachable!(),
125                 };
126                 let safe_to_unwrap = unwrappable != invert;
127                 return vec![UnwrapInfo { ident: path, check: expr, branch, safe_to_unwrap }];
128             }
129         }
130     }
131     Vec::new()
132 }
133
134 impl<'a, 'tcx> UnwrappableVariablesVisitor<'a, 'tcx> {
135     fn visit_branch(&mut self, cond: &'tcx Expr<'_>, branch: &'tcx Expr<'_>, else_branch: bool) {
136         let prev_len = self.unwrappables.len();
137         for unwrap_info in collect_unwrap_info(self.cx, cond, branch, else_branch) {
138             if is_potentially_mutated(unwrap_info.ident, cond, self.cx)
139                 || is_potentially_mutated(unwrap_info.ident, branch, self.cx)
140             {
141                 // if the variable is mutated, we don't know whether it can be unwrapped:
142                 continue;
143             }
144             self.unwrappables.push(unwrap_info);
145         }
146         walk_expr(self, branch);
147         self.unwrappables.truncate(prev_len);
148     }
149 }
150
151 impl<'a, 'tcx> Visitor<'tcx> for UnwrappableVariablesVisitor<'a, 'tcx> {
152     type Map = Map<'tcx>;
153
154     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
155         // Shouldn't lint when `expr` is in macro.
156         if in_external_macro(self.cx.tcx.sess, expr.span) {
157             return;
158         }
159         if let ExprKind::If(cond, then, els) = &expr.kind {
160             walk_expr(self, cond);
161             self.visit_branch(cond, then, false);
162             if let Some(els) = els {
163                 self.visit_branch(cond, els, true);
164             }
165         } else {
166             // find `unwrap[_err]()` calls:
167             if_chain! {
168                 if let ExprKind::MethodCall(ref method_name, _, ref args, _) = expr.kind;
169                 if let ExprKind::Path(QPath::Resolved(None, ref path)) = args[0].kind;
170                 if [sym::unwrap, sym!(unwrap_err)].contains(&method_name.ident.name);
171                 let call_to_unwrap = method_name.ident.name == sym::unwrap;
172                 if let Some(unwrappable) = self.unwrappables.iter()
173                     .find(|u| u.ident.res == path.res);
174                 // Span contexts should not differ with the conditional branch
175                 if !differing_macro_contexts(unwrappable.branch.span, expr.span);
176                 if !differing_macro_contexts(unwrappable.branch.span, unwrappable.check.span);
177                 then {
178                     if call_to_unwrap == unwrappable.safe_to_unwrap {
179                         span_lint_and_then(
180                             self.cx,
181                             UNNECESSARY_UNWRAP,
182                             expr.span,
183                             &format!("you checked before that `{}()` cannot fail, \
184                             instead of checking and unwrapping, it's better to use `if let` or `match`",
185                             method_name.ident.name),
186                             |diag| { diag.span_label(unwrappable.check.span, "the check is happening here"); },
187                         );
188                     } else {
189                         span_lint_and_then(
190                             self.cx,
191                             PANICKING_UNWRAP,
192                             expr.span,
193                             &format!("this call to `{}()` will always panic",
194                             method_name.ident.name),
195                             |diag| { diag.span_label(unwrappable.check.span, "because of this check"); },
196                         );
197                     }
198                 }
199             }
200             walk_expr(self, expr);
201         }
202     }
203
204     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
205         NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
206     }
207 }
208
209 declare_lint_pass!(Unwrap => [PANICKING_UNWRAP, UNNECESSARY_UNWRAP]);
210
211 impl<'tcx> LateLintPass<'tcx> for Unwrap {
212     fn check_fn(
213         &mut self,
214         cx: &LateContext<'tcx>,
215         kind: FnKind<'tcx>,
216         decl: &'tcx FnDecl<'_>,
217         body: &'tcx Body<'_>,
218         span: Span,
219         fn_id: HirId,
220     ) {
221         if span.from_expansion() {
222             return;
223         }
224
225         let mut v = UnwrappableVariablesVisitor {
226             cx,
227             unwrappables: Vec::new(),
228         };
229
230         walk_fn(&mut v, kind, decl, body.id(), span, fn_id);
231     }
232 }