1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
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.
10 use crate::rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
11 use crate::rustc::hir::*;
12 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
14 use crate::rustc::{declare_tool_lint, lint_array};
15 use crate::syntax::ast;
16 use crate::utils::{get_parent_expr, span_lint, span_note_and_lint};
17 use if_chain::if_chain;
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.
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.
26 /// **Known problems:** Code which intentionally depends on the evaluation
27 /// order, or which is correct for any evaluation order.
36 /// // Unclear whether a is 1 or 2.
38 declare_clippy_lint! {
39 pub EVAL_ORDER_DEPENDENCE,
41 "whether a variable read occurs before a write depends on sub-expression evaluation order"
44 /// **What it does:** Checks for diverging calls that are not match arms or
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.
50 /// **Known problems:** Someone might want to use `some_bool || panic!()` as a
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!()`
60 declare_clippy_lint! {
61 pub DIVERGING_SUB_EXPRESSION,
63 "whether an expression contains a diverging sub expression"
66 #[derive(Copy, Clone)]
67 pub struct EvalOrderDependence;
69 impl LintPass for EvalOrderDependence {
70 fn get_lints(&self) -> LintArray {
71 lint_array!(EVAL_ORDER_DEPENDENCE, DIVERGING_SUB_EXPRESSION)
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.
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 {
90 check_for_unsequenced_reads(&mut visitor);
99 fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
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);
113 struct DivergenceVisitor<'a, 'tcx: 'a> {
114 cx: &'a LateContext<'a, 'tcx>,
117 impl<'a, 'tcx> DivergenceVisitor<'a, 'tcx> {
118 fn maybe_walk_expr(&mut self, e: &'tcx Expr) {
120 ExprKind::Closure(.., _) => {},
121 ExprKind::Match(ref e, ref arms, _) => {
124 if let Some(ref guard) = arm.guard {
126 Guard::If(if_expr) => self.visit_expr(if_expr),
129 // make sure top level arm expressions aren't linted
130 self.maybe_walk_expr(&*arm.body);
133 _ => walk_expr(self, e),
136 fn report_diverging_sub_expr(&mut self, e: &Expr) {
137 span_lint(self.cx, DIVERGING_SUB_EXPRESSION, e.span, "sub-expression diverges");
141 impl<'a, 'tcx> Visitor<'tcx> for DivergenceVisitor<'a, 'tcx> {
142 fn visit_expr(&mut self, e: &'tcx Expr) {
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);
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);
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);
164 // do not lint expressions referencing objects of type `!`, as that required a
165 // diverging expression
169 self.maybe_walk_expr(e);
171 fn visit_block(&mut self, _: &'tcx Block) {
172 // don't continue over blocks, LateLintPass already does that
174 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
175 NestedVisitorMap::None
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.
182 /// This means reads for which there is a common ancestor between the read and
183 /// the write such that
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
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.
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;
197 let parent_id = map.get_parent_node(cur_id);
198 if parent_id == cur_id {
201 let parent_node = match map.find(parent_id) {
202 Some(parent) => parent,
206 let stop_early = match parent_node {
207 Node::Expr(expr) => check_expr(vis, expr),
208 Node::Stmt(stmt) => check_stmt(vis, stmt),
210 // We reached the top of the function, stop.
213 _ => StopEarly::KeepGoing,
216 StopEarly::Stop => break,
217 StopEarly::KeepGoing => {},
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`).
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;
240 | ExprKind::MethodCall(..)
241 | ExprKind::Call(_, _)
242 | ExprKind::Assign(_, _)
243 | ExprKind::Index(_, _)
244 | ExprKind::Repeat(_, _)
245 | ExprKind::Struct(_, _, _) => {
246 walk_expr(vis, expr);
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.
253 walk_expr(vis, expr);
256 ExprKind::Closure(_, _, _, _, _) => {
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
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
266 // This is also the only place we need to stop early (grrr).
267 return StopEarly::Stop;
269 // All other expressions either have only one child or strictly
270 // sequence the evaluation order of their sub-expressions.
274 vis.last_expr = expr;
279 fn check_stmt<'a, 'tcx>(vis: &mut ReadVisitor<'a, 'tcx>, stmt: &'tcx Stmt) -> StopEarly {
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),
290 .and_then(|local| local.init.as_ref())
291 .map_or(StopEarly::KeepGoing, |expr| check_expr(vis, expr))
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.
301 /// The expressions where the write to the variable occurred (for reporting
303 write_expr: &'tcx Expr,
304 /// The last (highest in the AST) expression we've checked, so we know not
306 last_expr: &'tcx Expr,
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 {
316 ExprKind::Path(ref qpath) => {
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);
327 EVAL_ORDER_DEPENDENCE,
329 "unsequenced read of a variable",
330 self.write_expr.span,
331 "whether read occurs before this write depends on evaluation order"
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(_, _, _, _, _) |
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.
347 // let a = foo(&{x = 1; x}, x);
351 ExprKind::AddrOf(_, _) => {
357 walk_expr(self, expr);
359 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
360 NestedVisitorMap::None
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;