1 //! `completions` crate provides utilities for generating completions of user input.
2
3 #![warn(rust_2018_idioms, unused_lifetimes, semicolon_in_expressions_from_macros)]
4
5 mod completions;
6 mod config;
7 mod context;
8 mod item;
9 mod render;
10
11 #[cfg(test)]
12 mod tests;
13 mod snippet;
14
15 use ide_db::{
16 base_db::FilePosition,
17 helpers::mod_path_to_ast,
18 imports::{
19 import_assets::NameToImport,
20 insert_use::{self, ImportScope},
21 },
22 items_locator, RootDatabase,
23 };
24 use syntax::algo;
25 use text_edit::TextEdit;
26
27 use crate::{
28 completions::Completions,
29 context::{
30 CompletionAnalysis, CompletionContext, NameRefContext, NameRefKind, PathCompletionCtx,
31 PathKind,
32 },
33 };
34
35 pub use crate::{
36 config::{CallableSnippets, CompletionConfig},
37 item::{
38 CompletionItem, CompletionItemKind, CompletionRelevance, CompletionRelevancePostfixMatch,
39 },
40 snippet::{Snippet, SnippetScope},
41 };
42
43 //FIXME: split the following feature into fine-grained features.
44
45 // Feature: Magic Completions
46 //
47 // In addition to usual reference completion, rust-analyzer provides some ✨magic✨
48 // completions as well:
49 //
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.
54 //
55 // When completing a function call, `()` are automatically inserted. If a function
56 // takes arguments, the cursor is positioned inside the parenthesis.
57 //
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:
60 //
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)`
72 //
73 // There also snippet completions:
74 //
75 // .Expressions
76 // - `pd` -> `eprintln!(" = {:?}", );`
77 // - `ppd` -> `eprintln!(" = {:#?}", );`
78 //
79 // .Items
80 // - `tfn` -> `#[test] fn feature(){}`
81 // - `tmod` ->
82 // ```rust
83 // #[cfg(test)]
84 // mod tests {
85 // use super::*;
86 //
87 // #[test]
88 // fn test_name() {}
89 // }
90 // ```
91 //
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.
95 //
96 // image::https://user-images.githubusercontent.com/48062697/113020667-b72ab880-917a-11eb-8778-716cf26a0eb3.gif[]
97
98 /// Main entry point for completion. We run completion as a two-phase process.
99 ///
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.
103 ///
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
109 ///
110 /// ```no_run
111 /// fn f() {
112 /// let foo = 92;
113 /// let _ = bar$0
114 /// }
115 /// ```
116 ///
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).
120 ///
121 /// # Speculative Completion Problem
122 ///
123 /// There's a curious unsolved problem in the current implementation. Often, you
124 /// want to compute completions on a *slightly different* text document.
125 ///
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`.
128 ///
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.
133 ///
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 /// workaround for this.
137 ///
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
141 /// that.
142 ///
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
147 /// analysis.
completions( db: &RootDatabase, config: &CompletionConfig, position: FilePosition, trigger_character: Option<char>, ) -> Option<Vec<CompletionItem>>148 pub fn completions(
149 db: &RootDatabase,
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();
156
157 // prevent `(` from triggering unwanted completion noise
158 if trigger_character == Some('(') {
159 if let CompletionAnalysis::NameRef(NameRefContext {
160 kind:
161 NameRefKind::Path(
162 path_ctx @ PathCompletionCtx { kind: PathKind::Vis { has_in_token }, .. },
163 ),
164 ..
165 }) = analysis
166 {
167 completions::vis::complete_vis_path(&mut completions, ctx, path_ctx, has_in_token);
168 }
169 return Some(completions.into());
170 }
171
172 {
173 let acc = &mut completions;
174
175 match analysis {
176 CompletionAnalysis::Name(name_ctx) => completions::complete_name(acc, ctx, name_ctx),
177 CompletionAnalysis::NameRef(name_ref_ctx) => {
178 completions::complete_name_ref(acc, ctx, name_ref_ctx)
179 }
180 CompletionAnalysis::Lifetime(lifetime_ctx) => {
181 completions::lifetime::complete_label(acc, ctx, lifetime_ctx);
182 completions::lifetime::complete_lifetime(acc, ctx, lifetime_ctx);
183 }
184 CompletionAnalysis::String { original, expanded: Some(expanded) } => {
185 completions::extern_abi::complete_extern_abi(acc, ctx, expanded);
186 completions::format_string::format_string(acc, ctx, original, expanded);
187 completions::env_vars::complete_cargo_env_vars(acc, ctx, expanded);
188 }
189 CompletionAnalysis::UnexpandedAttrTT {
190 colon_prefix,
191 fake_attribute_under_caret: Some(attr),
192 } => {
193 completions::attribute::complete_known_attribute_input(
194 acc,
195 ctx,
196 colon_prefix,
197 attr,
198 );
199 }
200 CompletionAnalysis::UnexpandedAttrTT { .. } | CompletionAnalysis::String { .. } => (),
201 }
202 }
203
204 Some(completions.into())
205 }
206
207 /// Resolves additional completion data at the position given.
208 /// This is used for import insertion done via completions like flyimport and custom user snippets.
209 pub fn resolve_completion_edits(
210 db: &RootDatabase,
211 config: &CompletionConfig,
212 FilePosition { file_id, offset }: FilePosition,
213 imports: impl IntoIterator<Item = (String, String)>,
214 ) -> Option<Vec<TextEdit>> {
215 let _p = profile::span("resolve_completion_edits");
216 let sema = hir::Semantics::new(db);
217
218 let original_file = sema.parse(file_id);
219 let original_token =
220 syntax::AstNode::syntax(&original_file).token_at_offset(offset).left_biased()?;
221 let position_for_import = &original_token.parent()?;
222 let scope = ImportScope::find_insert_use_container(position_for_import, &sema)?;
223
224 let current_module = sema.scope(position_for_import)?.module();
225 let current_crate = current_module.krate();
226 let new_ast = scope.clone_for_update();
227 let mut import_insert = TextEdit::builder();
228
229 imports.into_iter().for_each(|(full_import_path, imported_name)| {
230 let items_with_name = items_locator::items_with_name(
231 &sema,
232 current_crate,
233 NameToImport::exact_case_sensitive(imported_name),
234 items_locator::AssocItemSearch::Include,
235 Some(items_locator::DEFAULT_QUERY_SEARCH_LIMIT.inner()),
236 );
237 let import = items_with_name
238 .filter_map(|candidate| {
239 current_module.find_use_path_prefixed(
240 db,
241 candidate,
242 config.insert_use.prefix_kind,
243 config.prefer_no_std,
244 )
245 })
246 .find(|mod_path| mod_path.display(db).to_string() == full_import_path);
247 if let Some(import_path) = import {
248 insert_use::insert_use(&new_ast, mod_path_to_ast(&import_path), &config.insert_use);
249 }
250 });
251
252 algo::diff(scope.as_syntax_node(), new_ast.as_syntax_node()).into_text_edit(&mut import_insert);
253 Some(vec![import_insert.finish()])
254 }
255