1 use rustc::hir::def_id::DefId;
2 use rustc::hir::intravisit::{Visitor, walk_expr, NestedVisitorMap};
6 use utils::{get_parent_expr, span_note_and_lint, span_lint};
8 /// **What it does:** Checks for a read and a write to the same variable where
9 /// whether the read occurs before or after the write depends on the evaluation
10 /// order of sub-expressions.
12 /// **Why is this bad?** It is often confusing to read. In addition, the
13 /// sub-expression evaluation order for Rust is not well documented.
15 /// **Known problems:** Code which intentionally depends on the evaluation
16 /// order, or which is correct for any evaluation order.
21 /// let a = {x = 1; 1} + x;
22 /// // Unclear whether a is 1 or 2.
25 pub EVAL_ORDER_DEPENDENCE,
27 "whether a variable read occurs before a write depends on sub-expression evaluation order"
30 /// **What it does:** Checks for diverging calls that are not match arms or statements.
32 /// **Why is this bad?** It is often confusing to read. In addition, the
33 /// sub-expression evaluation order for Rust is not well documented.
35 /// **Known problems:** Someone might want to use `some_bool || panic!()` as a shorthand.
39 /// let a = b() || panic!() || c();
40 /// // `c()` is dead, `panic!()` is only called if `b()` returns `false`
41 /// let x = (a, b, c, panic!());
42 /// // can simply be replaced by `panic!()`
45 pub DIVERGING_SUB_EXPRESSION,
47 "whether an expression contains a diverging sub expression"
51 pub struct EvalOrderDependence;
53 impl LintPass for EvalOrderDependence {
54 fn get_lints(&self) -> LintArray {
55 lint_array!(EVAL_ORDER_DEPENDENCE, DIVERGING_SUB_EXPRESSION)
59 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for EvalOrderDependence {
60 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
61 // Find a write to a local variable.
63 ExprAssign(ref lhs, _) |
64 ExprAssignOp(_, ref lhs, _) => {
65 if let ExprPath(ref qpath) = lhs.node {
66 if let QPath::Resolved(_, ref path) = *qpath {
67 if path.segments.len() == 1 {
68 let var = cx.tables.qpath_def(qpath, lhs.id).def_id();
69 let mut visitor = ReadVisitor {
75 check_for_unsequenced_reads(&mut visitor);
83 fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
86 StmtSemi(ref e, _) => DivergenceVisitor { cx: cx }.maybe_walk_expr(e),
87 StmtDecl(ref d, _) => {
88 if let DeclLocal(ref local) = d.node {
89 if let Local { init: Some(ref e), .. } = **local {
90 DivergenceVisitor { cx: cx }.visit_expr(e);
98 struct DivergenceVisitor<'a, 'tcx: 'a> {
99 cx: &'a LateContext<'a, 'tcx>,
102 impl<'a, 'tcx> DivergenceVisitor<'a, 'tcx> {
103 fn maybe_walk_expr(&mut self, e: &'tcx Expr) {
105 ExprClosure(..) => {},
106 ExprMatch(ref e, ref arms, _) => {
109 if let Some(ref guard) = arm.guard {
110 self.visit_expr(guard);
112 // make sure top level arm expressions aren't linted
113 self.maybe_walk_expr(&*arm.body);
116 _ => walk_expr(self, e),
119 fn report_diverging_sub_expr(&mut self, e: &Expr) {
120 span_lint(self.cx, DIVERGING_SUB_EXPRESSION, e.span, "sub-expression diverges");
124 impl<'a, 'tcx> Visitor<'tcx> for DivergenceVisitor<'a, 'tcx> {
125 fn visit_expr(&mut self, e: &'tcx Expr) {
127 ExprAgain(_) | ExprBreak(_, _) | ExprRet(_) => self.report_diverging_sub_expr(e),
128 ExprCall(ref func, _) => {
129 let typ = self.cx.tables.expr_ty(func);
131 ty::TyFnDef(..) | ty::TyFnPtr(_) => {
132 let sig = typ.fn_sig(self.cx.tcx);
133 if let ty::TyNever = self.cx.tcx.erase_late_bound_regions(&sig).output().sty {
134 self.report_diverging_sub_expr(e);
140 ExprMethodCall(..) => {
141 let borrowed_table = self.cx.tables;
142 if borrowed_table.expr_ty(e).is_never() {
143 self.report_diverging_sub_expr(e);
147 // do not lint expressions referencing objects of type `!`, as that required a diverging expression
151 self.maybe_walk_expr(e);
153 fn visit_block(&mut self, _: &'tcx Block) {
154 // don't continue over blocks, LateLintPass already does that
156 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
157 NestedVisitorMap::None
161 /// Walks up the AST from the given write expression (`vis.write_expr`) looking
162 /// for reads to the same variable that are unsequenced relative to the write.
164 /// This means reads for which there is a common ancestor between the read and
165 /// the write such that
167 /// * evaluating the ancestor necessarily evaluates both the read and the write
168 /// (for example, `&x` and `|| x = 1` don't necessarily evaluate `x`), and
170 /// * which one is evaluated first depends on the order of sub-expression
171 /// evaluation. Blocks, `if`s, loops, `match`es, and the short-circuiting
172 /// logical operators are considered to have a defined evaluation order.
174 /// When such a read is found, the lint is triggered.
175 fn check_for_unsequenced_reads(vis: &mut ReadVisitor) {
176 let map = &vis.cx.tcx.hir;
177 let mut cur_id = vis.write_expr.id;
179 let parent_id = map.get_parent_node(cur_id);
180 if parent_id == cur_id {
183 let parent_node = match map.find(parent_id) {
184 Some(parent) => parent,
188 let stop_early = match parent_node {
189 map::Node::NodeExpr(expr) => check_expr(vis, expr),
190 map::Node::NodeStmt(stmt) => check_stmt(vis, stmt),
191 map::Node::NodeItem(_) => {
192 // We reached the top of the function, stop.
195 _ => StopEarly::KeepGoing,
198 StopEarly::Stop => break,
199 StopEarly::KeepGoing => {},
206 /// Whether to stop early for the loop in `check_for_unsequenced_reads`. (If
207 /// `check_expr` weren't an independent function, this would be unnecessary and
208 /// we could just use `break`).
214 fn check_expr<'a, 'tcx>(vis: &mut ReadVisitor<'a, 'tcx>, expr: &'tcx Expr) -> StopEarly {
215 if expr.id == vis.last_expr.id {
216 return StopEarly::KeepGoing;
227 ExprStruct(_, _, _) => {
228 walk_expr(vis, expr);
230 ExprBinary(op, _, _) |
231 ExprAssignOp(op, _, _) => {
232 if op.node == BiAnd || op.node == BiOr {
233 // x && y and x || y always evaluate x first, so these are
234 // strictly sequenced.
236 walk_expr(vis, expr);
239 ExprClosure(_, _, _, _) => {
242 // * `var` is defined in the closure body, in which case we've
243 // reached the top of the enclosing function and can stop, or
245 // * `var` is captured by the closure, in which case, because
246 // evaluating a closure does not evaluate its body, we don't
247 // necessarily have a write, so we need to stop to avoid
248 // generating false positives.
250 // This is also the only place we need to stop early (grrr).
251 return StopEarly::Stop;
253 // All other expressions either have only one child or strictly
254 // sequence the evaluation order of their sub-expressions.
258 vis.last_expr = expr;
263 fn check_stmt<'a, 'tcx>(vis: &mut ReadVisitor<'a, 'tcx>, stmt: &'tcx Stmt) -> StopEarly {
265 StmtExpr(ref expr, _) |
266 StmtSemi(ref expr, _) => check_expr(vis, expr),
267 StmtDecl(ref decl, _) => {
268 // If the declaration is of a local variable, check its initializer
269 // expression if it has one. Otherwise, keep going.
270 let local = match decl.node {
271 DeclLocal(ref local) => Some(local),
274 local.and_then(|local| local.init.as_ref())
275 .map_or(StopEarly::KeepGoing, |expr| check_expr(vis, expr))
280 /// A visitor that looks for reads from a variable.
281 struct ReadVisitor<'a, 'tcx: 'a> {
282 cx: &'a LateContext<'a, 'tcx>,
283 /// The id of the variable we're looking for.
285 /// The expressions where the write to the variable occurred (for reporting
287 write_expr: &'tcx Expr,
288 /// The last (highest in the AST) expression we've checked, so we know not
290 last_expr: &'tcx Expr,
293 impl<'a, 'tcx> Visitor<'tcx> for ReadVisitor<'a, 'tcx> {
294 fn visit_expr(&mut self, expr: &'tcx Expr) {
295 if expr.id == self.last_expr.id {
300 ExprPath(ref qpath) => {
301 if let QPath::Resolved(None, ref path) = *qpath {
302 if path.segments.len() == 1 && self.cx.tables.qpath_def(qpath, expr.id).def_id() == self.var {
303 if is_in_assignment_position(self.cx, expr) {
304 // This is a write, not a read.
308 EVAL_ORDER_DEPENDENCE,
310 "unsequenced read of a variable",
311 self.write_expr.span,
312 "whether read occurs before this write depends on evaluation order"
318 // We're about to descend a closure. Since we don't know when (or
319 // if) the closure will be evaluated, any reads in it might not
320 // occur here (or ever). Like above, bail to avoid false positives.
321 ExprClosure(_, _, _, _) |
323 // We want to avoid a false positive when a variable name occurs
324 // only to have its address taken, so we stop here. Technically,
325 // this misses some weird cases, eg.
329 // let a = foo(&{x = 1; x}, x);
333 ExprAddrOf(_, _) => {
339 walk_expr(self, expr);
341 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
342 NestedVisitorMap::None
346 /// Returns true if `expr` is the LHS of an assignment, like `expr = ...`.
347 fn is_in_assignment_position(cx: &LateContext, expr: &Expr) -> bool {
348 if let Some(parent) = get_parent_expr(cx, expr) {
349 if let ExprAssign(ref lhs, _) = parent.node {
350 return lhs.id == expr.id;