Skip to content

Commit 1338ddb

Browse files
committed
add: Adding self keyword completion in complete_fn_param
1 parent 10ac4e5 commit 1338ddb

File tree

1 file changed

+45
-7
lines changed

1 file changed

+45
-7
lines changed

crates/ide_completion/src/completions/fn_param.rs

Lines changed: 45 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,9 @@ use crate::{CompletionContext, CompletionItem, CompletionItemKind, CompletionKin
1212
/// functions in a file have a `spam: &mut Spam` parameter, a completion with
1313
/// `spam: &mut Spam` insert text/label and `spam` lookup string will be
1414
/// suggested.
15-
pub(crate) fn complete_fn_param(acc: &mut Completions, ctx: &CompletionContext) {
15+
pub(crate) fn complete_fn_param(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> {
1616
if !ctx.is_param {
17-
return;
17+
return None;
1818
}
1919

2020
let mut params = FxHashMap::default();
@@ -53,11 +53,27 @@ pub(crate) fn complete_fn_param(acc: &mut Completions, ctx: &CompletionContext)
5353
};
5454
}
5555

56-
params.into_iter().for_each(|(label, lookup)| {
57-
let mut item = CompletionItem::new(CompletionKind::Magic, ctx.source_range(), label);
58-
item.kind(CompletionItemKind::Binding).lookup_by(lookup);
59-
item.add_to(acc)
60-
});
56+
let self_completion_items = ["self", "&self", "mut self", "&mut self"];
57+
if ctx.impl_def.is_some() && me?.param_list()?.params().next().is_none() {
58+
self_completion_items.iter().for_each(|self_item| {
59+
add_new_item_to_acc(ctx, acc, self_item.to_string(), self_item.to_string())
60+
});
61+
}
62+
63+
params.into_iter().for_each(|(label, lookup)| add_new_item_to_acc(ctx, acc, label, lookup));
64+
65+
Some(())
66+
}
67+
68+
fn add_new_item_to_acc(
69+
ctx: &CompletionContext,
70+
acc: &mut Completions,
71+
label: String,
72+
lookup: String,
73+
) {
74+
let mut item = CompletionItem::new(CompletionKind::Magic, ctx.source_range(), label);
75+
item.kind(CompletionItemKind::Binding).lookup_by(lookup);
76+
item.add_to(acc)
6177
}
6278

6379
#[cfg(test)]
@@ -143,4 +159,26 @@ fn foo2($0) {}
143159
"#]],
144160
)
145161
}
162+
163+
#[test]
164+
fn test_param_completion_self_param() {
165+
check(
166+
r#"
167+
struct A {}
168+
169+
impl A {
170+
fn foo(file_id: FileId) {}
171+
fn new($0) {
172+
}
173+
}
174+
"#,
175+
expect![[r#"
176+
bn self
177+
bn &self
178+
bn mut self
179+
bn &mut self
180+
bn file_id: FileId
181+
"#]],
182+
)
183+
}
146184
}

0 commit comments

Comments
 (0)