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