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