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