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