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