]> git.lizzy.rs Git - rust.git/blob - crates/ide-diagnostics/src/handlers/missing_fields.rs
Auto merge of #12120 - iDawer:ide.sig_help, 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     }
176
177     let krate = ctx.sema.to_module_def(d.file.original_file(ctx.sema.db))?.krate();
178     let module = krate.root_module(ctx.sema.db);
179
180     // Look for a ::new() associated function
181     let has_new_func = ty
182         .iterate_assoc_items(ctx.sema.db, krate, |assoc_item| {
183             if let AssocItem::Function(func) = assoc_item {
184                 if func.name(ctx.sema.db) == known::new
185                     && func.assoc_fn_params(ctx.sema.db).is_empty()
186                 {
187                     return Some(());
188                 }
189             }
190
191             None
192         })
193         .is_some();
194
195     if has_new_func {
196         Some(make::ext::expr_ty_new(&make_ty(ty, ctx.sema.db, module)))
197     } else if !ty.is_array()
198         && ty.impls_trait(ctx.sema.db, FamousDefs(&ctx.sema, krate).core_default_Default()?, &[])
199     {
200         Some(make::ext::expr_ty_default(&make_ty(ty, ctx.sema.db, module)))
201     } else {
202         None
203     }
204 }
205
206 #[cfg(test)]
207 mod tests {
208     use crate::tests::{check_diagnostics, check_fix};
209
210     #[test]
211     fn missing_record_pat_field_diagnostic() {
212         check_diagnostics(
213             r#"
214 struct S { foo: i32, bar: () }
215 fn baz(s: S) {
216     let S { foo: _ } = s;
217       //^ ðŸ’¡ error: missing structure fields:
218       //| - bar
219 }
220 "#,
221         );
222     }
223
224     #[test]
225     fn missing_record_pat_field_no_diagnostic_if_not_exhaustive() {
226         check_diagnostics(
227             r"
228 struct S { foo: i32, bar: () }
229 fn baz(s: S) -> i32 {
230     match s {
231         S { foo, .. } => foo,
232     }
233 }
234 ",
235         )
236     }
237
238     #[test]
239     fn missing_record_pat_field_box() {
240         check_diagnostics(
241             r"
242 struct S { s: Box<u32> }
243 fn x(a: S) {
244     let S { box s } = a;
245 }
246 ",
247         )
248     }
249
250     #[test]
251     fn missing_record_pat_field_ref() {
252         check_diagnostics(
253             r"
254 struct S { s: u32 }
255 fn x(a: S) {
256     let S { ref s } = a;
257 }
258 ",
259         )
260     }
261
262     #[test]
263     fn range_mapping_out_of_macros() {
264         check_fix(
265             r#"
266 fn some() {}
267 fn items() {}
268 fn here() {}
269
270 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
271
272 fn main() {
273     let _x = id![Foo { a: $042 }];
274 }
275
276 pub struct Foo { pub a: i32, pub b: i32 }
277 "#,
278             r#"
279 fn some() {}
280 fn items() {}
281 fn here() {}
282
283 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
284
285 fn main() {
286     let _x = id![Foo {a:42, b: 0 }];
287 }
288
289 pub struct Foo { pub a: i32, pub b: i32 }
290 "#,
291         );
292     }
293
294     #[test]
295     fn test_fill_struct_fields_empty() {
296         check_fix(
297             r#"
298 struct TestStruct { one: i32, two: i64 }
299
300 fn test_fn() {
301     let s = TestStruct {$0};
302 }
303 "#,
304             r#"
305 struct TestStruct { one: i32, two: i64 }
306
307 fn test_fn() {
308     let s = TestStruct { one: 0, two: 0 };
309 }
310 "#,
311         );
312     }
313
314     #[test]
315     fn test_fill_struct_fields_self() {
316         check_fix(
317             r#"
318 struct TestStruct { one: i32 }
319
320 impl TestStruct {
321     fn test_fn() { let s = Self {$0}; }
322 }
323 "#,
324             r#"
325 struct TestStruct { one: i32 }
326
327 impl TestStruct {
328     fn test_fn() { let s = Self { one: 0 }; }
329 }
330 "#,
331         );
332     }
333
334     #[test]
335     fn test_fill_struct_fields_enum() {
336         check_fix(
337             r#"
338 enum Expr {
339     Bin { lhs: Box<Expr>, rhs: Box<Expr> }
340 }
341
342 impl Expr {
343     fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
344         Expr::Bin {$0 }
345     }
346 }
347 "#,
348             r#"
349 enum Expr {
350     Bin { lhs: Box<Expr>, rhs: Box<Expr> }
351 }
352
353 impl Expr {
354     fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
355         Expr::Bin { lhs, rhs }
356     }
357 }
358 "#,
359         );
360     }
361
362     #[test]
363     fn test_fill_struct_fields_partial() {
364         check_fix(
365             r#"
366 struct TestStruct { one: i32, two: i64 }
367
368 fn test_fn() {
369     let s = TestStruct{ two: 2$0 };
370 }
371 "#,
372             r"
373 struct TestStruct { one: i32, two: i64 }
374
375 fn test_fn() {
376     let s = TestStruct{ two: 2, one: 0 };
377 }
378 ",
379         );
380     }
381
382     #[test]
383     fn test_fill_struct_fields_new() {
384         check_fix(
385             r#"
386 struct TestWithNew(usize);
387 impl TestWithNew {
388     pub fn new() -> Self {
389         Self(0)
390     }
391 }
392 struct TestStruct { one: i32, two: TestWithNew }
393
394 fn test_fn() {
395     let s = TestStruct{ $0 };
396 }
397 "#,
398             r"
399 struct TestWithNew(usize);
400 impl TestWithNew {
401     pub fn new() -> Self {
402         Self(0)
403     }
404 }
405 struct TestStruct { one: i32, two: TestWithNew }
406
407 fn test_fn() {
408     let s = TestStruct{ one: 0, two: TestWithNew::new()  };
409 }
410 ",
411         );
412     }
413
414     #[test]
415     fn test_fill_struct_fields_default() {
416         check_fix(
417             r#"
418 //- minicore: default
419 struct TestWithDefault(usize);
420 impl Default for TestWithDefault {
421     pub fn default() -> Self {
422         Self(0)
423     }
424 }
425 struct TestStruct { one: i32, two: TestWithDefault }
426
427 fn test_fn() {
428     let s = TestStruct{ $0 };
429 }
430 "#,
431             r"
432 struct TestWithDefault(usize);
433 impl Default for TestWithDefault {
434     pub fn default() -> Self {
435         Self(0)
436     }
437 }
438 struct TestStruct { one: i32, two: TestWithDefault }
439
440 fn test_fn() {
441     let s = TestStruct{ one: 0, two: TestWithDefault::default()  };
442 }
443 ",
444         );
445     }
446
447     #[test]
448     fn test_fill_struct_fields_raw_ident() {
449         check_fix(
450             r#"
451 struct TestStruct { r#type: u8 }
452
453 fn test_fn() {
454     TestStruct { $0 };
455 }
456 "#,
457             r"
458 struct TestStruct { r#type: u8 }
459
460 fn test_fn() {
461     TestStruct { r#type: 0  };
462 }
463 ",
464         );
465     }
466
467     #[test]
468     fn test_fill_struct_fields_no_diagnostic() {
469         check_diagnostics(
470             r#"
471 struct TestStruct { one: i32, two: i64 }
472
473 fn test_fn() {
474     let one = 1;
475     let s = TestStruct{ one, two: 2 };
476 }
477         "#,
478         );
479     }
480
481     #[test]
482     fn test_fill_struct_fields_no_diagnostic_on_spread() {
483         check_diagnostics(
484             r#"
485 struct TestStruct { one: i32, two: i64 }
486
487 fn test_fn() {
488     let one = 1;
489     let s = TestStruct{ ..a };
490 }
491 "#,
492         );
493     }
494
495     #[test]
496     fn test_fill_struct_fields_blank_line() {
497         check_fix(
498             r#"
499 struct S { a: (), b: () }
500
501 fn f() {
502     S {
503         $0
504     };
505 }
506 "#,
507             r#"
508 struct S { a: (), b: () }
509
510 fn f() {
511     S {
512         a: todo!(),
513         b: todo!(),
514     };
515 }
516 "#,
517         );
518     }
519
520     #[test]
521     fn test_fill_struct_fields_shorthand() {
522         cov_mark::check!(field_shorthand);
523         check_fix(
524             r#"
525 struct S { a: &'static str, b: i32 }
526
527 fn f() {
528     let a = "hello";
529     let b = 1i32;
530     S {
531         $0
532     };
533 }
534 "#,
535             r#"
536 struct S { a: &'static str, b: i32 }
537
538 fn f() {
539     let a = "hello";
540     let b = 1i32;
541     S {
542         a,
543         b,
544     };
545 }
546 "#,
547         );
548     }
549
550     #[test]
551     fn test_fill_struct_fields_shorthand_ty_mismatch() {
552         check_fix(
553             r#"
554 struct S { a: &'static str, b: i32 }
555
556 fn f() {
557     let a = "hello";
558     let b = 1usize;
559     S {
560         $0
561     };
562 }
563 "#,
564             r#"
565 struct S { a: &'static str, b: i32 }
566
567 fn f() {
568     let a = "hello";
569     let b = 1usize;
570     S {
571         a,
572         b: 0,
573     };
574 }
575 "#,
576         );
577     }
578
579     #[test]
580     fn test_fill_struct_fields_shorthand_unifies() {
581         check_fix(
582             r#"
583 struct S<T> { a: &'static str, b: T }
584
585 fn f() {
586     let a = "hello";
587     let b = 1i32;
588     S {
589         $0
590     };
591 }
592 "#,
593             r#"
594 struct S<T> { a: &'static str, b: T }
595
596 fn f() {
597     let a = "hello";
598     let b = 1i32;
599     S {
600         a,
601         b,
602     };
603 }
604 "#,
605         );
606     }
607
608     #[test]
609     fn test_fill_struct_pat_fields() {
610         check_fix(
611             r#"
612 struct S { a: &'static str, b: i32 }
613
614 fn f() {
615     let S {
616         $0
617     };
618 }
619 "#,
620             r#"
621 struct S { a: &'static str, b: i32 }
622
623 fn f() {
624     let S {
625         a,
626         b,
627     };
628 }
629 "#,
630         );
631     }
632
633     #[test]
634     fn test_fill_struct_pat_fields_partial() {
635         check_fix(
636             r#"
637 struct S { a: &'static str, b: i32 }
638
639 fn f() {
640     let S {
641         a,$0
642     };
643 }
644 "#,
645             r#"
646 struct S { a: &'static str, b: i32 }
647
648 fn f() {
649     let S {
650         a,
651         b,
652     };
653 }
654 "#,
655         );
656     }
657
658     #[test]
659     fn import_extern_crate_clash_with_inner_item() {
660         // This is more of a resolver test, but doesn't really work with the hir_def testsuite.
661
662         check_diagnostics(
663             r#"
664 //- /lib.rs crate:lib deps:jwt
665 mod permissions;
666
667 use permissions::jwt;
668
669 fn f() {
670     fn inner() {}
671     jwt::Claims {}; // should resolve to the local one with 0 fields, and not get a diagnostic
672 }
673
674 //- /permissions.rs
675 pub mod jwt  {
676     pub struct Claims {}
677 }
678
679 //- /jwt/lib.rs crate:jwt
680 pub struct Claims {
681     field: u8,
682 }
683         "#,
684         );
685     }
686 }