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