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