]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/temporary_assignment.rs
Allow UUID style formatting for `inconsistent_digit_grouping` lint
[rust.git] / clippy_lints / src / temporary_assignment.rs
1 use crate::utils::{is_adjusted, span_lint};
2 use rustc_hir::def::{DefKind, Res};
3 use rustc_hir::{Expr, ExprKind};
4 use rustc_lint::{LateContext, LateLintPass};
5 use rustc_session::{declare_lint_pass, declare_tool_lint};
6
7 declare_clippy_lint! {
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     pub TEMPORARY_ASSIGNMENT,
21     complexity,
22     "assignments to temporaries"
23 }
24
25 fn is_temporary(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool {
26     match &expr.kind {
27         ExprKind::Struct(..) | ExprKind::Tup(..) => true,
28         ExprKind::Path(qpath) => {
29             if let Res::Def(DefKind::Const, ..) = cx.tables.qpath_res(qpath, expr.hir_id) {
30                 true
31             } else {
32                 false
33             }
34         },
35         _ => false,
36     }
37 }
38
39 declare_lint_pass!(TemporaryAssignment => [TEMPORARY_ASSIGNMENT]);
40
41 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TemporaryAssignment {
42     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
43         if let ExprKind::Assign(target, ..) = &expr.kind {
44             let mut base = target;
45             while let ExprKind::Field(f, _) | ExprKind::Index(f, _) = &base.kind {
46                 base = f;
47             }
48             if is_temporary(cx, base) && !is_adjusted(cx, base) {
49                 span_lint(cx, TEMPORARY_ASSIGNMENT, expr.span, "assignment to temporary");
50             }
51         }
52     }
53 }