1 //! `completions` crate provides utilities for generating completions of user input.
13 use completions::flyimport::position_for_import;
15 base_db::FilePosition,
17 import_assets::{LocatedImport, NameToImport},
18 insert_use::ImportScope,
20 items_locator, RootDatabase,
22 use text_edit::TextEdit;
24 use crate::{completions::Completions, context::CompletionContext, item::CompletionKind};
27 config::CompletionConfig,
28 item::{CompletionItem, CompletionItemKind, CompletionRelevance, ImportEdit},
31 //FIXME: split the following feature into fine-grained features.
33 // Feature: Magic Completions
35 // In addition to usual reference completion, rust-analyzer provides some ✨magic✨
36 // completions as well:
38 // Keywords like `if`, `else` `while`, `loop` are completed with braces, and cursor
39 // is placed at the appropriate position. Even though `if` is easy to type, you
40 // still want to complete it, to get ` { }` for free! `return` is inserted with a
41 // space or `;` depending on the return type of the function.
43 // When completing a function call, `()` are automatically inserted. If a function
44 // takes arguments, the cursor is positioned inside the parenthesis.
46 // There are postfix completions, which can be triggered by typing something like
47 // `foo().if`. The word after `.` determines postfix completion. Possible variants are:
49 // - `expr.if` -> `if expr {}` or `if let ... {}` for `Option` or `Result`
50 // - `expr.match` -> `match expr {}`
51 // - `expr.while` -> `while expr {}` or `while let ... {}` for `Option` or `Result`
52 // - `expr.ref` -> `&expr`
53 // - `expr.refm` -> `&mut expr`
54 // - `expr.let` -> `let $0 = expr;`
55 // - `expr.letm` -> `let mut $0 = expr;`
56 // - `expr.not` -> `!expr`
57 // - `expr.dbg` -> `dbg!(expr)`
58 // - `expr.dbgr` -> `dbg!(&expr)`
59 // - `expr.call` -> `(expr)`
61 // There also snippet completions:
64 // - `pd` -> `eprintln!(" = {:?}", );`
65 // - `ppd` -> `eprintln!(" = {:#?}", );`
68 // - `tfn` -> `#[test] fn feature(){}`
80 // And the auto import completions, enabled with the `rust-analyzer.completion.autoimport.enable` setting and the corresponding LSP client capabilities.
81 // Those are the additional completion options with automatic `use` import and options from all project importable items,
82 // fuzzy matched against the completion input.
84 // image::https://user-images.githubusercontent.com/48062697/113020667-b72ab880-917a-11eb-8778-716cf26a0eb3.gif[]
86 /// Main entry point for completion. We run completion as a two-phase process.
88 /// First, we look at the position and collect a so-called `CompletionContext.
89 /// This is a somewhat messy process, because, during completion, syntax tree is
90 /// incomplete and can look really weird.
92 /// Once the context is collected, we run a series of completion routines which
93 /// look at the context and produce completion items. One subtlety about this
94 /// phase is that completion engine should not filter by the substring which is
95 /// already present, it should give all possible variants for the identifier at
96 /// the caret. In other words, for
105 /// `foo` *should* be present among the completion variants. Filtering by
106 /// identifier prefix/fuzzy match should be done higher in the stack, together
107 /// with ordering of completions (currently this is done by the client).
109 /// # Speculative Completion Problem
111 /// There's a curious unsolved problem in the current implementation. Often, you
112 /// want to compute completions on a *slightly different* text document.
114 /// In the simplest case, when the code looks like `let x = `, you want to
115 /// insert a fake identifier to get a better syntax tree: `let x = complete_me`.
117 /// We do this in `CompletionContext`, and it works OK-enough for *syntax*
118 /// analysis. However, we might want to, eg, ask for the type of `complete_me`
119 /// variable, and that's where our current infrastructure breaks down. salsa
120 /// doesn't allow such "phantom" inputs.
122 /// Another case where this would be instrumental is macro expansion. We want to
123 /// insert a fake ident and re-expand code. There's `expand_speculative` as a
124 /// work-around for this.
126 /// A different use-case is completion of injection (examples and links in doc
127 /// comments). When computing completion for a path in a doc-comment, you want
128 /// to inject a fake path expression into the item being documented and complete
131 /// IntelliJ has CodeFragment/Context infrastructure for that. You can create a
132 /// temporary PSI node, and say that the context ("parent") of this node is some
133 /// existing node. Asking for, eg, type of this `CodeFragment` node works
134 /// correctly, as the underlying infrastructure makes use of contexts to do
138 config: &CompletionConfig,
139 position: FilePosition,
140 ) -> Option<Completions> {
141 let ctx = CompletionContext::new(db, position, config)?;
143 if ctx.no_completion_required() {
144 cov_mark::hit!(no_completion_required);
145 // No work required here.
149 let mut acc = Completions::default();
150 completions::attribute::complete_attribute(&mut acc, &ctx);
151 completions::fn_param::complete_fn_param(&mut acc, &ctx);
152 completions::keyword::complete_expr_keyword(&mut acc, &ctx);
153 completions::snippet::complete_expr_snippet(&mut acc, &ctx);
154 completions::snippet::complete_item_snippet(&mut acc, &ctx);
155 completions::qualified_path::complete_qualified_path(&mut acc, &ctx);
156 completions::unqualified_path::complete_unqualified_path(&mut acc, &ctx);
157 completions::dot::complete_dot(&mut acc, &ctx);
158 completions::record::complete_record(&mut acc, &ctx);
159 completions::record::complete_record_literal(&mut acc, &ctx);
160 completions::pattern::complete_pattern(&mut acc, &ctx);
161 completions::postfix::complete_postfix(&mut acc, &ctx);
162 completions::trait_impl::complete_trait_impl(&mut acc, &ctx);
163 completions::mod_::complete_mod(&mut acc, &ctx);
164 completions::flyimport::import_on_the_fly(&mut acc, &ctx);
165 completions::lifetime::complete_lifetime(&mut acc, &ctx);
166 completions::lifetime::complete_label(&mut acc, &ctx);
171 /// Resolves additional completion data at the position given.
172 pub fn resolve_completion_edits(
174 config: &CompletionConfig,
175 position: FilePosition,
176 full_import_path: &str,
177 imported_name: String,
178 ) -> Option<Vec<TextEdit>> {
179 let ctx = CompletionContext::new(db, position, config)?;
180 let position_for_import = position_for_import(&ctx, None)?;
181 let scope = ImportScope::find_insert_use_container_with_macros(position_for_import, &ctx.sema)?;
183 let current_module = ctx.sema.scope(position_for_import).module()?;
184 let current_crate = current_module.krate();
186 let (import_path, item_to_import) = items_locator::items_with_name(
189 NameToImport::Exact(imported_name),
190 items_locator::AssocItemSearch::Include,
191 Some(items_locator::DEFAULT_QUERY_SEARCH_LIMIT.inner()),
193 .filter_map(|candidate| {
195 .find_use_path_prefixed(db, candidate, config.insert_use.prefix_kind)
196 .zip(Some(candidate))
198 .find(|(mod_path, _)| mod_path.to_string() == full_import_path)?;
200 LocatedImport::new(import_path.clone(), item_to_import, item_to_import, Some(import_path));
202 ImportEdit { import, scope }.to_text_edit(config.insert_use).map(|edit| vec![edit])