]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/temporary_assignment.rs
Merge pull request #3465 from flip1995/rustfmt
[rust.git] / clippy_lints / src / temporary_assignment.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::rustc::hir::{Expr, ExprKind};
11 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
12 use crate::rustc::{declare_tool_lint, lint_array};
13 use crate::utils::is_adjusted;
14 use crate::utils::span_lint;
15
16 /// **What it does:** Checks for construction of a structure or tuple just to
17 /// assign a value in it.
18 ///
19 /// **Why is this bad?** Readability. If the structure is only created to be
20 /// updated, why not write the structure you want in the first place?
21 ///
22 /// **Known problems:** None.
23 ///
24 /// **Example:**
25 /// ```rust
26 /// (0, 0).0 = 1
27 /// ```
28 declare_clippy_lint! {
29     pub TEMPORARY_ASSIGNMENT,
30     complexity,
31     "assignments to temporaries"
32 }
33
34 fn is_temporary(expr: &Expr) -> bool {
35     match expr.node {
36         ExprKind::Struct(..) | ExprKind::Tup(..) => true,
37         _ => false,
38     }
39 }
40
41 #[derive(Copy, Clone)]
42 pub struct Pass;
43
44 impl LintPass for Pass {
45     fn get_lints(&self) -> LintArray {
46         lint_array!(TEMPORARY_ASSIGNMENT)
47     }
48 }
49
50 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
51     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
52         if let ExprKind::Assign(ref target, _) = expr.node {
53             if let ExprKind::Field(ref base, _) = target.node {
54                 if is_temporary(base) && !is_adjusted(cx, base) {
55                     span_lint(cx, TEMPORARY_ASSIGNMENT, expr.span, "assignment to temporary");
56                 }
57             }
58         }
59     }
60 }