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