]> git.lizzy.rs Git - rust.git/blob - crates/ide_completion/src/context.rs
Fill out expected type for functional update syntax completion
[rust.git] / crates / ide_completion / src / context.rs
1 //! See `CompletionContext` structure.
2
3 use base_db::SourceDatabaseExt;
4 use hir::{Local, Name, ScopeDef, Semantics, SemanticsScope, Type, TypeInfo};
5 use ide_db::{
6     base_db::{FilePosition, SourceDatabase},
7     call_info::ActiveParameter,
8     RootDatabase,
9 };
10 use syntax::{
11     algo::find_node_at_offset,
12     ast::{self, NameOrNameRef, NameOwner},
13     match_ast, AstNode, NodeOrToken,
14     SyntaxKind::{self, *},
15     SyntaxNode, SyntaxToken, TextRange, TextSize, T,
16 };
17 use text_edit::Indel;
18
19 use crate::{
20     patterns::{
21         determine_location, determine_prev_sibling, for_is_prev2, inside_impl_trait_block,
22         is_in_loop_body, previous_token, ImmediateLocation, ImmediatePrevSibling,
23     },
24     CompletionConfig,
25 };
26
27 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
28 pub(crate) enum PatternRefutability {
29     Refutable,
30     Irrefutable,
31 }
32
33 #[derive(Debug)]
34 pub(super) enum PathKind {
35     Expr,
36     Type,
37 }
38
39 #[derive(Debug)]
40 pub(crate) struct PathCompletionContext {
41     /// If this is a call with () already there
42     call_kind: Option<CallKind>,
43     /// A single-indent path, like `foo`. `::foo` should not be considered a trivial path.
44     pub(super) is_trivial_path: bool,
45     /// If not a trivial path, the prefix (qualifier).
46     pub(super) qualifier: Option<ast::Path>,
47     /// Whether the qualifier comes from a use tree parent or not
48     pub(super) use_tree_parent: bool,
49     pub(super) kind: Option<PathKind>,
50     /// Whether the path segment has type args or not.
51     pub(super) has_type_args: bool,
52     /// `true` if we are a statement or a last expr in the block.
53     pub(super) can_be_stmt: bool,
54     pub(super) in_loop_body: bool,
55 }
56
57 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
58 pub(crate) enum CallKind {
59     Pat,
60     Mac,
61     Expr,
62 }
63 /// `CompletionContext` is created early during completion to figure out, where
64 /// exactly is the cursor, syntax-wise.
65 #[derive(Debug)]
66 pub(crate) struct CompletionContext<'a> {
67     pub(super) sema: Semantics<'a, RootDatabase>,
68     pub(super) scope: SemanticsScope<'a>,
69     pub(super) db: &'a RootDatabase,
70     pub(super) config: &'a CompletionConfig,
71     pub(super) position: FilePosition,
72     /// The token before the cursor, in the original file.
73     pub(super) original_token: SyntaxToken,
74     /// The token before the cursor, in the macro-expanded file.
75     pub(super) token: SyntaxToken,
76     pub(super) krate: Option<hir::Crate>,
77     pub(super) expected_name: Option<NameOrNameRef>,
78     pub(super) expected_type: Option<Type>,
79
80     /// The parent function of the cursor position if it exists.
81     pub(super) function_def: Option<ast::Fn>,
82     /// The parent impl of the cursor position if it exists.
83     pub(super) impl_def: Option<ast::Impl>,
84     pub(super) name_ref_syntax: Option<ast::NameRef>,
85
86     // potentially set if we are completing a lifetime
87     pub(super) lifetime_syntax: Option<ast::Lifetime>,
88     pub(super) lifetime_param_syntax: Option<ast::LifetimeParam>,
89     pub(super) lifetime_allowed: bool,
90     pub(super) is_label_ref: bool,
91
92     // potentially set if we are completing a name
93     pub(super) is_pat_or_const: Option<PatternRefutability>,
94     pub(super) is_param: bool,
95
96     pub(super) completion_location: Option<ImmediateLocation>,
97     pub(super) prev_sibling: Option<ImmediatePrevSibling>,
98     pub(super) attribute_under_caret: Option<ast::Attr>,
99     pub(super) previous_token: Option<SyntaxToken>,
100
101     pub(super) path_context: Option<PathCompletionContext>,
102     pub(super) active_parameter: Option<ActiveParameter>,
103     pub(super) locals: Vec<(String, Local)>,
104
105     pub(super) incomplete_let: bool,
106
107     no_completion_required: bool,
108 }
109
110 impl<'a> CompletionContext<'a> {
111     pub(super) fn new(
112         db: &'a RootDatabase,
113         position: FilePosition,
114         config: &'a CompletionConfig,
115     ) -> Option<CompletionContext<'a>> {
116         let sema = Semantics::new(db);
117
118         let original_file = sema.parse(position.file_id);
119
120         // Insert a fake ident to get a valid parse tree. We will use this file
121         // to determine context, though the original_file will be used for
122         // actual completion.
123         let file_with_fake_ident = {
124             let parse = db.parse(position.file_id);
125             let edit = Indel::insert(position.offset, "intellijRulezz".to_string());
126             parse.reparse(&edit).tree()
127         };
128         let fake_ident_token =
129             file_with_fake_ident.syntax().token_at_offset(position.offset).right_biased().unwrap();
130
131         let krate = sema.to_module_def(position.file_id).map(|m| m.krate());
132         let original_token =
133             original_file.syntax().token_at_offset(position.offset).left_biased()?;
134         let token = sema.descend_into_macros(original_token.clone());
135         let scope = sema.scope_at_offset(&token, position.offset);
136         let mut locals = vec![];
137         scope.process_all_names(&mut |name, scope| {
138             if let ScopeDef::Local(local) = scope {
139                 locals.push((name.to_string(), local));
140             }
141         });
142         let mut ctx = CompletionContext {
143             sema,
144             scope,
145             db,
146             config,
147             position,
148             original_token,
149             token,
150             krate,
151             expected_name: None,
152             expected_type: None,
153             function_def: None,
154             impl_def: None,
155             name_ref_syntax: None,
156             lifetime_syntax: None,
157             lifetime_param_syntax: None,
158             lifetime_allowed: false,
159             is_label_ref: false,
160             is_pat_or_const: None,
161             is_param: false,
162             completion_location: None,
163             prev_sibling: None,
164             attribute_under_caret: None,
165             previous_token: None,
166             path_context: None,
167             active_parameter: ActiveParameter::at(db, position),
168             locals,
169             incomplete_let: false,
170             no_completion_required: false,
171         };
172
173         let mut original_file = original_file.syntax().clone();
174         let mut speculative_file = file_with_fake_ident.syntax().clone();
175         let mut offset = position.offset;
176         let mut fake_ident_token = fake_ident_token;
177
178         // Are we inside a macro call?
179         while let (Some(actual_macro_call), Some(macro_call_with_fake_ident)) = (
180             find_node_at_offset::<ast::MacroCall>(&original_file, offset),
181             find_node_at_offset::<ast::MacroCall>(&speculative_file, offset),
182         ) {
183             if actual_macro_call.path().as_ref().map(|s| s.syntax().text())
184                 != macro_call_with_fake_ident.path().as_ref().map(|s| s.syntax().text())
185             {
186                 break;
187             }
188             let speculative_args = match macro_call_with_fake_ident.token_tree() {
189                 Some(tt) => tt,
190                 None => break,
191             };
192             if let (Some(actual_expansion), Some(speculative_expansion)) = (
193                 ctx.sema.expand(&actual_macro_call),
194                 ctx.sema.speculative_expand(
195                     &actual_macro_call,
196                     &speculative_args,
197                     fake_ident_token,
198                 ),
199             ) {
200                 let new_offset = speculative_expansion.1.text_range().start();
201                 if new_offset > actual_expansion.text_range().end() {
202                     break;
203                 }
204                 original_file = actual_expansion;
205                 speculative_file = speculative_expansion.0;
206                 fake_ident_token = speculative_expansion.1;
207                 offset = new_offset;
208             } else {
209                 break;
210             }
211         }
212         ctx.fill(&original_file, speculative_file, offset);
213         Some(ctx)
214     }
215
216     /// Checks whether completions in that particular case don't make much sense.
217     /// Examples:
218     /// - `fn $0` -- we expect function name, it's unlikely that "hint" will be helpful.
219     ///   Exception for this case is `impl Trait for Foo`, where we would like to hint trait method names.
220     /// - `for _ i$0` -- obviously, it'll be "in" keyword.
221     pub(crate) fn no_completion_required(&self) -> bool {
222         self.no_completion_required
223     }
224
225     /// The range of the identifier that is being completed.
226     pub(crate) fn source_range(&self) -> TextRange {
227         // check kind of macro-expanded token, but use range of original token
228         let kind = self.token.kind();
229         if kind == IDENT || kind == LIFETIME_IDENT || kind == UNDERSCORE || kind.is_keyword() {
230             cov_mark::hit!(completes_if_prefix_is_keyword);
231             self.original_token.text_range()
232         } else if kind == CHAR {
233             // assume we are completing a lifetime but the user has only typed the '
234             cov_mark::hit!(completes_if_lifetime_without_idents);
235             TextRange::at(self.original_token.text_range().start(), TextSize::from(1))
236         } else {
237             TextRange::empty(self.position.offset)
238         }
239     }
240
241     pub(crate) fn previous_token_is(&self, kind: SyntaxKind) -> bool {
242         self.previous_token.as_ref().map_or(false, |tok| tok.kind() == kind)
243     }
244
245     pub(crate) fn expects_assoc_item(&self) -> bool {
246         matches!(self.completion_location, Some(ImmediateLocation::Trait | ImmediateLocation::Impl))
247     }
248
249     pub(crate) fn has_dot_receiver(&self) -> bool {
250         matches!(
251             &self.completion_location,
252             Some(ImmediateLocation::FieldAccess { receiver, .. } | ImmediateLocation::MethodCall { receiver,.. })
253                 if receiver.is_some()
254         )
255     }
256
257     pub(crate) fn dot_receiver(&self) -> Option<&ast::Expr> {
258         match &self.completion_location {
259             Some(
260                 ImmediateLocation::MethodCall { receiver, .. }
261                 | ImmediateLocation::FieldAccess { receiver, .. },
262             ) => receiver.as_ref(),
263             _ => None,
264         }
265     }
266
267     pub(crate) fn expects_non_trait_assoc_item(&self) -> bool {
268         matches!(self.completion_location, Some(ImmediateLocation::Impl))
269     }
270
271     pub(crate) fn expects_item(&self) -> bool {
272         matches!(self.completion_location, Some(ImmediateLocation::ItemList))
273     }
274
275     pub(crate) fn expects_generic_arg(&self) -> bool {
276         matches!(self.completion_location, Some(ImmediateLocation::GenericArgList(_)))
277     }
278
279     pub(crate) fn has_block_expr_parent(&self) -> bool {
280         matches!(self.completion_location, Some(ImmediateLocation::BlockExpr))
281     }
282
283     pub(crate) fn expects_ident_pat_or_ref_expr(&self) -> bool {
284         matches!(
285             self.completion_location,
286             Some(ImmediateLocation::IdentPat | ImmediateLocation::RefExpr)
287         )
288     }
289
290     pub(crate) fn expect_field(&self) -> bool {
291         matches!(
292             self.completion_location,
293             Some(ImmediateLocation::RecordField | ImmediateLocation::TupleField)
294         )
295     }
296
297     pub(crate) fn in_use_tree(&self) -> bool {
298         matches!(
299             self.completion_location,
300             Some(ImmediateLocation::Use | ImmediateLocation::UseTree)
301         )
302     }
303
304     pub(crate) fn has_impl_or_trait_prev_sibling(&self) -> bool {
305         matches!(
306             self.prev_sibling,
307             Some(ImmediatePrevSibling::ImplDefType | ImmediatePrevSibling::TraitDefName)
308         )
309     }
310
311     pub(crate) fn has_impl_prev_sibling(&self) -> bool {
312         matches!(self.prev_sibling, Some(ImmediatePrevSibling::ImplDefType))
313     }
314
315     pub(crate) fn has_visibility_prev_sibling(&self) -> bool {
316         matches!(self.prev_sibling, Some(ImmediatePrevSibling::Visibility))
317     }
318
319     pub(crate) fn after_if(&self) -> bool {
320         matches!(self.prev_sibling, Some(ImmediatePrevSibling::IfExpr))
321     }
322
323     pub(crate) fn is_path_disallowed(&self) -> bool {
324         self.attribute_under_caret.is_some()
325             || self.previous_token_is(T![unsafe])
326             || matches!(
327                 self.prev_sibling,
328                 Some(ImmediatePrevSibling::Attribute | ImmediatePrevSibling::Visibility)
329             )
330             || matches!(
331                 self.completion_location,
332                 Some(
333                     ImmediateLocation::Attribute(_)
334                         | ImmediateLocation::ModDeclaration(_)
335                         | ImmediateLocation::RecordPat(_)
336                         | ImmediateLocation::RecordExpr(_)
337                 )
338             )
339     }
340
341     pub(crate) fn expects_expression(&self) -> bool {
342         matches!(self.path_context, Some(PathCompletionContext { kind: Some(PathKind::Expr), .. }))
343     }
344
345     pub(crate) fn expects_type(&self) -> bool {
346         matches!(self.path_context, Some(PathCompletionContext { kind: Some(PathKind::Type), .. }))
347     }
348
349     pub(crate) fn path_call_kind(&self) -> Option<CallKind> {
350         self.path_context.as_ref().and_then(|it| it.call_kind)
351     }
352
353     pub(crate) fn is_trivial_path(&self) -> bool {
354         matches!(self.path_context, Some(PathCompletionContext { is_trivial_path: true, .. }))
355     }
356
357     pub(crate) fn is_non_trivial_path(&self) -> bool {
358         matches!(self.path_context, Some(PathCompletionContext { is_trivial_path: false, .. }))
359     }
360
361     pub(crate) fn path_qual(&self) -> Option<&ast::Path> {
362         self.path_context.as_ref().and_then(|it| it.qualifier.as_ref())
363     }
364
365     /// Checks if an item is visible and not `doc(hidden)` at the completion site.
366     pub(crate) fn is_visible<I>(&self, item: &I) -> bool
367     where
368         I: hir::HasVisibility + hir::HasAttrs + hir::HasCrate + Copy,
369     {
370         self.is_visible_impl(&item.visibility(self.db), &item.attrs(self.db), item.krate(self.db))
371     }
372
373     pub(crate) fn is_scope_def_hidden(&self, scope_def: &ScopeDef) -> bool {
374         if let (Some(attrs), Some(krate)) = (scope_def.attrs(self.db), scope_def.krate(self.db)) {
375             return self.is_doc_hidden(&attrs, krate);
376         }
377
378         false
379     }
380
381     pub(crate) fn is_item_hidden(&self, item: &hir::ItemInNs) -> bool {
382         let attrs = item.attrs(self.db);
383         let krate = item.krate(self.db);
384         match (attrs, krate) {
385             (Some(attrs), Some(krate)) => self.is_doc_hidden(&attrs, krate),
386             _ => false,
387         }
388     }
389
390     /// A version of [`SemanticsScope::process_all_names`] that filters out `#[doc(hidden)]` items.
391     pub(crate) fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
392         self.scope.process_all_names(&mut |name, def| {
393             if self.is_scope_def_hidden(&def) {
394                 return;
395             }
396
397             f(name, def);
398         })
399     }
400
401     fn is_visible_impl(
402         &self,
403         vis: &hir::Visibility,
404         attrs: &hir::Attrs,
405         defining_crate: hir::Crate,
406     ) -> bool {
407         let module = match self.scope.module() {
408             Some(it) => it,
409             None => return false,
410         };
411         if !vis.is_visible_from(self.db, module.into()) {
412             // If the definition location is editable, also show private items
413             let root_file = defining_crate.root_file(self.db);
414             let source_root_id = self.db.file_source_root(root_file);
415             let is_editable = !self.db.source_root(source_root_id).is_library;
416             return is_editable;
417         }
418
419         !self.is_doc_hidden(attrs, defining_crate)
420     }
421
422     fn is_doc_hidden(&self, attrs: &hir::Attrs, defining_crate: hir::Crate) -> bool {
423         let module = match self.scope.module() {
424             Some(it) => it,
425             None => return true,
426         };
427         if module.krate() != defining_crate && attrs.has_doc_hidden() {
428             // `doc(hidden)` items are only completed within the defining crate.
429             return true;
430         }
431
432         false
433     }
434
435     fn fill_impl_def(&mut self) {
436         self.impl_def = self
437             .sema
438             .token_ancestors_with_macros(self.token.clone())
439             .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
440             .find_map(ast::Impl::cast);
441     }
442
443     fn expected_type_and_name(&self) -> (Option<Type>, Option<NameOrNameRef>) {
444         let mut node = match self.token.parent() {
445             Some(it) => it,
446             None => return (None, None),
447         };
448         loop {
449             break match_ast! {
450                 match node {
451                     ast::LetStmt(it) => {
452                         cov_mark::hit!(expected_type_let_with_leading_char);
453                         cov_mark::hit!(expected_type_let_without_leading_char);
454                         let ty = it.pat()
455                             .and_then(|pat| self.sema.type_of_pat(&pat))
456                             .or_else(|| it.initializer().and_then(|it| self.sema.type_of_expr(&it)))
457                             .map(TypeInfo::original);
458                         let name = if let Some(ast::Pat::IdentPat(ident)) = it.pat() {
459                             ident.name().map(NameOrNameRef::Name)
460                         } else {
461                             None
462                         };
463
464                         (ty, name)
465                     },
466                     ast::ArgList(_it) => {
467                         cov_mark::hit!(expected_type_fn_param);
468                         ActiveParameter::at_token(
469                             &self.sema,
470                             self.token.clone(),
471                         ).map(|ap| {
472                             let name = ap.ident().map(NameOrNameRef::Name);
473                             let ty = if has_ref(&self.token) {
474                                 cov_mark::hit!(expected_type_fn_param_ref);
475                                 ap.ty.remove_ref()
476                             } else {
477                                 Some(ap.ty)
478                             };
479                             (ty, name)
480                         })
481                         .unwrap_or((None, None))
482                     },
483                     ast::RecordExprFieldList(it) => {
484                         // wouldn't try {} be nice...
485                         (|| {
486                             if self.token.kind() == T![..]
487                                 || self.token.prev_token().map(|t| t.kind()) == Some(T![..])
488                             {
489                                 cov_mark::hit!(expected_type_struct_func_update);
490                                 let record_expr = it.syntax().parent().and_then(ast::RecordExpr::cast)?;
491                                 let ty = self.sema.type_of_expr(&record_expr.into())?;
492                                 Some((
493                                     Some(ty.original),
494                                     None
495                                 ))
496                             } else {
497                                 cov_mark::hit!(expected_type_struct_field_without_leading_char);
498                                 let expr_field = self.token.prev_sibling_or_token()?
499                                     .into_node()
500                                     .and_then(ast::RecordExprField::cast)?;
501                                 let (_, _, ty) = self.sema.resolve_record_field(&expr_field)?;
502                                 Some((
503                                     Some(ty),
504                                     expr_field.field_name().map(NameOrNameRef::NameRef),
505                                 ))
506                             }
507                         })().unwrap_or((None, None))
508                     },
509                     ast::RecordExprField(it) => {
510                         cov_mark::hit!(expected_type_struct_field_with_leading_char);
511                         (
512                             it.expr().as_ref().and_then(|e| self.sema.type_of_expr(e)).map(TypeInfo::original),
513                             it.field_name().map(NameOrNameRef::NameRef),
514                         )
515                     },
516                     ast::MatchExpr(it) => {
517                         cov_mark::hit!(expected_type_match_arm_without_leading_char);
518                         let ty = it.expr().and_then(|e| self.sema.type_of_expr(&e)).map(TypeInfo::original);
519                         (ty, None)
520                     },
521                     ast::IfExpr(it) => {
522                         cov_mark::hit!(expected_type_if_let_without_leading_char);
523                         let ty = it.condition()
524                             .and_then(|cond| cond.expr())
525                             .and_then(|e| self.sema.type_of_expr(&e))
526                             .map(TypeInfo::original);
527                         (ty, None)
528                     },
529                     ast::IdentPat(it) => {
530                         cov_mark::hit!(expected_type_if_let_with_leading_char);
531                         cov_mark::hit!(expected_type_match_arm_with_leading_char);
532                         let ty = self.sema.type_of_pat(&ast::Pat::from(it)).map(TypeInfo::original);
533                         (ty, None)
534                     },
535                     ast::Fn(it) => {
536                         cov_mark::hit!(expected_type_fn_ret_with_leading_char);
537                         cov_mark::hit!(expected_type_fn_ret_without_leading_char);
538                         let def = self.sema.to_def(&it);
539                         (def.map(|def| def.ret_type(self.db)), None)
540                     },
541                     ast::ClosureExpr(it) => {
542                         let ty = self.sema.type_of_expr(&it.into());
543                         ty.and_then(|ty| ty.original.as_callable(self.db))
544                             .map(|c| (Some(c.return_type()), None))
545                             .unwrap_or((None, None))
546                     },
547                     ast::Stmt(_it) => (None, None),
548                     ast::Item(__) => (None, None),
549                     _ => {
550                         match node.parent() {
551                             Some(n) => {
552                                 node = n;
553                                 continue;
554                             },
555                             None => (None, None),
556                         }
557                     },
558                 }
559             };
560         }
561     }
562
563     fn fill(
564         &mut self,
565         original_file: &SyntaxNode,
566         file_with_fake_ident: SyntaxNode,
567         offset: TextSize,
568     ) {
569         let fake_ident_token = file_with_fake_ident.token_at_offset(offset).right_biased().unwrap();
570         let syntax_element = NodeOrToken::Token(fake_ident_token);
571         self.previous_token = previous_token(syntax_element.clone());
572         self.attribute_under_caret = syntax_element.ancestors().find_map(ast::Attr::cast);
573         self.no_completion_required = {
574             let inside_impl_trait_block = inside_impl_trait_block(syntax_element.clone());
575             let fn_is_prev = self.previous_token_is(T![fn]);
576             let for_is_prev2 = for_is_prev2(syntax_element.clone());
577             (fn_is_prev && !inside_impl_trait_block) || for_is_prev2
578         };
579
580         self.incomplete_let =
581             syntax_element.ancestors().take(6).find_map(ast::LetStmt::cast).map_or(false, |it| {
582                 it.syntax().text_range().end() == syntax_element.text_range().end()
583             });
584
585         let (expected_type, expected_name) = self.expected_type_and_name();
586         self.expected_type = expected_type;
587         self.expected_name = expected_name;
588
589         let name_like = match find_node_at_offset(&file_with_fake_ident, offset) {
590             Some(it) => it,
591             None => return,
592         };
593         self.completion_location =
594             determine_location(&self.sema, original_file, offset, &name_like);
595         self.prev_sibling = determine_prev_sibling(&name_like);
596         match name_like {
597             ast::NameLike::Lifetime(lifetime) => {
598                 self.classify_lifetime(original_file, lifetime, offset);
599             }
600             ast::NameLike::NameRef(name_ref) => {
601                 self.classify_name_ref(original_file, name_ref);
602             }
603             ast::NameLike::Name(name) => {
604                 self.classify_name(name);
605             }
606         }
607     }
608
609     fn classify_lifetime(
610         &mut self,
611         original_file: &SyntaxNode,
612         lifetime: ast::Lifetime,
613         offset: TextSize,
614     ) {
615         self.lifetime_syntax =
616             find_node_at_offset(original_file, lifetime.syntax().text_range().start());
617         if let Some(parent) = lifetime.syntax().parent() {
618             if parent.kind() == ERROR {
619                 return;
620             }
621
622             match_ast! {
623                 match parent {
624                     ast::LifetimeParam(_it) => {
625                         self.lifetime_allowed = true;
626                         self.lifetime_param_syntax =
627                             self.sema.find_node_at_offset_with_macros(original_file, offset);
628                     },
629                     ast::BreakExpr(_it) => self.is_label_ref = true,
630                     ast::ContinueExpr(_it) => self.is_label_ref = true,
631                     ast::Label(_it) => (),
632                     _ => self.lifetime_allowed = true,
633                 }
634             }
635         }
636     }
637
638     fn classify_name(&mut self, name: ast::Name) {
639         if let Some(bind_pat) = name.syntax().parent().and_then(ast::IdentPat::cast) {
640             self.is_pat_or_const = Some(PatternRefutability::Refutable);
641             if !bind_pat.is_simple_ident() {
642                 self.is_pat_or_const = None;
643             } else {
644                 let irrefutable_pat = bind_pat.syntax().ancestors().find_map(|node| {
645                     match_ast! {
646                         match node {
647                             ast::LetStmt(it) => Some(it.pat()),
648                             ast::Param(it) => Some(it.pat()),
649                             _ => None,
650                         }
651                     }
652                 });
653                 if let Some(Some(pat)) = irrefutable_pat {
654                     // This check is here since we could be inside a pattern in the initializer expression of the let statement.
655                     if pat.syntax().text_range().contains_range(bind_pat.syntax().text_range()) {
656                         self.is_pat_or_const = Some(PatternRefutability::Irrefutable);
657                     }
658                 }
659
660                 let is_name_in_field_pat = bind_pat
661                     .syntax()
662                     .parent()
663                     .and_then(ast::RecordPatField::cast)
664                     .map_or(false, |pat_field| pat_field.name_ref().is_none());
665                 if is_name_in_field_pat {
666                     self.is_pat_or_const = None;
667                 }
668             }
669
670             self.fill_impl_def();
671         }
672
673         self.is_param |= is_node::<ast::Param>(name.syntax());
674     }
675
676     fn classify_name_ref(&mut self, original_file: &SyntaxNode, name_ref: ast::NameRef) {
677         self.fill_impl_def();
678
679         self.name_ref_syntax =
680             find_node_at_offset(original_file, name_ref.syntax().text_range().start());
681
682         self.function_def = self
683             .sema
684             .token_ancestors_with_macros(self.token.clone())
685             .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
686             .find_map(ast::Fn::cast);
687
688         let parent = match name_ref.syntax().parent() {
689             Some(it) => it,
690             None => return,
691         };
692
693         if let Some(segment) = ast::PathSegment::cast(parent) {
694             let path_ctx = self.path_context.get_or_insert(PathCompletionContext {
695                 call_kind: None,
696                 is_trivial_path: false,
697                 qualifier: None,
698                 has_type_args: false,
699                 can_be_stmt: false,
700                 in_loop_body: false,
701                 use_tree_parent: false,
702                 kind: None,
703             });
704             path_ctx.in_loop_body = is_in_loop_body(name_ref.syntax());
705             let path = segment.parent_path();
706
707             if let Some(p) = path.syntax().parent() {
708                 path_ctx.call_kind = match_ast! {
709                     match p {
710                         ast::PathExpr(it) => it.syntax().parent().and_then(ast::CallExpr::cast).map(|_| CallKind::Expr),
711                         ast::MacroCall(it) => it.excl_token().and(Some(CallKind::Mac)),
712                         ast::TupleStructPat(_it) => Some(CallKind::Pat),
713                         _ => None
714                     }
715                 };
716             }
717
718             if let Some(parent) = path.syntax().parent() {
719                 path_ctx.kind = match_ast! {
720                     match parent {
721                         ast::PathType(_it) => Some(PathKind::Type),
722                         ast::PathExpr(_it) => Some(PathKind::Expr),
723                         _ => None,
724                     }
725                 };
726             }
727             path_ctx.has_type_args = segment.generic_arg_list().is_some();
728
729             if let Some((path, use_tree_parent)) = path_or_use_tree_qualifier(&path) {
730                 path_ctx.use_tree_parent = use_tree_parent;
731                 path_ctx.qualifier = path
732                     .segment()
733                     .and_then(|it| {
734                         find_node_with_range::<ast::PathSegment>(
735                             original_file,
736                             it.syntax().text_range(),
737                         )
738                     })
739                     .map(|it| it.parent_path());
740                 return;
741             }
742
743             if let Some(segment) = path.segment() {
744                 if segment.coloncolon_token().is_some() {
745                     return;
746                 }
747             }
748
749             path_ctx.is_trivial_path = true;
750
751             // Find either enclosing expr statement (thing with `;`) or a
752             // block. If block, check that we are the last expr.
753             path_ctx.can_be_stmt = name_ref
754                 .syntax()
755                 .ancestors()
756                 .find_map(|node| {
757                     if let Some(stmt) = ast::ExprStmt::cast(node.clone()) {
758                         return Some(stmt.syntax().text_range() == name_ref.syntax().text_range());
759                     }
760                     if let Some(block) = ast::BlockExpr::cast(node) {
761                         return Some(
762                             block.tail_expr().map(|e| e.syntax().text_range())
763                                 == Some(name_ref.syntax().text_range()),
764                         );
765                     }
766                     None
767                 })
768                 .unwrap_or(false);
769         }
770     }
771 }
772
773 fn find_node_with_range<N: AstNode>(syntax: &SyntaxNode, range: TextRange) -> Option<N> {
774     syntax.covering_element(range).ancestors().find_map(N::cast)
775 }
776
777 fn is_node<N: AstNode>(node: &SyntaxNode) -> bool {
778     match node.ancestors().find_map(N::cast) {
779         None => false,
780         Some(n) => n.syntax().text_range() == node.text_range(),
781     }
782 }
783
784 fn path_or_use_tree_qualifier(path: &ast::Path) -> Option<(ast::Path, bool)> {
785     if let Some(qual) = path.qualifier() {
786         return Some((qual, false));
787     }
788     let use_tree_list = path.syntax().ancestors().find_map(ast::UseTreeList::cast)?;
789     let use_tree = use_tree_list.syntax().parent().and_then(ast::UseTree::cast)?;
790     use_tree.path().zip(Some(true))
791 }
792
793 fn has_ref(token: &SyntaxToken) -> bool {
794     let mut token = token.clone();
795     for skip in [WHITESPACE, IDENT, T![mut]] {
796         if token.kind() == skip {
797             token = match token.prev_token() {
798                 Some(it) => it,
799                 None => return false,
800             }
801         }
802     }
803     token.kind() == T![&]
804 }
805
806 #[cfg(test)]
807 mod tests {
808     use expect_test::{expect, Expect};
809     use hir::HirDisplay;
810
811     use crate::tests::{position, TEST_CONFIG};
812
813     use super::CompletionContext;
814
815     fn check_expected_type_and_name(ra_fixture: &str, expect: Expect) {
816         let (db, pos) = position(ra_fixture);
817         let completion_context = CompletionContext::new(&db, pos, &TEST_CONFIG).unwrap();
818
819         let ty = completion_context
820             .expected_type
821             .map(|t| t.display_test(&db).to_string())
822             .unwrap_or("?".to_owned());
823
824         let name = completion_context
825             .expected_name
826             .map_or_else(|| "?".to_owned(), |name| name.to_string());
827
828         expect.assert_eq(&format!("ty: {}, name: {}", ty, name));
829     }
830
831     #[test]
832     fn expected_type_let_without_leading_char() {
833         cov_mark::check!(expected_type_let_without_leading_char);
834         check_expected_type_and_name(
835             r#"
836 fn foo() {
837     let x: u32 = $0;
838 }
839 "#,
840             expect![[r#"ty: u32, name: x"#]],
841         );
842     }
843
844     #[test]
845     fn expected_type_let_with_leading_char() {
846         cov_mark::check!(expected_type_let_with_leading_char);
847         check_expected_type_and_name(
848             r#"
849 fn foo() {
850     let x: u32 = c$0;
851 }
852 "#,
853             expect![[r#"ty: u32, name: x"#]],
854         );
855     }
856
857     #[test]
858     fn expected_type_let_pat() {
859         check_expected_type_and_name(
860             r#"
861 fn foo() {
862     let x$0 = 0u32;
863 }
864 "#,
865             expect![[r#"ty: u32, name: ?"#]],
866         );
867         check_expected_type_and_name(
868             r#"
869 fn foo() {
870     let $0 = 0u32;
871 }
872 "#,
873             expect![[r#"ty: u32, name: ?"#]],
874         );
875     }
876
877     #[test]
878     fn expected_type_fn_param() {
879         cov_mark::check!(expected_type_fn_param);
880         check_expected_type_and_name(
881             r#"
882 fn foo() { bar($0); }
883 fn bar(x: u32) {}
884 "#,
885             expect![[r#"ty: u32, name: x"#]],
886         );
887         check_expected_type_and_name(
888             r#"
889 fn foo() { bar(c$0); }
890 fn bar(x: u32) {}
891 "#,
892             expect![[r#"ty: u32, name: x"#]],
893         );
894     }
895
896     #[test]
897     fn expected_type_fn_param_ref() {
898         cov_mark::check!(expected_type_fn_param_ref);
899         check_expected_type_and_name(
900             r#"
901 fn foo() { bar(&$0); }
902 fn bar(x: &u32) {}
903 "#,
904             expect![[r#"ty: u32, name: x"#]],
905         );
906         check_expected_type_and_name(
907             r#"
908 fn foo() { bar(&mut $0); }
909 fn bar(x: &mut u32) {}
910 "#,
911             expect![[r#"ty: u32, name: x"#]],
912         );
913         check_expected_type_and_name(
914             r#"
915 fn foo() { bar(&c$0); }
916 fn bar(x: &u32) {}
917         "#,
918             expect![[r#"ty: u32, name: x"#]],
919         );
920     }
921
922     #[test]
923     fn expected_type_struct_field_without_leading_char() {
924         cov_mark::check!(expected_type_struct_field_without_leading_char);
925         check_expected_type_and_name(
926             r#"
927 struct Foo { a: u32 }
928 fn foo() {
929     Foo { a: $0 };
930 }
931 "#,
932             expect![[r#"ty: u32, name: a"#]],
933         )
934     }
935
936     #[test]
937     fn expected_type_generic_struct_field() {
938         check_expected_type_and_name(
939             r#"
940 struct Foo<T> { a: T }
941 fn foo() -> Foo<u32> {
942     Foo { a: $0 }
943 }
944 "#,
945             expect![[r#"ty: u32, name: a"#]],
946         )
947     }
948
949     #[test]
950     fn expected_type_struct_field_with_leading_char() {
951         cov_mark::check!(expected_type_struct_field_with_leading_char);
952         check_expected_type_and_name(
953             r#"
954 struct Foo { a: u32 }
955 fn foo() {
956     Foo { a: c$0 };
957 }
958 "#,
959             expect![[r#"ty: u32, name: a"#]],
960         );
961     }
962
963     #[test]
964     fn expected_type_match_arm_without_leading_char() {
965         cov_mark::check!(expected_type_match_arm_without_leading_char);
966         check_expected_type_and_name(
967             r#"
968 enum E { X }
969 fn foo() {
970    match E::X { $0 }
971 }
972 "#,
973             expect![[r#"ty: E, name: ?"#]],
974         );
975     }
976
977     #[test]
978     fn expected_type_match_arm_with_leading_char() {
979         cov_mark::check!(expected_type_match_arm_with_leading_char);
980         check_expected_type_and_name(
981             r#"
982 enum E { X }
983 fn foo() {
984    match E::X { c$0 }
985 }
986 "#,
987             expect![[r#"ty: E, name: ?"#]],
988         );
989     }
990
991     #[test]
992     fn expected_type_if_let_without_leading_char() {
993         cov_mark::check!(expected_type_if_let_without_leading_char);
994         check_expected_type_and_name(
995             r#"
996 enum Foo { Bar, Baz, Quux }
997
998 fn foo() {
999     let f = Foo::Quux;
1000     if let $0 = f { }
1001 }
1002 "#,
1003             expect![[r#"ty: Foo, name: ?"#]],
1004         )
1005     }
1006
1007     #[test]
1008     fn expected_type_if_let_with_leading_char() {
1009         cov_mark::check!(expected_type_if_let_with_leading_char);
1010         check_expected_type_and_name(
1011             r#"
1012 enum Foo { Bar, Baz, Quux }
1013
1014 fn foo() {
1015     let f = Foo::Quux;
1016     if let c$0 = f { }
1017 }
1018 "#,
1019             expect![[r#"ty: Foo, name: ?"#]],
1020         )
1021     }
1022
1023     #[test]
1024     fn expected_type_fn_ret_without_leading_char() {
1025         cov_mark::check!(expected_type_fn_ret_without_leading_char);
1026         check_expected_type_and_name(
1027             r#"
1028 fn foo() -> u32 {
1029     $0
1030 }
1031 "#,
1032             expect![[r#"ty: u32, name: ?"#]],
1033         )
1034     }
1035
1036     #[test]
1037     fn expected_type_fn_ret_with_leading_char() {
1038         cov_mark::check!(expected_type_fn_ret_with_leading_char);
1039         check_expected_type_and_name(
1040             r#"
1041 fn foo() -> u32 {
1042     c$0
1043 }
1044 "#,
1045             expect![[r#"ty: u32, name: ?"#]],
1046         )
1047     }
1048
1049     #[test]
1050     fn expected_type_fn_ret_fn_ref_fully_typed() {
1051         check_expected_type_and_name(
1052             r#"
1053 fn foo() -> u32 {
1054     foo$0
1055 }
1056 "#,
1057             expect![[r#"ty: u32, name: ?"#]],
1058         )
1059     }
1060
1061     #[test]
1062     fn expected_type_closure_param_return() {
1063         // FIXME: make this work with `|| $0`
1064         check_expected_type_and_name(
1065             r#"
1066 //- minicore: fn
1067 fn foo() {
1068     bar(|| a$0);
1069 }
1070
1071 fn bar(f: impl FnOnce() -> u32) {}
1072 "#,
1073             expect![[r#"ty: u32, name: ?"#]],
1074         );
1075     }
1076
1077     #[test]
1078     fn expected_type_generic_function() {
1079         check_expected_type_and_name(
1080             r#"
1081 fn foo() {
1082     bar::<u32>($0);
1083 }
1084
1085 fn bar<T>(t: T) {}
1086 "#,
1087             expect![[r#"ty: u32, name: t"#]],
1088         );
1089     }
1090
1091     #[test]
1092     fn expected_type_generic_method() {
1093         check_expected_type_and_name(
1094             r#"
1095 fn foo() {
1096     S(1u32).bar($0);
1097 }
1098
1099 struct S<T>(T);
1100 impl<T> S<T> {
1101     fn bar(self, t: T) {}
1102 }
1103 "#,
1104             expect![[r#"ty: u32, name: t"#]],
1105         );
1106     }
1107
1108     #[test]
1109     fn expected_type_functional_update() {
1110         cov_mark::check!(expected_type_struct_func_update);
1111         check_expected_type_and_name(
1112             r#"
1113 struct Foo { field: u32 }
1114 fn foo() {
1115     Foo {
1116         ..$0
1117     }
1118 }
1119 "#,
1120             expect![[r#"ty: Foo, name: ?"#]],
1121         );
1122     }
1123 }