]> git.lizzy.rs Git - rust.git/blob - crates/completion/src/lib.rs
Merge #6635
[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::base_db::FilePosition;
15 use ide_db::RootDatabase;
16
17 use crate::{completions::Completions, context::CompletionContext, item::CompletionKind};
18
19 pub use crate::{
20     config::CompletionConfig,
21     item::{CompletionItem, CompletionItemKind, CompletionScore, InsertTextFormat},
22 };
23
24 //FIXME: split the following feature into fine-grained features.
25
26 // Feature: Magic Completions
27 //
28 // In addition to usual reference completion, rust-analyzer provides some ✨magic✨
29 // completions as well:
30 //
31 // Keywords like `if`, `else` `while`, `loop` are completed with braces, and cursor
32 // is placed at the appropriate position. Even though `if` is easy to type, you
33 // still want to complete it, to get ` { }` for free! `return` is inserted with a
34 // space or `;` depending on the return type of the function.
35 //
36 // When completing a function call, `()` are automatically inserted. If a function
37 // takes arguments, the cursor is positioned inside the parenthesis.
38 //
39 // There are postfix completions, which can be triggered by typing something like
40 // `foo().if`. The word after `.` determines postfix completion. Possible variants are:
41 //
42 // - `expr.if` -> `if expr {}` or `if let ... {}` for `Option` or `Result`
43 // - `expr.match` -> `match expr {}`
44 // - `expr.while` -> `while expr {}` or `while let ... {}` for `Option` or `Result`
45 // - `expr.ref` -> `&expr`
46 // - `expr.refm` -> `&mut expr`
47 // - `expr.not` -> `!expr`
48 // - `expr.dbg` -> `dbg!(expr)`
49 // - `expr.dbgr` -> `dbg!(&expr)`
50 // - `expr.call` -> `(expr)`
51 //
52 // There also snippet completions:
53 //
54 // .Expressions
55 // - `pd` -> `eprintln!(" = {:?}", );`
56 // - `ppd` -> `eprintln!(" = {:#?}", );`
57 //
58 // .Items
59 // - `tfn` -> `#[test] fn feature(){}`
60 // - `tmod` ->
61 // ```rust
62 // #[cfg(test)]
63 // mod tests {
64 //     use super::*;
65 //
66 //     #[test]
67 //     fn test_name() {}
68 // }
69 // ```
70 //
71 // And experimental completions, enabled with the `rust-analyzer.completion.enableExperimental` setting.
72 // This flag enables or disables:
73 //
74 // - Auto import: additional completion options with automatic `use` import and options from all project importable items, matched for the input
75 //
76 // Experimental completions might cause issues with performance and completion list look.
77
78 /// Main entry point for completion. We run completion as a two-phase process.
79 ///
80 /// First, we look at the position and collect a so-called `CompletionContext.
81 /// This is a somewhat messy process, because, during completion, syntax tree is
82 /// incomplete and can look really weird.
83 ///
84 /// Once the context is collected, we run a series of completion routines which
85 /// look at the context and produce completion items. One subtlety about this
86 /// phase is that completion engine should not filter by the substring which is
87 /// already present, it should give all possible variants for the identifier at
88 /// the caret. In other words, for
89 ///
90 /// ```no_run
91 /// fn f() {
92 ///     let foo = 92;
93 ///     let _ = bar<|>
94 /// }
95 /// ```
96 ///
97 /// `foo` *should* be present among the completion variants. Filtering by
98 /// identifier prefix/fuzzy match should be done higher in the stack, together
99 /// with ordering of completions (currently this is done by the client).
100 pub fn completions(
101     db: &RootDatabase,
102     config: &CompletionConfig,
103     position: FilePosition,
104 ) -> Option<Completions> {
105     let ctx = CompletionContext::new(db, position, config)?;
106
107     if ctx.no_completion_required() {
108         // No work required here.
109         return None;
110     }
111
112     let mut acc = Completions::default();
113     completions::attribute::complete_attribute(&mut acc, &ctx);
114     completions::fn_param::complete_fn_param(&mut acc, &ctx);
115     completions::keyword::complete_expr_keyword(&mut acc, &ctx);
116     completions::keyword::complete_use_tree_keyword(&mut acc, &ctx);
117     completions::snippet::complete_expr_snippet(&mut acc, &ctx);
118     completions::snippet::complete_item_snippet(&mut acc, &ctx);
119     completions::qualified_path::complete_qualified_path(&mut acc, &ctx);
120     completions::unqualified_path::complete_unqualified_path(&mut acc, &ctx);
121     completions::dot::complete_dot(&mut acc, &ctx);
122     completions::record::complete_record(&mut acc, &ctx);
123     completions::pattern::complete_pattern(&mut acc, &ctx);
124     completions::postfix::complete_postfix(&mut acc, &ctx);
125     completions::macro_in_item_position::complete_macro_in_item_position(&mut acc, &ctx);
126     completions::trait_impl::complete_trait_impl(&mut acc, &ctx);
127     completions::mod_::complete_mod(&mut acc, &ctx);
128
129     Some(acc)
130 }
131
132 #[cfg(test)]
133 mod tests {
134     use crate::config::CompletionConfig;
135     use crate::test_utils;
136
137     struct DetailAndDocumentation<'a> {
138         detail: &'a str,
139         documentation: &'a str,
140     }
141
142     fn check_detail_and_documentation(ra_fixture: &str, expected: DetailAndDocumentation) {
143         let (db, position) = test_utils::position(ra_fixture);
144         let config = CompletionConfig::default();
145         let completions: Vec<_> = crate::completions(&db, &config, position).unwrap().into();
146         for item in completions {
147             if item.detail() == Some(expected.detail) {
148                 let opt = item.documentation();
149                 let doc = opt.as_ref().map(|it| it.as_str());
150                 assert_eq!(doc, Some(expected.documentation));
151                 return;
152             }
153         }
154         panic!("completion detail not found: {}", expected.detail)
155     }
156
157     fn check_no_completion(ra_fixture: &str) {
158         let (db, position) = test_utils::position(ra_fixture);
159         let config = CompletionConfig::default();
160
161         let completions: Option<Vec<String>> = crate::completions(&db, &config, position)
162             .and_then(|completions| {
163                 let completions: Vec<_> = completions.into();
164                 if completions.is_empty() {
165                     None
166                 } else {
167                     Some(completions)
168                 }
169             })
170             .map(|completions| {
171                 completions.into_iter().map(|completion| format!("{:?}", completion)).collect()
172             });
173
174         // `assert_eq` instead of `assert!(completions.is_none())` to get the list of completions if test will panic.
175         assert_eq!(completions, None, "Completions were generated, but weren't expected");
176     }
177
178     #[test]
179     fn test_completion_detail_from_macro_generated_struct_fn_doc_attr() {
180         check_detail_and_documentation(
181             r#"
182             //- /lib.rs
183             macro_rules! bar {
184                 () => {
185                     struct Bar;
186                     impl Bar {
187                         #[doc = "Do the foo"]
188                         fn foo(&self) {}
189                     }
190                 }
191             }
192
193             bar!();
194
195             fn foo() {
196                 let bar = Bar;
197                 bar.fo<|>;
198             }
199             "#,
200             DetailAndDocumentation { detail: "fn foo(&self)", documentation: "Do the foo" },
201         );
202     }
203
204     #[test]
205     fn test_completion_detail_from_macro_generated_struct_fn_doc_comment() {
206         check_detail_and_documentation(
207             r#"
208             //- /lib.rs
209             macro_rules! bar {
210                 () => {
211                     struct Bar;
212                     impl Bar {
213                         /// Do the foo
214                         fn foo(&self) {}
215                     }
216                 }
217             }
218
219             bar!();
220
221             fn foo() {
222                 let bar = Bar;
223                 bar.fo<|>;
224             }
225             "#,
226             DetailAndDocumentation { detail: "fn foo(&self)", documentation: " Do the foo" },
227         );
228     }
229
230     #[test]
231     fn test_no_completions_required() {
232         // There must be no hint for 'in' keyword.
233         check_no_completion(
234             r#"
235             fn foo() {
236                 for i i<|>
237             }
238             "#,
239         );
240         // After 'in' keyword hints may be spawned.
241         check_detail_and_documentation(
242             r#"
243             /// Do the foo
244             fn foo() -> &'static str { "foo" }
245
246             fn bar() {
247                 for c in fo<|>
248             }
249             "#,
250             DetailAndDocumentation {
251                 detail: "fn foo() -> &'static str",
252                 documentation: "Do the foo",
253             },
254         );
255     }
256 }