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