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