]> git.lizzy.rs Git - rust.git/blob - crates/ide-diagnostics/src/handlers/missing_fields.rs
cleanup
[rust.git] / 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, 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 // TODO: how to depupicate with `ide-assists/generate_new`
21 pub fn use_trivial_constructor(
22     db: &ide_db::RootDatabase,
23     path: ast::Path,
24     ty: &hir::Type,
25 ) -> Option<ast::Expr> {
26     match ty.as_adt() {
27         Some(hir::Adt::Enum(x)) => {
28             let variants = x.variants(db);
29
30             if variants.len() == 1 {
31                 let variant = variants[0];
32
33                 if variant.fields(db).is_empty() {
34                     let path = ast::make::path_qualified(
35                         path,
36                         syntax::ast::make::path_segment(ast::make::name_ref(
37                             &variant.name(db).to_smol_str(),
38                         )),
39                     );
40
41                     let is_record = variant.kind(db) == hir::StructKind::Record;
42
43                     return Some(if is_record {
44                         ast::Expr::RecordExpr(syntax::ast::make::record_expr(
45                             path,
46                             ast::make::record_expr_field_list(std::iter::empty()),
47                         ))
48                     } else {
49                         syntax::ast::make::expr_path(path)
50                     });
51                 }
52             }
53         }
54         Some(hir::Adt::Struct(x)) => {
55             if x.fields(db).is_empty() {
56                 return Some(syntax::ast::make::expr_path(path));
57             }
58         }
59         _ => {}
60     }
61
62     None
63 }
64
65 // Diagnostic: missing-fields
66 //
67 // This diagnostic is triggered if record lacks some fields that exist in the corresponding structure.
68 //
69 // Example:
70 //
71 // ```rust
72 // struct A { a: u8, b: u8 }
73 //
74 // let a = A { a: 10 };
75 // ```
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);
80     }
81
82     let ptr = InFile::new(
83         d.file,
84         d.field_list_parent_path
85             .clone()
86             .map(SyntaxNodePtr::from)
87             .unwrap_or_else(|| d.field_list_parent.clone().either(|it| it.into(), |it| it.into())),
88     );
89
90     Diagnostic::new("missing-fields", message, ctx.sema.diagnostics_display_range(ptr).range)
91         .with_fixes(fixes(ctx, d))
92 }
93
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 :
97     // `struct A(usize);`
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()) {
101         return None;
102     }
103
104     let root = ctx.sema.db.parse_or_expand(d.file)?;
105
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(),
109     };
110
111     let build_text_edit = |parent_syntax, new_syntax: &SyntaxNode, old_syntax| {
112         let edit = {
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());
122             } else {
123                 algo::diff(old_syntax, new_syntax).into_text_edit(&mut builder);
124             }
125             builder.finish()
126         };
127         Some(vec![fix(
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,
132         )])
133     };
134
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);
139
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);
144                 }
145             });
146
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())
151                 }
152             };
153
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) {
161                         None
162                     } else {
163                         Some(generate_fill_expr(ty))
164                     }
165                 } else {
166                     let expr = (|| -> Option<ast::Expr> {
167                         let item_in_ns = hir::ItemInNs::from(hir::ModuleDef::from(ty.as_adt()?));
168
169                         let type_path = current_module.find_use_path(
170                             ctx.sema.db,
171                             item_for_path_search(ctx.sema.db, item_in_ns)?,
172                         )?;
173
174                         use_trivial_constructor(
175                             &ctx.sema.db,
176                             ide_db::helpers::mod_path_to_ast(&type_path),
177                             &ty,
178                         )
179                     })();
180
181                     if expr.is_some() {
182                         expr
183                     } else {
184                         Some(generate_fill_expr(ty))
185                     }
186                 };
187                 let field = make::record_expr_field(
188                     make::name_ref(&f.name(ctx.sema.db).to_smol_str()),
189                     field_expr,
190                 );
191                 new_field_list.add_field(field.clone_for_update());
192             }
193             build_text_edit(
194                 field_list_parent.syntax(),
195                 new_field_list.syntax(),
196                 old_field_list.syntax(),
197             )
198         }
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);
202
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(),
208                 ));
209                 new_field_list.add_field(field.clone_for_update());
210             }
211             build_text_edit(
212                 field_list_parent.syntax(),
213                 new_field_list.syntax(),
214                 old_field_list.syntax(),
215             )
216         }
217     }
218 }
219
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()),
224     };
225
226     make::ty(&ty_str)
227 }
228
229 fn get_default_constructor(
230     ctx: &DiagnosticsContext<'_>,
231     d: &hir::MissingFields,
232     ty: &Type,
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());
237         }
238         if builtin_ty.is_float() {
239             return Some(make::ext::zero_float());
240         }
241         if builtin_ty.is_char() {
242             return Some(make::ext::empty_char());
243         }
244         if builtin_ty.is_str() {
245             return Some(make::ext::empty_str());
246         }
247         if builtin_ty.is_bool() {
248             return Some(make::ext::default_bool());
249         }
250     }
251
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);
254
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()
261                 {
262                     return Some(());
263                 }
264             }
265
266             None
267         })
268         .is_some();
269
270     let famous_defs = FamousDefs(&ctx.sema, krate);
271     if has_new_func {
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()?, &[])
277     {
278         Some(make::ext::expr_ty_default(&make_ty(ty, ctx.sema.db, module)))
279     } else {
280         None
281     }
282 }
283
284 #[cfg(test)]
285 mod tests {
286     use crate::tests::{check_diagnostics, check_fix};
287
288     #[test]
289     fn missing_record_pat_field_diagnostic() {
290         check_diagnostics(
291             r#"
292 struct S { foo: i32, bar: () }
293 fn baz(s: S) {
294     let S { foo: _ } = s;
295       //^ ðŸ’¡ error: missing structure fields:
296       //| - bar
297 }
298 "#,
299         );
300     }
301
302     #[test]
303     fn missing_record_pat_field_no_diagnostic_if_not_exhaustive() {
304         check_diagnostics(
305             r"
306 struct S { foo: i32, bar: () }
307 fn baz(s: S) -> i32 {
308     match s {
309         S { foo, .. } => foo,
310     }
311 }
312 ",
313         )
314     }
315
316     #[test]
317     fn missing_record_pat_field_box() {
318         check_diagnostics(
319             r"
320 struct S { s: Box<u32> }
321 fn x(a: S) {
322     let S { box s } = a;
323 }
324 ",
325         )
326     }
327
328     #[test]
329     fn missing_record_pat_field_ref() {
330         check_diagnostics(
331             r"
332 struct S { s: u32 }
333 fn x(a: S) {
334     let S { ref s } = a;
335 }
336 ",
337         )
338     }
339
340     #[test]
341     fn range_mapping_out_of_macros() {
342         check_fix(
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: $042 }];
352 }
353
354 pub struct Foo { pub a: i32, pub b: i32 }
355 "#,
356             r#"
357 fn some() {}
358 fn items() {}
359 fn here() {}
360
361 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
362
363 fn main() {
364     let _x = id![Foo {a:42, b: 0 }];
365 }
366
367 pub struct Foo { pub a: i32, pub b: i32 }
368 "#,
369         );
370     }
371
372     #[test]
373     fn test_fill_struct_fields_empty() {
374         check_fix(
375             r#"
376 //- minicore: option
377 struct TestStruct { one: i32, two: i64, three: Option<i32>, four: bool }
378
379 fn test_fn() {
380     let s = TestStruct {$0};
381 }
382 "#,
383             r#"
384 struct TestStruct { one: i32, two: i64, three: Option<i32>, four: bool }
385
386 fn test_fn() {
387     let s = TestStruct { one: 0, two: 0, three: None, four: false };
388 }
389 "#,
390         );
391     }
392
393     #[test]
394     fn test_fill_struct_fields_self() {
395         check_fix(
396             r#"
397 struct TestStruct { one: i32 }
398
399 impl TestStruct {
400     fn test_fn() { let s = Self {$0}; }
401 }
402 "#,
403             r#"
404 struct TestStruct { one: i32 }
405
406 impl TestStruct {
407     fn test_fn() { let s = Self { one: 0 }; }
408 }
409 "#,
410         );
411     }
412
413     #[test]
414     fn test_fill_struct_fields_enum() {
415         check_fix(
416             r#"
417 enum Expr {
418     Bin { lhs: Box<Expr>, rhs: Box<Expr> }
419 }
420
421 impl Expr {
422     fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
423         Expr::Bin {$0 }
424     }
425 }
426 "#,
427             r#"
428 enum Expr {
429     Bin { lhs: Box<Expr>, rhs: Box<Expr> }
430 }
431
432 impl Expr {
433     fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
434         Expr::Bin { lhs, rhs }
435     }
436 }
437 "#,
438         );
439     }
440
441     #[test]
442     fn test_fill_struct_fields_partial() {
443         check_fix(
444             r#"
445 struct TestStruct { one: i32, two: i64 }
446
447 fn test_fn() {
448     let s = TestStruct{ two: 2$0 };
449 }
450 "#,
451             r"
452 struct TestStruct { one: i32, two: i64 }
453
454 fn test_fn() {
455     let s = TestStruct{ two: 2, one: 0 };
456 }
457 ",
458         );
459     }
460
461     #[test]
462     fn test_fill_struct_fields_new() {
463         check_fix(
464             r#"
465 struct TestWithNew(usize);
466 impl TestWithNew {
467     pub fn new() -> Self {
468         Self(0)
469     }
470 }
471 struct TestStruct { one: i32, two: TestWithNew }
472
473 fn test_fn() {
474     let s = TestStruct{ $0 };
475 }
476 "#,
477             r"
478 struct TestWithNew(usize);
479 impl TestWithNew {
480     pub fn new() -> Self {
481         Self(0)
482     }
483 }
484 struct TestStruct { one: i32, two: TestWithNew }
485
486 fn test_fn() {
487     let s = TestStruct{ one: 0, two: TestWithNew::new()  };
488 }
489 ",
490         );
491     }
492
493     #[test]
494     fn test_fill_struct_fields_default() {
495         check_fix(
496             r#"
497 //- minicore: default, option
498 struct TestWithDefault(usize);
499 impl Default for TestWithDefault {
500     pub fn default() -> Self {
501         Self(0)
502     }
503 }
504 struct TestStruct { one: i32, two: TestWithDefault }
505
506 fn test_fn() {
507     let s = TestStruct{ $0 };
508 }
509 "#,
510             r"
511 struct TestWithDefault(usize);
512 impl Default for TestWithDefault {
513     pub fn default() -> Self {
514         Self(0)
515     }
516 }
517 struct TestStruct { one: i32, two: TestWithDefault }
518
519 fn test_fn() {
520     let s = TestStruct{ one: 0, two: TestWithDefault::default()  };
521 }
522 ",
523         );
524     }
525
526     #[test]
527     fn test_fill_struct_fields_raw_ident() {
528         check_fix(
529             r#"
530 struct TestStruct { r#type: u8 }
531
532 fn test_fn() {
533     TestStruct { $0 };
534 }
535 "#,
536             r"
537 struct TestStruct { r#type: u8 }
538
539 fn test_fn() {
540     TestStruct { r#type: 0  };
541 }
542 ",
543         );
544     }
545
546     #[test]
547     fn test_fill_struct_fields_no_diagnostic() {
548         check_diagnostics(
549             r#"
550 struct TestStruct { one: i32, two: i64 }
551
552 fn test_fn() {
553     let one = 1;
554     let s = TestStruct{ one, two: 2 };
555 }
556         "#,
557         );
558     }
559
560     #[test]
561     fn test_fill_struct_fields_no_diagnostic_on_spread() {
562         check_diagnostics(
563             r#"
564 struct TestStruct { one: i32, two: i64 }
565
566 fn test_fn() {
567     let one = 1;
568     let s = TestStruct{ ..a };
569 }
570 "#,
571         );
572     }
573
574     #[test]
575     fn test_fill_struct_fields_blank_line() {
576         check_fix(
577             r#"
578 struct S { a: (), b: () }
579
580 fn f() {
581     S {
582         $0
583     };
584 }
585 "#,
586             r#"
587 struct S { a: (), b: () }
588
589 fn f() {
590     S {
591         a: todo!(),
592         b: todo!(),
593     };
594 }
595 "#,
596         );
597     }
598
599     #[test]
600     fn test_fill_struct_fields_shorthand() {
601         cov_mark::check!(field_shorthand);
602         check_fix(
603             r#"
604 struct S { a: &'static str, b: i32 }
605
606 fn f() {
607     let a = "hello";
608     let b = 1i32;
609     S {
610         $0
611     };
612 }
613 "#,
614             r#"
615 struct S { a: &'static str, b: i32 }
616
617 fn f() {
618     let a = "hello";
619     let b = 1i32;
620     S {
621         a,
622         b,
623     };
624 }
625 "#,
626         );
627     }
628
629     #[test]
630     fn test_fill_struct_fields_shorthand_ty_mismatch() {
631         check_fix(
632             r#"
633 struct S { a: &'static str, b: i32 }
634
635 fn f() {
636     let a = "hello";
637     let b = 1usize;
638     S {
639         $0
640     };
641 }
642 "#,
643             r#"
644 struct S { a: &'static str, b: i32 }
645
646 fn f() {
647     let a = "hello";
648     let b = 1usize;
649     S {
650         a,
651         b: 0,
652     };
653 }
654 "#,
655         );
656     }
657
658     #[test]
659     fn test_fill_struct_fields_shorthand_unifies() {
660         check_fix(
661             r#"
662 struct S<T> { a: &'static str, b: T }
663
664 fn f() {
665     let a = "hello";
666     let b = 1i32;
667     S {
668         $0
669     };
670 }
671 "#,
672             r#"
673 struct S<T> { a: &'static str, b: T }
674
675 fn f() {
676     let a = "hello";
677     let b = 1i32;
678     S {
679         a,
680         b,
681     };
682 }
683 "#,
684         );
685     }
686
687     #[test]
688     fn test_fill_struct_pat_fields() {
689         check_fix(
690             r#"
691 struct S { a: &'static str, b: i32 }
692
693 fn f() {
694     let S {
695         $0
696     };
697 }
698 "#,
699             r#"
700 struct S { a: &'static str, b: i32 }
701
702 fn f() {
703     let S {
704         a,
705         b,
706     };
707 }
708 "#,
709         );
710     }
711
712     #[test]
713     fn test_fill_struct_pat_fields_partial() {
714         check_fix(
715             r#"
716 struct S { a: &'static str, b: i32 }
717
718 fn f() {
719     let S {
720         a,$0
721     };
722 }
723 "#,
724             r#"
725 struct S { a: &'static str, b: i32 }
726
727 fn f() {
728     let S {
729         a,
730         b,
731     };
732 }
733 "#,
734         );
735     }
736
737     #[test]
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.
740
741         check_diagnostics(
742             r#"
743 //- /lib.rs crate:lib deps:jwt
744 mod permissions;
745
746 use permissions::jwt;
747
748 fn f() {
749     fn inner() {}
750     jwt::Claims {}; // should resolve to the local one with 0 fields, and not get a diagnostic
751 }
752
753 //- /permissions.rs
754 pub mod jwt  {
755     pub struct Claims {}
756 }
757
758 //- /jwt/lib.rs crate:jwt
759 pub struct Claims {
760     field: u8,
761 }
762         "#,
763         );
764     }
765 }