]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_update.rs
Merge commit 'ff0993c5e9162ddaea78e83d0f0161e68bd4ea73' into clippy
[rust.git] / clippy_lints / src / needless_update.rs
1 use crate::utils::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:** Checks for needlessly including a base struct on update
9     /// when all fields are changed anyway.
10     ///
11     /// **Why is this bad?** This will cost resources (because the base has to be
12     /// somewhere), and make the code less readable.
13     ///
14     /// **Known problems:** None.
15     ///
16     /// **Example:**
17     /// ```rust
18     /// # struct Point {
19     /// #     x: i32,
20     /// #     y: i32,
21     /// #     z: i32,
22     /// # }
23     /// # let zero_point = Point { x: 0, y: 0, z: 0 };
24     ///
25     /// // Bad
26     /// Point {
27     ///     x: 1,
28     ///     y: 1,
29     ///     z: 1,
30     ///     ..zero_point
31     /// };
32     ///
33     /// // Ok
34     /// Point {
35     ///     x: 1,
36     ///     y: 1,
37     ///     ..zero_point
38     /// };
39     /// ```
40     pub NEEDLESS_UPDATE,
41     complexity,
42     "using `Foo { ..base }` when there are no missing fields"
43 }
44
45 declare_lint_pass!(NeedlessUpdate => [NEEDLESS_UPDATE]);
46
47 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessUpdate {
48     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
49         if let ExprKind::Struct(_, ref fields, Some(ref base)) = expr.kind {
50             let ty = cx.tables.expr_ty(expr);
51             if let ty::Adt(def, _) = ty.kind {
52                 if fields.len() == def.non_enum_variant().fields.len() {
53                     span_lint(
54                         cx,
55                         NEEDLESS_UPDATE,
56                         base.span,
57                         "struct update has no effect, all the fields in the struct have already been specified",
58                     );
59                 }
60             }
61         }
62     }
63 }