]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_update.rs
Auto merge of #3598 - xfix:apply-cargo-fix-edition-idioms, r=phansch
[rust.git] / clippy_lints / src / needless_update.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10 use crate::utils::span_lint;
11 use rustc::hir::{Expr, ExprKind};
12 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
13 use rustc::ty;
14 use rustc::{declare_tool_lint, lint_array};
15
16 /// **What it does:** Checks for needlessly including a base struct on update
17 /// when all fields are changed anyway.
18 ///
19 /// **Why is this bad?** This will cost resources (because the base has to be
20 /// somewhere), and make the code less readable.
21 ///
22 /// **Known problems:** None.
23 ///
24 /// **Example:**
25 /// ```rust
26 /// Point {
27 ///     x: 1,
28 ///     y: 0,
29 ///     ..zero_point
30 /// }
31 /// ```
32 declare_clippy_lint! {
33     pub NEEDLESS_UPDATE,
34     complexity,
35     "using `Foo { ..base }` when there are no missing fields"
36 }
37
38 #[derive(Copy, Clone)]
39 pub struct Pass;
40
41 impl LintPass for Pass {
42     fn get_lints(&self) -> LintArray {
43         lint_array!(NEEDLESS_UPDATE)
44     }
45 }
46
47 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
48     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
49         if let ExprKind::Struct(_, ref fields, Some(ref base)) = expr.node {
50             let ty = cx.tables.expr_ty(expr);
51             if let ty::Adt(def, _) = ty.sty {
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 }