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