81 lines
2.7 KiB
Rust
Raw Normal View History

2020-07-10 16:07:12 +02:00
//! See `complete_fn_param`.
2020-08-12 18:26:51 +02:00
use rustc_hash::FxHashMap;
use syntax::{
2020-04-09 23:02:10 +02:00
ast::{self, ModuleItemOwner},
match_ast, AstNode,
};
2019-01-08 22:33:36 +03:00
use crate::{
context::ParamKind, CompletionContext, CompletionItem, CompletionItemKind, CompletionKind,
Completions,
};
2019-01-08 22:33:36 +03:00
2019-02-11 17:18:27 +01:00
/// Complete repeated parameters, both name and type. For example, if all
2019-01-08 22:33:36 +03:00
/// functions in a file have a `spam: &mut Spam` parameter, a completion with
/// `spam: &mut Spam` insert text/label and `spam` lookup string will be
/// suggested.
pub(crate) fn complete_fn_param(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> {
if ctx.is_param != Some(ParamKind::Function) {
return None;
2019-01-08 22:33:36 +03:00
}
let mut params = FxHashMap::default();
2020-07-30 11:42:51 +02:00
2020-07-30 14:51:08 +02:00
let me = ctx.token.ancestors().find_map(ast::Fn::cast);
let mut process_fn = |func: ast::Fn| {
2020-07-30 11:42:51 +02:00
if Some(&func) == me.as_ref() {
return;
}
func.param_list().into_iter().flat_map(|it| it.params()).for_each(|param| {
if let Some(pat) = param.pat() {
let text = param.syntax().text().to_string();
let lookup = pat.syntax().text().to_string();
params.entry(text).or_insert(lookup);
}
});
2020-07-30 11:42:51 +02:00
};
for node in ctx.token.ancestors() {
2020-07-30 11:42:51 +02:00
match_ast! {
2019-10-05 17:03:03 +03:00
match node {
2020-07-30 11:42:51 +02:00
ast::SourceFile(it) => it.items().filter_map(|item| match item {
2020-07-30 14:51:08 +02:00
ast::Item::Fn(it) => Some(it),
2020-07-30 11:42:51 +02:00
_ => None,
}).for_each(&mut process_fn),
ast::ItemList(it) => it.items().filter_map(|item| match item {
2020-07-30 14:51:08 +02:00
ast::Item::Fn(it) => Some(it),
2020-07-30 11:42:51 +02:00
_ => None,
}).for_each(&mut process_fn),
ast::AssocItemList(it) => it.assoc_items().filter_map(|item| match item {
2020-07-30 14:51:08 +02:00
ast::AssocItem::Fn(it) => Some(it),
2020-07-30 11:42:51 +02:00
_ => None,
}).for_each(&mut process_fn),
2020-04-09 23:02:10 +02:00
_ => continue,
}
};
2019-01-08 22:33:36 +03:00
}
2020-07-10 16:29:14 +02:00
let self_completion_items = ["self", "&self", "mut self", "&mut self"];
if ctx.impl_def.is_some() && me?.param_list()?.params().next().is_none() {
self_completion_items.iter().for_each(|self_item| {
add_new_item_to_acc(ctx, acc, self_item.to_string(), self_item.to_string())
});
}
params.into_iter().for_each(|(label, lookup)| add_new_item_to_acc(ctx, acc, label, lookup));
Some(())
}
fn add_new_item_to_acc(
ctx: &CompletionContext,
acc: &mut Completions,
label: String,
lookup: String,
) {
let mut item = CompletionItem::new(CompletionKind::Magic, ctx.source_range(), label);
item.kind(CompletionItemKind::Binding).lookup_by(lookup);
item.add_to(acc)
2019-01-08 22:33:36 +03:00
}