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