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