about summary refs log tree commit diff
path: root/clippy_lints/src/needless_update.rs
blob: 8f325404deb45bffcb0ae58fc1fd91cdd0586276 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use clippy_utils::diagnostics::span_lint;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty;
use rustc_session::{declare_lint_pass, declare_tool_lint};

declare_clippy_lint! {
    /// **What it does:** Checks for needlessly including a base struct on update
    /// when all fields are changed anyway.
    ///
    /// This lint is not applied to structs marked with
    /// [non_exhaustive](https://doc.rust-lang.org/reference/attributes/type_system.html).
    ///
    /// **Why is this bad?** This will cost resources (because the base has to be
    /// somewhere), and make the code less readable.
    ///
    /// **Known problems:** None.
    ///
    /// **Example:**
    /// ```rust
    /// # struct Point {
    /// #     x: i32,
    /// #     y: i32,
    /// #     z: i32,
    /// # }
    /// # let zero_point = Point { x: 0, y: 0, z: 0 };
    ///
    /// // Bad
    /// Point {
    ///     x: 1,
    ///     y: 1,
    ///     z: 1,
    ///     ..zero_point
    /// };
    ///
    /// // Ok
    /// Point {
    ///     x: 1,
    ///     y: 1,
    ///     ..zero_point
    /// };
    /// ```
    pub NEEDLESS_UPDATE,
    complexity,
    "using `Foo { ..base }` when there are no missing fields"
}

declare_lint_pass!(NeedlessUpdate => [NEEDLESS_UPDATE]);

impl<'tcx> LateLintPass<'tcx> for NeedlessUpdate {
    fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
        if let ExprKind::Struct(_, fields, Some(base)) = expr.kind {
            let ty = cx.typeck_results().expr_ty(expr);
            if let ty::Adt(def, _) = ty.kind() {
                if fields.len() == def.non_enum_variant().fields.len()
                    && !def.variants[0_usize.into()].is_field_list_non_exhaustive()
                {
                    span_lint(
                        cx,
                        NEEDLESS_UPDATE,
                        base.span,
                        "struct update has no effect, all the fields in the struct have already been specified",
                    );
                }
            }
        }
    }
}