]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/mixed_read_write_in_expression.rs
merge rustc history
[rust.git] / clippy_lints / src / mixed_read_write_in_expression.rs
1 use clippy_utils::diagnostics::{span_lint, span_lint_and_note};
2 use clippy_utils::{get_parent_expr, path_to_local, path_to_local_id};
3 use if_chain::if_chain;
4 use rustc_hir::intravisit::{walk_expr, Visitor};
5 use rustc_hir::{BinOpKind, Block, Expr, ExprKind, Guard, HirId, Local, Node, Stmt, StmtKind};
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_middle::ty;
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9
10 declare_clippy_lint! {
11     /// ### What it does
12     /// Checks for a read and a write to the same variable where
13     /// whether the read occurs before or after the write depends on the evaluation
14     /// order of sub-expressions.
15     ///
16     /// ### Why is this bad?
17     /// It is often confusing to read. As described [here](https://doc.rust-lang.org/reference/expressions.html?highlight=subexpression#evaluation-order-of-operands),
18     /// the operands of these expressions are evaluated before applying the effects of the expression.
19     ///
20     /// ### Known problems
21     /// Code which intentionally depends on the evaluation
22     /// order, or which is correct for any evaluation order.
23     ///
24     /// ### Example
25     /// ```rust
26     /// let mut x = 0;
27     ///
28     /// let a = {
29     ///     x = 1;
30     ///     1
31     /// } + x;
32     /// // Unclear whether a is 1 or 2.
33     /// ```
34     ///
35     /// Use instead:
36     /// ```rust
37     /// # let mut x = 0;
38     /// let tmp = {
39     ///     x = 1;
40     ///     1
41     /// };
42     /// let a = tmp + x;
43     /// ```
44     #[clippy::version = "pre 1.29.0"]
45     pub MIXED_READ_WRITE_IN_EXPRESSION,
46     restriction,
47     "whether a variable read occurs before a write depends on sub-expression evaluation order"
48 }
49
50 declare_clippy_lint! {
51     /// ### What it does
52     /// Checks for diverging calls that are not match arms or
53     /// statements.
54     ///
55     /// ### Why is this bad?
56     /// It is often confusing to read. In addition, the
57     /// sub-expression evaluation order for Rust is not well documented.
58     ///
59     /// ### Known problems
60     /// Someone might want to use `some_bool || panic!()` as a
61     /// shorthand.
62     ///
63     /// ### Example
64     /// ```rust,no_run
65     /// # fn b() -> bool { true }
66     /// # fn c() -> bool { true }
67     /// let a = b() || panic!() || c();
68     /// // `c()` is dead, `panic!()` is only called if `b()` returns `false`
69     /// let x = (a, b, c, panic!());
70     /// // can simply be replaced by `panic!()`
71     /// ```
72     #[clippy::version = "pre 1.29.0"]
73     pub DIVERGING_SUB_EXPRESSION,
74     complexity,
75     "whether an expression contains a diverging sub expression"
76 }
77
78 declare_lint_pass!(EvalOrderDependence => [MIXED_READ_WRITE_IN_EXPRESSION, DIVERGING_SUB_EXPRESSION]);
79
80 impl<'tcx> LateLintPass<'tcx> for EvalOrderDependence {
81     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
82         // Find a write to a local variable.
83         let var = if_chain! {
84             if let ExprKind::Assign(lhs, ..) | ExprKind::AssignOp(_, lhs, _) = expr.kind;
85             if let Some(var) = path_to_local(lhs);
86             if expr.span.desugaring_kind().is_none();
87             then { var } else { return; }
88         };
89         let mut visitor = ReadVisitor {
90             cx,
91             var,
92             write_expr: expr,
93             last_expr: expr,
94         };
95         check_for_unsequenced_reads(&mut visitor);
96     }
97     fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
98         match stmt.kind {
99             StmtKind::Local(local) => {
100                 if let Local { init: Some(e), .. } = local {
101                     DivergenceVisitor { cx }.visit_expr(e);
102                 }
103             },
104             StmtKind::Expr(e) | StmtKind::Semi(e) => DivergenceVisitor { cx }.maybe_walk_expr(e),
105             StmtKind::Item(..) => {},
106         }
107     }
108 }
109
110 struct DivergenceVisitor<'a, 'tcx> {
111     cx: &'a LateContext<'tcx>,
112 }
113
114 impl<'a, 'tcx> DivergenceVisitor<'a, 'tcx> {
115     fn maybe_walk_expr(&mut self, e: &'tcx Expr<'_>) {
116         match e.kind {
117             ExprKind::Closure { .. } => {},
118             ExprKind::Match(e, arms, _) => {
119                 self.visit_expr(e);
120                 for arm in arms {
121                     if let Some(Guard::If(if_expr)) = arm.guard {
122                         self.visit_expr(if_expr);
123                     }
124                     // make sure top level arm expressions aren't linted
125                     self.maybe_walk_expr(arm.body);
126                 }
127             },
128             _ => walk_expr(self, e),
129         }
130     }
131     fn report_diverging_sub_expr(&mut self, e: &Expr<'_>) {
132         span_lint(self.cx, DIVERGING_SUB_EXPRESSION, e.span, "sub-expression diverges");
133     }
134 }
135
136 impl<'a, 'tcx> Visitor<'tcx> for DivergenceVisitor<'a, 'tcx> {
137     fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
138         match e.kind {
139             ExprKind::Continue(_) | ExprKind::Break(_, _) | ExprKind::Ret(_) => self.report_diverging_sub_expr(e),
140             ExprKind::Call(func, _) => {
141                 let typ = self.cx.typeck_results().expr_ty(func);
142                 match typ.kind() {
143                     ty::FnDef(..) | ty::FnPtr(_) => {
144                         let sig = typ.fn_sig(self.cx.tcx);
145                         if self.cx.tcx.erase_late_bound_regions(sig).output().kind() == &ty::Never {
146                             self.report_diverging_sub_expr(e);
147                         }
148                     },
149                     _ => {},
150                 }
151             },
152             ExprKind::MethodCall(..) => {
153                 let borrowed_table = self.cx.typeck_results();
154                 if borrowed_table.expr_ty(e).is_never() {
155                     self.report_diverging_sub_expr(e);
156                 }
157             },
158             _ => {
159                 // do not lint expressions referencing objects of type `!`, as that required a
160                 // diverging expression
161                 // to begin with
162             },
163         }
164         self.maybe_walk_expr(e);
165     }
166     fn visit_block(&mut self, _: &'tcx Block<'_>) {
167         // don't continue over blocks, LateLintPass already does that
168     }
169 }
170
171 /// Walks up the AST from the given write expression (`vis.write_expr`) looking
172 /// for reads to the same variable that are unsequenced relative to the write.
173 ///
174 /// This means reads for which there is a common ancestor between the read and
175 /// the write such that
176 ///
177 /// * evaluating the ancestor necessarily evaluates both the read and the write (for example, `&x`
178 ///   and `|| x = 1` don't necessarily evaluate `x`), and
179 ///
180 /// * which one is evaluated first depends on the order of sub-expression evaluation. Blocks, `if`s,
181 ///   loops, `match`es, and the short-circuiting logical operators are considered to have a defined
182 ///   evaluation order.
183 ///
184 /// When such a read is found, the lint is triggered.
185 fn check_for_unsequenced_reads(vis: &mut ReadVisitor<'_, '_>) {
186     let map = &vis.cx.tcx.hir();
187     let mut cur_id = vis.write_expr.hir_id;
188     loop {
189         let parent_id = map.get_parent_node(cur_id);
190         if parent_id == cur_id {
191             break;
192         }
193         let parent_node = match map.find(parent_id) {
194             Some(parent) => parent,
195             None => break,
196         };
197
198         let stop_early = match parent_node {
199             Node::Expr(expr) => check_expr(vis, expr),
200             Node::Stmt(stmt) => check_stmt(vis, stmt),
201             Node::Item(_) => {
202                 // We reached the top of the function, stop.
203                 break;
204             },
205             _ => StopEarly::KeepGoing,
206         };
207         match stop_early {
208             StopEarly::Stop => break,
209             StopEarly::KeepGoing => {},
210         }
211
212         cur_id = parent_id;
213     }
214 }
215
216 /// Whether to stop early for the loop in `check_for_unsequenced_reads`. (If
217 /// `check_expr` weren't an independent function, this would be unnecessary and
218 /// we could just use `break`).
219 enum StopEarly {
220     KeepGoing,
221     Stop,
222 }
223
224 fn check_expr<'a, 'tcx>(vis: &mut ReadVisitor<'a, 'tcx>, expr: &'tcx Expr<'_>) -> StopEarly {
225     if expr.hir_id == vis.last_expr.hir_id {
226         return StopEarly::KeepGoing;
227     }
228
229     match expr.kind {
230         ExprKind::Array(_)
231         | ExprKind::Tup(_)
232         | ExprKind::MethodCall(..)
233         | ExprKind::Call(_, _)
234         | ExprKind::Assign(..)
235         | ExprKind::Index(_, _)
236         | ExprKind::Repeat(_, _)
237         | ExprKind::Struct(_, _, _) => {
238             walk_expr(vis, expr);
239         },
240         ExprKind::Binary(op, _, _) | ExprKind::AssignOp(op, _, _) => {
241             if op.node == BinOpKind::And || op.node == BinOpKind::Or {
242                 // x && y and x || y always evaluate x first, so these are
243                 // strictly sequenced.
244             } else {
245                 walk_expr(vis, expr);
246             }
247         },
248         ExprKind::Closure { .. } => {
249             // Either
250             //
251             // * `var` is defined in the closure body, in which case we've reached the top of the enclosing
252             //   function and can stop, or
253             //
254             // * `var` is captured by the closure, in which case, because evaluating a closure does not evaluate
255             //   its body, we don't necessarily have a write, so we need to stop to avoid generating false
256             //   positives.
257             //
258             // This is also the only place we need to stop early (grrr).
259             return StopEarly::Stop;
260         },
261         // All other expressions either have only one child or strictly
262         // sequence the evaluation order of their sub-expressions.
263         _ => {},
264     }
265
266     vis.last_expr = expr;
267
268     StopEarly::KeepGoing
269 }
270
271 fn check_stmt<'a, 'tcx>(vis: &mut ReadVisitor<'a, 'tcx>, stmt: &'tcx Stmt<'_>) -> StopEarly {
272     match stmt.kind {
273         StmtKind::Expr(expr) | StmtKind::Semi(expr) => check_expr(vis, expr),
274         // If the declaration is of a local variable, check its initializer
275         // expression if it has one. Otherwise, keep going.
276         StmtKind::Local(local) => local
277             .init
278             .as_ref()
279             .map_or(StopEarly::KeepGoing, |expr| check_expr(vis, expr)),
280         StmtKind::Item(..) => StopEarly::KeepGoing,
281     }
282 }
283
284 /// A visitor that looks for reads from a variable.
285 struct ReadVisitor<'a, 'tcx> {
286     cx: &'a LateContext<'tcx>,
287     /// The ID of the variable we're looking for.
288     var: HirId,
289     /// The expressions where the write to the variable occurred (for reporting
290     /// in the lint).
291     write_expr: &'tcx Expr<'tcx>,
292     /// The last (highest in the AST) expression we've checked, so we know not
293     /// to recheck it.
294     last_expr: &'tcx Expr<'tcx>,
295 }
296
297 impl<'a, 'tcx> Visitor<'tcx> for ReadVisitor<'a, 'tcx> {
298     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
299         if expr.hir_id == self.last_expr.hir_id {
300             return;
301         }
302
303         if path_to_local_id(expr, self.var) {
304             // Check that this is a read, not a write.
305             if !is_in_assignment_position(self.cx, expr) {
306                 span_lint_and_note(
307                     self.cx,
308                     MIXED_READ_WRITE_IN_EXPRESSION,
309                     expr.span,
310                     &format!("unsequenced read of `{}`", self.cx.tcx.hir().name(self.var)),
311                     Some(self.write_expr.span),
312                     "whether read occurs before this write depends on evaluation order",
313                 );
314             }
315         }
316         match expr.kind {
317             // We're about to descend a closure. Since we don't know when (or
318             // if) the closure will be evaluated, any reads in it might not
319             // occur here (or ever). Like above, bail to avoid false positives.
320             ExprKind::Closure{..} |
321
322             // We want to avoid a false positive when a variable name occurs
323             // only to have its address taken, so we stop here. Technically,
324             // this misses some weird cases, eg.
325             //
326             // ```rust
327             // let mut x = 0;
328             // let a = foo(&{x = 1; x}, x);
329             // ```
330             //
331             // TODO: fix this
332             ExprKind::AddrOf(_, _, _) => {
333                 return;
334             }
335             _ => {}
336         }
337
338         walk_expr(self, expr);
339     }
340 }
341
342 /// Returns `true` if `expr` is the LHS of an assignment, like `expr = ...`.
343 fn is_in_assignment_position(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
344     if let Some(parent) = get_parent_expr(cx, expr) {
345         if let ExprKind::Assign(lhs, ..) = parent.kind {
346             return lhs.hir_id == expr.hir_id;
347         }
348     }
349     false
350 }