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