]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_update.rs
Auto merge of #4920 - lily-commure:fix-unnecessary-filter-map-docs, r=phansch
[rust.git] / clippy_lints / src / needless_update.rs
1 use crate::utils::span_lint;
2 use rustc::declare_lint_pass;
3 use rustc::hir::{Expr, ExprKind};
4 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
5 use rustc::ty;
6 use rustc_session::declare_tool_lint;
7
8 declare_clippy_lint! {
9     /// **What it does:** Checks for needlessly including a base struct on update
10     /// when all fields are changed anyway.
11     ///
12     /// **Why is this bad?** This will cost resources (because the base has to be
13     /// somewhere), and make the code less readable.
14     ///
15     /// **Known problems:** None.
16     ///
17     /// **Example:**
18     /// ```rust
19     /// # struct Point {
20     /// #     x: i32,
21     /// #     y: i32,
22     /// #     z: i32,
23     /// # }
24     /// # let zero_point = Point { x: 0, y: 0, z: 0 };
25     /// Point {
26     ///     x: 1,
27     ///     y: 1,
28     ///     ..zero_point
29     /// };
30     /// ```
31     pub NEEDLESS_UPDATE,
32     complexity,
33     "using `Foo { ..base }` when there are no missing fields"
34 }
35
36 declare_lint_pass!(NeedlessUpdate => [NEEDLESS_UPDATE]);
37
38 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessUpdate {
39     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
40         if let ExprKind::Struct(_, ref fields, Some(ref base)) = expr.kind {
41             let ty = cx.tables.expr_ty(expr);
42             if let ty::Adt(def, _) = ty.kind {
43                 if fields.len() == def.non_enum_variant().fields.len() {
44                     span_lint(
45                         cx,
46                         NEEDLESS_UPDATE,
47                         base.span,
48                         "struct update has no effect, all the fields in the struct have already been specified",
49                     );
50                 }
51             }
52         }
53     }
54 }