]> git.lizzy.rs Git - rust.git/blob - crates/completion/src/lib.rs
c689b0ddee57b36c6fd3f5de41be29346c021ff9
[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, CompletionResolveCapability},
21     item::{CompletionItem, CompletionItemKind, CompletionScore, ImportToAdd, 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.let` -> `let <|> = expr;`
48 // - `expr.letm` -> `let mut <|> = expr;`
49 // - `expr.not` -> `!expr`
50 // - `expr.dbg` -> `dbg!(expr)`
51 // - `expr.dbgr` -> `dbg!(&expr)`
52 // - `expr.call` -> `(expr)`
53 //
54 // There also snippet completions:
55 //
56 // .Expressions
57 // - `pd` -> `eprintln!(" = {:?}", );`
58 // - `ppd` -> `eprintln!(" = {:#?}", );`
59 //
60 // .Items
61 // - `tfn` -> `#[test] fn feature(){}`
62 // - `tmod` ->
63 // ```rust
64 // #[cfg(test)]
65 // mod tests {
66 //     use super::*;
67 //
68 //     #[test]
69 //     fn test_name() {}
70 // }
71 // ```
72 //
73 // And experimental completions, enabled with the `rust-analyzer.completion.enableExperimental` setting.
74 // This flag enables or disables:
75 //
76 // - Auto import: additional completion options with automatic `use` import and options from all project importable items, matched for the input
77 //
78 // Experimental completions might cause issues with performance and completion list look.
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<|>
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).
102 pub 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
131     Some(acc)
132 }
133
134 #[cfg(test)]
135 mod tests {
136     use crate::config::CompletionConfig;
137     use crate::test_utils;
138
139     struct DetailAndDocumentation<'a> {
140         detail: &'a str,
141         documentation: &'a str,
142     }
143
144     fn check_detail_and_documentation(ra_fixture: &str, expected: DetailAndDocumentation) {
145         let (db, position) = test_utils::position(ra_fixture);
146         let config = CompletionConfig::default();
147         let completions: Vec<_> = crate::completions(&db, &config, position).unwrap().into();
148         for item in completions {
149             if item.detail() == Some(expected.detail) {
150                 let opt = item.documentation();
151                 let doc = opt.as_ref().map(|it| it.as_str());
152                 assert_eq!(doc, Some(expected.documentation));
153                 return;
154             }
155         }
156         panic!("completion detail not found: {}", expected.detail)
157     }
158
159     fn check_no_completion(ra_fixture: &str) {
160         let (db, position) = test_utils::position(ra_fixture);
161         let config = CompletionConfig::default();
162
163         let completions: Option<Vec<String>> = crate::completions(&db, &config, position)
164             .and_then(|completions| {
165                 let completions: Vec<_> = completions.into();
166                 if completions.is_empty() {
167                     None
168                 } else {
169                     Some(completions)
170                 }
171             })
172             .map(|completions| {
173                 completions.into_iter().map(|completion| format!("{:?}", completion)).collect()
174             });
175
176         // `assert_eq` instead of `assert!(completions.is_none())` to get the list of completions if test will panic.
177         assert_eq!(completions, None, "Completions were generated, but weren't expected");
178     }
179
180     #[test]
181     fn test_completion_detail_from_macro_generated_struct_fn_doc_attr() {
182         check_detail_and_documentation(
183             r#"
184             //- /lib.rs
185             macro_rules! bar {
186                 () => {
187                     struct Bar;
188                     impl Bar {
189                         #[doc = "Do the foo"]
190                         fn foo(&self) {}
191                     }
192                 }
193             }
194
195             bar!();
196
197             fn foo() {
198                 let bar = Bar;
199                 bar.fo<|>;
200             }
201             "#,
202             DetailAndDocumentation { detail: "fn foo(&self)", documentation: "Do the foo" },
203         );
204     }
205
206     #[test]
207     fn test_completion_detail_from_macro_generated_struct_fn_doc_comment() {
208         check_detail_and_documentation(
209             r#"
210             //- /lib.rs
211             macro_rules! bar {
212                 () => {
213                     struct Bar;
214                     impl Bar {
215                         /// Do the foo
216                         fn foo(&self) {}
217                     }
218                 }
219             }
220
221             bar!();
222
223             fn foo() {
224                 let bar = Bar;
225                 bar.fo<|>;
226             }
227             "#,
228             DetailAndDocumentation { detail: "fn foo(&self)", documentation: " Do the foo" },
229         );
230     }
231
232     #[test]
233     fn test_no_completions_required() {
234         // There must be no hint for 'in' keyword.
235         check_no_completion(
236             r#"
237             fn foo() {
238                 for i i<|>
239             }
240             "#,
241         );
242         // After 'in' keyword hints may be spawned.
243         check_detail_and_documentation(
244             r#"
245             /// Do the foo
246             fn foo() -> &'static str { "foo" }
247
248             fn bar() {
249                 for c in fo<|>
250             }
251             "#,
252             DetailAndDocumentation {
253                 detail: "fn foo() -> &'static str",
254                 documentation: "Do the foo",
255             },
256         );
257     }
258 }