]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/temporary_assignment.rs
round 1
[rust.git] / clippy_lints / src / temporary_assignment.rs
1 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
2 use rustc::hir::{Expr, ExprAssign, ExprField, ExprStruct, ExprTup, ExprTupField};
3 use utils::is_adjusted;
4 use utils::span_lint;
5
6 /// **What it does:** This lint checks for construction of a structure or tuple just to assign a value in it.
7 ///
8 /// **Why is this bad?** Readability. If the structure is only created to be updated, why not write the structure you want in the first place?
9 ///
10 /// **Known problems:** None.
11 ///
12 /// **Example:** `(0, 0).0 = 1`
13 declare_lint! {
14     pub TEMPORARY_ASSIGNMENT,
15     Warn,
16     "assignments to temporaries"
17 }
18
19 fn is_temporary(expr: &Expr) -> bool {
20     match expr.node {
21         ExprStruct(..) | ExprTup(..) => true,
22         _ => false,
23     }
24 }
25
26 #[derive(Copy, Clone)]
27 pub struct Pass;
28
29 impl LintPass for Pass {
30     fn get_lints(&self) -> LintArray {
31         lint_array!(TEMPORARY_ASSIGNMENT)
32     }
33 }
34
35 impl LateLintPass for Pass {
36     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
37         if let ExprAssign(ref target, _) = expr.node {
38             match target.node {
39                 ExprField(ref base, _) |
40                 ExprTupField(ref base, _) => {
41                     if is_temporary(base) && !is_adjusted(cx, base) {
42                         span_lint(cx, TEMPORARY_ASSIGNMENT, expr.span, "assignment to temporary");
43                     }
44                 }
45                 _ => (),
46             }
47         }
48     }
49 }