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