Skip to content

Commit a8968e5

Browse files
authored
Make inconsistent_struct_constructor "all fields are shorthand" requirement configurable (#13737)
Fixes#11846. This PR has three commits: - The first commit adds an `initializer-suggestions` configuration to control suggestion applicability when initializers are present. The following are the options: - "none": do not suggest - "maybe-incorrect": suggest, but do not apply suggestions with `--fix` - "machine-applicable": suggest and apply suggestions with `--fix` - The second commit fixes suggestions to handle field attributes (problem [noticed by @samueltardieu](rust-lang/rust-clippy#13737 (comment))). - The third commit adds `initializer-suggestions = "machine-applicable"` to Clippy's `clippy.toml` and applies the suggestions. (Nothing seems to break.) --- changelog: make `inconsistent_struct_constructor` "all fields are shorthand" requirement configurable
2 parents 363e61d + 8a38bcc commit a8968e5

41 files changed

Lines changed: 450 additions & 97 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6252,6 +6252,7 @@ Released 2018-09-13
62526252
[`future-size-threshold`]: https://doc.rust-lang.org/clippy/lint_configuration.html#future-size-threshold
62536253
[`ignore-interior-mutability`]: https://doc.rust-lang.org/clippy/lint_configuration.html#ignore-interior-mutability
62546254
[`large-error-threshold`]: https://doc.rust-lang.org/clippy/lint_configuration.html#large-error-threshold
6255+
[`lint-inconsistent-struct-field-initializers`]: https://doc.rust-lang.org/clippy/lint_configuration.html#lint-inconsistent-struct-field-initializers
62556256
[`literal-representation-threshold`]: https://doc.rust-lang.org/clippy/lint_configuration.html#literal-representation-threshold
62566257
[`matches-for-let-else`]: https://doc.rust-lang.org/clippy/lint_configuration.html#matches-for-let-else
62576258
[`max-fn-params-bools`]: https://doc.rust-lang.org/clippy/lint_configuration.html#max-fn-params-bools

‎book/src/lint_configuration.md‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -582,6 +582,33 @@ The maximum size of the `Err`-variant in a `Result` returned from a function
582582
*[`result_large_err`](https://rust-lang.github.io/rust-clippy/master/index.html#result_large_err)
583583

584584

585+
## `lint-inconsistent-struct-field-initializers`
586+
Whether to suggest reordering constructor fields when initializers are present.
587+
588+
Warnings produced by this configuration aren't necessarily fixed by just reordering the fields. Even if the
589+
suggested code would compile, it can change semantics if the initializer expressions have side effects. The
590+
following example [from rust-clippy#11846] shows how the suggestion can run into borrow check errors:
591+
592+
```rust
593+
structMyStruct {
594+
vector:Vec<u32>,
595+
length:usize
596+
}
597+
fnmain() {
598+
letvector=vec![1,2,3];
599+
MyStruct { length:vector.len(), vector};
600+
}
601+
```
602+
603+
[from rust-clippy#11846]: https://github.com/rust-lang/rust-clippy/issues/11846#issuecomment-1820747924
604+
605+
**Default Value:**`false`
606+
607+
---
608+
**Affected lints:**
609+
*[`inconsistent_struct_constructor`](https://rust-lang.github.io/rust-clippy/master/index.html#inconsistent_struct_constructor)
610+
611+
585612
## `literal-representation-threshold`
586613
The lower bound for linting decimal literals
587614

‎clippy.toml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
avoid-breaking-exported-api = false
22

3+
lint-inconsistent-struct-field-initializers = true
4+
35
[[disallowed-methods]]
46
path = "rustc_lint::context::LintContext::lint"
57
reason = "this function does not add a link to our documentation, please use the `clippy_utils::diagnostics::span_lint*` functions instead"

‎clippy_config/src/conf.rs‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -532,6 +532,26 @@ define_Conf! {
532532
/// The maximum size of the `Err`-variant in a `Result` returned from a function
533533
#[lints(result_large_err)]
534534
large_error_threshold:u64 = 128,
535+
/// Whether to suggest reordering constructor fields when initializers are present.
536+
///
537+
/// Warnings produced by this configuration aren't necessarily fixed by just reordering the fields. Even if the
538+
/// suggested code would compile, it can change semantics if the initializer expressions have side effects. The
539+
/// following example [from rust-clippy#11846] shows how the suggestion can run into borrow check errors:
540+
///
541+
/// ```rust
542+
/// struct MyStruct {
543+
/// vector: Vec<u32>,
544+
/// length: usize
545+
/// }
546+
/// fn main() {
547+
/// let vector = vec![1,2,3];
548+
/// MyStruct { length: vector.len(), vector};
549+
/// }
550+
/// ```
551+
///
552+
/// [from rust-clippy#11846]: https://github.com/rust-lang/rust-clippy/issues/11846#issuecomment-1820747924
553+
#[lints(inconsistent_struct_constructor)]
554+
lint_inconsistent_struct_field_initializers:bool = false,
535555
/// The lower bound for linting decimal literals
536556
#[lints(decimal_literal_representation)]
537557
literal_representation_threshold:u64 = 16384,

‎clippy_dev/src/fmt.rs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -179,8 +179,8 @@ fn fmt_conf(check: bool) -> Result<(), Error> {
179179
#[expect(clippy::drain_collect)]
180180
fields.push(ClippyConf{
181181
name,
182-
lints: lints.drain(..).collect(),
183182
attrs:&conf[attrs_start..attrs_end],
183+
lints: lints.drain(..).collect(),
184184
field: conf[field_start..i].trim_end(),
185185
});
186186
attrs_start = i;
@@ -191,8 +191,8 @@ fn fmt_conf(check: bool) -> Result<(), Error> {
191191
#[expect(clippy::drain_collect)]
192192
fields.push(ClippyConf{
193193
name,
194-
lints: lints.drain(..).collect(),
195194
attrs:&conf[attrs_start..attrs_end],
195+
lints: lints.drain(..).collect(),
196196
field: conf[field_start..i].trim_end(),
197197
});
198198
attrs_start = i;
@@ -220,8 +220,8 @@ fn fmt_conf(check: bool) -> Result<(), Error> {
220220
}
221221
fields.push(ClippyConf{
222222
name,
223-
lints,
224223
attrs:&conf[attrs_start..attrs_end],
224+
lints,
225225
field: conf[field_start..].trim_end(),
226226
});
227227

‎clippy_lints/src/arbitrary_source_item_ordering.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -428,8 +428,8 @@ impl<'tcx> LateLintPass<'tcx> for ArbitrarySourceItemOrdering {
428428

429429
// Makes a note of the current item for comparison with the next.
430430
cur_t = Some(CurItem{
431-
order: module_level_order,
432431
item,
432+
order: module_level_order,
433433
name:get_item_name(item),
434434
});
435435
}

‎clippy_lints/src/doc/mod.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -797,8 +797,8 @@ fn check_attrs(cx: &LateContext<'_>, valid_idents: &FxHashSet<String>, attrs: &[
797797
parser.into_offset_iter(),
798798
&doc,
799799
Fragments{
800-
fragments:&fragments,
801800
doc:&doc,
801+
fragments:&fragments,
802802
},
803803
))
804804
}

‎clippy_lints/src/entry.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -678,12 +678,12 @@ fn find_insert_calls<'tcx>(
678678
map: contains_expr.map,
679679
key: contains_expr.key,
680680
ctxt: expr.span.ctxt(),
681-
edits:Vec::new(),
682-
is_map_used:false,
683681
allow_insert_closure:true,
684682
can_use_entry:true,
685683
in_tail_pos:true,
686684
is_single_insert:true,
685+
is_map_used:false,
686+
edits:Vec::new(),
687687
loops:Vec::new(),
688688
locals:HirIdSet::default(),
689689
};

‎clippy_lints/src/implied_bounds_in_impls.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -243,11 +243,11 @@ fn collect_supertrait_bounds<'tcx>(cx: &LateContext<'tcx>, bounds: GenericBounds
243243
&& !predicates.is_empty()
244244
{
245245
Some(ImplTraitBound{
246+
span: bound.span(),
246247
predicates,
248+
trait_def_id,
247249
args: path.args.map_or([].as_slice(), |p| p.args),
248250
constraints: path.args.map_or([].as_slice(), |p| p.constraints),
249-
trait_def_id,
250-
span: bound.span(),
251251
})
252252
}else{
253253
None

‎clippy_lints/src/inconsistent_struct_constructor.rs‎

Lines changed: 90 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,21 @@
1-
use clippy_utils::diagnostics::span_lint_and_sugg;
1+
use clippy_config::Conf;
2+
use clippy_utils::diagnostics::span_lint_and_then;
23
use clippy_utils::fulfill_or_allowed;
34
use clippy_utils::source::snippet;
45
use rustc_data_structures::fx::FxHashMap;
56
use rustc_errors::Applicability;
6-
use rustc_hir::{selfas hir,ExprKind,StructTailExpr};
7+
use rustc_hir::{selfas hir,ExprKind};
78
use rustc_lint::{LateContext,LateLintPass};
8-
use rustc_session::declare_lint_pass;
9+
use rustc_middle::ty::TyCtxt;
10+
use rustc_session::impl_lint_pass;
11+
use rustc_span::Span;
912
use rustc_span::symbol::Symbol;
10-
use std::fmt::{self,Writeas _};
1113

1214
declare_clippy_lint!{
1315
/// ### What it does
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.
16+
/// Checks for struct constructors where the order of the field
17+
/// init in the constructor is inconsistent with the order in the
18+
/// struct definition.
1719
///
1820
/// ### Why is this bad?
1921
/// Since the order of fields in a constructor doesn't affect the
@@ -59,16 +61,37 @@ declare_clippy_lint! {
5961
#[clippy::version = "1.52.0"]
6062
pubINCONSISTENT_STRUCT_CONSTRUCTOR,
6163
pedantic,
62-
"the order of the field init shorthand is inconsistent with the order in the struct definition"
64+
"the order of the field init is inconsistent with the order in the struct definition"
6365
}
6466

65-
declare_lint_pass!(InconsistentStructConstructor => [INCONSISTENT_STRUCT_CONSTRUCTOR]);
67+
pubstructInconsistentStructConstructor{
68+
lint_inconsistent_struct_field_initializers:bool,
69+
}
70+
71+
implInconsistentStructConstructor{
72+
pubfnnew(conf:&'staticConf) -> Self{
73+
Self{
74+
lint_inconsistent_struct_field_initializers: conf.lint_inconsistent_struct_field_initializers,
75+
}
76+
}
77+
}
78+
79+
impl_lint_pass!(InconsistentStructConstructor => [INCONSISTENT_STRUCT_CONSTRUCTOR]);
6680

6781
impl<'tcx>LateLintPass<'tcx>forInconsistentStructConstructor{
6882
fncheck_expr(&mutself,cx:&LateContext<'tcx>,expr:&'tcx hir::Expr<'_>){
69-
ifletExprKind::Struct(qpath, fields, base) = expr.kind
70-
&& fields.iter().all(|f| f.is_shorthand)
71-
&& !expr.span.from_expansion()
83+
letExprKind::Struct(_, fields, _) = expr.kindelse{
84+
return;
85+
};
86+
let all_fields_are_shorthand = fields.iter().all(|f| f.is_shorthand);
87+
let applicability = if all_fields_are_shorthand {
88+
Applicability::MachineApplicable
89+
}elseifself.lint_inconsistent_struct_field_initializers{
90+
Applicability::MaybeIncorrect
91+
}else{
92+
return;
93+
};
94+
if !expr.span.from_expansion()
7295
&& let ty = cx.typeck_results().expr_ty(expr)
7396
&& letSome(adt_def) = ty.ty_adt_def()
7497
&& adt_def.is_struct()
@@ -85,36 +108,24 @@ impl<'tcx> LateLintPass<'tcx> for InconsistentStructConstructor {
85108
return;
86109
}
87110

88-
letmut ordered_fields:Vec<_> = fields.iter().map(|f| f.ident.name).collect();
89-
ordered_fields.sort_unstable_by_key(|id| def_order_map[id]);
90-
91-
letmut fields_snippet = String::new();
92-
let(last_ident, idents) = ordered_fields.split_last().unwrap();
93-
for ident in idents {
94-
let _: fmt::Result = write!(fields_snippet,"{ident}, ");
95-
}
96-
fields_snippet.push_str(&last_ident.to_string());
97-
98-
let base_snippet = ifletStructTailExpr::Base(base) = base {
99-
format!(", ..{}", snippet(cx, base.span,".."))
100-
}else{
101-
String::new()
102-
};
103-
104-
let sugg = format!(
105-
"{} {{ {fields_snippet}{base_snippet} }}",
106-
snippet(cx, qpath.span(),".."),
107-
);
111+
let span = field_with_attrs_span(cx.tcx, fields.first().unwrap())
112+
.with_hi(field_with_attrs_span(cx.tcx, fields.last().unwrap()).hi());
108113

109114
if !fulfill_or_allowed(cx,INCONSISTENT_STRUCT_CONSTRUCTOR,Some(ty_hir_id)){
110-
span_lint_and_sugg(
115+
span_lint_and_then(
111116
cx,
112117
INCONSISTENT_STRUCT_CONSTRUCTOR,
113-
expr.span,
118+
span,
114119
"struct constructor field order is inconsistent with struct definition field order",
115-
"try",
116-
sugg,
117-
Applicability::MachineApplicable,
120+
|diag| {
121+
let msg = if all_fields_are_shorthand {
122+
"try"
123+
}else{
124+
"if the field evaluation order doesn't matter, try"
125+
};
126+
let sugg = suggestion(cx, fields,&def_order_map);
127+
diag.span_suggestion(span, msg, sugg, applicability);
128+
},
118129
);
119130
}
120131
}
@@ -135,3 +146,45 @@ fn is_consistent_order<'tcx>(fields: &'tcx [hir::ExprField<'tcx>], def_order_map
135146

136147
true
137148
}
149+
150+
fnsuggestion<'tcx>(
151+
cx:&LateContext<'_>,
152+
fields:&'tcx[hir::ExprField<'tcx>],
153+
def_order_map:&FxHashMap<Symbol,usize>,
154+
) -> String{
155+
let ws = fields
156+
.windows(2)
157+
.map(|w| {
158+
let w0_span = field_with_attrs_span(cx.tcx,&w[0]);
159+
let w1_span = field_with_attrs_span(cx.tcx,&w[1]);
160+
let span = w0_span.between(w1_span);
161+
snippet(cx, span," ")
162+
})
163+
.collect::<Vec<_>>();
164+
165+
letmut fields = fields.to_vec();
166+
fields.sort_unstable_by_key(|field| def_order_map[&field.ident.name]);
167+
let field_snippets = fields
168+
.iter()
169+
.map(|field| snippet(cx,field_with_attrs_span(cx.tcx, field),".."))
170+
.collect::<Vec<_>>();
171+
172+
assert_eq!(field_snippets.len(), ws.len() + 1);
173+
174+
letmut sugg = String::new();
175+
for i in0..field_snippets.len(){
176+
sugg += &field_snippets[i];
177+
if i < ws.len(){
178+
sugg += &ws[i];
179+
}
180+
}
181+
sugg
182+
}
183+
184+
fnfield_with_attrs_span(tcx:TyCtxt<'_>,field:&hir::ExprField<'_>) -> Span{
185+
ifletSome(attr) = tcx.hir().attrs(field.hir_id).first(){
186+
field.span.with_lo(attr.span.lo())
187+
}else{
188+
field.span
189+
}
190+
}

0 commit comments

Comments
 (0)