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