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;
8 use if_chain::if_chain;
10 use crate::utils::{snippet, span_lint_and_sugg};
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.
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,
20 /// #[derive(Debug, PartialEq, Eq)]
28 /// // This assertion never fails.
29 /// assert_eq!(Foo { x, y }, Foo { y, x });
32 /// inconsistent order means nothing and just decreases readability and consistency.
34 /// **Known problems:** None.
58 pub INCONSISTENT_STRUCT_CONSTRUCTOR,
60 "the order of the field init shorthand is inconsistent with the order in the struct definition"
63 declare_lint_pass!(InconsistentStructConstructor => [INCONSISTENT_STRUCT_CONSTRUCTOR]);
65 impl LateLintPass<'_> for InconsistentStructConstructor {
66 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
68 if let ExprKind::Struct(qpath, fields, base) = expr.kind;
69 if let Some(def_id) = cx.qpath_res(qpath, expr.hir_id).opt_def_id();
70 let ty = cx.tcx.type_of(def_id);
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);
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);
81 if is_consistent_order(fields, &def_order_map) {
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]);
88 let mut fields_snippet = String::new();
89 let (last_ident, idents) = ordered_fields.split_last().unwrap();
91 fields_snippet.push_str(&format!("{}, ", ident));
93 fields_snippet.push_str(&last_ident.to_string());
95 let base_snippet = if let Some(base) = base {
96 format!(", ..{}", snippet(cx, base.span, ".."))
101 let sugg = format!("{} {{ {}{} }}",
102 snippet(cx, qpath.span(), ".."),
109 INCONSISTENT_STRUCT_CONSTRUCTOR,
111 "inconsistent struct constructor",
114 Applicability::MachineApplicable,
121 // Check whether the order of the fields in the constructor is consistent with the order in the
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;
126 let next_idx = def_order_map[&f.ident.name];
127 if cur_idx > next_idx {