]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/temporary_assignment.rs
Auto merge of #81993 - flip1995:clippyup, r=Manishearth
[rust.git] / clippy_lints / src / temporary_assignment.rs
1 use crate::utils::{is_adjusted, span_lint};
2 use rustc_hir::{Expr, ExprKind};
3 use rustc_lint::{LateContext, LateLintPass};
4 use rustc_session::{declare_lint_pass, declare_tool_lint};
5
6 declare_clippy_lint! {
7     /// **What it does:** Checks for construction of a structure or tuple just to
8     /// assign a value in it.
9     ///
10     /// **Why is this bad?** Readability. If the structure is only created to be
11     /// updated, why not write the structure you want in the first place?
12     ///
13     /// **Known problems:** None.
14     ///
15     /// **Example:**
16     /// ```rust
17     /// (0, 0).0 = 1
18     /// ```
19     pub TEMPORARY_ASSIGNMENT,
20     complexity,
21     "assignments to temporaries"
22 }
23
24 fn is_temporary(expr: &Expr<'_>) -> bool {
25     matches!(&expr.kind, ExprKind::Struct(..) | ExprKind::Tup(..))
26 }
27
28 declare_lint_pass!(TemporaryAssignment => [TEMPORARY_ASSIGNMENT]);
29
30 impl<'tcx> LateLintPass<'tcx> for TemporaryAssignment {
31     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
32         if let ExprKind::Assign(target, ..) = &expr.kind {
33             let mut base = target;
34             while let ExprKind::Field(f, _) | ExprKind::Index(f, _) = &base.kind {
35                 base = f;
36             }
37             if is_temporary(base) && !is_adjusted(cx, base) {
38                 span_lint(cx, TEMPORARY_ASSIGNMENT, expr.span, "assignment to temporary");
39             }
40         }
41     }
42 }