]> git.lizzy.rs Git - rust.git/blob - crates/ide-completion/src/context.rs
Auto merge of #12359 - lnicola:universal-vsix-part-2, r=lnicola
[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::{
7     HasAttrs, Local, Name, PathResolution, ScopeDef, Semantics, SemanticsScope, Type, TypeInfo,
8 };
9 use ide_db::{
10     active_parameter::ActiveParameter,
11     base_db::{FilePosition, SourceDatabase},
12     famous_defs::FamousDefs,
13     FxHashMap, FxHashSet, RootDatabase,
14 };
15 use syntax::{
16     algo::{find_node_at_offset, non_trivia_sibling},
17     ast::{self, AttrKind, HasArgList, HasName, NameOrNameRef},
18     match_ast, AstNode, AstToken, NodeOrToken,
19     SyntaxKind::{self, *},
20     SyntaxNode, SyntaxToken, TextRange, TextSize, T,
21 };
22 use text_edit::Indel;
23
24 use crate::{
25     patterns::{
26         determine_location, determine_prev_sibling, is_in_loop_body, is_in_token_of_for_loop,
27         previous_token, ImmediateLocation, ImmediatePrevSibling,
28     },
29     CompletionConfig,
30 };
31
32 const COMPLETION_MARKER: &str = "intellijRulezz";
33
34 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
35 pub(crate) enum PatternRefutability {
36     Refutable,
37     Irrefutable,
38 }
39
40 pub(crate) enum Visible {
41     Yes,
42     Editable,
43     No,
44 }
45
46 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
47 pub(super) enum PathKind {
48     Expr {
49         in_block_expr: bool,
50         in_loop_body: bool,
51         in_functional_update: bool,
52     },
53     Type,
54     Attr {
55         kind: AttrKind,
56         annotated_item_kind: Option<SyntaxKind>,
57     },
58     Derive,
59     /// Path in item position, that is inside an (Assoc)ItemList
60     Item {
61         kind: ItemListKind,
62     },
63     Pat,
64     Vis {
65         has_in_token: bool,
66     },
67     Use,
68 }
69
70 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
71 pub(super) enum ItemListKind {
72     SourceFile,
73     Module,
74     Impl,
75     Trait,
76     ExternBlock,
77 }
78
79 #[derive(Debug)]
80 pub(crate) struct PathCompletionCtx {
81     /// If this is a call with () already there (or {} in case of record patterns)
82     pub(super) has_call_parens: bool,
83     /// If this has a macro call bang !
84     pub(super) has_macro_bang: bool,
85     /// Whether this path stars with a `::`.
86     pub(super) is_absolute_path: bool,
87     /// The qualifier of the current path if it exists.
88     pub(super) qualifier: Option<PathQualifierCtx>,
89     #[allow(dead_code)]
90     // FIXME: use this
91     /// The parent of the path we are completing.
92     pub(super) parent: Option<ast::Path>,
93     pub(super) kind: PathKind,
94     /// Whether the path segment has type args or not.
95     pub(super) has_type_args: bool,
96 }
97
98 #[derive(Debug)]
99 pub(crate) struct PathQualifierCtx {
100     pub(crate) path: ast::Path,
101     pub(crate) resolution: Option<PathResolution>,
102     /// Whether this path consists solely of `super` segments
103     pub(crate) is_super_chain: bool,
104     /// Whether the qualifier comes from a use tree parent or not
105     pub(crate) use_tree_parent: bool,
106     /// <_>
107     pub(crate) is_infer_qualifier: bool,
108 }
109
110 #[derive(Debug)]
111 pub(super) struct PatternContext {
112     pub(super) refutability: PatternRefutability,
113     pub(super) param_ctx: Option<(ast::ParamList, ast::Param, ParamKind)>,
114     pub(super) has_type_ascription: bool,
115     pub(super) parent_pat: Option<ast::Pat>,
116     pub(super) ref_token: Option<SyntaxToken>,
117     pub(super) mut_token: Option<SyntaxToken>,
118 }
119
120 #[derive(Debug)]
121 pub(super) struct LifetimeContext {
122     pub(super) lifetime: Option<ast::Lifetime>,
123     pub(super) kind: LifetimeKind,
124 }
125
126 #[derive(Debug)]
127 pub(super) enum LifetimeKind {
128     LifetimeParam { is_decl: bool, param: ast::LifetimeParam },
129     Lifetime,
130     LabelRef,
131     LabelDef,
132 }
133
134 #[derive(Debug)]
135 pub(super) struct NameContext {
136     #[allow(dead_code)]
137     pub(super) name: Option<ast::Name>,
138     pub(super) kind: NameKind,
139 }
140
141 #[derive(Debug)]
142 #[allow(dead_code)]
143 pub(super) enum NameKind {
144     Const,
145     ConstParam,
146     Enum,
147     Function,
148     IdentPat,
149     MacroDef,
150     MacroRules,
151     /// Fake node
152     Module(ast::Module),
153     RecordField,
154     Rename,
155     SelfParam,
156     Static,
157     Struct,
158     Trait,
159     TypeAlias,
160     TypeParam,
161     Union,
162     Variant,
163 }
164
165 #[derive(Debug)]
166 pub(super) struct NameRefContext {
167     /// NameRef syntax in the original file
168     pub(super) nameref: Option<ast::NameRef>,
169     pub(super) dot_access: Option<DotAccess>,
170     pub(super) path_ctx: Option<PathCompletionCtx>,
171 }
172
173 #[derive(Debug)]
174 pub(super) enum IdentContext {
175     Name(NameContext),
176     NameRef(NameRefContext),
177     Lifetime(LifetimeContext),
178     /// Original token, fake token
179     String {
180         original: ast::String,
181         expanded: Option<ast::String>,
182     },
183     UnexpandedAttrTT {
184         fake_attribute_under_caret: Option<ast::Attr>,
185     },
186 }
187
188 #[derive(Debug)]
189 pub(super) enum DotAccess {
190     Field {
191         receiver: Option<ast::Expr>,
192         /// True if the receiver is an integer and there is no ident in the original file after it yet
193         /// like `0.$0`
194         receiver_is_ambiguous_float_literal: bool,
195     },
196     Method {
197         receiver: Option<ast::Expr>,
198         has_parens: bool,
199     },
200 }
201
202 #[derive(Clone, Debug, PartialEq, Eq)]
203 pub(crate) enum ParamKind {
204     Function(ast::Fn),
205     Closure(ast::ClosureExpr),
206 }
207
208 /// `CompletionContext` is created early during completion to figure out, where
209 /// exactly is the cursor, syntax-wise.
210 #[derive(Debug)]
211 pub(crate) struct CompletionContext<'a> {
212     pub(super) sema: Semantics<'a, RootDatabase>,
213     pub(super) scope: SemanticsScope<'a>,
214     pub(super) db: &'a RootDatabase,
215     pub(super) config: &'a CompletionConfig,
216     pub(super) position: FilePosition,
217
218     /// The token before the cursor, in the original file.
219     pub(super) original_token: SyntaxToken,
220     /// The token before the cursor, in the macro-expanded file.
221     pub(super) token: SyntaxToken,
222     /// The crate of the current file.
223     pub(super) krate: hir::Crate,
224     /// The module of the `scope`.
225     pub(super) module: hir::Module,
226
227     /// The expected name of what we are completing.
228     /// This is usually the parameter name of the function argument we are completing.
229     pub(super) expected_name: Option<NameOrNameRef>,
230     /// The expected type of what we are completing.
231     pub(super) expected_type: Option<Type>,
232
233     /// The parent function of the cursor position if it exists.
234     pub(super) function_def: Option<ast::Fn>,
235     /// The parent impl of the cursor position if it exists.
236     pub(super) impl_def: Option<ast::Impl>,
237     /// Are we completing inside a let statement with a missing semicolon?
238     pub(super) incomplete_let: bool,
239
240     pub(super) completion_location: Option<ImmediateLocation>,
241     pub(super) prev_sibling: Option<ImmediatePrevSibling>,
242     pub(super) previous_token: Option<SyntaxToken>,
243
244     pub(super) ident_ctx: IdentContext,
245
246     pub(super) pattern_ctx: Option<PatternContext>,
247
248     pub(super) existing_derives: FxHashSet<hir::Macro>,
249
250     pub(super) locals: FxHashMap<Name, Local>,
251 }
252
253 impl<'a> CompletionContext<'a> {
254     /// The range of the identifier that is being completed.
255     pub(crate) fn source_range(&self) -> TextRange {
256         // check kind of macro-expanded token, but use range of original token
257         let kind = self.token.kind();
258         match kind {
259             CHAR => {
260                 // assume we are completing a lifetime but the user has only typed the '
261                 cov_mark::hit!(completes_if_lifetime_without_idents);
262                 TextRange::at(self.original_token.text_range().start(), TextSize::from(1))
263             }
264             IDENT | LIFETIME_IDENT | UNDERSCORE => self.original_token.text_range(),
265             _ if kind.is_keyword() => self.original_token.text_range(),
266             _ => TextRange::empty(self.position.offset),
267         }
268     }
269
270     pub(crate) fn previous_token_is(&self, kind: SyntaxKind) -> bool {
271         self.previous_token.as_ref().map_or(false, |tok| tok.kind() == kind)
272     }
273
274     pub(crate) fn famous_defs(&self) -> FamousDefs {
275         FamousDefs(&self.sema, self.krate)
276     }
277
278     pub(super) fn nameref_ctx(&self) -> Option<&NameRefContext> {
279         match &self.ident_ctx {
280             IdentContext::NameRef(it) => Some(it),
281             _ => None,
282         }
283     }
284
285     pub(super) fn name_ctx(&self) -> Option<&NameContext> {
286         match &self.ident_ctx {
287             IdentContext::Name(it) => Some(it),
288             _ => None,
289         }
290     }
291
292     pub(super) fn lifetime_ctx(&self) -> Option<&LifetimeContext> {
293         match &self.ident_ctx {
294             IdentContext::Lifetime(it) => Some(it),
295             _ => None,
296         }
297     }
298
299     pub(crate) fn dot_receiver(&self) -> Option<&ast::Expr> {
300         match self.nameref_ctx() {
301             Some(NameRefContext {
302                 dot_access:
303                     Some(DotAccess::Method { receiver, .. } | DotAccess::Field { receiver, .. }),
304                 ..
305             }) => receiver.as_ref(),
306             _ => None,
307         }
308     }
309
310     pub(crate) fn has_dot_receiver(&self) -> bool {
311         self.dot_receiver().is_some()
312     }
313
314     pub(crate) fn expects_assoc_item(&self) -> bool {
315         matches!(self.completion_location, Some(ImmediateLocation::Trait | ImmediateLocation::Impl))
316     }
317
318     pub(crate) fn expects_variant(&self) -> bool {
319         matches!(self.name_ctx(), Some(NameContext { kind: NameKind::Variant, .. }))
320     }
321
322     pub(crate) fn expects_non_trait_assoc_item(&self) -> bool {
323         matches!(self.completion_location, Some(ImmediateLocation::Impl))
324     }
325
326     pub(crate) fn expects_item(&self) -> bool {
327         matches!(self.completion_location, Some(ImmediateLocation::ItemList))
328     }
329
330     // FIXME: This shouldn't exist
331     pub(crate) fn expects_generic_arg(&self) -> bool {
332         matches!(self.completion_location, Some(ImmediateLocation::GenericArgList(_)))
333     }
334
335     pub(crate) fn has_block_expr_parent(&self) -> bool {
336         matches!(self.completion_location, Some(ImmediateLocation::StmtList))
337     }
338
339     pub(crate) fn expects_ident_ref_expr(&self) -> bool {
340         matches!(self.completion_location, Some(ImmediateLocation::RefExpr))
341     }
342
343     pub(crate) fn expect_field(&self) -> bool {
344         matches!(self.completion_location, Some(ImmediateLocation::TupleField))
345             || matches!(self.name_ctx(), Some(NameContext { kind: NameKind::RecordField, .. }))
346     }
347
348     /// Whether the cursor is right after a trait or impl header.
349     /// trait Foo ident$0
350     // FIXME: This probably shouldn't exist
351     pub(crate) fn has_unfinished_impl_or_trait_prev_sibling(&self) -> bool {
352         matches!(
353             self.prev_sibling,
354             Some(ImmediatePrevSibling::ImplDefType | ImmediatePrevSibling::TraitDefName)
355         )
356     }
357
358     // FIXME: This probably shouldn't exist
359     pub(crate) fn has_impl_prev_sibling(&self) -> bool {
360         matches!(self.prev_sibling, Some(ImmediatePrevSibling::ImplDefType))
361     }
362
363     pub(crate) fn has_visibility_prev_sibling(&self) -> bool {
364         matches!(self.prev_sibling, Some(ImmediatePrevSibling::Visibility))
365     }
366
367     pub(crate) fn after_if(&self) -> bool {
368         matches!(self.prev_sibling, Some(ImmediatePrevSibling::IfExpr))
369     }
370
371     // FIXME: This shouldn't exist
372     pub(crate) fn is_path_disallowed(&self) -> bool {
373         self.previous_token_is(T![unsafe])
374             || matches!(self.prev_sibling, Some(ImmediatePrevSibling::Visibility))
375             || matches!(
376                 self.completion_location,
377                 Some(ImmediateLocation::RecordPat(_) | ImmediateLocation::RecordExpr(_))
378             )
379             || matches!(
380                 self.name_ctx(),
381                 Some(NameContext { kind: NameKind::Module(_) | NameKind::Rename, .. })
382             )
383     }
384
385     pub(crate) fn path_context(&self) -> Option<&PathCompletionCtx> {
386         self.nameref_ctx().and_then(|ctx| ctx.path_ctx.as_ref())
387     }
388
389     pub(crate) fn expects_expression(&self) -> bool {
390         matches!(self.path_context(), Some(PathCompletionCtx { kind: PathKind::Expr { .. }, .. }))
391     }
392
393     pub(crate) fn is_non_trivial_path(&self) -> bool {
394         matches!(
395             self.path_context(),
396             Some(
397                 PathCompletionCtx { is_absolute_path: true, .. }
398                     | PathCompletionCtx { qualifier: Some(_), .. }
399             )
400         )
401     }
402
403     pub(crate) fn path_qual(&self) -> Option<&ast::Path> {
404         self.path_context().and_then(|it| it.qualifier.as_ref().map(|it| &it.path))
405     }
406
407     pub(crate) fn path_kind(&self) -> Option<PathKind> {
408         self.path_context().map(|it| it.kind)
409     }
410
411     /// Checks if an item is visible and not `doc(hidden)` at the completion site.
412     pub(crate) fn is_visible<I>(&self, item: &I) -> Visible
413     where
414         I: hir::HasVisibility + hir::HasAttrs + hir::HasCrate + Copy,
415     {
416         self.is_visible_impl(&item.visibility(self.db), &item.attrs(self.db), item.krate(self.db))
417     }
418
419     pub(crate) fn is_scope_def_hidden(&self, scope_def: ScopeDef) -> bool {
420         if let (Some(attrs), Some(krate)) = (scope_def.attrs(self.db), scope_def.krate(self.db)) {
421             return self.is_doc_hidden(&attrs, krate);
422         }
423
424         false
425     }
426
427     /// Check if an item is `#[doc(hidden)]`.
428     pub(crate) fn is_item_hidden(&self, item: &hir::ItemInNs) -> bool {
429         let attrs = item.attrs(self.db);
430         let krate = item.krate(self.db);
431         match (attrs, krate) {
432             (Some(attrs), Some(krate)) => self.is_doc_hidden(&attrs, krate),
433             _ => false,
434         }
435     }
436     /// Whether the given trait is an operator trait or not.
437     pub(crate) fn is_ops_trait(&self, trait_: hir::Trait) -> bool {
438         match trait_.attrs(self.db).lang() {
439             Some(lang) => OP_TRAIT_LANG_NAMES.contains(&lang.as_str()),
440             None => false,
441         }
442     }
443
444     /// Returns the traits in scope, with the [`Drop`] trait removed.
445     pub(crate) fn traits_in_scope(&self) -> hir::VisibleTraits {
446         let mut traits_in_scope = self.scope.visible_traits();
447         if let Some(drop) = self.famous_defs().core_ops_Drop() {
448             traits_in_scope.0.remove(&drop.into());
449         }
450         traits_in_scope
451     }
452
453     /// A version of [`SemanticsScope::process_all_names`] that filters out `#[doc(hidden)]` items.
454     pub(crate) fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
455         let _p = profile::span("CompletionContext::process_all_names");
456         self.scope.process_all_names(&mut |name, def| {
457             if self.is_scope_def_hidden(def) {
458                 return;
459             }
460
461             f(name, def);
462         });
463     }
464
465     pub(crate) fn process_all_names_raw(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
466         let _p = profile::span("CompletionContext::process_all_names_raw");
467         self.scope.process_all_names(&mut |name, def| f(name, def));
468     }
469
470     fn is_visible_impl(
471         &self,
472         vis: &hir::Visibility,
473         attrs: &hir::Attrs,
474         defining_crate: hir::Crate,
475     ) -> Visible {
476         if !vis.is_visible_from(self.db, self.module.into()) {
477             if !self.config.enable_private_editable {
478                 return Visible::No;
479             }
480             // If the definition location is editable, also show private items
481             let root_file = defining_crate.root_file(self.db);
482             let source_root_id = self.db.file_source_root(root_file);
483             let is_editable = !self.db.source_root(source_root_id).is_library;
484             return if is_editable { Visible::Editable } else { Visible::No };
485         }
486
487         if self.is_doc_hidden(attrs, defining_crate) {
488             Visible::No
489         } else {
490             Visible::Yes
491         }
492     }
493
494     fn is_doc_hidden(&self, attrs: &hir::Attrs, defining_crate: hir::Crate) -> bool {
495         // `doc(hidden)` items are only completed within the defining crate.
496         self.krate != defining_crate && attrs.has_doc_hidden()
497     }
498 }
499
500 // CompletionContext construction
501 impl<'a> CompletionContext<'a> {
502     pub(super) fn new(
503         db: &'a RootDatabase,
504         position @ FilePosition { file_id, offset }: FilePosition,
505         config: &'a CompletionConfig,
506     ) -> Option<CompletionContext<'a>> {
507         let _p = profile::span("CompletionContext::new");
508         let sema = Semantics::new(db);
509
510         let original_file = sema.parse(file_id);
511
512         // Insert a fake ident to get a valid parse tree. We will use this file
513         // to determine context, though the original_file will be used for
514         // actual completion.
515         let file_with_fake_ident = {
516             let parse = db.parse(file_id);
517             let edit = Indel::insert(offset, COMPLETION_MARKER.to_string());
518             parse.reparse(&edit).tree()
519         };
520         let fake_ident_token =
521             file_with_fake_ident.syntax().token_at_offset(offset).right_biased()?;
522
523         let original_token = original_file.syntax().token_at_offset(offset).left_biased()?;
524         let token = sema.descend_into_macros_single(original_token.clone());
525         let scope = sema.scope_at_offset(&token.parent()?, offset)?;
526         let krate = scope.krate();
527         let module = scope.module();
528
529         let mut locals = FxHashMap::default();
530         scope.process_all_names(&mut |name, scope| {
531             if let ScopeDef::Local(local) = scope {
532                 locals.insert(name, local);
533             }
534         });
535
536         let mut ctx = CompletionContext {
537             sema,
538             scope,
539             db,
540             config,
541             position,
542             original_token,
543             token,
544             krate,
545             module,
546             expected_name: None,
547             expected_type: None,
548             function_def: None,
549             impl_def: None,
550             incomplete_let: false,
551             completion_location: None,
552             prev_sibling: None,
553             previous_token: None,
554             // dummy value, will be overwritten
555             ident_ctx: IdentContext::UnexpandedAttrTT { fake_attribute_under_caret: None },
556             pattern_ctx: None,
557             existing_derives: Default::default(),
558             locals,
559         };
560         ctx.expand_and_fill(
561             original_file.syntax().clone(),
562             file_with_fake_ident.syntax().clone(),
563             offset,
564             fake_ident_token,
565         )?;
566         Some(ctx)
567     }
568
569     /// Expand attributes and macro calls at the current cursor position for both the original file
570     /// and fake file repeatedly. As soon as one of the two expansions fail we stop so the original
571     /// and speculative states stay in sync.
572     fn expand_and_fill(
573         &mut self,
574         mut original_file: SyntaxNode,
575         mut speculative_file: SyntaxNode,
576         mut offset: TextSize,
577         mut fake_ident_token: SyntaxToken,
578     ) -> Option<()> {
579         let _p = profile::span("CompletionContext::expand_and_fill");
580         let mut derive_ctx = None;
581
582         'expansion: loop {
583             let parent_item =
584                 |item: &ast::Item| item.syntax().ancestors().skip(1).find_map(ast::Item::cast);
585             let ancestor_items = iter::successors(
586                 Option::zip(
587                     find_node_at_offset::<ast::Item>(&original_file, offset),
588                     find_node_at_offset::<ast::Item>(&speculative_file, offset),
589                 ),
590                 |(a, b)| parent_item(a).zip(parent_item(b)),
591             );
592
593             // first try to expand attributes as these are always the outermost macro calls
594             'ancestors: for (actual_item, item_with_fake_ident) in ancestor_items {
595                 match (
596                     self.sema.expand_attr_macro(&actual_item),
597                     self.sema.speculative_expand_attr_macro(
598                         &actual_item,
599                         &item_with_fake_ident,
600                         fake_ident_token.clone(),
601                     ),
602                 ) {
603                     // maybe parent items have attributes, so continue walking the ancestors
604                     (None, None) => continue 'ancestors,
605                     // successful expansions
606                     (Some(actual_expansion), Some((fake_expansion, fake_mapped_token))) => {
607                         let new_offset = fake_mapped_token.text_range().start();
608                         if new_offset > actual_expansion.text_range().end() {
609                             // offset outside of bounds from the original expansion,
610                             // stop here to prevent problems from happening
611                             break 'expansion;
612                         }
613                         original_file = actual_expansion;
614                         speculative_file = fake_expansion;
615                         fake_ident_token = fake_mapped_token;
616                         offset = new_offset;
617                         continue 'expansion;
618                     }
619                     // exactly one expansion failed, inconsistent state so stop expanding completely
620                     _ => break 'expansion,
621                 }
622             }
623
624             // No attributes have been expanded, so look for macro_call! token trees or derive token trees
625             let orig_tt = match find_node_at_offset::<ast::TokenTree>(&original_file, offset) {
626                 Some(it) => it,
627                 None => break 'expansion,
628             };
629             let spec_tt = match find_node_at_offset::<ast::TokenTree>(&speculative_file, offset) {
630                 Some(it) => it,
631                 None => break 'expansion,
632             };
633
634             // Expand pseudo-derive expansion
635             if let (Some(orig_attr), Some(spec_attr)) = (
636                 orig_tt.syntax().parent().and_then(ast::Meta::cast).and_then(|it| it.parent_attr()),
637                 spec_tt.syntax().parent().and_then(ast::Meta::cast).and_then(|it| it.parent_attr()),
638             ) {
639                 if let (Some(actual_expansion), Some((fake_expansion, fake_mapped_token))) = (
640                     self.sema.expand_derive_as_pseudo_attr_macro(&orig_attr),
641                     self.sema.speculative_expand_derive_as_pseudo_attr_macro(
642                         &orig_attr,
643                         &spec_attr,
644                         fake_ident_token.clone(),
645                     ),
646                 ) {
647                     derive_ctx = Some((
648                         actual_expansion,
649                         fake_expansion,
650                         fake_mapped_token.text_range().start(),
651                         orig_attr,
652                     ));
653                 }
654                 // at this point we won't have any more successful expansions, so stop
655                 break 'expansion;
656             }
657
658             // Expand fn-like macro calls
659             if let (Some(actual_macro_call), Some(macro_call_with_fake_ident)) = (
660                 orig_tt.syntax().ancestors().find_map(ast::MacroCall::cast),
661                 spec_tt.syntax().ancestors().find_map(ast::MacroCall::cast),
662             ) {
663                 let mac_call_path0 = actual_macro_call.path().as_ref().map(|s| s.syntax().text());
664                 let mac_call_path1 =
665                     macro_call_with_fake_ident.path().as_ref().map(|s| s.syntax().text());
666
667                 // inconsistent state, stop expanding
668                 if mac_call_path0 != mac_call_path1 {
669                     break 'expansion;
670                 }
671                 let speculative_args = match macro_call_with_fake_ident.token_tree() {
672                     Some(tt) => tt,
673                     None => break 'expansion,
674                 };
675
676                 match (
677                     self.sema.expand(&actual_macro_call),
678                     self.sema.speculative_expand(
679                         &actual_macro_call,
680                         &speculative_args,
681                         fake_ident_token.clone(),
682                     ),
683                 ) {
684                     // successful expansions
685                     (Some(actual_expansion), Some((fake_expansion, fake_mapped_token))) => {
686                         let new_offset = fake_mapped_token.text_range().start();
687                         if new_offset > actual_expansion.text_range().end() {
688                             // offset outside of bounds from the original expansion,
689                             // stop here to prevent problems from happening
690                             break 'expansion;
691                         }
692                         original_file = actual_expansion;
693                         speculative_file = fake_expansion;
694                         fake_ident_token = fake_mapped_token;
695                         offset = new_offset;
696                         continue 'expansion;
697                     }
698                     // at least on expansion failed, we won't have anything to expand from this point
699                     // onwards so break out
700                     _ => break 'expansion,
701                 }
702             }
703
704             // none of our states have changed so stop the loop
705             break 'expansion;
706         }
707
708         self.fill(&original_file, speculative_file, offset, derive_ctx)
709     }
710
711     /// Calculate the expected type and name of the cursor position.
712     fn expected_type_and_name(&self) -> (Option<Type>, Option<NameOrNameRef>) {
713         let mut node = match self.token.parent() {
714             Some(it) => it,
715             None => return (None, None),
716         };
717         loop {
718             break match_ast! {
719                 match node {
720                     ast::LetStmt(it) => {
721                         cov_mark::hit!(expected_type_let_with_leading_char);
722                         cov_mark::hit!(expected_type_let_without_leading_char);
723                         let ty = it.pat()
724                             .and_then(|pat| self.sema.type_of_pat(&pat))
725                             .or_else(|| it.initializer().and_then(|it| self.sema.type_of_expr(&it)))
726                             .map(TypeInfo::original);
727                         let name = match it.pat() {
728                             Some(ast::Pat::IdentPat(ident)) => ident.name().map(NameOrNameRef::Name),
729                             Some(_) | None => None,
730                         };
731
732                         (ty, name)
733                     },
734                     ast::LetExpr(it) => {
735                         cov_mark::hit!(expected_type_if_let_without_leading_char);
736                         let ty = it.pat()
737                             .and_then(|pat| self.sema.type_of_pat(&pat))
738                             .or_else(|| it.expr().and_then(|it| self.sema.type_of_expr(&it)))
739                             .map(TypeInfo::original);
740                         (ty, None)
741                     },
742                     ast::ArgList(_) => {
743                         cov_mark::hit!(expected_type_fn_param);
744                         ActiveParameter::at_token(
745                             &self.sema,
746                             self.token.clone(),
747                         ).map(|ap| {
748                             let name = ap.ident().map(NameOrNameRef::Name);
749                             let ty = if has_ref(&self.token) {
750                                 cov_mark::hit!(expected_type_fn_param_ref);
751                                 ap.ty.remove_ref()
752                             } else {
753                                 Some(ap.ty)
754                             };
755                             (ty, name)
756                         })
757                         .unwrap_or((None, None))
758                     },
759                     ast::RecordExprFieldList(it) => {
760                         // wouldn't try {} be nice...
761                         (|| {
762                             if self.token.kind() == T![..]
763                                 || self.token.prev_token().map(|t| t.kind()) == Some(T![..])
764                             {
765                                 cov_mark::hit!(expected_type_struct_func_update);
766                                 let record_expr = it.syntax().parent().and_then(ast::RecordExpr::cast)?;
767                                 let ty = self.sema.type_of_expr(&record_expr.into())?;
768                                 Some((
769                                     Some(ty.original),
770                                     None
771                                 ))
772                             } else {
773                                 cov_mark::hit!(expected_type_struct_field_without_leading_char);
774                                 let expr_field = self.token.prev_sibling_or_token()?
775                                     .into_node()
776                                     .and_then(ast::RecordExprField::cast)?;
777                                 let (_, _, ty) = self.sema.resolve_record_field(&expr_field)?;
778                                 Some((
779                                     Some(ty),
780                                     expr_field.field_name().map(NameOrNameRef::NameRef),
781                                 ))
782                             }
783                         })().unwrap_or((None, None))
784                     },
785                     ast::RecordExprField(it) => {
786                         if let Some(expr) = it.expr() {
787                             cov_mark::hit!(expected_type_struct_field_with_leading_char);
788                             (
789                                 self.sema.type_of_expr(&expr).map(TypeInfo::original),
790                                 it.field_name().map(NameOrNameRef::NameRef),
791                             )
792                         } else {
793                             cov_mark::hit!(expected_type_struct_field_followed_by_comma);
794                             let ty = self.sema.resolve_record_field(&it)
795                                 .map(|(_, _, ty)| ty);
796                             (
797                                 ty,
798                                 it.field_name().map(NameOrNameRef::NameRef),
799                             )
800                         }
801                     },
802                     // match foo { $0 }
803                     // match foo { ..., pat => $0 }
804                     ast::MatchExpr(it) => {
805                         let ty = if self.previous_token_is(T![=>]) {
806                             // match foo { ..., pat => $0 }
807                             cov_mark::hit!(expected_type_match_arm_body_without_leading_char);
808                             cov_mark::hit!(expected_type_match_arm_body_with_leading_char);
809                             self.sema.type_of_expr(&it.into())
810                         } else {
811                             // match foo { $0 }
812                             cov_mark::hit!(expected_type_match_arm_without_leading_char);
813                             it.expr().and_then(|e| self.sema.type_of_expr(&e))
814                         }.map(TypeInfo::original);
815                         (ty, None)
816                     },
817                     ast::IfExpr(it) => {
818                         let ty = it.condition()
819                             .and_then(|e| self.sema.type_of_expr(&e))
820                             .map(TypeInfo::original);
821                         (ty, None)
822                     },
823                     ast::IdentPat(it) => {
824                         cov_mark::hit!(expected_type_if_let_with_leading_char);
825                         cov_mark::hit!(expected_type_match_arm_with_leading_char);
826                         let ty = self.sema.type_of_pat(&ast::Pat::from(it)).map(TypeInfo::original);
827                         (ty, None)
828                     },
829                     ast::Fn(it) => {
830                         cov_mark::hit!(expected_type_fn_ret_with_leading_char);
831                         cov_mark::hit!(expected_type_fn_ret_without_leading_char);
832                         let def = self.sema.to_def(&it);
833                         (def.map(|def| def.ret_type(self.db)), None)
834                     },
835                     ast::ClosureExpr(it) => {
836                         let ty = self.sema.type_of_expr(&it.into());
837                         ty.and_then(|ty| ty.original.as_callable(self.db))
838                             .map(|c| (Some(c.return_type()), None))
839                             .unwrap_or((None, None))
840                     },
841                     ast::ParamList(_) => (None, None),
842                     ast::Stmt(_) => (None, None),
843                     ast::Item(_) => (None, None),
844                     _ => {
845                         match node.parent() {
846                             Some(n) => {
847                                 node = n;
848                                 continue;
849                             },
850                             None => (None, None),
851                         }
852                     },
853                 }
854             };
855         }
856     }
857
858     /// Fill the completion context, this is what does semantic reasoning about the surrounding context
859     /// of the completion location.
860     fn fill(
861         &mut self,
862         original_file: &SyntaxNode,
863         file_with_fake_ident: SyntaxNode,
864         offset: TextSize,
865         derive_ctx: Option<(SyntaxNode, SyntaxNode, TextSize, ast::Attr)>,
866     ) -> Option<()> {
867         let fake_ident_token = file_with_fake_ident.token_at_offset(offset).right_biased().unwrap();
868         let syntax_element = NodeOrToken::Token(fake_ident_token);
869         if is_in_token_of_for_loop(syntax_element.clone()) {
870             // for pat $0
871             // there is nothing to complete here except `in` keyword
872             // don't bother populating the context
873             // FIXME: the completion calculations should end up good enough
874             // such that this special case becomes unnecessary
875             return None;
876         }
877
878         self.previous_token = previous_token(syntax_element.clone());
879
880         self.incomplete_let =
881             syntax_element.ancestors().take(6).find_map(ast::LetStmt::cast).map_or(false, |it| {
882                 it.syntax().text_range().end() == syntax_element.text_range().end()
883             });
884
885         (self.expected_type, self.expected_name) = self.expected_type_and_name();
886
887         // Overwrite the path kind for derives
888         if let Some((original_file, file_with_fake_ident, offset, origin_attr)) = derive_ctx {
889             self.existing_derives = self
890                 .sema
891                 .resolve_derive_macro(&origin_attr)
892                 .into_iter()
893                 .flatten()
894                 .flatten()
895                 .collect();
896
897             if let Some(ast::NameLike::NameRef(name_ref)) =
898                 find_node_at_offset(&file_with_fake_ident, offset)
899             {
900                 let parent = name_ref.syntax().parent()?;
901                 let (mut nameref_ctx, _) =
902                     Self::classify_name_ref(&self.sema, &original_file, name_ref, parent);
903                 if let Some(path_ctx) = &mut nameref_ctx.path_ctx {
904                     path_ctx.kind = PathKind::Derive;
905                 }
906                 self.ident_ctx = IdentContext::NameRef(nameref_ctx);
907                 return Some(());
908             }
909             return None;
910         }
911
912         let name_like = match find_node_at_offset(&file_with_fake_ident, offset) {
913             Some(it) => it,
914             None => {
915                 if let Some(original) = ast::String::cast(self.original_token.clone()) {
916                     self.ident_ctx = IdentContext::String {
917                         original,
918                         expanded: ast::String::cast(self.token.clone()),
919                     };
920                 } else {
921                     // Fix up trailing whitespace problem
922                     // #[attr(foo = $0
923                     let token = if self.token.kind() == SyntaxKind::WHITESPACE {
924                         self.previous_token.as_ref()?
925                     } else {
926                         &self.token
927                     };
928                     let p = token.parent()?;
929                     if p.kind() == SyntaxKind::TOKEN_TREE
930                         && p.ancestors().any(|it| it.kind() == SyntaxKind::META)
931                     {
932                         self.ident_ctx = IdentContext::UnexpandedAttrTT {
933                             fake_attribute_under_caret: syntax_element
934                                 .ancestors()
935                                 .find_map(ast::Attr::cast),
936                         };
937                     } else {
938                         return None;
939                     }
940                 }
941                 return Some(());
942             }
943         };
944         self.completion_location =
945             determine_location(&self.sema, original_file, offset, &name_like);
946         self.prev_sibling = determine_prev_sibling(&name_like);
947         self.impl_def = self
948             .sema
949             .token_ancestors_with_macros(self.token.clone())
950             .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
951             .find_map(ast::Impl::cast);
952         self.function_def = self
953             .sema
954             .token_ancestors_with_macros(self.token.clone())
955             .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
956             .find_map(ast::Fn::cast);
957
958         match name_like {
959             ast::NameLike::Lifetime(lifetime) => {
960                 self.ident_ctx = IdentContext::Lifetime(Self::classify_lifetime(
961                     &self.sema,
962                     original_file,
963                     lifetime,
964                 )?);
965             }
966             ast::NameLike::NameRef(name_ref) => {
967                 let parent = name_ref.syntax().parent()?;
968                 let (nameref_ctx, pat_ctx) =
969                     Self::classify_name_ref(&self.sema, &original_file, name_ref, parent);
970                 self.ident_ctx = IdentContext::NameRef(nameref_ctx);
971                 self.pattern_ctx = pat_ctx;
972             }
973             ast::NameLike::Name(name) => {
974                 let (name_ctx, pat_ctx) = Self::classify_name(&self.sema, original_file, name)?;
975                 self.pattern_ctx = pat_ctx;
976                 self.ident_ctx = IdentContext::Name(name_ctx);
977             }
978         }
979         Some(())
980     }
981
982     fn classify_lifetime(
983         _sema: &Semantics<RootDatabase>,
984         original_file: &SyntaxNode,
985         lifetime: ast::Lifetime,
986     ) -> Option<LifetimeContext> {
987         let parent = lifetime.syntax().parent()?;
988         if parent.kind() == ERROR {
989             return None;
990         }
991
992         let kind = match_ast! {
993             match parent {
994                 ast::LifetimeParam(param) => LifetimeKind::LifetimeParam {
995                     is_decl: param.lifetime().as_ref() == Some(&lifetime),
996                     param
997                 },
998                 ast::BreakExpr(_) => LifetimeKind::LabelRef,
999                 ast::ContinueExpr(_) => LifetimeKind::LabelRef,
1000                 ast::Label(_) => LifetimeKind::LabelDef,
1001                 _ => LifetimeKind::Lifetime,
1002             }
1003         };
1004         let lifetime = find_node_at_offset(&original_file, lifetime.syntax().text_range().start());
1005
1006         Some(LifetimeContext { lifetime, kind })
1007     }
1008
1009     fn classify_name(
1010         _sema: &Semantics<RootDatabase>,
1011         original_file: &SyntaxNode,
1012         name: ast::Name,
1013     ) -> Option<(NameContext, Option<PatternContext>)> {
1014         let parent = name.syntax().parent()?;
1015         let mut pat_ctx = None;
1016         let kind = match_ast! {
1017             match parent {
1018                 ast::Const(_) => NameKind::Const,
1019                 ast::ConstParam(_) => NameKind::ConstParam,
1020                 ast::Enum(_) => NameKind::Enum,
1021                 ast::Fn(_) => NameKind::Function,
1022                 ast::IdentPat(bind_pat) => {
1023                     let is_name_in_field_pat = bind_pat
1024                         .syntax()
1025                         .parent()
1026                         .and_then(ast::RecordPatField::cast)
1027                         .map_or(false, |pat_field| pat_field.name_ref().is_none());
1028                     if !is_name_in_field_pat {
1029                         pat_ctx = Some(pattern_context_for(original_file, bind_pat.into()));
1030                     }
1031
1032                     NameKind::IdentPat
1033                 },
1034                 ast::MacroDef(_) => NameKind::MacroDef,
1035                 ast::MacroRules(_) => NameKind::MacroRules,
1036                 ast::Module(module) => NameKind::Module(module),
1037                 ast::RecordField(_) => NameKind::RecordField,
1038                 ast::Rename(_) => NameKind::Rename,
1039                 ast::SelfParam(_) => NameKind::SelfParam,
1040                 ast::Static(_) => NameKind::Static,
1041                 ast::Struct(_) => NameKind::Struct,
1042                 ast::Trait(_) => NameKind::Trait,
1043                 ast::TypeAlias(_) => NameKind::TypeAlias,
1044                 ast::TypeParam(_) => NameKind::TypeParam,
1045                 ast::Union(_) => NameKind::Union,
1046                 ast::Variant(_) => NameKind::Variant,
1047                 _ => return None,
1048             }
1049         };
1050         let name = find_node_at_offset(&original_file, name.syntax().text_range().start());
1051         Some((NameContext { name, kind }, pat_ctx))
1052     }
1053
1054     fn classify_name_ref(
1055         sema: &Semantics<RootDatabase>,
1056         original_file: &SyntaxNode,
1057         name_ref: ast::NameRef,
1058         parent: SyntaxNode,
1059     ) -> (NameRefContext, Option<PatternContext>) {
1060         let nameref = find_node_at_offset(&original_file, name_ref.syntax().text_range().start());
1061
1062         let mut nameref_ctx = NameRefContext { dot_access: None, path_ctx: None, nameref };
1063
1064         let segment = match_ast! {
1065             match parent {
1066                 ast::PathSegment(segment) => segment,
1067                 ast::FieldExpr(field) => {
1068                     let receiver = find_in_original_file(field.expr(), original_file);
1069                     let receiver_is_ambiguous_float_literal = match &receiver {
1070                         Some(ast::Expr::Literal(l)) => matches! {
1071                             l.kind(),
1072                             ast::LiteralKind::FloatNumber { .. } if l.syntax().last_token().map_or(false, |it| it.text().ends_with('.'))
1073                         },
1074                         _ => false,
1075                     };
1076                     nameref_ctx.dot_access = Some(DotAccess::Field { receiver, receiver_is_ambiguous_float_literal });
1077                     return (nameref_ctx, None);
1078                 },
1079                 ast::MethodCallExpr(method) => {
1080                     nameref_ctx.dot_access = Some(
1081                         DotAccess::Method {
1082                             receiver: find_in_original_file(method.receiver(), original_file),
1083                             has_parens: method.arg_list().map_or(false, |it| it.l_paren_token().is_some())
1084                         }
1085                     );
1086                     return (nameref_ctx, None);
1087                 },
1088                 _ => return (nameref_ctx, None),
1089             }
1090         };
1091
1092         let path = segment.parent_path();
1093         let mut path_ctx = PathCompletionCtx {
1094             has_call_parens: false,
1095             has_macro_bang: false,
1096             is_absolute_path: false,
1097             qualifier: None,
1098             parent: path.parent_path(),
1099             kind: PathKind::Item { kind: ItemListKind::SourceFile },
1100             has_type_args: false,
1101         };
1102         let mut pat_ctx = None;
1103
1104         let is_in_block = |it: &SyntaxNode| {
1105             it.parent()
1106                 .map(|node| {
1107                     ast::ExprStmt::can_cast(node.kind()) || ast::StmtList::can_cast(node.kind())
1108                 })
1109                 .unwrap_or(false)
1110         };
1111         let is_in_func_update = |it: &SyntaxNode| {
1112             it.parent().map_or(false, |it| ast::RecordExprFieldList::can_cast(it.kind()))
1113         };
1114
1115         let kind = path.syntax().ancestors().find_map(|it| {
1116             // using Option<Option<PathKind>> as extra controlflow
1117             let kind = match_ast! {
1118                 match it {
1119                     ast::PathType(_) => Some(PathKind::Type),
1120                     ast::PathExpr(it) => {
1121                         path_ctx.has_call_parens = it.syntax().parent().map_or(false, |it| ast::CallExpr::can_cast(it.kind()));
1122                         let in_block_expr = is_in_block(it.syntax());
1123                         let in_loop_body = is_in_loop_body(it.syntax());
1124                         let in_functional_update = is_in_func_update(it.syntax());
1125                         Some(PathKind::Expr { in_block_expr, in_loop_body, in_functional_update })
1126                     },
1127                     ast::TupleStructPat(it) => {
1128                         path_ctx.has_call_parens = true;
1129                         pat_ctx = Some(pattern_context_for(original_file, it.into()));
1130                         Some(PathKind::Pat)
1131                     },
1132                     ast::RecordPat(it) => {
1133                         path_ctx.has_call_parens = true;
1134                         pat_ctx = Some(pattern_context_for(original_file, it.into()));
1135                         Some(PathKind::Pat)
1136                     },
1137                     ast::PathPat(it) => {
1138                         pat_ctx = Some(pattern_context_for(original_file, it.into()));
1139                         Some(PathKind::Pat)
1140                     },
1141                     ast::MacroCall(it) => {
1142                         path_ctx.has_macro_bang = it.excl_token().is_some();
1143                         let parent = it.syntax().parent();
1144                         match parent.as_ref().map(|it| it.kind()) {
1145                             Some(SyntaxKind::MACRO_PAT) => Some(PathKind::Pat),
1146                             Some(SyntaxKind::MACRO_TYPE) => Some(PathKind::Type),
1147                             Some(SyntaxKind::ITEM_LIST) => Some(PathKind::Item { kind: ItemListKind::Module }),
1148                             Some(SyntaxKind::ASSOC_ITEM_LIST) => Some(PathKind::Item { kind: match parent.and_then(|it| it.parent()).map(|it| it.kind()) {
1149                                 Some(SyntaxKind::TRAIT) => ItemListKind::Trait,
1150                                 Some(SyntaxKind::IMPL) => ItemListKind::Impl,
1151                                 _ => return Some(None),
1152                             } }),
1153                             Some(SyntaxKind::EXTERN_ITEM_LIST) => Some(PathKind::Item { kind: ItemListKind::ExternBlock }),
1154                             Some(SyntaxKind::SOURCE_FILE) => Some(PathKind::Item { kind: ItemListKind::SourceFile }),
1155                             _ => {
1156                                return Some(parent.and_then(ast::MacroExpr::cast).map(|it| {
1157                                     let in_loop_body = is_in_loop_body(it.syntax());
1158                                     let in_block_expr = is_in_block(it.syntax());
1159                                     let in_functional_update = is_in_func_update(it.syntax());
1160                                     PathKind::Expr { in_block_expr, in_loop_body, in_functional_update }
1161                                 }));
1162                             },
1163                         }
1164                     },
1165                     ast::Meta(meta) => (|| {
1166                         let attr = meta.parent_attr()?;
1167                         let kind = attr.kind();
1168                         let attached = attr.syntax().parent()?;
1169                         let is_trailing_outer_attr = kind != AttrKind::Inner
1170                             && non_trivia_sibling(attr.syntax().clone().into(), syntax::Direction::Next).is_none();
1171                         let annotated_item_kind = if is_trailing_outer_attr {
1172                             None
1173                         } else {
1174                             Some(attached.kind())
1175                         };
1176                         Some(PathKind::Attr {
1177                             kind,
1178                             annotated_item_kind,
1179                         })
1180                     })(),
1181                     ast::Visibility(it) => Some(PathKind::Vis { has_in_token: it.in_token().is_some() }),
1182                     ast::UseTree(_) => Some(PathKind::Use),
1183                     ast::ItemList(_) => Some(PathKind::Item { kind: ItemListKind::Module }),
1184                     ast::AssocItemList(it) => Some(PathKind::Item { kind: {
1185                             match it.syntax().parent()?.kind() {
1186                                 SyntaxKind::TRAIT => ItemListKind::Trait,
1187                                 SyntaxKind::IMPL => ItemListKind::Impl,
1188                                 _ => return None,
1189                             }
1190                         }}),
1191                     ast::ExternItemList(_) => Some(PathKind::Item { kind: ItemListKind::ExternBlock }),
1192                     ast::SourceFile(_) => Some(PathKind::Item { kind: ItemListKind::SourceFile }),
1193                     _ => return None,
1194                 }
1195             };
1196             Some(kind)
1197         }).flatten();
1198         match kind {
1199             Some(kind) => path_ctx.kind = kind,
1200             None => return (nameref_ctx, pat_ctx),
1201         }
1202         path_ctx.has_type_args = segment.generic_arg_list().is_some();
1203
1204         if let Some((path, use_tree_parent)) = path_or_use_tree_qualifier(&path) {
1205             if !use_tree_parent {
1206                 path_ctx.is_absolute_path =
1207                     path.top_path().segment().map_or(false, |it| it.coloncolon_token().is_some());
1208             }
1209
1210             let path = path
1211                 .segment()
1212                 .and_then(|it| find_node_in_file(original_file, &it))
1213                 .map(|it| it.parent_path());
1214             path_ctx.qualifier = path.map(|path| {
1215                 let res = sema.resolve_path(&path);
1216                 let is_super_chain = iter::successors(Some(path.clone()), |p| p.qualifier())
1217                     .all(|p| p.segment().and_then(|s| s.super_token()).is_some());
1218
1219                 // `<_>::$0`
1220                 let is_infer_qualifier = path.qualifier().is_none()
1221                     && matches!(
1222                         path.segment().and_then(|it| it.kind()),
1223                         Some(ast::PathSegmentKind::Type {
1224                             type_ref: Some(ast::Type::InferType(_)),
1225                             trait_ref: None,
1226                         })
1227                     );
1228
1229                 PathQualifierCtx {
1230                     path,
1231                     resolution: res,
1232                     is_super_chain,
1233                     use_tree_parent,
1234                     is_infer_qualifier,
1235                 }
1236             });
1237         } else if let Some(segment) = path.segment() {
1238             if segment.coloncolon_token().is_some() {
1239                 path_ctx.is_absolute_path = true;
1240             }
1241         }
1242         nameref_ctx.path_ctx = Some(path_ctx);
1243         (nameref_ctx, pat_ctx)
1244     }
1245 }
1246
1247 fn pattern_context_for(original_file: &SyntaxNode, pat: ast::Pat) -> PatternContext {
1248     let mut is_param = None;
1249     let (refutability, has_type_ascription) =
1250     pat
1251         .syntax()
1252         .ancestors()
1253         .skip_while(|it| ast::Pat::can_cast(it.kind()))
1254         .next()
1255         .map_or((PatternRefutability::Irrefutable, false), |node| {
1256             let refutability = match_ast! {
1257                 match node {
1258                     ast::LetStmt(let_) => return (PatternRefutability::Irrefutable, let_.ty().is_some()),
1259                     ast::Param(param) => {
1260                         let has_type_ascription = param.ty().is_some();
1261                         is_param = (|| {
1262                             let fake_param_list = param.syntax().parent().and_then(ast::ParamList::cast)?;
1263                             let param_list = find_node_in_file_compensated(original_file, &fake_param_list)?;
1264                             let param_list_owner = param_list.syntax().parent()?;
1265                             let kind = match_ast! {
1266                                 match param_list_owner {
1267                                     ast::ClosureExpr(closure) => ParamKind::Closure(closure),
1268                                     ast::Fn(fn_) => ParamKind::Function(fn_),
1269                                     _ => return None,
1270                                 }
1271                             };
1272                             Some((param_list, param, kind))
1273                         })();
1274                         return (PatternRefutability::Irrefutable, has_type_ascription)
1275                     },
1276                     ast::MatchArm(_) => PatternRefutability::Refutable,
1277                     ast::LetExpr(_) => PatternRefutability::Refutable,
1278                     ast::ForExpr(_) => PatternRefutability::Irrefutable,
1279                     _ => PatternRefutability::Irrefutable,
1280                 }
1281             };
1282             (refutability, false)
1283         });
1284     let (ref_token, mut_token) = match &pat {
1285         ast::Pat::IdentPat(it) => (it.ref_token(), it.mut_token()),
1286         _ => (None, None),
1287     };
1288     PatternContext {
1289         refutability,
1290         param_ctx: is_param,
1291         has_type_ascription,
1292         parent_pat: pat.syntax().parent().and_then(ast::Pat::cast),
1293         mut_token,
1294         ref_token,
1295     }
1296 }
1297
1298 fn find_in_original_file<N: AstNode>(x: Option<N>, original_file: &SyntaxNode) -> Option<N> {
1299     fn find_node_with_range<N: AstNode>(syntax: &SyntaxNode, range: TextRange) -> Option<N> {
1300         let range = syntax.text_range().intersect(range)?;
1301         syntax.covering_element(range).ancestors().find_map(N::cast)
1302     }
1303     x.map(|e| e.syntax().text_range()).and_then(|r| find_node_with_range(original_file, r))
1304 }
1305
1306 /// Attempts to find `node` inside `syntax` via `node`'s text range.
1307 fn find_node_in_file<N: AstNode>(syntax: &SyntaxNode, node: &N) -> Option<N> {
1308     let syntax_range = syntax.text_range();
1309     let range = node.syntax().text_range();
1310     let intersection = range.intersect(syntax_range)?;
1311     syntax.covering_element(intersection).ancestors().find_map(N::cast)
1312 }
1313
1314 /// Attempts to find `node` inside `syntax` via `node`'s text range while compensating
1315 /// for the offset introduced by the fake ident.
1316 /// This is wrong if `node` comes before the insertion point! Use `find_node_in_file` instead.
1317 fn find_node_in_file_compensated<N: AstNode>(syntax: &SyntaxNode, node: &N) -> Option<N> {
1318     let syntax_range = syntax.text_range();
1319     let range = node.syntax().text_range();
1320     let end = range.end().checked_sub(TextSize::try_from(COMPLETION_MARKER.len()).ok()?)?;
1321     if end < range.start() {
1322         return None;
1323     }
1324     let range = TextRange::new(range.start(), end);
1325     // our inserted ident could cause `range` to be go outside of the original syntax, so cap it
1326     let intersection = range.intersect(syntax_range)?;
1327     syntax.covering_element(intersection).ancestors().find_map(N::cast)
1328 }
1329
1330 fn path_or_use_tree_qualifier(path: &ast::Path) -> Option<(ast::Path, bool)> {
1331     if let Some(qual) = path.qualifier() {
1332         return Some((qual, false));
1333     }
1334     let use_tree_list = path.syntax().ancestors().find_map(ast::UseTreeList::cast)?;
1335     let use_tree = use_tree_list.syntax().parent().and_then(ast::UseTree::cast)?;
1336     Some((use_tree.path()?, true))
1337 }
1338
1339 fn has_ref(token: &SyntaxToken) -> bool {
1340     let mut token = token.clone();
1341     for skip in [IDENT, WHITESPACE, T![mut]] {
1342         if token.kind() == skip {
1343             token = match token.prev_token() {
1344                 Some(it) => it,
1345                 None => return false,
1346             }
1347         }
1348     }
1349     token.kind() == T![&]
1350 }
1351
1352 const OP_TRAIT_LANG_NAMES: &[&str] = &[
1353     "add_assign",
1354     "add",
1355     "bitand_assign",
1356     "bitand",
1357     "bitor_assign",
1358     "bitor",
1359     "bitxor_assign",
1360     "bitxor",
1361     "deref_mut",
1362     "deref",
1363     "div_assign",
1364     "div",
1365     "eq",
1366     "fn_mut",
1367     "fn_once",
1368     "fn",
1369     "index_mut",
1370     "index",
1371     "mul_assign",
1372     "mul",
1373     "neg",
1374     "not",
1375     "partial_ord",
1376     "rem_assign",
1377     "rem",
1378     "shl_assign",
1379     "shl",
1380     "shr_assign",
1381     "shr",
1382     "sub",
1383 ];
1384
1385 #[cfg(test)]
1386 mod tests {
1387     use expect_test::{expect, Expect};
1388     use hir::HirDisplay;
1389
1390     use crate::tests::{position, TEST_CONFIG};
1391
1392     use super::CompletionContext;
1393
1394     fn check_expected_type_and_name(ra_fixture: &str, expect: Expect) {
1395         let (db, pos) = position(ra_fixture);
1396         let config = TEST_CONFIG;
1397         let completion_context = CompletionContext::new(&db, pos, &config).unwrap();
1398
1399         let ty = completion_context
1400             .expected_type
1401             .map(|t| t.display_test(&db).to_string())
1402             .unwrap_or("?".to_owned());
1403
1404         let name = completion_context
1405             .expected_name
1406             .map_or_else(|| "?".to_owned(), |name| name.to_string());
1407
1408         expect.assert_eq(&format!("ty: {}, name: {}", ty, name));
1409     }
1410
1411     #[test]
1412     fn expected_type_let_without_leading_char() {
1413         cov_mark::check!(expected_type_let_without_leading_char);
1414         check_expected_type_and_name(
1415             r#"
1416 fn foo() {
1417     let x: u32 = $0;
1418 }
1419 "#,
1420             expect![[r#"ty: u32, name: x"#]],
1421         );
1422     }
1423
1424     #[test]
1425     fn expected_type_let_with_leading_char() {
1426         cov_mark::check!(expected_type_let_with_leading_char);
1427         check_expected_type_and_name(
1428             r#"
1429 fn foo() {
1430     let x: u32 = c$0;
1431 }
1432 "#,
1433             expect![[r#"ty: u32, name: x"#]],
1434         );
1435     }
1436
1437     #[test]
1438     fn expected_type_let_pat() {
1439         check_expected_type_and_name(
1440             r#"
1441 fn foo() {
1442     let x$0 = 0u32;
1443 }
1444 "#,
1445             expect![[r#"ty: u32, name: ?"#]],
1446         );
1447         check_expected_type_and_name(
1448             r#"
1449 fn foo() {
1450     let $0 = 0u32;
1451 }
1452 "#,
1453             expect![[r#"ty: u32, name: ?"#]],
1454         );
1455     }
1456
1457     #[test]
1458     fn expected_type_fn_param() {
1459         cov_mark::check!(expected_type_fn_param);
1460         check_expected_type_and_name(
1461             r#"
1462 fn foo() { bar($0); }
1463 fn bar(x: u32) {}
1464 "#,
1465             expect![[r#"ty: u32, name: x"#]],
1466         );
1467         check_expected_type_and_name(
1468             r#"
1469 fn foo() { bar(c$0); }
1470 fn bar(x: u32) {}
1471 "#,
1472             expect![[r#"ty: u32, name: x"#]],
1473         );
1474     }
1475
1476     #[test]
1477     fn expected_type_fn_param_ref() {
1478         cov_mark::check!(expected_type_fn_param_ref);
1479         check_expected_type_and_name(
1480             r#"
1481 fn foo() { bar(&$0); }
1482 fn bar(x: &u32) {}
1483 "#,
1484             expect![[r#"ty: u32, name: x"#]],
1485         );
1486         check_expected_type_and_name(
1487             r#"
1488 fn foo() { bar(&mut $0); }
1489 fn bar(x: &mut u32) {}
1490 "#,
1491             expect![[r#"ty: u32, name: x"#]],
1492         );
1493         check_expected_type_and_name(
1494             r#"
1495 fn foo() { bar(& c$0); }
1496 fn bar(x: &u32) {}
1497         "#,
1498             expect![[r#"ty: u32, name: x"#]],
1499         );
1500         check_expected_type_and_name(
1501             r#"
1502 fn foo() { bar(&mut c$0); }
1503 fn bar(x: &mut u32) {}
1504 "#,
1505             expect![[r#"ty: u32, name: x"#]],
1506         );
1507         check_expected_type_and_name(
1508             r#"
1509 fn foo() { bar(&c$0); }
1510 fn bar(x: &u32) {}
1511         "#,
1512             expect![[r#"ty: u32, name: x"#]],
1513         );
1514     }
1515
1516     #[test]
1517     fn expected_type_struct_field_without_leading_char() {
1518         cov_mark::check!(expected_type_struct_field_without_leading_char);
1519         check_expected_type_and_name(
1520             r#"
1521 struct Foo { a: u32 }
1522 fn foo() {
1523     Foo { a: $0 };
1524 }
1525 "#,
1526             expect![[r#"ty: u32, name: a"#]],
1527         )
1528     }
1529
1530     #[test]
1531     fn expected_type_struct_field_followed_by_comma() {
1532         cov_mark::check!(expected_type_struct_field_followed_by_comma);
1533         check_expected_type_and_name(
1534             r#"
1535 struct Foo { a: u32 }
1536 fn foo() {
1537     Foo { a: $0, };
1538 }
1539 "#,
1540             expect![[r#"ty: u32, name: a"#]],
1541         )
1542     }
1543
1544     #[test]
1545     fn expected_type_generic_struct_field() {
1546         check_expected_type_and_name(
1547             r#"
1548 struct Foo<T> { a: T }
1549 fn foo() -> Foo<u32> {
1550     Foo { a: $0 }
1551 }
1552 "#,
1553             expect![[r#"ty: u32, name: a"#]],
1554         )
1555     }
1556
1557     #[test]
1558     fn expected_type_struct_field_with_leading_char() {
1559         cov_mark::check!(expected_type_struct_field_with_leading_char);
1560         check_expected_type_and_name(
1561             r#"
1562 struct Foo { a: u32 }
1563 fn foo() {
1564     Foo { a: c$0 };
1565 }
1566 "#,
1567             expect![[r#"ty: u32, name: a"#]],
1568         );
1569     }
1570
1571     #[test]
1572     fn expected_type_match_arm_without_leading_char() {
1573         cov_mark::check!(expected_type_match_arm_without_leading_char);
1574         check_expected_type_and_name(
1575             r#"
1576 enum E { X }
1577 fn foo() {
1578    match E::X { $0 }
1579 }
1580 "#,
1581             expect![[r#"ty: E, name: ?"#]],
1582         );
1583     }
1584
1585     #[test]
1586     fn expected_type_match_arm_with_leading_char() {
1587         cov_mark::check!(expected_type_match_arm_with_leading_char);
1588         check_expected_type_and_name(
1589             r#"
1590 enum E { X }
1591 fn foo() {
1592    match E::X { c$0 }
1593 }
1594 "#,
1595             expect![[r#"ty: E, name: ?"#]],
1596         );
1597     }
1598
1599     #[test]
1600     fn expected_type_match_arm_body_without_leading_char() {
1601         cov_mark::check!(expected_type_match_arm_body_without_leading_char);
1602         check_expected_type_and_name(
1603             r#"
1604 struct Foo;
1605 enum E { X }
1606 fn foo() -> Foo {
1607    match E::X { E::X => $0 }
1608 }
1609 "#,
1610             expect![[r#"ty: Foo, name: ?"#]],
1611         );
1612     }
1613
1614     #[test]
1615     fn expected_type_match_body_arm_with_leading_char() {
1616         cov_mark::check!(expected_type_match_arm_body_with_leading_char);
1617         check_expected_type_and_name(
1618             r#"
1619 struct Foo;
1620 enum E { X }
1621 fn foo() -> Foo {
1622    match E::X { E::X => c$0 }
1623 }
1624 "#,
1625             expect![[r#"ty: Foo, name: ?"#]],
1626         );
1627     }
1628
1629     #[test]
1630     fn expected_type_if_let_without_leading_char() {
1631         cov_mark::check!(expected_type_if_let_without_leading_char);
1632         check_expected_type_and_name(
1633             r#"
1634 enum Foo { Bar, Baz, Quux }
1635
1636 fn foo() {
1637     let f = Foo::Quux;
1638     if let $0 = f { }
1639 }
1640 "#,
1641             expect![[r#"ty: Foo, name: ?"#]],
1642         )
1643     }
1644
1645     #[test]
1646     fn expected_type_if_let_with_leading_char() {
1647         cov_mark::check!(expected_type_if_let_with_leading_char);
1648         check_expected_type_and_name(
1649             r#"
1650 enum Foo { Bar, Baz, Quux }
1651
1652 fn foo() {
1653     let f = Foo::Quux;
1654     if let c$0 = f { }
1655 }
1656 "#,
1657             expect![[r#"ty: Foo, name: ?"#]],
1658         )
1659     }
1660
1661     #[test]
1662     fn expected_type_fn_ret_without_leading_char() {
1663         cov_mark::check!(expected_type_fn_ret_without_leading_char);
1664         check_expected_type_and_name(
1665             r#"
1666 fn foo() -> u32 {
1667     $0
1668 }
1669 "#,
1670             expect![[r#"ty: u32, name: ?"#]],
1671         )
1672     }
1673
1674     #[test]
1675     fn expected_type_fn_ret_with_leading_char() {
1676         cov_mark::check!(expected_type_fn_ret_with_leading_char);
1677         check_expected_type_and_name(
1678             r#"
1679 fn foo() -> u32 {
1680     c$0
1681 }
1682 "#,
1683             expect![[r#"ty: u32, name: ?"#]],
1684         )
1685     }
1686
1687     #[test]
1688     fn expected_type_fn_ret_fn_ref_fully_typed() {
1689         check_expected_type_and_name(
1690             r#"
1691 fn foo() -> u32 {
1692     foo$0
1693 }
1694 "#,
1695             expect![[r#"ty: u32, name: ?"#]],
1696         )
1697     }
1698
1699     #[test]
1700     fn expected_type_closure_param_return() {
1701         // FIXME: make this work with `|| $0`
1702         check_expected_type_and_name(
1703             r#"
1704 //- minicore: fn
1705 fn foo() {
1706     bar(|| a$0);
1707 }
1708
1709 fn bar(f: impl FnOnce() -> u32) {}
1710 "#,
1711             expect![[r#"ty: u32, name: ?"#]],
1712         );
1713     }
1714
1715     #[test]
1716     fn expected_type_generic_function() {
1717         check_expected_type_and_name(
1718             r#"
1719 fn foo() {
1720     bar::<u32>($0);
1721 }
1722
1723 fn bar<T>(t: T) {}
1724 "#,
1725             expect![[r#"ty: u32, name: t"#]],
1726         );
1727     }
1728
1729     #[test]
1730     fn expected_type_generic_method() {
1731         check_expected_type_and_name(
1732             r#"
1733 fn foo() {
1734     S(1u32).bar($0);
1735 }
1736
1737 struct S<T>(T);
1738 impl<T> S<T> {
1739     fn bar(self, t: T) {}
1740 }
1741 "#,
1742             expect![[r#"ty: u32, name: t"#]],
1743         );
1744     }
1745
1746     #[test]
1747     fn expected_type_functional_update() {
1748         cov_mark::check!(expected_type_struct_func_update);
1749         check_expected_type_and_name(
1750             r#"
1751 struct Foo { field: u32 }
1752 fn foo() {
1753     Foo {
1754         ..$0
1755     }
1756 }
1757 "#,
1758             expect![[r#"ty: Foo, name: ?"#]],
1759         );
1760     }
1761
1762     #[test]
1763     fn expected_type_param_pat() {
1764         check_expected_type_and_name(
1765             r#"
1766 struct Foo { field: u32 }
1767 fn foo(a$0: Foo) {}
1768 "#,
1769             expect![[r#"ty: Foo, name: ?"#]],
1770         );
1771         check_expected_type_and_name(
1772             r#"
1773 struct Foo { field: u32 }
1774 fn foo($0: Foo) {}
1775 "#,
1776             // FIXME make this work, currently fails due to pattern recovery eating the `:`
1777             expect![[r#"ty: ?, name: ?"#]],
1778         );
1779     }
1780 }