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