aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_editor/src/completion.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_editor/src/completion.rs')
-rw-r--r--crates/ra_editor/src/completion.rs602
1 files changed, 0 insertions, 602 deletions
diff --git a/crates/ra_editor/src/completion.rs b/crates/ra_editor/src/completion.rs
deleted file mode 100644
index 20c8546a4..000000000
--- a/crates/ra_editor/src/completion.rs
+++ /dev/null
@@ -1,602 +0,0 @@
1/// FIXME: move completion from ra_editor to ra_analysis
2
3use rustc_hash::{FxHashMap, FxHashSet};
4
5use ra_syntax::{
6 algo::visit::{visitor, visitor_ctx, Visitor, VisitorCtx},
7 ast::{self, AstChildren, LoopBodyOwner, ModuleItemOwner},
8 AstNode, File,
9 SyntaxKind::*,
10 SyntaxNodeRef, TextUnit,
11};
12
13use crate::{
14 find_node_at_offset,
15 scope::{FnScopes, ModuleScope},
16 AtomEdit,
17};
18
19#[derive(Debug)]
20pub struct CompletionItem {
21 /// What user sees in pop-up
22 pub label: String,
23 /// What string is used for filtering, defaults to label
24 pub lookup: Option<String>,
25 /// What is inserted, defaults to label
26 pub snippet: Option<String>,
27}
28
29pub fn scope_completion(file: &File, offset: TextUnit) -> Option<Vec<CompletionItem>> {
30 // Insert a fake ident to get a valid parse tree
31 let file = {
32 let edit = AtomEdit::insert(offset, "intellijRulezz".to_string());
33 file.reparse(&edit)
34 };
35 let mut has_completions = false;
36 let mut res = Vec::new();
37 if let Some(name_ref) = find_node_at_offset::<ast::NameRef>(file.syntax(), offset) {
38 has_completions = true;
39 complete_name_ref(&file, name_ref, &mut res);
40 // special case, `trait T { fn foo(i_am_a_name_ref) {} }`
41 if is_node::<ast::Param>(name_ref.syntax()) {
42 param_completions(name_ref.syntax(), &mut res);
43 }
44 let name_range = name_ref.syntax().range();
45 let top_node = name_ref
46 .syntax()
47 .ancestors()
48 .take_while(|it| it.range() == name_range)
49 .last()
50 .unwrap();
51 match top_node.parent().map(|it| it.kind()) {
52 Some(ROOT) | Some(ITEM_LIST) => complete_mod_item_snippets(&mut res),
53 _ => (),
54 }
55 }
56 if let Some(name) = find_node_at_offset::<ast::Name>(file.syntax(), offset) {
57 if is_node::<ast::Param>(name.syntax()) {
58 has_completions = true;
59 param_completions(name.syntax(), &mut res);
60 }
61 }
62 if has_completions {
63 Some(res)
64 } else {
65 None
66 }
67}
68
69pub fn complete_module_items(items: AstChildren<ast::ModuleItem>, this_item: Option<ast::NameRef>, acc: &mut Vec<CompletionItem>) {
70 let scope = ModuleScope::new(items);
71 acc.extend(
72 scope
73 .entries()
74 .iter()
75 .filter(|entry| Some(entry.syntax()) != this_item.map(|it| it.syntax()))
76 .map(|entry| CompletionItem {
77 label: entry.name().to_string(),
78 lookup: None,
79 snippet: None,
80 }),
81 );
82}
83
84fn complete_name_ref(file: &File, name_ref: ast::NameRef, acc: &mut Vec<CompletionItem>) {
85 if !is_node::<ast::Path>(name_ref.syntax()) {
86 return;
87 }
88 let mut visited_fn = false;
89 for node in name_ref.syntax().ancestors() {
90 if let Some(items) = visitor()
91 .visit::<ast::Root, _>(|it| Some(it.items()))
92 .visit::<ast::Module, _>(|it| Some(it.item_list()?.items()))
93 .accept(node)
94 {
95 if let Some(items) = items {
96 complete_module_items(items, Some(name_ref), acc);
97 }
98 break;
99 } else if !visited_fn {
100 if let Some(fn_def) = ast::FnDef::cast(node) {
101 visited_fn = true;
102 complete_expr_keywords(&file, fn_def, name_ref, acc);
103 complete_expr_snippets(acc);
104 let scopes = FnScopes::new(fn_def);
105 complete_fn(name_ref, &scopes, acc);
106 }
107 }
108 }
109}
110
111fn param_completions(ctx: SyntaxNodeRef, acc: &mut Vec<CompletionItem>) {
112 let mut params = FxHashMap::default();
113 for node in ctx.ancestors() {
114 let _ = visitor_ctx(&mut params)
115 .visit::<ast::Root, _>(process)
116 .visit::<ast::ItemList, _>(process)
117 .accept(node);
118 }
119 params
120 .into_iter()
121 .filter_map(|(label, (count, param))| {
122 let lookup = param.pat()?.syntax().text().to_string();
123 if count < 2 {
124 None
125 } else {
126 Some((label, lookup))
127 }
128 })
129 .for_each(|(label, lookup)| {
130 acc.push(CompletionItem {
131 label,
132 lookup: Some(lookup),
133 snippet: None,
134 })
135 });
136
137 fn process<'a, N: ast::FnDefOwner<'a>>(
138 node: N,
139 params: &mut FxHashMap<String, (u32, ast::Param<'a>)>,
140 ) {
141 node.functions()
142 .filter_map(|it| it.param_list())
143 .flat_map(|it| it.params())
144 .for_each(|param| {
145 let text = param.syntax().text().to_string();
146 params.entry(text).or_insert((0, param)).0 += 1;
147 })
148 }
149}
150
151fn is_node<'a, N: AstNode<'a>>(node: SyntaxNodeRef<'a>) -> bool {
152 match node.ancestors().filter_map(N::cast).next() {
153 None => false,
154 Some(n) => n.syntax().range() == node.range(),
155 }
156}
157
158fn complete_expr_keywords(
159 file: &File,
160 fn_def: ast::FnDef,
161 name_ref: ast::NameRef,
162 acc: &mut Vec<CompletionItem>,
163) {
164 acc.push(keyword("if", "if $0 {}"));
165 acc.push(keyword("match", "match $0 {}"));
166 acc.push(keyword("while", "while $0 {}"));
167 acc.push(keyword("loop", "loop {$0}"));
168
169 if let Some(off) = name_ref.syntax().range().start().checked_sub(2.into()) {
170 if let Some(if_expr) = find_node_at_offset::<ast::IfExpr>(file.syntax(), off) {
171 if if_expr.syntax().range().end() < name_ref.syntax().range().start() {
172 acc.push(keyword("else", "else {$0}"));
173 acc.push(keyword("else if", "else if $0 {}"));
174 }
175 }
176 }
177 if is_in_loop_body(name_ref) {
178 acc.push(keyword("continue", "continue"));
179 acc.push(keyword("break", "break"));
180 }
181 acc.extend(complete_return(fn_def, name_ref));
182}
183
184fn is_in_loop_body(name_ref: ast::NameRef) -> bool {
185 for node in name_ref.syntax().ancestors() {
186 if node.kind() == FN_DEF || node.kind() == LAMBDA_EXPR {
187 break;
188 }
189 let loop_body = visitor()
190 .visit::<ast::ForExpr, _>(LoopBodyOwner::loop_body)
191 .visit::<ast::WhileExpr, _>(LoopBodyOwner::loop_body)
192 .visit::<ast::LoopExpr, _>(LoopBodyOwner::loop_body)
193 .accept(node);
194 if let Some(Some(body)) = loop_body {
195 if name_ref.syntax().range().is_subrange(&body.syntax().range()) {
196 return true;
197 }
198 }
199 }
200 false
201}
202
203fn complete_return(fn_def: ast::FnDef, name_ref: ast::NameRef) -> Option<CompletionItem> {
204 // let is_last_in_block = name_ref.syntax().ancestors().filter_map(ast::Expr::cast)
205 // .next()
206 // .and_then(|it| it.syntax().parent())
207 // .and_then(ast::Block::cast)
208 // .is_some();
209
210 // if is_last_in_block {
211 // return None;
212 // }
213
214 let is_stmt = match name_ref
215 .syntax()
216 .ancestors()
217 .filter_map(ast::ExprStmt::cast)
218 .next()
219 {
220 None => false,
221 Some(expr_stmt) => expr_stmt.syntax().range() == name_ref.syntax().range(),
222 };
223 let snip = match (is_stmt, fn_def.ret_type().is_some()) {
224 (true, true) => "return $0;",
225 (true, false) => "return;",
226 (false, true) => "return $0",
227 (false, false) => "return",
228 };
229 Some(keyword("return", snip))
230}
231
232fn keyword(kw: &str, snip: &str) -> CompletionItem {
233 CompletionItem {
234 label: kw.to_string(),
235 lookup: None,
236 snippet: Some(snip.to_string()),
237 }
238}
239
240fn complete_expr_snippets(acc: &mut Vec<CompletionItem>) {
241 acc.push(CompletionItem {
242 label: "pd".to_string(),
243 lookup: None,
244 snippet: Some("eprintln!(\"$0 = {:?}\", $0);".to_string()),
245 });
246 acc.push(CompletionItem {
247 label: "ppd".to_string(),
248 lookup: None,
249 snippet: Some("eprintln!(\"$0 = {:#?}\", $0);".to_string()),
250 });
251}
252
253fn complete_mod_item_snippets(acc: &mut Vec<CompletionItem>) {
254 acc.push(CompletionItem {
255 label: "tfn".to_string(),
256 lookup: None,
257 snippet: Some("#[test]\nfn $1() {\n $0\n}".to_string()),
258 });
259 acc.push(CompletionItem {
260 label: "pub(crate)".to_string(),
261 lookup: None,
262 snippet: Some("pub(crate) $0".to_string()),
263 })
264}
265
266fn complete_fn(name_ref: ast::NameRef, scopes: &FnScopes, acc: &mut Vec<CompletionItem>) {
267 let mut shadowed = FxHashSet::default();
268 acc.extend(
269 scopes
270 .scope_chain(name_ref.syntax())
271 .flat_map(|scope| scopes.entries(scope).iter())
272 .filter(|entry| shadowed.insert(entry.name()))
273 .map(|entry| CompletionItem {
274 label: entry.name().to_string(),
275 lookup: None,
276 snippet: None,
277 }),
278 );
279 if scopes.self_param.is_some() {
280 acc.push(CompletionItem {
281 label: "self".to_string(),
282 lookup: None,
283 snippet: None,
284 })
285 }
286}
287
288#[cfg(test)]
289mod tests {
290 use super::*;
291 use test_utils::{assert_eq_dbg, extract_offset};
292
293 fn check_scope_completion(code: &str, expected_completions: &str) {
294 let (off, code) = extract_offset(&code);
295 let file = File::parse(&code);
296 let completions = scope_completion(&file, off)
297 .unwrap()
298 .into_iter()
299 .filter(|c| c.snippet.is_none())
300 .collect::<Vec<_>>();
301 assert_eq_dbg(expected_completions, &completions);
302 }
303
304 fn check_snippet_completion(code: &str, expected_completions: &str) {
305 let (off, code) = extract_offset(&code);
306 let file = File::parse(&code);
307 let completions = scope_completion(&file, off)
308 .unwrap()
309 .into_iter()
310 .filter(|c| c.snippet.is_some())
311 .collect::<Vec<_>>();
312 assert_eq_dbg(expected_completions, &completions);
313 }
314
315 #[test]
316 fn test_completion_let_scope() {
317 check_scope_completion(
318 r"
319 fn quux(x: i32) {
320 let y = 92;
321 1 + <|>;
322 let z = ();
323 }
324 ",
325 r#"[CompletionItem { label: "y", lookup: None, snippet: None },
326 CompletionItem { label: "x", lookup: None, snippet: None },
327 CompletionItem { label: "quux", lookup: None, snippet: None }]"#,
328 );
329 }
330
331 #[test]
332 fn test_completion_if_let_scope() {
333 check_scope_completion(
334 r"
335 fn quux() {
336 if let Some(x) = foo() {
337 let y = 92;
338 };
339 if let Some(a) = bar() {
340 let b = 62;
341 1 + <|>
342 }
343 }
344 ",
345 r#"[CompletionItem { label: "b", lookup: None, snippet: None },
346 CompletionItem { label: "a", lookup: None, snippet: None },
347 CompletionItem { label: "quux", lookup: None, snippet: None }]"#,
348 );
349 }
350
351 #[test]
352 fn test_completion_for_scope() {
353 check_scope_completion(
354 r"
355 fn quux() {
356 for x in &[1, 2, 3] {
357 <|>
358 }
359 }
360 ",
361 r#"[CompletionItem { label: "x", lookup: None, snippet: None },
362 CompletionItem { label: "quux", lookup: None, snippet: None }]"#,
363 );
364 }
365
366 #[test]
367 fn test_completion_mod_scope() {
368 check_scope_completion(
369 r"
370 struct Foo;
371 enum Baz {}
372 fn quux() {
373 <|>
374 }
375 ",
376 r#"[CompletionItem { label: "Foo", lookup: None, snippet: None },
377 CompletionItem { label: "Baz", lookup: None, snippet: None },
378 CompletionItem { label: "quux", lookup: None, snippet: None }]"#,
379 );
380 }
381
382 #[test]
383 fn test_completion_mod_scope_no_self_use() {
384 check_scope_completion(
385 r"
386 use foo<|>;
387 ",
388 r#"[]"#,
389 );
390 }
391
392 #[test]
393 fn test_completion_mod_scope_nested() {
394 check_scope_completion(
395 r"
396 struct Foo;
397 mod m {
398 struct Bar;
399 fn quux() { <|> }
400 }
401 ",
402 r#"[CompletionItem { label: "Bar", lookup: None, snippet: None },
403 CompletionItem { label: "quux", lookup: None, snippet: None }]"#,
404 );
405 }
406
407 #[test]
408 fn test_complete_type() {
409 check_scope_completion(
410 r"
411 struct Foo;
412 fn x() -> <|>
413 ",
414 r#"[CompletionItem { label: "Foo", lookup: None, snippet: None },
415 CompletionItem { label: "x", lookup: None, snippet: None }]"#,
416 )
417 }
418
419 #[test]
420 fn test_complete_shadowing() {
421 check_scope_completion(
422 r"
423 fn foo() -> {
424 let bar = 92;
425 {
426 let bar = 62;
427 <|>
428 }
429 }
430 ",
431 r#"[CompletionItem { label: "bar", lookup: None, snippet: None },
432 CompletionItem { label: "foo", lookup: None, snippet: None }]"#,
433 )
434 }
435
436 #[test]
437 fn test_complete_self() {
438 check_scope_completion(
439 r"
440 impl S { fn foo(&self) { <|> } }
441 ",
442 r#"[CompletionItem { label: "self", lookup: None, snippet: None }]"#,
443 )
444 }
445
446 #[test]
447 fn test_completion_kewords() {
448 check_snippet_completion(r"
449 fn quux() {
450 <|>
451 }
452 ", r#"[CompletionItem { label: "if", lookup: None, snippet: Some("if $0 {}") },
453 CompletionItem { label: "match", lookup: None, snippet: Some("match $0 {}") },
454 CompletionItem { label: "while", lookup: None, snippet: Some("while $0 {}") },
455 CompletionItem { label: "loop", lookup: None, snippet: Some("loop {$0}") },
456 CompletionItem { label: "return", lookup: None, snippet: Some("return") },
457 CompletionItem { label: "pd", lookup: None, snippet: Some("eprintln!(\"$0 = {:?}\", $0);") },
458 CompletionItem { label: "ppd", lookup: None, snippet: Some("eprintln!(\"$0 = {:#?}\", $0);") }]"#);
459 }
460
461 #[test]
462 fn test_completion_else() {
463 check_snippet_completion(r"
464 fn quux() {
465 if true {
466 ()
467 } <|>
468 }
469 ", r#"[CompletionItem { label: "if", lookup: None, snippet: Some("if $0 {}") },
470 CompletionItem { label: "match", lookup: None, snippet: Some("match $0 {}") },
471 CompletionItem { label: "while", lookup: None, snippet: Some("while $0 {}") },
472 CompletionItem { label: "loop", lookup: None, snippet: Some("loop {$0}") },
473 CompletionItem { label: "else", lookup: None, snippet: Some("else {$0}") },
474 CompletionItem { label: "else if", lookup: None, snippet: Some("else if $0 {}") },
475 CompletionItem { label: "return", lookup: None, snippet: Some("return") },
476 CompletionItem { label: "pd", lookup: None, snippet: Some("eprintln!(\"$0 = {:?}\", $0);") },
477 CompletionItem { label: "ppd", lookup: None, snippet: Some("eprintln!(\"$0 = {:#?}\", $0);") }]"#);
478 }
479
480 #[test]
481 fn test_completion_return_value() {
482 check_snippet_completion(r"
483 fn quux() -> i32 {
484 <|>
485 92
486 }
487 ", r#"[CompletionItem { label: "if", lookup: None, snippet: Some("if $0 {}") },
488 CompletionItem { label: "match", lookup: None, snippet: Some("match $0 {}") },
489 CompletionItem { label: "while", lookup: None, snippet: Some("while $0 {}") },
490 CompletionItem { label: "loop", lookup: None, snippet: Some("loop {$0}") },
491 CompletionItem { label: "return", lookup: None, snippet: Some("return $0;") },
492 CompletionItem { label: "pd", lookup: None, snippet: Some("eprintln!(\"$0 = {:?}\", $0);") },
493 CompletionItem { label: "ppd", lookup: None, snippet: Some("eprintln!(\"$0 = {:#?}\", $0);") }]"#);
494 check_snippet_completion(r"
495 fn quux() {
496 <|>
497 92
498 }
499 ", r#"[CompletionItem { label: "if", lookup: None, snippet: Some("if $0 {}") },
500 CompletionItem { label: "match", lookup: None, snippet: Some("match $0 {}") },
501 CompletionItem { label: "while", lookup: None, snippet: Some("while $0 {}") },
502 CompletionItem { label: "loop", lookup: None, snippet: Some("loop {$0}") },
503 CompletionItem { label: "return", lookup: None, snippet: Some("return;") },
504 CompletionItem { label: "pd", lookup: None, snippet: Some("eprintln!(\"$0 = {:?}\", $0);") },
505 CompletionItem { label: "ppd", lookup: None, snippet: Some("eprintln!(\"$0 = {:#?}\", $0);") }]"#);
506 }
507
508 #[test]
509 fn test_completion_return_no_stmt() {
510 check_snippet_completion(r"
511 fn quux() -> i32 {
512 match () {
513 () => <|>
514 }
515 }
516 ", r#"[CompletionItem { label: "if", lookup: None, snippet: Some("if $0 {}") },
517 CompletionItem { label: "match", lookup: None, snippet: Some("match $0 {}") },
518 CompletionItem { label: "while", lookup: None, snippet: Some("while $0 {}") },
519 CompletionItem { label: "loop", lookup: None, snippet: Some("loop {$0}") },
520 CompletionItem { label: "return", lookup: None, snippet: Some("return $0") },
521 CompletionItem { label: "pd", lookup: None, snippet: Some("eprintln!(\"$0 = {:?}\", $0);") },
522 CompletionItem { label: "ppd", lookup: None, snippet: Some("eprintln!(\"$0 = {:#?}\", $0);") }]"#);
523 }
524
525 #[test]
526 fn test_continue_break_completion() {
527 check_snippet_completion(r"
528 fn quux() -> i32 {
529 loop { <|> }
530 }
531 ", r#"[CompletionItem { label: "if", lookup: None, snippet: Some("if $0 {}") },
532 CompletionItem { label: "match", lookup: None, snippet: Some("match $0 {}") },
533 CompletionItem { label: "while", lookup: None, snippet: Some("while $0 {}") },
534 CompletionItem { label: "loop", lookup: None, snippet: Some("loop {$0}") },
535 CompletionItem { label: "continue", lookup: None, snippet: Some("continue") },
536 CompletionItem { label: "break", lookup: None, snippet: Some("break") },
537 CompletionItem { label: "return", lookup: None, snippet: Some("return $0") },
538 CompletionItem { label: "pd", lookup: None, snippet: Some("eprintln!(\"$0 = {:?}\", $0);") },
539 CompletionItem { label: "ppd", lookup: None, snippet: Some("eprintln!(\"$0 = {:#?}\", $0);") }]"#);
540 check_snippet_completion(r"
541 fn quux() -> i32 {
542 loop { || { <|> } }
543 }
544 ", r#"[CompletionItem { label: "if", lookup: None, snippet: Some("if $0 {}") },
545 CompletionItem { label: "match", lookup: None, snippet: Some("match $0 {}") },
546 CompletionItem { label: "while", lookup: None, snippet: Some("while $0 {}") },
547 CompletionItem { label: "loop", lookup: None, snippet: Some("loop {$0}") },
548 CompletionItem { label: "return", lookup: None, snippet: Some("return $0") },
549 CompletionItem { label: "pd", lookup: None, snippet: Some("eprintln!(\"$0 = {:?}\", $0);") },
550 CompletionItem { label: "ppd", lookup: None, snippet: Some("eprintln!(\"$0 = {:#?}\", $0);") }]"#);
551 }
552
553 #[test]
554 fn test_param_completion_last_param() {
555 check_scope_completion(r"
556 fn foo(file_id: FileId) {}
557 fn bar(file_id: FileId) {}
558 fn baz(file<|>) {}
559 ", r#"[CompletionItem { label: "file_id: FileId", lookup: Some("file_id"), snippet: None }]"#);
560 }
561
562 #[test]
563 fn test_param_completion_nth_param() {
564 check_scope_completion(r"
565 fn foo(file_id: FileId) {}
566 fn bar(file_id: FileId) {}
567 fn baz(file<|>, x: i32) {}
568 ", r#"[CompletionItem { label: "file_id: FileId", lookup: Some("file_id"), snippet: None }]"#);
569 }
570
571 #[test]
572 fn test_param_completion_trait_param() {
573 check_scope_completion(r"
574 pub(crate) trait SourceRoot {
575 pub fn contains(&self, file_id: FileId) -> bool;
576 pub fn module_map(&self) -> &ModuleMap;
577 pub fn lines(&self, file_id: FileId) -> &LineIndex;
578 pub fn syntax(&self, file<|>)
579 }
580 ", r#"[CompletionItem { label: "self", lookup: None, snippet: None },
581 CompletionItem { label: "SourceRoot", lookup: None, snippet: None },
582 CompletionItem { label: "file_id: FileId", lookup: Some("file_id"), snippet: None }]"#);
583 }
584
585 #[test]
586 fn test_item_snippets() {
587 // check_snippet_completion(r"
588 // <|>
589 // ",
590 // r##"[CompletionItem { label: "tfn", lookup: None, snippet: Some("#[test]\nfn $1() {\n $0\n}") }]"##,
591 // );
592 check_snippet_completion(r"
593 #[cfg(test)]
594 mod tests {
595 <|>
596 }
597 ",
598 r##"[CompletionItem { label: "tfn", lookup: None, snippet: Some("#[test]\nfn $1() {\n $0\n}") },
599 CompletionItem { label: "pub(crate)", lookup: None, snippet: Some("pub(crate) $0") }]"##,
600 );
601 }
602}