Skip to content

Commit dcd4157

Browse files
committed
Use struct init shorthand in fill struct fields assist
1 parent 97409e5 commit dcd4157

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

crates/ide_diagnostics/src/handlers/missing_fields.rs

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use either::Either;
22
use hir::{db::AstDatabase, InFile};
33
use ide_db::{assists::Assist, source_change::SourceChange};
4+
use rustc_hash::FxHashMap;
45
use stdx::format_to;
56
use syntax::{algo, ast::make, AstNode, SyntaxNodePtr};
67
use text_edit::TextEdit;
@@ -54,9 +55,26 @@ fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::MissingFields) -> Option<Vec<Ass
5455
};
5556
let old_field_list = field_list_parent.record_expr_field_list()?;
5657
let new_field_list = old_field_list.clone_for_update();
57-
for f in d.missed_fields.iter() {
58+
let mut locals = FxHashMap::default();
59+
ctx.sema.scope(field_list_parent.syntax()).process_all_names(&mut |name, def| {
60+
if let hir::ScopeDef::Local(local) = def {
61+
locals.insert(name.clone(), local);
62+
}
63+
});
64+
let missing_fields = ctx.sema.record_literal_missing_fields(&field_list_parent);
65+
for (f, ty) in missing_fields.iter() {
66+
let field_expr = if let Some(local_candidate) = locals.get(&f.name(ctx.sema.db)) {
67+
let candidate_ty = local_candidate.ty(ctx.sema.db);
68+
if ty.could_unify_with(ctx.sema.db, &candidate_ty) {
69+
None
70+
} else {
71+
Some(make::expr_unit())
72+
}
73+
} else {
74+
Some(make::expr_unit())
75+
};
5876
let field =
59-
make::record_expr_field(make::name_ref(&f.to_string()), Some(make::expr_unit()))
77+
make::record_expr_field(make::name_ref(&f.name(ctx.sema.db).to_string()), field_expr)
6078
.clone_for_update();
6179
new_field_list.add_field(field);
6280
}

0 commit comments

Comments
 (0)