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