1 //! See [`complete_fn_param`].
7 ast::{self, HasModuleItem},
8 match_ast, AstNode, Direction, SyntaxKind, TextRange, TextSize,
12 context::{ParamContext, ParamKind, PatternContext},
13 CompletionContext, CompletionItem, CompletionItemKind, Completions,
16 // FIXME: Make this a submodule of [`pattern`]
17 /// Complete repeated parameters, both name and type. For example, if all
18 /// functions in a file have a `spam: &mut Spam` parameter, a completion with
19 /// `spam: &mut Spam` insert text/label will be suggested.
21 /// Also complete parameters for closure or local functions from the surrounding defined locals.
22 pub(crate) fn complete_fn_param(
23 acc: &mut Completions,
24 ctx: &CompletionContext<'_>,
25 pattern_ctx: &PatternContext,
27 let (ParamContext { param_list, kind, .. }, impl_) = match pattern_ctx {
28 PatternContext { param_ctx: Some(kind), impl_, .. } => (kind, impl_),
32 let comma_wrapper = comma_wrapper(ctx);
33 let mut add_new_item_to_acc = |label: &str| {
34 let mk_item = |label: &str, range: TextRange| {
35 CompletionItem::new(CompletionItemKind::Binding, range, label)
37 let item = match &comma_wrapper {
38 Some((fmt, range)) => mk_item(&fmt(label), *range),
39 None => mk_item(label, ctx.source_range()),
41 // Completion lookup is omitted intentionally here.
42 // See the full discussion: https://github.com/rust-lang/rust-analyzer/issues/12073
47 ParamKind::Function(function) => {
48 fill_fn_params(ctx, function, param_list, impl_, add_new_item_to_acc);
50 ParamKind::Closure(closure) => {
51 let stmt_list = closure.syntax().ancestors().find_map(ast::StmtList::cast)?;
52 params_from_stmt_list_scope(ctx, stmt_list, |name, ty| {
53 add_new_item_to_acc(&format!("{name}: {ty}"));
62 ctx: &CompletionContext<'_>,
64 param_list: &ast::ParamList,
65 impl_: &Option<ast::Impl>,
66 mut add_new_item_to_acc: impl FnMut(&str),
68 let mut file_params = FxHashMap::default();
70 let mut extract_params = |f: ast::Fn| {
71 f.param_list().into_iter().flat_map(|it| it.params()).for_each(|param| {
72 if let Some(pat) = param.pat() {
73 // FIXME: We should be able to turn these into SmolStr without having to allocate a String
74 let whole_param = param.syntax().text().to_string();
75 let binding = pat.syntax().text().to_string();
76 file_params.entry(whole_param).or_insert(binding);
81 for node in ctx.token.parent_ancestors() {
84 ast::SourceFile(it) => it.items().filter_map(|item| match item {
85 ast::Item::Fn(it) => Some(it),
87 }).for_each(&mut extract_params),
88 ast::ItemList(it) => it.items().filter_map(|item| match item {
89 ast::Item::Fn(it) => Some(it),
91 }).for_each(&mut extract_params),
92 ast::AssocItemList(it) => it.assoc_items().filter_map(|item| match item {
93 ast::AssocItem::Fn(it) => Some(it),
95 }).for_each(&mut extract_params),
101 if let Some(stmt_list) = function.syntax().parent().and_then(ast::StmtList::cast) {
102 params_from_stmt_list_scope(ctx, stmt_list, |name, ty| {
103 file_params.entry(format!("{name}: {ty}")).or_insert(name.to_string());
106 remove_duplicated(&mut file_params, param_list.params());
107 let self_completion_items = ["self", "&self", "mut self", "&mut self"];
108 if should_add_self_completions(ctx.token.text_range().start(), param_list, impl_) {
109 self_completion_items.into_iter().for_each(|self_item| add_new_item_to_acc(self_item));
112 file_params.keys().for_each(|whole_param| add_new_item_to_acc(whole_param));
115 fn params_from_stmt_list_scope(
116 ctx: &CompletionContext<'_>,
117 stmt_list: ast::StmtList,
118 mut cb: impl FnMut(hir::Name, String),
120 let syntax_node = match stmt_list.syntax().last_child() {
125 ctx.sema.scope_at_offset(stmt_list.syntax(), syntax_node.text_range().end())
127 let module = scope.module().into();
128 scope.process_all_names(&mut |name, def| {
129 if let hir::ScopeDef::Local(local) = def {
130 if let Ok(ty) = local.ty(ctx.db).display_source_code(ctx.db, module) {
138 fn remove_duplicated(
139 file_params: &mut FxHashMap<String, String>,
140 fn_params: ast::AstChildren<ast::Param>,
142 fn_params.for_each(|param| {
143 let whole_param = param.syntax().text().to_string();
144 file_params.remove(&whole_param);
147 // remove suggestions for patterns that already exist
148 // if the type is missing we are checking the current param to be completed
149 // in which case this would find itself removing the suggestions due to itself
150 Some(pattern) if param.ty().is_some() => {
151 let binding = pattern.syntax().text().to_string();
152 file_params.retain(|_, v| v != &binding);
159 fn should_add_self_completions(
161 param_list: &ast::ParamList,
162 impl_: &Option<ast::Impl>,
164 if impl_.is_none() || param_list.self_param().is_some() {
167 match param_list.params().next() {
168 Some(first) => first.pat().map_or(false, |pat| pat.syntax().text_range().contains(cursor)),
173 fn comma_wrapper(ctx: &CompletionContext<'_>) -> Option<(impl Fn(&str) -> String, TextRange)> {
174 let param = ctx.token.parent_ancestors().find(|node| node.kind() == SyntaxKind::PARAM)?;
176 let next_token_kind = {
177 let t = param.last_token()?.next_token()?;
178 let t = algo::skip_whitespace_token(t, Direction::Next)?;
181 let prev_token_kind = {
182 let t = param.first_token()?.prev_token()?;
183 let t = algo::skip_whitespace_token(t, Direction::Prev)?;
187 let has_trailing_comma =
188 matches!(next_token_kind, SyntaxKind::COMMA | SyntaxKind::R_PAREN | SyntaxKind::PIPE);
189 let trailing = if has_trailing_comma { "" } else { "," };
191 let has_leading_comma =
192 matches!(prev_token_kind, SyntaxKind::COMMA | SyntaxKind::L_PAREN | SyntaxKind::PIPE);
193 let leading = if has_leading_comma { "" } else { ", " };
195 Some((move |label: &_| (format!("{}{}{}", leading, label, trailing)), param.text_range()))