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