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 {
51 in_functional_update: bool,
56 annotated_item_kind: Option<SyntaxKind>,
59 /// Path in item position, that is inside an (Assoc)ItemList
70 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
71 pub(super) enum ItemListKind {
80 pub(crate) struct PathCompletionCtx {
81 /// If this is a call with () already there (or {} in case of record patterns)
82 pub(super) has_call_parens: bool,
83 /// If this has a macro call bang !
84 pub(super) has_macro_bang: bool,
85 /// Whether this path stars with a `::`.
86 pub(super) is_absolute_path: bool,
87 /// The qualifier of the current path if it exists.
88 pub(super) qualifier: Option<PathQualifierCtx>,
91 /// The parent of the path we are completing.
92 pub(super) parent: Option<ast::Path>,
93 pub(super) kind: PathKind,
94 /// Whether the path segment has type args or not.
95 pub(super) has_type_args: bool,
99 pub(crate) struct PathQualifierCtx {
100 pub(crate) path: ast::Path,
101 pub(crate) resolution: Option<PathResolution>,
102 /// Whether this path consists solely of `super` segments
103 pub(crate) is_super_chain: bool,
104 /// Whether the qualifier comes from a use tree parent or not
105 pub(crate) use_tree_parent: bool,
107 pub(crate) is_infer_qualifier: bool,
111 pub(super) struct PatternContext {
112 pub(super) refutability: PatternRefutability,
113 pub(super) param_ctx: Option<(ast::ParamList, ast::Param, ParamKind)>,
114 pub(super) has_type_ascription: bool,
115 pub(super) parent_pat: Option<ast::Pat>,
116 pub(super) ref_token: Option<SyntaxToken>,
117 pub(super) mut_token: Option<SyntaxToken>,
121 pub(super) struct LifetimeContext {
122 pub(super) lifetime: Option<ast::Lifetime>,
123 pub(super) kind: LifetimeKind,
127 pub(super) enum LifetimeKind {
128 LifetimeParam { is_decl: bool, param: ast::LifetimeParam },
135 pub(super) struct NameContext {
137 pub(super) name: Option<ast::Name>,
138 pub(super) kind: NameKind,
143 pub(super) enum NameKind {
166 pub(super) struct NameRefContext {
167 /// NameRef syntax in the original file
168 pub(super) nameref: Option<ast::NameRef>,
169 pub(super) dot_access: Option<DotAccess>,
170 pub(super) path_ctx: Option<PathCompletionCtx>,
174 pub(super) enum IdentContext {
176 NameRef(NameRefContext),
177 Lifetime(LifetimeContext),
178 /// Original token, fake token
180 original: ast::String,
181 expanded: Option<ast::String>,
184 fake_attribute_under_caret: Option<ast::Attr>,
189 pub(super) enum DotAccess {
191 receiver: Option<ast::Expr>,
192 /// True if the receiver is an integer and there is no ident in the original file after it yet
194 receiver_is_ambiguous_float_literal: bool,
197 receiver: Option<ast::Expr>,
202 #[derive(Clone, Debug, PartialEq, Eq)]
203 pub(crate) enum ParamKind {
205 Closure(ast::ClosureExpr),
208 /// `CompletionContext` is created early during completion to figure out, where
209 /// exactly is the cursor, syntax-wise.
211 pub(crate) struct CompletionContext<'a> {
212 pub(super) sema: Semantics<'a, RootDatabase>,
213 pub(super) scope: SemanticsScope<'a>,
214 pub(super) db: &'a RootDatabase,
215 pub(super) config: &'a CompletionConfig,
216 pub(super) position: FilePosition,
218 /// The token before the cursor, in the original file.
219 pub(super) original_token: SyntaxToken,
220 /// The token before the cursor, in the macro-expanded file.
221 pub(super) token: SyntaxToken,
222 /// The crate of the current file.
223 pub(super) krate: hir::Crate,
224 /// The module of the `scope`.
225 pub(super) module: hir::Module,
227 /// The expected name of what we are completing.
228 /// This is usually the parameter name of the function argument we are completing.
229 pub(super) expected_name: Option<NameOrNameRef>,
230 /// The expected type of what we are completing.
231 pub(super) expected_type: Option<Type>,
233 /// The parent function of the cursor position if it exists.
234 pub(super) function_def: Option<ast::Fn>,
235 /// The parent impl of the cursor position if it exists.
236 pub(super) impl_def: Option<ast::Impl>,
237 /// Are we completing inside a let statement with a missing semicolon?
238 pub(super) incomplete_let: bool,
240 pub(super) completion_location: Option<ImmediateLocation>,
241 pub(super) prev_sibling: Option<ImmediatePrevSibling>,
242 pub(super) previous_token: Option<SyntaxToken>,
244 pub(super) ident_ctx: IdentContext,
246 pub(super) pattern_ctx: Option<PatternContext>,
248 pub(super) existing_derives: FxHashSet<hir::Macro>,
250 pub(super) locals: FxHashMap<Name, Local>,
253 impl<'a> CompletionContext<'a> {
254 /// The range of the identifier that is being completed.
255 pub(crate) fn source_range(&self) -> TextRange {
256 // check kind of macro-expanded token, but use range of original token
257 let kind = self.token.kind();
260 // assume we are completing a lifetime but the user has only typed the '
261 cov_mark::hit!(completes_if_lifetime_without_idents);
262 TextRange::at(self.original_token.text_range().start(), TextSize::from(1))
264 IDENT | LIFETIME_IDENT | UNDERSCORE => self.original_token.text_range(),
265 _ if kind.is_keyword() => self.original_token.text_range(),
266 _ => TextRange::empty(self.position.offset),
270 pub(crate) fn previous_token_is(&self, kind: SyntaxKind) -> bool {
271 self.previous_token.as_ref().map_or(false, |tok| tok.kind() == kind)
274 pub(crate) fn famous_defs(&self) -> FamousDefs {
275 FamousDefs(&self.sema, self.krate)
278 pub(super) fn nameref_ctx(&self) -> Option<&NameRefContext> {
279 match &self.ident_ctx {
280 IdentContext::NameRef(it) => Some(it),
285 pub(super) fn name_ctx(&self) -> Option<&NameContext> {
286 match &self.ident_ctx {
287 IdentContext::Name(it) => Some(it),
292 pub(super) fn lifetime_ctx(&self) -> Option<&LifetimeContext> {
293 match &self.ident_ctx {
294 IdentContext::Lifetime(it) => Some(it),
299 pub(crate) fn dot_receiver(&self) -> Option<&ast::Expr> {
300 match self.nameref_ctx() {
301 Some(NameRefContext {
303 Some(DotAccess::Method { receiver, .. } | DotAccess::Field { receiver, .. }),
305 }) => receiver.as_ref(),
310 pub(crate) fn has_dot_receiver(&self) -> bool {
311 self.dot_receiver().is_some()
314 pub(crate) fn expects_assoc_item(&self) -> bool {
315 matches!(self.completion_location, Some(ImmediateLocation::Trait | ImmediateLocation::Impl))
318 pub(crate) fn expects_variant(&self) -> bool {
319 matches!(self.name_ctx(), Some(NameContext { kind: NameKind::Variant, .. }))
322 pub(crate) fn expects_non_trait_assoc_item(&self) -> bool {
323 matches!(self.completion_location, Some(ImmediateLocation::Impl))
326 pub(crate) fn expects_item(&self) -> bool {
327 matches!(self.completion_location, Some(ImmediateLocation::ItemList))
330 // FIXME: This shouldn't exist
331 pub(crate) fn expects_generic_arg(&self) -> bool {
332 matches!(self.completion_location, Some(ImmediateLocation::GenericArgList(_)))
335 pub(crate) fn has_block_expr_parent(&self) -> bool {
336 matches!(self.completion_location, Some(ImmediateLocation::StmtList))
339 pub(crate) fn expects_ident_ref_expr(&self) -> bool {
340 matches!(self.completion_location, Some(ImmediateLocation::RefExpr))
343 pub(crate) fn expect_field(&self) -> bool {
344 matches!(self.completion_location, Some(ImmediateLocation::TupleField))
345 || matches!(self.name_ctx(), Some(NameContext { kind: NameKind::RecordField, .. }))
348 /// Whether the cursor is right after a trait or impl header.
349 /// trait Foo ident$0
350 // FIXME: This probably shouldn't exist
351 pub(crate) fn has_unfinished_impl_or_trait_prev_sibling(&self) -> bool {
354 Some(ImmediatePrevSibling::ImplDefType | ImmediatePrevSibling::TraitDefName)
358 // FIXME: This probably shouldn't exist
359 pub(crate) fn has_impl_prev_sibling(&self) -> bool {
360 matches!(self.prev_sibling, Some(ImmediatePrevSibling::ImplDefType))
363 pub(crate) fn has_visibility_prev_sibling(&self) -> bool {
364 matches!(self.prev_sibling, Some(ImmediatePrevSibling::Visibility))
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.previous_token_is(T![unsafe])
376 Some(ImmediatePrevSibling::Attribute | ImmediatePrevSibling::Visibility)
379 self.completion_location,
380 Some(ImmediateLocation::RecordPat(_) | ImmediateLocation::RecordExpr(_))
384 Some(NameContext { kind: NameKind::Module(_) | NameKind::Rename, .. })
388 pub(crate) fn path_context(&self) -> Option<&PathCompletionCtx> {
389 self.nameref_ctx().and_then(|ctx| ctx.path_ctx.as_ref())
392 pub(crate) fn expects_expression(&self) -> bool {
393 matches!(self.path_context(), Some(PathCompletionCtx { kind: PathKind::Expr { .. }, .. }))
396 pub(crate) fn is_non_trivial_path(&self) -> bool {
400 PathCompletionCtx { is_absolute_path: true, .. }
401 | PathCompletionCtx { qualifier: Some(_), .. }
406 pub(crate) fn path_qual(&self) -> Option<&ast::Path> {
407 self.path_context().and_then(|it| it.qualifier.as_ref().map(|it| &it.path))
410 pub(crate) fn path_kind(&self) -> Option<PathKind> {
411 self.path_context().map(|it| it.kind)
414 /// Checks if an item is visible and not `doc(hidden)` at the completion site.
415 pub(crate) fn is_visible<I>(&self, item: &I) -> Visible
417 I: hir::HasVisibility + hir::HasAttrs + hir::HasCrate + Copy,
419 self.is_visible_impl(&item.visibility(self.db), &item.attrs(self.db), item.krate(self.db))
422 pub(crate) fn is_scope_def_hidden(&self, scope_def: ScopeDef) -> bool {
423 if let (Some(attrs), Some(krate)) = (scope_def.attrs(self.db), scope_def.krate(self.db)) {
424 return self.is_doc_hidden(&attrs, krate);
430 /// Check if an item is `#[doc(hidden)]`.
431 pub(crate) fn is_item_hidden(&self, item: &hir::ItemInNs) -> bool {
432 let attrs = item.attrs(self.db);
433 let krate = item.krate(self.db);
434 match (attrs, krate) {
435 (Some(attrs), Some(krate)) => self.is_doc_hidden(&attrs, krate),
439 /// Whether the given trait is an operator trait or not.
440 pub(crate) fn is_ops_trait(&self, trait_: hir::Trait) -> bool {
441 match trait_.attrs(self.db).lang() {
442 Some(lang) => OP_TRAIT_LANG_NAMES.contains(&lang.as_str()),
447 /// Returns the traits in scope, with the [`Drop`] trait removed.
448 pub(crate) fn traits_in_scope(&self) -> hir::VisibleTraits {
449 let mut traits_in_scope = self.scope.visible_traits();
450 if let Some(drop) = self.famous_defs().core_ops_Drop() {
451 traits_in_scope.0.remove(&drop.into());
456 /// A version of [`SemanticsScope::process_all_names`] that filters out `#[doc(hidden)]` items.
457 pub(crate) fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
458 let _p = profile::span("CompletionContext::process_all_names");
459 self.scope.process_all_names(&mut |name, def| {
460 if self.is_scope_def_hidden(def) {
468 pub(crate) fn process_all_names_raw(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
469 let _p = profile::span("CompletionContext::process_all_names_raw");
470 self.scope.process_all_names(&mut |name, def| f(name, def));
475 vis: &hir::Visibility,
477 defining_crate: hir::Crate,
479 if !vis.is_visible_from(self.db, self.module.into()) {
480 if !self.config.enable_private_editable {
483 // If the definition location is editable, also show private items
484 let root_file = defining_crate.root_file(self.db);
485 let source_root_id = self.db.file_source_root(root_file);
486 let is_editable = !self.db.source_root(source_root_id).is_library;
487 return if is_editable { Visible::Editable } else { Visible::No };
490 if self.is_doc_hidden(attrs, defining_crate) {
497 fn is_doc_hidden(&self, attrs: &hir::Attrs, defining_crate: hir::Crate) -> bool {
498 // `doc(hidden)` items are only completed within the defining crate.
499 self.krate != defining_crate && attrs.has_doc_hidden()
503 // CompletionContext construction
504 impl<'a> CompletionContext<'a> {
506 db: &'a RootDatabase,
507 position @ FilePosition { file_id, offset }: FilePosition,
508 config: &'a CompletionConfig,
509 ) -> Option<CompletionContext<'a>> {
510 let _p = profile::span("CompletionContext::new");
511 let sema = Semantics::new(db);
513 let original_file = sema.parse(file_id);
515 // Insert a fake ident to get a valid parse tree. We will use this file
516 // to determine context, though the original_file will be used for
517 // actual completion.
518 let file_with_fake_ident = {
519 let parse = db.parse(file_id);
520 let edit = Indel::insert(offset, COMPLETION_MARKER.to_string());
521 parse.reparse(&edit).tree()
523 let fake_ident_token =
524 file_with_fake_ident.syntax().token_at_offset(offset).right_biased()?;
526 let original_token = original_file.syntax().token_at_offset(offset).left_biased()?;
527 let token = sema.descend_into_macros_single(original_token.clone());
528 let scope = sema.scope_at_offset(&token.parent()?, offset)?;
529 let krate = scope.krate();
530 let module = scope.module();
532 let mut locals = FxHashMap::default();
533 scope.process_all_names(&mut |name, scope| {
534 if let ScopeDef::Local(local) = scope {
535 locals.insert(name, local);
539 let mut ctx = CompletionContext {
553 incomplete_let: false,
554 completion_location: None,
556 previous_token: None,
557 // dummy value, will be overwritten
558 ident_ctx: IdentContext::UnexpandedAttrTT { fake_attribute_under_caret: None },
560 existing_derives: Default::default(),
564 original_file.syntax().clone(),
565 file_with_fake_ident.syntax().clone(),
572 /// Expand attributes and macro calls at the current cursor position for both the original file
573 /// and fake file repeatedly. As soon as one of the two expansions fail we stop so the original
574 /// and speculative states stay in sync.
577 mut original_file: SyntaxNode,
578 mut speculative_file: SyntaxNode,
579 mut offset: TextSize,
580 mut fake_ident_token: SyntaxToken,
582 let _p = profile::span("CompletionContext::expand_and_fill");
583 let mut derive_ctx = None;
587 |item: &ast::Item| item.syntax().ancestors().skip(1).find_map(ast::Item::cast);
588 let ancestor_items = iter::successors(
590 find_node_at_offset::<ast::Item>(&original_file, offset),
591 find_node_at_offset::<ast::Item>(&speculative_file, offset),
593 |(a, b)| parent_item(a).zip(parent_item(b)),
596 // first try to expand attributes as these are always the outermost macro calls
597 'ancestors: for (actual_item, item_with_fake_ident) in ancestor_items {
599 self.sema.expand_attr_macro(&actual_item),
600 self.sema.speculative_expand_attr_macro(
602 &item_with_fake_ident,
603 fake_ident_token.clone(),
606 // maybe parent items have attributes, so continue walking the ancestors
607 (None, None) => continue 'ancestors,
608 // successful expansions
609 (Some(actual_expansion), Some((fake_expansion, fake_mapped_token))) => {
610 let new_offset = fake_mapped_token.text_range().start();
611 if new_offset > actual_expansion.text_range().end() {
612 // offset outside of bounds from the original expansion,
613 // stop here to prevent problems from happening
616 original_file = actual_expansion;
617 speculative_file = fake_expansion;
618 fake_ident_token = fake_mapped_token;
622 // exactly one expansion failed, inconsistent state so stop expanding completely
623 _ => break 'expansion,
627 // No attributes have been expanded, so look for macro_call! token trees or derive token trees
628 let orig_tt = match find_node_at_offset::<ast::TokenTree>(&original_file, offset) {
630 None => break 'expansion,
632 let spec_tt = match find_node_at_offset::<ast::TokenTree>(&speculative_file, offset) {
634 None => break 'expansion,
637 // Expand pseudo-derive expansion
638 if let (Some(orig_attr), Some(spec_attr)) = (
639 orig_tt.syntax().parent().and_then(ast::Meta::cast).and_then(|it| it.parent_attr()),
640 spec_tt.syntax().parent().and_then(ast::Meta::cast).and_then(|it| it.parent_attr()),
642 if let (Some(actual_expansion), Some((fake_expansion, fake_mapped_token))) = (
643 self.sema.expand_derive_as_pseudo_attr_macro(&orig_attr),
644 self.sema.speculative_expand_derive_as_pseudo_attr_macro(
647 fake_ident_token.clone(),
653 fake_mapped_token.text_range().start(),
657 // at this point we won't have any more successful expansions, so stop
661 // Expand fn-like macro calls
662 if let (Some(actual_macro_call), Some(macro_call_with_fake_ident)) = (
663 orig_tt.syntax().ancestors().find_map(ast::MacroCall::cast),
664 spec_tt.syntax().ancestors().find_map(ast::MacroCall::cast),
666 let mac_call_path0 = actual_macro_call.path().as_ref().map(|s| s.syntax().text());
668 macro_call_with_fake_ident.path().as_ref().map(|s| s.syntax().text());
670 // inconsistent state, stop expanding
671 if mac_call_path0 != mac_call_path1 {
674 let speculative_args = match macro_call_with_fake_ident.token_tree() {
676 None => break 'expansion,
680 self.sema.expand(&actual_macro_call),
681 self.sema.speculative_expand(
684 fake_ident_token.clone(),
687 // successful expansions
688 (Some(actual_expansion), Some((fake_expansion, fake_mapped_token))) => {
689 let new_offset = fake_mapped_token.text_range().start();
690 if new_offset > actual_expansion.text_range().end() {
691 // offset outside of bounds from the original expansion,
692 // stop here to prevent problems from happening
695 original_file = actual_expansion;
696 speculative_file = fake_expansion;
697 fake_ident_token = fake_mapped_token;
701 // at least on expansion failed, we won't have anything to expand from this point
702 // onwards so break out
703 _ => break 'expansion,
707 // none of our states have changed so stop the loop
711 self.fill(&original_file, speculative_file, offset, derive_ctx)
714 /// Calculate the expected type and name of the cursor position.
715 fn expected_type_and_name(&self) -> (Option<Type>, Option<NameOrNameRef>) {
716 let mut node = match self.token.parent() {
718 None => return (None, None),
723 ast::LetStmt(it) => {
724 cov_mark::hit!(expected_type_let_with_leading_char);
725 cov_mark::hit!(expected_type_let_without_leading_char);
727 .and_then(|pat| self.sema.type_of_pat(&pat))
728 .or_else(|| it.initializer().and_then(|it| self.sema.type_of_expr(&it)))
729 .map(TypeInfo::original);
730 let name = match it.pat() {
731 Some(ast::Pat::IdentPat(ident)) => ident.name().map(NameOrNameRef::Name),
732 Some(_) | None => None,
737 ast::LetExpr(it) => {
738 cov_mark::hit!(expected_type_if_let_without_leading_char);
740 .and_then(|pat| self.sema.type_of_pat(&pat))
741 .or_else(|| it.expr().and_then(|it| self.sema.type_of_expr(&it)))
742 .map(TypeInfo::original);
746 cov_mark::hit!(expected_type_fn_param);
747 ActiveParameter::at_token(
751 let name = ap.ident().map(NameOrNameRef::Name);
752 let ty = if has_ref(&self.token) {
753 cov_mark::hit!(expected_type_fn_param_ref);
760 .unwrap_or((None, None))
762 ast::RecordExprFieldList(it) => {
763 // wouldn't try {} be nice...
765 if self.token.kind() == T![..]
766 || self.token.prev_token().map(|t| t.kind()) == Some(T![..])
768 cov_mark::hit!(expected_type_struct_func_update);
769 let record_expr = it.syntax().parent().and_then(ast::RecordExpr::cast)?;
770 let ty = self.sema.type_of_expr(&record_expr.into())?;
776 cov_mark::hit!(expected_type_struct_field_without_leading_char);
777 let expr_field = self.token.prev_sibling_or_token()?
779 .and_then(ast::RecordExprField::cast)?;
780 let (_, _, ty) = self.sema.resolve_record_field(&expr_field)?;
783 expr_field.field_name().map(NameOrNameRef::NameRef),
786 })().unwrap_or((None, None))
788 ast::RecordExprField(it) => {
789 if let Some(expr) = it.expr() {
790 cov_mark::hit!(expected_type_struct_field_with_leading_char);
792 self.sema.type_of_expr(&expr).map(TypeInfo::original),
793 it.field_name().map(NameOrNameRef::NameRef),
796 cov_mark::hit!(expected_type_struct_field_followed_by_comma);
797 let ty = self.sema.resolve_record_field(&it)
798 .map(|(_, _, ty)| ty);
801 it.field_name().map(NameOrNameRef::NameRef),
806 // match foo { ..., pat => $0 }
807 ast::MatchExpr(it) => {
808 let ty = if self.previous_token_is(T![=>]) {
809 // match foo { ..., pat => $0 }
810 cov_mark::hit!(expected_type_match_arm_body_without_leading_char);
811 cov_mark::hit!(expected_type_match_arm_body_with_leading_char);
812 self.sema.type_of_expr(&it.into())
815 cov_mark::hit!(expected_type_match_arm_without_leading_char);
816 it.expr().and_then(|e| self.sema.type_of_expr(&e))
817 }.map(TypeInfo::original);
821 let ty = it.condition()
822 .and_then(|e| self.sema.type_of_expr(&e))
823 .map(TypeInfo::original);
826 ast::IdentPat(it) => {
827 cov_mark::hit!(expected_type_if_let_with_leading_char);
828 cov_mark::hit!(expected_type_match_arm_with_leading_char);
829 let ty = self.sema.type_of_pat(&ast::Pat::from(it)).map(TypeInfo::original);
833 cov_mark::hit!(expected_type_fn_ret_with_leading_char);
834 cov_mark::hit!(expected_type_fn_ret_without_leading_char);
835 let def = self.sema.to_def(&it);
836 (def.map(|def| def.ret_type(self.db)), None)
838 ast::ClosureExpr(it) => {
839 let ty = self.sema.type_of_expr(&it.into());
840 ty.and_then(|ty| ty.original.as_callable(self.db))
841 .map(|c| (Some(c.return_type()), None))
842 .unwrap_or((None, None))
844 ast::ParamList(_) => (None, None),
845 ast::Stmt(_) => (None, None),
846 ast::Item(_) => (None, None),
848 match node.parent() {
853 None => (None, None),
861 /// Fill the completion context, this is what does semantic reasoning about the surrounding context
862 /// of the completion location.
865 original_file: &SyntaxNode,
866 file_with_fake_ident: SyntaxNode,
868 derive_ctx: Option<(SyntaxNode, SyntaxNode, TextSize, ast::Attr)>,
870 let fake_ident_token = file_with_fake_ident.token_at_offset(offset).right_biased().unwrap();
871 let syntax_element = NodeOrToken::Token(fake_ident_token);
872 if is_in_token_of_for_loop(syntax_element.clone()) {
874 // there is nothing to complete here except `in` keyword
875 // don't bother populating the context
876 // FIXME: the completion calculations should end up good enough
877 // such that this special case becomes unnecessary
881 self.previous_token = previous_token(syntax_element.clone());
883 self.incomplete_let =
884 syntax_element.ancestors().take(6).find_map(ast::LetStmt::cast).map_or(false, |it| {
885 it.syntax().text_range().end() == syntax_element.text_range().end()
888 (self.expected_type, self.expected_name) = self.expected_type_and_name();
890 // Overwrite the path kind for derives
891 if let Some((original_file, file_with_fake_ident, offset, origin_attr)) = derive_ctx {
892 self.existing_derives = self
894 .resolve_derive_macro(&origin_attr)
900 if let Some(ast::NameLike::NameRef(name_ref)) =
901 find_node_at_offset(&file_with_fake_ident, offset)
903 let parent = name_ref.syntax().parent()?;
904 let (mut nameref_ctx, _) =
905 Self::classify_name_ref(&self.sema, &original_file, name_ref, parent);
906 if let Some(path_ctx) = &mut nameref_ctx.path_ctx {
907 path_ctx.kind = PathKind::Derive;
909 self.ident_ctx = IdentContext::NameRef(nameref_ctx);
915 let name_like = match find_node_at_offset(&file_with_fake_ident, offset) {
918 if let Some(original) = ast::String::cast(self.original_token.clone()) {
919 self.ident_ctx = IdentContext::String {
921 expanded: ast::String::cast(self.token.clone()),
924 // Fix up trailing whitespace problem
926 let token = if self.token.kind() == SyntaxKind::WHITESPACE {
927 self.previous_token.as_ref()?
931 let p = token.parent()?;
932 if p.kind() == SyntaxKind::TOKEN_TREE
933 && p.ancestors().any(|it| it.kind() == SyntaxKind::META)
935 self.ident_ctx = IdentContext::UnexpandedAttrTT {
936 fake_attribute_under_caret: syntax_element
938 .find_map(ast::Attr::cast),
947 self.completion_location =
948 determine_location(&self.sema, original_file, offset, &name_like);
949 self.prev_sibling = determine_prev_sibling(&name_like);
952 .token_ancestors_with_macros(self.token.clone())
953 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
954 .find_map(ast::Impl::cast);
955 self.function_def = self
957 .token_ancestors_with_macros(self.token.clone())
958 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
959 .find_map(ast::Fn::cast);
962 ast::NameLike::Lifetime(lifetime) => {
963 self.ident_ctx = IdentContext::Lifetime(Self::classify_lifetime(
969 ast::NameLike::NameRef(name_ref) => {
970 let parent = name_ref.syntax().parent()?;
971 let (nameref_ctx, pat_ctx) =
972 Self::classify_name_ref(&self.sema, &original_file, name_ref, parent);
973 self.ident_ctx = IdentContext::NameRef(nameref_ctx);
974 self.pattern_ctx = pat_ctx;
976 ast::NameLike::Name(name) => {
977 let (name_ctx, pat_ctx) = Self::classify_name(&self.sema, original_file, name)?;
978 self.pattern_ctx = pat_ctx;
979 self.ident_ctx = IdentContext::Name(name_ctx);
985 fn classify_lifetime(
986 _sema: &Semantics<RootDatabase>,
987 original_file: &SyntaxNode,
988 lifetime: ast::Lifetime,
989 ) -> Option<LifetimeContext> {
990 let parent = lifetime.syntax().parent()?;
991 if parent.kind() == ERROR {
995 let kind = match_ast! {
997 ast::LifetimeParam(param) => LifetimeKind::LifetimeParam {
998 is_decl: param.lifetime().as_ref() == Some(&lifetime),
1001 ast::BreakExpr(_) => LifetimeKind::LabelRef,
1002 ast::ContinueExpr(_) => LifetimeKind::LabelRef,
1003 ast::Label(_) => LifetimeKind::LabelDef,
1004 _ => LifetimeKind::Lifetime,
1007 let lifetime = find_node_at_offset(&original_file, lifetime.syntax().text_range().start());
1009 Some(LifetimeContext { lifetime, kind })
1013 _sema: &Semantics<RootDatabase>,
1014 original_file: &SyntaxNode,
1016 ) -> Option<(NameContext, Option<PatternContext>)> {
1017 let parent = name.syntax().parent()?;
1018 let mut pat_ctx = None;
1019 let kind = match_ast! {
1021 ast::Const(_) => NameKind::Const,
1022 ast::ConstParam(_) => NameKind::ConstParam,
1023 ast::Enum(_) => NameKind::Enum,
1024 ast::Fn(_) => NameKind::Function,
1025 ast::IdentPat(bind_pat) => {
1026 let is_name_in_field_pat = bind_pat
1029 .and_then(ast::RecordPatField::cast)
1030 .map_or(false, |pat_field| pat_field.name_ref().is_none());
1031 if !is_name_in_field_pat {
1032 pat_ctx = Some(pattern_context_for(original_file, bind_pat.into()));
1037 ast::MacroDef(_) => NameKind::MacroDef,
1038 ast::MacroRules(_) => NameKind::MacroRules,
1039 ast::Module(module) => NameKind::Module(module),
1040 ast::RecordField(_) => NameKind::RecordField,
1041 ast::Rename(_) => NameKind::Rename,
1042 ast::SelfParam(_) => NameKind::SelfParam,
1043 ast::Static(_) => NameKind::Static,
1044 ast::Struct(_) => NameKind::Struct,
1045 ast::Trait(_) => NameKind::Trait,
1046 ast::TypeAlias(_) => NameKind::TypeAlias,
1047 ast::TypeParam(_) => NameKind::TypeParam,
1048 ast::Union(_) => NameKind::Union,
1049 ast::Variant(_) => NameKind::Variant,
1053 let name = find_node_at_offset(&original_file, name.syntax().text_range().start());
1054 Some((NameContext { name, kind }, pat_ctx))
1057 fn classify_name_ref(
1058 sema: &Semantics<RootDatabase>,
1059 original_file: &SyntaxNode,
1060 name_ref: ast::NameRef,
1062 ) -> (NameRefContext, Option<PatternContext>) {
1063 let nameref = find_node_at_offset(&original_file, name_ref.syntax().text_range().start());
1065 let mut nameref_ctx = NameRefContext { dot_access: None, path_ctx: None, nameref };
1067 let segment = match_ast! {
1069 ast::PathSegment(segment) => segment,
1070 ast::FieldExpr(field) => {
1071 let receiver = find_in_original_file(field.expr(), original_file);
1072 let receiver_is_ambiguous_float_literal = match &receiver {
1073 Some(ast::Expr::Literal(l)) => matches! {
1075 ast::LiteralKind::FloatNumber { .. } if l.syntax().last_token().map_or(false, |it| it.text().ends_with('.'))
1079 nameref_ctx.dot_access = Some(DotAccess::Field { receiver, receiver_is_ambiguous_float_literal });
1080 return (nameref_ctx, None);
1082 ast::MethodCallExpr(method) => {
1083 nameref_ctx.dot_access = Some(
1085 receiver: find_in_original_file(method.receiver(), original_file),
1086 has_parens: method.arg_list().map_or(false, |it| it.l_paren_token().is_some())
1089 return (nameref_ctx, None);
1091 _ => return (nameref_ctx, None),
1095 let path = segment.parent_path();
1096 let mut path_ctx = PathCompletionCtx {
1097 has_call_parens: false,
1098 has_macro_bang: false,
1099 is_absolute_path: false,
1101 parent: path.parent_path(),
1102 kind: PathKind::Item { kind: ItemListKind::SourceFile },
1103 has_type_args: false,
1105 let mut pat_ctx = None;
1107 let is_in_block = |it: &SyntaxNode| {
1110 ast::ExprStmt::can_cast(node.kind()) || ast::StmtList::can_cast(node.kind())
1114 let is_in_func_update = |it: &SyntaxNode| {
1115 it.parent().map_or(false, |it| ast::RecordExprFieldList::can_cast(it.kind()))
1118 let kind = path.syntax().ancestors().find_map(|it| {
1119 // using Option<Option<PathKind>> as extra controlflow
1120 let kind = match_ast! {
1122 ast::PathType(_) => Some(PathKind::Type),
1123 ast::PathExpr(it) => {
1124 path_ctx.has_call_parens = it.syntax().parent().map_or(false, |it| ast::CallExpr::can_cast(it.kind()));
1125 let in_block_expr = is_in_block(it.syntax());
1126 let in_loop_body = is_in_loop_body(it.syntax());
1127 let in_functional_update = is_in_func_update(it.syntax());
1128 Some(PathKind::Expr { in_block_expr, in_loop_body, in_functional_update })
1130 ast::TupleStructPat(it) => {
1131 path_ctx.has_call_parens = true;
1132 pat_ctx = Some(pattern_context_for(original_file, it.into()));
1135 ast::RecordPat(it) => {
1136 path_ctx.has_call_parens = true;
1137 pat_ctx = Some(pattern_context_for(original_file, it.into()));
1140 ast::PathPat(it) => {
1141 pat_ctx = Some(pattern_context_for(original_file, it.into()));
1144 ast::MacroCall(it) => {
1145 path_ctx.has_macro_bang = it.excl_token().is_some();
1146 let parent = it.syntax().parent();
1147 match parent.as_ref().map(|it| it.kind()) {
1148 Some(SyntaxKind::MACRO_PAT) => Some(PathKind::Pat),
1149 Some(SyntaxKind::MACRO_TYPE) => Some(PathKind::Type),
1150 Some(SyntaxKind::ITEM_LIST) => Some(PathKind::Item { kind: ItemListKind::Module }),
1151 Some(SyntaxKind::ASSOC_ITEM_LIST) => Some(PathKind::Item { kind: match parent.and_then(|it| it.parent()).map(|it| it.kind()) {
1152 Some(SyntaxKind::TRAIT) => ItemListKind::Trait,
1153 Some(SyntaxKind::IMPL) => ItemListKind::Impl,
1154 _ => return Some(None),
1156 Some(SyntaxKind::EXTERN_ITEM_LIST) => Some(PathKind::Item { kind: ItemListKind::ExternBlock }),
1157 Some(SyntaxKind::SOURCE_FILE) => Some(PathKind::Item { kind: ItemListKind::SourceFile }),
1159 return Some(parent.and_then(ast::MacroExpr::cast).map(|it| {
1160 let in_loop_body = is_in_loop_body(it.syntax());
1161 let in_block_expr = is_in_block(it.syntax());
1162 let in_functional_update = is_in_func_update(it.syntax());
1163 PathKind::Expr { in_block_expr, in_loop_body, in_functional_update }
1168 ast::Meta(meta) => (|| {
1169 let attr = meta.parent_attr()?;
1170 let kind = attr.kind();
1171 let attached = attr.syntax().parent()?;
1172 let is_trailing_outer_attr = kind != AttrKind::Inner
1173 && non_trivia_sibling(attr.syntax().clone().into(), syntax::Direction::Next).is_none();
1174 let annotated_item_kind = if is_trailing_outer_attr {
1177 Some(attached.kind())
1179 Some(PathKind::Attr {
1181 annotated_item_kind,
1184 ast::Visibility(it) => Some(PathKind::Vis { has_in_token: it.in_token().is_some() }),
1185 ast::UseTree(_) => Some(PathKind::Use),
1186 ast::ItemList(_) => Some(PathKind::Item { kind: ItemListKind::Module }),
1187 ast::AssocItemList(it) => Some(PathKind::Item { kind: {
1188 match it.syntax().parent()?.kind() {
1189 SyntaxKind::TRAIT => ItemListKind::Trait,
1190 SyntaxKind::IMPL => ItemListKind::Impl,
1194 ast::ExternItemList(_) => Some(PathKind::Item { kind: ItemListKind::ExternBlock }),
1195 ast::SourceFile(_) => Some(PathKind::Item { kind: ItemListKind::SourceFile }),
1202 Some(kind) => path_ctx.kind = kind,
1203 None => return (nameref_ctx, pat_ctx),
1205 path_ctx.has_type_args = segment.generic_arg_list().is_some();
1207 if let Some((path, use_tree_parent)) = path_or_use_tree_qualifier(&path) {
1208 if !use_tree_parent {
1209 path_ctx.is_absolute_path =
1210 path.top_path().segment().map_or(false, |it| it.coloncolon_token().is_some());
1215 .and_then(|it| find_node_in_file(original_file, &it))
1216 .map(|it| it.parent_path());
1217 path_ctx.qualifier = path.map(|path| {
1218 let res = sema.resolve_path(&path);
1219 let is_super_chain = iter::successors(Some(path.clone()), |p| p.qualifier())
1220 .all(|p| p.segment().and_then(|s| s.super_token()).is_some());
1223 let is_infer_qualifier = path.qualifier().is_none()
1225 path.segment().and_then(|it| it.kind()),
1226 Some(ast::PathSegmentKind::Type {
1227 type_ref: Some(ast::Type::InferType(_)),
1240 } else if let Some(segment) = path.segment() {
1241 if segment.coloncolon_token().is_some() {
1242 path_ctx.is_absolute_path = true;
1245 nameref_ctx.path_ctx = Some(path_ctx);
1246 (nameref_ctx, pat_ctx)
1250 fn pattern_context_for(original_file: &SyntaxNode, pat: ast::Pat) -> PatternContext {
1251 let mut is_param = None;
1252 let (refutability, has_type_ascription) =
1256 .skip_while(|it| ast::Pat::can_cast(it.kind()))
1258 .map_or((PatternRefutability::Irrefutable, false), |node| {
1259 let refutability = match_ast! {
1261 ast::LetStmt(let_) => return (PatternRefutability::Irrefutable, let_.ty().is_some()),
1262 ast::Param(param) => {
1263 let has_type_ascription = param.ty().is_some();
1265 let fake_param_list = param.syntax().parent().and_then(ast::ParamList::cast)?;
1266 let param_list = find_node_in_file_compensated(original_file, &fake_param_list)?;
1267 let param_list_owner = param_list.syntax().parent()?;
1268 let kind = match_ast! {
1269 match param_list_owner {
1270 ast::ClosureExpr(closure) => ParamKind::Closure(closure),
1271 ast::Fn(fn_) => ParamKind::Function(fn_),
1275 Some((param_list, param, kind))
1277 return (PatternRefutability::Irrefutable, has_type_ascription)
1279 ast::MatchArm(_) => PatternRefutability::Refutable,
1280 ast::LetExpr(_) => PatternRefutability::Refutable,
1281 ast::ForExpr(_) => PatternRefutability::Irrefutable,
1282 _ => PatternRefutability::Irrefutable,
1285 (refutability, false)
1287 let (ref_token, mut_token) = match &pat {
1288 ast::Pat::IdentPat(it) => (it.ref_token(), it.mut_token()),
1293 param_ctx: is_param,
1294 has_type_ascription,
1295 parent_pat: pat.syntax().parent().and_then(ast::Pat::cast),
1301 fn find_in_original_file<N: AstNode>(x: Option<N>, original_file: &SyntaxNode) -> Option<N> {
1302 fn find_node_with_range<N: AstNode>(syntax: &SyntaxNode, range: TextRange) -> Option<N> {
1303 let range = syntax.text_range().intersect(range)?;
1304 syntax.covering_element(range).ancestors().find_map(N::cast)
1306 x.map(|e| e.syntax().text_range()).and_then(|r| find_node_with_range(original_file, r))
1309 /// Attempts to find `node` inside `syntax` via `node`'s text range.
1310 fn find_node_in_file<N: AstNode>(syntax: &SyntaxNode, node: &N) -> Option<N> {
1311 let syntax_range = syntax.text_range();
1312 let range = node.syntax().text_range();
1313 let intersection = range.intersect(syntax_range)?;
1314 syntax.covering_element(intersection).ancestors().find_map(N::cast)
1317 /// Attempts to find `node` inside `syntax` via `node`'s text range while compensating
1318 /// for the offset introduced by the fake ident.
1319 /// This is wrong if `node` comes before the insertion point! Use `find_node_in_file` instead.
1320 fn find_node_in_file_compensated<N: AstNode>(syntax: &SyntaxNode, node: &N) -> Option<N> {
1321 let syntax_range = syntax.text_range();
1322 let range = node.syntax().text_range();
1323 let end = range.end().checked_sub(TextSize::try_from(COMPLETION_MARKER.len()).ok()?)?;
1324 if end < range.start() {
1327 let range = TextRange::new(range.start(), end);
1328 // our inserted ident could cause `range` to be go outside of the original syntax, so cap it
1329 let intersection = range.intersect(syntax_range)?;
1330 syntax.covering_element(intersection).ancestors().find_map(N::cast)
1333 fn path_or_use_tree_qualifier(path: &ast::Path) -> Option<(ast::Path, bool)> {
1334 if let Some(qual) = path.qualifier() {
1335 return Some((qual, false));
1337 let use_tree_list = path.syntax().ancestors().find_map(ast::UseTreeList::cast)?;
1338 let use_tree = use_tree_list.syntax().parent().and_then(ast::UseTree::cast)?;
1339 Some((use_tree.path()?, true))
1342 fn has_ref(token: &SyntaxToken) -> bool {
1343 let mut token = token.clone();
1344 for skip in [IDENT, WHITESPACE, T![mut]] {
1345 if token.kind() == skip {
1346 token = match token.prev_token() {
1348 None => return false,
1352 token.kind() == T![&]
1355 const OP_TRAIT_LANG_NAMES: &[&str] = &[
1390 use expect_test::{expect, Expect};
1391 use hir::HirDisplay;
1393 use crate::tests::{position, TEST_CONFIG};
1395 use super::CompletionContext;
1397 fn check_expected_type_and_name(ra_fixture: &str, expect: Expect) {
1398 let (db, pos) = position(ra_fixture);
1399 let config = TEST_CONFIG;
1400 let completion_context = CompletionContext::new(&db, pos, &config).unwrap();
1402 let ty = completion_context
1404 .map(|t| t.display_test(&db).to_string())
1405 .unwrap_or("?".to_owned());
1407 let name = completion_context
1409 .map_or_else(|| "?".to_owned(), |name| name.to_string());
1411 expect.assert_eq(&format!("ty: {}, name: {}", ty, name));
1415 fn expected_type_let_without_leading_char() {
1416 cov_mark::check!(expected_type_let_without_leading_char);
1417 check_expected_type_and_name(
1423 expect![[r#"ty: u32, name: x"#]],
1428 fn expected_type_let_with_leading_char() {
1429 cov_mark::check!(expected_type_let_with_leading_char);
1430 check_expected_type_and_name(
1436 expect![[r#"ty: u32, name: x"#]],
1441 fn expected_type_let_pat() {
1442 check_expected_type_and_name(
1448 expect![[r#"ty: u32, name: ?"#]],
1450 check_expected_type_and_name(
1456 expect![[r#"ty: u32, name: ?"#]],
1461 fn expected_type_fn_param() {
1462 cov_mark::check!(expected_type_fn_param);
1463 check_expected_type_and_name(
1465 fn foo() { bar($0); }
1468 expect![[r#"ty: u32, name: x"#]],
1470 check_expected_type_and_name(
1472 fn foo() { bar(c$0); }
1475 expect![[r#"ty: u32, name: x"#]],
1480 fn expected_type_fn_param_ref() {
1481 cov_mark::check!(expected_type_fn_param_ref);
1482 check_expected_type_and_name(
1484 fn foo() { bar(&$0); }
1487 expect![[r#"ty: u32, name: x"#]],
1489 check_expected_type_and_name(
1491 fn foo() { bar(&mut $0); }
1492 fn bar(x: &mut u32) {}
1494 expect![[r#"ty: u32, name: x"#]],
1496 check_expected_type_and_name(
1498 fn foo() { bar(& c$0); }
1501 expect![[r#"ty: u32, name: x"#]],
1503 check_expected_type_and_name(
1505 fn foo() { bar(&mut c$0); }
1506 fn bar(x: &mut u32) {}
1508 expect![[r#"ty: u32, name: x"#]],
1510 check_expected_type_and_name(
1512 fn foo() { bar(&c$0); }
1515 expect![[r#"ty: u32, name: x"#]],
1520 fn expected_type_struct_field_without_leading_char() {
1521 cov_mark::check!(expected_type_struct_field_without_leading_char);
1522 check_expected_type_and_name(
1524 struct Foo { a: u32 }
1529 expect![[r#"ty: u32, name: a"#]],
1534 fn expected_type_struct_field_followed_by_comma() {
1535 cov_mark::check!(expected_type_struct_field_followed_by_comma);
1536 check_expected_type_and_name(
1538 struct Foo { a: u32 }
1543 expect![[r#"ty: u32, name: a"#]],
1548 fn expected_type_generic_struct_field() {
1549 check_expected_type_and_name(
1551 struct Foo<T> { a: T }
1552 fn foo() -> Foo<u32> {
1556 expect![[r#"ty: u32, name: a"#]],
1561 fn expected_type_struct_field_with_leading_char() {
1562 cov_mark::check!(expected_type_struct_field_with_leading_char);
1563 check_expected_type_and_name(
1565 struct Foo { a: u32 }
1570 expect![[r#"ty: u32, name: a"#]],
1575 fn expected_type_match_arm_without_leading_char() {
1576 cov_mark::check!(expected_type_match_arm_without_leading_char);
1577 check_expected_type_and_name(
1584 expect![[r#"ty: E, name: ?"#]],
1589 fn expected_type_match_arm_with_leading_char() {
1590 cov_mark::check!(expected_type_match_arm_with_leading_char);
1591 check_expected_type_and_name(
1598 expect![[r#"ty: E, name: ?"#]],
1603 fn expected_type_match_arm_body_without_leading_char() {
1604 cov_mark::check!(expected_type_match_arm_body_without_leading_char);
1605 check_expected_type_and_name(
1610 match E::X { E::X => $0 }
1613 expect![[r#"ty: Foo, name: ?"#]],
1618 fn expected_type_match_body_arm_with_leading_char() {
1619 cov_mark::check!(expected_type_match_arm_body_with_leading_char);
1620 check_expected_type_and_name(
1625 match E::X { E::X => c$0 }
1628 expect![[r#"ty: Foo, name: ?"#]],
1633 fn expected_type_if_let_without_leading_char() {
1634 cov_mark::check!(expected_type_if_let_without_leading_char);
1635 check_expected_type_and_name(
1637 enum Foo { Bar, Baz, Quux }
1644 expect![[r#"ty: Foo, name: ?"#]],
1649 fn expected_type_if_let_with_leading_char() {
1650 cov_mark::check!(expected_type_if_let_with_leading_char);
1651 check_expected_type_and_name(
1653 enum Foo { Bar, Baz, Quux }
1660 expect![[r#"ty: Foo, name: ?"#]],
1665 fn expected_type_fn_ret_without_leading_char() {
1666 cov_mark::check!(expected_type_fn_ret_without_leading_char);
1667 check_expected_type_and_name(
1673 expect![[r#"ty: u32, name: ?"#]],
1678 fn expected_type_fn_ret_with_leading_char() {
1679 cov_mark::check!(expected_type_fn_ret_with_leading_char);
1680 check_expected_type_and_name(
1686 expect![[r#"ty: u32, name: ?"#]],
1691 fn expected_type_fn_ret_fn_ref_fully_typed() {
1692 check_expected_type_and_name(
1698 expect![[r#"ty: u32, name: ?"#]],
1703 fn expected_type_closure_param_return() {
1704 // FIXME: make this work with `|| $0`
1705 check_expected_type_and_name(
1712 fn bar(f: impl FnOnce() -> u32) {}
1714 expect![[r#"ty: u32, name: ?"#]],
1719 fn expected_type_generic_function() {
1720 check_expected_type_and_name(
1728 expect![[r#"ty: u32, name: t"#]],
1733 fn expected_type_generic_method() {
1734 check_expected_type_and_name(
1742 fn bar(self, t: T) {}
1745 expect![[r#"ty: u32, name: t"#]],
1750 fn expected_type_functional_update() {
1751 cov_mark::check!(expected_type_struct_func_update);
1752 check_expected_type_and_name(
1754 struct Foo { field: u32 }
1761 expect![[r#"ty: Foo, name: ?"#]],
1766 fn expected_type_param_pat() {
1767 check_expected_type_and_name(
1769 struct Foo { field: u32 }
1772 expect![[r#"ty: Foo, name: ?"#]],
1774 check_expected_type_and_name(
1776 struct Foo { field: u32 }
1779 // FIXME make this work, currently fails due to pattern recovery eating the `:`
1780 expect![[r#"ty: ?, name: ?"#]],