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());
177 let krate = ctx.sema.to_module_def(d.file.original_file(ctx.sema.db))?.krate();
178 let module = krate.root_module(ctx.sema.db);
180 // Look for a ::new() associated function
181 let has_new_func = ty
182 .iterate_assoc_items(ctx.sema.db, krate, |assoc_item| {
183 if let AssocItem::Function(func) = assoc_item {
184 if func.name(ctx.sema.db) == known::new
185 && func.assoc_fn_params(ctx.sema.db).is_empty()
196 Some(make::ext::expr_ty_new(&make_ty(ty, ctx.sema.db, module)))
197 } else if !ty.is_array()
198 && ty.impls_trait(ctx.sema.db, FamousDefs(&ctx.sema, krate).core_default_Default()?, &[])
200 Some(make::ext::expr_ty_default(&make_ty(ty, ctx.sema.db, module)))
208 use crate::tests::{check_diagnostics, check_fix};
211 fn missing_record_pat_field_diagnostic() {
214 struct S { foo: i32, bar: () }
216 let S { foo: _ } = s;
217 //^ 💡 error: missing structure fields:
225 fn missing_record_pat_field_no_diagnostic_if_not_exhaustive() {
228 struct S { foo: i32, bar: () }
229 fn baz(s: S) -> i32 {
231 S { foo, .. } => foo,
239 fn missing_record_pat_field_box() {
242 struct S { s: Box<u32> }
251 fn missing_record_pat_field_ref() {
263 fn range_mapping_out_of_macros() {
270 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
273 let _x = id![Foo { a: $042 }];
276 pub struct Foo { pub a: i32, pub b: i32 }
283 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
286 let _x = id![Foo {a:42, b: 0 }];
289 pub struct Foo { pub a: i32, pub b: i32 }
295 fn test_fill_struct_fields_empty() {
298 struct TestStruct { one: i32, two: i64 }
301 let s = TestStruct {$0};
305 struct TestStruct { one: i32, two: i64 }
308 let s = TestStruct { one: 0, two: 0 };
315 fn test_fill_struct_fields_self() {
318 struct TestStruct { one: i32 }
321 fn test_fn() { let s = Self {$0}; }
325 struct TestStruct { one: i32 }
328 fn test_fn() { let s = Self { one: 0 }; }
335 fn test_fill_struct_fields_enum() {
339 Bin { lhs: Box<Expr>, rhs: Box<Expr> }
343 fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
350 Bin { lhs: Box<Expr>, rhs: Box<Expr> }
354 fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
355 Expr::Bin { lhs, rhs }
363 fn test_fill_struct_fields_partial() {
366 struct TestStruct { one: i32, two: i64 }
369 let s = TestStruct{ two: 2$0 };
373 struct TestStruct { one: i32, two: i64 }
376 let s = TestStruct{ two: 2, one: 0 };
383 fn test_fill_struct_fields_new() {
386 struct TestWithNew(usize);
388 pub fn new() -> Self {
392 struct TestStruct { one: i32, two: TestWithNew }
395 let s = TestStruct{ $0 };
399 struct TestWithNew(usize);
401 pub fn new() -> Self {
405 struct TestStruct { one: i32, two: TestWithNew }
408 let s = TestStruct{ one: 0, two: TestWithNew::new() };
415 fn test_fill_struct_fields_default() {
418 //- minicore: default
419 struct TestWithDefault(usize);
420 impl Default for TestWithDefault {
421 pub fn default() -> Self {
425 struct TestStruct { one: i32, two: TestWithDefault }
428 let s = TestStruct{ $0 };
432 struct TestWithDefault(usize);
433 impl Default for TestWithDefault {
434 pub fn default() -> Self {
438 struct TestStruct { one: i32, two: TestWithDefault }
441 let s = TestStruct{ one: 0, two: TestWithDefault::default() };
448 fn test_fill_struct_fields_raw_ident() {
451 struct TestStruct { r#type: u8 }
458 struct TestStruct { r#type: u8 }
461 TestStruct { r#type: 0 };
468 fn test_fill_struct_fields_no_diagnostic() {
471 struct TestStruct { one: i32, two: i64 }
475 let s = TestStruct{ one, two: 2 };
482 fn test_fill_struct_fields_no_diagnostic_on_spread() {
485 struct TestStruct { one: i32, two: i64 }
489 let s = TestStruct{ ..a };
496 fn test_fill_struct_fields_blank_line() {
499 struct S { a: (), b: () }
508 struct S { a: (), b: () }
521 fn test_fill_struct_fields_shorthand() {
522 cov_mark::check!(field_shorthand);
525 struct S { a: &'static str, b: i32 }
536 struct S { a: &'static str, b: i32 }
551 fn test_fill_struct_fields_shorthand_ty_mismatch() {
554 struct S { a: &'static str, b: i32 }
565 struct S { a: &'static str, b: i32 }
580 fn test_fill_struct_fields_shorthand_unifies() {
583 struct S<T> { a: &'static str, b: T }
594 struct S<T> { a: &'static str, b: T }
609 fn test_fill_struct_pat_fields() {
612 struct S { a: &'static str, b: i32 }
621 struct S { a: &'static str, b: i32 }
634 fn test_fill_struct_pat_fields_partial() {
637 struct S { a: &'static str, b: i32 }
646 struct S { a: &'static str, b: i32 }
659 fn import_extern_crate_clash_with_inner_item() {
660 // This is more of a resolver test, but doesn't really work with the hir_def testsuite.
664 //- /lib.rs crate:lib deps:jwt
667 use permissions::jwt;
671 jwt::Claims {}; // should resolve to the local one with 0 fields, and not get a diagnostic
679 //- /jwt/lib.rs crate:jwt