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