]> git.lizzy.rs Git - rust.git/blob - src/tools/rust-analyzer/crates/ide-completion/src/lib.rs
Auto merge of #102184 - chenyukang:fix-102087-add-binding-sugg, r=nagisa
[rust.git] / src / tools / rust-analyzer / crates / ide-completion / src / lib.rs
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 /// work-around 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.
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 { kind, .. }) = &analysis {
160             if let NameRefKind::Path(
161                 path_ctx @ PathCompletionCtx { kind: PathKind::Vis { has_in_token }, .. },
162             ) = kind
163             {
164                 completions::vis::complete_vis_path(&mut completions, ctx, path_ctx, has_in_token);
165             }
166         }
167         // prevent `(` from triggering unwanted completion noise
168         return Some(completions.into());
169     }
170
171     {
172         let acc = &mut completions;
173
174         match &analysis {
175             CompletionAnalysis::Name(name_ctx) => completions::complete_name(acc, ctx, name_ctx),
176             CompletionAnalysis::NameRef(name_ref_ctx) => {
177                 completions::complete_name_ref(acc, ctx, name_ref_ctx)
178             }
179             CompletionAnalysis::Lifetime(lifetime_ctx) => {
180                 completions::lifetime::complete_label(acc, ctx, lifetime_ctx);
181                 completions::lifetime::complete_lifetime(acc, ctx, lifetime_ctx);
182             }
183             CompletionAnalysis::String { original, expanded: Some(expanded) } => {
184                 completions::extern_abi::complete_extern_abi(acc, ctx, expanded);
185                 completions::format_string::format_string(acc, ctx, original, expanded);
186             }
187             CompletionAnalysis::UnexpandedAttrTT {
188                 colon_prefix,
189                 fake_attribute_under_caret: Some(attr),
190             } => {
191                 completions::attribute::complete_known_attribute_input(
192                     acc,
193                     ctx,
194                     colon_prefix,
195                     attr,
196                 );
197             }
198             CompletionAnalysis::UnexpandedAttrTT { .. } | CompletionAnalysis::String { .. } => (),
199         }
200     }
201
202     Some(completions.into())
203 }
204
205 /// Resolves additional completion data at the position given.
206 /// This is used for import insertion done via completions like flyimport and custom user snippets.
207 pub fn resolve_completion_edits(
208     db: &RootDatabase,
209     config: &CompletionConfig,
210     FilePosition { file_id, offset }: FilePosition,
211     imports: impl IntoIterator<Item = (String, String)>,
212 ) -> Option<Vec<TextEdit>> {
213     let _p = profile::span("resolve_completion_edits");
214     let sema = hir::Semantics::new(db);
215
216     let original_file = sema.parse(file_id);
217     let original_token =
218         syntax::AstNode::syntax(&original_file).token_at_offset(offset).left_biased()?;
219     let position_for_import = &original_token.parent()?;
220     let scope = ImportScope::find_insert_use_container(position_for_import, &sema)?;
221
222     let current_module = sema.scope(position_for_import)?.module();
223     let current_crate = current_module.krate();
224     let new_ast = scope.clone_for_update();
225     let mut import_insert = TextEdit::builder();
226
227     imports.into_iter().for_each(|(full_import_path, imported_name)| {
228         let items_with_name = items_locator::items_with_name(
229             &sema,
230             current_crate,
231             NameToImport::exact_case_sensitive(imported_name),
232             items_locator::AssocItemSearch::Include,
233             Some(items_locator::DEFAULT_QUERY_SEARCH_LIMIT.inner()),
234         );
235         let import = items_with_name
236             .filter_map(|candidate| {
237                 current_module.find_use_path_prefixed(
238                     db,
239                     candidate,
240                     config.insert_use.prefix_kind,
241                     config.prefer_no_std,
242                 )
243             })
244             .find(|mod_path| mod_path.to_string() == full_import_path);
245         if let Some(import_path) = import {
246             insert_use::insert_use(&new_ast, mod_path_to_ast(&import_path), &config.insert_use);
247         }
248     });
249
250     algo::diff(scope.as_syntax_node(), new_ast.as_syntax_node()).into_text_edit(&mut import_insert);
251     Some(vec![import_insert.finish()])
252 }