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