Skip to content

Commit 0435463

Browse files
committed
feat(diagnostics): use Default::default() expression instead of todo! when missing fields
Signed-off-by: Benjamin Coenen <[email protected]>
1 parent 3d63abf commit 0435463

File tree

2 files changed

+20
-4
lines changed

2 files changed

+20
-4
lines changed

crates/ide_diagnostics/src/handlers/missing_fields.rs

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use either::Either;
2-
use hir::{db::AstDatabase, InFile};
3-
use ide_db::{assists::Assist, source_change::SourceChange};
2+
use hir::{db::AstDatabase, InFile, Type};
3+
use ide_db::{assists::Assist, helpers::FamousDefs, source_change::SourceChange};
44
use rustc_hash::FxHashMap;
55
use stdx::format_to;
66
use syntax::{algo, ast::make, AstNode, SyntaxNodePtr};
@@ -63,17 +63,30 @@ fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::MissingFields) -> Option<Vec<Ass
6363
}
6464
});
6565
let missing_fields = ctx.sema.record_literal_missing_fields(&field_list_parent);
66+
67+
let generate_default_expr = |ty: &Type| {
68+
let krate = ctx.sema.to_module_def(d.file.original_file(ctx.sema.db))?.krate();
69+
let default_trait = FamousDefs(&ctx.sema, Some(krate)).core_default_Default();
70+
71+
match default_trait {
72+
Some(default_trait) if ty.impls_trait(ctx.sema.db, default_trait, &[]) => {
73+
Some(make::ext::expr_default())
74+
}
75+
_ => Some(make::ext::expr_todo()),
76+
}
77+
};
78+
6679
for (f, ty) in missing_fields.iter() {
6780
let field_expr = if let Some(local_candidate) = locals.get(&f.name(ctx.sema.db)) {
6881
cov_mark::hit!(field_shorthand);
6982
let candidate_ty = local_candidate.ty(ctx.sema.db);
7083
if ty.could_unify_with(ctx.sema.db, &candidate_ty) {
7184
None
7285
} else {
73-
Some(make::ext::expr_todo())
86+
generate_default_expr(ty)
7487
}
7588
} else {
76-
Some(make::ext::expr_todo())
89+
generate_default_expr(ty)
7790
};
7891
let field =
7992
make::record_expr_field(make::name_ref(&f.name(ctx.sema.db).to_smol_str()), field_expr)

crates/syntax/src/ast/make.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,9 @@ pub mod ext {
5959
pub fn expr_todo() -> ast::Expr {
6060
expr_from_text("todo!()")
6161
}
62+
pub fn expr_default() -> ast::Expr {
63+
expr_from_text("Default::default()")
64+
}
6265
pub fn empty_block_expr() -> ast::BlockExpr {
6366
block_expr(None, None)
6467
}

0 commit comments

Comments
 (0)