Skip to content

Commit 9469076

Browse files
committed
Add shorthand field completion for record-expr
```rust struct Foo { bar: bool, n: i32 } fn baz() { let bar = true; let foo = Fo$0; } ``` **Before this PR**: ```rust struct Foo { bar: bool, n: i32 } fn baz() { let bar = true; let foo = Foo { bar: ${1:()}, n: ${2:()} }$0; } ``` **After this PR**: ```rust struct Foo { bar: bool, n: i32 } fn baz() { let bar = true; let foo = Foo { bar$1, n: ${2:()} }$0; } ```
1 parent b93180b commit 9469076

File tree

2 files changed

+40
-6
lines changed

2 files changed

+40
-6
lines changed

crates/ide-completion/src/completions/record.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,33 @@ fn baz() {
181181
)
182182
}
183183

184+
#[test]
185+
fn literal_struct_completion_shorthand() {
186+
check_edit(
187+
"FooDesc{}",
188+
r#"
189+
struct FooDesc { pub bar: bool, n: i32 }
190+
191+
fn create_foo(foo_desc: &FooDesc) -> () { () }
192+
193+
fn baz() {
194+
let bar = true;
195+
let foo = create_foo(&$0);
196+
}
197+
"#,
198+
r#"
199+
struct FooDesc { pub bar: bool, n: i32 }
200+
201+
fn create_foo(foo_desc: &FooDesc) -> () { () }
202+
203+
fn baz() {
204+
let bar = true;
205+
let foo = create_foo(&FooDesc { bar$1, n: ${2:()} }$0);
206+
}
207+
"#,
208+
)
209+
}
210+
184211
#[test]
185212
fn enum_variant_no_snippets() {
186213
let conf = CompletionConfig { snippet_cap: SnippetCap::new(false), ..TEST_CONFIG };

crates/ide-completion/src/render/variant.rs

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,14 +26,21 @@ pub(crate) fn render_record_lit(
2626
return RenderedLiteral { literal: path.to_owned(), detail: path.to_owned() };
2727
}
2828
let completions = fields.iter().enumerate().format_with(", ", |(idx, field), f| {
29+
let mut fmt_field = |fill, tab| {
30+
let field_name = field.name(ctx.db);
31+
32+
if let Some(local) = ctx.locals.get(&field_name)
33+
&& local.ty(ctx.db) == field.ty(ctx.db).to_type(ctx.db)
34+
{
35+
f(&format_args!("{}{tab}", field_name.display(ctx.db, ctx.edition)))
36+
} else {
37+
f(&format_args!("{}: {fill}", field_name.display(ctx.db, ctx.edition)))
38+
}
39+
};
2940
if snippet_cap.is_some() {
30-
f(&format_args!(
31-
"{}: ${{{}:()}}",
32-
field.name(ctx.db).display(ctx.db, ctx.edition),
33-
idx + 1
34-
))
41+
fmt_field(format_args!("${{{}:()}}", idx + 1), format_args!("${}", idx + 1))
3542
} else {
36-
f(&format_args!("{}: ()", field.name(ctx.db).display(ctx.db, ctx.edition)))
43+
fmt_field(format_args!("()"), format_args!(""))
3744
}
3845
});
3946

0 commit comments

Comments
 (0)