]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_update.rs
Auto merge of #3946 - rchaser53:issue-3920, r=flip1995
[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, LintArray, LintPass};
4 use rustc::ty;
5 use rustc::{declare_tool_lint, lint_array};
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     /// Point {
19     ///     x: 1,
20     ///     y: 0,
21     ///     ..zero_point
22     /// }
23     /// ```
24     pub NEEDLESS_UPDATE,
25     complexity,
26     "using `Foo { ..base }` when there are no missing fields"
27 }
28
29 #[derive(Copy, Clone)]
30 pub struct Pass;
31
32 impl LintPass for Pass {
33     fn get_lints(&self) -> LintArray {
34         lint_array!(NEEDLESS_UPDATE)
35     }
36
37     fn name(&self) -> &'static str {
38         "NeedUpdate"
39     }
40 }
41
42 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
43     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
44         if let ExprKind::Struct(_, ref fields, Some(ref base)) = expr.node {
45             let ty = cx.tables.expr_ty(expr);
46             if let ty::Adt(def, _) = ty.sty {
47                 if fields.len() == def.non_enum_variant().fields.len() {
48                     span_lint(
49                         cx,
50                         NEEDLESS_UPDATE,
51                         base.span,
52                         "struct update has no effect, all the fields in the struct have already been specified",
53                     );
54                 }
55             }
56         }
57     }
58 }