aboutsummaryrefslogtreecommitdiff
path: root/crates/ide/src/completion/completion_context.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ide/src/completion/completion_context.rs')
-rw-r--r--crates/ide/src/completion/completion_context.rs504
1 files changed, 0 insertions, 504 deletions
diff --git a/crates/ide/src/completion/completion_context.rs b/crates/ide/src/completion/completion_context.rs
deleted file mode 100644
index 8dea8a4bf..000000000
--- a/crates/ide/src/completion/completion_context.rs
+++ /dev/null
@@ -1,504 +0,0 @@
1//! FIXME: write short doc here
2
3use base_db::SourceDatabase;
4use hir::{Local, ScopeDef, Semantics, SemanticsScope, Type};
5use ide_db::RootDatabase;
6use syntax::{
7 algo::{find_covering_element, find_node_at_offset},
8 ast, match_ast, AstNode, NodeOrToken,
9 SyntaxKind::*,
10 SyntaxNode, SyntaxToken, TextRange, TextSize,
11};
12use test_utils::mark;
13use text_edit::Indel;
14
15use crate::{
16 call_info::ActiveParameter,
17 completion::{
18 patterns::{
19 has_bind_pat_parent, has_block_expr_parent, has_field_list_parent,
20 has_impl_as_prev_sibling, has_impl_parent, has_item_list_or_source_file_parent,
21 has_ref_parent, has_trait_as_prev_sibling, has_trait_parent, if_is_prev,
22 is_in_loop_body, is_match_arm, unsafe_is_prev,
23 },
24 CompletionConfig,
25 },
26 FilePosition,
27};
28
29/// `CompletionContext` is created early during completion to figure out, where
30/// exactly is the cursor, syntax-wise.
31#[derive(Debug)]
32pub(crate) struct CompletionContext<'a> {
33 pub(super) sema: Semantics<'a, RootDatabase>,
34 pub(super) scope: SemanticsScope<'a>,
35 pub(super) db: &'a RootDatabase,
36 pub(super) config: &'a CompletionConfig,
37 pub(super) position: FilePosition,
38 /// The token before the cursor, in the original file.
39 pub(super) original_token: SyntaxToken,
40 /// The token before the cursor, in the macro-expanded file.
41 pub(super) token: SyntaxToken,
42 pub(super) krate: Option<hir::Crate>,
43 pub(super) expected_type: Option<Type>,
44 pub(super) name_ref_syntax: Option<ast::NameRef>,
45 pub(super) function_syntax: Option<ast::Fn>,
46 pub(super) use_item_syntax: Option<ast::Use>,
47 pub(super) record_lit_syntax: Option<ast::RecordExpr>,
48 pub(super) record_pat_syntax: Option<ast::RecordPat>,
49 pub(super) record_field_syntax: Option<ast::RecordExprField>,
50 pub(super) impl_def: Option<ast::Impl>,
51 /// FIXME: `ActiveParameter` is string-based, which is very very wrong
52 pub(super) active_parameter: Option<ActiveParameter>,
53 pub(super) is_param: bool,
54 /// If a name-binding or reference to a const in a pattern.
55 /// Irrefutable patterns (like let) are excluded.
56 pub(super) is_pat_binding_or_const: bool,
57 /// A single-indent path, like `foo`. `::foo` should not be considered a trivial path.
58 pub(super) is_trivial_path: bool,
59 /// If not a trivial path, the prefix (qualifier).
60 pub(super) path_qual: Option<ast::Path>,
61 pub(super) after_if: bool,
62 /// `true` if we are a statement or a last expr in the block.
63 pub(super) can_be_stmt: bool,
64 /// `true` if we expect an expression at the cursor position.
65 pub(super) is_expr: bool,
66 /// Something is typed at the "top" level, in module or impl/trait.
67 pub(super) is_new_item: bool,
68 /// The receiver if this is a field or method access, i.e. writing something.<|>
69 pub(super) dot_receiver: Option<ast::Expr>,
70 pub(super) dot_receiver_is_ambiguous_float_literal: bool,
71 /// If this is a call (method or function) in particular, i.e. the () are already there.
72 pub(super) is_call: bool,
73 /// Like `is_call`, but for tuple patterns.
74 pub(super) is_pattern_call: bool,
75 /// If this is a macro call, i.e. the () are already there.
76 pub(super) is_macro_call: bool,
77 pub(super) is_path_type: bool,
78 pub(super) has_type_args: bool,
79 pub(super) attribute_under_caret: Option<ast::Attr>,
80 pub(super) mod_declaration_under_caret: Option<ast::Module>,
81 pub(super) unsafe_is_prev: bool,
82 pub(super) if_is_prev: bool,
83 pub(super) block_expr_parent: bool,
84 pub(super) bind_pat_parent: bool,
85 pub(super) ref_pat_parent: bool,
86 pub(super) in_loop_body: bool,
87 pub(super) has_trait_parent: bool,
88 pub(super) has_impl_parent: bool,
89 pub(super) has_field_list_parent: bool,
90 pub(super) trait_as_prev_sibling: bool,
91 pub(super) impl_as_prev_sibling: bool,
92 pub(super) is_match_arm: bool,
93 pub(super) has_item_list_or_source_file_parent: bool,
94 pub(super) locals: Vec<(String, Local)>,
95}
96
97impl<'a> CompletionContext<'a> {
98 pub(super) fn new(
99 db: &'a RootDatabase,
100 position: FilePosition,
101 config: &'a CompletionConfig,
102 ) -> Option<CompletionContext<'a>> {
103 let sema = Semantics::new(db);
104
105 let original_file = sema.parse(position.file_id);
106
107 // Insert a fake ident to get a valid parse tree. We will use this file
108 // to determine context, though the original_file will be used for
109 // actual completion.
110 let file_with_fake_ident = {
111 let parse = db.parse(position.file_id);
112 let edit = Indel::insert(position.offset, "intellijRulezz".to_string());
113 parse.reparse(&edit).tree()
114 };
115 let fake_ident_token =
116 file_with_fake_ident.syntax().token_at_offset(position.offset).right_biased().unwrap();
117
118 let krate = sema.to_module_def(position.file_id).map(|m| m.krate());
119 let original_token =
120 original_file.syntax().token_at_offset(position.offset).left_biased()?;
121 let token = sema.descend_into_macros(original_token.clone());
122 let scope = sema.scope_at_offset(&token.parent(), position.offset);
123 let mut locals = vec![];
124 scope.process_all_names(&mut |name, scope| {
125 if let ScopeDef::Local(local) = scope {
126 locals.push((name.to_string(), local));
127 }
128 });
129 let mut ctx = CompletionContext {
130 sema,
131 scope,
132 db,
133 config,
134 original_token,
135 token,
136 position,
137 krate,
138 expected_type: None,
139 name_ref_syntax: None,
140 function_syntax: None,
141 use_item_syntax: None,
142 record_lit_syntax: None,
143 record_pat_syntax: None,
144 record_field_syntax: None,
145 impl_def: None,
146 active_parameter: ActiveParameter::at(db, position),
147 is_param: false,
148 is_pat_binding_or_const: false,
149 is_trivial_path: false,
150 path_qual: None,
151 after_if: false,
152 can_be_stmt: false,
153 is_expr: false,
154 is_new_item: false,
155 dot_receiver: None,
156 is_call: false,
157 is_pattern_call: false,
158 is_macro_call: false,
159 is_path_type: false,
160 has_type_args: false,
161 dot_receiver_is_ambiguous_float_literal: false,
162 attribute_under_caret: None,
163 mod_declaration_under_caret: None,
164 unsafe_is_prev: false,
165 in_loop_body: false,
166 ref_pat_parent: false,
167 bind_pat_parent: false,
168 block_expr_parent: false,
169 has_trait_parent: false,
170 has_impl_parent: false,
171 has_field_list_parent: false,
172 trait_as_prev_sibling: false,
173 impl_as_prev_sibling: false,
174 if_is_prev: false,
175 is_match_arm: false,
176 has_item_list_or_source_file_parent: false,
177 locals,
178 };
179
180 let mut original_file = original_file.syntax().clone();
181 let mut hypothetical_file = file_with_fake_ident.syntax().clone();
182 let mut offset = position.offset;
183 let mut fake_ident_token = fake_ident_token;
184
185 // Are we inside a macro call?
186 while let (Some(actual_macro_call), Some(macro_call_with_fake_ident)) = (
187 find_node_at_offset::<ast::MacroCall>(&original_file, offset),
188 find_node_at_offset::<ast::MacroCall>(&hypothetical_file, offset),
189 ) {
190 if actual_macro_call.path().as_ref().map(|s| s.syntax().text())
191 != macro_call_with_fake_ident.path().as_ref().map(|s| s.syntax().text())
192 {
193 break;
194 }
195 let hypothetical_args = match macro_call_with_fake_ident.token_tree() {
196 Some(tt) => tt,
197 None => break,
198 };
199 if let (Some(actual_expansion), Some(hypothetical_expansion)) = (
200 ctx.sema.expand(&actual_macro_call),
201 ctx.sema.speculative_expand(
202 &actual_macro_call,
203 &hypothetical_args,
204 fake_ident_token,
205 ),
206 ) {
207 let new_offset = hypothetical_expansion.1.text_range().start();
208 if new_offset > actual_expansion.text_range().end() {
209 break;
210 }
211 original_file = actual_expansion;
212 hypothetical_file = hypothetical_expansion.0;
213 fake_ident_token = hypothetical_expansion.1;
214 offset = new_offset;
215 } else {
216 break;
217 }
218 }
219 ctx.fill_keyword_patterns(&hypothetical_file, offset);
220 ctx.fill(&original_file, hypothetical_file, offset);
221 Some(ctx)
222 }
223
224 /// The range of the identifier that is being completed.
225 pub(crate) fn source_range(&self) -> TextRange {
226 // check kind of macro-expanded token, but use range of original token
227 let kind = self.token.kind();
228 if kind == IDENT || kind == UNDERSCORE || kind.is_keyword() {
229 mark::hit!(completes_if_prefix_is_keyword);
230 self.original_token.text_range()
231 } else {
232 TextRange::empty(self.position.offset)
233 }
234 }
235
236 fn fill_keyword_patterns(&mut self, file_with_fake_ident: &SyntaxNode, offset: TextSize) {
237 let fake_ident_token = file_with_fake_ident.token_at_offset(offset).right_biased().unwrap();
238 let syntax_element = NodeOrToken::Token(fake_ident_token);
239 self.block_expr_parent = has_block_expr_parent(syntax_element.clone());
240 self.unsafe_is_prev = unsafe_is_prev(syntax_element.clone());
241 self.if_is_prev = if_is_prev(syntax_element.clone());
242 self.bind_pat_parent = has_bind_pat_parent(syntax_element.clone());
243 self.ref_pat_parent = has_ref_parent(syntax_element.clone());
244 self.in_loop_body = is_in_loop_body(syntax_element.clone());
245 self.has_trait_parent = has_trait_parent(syntax_element.clone());
246 self.has_impl_parent = has_impl_parent(syntax_element.clone());
247 self.has_field_list_parent = has_field_list_parent(syntax_element.clone());
248 self.impl_as_prev_sibling = has_impl_as_prev_sibling(syntax_element.clone());
249 self.trait_as_prev_sibling = has_trait_as_prev_sibling(syntax_element.clone());
250 self.is_match_arm = is_match_arm(syntax_element.clone());
251 self.has_item_list_or_source_file_parent =
252 has_item_list_or_source_file_parent(syntax_element.clone());
253 self.mod_declaration_under_caret =
254 find_node_at_offset::<ast::Module>(&file_with_fake_ident, offset)
255 .filter(|module| module.item_list().is_none());
256 }
257
258 fn fill(
259 &mut self,
260 original_file: &SyntaxNode,
261 file_with_fake_ident: SyntaxNode,
262 offset: TextSize,
263 ) {
264 // FIXME: this is wrong in at least two cases:
265 // * when there's no token `foo(<|>)`
266 // * when there is a token, but it happens to have type of it's own
267 self.expected_type = self
268 .token
269 .ancestors()
270 .find_map(|node| {
271 let ty = match_ast! {
272 match node {
273 ast::Pat(it) => self.sema.type_of_pat(&it),
274 ast::Expr(it) => self.sema.type_of_expr(&it),
275 _ => return None,
276 }
277 };
278 Some(ty)
279 })
280 .flatten();
281 self.attribute_under_caret = find_node_at_offset(&file_with_fake_ident, offset);
282
283 // First, let's try to complete a reference to some declaration.
284 if let Some(name_ref) = find_node_at_offset::<ast::NameRef>(&file_with_fake_ident, offset) {
285 // Special case, `trait T { fn foo(i_am_a_name_ref) {} }`.
286 // See RFC#1685.
287 if is_node::<ast::Param>(name_ref.syntax()) {
288 self.is_param = true;
289 return;
290 }
291 // FIXME: remove this (V) duplication and make the check more precise
292 if name_ref.syntax().ancestors().find_map(ast::RecordPatFieldList::cast).is_some() {
293 self.record_pat_syntax =
294 self.sema.find_node_at_offset_with_macros(&original_file, offset);
295 }
296 self.classify_name_ref(original_file, name_ref, offset);
297 }
298
299 // Otherwise, see if this is a declaration. We can use heuristics to
300 // suggest declaration names, see `CompletionKind::Magic`.
301 if let Some(name) = find_node_at_offset::<ast::Name>(&file_with_fake_ident, offset) {
302 if let Some(bind_pat) = name.syntax().ancestors().find_map(ast::IdentPat::cast) {
303 self.is_pat_binding_or_const = true;
304 if bind_pat.at_token().is_some()
305 || bind_pat.ref_token().is_some()
306 || bind_pat.mut_token().is_some()
307 {
308 self.is_pat_binding_or_const = false;
309 }
310 if bind_pat.syntax().parent().and_then(ast::RecordPatFieldList::cast).is_some() {
311 self.is_pat_binding_or_const = false;
312 }
313 if let Some(let_stmt) = bind_pat.syntax().ancestors().find_map(ast::LetStmt::cast) {
314 if let Some(pat) = let_stmt.pat() {
315 if pat.syntax().text_range().contains_range(bind_pat.syntax().text_range())
316 {
317 self.is_pat_binding_or_const = false;
318 }
319 }
320 }
321 }
322 if is_node::<ast::Param>(name.syntax()) {
323 self.is_param = true;
324 return;
325 }
326 // FIXME: remove this (^) duplication and make the check more precise
327 if name.syntax().ancestors().find_map(ast::RecordPatFieldList::cast).is_some() {
328 self.record_pat_syntax =
329 self.sema.find_node_at_offset_with_macros(&original_file, offset);
330 }
331 }
332 }
333
334 fn classify_name_ref(
335 &mut self,
336 original_file: &SyntaxNode,
337 name_ref: ast::NameRef,
338 offset: TextSize,
339 ) {
340 self.name_ref_syntax =
341 find_node_at_offset(&original_file, name_ref.syntax().text_range().start());
342 let name_range = name_ref.syntax().text_range();
343 if ast::RecordExprField::for_field_name(&name_ref).is_some() {
344 self.record_lit_syntax =
345 self.sema.find_node_at_offset_with_macros(&original_file, offset);
346 }
347
348 self.impl_def = self
349 .sema
350 .ancestors_with_macros(self.token.parent())
351 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
352 .find_map(ast::Impl::cast);
353
354 let top_node = name_ref
355 .syntax()
356 .ancestors()
357 .take_while(|it| it.text_range() == name_range)
358 .last()
359 .unwrap();
360
361 match top_node.parent().map(|it| it.kind()) {
362 Some(SOURCE_FILE) | Some(ITEM_LIST) => {
363 self.is_new_item = true;
364 return;
365 }
366 _ => (),
367 }
368
369 self.use_item_syntax =
370 self.sema.ancestors_with_macros(self.token.parent()).find_map(ast::Use::cast);
371
372 self.function_syntax = self
373 .sema
374 .ancestors_with_macros(self.token.parent())
375 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
376 .find_map(ast::Fn::cast);
377
378 self.record_field_syntax = self
379 .sema
380 .ancestors_with_macros(self.token.parent())
381 .take_while(|it| {
382 it.kind() != SOURCE_FILE && it.kind() != MODULE && it.kind() != CALL_EXPR
383 })
384 .find_map(ast::RecordExprField::cast);
385
386 let parent = match name_ref.syntax().parent() {
387 Some(it) => it,
388 None => return,
389 };
390
391 if let Some(segment) = ast::PathSegment::cast(parent.clone()) {
392 let path = segment.parent_path();
393 self.is_call = path
394 .syntax()
395 .parent()
396 .and_then(ast::PathExpr::cast)
397 .and_then(|it| it.syntax().parent().and_then(ast::CallExpr::cast))
398 .is_some();
399 self.is_macro_call = path.syntax().parent().and_then(ast::MacroCall::cast).is_some();
400 self.is_pattern_call =
401 path.syntax().parent().and_then(ast::TupleStructPat::cast).is_some();
402
403 self.is_path_type = path.syntax().parent().and_then(ast::PathType::cast).is_some();
404 self.has_type_args = segment.generic_arg_list().is_some();
405
406 if let Some(path) = path_or_use_tree_qualifier(&path) {
407 self.path_qual = path
408 .segment()
409 .and_then(|it| {
410 find_node_with_range::<ast::PathSegment>(
411 original_file,
412 it.syntax().text_range(),
413 )
414 })
415 .map(|it| it.parent_path());
416 return;
417 }
418
419 if let Some(segment) = path.segment() {
420 if segment.coloncolon_token().is_some() {
421 return;
422 }
423 }
424
425 self.is_trivial_path = true;
426
427 // Find either enclosing expr statement (thing with `;`) or a
428 // block. If block, check that we are the last expr.
429 self.can_be_stmt = name_ref
430 .syntax()
431 .ancestors()
432 .find_map(|node| {
433 if let Some(stmt) = ast::ExprStmt::cast(node.clone()) {
434 return Some(stmt.syntax().text_range() == name_ref.syntax().text_range());
435 }
436 if let Some(block) = ast::BlockExpr::cast(node) {
437 return Some(
438 block.expr().map(|e| e.syntax().text_range())
439 == Some(name_ref.syntax().text_range()),
440 );
441 }
442 None
443 })
444 .unwrap_or(false);
445 self.is_expr = path.syntax().parent().and_then(ast::PathExpr::cast).is_some();
446
447 if let Some(off) = name_ref.syntax().text_range().start().checked_sub(2.into()) {
448 if let Some(if_expr) =
449 self.sema.find_node_at_offset_with_macros::<ast::IfExpr>(original_file, off)
450 {
451 if if_expr.syntax().text_range().end() < name_ref.syntax().text_range().start()
452 {
453 self.after_if = true;
454 }
455 }
456 }
457 }
458 if let Some(field_expr) = ast::FieldExpr::cast(parent.clone()) {
459 // The receiver comes before the point of insertion of the fake
460 // ident, so it should have the same range in the non-modified file
461 self.dot_receiver = field_expr
462 .expr()
463 .map(|e| e.syntax().text_range())
464 .and_then(|r| find_node_with_range(original_file, r));
465 self.dot_receiver_is_ambiguous_float_literal =
466 if let Some(ast::Expr::Literal(l)) = &self.dot_receiver {
467 match l.kind() {
468 ast::LiteralKind::FloatNumber { .. } => l.token().text().ends_with('.'),
469 _ => false,
470 }
471 } else {
472 false
473 };
474 }
475 if let Some(method_call_expr) = ast::MethodCallExpr::cast(parent) {
476 // As above
477 self.dot_receiver = method_call_expr
478 .receiver()
479 .map(|e| e.syntax().text_range())
480 .and_then(|r| find_node_with_range(original_file, r));
481 self.is_call = true;
482 }
483 }
484}
485
486fn find_node_with_range<N: AstNode>(syntax: &SyntaxNode, range: TextRange) -> Option<N> {
487 find_covering_element(syntax, range).ancestors().find_map(N::cast)
488}
489
490fn is_node<N: AstNode>(node: &SyntaxNode) -> bool {
491 match node.ancestors().find_map(N::cast) {
492 None => false,
493 Some(n) => n.syntax().text_range() == node.text_range(),
494 }
495}
496
497fn path_or_use_tree_qualifier(path: &ast::Path) -> Option<ast::Path> {
498 if let Some(qual) = path.qualifier() {
499 return Some(qual);
500 }
501 let use_tree_list = path.syntax().ancestors().find_map(ast::UseTreeList::cast)?;
502 let use_tree = use_tree_list.syntax().parent().and_then(ast::UseTree::cast)?;
503 use_tree.path()
504}