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