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