]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/inconsistent_struct_constructor.rs
Auto merge of #6924 - mgacek8:issue6727_copy_types, r=llogiq
[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:** Checks for struct constructors where all fields are shorthand and
13     /// the order of the field init shorthand in the constructor is inconsistent
14     /// 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 can be confusing and 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     ///
46     /// Foo { y, x };
47     /// ```
48     ///
49     /// Use instead:
50     /// ```rust
51     /// # struct Foo {
52     /// #     x: i32,
53     /// #     y: i32,
54     /// # }
55     /// # let x = 1;
56     /// # let y = 2;
57     /// Foo { x, y };
58     /// ```
59     pub INCONSISTENT_STRUCT_CONSTRUCTOR,
60     style,
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 let ExprKind::Struct(qpath, fields, base) = expr.kind;
70             let ty = cx.typeck_results().expr_ty(expr);
71             if let Some(adt_def) = ty.ty_adt_def();
72             if adt_def.is_struct();
73             if let Some(variant) = adt_def.variants.iter().next();
74             if fields.iter().all(|f| f.is_shorthand);
75             then {
76                 let mut def_order_map = FxHashMap::default();
77                 for (idx, field) in variant.fields.iter().enumerate() {
78                     def_order_map.insert(field.ident.name, idx);
79                 }
80
81                 if is_consistent_order(fields, &def_order_map) {
82                     return;
83                 }
84
85                 let mut ordered_fields: Vec<_> = fields.iter().map(|f| f.ident.name).collect();
86                 ordered_fields.sort_unstable_by_key(|id| def_order_map[id]);
87
88                 let mut fields_snippet = String::new();
89                 let (last_ident, idents) = ordered_fields.split_last().unwrap();
90                 for ident in idents {
91                     fields_snippet.push_str(&format!("{}, ", ident));
92                 }
93                 fields_snippet.push_str(&last_ident.to_string());
94
95                 let base_snippet = if let Some(base) = base {
96                         format!(", ..{}", snippet(cx, base.span, ".."))
97                     } else {
98                         String::new()
99                     };
100
101                 let sugg = format!("{} {{ {}{} }}",
102                     snippet(cx, qpath.span(), ".."),
103                     fields_snippet,
104                     base_snippet,
105                     );
106
107                 span_lint_and_sugg(
108                     cx,
109                     INCONSISTENT_STRUCT_CONSTRUCTOR,
110                     expr.span,
111                     "struct constructor field order is inconsistent with struct definition field order",
112                     "try",
113                     sugg,
114                     Applicability::MachineApplicable,
115                 )
116             }
117         }
118     }
119 }
120
121 // Check whether the order of the fields in the constructor is consistent with the order in the
122 // definition.
123 fn is_consistent_order<'tcx>(fields: &'tcx [hir::Field<'tcx>], def_order_map: &FxHashMap<Symbol, usize>) -> bool {
124     let mut cur_idx = usize::MIN;
125     for f in fields {
126         let next_idx = def_order_map[&f.ident.name];
127         if cur_idx > next_idx {
128             return false;
129         }
130         cur_idx = next_idx;
131     }
132
133     true
134 }