3 db::{AstDatabase, HirDatabase},
4 known, AssocItem, HirDisplay, InFile, Type,
6 use ide_db::{assists::Assist, famous_defs::FamousDefs, source_change::SourceChange};
7 use rustc_hash::FxHashMap;
12 AstNode, SyntaxNodePtr,
14 use text_edit::TextEdit;
16 use crate::{fix, Diagnostic, DiagnosticsContext};
18 // Diagnostic: missing-fields
20 // This diagnostic is triggered if record lacks some fields that exist in the corresponding structure.
25 // struct A { a: u8, b: u8 }
27 // let a = A { a: 10 };
29 pub(crate) fn missing_fields(ctx: &DiagnosticsContext<'_>, d: &hir::MissingFields) -> Diagnostic {
30 let mut message = String::from("missing structure fields:\n");
31 for field in &d.missed_fields {
32 format_to!(message, "- {}\n", field);
35 let ptr = InFile::new(
37 d.field_list_parent_path
39 .map(SyntaxNodePtr::from)
40 .unwrap_or_else(|| d.field_list_parent.clone().either(|it| it.into(), |it| it.into())),
43 Diagnostic::new("missing-fields", message, ctx.sema.diagnostics_display_range(ptr).range)
44 .with_fixes(fixes(ctx, d))
47 fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::MissingFields) -> Option<Vec<Assist>> {
48 // Note that although we could add a diagnostics to
49 // fill the missing tuple field, e.g :
51 // `let a = A { 0: () }`
52 // but it is uncommon usage and it should not be encouraged.
53 if d.missed_fields.iter().any(|it| it.as_tuple_index().is_some()) {
57 let root = ctx.sema.db.parse_or_expand(d.file)?;
58 let field_list_parent = match &d.field_list_parent {
59 Either::Left(record_expr) => record_expr.to_node(&root),
60 // FIXE: patterns should be fixable as well.
61 Either::Right(_) => return None,
63 let old_field_list = field_list_parent.record_expr_field_list()?;
65 let new_field_list = old_field_list.clone_for_update();
66 let mut locals = FxHashMap::default();
67 ctx.sema.scope(field_list_parent.syntax())?.process_all_names(&mut |name, def| {
68 if let hir::ScopeDef::Local(local) = def {
69 locals.insert(name, local);
72 let missing_fields = ctx.sema.record_literal_missing_fields(&field_list_parent);
74 let generate_fill_expr = |ty: &Type| match ctx.config.expr_fill_default {
75 crate::ExprFillDefaultMode::Todo => Some(make::ext::expr_todo()),
76 crate::ExprFillDefaultMode::Default => {
77 let default_constr = get_default_constructor(ctx, d, ty);
78 match default_constr {
79 Some(default_constr) => Some(default_constr),
80 _ => Some(make::ext::expr_todo()),
85 for (f, ty) in missing_fields.iter() {
86 let field_expr = if let Some(local_candidate) = locals.get(&f.name(ctx.sema.db)) {
87 cov_mark::hit!(field_shorthand);
88 let candidate_ty = local_candidate.ty(ctx.sema.db);
89 if ty.could_unify_with(ctx.sema.db, &candidate_ty) {
92 generate_fill_expr(ty)
95 generate_fill_expr(ty)
98 make::record_expr_field(make::name_ref(&f.name(ctx.sema.db).to_smol_str()), field_expr)
100 new_field_list.add_field(field);
103 let mut builder = TextEdit::builder();
104 if d.file.is_macro() {
105 // we can't map the diff up into the macro input unfortunately, as the macro loses all
106 // whitespace information so the diff wouldn't be applicable no matter what
107 // This has the downside that the cursor will be moved in macros by doing it without a diff
108 // but that is a trade off we can make.
109 // FIXE: this also currently discards a lot of whitespace in the input... we really need a formatter here
110 let range = ctx.sema.original_range_opt(old_field_list.syntax())?;
111 builder.replace(range.range, new_field_list.to_string());
113 algo::diff(old_field_list.syntax(), new_field_list.syntax()).into_text_edit(&mut builder);
115 let edit = builder.finish();
117 "fill_missing_fields",
118 "Fill struct fields",
119 SourceChange::from_text_edit(d.file.original_file(ctx.sema.db), edit),
120 ctx.sema.original_range(field_list_parent.syntax()).range,
124 fn make_ty(ty: &hir::Type, db: &dyn HirDatabase, module: hir::Module) -> ast::Type {
125 let ty_str = match ty.as_adt() {
126 Some(adt) => adt.name(db).to_string(),
127 None => ty.display_source_code(db, module.into()).ok().unwrap_or_else(|| "_".to_string()),
133 fn get_default_constructor(
134 ctx: &DiagnosticsContext<'_>,
135 d: &hir::MissingFields,
137 ) -> Option<ast::Expr> {
138 if let Some(builtin_ty) = ty.as_builtin() {
139 if builtin_ty.is_int() || builtin_ty.is_uint() {
140 return Some(make::ext::zero_number());
142 if builtin_ty.is_float() {
143 return Some(make::ext::zero_float());
145 if builtin_ty.is_char() {
146 return Some(make::ext::empty_char());
148 if builtin_ty.is_str() {
149 return Some(make::ext::empty_str());
153 let krate = ctx.sema.to_module_def(d.file.original_file(ctx.sema.db))?.krate();
154 let module = krate.root_module(ctx.sema.db);
156 // Look for a ::new() associated function
157 let has_new_func = ty
158 .iterate_assoc_items(ctx.sema.db, krate, |assoc_item| {
159 if let AssocItem::Function(func) = assoc_item {
160 if func.name(ctx.sema.db) == known::new
161 && func.assoc_fn_params(ctx.sema.db).is_empty()
172 Some(make::ext::expr_ty_new(&make_ty(ty, ctx.sema.db, module)))
173 } else if !ty.is_array()
174 && ty.impls_trait(ctx.sema.db, FamousDefs(&ctx.sema, krate).core_default_Default()?, &[])
176 Some(make::ext::expr_ty_default(&make_ty(ty, ctx.sema.db, module)))
184 use crate::tests::{check_diagnostics, check_fix};
187 fn missing_record_pat_field_diagnostic() {
190 struct S { foo: i32, bar: () }
192 let S { foo: _ } = s;
193 //^ error: missing structure fields:
201 fn missing_record_pat_field_no_diagnostic_if_not_exhaustive() {
204 struct S { foo: i32, bar: () }
205 fn baz(s: S) -> i32 {
207 S { foo, .. } => foo,
215 fn missing_record_pat_field_box() {
218 struct S { s: Box<u32> }
227 fn missing_record_pat_field_ref() {
239 fn range_mapping_out_of_macros() {
246 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
249 let _x = id![Foo { a: $042 }];
252 pub struct Foo { pub a: i32, pub b: i32 }
259 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
262 let _x = id![Foo {a:42, b: 0 }];
265 pub struct Foo { pub a: i32, pub b: i32 }
271 fn test_fill_struct_fields_empty() {
274 struct TestStruct { one: i32, two: i64 }
277 let s = TestStruct {$0};
281 struct TestStruct { one: i32, two: i64 }
284 let s = TestStruct { one: 0, two: 0 };
291 fn test_fill_struct_fields_self() {
294 struct TestStruct { one: i32 }
297 fn test_fn() { let s = Self {$0}; }
301 struct TestStruct { one: i32 }
304 fn test_fn() { let s = Self { one: 0 }; }
311 fn test_fill_struct_fields_enum() {
315 Bin { lhs: Box<Expr>, rhs: Box<Expr> }
319 fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
326 Bin { lhs: Box<Expr>, rhs: Box<Expr> }
330 fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
331 Expr::Bin { lhs, rhs }
339 fn test_fill_struct_fields_partial() {
342 struct TestStruct { one: i32, two: i64 }
345 let s = TestStruct{ two: 2$0 };
349 struct TestStruct { one: i32, two: i64 }
352 let s = TestStruct{ two: 2, one: 0 };
359 fn test_fill_struct_fields_new() {
362 struct TestWithNew(usize);
364 pub fn new() -> Self {
368 struct TestStruct { one: i32, two: TestWithNew }
371 let s = TestStruct{ $0 };
375 struct TestWithNew(usize);
377 pub fn new() -> Self {
381 struct TestStruct { one: i32, two: TestWithNew }
384 let s = TestStruct{ one: 0, two: TestWithNew::new() };
391 fn test_fill_struct_fields_default() {
394 //- minicore: default
395 struct TestWithDefault(usize);
396 impl Default for TestWithDefault {
397 pub fn default() -> Self {
401 struct TestStruct { one: i32, two: TestWithDefault }
404 let s = TestStruct{ $0 };
408 struct TestWithDefault(usize);
409 impl Default for TestWithDefault {
410 pub fn default() -> Self {
414 struct TestStruct { one: i32, two: TestWithDefault }
417 let s = TestStruct{ one: 0, two: TestWithDefault::default() };
424 fn test_fill_struct_fields_raw_ident() {
427 struct TestStruct { r#type: u8 }
434 struct TestStruct { r#type: u8 }
437 TestStruct { r#type: 0 };
444 fn test_fill_struct_fields_no_diagnostic() {
447 struct TestStruct { one: i32, two: i64 }
451 let s = TestStruct{ one, two: 2 };
458 fn test_fill_struct_fields_no_diagnostic_on_spread() {
461 struct TestStruct { one: i32, two: i64 }
465 let s = TestStruct{ ..a };
472 fn test_fill_struct_fields_blank_line() {
475 struct S { a: (), b: () }
484 struct S { a: (), b: () }
497 fn test_fill_struct_fields_shorthand() {
498 cov_mark::check!(field_shorthand);
501 struct S { a: &'static str, b: i32 }
512 struct S { a: &'static str, b: i32 }
527 fn test_fill_struct_fields_shorthand_ty_mismatch() {
530 struct S { a: &'static str, b: i32 }
541 struct S { a: &'static str, b: i32 }
556 fn test_fill_struct_fields_shorthand_unifies() {
559 struct S<T> { a: &'static str, b: T }
570 struct S<T> { a: &'static str, b: T }
585 fn import_extern_crate_clash_with_inner_item() {
586 // This is more of a resolver test, but doesn't really work with the hir_def testsuite.
590 //- /lib.rs crate:lib deps:jwt
593 use permissions::jwt;
597 jwt::Claims {}; // should resolve to the local one with 0 fields, and not get a diagnostic
605 //- /jwt/lib.rs crate:jwt