]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/needless_update.rs
Rollup merge of #91630 - GuillaumeGomez:missing-whitespace, r=notriddle
[rust.git] / src / tools / clippy / clippy_lints / src / needless_update.rs
1 use clippy_utils::diagnostics::span_lint;
2 use rustc_hir::{Expr, ExprKind};
3 use rustc_lint::{LateContext, LateLintPass};
4 use rustc_middle::ty;
5 use rustc_session::{declare_lint_pass, declare_tool_lint};
6
7 declare_clippy_lint! {
8     /// ### What it does
9     /// Checks for needlessly including a base struct on update
10     /// when all fields are changed anyway.
11     ///
12     /// This lint is not applied to structs marked with
13     /// [non_exhaustive](https://doc.rust-lang.org/reference/attributes/type_system.html).
14     ///
15     /// ### Why is this bad?
16     /// This will cost resources (because the base has to be
17     /// somewhere), and make the code less readable.
18     ///
19     /// ### Example
20     /// ```rust
21     /// # struct Point {
22     /// #     x: i32,
23     /// #     y: i32,
24     /// #     z: i32,
25     /// # }
26     /// # let zero_point = Point { x: 0, y: 0, z: 0 };
27     ///
28     /// // Bad
29     /// Point {
30     ///     x: 1,
31     ///     y: 1,
32     ///     z: 1,
33     ///     ..zero_point
34     /// };
35     ///
36     /// // Ok
37     /// Point {
38     ///     x: 1,
39     ///     y: 1,
40     ///     ..zero_point
41     /// };
42     /// ```
43     #[clippy::version = "pre 1.29.0"]
44     pub NEEDLESS_UPDATE,
45     complexity,
46     "using `Foo { ..base }` when there are no missing fields"
47 }
48
49 declare_lint_pass!(NeedlessUpdate => [NEEDLESS_UPDATE]);
50
51 impl<'tcx> LateLintPass<'tcx> for NeedlessUpdate {
52     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
53         if let ExprKind::Struct(_, fields, Some(base)) = expr.kind {
54             let ty = cx.typeck_results().expr_ty(expr);
55             if let ty::Adt(def, _) = ty.kind() {
56                 if fields.len() == def.non_enum_variant().fields.len()
57                     && !def.variants[0_usize.into()].is_field_list_non_exhaustive()
58                 {
59                     span_lint(
60                         cx,
61                         NEEDLESS_UPDATE,
62                         base.span,
63                         "struct update has no effect, all the fields in the struct have already been specified",
64                     );
65                 }
66             }
67         }
68     }
69 }