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