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