1 //! See `CompletionContext` structure.
5 use base_db::SourceDatabaseExt;
7 HasAttrs, Local, Name, PathResolution, ScopeDef, Semantics, SemanticsScope, Type, TypeInfo,
10 active_parameter::ActiveParameter,
11 base_db::{FilePosition, SourceDatabase},
12 famous_defs::FamousDefs,
13 FxHashMap, FxHashSet, RootDatabase,
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,
26 determine_location, determine_prev_sibling, is_in_loop_body, is_in_token_of_for_loop,
27 previous_token, ImmediateLocation, ImmediatePrevSibling,
32 const COMPLETION_MARKER: &str = "intellijRulezz";
34 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
35 pub(crate) enum PatternRefutability {
40 pub(crate) enum Visible {
46 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
47 pub(super) enum PathKind {
55 annotated_item_kind: Option<SyntaxKind>,
58 /// Path in item position, that is inside an (Assoc)ItemList
69 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
70 pub(super) enum ItemListKind {
79 #[derive(Debug, Default)]
80 pub(super) struct QualifierCtx {
81 pub(super) unsafe_tok: Option<SyntaxToken>,
82 pub(super) vis_node: Option<ast::Visibility>,
86 pub(super) fn none(&self) -> bool {
87 self.unsafe_tok.is_none() && self.vis_node.is_none()
92 pub(crate) struct PathCompletionCtx {
93 /// If this is a call with () already there (or {} in case of record patterns)
94 pub(super) has_call_parens: bool,
95 /// If this has a macro call bang !
96 pub(super) has_macro_bang: bool,
97 /// Whether this path stars with a `::`.
98 pub(super) is_absolute_path: bool,
99 /// The qualifier of the current path if it exists.
100 pub(super) qualifier: Option<PathQualifierCtx>,
103 /// The parent of the path we are completing.
104 pub(super) parent: Option<ast::Path>,
105 pub(super) kind: PathKind,
106 /// Whether the path segment has type args or not.
107 pub(super) has_type_args: bool,
111 pub(crate) struct PathQualifierCtx {
112 pub(crate) path: ast::Path,
113 pub(crate) resolution: Option<PathResolution>,
114 /// Whether this path consists solely of `super` segments
115 pub(crate) is_super_chain: bool,
116 /// Whether the qualifier comes from a use tree parent or not
117 pub(crate) use_tree_parent: bool,
119 pub(crate) is_infer_qualifier: bool,
123 pub(super) struct PatternContext {
124 pub(super) refutability: PatternRefutability,
125 pub(super) param_ctx: Option<(ast::ParamList, ast::Param, ParamKind)>,
126 pub(super) has_type_ascription: bool,
127 pub(super) parent_pat: Option<ast::Pat>,
128 pub(super) ref_token: Option<SyntaxToken>,
129 pub(super) mut_token: Option<SyntaxToken>,
130 /// The record pattern this name or ref is a field of
131 pub(super) record_pat: Option<ast::RecordPat>,
135 pub(super) struct LifetimeContext {
136 pub(super) lifetime: Option<ast::Lifetime>,
137 pub(super) kind: LifetimeKind,
141 pub(super) enum LifetimeKind {
142 LifetimeParam { is_decl: bool, param: ast::LifetimeParam },
149 pub(super) struct NameContext {
151 pub(super) name: Option<ast::Name>,
152 pub(super) kind: NameKind,
157 pub(super) enum NameKind {
180 pub(super) struct NameRefContext {
181 /// NameRef syntax in the original file
182 pub(super) nameref: Option<ast::NameRef>,
183 // FIXME: these fields are actually disjoint -> enum
184 pub(super) dot_access: Option<DotAccess>,
185 pub(super) path_ctx: Option<PathCompletionCtx>,
186 /// The record expression this nameref is a field of
187 pub(super) record_expr: Option<(ast::RecordExpr, bool)>,
191 pub(super) enum IdentContext {
193 NameRef(NameRefContext),
194 Lifetime(LifetimeContext),
195 /// Original token, fake token
197 original: ast::String,
198 expanded: Option<ast::String>,
201 fake_attribute_under_caret: Option<ast::Attr>,
206 pub(super) struct DotAccess {
207 pub(super) receiver: Option<ast::Expr>,
208 pub(super) receiver_ty: Option<TypeInfo>,
209 pub(super) kind: DotAccessKind,
213 pub(super) enum DotAccessKind {
215 /// True if the receiver is an integer and there is no ident in the original file after it yet
217 receiver_is_ambiguous_float_literal: bool,
224 #[derive(Clone, Debug, PartialEq, Eq)]
225 pub(crate) enum ParamKind {
227 Closure(ast::ClosureExpr),
230 /// `CompletionContext` is created early during completion to figure out, where
231 /// exactly is the cursor, syntax-wise.
233 pub(crate) struct CompletionContext<'a> {
234 pub(super) sema: Semantics<'a, RootDatabase>,
235 pub(super) scope: SemanticsScope<'a>,
236 pub(super) db: &'a RootDatabase,
237 pub(super) config: &'a CompletionConfig,
238 pub(super) position: FilePosition,
240 /// The token before the cursor, in the original file.
241 pub(super) original_token: SyntaxToken,
242 /// The token before the cursor, in the macro-expanded file.
243 pub(super) token: SyntaxToken,
244 /// The crate of the current file.
245 pub(super) krate: hir::Crate,
246 /// The module of the `scope`.
247 pub(super) module: hir::Module,
249 /// The expected name of what we are completing.
250 /// This is usually the parameter name of the function argument we are completing.
251 pub(super) expected_name: Option<NameOrNameRef>,
252 /// The expected type of what we are completing.
253 pub(super) expected_type: Option<Type>,
255 /// The parent function of the cursor position if it exists.
256 pub(super) function_def: Option<ast::Fn>,
257 /// The parent impl of the cursor position if it exists.
258 pub(super) impl_def: Option<ast::Impl>,
259 /// Are we completing inside a let statement with a missing semicolon?
260 pub(super) incomplete_let: bool,
262 pub(super) completion_location: Option<ImmediateLocation>,
263 pub(super) prev_sibling: Option<ImmediatePrevSibling>,
264 pub(super) previous_token: Option<SyntaxToken>,
266 pub(super) ident_ctx: IdentContext,
268 pub(super) pattern_ctx: Option<PatternContext>,
269 pub(super) qualifier_ctx: QualifierCtx,
271 pub(super) existing_derives: FxHashSet<hir::Macro>,
273 pub(super) locals: FxHashMap<Name, Local>,
276 impl<'a> CompletionContext<'a> {
277 /// The range of the identifier that is being completed.
278 pub(crate) fn source_range(&self) -> TextRange {
279 // check kind of macro-expanded token, but use range of original token
280 let kind = self.token.kind();
283 // assume we are completing a lifetime but the user has only typed the '
284 cov_mark::hit!(completes_if_lifetime_without_idents);
285 TextRange::at(self.original_token.text_range().start(), TextSize::from(1))
287 IDENT | LIFETIME_IDENT | UNDERSCORE => self.original_token.text_range(),
288 _ if kind.is_keyword() => self.original_token.text_range(),
289 _ => TextRange::empty(self.position.offset),
293 pub(crate) fn previous_token_is(&self, kind: SyntaxKind) -> bool {
294 self.previous_token.as_ref().map_or(false, |tok| tok.kind() == kind)
297 pub(crate) fn famous_defs(&self) -> FamousDefs {
298 FamousDefs(&self.sema, self.krate)
301 pub(super) fn nameref_ctx(&self) -> Option<&NameRefContext> {
302 match &self.ident_ctx {
303 IdentContext::NameRef(it) => Some(it),
308 pub(super) fn name_ctx(&self) -> Option<&NameContext> {
309 match &self.ident_ctx {
310 IdentContext::Name(it) => Some(it),
315 pub(super) fn lifetime_ctx(&self) -> Option<&LifetimeContext> {
316 match &self.ident_ctx {
317 IdentContext::Lifetime(it) => Some(it),
322 pub(crate) fn dot_receiver(&self) -> Option<&ast::Expr> {
323 match self.nameref_ctx() {
324 Some(NameRefContext { dot_access: Some(DotAccess { receiver, .. }), .. }) => {
331 pub(crate) fn has_dot_receiver(&self) -> bool {
332 self.dot_receiver().is_some()
335 pub(crate) fn expects_assoc_item(&self) -> bool {
336 matches!(self.completion_location, Some(ImmediateLocation::Trait | ImmediateLocation::Impl))
339 pub(crate) fn expects_item(&self) -> bool {
340 matches!(self.completion_location, Some(ImmediateLocation::ItemList))
343 // FIXME: This shouldn't exist
344 pub(crate) fn expects_generic_arg(&self) -> bool {
345 matches!(self.completion_location, Some(ImmediateLocation::GenericArgList(_)))
348 pub(crate) fn expects_ident_ref_expr(&self) -> bool {
349 matches!(self.completion_location, Some(ImmediateLocation::RefExpr))
352 /// Whether the cursor is right after a trait or impl header.
353 /// trait Foo ident$0
354 // FIXME: This probably shouldn't exist
355 pub(crate) fn has_unfinished_impl_or_trait_prev_sibling(&self) -> bool {
358 Some(ImmediatePrevSibling::ImplDefType | ImmediatePrevSibling::TraitDefName)
362 // FIXME: This probably shouldn't exist
363 pub(crate) fn has_impl_prev_sibling(&self) -> bool {
364 matches!(self.prev_sibling, Some(ImmediatePrevSibling::ImplDefType))
367 pub(crate) fn after_if(&self) -> bool {
368 matches!(self.prev_sibling, Some(ImmediatePrevSibling::IfExpr))
371 // FIXME: This shouldn't exist
372 pub(crate) fn is_path_disallowed(&self) -> bool {
373 !self.qualifier_ctx.none()
374 || (matches!(self.name_ctx(), Some(NameContext { .. })) && self.pattern_ctx.is_none())
375 || matches!(self.pattern_ctx, Some(PatternContext { record_pat: Some(_), .. }))
378 Some(NameRefContext { record_expr: Some((_, false)), .. })
382 pub(crate) fn path_context(&self) -> Option<&PathCompletionCtx> {
383 self.nameref_ctx().and_then(|ctx| ctx.path_ctx.as_ref())
386 pub(crate) fn expects_expression(&self) -> bool {
387 matches!(self.path_context(), Some(PathCompletionCtx { kind: PathKind::Expr { .. }, .. }))
390 pub(crate) fn is_non_trivial_path(&self) -> bool {
394 PathCompletionCtx { is_absolute_path: true, .. }
395 | PathCompletionCtx { qualifier: Some(_), .. }
400 pub(crate) fn path_qual(&self) -> Option<&ast::Path> {
401 self.path_context().and_then(|it| it.qualifier.as_ref().map(|it| &it.path))
404 pub(crate) fn path_kind(&self) -> Option<PathKind> {
405 self.path_context().map(|it| it.kind)
408 /// Checks if an item is visible and not `doc(hidden)` at the completion site.
409 pub(crate) fn is_visible<I>(&self, item: &I) -> Visible
411 I: hir::HasVisibility + hir::HasAttrs + hir::HasCrate + Copy,
413 self.is_visible_impl(&item.visibility(self.db), &item.attrs(self.db), item.krate(self.db))
416 pub(crate) fn is_scope_def_hidden(&self, scope_def: ScopeDef) -> bool {
417 if let (Some(attrs), Some(krate)) = (scope_def.attrs(self.db), scope_def.krate(self.db)) {
418 return self.is_doc_hidden(&attrs, krate);
424 /// Check if an item is `#[doc(hidden)]`.
425 pub(crate) fn is_item_hidden(&self, item: &hir::ItemInNs) -> bool {
426 let attrs = item.attrs(self.db);
427 let krate = item.krate(self.db);
428 match (attrs, krate) {
429 (Some(attrs), Some(krate)) => self.is_doc_hidden(&attrs, krate),
433 /// Whether the given trait is an operator trait or not.
434 pub(crate) fn is_ops_trait(&self, trait_: hir::Trait) -> bool {
435 match trait_.attrs(self.db).lang() {
436 Some(lang) => OP_TRAIT_LANG_NAMES.contains(&lang.as_str()),
441 /// Returns the traits in scope, with the [`Drop`] trait removed.
442 pub(crate) fn traits_in_scope(&self) -> hir::VisibleTraits {
443 let mut traits_in_scope = self.scope.visible_traits();
444 if let Some(drop) = self.famous_defs().core_ops_Drop() {
445 traits_in_scope.0.remove(&drop.into());
450 /// A version of [`SemanticsScope::process_all_names`] that filters out `#[doc(hidden)]` items.
451 pub(crate) fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
452 let _p = profile::span("CompletionContext::process_all_names");
453 self.scope.process_all_names(&mut |name, def| {
454 if self.is_scope_def_hidden(def) {
462 pub(crate) fn process_all_names_raw(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
463 let _p = profile::span("CompletionContext::process_all_names_raw");
464 self.scope.process_all_names(&mut |name, def| f(name, def));
469 vis: &hir::Visibility,
471 defining_crate: hir::Crate,
473 if !vis.is_visible_from(self.db, self.module.into()) {
474 if !self.config.enable_private_editable {
477 // If the definition location is editable, also show private items
478 let root_file = defining_crate.root_file(self.db);
479 let source_root_id = self.db.file_source_root(root_file);
480 let is_editable = !self.db.source_root(source_root_id).is_library;
481 return if is_editable { Visible::Editable } else { Visible::No };
484 if self.is_doc_hidden(attrs, defining_crate) {
491 fn is_doc_hidden(&self, attrs: &hir::Attrs, defining_crate: hir::Crate) -> bool {
492 // `doc(hidden)` items are only completed within the defining crate.
493 self.krate != defining_crate && attrs.has_doc_hidden()
497 // CompletionContext construction
498 impl<'a> CompletionContext<'a> {
500 db: &'a RootDatabase,
501 position @ FilePosition { file_id, offset }: FilePosition,
502 config: &'a CompletionConfig,
503 ) -> Option<CompletionContext<'a>> {
504 let _p = profile::span("CompletionContext::new");
505 let sema = Semantics::new(db);
507 let original_file = sema.parse(file_id);
509 // Insert a fake ident to get a valid parse tree. We will use this file
510 // to determine context, though the original_file will be used for
511 // actual completion.
512 let file_with_fake_ident = {
513 let parse = db.parse(file_id);
514 let edit = Indel::insert(offset, COMPLETION_MARKER.to_string());
515 parse.reparse(&edit).tree()
517 let fake_ident_token =
518 file_with_fake_ident.syntax().token_at_offset(offset).right_biased()?;
520 let original_token = original_file.syntax().token_at_offset(offset).left_biased()?;
521 let token = sema.descend_into_macros_single(original_token.clone());
522 let scope = sema.scope_at_offset(&token.parent()?, offset)?;
523 let krate = scope.krate();
524 let module = scope.module();
526 let mut locals = FxHashMap::default();
527 scope.process_all_names(&mut |name, scope| {
528 if let ScopeDef::Local(local) = scope {
529 locals.insert(name, local);
533 let mut ctx = CompletionContext {
547 incomplete_let: false,
548 completion_location: None,
550 previous_token: None,
551 // dummy value, will be overwritten
552 ident_ctx: IdentContext::UnexpandedAttrTT { fake_attribute_under_caret: None },
554 qualifier_ctx: Default::default(),
555 existing_derives: Default::default(),
559 original_file.syntax().clone(),
560 file_with_fake_ident.syntax().clone(),
567 /// Expand attributes and macro calls at the current cursor position for both the original file
568 /// and fake file repeatedly. As soon as one of the two expansions fail we stop so the original
569 /// and speculative states stay in sync.
572 mut original_file: SyntaxNode,
573 mut speculative_file: SyntaxNode,
574 mut offset: TextSize,
575 mut fake_ident_token: SyntaxToken,
577 let _p = profile::span("CompletionContext::expand_and_fill");
578 let mut derive_ctx = None;
582 |item: &ast::Item| item.syntax().ancestors().skip(1).find_map(ast::Item::cast);
583 let ancestor_items = iter::successors(
585 find_node_at_offset::<ast::Item>(&original_file, offset),
586 find_node_at_offset::<ast::Item>(&speculative_file, offset),
588 |(a, b)| parent_item(a).zip(parent_item(b)),
591 // first try to expand attributes as these are always the outermost macro calls
592 'ancestors: for (actual_item, item_with_fake_ident) in ancestor_items {
594 self.sema.expand_attr_macro(&actual_item),
595 self.sema.speculative_expand_attr_macro(
597 &item_with_fake_ident,
598 fake_ident_token.clone(),
601 // maybe parent items have attributes, so continue walking the ancestors
602 (None, None) => continue 'ancestors,
603 // successful expansions
604 (Some(actual_expansion), Some((fake_expansion, fake_mapped_token))) => {
605 let new_offset = fake_mapped_token.text_range().start();
606 if new_offset > actual_expansion.text_range().end() {
607 // offset outside of bounds from the original expansion,
608 // stop here to prevent problems from happening
611 original_file = actual_expansion;
612 speculative_file = fake_expansion;
613 fake_ident_token = fake_mapped_token;
617 // exactly one expansion failed, inconsistent state so stop expanding completely
618 _ => break 'expansion,
622 // No attributes have been expanded, so look for macro_call! token trees or derive token trees
623 let orig_tt = match find_node_at_offset::<ast::TokenTree>(&original_file, offset) {
625 None => break 'expansion,
627 let spec_tt = match find_node_at_offset::<ast::TokenTree>(&speculative_file, offset) {
629 None => break 'expansion,
632 // Expand pseudo-derive expansion
633 if let (Some(orig_attr), Some(spec_attr)) = (
634 orig_tt.syntax().parent().and_then(ast::Meta::cast).and_then(|it| it.parent_attr()),
635 spec_tt.syntax().parent().and_then(ast::Meta::cast).and_then(|it| it.parent_attr()),
637 if let (Some(actual_expansion), Some((fake_expansion, fake_mapped_token))) = (
638 self.sema.expand_derive_as_pseudo_attr_macro(&orig_attr),
639 self.sema.speculative_expand_derive_as_pseudo_attr_macro(
642 fake_ident_token.clone(),
648 fake_mapped_token.text_range().start(),
652 // at this point we won't have any more successful expansions, so stop
656 // Expand fn-like macro calls
657 if let (Some(actual_macro_call), Some(macro_call_with_fake_ident)) = (
658 orig_tt.syntax().ancestors().find_map(ast::MacroCall::cast),
659 spec_tt.syntax().ancestors().find_map(ast::MacroCall::cast),
661 let mac_call_path0 = actual_macro_call.path().as_ref().map(|s| s.syntax().text());
663 macro_call_with_fake_ident.path().as_ref().map(|s| s.syntax().text());
665 // inconsistent state, stop expanding
666 if mac_call_path0 != mac_call_path1 {
669 let speculative_args = match macro_call_with_fake_ident.token_tree() {
671 None => break 'expansion,
675 self.sema.expand(&actual_macro_call),
676 self.sema.speculative_expand(
679 fake_ident_token.clone(),
682 // successful expansions
683 (Some(actual_expansion), Some((fake_expansion, fake_mapped_token))) => {
684 let new_offset = fake_mapped_token.text_range().start();
685 if new_offset > actual_expansion.text_range().end() {
686 // offset outside of bounds from the original expansion,
687 // stop here to prevent problems from happening
690 original_file = actual_expansion;
691 speculative_file = fake_expansion;
692 fake_ident_token = fake_mapped_token;
696 // at least on expansion failed, we won't have anything to expand from this point
697 // onwards so break out
698 _ => break 'expansion,
702 // none of our states have changed so stop the loop
706 self.fill(&original_file, speculative_file, offset, derive_ctx)
709 /// Calculate the expected type and name of the cursor position.
710 fn expected_type_and_name(&self) -> (Option<Type>, Option<NameOrNameRef>) {
711 let mut node = match self.token.parent() {
713 None => return (None, None),
718 ast::LetStmt(it) => {
719 cov_mark::hit!(expected_type_let_with_leading_char);
720 cov_mark::hit!(expected_type_let_without_leading_char);
722 .and_then(|pat| self.sema.type_of_pat(&pat))
723 .or_else(|| it.initializer().and_then(|it| self.sema.type_of_expr(&it)))
724 .map(TypeInfo::original);
725 let name = match it.pat() {
726 Some(ast::Pat::IdentPat(ident)) => ident.name().map(NameOrNameRef::Name),
727 Some(_) | None => None,
732 ast::LetExpr(it) => {
733 cov_mark::hit!(expected_type_if_let_without_leading_char);
735 .and_then(|pat| self.sema.type_of_pat(&pat))
736 .or_else(|| it.expr().and_then(|it| self.sema.type_of_expr(&it)))
737 .map(TypeInfo::original);
741 cov_mark::hit!(expected_type_fn_param);
742 ActiveParameter::at_token(
746 let name = ap.ident().map(NameOrNameRef::Name);
747 let ty = if has_ref(&self.token) {
748 cov_mark::hit!(expected_type_fn_param_ref);
755 .unwrap_or((None, None))
757 ast::RecordExprFieldList(it) => {
758 // wouldn't try {} be nice...
760 if self.token.kind() == T![..]
761 || self.token.prev_token().map(|t| t.kind()) == Some(T![..])
763 cov_mark::hit!(expected_type_struct_func_update);
764 let record_expr = it.syntax().parent().and_then(ast::RecordExpr::cast)?;
765 let ty = self.sema.type_of_expr(&record_expr.into())?;
771 cov_mark::hit!(expected_type_struct_field_without_leading_char);
772 let expr_field = self.token.prev_sibling_or_token()?
774 .and_then(ast::RecordExprField::cast)?;
775 let (_, _, ty) = self.sema.resolve_record_field(&expr_field)?;
778 expr_field.field_name().map(NameOrNameRef::NameRef),
781 })().unwrap_or((None, None))
783 ast::RecordExprField(it) => {
784 if let Some(expr) = it.expr() {
785 cov_mark::hit!(expected_type_struct_field_with_leading_char);
787 self.sema.type_of_expr(&expr).map(TypeInfo::original),
788 it.field_name().map(NameOrNameRef::NameRef),
791 cov_mark::hit!(expected_type_struct_field_followed_by_comma);
792 let ty = self.sema.resolve_record_field(&it)
793 .map(|(_, _, ty)| ty);
796 it.field_name().map(NameOrNameRef::NameRef),
801 // match foo { ..., pat => $0 }
802 ast::MatchExpr(it) => {
803 let ty = if self.previous_token_is(T![=>]) {
804 // match foo { ..., pat => $0 }
805 cov_mark::hit!(expected_type_match_arm_body_without_leading_char);
806 cov_mark::hit!(expected_type_match_arm_body_with_leading_char);
807 self.sema.type_of_expr(&it.into())
810 cov_mark::hit!(expected_type_match_arm_without_leading_char);
811 it.expr().and_then(|e| self.sema.type_of_expr(&e))
812 }.map(TypeInfo::original);
816 let ty = it.condition()
817 .and_then(|e| self.sema.type_of_expr(&e))
818 .map(TypeInfo::original);
821 ast::IdentPat(it) => {
822 cov_mark::hit!(expected_type_if_let_with_leading_char);
823 cov_mark::hit!(expected_type_match_arm_with_leading_char);
824 let ty = self.sema.type_of_pat(&ast::Pat::from(it)).map(TypeInfo::original);
828 cov_mark::hit!(expected_type_fn_ret_with_leading_char);
829 cov_mark::hit!(expected_type_fn_ret_without_leading_char);
830 let def = self.sema.to_def(&it);
831 (def.map(|def| def.ret_type(self.db)), None)
833 ast::ClosureExpr(it) => {
834 let ty = self.sema.type_of_expr(&it.into());
835 ty.and_then(|ty| ty.original.as_callable(self.db))
836 .map(|c| (Some(c.return_type()), None))
837 .unwrap_or((None, None))
839 ast::ParamList(_) => (None, None),
840 ast::Stmt(_) => (None, None),
841 ast::Item(_) => (None, None),
843 match node.parent() {
848 None => (None, None),
856 /// Fill the completion context, this is what does semantic reasoning about the surrounding context
857 /// of the completion location.
860 original_file: &SyntaxNode,
861 file_with_fake_ident: SyntaxNode,
863 derive_ctx: Option<(SyntaxNode, SyntaxNode, TextSize, ast::Attr)>,
865 let fake_ident_token = file_with_fake_ident.token_at_offset(offset).right_biased()?;
866 let syntax_element = NodeOrToken::Token(fake_ident_token);
867 if is_in_token_of_for_loop(syntax_element.clone()) {
869 // there is nothing to complete here except `in` keyword
870 // don't bother populating the context
871 // FIXME: the completion calculations should end up good enough
872 // such that this special case becomes unnecessary
876 self.previous_token = previous_token(syntax_element.clone());
878 self.incomplete_let =
879 syntax_element.ancestors().take(6).find_map(ast::LetStmt::cast).map_or(false, |it| {
880 it.syntax().text_range().end() == syntax_element.text_range().end()
883 (self.expected_type, self.expected_name) = self.expected_type_and_name();
885 // Overwrite the path kind for derives
886 if let Some((original_file, file_with_fake_ident, offset, origin_attr)) = derive_ctx {
887 self.existing_derives = self
889 .resolve_derive_macro(&origin_attr)
895 if let Some(ast::NameLike::NameRef(name_ref)) =
896 find_node_at_offset(&file_with_fake_ident, offset)
898 let parent = name_ref.syntax().parent()?;
899 let (mut nameref_ctx, _) =
900 Self::classify_name_ref(&self.sema, &original_file, name_ref, parent);
901 if let Some(path_ctx) = &mut nameref_ctx.path_ctx {
902 path_ctx.kind = PathKind::Derive;
904 self.ident_ctx = IdentContext::NameRef(nameref_ctx);
910 let name_like = match find_node_at_offset(&file_with_fake_ident, offset) {
913 if let Some(original) = ast::String::cast(self.original_token.clone()) {
914 self.ident_ctx = IdentContext::String {
916 expanded: ast::String::cast(self.token.clone()),
919 // Fix up trailing whitespace problem
921 let token = if self.token.kind() == SyntaxKind::WHITESPACE {
922 self.previous_token.as_ref()?
926 let p = token.parent()?;
927 if p.kind() == SyntaxKind::TOKEN_TREE
928 && p.ancestors().any(|it| it.kind() == SyntaxKind::META)
930 self.ident_ctx = IdentContext::UnexpandedAttrTT {
931 fake_attribute_under_caret: syntax_element
933 .find_map(ast::Attr::cast),
942 self.completion_location =
943 determine_location(&self.sema, original_file, offset, &name_like);
944 self.prev_sibling = determine_prev_sibling(&name_like);
947 .token_ancestors_with_macros(self.token.clone())
948 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
949 .find_map(ast::Impl::cast);
950 self.function_def = self
952 .token_ancestors_with_macros(self.token.clone())
953 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
954 .find_map(ast::Fn::cast);
957 ast::NameLike::Lifetime(lifetime) => {
958 self.ident_ctx = IdentContext::Lifetime(Self::classify_lifetime(
964 ast::NameLike::NameRef(name_ref) => {
965 let parent = name_ref.syntax().parent()?;
966 let (nameref_ctx, pat_ctx) =
967 Self::classify_name_ref(&self.sema, &original_file, name_ref, parent.clone());
969 // Extract qualifiers
970 if let Some(path_ctx) = &nameref_ctx.path_ctx {
971 if path_ctx.qualifier.is_none() {
972 let top = match path_ctx.kind {
973 PathKind::Expr { in_block_expr: true, .. } => parent
975 .find(|it| ast::PathExpr::can_cast(it.kind()))
977 let parent = p.parent()?;
978 if ast::StmtList::can_cast(parent.kind()) {
980 } else if ast::ExprStmt::can_cast(parent.kind()) {
986 PathKind::Item { .. } => {
987 parent.ancestors().find(|it| ast::MacroCall::can_cast(it.kind()))
991 if let Some(top) = top {
992 if let Some(NodeOrToken::Node(error_node)) =
993 syntax::algo::non_trivia_sibling(
995 syntax::Direction::Prev,
998 if error_node.kind() == SyntaxKind::ERROR {
999 self.qualifier_ctx.unsafe_tok = error_node
1000 .children_with_tokens()
1001 .filter_map(NodeOrToken::into_token)
1002 .find(|it| it.kind() == T![unsafe]);
1003 self.qualifier_ctx.vis_node =
1004 error_node.children().find_map(ast::Visibility::cast);
1010 self.ident_ctx = IdentContext::NameRef(nameref_ctx);
1011 self.pattern_ctx = pat_ctx;
1013 ast::NameLike::Name(name) => {
1014 let (name_ctx, pat_ctx) = Self::classify_name(&self.sema, original_file, name)?;
1015 self.pattern_ctx = pat_ctx;
1016 self.ident_ctx = IdentContext::Name(name_ctx);
1022 fn classify_lifetime(
1023 _sema: &Semantics<RootDatabase>,
1024 original_file: &SyntaxNode,
1025 lifetime: ast::Lifetime,
1026 ) -> Option<LifetimeContext> {
1027 let parent = lifetime.syntax().parent()?;
1028 if parent.kind() == ERROR {
1032 let kind = match_ast! {
1034 ast::LifetimeParam(param) => LifetimeKind::LifetimeParam {
1035 is_decl: param.lifetime().as_ref() == Some(&lifetime),
1038 ast::BreakExpr(_) => LifetimeKind::LabelRef,
1039 ast::ContinueExpr(_) => LifetimeKind::LabelRef,
1040 ast::Label(_) => LifetimeKind::LabelDef,
1041 _ => LifetimeKind::Lifetime,
1044 let lifetime = find_node_at_offset(&original_file, lifetime.syntax().text_range().start());
1046 Some(LifetimeContext { lifetime, kind })
1050 _sema: &Semantics<RootDatabase>,
1051 original_file: &SyntaxNode,
1053 ) -> Option<(NameContext, Option<PatternContext>)> {
1054 let parent = name.syntax().parent()?;
1055 let mut pat_ctx = None;
1056 let kind = match_ast! {
1058 ast::Const(_) => NameKind::Const,
1059 ast::ConstParam(_) => NameKind::ConstParam,
1060 ast::Enum(_) => NameKind::Enum,
1061 ast::Fn(_) => NameKind::Function,
1062 ast::IdentPat(bind_pat) => {
1064 let mut pat_ctx = pattern_context_for(original_file, bind_pat.into());
1065 if let Some(record_field) = ast::RecordPatField::for_field_name(&name) {
1066 pat_ctx.record_pat = find_node_in_file_compensated(original_file, &record_field.parent_record_pat());
1073 ast::MacroDef(_) => NameKind::MacroDef,
1074 ast::MacroRules(_) => NameKind::MacroRules,
1075 ast::Module(module) => NameKind::Module(module),
1076 ast::RecordField(_) => NameKind::RecordField,
1077 ast::Rename(_) => NameKind::Rename,
1078 ast::SelfParam(_) => NameKind::SelfParam,
1079 ast::Static(_) => NameKind::Static,
1080 ast::Struct(_) => NameKind::Struct,
1081 ast::Trait(_) => NameKind::Trait,
1082 ast::TypeAlias(_) => NameKind::TypeAlias,
1083 ast::TypeParam(_) => NameKind::TypeParam,
1084 ast::Union(_) => NameKind::Union,
1085 ast::Variant(_) => NameKind::Variant,
1089 let name = find_node_at_offset(&original_file, name.syntax().text_range().start());
1090 Some((NameContext { name, kind }, pat_ctx))
1093 fn classify_name_ref(
1094 sema: &Semantics<RootDatabase>,
1095 original_file: &SyntaxNode,
1096 name_ref: ast::NameRef,
1098 ) -> (NameRefContext, Option<PatternContext>) {
1099 let nameref = find_node_at_offset(&original_file, name_ref.syntax().text_range().start());
1101 let mut nameref_ctx =
1102 NameRefContext { dot_access: None, path_ctx: None, nameref, record_expr: None };
1104 if let Some(record_field) = ast::RecordExprField::for_field_name(&name_ref) {
1105 nameref_ctx.record_expr =
1106 find_node_in_file_compensated(original_file, &record_field.parent_record_lit())
1108 return (nameref_ctx, None);
1110 if let Some(record_field) = ast::RecordPatField::for_field_name_ref(&name_ref) {
1112 pattern_context_for(original_file, record_field.parent_record_pat().clone().into());
1115 Some(PatternContext {
1117 has_type_ascription: false,
1120 record_pat: find_node_in_file_compensated(
1122 &record_field.parent_record_pat(),
1129 let segment = match_ast! {
1131 ast::PathSegment(segment) => segment,
1132 ast::FieldExpr(field) => {
1133 let receiver = find_in_original_file(field.expr(), original_file);
1134 let receiver_is_ambiguous_float_literal = match &receiver {
1135 Some(ast::Expr::Literal(l)) => matches! {
1137 ast::LiteralKind::FloatNumber { .. } if l.syntax().last_token().map_or(false, |it| it.text().ends_with('.'))
1141 nameref_ctx.dot_access = Some(DotAccess {
1142 receiver_ty: receiver.as_ref().and_then(|it| sema.type_of_expr(it)),
1143 kind: DotAccessKind::Field { receiver_is_ambiguous_float_literal },
1146 return (nameref_ctx, None);
1148 ast::MethodCallExpr(method) => {
1149 let receiver = find_in_original_file(method.receiver(), original_file);
1150 nameref_ctx.dot_access = Some(DotAccess {
1151 receiver_ty: receiver.as_ref().and_then(|it| sema.type_of_expr(it)),
1152 kind: DotAccessKind::Method { has_parens: method.arg_list().map_or(false, |it| it.l_paren_token().is_some()) },
1155 return (nameref_ctx, None);
1157 _ => return (nameref_ctx, None),
1161 let path = segment.parent_path();
1162 let mut path_ctx = PathCompletionCtx {
1163 has_call_parens: false,
1164 has_macro_bang: false,
1165 is_absolute_path: false,
1167 parent: path.parent_path(),
1168 kind: PathKind::Item { kind: ItemListKind::SourceFile },
1169 has_type_args: false,
1171 let mut pat_ctx = None;
1173 let is_in_block = |it: &SyntaxNode| {
1176 ast::ExprStmt::can_cast(node.kind()) || ast::StmtList::can_cast(node.kind())
1180 let mut fill_record_expr = |syn: &SyntaxNode| {
1181 if let Some(record_expr) = syn.ancestors().nth(2).and_then(ast::RecordExpr::cast) {
1182 nameref_ctx.record_expr =
1183 find_node_in_file_compensated(original_file, &record_expr).zip(Some(true));
1187 // We do not want to generate path completions when we are sandwiched between an item decl signature and its body.
1188 // ex. trait Foo $0 {}
1189 // in these cases parser recovery usually kicks in for our inserted identifier, causing it
1190 // to either be parsed as an ExprStmt or a MacroCall, depending on whether it is in a block
1191 // expression or an item list.
1192 // The following code checks if the body is missing, if it is we either cut off the body
1193 // from the item or it was missing in the first place
1194 let inbetween_body_and_decl_check = |node: SyntaxNode| {
1195 if let Some(NodeOrToken::Node(n)) =
1196 syntax::algo::non_trivia_sibling(node.into(), syntax::Direction::Prev)
1198 if let Some(item) = ast::Item::cast(n) {
1200 ast::Item::Const(it) => it.body().is_none(),
1201 ast::Item::Enum(it) => it.variant_list().is_none(),
1202 ast::Item::ExternBlock(it) => it.extern_item_list().is_none(),
1203 ast::Item::Fn(it) => it.body().is_none(),
1204 ast::Item::Impl(it) => it.assoc_item_list().is_none(),
1205 ast::Item::Module(it) => it.item_list().is_none(),
1206 ast::Item::Static(it) => it.body().is_none(),
1207 ast::Item::Struct(it) => it.field_list().is_none(),
1208 ast::Item::Trait(it) => it.assoc_item_list().is_none(),
1209 ast::Item::TypeAlias(it) => it.ty().is_none(),
1210 ast::Item::Union(it) => it.record_field_list().is_none(),
1221 let kind = path.syntax().ancestors().find_map(|it| {
1222 // using Option<Option<PathKind>> as extra controlflow
1223 let kind = match_ast! {
1225 ast::PathType(_) => Some(PathKind::Type),
1226 ast::PathExpr(it) => {
1227 if let Some(p) = it.syntax().parent() {
1228 if ast::ExprStmt::can_cast(p.kind()) {
1229 if inbetween_body_and_decl_check(p) {
1235 fill_record_expr(it.syntax());
1237 path_ctx.has_call_parens = it.syntax().parent().map_or(false, |it| ast::CallExpr::can_cast(it.kind()));
1238 let in_block_expr = is_in_block(it.syntax());
1239 let in_loop_body = is_in_loop_body(it.syntax());
1240 Some(PathKind::Expr { in_block_expr, in_loop_body })
1242 ast::TupleStructPat(it) => {
1243 path_ctx.has_call_parens = true;
1244 pat_ctx = Some(pattern_context_for(original_file, it.into()));
1247 ast::RecordPat(it) => {
1248 path_ctx.has_call_parens = true;
1249 pat_ctx = Some(pattern_context_for(original_file, it.into()));
1252 ast::PathPat(it) => {
1253 pat_ctx = Some(pattern_context_for(original_file, it.into()));
1256 ast::MacroCall(it) => {
1257 if inbetween_body_and_decl_check(it.syntax().clone()) {
1261 path_ctx.has_macro_bang = it.excl_token().is_some();
1262 let parent = it.syntax().parent();
1263 match parent.as_ref().map(|it| it.kind()) {
1264 Some(SyntaxKind::MACRO_PAT) => Some(PathKind::Pat),
1265 Some(SyntaxKind::MACRO_TYPE) => Some(PathKind::Type),
1266 Some(SyntaxKind::ITEM_LIST) => Some(PathKind::Item { kind: ItemListKind::Module }),
1267 Some(SyntaxKind::ASSOC_ITEM_LIST) => Some(PathKind::Item { kind: match parent.and_then(|it| it.parent()) {
1268 Some(it) => match_ast! {
1270 ast::Trait(_) => ItemListKind::Trait,
1271 ast::Impl(it) => if it.trait_().is_some() {
1272 ItemListKind::TraitImpl
1276 _ => return Some(None)
1279 None => return Some(None),
1281 Some(SyntaxKind::EXTERN_ITEM_LIST) => Some(PathKind::Item { kind: ItemListKind::ExternBlock }),
1282 Some(SyntaxKind::SOURCE_FILE) => Some(PathKind::Item { kind: ItemListKind::SourceFile }),
1284 return Some(parent.and_then(ast::MacroExpr::cast).map(|it| {
1285 let in_loop_body = is_in_loop_body(it.syntax());
1286 let in_block_expr = is_in_block(it.syntax());
1287 fill_record_expr(it.syntax());
1288 PathKind::Expr { in_block_expr, in_loop_body }
1293 ast::Meta(meta) => (|| {
1294 let attr = meta.parent_attr()?;
1295 let kind = attr.kind();
1296 let attached = attr.syntax().parent()?;
1297 let is_trailing_outer_attr = kind != AttrKind::Inner
1298 && non_trivia_sibling(attr.syntax().clone().into(), syntax::Direction::Next).is_none();
1299 let annotated_item_kind = if is_trailing_outer_attr {
1302 Some(attached.kind())
1304 Some(PathKind::Attr {
1306 annotated_item_kind,
1309 ast::Visibility(it) => Some(PathKind::Vis { has_in_token: it.in_token().is_some() }),
1310 ast::UseTree(_) => Some(PathKind::Use),
1311 ast::ItemList(_) => Some(PathKind::Item { kind: ItemListKind::Module }),
1312 ast::AssocItemList(it) => Some(PathKind::Item { kind: {
1314 match (it.syntax().parent()?) {
1315 ast::Trait(_) => ItemListKind::Trait,
1316 ast::Impl(it) => if it.trait_().is_some() {
1317 ItemListKind::TraitImpl
1325 ast::ExternItemList(_) => Some(PathKind::Item { kind: ItemListKind::ExternBlock }),
1326 ast::SourceFile(_) => Some(PathKind::Item { kind: ItemListKind::SourceFile }),
1333 Some(kind) => path_ctx.kind = kind,
1334 None => return (nameref_ctx, pat_ctx),
1336 path_ctx.has_type_args = segment.generic_arg_list().is_some();
1338 if let Some((path, use_tree_parent)) = path_or_use_tree_qualifier(&path) {
1339 if !use_tree_parent {
1340 path_ctx.is_absolute_path =
1341 path.top_path().segment().map_or(false, |it| it.coloncolon_token().is_some());
1346 .and_then(|it| find_node_in_file(original_file, &it))
1347 .map(|it| it.parent_path());
1348 path_ctx.qualifier = path.map(|path| {
1349 let res = sema.resolve_path(&path);
1350 let is_super_chain = iter::successors(Some(path.clone()), |p| p.qualifier())
1351 .all(|p| p.segment().and_then(|s| s.super_token()).is_some());
1354 let is_infer_qualifier = path.qualifier().is_none()
1356 path.segment().and_then(|it| it.kind()),
1357 Some(ast::PathSegmentKind::Type {
1358 type_ref: Some(ast::Type::InferType(_)),
1371 } else if let Some(segment) = path.segment() {
1372 if segment.coloncolon_token().is_some() {
1373 path_ctx.is_absolute_path = true;
1376 nameref_ctx.path_ctx = Some(path_ctx);
1377 (nameref_ctx, pat_ctx)
1381 fn pattern_context_for(original_file: &SyntaxNode, pat: ast::Pat) -> PatternContext {
1382 let mut is_param = None;
1383 let (refutability, has_type_ascription) =
1387 .skip_while(|it| ast::Pat::can_cast(it.kind()))
1389 .map_or((PatternRefutability::Irrefutable, false), |node| {
1390 let refutability = match_ast! {
1392 ast::LetStmt(let_) => return (PatternRefutability::Irrefutable, let_.ty().is_some()),
1393 ast::Param(param) => {
1394 let has_type_ascription = param.ty().is_some();
1396 let fake_param_list = param.syntax().parent().and_then(ast::ParamList::cast)?;
1397 let param_list = find_node_in_file_compensated(original_file, &fake_param_list)?;
1398 let param_list_owner = param_list.syntax().parent()?;
1399 let kind = match_ast! {
1400 match param_list_owner {
1401 ast::ClosureExpr(closure) => ParamKind::Closure(closure),
1402 ast::Fn(fn_) => ParamKind::Function(fn_),
1406 Some((param_list, param, kind))
1408 return (PatternRefutability::Irrefutable, has_type_ascription)
1410 ast::MatchArm(_) => PatternRefutability::Refutable,
1411 ast::LetExpr(_) => PatternRefutability::Refutable,
1412 ast::ForExpr(_) => PatternRefutability::Irrefutable,
1413 _ => PatternRefutability::Irrefutable,
1416 (refutability, false)
1418 let (ref_token, mut_token) = match &pat {
1419 ast::Pat::IdentPat(it) => (it.ref_token(), it.mut_token()),
1424 param_ctx: is_param,
1425 has_type_ascription,
1426 parent_pat: pat.syntax().parent().and_then(ast::Pat::cast),
1433 fn find_in_original_file<N: AstNode>(x: Option<N>, original_file: &SyntaxNode) -> Option<N> {
1434 fn find_node_with_range<N: AstNode>(syntax: &SyntaxNode, range: TextRange) -> Option<N> {
1435 let range = syntax.text_range().intersect(range)?;
1436 syntax.covering_element(range).ancestors().find_map(N::cast)
1438 x.map(|e| e.syntax().text_range()).and_then(|r| find_node_with_range(original_file, r))
1441 /// Attempts to find `node` inside `syntax` via `node`'s text range.
1442 fn find_node_in_file<N: AstNode>(syntax: &SyntaxNode, node: &N) -> Option<N> {
1443 let syntax_range = syntax.text_range();
1444 let range = node.syntax().text_range();
1445 let intersection = range.intersect(syntax_range)?;
1446 syntax.covering_element(intersection).ancestors().find_map(N::cast)
1449 /// Attempts to find `node` inside `syntax` via `node`'s text range while compensating
1450 /// for the offset introduced by the fake ident.
1451 /// This is wrong if `node` comes before the insertion point! Use `find_node_in_file` instead.
1452 fn find_node_in_file_compensated<N: AstNode>(syntax: &SyntaxNode, node: &N) -> Option<N> {
1453 let syntax_range = syntax.text_range();
1454 let range = node.syntax().text_range();
1455 let end = range.end().checked_sub(TextSize::try_from(COMPLETION_MARKER.len()).ok()?)?;
1456 if end < range.start() {
1459 let range = TextRange::new(range.start(), end);
1460 // our inserted ident could cause `range` to be go outside of the original syntax, so cap it
1461 let intersection = range.intersect(syntax_range)?;
1462 syntax.covering_element(intersection).ancestors().find_map(N::cast)
1465 fn path_or_use_tree_qualifier(path: &ast::Path) -> Option<(ast::Path, bool)> {
1466 if let Some(qual) = path.qualifier() {
1467 return Some((qual, false));
1469 let use_tree_list = path.syntax().ancestors().find_map(ast::UseTreeList::cast)?;
1470 let use_tree = use_tree_list.syntax().parent().and_then(ast::UseTree::cast)?;
1471 Some((use_tree.path()?, true))
1474 fn has_ref(token: &SyntaxToken) -> bool {
1475 let mut token = token.clone();
1476 for skip in [IDENT, WHITESPACE, T![mut]] {
1477 if token.kind() == skip {
1478 token = match token.prev_token() {
1480 None => return false,
1484 token.kind() == T![&]
1487 const OP_TRAIT_LANG_NAMES: &[&str] = &[
1522 use expect_test::{expect, Expect};
1523 use hir::HirDisplay;
1525 use crate::tests::{position, TEST_CONFIG};
1527 use super::CompletionContext;
1529 fn check_expected_type_and_name(ra_fixture: &str, expect: Expect) {
1530 let (db, pos) = position(ra_fixture);
1531 let config = TEST_CONFIG;
1532 let completion_context = CompletionContext::new(&db, pos, &config).unwrap();
1534 let ty = completion_context
1536 .map(|t| t.display_test(&db).to_string())
1537 .unwrap_or("?".to_owned());
1539 let name = completion_context
1541 .map_or_else(|| "?".to_owned(), |name| name.to_string());
1543 expect.assert_eq(&format!("ty: {}, name: {}", ty, name));
1547 fn expected_type_let_without_leading_char() {
1548 cov_mark::check!(expected_type_let_without_leading_char);
1549 check_expected_type_and_name(
1555 expect![[r#"ty: u32, name: x"#]],
1560 fn expected_type_let_with_leading_char() {
1561 cov_mark::check!(expected_type_let_with_leading_char);
1562 check_expected_type_and_name(
1568 expect![[r#"ty: u32, name: x"#]],
1573 fn expected_type_let_pat() {
1574 check_expected_type_and_name(
1580 expect![[r#"ty: u32, name: ?"#]],
1582 check_expected_type_and_name(
1588 expect![[r#"ty: u32, name: ?"#]],
1593 fn expected_type_fn_param() {
1594 cov_mark::check!(expected_type_fn_param);
1595 check_expected_type_and_name(
1597 fn foo() { bar($0); }
1600 expect![[r#"ty: u32, name: x"#]],
1602 check_expected_type_and_name(
1604 fn foo() { bar(c$0); }
1607 expect![[r#"ty: u32, name: x"#]],
1612 fn expected_type_fn_param_ref() {
1613 cov_mark::check!(expected_type_fn_param_ref);
1614 check_expected_type_and_name(
1616 fn foo() { bar(&$0); }
1619 expect![[r#"ty: u32, name: x"#]],
1621 check_expected_type_and_name(
1623 fn foo() { bar(&mut $0); }
1624 fn bar(x: &mut u32) {}
1626 expect![[r#"ty: u32, name: x"#]],
1628 check_expected_type_and_name(
1630 fn foo() { bar(& c$0); }
1633 expect![[r#"ty: u32, name: x"#]],
1635 check_expected_type_and_name(
1637 fn foo() { bar(&mut c$0); }
1638 fn bar(x: &mut u32) {}
1640 expect![[r#"ty: u32, name: x"#]],
1642 check_expected_type_and_name(
1644 fn foo() { bar(&c$0); }
1647 expect![[r#"ty: u32, name: x"#]],
1652 fn expected_type_struct_field_without_leading_char() {
1653 cov_mark::check!(expected_type_struct_field_without_leading_char);
1654 check_expected_type_and_name(
1656 struct Foo { a: u32 }
1661 expect![[r#"ty: u32, name: a"#]],
1666 fn expected_type_struct_field_followed_by_comma() {
1667 cov_mark::check!(expected_type_struct_field_followed_by_comma);
1668 check_expected_type_and_name(
1670 struct Foo { a: u32 }
1675 expect![[r#"ty: u32, name: a"#]],
1680 fn expected_type_generic_struct_field() {
1681 check_expected_type_and_name(
1683 struct Foo<T> { a: T }
1684 fn foo() -> Foo<u32> {
1688 expect![[r#"ty: u32, name: a"#]],
1693 fn expected_type_struct_field_with_leading_char() {
1694 cov_mark::check!(expected_type_struct_field_with_leading_char);
1695 check_expected_type_and_name(
1697 struct Foo { a: u32 }
1702 expect![[r#"ty: u32, name: a"#]],
1707 fn expected_type_match_arm_without_leading_char() {
1708 cov_mark::check!(expected_type_match_arm_without_leading_char);
1709 check_expected_type_and_name(
1716 expect![[r#"ty: E, name: ?"#]],
1721 fn expected_type_match_arm_with_leading_char() {
1722 cov_mark::check!(expected_type_match_arm_with_leading_char);
1723 check_expected_type_and_name(
1730 expect![[r#"ty: E, name: ?"#]],
1735 fn expected_type_match_arm_body_without_leading_char() {
1736 cov_mark::check!(expected_type_match_arm_body_without_leading_char);
1737 check_expected_type_and_name(
1742 match E::X { E::X => $0 }
1745 expect![[r#"ty: Foo, name: ?"#]],
1750 fn expected_type_match_body_arm_with_leading_char() {
1751 cov_mark::check!(expected_type_match_arm_body_with_leading_char);
1752 check_expected_type_and_name(
1757 match E::X { E::X => c$0 }
1760 expect![[r#"ty: Foo, name: ?"#]],
1765 fn expected_type_if_let_without_leading_char() {
1766 cov_mark::check!(expected_type_if_let_without_leading_char);
1767 check_expected_type_and_name(
1769 enum Foo { Bar, Baz, Quux }
1776 expect![[r#"ty: Foo, name: ?"#]],
1781 fn expected_type_if_let_with_leading_char() {
1782 cov_mark::check!(expected_type_if_let_with_leading_char);
1783 check_expected_type_and_name(
1785 enum Foo { Bar, Baz, Quux }
1792 expect![[r#"ty: Foo, name: ?"#]],
1797 fn expected_type_fn_ret_without_leading_char() {
1798 cov_mark::check!(expected_type_fn_ret_without_leading_char);
1799 check_expected_type_and_name(
1805 expect![[r#"ty: u32, name: ?"#]],
1810 fn expected_type_fn_ret_with_leading_char() {
1811 cov_mark::check!(expected_type_fn_ret_with_leading_char);
1812 check_expected_type_and_name(
1818 expect![[r#"ty: u32, name: ?"#]],
1823 fn expected_type_fn_ret_fn_ref_fully_typed() {
1824 check_expected_type_and_name(
1830 expect![[r#"ty: u32, name: ?"#]],
1835 fn expected_type_closure_param_return() {
1836 // FIXME: make this work with `|| $0`
1837 check_expected_type_and_name(
1844 fn bar(f: impl FnOnce() -> u32) {}
1846 expect![[r#"ty: u32, name: ?"#]],
1851 fn expected_type_generic_function() {
1852 check_expected_type_and_name(
1860 expect![[r#"ty: u32, name: t"#]],
1865 fn expected_type_generic_method() {
1866 check_expected_type_and_name(
1874 fn bar(self, t: T) {}
1877 expect![[r#"ty: u32, name: t"#]],
1882 fn expected_type_functional_update() {
1883 cov_mark::check!(expected_type_struct_func_update);
1884 check_expected_type_and_name(
1886 struct Foo { field: u32 }
1893 expect![[r#"ty: Foo, name: ?"#]],
1898 fn expected_type_param_pat() {
1899 check_expected_type_and_name(
1901 struct Foo { field: u32 }
1904 expect![[r#"ty: Foo, name: ?"#]],
1906 check_expected_type_and_name(
1908 struct Foo { field: u32 }
1911 // FIXME make this work, currently fails due to pattern recovery eating the `:`
1912 expect![[r#"ty: ?, name: ?"#]],