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