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