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