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