]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/temporary_assignment.rs
Rollup merge of #87759 - m-ou-se:linux-process-sealed, r=jyn514
[rust.git] / src / tools / clippy / clippy_lints / src / temporary_assignment.rs
1 use clippy_utils::diagnostics::span_lint;
2 use clippy_utils::is_adjusted;
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
9     /// Checks for construction of a structure or tuple just to
10     /// assign a value in it.
11     ///
12     /// ### Why is this bad?
13     /// Readability. If the structure is only created to be
14     /// updated, why not write the structure you want in the first place?
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(expr: &Expr<'_>) -> bool {
26     matches!(&expr.kind, ExprKind::Struct(..) | ExprKind::Tup(..))
27 }
28
29 declare_lint_pass!(TemporaryAssignment => [TEMPORARY_ASSIGNMENT]);
30
31 impl<'tcx> LateLintPass<'tcx> for TemporaryAssignment {
32     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
33         if let ExprKind::Assign(target, ..) = &expr.kind {
34             let mut base = target;
35             while let ExprKind::Field(f, _) | ExprKind::Index(f, _) = &base.kind {
36                 base = f;
37             }
38             if is_temporary(base) && !is_adjusted(cx, base) {
39                 span_lint(cx, TEMPORARY_ASSIGNMENT, expr.span, "assignment to temporary");
40             }
41         }
42     }
43 }