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 use std::fmt::Write as _;
12 declare_clippy_lint! {
14 /// Checks for struct constructors where all fields are shorthand and
15 /// the order of the field init shorthand in the constructor is inconsistent
16 /// with the order in the struct definition.
18 /// ### Why is this bad?
19 /// Since the order of fields in a constructor doesn't affect the
20 /// resulted instance as the below example indicates,
23 /// #[derive(Debug, PartialEq, Eq)]
31 /// // This assertion never fails:
32 /// assert_eq!(Foo { x, y }, Foo { y, x });
35 /// inconsistent order can be confusing and decreases readability and consistency.
59 #[clippy::version = "1.52.0"]
60 pub INCONSISTENT_STRUCT_CONSTRUCTOR,
62 "the order of the field init shorthand is inconsistent with the order in the struct definition"
65 declare_lint_pass!(InconsistentStructConstructor => [INCONSISTENT_STRUCT_CONSTRUCTOR]);
67 impl<'tcx> LateLintPass<'tcx> for InconsistentStructConstructor {
68 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
70 if !expr.span.from_expansion();
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);
78 let mut def_order_map = FxHashMap::default();
79 for (idx, field) in variant.fields.iter().enumerate() {
80 def_order_map.insert(field.name, idx);
83 if is_consistent_order(fields, &def_order_map) {
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]);
90 let mut fields_snippet = String::new();
91 let (last_ident, idents) = ordered_fields.split_last().unwrap();
93 let _ = write!(fields_snippet, "{}, ", ident);
95 fields_snippet.push_str(&last_ident.to_string());
97 let base_snippet = if let Some(base) = base {
98 format!(", ..{}", snippet(cx, base.span, ".."))
103 let sugg = format!("{} {{ {}{} }}",
104 snippet(cx, qpath.span(), ".."),
111 INCONSISTENT_STRUCT_CONSTRUCTOR,
113 "struct constructor field order is inconsistent with struct definition field order",
116 Applicability::MachineApplicable,
123 // Check whether the order of the fields in the constructor is consistent with the order in the
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;
128 let next_idx = def_order_map[&f.ident.name];
129 if cur_idx > next_idx {