1 //! Complete fields in record literals and patterns.
2 use ide_db::{helpers::FamousDefs, SymbolKind};
6 item::CompletionKind, patterns::ImmediateLocation, CompletionContext, CompletionItem,
10 pub(crate) fn complete_record(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> {
11 let missing_fields = match &ctx.completion_location {
12 Some(ImmediateLocation::RecordExpr(record_expr)) => {
13 let ty = ctx.sema.type_of_expr(&Expr::RecordExpr(record_expr.clone()));
14 let default_trait = FamousDefs(&ctx.sema, ctx.krate).core_default_Default();
15 let impl_default_trait = default_trait.zip(ty).map_or(false, |(default_trait, ty)| {
16 ty.original.impls_trait(ctx.db, default_trait, &[])
19 let missing_fields = ctx.sema.record_literal_missing_fields(record_expr);
20 if impl_default_trait && !missing_fields.is_empty() {
21 let completion_text = "..Default::default()";
22 let mut item = CompletionItem::new(
23 CompletionKind::Snippet,
28 completion_text.strip_prefix(ctx.token.text()).unwrap_or(completion_text);
29 item.insert_text(completion_text).kind(SymbolKind::Field);
35 Some(ImmediateLocation::RecordPat(record_pat)) => {
36 ctx.sema.record_pattern_missing_fields(record_pat)
41 for (field, ty) in missing_fields {
42 acc.add_field(ctx, None, field, &ty);
48 pub(crate) fn complete_record_literal(
49 acc: &mut Completions,
50 ctx: &CompletionContext,
52 if !ctx.expects_expression() {
56 if let hir::Adt::Struct(strukt) = ctx.expected_type.as_ref()?.as_adt()? {
57 acc.add_struct_literal(ctx, strukt, None);
65 use crate::tests::check_edit;
68 fn literal_struct_completion_edit() {
72 struct FooDesc { pub bar: bool }
74 fn create_foo(foo_desc: &FooDesc) -> () { () }
77 let foo = create_foo(&$0);
81 struct FooDesc { pub bar: bool }
83 fn create_foo(foo_desc: &FooDesc) -> () { () }
86 let foo = create_foo(&FooDesc { bar: ${1:()} }$0);
93 fn literal_struct_complexion_module() {
98 pub struct FooDesc { pub six: bool, pub neuf: Vec<String>, pub bar: bool }
99 pub fn create_foo(foo_desc: &FooDesc) -> () { () }
105 let foo = create_foo(&$0);
110 pub struct FooDesc { pub six: bool, pub neuf: Vec<String>, pub bar: bool }
111 pub fn create_foo(foo_desc: &FooDesc) -> () { () }
117 let foo = create_foo(&FooDesc { six: ${1:()}, neuf: ${2:()}, bar: ${3:()} }$0);
124 fn default_completion_edit() {
126 "..Default::default()",
128 //- minicore: default
129 struct Struct { foo: u32, bar: usize }
131 impl Default for Struct {
132 fn default() -> Self {}
143 struct Struct { foo: u32, bar: usize }
145 impl Default for Struct {
146 fn default() -> Self {}
158 "..Default::default()",
160 //- minicore: default
161 struct Struct { foo: u32, bar: usize }
163 impl Default for Struct {
164 fn default() -> Self {}
175 struct Struct { foo: u32, bar: usize }
177 impl Default for Struct {
178 fn default() -> Self {}