]> git.proxmox.com Git - rustc.git/blob - src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/missing_fields.rs
New upstream version 1.68.2+dfsg1
[rustc.git] / src / tools / rust-analyzer / crates / ide-diagnostics / src / handlers / missing_fields.rs
1 use either::Either;
2 use hir::{
3 db::{AstDatabase, HirDatabase},
4 known, AssocItem, HirDisplay, InFile, Type,
5 };
6 use ide_db::{
7 assists::Assist, famous_defs::FamousDefs, imports::import_assets::item_for_path_search,
8 source_change::SourceChange, use_trivial_contructor::use_trivial_constructor, FxHashMap,
9 };
10 use stdx::format_to;
11 use syntax::{
12 algo,
13 ast::{self, make},
14 AstNode, SyntaxNode, SyntaxNodePtr,
15 };
16 use text_edit::TextEdit;
17
18 use crate::{fix, Diagnostic, DiagnosticsContext};
19
20 // Diagnostic: missing-fields
21 //
22 // This diagnostic is triggered if record lacks some fields that exist in the corresponding structure.
23 //
24 // Example:
25 //
26 // ```rust
27 // struct A { a: u8, b: u8 }
28 //
29 // let a = A { a: 10 };
30 // ```
31 pub(crate) fn missing_fields(ctx: &DiagnosticsContext<'_>, d: &hir::MissingFields) -> Diagnostic {
32 let mut message = String::from("missing structure fields:\n");
33 for field in &d.missed_fields {
34 format_to!(message, "- {}\n", field);
35 }
36
37 let ptr = InFile::new(
38 d.file,
39 d.field_list_parent_path
40 .clone()
41 .map(SyntaxNodePtr::from)
42 .unwrap_or_else(|| d.field_list_parent.clone().either(|it| it.into(), |it| it.into())),
43 );
44
45 Diagnostic::new("missing-fields", message, ctx.sema.diagnostics_display_range(ptr).range)
46 .with_fixes(fixes(ctx, d))
47 }
48
49 fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::MissingFields) -> Option<Vec<Assist>> {
50 // Note that although we could add a diagnostics to
51 // fill the missing tuple field, e.g :
52 // `struct A(usize);`
53 // `let a = A { 0: () }`
54 // but it is uncommon usage and it should not be encouraged.
55 if d.missed_fields.iter().any(|it| it.as_tuple_index().is_some()) {
56 return None;
57 }
58
59 let root = ctx.sema.db.parse_or_expand(d.file)?;
60
61 let current_module = match &d.field_list_parent {
62 Either::Left(ptr) => ctx.sema.scope(ptr.to_node(&root).syntax()).map(|it| it.module()),
63 Either::Right(ptr) => ctx.sema.scope(ptr.to_node(&root).syntax()).map(|it| it.module()),
64 };
65
66 let build_text_edit = |parent_syntax, new_syntax: &SyntaxNode, old_syntax| {
67 let edit = {
68 let mut builder = TextEdit::builder();
69 if d.file.is_macro() {
70 // we can't map the diff up into the macro input unfortunately, as the macro loses all
71 // whitespace information so the diff wouldn't be applicable no matter what
72 // This has the downside that the cursor will be moved in macros by doing it without a diff
73 // but that is a trade off we can make.
74 // FIXME: this also currently discards a lot of whitespace in the input... we really need a formatter here
75 let range = ctx.sema.original_range_opt(old_syntax)?;
76 builder.replace(range.range, new_syntax.to_string());
77 } else {
78 algo::diff(old_syntax, new_syntax).into_text_edit(&mut builder);
79 }
80 builder.finish()
81 };
82 Some(vec![fix(
83 "fill_missing_fields",
84 "Fill struct fields",
85 SourceChange::from_text_edit(d.file.original_file(ctx.sema.db), edit),
86 ctx.sema.original_range(parent_syntax).range,
87 )])
88 };
89
90 match &d.field_list_parent {
91 Either::Left(record_expr) => {
92 let field_list_parent = record_expr.to_node(&root);
93 let missing_fields = ctx.sema.record_literal_missing_fields(&field_list_parent);
94
95 let mut locals = FxHashMap::default();
96 ctx.sema.scope(field_list_parent.syntax())?.process_all_names(&mut |name, def| {
97 if let hir::ScopeDef::Local(local) = def {
98 locals.insert(name, local);
99 }
100 });
101
102 let generate_fill_expr = |ty: &Type| match ctx.config.expr_fill_default {
103 crate::ExprFillDefaultMode::Todo => make::ext::expr_todo(),
104 crate::ExprFillDefaultMode::Default => {
105 get_default_constructor(ctx, d, ty).unwrap_or_else(|| make::ext::expr_todo())
106 }
107 };
108
109 let old_field_list = field_list_parent.record_expr_field_list()?;
110 let new_field_list = old_field_list.clone_for_update();
111 for (f, ty) in missing_fields.iter() {
112 let field_expr = if let Some(local_candidate) = locals.get(&f.name(ctx.sema.db)) {
113 cov_mark::hit!(field_shorthand);
114 let candidate_ty = local_candidate.ty(ctx.sema.db);
115 if ty.could_unify_with(ctx.sema.db, &candidate_ty) {
116 None
117 } else {
118 Some(generate_fill_expr(ty))
119 }
120 } else {
121 let expr = (|| -> Option<ast::Expr> {
122 let item_in_ns = hir::ItemInNs::from(hir::ModuleDef::from(ty.as_adt()?));
123
124 let type_path = current_module?.find_use_path(
125 ctx.sema.db,
126 item_for_path_search(ctx.sema.db, item_in_ns)?,
127 ctx.config.prefer_no_std,
128 )?;
129
130 use_trivial_constructor(
131 ctx.sema.db,
132 ide_db::helpers::mod_path_to_ast(&type_path),
133 ty,
134 )
135 })();
136
137 if expr.is_some() {
138 expr
139 } else {
140 Some(generate_fill_expr(ty))
141 }
142 };
143 let field = make::record_expr_field(
144 make::name_ref(&f.name(ctx.sema.db).to_smol_str()),
145 field_expr,
146 );
147 new_field_list.add_field(field.clone_for_update());
148 }
149 build_text_edit(
150 field_list_parent.syntax(),
151 new_field_list.syntax(),
152 old_field_list.syntax(),
153 )
154 }
155 Either::Right(record_pat) => {
156 let field_list_parent = record_pat.to_node(&root);
157 let missing_fields = ctx.sema.record_pattern_missing_fields(&field_list_parent);
158
159 let old_field_list = field_list_parent.record_pat_field_list()?;
160 let new_field_list = old_field_list.clone_for_update();
161 for (f, _) in missing_fields.iter() {
162 let field = make::record_pat_field_shorthand(make::name_ref(
163 &f.name(ctx.sema.db).to_smol_str(),
164 ));
165 new_field_list.add_field(field.clone_for_update());
166 }
167 build_text_edit(
168 field_list_parent.syntax(),
169 new_field_list.syntax(),
170 old_field_list.syntax(),
171 )
172 }
173 }
174 }
175
176 fn make_ty(ty: &hir::Type, db: &dyn HirDatabase, module: hir::Module) -> ast::Type {
177 let ty_str = match ty.as_adt() {
178 Some(adt) => adt.name(db).to_string(),
179 None => ty.display_source_code(db, module.into()).ok().unwrap_or_else(|| "_".to_string()),
180 };
181
182 make::ty(&ty_str)
183 }
184
185 fn get_default_constructor(
186 ctx: &DiagnosticsContext<'_>,
187 d: &hir::MissingFields,
188 ty: &Type,
189 ) -> Option<ast::Expr> {
190 if let Some(builtin_ty) = ty.as_builtin() {
191 if builtin_ty.is_int() || builtin_ty.is_uint() {
192 return Some(make::ext::zero_number());
193 }
194 if builtin_ty.is_float() {
195 return Some(make::ext::zero_float());
196 }
197 if builtin_ty.is_char() {
198 return Some(make::ext::empty_char());
199 }
200 if builtin_ty.is_str() {
201 return Some(make::ext::empty_str());
202 }
203 if builtin_ty.is_bool() {
204 return Some(make::ext::default_bool());
205 }
206 }
207
208 let krate = ctx.sema.to_module_def(d.file.original_file(ctx.sema.db))?.krate();
209 let module = krate.root_module(ctx.sema.db);
210
211 // Look for a ::new() associated function
212 let has_new_func = ty
213 .iterate_assoc_items(ctx.sema.db, krate, |assoc_item| {
214 if let AssocItem::Function(func) = assoc_item {
215 if func.name(ctx.sema.db) == known::new
216 && func.assoc_fn_params(ctx.sema.db).is_empty()
217 {
218 return Some(());
219 }
220 }
221
222 None
223 })
224 .is_some();
225
226 let famous_defs = FamousDefs(&ctx.sema, krate);
227 if has_new_func {
228 Some(make::ext::expr_ty_new(&make_ty(ty, ctx.sema.db, module)))
229 } else if ty.as_adt() == famous_defs.core_option_Option()?.ty(ctx.sema.db).as_adt() {
230 Some(make::ext::option_none())
231 } else if !ty.is_array()
232 && ty.impls_trait(ctx.sema.db, famous_defs.core_default_Default()?, &[])
233 {
234 Some(make::ext::expr_ty_default(&make_ty(ty, ctx.sema.db, module)))
235 } else {
236 None
237 }
238 }
239
240 #[cfg(test)]
241 mod tests {
242 use crate::tests::{check_diagnostics, check_fix};
243
244 #[test]
245 fn missing_record_pat_field_diagnostic() {
246 check_diagnostics(
247 r#"
248 struct S { foo: i32, bar: () }
249 fn baz(s: S) {
250 let S { foo: _ } = s;
251 //^ 💡 error: missing structure fields:
252 //| - bar
253 }
254 "#,
255 );
256 }
257
258 #[test]
259 fn missing_record_pat_field_no_diagnostic_if_not_exhaustive() {
260 check_diagnostics(
261 r"
262 struct S { foo: i32, bar: () }
263 fn baz(s: S) -> i32 {
264 match s {
265 S { foo, .. } => foo,
266 }
267 }
268 ",
269 )
270 }
271
272 #[test]
273 fn missing_record_pat_field_box() {
274 check_diagnostics(
275 r"
276 struct S { s: Box<u32> }
277 fn x(a: S) {
278 let S { box s } = a;
279 }
280 ",
281 )
282 }
283
284 #[test]
285 fn missing_record_pat_field_ref() {
286 check_diagnostics(
287 r"
288 struct S { s: u32 }
289 fn x(a: S) {
290 let S { ref s } = a;
291 }
292 ",
293 )
294 }
295
296 #[test]
297 fn missing_record_expr_in_assignee_expr() {
298 check_diagnostics(
299 r"
300 struct S { s: usize, t: usize }
301 struct S2 { s: S, t: () }
302 struct T(S);
303 fn regular(a: S) {
304 let s;
305 S { s, .. } = a;
306 }
307 fn nested(a: S2) {
308 let s;
309 S2 { s: S { s, .. }, .. } = a;
310 }
311 fn in_tuple(a: (S,)) {
312 let s;
313 (S { s, .. },) = a;
314 }
315 fn in_array(a: [S;1]) {
316 let s;
317 [S { s, .. },] = a;
318 }
319 fn in_tuple_struct(a: T) {
320 let s;
321 T(S { s, .. }) = a;
322 }
323 ",
324 );
325 }
326
327 #[test]
328 fn range_mapping_out_of_macros() {
329 check_fix(
330 r#"
331 fn some() {}
332 fn items() {}
333 fn here() {}
334
335 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
336
337 fn main() {
338 let _x = id![Foo { a: $042 }];
339 }
340
341 pub struct Foo { pub a: i32, pub b: i32 }
342 "#,
343 r#"
344 fn some() {}
345 fn items() {}
346 fn here() {}
347
348 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
349
350 fn main() {
351 let _x = id![Foo {a:42, b: 0 }];
352 }
353
354 pub struct Foo { pub a: i32, pub b: i32 }
355 "#,
356 );
357 }
358
359 #[test]
360 fn test_fill_struct_fields_empty() {
361 check_fix(
362 r#"
363 //- minicore: option
364 struct TestStruct { one: i32, two: i64, three: Option<i32>, four: bool }
365
366 fn test_fn() {
367 let s = TestStruct {$0};
368 }
369 "#,
370 r#"
371 struct TestStruct { one: i32, two: i64, three: Option<i32>, four: bool }
372
373 fn test_fn() {
374 let s = TestStruct { one: 0, two: 0, three: None, four: false };
375 }
376 "#,
377 );
378 }
379
380 #[test]
381 fn test_fill_struct_zst_fields() {
382 check_fix(
383 r#"
384 struct Empty;
385
386 struct TestStruct { one: i32, two: Empty }
387
388 fn test_fn() {
389 let s = TestStruct {$0};
390 }
391 "#,
392 r#"
393 struct Empty;
394
395 struct TestStruct { one: i32, two: Empty }
396
397 fn test_fn() {
398 let s = TestStruct { one: 0, two: Empty };
399 }
400 "#,
401 );
402 check_fix(
403 r#"
404 enum Empty { Foo };
405
406 struct TestStruct { one: i32, two: Empty }
407
408 fn test_fn() {
409 let s = TestStruct {$0};
410 }
411 "#,
412 r#"
413 enum Empty { Foo };
414
415 struct TestStruct { one: i32, two: Empty }
416
417 fn test_fn() {
418 let s = TestStruct { one: 0, two: Empty::Foo };
419 }
420 "#,
421 );
422
423 // make sure the assist doesn't fill non Unit variants
424 check_fix(
425 r#"
426 struct Empty {};
427
428 struct TestStruct { one: i32, two: Empty }
429
430 fn test_fn() {
431 let s = TestStruct {$0};
432 }
433 "#,
434 r#"
435 struct Empty {};
436
437 struct TestStruct { one: i32, two: Empty }
438
439 fn test_fn() {
440 let s = TestStruct { one: 0, two: todo!() };
441 }
442 "#,
443 );
444 check_fix(
445 r#"
446 enum Empty { Foo {} };
447
448 struct TestStruct { one: i32, two: Empty }
449
450 fn test_fn() {
451 let s = TestStruct {$0};
452 }
453 "#,
454 r#"
455 enum Empty { Foo {} };
456
457 struct TestStruct { one: i32, two: Empty }
458
459 fn test_fn() {
460 let s = TestStruct { one: 0, two: todo!() };
461 }
462 "#,
463 );
464 }
465
466 #[test]
467 fn test_fill_struct_fields_self() {
468 check_fix(
469 r#"
470 struct TestStruct { one: i32 }
471
472 impl TestStruct {
473 fn test_fn() { let s = Self {$0}; }
474 }
475 "#,
476 r#"
477 struct TestStruct { one: i32 }
478
479 impl TestStruct {
480 fn test_fn() { let s = Self { one: 0 }; }
481 }
482 "#,
483 );
484 }
485
486 #[test]
487 fn test_fill_struct_fields_enum() {
488 check_fix(
489 r#"
490 enum Expr {
491 Bin { lhs: Box<Expr>, rhs: Box<Expr> }
492 }
493
494 impl Expr {
495 fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
496 Expr::Bin {$0 }
497 }
498 }
499 "#,
500 r#"
501 enum Expr {
502 Bin { lhs: Box<Expr>, rhs: Box<Expr> }
503 }
504
505 impl Expr {
506 fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
507 Expr::Bin { lhs, rhs }
508 }
509 }
510 "#,
511 );
512 }
513
514 #[test]
515 fn test_fill_struct_fields_partial() {
516 check_fix(
517 r#"
518 struct TestStruct { one: i32, two: i64 }
519
520 fn test_fn() {
521 let s = TestStruct{ two: 2$0 };
522 }
523 "#,
524 r"
525 struct TestStruct { one: i32, two: i64 }
526
527 fn test_fn() {
528 let s = TestStruct{ two: 2, one: 0 };
529 }
530 ",
531 );
532 }
533
534 #[test]
535 fn test_fill_struct_fields_new() {
536 check_fix(
537 r#"
538 struct TestWithNew(usize);
539 impl TestWithNew {
540 pub fn new() -> Self {
541 Self(0)
542 }
543 }
544 struct TestStruct { one: i32, two: TestWithNew }
545
546 fn test_fn() {
547 let s = TestStruct{ $0 };
548 }
549 "#,
550 r"
551 struct TestWithNew(usize);
552 impl TestWithNew {
553 pub fn new() -> Self {
554 Self(0)
555 }
556 }
557 struct TestStruct { one: i32, two: TestWithNew }
558
559 fn test_fn() {
560 let s = TestStruct{ one: 0, two: TestWithNew::new() };
561 }
562 ",
563 );
564 }
565
566 #[test]
567 fn test_fill_struct_fields_default() {
568 check_fix(
569 r#"
570 //- minicore: default, option
571 struct TestWithDefault(usize);
572 impl Default for TestWithDefault {
573 pub fn default() -> Self {
574 Self(0)
575 }
576 }
577 struct TestStruct { one: i32, two: TestWithDefault }
578
579 fn test_fn() {
580 let s = TestStruct{ $0 };
581 }
582 "#,
583 r"
584 struct TestWithDefault(usize);
585 impl Default for TestWithDefault {
586 pub fn default() -> Self {
587 Self(0)
588 }
589 }
590 struct TestStruct { one: i32, two: TestWithDefault }
591
592 fn test_fn() {
593 let s = TestStruct{ one: 0, two: TestWithDefault::default() };
594 }
595 ",
596 );
597 }
598
599 #[test]
600 fn test_fill_struct_fields_raw_ident() {
601 check_fix(
602 r#"
603 struct TestStruct { r#type: u8 }
604
605 fn test_fn() {
606 TestStruct { $0 };
607 }
608 "#,
609 r"
610 struct TestStruct { r#type: u8 }
611
612 fn test_fn() {
613 TestStruct { r#type: 0 };
614 }
615 ",
616 );
617 }
618
619 #[test]
620 fn test_fill_struct_fields_no_diagnostic() {
621 check_diagnostics(
622 r#"
623 struct TestStruct { one: i32, two: i64 }
624
625 fn test_fn() {
626 let one = 1;
627 let s = TestStruct{ one, two: 2 };
628 }
629 "#,
630 );
631 }
632
633 #[test]
634 fn test_fill_struct_fields_no_diagnostic_on_spread() {
635 check_diagnostics(
636 r#"
637 struct TestStruct { one: i32, two: i64 }
638
639 fn test_fn() {
640 let one = 1;
641 let s = TestStruct{ ..a };
642 }
643 "#,
644 );
645 }
646
647 #[test]
648 fn test_fill_struct_fields_blank_line() {
649 check_fix(
650 r#"
651 struct S { a: (), b: () }
652
653 fn f() {
654 S {
655 $0
656 };
657 }
658 "#,
659 r#"
660 struct S { a: (), b: () }
661
662 fn f() {
663 S {
664 a: todo!(),
665 b: todo!(),
666 };
667 }
668 "#,
669 );
670 }
671
672 #[test]
673 fn test_fill_struct_fields_shorthand() {
674 cov_mark::check!(field_shorthand);
675 check_fix(
676 r#"
677 struct S { a: &'static str, b: i32 }
678
679 fn f() {
680 let a = "hello";
681 let b = 1i32;
682 S {
683 $0
684 };
685 }
686 "#,
687 r#"
688 struct S { a: &'static str, b: i32 }
689
690 fn f() {
691 let a = "hello";
692 let b = 1i32;
693 S {
694 a,
695 b,
696 };
697 }
698 "#,
699 );
700 }
701
702 #[test]
703 fn test_fill_struct_fields_shorthand_ty_mismatch() {
704 check_fix(
705 r#"
706 struct S { a: &'static str, b: i32 }
707
708 fn f() {
709 let a = "hello";
710 let b = 1usize;
711 S {
712 $0
713 };
714 }
715 "#,
716 r#"
717 struct S { a: &'static str, b: i32 }
718
719 fn f() {
720 let a = "hello";
721 let b = 1usize;
722 S {
723 a,
724 b: 0,
725 };
726 }
727 "#,
728 );
729 }
730
731 #[test]
732 fn test_fill_struct_fields_shorthand_unifies() {
733 check_fix(
734 r#"
735 struct S<T> { a: &'static str, b: T }
736
737 fn f() {
738 let a = "hello";
739 let b = 1i32;
740 S {
741 $0
742 };
743 }
744 "#,
745 r#"
746 struct S<T> { a: &'static str, b: T }
747
748 fn f() {
749 let a = "hello";
750 let b = 1i32;
751 S {
752 a,
753 b,
754 };
755 }
756 "#,
757 );
758 }
759
760 #[test]
761 fn test_fill_struct_pat_fields() {
762 check_fix(
763 r#"
764 struct S { a: &'static str, b: i32 }
765
766 fn f() {
767 let S {
768 $0
769 };
770 }
771 "#,
772 r#"
773 struct S { a: &'static str, b: i32 }
774
775 fn f() {
776 let S {
777 a,
778 b,
779 };
780 }
781 "#,
782 );
783 }
784
785 #[test]
786 fn test_fill_struct_pat_fields_partial() {
787 check_fix(
788 r#"
789 struct S { a: &'static str, b: i32 }
790
791 fn f() {
792 let S {
793 a,$0
794 };
795 }
796 "#,
797 r#"
798 struct S { a: &'static str, b: i32 }
799
800 fn f() {
801 let S {
802 a,
803 b,
804 };
805 }
806 "#,
807 );
808 }
809
810 #[test]
811 fn import_extern_crate_clash_with_inner_item() {
812 // This is more of a resolver test, but doesn't really work with the hir_def testsuite.
813
814 check_diagnostics(
815 r#"
816 //- /lib.rs crate:lib deps:jwt
817 mod permissions;
818
819 use permissions::jwt;
820
821 fn f() {
822 fn inner() {}
823 jwt::Claims {}; // should resolve to the local one with 0 fields, and not get a diagnostic
824 }
825
826 //- /permissions.rs
827 pub mod jwt {
828 pub struct Claims {}
829 }
830
831 //- /jwt/lib.rs crate:jwt
832 pub struct Claims {
833 field: u8,
834 }
835 "#,
836 );
837 }
838 }