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