]> git.lizzy.rs Git - rust.git/blob - crates/completion/src/lib.rs
8df9f00fe299c287e013713240ecfac2b7aa9e13
[rust.git] / crates / completion / src / lib.rs
1 //! `completions` crate provides utilities for generating completions of user input.
2
3 mod config;
4 mod item;
5 mod context;
6 mod patterns;
7 mod generated_lint_completions;
8 #[cfg(test)]
9 mod test_utils;
10 mod render;
11
12 mod completions;
13
14 use ide_db::{
15     base_db::FilePosition, helpers::insert_use::ImportScope, imports_locator, RootDatabase,
16 };
17 use syntax::AstNode;
18 use text_edit::TextEdit;
19
20 use crate::{completions::Completions, context::CompletionContext, item::CompletionKind};
21
22 pub use crate::{
23     config::{CompletionConfig, CompletionResolveCapability},
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 <|> = expr;`
51 // - `expr.letm` -> `let mut <|> = 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 experimental completions, enabled with the `rust-analyzer.completion.disableFuzzyAutoimports` setting.
77 // This flag enables or disables:
78 //
79 // - Auto import: additional completion options with automatic `use` import and options from all project importable items, matched for the input
80 //
81 // Experimental completions might cause issues with performance and completion list look.
82
83 /// Main entry point for completion. We run completion as a two-phase process.
84 ///
85 /// First, we look at the position and collect a so-called `CompletionContext.
86 /// This is a somewhat messy process, because, during completion, syntax tree is
87 /// incomplete and can look really weird.
88 ///
89 /// Once the context is collected, we run a series of completion routines which
90 /// look at the context and produce completion items. One subtlety about this
91 /// phase is that completion engine should not filter by the substring which is
92 /// already present, it should give all possible variants for the identifier at
93 /// the caret. In other words, for
94 ///
95 /// ```no_run
96 /// fn f() {
97 ///     let foo = 92;
98 ///     let _ = bar<|>
99 /// }
100 /// ```
101 ///
102 /// `foo` *should* be present among the completion variants. Filtering by
103 /// identifier prefix/fuzzy match should be done higher in the stack, together
104 /// with ordering of completions (currently this is done by the client).
105 pub fn completions(
106     db: &RootDatabase,
107     config: &CompletionConfig,
108     position: FilePosition,
109 ) -> Option<Completions> {
110     let ctx = CompletionContext::new(db, position, config)?;
111
112     if ctx.no_completion_required() {
113         // No work required here.
114         return None;
115     }
116
117     let mut acc = Completions::default();
118     completions::attribute::complete_attribute(&mut acc, &ctx);
119     completions::fn_param::complete_fn_param(&mut acc, &ctx);
120     completions::keyword::complete_expr_keyword(&mut acc, &ctx);
121     completions::keyword::complete_use_tree_keyword(&mut acc, &ctx);
122     completions::snippet::complete_expr_snippet(&mut acc, &ctx);
123     completions::snippet::complete_item_snippet(&mut acc, &ctx);
124     completions::qualified_path::complete_qualified_path(&mut acc, &ctx);
125     completions::unqualified_path::complete_unqualified_path(&mut acc, &ctx);
126     completions::dot::complete_dot(&mut acc, &ctx);
127     completions::record::complete_record(&mut acc, &ctx);
128     completions::pattern::complete_pattern(&mut acc, &ctx);
129     completions::postfix::complete_postfix(&mut acc, &ctx);
130     completions::macro_in_item_position::complete_macro_in_item_position(&mut acc, &ctx);
131     completions::trait_impl::complete_trait_impl(&mut acc, &ctx);
132     completions::mod_::complete_mod(&mut acc, &ctx);
133
134     Some(acc)
135 }
136
137 /// Resolves additional completion data at the position given.
138 pub fn resolve_completion_edits(
139     db: &RootDatabase,
140     config: &CompletionConfig,
141     position: FilePosition,
142     full_import_path: &str,
143     imported_name: &str,
144 ) -> Option<Vec<TextEdit>> {
145     let ctx = CompletionContext::new(db, position, config)?;
146     let anchor = ctx.name_ref_syntax.as_ref()?;
147     let import_scope = ImportScope::find_insert_use_container(anchor.syntax(), &ctx.sema)?;
148
149     let current_module = ctx.sema.scope(anchor.syntax()).module()?;
150     let current_crate = current_module.krate();
151
152     let import_path = imports_locator::find_exact_imports(&ctx.sema, current_crate, imported_name)
153         .filter_map(|candidate| {
154             let item: hir::ItemInNs = candidate.either(Into::into, Into::into);
155             current_module.find_use_path(db, item)
156         })
157         .find(|mod_path| mod_path.to_string() == full_import_path)?;
158
159     ImportEdit { import_path, import_scope, merge_behaviour: config.merge }
160         .to_text_edit()
161         .map(|edit| vec![edit])
162 }
163
164 #[cfg(test)]
165 mod tests {
166     use crate::config::CompletionConfig;
167     use crate::test_utils;
168
169     struct DetailAndDocumentation<'a> {
170         detail: &'a str,
171         documentation: &'a str,
172     }
173
174     fn check_detail_and_documentation(ra_fixture: &str, expected: DetailAndDocumentation) {
175         let (db, position) = test_utils::position(ra_fixture);
176         let config = CompletionConfig::default();
177         let completions: Vec<_> = crate::completions(&db, &config, position).unwrap().into();
178         for item in completions {
179             if item.detail() == Some(expected.detail) {
180                 let opt = item.documentation();
181                 let doc = opt.as_ref().map(|it| it.as_str());
182                 assert_eq!(doc, Some(expected.documentation));
183                 return;
184             }
185         }
186         panic!("completion detail not found: {}", expected.detail)
187     }
188
189     fn check_no_completion(ra_fixture: &str) {
190         let (db, position) = test_utils::position(ra_fixture);
191         let config = CompletionConfig::default();
192
193         let completions: Option<Vec<String>> = crate::completions(&db, &config, position)
194             .and_then(|completions| {
195                 let completions: Vec<_> = completions.into();
196                 if completions.is_empty() {
197                     None
198                 } else {
199                     Some(completions)
200                 }
201             })
202             .map(|completions| {
203                 completions.into_iter().map(|completion| format!("{:?}", completion)).collect()
204             });
205
206         // `assert_eq` instead of `assert!(completions.is_none())` to get the list of completions if test will panic.
207         assert_eq!(completions, None, "Completions were generated, but weren't expected");
208     }
209
210     #[test]
211     fn test_completion_detail_from_macro_generated_struct_fn_doc_attr() {
212         check_detail_and_documentation(
213             r#"
214             //- /lib.rs
215             macro_rules! bar {
216                 () => {
217                     struct Bar;
218                     impl Bar {
219                         #[doc = "Do the foo"]
220                         fn foo(&self) {}
221                     }
222                 }
223             }
224
225             bar!();
226
227             fn foo() {
228                 let bar = Bar;
229                 bar.fo<|>;
230             }
231             "#,
232             DetailAndDocumentation { detail: "fn foo(&self)", documentation: "Do the foo" },
233         );
234     }
235
236     #[test]
237     fn test_completion_detail_from_macro_generated_struct_fn_doc_comment() {
238         check_detail_and_documentation(
239             r#"
240             //- /lib.rs
241             macro_rules! bar {
242                 () => {
243                     struct Bar;
244                     impl Bar {
245                         /// Do the foo
246                         fn foo(&self) {}
247                     }
248                 }
249             }
250
251             bar!();
252
253             fn foo() {
254                 let bar = Bar;
255                 bar.fo<|>;
256             }
257             "#,
258             DetailAndDocumentation { detail: "fn foo(&self)", documentation: " Do the foo" },
259         );
260     }
261
262     #[test]
263     fn test_no_completions_required() {
264         // There must be no hint for 'in' keyword.
265         check_no_completion(
266             r#"
267             fn foo() {
268                 for i i<|>
269             }
270             "#,
271         );
272         // After 'in' keyword hints may be spawned.
273         check_detail_and_documentation(
274             r#"
275             /// Do the foo
276             fn foo() -> &'static str { "foo" }
277
278             fn bar() {
279                 for c in fo<|>
280             }
281             "#,
282             DetailAndDocumentation {
283                 detail: "fn foo() -> &'static str",
284                 documentation: "Do the foo",
285             },
286         );
287     }
288 }