]> git.lizzy.rs Git - rust.git/blob - crates/ide_completion/src/lib.rs
Merge #9972
[rust.git] / crates / ide_completion / src / lib.rs
1 //! `completions` crate provides utilities for generating completions of user input.
2
3 mod completions;
4 mod config;
5 mod context;
6 mod item;
7 mod patterns;
8 mod render;
9
10 #[cfg(test)]
11 mod tests;
12
13 use completions::flyimport::position_for_import;
14 use ide_db::{
15     base_db::FilePosition,
16     helpers::{
17         import_assets::{LocatedImport, NameToImport},
18         insert_use::ImportScope,
19     },
20     items_locator, RootDatabase,
21 };
22 use text_edit::TextEdit;
23
24 use crate::{completions::Completions, context::CompletionContext, item::CompletionKind};
25
26 pub use crate::{
27     config::CompletionConfig,
28     item::{CompletionItem, CompletionItemKind, CompletionRelevance, ImportEdit},
29 };
30
31 //FIXME: split the following feature into fine-grained features.
32
33 // Feature: Magic Completions
34 //
35 // In addition to usual reference completion, rust-analyzer provides some ✨magic✨
36 // completions as well:
37 //
38 // Keywords like `if`, `else` `while`, `loop` are completed with braces, and cursor
39 // is placed at the appropriate position. Even though `if` is easy to type, you
40 // still want to complete it, to get ` { }` for free! `return` is inserted with a
41 // space or `;` depending on the return type of the function.
42 //
43 // When completing a function call, `()` are automatically inserted. If a function
44 // takes arguments, the cursor is positioned inside the parenthesis.
45 //
46 // There are postfix completions, which can be triggered by typing something like
47 // `foo().if`. The word after `.` determines postfix completion. Possible variants are:
48 //
49 // - `expr.if` -> `if expr {}` or `if let ... {}` for `Option` or `Result`
50 // - `expr.match` -> `match expr {}`
51 // - `expr.while` -> `while expr {}` or `while let ... {}` for `Option` or `Result`
52 // - `expr.ref` -> `&expr`
53 // - `expr.refm` -> `&mut expr`
54 // - `expr.let` -> `let $0 = expr;`
55 // - `expr.letm` -> `let mut $0 = expr;`
56 // - `expr.not` -> `!expr`
57 // - `expr.dbg` -> `dbg!(expr)`
58 // - `expr.dbgr` -> `dbg!(&expr)`
59 // - `expr.call` -> `(expr)`
60 //
61 // There also snippet completions:
62 //
63 // .Expressions
64 // - `pd` -> `eprintln!(" = {:?}", );`
65 // - `ppd` -> `eprintln!(" = {:#?}", );`
66 //
67 // .Items
68 // - `tfn` -> `#[test] fn feature(){}`
69 // - `tmod` ->
70 // ```rust
71 // #[cfg(test)]
72 // mod tests {
73 //     use super::*;
74 //
75 //     #[test]
76 //     fn test_name() {}
77 // }
78 // ```
79 //
80 // And the auto import completions, enabled with the `rust-analyzer.completion.autoimport.enable` setting and the corresponding LSP client capabilities.
81 // Those are the additional completion options with automatic `use` import and options from all project importable items,
82 // fuzzy matched against the completion input.
83 //
84 // image::https://user-images.githubusercontent.com/48062697/113020667-b72ab880-917a-11eb-8778-716cf26a0eb3.gif[]
85
86 /// Main entry point for completion. We run completion as a two-phase process.
87 ///
88 /// First, we look at the position and collect a so-called `CompletionContext.
89 /// This is a somewhat messy process, because, during completion, syntax tree is
90 /// incomplete and can look really weird.
91 ///
92 /// Once the context is collected, we run a series of completion routines which
93 /// look at the context and produce completion items. One subtlety about this
94 /// phase is that completion engine should not filter by the substring which is
95 /// already present, it should give all possible variants for the identifier at
96 /// the caret. In other words, for
97 ///
98 /// ```no_run
99 /// fn f() {
100 ///     let foo = 92;
101 ///     let _ = bar$0
102 /// }
103 /// ```
104 ///
105 /// `foo` *should* be present among the completion variants. Filtering by
106 /// identifier prefix/fuzzy match should be done higher in the stack, together
107 /// with ordering of completions (currently this is done by the client).
108 ///
109 /// # Speculative Completion Problem
110 ///
111 /// There's a curious unsolved problem in the current implementation. Often, you
112 /// want to compute completions on a *slightly different* text document.
113 ///
114 /// In the simplest case, when the code looks like `let x = `, you want to
115 /// insert a fake identifier to get a better syntax tree: `let x = complete_me`.
116 ///
117 /// We do this in `CompletionContext`, and it works OK-enough for *syntax*
118 /// analysis. However, we might want to, eg, ask for the type of `complete_me`
119 /// variable, and that's where our current infrastructure breaks down. salsa
120 /// doesn't allow such "phantom" inputs.
121 ///
122 /// Another case where this would be instrumental is macro expansion. We want to
123 /// insert a fake ident and re-expand code. There's `expand_speculative` as a
124 /// work-around for this.
125 ///
126 /// A different use-case is completion of injection (examples and links in doc
127 /// comments). When computing completion for a path in a doc-comment, you want
128 /// to inject a fake path expression into the item being documented and complete
129 /// that.
130 ///
131 /// IntelliJ has CodeFragment/Context infrastructure for that. You can create a
132 /// temporary PSI node, and say that the context ("parent") of this node is some
133 /// existing node. Asking for, eg, type of this `CodeFragment` node works
134 /// correctly, as the underlying infrastructure makes use of contexts to do
135 /// analysis.
136 pub fn completions(
137     db: &RootDatabase,
138     config: &CompletionConfig,
139     position: FilePosition,
140 ) -> Option<Completions> {
141     let ctx = CompletionContext::new(db, position, config)?;
142
143     if ctx.no_completion_required() {
144         cov_mark::hit!(no_completion_required);
145         // No work required here.
146         return None;
147     }
148
149     let mut acc = Completions::default();
150     completions::attribute::complete_attribute(&mut acc, &ctx);
151     completions::fn_param::complete_fn_param(&mut acc, &ctx);
152     completions::keyword::complete_expr_keyword(&mut acc, &ctx);
153     completions::snippet::complete_expr_snippet(&mut acc, &ctx);
154     completions::snippet::complete_item_snippet(&mut acc, &ctx);
155     completions::qualified_path::complete_qualified_path(&mut acc, &ctx);
156     completions::unqualified_path::complete_unqualified_path(&mut acc, &ctx);
157     completions::dot::complete_dot(&mut acc, &ctx);
158     completions::record::complete_record(&mut acc, &ctx);
159     completions::record::complete_record_literal(&mut acc, &ctx);
160     completions::pattern::complete_pattern(&mut acc, &ctx);
161     completions::postfix::complete_postfix(&mut acc, &ctx);
162     completions::trait_impl::complete_trait_impl(&mut acc, &ctx);
163     completions::mod_::complete_mod(&mut acc, &ctx);
164     completions::flyimport::import_on_the_fly(&mut acc, &ctx);
165     completions::lifetime::complete_lifetime(&mut acc, &ctx);
166     completions::lifetime::complete_label(&mut acc, &ctx);
167
168     Some(acc)
169 }
170
171 /// Resolves additional completion data at the position given.
172 pub fn resolve_completion_edits(
173     db: &RootDatabase,
174     config: &CompletionConfig,
175     position: FilePosition,
176     full_import_path: &str,
177     imported_name: String,
178 ) -> Option<Vec<TextEdit>> {
179     let ctx = CompletionContext::new(db, position, config)?;
180     let position_for_import = position_for_import(&ctx, None)?;
181     let scope = ImportScope::find_insert_use_container_with_macros(position_for_import, &ctx.sema)?;
182
183     let current_module = ctx.sema.scope(position_for_import).module()?;
184     let current_crate = current_module.krate();
185
186     let (import_path, item_to_import) = items_locator::items_with_name(
187         &ctx.sema,
188         current_crate,
189         NameToImport::Exact(imported_name),
190         items_locator::AssocItemSearch::Include,
191         Some(items_locator::DEFAULT_QUERY_SEARCH_LIMIT.inner()),
192     )
193     .filter_map(|candidate| {
194         current_module
195             .find_use_path_prefixed(db, candidate, config.insert_use.prefix_kind)
196             .zip(Some(candidate))
197     })
198     .find(|(mod_path, _)| mod_path.to_string() == full_import_path)?;
199     let import =
200         LocatedImport::new(import_path.clone(), item_to_import, item_to_import, Some(import_path));
201
202     ImportEdit { import, scope }.to_text_edit(config.insert_use).map(|edit| vec![edit])
203 }