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