ide_completion/
lib.rs

1//! `completions` crate provides utilities for generating completions of user input.
2
3// It's useful to refer to code that is private in doc comments.
4#![allow(rustdoc::private_intra_doc_links)]
5#![cfg_attr(feature = "in-rust-tree", feature(rustc_private))]
6
7#[cfg(feature = "in-rust-tree")]
8extern crate rustc_driver as _;
9
10mod completions;
11mod config;
12mod context;
13mod item;
14mod render;
15
16mod snippet;
17#[cfg(test)]
18mod tests;
19
20use ide_db::{
21    FilePosition, FxHashSet, RootDatabase,
22    imports::insert_use::{self, ImportScope},
23    syntax_helpers::tree_diff::diff,
24    text_edit::TextEdit,
25};
26use syntax::ast::make;
27
28use crate::{
29    completions::Completions,
30    context::{
31        CompletionAnalysis, CompletionContext, NameRefContext, NameRefKind, PathCompletionCtx,
32        PathKind,
33    },
34};
35
36pub use crate::{
37    config::{AutoImportExclusionType, CallableSnippets, CompletionConfig},
38    item::{
39        CompletionItem, CompletionItemKind, CompletionItemRefMode, CompletionRelevance,
40        CompletionRelevancePostfixMatch, CompletionRelevanceReturnType,
41        CompletionRelevanceTypeMatch,
42    },
43    snippet::{Snippet, SnippetScope},
44};
45
46#[derive(Copy, Clone, Debug, PartialEq, Eq)]
47pub struct CompletionFieldsToResolve {
48    pub resolve_label_details: bool,
49    pub resolve_tags: bool,
50    pub resolve_detail: bool,
51    pub resolve_documentation: bool,
52    pub resolve_filter_text: bool,
53    pub resolve_text_edit: bool,
54    pub resolve_command: bool,
55}
56
57impl CompletionFieldsToResolve {
58    pub fn from_client_capabilities(client_capability_fields: &FxHashSet<&str>) -> Self {
59        Self {
60            resolve_label_details: client_capability_fields.contains("labelDetails"),
61            resolve_tags: client_capability_fields.contains("tags"),
62            resolve_detail: client_capability_fields.contains("detail"),
63            resolve_documentation: client_capability_fields.contains("documentation"),
64            resolve_filter_text: client_capability_fields.contains("filterText"),
65            resolve_text_edit: client_capability_fields.contains("textEdit"),
66            resolve_command: client_capability_fields.contains("command"),
67        }
68    }
69
70    pub const fn empty() -> Self {
71        Self {
72            resolve_label_details: false,
73            resolve_tags: false,
74            resolve_detail: false,
75            resolve_documentation: false,
76            resolve_filter_text: false,
77            resolve_text_edit: false,
78            resolve_command: false,
79        }
80    }
81}
82
83//FIXME: split the following feature into fine-grained features.
84
85// Feature: Magic Completions
86//
87// In addition to usual reference completion, rust-analyzer provides some ✨magic✨
88// completions as well:
89//
90// Keywords like `if`, `else` `while`, `loop` are completed with braces, and cursor
91// is placed at the appropriate position. Even though `if` is easy to type, you
92// still want to complete it, to get ` { }` for free! `return` is inserted with a
93// space or `;` depending on the return type of the function.
94//
95// When completing a function call, `()` are automatically inserted. If a function
96// takes arguments, the cursor is positioned inside the parenthesis.
97//
98// There are postfix completions, which can be triggered by typing something like
99// `foo().if`. The word after `.` determines postfix completion. Possible variants are:
100//
101// - `expr.if` -> `if expr {}` or `if let ... {}` for `Option` or `Result`
102// - `expr.match` -> `match expr {}`
103// - `expr.while` -> `while expr {}` or `while let ... {}` for `Option` or `Result`
104// - `expr.ref` -> `&expr`
105// - `expr.refm` -> `&mut expr`
106// - `expr.let` -> `let $0 = expr;`
107// - `expr.lete` -> `let $1 = expr else { $0 };`
108// - `expr.letm` -> `let mut $0 = expr;`
109// - `expr.not` -> `!expr`
110// - `expr.dbg` -> `dbg!(expr)`
111// - `expr.dbgr` -> `dbg!(&expr)`
112// - `expr.call` -> `(expr)`
113//
114// There also snippet completions:
115//
116// #### Expressions
117//
118// - `pd` -> `eprintln!(" = {:?}", );`
119// - `ppd` -> `eprintln!(" = {:#?}", );`
120//
121// #### Items
122//
123// - `tfn` -> `#[test] fn feature(){}`
124// - `tmod` ->
125// ```rust
126// #[cfg(test)]
127// mod tests {
128//     use super::*;
129//
130//     #[test]
131//     fn test_name() {}
132// }
133// ```
134//
135// And the auto import completions, enabled with the `rust-analyzer.completion.autoimport.enable` setting and the corresponding LSP client capabilities.
136// Those are the additional completion options with automatic `use` import and options from all project importable items,
137// fuzzy matched against the completion input.
138//
139// ![Magic Completions](https://user-images.githubusercontent.com/48062697/113020667-b72ab880-917a-11eb-8778-716cf26a0eb3.gif)
140
141/// Main entry point for completion. We run completion as a two-phase process.
142///
143/// First, we look at the position and collect a so-called `CompletionContext`.
144/// This is a somewhat messy process, because, during completion, syntax tree is
145/// incomplete and can look really weird.
146///
147/// Once the context is collected, we run a series of completion routines which
148/// look at the context and produce completion items. One subtlety about this
149/// phase is that completion engine should not filter by the substring which is
150/// already present, it should give all possible variants for the identifier at
151/// the caret. In other words, for
152///
153/// ```ignore
154/// fn f() {
155///     let foo = 92;
156///     let _ = bar$0
157/// }
158/// ```
159///
160/// `foo` *should* be present among the completion variants. Filtering by
161/// identifier prefix/fuzzy match should be done higher in the stack, together
162/// with ordering of completions (currently this is done by the client).
163///
164/// # Speculative Completion Problem
165///
166/// There's a curious unsolved problem in the current implementation. Often, you
167/// want to compute completions on a *slightly different* text document.
168///
169/// In the simplest case, when the code looks like `let x = `, you want to
170/// insert a fake identifier to get a better syntax tree: `let x = complete_me`.
171///
172/// We do this in `CompletionContext`, and it works OK-enough for *syntax*
173/// analysis. However, we might want to, eg, ask for the type of `complete_me`
174/// variable, and that's where our current infrastructure breaks down. salsa
175/// doesn't allow such "phantom" inputs.
176///
177/// Another case where this would be instrumental is macro expansion. We want to
178/// insert a fake ident and re-expand code. There's `expand_speculative` as a
179/// workaround for this.
180///
181/// A different use-case is completion of injection (examples and links in doc
182/// comments). When computing completion for a path in a doc-comment, you want
183/// to inject a fake path expression into the item being documented and complete
184/// that.
185///
186/// IntelliJ has CodeFragment/Context infrastructure for that. You can create a
187/// temporary PSI node, and say that the context ("parent") of this node is some
188/// existing node. Asking for, eg, type of this `CodeFragment` node works
189/// correctly, as the underlying infrastructure makes use of contexts to do
190/// analysis.
191pub fn completions(
192    db: &RootDatabase,
193    config: &CompletionConfig<'_>,
194    position: FilePosition,
195    trigger_character: Option<char>,
196) -> Option<Vec<CompletionItem>> {
197    let (ctx, analysis) = &CompletionContext::new(db, position, config, trigger_character)?;
198    let mut completions = Completions::default();
199
200    // prevent `(` from triggering unwanted completion noise
201    if trigger_character == Some('(') {
202        if let CompletionAnalysis::NameRef(NameRefContext {
203            kind:
204                NameRefKind::Path(
205                    path_ctx @ PathCompletionCtx { kind: PathKind::Vis { has_in_token }, .. },
206                ),
207            ..
208        }) = analysis
209        {
210            completions::vis::complete_vis_path(&mut completions, ctx, path_ctx, has_in_token);
211        }
212        return Some(completions.into());
213    }
214
215    // when the user types a bare `_` (that is it does not belong to an identifier)
216    // the user might just wanted to type a `_` for type inference or pattern discarding
217    // so try to suppress completions in those cases
218    if trigger_character == Some('_')
219        && ctx.original_token.kind() == syntax::SyntaxKind::UNDERSCORE
220        && let CompletionAnalysis::NameRef(NameRefContext {
221            kind:
222                NameRefKind::Path(
223                    path_ctx @ PathCompletionCtx {
224                        kind: PathKind::Type { .. } | PathKind::Pat { .. },
225                        ..
226                    },
227                ),
228            ..
229        }) = analysis
230        && path_ctx.is_trivial_path()
231    {
232        return None;
233    }
234
235    {
236        let acc = &mut completions;
237
238        match analysis {
239            CompletionAnalysis::Name(name_ctx) => completions::complete_name(acc, ctx, name_ctx),
240            CompletionAnalysis::NameRef(name_ref_ctx) => {
241                completions::complete_name_ref(acc, ctx, name_ref_ctx)
242            }
243            CompletionAnalysis::Lifetime(lifetime_ctx) => {
244                completions::lifetime::complete_label(acc, ctx, lifetime_ctx);
245                completions::lifetime::complete_lifetime(acc, ctx, lifetime_ctx);
246            }
247            CompletionAnalysis::String { original, expanded: Some(expanded) } => {
248                completions::extern_abi::complete_extern_abi(acc, ctx, expanded);
249                completions::format_string::format_string(acc, ctx, original, expanded);
250                completions::env_vars::complete_cargo_env_vars(acc, ctx, original, expanded);
251                completions::ra_fixture::complete_ra_fixture(acc, ctx, original, expanded);
252            }
253            CompletionAnalysis::UnexpandedAttrTT {
254                colon_prefix,
255                fake_attribute_under_caret: Some(attr),
256                extern_crate,
257            } => {
258                completions::attribute::complete_known_attribute_input(
259                    acc,
260                    ctx,
261                    colon_prefix,
262                    attr,
263                    extern_crate.as_ref(),
264                );
265            }
266            CompletionAnalysis::UnexpandedAttrTT { .. } | CompletionAnalysis::String { .. } => (),
267        }
268    }
269
270    Some(completions.into())
271}
272
273/// Resolves additional completion data at the position given.
274/// This is used for import insertion done via completions like flyimport and custom user snippets.
275pub fn resolve_completion_edits(
276    db: &RootDatabase,
277    config: &CompletionConfig<'_>,
278    FilePosition { file_id, offset }: FilePosition,
279    imports: impl IntoIterator<Item = String>,
280) -> Option<Vec<TextEdit>> {
281    let _p = tracing::info_span!("resolve_completion_edits").entered();
282    let sema = hir::Semantics::new(db);
283
284    let editioned_file_id = sema.attach_first_edition(file_id);
285
286    let original_file = sema.parse(editioned_file_id);
287    let original_token =
288        syntax::AstNode::syntax(&original_file).token_at_offset(offset).left_biased()?;
289    let position_for_import = &original_token.parent()?;
290    let scope = ImportScope::find_insert_use_container(position_for_import, &sema)?;
291
292    let current_module = sema.scope(position_for_import)?.module();
293    let current_crate = current_module.krate(db);
294    let current_edition = current_crate.edition(db);
295    let new_ast = scope.clone_for_update();
296    let mut import_insert = TextEdit::builder();
297
298    imports.into_iter().for_each(|full_import_path| {
299        insert_use::insert_use(
300            &new_ast,
301            make::path_from_text_with_edition(&full_import_path, current_edition),
302            &config.insert_use,
303        );
304    });
305
306    diff(scope.as_syntax_node(), new_ast.as_syntax_node()).into_text_edit(&mut import_insert);
307    Some(vec![import_insert.finish()])
308}