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