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 pub(crate) struct PathCompletionCtx {
80 /// If this is a call with () already there (or {} in case of record patterns)
81 pub(super) has_call_parens: bool,
82 /// If this has a macro call bang !
83 pub(super) has_macro_bang: bool,
84 /// Whether this path stars with a `::`.
85 pub(super) is_absolute_path: bool,
86 /// The qualifier of the current path if it exists.
87 pub(super) qualifier: Option<PathQualifierCtx>,
90 /// The parent of the path we are completing.
91 pub(super) parent: Option<ast::Path>,
92 pub(super) kind: PathKind,
93 /// Whether the path segment has type args or not.
94 pub(super) has_type_args: bool,
98 pub(crate) struct PathQualifierCtx {
99 pub(crate) path: ast::Path,
100 pub(crate) resolution: Option<PathResolution>,
101 /// Whether this path consists solely of `super` segments
102 pub(crate) is_super_chain: bool,
103 /// Whether the qualifier comes from a use tree parent or not
104 pub(crate) use_tree_parent: bool,
106 pub(crate) is_infer_qualifier: bool,
110 pub(super) struct PatternContext {
111 pub(super) refutability: PatternRefutability,
112 pub(super) param_ctx: Option<(ast::ParamList, ast::Param, ParamKind)>,
113 pub(super) has_type_ascription: bool,
114 pub(super) parent_pat: Option<ast::Pat>,
115 pub(super) ref_token: Option<SyntaxToken>,
116 pub(super) mut_token: Option<SyntaxToken>,
117 /// The record pattern this name or ref is a field of
118 pub(super) record_pat: Option<ast::RecordPat>,
122 pub(super) struct LifetimeContext {
123 pub(super) lifetime: Option<ast::Lifetime>,
124 pub(super) kind: LifetimeKind,
128 pub(super) enum LifetimeKind {
129 LifetimeParam { is_decl: bool, param: ast::LifetimeParam },
136 pub(super) struct NameContext {
138 pub(super) name: Option<ast::Name>,
139 pub(super) kind: NameKind,
144 pub(super) enum NameKind {
167 pub(super) struct NameRefContext {
168 /// NameRef syntax in the original file
169 pub(super) nameref: Option<ast::NameRef>,
170 // FIXME: these fields are actually disjoint -> enum
171 pub(super) dot_access: Option<DotAccess>,
172 pub(super) path_ctx: Option<PathCompletionCtx>,
173 /// The record expression this nameref is a field of
174 pub(super) record_expr: Option<(ast::RecordExpr, bool)>,
178 pub(super) enum IdentContext {
180 NameRef(NameRefContext),
181 Lifetime(LifetimeContext),
182 /// Original token, fake token
184 original: ast::String,
185 expanded: Option<ast::String>,
188 fake_attribute_under_caret: Option<ast::Attr>,
193 pub(super) struct DotAccess {
194 pub(super) receiver: Option<ast::Expr>,
195 pub(super) receiver_ty: Option<TypeInfo>,
196 pub(super) kind: DotAccessKind,
200 pub(super) enum DotAccessKind {
202 /// True if the receiver is an integer and there is no ident in the original file after it yet
204 receiver_is_ambiguous_float_literal: bool,
211 #[derive(Clone, Debug, PartialEq, Eq)]
212 pub(crate) enum ParamKind {
214 Closure(ast::ClosureExpr),
217 /// `CompletionContext` is created early during completion to figure out, where
218 /// exactly is the cursor, syntax-wise.
220 pub(crate) struct CompletionContext<'a> {
221 pub(super) sema: Semantics<'a, RootDatabase>,
222 pub(super) scope: SemanticsScope<'a>,
223 pub(super) db: &'a RootDatabase,
224 pub(super) config: &'a CompletionConfig,
225 pub(super) position: FilePosition,
227 /// The token before the cursor, in the original file.
228 pub(super) original_token: SyntaxToken,
229 /// The token before the cursor, in the macro-expanded file.
230 pub(super) token: SyntaxToken,
231 /// The crate of the current file.
232 pub(super) krate: hir::Crate,
233 /// The module of the `scope`.
234 pub(super) module: hir::Module,
236 /// The expected name of what we are completing.
237 /// This is usually the parameter name of the function argument we are completing.
238 pub(super) expected_name: Option<NameOrNameRef>,
239 /// The expected type of what we are completing.
240 pub(super) expected_type: Option<Type>,
242 /// The parent function of the cursor position if it exists.
243 pub(super) function_def: Option<ast::Fn>,
244 /// The parent impl of the cursor position if it exists.
245 pub(super) impl_def: Option<ast::Impl>,
246 /// Are we completing inside a let statement with a missing semicolon?
247 pub(super) incomplete_let: bool,
249 pub(super) completion_location: Option<ImmediateLocation>,
250 pub(super) prev_sibling: Option<ImmediatePrevSibling>,
251 pub(super) previous_token: Option<SyntaxToken>,
253 pub(super) ident_ctx: IdentContext,
255 pub(super) pattern_ctx: Option<PatternContext>,
257 pub(super) existing_derives: FxHashSet<hir::Macro>,
259 pub(super) locals: FxHashMap<Name, Local>,
262 impl<'a> CompletionContext<'a> {
263 /// The range of the identifier that is being completed.
264 pub(crate) fn source_range(&self) -> TextRange {
265 // check kind of macro-expanded token, but use range of original token
266 let kind = self.token.kind();
269 // assume we are completing a lifetime but the user has only typed the '
270 cov_mark::hit!(completes_if_lifetime_without_idents);
271 TextRange::at(self.original_token.text_range().start(), TextSize::from(1))
273 IDENT | LIFETIME_IDENT | UNDERSCORE => self.original_token.text_range(),
274 _ if kind.is_keyword() => self.original_token.text_range(),
275 _ => TextRange::empty(self.position.offset),
279 pub(crate) fn previous_token_is(&self, kind: SyntaxKind) -> bool {
280 self.previous_token.as_ref().map_or(false, |tok| tok.kind() == kind)
283 pub(crate) fn famous_defs(&self) -> FamousDefs {
284 FamousDefs(&self.sema, self.krate)
287 pub(super) fn nameref_ctx(&self) -> Option<&NameRefContext> {
288 match &self.ident_ctx {
289 IdentContext::NameRef(it) => Some(it),
294 pub(super) fn name_ctx(&self) -> Option<&NameContext> {
295 match &self.ident_ctx {
296 IdentContext::Name(it) => Some(it),
301 pub(super) fn lifetime_ctx(&self) -> Option<&LifetimeContext> {
302 match &self.ident_ctx {
303 IdentContext::Lifetime(it) => Some(it),
308 pub(crate) fn dot_receiver(&self) -> Option<&ast::Expr> {
309 match self.nameref_ctx() {
310 Some(NameRefContext { dot_access: Some(DotAccess { receiver, .. }), .. }) => {
317 pub(crate) fn has_dot_receiver(&self) -> bool {
318 self.dot_receiver().is_some()
321 pub(crate) fn expects_assoc_item(&self) -> bool {
322 matches!(self.completion_location, Some(ImmediateLocation::Trait | ImmediateLocation::Impl))
325 pub(crate) fn expects_non_trait_assoc_item(&self) -> bool {
326 matches!(self.completion_location, Some(ImmediateLocation::Impl))
329 pub(crate) fn expects_item(&self) -> bool {
330 matches!(self.completion_location, Some(ImmediateLocation::ItemList))
333 // FIXME: This shouldn't exist
334 pub(crate) fn expects_generic_arg(&self) -> bool {
335 matches!(self.completion_location, Some(ImmediateLocation::GenericArgList(_)))
338 pub(crate) fn has_block_expr_parent(&self) -> bool {
339 matches!(self.completion_location, Some(ImmediateLocation::StmtList))
342 pub(crate) fn expects_ident_ref_expr(&self) -> bool {
343 matches!(self.completion_location, Some(ImmediateLocation::RefExpr))
346 pub(crate) fn expect_field(&self) -> bool {
347 matches!(self.completion_location, Some(ImmediateLocation::TupleField))
348 || matches!(self.name_ctx(), Some(NameContext { kind: NameKind::RecordField, .. }))
351 /// Whether the cursor is right after a trait or impl header.
352 /// trait Foo ident$0
353 // FIXME: This probably shouldn't exist
354 pub(crate) fn has_unfinished_impl_or_trait_prev_sibling(&self) -> bool {
357 Some(ImmediatePrevSibling::ImplDefType | ImmediatePrevSibling::TraitDefName)
361 // FIXME: This probably shouldn't exist
362 pub(crate) fn has_impl_prev_sibling(&self) -> bool {
363 matches!(self.prev_sibling, Some(ImmediatePrevSibling::ImplDefType))
366 pub(crate) fn has_visibility_prev_sibling(&self) -> bool {
367 matches!(self.prev_sibling, Some(ImmediatePrevSibling::Visibility))
370 pub(crate) fn after_if(&self) -> bool {
371 matches!(self.prev_sibling, Some(ImmediatePrevSibling::IfExpr))
374 // FIXME: This shouldn't exist
375 pub(crate) fn is_path_disallowed(&self) -> bool {
376 self.previous_token_is(T![unsafe])
377 || matches!(self.prev_sibling, Some(ImmediatePrevSibling::Visibility))
378 || (matches!(self.name_ctx(), Some(NameContext { .. })) && self.pattern_ctx.is_none())
379 || matches!(self.pattern_ctx, Some(PatternContext { record_pat: Some(_), .. }))
382 Some(NameRefContext { record_expr: Some((_, false)), .. })
386 pub(crate) fn path_context(&self) -> Option<&PathCompletionCtx> {
387 self.nameref_ctx().and_then(|ctx| ctx.path_ctx.as_ref())
390 pub(crate) fn expects_expression(&self) -> bool {
391 matches!(self.path_context(), Some(PathCompletionCtx { kind: PathKind::Expr { .. }, .. }))
394 pub(crate) fn is_non_trivial_path(&self) -> bool {
398 PathCompletionCtx { is_absolute_path: true, .. }
399 | PathCompletionCtx { qualifier: Some(_), .. }
404 pub(crate) fn path_qual(&self) -> Option<&ast::Path> {
405 self.path_context().and_then(|it| it.qualifier.as_ref().map(|it| &it.path))
408 pub(crate) fn path_kind(&self) -> Option<PathKind> {
409 self.path_context().map(|it| it.kind)
412 /// Checks if an item is visible and not `doc(hidden)` at the completion site.
413 pub(crate) fn is_visible<I>(&self, item: &I) -> Visible
415 I: hir::HasVisibility + hir::HasAttrs + hir::HasCrate + Copy,
417 self.is_visible_impl(&item.visibility(self.db), &item.attrs(self.db), item.krate(self.db))
420 pub(crate) fn is_scope_def_hidden(&self, scope_def: ScopeDef) -> bool {
421 if let (Some(attrs), Some(krate)) = (scope_def.attrs(self.db), scope_def.krate(self.db)) {
422 return self.is_doc_hidden(&attrs, krate);
428 /// Check if an item is `#[doc(hidden)]`.
429 pub(crate) fn is_item_hidden(&self, item: &hir::ItemInNs) -> bool {
430 let attrs = item.attrs(self.db);
431 let krate = item.krate(self.db);
432 match (attrs, krate) {
433 (Some(attrs), Some(krate)) => self.is_doc_hidden(&attrs, krate),
437 /// Whether the given trait is an operator trait or not.
438 pub(crate) fn is_ops_trait(&self, trait_: hir::Trait) -> bool {
439 match trait_.attrs(self.db).lang() {
440 Some(lang) => OP_TRAIT_LANG_NAMES.contains(&lang.as_str()),
445 /// Returns the traits in scope, with the [`Drop`] trait removed.
446 pub(crate) fn traits_in_scope(&self) -> hir::VisibleTraits {
447 let mut traits_in_scope = self.scope.visible_traits();
448 if let Some(drop) = self.famous_defs().core_ops_Drop() {
449 traits_in_scope.0.remove(&drop.into());
454 /// A version of [`SemanticsScope::process_all_names`] that filters out `#[doc(hidden)]` items.
455 pub(crate) fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
456 let _p = profile::span("CompletionContext::process_all_names");
457 self.scope.process_all_names(&mut |name, def| {
458 if self.is_scope_def_hidden(def) {
466 pub(crate) fn process_all_names_raw(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
467 let _p = profile::span("CompletionContext::process_all_names_raw");
468 self.scope.process_all_names(&mut |name, def| f(name, def));
473 vis: &hir::Visibility,
475 defining_crate: hir::Crate,
477 if !vis.is_visible_from(self.db, self.module.into()) {
478 if !self.config.enable_private_editable {
481 // If the definition location is editable, also show private items
482 let root_file = defining_crate.root_file(self.db);
483 let source_root_id = self.db.file_source_root(root_file);
484 let is_editable = !self.db.source_root(source_root_id).is_library;
485 return if is_editable { Visible::Editable } else { Visible::No };
488 if self.is_doc_hidden(attrs, defining_crate) {
495 fn is_doc_hidden(&self, attrs: &hir::Attrs, defining_crate: hir::Crate) -> bool {
496 // `doc(hidden)` items are only completed within the defining crate.
497 self.krate != defining_crate && attrs.has_doc_hidden()
501 // CompletionContext construction
502 impl<'a> CompletionContext<'a> {
504 db: &'a RootDatabase,
505 position @ FilePosition { file_id, offset }: FilePosition,
506 config: &'a CompletionConfig,
507 ) -> Option<CompletionContext<'a>> {
508 let _p = profile::span("CompletionContext::new");
509 let sema = Semantics::new(db);
511 let original_file = sema.parse(file_id);
513 // Insert a fake ident to get a valid parse tree. We will use this file
514 // to determine context, though the original_file will be used for
515 // actual completion.
516 let file_with_fake_ident = {
517 let parse = db.parse(file_id);
518 let edit = Indel::insert(offset, COMPLETION_MARKER.to_string());
519 parse.reparse(&edit).tree()
521 let fake_ident_token =
522 file_with_fake_ident.syntax().token_at_offset(offset).right_biased()?;
524 let original_token = original_file.syntax().token_at_offset(offset).left_biased()?;
525 let token = sema.descend_into_macros_single(original_token.clone());
526 let scope = sema.scope_at_offset(&token.parent()?, offset)?;
527 let krate = scope.krate();
528 let module = scope.module();
530 let mut locals = FxHashMap::default();
531 scope.process_all_names(&mut |name, scope| {
532 if let ScopeDef::Local(local) = scope {
533 locals.insert(name, local);
537 let mut ctx = CompletionContext {
551 incomplete_let: false,
552 completion_location: None,
554 previous_token: None,
555 // dummy value, will be overwritten
556 ident_ctx: IdentContext::UnexpandedAttrTT { fake_attribute_under_caret: None },
558 existing_derives: Default::default(),
562 original_file.syntax().clone(),
563 file_with_fake_ident.syntax().clone(),
570 /// Expand attributes and macro calls at the current cursor position for both the original file
571 /// and fake file repeatedly. As soon as one of the two expansions fail we stop so the original
572 /// and speculative states stay in sync.
575 mut original_file: SyntaxNode,
576 mut speculative_file: SyntaxNode,
577 mut offset: TextSize,
578 mut fake_ident_token: SyntaxToken,
580 let _p = profile::span("CompletionContext::expand_and_fill");
581 let mut derive_ctx = None;
585 |item: &ast::Item| item.syntax().ancestors().skip(1).find_map(ast::Item::cast);
586 let ancestor_items = iter::successors(
588 find_node_at_offset::<ast::Item>(&original_file, offset),
589 find_node_at_offset::<ast::Item>(&speculative_file, offset),
591 |(a, b)| parent_item(a).zip(parent_item(b)),
594 // first try to expand attributes as these are always the outermost macro calls
595 'ancestors: for (actual_item, item_with_fake_ident) in ancestor_items {
597 self.sema.expand_attr_macro(&actual_item),
598 self.sema.speculative_expand_attr_macro(
600 &item_with_fake_ident,
601 fake_ident_token.clone(),
604 // maybe parent items have attributes, so continue walking the ancestors
605 (None, None) => continue 'ancestors,
606 // successful expansions
607 (Some(actual_expansion), Some((fake_expansion, fake_mapped_token))) => {
608 let new_offset = fake_mapped_token.text_range().start();
609 if new_offset > actual_expansion.text_range().end() {
610 // offset outside of bounds from the original expansion,
611 // stop here to prevent problems from happening
614 original_file = actual_expansion;
615 speculative_file = fake_expansion;
616 fake_ident_token = fake_mapped_token;
620 // exactly one expansion failed, inconsistent state so stop expanding completely
621 _ => break 'expansion,
625 // No attributes have been expanded, so look for macro_call! token trees or derive token trees
626 let orig_tt = match find_node_at_offset::<ast::TokenTree>(&original_file, offset) {
628 None => break 'expansion,
630 let spec_tt = match find_node_at_offset::<ast::TokenTree>(&speculative_file, offset) {
632 None => break 'expansion,
635 // Expand pseudo-derive expansion
636 if let (Some(orig_attr), Some(spec_attr)) = (
637 orig_tt.syntax().parent().and_then(ast::Meta::cast).and_then(|it| it.parent_attr()),
638 spec_tt.syntax().parent().and_then(ast::Meta::cast).and_then(|it| it.parent_attr()),
640 if let (Some(actual_expansion), Some((fake_expansion, fake_mapped_token))) = (
641 self.sema.expand_derive_as_pseudo_attr_macro(&orig_attr),
642 self.sema.speculative_expand_derive_as_pseudo_attr_macro(
645 fake_ident_token.clone(),
651 fake_mapped_token.text_range().start(),
655 // at this point we won't have any more successful expansions, so stop
659 // Expand fn-like macro calls
660 if let (Some(actual_macro_call), Some(macro_call_with_fake_ident)) = (
661 orig_tt.syntax().ancestors().find_map(ast::MacroCall::cast),
662 spec_tt.syntax().ancestors().find_map(ast::MacroCall::cast),
664 let mac_call_path0 = actual_macro_call.path().as_ref().map(|s| s.syntax().text());
666 macro_call_with_fake_ident.path().as_ref().map(|s| s.syntax().text());
668 // inconsistent state, stop expanding
669 if mac_call_path0 != mac_call_path1 {
672 let speculative_args = match macro_call_with_fake_ident.token_tree() {
674 None => break 'expansion,
678 self.sema.expand(&actual_macro_call),
679 self.sema.speculative_expand(
682 fake_ident_token.clone(),
685 // successful expansions
686 (Some(actual_expansion), Some((fake_expansion, fake_mapped_token))) => {
687 let new_offset = fake_mapped_token.text_range().start();
688 if new_offset > actual_expansion.text_range().end() {
689 // offset outside of bounds from the original expansion,
690 // stop here to prevent problems from happening
693 original_file = actual_expansion;
694 speculative_file = fake_expansion;
695 fake_ident_token = fake_mapped_token;
699 // at least on expansion failed, we won't have anything to expand from this point
700 // onwards so break out
701 _ => break 'expansion,
705 // none of our states have changed so stop the loop
709 self.fill(&original_file, speculative_file, offset, derive_ctx)
712 /// Calculate the expected type and name of the cursor position.
713 fn expected_type_and_name(&self) -> (Option<Type>, Option<NameOrNameRef>) {
714 let mut node = match self.token.parent() {
716 None => return (None, None),
721 ast::LetStmt(it) => {
722 cov_mark::hit!(expected_type_let_with_leading_char);
723 cov_mark::hit!(expected_type_let_without_leading_char);
725 .and_then(|pat| self.sema.type_of_pat(&pat))
726 .or_else(|| it.initializer().and_then(|it| self.sema.type_of_expr(&it)))
727 .map(TypeInfo::original);
728 let name = match it.pat() {
729 Some(ast::Pat::IdentPat(ident)) => ident.name().map(NameOrNameRef::Name),
730 Some(_) | None => None,
735 ast::LetExpr(it) => {
736 cov_mark::hit!(expected_type_if_let_without_leading_char);
738 .and_then(|pat| self.sema.type_of_pat(&pat))
739 .or_else(|| it.expr().and_then(|it| self.sema.type_of_expr(&it)))
740 .map(TypeInfo::original);
744 cov_mark::hit!(expected_type_fn_param);
745 ActiveParameter::at_token(
749 let name = ap.ident().map(NameOrNameRef::Name);
750 let ty = if has_ref(&self.token) {
751 cov_mark::hit!(expected_type_fn_param_ref);
758 .unwrap_or((None, None))
760 ast::RecordExprFieldList(it) => {
761 // wouldn't try {} be nice...
763 if self.token.kind() == T![..]
764 || self.token.prev_token().map(|t| t.kind()) == Some(T![..])
766 cov_mark::hit!(expected_type_struct_func_update);
767 let record_expr = it.syntax().parent().and_then(ast::RecordExpr::cast)?;
768 let ty = self.sema.type_of_expr(&record_expr.into())?;
774 cov_mark::hit!(expected_type_struct_field_without_leading_char);
775 let expr_field = self.token.prev_sibling_or_token()?
777 .and_then(ast::RecordExprField::cast)?;
778 let (_, _, ty) = self.sema.resolve_record_field(&expr_field)?;
781 expr_field.field_name().map(NameOrNameRef::NameRef),
784 })().unwrap_or((None, None))
786 ast::RecordExprField(it) => {
787 if let Some(expr) = it.expr() {
788 cov_mark::hit!(expected_type_struct_field_with_leading_char);
790 self.sema.type_of_expr(&expr).map(TypeInfo::original),
791 it.field_name().map(NameOrNameRef::NameRef),
794 cov_mark::hit!(expected_type_struct_field_followed_by_comma);
795 let ty = self.sema.resolve_record_field(&it)
796 .map(|(_, _, ty)| ty);
799 it.field_name().map(NameOrNameRef::NameRef),
804 // match foo { ..., pat => $0 }
805 ast::MatchExpr(it) => {
806 let ty = if self.previous_token_is(T![=>]) {
807 // match foo { ..., pat => $0 }
808 cov_mark::hit!(expected_type_match_arm_body_without_leading_char);
809 cov_mark::hit!(expected_type_match_arm_body_with_leading_char);
810 self.sema.type_of_expr(&it.into())
813 cov_mark::hit!(expected_type_match_arm_without_leading_char);
814 it.expr().and_then(|e| self.sema.type_of_expr(&e))
815 }.map(TypeInfo::original);
819 let ty = it.condition()
820 .and_then(|e| self.sema.type_of_expr(&e))
821 .map(TypeInfo::original);
824 ast::IdentPat(it) => {
825 cov_mark::hit!(expected_type_if_let_with_leading_char);
826 cov_mark::hit!(expected_type_match_arm_with_leading_char);
827 let ty = self.sema.type_of_pat(&ast::Pat::from(it)).map(TypeInfo::original);
831 cov_mark::hit!(expected_type_fn_ret_with_leading_char);
832 cov_mark::hit!(expected_type_fn_ret_without_leading_char);
833 let def = self.sema.to_def(&it);
834 (def.map(|def| def.ret_type(self.db)), None)
836 ast::ClosureExpr(it) => {
837 let ty = self.sema.type_of_expr(&it.into());
838 ty.and_then(|ty| ty.original.as_callable(self.db))
839 .map(|c| (Some(c.return_type()), None))
840 .unwrap_or((None, None))
842 ast::ParamList(_) => (None, None),
843 ast::Stmt(_) => (None, None),
844 ast::Item(_) => (None, None),
846 match node.parent() {
851 None => (None, None),
859 /// Fill the completion context, this is what does semantic reasoning about the surrounding context
860 /// of the completion location.
863 original_file: &SyntaxNode,
864 file_with_fake_ident: SyntaxNode,
866 derive_ctx: Option<(SyntaxNode, SyntaxNode, TextSize, ast::Attr)>,
868 let fake_ident_token = file_with_fake_ident.token_at_offset(offset).right_biased().unwrap();
869 let syntax_element = NodeOrToken::Token(fake_ident_token);
870 if is_in_token_of_for_loop(syntax_element.clone()) {
872 // there is nothing to complete here except `in` keyword
873 // don't bother populating the context
874 // FIXME: the completion calculations should end up good enough
875 // such that this special case becomes unnecessary
879 self.previous_token = previous_token(syntax_element.clone());
881 self.incomplete_let =
882 syntax_element.ancestors().take(6).find_map(ast::LetStmt::cast).map_or(false, |it| {
883 it.syntax().text_range().end() == syntax_element.text_range().end()
886 (self.expected_type, self.expected_name) = self.expected_type_and_name();
888 // Overwrite the path kind for derives
889 if let Some((original_file, file_with_fake_ident, offset, origin_attr)) = derive_ctx {
890 self.existing_derives = self
892 .resolve_derive_macro(&origin_attr)
898 if let Some(ast::NameLike::NameRef(name_ref)) =
899 find_node_at_offset(&file_with_fake_ident, offset)
901 let parent = name_ref.syntax().parent()?;
902 let (mut nameref_ctx, _) =
903 Self::classify_name_ref(&self.sema, &original_file, name_ref, parent);
904 if let Some(path_ctx) = &mut nameref_ctx.path_ctx {
905 path_ctx.kind = PathKind::Derive;
907 self.ident_ctx = IdentContext::NameRef(nameref_ctx);
913 let name_like = match find_node_at_offset(&file_with_fake_ident, offset) {
916 if let Some(original) = ast::String::cast(self.original_token.clone()) {
917 self.ident_ctx = IdentContext::String {
919 expanded: ast::String::cast(self.token.clone()),
922 // Fix up trailing whitespace problem
924 let token = if self.token.kind() == SyntaxKind::WHITESPACE {
925 self.previous_token.as_ref()?
929 let p = token.parent()?;
930 if p.kind() == SyntaxKind::TOKEN_TREE
931 && p.ancestors().any(|it| it.kind() == SyntaxKind::META)
933 self.ident_ctx = IdentContext::UnexpandedAttrTT {
934 fake_attribute_under_caret: syntax_element
936 .find_map(ast::Attr::cast),
945 self.completion_location =
946 determine_location(&self.sema, original_file, offset, &name_like);
947 self.prev_sibling = determine_prev_sibling(&name_like);
950 .token_ancestors_with_macros(self.token.clone())
951 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
952 .find_map(ast::Impl::cast);
953 self.function_def = self
955 .token_ancestors_with_macros(self.token.clone())
956 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
957 .find_map(ast::Fn::cast);
960 ast::NameLike::Lifetime(lifetime) => {
961 self.ident_ctx = IdentContext::Lifetime(Self::classify_lifetime(
967 ast::NameLike::NameRef(name_ref) => {
968 let parent = name_ref.syntax().parent()?;
969 let (nameref_ctx, pat_ctx) =
970 Self::classify_name_ref(&self.sema, &original_file, name_ref, parent);
971 self.ident_ctx = IdentContext::NameRef(nameref_ctx);
972 self.pattern_ctx = pat_ctx;
974 ast::NameLike::Name(name) => {
975 let (name_ctx, pat_ctx) = Self::classify_name(&self.sema, original_file, name)?;
976 self.pattern_ctx = pat_ctx;
977 self.ident_ctx = IdentContext::Name(name_ctx);
983 fn classify_lifetime(
984 _sema: &Semantics<RootDatabase>,
985 original_file: &SyntaxNode,
986 lifetime: ast::Lifetime,
987 ) -> Option<LifetimeContext> {
988 let parent = lifetime.syntax().parent()?;
989 if parent.kind() == ERROR {
993 let kind = match_ast! {
995 ast::LifetimeParam(param) => LifetimeKind::LifetimeParam {
996 is_decl: param.lifetime().as_ref() == Some(&lifetime),
999 ast::BreakExpr(_) => LifetimeKind::LabelRef,
1000 ast::ContinueExpr(_) => LifetimeKind::LabelRef,
1001 ast::Label(_) => LifetimeKind::LabelDef,
1002 _ => LifetimeKind::Lifetime,
1005 let lifetime = find_node_at_offset(&original_file, lifetime.syntax().text_range().start());
1007 Some(LifetimeContext { lifetime, kind })
1011 _sema: &Semantics<RootDatabase>,
1012 original_file: &SyntaxNode,
1014 ) -> Option<(NameContext, Option<PatternContext>)> {
1015 let parent = name.syntax().parent()?;
1016 let mut pat_ctx = None;
1017 let kind = match_ast! {
1019 ast::Const(_) => NameKind::Const,
1020 ast::ConstParam(_) => NameKind::ConstParam,
1021 ast::Enum(_) => NameKind::Enum,
1022 ast::Fn(_) => NameKind::Function,
1023 ast::IdentPat(bind_pat) => {
1025 let mut pat_ctx = pattern_context_for(original_file, bind_pat.into());
1026 if let Some(record_field) = ast::RecordPatField::for_field_name(&name) {
1027 pat_ctx.record_pat = find_node_in_file_compensated(original_file, &record_field.parent_record_pat());
1034 ast::MacroDef(_) => NameKind::MacroDef,
1035 ast::MacroRules(_) => NameKind::MacroRules,
1036 ast::Module(module) => NameKind::Module(module),
1037 ast::RecordField(_) => NameKind::RecordField,
1038 ast::Rename(_) => NameKind::Rename,
1039 ast::SelfParam(_) => NameKind::SelfParam,
1040 ast::Static(_) => NameKind::Static,
1041 ast::Struct(_) => NameKind::Struct,
1042 ast::Trait(_) => NameKind::Trait,
1043 ast::TypeAlias(_) => NameKind::TypeAlias,
1044 ast::TypeParam(_) => NameKind::TypeParam,
1045 ast::Union(_) => NameKind::Union,
1046 ast::Variant(_) => NameKind::Variant,
1050 let name = find_node_at_offset(&original_file, name.syntax().text_range().start());
1051 Some((NameContext { name, kind }, pat_ctx))
1054 fn classify_name_ref(
1055 sema: &Semantics<RootDatabase>,
1056 original_file: &SyntaxNode,
1057 name_ref: ast::NameRef,
1059 ) -> (NameRefContext, Option<PatternContext>) {
1060 let nameref = find_node_at_offset(&original_file, name_ref.syntax().text_range().start());
1062 let mut nameref_ctx =
1063 NameRefContext { dot_access: None, path_ctx: None, nameref, record_expr: None };
1065 if let Some(record_field) = ast::RecordExprField::for_field_name(&name_ref) {
1066 nameref_ctx.record_expr =
1067 find_node_in_file_compensated(original_file, &record_field.parent_record_lit())
1069 return (nameref_ctx, None);
1071 if let Some(record_field) = ast::RecordPatField::for_field_name_ref(&name_ref) {
1073 pattern_context_for(original_file, record_field.parent_record_pat().clone().into());
1076 Some(PatternContext {
1078 has_type_ascription: false,
1081 record_pat: find_node_in_file_compensated(
1083 &record_field.parent_record_pat(),
1090 let segment = match_ast! {
1092 ast::PathSegment(segment) => segment,
1093 ast::FieldExpr(field) => {
1094 let receiver = find_in_original_file(field.expr(), original_file);
1095 let receiver_is_ambiguous_float_literal = match &receiver {
1096 Some(ast::Expr::Literal(l)) => matches! {
1098 ast::LiteralKind::FloatNumber { .. } if l.syntax().last_token().map_or(false, |it| it.text().ends_with('.'))
1102 nameref_ctx.dot_access = Some(DotAccess {
1103 receiver_ty: receiver.as_ref().and_then(|it| sema.type_of_expr(it)),
1104 kind: DotAccessKind::Field { receiver_is_ambiguous_float_literal },
1107 return (nameref_ctx, None);
1109 ast::MethodCallExpr(method) => {
1110 let receiver = find_in_original_file(method.receiver(), original_file);
1111 nameref_ctx.dot_access = Some(DotAccess {
1112 receiver_ty: receiver.as_ref().and_then(|it| sema.type_of_expr(it)),
1113 kind: DotAccessKind::Method { has_parens: method.arg_list().map_or(false, |it| it.l_paren_token().is_some()) },
1116 return (nameref_ctx, None);
1118 _ => return (nameref_ctx, None),
1122 let path = segment.parent_path();
1123 let mut path_ctx = PathCompletionCtx {
1124 has_call_parens: false,
1125 has_macro_bang: false,
1126 is_absolute_path: false,
1128 parent: path.parent_path(),
1129 kind: PathKind::Item { kind: ItemListKind::SourceFile },
1130 has_type_args: false,
1132 let mut pat_ctx = None;
1134 let is_in_block = |it: &SyntaxNode| {
1137 ast::ExprStmt::can_cast(node.kind()) || ast::StmtList::can_cast(node.kind())
1141 let mut fill_record_expr = |syn: &SyntaxNode| {
1142 if let Some(record_expr) = syn.ancestors().nth(2).and_then(ast::RecordExpr::cast) {
1143 nameref_ctx.record_expr =
1144 find_node_in_file_compensated(original_file, &record_expr).zip(Some(true));
1148 let kind = path.syntax().ancestors().find_map(|it| {
1149 // using Option<Option<PathKind>> as extra controlflow
1150 let kind = match_ast! {
1152 ast::PathType(_) => Some(PathKind::Type),
1153 ast::PathExpr(it) => {
1154 fill_record_expr(it.syntax());
1156 path_ctx.has_call_parens = it.syntax().parent().map_or(false, |it| ast::CallExpr::can_cast(it.kind()));
1157 let in_block_expr = is_in_block(it.syntax());
1158 let in_loop_body = is_in_loop_body(it.syntax());
1159 Some(PathKind::Expr { in_block_expr, in_loop_body })
1161 ast::TupleStructPat(it) => {
1162 path_ctx.has_call_parens = true;
1163 pat_ctx = Some(pattern_context_for(original_file, it.into()));
1166 ast::RecordPat(it) => {
1167 path_ctx.has_call_parens = true;
1168 pat_ctx = Some(pattern_context_for(original_file, it.into()));
1171 ast::PathPat(it) => {
1172 pat_ctx = Some(pattern_context_for(original_file, it.into()));
1175 ast::MacroCall(it) => {
1176 path_ctx.has_macro_bang = it.excl_token().is_some();
1177 let parent = it.syntax().parent();
1178 match parent.as_ref().map(|it| it.kind()) {
1179 Some(SyntaxKind::MACRO_PAT) => Some(PathKind::Pat),
1180 Some(SyntaxKind::MACRO_TYPE) => Some(PathKind::Type),
1181 Some(SyntaxKind::ITEM_LIST) => Some(PathKind::Item { kind: ItemListKind::Module }),
1182 Some(SyntaxKind::ASSOC_ITEM_LIST) => Some(PathKind::Item { kind: match parent.and_then(|it| it.parent()).map(|it| it.kind()) {
1183 Some(SyntaxKind::TRAIT) => ItemListKind::Trait,
1184 Some(SyntaxKind::IMPL) => ItemListKind::Impl,
1185 _ => return Some(None),
1187 Some(SyntaxKind::EXTERN_ITEM_LIST) => Some(PathKind::Item { kind: ItemListKind::ExternBlock }),
1188 Some(SyntaxKind::SOURCE_FILE) => Some(PathKind::Item { kind: ItemListKind::SourceFile }),
1190 return Some(parent.and_then(ast::MacroExpr::cast).map(|it| {
1191 let in_loop_body = is_in_loop_body(it.syntax());
1192 let in_block_expr = is_in_block(it.syntax());
1193 fill_record_expr(it.syntax());
1194 PathKind::Expr { in_block_expr, in_loop_body }
1199 ast::Meta(meta) => (|| {
1200 let attr = meta.parent_attr()?;
1201 let kind = attr.kind();
1202 let attached = attr.syntax().parent()?;
1203 let is_trailing_outer_attr = kind != AttrKind::Inner
1204 && non_trivia_sibling(attr.syntax().clone().into(), syntax::Direction::Next).is_none();
1205 let annotated_item_kind = if is_trailing_outer_attr {
1208 Some(attached.kind())
1210 Some(PathKind::Attr {
1212 annotated_item_kind,
1215 ast::Visibility(it) => Some(PathKind::Vis { has_in_token: it.in_token().is_some() }),
1216 ast::UseTree(_) => Some(PathKind::Use),
1217 ast::ItemList(_) => Some(PathKind::Item { kind: ItemListKind::Module }),
1218 ast::AssocItemList(it) => Some(PathKind::Item { kind: {
1219 match it.syntax().parent()?.kind() {
1220 SyntaxKind::TRAIT => ItemListKind::Trait,
1221 SyntaxKind::IMPL => ItemListKind::Impl,
1225 ast::ExternItemList(_) => Some(PathKind::Item { kind: ItemListKind::ExternBlock }),
1226 ast::SourceFile(_) => Some(PathKind::Item { kind: ItemListKind::SourceFile }),
1233 Some(kind) => path_ctx.kind = kind,
1234 None => return (nameref_ctx, pat_ctx),
1236 path_ctx.has_type_args = segment.generic_arg_list().is_some();
1238 if let Some((path, use_tree_parent)) = path_or_use_tree_qualifier(&path) {
1239 if !use_tree_parent {
1240 path_ctx.is_absolute_path =
1241 path.top_path().segment().map_or(false, |it| it.coloncolon_token().is_some());
1246 .and_then(|it| find_node_in_file(original_file, &it))
1247 .map(|it| it.parent_path());
1248 path_ctx.qualifier = path.map(|path| {
1249 let res = sema.resolve_path(&path);
1250 let is_super_chain = iter::successors(Some(path.clone()), |p| p.qualifier())
1251 .all(|p| p.segment().and_then(|s| s.super_token()).is_some());
1254 let is_infer_qualifier = path.qualifier().is_none()
1256 path.segment().and_then(|it| it.kind()),
1257 Some(ast::PathSegmentKind::Type {
1258 type_ref: Some(ast::Type::InferType(_)),
1271 } else if let Some(segment) = path.segment() {
1272 if segment.coloncolon_token().is_some() {
1273 path_ctx.is_absolute_path = true;
1276 nameref_ctx.path_ctx = Some(path_ctx);
1277 (nameref_ctx, pat_ctx)
1281 fn pattern_context_for(original_file: &SyntaxNode, pat: ast::Pat) -> PatternContext {
1282 let mut is_param = None;
1283 let (refutability, has_type_ascription) =
1287 .skip_while(|it| ast::Pat::can_cast(it.kind()))
1289 .map_or((PatternRefutability::Irrefutable, false), |node| {
1290 let refutability = match_ast! {
1292 ast::LetStmt(let_) => return (PatternRefutability::Irrefutable, let_.ty().is_some()),
1293 ast::Param(param) => {
1294 let has_type_ascription = param.ty().is_some();
1296 let fake_param_list = param.syntax().parent().and_then(ast::ParamList::cast)?;
1297 let param_list = find_node_in_file_compensated(original_file, &fake_param_list)?;
1298 let param_list_owner = param_list.syntax().parent()?;
1299 let kind = match_ast! {
1300 match param_list_owner {
1301 ast::ClosureExpr(closure) => ParamKind::Closure(closure),
1302 ast::Fn(fn_) => ParamKind::Function(fn_),
1306 Some((param_list, param, kind))
1308 return (PatternRefutability::Irrefutable, has_type_ascription)
1310 ast::MatchArm(_) => PatternRefutability::Refutable,
1311 ast::LetExpr(_) => PatternRefutability::Refutable,
1312 ast::ForExpr(_) => PatternRefutability::Irrefutable,
1313 _ => PatternRefutability::Irrefutable,
1316 (refutability, false)
1318 let (ref_token, mut_token) = match &pat {
1319 ast::Pat::IdentPat(it) => (it.ref_token(), it.mut_token()),
1324 param_ctx: is_param,
1325 has_type_ascription,
1326 parent_pat: pat.syntax().parent().and_then(ast::Pat::cast),
1333 fn find_in_original_file<N: AstNode>(x: Option<N>, original_file: &SyntaxNode) -> Option<N> {
1334 fn find_node_with_range<N: AstNode>(syntax: &SyntaxNode, range: TextRange) -> Option<N> {
1335 let range = syntax.text_range().intersect(range)?;
1336 syntax.covering_element(range).ancestors().find_map(N::cast)
1338 x.map(|e| e.syntax().text_range()).and_then(|r| find_node_with_range(original_file, r))
1341 /// Attempts to find `node` inside `syntax` via `node`'s text range.
1342 fn find_node_in_file<N: AstNode>(syntax: &SyntaxNode, node: &N) -> Option<N> {
1343 let syntax_range = syntax.text_range();
1344 let range = node.syntax().text_range();
1345 let intersection = range.intersect(syntax_range)?;
1346 syntax.covering_element(intersection).ancestors().find_map(N::cast)
1349 /// Attempts to find `node` inside `syntax` via `node`'s text range while compensating
1350 /// for the offset introduced by the fake ident.
1351 /// This is wrong if `node` comes before the insertion point! Use `find_node_in_file` instead.
1352 fn find_node_in_file_compensated<N: AstNode>(syntax: &SyntaxNode, node: &N) -> Option<N> {
1353 let syntax_range = syntax.text_range();
1354 let range = node.syntax().text_range();
1355 let end = range.end().checked_sub(TextSize::try_from(COMPLETION_MARKER.len()).ok()?)?;
1356 if end < range.start() {
1359 let range = TextRange::new(range.start(), end);
1360 // our inserted ident could cause `range` to be go outside of the original syntax, so cap it
1361 let intersection = range.intersect(syntax_range)?;
1362 syntax.covering_element(intersection).ancestors().find_map(N::cast)
1365 fn path_or_use_tree_qualifier(path: &ast::Path) -> Option<(ast::Path, bool)> {
1366 if let Some(qual) = path.qualifier() {
1367 return Some((qual, false));
1369 let use_tree_list = path.syntax().ancestors().find_map(ast::UseTreeList::cast)?;
1370 let use_tree = use_tree_list.syntax().parent().and_then(ast::UseTree::cast)?;
1371 Some((use_tree.path()?, true))
1374 fn has_ref(token: &SyntaxToken) -> bool {
1375 let mut token = token.clone();
1376 for skip in [IDENT, WHITESPACE, T![mut]] {
1377 if token.kind() == skip {
1378 token = match token.prev_token() {
1380 None => return false,
1384 token.kind() == T![&]
1387 const OP_TRAIT_LANG_NAMES: &[&str] = &[
1422 use expect_test::{expect, Expect};
1423 use hir::HirDisplay;
1425 use crate::tests::{position, TEST_CONFIG};
1427 use super::CompletionContext;
1429 fn check_expected_type_and_name(ra_fixture: &str, expect: Expect) {
1430 let (db, pos) = position(ra_fixture);
1431 let config = TEST_CONFIG;
1432 let completion_context = CompletionContext::new(&db, pos, &config).unwrap();
1434 let ty = completion_context
1436 .map(|t| t.display_test(&db).to_string())
1437 .unwrap_or("?".to_owned());
1439 let name = completion_context
1441 .map_or_else(|| "?".to_owned(), |name| name.to_string());
1443 expect.assert_eq(&format!("ty: {}, name: {}", ty, name));
1447 fn expected_type_let_without_leading_char() {
1448 cov_mark::check!(expected_type_let_without_leading_char);
1449 check_expected_type_and_name(
1455 expect![[r#"ty: u32, name: x"#]],
1460 fn expected_type_let_with_leading_char() {
1461 cov_mark::check!(expected_type_let_with_leading_char);
1462 check_expected_type_and_name(
1468 expect![[r#"ty: u32, name: x"#]],
1473 fn expected_type_let_pat() {
1474 check_expected_type_and_name(
1480 expect![[r#"ty: u32, name: ?"#]],
1482 check_expected_type_and_name(
1488 expect![[r#"ty: u32, name: ?"#]],
1493 fn expected_type_fn_param() {
1494 cov_mark::check!(expected_type_fn_param);
1495 check_expected_type_and_name(
1497 fn foo() { bar($0); }
1500 expect![[r#"ty: u32, name: x"#]],
1502 check_expected_type_and_name(
1504 fn foo() { bar(c$0); }
1507 expect![[r#"ty: u32, name: x"#]],
1512 fn expected_type_fn_param_ref() {
1513 cov_mark::check!(expected_type_fn_param_ref);
1514 check_expected_type_and_name(
1516 fn foo() { bar(&$0); }
1519 expect![[r#"ty: u32, name: x"#]],
1521 check_expected_type_and_name(
1523 fn foo() { bar(&mut $0); }
1524 fn bar(x: &mut u32) {}
1526 expect![[r#"ty: u32, name: x"#]],
1528 check_expected_type_and_name(
1530 fn foo() { bar(& c$0); }
1533 expect![[r#"ty: u32, name: x"#]],
1535 check_expected_type_and_name(
1537 fn foo() { bar(&mut c$0); }
1538 fn bar(x: &mut u32) {}
1540 expect![[r#"ty: u32, name: x"#]],
1542 check_expected_type_and_name(
1544 fn foo() { bar(&c$0); }
1547 expect![[r#"ty: u32, name: x"#]],
1552 fn expected_type_struct_field_without_leading_char() {
1553 cov_mark::check!(expected_type_struct_field_without_leading_char);
1554 check_expected_type_and_name(
1556 struct Foo { a: u32 }
1561 expect![[r#"ty: u32, name: a"#]],
1566 fn expected_type_struct_field_followed_by_comma() {
1567 cov_mark::check!(expected_type_struct_field_followed_by_comma);
1568 check_expected_type_and_name(
1570 struct Foo { a: u32 }
1575 expect![[r#"ty: u32, name: a"#]],
1580 fn expected_type_generic_struct_field() {
1581 check_expected_type_and_name(
1583 struct Foo<T> { a: T }
1584 fn foo() -> Foo<u32> {
1588 expect![[r#"ty: u32, name: a"#]],
1593 fn expected_type_struct_field_with_leading_char() {
1594 cov_mark::check!(expected_type_struct_field_with_leading_char);
1595 check_expected_type_and_name(
1597 struct Foo { a: u32 }
1602 expect![[r#"ty: u32, name: a"#]],
1607 fn expected_type_match_arm_without_leading_char() {
1608 cov_mark::check!(expected_type_match_arm_without_leading_char);
1609 check_expected_type_and_name(
1616 expect![[r#"ty: E, name: ?"#]],
1621 fn expected_type_match_arm_with_leading_char() {
1622 cov_mark::check!(expected_type_match_arm_with_leading_char);
1623 check_expected_type_and_name(
1630 expect![[r#"ty: E, name: ?"#]],
1635 fn expected_type_match_arm_body_without_leading_char() {
1636 cov_mark::check!(expected_type_match_arm_body_without_leading_char);
1637 check_expected_type_and_name(
1642 match E::X { E::X => $0 }
1645 expect![[r#"ty: Foo, name: ?"#]],
1650 fn expected_type_match_body_arm_with_leading_char() {
1651 cov_mark::check!(expected_type_match_arm_body_with_leading_char);
1652 check_expected_type_and_name(
1657 match E::X { E::X => c$0 }
1660 expect![[r#"ty: Foo, name: ?"#]],
1665 fn expected_type_if_let_without_leading_char() {
1666 cov_mark::check!(expected_type_if_let_without_leading_char);
1667 check_expected_type_and_name(
1669 enum Foo { Bar, Baz, Quux }
1676 expect![[r#"ty: Foo, name: ?"#]],
1681 fn expected_type_if_let_with_leading_char() {
1682 cov_mark::check!(expected_type_if_let_with_leading_char);
1683 check_expected_type_and_name(
1685 enum Foo { Bar, Baz, Quux }
1692 expect![[r#"ty: Foo, name: ?"#]],
1697 fn expected_type_fn_ret_without_leading_char() {
1698 cov_mark::check!(expected_type_fn_ret_without_leading_char);
1699 check_expected_type_and_name(
1705 expect![[r#"ty: u32, name: ?"#]],
1710 fn expected_type_fn_ret_with_leading_char() {
1711 cov_mark::check!(expected_type_fn_ret_with_leading_char);
1712 check_expected_type_and_name(
1718 expect![[r#"ty: u32, name: ?"#]],
1723 fn expected_type_fn_ret_fn_ref_fully_typed() {
1724 check_expected_type_and_name(
1730 expect![[r#"ty: u32, name: ?"#]],
1735 fn expected_type_closure_param_return() {
1736 // FIXME: make this work with `|| $0`
1737 check_expected_type_and_name(
1744 fn bar(f: impl FnOnce() -> u32) {}
1746 expect![[r#"ty: u32, name: ?"#]],
1751 fn expected_type_generic_function() {
1752 check_expected_type_and_name(
1760 expect![[r#"ty: u32, name: t"#]],
1765 fn expected_type_generic_method() {
1766 check_expected_type_and_name(
1774 fn bar(self, t: T) {}
1777 expect![[r#"ty: u32, name: t"#]],
1782 fn expected_type_functional_update() {
1783 cov_mark::check!(expected_type_struct_func_update);
1784 check_expected_type_and_name(
1786 struct Foo { field: u32 }
1793 expect![[r#"ty: Foo, name: ?"#]],
1798 fn expected_type_param_pat() {
1799 check_expected_type_and_name(
1801 struct Foo { field: u32 }
1804 expect![[r#"ty: Foo, name: ?"#]],
1806 check_expected_type_and_name(
1808 struct Foo { field: u32 }
1811 // FIXME make this work, currently fails due to pattern recovery eating the `:`
1812 expect![[r#"ty: ?, name: ?"#]],