]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/temporary_assignment.rs
Use lint pass macros
[rust.git] / clippy_lints / src / temporary_assignment.rs
1 use crate::utils::is_adjusted;
2 use crate::utils::span_lint;
3 use rustc::hir::def::Def;
4 use rustc::hir::{Expr, ExprKind};
5 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
6 use rustc::{declare_lint_pass, declare_tool_lint};
7
8 declare_clippy_lint! {
9     /// **What it does:** Checks for construction of a structure or tuple just to
10     /// assign a value in it.
11     ///
12     /// **Why is this bad?** Readability. If the structure is only created to be
13     /// updated, why not write the structure you want in the first place?
14     ///
15     /// **Known problems:** None.
16     ///
17     /// **Example:**
18     /// ```rust
19     /// (0, 0).0 = 1
20     /// ```
21     pub TEMPORARY_ASSIGNMENT,
22     complexity,
23     "assignments to temporaries"
24 }
25
26 fn is_temporary(cx: &LateContext<'_, '_>, expr: &Expr) -> bool {
27     match &expr.node {
28         ExprKind::Struct(..) | ExprKind::Tup(..) => true,
29         ExprKind::Path(qpath) => {
30             if let Def::Const(..) = cx.tables.qpath_def(qpath, expr.hir_id) {
31                 true
32             } else {
33                 false
34             }
35         },
36         _ => false,
37     }
38 }
39
40 declare_lint_pass!(TemporaryAssignment => [TEMPORARY_ASSIGNMENT]);
41
42 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TemporaryAssignment {
43     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
44         if let ExprKind::Assign(target, _) = &expr.node {
45             let mut base = target;
46             while let ExprKind::Field(f, _) | ExprKind::Index(f, _) = &base.node {
47                 base = f;
48             }
49             if is_temporary(cx, base) && !is_adjusted(cx, base) {
50                 span_lint(cx, TEMPORARY_ASSIGNMENT, expr.span, "assignment to temporary");
51             }
52         }
53     }
54 }