3 db::{AstDatabase, HirDatabase},
4 known, AssocItem, HirDisplay, InFile, Type,
7 assists::Assist, famous_defs::FamousDefs, imports::import_assets::item_for_path_search,
8 source_change::SourceChange, FxHashMap,
14 AstNode, SyntaxNode, SyntaxNodePtr,
16 use text_edit::TextEdit;
18 use crate::{fix, Diagnostic, DiagnosticsContext};
20 // TODO: how to depupicate with `ide-assists/generate_new`
21 pub fn use_trivial_constructor(
22 db: &ide_db::RootDatabase,
25 ) -> Option<ast::Expr> {
27 Some(hir::Adt::Enum(x)) => {
28 let variants = x.variants(db);
30 if variants.len() == 1 {
31 let variant = variants[0];
33 if variant.fields(db).is_empty() {
34 let path = ast::make::path_qualified(
36 syntax::ast::make::path_segment(ast::make::name_ref(
37 &variant.name(db).to_smol_str(),
41 let is_record = variant.kind(db) == hir::StructKind::Record;
43 return Some(if is_record {
44 ast::Expr::RecordExpr(syntax::ast::make::record_expr(
46 ast::make::record_expr_field_list(std::iter::empty()),
49 syntax::ast::make::expr_path(path)
54 Some(hir::Adt::Struct(x)) => {
55 if x.fields(db).is_empty() {
56 return Some(syntax::ast::make::expr_path(path));
65 // Diagnostic: missing-fields
67 // This diagnostic is triggered if record lacks some fields that exist in the corresponding structure.
72 // struct A { a: u8, b: u8 }
74 // let a = A { a: 10 };
76 pub(crate) fn missing_fields(ctx: &DiagnosticsContext<'_>, d: &hir::MissingFields) -> Diagnostic {
77 let mut message = String::from("missing structure fields:\n");
78 for field in &d.missed_fields {
79 format_to!(message, "- {}\n", field);
82 let ptr = InFile::new(
84 d.field_list_parent_path
86 .map(SyntaxNodePtr::from)
87 .unwrap_or_else(|| d.field_list_parent.clone().either(|it| it.into(), |it| it.into())),
90 Diagnostic::new("missing-fields", message, ctx.sema.diagnostics_display_range(ptr).range)
91 .with_fixes(fixes(ctx, d))
94 fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::MissingFields) -> Option<Vec<Assist>> {
95 // Note that although we could add a diagnostics to
96 // fill the missing tuple field, e.g :
98 // `let a = A { 0: () }`
99 // but it is uncommon usage and it should not be encouraged.
100 if d.missed_fields.iter().any(|it| it.as_tuple_index().is_some()) {
104 let root = ctx.sema.db.parse_or_expand(d.file)?;
106 let current_module = match &d.field_list_parent {
107 Either::Left(ptr) => ctx.sema.scope(ptr.to_node(&root).syntax()).unwrap().module(),
108 Either::Right(ptr) => ctx.sema.scope(ptr.to_node(&root).syntax()).unwrap().module(),
111 let build_text_edit = |parent_syntax, new_syntax: &SyntaxNode, old_syntax| {
113 let mut builder = TextEdit::builder();
114 if d.file.is_macro() {
115 // we can't map the diff up into the macro input unfortunately, as the macro loses all
116 // whitespace information so the diff wouldn't be applicable no matter what
117 // This has the downside that the cursor will be moved in macros by doing it without a diff
118 // but that is a trade off we can make.
119 // FIXME: this also currently discards a lot of whitespace in the input... we really need a formatter here
120 let range = ctx.sema.original_range_opt(old_syntax)?;
121 builder.replace(range.range, new_syntax.to_string());
123 algo::diff(old_syntax, new_syntax).into_text_edit(&mut builder);
128 "fill_missing_fields",
129 "Fill struct fields",
130 SourceChange::from_text_edit(d.file.original_file(ctx.sema.db), edit),
131 ctx.sema.original_range(parent_syntax).range,
135 match &d.field_list_parent {
136 Either::Left(record_expr) => {
137 let field_list_parent = record_expr.to_node(&root);
138 let missing_fields = ctx.sema.record_literal_missing_fields(&field_list_parent);
140 let mut locals = FxHashMap::default();
141 ctx.sema.scope(field_list_parent.syntax())?.process_all_names(&mut |name, def| {
142 if let hir::ScopeDef::Local(local) = def {
143 locals.insert(name, local);
147 let generate_fill_expr = |ty: &Type| match ctx.config.expr_fill_default {
148 crate::ExprFillDefaultMode::Todo => make::ext::expr_todo(),
149 crate::ExprFillDefaultMode::Default => {
150 get_default_constructor(ctx, d, ty).unwrap_or_else(|| make::ext::expr_todo())
154 let old_field_list = field_list_parent.record_expr_field_list()?;
155 let new_field_list = old_field_list.clone_for_update();
156 for (f, ty) in missing_fields.iter() {
157 let field_expr = if let Some(local_candidate) = locals.get(&f.name(ctx.sema.db)) {
158 cov_mark::hit!(field_shorthand);
159 let candidate_ty = local_candidate.ty(ctx.sema.db);
160 if ty.could_unify_with(ctx.sema.db, &candidate_ty) {
163 Some(generate_fill_expr(ty))
166 let expr = (|| -> Option<ast::Expr> {
167 let item_in_ns = hir::ItemInNs::from(hir::ModuleDef::from(ty.as_adt()?));
169 let type_path = current_module.find_use_path(
171 item_for_path_search(ctx.sema.db, item_in_ns)?,
174 use_trivial_constructor(
176 ide_db::helpers::mod_path_to_ast(&type_path),
184 Some(generate_fill_expr(ty))
187 let field = make::record_expr_field(
188 make::name_ref(&f.name(ctx.sema.db).to_smol_str()),
191 new_field_list.add_field(field.clone_for_update());
194 field_list_parent.syntax(),
195 new_field_list.syntax(),
196 old_field_list.syntax(),
199 Either::Right(record_pat) => {
200 let field_list_parent = record_pat.to_node(&root);
201 let missing_fields = ctx.sema.record_pattern_missing_fields(&field_list_parent);
203 let old_field_list = field_list_parent.record_pat_field_list()?;
204 let new_field_list = old_field_list.clone_for_update();
205 for (f, _) in missing_fields.iter() {
206 let field = make::record_pat_field_shorthand(make::name_ref(
207 &f.name(ctx.sema.db).to_smol_str(),
209 new_field_list.add_field(field.clone_for_update());
212 field_list_parent.syntax(),
213 new_field_list.syntax(),
214 old_field_list.syntax(),
220 fn make_ty(ty: &hir::Type, db: &dyn HirDatabase, module: hir::Module) -> ast::Type {
221 let ty_str = match ty.as_adt() {
222 Some(adt) => adt.name(db).to_string(),
223 None => ty.display_source_code(db, module.into()).ok().unwrap_or_else(|| "_".to_string()),
229 fn get_default_constructor(
230 ctx: &DiagnosticsContext<'_>,
231 d: &hir::MissingFields,
233 ) -> Option<ast::Expr> {
234 if let Some(builtin_ty) = ty.as_builtin() {
235 if builtin_ty.is_int() || builtin_ty.is_uint() {
236 return Some(make::ext::zero_number());
238 if builtin_ty.is_float() {
239 return Some(make::ext::zero_float());
241 if builtin_ty.is_char() {
242 return Some(make::ext::empty_char());
244 if builtin_ty.is_str() {
245 return Some(make::ext::empty_str());
247 if builtin_ty.is_bool() {
248 return Some(make::ext::default_bool());
252 let krate = ctx.sema.to_module_def(d.file.original_file(ctx.sema.db))?.krate();
253 let module = krate.root_module(ctx.sema.db);
255 // Look for a ::new() associated function
256 let has_new_func = ty
257 .iterate_assoc_items(ctx.sema.db, krate, |assoc_item| {
258 if let AssocItem::Function(func) = assoc_item {
259 if func.name(ctx.sema.db) == known::new
260 && func.assoc_fn_params(ctx.sema.db).is_empty()
270 let famous_defs = FamousDefs(&ctx.sema, krate);
272 Some(make::ext::expr_ty_new(&make_ty(ty, ctx.sema.db, module)))
273 } else if ty.as_adt() == famous_defs.core_option_Option()?.ty(ctx.sema.db).as_adt() {
274 Some(make::ext::option_none())
275 } else if !ty.is_array()
276 && ty.impls_trait(ctx.sema.db, famous_defs.core_default_Default()?, &[])
278 Some(make::ext::expr_ty_default(&make_ty(ty, ctx.sema.db, module)))
286 use crate::tests::{check_diagnostics, check_fix};
289 fn missing_record_pat_field_diagnostic() {
292 struct S { foo: i32, bar: () }
294 let S { foo: _ } = s;
295 //^ 💡 error: missing structure fields:
303 fn missing_record_pat_field_no_diagnostic_if_not_exhaustive() {
306 struct S { foo: i32, bar: () }
307 fn baz(s: S) -> i32 {
309 S { foo, .. } => foo,
317 fn missing_record_pat_field_box() {
320 struct S { s: Box<u32> }
329 fn missing_record_pat_field_ref() {
341 fn range_mapping_out_of_macros() {
348 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
351 let _x = id![Foo { a: $042 }];
354 pub struct Foo { pub a: i32, pub b: i32 }
361 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
364 let _x = id![Foo {a:42, b: 0 }];
367 pub struct Foo { pub a: i32, pub b: i32 }
373 fn test_fill_struct_fields_empty() {
377 struct TestStruct { one: i32, two: i64, three: Option<i32>, four: bool }
380 let s = TestStruct {$0};
384 struct TestStruct { one: i32, two: i64, three: Option<i32>, four: bool }
387 let s = TestStruct { one: 0, two: 0, three: None, four: false };
394 fn test_fill_struct_fields_self() {
397 struct TestStruct { one: i32 }
400 fn test_fn() { let s = Self {$0}; }
404 struct TestStruct { one: i32 }
407 fn test_fn() { let s = Self { one: 0 }; }
414 fn test_fill_struct_fields_enum() {
418 Bin { lhs: Box<Expr>, rhs: Box<Expr> }
422 fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
429 Bin { lhs: Box<Expr>, rhs: Box<Expr> }
433 fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
434 Expr::Bin { lhs, rhs }
442 fn test_fill_struct_fields_partial() {
445 struct TestStruct { one: i32, two: i64 }
448 let s = TestStruct{ two: 2$0 };
452 struct TestStruct { one: i32, two: i64 }
455 let s = TestStruct{ two: 2, one: 0 };
462 fn test_fill_struct_fields_new() {
465 struct TestWithNew(usize);
467 pub fn new() -> Self {
471 struct TestStruct { one: i32, two: TestWithNew }
474 let s = TestStruct{ $0 };
478 struct TestWithNew(usize);
480 pub fn new() -> Self {
484 struct TestStruct { one: i32, two: TestWithNew }
487 let s = TestStruct{ one: 0, two: TestWithNew::new() };
494 fn test_fill_struct_fields_default() {
497 //- minicore: default, option
498 struct TestWithDefault(usize);
499 impl Default for TestWithDefault {
500 pub fn default() -> Self {
504 struct TestStruct { one: i32, two: TestWithDefault }
507 let s = TestStruct{ $0 };
511 struct TestWithDefault(usize);
512 impl Default for TestWithDefault {
513 pub fn default() -> Self {
517 struct TestStruct { one: i32, two: TestWithDefault }
520 let s = TestStruct{ one: 0, two: TestWithDefault::default() };
527 fn test_fill_struct_fields_raw_ident() {
530 struct TestStruct { r#type: u8 }
537 struct TestStruct { r#type: u8 }
540 TestStruct { r#type: 0 };
547 fn test_fill_struct_fields_no_diagnostic() {
550 struct TestStruct { one: i32, two: i64 }
554 let s = TestStruct{ one, two: 2 };
561 fn test_fill_struct_fields_no_diagnostic_on_spread() {
564 struct TestStruct { one: i32, two: i64 }
568 let s = TestStruct{ ..a };
575 fn test_fill_struct_fields_blank_line() {
578 struct S { a: (), b: () }
587 struct S { a: (), b: () }
600 fn test_fill_struct_fields_shorthand() {
601 cov_mark::check!(field_shorthand);
604 struct S { a: &'static str, b: i32 }
615 struct S { a: &'static str, b: i32 }
630 fn test_fill_struct_fields_shorthand_ty_mismatch() {
633 struct S { a: &'static str, b: i32 }
644 struct S { a: &'static str, b: i32 }
659 fn test_fill_struct_fields_shorthand_unifies() {
662 struct S<T> { a: &'static str, b: T }
673 struct S<T> { a: &'static str, b: T }
688 fn test_fill_struct_pat_fields() {
691 struct S { a: &'static str, b: i32 }
700 struct S { a: &'static str, b: i32 }
713 fn test_fill_struct_pat_fields_partial() {
716 struct S { a: &'static str, b: i32 }
725 struct S { a: &'static str, b: i32 }
738 fn import_extern_crate_clash_with_inner_item() {
739 // This is more of a resolver test, but doesn't really work with the hir_def testsuite.
743 //- /lib.rs crate:lib deps:jwt
746 use permissions::jwt;
750 jwt::Claims {}; // should resolve to the local one with 0 fields, and not get a diagnostic
758 //- /jwt/lib.rs crate:jwt