1 //! See [`complete_fn_param`].
3 use rustc_hash::FxHashMap;
5 ast::{self, HasModuleItem},
10 context::{ParamKind, PatternContext},
11 CompletionContext, CompletionItem, CompletionItemKind, CompletionKind, Completions,
14 /// Complete repeated parameters, both name and type. For example, if all
15 /// functions in a file have a `spam: &mut Spam` parameter, a completion with
16 /// `spam: &mut Spam` insert text/label and `spam` lookup string will be
18 pub(crate) fn complete_fn_param(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> {
19 if !matches!(ctx.pattern_ctx, Some(PatternContext { is_param: Some(ParamKind::Function), .. }))
24 let mut params = FxHashMap::default();
26 let me = ctx.token.ancestors().find_map(ast::Fn::cast);
27 let mut process_fn = |func: ast::Fn| {
28 if Some(&func) == me.as_ref() {
31 func.param_list().into_iter().flat_map(|it| it.params()).for_each(|param| {
32 if let Some(pat) = param.pat() {
33 let text = param.syntax().text().to_string();
34 let lookup = pat.syntax().text().to_string();
35 params.entry(text).or_insert(lookup);
40 for node in ctx.token.ancestors() {
43 ast::SourceFile(it) => it.items().filter_map(|item| match item {
44 ast::Item::Fn(it) => Some(it),
46 }).for_each(&mut process_fn),
47 ast::ItemList(it) => it.items().filter_map(|item| match item {
48 ast::Item::Fn(it) => Some(it),
50 }).for_each(&mut process_fn),
51 ast::AssocItemList(it) => it.assoc_items().filter_map(|item| match item {
52 ast::AssocItem::Fn(it) => Some(it),
54 }).for_each(&mut process_fn),
60 let self_completion_items = ["self", "&self", "mut self", "&mut self"];
61 if ctx.impl_def.is_some() && me?.param_list()?.params().next().is_none() {
62 self_completion_items.iter().for_each(|self_item| {
63 add_new_item_to_acc(ctx, acc, self_item.to_string(), self_item.to_string())
67 params.into_iter().for_each(|(label, lookup)| add_new_item_to_acc(ctx, acc, label, lookup));
72 fn add_new_item_to_acc(
73 ctx: &CompletionContext,
74 acc: &mut Completions,
78 let mut item = CompletionItem::new(CompletionKind::Magic, ctx.source_range(), label);
79 item.kind(CompletionItemKind::Binding).lookup_by(lookup);