]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/temporary_assignment.rs
Remove all copyright license headers
[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_tool_lint, lint_array};
7
8 /// **What it does:** Checks for construction of a structure or tuple just to
9 /// assign a value in it.
10 ///
11 /// **Why is this bad?** Readability. If the structure is only created to be
12 /// updated, why not write the structure you want in the first place?
13 ///
14 /// **Known problems:** None.
15 ///
16 /// **Example:**
17 /// ```rust
18 /// (0, 0).0 = 1
19 /// ```
20 declare_clippy_lint! {
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 #[derive(Copy, Clone)]
41 pub struct Pass;
42
43 impl LintPass for Pass {
44     fn get_lints(&self) -> LintArray {
45         lint_array!(TEMPORARY_ASSIGNMENT)
46     }
47 }
48
49 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
50     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
51         if let ExprKind::Assign(target, _) = &expr.node {
52             let mut base = target;
53             while let ExprKind::Field(f, _) | ExprKind::Index(f, _) = &base.node {
54                 base = f;
55             }
56             if is_temporary(cx, base) && !is_adjusted(cx, base) {
57                 span_lint(cx, TEMPORARY_ASSIGNMENT, expr.span, "assignment to temporary");
58             }
59         }
60     }
61 }