1 //! `completions` crate provides utilities for generating completions of user input.
3 #![warn(rust_2018_idioms, unused_lifetimes, semicolon_in_expressions_from_macros)]
16 base_db::FilePosition,
17 helpers::mod_path_to_ast,
19 import_assets::NameToImport,
20 insert_use::{self, ImportScope},
22 items_locator, RootDatabase,
25 use text_edit::TextEdit;
28 completions::Completions,
30 CompletionAnalysis, CompletionContext, NameRefContext, NameRefKind, PathCompletionCtx,
36 config::{CallableSnippets, CompletionConfig},
38 CompletionItem, CompletionItemKind, CompletionRelevance, CompletionRelevancePostfixMatch,
40 snippet::{Snippet, SnippetScope},
43 //FIXME: split the following feature into fine-grained features.
45 // Feature: Magic Completions
47 // In addition to usual reference completion, rust-analyzer provides some ✨magic✨
48 // completions as well:
50 // Keywords like `if`, `else` `while`, `loop` are completed with braces, and cursor
51 // is placed at the appropriate position. Even though `if` is easy to type, you
52 // still want to complete it, to get ` { }` for free! `return` is inserted with a
53 // space or `;` depending on the return type of the function.
55 // When completing a function call, `()` are automatically inserted. If a function
56 // takes arguments, the cursor is positioned inside the parenthesis.
58 // There are postfix completions, which can be triggered by typing something like
59 // `foo().if`. The word after `.` determines postfix completion. Possible variants are:
61 // - `expr.if` -> `if expr {}` or `if let ... {}` for `Option` or `Result`
62 // - `expr.match` -> `match expr {}`
63 // - `expr.while` -> `while expr {}` or `while let ... {}` for `Option` or `Result`
64 // - `expr.ref` -> `&expr`
65 // - `expr.refm` -> `&mut expr`
66 // - `expr.let` -> `let $0 = expr;`
67 // - `expr.letm` -> `let mut $0 = expr;`
68 // - `expr.not` -> `!expr`
69 // - `expr.dbg` -> `dbg!(expr)`
70 // - `expr.dbgr` -> `dbg!(&expr)`
71 // - `expr.call` -> `(expr)`
73 // There also snippet completions:
76 // - `pd` -> `eprintln!(" = {:?}", );`
77 // - `ppd` -> `eprintln!(" = {:#?}", );`
80 // - `tfn` -> `#[test] fn feature(){}`
92 // And the auto import completions, enabled with the `rust-analyzer.completion.autoimport.enable` setting and the corresponding LSP client capabilities.
93 // Those are the additional completion options with automatic `use` import and options from all project importable items,
94 // fuzzy matched against the completion input.
96 // image::https://user-images.githubusercontent.com/48062697/113020667-b72ab880-917a-11eb-8778-716cf26a0eb3.gif[]
98 /// Main entry point for completion. We run completion as a two-phase process.
100 /// First, we look at the position and collect a so-called `CompletionContext.
101 /// This is a somewhat messy process, because, during completion, syntax tree is
102 /// incomplete and can look really weird.
104 /// Once the context is collected, we run a series of completion routines which
105 /// look at the context and produce completion items. One subtlety about this
106 /// phase is that completion engine should not filter by the substring which is
107 /// already present, it should give all possible variants for the identifier at
108 /// the caret. In other words, for
117 /// `foo` *should* be present among the completion variants. Filtering by
118 /// identifier prefix/fuzzy match should be done higher in the stack, together
119 /// with ordering of completions (currently this is done by the client).
121 /// # Speculative Completion Problem
123 /// There's a curious unsolved problem in the current implementation. Often, you
124 /// want to compute completions on a *slightly different* text document.
126 /// In the simplest case, when the code looks like `let x = `, you want to
127 /// insert a fake identifier to get a better syntax tree: `let x = complete_me`.
129 /// We do this in `CompletionContext`, and it works OK-enough for *syntax*
130 /// analysis. However, we might want to, eg, ask for the type of `complete_me`
131 /// variable, and that's where our current infrastructure breaks down. salsa
132 /// doesn't allow such "phantom" inputs.
134 /// Another case where this would be instrumental is macro expansion. We want to
135 /// insert a fake ident and re-expand code. There's `expand_speculative` as a
136 /// work-around for this.
138 /// A different use-case is completion of injection (examples and links in doc
139 /// comments). When computing completion for a path in a doc-comment, you want
140 /// to inject a fake path expression into the item being documented and complete
143 /// IntelliJ has CodeFragment/Context infrastructure for that. You can create a
144 /// temporary PSI node, and say that the context ("parent") of this node is some
145 /// existing node. Asking for, eg, type of this `CodeFragment` node works
146 /// correctly, as the underlying infrastructure makes use of contexts to do
150 config: &CompletionConfig,
151 position: FilePosition,
152 trigger_character: Option<char>,
153 ) -> Option<Vec<CompletionItem>> {
154 let (ctx, analysis) = &CompletionContext::new(db, position, config)?;
155 let mut completions = Completions::default();
157 // prevent `(` from triggering unwanted completion noise
158 if trigger_character == Some('(') {
159 if let CompletionAnalysis::NameRef(NameRefContext { kind, .. }) = &analysis {
160 if let NameRefKind::Path(
161 path_ctx @ PathCompletionCtx { kind: PathKind::Vis { has_in_token }, .. },
164 completions::vis::complete_vis_path(&mut completions, ctx, path_ctx, has_in_token);
167 // prevent `(` from triggering unwanted completion noise
168 return Some(completions.into());
172 let acc = &mut completions;
175 CompletionAnalysis::Name(name_ctx) => completions::complete_name(acc, ctx, name_ctx),
176 CompletionAnalysis::NameRef(name_ref_ctx) => {
177 completions::complete_name_ref(acc, ctx, name_ref_ctx)
179 CompletionAnalysis::Lifetime(lifetime_ctx) => {
180 completions::lifetime::complete_label(acc, ctx, lifetime_ctx);
181 completions::lifetime::complete_lifetime(acc, ctx, lifetime_ctx);
183 CompletionAnalysis::String { original, expanded: Some(expanded) } => {
184 completions::extern_abi::complete_extern_abi(acc, ctx, expanded);
185 completions::format_string::format_string(acc, ctx, original, expanded);
186 completions::env_vars::complete_cargo_env_vars(acc, ctx, expanded);
188 CompletionAnalysis::UnexpandedAttrTT {
190 fake_attribute_under_caret: Some(attr),
192 completions::attribute::complete_known_attribute_input(
199 CompletionAnalysis::UnexpandedAttrTT { .. } | CompletionAnalysis::String { .. } => (),
203 Some(completions.into())
206 /// Resolves additional completion data at the position given.
207 /// This is used for import insertion done via completions like flyimport and custom user snippets.
208 pub fn resolve_completion_edits(
210 config: &CompletionConfig,
211 FilePosition { file_id, offset }: FilePosition,
212 imports: impl IntoIterator<Item = (String, String)>,
213 ) -> Option<Vec<TextEdit>> {
214 let _p = profile::span("resolve_completion_edits");
215 let sema = hir::Semantics::new(db);
217 let original_file = sema.parse(file_id);
219 syntax::AstNode::syntax(&original_file).token_at_offset(offset).left_biased()?;
220 let position_for_import = &original_token.parent()?;
221 let scope = ImportScope::find_insert_use_container(position_for_import, &sema)?;
223 let current_module = sema.scope(position_for_import)?.module();
224 let current_crate = current_module.krate();
225 let new_ast = scope.clone_for_update();
226 let mut import_insert = TextEdit::builder();
228 imports.into_iter().for_each(|(full_import_path, imported_name)| {
229 let items_with_name = items_locator::items_with_name(
232 NameToImport::exact_case_sensitive(imported_name),
233 items_locator::AssocItemSearch::Include,
234 Some(items_locator::DEFAULT_QUERY_SEARCH_LIMIT.inner()),
236 let import = items_with_name
237 .filter_map(|candidate| {
238 current_module.find_use_path_prefixed(
241 config.insert_use.prefix_kind,
242 config.prefer_no_std,
245 .find(|mod_path| mod_path.to_string() == full_import_path);
246 if let Some(import_path) = import {
247 insert_use::insert_use(&new_ast, mod_path_to_ast(&import_path), &config.insert_use);
251 algo::diff(scope.as_syntax_node(), new_ast.as_syntax_node()).into_text_edit(&mut import_insert);
252 Some(vec![import_insert.finish()])