]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_update.rs
82cd502081f7c7e347261845005f668ec8074fb2
[rust.git] / clippy_lints / src / needless_update.rs
1 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
2 use rustc::ty::TyAdt;
3 use rustc::hir::{Expr, ExprStruct};
4 use 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_lint! {
19     pub NEEDLESS_UPDATE,
20     Warn,
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 LateLintPass for Pass {
34     fn check_expr<'a, 'tcx: 'a>(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
35         if let ExprStruct(_, ref fields, Some(ref base)) = expr.node {
36             let ty = cx.tcx.tables().expr_ty(expr);
37             if let TyAdt(def, _) = ty.sty {
38                 if fields.len() == def.struct_variant().fields.len() {
39                     span_lint(cx,
40                               NEEDLESS_UPDATE,
41                               base.span,
42                               "struct update has no effect, all the fields in the struct have already been specified");
43                 }
44             }
45         }
46     }
47 }