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