aboutsummaryrefslogtreecommitdiff
path: root/crates/ide_completion/src/lib.rs
diff options
context:
space:
mode:
authorAleksey Kladov <[email protected]>2021-02-17 14:53:31 +0000
committerAleksey Kladov <[email protected]>2021-02-17 14:53:31 +0000
commit3db64a400c78bbd2708e67ddc07df1001fff3f29 (patch)
tree5386aab9c452981be09bc3e4362643a34e6e3617 /crates/ide_completion/src/lib.rs
parent6334ce866ab095215381c4b72692b20a84d26e96 (diff)
rename completion -> ide_completion
We don't have completion-related PRs in flight, so lets do it
Diffstat (limited to 'crates/ide_completion/src/lib.rs')
-rw-r--r--crates/ide_completion/src/lib.rs275
1 files changed, 275 insertions, 0 deletions
diff --git a/crates/ide_completion/src/lib.rs b/crates/ide_completion/src/lib.rs
new file mode 100644
index 000000000..db8bfbbc3
--- /dev/null
+++ b/crates/ide_completion/src/lib.rs
@@ -0,0 +1,275 @@
1//! `completions` crate provides utilities for generating completions of user input.
2
3mod config;
4mod item;
5mod context;
6mod patterns;
7mod generated_lint_completions;
8#[cfg(test)]
9mod test_utils;
10mod render;
11
12mod completions;
13
14use completions::flyimport::position_for_import;
15use ide_db::{
16 base_db::FilePosition, helpers::insert_use::ImportScope, imports_locator, RootDatabase,
17};
18use text_edit::TextEdit;
19
20use crate::{completions::Completions, context::CompletionContext, item::CompletionKind};
21
22pub use crate::{
23 config::CompletionConfig,
24 item::{CompletionItem, CompletionItemKind, CompletionScore, ImportEdit, InsertTextFormat},
25};
26
27//FIXME: split the following feature into fine-grained features.
28
29// Feature: Magic Completions
30//
31// In addition to usual reference completion, rust-analyzer provides some ✨magic✨
32// completions as well:
33//
34// Keywords like `if`, `else` `while`, `loop` are completed with braces, and cursor
35// is placed at the appropriate position. Even though `if` is easy to type, you
36// still want to complete it, to get ` { }` for free! `return` is inserted with a
37// space or `;` depending on the return type of the function.
38//
39// When completing a function call, `()` are automatically inserted. If a function
40// takes arguments, the cursor is positioned inside the parenthesis.
41//
42// There are postfix completions, which can be triggered by typing something like
43// `foo().if`. The word after `.` determines postfix completion. Possible variants are:
44//
45// - `expr.if` -> `if expr {}` or `if let ... {}` for `Option` or `Result`
46// - `expr.match` -> `match expr {}`
47// - `expr.while` -> `while expr {}` or `while let ... {}` for `Option` or `Result`
48// - `expr.ref` -> `&expr`
49// - `expr.refm` -> `&mut expr`
50// - `expr.let` -> `let $0 = expr;`
51// - `expr.letm` -> `let mut $0 = expr;`
52// - `expr.not` -> `!expr`
53// - `expr.dbg` -> `dbg!(expr)`
54// - `expr.dbgr` -> `dbg!(&expr)`
55// - `expr.call` -> `(expr)`
56//
57// There also snippet completions:
58//
59// .Expressions
60// - `pd` -> `eprintln!(" = {:?}", );`
61// - `ppd` -> `eprintln!(" = {:#?}", );`
62//
63// .Items
64// - `tfn` -> `#[test] fn feature(){}`
65// - `tmod` ->
66// ```rust
67// #[cfg(test)]
68// mod tests {
69// use super::*;
70//
71// #[test]
72// fn test_name() {}
73// }
74// ```
75//
76// And the auto import completions, enabled with the `rust-analyzer.completion.autoimport.enable` setting and the corresponding LSP client capabilities.
77// Those are the additional completion options with automatic `use` import and options from all project importable items,
78// fuzzy matched agains the completion imput.
79
80/// Main entry point for completion. We run completion as a two-phase process.
81///
82/// First, we look at the position and collect a so-called `CompletionContext.
83/// This is a somewhat messy process, because, during completion, syntax tree is
84/// incomplete and can look really weird.
85///
86/// Once the context is collected, we run a series of completion routines which
87/// look at the context and produce completion items. One subtlety about this
88/// phase is that completion engine should not filter by the substring which is
89/// already present, it should give all possible variants for the identifier at
90/// the caret. In other words, for
91///
92/// ```no_run
93/// fn f() {
94/// let foo = 92;
95/// let _ = bar$0
96/// }
97/// ```
98///
99/// `foo` *should* be present among the completion variants. Filtering by
100/// identifier prefix/fuzzy match should be done higher in the stack, together
101/// with ordering of completions (currently this is done by the client).
102pub fn completions(
103 db: &RootDatabase,
104 config: &CompletionConfig,
105 position: FilePosition,
106) -> Option<Completions> {
107 let ctx = CompletionContext::new(db, position, config)?;
108
109 if ctx.no_completion_required() {
110 // No work required here.
111 return None;
112 }
113
114 let mut acc = Completions::default();
115 completions::attribute::complete_attribute(&mut acc, &ctx);
116 completions::fn_param::complete_fn_param(&mut acc, &ctx);
117 completions::keyword::complete_expr_keyword(&mut acc, &ctx);
118 completions::keyword::complete_use_tree_keyword(&mut acc, &ctx);
119 completions::snippet::complete_expr_snippet(&mut acc, &ctx);
120 completions::snippet::complete_item_snippet(&mut acc, &ctx);
121 completions::qualified_path::complete_qualified_path(&mut acc, &ctx);
122 completions::unqualified_path::complete_unqualified_path(&mut acc, &ctx);
123 completions::dot::complete_dot(&mut acc, &ctx);
124 completions::record::complete_record(&mut acc, &ctx);
125 completions::pattern::complete_pattern(&mut acc, &ctx);
126 completions::postfix::complete_postfix(&mut acc, &ctx);
127 completions::macro_in_item_position::complete_macro_in_item_position(&mut acc, &ctx);
128 completions::trait_impl::complete_trait_impl(&mut acc, &ctx);
129 completions::mod_::complete_mod(&mut acc, &ctx);
130 completions::flyimport::import_on_the_fly(&mut acc, &ctx);
131
132 Some(acc)
133}
134
135/// Resolves additional completion data at the position given.
136pub fn resolve_completion_edits(
137 db: &RootDatabase,
138 config: &CompletionConfig,
139 position: FilePosition,
140 full_import_path: &str,
141 imported_name: String,
142 import_for_trait_assoc_item: bool,
143) -> Option<Vec<TextEdit>> {
144 let ctx = CompletionContext::new(db, position, config)?;
145 let position_for_import = position_for_import(&ctx, None)?;
146 let import_scope = ImportScope::find_insert_use_container(position_for_import, &ctx.sema)?;
147
148 let current_module = ctx.sema.scope(position_for_import).module()?;
149 let current_crate = current_module.krate();
150
151 let import_path = imports_locator::find_exact_imports(&ctx.sema, current_crate, imported_name)
152 .filter_map(|candidate| {
153 let item: hir::ItemInNs = candidate.either(Into::into, Into::into);
154 current_module.find_use_path(db, item)
155 })
156 .find(|mod_path| mod_path.to_string() == full_import_path)?;
157
158 ImportEdit { import_path, import_scope, import_for_trait_assoc_item }
159 .to_text_edit(config.insert_use.merge)
160 .map(|edit| vec![edit])
161}
162
163#[cfg(test)]
164mod tests {
165 use crate::test_utils::{self, TEST_CONFIG};
166
167 struct DetailAndDocumentation<'a> {
168 detail: &'a str,
169 documentation: &'a str,
170 }
171
172 fn check_detail_and_documentation(ra_fixture: &str, expected: DetailAndDocumentation) {
173 let (db, position) = test_utils::position(ra_fixture);
174 let config = TEST_CONFIG;
175 let completions: Vec<_> = crate::completions(&db, &config, position).unwrap().into();
176 for item in completions {
177 if item.detail() == Some(expected.detail) {
178 let opt = item.documentation();
179 let doc = opt.as_ref().map(|it| it.as_str());
180 assert_eq!(doc, Some(expected.documentation));
181 return;
182 }
183 }
184 panic!("completion detail not found: {}", expected.detail)
185 }
186
187 fn check_no_completion(ra_fixture: &str) {
188 let (db, position) = test_utils::position(ra_fixture);
189 let config = TEST_CONFIG;
190
191 let completions: Option<Vec<String>> = crate::completions(&db, &config, position)
192 .and_then(|completions| {
193 let completions: Vec<_> = completions.into();
194 if completions.is_empty() {
195 None
196 } else {
197 Some(completions)
198 }
199 })
200 .map(|completions| {
201 completions.into_iter().map(|completion| format!("{:?}", completion)).collect()
202 });
203
204 // `assert_eq` instead of `assert!(completions.is_none())` to get the list of completions if test will panic.
205 assert_eq!(completions, None, "Completions were generated, but weren't expected");
206 }
207
208 #[test]
209 fn test_completion_detail_from_macro_generated_struct_fn_doc_attr() {
210 check_detail_and_documentation(
211 r#"
212macro_rules! bar {
213 () => {
214 struct Bar;
215 impl Bar {
216 #[doc = "Do the foo"]
217 fn foo(&self) {}
218 }
219 }
220}
221
222bar!();
223
224fn foo() {
225 let bar = Bar;
226 bar.fo$0;
227}
228"#,
229 DetailAndDocumentation { detail: "-> ()", documentation: "Do the foo" },
230 );
231 }
232
233 #[test]
234 fn test_completion_detail_from_macro_generated_struct_fn_doc_comment() {
235 check_detail_and_documentation(
236 r#"
237macro_rules! bar {
238 () => {
239 struct Bar;
240 impl Bar {
241 /// Do the foo
242 fn foo(&self) {}
243 }
244 }
245}
246
247bar!();
248
249fn foo() {
250 let bar = Bar;
251 bar.fo$0;
252}
253"#,
254 DetailAndDocumentation { detail: "-> ()", documentation: " Do the foo" },
255 );
256 }
257
258 #[test]
259 fn test_no_completions_required() {
260 // There must be no hint for 'in' keyword.
261 check_no_completion(r#"fn foo() { for i i$0 }"#);
262 // After 'in' keyword hints may be spawned.
263 check_detail_and_documentation(
264 r#"
265/// Do the foo
266fn foo() -> &'static str { "foo" }
267
268fn bar() {
269 for c in fo$0
270}
271"#,
272 DetailAndDocumentation { detail: "-> &str", documentation: "Do the foo" },
273 );
274 }
275}