]> git.lizzy.rs Git - rust.git/blob - crates/ide_completion/src/context.rs
simplify
[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::{
5     base_db::{FilePosition, SourceDatabase},
6     call_info::ActiveParameter,
7     RootDatabase,
8 };
9 use syntax::{
10     algo::find_node_at_offset,
11     ast::{self, NameOrNameRef, NameOwner},
12     match_ast, AstNode, NodeOrToken,
13     SyntaxKind::{self, *},
14     SyntaxNode, SyntaxToken, TextRange, TextSize, T,
15 };
16 use text_edit::Indel;
17
18 use crate::{
19     patterns::{
20         for_is_prev2, has_bind_pat_parent, has_block_expr_parent, has_field_list_parent,
21         has_impl_parent, has_item_list_or_source_file_parent, has_prev_sibling, has_ref_parent,
22         has_trait_parent, inside_impl_trait_block, is_in_loop_body, is_match_arm, previous_token,
23     },
24     CompletionConfig,
25 };
26
27 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
28 pub(crate) enum PatternRefutability {
29     Refutable,
30     Irrefutable,
31 }
32
33 /// Direct parent container of the cursor position
34 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
35 pub(crate) enum ImmediateLocation {
36     Impl,
37     Trait,
38     RecordFieldList,
39     RefPatOrExpr,
40     IdentPat,
41     BlockExpr,
42     ItemList,
43 }
44
45 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
46 pub(crate) enum PrevSibling {
47     Trait,
48     Impl,
49 }
50
51 /// `CompletionContext` is created early during completion to figure out, where
52 /// exactly is the cursor, syntax-wise.
53 #[derive(Debug)]
54 pub(crate) struct CompletionContext<'a> {
55     pub(super) sema: Semantics<'a, RootDatabase>,
56     pub(super) scope: SemanticsScope<'a>,
57     pub(super) db: &'a RootDatabase,
58     pub(super) config: &'a CompletionConfig,
59     pub(super) position: FilePosition,
60     /// The token before the cursor, in the original file.
61     pub(super) original_token: SyntaxToken,
62     /// The token before the cursor, in the macro-expanded file.
63     pub(super) token: SyntaxToken,
64     pub(super) krate: Option<hir::Crate>,
65     pub(super) expected_name: Option<NameOrNameRef>,
66     pub(super) expected_type: Option<Type>,
67     pub(super) name_ref_syntax: Option<ast::NameRef>,
68
69     pub(super) use_item_syntax: Option<ast::Use>,
70
71     /// The parent function of the cursor position if it exists.
72     pub(super) function_def: Option<ast::Fn>,
73     /// The parent impl of the cursor position if it exists.
74     pub(super) impl_def: Option<ast::Impl>,
75
76     /// RecordExpr the token is a field of
77     pub(super) record_lit_syntax: Option<ast::RecordExpr>,
78     /// RecordPat the token is a field of
79     pub(super) record_pat_syntax: Option<ast::RecordPat>,
80
81     // potentially set if we are completing a lifetime
82     pub(super) lifetime_syntax: Option<ast::Lifetime>,
83     pub(super) lifetime_param_syntax: Option<ast::LifetimeParam>,
84     pub(super) lifetime_allowed: bool,
85     pub(super) is_label_ref: bool,
86
87     // potentially set if we are completing a name
88     pub(super) is_pat_or_const: Option<PatternRefutability>,
89     pub(super) is_param: bool,
90
91     pub(super) completion_location: Option<ImmediateLocation>,
92
93     /// FIXME: `ActiveParameter` is string-based, which is very very wrong
94     pub(super) active_parameter: Option<ActiveParameter>,
95     /// A single-indent path, like `foo`. `::foo` should not be considered a trivial path.
96     pub(super) is_trivial_path: bool,
97     /// If not a trivial path, the prefix (qualifier).
98     pub(super) path_qual: Option<ast::Path>,
99     pub(super) after_if: bool,
100     /// `true` if we are a statement or a last expr in the block.
101     pub(super) can_be_stmt: bool,
102     /// `true` if we expect an expression at the cursor position.
103     pub(super) is_expr: bool,
104     /// Something is typed at the "top" level, in module or impl/trait.
105     pub(super) is_new_item: bool,
106     /// The receiver if this is a field or method access, i.e. writing something.$0
107     pub(super) dot_receiver: Option<ast::Expr>,
108     pub(super) dot_receiver_is_ambiguous_float_literal: bool,
109     /// If this is a call (method or function) in particular, i.e. the () are already there.
110     pub(super) is_call: bool,
111     /// Like `is_call`, but for tuple patterns.
112     pub(super) is_pattern_call: bool,
113     /// If this is a macro call, i.e. the () are already there.
114     pub(super) is_macro_call: bool,
115     pub(super) is_path_type: bool,
116     pub(super) has_type_args: bool,
117     pub(super) attribute_under_caret: Option<ast::Attr>,
118     pub(super) locals: Vec<(String, Local)>,
119
120     pub(super) mod_declaration_under_caret: Option<ast::Module>,
121
122     // keyword patterns
123     pub(super) previous_token: Option<SyntaxToken>,
124     pub(super) in_loop_body: bool,
125     pub(super) prev_sibling: Option<PrevSibling>,
126     pub(super) is_match_arm: bool,
127     pub(super) incomplete_let: bool,
128
129     no_completion_required: bool,
130 }
131 impl<'a> CompletionContext<'a> {
132     pub(super) fn new(
133         db: &'a RootDatabase,
134         position: FilePosition,
135         config: &'a CompletionConfig,
136     ) -> Option<CompletionContext<'a>> {
137         let sema = Semantics::new(db);
138
139         let original_file = sema.parse(position.file_id);
140
141         // Insert a fake ident to get a valid parse tree. We will use this file
142         // to determine context, though the original_file will be used for
143         // actual completion.
144         let file_with_fake_ident = {
145             let parse = db.parse(position.file_id);
146             let edit = Indel::insert(position.offset, "intellijRulezz".to_string());
147             parse.reparse(&edit).tree()
148         };
149         let fake_ident_token =
150             file_with_fake_ident.syntax().token_at_offset(position.offset).right_biased().unwrap();
151
152         let krate = sema.to_module_def(position.file_id).map(|m| m.krate());
153         let original_token =
154             original_file.syntax().token_at_offset(position.offset).left_biased()?;
155         let token = sema.descend_into_macros(original_token.clone());
156         let scope = sema.scope_at_offset(&token, position.offset);
157         let mut locals = vec![];
158         scope.process_all_names(&mut |name, scope| {
159             if let ScopeDef::Local(local) = scope {
160                 locals.push((name.to_string(), local));
161             }
162         });
163         let mut ctx = CompletionContext {
164             sema,
165             scope,
166             db,
167             config,
168             position,
169             original_token,
170             token,
171             krate,
172             lifetime_allowed: false,
173             expected_name: None,
174             expected_type: None,
175             name_ref_syntax: None,
176             lifetime_syntax: None,
177             lifetime_param_syntax: None,
178             function_def: None,
179             use_item_syntax: None,
180             record_lit_syntax: None,
181             record_pat_syntax: None,
182             impl_def: None,
183             active_parameter: ActiveParameter::at(db, position),
184             is_label_ref: false,
185             is_param: false,
186             is_pat_or_const: None,
187             is_trivial_path: false,
188             path_qual: None,
189             after_if: false,
190             can_be_stmt: false,
191             is_expr: false,
192             is_new_item: false,
193             dot_receiver: None,
194             dot_receiver_is_ambiguous_float_literal: false,
195             is_call: false,
196             is_pattern_call: false,
197             is_macro_call: false,
198             is_path_type: false,
199             has_type_args: false,
200             attribute_under_caret: None,
201             mod_declaration_under_caret: None,
202             previous_token: None,
203             in_loop_body: false,
204             completion_location: None,
205             prev_sibling: None,
206             is_match_arm: false,
207             no_completion_required: false,
208             incomplete_let: false,
209             locals,
210         };
211
212         let mut original_file = original_file.syntax().clone();
213         let mut speculative_file = file_with_fake_ident.syntax().clone();
214         let mut offset = position.offset;
215         let mut fake_ident_token = fake_ident_token;
216
217         // Are we inside a macro call?
218         while let (Some(actual_macro_call), Some(macro_call_with_fake_ident)) = (
219             find_node_at_offset::<ast::MacroCall>(&original_file, offset),
220             find_node_at_offset::<ast::MacroCall>(&speculative_file, offset),
221         ) {
222             if actual_macro_call.path().as_ref().map(|s| s.syntax().text())
223                 != macro_call_with_fake_ident.path().as_ref().map(|s| s.syntax().text())
224             {
225                 break;
226             }
227             let speculative_args = match macro_call_with_fake_ident.token_tree() {
228                 Some(tt) => tt,
229                 None => break,
230             };
231             if let (Some(actual_expansion), Some(speculative_expansion)) = (
232                 ctx.sema.expand(&actual_macro_call),
233                 ctx.sema.speculative_expand(
234                     &actual_macro_call,
235                     &speculative_args,
236                     fake_ident_token,
237                 ),
238             ) {
239                 let new_offset = speculative_expansion.1.text_range().start();
240                 if new_offset > actual_expansion.text_range().end() {
241                     break;
242                 }
243                 original_file = actual_expansion;
244                 speculative_file = speculative_expansion.0;
245                 fake_ident_token = speculative_expansion.1;
246                 offset = new_offset;
247             } else {
248                 break;
249             }
250         }
251         ctx.fill_keyword_patterns(&speculative_file, offset);
252         ctx.fill(&original_file, speculative_file, offset);
253         Some(ctx)
254     }
255
256     /// Checks whether completions in that particular case don't make much sense.
257     /// Examples:
258     /// - `fn $0` -- we expect function name, it's unlikely that "hint" will be helpful.
259     ///   Exception for this case is `impl Trait for Foo`, where we would like to hint trait method names.
260     /// - `for _ i$0` -- obviously, it'll be "in" keyword.
261     pub(crate) fn no_completion_required(&self) -> bool {
262         self.no_completion_required
263     }
264
265     /// The range of the identifier that is being completed.
266     pub(crate) fn source_range(&self) -> TextRange {
267         // check kind of macro-expanded token, but use range of original token
268         let kind = self.token.kind();
269         if kind == IDENT || kind == LIFETIME_IDENT || kind == UNDERSCORE || kind.is_keyword() {
270             cov_mark::hit!(completes_if_prefix_is_keyword);
271             self.original_token.text_range()
272         } else if kind == CHAR {
273             // assume we are completing a lifetime but the user has only typed the '
274             cov_mark::hit!(completes_if_lifetime_without_idents);
275             TextRange::at(self.original_token.text_range().start(), TextSize::from(1))
276         } else {
277             TextRange::empty(self.position.offset)
278         }
279     }
280
281     pub(crate) fn previous_token_is(&self, kind: SyntaxKind) -> bool {
282         self.previous_token.as_ref().map_or(false, |tok| tok.kind() == kind)
283     }
284
285     pub(crate) fn has_impl_or_trait_parent(&self) -> bool {
286         matches!(
287             self.completion_location,
288             Some(ImmediateLocation::Trait) | Some(ImmediateLocation::Impl)
289         )
290     }
291
292     pub(crate) fn has_block_expr_parent(&self) -> bool {
293         matches!(self.completion_location, Some(ImmediateLocation::BlockExpr))
294     }
295
296     pub(crate) fn has_item_list_parent(&self) -> bool {
297         matches!(self.completion_location, Some(ImmediateLocation::ItemList))
298     }
299
300     pub(crate) fn has_ident_or_ref_pat_parent(&self) -> bool {
301         matches!(
302             self.completion_location,
303             Some(ImmediateLocation::IdentPat) | Some(ImmediateLocation::RefPatOrExpr)
304         )
305     }
306
307     pub(crate) fn has_impl_parent(&self) -> bool {
308         matches!(self.completion_location, Some(ImmediateLocation::Impl))
309     }
310
311     pub(crate) fn has_field_list_parent(&self) -> bool {
312         matches!(self.completion_location, Some(ImmediateLocation::RecordFieldList))
313     }
314
315     pub(crate) fn has_impl_or_trait_prev_sibling(&self) -> bool {
316         self.prev_sibling.is_some()
317     }
318
319     fn fill_keyword_patterns(&mut self, file_with_fake_ident: &SyntaxNode, offset: TextSize) {
320         let fake_ident_token = file_with_fake_ident.token_at_offset(offset).right_biased().unwrap();
321         let syntax_element = NodeOrToken::Token(fake_ident_token);
322         self.previous_token = previous_token(syntax_element.clone());
323         self.in_loop_body = is_in_loop_body(syntax_element.clone());
324         self.is_match_arm = is_match_arm(syntax_element.clone());
325         if has_prev_sibling(syntax_element.clone(), IMPL) {
326             self.prev_sibling = Some(PrevSibling::Impl)
327         } else if has_prev_sibling(syntax_element.clone(), TRAIT) {
328             self.prev_sibling = Some(PrevSibling::Trait)
329         }
330
331         if has_block_expr_parent(syntax_element.clone()) {
332             self.completion_location = Some(ImmediateLocation::BlockExpr);
333         } else if has_bind_pat_parent(syntax_element.clone()) {
334             self.completion_location = Some(ImmediateLocation::IdentPat);
335         } else if has_ref_parent(syntax_element.clone()) {
336             self.completion_location = Some(ImmediateLocation::RefPatOrExpr);
337         } else if has_impl_parent(syntax_element.clone()) {
338             self.completion_location = Some(ImmediateLocation::Impl);
339         } else if has_field_list_parent(syntax_element.clone()) {
340             self.completion_location = Some(ImmediateLocation::RecordFieldList);
341         } else if has_trait_parent(syntax_element.clone()) {
342             self.completion_location = Some(ImmediateLocation::Trait);
343         } else if has_item_list_or_source_file_parent(syntax_element.clone()) {
344             self.completion_location = Some(ImmediateLocation::ItemList);
345         }
346
347         self.mod_declaration_under_caret =
348             find_node_at_offset::<ast::Module>(&file_with_fake_ident, offset)
349                 .filter(|module| module.item_list().is_none());
350         self.incomplete_let =
351             syntax_element.ancestors().take(6).find_map(ast::LetStmt::cast).map_or(false, |it| {
352                 it.syntax().text_range().end() == syntax_element.text_range().end()
353             });
354
355         let inside_impl_trait_block = inside_impl_trait_block(syntax_element.clone());
356         let fn_is_prev = self.previous_token_is(T![fn]);
357         let for_is_prev2 = for_is_prev2(syntax_element.clone());
358         self.no_completion_required = (fn_is_prev && !inside_impl_trait_block) || for_is_prev2;
359     }
360
361     fn fill_impl_def(&mut self) {
362         self.impl_def = self
363             .sema
364             .token_ancestors_with_macros(self.token.clone())
365             .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
366             .find_map(ast::Impl::cast);
367     }
368
369     fn expected_type_and_name(&self) -> (Option<Type>, Option<NameOrNameRef>) {
370         let mut node = match self.token.parent() {
371             Some(it) => it,
372             None => return (None, None),
373         };
374         loop {
375             break match_ast! {
376                 match node {
377                     ast::LetStmt(it) => {
378                         cov_mark::hit!(expected_type_let_with_leading_char);
379                         cov_mark::hit!(expected_type_let_without_leading_char);
380                         let ty = it.pat()
381                             .and_then(|pat| self.sema.type_of_pat(&pat))
382                             .or_else(|| it.initializer().and_then(|it| self.sema.type_of_expr(&it)));
383                         let name = if let Some(ast::Pat::IdentPat(ident)) = it.pat() {
384                             ident.name().map(NameOrNameRef::Name)
385                         } else {
386                             None
387                         };
388
389                         (ty, name)
390                     },
391                     ast::ArgList(_it) => {
392                         cov_mark::hit!(expected_type_fn_param_with_leading_char);
393                         cov_mark::hit!(expected_type_fn_param_without_leading_char);
394                         ActiveParameter::at_token(
395                             &self.sema,
396                             self.token.clone(),
397                         ).map(|ap| {
398                             let name = ap.ident().map(NameOrNameRef::Name);
399                             (Some(ap.ty), name)
400                         })
401                         .unwrap_or((None, None))
402                     },
403                     ast::RecordExprFieldList(_it) => {
404                         cov_mark::hit!(expected_type_struct_field_without_leading_char);
405                         // wouldn't try {} be nice...
406                         (|| {
407                             let expr_field = self.token.prev_sibling_or_token()?
408                                       .into_node()
409                                       .and_then(|node| ast::RecordExprField::cast(node))?;
410                             let (_, _, ty) = self.sema.resolve_record_field(&expr_field)?;
411                             Some((
412                                 Some(ty),
413                                 expr_field.field_name().map(NameOrNameRef::NameRef),
414                             ))
415                         })().unwrap_or((None, None))
416                     },
417                     ast::RecordExprField(it) => {
418                         cov_mark::hit!(expected_type_struct_field_with_leading_char);
419                         (
420                             it.expr().as_ref().and_then(|e| self.sema.type_of_expr(e)),
421                             it.field_name().map(NameOrNameRef::NameRef),
422                         )
423                     },
424                     ast::MatchExpr(it) => {
425                         cov_mark::hit!(expected_type_match_arm_without_leading_char);
426                         let ty = it.expr()
427                             .and_then(|e| self.sema.type_of_expr(&e));
428                         (ty, None)
429                     },
430                     ast::IfExpr(it) => {
431                         cov_mark::hit!(expected_type_if_let_without_leading_char);
432                         let ty = it.condition()
433                             .and_then(|cond| cond.expr())
434                             .and_then(|e| self.sema.type_of_expr(&e));
435                         (ty, None)
436                     },
437                     ast::IdentPat(it) => {
438                         cov_mark::hit!(expected_type_if_let_with_leading_char);
439                         cov_mark::hit!(expected_type_match_arm_with_leading_char);
440                         let ty = self.sema.type_of_pat(&ast::Pat::from(it));
441                         (ty, None)
442                     },
443                     ast::Fn(it) => {
444                         cov_mark::hit!(expected_type_fn_ret_with_leading_char);
445                         cov_mark::hit!(expected_type_fn_ret_without_leading_char);
446                         let def = self.sema.to_def(&it);
447                         (def.map(|def| def.ret_type(self.db)), None)
448                     },
449                     ast::ClosureExpr(it) => {
450                         let ty = self.sema.type_of_expr(&it.into());
451                         ty.and_then(|ty| ty.as_callable(self.db))
452                             .map(|c| (Some(c.return_type()), None))
453                             .unwrap_or((None, None))
454                     },
455                     ast::Stmt(_it) => (None, None),
456                     _ => {
457                         match node.parent() {
458                             Some(n) => {
459                                 node = n;
460                                 continue;
461                             },
462                             None => (None, None),
463                         }
464                     },
465                 }
466             };
467         }
468     }
469
470     fn fill(
471         &mut self,
472         original_file: &SyntaxNode,
473         file_with_fake_ident: SyntaxNode,
474         offset: TextSize,
475     ) {
476         let (expected_type, expected_name) = self.expected_type_and_name();
477         self.expected_type = expected_type;
478         self.expected_name = expected_name;
479         self.attribute_under_caret = find_node_at_offset(&file_with_fake_ident, offset);
480         let name_like = match find_node_at_offset(&&file_with_fake_ident, offset) {
481             Some(it) => it,
482             None => return,
483         };
484         match name_like {
485             ast::NameLike::Lifetime(lifetime) => {
486                 self.classify_lifetime(original_file, lifetime, offset);
487             }
488             ast::NameLike::NameRef(name_ref) => {
489                 self.classify_name_ref(original_file, name_ref, offset);
490             }
491             ast::NameLike::Name(name) => {
492                 self.classify_name(original_file, name, offset);
493             }
494         }
495     }
496
497     fn classify_lifetime(
498         &mut self,
499         original_file: &SyntaxNode,
500         lifetime: ast::Lifetime,
501         offset: TextSize,
502     ) {
503         self.lifetime_syntax =
504             find_node_at_offset(original_file, lifetime.syntax().text_range().start());
505         if let Some(parent) = lifetime.syntax().parent() {
506             if parent.kind() == ERROR {
507                 return;
508             }
509
510             match_ast! {
511                 match parent {
512                     ast::LifetimeParam(_it) => {
513                         self.lifetime_allowed = true;
514                         self.lifetime_param_syntax =
515                             self.sema.find_node_at_offset_with_macros(original_file, offset);
516                     },
517                     ast::BreakExpr(_it) => self.is_label_ref = true,
518                     ast::ContinueExpr(_it) => self.is_label_ref = true,
519                     ast::Label(_it) => (),
520                     _ => self.lifetime_allowed = true,
521                 }
522             }
523         }
524     }
525
526     fn classify_name(&mut self, original_file: &SyntaxNode, name: ast::Name, offset: TextSize) {
527         if let Some(bind_pat) = name.syntax().parent().and_then(ast::IdentPat::cast) {
528             self.is_pat_or_const = Some(PatternRefutability::Refutable);
529             // if any of these is here our bind pat can't be a const pat anymore
530             let complex_ident_pat = bind_pat.at_token().is_some()
531                 || bind_pat.ref_token().is_some()
532                 || bind_pat.mut_token().is_some();
533             if complex_ident_pat {
534                 self.is_pat_or_const = None;
535             } else {
536                 let irrefutable_pat = bind_pat.syntax().ancestors().find_map(|node| {
537                     match_ast! {
538                         match node {
539                             ast::LetStmt(it) => Some(it.pat()),
540                             ast::Param(it) => Some(it.pat()),
541                             _ => None,
542                         }
543                     }
544                 });
545                 if let Some(Some(pat)) = irrefutable_pat {
546                     // This check is here since we could be inside a pattern in the initializer expression of the let statement.
547                     if pat.syntax().text_range().contains_range(bind_pat.syntax().text_range()) {
548                         self.is_pat_or_const = Some(PatternRefutability::Irrefutable);
549                     }
550                 }
551
552                 let is_name_in_field_pat = bind_pat
553                     .syntax()
554                     .parent()
555                     .and_then(ast::RecordPatField::cast)
556                     .map_or(false, |pat_field| pat_field.name_ref().is_none());
557                 if is_name_in_field_pat {
558                     self.is_pat_or_const = None;
559                 }
560             }
561
562             self.fill_impl_def();
563         }
564         self.is_param |= is_node::<ast::Param>(name.syntax());
565         if ast::RecordPatField::for_field_name(&name).is_some() {
566             self.record_pat_syntax =
567                 self.sema.find_node_at_offset_with_macros(&original_file, offset);
568         }
569     }
570
571     fn classify_name_ref(
572         &mut self,
573         original_file: &SyntaxNode,
574         name_ref: ast::NameRef,
575         offset: TextSize,
576     ) {
577         self.fill_impl_def();
578         if ast::RecordExprField::for_field_name(&name_ref).is_some() {
579             self.record_lit_syntax =
580                 self.sema.find_node_at_offset_with_macros(original_file, offset);
581         }
582         if ast::RecordPatField::for_field_name_ref(&name_ref).is_some() {
583             self.record_pat_syntax =
584                 self.sema.find_node_at_offset_with_macros(&original_file, offset);
585         }
586
587         self.name_ref_syntax =
588             find_node_at_offset(original_file, name_ref.syntax().text_range().start());
589
590         let name_range = name_ref.syntax().text_range();
591         let top_node = name_ref
592             .syntax()
593             .ancestors()
594             .take_while(|it| it.text_range() == name_range)
595             .last()
596             .unwrap();
597
598         if matches!(top_node.parent().map(|it| it.kind()), Some(SOURCE_FILE) | Some(ITEM_LIST)) {
599             self.is_new_item = true;
600             return;
601         }
602
603         self.use_item_syntax =
604             self.sema.token_ancestors_with_macros(self.token.clone()).find_map(ast::Use::cast);
605
606         self.function_def = self
607             .sema
608             .token_ancestors_with_macros(self.token.clone())
609             .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
610             .find_map(ast::Fn::cast);
611
612         let parent = match name_ref.syntax().parent() {
613             Some(it) => it,
614             None => return,
615         };
616
617         if let Some(segment) = ast::PathSegment::cast(parent.clone()) {
618             let path = segment.parent_path();
619             self.is_call = path
620                 .syntax()
621                 .parent()
622                 .and_then(ast::PathExpr::cast)
623                 .and_then(|it| it.syntax().parent().and_then(ast::CallExpr::cast))
624                 .is_some();
625             self.is_macro_call = path.syntax().parent().and_then(ast::MacroCall::cast).is_some();
626             self.is_pattern_call =
627                 path.syntax().parent().and_then(ast::TupleStructPat::cast).is_some();
628
629             self.is_path_type = path.syntax().parent().and_then(ast::PathType::cast).is_some();
630             self.has_type_args = segment.generic_arg_list().is_some();
631
632             if let Some(path) = path_or_use_tree_qualifier(&path) {
633                 self.path_qual = path
634                     .segment()
635                     .and_then(|it| {
636                         find_node_with_range::<ast::PathSegment>(
637                             original_file,
638                             it.syntax().text_range(),
639                         )
640                     })
641                     .map(|it| it.parent_path());
642                 return;
643             }
644
645             if let Some(segment) = path.segment() {
646                 if segment.coloncolon_token().is_some() {
647                     return;
648                 }
649             }
650
651             self.is_trivial_path = true;
652
653             // Find either enclosing expr statement (thing with `;`) or a
654             // block. If block, check that we are the last expr.
655             self.can_be_stmt = name_ref
656                 .syntax()
657                 .ancestors()
658                 .find_map(|node| {
659                     if let Some(stmt) = ast::ExprStmt::cast(node.clone()) {
660                         return Some(stmt.syntax().text_range() == name_ref.syntax().text_range());
661                     }
662                     if let Some(block) = ast::BlockExpr::cast(node) {
663                         return Some(
664                             block.tail_expr().map(|e| e.syntax().text_range())
665                                 == Some(name_ref.syntax().text_range()),
666                         );
667                     }
668                     None
669                 })
670                 .unwrap_or(false);
671             self.is_expr = path.syntax().parent().and_then(ast::PathExpr::cast).is_some();
672
673             if let Some(off) = name_ref.syntax().text_range().start().checked_sub(2.into()) {
674                 if let Some(if_expr) =
675                     self.sema.find_node_at_offset_with_macros::<ast::IfExpr>(original_file, off)
676                 {
677                     if if_expr.syntax().text_range().end() < name_ref.syntax().text_range().start()
678                     {
679                         self.after_if = true;
680                     }
681                 }
682             }
683         }
684
685         if let Some(field_expr) = ast::FieldExpr::cast(parent.clone()) {
686             // The receiver comes before the point of insertion of the fake
687             // ident, so it should have the same range in the non-modified file
688             self.dot_receiver = field_expr
689                 .expr()
690                 .map(|e| e.syntax().text_range())
691                 .and_then(|r| find_node_with_range(original_file, r));
692             self.dot_receiver_is_ambiguous_float_literal =
693                 if let Some(ast::Expr::Literal(l)) = &self.dot_receiver {
694                     match l.kind() {
695                         ast::LiteralKind::FloatNumber { .. } => l.token().text().ends_with('.'),
696                         _ => false,
697                     }
698                 } else {
699                     false
700                 };
701         }
702
703         if let Some(method_call_expr) = ast::MethodCallExpr::cast(parent) {
704             // As above
705             self.dot_receiver = method_call_expr
706                 .receiver()
707                 .map(|e| e.syntax().text_range())
708                 .and_then(|r| find_node_with_range(original_file, r));
709             self.is_call = true;
710         }
711     }
712 }
713
714 fn find_node_with_range<N: AstNode>(syntax: &SyntaxNode, range: TextRange) -> Option<N> {
715     syntax.covering_element(range).ancestors().find_map(N::cast)
716 }
717
718 fn is_node<N: AstNode>(node: &SyntaxNode) -> bool {
719     match node.ancestors().find_map(N::cast) {
720         None => false,
721         Some(n) => n.syntax().text_range() == node.text_range(),
722     }
723 }
724
725 fn path_or_use_tree_qualifier(path: &ast::Path) -> Option<ast::Path> {
726     if let Some(qual) = path.qualifier() {
727         return Some(qual);
728     }
729     let use_tree_list = path.syntax().ancestors().find_map(ast::UseTreeList::cast)?;
730     let use_tree = use_tree_list.syntax().parent().and_then(ast::UseTree::cast)?;
731     use_tree.path()
732 }
733
734 #[cfg(test)]
735 mod tests {
736     use expect_test::{expect, Expect};
737     use hir::HirDisplay;
738
739     use crate::test_utils::{position, TEST_CONFIG};
740
741     use super::CompletionContext;
742
743     fn check_expected_type_and_name(ra_fixture: &str, expect: Expect) {
744         let (db, pos) = position(ra_fixture);
745         let completion_context = CompletionContext::new(&db, pos, &TEST_CONFIG).unwrap();
746
747         let ty = completion_context
748             .expected_type
749             .map(|t| t.display_test(&db).to_string())
750             .unwrap_or("?".to_owned());
751
752         let name = completion_context
753             .expected_name
754             .map_or_else(|| "?".to_owned(), |name| name.to_string());
755
756         expect.assert_eq(&format!("ty: {}, name: {}", ty, name));
757     }
758
759     #[test]
760     fn expected_type_let_without_leading_char() {
761         cov_mark::check!(expected_type_let_without_leading_char);
762         check_expected_type_and_name(
763             r#"
764 fn foo() {
765     let x: u32 = $0;
766 }
767 "#,
768             expect![[r#"ty: u32, name: x"#]],
769         );
770     }
771
772     #[test]
773     fn expected_type_let_with_leading_char() {
774         cov_mark::check!(expected_type_let_with_leading_char);
775         check_expected_type_and_name(
776             r#"
777 fn foo() {
778     let x: u32 = c$0;
779 }
780 "#,
781             expect![[r#"ty: u32, name: x"#]],
782         );
783     }
784
785     #[test]
786     fn expected_type_let_pat() {
787         check_expected_type_and_name(
788             r#"
789 fn foo() {
790     let x$0 = 0u32;
791 }
792 "#,
793             expect![[r#"ty: u32, name: ?"#]],
794         );
795         check_expected_type_and_name(
796             r#"
797 fn foo() {
798     let $0 = 0u32;
799 }
800 "#,
801             expect![[r#"ty: u32, name: ?"#]],
802         );
803     }
804
805     #[test]
806     fn expected_type_fn_param_without_leading_char() {
807         cov_mark::check!(expected_type_fn_param_without_leading_char);
808         check_expected_type_and_name(
809             r#"
810 fn foo() {
811     bar($0);
812 }
813
814 fn bar(x: u32) {}
815 "#,
816             expect![[r#"ty: u32, name: x"#]],
817         );
818     }
819
820     #[test]
821     fn expected_type_fn_param_with_leading_char() {
822         cov_mark::check!(expected_type_fn_param_with_leading_char);
823         check_expected_type_and_name(
824             r#"
825 fn foo() {
826     bar(c$0);
827 }
828
829 fn bar(x: u32) {}
830 "#,
831             expect![[r#"ty: u32, name: x"#]],
832         );
833     }
834
835     #[test]
836     fn expected_type_struct_field_without_leading_char() {
837         cov_mark::check!(expected_type_struct_field_without_leading_char);
838         check_expected_type_and_name(
839             r#"
840 struct Foo { a: u32 }
841 fn foo() {
842     Foo { a: $0 };
843 }
844 "#,
845             expect![[r#"ty: u32, name: a"#]],
846         )
847     }
848
849     #[test]
850     fn expected_type_generic_struct_field() {
851         check_expected_type_and_name(
852             r#"
853 struct Foo<T> { a: T }
854 fn foo() -> Foo<u32> {
855     Foo { a: $0 }
856 }
857 "#,
858             expect![[r#"ty: u32, name: a"#]],
859         )
860     }
861
862     #[test]
863     fn expected_type_struct_field_with_leading_char() {
864         cov_mark::check!(expected_type_struct_field_with_leading_char);
865         check_expected_type_and_name(
866             r#"
867 struct Foo { a: u32 }
868 fn foo() {
869     Foo { a: c$0 };
870 }
871 "#,
872             expect![[r#"ty: u32, name: a"#]],
873         );
874     }
875
876     #[test]
877     fn expected_type_match_arm_without_leading_char() {
878         cov_mark::check!(expected_type_match_arm_without_leading_char);
879         check_expected_type_and_name(
880             r#"
881 enum E { X }
882 fn foo() {
883    match E::X { $0 }
884 }
885 "#,
886             expect![[r#"ty: E, name: ?"#]],
887         );
888     }
889
890     #[test]
891     fn expected_type_match_arm_with_leading_char() {
892         cov_mark::check!(expected_type_match_arm_with_leading_char);
893         check_expected_type_and_name(
894             r#"
895 enum E { X }
896 fn foo() {
897    match E::X { c$0 }
898 }
899 "#,
900             expect![[r#"ty: E, name: ?"#]],
901         );
902     }
903
904     #[test]
905     fn expected_type_if_let_without_leading_char() {
906         cov_mark::check!(expected_type_if_let_without_leading_char);
907         check_expected_type_and_name(
908             r#"
909 enum Foo { Bar, Baz, Quux }
910
911 fn foo() {
912     let f = Foo::Quux;
913     if let $0 = f { }
914 }
915 "#,
916             expect![[r#"ty: Foo, name: ?"#]],
917         )
918     }
919
920     #[test]
921     fn expected_type_if_let_with_leading_char() {
922         cov_mark::check!(expected_type_if_let_with_leading_char);
923         check_expected_type_and_name(
924             r#"
925 enum Foo { Bar, Baz, Quux }
926
927 fn foo() {
928     let f = Foo::Quux;
929     if let c$0 = f { }
930 }
931 "#,
932             expect![[r#"ty: Foo, name: ?"#]],
933         )
934     }
935
936     #[test]
937     fn expected_type_fn_ret_without_leading_char() {
938         cov_mark::check!(expected_type_fn_ret_without_leading_char);
939         check_expected_type_and_name(
940             r#"
941 fn foo() -> u32 {
942     $0
943 }
944 "#,
945             expect![[r#"ty: u32, name: ?"#]],
946         )
947     }
948
949     #[test]
950     fn expected_type_fn_ret_with_leading_char() {
951         cov_mark::check!(expected_type_fn_ret_with_leading_char);
952         check_expected_type_and_name(
953             r#"
954 fn foo() -> u32 {
955     c$0
956 }
957 "#,
958             expect![[r#"ty: u32, name: ?"#]],
959         )
960     }
961
962     #[test]
963     fn expected_type_fn_ret_fn_ref_fully_typed() {
964         check_expected_type_and_name(
965             r#"
966 fn foo() -> u32 {
967     foo$0
968 }
969 "#,
970             expect![[r#"ty: u32, name: ?"#]],
971         )
972     }
973
974     #[test]
975     fn expected_type_closure_param_return() {
976         // FIXME: make this work with `|| $0`
977         check_expected_type_and_name(
978             r#"
979 fn foo() {
980     bar(|| a$0);
981 }
982
983 fn bar(f: impl FnOnce() -> u32) {}
984 #[lang = "fn_once"]
985 trait FnOnce { type Output; }
986 "#,
987             expect![[r#"ty: u32, name: ?"#]],
988         );
989     }
990
991     #[test]
992     fn expected_type_generic_function() {
993         check_expected_type_and_name(
994             r#"
995 fn foo() {
996     bar::<u32>($0);
997 }
998
999 fn bar<T>(t: T) {}
1000 "#,
1001             expect![[r#"ty: u32, name: t"#]],
1002         );
1003     }
1004
1005     #[test]
1006     fn expected_type_generic_method() {
1007         check_expected_type_and_name(
1008             r#"
1009 fn foo() {
1010     S(1u32).bar($0);
1011 }
1012
1013 struct S<T>(T);
1014 impl<T> S<T> {
1015     fn bar(self, t: T) {}
1016 }
1017 "#,
1018             expect![[r#"ty: u32, name: t"#]],
1019         );
1020     }
1021 }