diff options
Diffstat (limited to 'crates/ra_analysis/src')
-rw-r--r-- | crates/ra_analysis/src/completion.rs | 623 | ||||
-rw-r--r-- | crates/ra_analysis/src/db.rs | 9 | ||||
-rw-r--r-- | crates/ra_analysis/src/descriptors/function/imp.rs | 26 | ||||
-rw-r--r-- | crates/ra_analysis/src/descriptors/function/mod.rs | 83 | ||||
-rw-r--r-- | crates/ra_analysis/src/descriptors/function/scope.rs | 433 | ||||
-rw-r--r-- | crates/ra_analysis/src/descriptors/mod.rs | 88 | ||||
-rw-r--r-- | crates/ra_analysis/src/descriptors/module/imp.rs | 19 | ||||
-rw-r--r-- | crates/ra_analysis/src/descriptors/module/mod.rs | 28 | ||||
-rw-r--r-- | crates/ra_analysis/src/descriptors/module/scope.rs | 12 | ||||
-rw-r--r-- | crates/ra_analysis/src/imp.rs | 37 | ||||
-rw-r--r-- | crates/ra_analysis/src/lib.rs | 11 | ||||
-rw-r--r-- | crates/ra_analysis/src/mock_analysis.rs | 71 | ||||
-rw-r--r-- | crates/ra_analysis/src/syntax_ptr.rs | 5 |
13 files changed, 1334 insertions, 111 deletions
diff --git a/crates/ra_analysis/src/completion.rs b/crates/ra_analysis/src/completion.rs index 0141d132e..340ae3f66 100644 --- a/crates/ra_analysis/src/completion.rs +++ b/crates/ra_analysis/src/completion.rs | |||
@@ -1,16 +1,32 @@ | |||
1 | use ra_editor::{CompletionItem, find_node_at_offset}; | 1 | use rustc_hash::{FxHashMap, FxHashSet}; |
2 | use ra_editor::{find_node_at_offset}; | ||
2 | use ra_syntax::{ | 3 | use ra_syntax::{ |
3 | AtomEdit, File, TextUnit, AstNode, | 4 | AtomEdit, File, TextUnit, AstNode, SyntaxNodeRef, |
4 | ast::{self, ModuleItemOwner, AstChildren}, | 5 | algo::visit::{visitor, visitor_ctx, Visitor, VisitorCtx}, |
6 | ast::{self, AstChildren, LoopBodyOwner, ModuleItemOwner}, | ||
7 | SyntaxKind::*, | ||
5 | }; | 8 | }; |
6 | 9 | ||
7 | use crate::{ | 10 | use crate::{ |
8 | FileId, Cancelable, | 11 | FileId, Cancelable, |
9 | input::FilesDatabase, | 12 | input::FilesDatabase, |
10 | db::{self, SyntaxDatabase}, | 13 | db::{self, SyntaxDatabase}, |
11 | descriptors::module::{ModulesDatabase, ModuleTree, ModuleId, scope::ModuleScope}, | 14 | descriptors::DescriptorDatabase, |
15 | descriptors::function::FnScopes, | ||
16 | descriptors::module::{ModuleTree, ModuleId, ModuleScope}, | ||
12 | }; | 17 | }; |
13 | 18 | ||
19 | |||
20 | #[derive(Debug)] | ||
21 | pub struct CompletionItem { | ||
22 | /// What user sees in pop-up | ||
23 | pub label: String, | ||
24 | /// What string is used for filtering, defaults to label | ||
25 | pub lookup: Option<String>, | ||
26 | /// What is inserted, defaults to label | ||
27 | pub snippet: Option<String>, | ||
28 | } | ||
29 | |||
14 | pub(crate) fn resolve_based_completion(db: &db::RootDatabase, file_id: FileId, offset: TextUnit) -> Cancelable<Option<Vec<CompletionItem>>> { | 30 | pub(crate) fn resolve_based_completion(db: &db::RootDatabase, file_id: FileId, offset: TextUnit) -> Cancelable<Option<Vec<CompletionItem>>> { |
15 | let source_root_id = db.file_source_root(file_id); | 31 | let source_root_id = db.file_source_root(file_id); |
16 | let file = db.file_syntax(file_id); | 32 | let file = db.file_syntax(file_id); |
@@ -72,3 +88,602 @@ fn crate_path(name_ref: ast::NameRef) -> Option<Vec<ast::NameRef>> { | |||
72 | res.reverse(); | 88 | res.reverse(); |
73 | Some(res) | 89 | Some(res) |
74 | } | 90 | } |
91 | |||
92 | |||
93 | pub(crate) fn scope_completion( | ||
94 | db: &db::RootDatabase, | ||
95 | file_id: FileId, | ||
96 | offset: TextUnit, | ||
97 | ) -> Option<Vec<CompletionItem>> { | ||
98 | let original_file = db.file_syntax(file_id); | ||
99 | // Insert a fake ident to get a valid parse tree | ||
100 | let file = { | ||
101 | let edit = AtomEdit::insert(offset, "intellijRulezz".to_string()); | ||
102 | original_file.reparse(&edit) | ||
103 | }; | ||
104 | let mut has_completions = false; | ||
105 | let mut res = Vec::new(); | ||
106 | if let Some(name_ref) = find_node_at_offset::<ast::NameRef>(file.syntax(), offset) { | ||
107 | has_completions = true; | ||
108 | complete_name_ref(&file, name_ref, &mut res); | ||
109 | // special case, `trait T { fn foo(i_am_a_name_ref) {} }` | ||
110 | if is_node::<ast::Param>(name_ref.syntax()) { | ||
111 | param_completions(name_ref.syntax(), &mut res); | ||
112 | } | ||
113 | let name_range = name_ref.syntax().range(); | ||
114 | let top_node = name_ref | ||
115 | .syntax() | ||
116 | .ancestors() | ||
117 | .take_while(|it| it.range() == name_range) | ||
118 | .last() | ||
119 | .unwrap(); | ||
120 | match top_node.parent().map(|it| it.kind()) { | ||
121 | Some(ROOT) | Some(ITEM_LIST) => complete_mod_item_snippets(&mut res), | ||
122 | _ => (), | ||
123 | } | ||
124 | } | ||
125 | if let Some(name) = find_node_at_offset::<ast::Name>(file.syntax(), offset) { | ||
126 | if is_node::<ast::Param>(name.syntax()) { | ||
127 | has_completions = true; | ||
128 | param_completions(name.syntax(), &mut res); | ||
129 | } | ||
130 | } | ||
131 | if has_completions { | ||
132 | Some(res) | ||
133 | } else { | ||
134 | None | ||
135 | } | ||
136 | } | ||
137 | |||
138 | fn complete_module_items( | ||
139 | file: &File, | ||
140 | items: AstChildren<ast::ModuleItem>, | ||
141 | this_item: Option<ast::NameRef>, | ||
142 | acc: &mut Vec<CompletionItem>, | ||
143 | ) { | ||
144 | let scope = ModuleScope::from_items(items); | ||
145 | acc.extend( | ||
146 | scope | ||
147 | .entries() | ||
148 | .iter() | ||
149 | .filter(|entry| { | ||
150 | let syntax = entry.ptr().resolve(file); | ||
151 | Some(syntax.borrowed()) != this_item.map(|it| it.syntax()) | ||
152 | }) | ||
153 | .map(|entry| CompletionItem { | ||
154 | label: entry.name().to_string(), | ||
155 | lookup: None, | ||
156 | snippet: None, | ||
157 | }), | ||
158 | ); | ||
159 | } | ||
160 | |||
161 | fn complete_name_ref( | ||
162 | file: &File, | ||
163 | name_ref: ast::NameRef, | ||
164 | acc: &mut Vec<CompletionItem>, | ||
165 | ) { | ||
166 | if !is_node::<ast::Path>(name_ref.syntax()) { | ||
167 | return; | ||
168 | } | ||
169 | let mut visited_fn = false; | ||
170 | for node in name_ref.syntax().ancestors() { | ||
171 | if let Some(items) = visitor() | ||
172 | .visit::<ast::Root, _>(|it| Some(it.items())) | ||
173 | .visit::<ast::Module, _>(|it| Some(it.item_list()?.items())) | ||
174 | .accept(node) | ||
175 | { | ||
176 | if let Some(items) = items { | ||
177 | complete_module_items(file, items, Some(name_ref), acc); | ||
178 | } | ||
179 | break; | ||
180 | } else if !visited_fn { | ||
181 | if let Some(fn_def) = ast::FnDef::cast(node) { | ||
182 | visited_fn = true; | ||
183 | complete_expr_keywords(&file, fn_def, name_ref, acc); | ||
184 | complete_expr_snippets(acc); | ||
185 | let scopes = FnScopes::new(fn_def); | ||
186 | complete_fn(name_ref, &scopes, acc); | ||
187 | } | ||
188 | } | ||
189 | } | ||
190 | } | ||
191 | |||
192 | fn param_completions(ctx: SyntaxNodeRef, acc: &mut Vec<CompletionItem>) { | ||
193 | let mut params = FxHashMap::default(); | ||
194 | for node in ctx.ancestors() { | ||
195 | let _ = visitor_ctx(&mut params) | ||
196 | .visit::<ast::Root, _>(process) | ||
197 | .visit::<ast::ItemList, _>(process) | ||
198 | .accept(node); | ||
199 | } | ||
200 | params | ||
201 | .into_iter() | ||
202 | .filter_map(|(label, (count, param))| { | ||
203 | let lookup = param.pat()?.syntax().text().to_string(); | ||
204 | if count < 2 { | ||
205 | None | ||
206 | } else { | ||
207 | Some((label, lookup)) | ||
208 | } | ||
209 | }) | ||
210 | .for_each(|(label, lookup)| { | ||
211 | acc.push(CompletionItem { | ||
212 | label, | ||
213 | lookup: Some(lookup), | ||
214 | snippet: None, | ||
215 | }) | ||
216 | }); | ||
217 | |||
218 | fn process<'a, N: ast::FnDefOwner<'a>>( | ||
219 | node: N, | ||
220 | params: &mut FxHashMap<String, (u32, ast::Param<'a>)>, | ||
221 | ) { | ||
222 | node.functions() | ||
223 | .filter_map(|it| it.param_list()) | ||
224 | .flat_map(|it| it.params()) | ||
225 | .for_each(|param| { | ||
226 | let text = param.syntax().text().to_string(); | ||
227 | params.entry(text).or_insert((0, param)).0 += 1; | ||
228 | }) | ||
229 | } | ||
230 | } | ||
231 | |||
232 | fn is_node<'a, N: AstNode<'a>>(node: SyntaxNodeRef<'a>) -> bool { | ||
233 | match node.ancestors().filter_map(N::cast).next() { | ||
234 | None => false, | ||
235 | Some(n) => n.syntax().range() == node.range(), | ||
236 | } | ||
237 | } | ||
238 | |||
239 | fn complete_expr_keywords( | ||
240 | file: &File, | ||
241 | fn_def: ast::FnDef, | ||
242 | name_ref: ast::NameRef, | ||
243 | acc: &mut Vec<CompletionItem>, | ||
244 | ) { | ||
245 | acc.push(keyword("if", "if $0 {}")); | ||
246 | acc.push(keyword("match", "match $0 {}")); | ||
247 | acc.push(keyword("while", "while $0 {}")); | ||
248 | acc.push(keyword("loop", "loop {$0}")); | ||
249 | |||
250 | if let Some(off) = name_ref.syntax().range().start().checked_sub(2.into()) { | ||
251 | if let Some(if_expr) = find_node_at_offset::<ast::IfExpr>(file.syntax(), off) { | ||
252 | if if_expr.syntax().range().end() < name_ref.syntax().range().start() { | ||
253 | acc.push(keyword("else", "else {$0}")); | ||
254 | acc.push(keyword("else if", "else if $0 {}")); | ||
255 | } | ||
256 | } | ||
257 | } | ||
258 | if is_in_loop_body(name_ref) { | ||
259 | acc.push(keyword("continue", "continue")); | ||
260 | acc.push(keyword("break", "break")); | ||
261 | } | ||
262 | acc.extend(complete_return(fn_def, name_ref)); | ||
263 | } | ||
264 | |||
265 | fn is_in_loop_body(name_ref: ast::NameRef) -> bool { | ||
266 | for node in name_ref.syntax().ancestors() { | ||
267 | if node.kind() == FN_DEF || node.kind() == LAMBDA_EXPR { | ||
268 | break; | ||
269 | } | ||
270 | let loop_body = visitor() | ||
271 | .visit::<ast::ForExpr, _>(LoopBodyOwner::loop_body) | ||
272 | .visit::<ast::WhileExpr, _>(LoopBodyOwner::loop_body) | ||
273 | .visit::<ast::LoopExpr, _>(LoopBodyOwner::loop_body) | ||
274 | .accept(node); | ||
275 | if let Some(Some(body)) = loop_body { | ||
276 | if name_ref.syntax().range().is_subrange(&body.syntax().range()) { | ||
277 | return true; | ||
278 | } | ||
279 | } | ||
280 | } | ||
281 | false | ||
282 | } | ||
283 | |||
284 | fn complete_return(fn_def: ast::FnDef, name_ref: ast::NameRef) -> Option<CompletionItem> { | ||
285 | // let is_last_in_block = name_ref.syntax().ancestors().filter_map(ast::Expr::cast) | ||
286 | // .next() | ||
287 | // .and_then(|it| it.syntax().parent()) | ||
288 | // .and_then(ast::Block::cast) | ||
289 | // .is_some(); | ||
290 | |||
291 | // if is_last_in_block { | ||
292 | // return None; | ||
293 | // } | ||
294 | |||
295 | let is_stmt = match name_ref | ||
296 | .syntax() | ||
297 | .ancestors() | ||
298 | .filter_map(ast::ExprStmt::cast) | ||
299 | .next() | ||
300 | { | ||
301 | None => false, | ||
302 | Some(expr_stmt) => expr_stmt.syntax().range() == name_ref.syntax().range(), | ||
303 | }; | ||
304 | let snip = match (is_stmt, fn_def.ret_type().is_some()) { | ||
305 | (true, true) => "return $0;", | ||
306 | (true, false) => "return;", | ||
307 | (false, true) => "return $0", | ||
308 | (false, false) => "return", | ||
309 | }; | ||
310 | Some(keyword("return", snip)) | ||
311 | } | ||
312 | |||
313 | fn keyword(kw: &str, snip: &str) -> CompletionItem { | ||
314 | CompletionItem { | ||
315 | label: kw.to_string(), | ||
316 | lookup: None, | ||
317 | snippet: Some(snip.to_string()), | ||
318 | } | ||
319 | } | ||
320 | |||
321 | fn complete_expr_snippets(acc: &mut Vec<CompletionItem>) { | ||
322 | acc.push(CompletionItem { | ||
323 | label: "pd".to_string(), | ||
324 | lookup: None, | ||
325 | snippet: Some("eprintln!(\"$0 = {:?}\", $0);".to_string()), | ||
326 | }); | ||
327 | acc.push(CompletionItem { | ||
328 | label: "ppd".to_string(), | ||
329 | lookup: None, | ||
330 | snippet: Some("eprintln!(\"$0 = {:#?}\", $0);".to_string()), | ||
331 | }); | ||
332 | } | ||
333 | |||
334 | fn complete_mod_item_snippets(acc: &mut Vec<CompletionItem>) { | ||
335 | acc.push(CompletionItem { | ||
336 | label: "tfn".to_string(), | ||
337 | lookup: None, | ||
338 | snippet: Some("#[test]\nfn $1() {\n $0\n}".to_string()), | ||
339 | }); | ||
340 | acc.push(CompletionItem { | ||
341 | label: "pub(crate)".to_string(), | ||
342 | lookup: None, | ||
343 | snippet: Some("pub(crate) $0".to_string()), | ||
344 | }) | ||
345 | } | ||
346 | |||
347 | fn complete_fn(name_ref: ast::NameRef, scopes: &FnScopes, acc: &mut Vec<CompletionItem>) { | ||
348 | let mut shadowed = FxHashSet::default(); | ||
349 | acc.extend( | ||
350 | scopes | ||
351 | .scope_chain(name_ref.syntax()) | ||
352 | .flat_map(|scope| scopes.entries(scope).iter()) | ||
353 | .filter(|entry| shadowed.insert(entry.name())) | ||
354 | .map(|entry| CompletionItem { | ||
355 | label: entry.name().to_string(), | ||
356 | lookup: None, | ||
357 | snippet: None, | ||
358 | }), | ||
359 | ); | ||
360 | if scopes.self_param.is_some() { | ||
361 | acc.push(CompletionItem { | ||
362 | label: "self".to_string(), | ||
363 | lookup: None, | ||
364 | snippet: None, | ||
365 | }) | ||
366 | } | ||
367 | } | ||
368 | |||
369 | #[cfg(test)] | ||
370 | mod tests { | ||
371 | use test_utils::{assert_eq_dbg, extract_offset}; | ||
372 | |||
373 | use crate::FileId; | ||
374 | use crate::mock_analysis::MockAnalysis; | ||
375 | |||
376 | use super::*; | ||
377 | |||
378 | fn check_scope_completion(code: &str, expected_completions: &str) { | ||
379 | let (off, code) = extract_offset(&code); | ||
380 | let analysis = MockAnalysis::with_files(&[("/main.rs", &code)]).analysis(); | ||
381 | let file_id = FileId(1); | ||
382 | let completions = scope_completion(&analysis.imp.db, file_id, off) | ||
383 | .unwrap() | ||
384 | .into_iter() | ||
385 | .filter(|c| c.snippet.is_none()) | ||
386 | .collect::<Vec<_>>(); | ||
387 | assert_eq_dbg(expected_completions, &completions); | ||
388 | } | ||
389 | |||
390 | fn check_snippet_completion(code: &str, expected_completions: &str) { | ||
391 | let (off, code) = extract_offset(&code); | ||
392 | let analysis = MockAnalysis::with_files(&[("/main.rs", &code)]).analysis(); | ||
393 | let file_id = FileId(1); | ||
394 | let completions = scope_completion(&analysis.imp.db, file_id, off) | ||
395 | .unwrap() | ||
396 | .into_iter() | ||
397 | .filter(|c| c.snippet.is_some()) | ||
398 | .collect::<Vec<_>>(); | ||
399 | assert_eq_dbg(expected_completions, &completions); | ||
400 | } | ||
401 | |||
402 | #[test] | ||
403 | fn test_completion_let_scope() { | ||
404 | check_scope_completion( | ||
405 | r" | ||
406 | fn quux(x: i32) { | ||
407 | let y = 92; | ||
408 | 1 + <|>; | ||
409 | let z = (); | ||
410 | } | ||
411 | ", | ||
412 | r#"[CompletionItem { label: "y", lookup: None, snippet: None }, | ||
413 | CompletionItem { label: "x", lookup: None, snippet: None }, | ||
414 | CompletionItem { label: "quux", lookup: None, snippet: None }]"#, | ||
415 | ); | ||
416 | } | ||
417 | |||
418 | #[test] | ||
419 | fn test_completion_if_let_scope() { | ||
420 | check_scope_completion( | ||
421 | r" | ||
422 | fn quux() { | ||
423 | if let Some(x) = foo() { | ||
424 | let y = 92; | ||
425 | }; | ||
426 | if let Some(a) = bar() { | ||
427 | let b = 62; | ||
428 | 1 + <|> | ||
429 | } | ||
430 | } | ||
431 | ", | ||
432 | r#"[CompletionItem { label: "b", lookup: None, snippet: None }, | ||
433 | CompletionItem { label: "a", lookup: None, snippet: None }, | ||
434 | CompletionItem { label: "quux", lookup: None, snippet: None }]"#, | ||
435 | ); | ||
436 | } | ||
437 | |||
438 | #[test] | ||
439 | fn test_completion_for_scope() { | ||
440 | check_scope_completion( | ||
441 | r" | ||
442 | fn quux() { | ||
443 | for x in &[1, 2, 3] { | ||
444 | <|> | ||
445 | } | ||
446 | } | ||
447 | ", | ||
448 | r#"[CompletionItem { label: "x", lookup: None, snippet: None }, | ||
449 | CompletionItem { label: "quux", lookup: None, snippet: None }]"#, | ||
450 | ); | ||
451 | } | ||
452 | |||
453 | #[test] | ||
454 | fn test_completion_mod_scope() { | ||
455 | check_scope_completion( | ||
456 | r" | ||
457 | struct Foo; | ||
458 | enum Baz {} | ||
459 | fn quux() { | ||
460 | <|> | ||
461 | } | ||
462 | ", | ||
463 | r#"[CompletionItem { label: "Foo", lookup: None, snippet: None }, | ||
464 | CompletionItem { label: "Baz", lookup: None, snippet: None }, | ||
465 | CompletionItem { label: "quux", lookup: None, snippet: None }]"#, | ||
466 | ); | ||
467 | } | ||
468 | |||
469 | #[test] | ||
470 | fn test_completion_mod_scope_no_self_use() { | ||
471 | check_scope_completion( | ||
472 | r" | ||
473 | use foo<|>; | ||
474 | ", | ||
475 | r#"[]"#, | ||
476 | ); | ||
477 | } | ||
478 | |||
479 | #[test] | ||
480 | fn test_completion_mod_scope_nested() { | ||
481 | check_scope_completion( | ||
482 | r" | ||
483 | struct Foo; | ||
484 | mod m { | ||
485 | struct Bar; | ||
486 | fn quux() { <|> } | ||
487 | } | ||
488 | ", | ||
489 | r#"[CompletionItem { label: "Bar", lookup: None, snippet: None }, | ||
490 | CompletionItem { label: "quux", lookup: None, snippet: None }]"#, | ||
491 | ); | ||
492 | } | ||
493 | |||
494 | #[test] | ||
495 | fn test_complete_type() { | ||
496 | check_scope_completion( | ||
497 | r" | ||
498 | struct Foo; | ||
499 | fn x() -> <|> | ||
500 | ", | ||
501 | r#"[CompletionItem { label: "Foo", lookup: None, snippet: None }, | ||
502 | CompletionItem { label: "x", lookup: None, snippet: None }]"#, | ||
503 | ) | ||
504 | } | ||
505 | |||
506 | #[test] | ||
507 | fn test_complete_shadowing() { | ||
508 | check_scope_completion( | ||
509 | r" | ||
510 | fn foo() -> { | ||
511 | let bar = 92; | ||
512 | { | ||
513 | let bar = 62; | ||
514 | <|> | ||
515 | } | ||
516 | } | ||
517 | ", | ||
518 | r#"[CompletionItem { label: "bar", lookup: None, snippet: None }, | ||
519 | CompletionItem { label: "foo", lookup: None, snippet: None }]"#, | ||
520 | ) | ||
521 | } | ||
522 | |||
523 | #[test] | ||
524 | fn test_complete_self() { | ||
525 | check_scope_completion( | ||
526 | r" | ||
527 | impl S { fn foo(&self) { <|> } } | ||
528 | ", | ||
529 | r#"[CompletionItem { label: "self", lookup: None, snippet: None }]"#, | ||
530 | ) | ||
531 | } | ||
532 | |||
533 | #[test] | ||
534 | fn test_completion_kewords() { | ||
535 | check_snippet_completion(r" | ||
536 | fn quux() { | ||
537 | <|> | ||
538 | } | ||
539 | ", r#"[CompletionItem { label: "if", lookup: None, snippet: Some("if $0 {}") }, | ||
540 | CompletionItem { label: "match", lookup: None, snippet: Some("match $0 {}") }, | ||
541 | CompletionItem { label: "while", lookup: None, snippet: Some("while $0 {}") }, | ||
542 | CompletionItem { label: "loop", lookup: None, snippet: Some("loop {$0}") }, | ||
543 | CompletionItem { label: "return", lookup: None, snippet: Some("return") }, | ||
544 | CompletionItem { label: "pd", lookup: None, snippet: Some("eprintln!(\"$0 = {:?}\", $0);") }, | ||
545 | CompletionItem { label: "ppd", lookup: None, snippet: Some("eprintln!(\"$0 = {:#?}\", $0);") }]"#); | ||
546 | } | ||
547 | |||
548 | #[test] | ||
549 | fn test_completion_else() { | ||
550 | check_snippet_completion(r" | ||
551 | fn quux() { | ||
552 | if true { | ||
553 | () | ||
554 | } <|> | ||
555 | } | ||
556 | ", r#"[CompletionItem { label: "if", lookup: None, snippet: Some("if $0 {}") }, | ||
557 | CompletionItem { label: "match", lookup: None, snippet: Some("match $0 {}") }, | ||
558 | CompletionItem { label: "while", lookup: None, snippet: Some("while $0 {}") }, | ||
559 | CompletionItem { label: "loop", lookup: None, snippet: Some("loop {$0}") }, | ||
560 | CompletionItem { label: "else", lookup: None, snippet: Some("else {$0}") }, | ||
561 | CompletionItem { label: "else if", lookup: None, snippet: Some("else if $0 {}") }, | ||
562 | CompletionItem { label: "return", lookup: None, snippet: Some("return") }, | ||
563 | CompletionItem { label: "pd", lookup: None, snippet: Some("eprintln!(\"$0 = {:?}\", $0);") }, | ||
564 | CompletionItem { label: "ppd", lookup: None, snippet: Some("eprintln!(\"$0 = {:#?}\", $0);") }]"#); | ||
565 | } | ||
566 | |||
567 | #[test] | ||
568 | fn test_completion_return_value() { | ||
569 | check_snippet_completion(r" | ||
570 | fn quux() -> i32 { | ||
571 | <|> | ||
572 | 92 | ||
573 | } | ||
574 | ", r#"[CompletionItem { label: "if", lookup: None, snippet: Some("if $0 {}") }, | ||
575 | CompletionItem { label: "match", lookup: None, snippet: Some("match $0 {}") }, | ||
576 | CompletionItem { label: "while", lookup: None, snippet: Some("while $0 {}") }, | ||
577 | CompletionItem { label: "loop", lookup: None, snippet: Some("loop {$0}") }, | ||
578 | CompletionItem { label: "return", lookup: None, snippet: Some("return $0;") }, | ||
579 | CompletionItem { label: "pd", lookup: None, snippet: Some("eprintln!(\"$0 = {:?}\", $0);") }, | ||
580 | CompletionItem { label: "ppd", lookup: None, snippet: Some("eprintln!(\"$0 = {:#?}\", $0);") }]"#); | ||
581 | check_snippet_completion(r" | ||
582 | fn quux() { | ||
583 | <|> | ||
584 | 92 | ||
585 | } | ||
586 | ", r#"[CompletionItem { label: "if", lookup: None, snippet: Some("if $0 {}") }, | ||
587 | CompletionItem { label: "match", lookup: None, snippet: Some("match $0 {}") }, | ||
588 | CompletionItem { label: "while", lookup: None, snippet: Some("while $0 {}") }, | ||
589 | CompletionItem { label: "loop", lookup: None, snippet: Some("loop {$0}") }, | ||
590 | CompletionItem { label: "return", lookup: None, snippet: Some("return;") }, | ||
591 | CompletionItem { label: "pd", lookup: None, snippet: Some("eprintln!(\"$0 = {:?}\", $0);") }, | ||
592 | CompletionItem { label: "ppd", lookup: None, snippet: Some("eprintln!(\"$0 = {:#?}\", $0);") }]"#); | ||
593 | } | ||
594 | |||
595 | #[test] | ||
596 | fn test_completion_return_no_stmt() { | ||
597 | check_snippet_completion(r" | ||
598 | fn quux() -> i32 { | ||
599 | match () { | ||
600 | () => <|> | ||
601 | } | ||
602 | } | ||
603 | ", r#"[CompletionItem { label: "if", lookup: None, snippet: Some("if $0 {}") }, | ||
604 | CompletionItem { label: "match", lookup: None, snippet: Some("match $0 {}") }, | ||
605 | CompletionItem { label: "while", lookup: None, snippet: Some("while $0 {}") }, | ||
606 | CompletionItem { label: "loop", lookup: None, snippet: Some("loop {$0}") }, | ||
607 | CompletionItem { label: "return", lookup: None, snippet: Some("return $0") }, | ||
608 | CompletionItem { label: "pd", lookup: None, snippet: Some("eprintln!(\"$0 = {:?}\", $0);") }, | ||
609 | CompletionItem { label: "ppd", lookup: None, snippet: Some("eprintln!(\"$0 = {:#?}\", $0);") }]"#); | ||
610 | } | ||
611 | |||
612 | #[test] | ||
613 | fn test_continue_break_completion() { | ||
614 | check_snippet_completion(r" | ||
615 | fn quux() -> i32 { | ||
616 | loop { <|> } | ||
617 | } | ||
618 | ", r#"[CompletionItem { label: "if", lookup: None, snippet: Some("if $0 {}") }, | ||
619 | CompletionItem { label: "match", lookup: None, snippet: Some("match $0 {}") }, | ||
620 | CompletionItem { label: "while", lookup: None, snippet: Some("while $0 {}") }, | ||
621 | CompletionItem { label: "loop", lookup: None, snippet: Some("loop {$0}") }, | ||
622 | CompletionItem { label: "continue", lookup: None, snippet: Some("continue") }, | ||
623 | CompletionItem { label: "break", lookup: None, snippet: Some("break") }, | ||
624 | CompletionItem { label: "return", lookup: None, snippet: Some("return $0") }, | ||
625 | CompletionItem { label: "pd", lookup: None, snippet: Some("eprintln!(\"$0 = {:?}\", $0);") }, | ||
626 | CompletionItem { label: "ppd", lookup: None, snippet: Some("eprintln!(\"$0 = {:#?}\", $0);") }]"#); | ||
627 | check_snippet_completion(r" | ||
628 | fn quux() -> i32 { | ||
629 | loop { || { <|> } } | ||
630 | } | ||
631 | ", r#"[CompletionItem { label: "if", lookup: None, snippet: Some("if $0 {}") }, | ||
632 | CompletionItem { label: "match", lookup: None, snippet: Some("match $0 {}") }, | ||
633 | CompletionItem { label: "while", lookup: None, snippet: Some("while $0 {}") }, | ||
634 | CompletionItem { label: "loop", lookup: None, snippet: Some("loop {$0}") }, | ||
635 | CompletionItem { label: "return", lookup: None, snippet: Some("return $0") }, | ||
636 | CompletionItem { label: "pd", lookup: None, snippet: Some("eprintln!(\"$0 = {:?}\", $0);") }, | ||
637 | CompletionItem { label: "ppd", lookup: None, snippet: Some("eprintln!(\"$0 = {:#?}\", $0);") }]"#); | ||
638 | } | ||
639 | |||
640 | #[test] | ||
641 | fn test_param_completion_last_param() { | ||
642 | check_scope_completion(r" | ||
643 | fn foo(file_id: FileId) {} | ||
644 | fn bar(file_id: FileId) {} | ||
645 | fn baz(file<|>) {} | ||
646 | ", r#"[CompletionItem { label: "file_id: FileId", lookup: Some("file_id"), snippet: None }]"#); | ||
647 | } | ||
648 | |||
649 | #[test] | ||
650 | fn test_param_completion_nth_param() { | ||
651 | check_scope_completion(r" | ||
652 | fn foo(file_id: FileId) {} | ||
653 | fn bar(file_id: FileId) {} | ||
654 | fn baz(file<|>, x: i32) {} | ||
655 | ", r#"[CompletionItem { label: "file_id: FileId", lookup: Some("file_id"), snippet: None }]"#); | ||
656 | } | ||
657 | |||
658 | #[test] | ||
659 | fn test_param_completion_trait_param() { | ||
660 | check_scope_completion(r" | ||
661 | pub(crate) trait SourceRoot { | ||
662 | pub fn contains(&self, file_id: FileId) -> bool; | ||
663 | pub fn module_map(&self) -> &ModuleMap; | ||
664 | pub fn lines(&self, file_id: FileId) -> &LineIndex; | ||
665 | pub fn syntax(&self, file<|>) | ||
666 | } | ||
667 | ", r#"[CompletionItem { label: "self", lookup: None, snippet: None }, | ||
668 | CompletionItem { label: "SourceRoot", lookup: None, snippet: None }, | ||
669 | CompletionItem { label: "file_id: FileId", lookup: Some("file_id"), snippet: None }]"#); | ||
670 | } | ||
671 | |||
672 | #[test] | ||
673 | fn test_item_snippets() { | ||
674 | // check_snippet_completion(r" | ||
675 | // <|> | ||
676 | // ", | ||
677 | // r##"[CompletionItem { label: "tfn", lookup: None, snippet: Some("#[test]\nfn $1() {\n $0\n}") }]"##, | ||
678 | // ); | ||
679 | check_snippet_completion(r" | ||
680 | #[cfg(test)] | ||
681 | mod tests { | ||
682 | <|> | ||
683 | } | ||
684 | ", | ||
685 | r##"[CompletionItem { label: "tfn", lookup: None, snippet: Some("#[test]\nfn $1() {\n $0\n}") }, | ||
686 | CompletionItem { label: "pub(crate)", lookup: None, snippet: Some("pub(crate) $0") }]"##, | ||
687 | ); | ||
688 | } | ||
689 | } | ||
diff --git a/crates/ra_analysis/src/db.rs b/crates/ra_analysis/src/db.rs index e7a5d5e2f..fe6587f20 100644 --- a/crates/ra_analysis/src/db.rs +++ b/crates/ra_analysis/src/db.rs | |||
@@ -9,7 +9,10 @@ use salsa; | |||
9 | use crate::{ | 9 | use crate::{ |
10 | db, | 10 | db, |
11 | Cancelable, Canceled, | 11 | Cancelable, Canceled, |
12 | descriptors::module::{SubmodulesQuery, ModuleTreeQuery, ModulesDatabase, ModuleScopeQuery}, | 12 | descriptors::{ |
13 | DescriptorDatabase, SubmodulesQuery, ModuleTreeQuery, ModuleScopeQuery, | ||
14 | FnSyntaxQuery, FnScopesQuery | ||
15 | }, | ||
13 | symbol_index::SymbolIndex, | 16 | symbol_index::SymbolIndex, |
14 | syntax_ptr::{SyntaxPtrDatabase, ResolveSyntaxPtrQuery}, | 17 | syntax_ptr::{SyntaxPtrDatabase, ResolveSyntaxPtrQuery}, |
15 | FileId, | 18 | FileId, |
@@ -63,10 +66,12 @@ salsa::database_storage! { | |||
63 | fn file_lines() for FileLinesQuery; | 66 | fn file_lines() for FileLinesQuery; |
64 | fn file_symbols() for FileSymbolsQuery; | 67 | fn file_symbols() for FileSymbolsQuery; |
65 | } | 68 | } |
66 | impl ModulesDatabase { | 69 | impl DescriptorDatabase { |
67 | fn module_tree() for ModuleTreeQuery; | 70 | fn module_tree() for ModuleTreeQuery; |
68 | fn module_descriptor() for SubmodulesQuery; | 71 | fn module_descriptor() for SubmodulesQuery; |
69 | fn module_scope() for ModuleScopeQuery; | 72 | fn module_scope() for ModuleScopeQuery; |
73 | fn fn_syntax() for FnSyntaxQuery; | ||
74 | fn fn_scopes() for FnScopesQuery; | ||
70 | } | 75 | } |
71 | impl SyntaxPtrDatabase { | 76 | impl SyntaxPtrDatabase { |
72 | fn resolve_syntax_ptr() for ResolveSyntaxPtrQuery; | 77 | fn resolve_syntax_ptr() for ResolveSyntaxPtrQuery; |
diff --git a/crates/ra_analysis/src/descriptors/function/imp.rs b/crates/ra_analysis/src/descriptors/function/imp.rs new file mode 100644 index 000000000..0a006f733 --- /dev/null +++ b/crates/ra_analysis/src/descriptors/function/imp.rs | |||
@@ -0,0 +1,26 @@ | |||
1 | use std::sync::Arc; | ||
2 | |||
3 | use ra_syntax::{ | ||
4 | ast::{AstNode, FnDef, FnDefNode}, | ||
5 | }; | ||
6 | |||
7 | use crate::{ | ||
8 | descriptors::{ | ||
9 | DescriptorDatabase, | ||
10 | function::{FnId, FnScopes}, | ||
11 | }, | ||
12 | }; | ||
13 | |||
14 | /// Resolve `FnId` to the corresponding `SyntaxNode` | ||
15 | /// TODO: this should return something more type-safe then `SyntaxNode` | ||
16 | pub(crate) fn fn_syntax(db: &impl DescriptorDatabase, fn_id: FnId) -> FnDefNode { | ||
17 | let syntax = db.resolve_syntax_ptr(fn_id.0); | ||
18 | let fn_def = FnDef::cast(syntax.borrowed()).unwrap(); | ||
19 | FnDefNode::new(fn_def) | ||
20 | } | ||
21 | |||
22 | pub(crate) fn fn_scopes(db: &impl DescriptorDatabase, fn_id: FnId) -> Arc<FnScopes> { | ||
23 | let syntax = db.fn_syntax(fn_id); | ||
24 | let res = FnScopes::new(syntax.ast()); | ||
25 | Arc::new(res) | ||
26 | } | ||
diff --git a/crates/ra_analysis/src/descriptors/function/mod.rs b/crates/ra_analysis/src/descriptors/function/mod.rs new file mode 100644 index 000000000..bb68b0ce7 --- /dev/null +++ b/crates/ra_analysis/src/descriptors/function/mod.rs | |||
@@ -0,0 +1,83 @@ | |||
1 | pub(super) mod imp; | ||
2 | mod scope; | ||
3 | |||
4 | use ra_syntax::{ | ||
5 | ast::{self, AstNode, NameOwner} | ||
6 | }; | ||
7 | |||
8 | use crate::{ | ||
9 | FileId, | ||
10 | syntax_ptr::SyntaxPtr | ||
11 | }; | ||
12 | |||
13 | pub(crate) use self::scope::{FnScopes, resolve_local_name}; | ||
14 | |||
15 | |||
16 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
17 | pub(crate) struct FnId(SyntaxPtr); | ||
18 | |||
19 | impl FnId { | ||
20 | pub(crate) fn new(file_id: FileId, fn_def: ast::FnDef) -> FnId { | ||
21 | let ptr = SyntaxPtr::new(file_id, fn_def.syntax()); | ||
22 | FnId(ptr) | ||
23 | } | ||
24 | } | ||
25 | |||
26 | |||
27 | #[derive(Debug, Clone)] | ||
28 | pub struct FnDescriptor { | ||
29 | pub name: String, | ||
30 | pub label: String, | ||
31 | pub ret_type: Option<String>, | ||
32 | pub params: Vec<String>, | ||
33 | } | ||
34 | |||
35 | impl FnDescriptor { | ||
36 | pub fn new(node: ast::FnDef) -> Option<Self> { | ||
37 | let name = node.name()?.text().to_string(); | ||
38 | |||
39 | // Strip the body out for the label. | ||
40 | let label: String = if let Some(body) = node.body() { | ||
41 | let body_range = body.syntax().range(); | ||
42 | let label: String = node | ||
43 | .syntax() | ||
44 | .children() | ||
45 | .filter(|child| !child.range().is_subrange(&body_range)) | ||
46 | .map(|node| node.text().to_string()) | ||
47 | .collect(); | ||
48 | label | ||
49 | } else { | ||
50 | node.syntax().text().to_string() | ||
51 | }; | ||
52 | |||
53 | let params = FnDescriptor::param_list(node); | ||
54 | let ret_type = node.ret_type().map(|r| r.syntax().text().to_string()); | ||
55 | |||
56 | Some(FnDescriptor { | ||
57 | name, | ||
58 | ret_type, | ||
59 | params, | ||
60 | label, | ||
61 | }) | ||
62 | } | ||
63 | |||
64 | fn param_list(node: ast::FnDef) -> Vec<String> { | ||
65 | let mut res = vec![]; | ||
66 | if let Some(param_list) = node.param_list() { | ||
67 | if let Some(self_param) = param_list.self_param() { | ||
68 | res.push(self_param.syntax().text().to_string()) | ||
69 | } | ||
70 | |||
71 | // Maybe use param.pat here? See if we can just extract the name? | ||
72 | //res.extend(param_list.params().map(|p| p.syntax().text().to_string())); | ||
73 | res.extend( | ||
74 | param_list | ||
75 | .params() | ||
76 | .filter_map(|p| p.pat()) | ||
77 | .map(|pat| pat.syntax().text().to_string()), | ||
78 | ); | ||
79 | } | ||
80 | res | ||
81 | } | ||
82 | } | ||
83 | |||
diff --git a/crates/ra_analysis/src/descriptors/function/scope.rs b/crates/ra_analysis/src/descriptors/function/scope.rs new file mode 100644 index 000000000..d9929414c --- /dev/null +++ b/crates/ra_analysis/src/descriptors/function/scope.rs | |||
@@ -0,0 +1,433 @@ | |||
1 | use rustc_hash::{FxHashMap, FxHashSet}; | ||
2 | |||
3 | use ra_syntax::{ | ||
4 | algo::generate, | ||
5 | ast::{self, ArgListOwner, LoopBodyOwner, NameOwner}, | ||
6 | AstNode, SmolStr, SyntaxNodeRef, | ||
7 | }; | ||
8 | |||
9 | use crate::syntax_ptr::LocalSyntaxPtr; | ||
10 | |||
11 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] | ||
12 | pub(crate) struct ScopeId(u32); | ||
13 | |||
14 | #[derive(Debug, PartialEq, Eq)] | ||
15 | pub struct FnScopes { | ||
16 | pub(crate) self_param: Option<LocalSyntaxPtr>, | ||
17 | scopes: Vec<ScopeData>, | ||
18 | scope_for: FxHashMap<LocalSyntaxPtr, ScopeId>, | ||
19 | } | ||
20 | |||
21 | #[derive(Debug, PartialEq, Eq)] | ||
22 | pub struct ScopeEntry { | ||
23 | name: SmolStr, | ||
24 | ptr: LocalSyntaxPtr, | ||
25 | } | ||
26 | |||
27 | #[derive(Debug, PartialEq, Eq)] | ||
28 | struct ScopeData { | ||
29 | parent: Option<ScopeId>, | ||
30 | entries: Vec<ScopeEntry>, | ||
31 | } | ||
32 | |||
33 | impl FnScopes { | ||
34 | pub(crate) fn new(fn_def: ast::FnDef) -> FnScopes { | ||
35 | let mut scopes = FnScopes { | ||
36 | self_param: fn_def | ||
37 | .param_list() | ||
38 | .and_then(|it| it.self_param()) | ||
39 | .map(|it| LocalSyntaxPtr::new(it.syntax())), | ||
40 | scopes: Vec::new(), | ||
41 | scope_for: FxHashMap::default(), | ||
42 | }; | ||
43 | let root = scopes.root_scope(); | ||
44 | scopes.add_params_bindings(root, fn_def.param_list()); | ||
45 | if let Some(body) = fn_def.body() { | ||
46 | compute_block_scopes(body, &mut scopes, root) | ||
47 | } | ||
48 | scopes | ||
49 | } | ||
50 | pub(crate) fn entries(&self, scope: ScopeId) -> &[ScopeEntry] { | ||
51 | &self.get(scope).entries | ||
52 | } | ||
53 | pub fn scope_chain<'a>(&'a self, node: SyntaxNodeRef) -> impl Iterator<Item = ScopeId> + 'a { | ||
54 | generate(self.scope_for(node), move |&scope| { | ||
55 | self.get(scope).parent | ||
56 | }) | ||
57 | } | ||
58 | fn root_scope(&mut self) -> ScopeId { | ||
59 | let res = ScopeId(self.scopes.len() as u32); | ||
60 | self.scopes.push(ScopeData { | ||
61 | parent: None, | ||
62 | entries: vec![], | ||
63 | }); | ||
64 | res | ||
65 | } | ||
66 | fn new_scope(&mut self, parent: ScopeId) -> ScopeId { | ||
67 | let res = ScopeId(self.scopes.len() as u32); | ||
68 | self.scopes.push(ScopeData { | ||
69 | parent: Some(parent), | ||
70 | entries: vec![], | ||
71 | }); | ||
72 | res | ||
73 | } | ||
74 | fn add_bindings(&mut self, scope: ScopeId, pat: ast::Pat) { | ||
75 | let entries = pat | ||
76 | .syntax() | ||
77 | .descendants() | ||
78 | .filter_map(ast::BindPat::cast) | ||
79 | .filter_map(ScopeEntry::new); | ||
80 | self.get_mut(scope).entries.extend(entries); | ||
81 | } | ||
82 | fn add_params_bindings(&mut self, scope: ScopeId, params: Option<ast::ParamList>) { | ||
83 | params | ||
84 | .into_iter() | ||
85 | .flat_map(|it| it.params()) | ||
86 | .filter_map(|it| it.pat()) | ||
87 | .for_each(|it| self.add_bindings(scope, it)); | ||
88 | } | ||
89 | fn set_scope(&mut self, node: SyntaxNodeRef, scope: ScopeId) { | ||
90 | self.scope_for.insert(LocalSyntaxPtr::new(node), scope); | ||
91 | } | ||
92 | fn scope_for(&self, node: SyntaxNodeRef) -> Option<ScopeId> { | ||
93 | node.ancestors() | ||
94 | .map(LocalSyntaxPtr::new) | ||
95 | .filter_map(|it| self.scope_for.get(&it).map(|&scope| scope)) | ||
96 | .next() | ||
97 | } | ||
98 | fn get(&self, scope: ScopeId) -> &ScopeData { | ||
99 | &self.scopes[scope.0 as usize] | ||
100 | } | ||
101 | fn get_mut(&mut self, scope: ScopeId) -> &mut ScopeData { | ||
102 | &mut self.scopes[scope.0 as usize] | ||
103 | } | ||
104 | } | ||
105 | |||
106 | impl ScopeEntry { | ||
107 | fn new(pat: ast::BindPat) -> Option<ScopeEntry> { | ||
108 | let name = pat.name()?; | ||
109 | let res = ScopeEntry { | ||
110 | name: name.text(), | ||
111 | ptr: LocalSyntaxPtr::new(pat.syntax()), | ||
112 | }; | ||
113 | Some(res) | ||
114 | } | ||
115 | pub(crate) fn name(&self) -> &SmolStr { | ||
116 | &self.name | ||
117 | } | ||
118 | pub(crate) fn ptr(&self) -> LocalSyntaxPtr { | ||
119 | self.ptr | ||
120 | } | ||
121 | } | ||
122 | |||
123 | fn compute_block_scopes(block: ast::Block, scopes: &mut FnScopes, mut scope: ScopeId) { | ||
124 | for stmt in block.statements() { | ||
125 | match stmt { | ||
126 | ast::Stmt::LetStmt(stmt) => { | ||
127 | if let Some(expr) = stmt.initializer() { | ||
128 | scopes.set_scope(expr.syntax(), scope); | ||
129 | compute_expr_scopes(expr, scopes, scope); | ||
130 | } | ||
131 | scope = scopes.new_scope(scope); | ||
132 | if let Some(pat) = stmt.pat() { | ||
133 | scopes.add_bindings(scope, pat); | ||
134 | } | ||
135 | } | ||
136 | ast::Stmt::ExprStmt(expr_stmt) => { | ||
137 | if let Some(expr) = expr_stmt.expr() { | ||
138 | scopes.set_scope(expr.syntax(), scope); | ||
139 | compute_expr_scopes(expr, scopes, scope); | ||
140 | } | ||
141 | } | ||
142 | } | ||
143 | } | ||
144 | if let Some(expr) = block.expr() { | ||
145 | scopes.set_scope(expr.syntax(), scope); | ||
146 | compute_expr_scopes(expr, scopes, scope); | ||
147 | } | ||
148 | } | ||
149 | |||
150 | fn compute_expr_scopes(expr: ast::Expr, scopes: &mut FnScopes, scope: ScopeId) { | ||
151 | match expr { | ||
152 | ast::Expr::IfExpr(e) => { | ||
153 | let cond_scope = e | ||
154 | .condition() | ||
155 | .and_then(|cond| compute_cond_scopes(cond, scopes, scope)); | ||
156 | if let Some(block) = e.then_branch() { | ||
157 | compute_block_scopes(block, scopes, cond_scope.unwrap_or(scope)); | ||
158 | } | ||
159 | if let Some(block) = e.else_branch() { | ||
160 | compute_block_scopes(block, scopes, scope); | ||
161 | } | ||
162 | } | ||
163 | ast::Expr::BlockExpr(e) => { | ||
164 | if let Some(block) = e.block() { | ||
165 | compute_block_scopes(block, scopes, scope); | ||
166 | } | ||
167 | } | ||
168 | ast::Expr::LoopExpr(e) => { | ||
169 | if let Some(block) = e.loop_body() { | ||
170 | compute_block_scopes(block, scopes, scope); | ||
171 | } | ||
172 | } | ||
173 | ast::Expr::WhileExpr(e) => { | ||
174 | let cond_scope = e | ||
175 | .condition() | ||
176 | .and_then(|cond| compute_cond_scopes(cond, scopes, scope)); | ||
177 | if let Some(block) = e.loop_body() { | ||
178 | compute_block_scopes(block, scopes, cond_scope.unwrap_or(scope)); | ||
179 | } | ||
180 | } | ||
181 | ast::Expr::ForExpr(e) => { | ||
182 | if let Some(expr) = e.iterable() { | ||
183 | compute_expr_scopes(expr, scopes, scope); | ||
184 | } | ||
185 | let mut scope = scope; | ||
186 | if let Some(pat) = e.pat() { | ||
187 | scope = scopes.new_scope(scope); | ||
188 | scopes.add_bindings(scope, pat); | ||
189 | } | ||
190 | if let Some(block) = e.loop_body() { | ||
191 | compute_block_scopes(block, scopes, scope); | ||
192 | } | ||
193 | } | ||
194 | ast::Expr::LambdaExpr(e) => { | ||
195 | let scope = scopes.new_scope(scope); | ||
196 | scopes.add_params_bindings(scope, e.param_list()); | ||
197 | if let Some(body) = e.body() { | ||
198 | scopes.set_scope(body.syntax(), scope); | ||
199 | compute_expr_scopes(body, scopes, scope); | ||
200 | } | ||
201 | } | ||
202 | ast::Expr::CallExpr(e) => { | ||
203 | compute_call_scopes(e.expr(), e.arg_list(), scopes, scope); | ||
204 | } | ||
205 | ast::Expr::MethodCallExpr(e) => { | ||
206 | compute_call_scopes(e.expr(), e.arg_list(), scopes, scope); | ||
207 | } | ||
208 | ast::Expr::MatchExpr(e) => { | ||
209 | if let Some(expr) = e.expr() { | ||
210 | compute_expr_scopes(expr, scopes, scope); | ||
211 | } | ||
212 | for arm in e.match_arm_list().into_iter().flat_map(|it| it.arms()) { | ||
213 | let scope = scopes.new_scope(scope); | ||
214 | for pat in arm.pats() { | ||
215 | scopes.add_bindings(scope, pat); | ||
216 | } | ||
217 | if let Some(expr) = arm.expr() { | ||
218 | compute_expr_scopes(expr, scopes, scope); | ||
219 | } | ||
220 | } | ||
221 | } | ||
222 | _ => expr | ||
223 | .syntax() | ||
224 | .children() | ||
225 | .filter_map(ast::Expr::cast) | ||
226 | .for_each(|expr| compute_expr_scopes(expr, scopes, scope)), | ||
227 | }; | ||
228 | |||
229 | fn compute_call_scopes( | ||
230 | receiver: Option<ast::Expr>, | ||
231 | arg_list: Option<ast::ArgList>, | ||
232 | scopes: &mut FnScopes, | ||
233 | scope: ScopeId, | ||
234 | ) { | ||
235 | arg_list | ||
236 | .into_iter() | ||
237 | .flat_map(|it| it.args()) | ||
238 | .chain(receiver) | ||
239 | .for_each(|expr| compute_expr_scopes(expr, scopes, scope)); | ||
240 | } | ||
241 | |||
242 | fn compute_cond_scopes( | ||
243 | cond: ast::Condition, | ||
244 | scopes: &mut FnScopes, | ||
245 | scope: ScopeId, | ||
246 | ) -> Option<ScopeId> { | ||
247 | if let Some(expr) = cond.expr() { | ||
248 | compute_expr_scopes(expr, scopes, scope); | ||
249 | } | ||
250 | if let Some(pat) = cond.pat() { | ||
251 | let s = scopes.new_scope(scope); | ||
252 | scopes.add_bindings(s, pat); | ||
253 | Some(s) | ||
254 | } else { | ||
255 | None | ||
256 | } | ||
257 | } | ||
258 | } | ||
259 | |||
260 | pub fn resolve_local_name<'a>( | ||
261 | name_ref: ast::NameRef, | ||
262 | scopes: &'a FnScopes, | ||
263 | ) -> Option<&'a ScopeEntry> { | ||
264 | let mut shadowed = FxHashSet::default(); | ||
265 | let ret = scopes | ||
266 | .scope_chain(name_ref.syntax()) | ||
267 | .flat_map(|scope| scopes.entries(scope).iter()) | ||
268 | .filter(|entry| shadowed.insert(entry.name())) | ||
269 | .filter(|entry| entry.name() == &name_ref.text()) | ||
270 | .nth(0); | ||
271 | ret | ||
272 | } | ||
273 | |||
274 | #[cfg(test)] | ||
275 | mod tests { | ||
276 | use ra_syntax::File; | ||
277 | use test_utils::extract_offset; | ||
278 | use ra_editor::{find_node_at_offset}; | ||
279 | |||
280 | use super::*; | ||
281 | |||
282 | |||
283 | fn do_check(code: &str, expected: &[&str]) { | ||
284 | let (off, code) = extract_offset(code); | ||
285 | let code = { | ||
286 | let mut buf = String::new(); | ||
287 | let off = u32::from(off) as usize; | ||
288 | buf.push_str(&code[..off]); | ||
289 | buf.push_str("marker"); | ||
290 | buf.push_str(&code[off..]); | ||
291 | buf | ||
292 | }; | ||
293 | let file = File::parse(&code); | ||
294 | let marker: ast::PathExpr = find_node_at_offset(file.syntax(), off).unwrap(); | ||
295 | let fn_def: ast::FnDef = find_node_at_offset(file.syntax(), off).unwrap(); | ||
296 | let scopes = FnScopes::new(fn_def); | ||
297 | let actual = scopes | ||
298 | .scope_chain(marker.syntax()) | ||
299 | .flat_map(|scope| scopes.entries(scope)) | ||
300 | .map(|it| it.name()) | ||
301 | .collect::<Vec<_>>(); | ||
302 | assert_eq!(actual.as_slice(), expected); | ||
303 | } | ||
304 | |||
305 | #[test] | ||
306 | fn test_lambda_scope() { | ||
307 | do_check( | ||
308 | r" | ||
309 | fn quux(foo: i32) { | ||
310 | let f = |bar, baz: i32| { | ||
311 | <|> | ||
312 | }; | ||
313 | }", | ||
314 | &["bar", "baz", "foo"], | ||
315 | ); | ||
316 | } | ||
317 | |||
318 | #[test] | ||
319 | fn test_call_scope() { | ||
320 | do_check( | ||
321 | r" | ||
322 | fn quux() { | ||
323 | f(|x| <|> ); | ||
324 | }", | ||
325 | &["x"], | ||
326 | ); | ||
327 | } | ||
328 | |||
329 | #[test] | ||
330 | fn test_metod_call_scope() { | ||
331 | do_check( | ||
332 | r" | ||
333 | fn quux() { | ||
334 | z.f(|x| <|> ); | ||
335 | }", | ||
336 | &["x"], | ||
337 | ); | ||
338 | } | ||
339 | |||
340 | #[test] | ||
341 | fn test_loop_scope() { | ||
342 | do_check( | ||
343 | r" | ||
344 | fn quux() { | ||
345 | loop { | ||
346 | let x = (); | ||
347 | <|> | ||
348 | }; | ||
349 | }", | ||
350 | &["x"], | ||
351 | ); | ||
352 | } | ||
353 | |||
354 | #[test] | ||
355 | fn test_match() { | ||
356 | do_check( | ||
357 | r" | ||
358 | fn quux() { | ||
359 | match () { | ||
360 | Some(x) => { | ||
361 | <|> | ||
362 | } | ||
363 | }; | ||
364 | }", | ||
365 | &["x"], | ||
366 | ); | ||
367 | } | ||
368 | |||
369 | #[test] | ||
370 | fn test_shadow_variable() { | ||
371 | do_check( | ||
372 | r" | ||
373 | fn foo(x: String) { | ||
374 | let x : &str = &x<|>; | ||
375 | }", | ||
376 | &["x"], | ||
377 | ); | ||
378 | } | ||
379 | |||
380 | fn do_check_local_name(code: &str, expected_offset: u32) { | ||
381 | let (off, code) = extract_offset(code); | ||
382 | let file = File::parse(&code); | ||
383 | let fn_def: ast::FnDef = find_node_at_offset(file.syntax(), off).unwrap(); | ||
384 | let name_ref: ast::NameRef = find_node_at_offset(file.syntax(), off).unwrap(); | ||
385 | |||
386 | let scopes = FnScopes::new(fn_def); | ||
387 | |||
388 | let local_name_entry = resolve_local_name(name_ref, &scopes).unwrap(); | ||
389 | let local_name = local_name_entry.ptr().resolve(&file); | ||
390 | let expected_name = | ||
391 | find_node_at_offset::<ast::Name>(file.syntax(), expected_offset.into()).unwrap(); | ||
392 | assert_eq!(local_name.range(), expected_name.syntax().range()); | ||
393 | } | ||
394 | |||
395 | #[test] | ||
396 | fn test_resolve_local_name() { | ||
397 | do_check_local_name( | ||
398 | r#" | ||
399 | fn foo(x: i32, y: u32) { | ||
400 | { | ||
401 | let z = x * 2; | ||
402 | } | ||
403 | { | ||
404 | let t = x<|> * 3; | ||
405 | } | ||
406 | }"#, | ||
407 | 21, | ||
408 | ); | ||
409 | } | ||
410 | |||
411 | #[test] | ||
412 | fn test_resolve_local_name_declaration() { | ||
413 | do_check_local_name( | ||
414 | r#" | ||
415 | fn foo(x: String) { | ||
416 | let x : &str = &x<|>; | ||
417 | }"#, | ||
418 | 21, | ||
419 | ); | ||
420 | } | ||
421 | |||
422 | #[test] | ||
423 | fn test_resolve_local_name_shadow() { | ||
424 | do_check_local_name( | ||
425 | r" | ||
426 | fn foo(x: String) { | ||
427 | let x : &str = &x; | ||
428 | x<|> | ||
429 | }", | ||
430 | 46, | ||
431 | ); | ||
432 | } | ||
433 | } | ||
diff --git a/crates/ra_analysis/src/descriptors/mod.rs b/crates/ra_analysis/src/descriptors/mod.rs index 0220f7d5d..0c4991757 100644 --- a/crates/ra_analysis/src/descriptors/mod.rs +++ b/crates/ra_analysis/src/descriptors/mod.rs | |||
@@ -1,62 +1,46 @@ | |||
1 | pub(crate) mod module; | 1 | pub(crate) mod module; |
2 | pub(crate) mod function; | ||
3 | |||
4 | use std::sync::Arc; | ||
2 | 5 | ||
3 | use ra_syntax::{ | 6 | use ra_syntax::{ |
4 | ast::{self, AstNode, NameOwner}, | 7 | SmolStr, |
8 | ast::{FnDefNode}, | ||
5 | }; | 9 | }; |
6 | 10 | ||
7 | #[derive(Debug, Clone)] | 11 | use crate::{ |
8 | pub struct FnDescriptor { | 12 | FileId, Cancelable, |
9 | pub name: String, | 13 | db::SyntaxDatabase, |
10 | pub label: String, | 14 | descriptors::module::{ModuleTree, ModuleId, ModuleScope}, |
11 | pub ret_type: Option<String>, | 15 | descriptors::function::{FnId, FnScopes}, |
12 | pub params: Vec<String>, | 16 | input::SourceRootId, |
13 | } | 17 | syntax_ptr::SyntaxPtrDatabase, |
14 | 18 | }; | |
15 | impl FnDescriptor { | ||
16 | pub fn new(node: ast::FnDef) -> Option<Self> { | ||
17 | let name = node.name()?.text().to_string(); | ||
18 | |||
19 | // Strip the body out for the label. | ||
20 | let label: String = if let Some(body) = node.body() { | ||
21 | let body_range = body.syntax().range(); | ||
22 | let label: String = node | ||
23 | .syntax() | ||
24 | .children() | ||
25 | .filter(|child| !child.range().is_subrange(&body_range)) | ||
26 | .map(|node| node.text().to_string()) | ||
27 | .collect(); | ||
28 | label | ||
29 | } else { | ||
30 | node.syntax().text().to_string() | ||
31 | }; | ||
32 | |||
33 | let params = FnDescriptor::param_list(node); | ||
34 | let ret_type = node.ret_type().map(|r| r.syntax().text().to_string()); | ||
35 | |||
36 | Some(FnDescriptor { | ||
37 | name, | ||
38 | ret_type, | ||
39 | params, | ||
40 | label, | ||
41 | }) | ||
42 | } | ||
43 | 19 | ||
44 | fn param_list(node: ast::FnDef) -> Vec<String> { | ||
45 | let mut res = vec![]; | ||
46 | if let Some(param_list) = node.param_list() { | ||
47 | if let Some(self_param) = param_list.self_param() { | ||
48 | res.push(self_param.syntax().text().to_string()) | ||
49 | } | ||
50 | 20 | ||
51 | // Maybe use param.pat here? See if we can just extract the name? | 21 | salsa::query_group! { |
52 | //res.extend(param_list.params().map(|p| p.syntax().text().to_string())); | 22 | pub(crate) trait DescriptorDatabase: SyntaxDatabase + SyntaxPtrDatabase { |
53 | res.extend( | 23 | fn module_tree(source_root_id: SourceRootId) -> Cancelable<Arc<ModuleTree>> { |
54 | param_list | 24 | type ModuleTreeQuery; |
55 | .params() | 25 | use fn module::imp::module_tree; |
56 | .filter_map(|p| p.pat()) | 26 | } |
57 | .map(|pat| pat.syntax().text().to_string()), | 27 | fn submodules(file_id: FileId) -> Cancelable<Arc<Vec<SmolStr>>> { |
58 | ); | 28 | type SubmodulesQuery; |
29 | use fn module::imp::submodules; | ||
30 | } | ||
31 | fn module_scope(source_root_id: SourceRootId, module_id: ModuleId) -> Cancelable<Arc<ModuleScope>> { | ||
32 | type ModuleScopeQuery; | ||
33 | use fn module::imp::module_scope; | ||
34 | } | ||
35 | fn fn_syntax(fn_id: FnId) -> FnDefNode { | ||
36 | type FnSyntaxQuery; | ||
37 | // Don't retain syntax trees in memory | ||
38 | storage volatile; | ||
39 | use fn function::imp::fn_syntax; | ||
40 | } | ||
41 | fn fn_scopes(fn_id: FnId) -> Arc<FnScopes> { | ||
42 | type FnScopesQuery; | ||
43 | use fn function::imp::fn_scopes; | ||
59 | } | 44 | } |
60 | res | ||
61 | } | 45 | } |
62 | } | 46 | } |
diff --git a/crates/ra_analysis/src/descriptors/module/imp.rs b/crates/ra_analysis/src/descriptors/module/imp.rs index 5fdaad137..dae3a356d 100644 --- a/crates/ra_analysis/src/descriptors/module/imp.rs +++ b/crates/ra_analysis/src/descriptors/module/imp.rs | |||
@@ -10,14 +10,15 @@ use ra_syntax::{ | |||
10 | use crate::{ | 10 | use crate::{ |
11 | FileId, Cancelable, FileResolverImp, db, | 11 | FileId, Cancelable, FileResolverImp, db, |
12 | input::{SourceRoot, SourceRootId}, | 12 | input::{SourceRoot, SourceRootId}, |
13 | descriptors::DescriptorDatabase, | ||
13 | }; | 14 | }; |
14 | 15 | ||
15 | use super::{ | 16 | use super::{ |
16 | ModuleData, ModuleTree, ModuleId, LinkId, LinkData, Problem, ModulesDatabase, ModuleScope | 17 | ModuleData, ModuleTree, ModuleId, LinkId, LinkData, Problem, ModuleScope |
17 | }; | 18 | }; |
18 | 19 | ||
19 | 20 | ||
20 | pub(super) fn submodules(db: &impl ModulesDatabase, file_id: FileId) -> Cancelable<Arc<Vec<SmolStr>>> { | 21 | pub(crate) fn submodules(db: &impl DescriptorDatabase, file_id: FileId) -> Cancelable<Arc<Vec<SmolStr>>> { |
21 | db::check_canceled(db)?; | 22 | db::check_canceled(db)?; |
22 | let file = db.file_syntax(file_id); | 23 | let file = db.file_syntax(file_id); |
23 | let root = file.ast(); | 24 | let root = file.ast(); |
@@ -25,7 +26,7 @@ pub(super) fn submodules(db: &impl ModulesDatabase, file_id: FileId) -> Cancelab | |||
25 | Ok(Arc::new(submodules)) | 26 | Ok(Arc::new(submodules)) |
26 | } | 27 | } |
27 | 28 | ||
28 | pub(super) fn modules(root: ast::Root<'_>) -> impl Iterator<Item = (SmolStr, ast::Module<'_>)> { | 29 | pub(crate) fn modules(root: ast::Root<'_>) -> impl Iterator<Item = (SmolStr, ast::Module<'_>)> { |
29 | root.modules().filter_map(|module| { | 30 | root.modules().filter_map(|module| { |
30 | let name = module.name()?.text(); | 31 | let name = module.name()?.text(); |
31 | if !module.has_semi() { | 32 | if !module.has_semi() { |
@@ -35,8 +36,8 @@ pub(super) fn modules(root: ast::Root<'_>) -> impl Iterator<Item = (SmolStr, ast | |||
35 | }) | 36 | }) |
36 | } | 37 | } |
37 | 38 | ||
38 | pub(super) fn module_scope( | 39 | pub(crate) fn module_scope( |
39 | db: &impl ModulesDatabase, | 40 | db: &impl DescriptorDatabase, |
40 | source_root_id: SourceRootId, | 41 | source_root_id: SourceRootId, |
41 | module_id: ModuleId, | 42 | module_id: ModuleId, |
42 | ) -> Cancelable<Arc<ModuleScope>> { | 43 | ) -> Cancelable<Arc<ModuleScope>> { |
@@ -47,8 +48,8 @@ pub(super) fn module_scope( | |||
47 | Ok(Arc::new(res)) | 48 | Ok(Arc::new(res)) |
48 | } | 49 | } |
49 | 50 | ||
50 | pub(super) fn module_tree( | 51 | pub(crate) fn module_tree( |
51 | db: &impl ModulesDatabase, | 52 | db: &impl DescriptorDatabase, |
52 | source_root: SourceRootId, | 53 | source_root: SourceRootId, |
53 | ) -> Cancelable<Arc<ModuleTree>> { | 54 | ) -> Cancelable<Arc<ModuleTree>> { |
54 | db::check_canceled(db)?; | 55 | db::check_canceled(db)?; |
@@ -64,7 +65,7 @@ pub struct Submodule { | |||
64 | 65 | ||
65 | 66 | ||
66 | fn create_module_tree<'a>( | 67 | fn create_module_tree<'a>( |
67 | db: &impl ModulesDatabase, | 68 | db: &impl DescriptorDatabase, |
68 | source_root: SourceRootId, | 69 | source_root: SourceRootId, |
69 | ) -> Cancelable<ModuleTree> { | 70 | ) -> Cancelable<ModuleTree> { |
70 | let mut tree = ModuleTree { | 71 | let mut tree = ModuleTree { |
@@ -88,7 +89,7 @@ fn create_module_tree<'a>( | |||
88 | } | 89 | } |
89 | 90 | ||
90 | fn build_subtree( | 91 | fn build_subtree( |
91 | db: &impl ModulesDatabase, | 92 | db: &impl DescriptorDatabase, |
92 | source_root: &SourceRoot, | 93 | source_root: &SourceRoot, |
93 | tree: &mut ModuleTree, | 94 | tree: &mut ModuleTree, |
94 | visited: &mut FxHashSet<FileId>, | 95 | visited: &mut FxHashSet<FileId>, |
diff --git a/crates/ra_analysis/src/descriptors/module/mod.rs b/crates/ra_analysis/src/descriptors/module/mod.rs index 9e5d73f94..667553f74 100644 --- a/crates/ra_analysis/src/descriptors/module/mod.rs +++ b/crates/ra_analysis/src/descriptors/module/mod.rs | |||
@@ -1,37 +1,13 @@ | |||
1 | mod imp; | 1 | pub(super) mod imp; |
2 | pub(crate) mod scope; | 2 | pub(crate) mod scope; |
3 | 3 | ||
4 | use std::sync::Arc; | ||
5 | |||
6 | use relative_path::RelativePathBuf; | 4 | use relative_path::RelativePathBuf; |
7 | use ra_syntax::{ast::{self, NameOwner, AstNode}, SmolStr, SyntaxNode}; | 5 | use ra_syntax::{ast::{self, NameOwner, AstNode}, SmolStr, SyntaxNode}; |
8 | 6 | ||
9 | use crate::{ | 7 | use crate::FileId; |
10 | FileId, Cancelable, | ||
11 | db::SyntaxDatabase, | ||
12 | input::SourceRootId, | ||
13 | }; | ||
14 | 8 | ||
15 | pub(crate) use self::scope::ModuleScope; | 9 | pub(crate) use self::scope::ModuleScope; |
16 | 10 | ||
17 | salsa::query_group! { | ||
18 | pub(crate) trait ModulesDatabase: SyntaxDatabase { | ||
19 | fn module_tree(source_root_id: SourceRootId) -> Cancelable<Arc<ModuleTree>> { | ||
20 | type ModuleTreeQuery; | ||
21 | use fn imp::module_tree; | ||
22 | } | ||
23 | fn submodules(file_id: FileId) -> Cancelable<Arc<Vec<SmolStr>>> { | ||
24 | type SubmodulesQuery; | ||
25 | use fn imp::submodules; | ||
26 | } | ||
27 | fn module_scope(source_root_id: SourceRootId, module_id: ModuleId) -> Cancelable<Arc<ModuleScope>> { | ||
28 | type ModuleScopeQuery; | ||
29 | use fn imp::module_scope; | ||
30 | } | ||
31 | } | ||
32 | } | ||
33 | |||
34 | |||
35 | #[derive(Debug, PartialEq, Eq, Hash)] | 11 | #[derive(Debug, PartialEq, Eq, Hash)] |
36 | pub(crate) struct ModuleTree { | 12 | pub(crate) struct ModuleTree { |
37 | mods: Vec<ModuleData>, | 13 | mods: Vec<ModuleData>, |
diff --git a/crates/ra_analysis/src/descriptors/module/scope.rs b/crates/ra_analysis/src/descriptors/module/scope.rs index da58ddce0..846b8b44f 100644 --- a/crates/ra_analysis/src/descriptors/module/scope.rs +++ b/crates/ra_analysis/src/descriptors/module/scope.rs | |||
@@ -2,8 +2,8 @@ | |||
2 | 2 | ||
3 | 3 | ||
4 | use ra_syntax::{ | 4 | use ra_syntax::{ |
5 | ast::{self, AstChildren, ModuleItemOwner}, | 5 | ast::{self, ModuleItemOwner}, |
6 | File, AstNode, SmolStr, SyntaxNode, SyntaxNodeRef, | 6 | File, AstNode, SmolStr, |
7 | }; | 7 | }; |
8 | 8 | ||
9 | use crate::syntax_ptr::LocalSyntaxPtr; | 9 | use crate::syntax_ptr::LocalSyntaxPtr; |
@@ -30,8 +30,12 @@ enum EntryKind { | |||
30 | 30 | ||
31 | impl ModuleScope { | 31 | impl ModuleScope { |
32 | pub fn new(file: &File) -> ModuleScope { | 32 | pub fn new(file: &File) -> ModuleScope { |
33 | ModuleScope::from_items(file.ast().items()) | ||
34 | } | ||
35 | |||
36 | pub fn from_items<'a>(items: impl Iterator<Item = ast::ModuleItem<'a>>) -> ModuleScope { | ||
33 | let mut entries = Vec::new(); | 37 | let mut entries = Vec::new(); |
34 | for item in file.ast().items() { | 38 | for item in items { |
35 | let entry = match item { | 39 | let entry = match item { |
36 | ast::ModuleItem::StructDef(item) => Entry::new(item), | 40 | ast::ModuleItem::StructDef(item) => Entry::new(item), |
37 | ast::ModuleItem::EnumDef(item) => Entry::new(item), | 41 | ast::ModuleItem::EnumDef(item) => Entry::new(item), |
@@ -99,7 +103,7 @@ fn collect_imports(tree: ast::UseTree, acc: &mut Vec<Entry>) { | |||
99 | #[cfg(test)] | 103 | #[cfg(test)] |
100 | mod tests { | 104 | mod tests { |
101 | use super::*; | 105 | use super::*; |
102 | use ra_syntax::{ast::ModuleItemOwner, File}; | 106 | use ra_syntax::{File}; |
103 | 107 | ||
104 | fn do_check(code: &str, expected: &[&str]) { | 108 | fn do_check(code: &str, expected: &[&str]) { |
105 | let file = File::parse(&code); | 109 | let file = File::parse(&code); |
diff --git a/crates/ra_analysis/src/imp.rs b/crates/ra_analysis/src/imp.rs index efb3182a6..38d4b6a23 100644 --- a/crates/ra_analysis/src/imp.rs +++ b/crates/ra_analysis/src/imp.rs | |||
@@ -3,7 +3,7 @@ use std::{ | |||
3 | sync::Arc, | 3 | sync::Arc, |
4 | }; | 4 | }; |
5 | 5 | ||
6 | use ra_editor::{self, find_node_at_offset, resolve_local_name, FileSymbol, LineIndex, LocalEdit, CompletionItem}; | 6 | use ra_editor::{self, find_node_at_offset, FileSymbol, LineIndex, LocalEdit}; |
7 | use ra_syntax::{ | 7 | use ra_syntax::{ |
8 | ast::{self, ArgListOwner, Expr, NameOwner}, | 8 | ast::{self, ArgListOwner, Expr, NameOwner}, |
9 | AstNode, File, SmolStr, | 9 | AstNode, File, SmolStr, |
@@ -21,9 +21,14 @@ use crate::{ | |||
21 | self, SyntaxDatabase, FileSyntaxQuery, | 21 | self, SyntaxDatabase, FileSyntaxQuery, |
22 | }, | 22 | }, |
23 | input::{SourceRootId, FilesDatabase, SourceRoot, WORKSPACE}, | 23 | input::{SourceRootId, FilesDatabase, SourceRoot, WORKSPACE}, |
24 | descriptors::module::{ModulesDatabase, ModuleTree, Problem}, | 24 | descriptors::{ |
25 | descriptors::{FnDescriptor}, | 25 | DescriptorDatabase, |
26 | module::{ModuleTree, Problem}, | ||
27 | function::{FnDescriptor, FnId}, | ||
28 | }, | ||
29 | completion::{scope_completion, resolve_based_completion, CompletionItem}, | ||
26 | symbol_index::SymbolIndex, | 30 | symbol_index::SymbolIndex, |
31 | syntax_ptr::SyntaxPtrDatabase, | ||
27 | CrateGraph, CrateId, Diagnostic, FileId, FileResolver, FileSystemEdit, Position, | 32 | CrateGraph, CrateId, Diagnostic, FileId, FileResolver, FileSystemEdit, Position, |
28 | Query, SourceChange, SourceFileEdit, Cancelable, | 33 | Query, SourceChange, SourceFileEdit, Cancelable, |
29 | }; | 34 | }; |
@@ -175,7 +180,7 @@ impl AnalysisHostImpl { | |||
175 | 180 | ||
176 | #[derive(Debug)] | 181 | #[derive(Debug)] |
177 | pub(crate) struct AnalysisImpl { | 182 | pub(crate) struct AnalysisImpl { |
178 | db: db::RootDatabase, | 183 | pub(crate) db: db::RootDatabase, |
179 | } | 184 | } |
180 | 185 | ||
181 | impl AnalysisImpl { | 186 | impl AnalysisImpl { |
@@ -245,12 +250,11 @@ impl AnalysisImpl { | |||
245 | pub fn completions(&self, file_id: FileId, offset: TextUnit) -> Cancelable<Option<Vec<CompletionItem>>> { | 250 | pub fn completions(&self, file_id: FileId, offset: TextUnit) -> Cancelable<Option<Vec<CompletionItem>>> { |
246 | let mut res = Vec::new(); | 251 | let mut res = Vec::new(); |
247 | let mut has_completions = false; | 252 | let mut has_completions = false; |
248 | let file = self.file_syntax(file_id); | 253 | if let Some(scope_based) = scope_completion(&self.db, file_id, offset) { |
249 | if let Some(scope_based) = ra_editor::scope_completion(&file, offset) { | ||
250 | res.extend(scope_based); | 254 | res.extend(scope_based); |
251 | has_completions = true; | 255 | has_completions = true; |
252 | } | 256 | } |
253 | if let Some(scope_based) = crate::completion::resolve_based_completion(&self.db, file_id, offset)? { | 257 | if let Some(scope_based) = resolve_based_completion(&self.db, file_id, offset)? { |
254 | res.extend(scope_based); | 258 | res.extend(scope_based); |
255 | has_completions = true; | 259 | has_completions = true; |
256 | } | 260 | } |
@@ -271,7 +275,7 @@ impl AnalysisImpl { | |||
271 | let syntax = file.syntax(); | 275 | let syntax = file.syntax(); |
272 | if let Some(name_ref) = find_node_at_offset::<ast::NameRef>(syntax, offset) { | 276 | if let Some(name_ref) = find_node_at_offset::<ast::NameRef>(syntax, offset) { |
273 | // First try to resolve the symbol locally | 277 | // First try to resolve the symbol locally |
274 | return if let Some((name, range)) = resolve_local_name(name_ref) { | 278 | return if let Some((name, range)) = resolve_local_name(&self.db, file_id, name_ref) { |
275 | let mut vec = vec![]; | 279 | let mut vec = vec![]; |
276 | vec.push(( | 280 | vec.push(( |
277 | file_id, | 281 | file_id, |
@@ -325,7 +329,7 @@ impl AnalysisImpl { | |||
325 | if let Some(name_ref) = find_node_at_offset::<ast::NameRef>(syntax, offset) { | 329 | if let Some(name_ref) = find_node_at_offset::<ast::NameRef>(syntax, offset) { |
326 | 330 | ||
327 | // We are only handing local references for now | 331 | // We are only handing local references for now |
328 | if let Some(resolved) = resolve_local_name(name_ref) { | 332 | if let Some(resolved) = resolve_local_name(&self.db, file_id, name_ref) { |
329 | 333 | ||
330 | ret.push((file_id, resolved.1)); | 334 | ret.push((file_id, resolved.1)); |
331 | 335 | ||
@@ -333,7 +337,7 @@ impl AnalysisImpl { | |||
333 | 337 | ||
334 | let refs : Vec<_> = fn_def.syntax().descendants() | 338 | let refs : Vec<_> = fn_def.syntax().descendants() |
335 | .filter_map(ast::NameRef::cast) | 339 | .filter_map(ast::NameRef::cast) |
336 | .filter(|&n: &ast::NameRef| resolve_local_name(n) == Some(resolved.clone())) | 340 | .filter(|&n: &ast::NameRef| resolve_local_name(&self.db, file_id, n) == Some(resolved.clone())) |
337 | .collect(); | 341 | .collect(); |
338 | 342 | ||
339 | for r in refs { | 343 | for r in refs { |
@@ -597,3 +601,16 @@ impl<'a> FnCallNode<'a> { | |||
597 | } | 601 | } |
598 | } | 602 | } |
599 | } | 603 | } |
604 | |||
605 | fn resolve_local_name( | ||
606 | db: &db::RootDatabase, | ||
607 | file_id: FileId, | ||
608 | name_ref: ast::NameRef, | ||
609 | ) -> Option<(SmolStr, TextRange)> { | ||
610 | let fn_def = name_ref.syntax().ancestors().find_map(ast::FnDef::cast)?; | ||
611 | let fn_id = FnId::new(file_id, fn_def); | ||
612 | let scopes = db.fn_scopes(fn_id); | ||
613 | let scope_entry = crate::descriptors::function::resolve_local_name(name_ref, &scopes)?; | ||
614 | let syntax = db.resolve_syntax_ptr(scope_entry.ptr().into_global(file_id)); | ||
615 | Some((scope_entry.name().clone(), syntax.range())) | ||
616 | } | ||
diff --git a/crates/ra_analysis/src/lib.rs b/crates/ra_analysis/src/lib.rs index 363c72c0b..776010281 100644 --- a/crates/ra_analysis/src/lib.rs +++ b/crates/ra_analysis/src/lib.rs | |||
@@ -13,6 +13,7 @@ mod imp; | |||
13 | mod symbol_index; | 13 | mod symbol_index; |
14 | mod completion; | 14 | mod completion; |
15 | mod syntax_ptr; | 15 | mod syntax_ptr; |
16 | mod mock_analysis; | ||
16 | 17 | ||
17 | use std::{ | 18 | use std::{ |
18 | fmt, | 19 | fmt, |
@@ -29,11 +30,13 @@ use crate::{ | |||
29 | }; | 30 | }; |
30 | 31 | ||
31 | pub use crate::{ | 32 | pub use crate::{ |
32 | descriptors::FnDescriptor, | 33 | descriptors::function::FnDescriptor, |
33 | input::{FileId, FileResolver, CrateGraph, CrateId} | 34 | completion::CompletionItem, |
35 | input::{FileId, FileResolver, CrateGraph, CrateId}, | ||
36 | mock_analysis::MockAnalysis, | ||
34 | }; | 37 | }; |
35 | pub use ra_editor::{ | 38 | pub use ra_editor::{ |
36 | CompletionItem, FileSymbol, Fold, FoldKind, HighlightedRange, LineIndex, Runnable, | 39 | FileSymbol, Fold, FoldKind, HighlightedRange, LineIndex, Runnable, |
37 | RunnableKind, StructureNode, | 40 | RunnableKind, StructureNode, |
38 | }; | 41 | }; |
39 | 42 | ||
@@ -197,7 +200,7 @@ impl Query { | |||
197 | 200 | ||
198 | #[derive(Debug)] | 201 | #[derive(Debug)] |
199 | pub struct Analysis { | 202 | pub struct Analysis { |
200 | imp: AnalysisImpl, | 203 | pub(crate) imp: AnalysisImpl, |
201 | } | 204 | } |
202 | 205 | ||
203 | impl Analysis { | 206 | impl Analysis { |
diff --git a/crates/ra_analysis/src/mock_analysis.rs b/crates/ra_analysis/src/mock_analysis.rs new file mode 100644 index 000000000..1c1dbee7c --- /dev/null +++ b/crates/ra_analysis/src/mock_analysis.rs | |||
@@ -0,0 +1,71 @@ | |||
1 | |||
2 | use std::sync::Arc; | ||
3 | |||
4 | use relative_path::{RelativePath, RelativePathBuf}; | ||
5 | |||
6 | use crate::{ | ||
7 | AnalysisChange, Analysis, AnalysisHost, FileId, FileResolver, | ||
8 | }; | ||
9 | |||
10 | /// Mock analysis is used in test to bootstrap an AnalysisHost/Analysis | ||
11 | /// from a set of in-memory files. | ||
12 | #[derive(Debug, Default)] | ||
13 | pub struct MockAnalysis { | ||
14 | files: Vec<(String, String)>, | ||
15 | } | ||
16 | |||
17 | impl MockAnalysis { | ||
18 | pub fn new() -> MockAnalysis { | ||
19 | MockAnalysis::default() | ||
20 | } | ||
21 | pub fn with_files(files: &[(&str, &str)]) -> MockAnalysis { | ||
22 | let files = files.iter() | ||
23 | .map(|it| (it.0.to_string(), it.1.to_string())) | ||
24 | .collect(); | ||
25 | MockAnalysis { files } | ||
26 | } | ||
27 | pub fn analysis_host(self) -> AnalysisHost { | ||
28 | let mut host = AnalysisHost::new(); | ||
29 | let mut file_map = Vec::new(); | ||
30 | let mut change = AnalysisChange::new(); | ||
31 | for (id, (path, contents)) in self.files.into_iter().enumerate() { | ||
32 | let file_id = FileId((id + 1) as u32); | ||
33 | assert!(path.starts_with('/')); | ||
34 | let path = RelativePathBuf::from_path(&path[1..]).unwrap(); | ||
35 | change.add_file(file_id, contents); | ||
36 | file_map.push((file_id, path)); | ||
37 | } | ||
38 | change.set_file_resolver(Arc::new(FileMap(file_map))); | ||
39 | host.apply_change(change); | ||
40 | host | ||
41 | } | ||
42 | pub fn analysis(self) -> Analysis { | ||
43 | self.analysis_host().analysis() | ||
44 | } | ||
45 | } | ||
46 | |||
47 | #[derive(Debug)] | ||
48 | struct FileMap(Vec<(FileId, RelativePathBuf)>); | ||
49 | |||
50 | impl FileMap { | ||
51 | fn iter<'a>(&'a self) -> impl Iterator<Item = (FileId, &'a RelativePath)> + 'a { | ||
52 | self.0 | ||
53 | .iter() | ||
54 | .map(|(id, path)| (*id, path.as_relative_path())) | ||
55 | } | ||
56 | |||
57 | fn path(&self, id: FileId) -> &RelativePath { | ||
58 | self.iter().find(|&(it, _)| it == id).unwrap().1 | ||
59 | } | ||
60 | } | ||
61 | |||
62 | impl FileResolver for FileMap { | ||
63 | fn file_stem(&self, id: FileId) -> String { | ||
64 | self.path(id).file_stem().unwrap().to_string() | ||
65 | } | ||
66 | fn resolve(&self, id: FileId, rel: &RelativePath) -> Option<FileId> { | ||
67 | let path = self.path(id).join(rel).normalize(); | ||
68 | let id = self.iter().find(|&(_, p)| path == p)?.0; | ||
69 | Some(id) | ||
70 | } | ||
71 | } | ||
diff --git a/crates/ra_analysis/src/syntax_ptr.rs b/crates/ra_analysis/src/syntax_ptr.rs index 6dc89cb43..c3c904633 100644 --- a/crates/ra_analysis/src/syntax_ptr.rs +++ b/crates/ra_analysis/src/syntax_ptr.rs | |||
@@ -12,6 +12,7 @@ salsa::query_group! { | |||
12 | pub(crate) trait SyntaxPtrDatabase: SyntaxDatabase { | 12 | pub(crate) trait SyntaxPtrDatabase: SyntaxDatabase { |
13 | fn resolve_syntax_ptr(ptr: SyntaxPtr) -> SyntaxNode { | 13 | fn resolve_syntax_ptr(ptr: SyntaxPtr) -> SyntaxNode { |
14 | type ResolveSyntaxPtrQuery; | 14 | type ResolveSyntaxPtrQuery; |
15 | // Don't retain syntax trees in memory | ||
15 | storage volatile; | 16 | storage volatile; |
16 | } | 17 | } |
17 | } | 18 | } |
@@ -83,6 +84,10 @@ impl LocalSyntaxPtr { | |||
83 | .unwrap_or_else(|| panic!("can't resolve local ptr to SyntaxNode: {:?}", self)) | 84 | .unwrap_or_else(|| panic!("can't resolve local ptr to SyntaxNode: {:?}", self)) |
84 | } | 85 | } |
85 | } | 86 | } |
87 | |||
88 | pub(crate) fn into_global(self, file_id: FileId) -> SyntaxPtr { | ||
89 | SyntaxPtr { file_id, local: self} | ||
90 | } | ||
86 | } | 91 | } |
87 | 92 | ||
88 | 93 | ||