1 //! `completions` crate provides utilities for generating completions of user input.
14 use completions::flyimport::position_for_import;
16 base_db::FilePosition,
18 import_assets::NameToImport,
19 insert_use::{self, ImportScope},
22 items_locator, RootDatabase,
25 use text_edit::TextEdit;
27 use crate::{completions::Completions, context::CompletionContext};
30 config::CompletionConfig,
31 item::{CompletionItem, CompletionItemKind, CompletionRelevance, ImportEdit},
32 snippet::{Snippet, SnippetScope},
35 //FIXME: split the following feature into fine-grained features.
37 // Feature: Magic Completions
39 // In addition to usual reference completion, rust-analyzer provides some ✨magic✨
40 // completions as well:
42 // Keywords like `if`, `else` `while`, `loop` are completed with braces, and cursor
43 // is placed at the appropriate position. Even though `if` is easy to type, you
44 // still want to complete it, to get ` { }` for free! `return` is inserted with a
45 // space or `;` depending on the return type of the function.
47 // When completing a function call, `()` are automatically inserted. If a function
48 // takes arguments, the cursor is positioned inside the parenthesis.
50 // There are postfix completions, which can be triggered by typing something like
51 // `foo().if`. The word after `.` determines postfix completion. Possible variants are:
53 // - `expr.if` -> `if expr {}` or `if let ... {}` for `Option` or `Result`
54 // - `expr.match` -> `match expr {}`
55 // - `expr.while` -> `while expr {}` or `while let ... {}` for `Option` or `Result`
56 // - `expr.ref` -> `&expr`
57 // - `expr.refm` -> `&mut expr`
58 // - `expr.let` -> `let $0 = expr;`
59 // - `expr.letm` -> `let mut $0 = expr;`
60 // - `expr.not` -> `!expr`
61 // - `expr.dbg` -> `dbg!(expr)`
62 // - `expr.dbgr` -> `dbg!(&expr)`
63 // - `expr.call` -> `(expr)`
65 // There also snippet completions:
68 // - `pd` -> `eprintln!(" = {:?}", );`
69 // - `ppd` -> `eprintln!(" = {:#?}", );`
72 // - `tfn` -> `#[test] fn feature(){}`
84 // And the auto import completions, enabled with the `rust-analyzer.completion.autoimport.enable` setting and the corresponding LSP client capabilities.
85 // Those are the additional completion options with automatic `use` import and options from all project importable items,
86 // fuzzy matched against the completion input.
88 // image::https://user-images.githubusercontent.com/48062697/113020667-b72ab880-917a-11eb-8778-716cf26a0eb3.gif[]
90 /// Main entry point for completion. We run completion as a two-phase process.
92 /// First, we look at the position and collect a so-called `CompletionContext.
93 /// This is a somewhat messy process, because, during completion, syntax tree is
94 /// incomplete and can look really weird.
96 /// Once the context is collected, we run a series of completion routines which
97 /// look at the context and produce completion items. One subtlety about this
98 /// phase is that completion engine should not filter by the substring which is
99 /// already present, it should give all possible variants for the identifier at
100 /// the caret. In other words, for
109 /// `foo` *should* be present among the completion variants. Filtering by
110 /// identifier prefix/fuzzy match should be done higher in the stack, together
111 /// with ordering of completions (currently this is done by the client).
113 /// # Speculative Completion Problem
115 /// There's a curious unsolved problem in the current implementation. Often, you
116 /// want to compute completions on a *slightly different* text document.
118 /// In the simplest case, when the code looks like `let x = `, you want to
119 /// insert a fake identifier to get a better syntax tree: `let x = complete_me`.
121 /// We do this in `CompletionContext`, and it works OK-enough for *syntax*
122 /// analysis. However, we might want to, eg, ask for the type of `complete_me`
123 /// variable, and that's where our current infrastructure breaks down. salsa
124 /// doesn't allow such "phantom" inputs.
126 /// Another case where this would be instrumental is macro expansion. We want to
127 /// insert a fake ident and re-expand code. There's `expand_speculative` as a
128 /// work-around for this.
130 /// A different use-case is completion of injection (examples and links in doc
131 /// comments). When computing completion for a path in a doc-comment, you want
132 /// to inject a fake path expression into the item being documented and complete
135 /// IntelliJ has CodeFragment/Context infrastructure for that. You can create a
136 /// temporary PSI node, and say that the context ("parent") of this node is some
137 /// existing node. Asking for, eg, type of this `CodeFragment` node works
138 /// correctly, as the underlying infrastructure makes use of contexts to do
142 config: &CompletionConfig,
143 position: FilePosition,
144 ) -> Option<Completions> {
145 let ctx = CompletionContext::new(db, position, config)?;
147 if ctx.no_completion_required() {
148 cov_mark::hit!(no_completion_required);
149 // No work required here.
153 let mut acc = Completions::default();
154 completions::attribute::complete_attribute(&mut acc, &ctx);
155 completions::fn_param::complete_fn_param(&mut acc, &ctx);
156 completions::keyword::complete_expr_keyword(&mut acc, &ctx);
157 completions::snippet::complete_expr_snippet(&mut acc, &ctx);
158 completions::snippet::complete_item_snippet(&mut acc, &ctx);
159 completions::qualified_path::complete_qualified_path(&mut acc, &ctx);
160 completions::unqualified_path::complete_unqualified_path(&mut acc, &ctx);
161 completions::dot::complete_dot(&mut acc, &ctx);
162 completions::record::complete_record(&mut acc, &ctx);
163 completions::record::complete_record_literal(&mut acc, &ctx);
164 completions::pattern::complete_pattern(&mut acc, &ctx);
165 completions::postfix::complete_postfix(&mut acc, &ctx);
166 completions::trait_impl::complete_trait_impl(&mut acc, &ctx);
167 completions::mod_::complete_mod(&mut acc, &ctx);
168 completions::flyimport::import_on_the_fly(&mut acc, &ctx);
169 completions::lifetime::complete_lifetime(&mut acc, &ctx);
170 completions::lifetime::complete_label(&mut acc, &ctx);
175 /// Resolves additional completion data at the position given.
176 /// This is used for import insertion done via completions like flyimport and custom user snippets.
177 pub fn resolve_completion_edits(
179 config: &CompletionConfig,
180 position: FilePosition,
181 imports: impl IntoIterator<Item = (String, String)>,
182 ) -> Option<Vec<TextEdit>> {
183 let _p = profile::span("resolve_completion_edits");
184 let ctx = CompletionContext::new(db, position, config)?;
185 let position_for_import = position_for_import(&ctx, None)?;
186 let scope = ImportScope::find_insert_use_container_with_macros(position_for_import, &ctx.sema)?;
188 let current_module = ctx.sema.scope(position_for_import).module()?;
189 let current_crate = current_module.krate();
190 let new_ast = scope.clone_for_update();
191 let mut import_insert = TextEdit::builder();
193 // FIXME: lift out and make some tests here, this is ImportEdit::to_text_edit but changed to work with multiple edits
194 imports.into_iter().for_each(|(full_import_path, imported_name)| {
195 let items_with_name = items_locator::items_with_name(
198 NameToImport::Exact(imported_name),
199 items_locator::AssocItemSearch::Include,
200 Some(items_locator::DEFAULT_QUERY_SEARCH_LIMIT.inner()),
202 let import = items_with_name
203 .filter_map(|candidate| {
204 current_module.find_use_path_prefixed(db, candidate, config.insert_use.prefix_kind)
206 .find(|mod_path| mod_path.to_string() == full_import_path);
207 if let Some(import_path) = import {
208 insert_use::insert_use(&new_ast, mod_path_to_ast(&import_path), &config.insert_use);
212 algo::diff(scope.as_syntax_node(), new_ast.as_syntax_node()).into_text_edit(&mut import_insert);
213 Some(vec![import_insert.finish()])