]> git.lizzy.rs Git - rust.git/blob - crates/completion/src/lib.rs
Reorganize completions structure
[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 presentation;
7 mod patterns;
8 mod generated_lint_completions;
9 #[cfg(test)]
10 mod test_utils;
11
12 mod completions;
13
14 use ide_db::base_db::FilePosition;
15 use ide_db::RootDatabase;
16
17 use crate::{
18     context::CompletionContext,
19     item::{CompletionKind, Completions},
20 };
21
22 pub use crate::{
23     config::CompletionConfig,
24     item::{CompletionItem, CompletionItemKind, CompletionScore, 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.not` -> `!expr`
51 // - `expr.dbg` -> `dbg!(expr)`
52 // - `expr.dbgr` -> `dbg!(&expr)`
53 // - `expr.call` -> `(expr)`
54 //
55 // There also snippet completions:
56 //
57 // .Expressions
58 // - `pd` -> `eprintln!(" = {:?}", );`
59 // - `ppd` -> `eprintln!(" = {:#?}", );`
60 //
61 // .Items
62 // - `tfn` -> `#[test] fn feature(){}`
63 // - `tmod` ->
64 // ```rust
65 // #[cfg(test)]
66 // mod tests {
67 //     use super::*;
68 //
69 //     #[test]
70 //     fn test_name() {}
71 // }
72 // ```
73
74 /// Main entry point for completion. We run completion as a two-phase process.
75 ///
76 /// First, we look at the position and collect a so-called `CompletionContext.
77 /// This is a somewhat messy process, because, during completion, syntax tree is
78 /// incomplete and can look really weird.
79 ///
80 /// Once the context is collected, we run a series of completion routines which
81 /// look at the context and produce completion items. One subtlety about this
82 /// phase is that completion engine should not filter by the substring which is
83 /// already present, it should give all possible variants for the identifier at
84 /// the caret. In other words, for
85 ///
86 /// ```no_run
87 /// fn f() {
88 ///     let foo = 92;
89 ///     let _ = bar<|>
90 /// }
91 /// ```
92 ///
93 /// `foo` *should* be present among the completion variants. Filtering by
94 /// identifier prefix/fuzzy match should be done higher in the stack, together
95 /// with ordering of completions (currently this is done by the client).
96 pub fn completions(
97     db: &RootDatabase,
98     config: &CompletionConfig,
99     position: FilePosition,
100 ) -> Option<Completions> {
101     let ctx = CompletionContext::new(db, position, config)?;
102
103     if ctx.no_completion_required() {
104         // No work required here.
105         return None;
106     }
107
108     let mut acc = Completions::default();
109     completions::attribute::complete_attribute(&mut acc, &ctx);
110     completions::fn_param::complete_fn_param(&mut acc, &ctx);
111     completions::keyword::complete_expr_keyword(&mut acc, &ctx);
112     completions::keyword::complete_use_tree_keyword(&mut acc, &ctx);
113     completions::snippet::complete_expr_snippet(&mut acc, &ctx);
114     completions::snippet::complete_item_snippet(&mut acc, &ctx);
115     completions::qualified_path::complete_qualified_path(&mut acc, &ctx);
116     completions::unqualified_path::complete_unqualified_path(&mut acc, &ctx);
117     completions::dot::complete_dot(&mut acc, &ctx);
118     completions::record::complete_record(&mut acc, &ctx);
119     completions::pattern::complete_pattern(&mut acc, &ctx);
120     completions::postfix::complete_postfix(&mut acc, &ctx);
121     completions::macro_in_item_position::complete_macro_in_item_position(&mut acc, &ctx);
122     completions::trait_impl::complete_trait_impl(&mut acc, &ctx);
123     completions::mod_::complete_mod(&mut acc, &ctx);
124
125     Some(acc)
126 }
127
128 #[cfg(test)]
129 mod tests {
130     use crate::config::CompletionConfig;
131     use crate::test_utils;
132
133     struct DetailAndDocumentation<'a> {
134         detail: &'a str,
135         documentation: &'a str,
136     }
137
138     fn check_detail_and_documentation(ra_fixture: &str, expected: DetailAndDocumentation) {
139         let (db, position) = test_utils::position(ra_fixture);
140         let config = CompletionConfig::default();
141         let completions: Vec<_> = crate::completions(&db, &config, position).unwrap().into();
142         for item in completions {
143             if item.detail() == Some(expected.detail) {
144                 let opt = item.documentation();
145                 let doc = opt.as_ref().map(|it| it.as_str());
146                 assert_eq!(doc, Some(expected.documentation));
147                 return;
148             }
149         }
150         panic!("completion detail not found: {}", expected.detail)
151     }
152
153     fn check_no_completion(ra_fixture: &str) {
154         let (db, position) = test_utils::position(ra_fixture);
155         let config = CompletionConfig::default();
156
157         let completions: Option<Vec<String>> = crate::completions(&db, &config, position)
158             .and_then(|completions| {
159                 let completions: Vec<_> = completions.into();
160                 if completions.is_empty() {
161                     None
162                 } else {
163                     Some(completions)
164                 }
165             })
166             .map(|completions| {
167                 completions.into_iter().map(|completion| format!("{:?}", completion)).collect()
168             });
169
170         // `assert_eq` instead of `assert!(completions.is_none())` to get the list of completions if test will panic.
171         assert_eq!(completions, None, "Completions were generated, but weren't expected");
172     }
173
174     #[test]
175     fn test_completion_detail_from_macro_generated_struct_fn_doc_attr() {
176         check_detail_and_documentation(
177             r#"
178             //- /lib.rs
179             macro_rules! bar {
180                 () => {
181                     struct Bar;
182                     impl Bar {
183                         #[doc = "Do the foo"]
184                         fn foo(&self) {}
185                     }
186                 }
187             }
188
189             bar!();
190
191             fn foo() {
192                 let bar = Bar;
193                 bar.fo<|>;
194             }
195             "#,
196             DetailAndDocumentation { detail: "fn foo(&self)", documentation: "Do the foo" },
197         );
198     }
199
200     #[test]
201     fn test_completion_detail_from_macro_generated_struct_fn_doc_comment() {
202         check_detail_and_documentation(
203             r#"
204             //- /lib.rs
205             macro_rules! bar {
206                 () => {
207                     struct Bar;
208                     impl Bar {
209                         /// Do the foo
210                         fn foo(&self) {}
211                     }
212                 }
213             }
214
215             bar!();
216
217             fn foo() {
218                 let bar = Bar;
219                 bar.fo<|>;
220             }
221             "#,
222             DetailAndDocumentation { detail: "fn foo(&self)", documentation: " Do the foo" },
223         );
224     }
225
226     #[test]
227     fn test_no_completions_required() {
228         // There must be no hint for 'in' keyword.
229         check_no_completion(
230             r#"
231             fn foo() {
232                 for i i<|>
233             }
234             "#,
235         );
236         // After 'in' keyword hints may be spawned.
237         check_detail_and_documentation(
238             r#"
239             /// Do the foo
240             fn foo() -> &'static str { "foo" }
241
242             fn bar() {
243                 for c in fo<|>
244             }
245             "#,
246             DetailAndDocumentation {
247                 detail: "fn foo() -> &'static str",
248                 documentation: "Do the foo",
249             },
250         );
251     }
252 }