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