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