3 db::{AstDatabase, HirDatabase},
4 known, AssocItem, HirDisplay, InFile, Type,
6 use ide_db::{assists::Assist, famous_defs::FamousDefs, source_change::SourceChange, FxHashMap};
11 AstNode, SyntaxNode, SyntaxNodePtr,
13 use text_edit::TextEdit;
15 use crate::{fix, Diagnostic, DiagnosticsContext};
17 // Diagnostic: missing-fields
19 // This diagnostic is triggered if record lacks some fields that exist in the corresponding structure.
24 // struct A { a: u8, b: u8 }
26 // let a = A { a: 10 };
28 pub(crate) fn missing_fields(ctx: &DiagnosticsContext<'_>, d: &hir::MissingFields) -> Diagnostic {
29 let mut message = String::from("missing structure fields:\n");
30 for field in &d.missed_fields {
31 format_to!(message, "- {}\n", field);
34 let ptr = InFile::new(
36 d.field_list_parent_path
38 .map(SyntaxNodePtr::from)
39 .unwrap_or_else(|| d.field_list_parent.clone().either(|it| it.into(), |it| it.into())),
42 Diagnostic::new("missing-fields", message, ctx.sema.diagnostics_display_range(ptr).range)
43 .with_fixes(fixes(ctx, d))
46 fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::MissingFields) -> Option<Vec<Assist>> {
47 // Note that although we could add a diagnostics to
48 // fill the missing tuple field, e.g :
50 // `let a = A { 0: () }`
51 // but it is uncommon usage and it should not be encouraged.
52 if d.missed_fields.iter().any(|it| it.as_tuple_index().is_some()) {
56 let root = ctx.sema.db.parse_or_expand(d.file)?;
58 let build_text_edit = |parent_syntax, new_syntax: &SyntaxNode, old_syntax| {
60 let mut builder = TextEdit::builder();
61 if d.file.is_macro() {
62 // we can't map the diff up into the macro input unfortunately, as the macro loses all
63 // whitespace information so the diff wouldn't be applicable no matter what
64 // This has the downside that the cursor will be moved in macros by doing it without a diff
65 // but that is a trade off we can make.
66 // FIXME: this also currently discards a lot of whitespace in the input... we really need a formatter here
67 let range = ctx.sema.original_range_opt(old_syntax)?;
68 builder.replace(range.range, new_syntax.to_string());
70 algo::diff(old_syntax, new_syntax).into_text_edit(&mut builder);
75 "fill_missing_fields",
77 SourceChange::from_text_edit(d.file.original_file(ctx.sema.db), edit),
78 ctx.sema.original_range(parent_syntax).range,
82 match &d.field_list_parent {
83 Either::Left(record_expr) => {
84 let field_list_parent = record_expr.to_node(&root);
85 let missing_fields = ctx.sema.record_literal_missing_fields(&field_list_parent);
87 let mut locals = FxHashMap::default();
88 ctx.sema.scope(field_list_parent.syntax())?.process_all_names(&mut |name, def| {
89 if let hir::ScopeDef::Local(local) = def {
90 locals.insert(name, local);
94 let generate_fill_expr = |ty: &Type| match ctx.config.expr_fill_default {
95 crate::ExprFillDefaultMode::Todo => make::ext::expr_todo(),
96 crate::ExprFillDefaultMode::Default => {
97 get_default_constructor(ctx, d, ty).unwrap_or_else(|| make::ext::expr_todo())
101 let old_field_list = field_list_parent.record_expr_field_list()?;
102 let new_field_list = old_field_list.clone_for_update();
103 for (f, ty) in missing_fields.iter() {
104 let field_expr = if let Some(local_candidate) = locals.get(&f.name(ctx.sema.db)) {
105 cov_mark::hit!(field_shorthand);
106 let candidate_ty = local_candidate.ty(ctx.sema.db);
107 if ty.could_unify_with(ctx.sema.db, &candidate_ty) {
110 Some(generate_fill_expr(ty))
113 Some(generate_fill_expr(ty))
115 let field = make::record_expr_field(
116 make::name_ref(&f.name(ctx.sema.db).to_smol_str()),
119 new_field_list.add_field(field.clone_for_update());
122 field_list_parent.syntax(),
123 new_field_list.syntax(),
124 old_field_list.syntax(),
127 Either::Right(record_pat) => {
128 let field_list_parent = record_pat.to_node(&root);
129 let missing_fields = ctx.sema.record_pattern_missing_fields(&field_list_parent);
131 let old_field_list = field_list_parent.record_pat_field_list()?;
132 let new_field_list = old_field_list.clone_for_update();
133 for (f, _) in missing_fields.iter() {
134 let field = make::record_pat_field_shorthand(make::name_ref(
135 &f.name(ctx.sema.db).to_smol_str(),
137 new_field_list.add_field(field.clone_for_update());
140 field_list_parent.syntax(),
141 new_field_list.syntax(),
142 old_field_list.syntax(),
148 fn make_ty(ty: &hir::Type, db: &dyn HirDatabase, module: hir::Module) -> ast::Type {
149 let ty_str = match ty.as_adt() {
150 Some(adt) => adt.name(db).to_string(),
151 None => ty.display_source_code(db, module.into()).ok().unwrap_or_else(|| "_".to_string()),
157 fn get_default_constructor(
158 ctx: &DiagnosticsContext<'_>,
159 d: &hir::MissingFields,
161 ) -> Option<ast::Expr> {
162 if let Some(builtin_ty) = ty.as_builtin() {
163 if builtin_ty.is_int() || builtin_ty.is_uint() {
164 return Some(make::ext::zero_number());
166 if builtin_ty.is_float() {
167 return Some(make::ext::zero_float());
169 if builtin_ty.is_char() {
170 return Some(make::ext::empty_char());
172 if builtin_ty.is_str() {
173 return Some(make::ext::empty_str());
175 if builtin_ty.is_bool() {
176 return Some(make::ext::default_bool());
180 let krate = ctx.sema.to_module_def(d.file.original_file(ctx.sema.db))?.krate();
181 let module = krate.root_module(ctx.sema.db);
183 // Look for a ::new() associated function
184 let has_new_func = ty
185 .iterate_assoc_items(ctx.sema.db, krate, |assoc_item| {
186 if let AssocItem::Function(func) = assoc_item {
187 if func.name(ctx.sema.db) == known::new
188 && func.assoc_fn_params(ctx.sema.db).is_empty()
198 let famous_defs = FamousDefs(&ctx.sema, krate);
200 Some(make::ext::expr_ty_new(&make_ty(ty, ctx.sema.db, module)))
201 } else if ty.as_adt() == famous_defs.core_option_Option()?.ty(ctx.sema.db).as_adt() {
202 Some(make::ext::option_none())
203 } else if !ty.is_array()
204 && ty.impls_trait(ctx.sema.db, famous_defs.core_default_Default()?, &[])
206 Some(make::ext::expr_ty_default(&make_ty(ty, ctx.sema.db, module)))
214 use crate::tests::{check_diagnostics, check_fix};
217 fn missing_record_pat_field_diagnostic() {
220 struct S { foo: i32, bar: () }
222 let S { foo: _ } = s;
223 //^ 💡 error: missing structure fields:
231 fn missing_record_pat_field_no_diagnostic_if_not_exhaustive() {
234 struct S { foo: i32, bar: () }
235 fn baz(s: S) -> i32 {
237 S { foo, .. } => foo,
245 fn missing_record_pat_field_box() {
248 struct S { s: Box<u32> }
257 fn missing_record_pat_field_ref() {
269 fn range_mapping_out_of_macros() {
276 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
279 let _x = id![Foo { a: $042 }];
282 pub struct Foo { pub a: i32, pub b: i32 }
289 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
292 let _x = id![Foo {a:42, b: 0 }];
295 pub struct Foo { pub a: i32, pub b: i32 }
301 fn test_fill_struct_fields_empty() {
305 struct TestStruct { one: i32, two: i64, three: Option<i32>, four: bool }
308 let s = TestStruct {$0};
312 struct TestStruct { one: i32, two: i64, three: Option<i32>, four: bool }
315 let s = TestStruct { one: 0, two: 0, three: None, four: false };
322 fn test_fill_struct_fields_self() {
325 struct TestStruct { one: i32 }
328 fn test_fn() { let s = Self {$0}; }
332 struct TestStruct { one: i32 }
335 fn test_fn() { let s = Self { one: 0 }; }
342 fn test_fill_struct_fields_enum() {
346 Bin { lhs: Box<Expr>, rhs: Box<Expr> }
350 fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
357 Bin { lhs: Box<Expr>, rhs: Box<Expr> }
361 fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
362 Expr::Bin { lhs, rhs }
370 fn test_fill_struct_fields_partial() {
373 struct TestStruct { one: i32, two: i64 }
376 let s = TestStruct{ two: 2$0 };
380 struct TestStruct { one: i32, two: i64 }
383 let s = TestStruct{ two: 2, one: 0 };
390 fn test_fill_struct_fields_new() {
393 struct TestWithNew(usize);
395 pub fn new() -> Self {
399 struct TestStruct { one: i32, two: TestWithNew }
402 let s = TestStruct{ $0 };
406 struct TestWithNew(usize);
408 pub fn new() -> Self {
412 struct TestStruct { one: i32, two: TestWithNew }
415 let s = TestStruct{ one: 0, two: TestWithNew::new() };
422 fn test_fill_struct_fields_default() {
425 //- minicore: default, option
426 struct TestWithDefault(usize);
427 impl Default for TestWithDefault {
428 pub fn default() -> Self {
432 struct TestStruct { one: i32, two: TestWithDefault }
435 let s = TestStruct{ $0 };
439 struct TestWithDefault(usize);
440 impl Default for TestWithDefault {
441 pub fn default() -> Self {
445 struct TestStruct { one: i32, two: TestWithDefault }
448 let s = TestStruct{ one: 0, two: TestWithDefault::default() };
455 fn test_fill_struct_fields_raw_ident() {
458 struct TestStruct { r#type: u8 }
465 struct TestStruct { r#type: u8 }
468 TestStruct { r#type: 0 };
475 fn test_fill_struct_fields_no_diagnostic() {
478 struct TestStruct { one: i32, two: i64 }
482 let s = TestStruct{ one, two: 2 };
489 fn test_fill_struct_fields_no_diagnostic_on_spread() {
492 struct TestStruct { one: i32, two: i64 }
496 let s = TestStruct{ ..a };
503 fn test_fill_struct_fields_blank_line() {
506 struct S { a: (), b: () }
515 struct S { a: (), b: () }
528 fn test_fill_struct_fields_shorthand() {
529 cov_mark::check!(field_shorthand);
532 struct S { a: &'static str, b: i32 }
543 struct S { a: &'static str, b: i32 }
558 fn test_fill_struct_fields_shorthand_ty_mismatch() {
561 struct S { a: &'static str, b: i32 }
572 struct S { a: &'static str, b: i32 }
587 fn test_fill_struct_fields_shorthand_unifies() {
590 struct S<T> { a: &'static str, b: T }
601 struct S<T> { a: &'static str, b: T }
616 fn test_fill_struct_pat_fields() {
619 struct S { a: &'static str, b: i32 }
628 struct S { a: &'static str, b: i32 }
641 fn test_fill_struct_pat_fields_partial() {
644 struct S { a: &'static str, b: i32 }
653 struct S { a: &'static str, b: i32 }
666 fn import_extern_crate_clash_with_inner_item() {
667 // This is more of a resolver test, but doesn't really work with the hir_def testsuite.
671 //- /lib.rs crate:lib deps:jwt
674 use permissions::jwt;
678 jwt::Claims {}; // should resolve to the local one with 0 fields, and not get a diagnostic
686 //- /jwt/lib.rs crate:jwt