]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/inconsistent_struct_constructor.rs
1debdef9d86c7b077594bef9115ec3fbf70d8f9b
[rust.git] / clippy_lints / src / inconsistent_struct_constructor.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::source::snippet;
3 use if_chain::if_chain;
4 use rustc_data_structures::fx::FxHashMap;
5 use rustc_errors::Applicability;
6 use rustc_hir::{self as hir, ExprKind};
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9 use rustc_span::symbol::Symbol;
10
11 declare_clippy_lint! {
12     /// ### What it does
13     /// Checks for struct constructors where all fields are shorthand and
14     /// the order of the field init shorthand in the constructor is inconsistent
15     /// with the order in the struct definition.
16     ///
17     /// ### Why is this bad?
18     /// Since the order of fields in a constructor doesn't affect the
19     /// resulted instance as the below example indicates,
20     ///
21     /// ```rust
22     /// #[derive(Debug, PartialEq, Eq)]
23     /// struct Foo {
24     ///     x: i32,
25     ///     y: i32,
26     /// }
27     /// let x = 1;
28     /// let y = 2;
29     ///
30     /// // This assertion never fails:
31     /// assert_eq!(Foo { x, y }, Foo { y, x });
32     /// ```
33     ///
34     /// inconsistent order can be confusing and decreases readability and consistency.
35     ///
36     /// ### Example
37     /// ```rust
38     /// struct Foo {
39     ///     x: i32,
40     ///     y: i32,
41     /// }
42     /// let x = 1;
43     /// let y = 2;
44     ///
45     /// Foo { y, x };
46     /// ```
47     ///
48     /// Use instead:
49     /// ```rust
50     /// # struct Foo {
51     /// #     x: i32,
52     /// #     y: i32,
53     /// # }
54     /// # let x = 1;
55     /// # let y = 2;
56     /// Foo { x, y };
57     /// ```
58     #[clippy::version = "1.52.0"]
59     pub INCONSISTENT_STRUCT_CONSTRUCTOR,
60     pedantic,
61     "the order of the field init shorthand is inconsistent with the order in the struct definition"
62 }
63
64 declare_lint_pass!(InconsistentStructConstructor => [INCONSISTENT_STRUCT_CONSTRUCTOR]);
65
66 impl LateLintPass<'_> for InconsistentStructConstructor {
67     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
68         if_chain! {
69             if !expr.span.from_expansion();
70             if let ExprKind::Struct(qpath, fields, base) = expr.kind;
71             let ty = cx.typeck_results().expr_ty(expr);
72             if let Some(adt_def) = ty.ty_adt_def();
73             if adt_def.is_struct();
74             if let Some(variant) = adt_def.variants.iter().next();
75             if fields.iter().all(|f| f.is_shorthand);
76             then {
77                 let mut def_order_map = FxHashMap::default();
78                 for (idx, field) in variant.fields.iter().enumerate() {
79                     def_order_map.insert(field.ident.name, idx);
80                 }
81
82                 if is_consistent_order(fields, &def_order_map) {
83                     return;
84                 }
85
86                 let mut ordered_fields: Vec<_> = fields.iter().map(|f| f.ident.name).collect();
87                 ordered_fields.sort_unstable_by_key(|id| def_order_map[id]);
88
89                 let mut fields_snippet = String::new();
90                 let (last_ident, idents) = ordered_fields.split_last().unwrap();
91                 for ident in idents {
92                     fields_snippet.push_str(&format!("{}, ", ident));
93                 }
94                 fields_snippet.push_str(&last_ident.to_string());
95
96                 let base_snippet = if let Some(base) = base {
97                         format!(", ..{}", snippet(cx, base.span, ".."))
98                     } else {
99                         String::new()
100                     };
101
102                 let sugg = format!("{} {{ {}{} }}",
103                     snippet(cx, qpath.span(), ".."),
104                     fields_snippet,
105                     base_snippet,
106                     );
107
108                 span_lint_and_sugg(
109                     cx,
110                     INCONSISTENT_STRUCT_CONSTRUCTOR,
111                     expr.span,
112                     "struct constructor field order is inconsistent with struct definition field order",
113                     "try",
114                     sugg,
115                     Applicability::MachineApplicable,
116                 )
117             }
118         }
119     }
120 }
121
122 // Check whether the order of the fields in the constructor is consistent with the order in the
123 // definition.
124 fn is_consistent_order<'tcx>(fields: &'tcx [hir::ExprField<'tcx>], def_order_map: &FxHashMap<Symbol, usize>) -> bool {
125     let mut cur_idx = usize::MIN;
126     for f in fields {
127         let next_idx = def_order_map[&f.ident.name];
128         if cur_idx > next_idx {
129             return false;
130         }
131         cur_idx = next_idx;
132     }
133
134     true
135 }