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