]> git.lizzy.rs Git - rust.git/blob - crates/ide_diagnostics/src/handlers/missing_fields.rs
add better default behavior on fill struct fields diagnostic
[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, helpers::FamousDefs, source_change::SourceChange};
7 use rustc_hash::FxHashMap;
8 use stdx::format_to;
9 use syntax::{
10     algo,
11     ast::{self, make},
12     AstNode, SyntaxNodePtr,
13 };
14 use text_edit::TextEdit;
15
16 use crate::{fix, Diagnostic, DiagnosticsContext};
17
18 // Diagnostic: missing-fields
19 //
20 // This diagnostic is triggered if record lacks some fields that exist in the corresponding structure.
21 //
22 // Example:
23 //
24 // ```rust
25 // struct A { a: u8, b: u8 }
26 //
27 // let a = A { a: 10 };
28 // ```
29 pub(crate) fn missing_fields(ctx: &DiagnosticsContext<'_>, d: &hir::MissingFields) -> Diagnostic {
30     let mut message = String::from("missing structure fields:\n");
31     for field in &d.missed_fields {
32         format_to!(message, "- {}\n", field);
33     }
34
35     let ptr = InFile::new(
36         d.file,
37         d.field_list_parent_path
38             .clone()
39             .map(SyntaxNodePtr::from)
40             .unwrap_or_else(|| d.field_list_parent.clone().either(|it| it.into(), |it| it.into())),
41     );
42
43     Diagnostic::new("missing-fields", message, ctx.sema.diagnostics_display_range(ptr).range)
44         .with_fixes(fixes(ctx, d))
45 }
46
47 fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::MissingFields) -> Option<Vec<Assist>> {
48     // Note that although we could add a diagnostics to
49     // fill the missing tuple field, e.g :
50     // `struct A(usize);`
51     // `let a = A { 0: () }`
52     // but it is uncommon usage and it should not be encouraged.
53     if d.missed_fields.iter().any(|it| it.as_tuple_index().is_some()) {
54         return None;
55     }
56
57     let root = ctx.sema.db.parse_or_expand(d.file)?;
58     let field_list_parent = match &d.field_list_parent {
59         Either::Left(record_expr) => record_expr.to_node(&root),
60         // FIXE: patterns should be fixable as well.
61         Either::Right(_) => return None,
62     };
63     let old_field_list = field_list_parent.record_expr_field_list()?;
64
65     let new_field_list = old_field_list.clone_for_update();
66     let mut locals = FxHashMap::default();
67     ctx.sema.scope(field_list_parent.syntax()).process_all_names(&mut |name, def| {
68         if let hir::ScopeDef::Local(local) = def {
69             locals.insert(name, local);
70         }
71     });
72     let missing_fields = ctx.sema.record_literal_missing_fields(&field_list_parent);
73
74     let generate_fill_expr = |ty: &Type| match ctx.config.expr_fill_default {
75         crate::ExprFillDefaultMode::Todo => Some(make::ext::expr_todo()),
76         crate::ExprFillDefaultMode::DefaultImpl => {
77             let default_constr = get_default_constructor(ctx, d, ty);
78             match default_constr {
79                 Some(default_constr) => Some(default_constr),
80                 _ => Some(make::ext::expr_todo()),
81             }
82         }
83     };
84
85     for (f, ty) in missing_fields.iter() {
86         let field_expr = if let Some(local_candidate) = locals.get(&f.name(ctx.sema.db)) {
87             cov_mark::hit!(field_shorthand);
88             let candidate_ty = local_candidate.ty(ctx.sema.db);
89             if ty.could_unify_with(ctx.sema.db, &candidate_ty) {
90                 None
91             } else {
92                 generate_fill_expr(ty)
93             }
94         } else {
95             generate_fill_expr(ty)
96         };
97         let field =
98             make::record_expr_field(make::name_ref(&f.name(ctx.sema.db).to_smol_str()), field_expr)
99                 .clone_for_update();
100         new_field_list.add_field(field);
101     }
102
103     let mut builder = TextEdit::builder();
104     if d.file.is_macro() {
105         // we can't map the diff up into the macro input unfortunately, as the macro loses all
106         // whitespace information so the diff wouldn't be applicable no matter what
107         // This has the downside that the cursor will be moved in macros by doing it without a diff
108         // but that is a trade off we can make.
109         // FIXE: this also currently discards a lot of whitespace in the input... we really need a formatter here
110         let range = ctx.sema.original_range_opt(old_field_list.syntax())?;
111         builder.replace(range.range, new_field_list.to_string());
112     } else {
113         algo::diff(old_field_list.syntax(), new_field_list.syntax()).into_text_edit(&mut builder);
114     }
115     let edit = builder.finish();
116     Some(vec![fix(
117         "fill_missing_fields",
118         "Fill struct fields",
119         SourceChange::from_text_edit(d.file.original_file(ctx.sema.db), edit),
120         ctx.sema.original_range(field_list_parent.syntax()).range,
121     )])
122 }
123
124 fn make_ty(ty: &hir::Type, db: &dyn HirDatabase, module: hir::Module) -> ast::Type {
125     let ty_str = match ty.as_adt() {
126         Some(adt) => adt.name(db).to_string(),
127         None => ty.display_source_code(db, module.into()).ok().unwrap_or_else(|| "_".to_string()),
128     };
129
130     make::ty(&ty_str)
131 }
132
133 fn get_default_constructor(
134     ctx: &DiagnosticsContext<'_>,
135     d: &hir::MissingFields,
136     ty: &Type,
137 ) -> Option<ast::Expr> {
138     if let Some(builtin_ty) = ty.as_builtin() {
139         if builtin_ty.is_int() || builtin_ty.is_uint() {
140             return Some(make::ext::zero_number());
141         }
142         if builtin_ty.is_float() {
143             return Some(make::ext::zero_float());
144         }
145         if builtin_ty.is_char() {
146             return Some(make::ext::empty_char());
147         }
148         if builtin_ty.is_str() {
149             return Some(make::ext::empty_str());
150         }
151     }
152
153     let krate = ctx.sema.to_module_def(d.file.original_file(ctx.sema.db))?.krate();
154     let module = krate.root_module(ctx.sema.db);
155
156     // Look for a ::new() associated function
157     let has_new_func = ty
158         .iterate_assoc_items(ctx.sema.db, krate, |assoc_item| {
159             if let AssocItem::Function(func) = assoc_item {
160                 if func.name(ctx.sema.db) == known::new
161                     && func.assoc_fn_params(ctx.sema.db).is_empty()
162                     && func.self_param(ctx.sema.db).is_none()
163                 {
164                     return Some(());
165                 }
166             }
167
168             None
169         })
170         .is_some();
171
172     if has_new_func {
173         Some(make::ext::expr_ty_new(&make_ty(ty, ctx.sema.db, module)))
174     } else if !ty.is_array()
175         && ty.impls_trait(
176             ctx.sema.db,
177             FamousDefs(&ctx.sema, Some(krate)).core_default_Default()?,
178             &[],
179         )
180     {
181         Some(make::ext::expr_ty_default(&make_ty(ty, ctx.sema.db, module)))
182     } else {
183         None
184     }
185 }
186
187 #[cfg(test)]
188 mod tests {
189     use crate::tests::{check_diagnostics, check_fix};
190
191     #[test]
192     fn missing_record_pat_field_diagnostic() {
193         check_diagnostics(
194             r#"
195 struct S { foo: i32, bar: () }
196 fn baz(s: S) {
197     let S { foo: _ } = s;
198       //^ error: missing structure fields:
199       //| - bar
200 }
201 "#,
202         );
203     }
204
205     #[test]
206     fn missing_record_pat_field_no_diagnostic_if_not_exhaustive() {
207         check_diagnostics(
208             r"
209 struct S { foo: i32, bar: () }
210 fn baz(s: S) -> i32 {
211     match s {
212         S { foo, .. } => foo,
213     }
214 }
215 ",
216         )
217     }
218
219     #[test]
220     fn missing_record_pat_field_box() {
221         check_diagnostics(
222             r"
223 struct S { s: Box<u32> }
224 fn x(a: S) {
225     let S { box s } = a;
226 }
227 ",
228         )
229     }
230
231     #[test]
232     fn missing_record_pat_field_ref() {
233         check_diagnostics(
234             r"
235 struct S { s: u32 }
236 fn x(a: S) {
237     let S { ref s } = a;
238 }
239 ",
240         )
241     }
242
243     #[test]
244     fn range_mapping_out_of_macros() {
245         check_fix(
246             r#"
247 fn some() {}
248 fn items() {}
249 fn here() {}
250
251 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
252
253 fn main() {
254     let _x = id![Foo { a: $042 }];
255 }
256
257 pub struct Foo { pub a: i32, pub b: i32 }
258 "#,
259             r#"
260 fn some() {}
261 fn items() {}
262 fn here() {}
263
264 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
265
266 fn main() {
267     let _x = id![Foo {a:42, b: 0 }];
268 }
269
270 pub struct Foo { pub a: i32, pub b: i32 }
271 "#,
272         );
273     }
274
275     #[test]
276     fn test_fill_struct_fields_empty() {
277         check_fix(
278             r#"
279 struct TestStruct { one: i32, two: i64 }
280
281 fn test_fn() {
282     let s = TestStruct {$0};
283 }
284 "#,
285             r#"
286 struct TestStruct { one: i32, two: i64 }
287
288 fn test_fn() {
289     let s = TestStruct { one: 0, two: 0 };
290 }
291 "#,
292         );
293     }
294
295     #[test]
296     fn test_fill_struct_fields_self() {
297         check_fix(
298             r#"
299 struct TestStruct { one: i32 }
300
301 impl TestStruct {
302     fn test_fn() { let s = Self {$0}; }
303 }
304 "#,
305             r#"
306 struct TestStruct { one: i32 }
307
308 impl TestStruct {
309     fn test_fn() { let s = Self { one: 0 }; }
310 }
311 "#,
312         );
313     }
314
315     #[test]
316     fn test_fill_struct_fields_enum() {
317         check_fix(
318             r#"
319 enum Expr {
320     Bin { lhs: Box<Expr>, rhs: Box<Expr> }
321 }
322
323 impl Expr {
324     fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
325         Expr::Bin {$0 }
326     }
327 }
328 "#,
329             r#"
330 enum Expr {
331     Bin { lhs: Box<Expr>, rhs: Box<Expr> }
332 }
333
334 impl Expr {
335     fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
336         Expr::Bin { lhs, rhs }
337     }
338 }
339 "#,
340         );
341     }
342
343     #[test]
344     fn test_fill_struct_fields_partial() {
345         check_fix(
346             r#"
347 struct TestStruct { one: i32, two: i64 }
348
349 fn test_fn() {
350     let s = TestStruct{ two: 2$0 };
351 }
352 "#,
353             r"
354 struct TestStruct { one: i32, two: i64 }
355
356 fn test_fn() {
357     let s = TestStruct{ two: 2, one: 0 };
358 }
359 ",
360         );
361     }
362
363     #[test]
364     fn test_fill_struct_fields_new() {
365         check_fix(
366             r#"
367 struct TestWithNew(usize);
368 impl TestWithNew {
369     pub fn new() -> Self {
370         Self(0)
371     }
372 }
373 struct TestStruct { one: i32, two: TestWithNew }
374
375 fn test_fn() {
376     let s = TestStruct{ $0 };
377 }
378 "#,
379             r"
380 struct TestWithNew(usize);
381 impl TestWithNew {
382     pub fn new() -> Self {
383         Self(0)
384     }
385 }
386 struct TestStruct { one: i32, two: TestWithNew }
387
388 fn test_fn() {
389     let s = TestStruct{ one: 0, two: TestWithNew::new()  };
390 }
391 ",
392         );
393     }
394
395     #[test]
396     fn test_fill_struct_fields_default() {
397         check_fix(
398             r#"
399 //- minicore: default
400 struct TestWithDefault(usize);
401 impl Default for TestWithDefault {
402     pub fn default() -> Self {
403         Self(0)
404     }
405 }
406 struct TestStruct { one: i32, two: TestWithDefault }
407
408 fn test_fn() {
409     let s = TestStruct{ $0 };
410 }
411 "#,
412             r"
413 struct TestWithDefault(usize);
414 impl Default for TestWithDefault {
415     pub fn default() -> Self {
416         Self(0)
417     }
418 }
419 struct TestStruct { one: i32, two: TestWithDefault }
420
421 fn test_fn() {
422     let s = TestStruct{ one: 0, two: TestWithDefault::default()  };
423 }
424 ",
425         );
426     }
427
428     #[test]
429     fn test_fill_struct_fields_raw_ident() {
430         check_fix(
431             r#"
432 struct TestStruct { r#type: u8 }
433
434 fn test_fn() {
435     TestStruct { $0 };
436 }
437 "#,
438             r"
439 struct TestStruct { r#type: u8 }
440
441 fn test_fn() {
442     TestStruct { r#type: 0  };
443 }
444 ",
445         );
446     }
447
448     #[test]
449     fn test_fill_struct_fields_no_diagnostic() {
450         check_diagnostics(
451             r#"
452 struct TestStruct { one: i32, two: i64 }
453
454 fn test_fn() {
455     let one = 1;
456     let s = TestStruct{ one, two: 2 };
457 }
458         "#,
459         );
460     }
461
462     #[test]
463     fn test_fill_struct_fields_no_diagnostic_on_spread() {
464         check_diagnostics(
465             r#"
466 struct TestStruct { one: i32, two: i64 }
467
468 fn test_fn() {
469     let one = 1;
470     let s = TestStruct{ ..a };
471 }
472 "#,
473         );
474     }
475
476     #[test]
477     fn test_fill_struct_fields_blank_line() {
478         check_fix(
479             r#"
480 struct S { a: (), b: () }
481
482 fn f() {
483     S {
484         $0
485     };
486 }
487 "#,
488             r#"
489 struct S { a: (), b: () }
490
491 fn f() {
492     S {
493         a: todo!(),
494         b: todo!(),
495     };
496 }
497 "#,
498         );
499     }
500
501     #[test]
502     fn test_fill_struct_fields_shorthand() {
503         cov_mark::check!(field_shorthand);
504         check_fix(
505             r#"
506 struct S { a: &'static str, b: i32 }
507
508 fn f() {
509     let a = "hello";
510     let b = 1i32;
511     S {
512         $0
513     };
514 }
515 "#,
516             r#"
517 struct S { a: &'static str, b: i32 }
518
519 fn f() {
520     let a = "hello";
521     let b = 1i32;
522     S {
523         a,
524         b,
525     };
526 }
527 "#,
528         );
529     }
530
531     #[test]
532     fn test_fill_struct_fields_shorthand_ty_mismatch() {
533         check_fix(
534             r#"
535 struct S { a: &'static str, b: i32 }
536
537 fn f() {
538     let a = "hello";
539     let b = 1usize;
540     S {
541         $0
542     };
543 }
544 "#,
545             r#"
546 struct S { a: &'static str, b: i32 }
547
548 fn f() {
549     let a = "hello";
550     let b = 1usize;
551     S {
552         a,
553         b: 0,
554     };
555 }
556 "#,
557         );
558     }
559
560     #[test]
561     fn test_fill_struct_fields_shorthand_unifies() {
562         check_fix(
563             r#"
564 struct S<T> { a: &'static str, b: T }
565
566 fn f() {
567     let a = "hello";
568     let b = 1i32;
569     S {
570         $0
571     };
572 }
573 "#,
574             r#"
575 struct S<T> { a: &'static str, b: T }
576
577 fn f() {
578     let a = "hello";
579     let b = 1i32;
580     S {
581         a,
582         b,
583     };
584 }
585 "#,
586         );
587     }
588
589     #[test]
590     fn import_extern_crate_clash_with_inner_item() {
591         // This is more of a resolver test, but doesn't really work with the hir_def testsuite.
592
593         check_diagnostics(
594             r#"
595 //- /lib.rs crate:lib deps:jwt
596 mod permissions;
597
598 use permissions::jwt;
599
600 fn f() {
601     fn inner() {}
602     jwt::Claims {}; // should resolve to the local one with 0 fields, and not get a diagnostic
603 }
604
605 //- /permissions.rs
606 pub mod jwt  {
607     pub struct Claims {}
608 }
609
610 //- /jwt/lib.rs crate:jwt
611 pub struct Claims {
612     field: u8,
613 }
614         "#,
615         );
616     }
617 }