]> git.lizzy.rs Git - rust.git/blob - crates/ide-diagnostics/src/handlers/missing_fields.rs
Auto merge of #12143 - bnjjj:master, r=Veykril
[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::{assists::Assist, famous_defs::FamousDefs, source_change::SourceChange, FxHashMap};
7 use stdx::format_to;
8 use syntax::{
9     algo,
10     ast::{self, make},
11     AstNode, SyntaxNode, SyntaxNodePtr,
12 };
13 use text_edit::TextEdit;
14
15 use crate::{fix, Diagnostic, DiagnosticsContext};
16
17 // Diagnostic: missing-fields
18 //
19 // This diagnostic is triggered if record lacks some fields that exist in the corresponding structure.
20 //
21 // Example:
22 //
23 // ```rust
24 // struct A { a: u8, b: u8 }
25 //
26 // let a = A { a: 10 };
27 // ```
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);
32     }
33
34     let ptr = InFile::new(
35         d.file,
36         d.field_list_parent_path
37             .clone()
38             .map(SyntaxNodePtr::from)
39             .unwrap_or_else(|| d.field_list_parent.clone().either(|it| it.into(), |it| it.into())),
40     );
41
42     Diagnostic::new("missing-fields", message, ctx.sema.diagnostics_display_range(ptr).range)
43         .with_fixes(fixes(ctx, d))
44 }
45
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 :
49     // `struct A(usize);`
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()) {
53         return None;
54     }
55
56     let root = ctx.sema.db.parse_or_expand(d.file)?;
57
58     let build_text_edit = |parent_syntax, new_syntax: &SyntaxNode, old_syntax| {
59         let edit = {
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());
69             } else {
70                 algo::diff(old_syntax, new_syntax).into_text_edit(&mut builder);
71             }
72             builder.finish()
73         };
74         Some(vec![fix(
75             "fill_missing_fields",
76             "Fill struct fields",
77             SourceChange::from_text_edit(d.file.original_file(ctx.sema.db), edit),
78             ctx.sema.original_range(parent_syntax).range,
79         )])
80     };
81
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);
86
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);
91                 }
92             });
93
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())
98                 }
99             };
100
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) {
108                         None
109                     } else {
110                         Some(generate_fill_expr(ty))
111                     }
112                 } else {
113                     Some(generate_fill_expr(ty))
114                 };
115                 let field = make::record_expr_field(
116                     make::name_ref(&f.name(ctx.sema.db).to_smol_str()),
117                     field_expr,
118                 );
119                 new_field_list.add_field(field.clone_for_update());
120             }
121             build_text_edit(
122                 field_list_parent.syntax(),
123                 new_field_list.syntax(),
124                 old_field_list.syntax(),
125             )
126         }
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);
130
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(),
136                 ));
137                 new_field_list.add_field(field.clone_for_update());
138             }
139             build_text_edit(
140                 field_list_parent.syntax(),
141                 new_field_list.syntax(),
142                 old_field_list.syntax(),
143             )
144         }
145     }
146 }
147
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()),
152     };
153
154     make::ty(&ty_str)
155 }
156
157 fn get_default_constructor(
158     ctx: &DiagnosticsContext<'_>,
159     d: &hir::MissingFields,
160     ty: &Type,
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());
165         }
166         if builtin_ty.is_float() {
167             return Some(make::ext::zero_float());
168         }
169         if builtin_ty.is_char() {
170             return Some(make::ext::empty_char());
171         }
172         if builtin_ty.is_str() {
173             return Some(make::ext::empty_str());
174         }
175         if builtin_ty.is_bool() {
176             return Some(make::ext::default_bool());
177         }
178     }
179
180     let krate = ctx.sema.to_module_def(d.file.original_file(ctx.sema.db))?.krate();
181     let module = krate.root_module(ctx.sema.db);
182
183     // Look for a ::new() associated function
184     let has_new_func = ty
185         .iterate_assoc_items(ctx.sema.db, krate, |assoc_item| {
186             if let AssocItem::Function(func) = assoc_item {
187                 if func.name(ctx.sema.db) == known::new
188                     && func.assoc_fn_params(ctx.sema.db).is_empty()
189                 {
190                     return Some(());
191                 }
192             }
193
194             None
195         })
196         .is_some();
197
198     let famous_defs = FamousDefs(&ctx.sema, krate);
199     if has_new_func {
200         Some(make::ext::expr_ty_new(&make_ty(ty, ctx.sema.db, module)))
201     } else if ty.as_adt() == famous_defs.core_option_Option()?.ty(ctx.sema.db).as_adt() {
202         Some(make::ext::option_none())
203     } else if !ty.is_array()
204         && ty.impls_trait(ctx.sema.db, famous_defs.core_default_Default()?, &[])
205     {
206         Some(make::ext::expr_ty_default(&make_ty(ty, ctx.sema.db, module)))
207     } else {
208         None
209     }
210 }
211
212 #[cfg(test)]
213 mod tests {
214     use crate::tests::{check_diagnostics, check_fix};
215
216     #[test]
217     fn missing_record_pat_field_diagnostic() {
218         check_diagnostics(
219             r#"
220 struct S { foo: i32, bar: () }
221 fn baz(s: S) {
222     let S { foo: _ } = s;
223       //^ ðŸ’¡ error: missing structure fields:
224       //| - bar
225 }
226 "#,
227         );
228     }
229
230     #[test]
231     fn missing_record_pat_field_no_diagnostic_if_not_exhaustive() {
232         check_diagnostics(
233             r"
234 struct S { foo: i32, bar: () }
235 fn baz(s: S) -> i32 {
236     match s {
237         S { foo, .. } => foo,
238     }
239 }
240 ",
241         )
242     }
243
244     #[test]
245     fn missing_record_pat_field_box() {
246         check_diagnostics(
247             r"
248 struct S { s: Box<u32> }
249 fn x(a: S) {
250     let S { box s } = a;
251 }
252 ",
253         )
254     }
255
256     #[test]
257     fn missing_record_pat_field_ref() {
258         check_diagnostics(
259             r"
260 struct S { s: u32 }
261 fn x(a: S) {
262     let S { ref s } = a;
263 }
264 ",
265         )
266     }
267
268     #[test]
269     fn range_mapping_out_of_macros() {
270         check_fix(
271             r#"
272 fn some() {}
273 fn items() {}
274 fn here() {}
275
276 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
277
278 fn main() {
279     let _x = id![Foo { a: $042 }];
280 }
281
282 pub struct Foo { pub a: i32, pub b: i32 }
283 "#,
284             r#"
285 fn some() {}
286 fn items() {}
287 fn here() {}
288
289 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
290
291 fn main() {
292     let _x = id![Foo {a:42, b: 0 }];
293 }
294
295 pub struct Foo { pub a: i32, pub b: i32 }
296 "#,
297         );
298     }
299
300     #[test]
301     fn test_fill_struct_fields_empty() {
302         check_fix(
303             r#"
304 //- minicore: option
305 struct TestStruct { one: i32, two: i64, three: Option<i32>, four: bool }
306
307 fn test_fn() {
308     let s = TestStruct {$0};
309 }
310 "#,
311             r#"
312 struct TestStruct { one: i32, two: i64, three: Option<i32>, four: bool }
313
314 fn test_fn() {
315     let s = TestStruct { one: 0, two: 0, three: None, four: false };
316 }
317 "#,
318         );
319     }
320
321     #[test]
322     fn test_fill_struct_fields_self() {
323         check_fix(
324             r#"
325 struct TestStruct { one: i32 }
326
327 impl TestStruct {
328     fn test_fn() { let s = Self {$0}; }
329 }
330 "#,
331             r#"
332 struct TestStruct { one: i32 }
333
334 impl TestStruct {
335     fn test_fn() { let s = Self { one: 0 }; }
336 }
337 "#,
338         );
339     }
340
341     #[test]
342     fn test_fill_struct_fields_enum() {
343         check_fix(
344             r#"
345 enum Expr {
346     Bin { lhs: Box<Expr>, rhs: Box<Expr> }
347 }
348
349 impl Expr {
350     fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
351         Expr::Bin {$0 }
352     }
353 }
354 "#,
355             r#"
356 enum Expr {
357     Bin { lhs: Box<Expr>, rhs: Box<Expr> }
358 }
359
360 impl Expr {
361     fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
362         Expr::Bin { lhs, rhs }
363     }
364 }
365 "#,
366         );
367     }
368
369     #[test]
370     fn test_fill_struct_fields_partial() {
371         check_fix(
372             r#"
373 struct TestStruct { one: i32, two: i64 }
374
375 fn test_fn() {
376     let s = TestStruct{ two: 2$0 };
377 }
378 "#,
379             r"
380 struct TestStruct { one: i32, two: i64 }
381
382 fn test_fn() {
383     let s = TestStruct{ two: 2, one: 0 };
384 }
385 ",
386         );
387     }
388
389     #[test]
390     fn test_fill_struct_fields_new() {
391         check_fix(
392             r#"
393 struct TestWithNew(usize);
394 impl TestWithNew {
395     pub fn new() -> Self {
396         Self(0)
397     }
398 }
399 struct TestStruct { one: i32, two: TestWithNew }
400
401 fn test_fn() {
402     let s = TestStruct{ $0 };
403 }
404 "#,
405             r"
406 struct TestWithNew(usize);
407 impl TestWithNew {
408     pub fn new() -> Self {
409         Self(0)
410     }
411 }
412 struct TestStruct { one: i32, two: TestWithNew }
413
414 fn test_fn() {
415     let s = TestStruct{ one: 0, two: TestWithNew::new()  };
416 }
417 ",
418         );
419     }
420
421     #[test]
422     fn test_fill_struct_fields_default() {
423         check_fix(
424             r#"
425 //- minicore: default, option
426 struct TestWithDefault(usize);
427 impl Default for TestWithDefault {
428     pub fn default() -> Self {
429         Self(0)
430     }
431 }
432 struct TestStruct { one: i32, two: TestWithDefault }
433
434 fn test_fn() {
435     let s = TestStruct{ $0 };
436 }
437 "#,
438             r"
439 struct TestWithDefault(usize);
440 impl Default for TestWithDefault {
441     pub fn default() -> Self {
442         Self(0)
443     }
444 }
445 struct TestStruct { one: i32, two: TestWithDefault }
446
447 fn test_fn() {
448     let s = TestStruct{ one: 0, two: TestWithDefault::default()  };
449 }
450 ",
451         );
452     }
453
454     #[test]
455     fn test_fill_struct_fields_raw_ident() {
456         check_fix(
457             r#"
458 struct TestStruct { r#type: u8 }
459
460 fn test_fn() {
461     TestStruct { $0 };
462 }
463 "#,
464             r"
465 struct TestStruct { r#type: u8 }
466
467 fn test_fn() {
468     TestStruct { r#type: 0  };
469 }
470 ",
471         );
472     }
473
474     #[test]
475     fn test_fill_struct_fields_no_diagnostic() {
476         check_diagnostics(
477             r#"
478 struct TestStruct { one: i32, two: i64 }
479
480 fn test_fn() {
481     let one = 1;
482     let s = TestStruct{ one, two: 2 };
483 }
484         "#,
485         );
486     }
487
488     #[test]
489     fn test_fill_struct_fields_no_diagnostic_on_spread() {
490         check_diagnostics(
491             r#"
492 struct TestStruct { one: i32, two: i64 }
493
494 fn test_fn() {
495     let one = 1;
496     let s = TestStruct{ ..a };
497 }
498 "#,
499         );
500     }
501
502     #[test]
503     fn test_fill_struct_fields_blank_line() {
504         check_fix(
505             r#"
506 struct S { a: (), b: () }
507
508 fn f() {
509     S {
510         $0
511     };
512 }
513 "#,
514             r#"
515 struct S { a: (), b: () }
516
517 fn f() {
518     S {
519         a: todo!(),
520         b: todo!(),
521     };
522 }
523 "#,
524         );
525     }
526
527     #[test]
528     fn test_fill_struct_fields_shorthand() {
529         cov_mark::check!(field_shorthand);
530         check_fix(
531             r#"
532 struct S { a: &'static str, b: i32 }
533
534 fn f() {
535     let a = "hello";
536     let b = 1i32;
537     S {
538         $0
539     };
540 }
541 "#,
542             r#"
543 struct S { a: &'static str, b: i32 }
544
545 fn f() {
546     let a = "hello";
547     let b = 1i32;
548     S {
549         a,
550         b,
551     };
552 }
553 "#,
554         );
555     }
556
557     #[test]
558     fn test_fill_struct_fields_shorthand_ty_mismatch() {
559         check_fix(
560             r#"
561 struct S { a: &'static str, b: i32 }
562
563 fn f() {
564     let a = "hello";
565     let b = 1usize;
566     S {
567         $0
568     };
569 }
570 "#,
571             r#"
572 struct S { a: &'static str, b: i32 }
573
574 fn f() {
575     let a = "hello";
576     let b = 1usize;
577     S {
578         a,
579         b: 0,
580     };
581 }
582 "#,
583         );
584     }
585
586     #[test]
587     fn test_fill_struct_fields_shorthand_unifies() {
588         check_fix(
589             r#"
590 struct S<T> { a: &'static str, b: T }
591
592 fn f() {
593     let a = "hello";
594     let b = 1i32;
595     S {
596         $0
597     };
598 }
599 "#,
600             r#"
601 struct S<T> { a: &'static str, b: T }
602
603 fn f() {
604     let a = "hello";
605     let b = 1i32;
606     S {
607         a,
608         b,
609     };
610 }
611 "#,
612         );
613     }
614
615     #[test]
616     fn test_fill_struct_pat_fields() {
617         check_fix(
618             r#"
619 struct S { a: &'static str, b: i32 }
620
621 fn f() {
622     let S {
623         $0
624     };
625 }
626 "#,
627             r#"
628 struct S { a: &'static str, b: i32 }
629
630 fn f() {
631     let S {
632         a,
633         b,
634     };
635 }
636 "#,
637         );
638     }
639
640     #[test]
641     fn test_fill_struct_pat_fields_partial() {
642         check_fix(
643             r#"
644 struct S { a: &'static str, b: i32 }
645
646 fn f() {
647     let S {
648         a,$0
649     };
650 }
651 "#,
652             r#"
653 struct S { a: &'static str, b: i32 }
654
655 fn f() {
656     let S {
657         a,
658         b,
659     };
660 }
661 "#,
662         );
663     }
664
665     #[test]
666     fn import_extern_crate_clash_with_inner_item() {
667         // This is more of a resolver test, but doesn't really work with the hir_def testsuite.
668
669         check_diagnostics(
670             r#"
671 //- /lib.rs crate:lib deps:jwt
672 mod permissions;
673
674 use permissions::jwt;
675
676 fn f() {
677     fn inner() {}
678     jwt::Claims {}; // should resolve to the local one with 0 fields, and not get a diagnostic
679 }
680
681 //- /permissions.rs
682 pub mod jwt  {
683     pub struct Claims {}
684 }
685
686 //- /jwt/lib.rs crate:jwt
687 pub struct Claims {
688     field: u8,
689 }
690         "#,
691         );
692     }
693 }