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_variant(&self) -> bool {
326 matches!(self.name_ctx(), Some(NameContext { kind: NameKind::Variant, .. }))
329 pub(crate) fn expects_non_trait_assoc_item(&self) -> bool {
330 matches!(self.completion_location, Some(ImmediateLocation::Impl))
333 pub(crate) fn expects_item(&self) -> bool {
334 matches!(self.completion_location, Some(ImmediateLocation::ItemList))
337 // FIXME: This shouldn't exist
338 pub(crate) fn expects_generic_arg(&self) -> bool {
339 matches!(self.completion_location, Some(ImmediateLocation::GenericArgList(_)))
342 pub(crate) fn has_block_expr_parent(&self) -> bool {
343 matches!(self.completion_location, Some(ImmediateLocation::StmtList))
346 pub(crate) fn expects_ident_ref_expr(&self) -> bool {
347 matches!(self.completion_location, Some(ImmediateLocation::RefExpr))
350 pub(crate) fn expect_field(&self) -> bool {
351 matches!(self.completion_location, Some(ImmediateLocation::TupleField))
352 || matches!(self.name_ctx(), Some(NameContext { kind: NameKind::RecordField, .. }))
355 /// Whether the cursor is right after a trait or impl header.
356 /// trait Foo ident$0
357 // FIXME: This probably shouldn't exist
358 pub(crate) fn has_unfinished_impl_or_trait_prev_sibling(&self) -> bool {
361 Some(ImmediatePrevSibling::ImplDefType | ImmediatePrevSibling::TraitDefName)
365 // FIXME: This probably shouldn't exist
366 pub(crate) fn has_impl_prev_sibling(&self) -> bool {
367 matches!(self.prev_sibling, Some(ImmediatePrevSibling::ImplDefType))
370 pub(crate) fn has_visibility_prev_sibling(&self) -> bool {
371 matches!(self.prev_sibling, Some(ImmediatePrevSibling::Visibility))
374 pub(crate) fn after_if(&self) -> bool {
375 matches!(self.prev_sibling, Some(ImmediatePrevSibling::IfExpr))
378 // FIXME: This shouldn't exist
379 pub(crate) fn is_path_disallowed(&self) -> bool {
380 self.previous_token_is(T![unsafe])
381 || matches!(self.prev_sibling, Some(ImmediatePrevSibling::Visibility))
384 Some(NameContext { kind: NameKind::Module(_) | NameKind::Rename, .. })
386 || matches!(self.pattern_ctx, Some(PatternContext { record_pat: Some(_), .. }))
389 Some(NameRefContext { record_expr: Some((_, false)), .. })
393 pub(crate) fn path_context(&self) -> Option<&PathCompletionCtx> {
394 self.nameref_ctx().and_then(|ctx| ctx.path_ctx.as_ref())
397 pub(crate) fn expects_expression(&self) -> bool {
398 matches!(self.path_context(), Some(PathCompletionCtx { kind: PathKind::Expr { .. }, .. }))
401 pub(crate) fn is_non_trivial_path(&self) -> bool {
405 PathCompletionCtx { is_absolute_path: true, .. }
406 | PathCompletionCtx { qualifier: Some(_), .. }
411 pub(crate) fn path_qual(&self) -> Option<&ast::Path> {
412 self.path_context().and_then(|it| it.qualifier.as_ref().map(|it| &it.path))
415 pub(crate) fn path_kind(&self) -> Option<PathKind> {
416 self.path_context().map(|it| it.kind)
419 /// Checks if an item is visible and not `doc(hidden)` at the completion site.
420 pub(crate) fn is_visible<I>(&self, item: &I) -> Visible
422 I: hir::HasVisibility + hir::HasAttrs + hir::HasCrate + Copy,
424 self.is_visible_impl(&item.visibility(self.db), &item.attrs(self.db), item.krate(self.db))
427 pub(crate) fn is_scope_def_hidden(&self, scope_def: ScopeDef) -> bool {
428 if let (Some(attrs), Some(krate)) = (scope_def.attrs(self.db), scope_def.krate(self.db)) {
429 return self.is_doc_hidden(&attrs, krate);
435 /// Check if an item is `#[doc(hidden)]`.
436 pub(crate) fn is_item_hidden(&self, item: &hir::ItemInNs) -> bool {
437 let attrs = item.attrs(self.db);
438 let krate = item.krate(self.db);
439 match (attrs, krate) {
440 (Some(attrs), Some(krate)) => self.is_doc_hidden(&attrs, krate),
444 /// Whether the given trait is an operator trait or not.
445 pub(crate) fn is_ops_trait(&self, trait_: hir::Trait) -> bool {
446 match trait_.attrs(self.db).lang() {
447 Some(lang) => OP_TRAIT_LANG_NAMES.contains(&lang.as_str()),
452 /// Returns the traits in scope, with the [`Drop`] trait removed.
453 pub(crate) fn traits_in_scope(&self) -> hir::VisibleTraits {
454 let mut traits_in_scope = self.scope.visible_traits();
455 if let Some(drop) = self.famous_defs().core_ops_Drop() {
456 traits_in_scope.0.remove(&drop.into());
461 /// A version of [`SemanticsScope::process_all_names`] that filters out `#[doc(hidden)]` items.
462 pub(crate) fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
463 let _p = profile::span("CompletionContext::process_all_names");
464 self.scope.process_all_names(&mut |name, def| {
465 if self.is_scope_def_hidden(def) {
473 pub(crate) fn process_all_names_raw(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
474 let _p = profile::span("CompletionContext::process_all_names_raw");
475 self.scope.process_all_names(&mut |name, def| f(name, def));
480 vis: &hir::Visibility,
482 defining_crate: hir::Crate,
484 if !vis.is_visible_from(self.db, self.module.into()) {
485 if !self.config.enable_private_editable {
488 // If the definition location is editable, also show private items
489 let root_file = defining_crate.root_file(self.db);
490 let source_root_id = self.db.file_source_root(root_file);
491 let is_editable = !self.db.source_root(source_root_id).is_library;
492 return if is_editable { Visible::Editable } else { Visible::No };
495 if self.is_doc_hidden(attrs, defining_crate) {
502 fn is_doc_hidden(&self, attrs: &hir::Attrs, defining_crate: hir::Crate) -> bool {
503 // `doc(hidden)` items are only completed within the defining crate.
504 self.krate != defining_crate && attrs.has_doc_hidden()
508 // CompletionContext construction
509 impl<'a> CompletionContext<'a> {
511 db: &'a RootDatabase,
512 position @ FilePosition { file_id, offset }: FilePosition,
513 config: &'a CompletionConfig,
514 ) -> Option<CompletionContext<'a>> {
515 let _p = profile::span("CompletionContext::new");
516 let sema = Semantics::new(db);
518 let original_file = sema.parse(file_id);
520 // Insert a fake ident to get a valid parse tree. We will use this file
521 // to determine context, though the original_file will be used for
522 // actual completion.
523 let file_with_fake_ident = {
524 let parse = db.parse(file_id);
525 let edit = Indel::insert(offset, COMPLETION_MARKER.to_string());
526 parse.reparse(&edit).tree()
528 let fake_ident_token =
529 file_with_fake_ident.syntax().token_at_offset(offset).right_biased()?;
531 let original_token = original_file.syntax().token_at_offset(offset).left_biased()?;
532 let token = sema.descend_into_macros_single(original_token.clone());
533 let scope = sema.scope_at_offset(&token.parent()?, offset)?;
534 let krate = scope.krate();
535 let module = scope.module();
537 let mut locals = FxHashMap::default();
538 scope.process_all_names(&mut |name, scope| {
539 if let ScopeDef::Local(local) = scope {
540 locals.insert(name, local);
544 let mut ctx = CompletionContext {
558 incomplete_let: false,
559 completion_location: None,
561 previous_token: None,
562 // dummy value, will be overwritten
563 ident_ctx: IdentContext::UnexpandedAttrTT { fake_attribute_under_caret: None },
565 existing_derives: Default::default(),
569 original_file.syntax().clone(),
570 file_with_fake_ident.syntax().clone(),
577 /// Expand attributes and macro calls at the current cursor position for both the original file
578 /// and fake file repeatedly. As soon as one of the two expansions fail we stop so the original
579 /// and speculative states stay in sync.
582 mut original_file: SyntaxNode,
583 mut speculative_file: SyntaxNode,
584 mut offset: TextSize,
585 mut fake_ident_token: SyntaxToken,
587 let _p = profile::span("CompletionContext::expand_and_fill");
588 let mut derive_ctx = None;
592 |item: &ast::Item| item.syntax().ancestors().skip(1).find_map(ast::Item::cast);
593 let ancestor_items = iter::successors(
595 find_node_at_offset::<ast::Item>(&original_file, offset),
596 find_node_at_offset::<ast::Item>(&speculative_file, offset),
598 |(a, b)| parent_item(a).zip(parent_item(b)),
601 // first try to expand attributes as these are always the outermost macro calls
602 'ancestors: for (actual_item, item_with_fake_ident) in ancestor_items {
604 self.sema.expand_attr_macro(&actual_item),
605 self.sema.speculative_expand_attr_macro(
607 &item_with_fake_ident,
608 fake_ident_token.clone(),
611 // maybe parent items have attributes, so continue walking the ancestors
612 (None, None) => continue 'ancestors,
613 // successful expansions
614 (Some(actual_expansion), Some((fake_expansion, fake_mapped_token))) => {
615 let new_offset = fake_mapped_token.text_range().start();
616 if new_offset > actual_expansion.text_range().end() {
617 // offset outside of bounds from the original expansion,
618 // stop here to prevent problems from happening
621 original_file = actual_expansion;
622 speculative_file = fake_expansion;
623 fake_ident_token = fake_mapped_token;
627 // exactly one expansion failed, inconsistent state so stop expanding completely
628 _ => break 'expansion,
632 // No attributes have been expanded, so look for macro_call! token trees or derive token trees
633 let orig_tt = match find_node_at_offset::<ast::TokenTree>(&original_file, offset) {
635 None => break 'expansion,
637 let spec_tt = match find_node_at_offset::<ast::TokenTree>(&speculative_file, offset) {
639 None => break 'expansion,
642 // Expand pseudo-derive expansion
643 if let (Some(orig_attr), Some(spec_attr)) = (
644 orig_tt.syntax().parent().and_then(ast::Meta::cast).and_then(|it| it.parent_attr()),
645 spec_tt.syntax().parent().and_then(ast::Meta::cast).and_then(|it| it.parent_attr()),
647 if let (Some(actual_expansion), Some((fake_expansion, fake_mapped_token))) = (
648 self.sema.expand_derive_as_pseudo_attr_macro(&orig_attr),
649 self.sema.speculative_expand_derive_as_pseudo_attr_macro(
652 fake_ident_token.clone(),
658 fake_mapped_token.text_range().start(),
662 // at this point we won't have any more successful expansions, so stop
666 // Expand fn-like macro calls
667 if let (Some(actual_macro_call), Some(macro_call_with_fake_ident)) = (
668 orig_tt.syntax().ancestors().find_map(ast::MacroCall::cast),
669 spec_tt.syntax().ancestors().find_map(ast::MacroCall::cast),
671 let mac_call_path0 = actual_macro_call.path().as_ref().map(|s| s.syntax().text());
673 macro_call_with_fake_ident.path().as_ref().map(|s| s.syntax().text());
675 // inconsistent state, stop expanding
676 if mac_call_path0 != mac_call_path1 {
679 let speculative_args = match macro_call_with_fake_ident.token_tree() {
681 None => break 'expansion,
685 self.sema.expand(&actual_macro_call),
686 self.sema.speculative_expand(
689 fake_ident_token.clone(),
692 // successful expansions
693 (Some(actual_expansion), Some((fake_expansion, fake_mapped_token))) => {
694 let new_offset = fake_mapped_token.text_range().start();
695 if new_offset > actual_expansion.text_range().end() {
696 // offset outside of bounds from the original expansion,
697 // stop here to prevent problems from happening
700 original_file = actual_expansion;
701 speculative_file = fake_expansion;
702 fake_ident_token = fake_mapped_token;
706 // at least on expansion failed, we won't have anything to expand from this point
707 // onwards so break out
708 _ => break 'expansion,
712 // none of our states have changed so stop the loop
716 self.fill(&original_file, speculative_file, offset, derive_ctx)
719 /// Calculate the expected type and name of the cursor position.
720 fn expected_type_and_name(&self) -> (Option<Type>, Option<NameOrNameRef>) {
721 let mut node = match self.token.parent() {
723 None => return (None, None),
728 ast::LetStmt(it) => {
729 cov_mark::hit!(expected_type_let_with_leading_char);
730 cov_mark::hit!(expected_type_let_without_leading_char);
732 .and_then(|pat| self.sema.type_of_pat(&pat))
733 .or_else(|| it.initializer().and_then(|it| self.sema.type_of_expr(&it)))
734 .map(TypeInfo::original);
735 let name = match it.pat() {
736 Some(ast::Pat::IdentPat(ident)) => ident.name().map(NameOrNameRef::Name),
737 Some(_) | None => None,
742 ast::LetExpr(it) => {
743 cov_mark::hit!(expected_type_if_let_without_leading_char);
745 .and_then(|pat| self.sema.type_of_pat(&pat))
746 .or_else(|| it.expr().and_then(|it| self.sema.type_of_expr(&it)))
747 .map(TypeInfo::original);
751 cov_mark::hit!(expected_type_fn_param);
752 ActiveParameter::at_token(
756 let name = ap.ident().map(NameOrNameRef::Name);
757 let ty = if has_ref(&self.token) {
758 cov_mark::hit!(expected_type_fn_param_ref);
765 .unwrap_or((None, None))
767 ast::RecordExprFieldList(it) => {
768 // wouldn't try {} be nice...
770 if self.token.kind() == T![..]
771 || self.token.prev_token().map(|t| t.kind()) == Some(T![..])
773 cov_mark::hit!(expected_type_struct_func_update);
774 let record_expr = it.syntax().parent().and_then(ast::RecordExpr::cast)?;
775 let ty = self.sema.type_of_expr(&record_expr.into())?;
781 cov_mark::hit!(expected_type_struct_field_without_leading_char);
782 let expr_field = self.token.prev_sibling_or_token()?
784 .and_then(ast::RecordExprField::cast)?;
785 let (_, _, ty) = self.sema.resolve_record_field(&expr_field)?;
788 expr_field.field_name().map(NameOrNameRef::NameRef),
791 })().unwrap_or((None, None))
793 ast::RecordExprField(it) => {
794 if let Some(expr) = it.expr() {
795 cov_mark::hit!(expected_type_struct_field_with_leading_char);
797 self.sema.type_of_expr(&expr).map(TypeInfo::original),
798 it.field_name().map(NameOrNameRef::NameRef),
801 cov_mark::hit!(expected_type_struct_field_followed_by_comma);
802 let ty = self.sema.resolve_record_field(&it)
803 .map(|(_, _, ty)| ty);
806 it.field_name().map(NameOrNameRef::NameRef),
811 // match foo { ..., pat => $0 }
812 ast::MatchExpr(it) => {
813 let ty = if self.previous_token_is(T![=>]) {
814 // match foo { ..., pat => $0 }
815 cov_mark::hit!(expected_type_match_arm_body_without_leading_char);
816 cov_mark::hit!(expected_type_match_arm_body_with_leading_char);
817 self.sema.type_of_expr(&it.into())
820 cov_mark::hit!(expected_type_match_arm_without_leading_char);
821 it.expr().and_then(|e| self.sema.type_of_expr(&e))
822 }.map(TypeInfo::original);
826 let ty = it.condition()
827 .and_then(|e| self.sema.type_of_expr(&e))
828 .map(TypeInfo::original);
831 ast::IdentPat(it) => {
832 cov_mark::hit!(expected_type_if_let_with_leading_char);
833 cov_mark::hit!(expected_type_match_arm_with_leading_char);
834 let ty = self.sema.type_of_pat(&ast::Pat::from(it)).map(TypeInfo::original);
838 cov_mark::hit!(expected_type_fn_ret_with_leading_char);
839 cov_mark::hit!(expected_type_fn_ret_without_leading_char);
840 let def = self.sema.to_def(&it);
841 (def.map(|def| def.ret_type(self.db)), None)
843 ast::ClosureExpr(it) => {
844 let ty = self.sema.type_of_expr(&it.into());
845 ty.and_then(|ty| ty.original.as_callable(self.db))
846 .map(|c| (Some(c.return_type()), None))
847 .unwrap_or((None, None))
849 ast::ParamList(_) => (None, None),
850 ast::Stmt(_) => (None, None),
851 ast::Item(_) => (None, None),
853 match node.parent() {
858 None => (None, None),
866 /// Fill the completion context, this is what does semantic reasoning about the surrounding context
867 /// of the completion location.
870 original_file: &SyntaxNode,
871 file_with_fake_ident: SyntaxNode,
873 derive_ctx: Option<(SyntaxNode, SyntaxNode, TextSize, ast::Attr)>,
875 let fake_ident_token = file_with_fake_ident.token_at_offset(offset).right_biased().unwrap();
876 let syntax_element = NodeOrToken::Token(fake_ident_token);
877 if is_in_token_of_for_loop(syntax_element.clone()) {
879 // there is nothing to complete here except `in` keyword
880 // don't bother populating the context
881 // FIXME: the completion calculations should end up good enough
882 // such that this special case becomes unnecessary
886 self.previous_token = previous_token(syntax_element.clone());
888 self.incomplete_let =
889 syntax_element.ancestors().take(6).find_map(ast::LetStmt::cast).map_or(false, |it| {
890 it.syntax().text_range().end() == syntax_element.text_range().end()
893 (self.expected_type, self.expected_name) = self.expected_type_and_name();
895 // Overwrite the path kind for derives
896 if let Some((original_file, file_with_fake_ident, offset, origin_attr)) = derive_ctx {
897 self.existing_derives = self
899 .resolve_derive_macro(&origin_attr)
905 if let Some(ast::NameLike::NameRef(name_ref)) =
906 find_node_at_offset(&file_with_fake_ident, offset)
908 let parent = name_ref.syntax().parent()?;
909 let (mut nameref_ctx, _) =
910 Self::classify_name_ref(&self.sema, &original_file, name_ref, parent);
911 if let Some(path_ctx) = &mut nameref_ctx.path_ctx {
912 path_ctx.kind = PathKind::Derive;
914 self.ident_ctx = IdentContext::NameRef(nameref_ctx);
920 let name_like = match find_node_at_offset(&file_with_fake_ident, offset) {
923 if let Some(original) = ast::String::cast(self.original_token.clone()) {
924 self.ident_ctx = IdentContext::String {
926 expanded: ast::String::cast(self.token.clone()),
929 // Fix up trailing whitespace problem
931 let token = if self.token.kind() == SyntaxKind::WHITESPACE {
932 self.previous_token.as_ref()?
936 let p = token.parent()?;
937 if p.kind() == SyntaxKind::TOKEN_TREE
938 && p.ancestors().any(|it| it.kind() == SyntaxKind::META)
940 self.ident_ctx = IdentContext::UnexpandedAttrTT {
941 fake_attribute_under_caret: syntax_element
943 .find_map(ast::Attr::cast),
952 self.completion_location =
953 determine_location(&self.sema, original_file, offset, &name_like);
954 self.prev_sibling = determine_prev_sibling(&name_like);
957 .token_ancestors_with_macros(self.token.clone())
958 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
959 .find_map(ast::Impl::cast);
960 self.function_def = self
962 .token_ancestors_with_macros(self.token.clone())
963 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
964 .find_map(ast::Fn::cast);
967 ast::NameLike::Lifetime(lifetime) => {
968 self.ident_ctx = IdentContext::Lifetime(Self::classify_lifetime(
974 ast::NameLike::NameRef(name_ref) => {
975 let parent = name_ref.syntax().parent()?;
976 let (nameref_ctx, pat_ctx) =
977 Self::classify_name_ref(&self.sema, &original_file, name_ref, parent);
978 self.ident_ctx = IdentContext::NameRef(nameref_ctx);
979 self.pattern_ctx = pat_ctx;
981 ast::NameLike::Name(name) => {
982 let (name_ctx, pat_ctx) = Self::classify_name(&self.sema, original_file, name)?;
983 self.pattern_ctx = pat_ctx;
984 self.ident_ctx = IdentContext::Name(name_ctx);
990 fn classify_lifetime(
991 _sema: &Semantics<RootDatabase>,
992 original_file: &SyntaxNode,
993 lifetime: ast::Lifetime,
994 ) -> Option<LifetimeContext> {
995 let parent = lifetime.syntax().parent()?;
996 if parent.kind() == ERROR {
1000 let kind = match_ast! {
1002 ast::LifetimeParam(param) => LifetimeKind::LifetimeParam {
1003 is_decl: param.lifetime().as_ref() == Some(&lifetime),
1006 ast::BreakExpr(_) => LifetimeKind::LabelRef,
1007 ast::ContinueExpr(_) => LifetimeKind::LabelRef,
1008 ast::Label(_) => LifetimeKind::LabelDef,
1009 _ => LifetimeKind::Lifetime,
1012 let lifetime = find_node_at_offset(&original_file, lifetime.syntax().text_range().start());
1014 Some(LifetimeContext { lifetime, kind })
1018 _sema: &Semantics<RootDatabase>,
1019 original_file: &SyntaxNode,
1021 ) -> Option<(NameContext, Option<PatternContext>)> {
1022 let parent = name.syntax().parent()?;
1023 let mut pat_ctx = None;
1024 let kind = match_ast! {
1026 ast::Const(_) => NameKind::Const,
1027 ast::ConstParam(_) => NameKind::ConstParam,
1028 ast::Enum(_) => NameKind::Enum,
1029 ast::Fn(_) => NameKind::Function,
1030 ast::IdentPat(bind_pat) => {
1032 let mut pat_ctx = pattern_context_for(original_file, bind_pat.into());
1033 if let Some(record_field) = ast::RecordPatField::for_field_name(&name) {
1034 pat_ctx.record_pat = find_node_in_file_compensated(original_file, &record_field.parent_record_pat());
1041 ast::MacroDef(_) => NameKind::MacroDef,
1042 ast::MacroRules(_) => NameKind::MacroRules,
1043 ast::Module(module) => NameKind::Module(module),
1044 ast::RecordField(_) => NameKind::RecordField,
1045 ast::Rename(_) => NameKind::Rename,
1046 ast::SelfParam(_) => NameKind::SelfParam,
1047 ast::Static(_) => NameKind::Static,
1048 ast::Struct(_) => NameKind::Struct,
1049 ast::Trait(_) => NameKind::Trait,
1050 ast::TypeAlias(_) => NameKind::TypeAlias,
1051 ast::TypeParam(_) => NameKind::TypeParam,
1052 ast::Union(_) => NameKind::Union,
1053 ast::Variant(_) => NameKind::Variant,
1057 let name = find_node_at_offset(&original_file, name.syntax().text_range().start());
1058 Some((NameContext { name, kind }, pat_ctx))
1061 fn classify_name_ref(
1062 sema: &Semantics<RootDatabase>,
1063 original_file: &SyntaxNode,
1064 name_ref: ast::NameRef,
1066 ) -> (NameRefContext, Option<PatternContext>) {
1067 let nameref = find_node_at_offset(&original_file, name_ref.syntax().text_range().start());
1069 let mut nameref_ctx =
1070 NameRefContext { dot_access: None, path_ctx: None, nameref, record_expr: None };
1072 if let Some(record_field) = ast::RecordExprField::for_field_name(&name_ref) {
1073 nameref_ctx.record_expr =
1074 find_node_in_file_compensated(original_file, &record_field.parent_record_lit())
1076 return (nameref_ctx, None);
1078 if let Some(record_field) = ast::RecordPatField::for_field_name_ref(&name_ref) {
1080 pattern_context_for(original_file, record_field.parent_record_pat().clone().into());
1083 Some(PatternContext {
1085 has_type_ascription: false,
1088 record_pat: find_node_in_file_compensated(
1090 &record_field.parent_record_pat(),
1097 let segment = match_ast! {
1099 ast::PathSegment(segment) => segment,
1100 ast::FieldExpr(field) => {
1101 let receiver = find_in_original_file(field.expr(), original_file);
1102 let receiver_is_ambiguous_float_literal = match &receiver {
1103 Some(ast::Expr::Literal(l)) => matches! {
1105 ast::LiteralKind::FloatNumber { .. } if l.syntax().last_token().map_or(false, |it| it.text().ends_with('.'))
1109 nameref_ctx.dot_access = Some(DotAccess {
1110 receiver_ty: receiver.as_ref().and_then(|it| sema.type_of_expr(it)),
1111 kind: DotAccessKind::Field { receiver_is_ambiguous_float_literal },
1114 return (nameref_ctx, None);
1116 ast::MethodCallExpr(method) => {
1117 let receiver = find_in_original_file(method.receiver(), original_file);
1118 nameref_ctx.dot_access = Some(DotAccess {
1119 receiver_ty: receiver.as_ref().and_then(|it| sema.type_of_expr(it)),
1120 kind: DotAccessKind::Method { has_parens: method.arg_list().map_or(false, |it| it.l_paren_token().is_some()) },
1123 return (nameref_ctx, None);
1125 _ => return (nameref_ctx, None),
1129 let path = segment.parent_path();
1130 let mut path_ctx = PathCompletionCtx {
1131 has_call_parens: false,
1132 has_macro_bang: false,
1133 is_absolute_path: false,
1135 parent: path.parent_path(),
1136 kind: PathKind::Item { kind: ItemListKind::SourceFile },
1137 has_type_args: false,
1139 let mut pat_ctx = None;
1141 let is_in_block = |it: &SyntaxNode| {
1144 ast::ExprStmt::can_cast(node.kind()) || ast::StmtList::can_cast(node.kind())
1148 let mut fill_record_expr = |syn: &SyntaxNode| {
1149 if let Some(record_expr) = syn.ancestors().nth(2).and_then(ast::RecordExpr::cast) {
1150 nameref_ctx.record_expr =
1151 find_node_in_file_compensated(original_file, &record_expr).zip(Some(true));
1155 let kind = path.syntax().ancestors().find_map(|it| {
1156 // using Option<Option<PathKind>> as extra controlflow
1157 let kind = match_ast! {
1159 ast::PathType(_) => Some(PathKind::Type),
1160 ast::PathExpr(it) => {
1161 fill_record_expr(it.syntax());
1163 path_ctx.has_call_parens = it.syntax().parent().map_or(false, |it| ast::CallExpr::can_cast(it.kind()));
1164 let in_block_expr = is_in_block(it.syntax());
1165 let in_loop_body = is_in_loop_body(it.syntax());
1166 Some(PathKind::Expr { in_block_expr, in_loop_body })
1168 ast::TupleStructPat(it) => {
1169 path_ctx.has_call_parens = true;
1170 pat_ctx = Some(pattern_context_for(original_file, it.into()));
1173 ast::RecordPat(it) => {
1174 path_ctx.has_call_parens = true;
1175 pat_ctx = Some(pattern_context_for(original_file, it.into()));
1178 ast::PathPat(it) => {
1179 pat_ctx = Some(pattern_context_for(original_file, it.into()));
1182 ast::MacroCall(it) => {
1183 path_ctx.has_macro_bang = it.excl_token().is_some();
1184 let parent = it.syntax().parent();
1185 match parent.as_ref().map(|it| it.kind()) {
1186 Some(SyntaxKind::MACRO_PAT) => Some(PathKind::Pat),
1187 Some(SyntaxKind::MACRO_TYPE) => Some(PathKind::Type),
1188 Some(SyntaxKind::ITEM_LIST) => Some(PathKind::Item { kind: ItemListKind::Module }),
1189 Some(SyntaxKind::ASSOC_ITEM_LIST) => Some(PathKind::Item { kind: match parent.and_then(|it| it.parent()).map(|it| it.kind()) {
1190 Some(SyntaxKind::TRAIT) => ItemListKind::Trait,
1191 Some(SyntaxKind::IMPL) => ItemListKind::Impl,
1192 _ => return Some(None),
1194 Some(SyntaxKind::EXTERN_ITEM_LIST) => Some(PathKind::Item { kind: ItemListKind::ExternBlock }),
1195 Some(SyntaxKind::SOURCE_FILE) => Some(PathKind::Item { kind: ItemListKind::SourceFile }),
1197 return Some(parent.and_then(ast::MacroExpr::cast).map(|it| {
1198 let in_loop_body = is_in_loop_body(it.syntax());
1199 let in_block_expr = is_in_block(it.syntax());
1200 fill_record_expr(it.syntax());
1201 PathKind::Expr { in_block_expr, in_loop_body }
1206 ast::Meta(meta) => (|| {
1207 let attr = meta.parent_attr()?;
1208 let kind = attr.kind();
1209 let attached = attr.syntax().parent()?;
1210 let is_trailing_outer_attr = kind != AttrKind::Inner
1211 && non_trivia_sibling(attr.syntax().clone().into(), syntax::Direction::Next).is_none();
1212 let annotated_item_kind = if is_trailing_outer_attr {
1215 Some(attached.kind())
1217 Some(PathKind::Attr {
1219 annotated_item_kind,
1222 ast::Visibility(it) => Some(PathKind::Vis { has_in_token: it.in_token().is_some() }),
1223 ast::UseTree(_) => Some(PathKind::Use),
1224 ast::ItemList(_) => Some(PathKind::Item { kind: ItemListKind::Module }),
1225 ast::AssocItemList(it) => Some(PathKind::Item { kind: {
1226 match it.syntax().parent()?.kind() {
1227 SyntaxKind::TRAIT => ItemListKind::Trait,
1228 SyntaxKind::IMPL => ItemListKind::Impl,
1232 ast::ExternItemList(_) => Some(PathKind::Item { kind: ItemListKind::ExternBlock }),
1233 ast::SourceFile(_) => Some(PathKind::Item { kind: ItemListKind::SourceFile }),
1240 Some(kind) => path_ctx.kind = kind,
1241 None => return (nameref_ctx, pat_ctx),
1243 path_ctx.has_type_args = segment.generic_arg_list().is_some();
1245 if let Some((path, use_tree_parent)) = path_or_use_tree_qualifier(&path) {
1246 if !use_tree_parent {
1247 path_ctx.is_absolute_path =
1248 path.top_path().segment().map_or(false, |it| it.coloncolon_token().is_some());
1253 .and_then(|it| find_node_in_file(original_file, &it))
1254 .map(|it| it.parent_path());
1255 path_ctx.qualifier = path.map(|path| {
1256 let res = sema.resolve_path(&path);
1257 let is_super_chain = iter::successors(Some(path.clone()), |p| p.qualifier())
1258 .all(|p| p.segment().and_then(|s| s.super_token()).is_some());
1261 let is_infer_qualifier = path.qualifier().is_none()
1263 path.segment().and_then(|it| it.kind()),
1264 Some(ast::PathSegmentKind::Type {
1265 type_ref: Some(ast::Type::InferType(_)),
1278 } else if let Some(segment) = path.segment() {
1279 if segment.coloncolon_token().is_some() {
1280 path_ctx.is_absolute_path = true;
1283 nameref_ctx.path_ctx = Some(path_ctx);
1284 (nameref_ctx, pat_ctx)
1288 fn pattern_context_for(original_file: &SyntaxNode, pat: ast::Pat) -> PatternContext {
1289 let mut is_param = None;
1290 let (refutability, has_type_ascription) =
1294 .skip_while(|it| ast::Pat::can_cast(it.kind()))
1296 .map_or((PatternRefutability::Irrefutable, false), |node| {
1297 let refutability = match_ast! {
1299 ast::LetStmt(let_) => return (PatternRefutability::Irrefutable, let_.ty().is_some()),
1300 ast::Param(param) => {
1301 let has_type_ascription = param.ty().is_some();
1303 let fake_param_list = param.syntax().parent().and_then(ast::ParamList::cast)?;
1304 let param_list = find_node_in_file_compensated(original_file, &fake_param_list)?;
1305 let param_list_owner = param_list.syntax().parent()?;
1306 let kind = match_ast! {
1307 match param_list_owner {
1308 ast::ClosureExpr(closure) => ParamKind::Closure(closure),
1309 ast::Fn(fn_) => ParamKind::Function(fn_),
1313 Some((param_list, param, kind))
1315 return (PatternRefutability::Irrefutable, has_type_ascription)
1317 ast::MatchArm(_) => PatternRefutability::Refutable,
1318 ast::LetExpr(_) => PatternRefutability::Refutable,
1319 ast::ForExpr(_) => PatternRefutability::Irrefutable,
1320 _ => PatternRefutability::Irrefutable,
1323 (refutability, false)
1325 let (ref_token, mut_token) = match &pat {
1326 ast::Pat::IdentPat(it) => (it.ref_token(), it.mut_token()),
1331 param_ctx: is_param,
1332 has_type_ascription,
1333 parent_pat: pat.syntax().parent().and_then(ast::Pat::cast),
1340 fn find_in_original_file<N: AstNode>(x: Option<N>, original_file: &SyntaxNode) -> Option<N> {
1341 fn find_node_with_range<N: AstNode>(syntax: &SyntaxNode, range: TextRange) -> Option<N> {
1342 let range = syntax.text_range().intersect(range)?;
1343 syntax.covering_element(range).ancestors().find_map(N::cast)
1345 x.map(|e| e.syntax().text_range()).and_then(|r| find_node_with_range(original_file, r))
1348 /// Attempts to find `node` inside `syntax` via `node`'s text range.
1349 fn find_node_in_file<N: AstNode>(syntax: &SyntaxNode, node: &N) -> Option<N> {
1350 let syntax_range = syntax.text_range();
1351 let range = node.syntax().text_range();
1352 let intersection = range.intersect(syntax_range)?;
1353 syntax.covering_element(intersection).ancestors().find_map(N::cast)
1356 /// Attempts to find `node` inside `syntax` via `node`'s text range while compensating
1357 /// for the offset introduced by the fake ident.
1358 /// This is wrong if `node` comes before the insertion point! Use `find_node_in_file` instead.
1359 fn find_node_in_file_compensated<N: AstNode>(syntax: &SyntaxNode, node: &N) -> Option<N> {
1360 let syntax_range = syntax.text_range();
1361 let range = node.syntax().text_range();
1362 let end = range.end().checked_sub(TextSize::try_from(COMPLETION_MARKER.len()).ok()?)?;
1363 if end < range.start() {
1366 let range = TextRange::new(range.start(), end);
1367 // our inserted ident could cause `range` to be go outside of the original syntax, so cap it
1368 let intersection = range.intersect(syntax_range)?;
1369 syntax.covering_element(intersection).ancestors().find_map(N::cast)
1372 fn path_or_use_tree_qualifier(path: &ast::Path) -> Option<(ast::Path, bool)> {
1373 if let Some(qual) = path.qualifier() {
1374 return Some((qual, false));
1376 let use_tree_list = path.syntax().ancestors().find_map(ast::UseTreeList::cast)?;
1377 let use_tree = use_tree_list.syntax().parent().and_then(ast::UseTree::cast)?;
1378 Some((use_tree.path()?, true))
1381 fn has_ref(token: &SyntaxToken) -> bool {
1382 let mut token = token.clone();
1383 for skip in [IDENT, WHITESPACE, T![mut]] {
1384 if token.kind() == skip {
1385 token = match token.prev_token() {
1387 None => return false,
1391 token.kind() == T![&]
1394 const OP_TRAIT_LANG_NAMES: &[&str] = &[
1429 use expect_test::{expect, Expect};
1430 use hir::HirDisplay;
1432 use crate::tests::{position, TEST_CONFIG};
1434 use super::CompletionContext;
1436 fn check_expected_type_and_name(ra_fixture: &str, expect: Expect) {
1437 let (db, pos) = position(ra_fixture);
1438 let config = TEST_CONFIG;
1439 let completion_context = CompletionContext::new(&db, pos, &config).unwrap();
1441 let ty = completion_context
1443 .map(|t| t.display_test(&db).to_string())
1444 .unwrap_or("?".to_owned());
1446 let name = completion_context
1448 .map_or_else(|| "?".to_owned(), |name| name.to_string());
1450 expect.assert_eq(&format!("ty: {}, name: {}", ty, name));
1454 fn expected_type_let_without_leading_char() {
1455 cov_mark::check!(expected_type_let_without_leading_char);
1456 check_expected_type_and_name(
1462 expect![[r#"ty: u32, name: x"#]],
1467 fn expected_type_let_with_leading_char() {
1468 cov_mark::check!(expected_type_let_with_leading_char);
1469 check_expected_type_and_name(
1475 expect![[r#"ty: u32, name: x"#]],
1480 fn expected_type_let_pat() {
1481 check_expected_type_and_name(
1487 expect![[r#"ty: u32, name: ?"#]],
1489 check_expected_type_and_name(
1495 expect![[r#"ty: u32, name: ?"#]],
1500 fn expected_type_fn_param() {
1501 cov_mark::check!(expected_type_fn_param);
1502 check_expected_type_and_name(
1504 fn foo() { bar($0); }
1507 expect![[r#"ty: u32, name: x"#]],
1509 check_expected_type_and_name(
1511 fn foo() { bar(c$0); }
1514 expect![[r#"ty: u32, name: x"#]],
1519 fn expected_type_fn_param_ref() {
1520 cov_mark::check!(expected_type_fn_param_ref);
1521 check_expected_type_and_name(
1523 fn foo() { bar(&$0); }
1526 expect![[r#"ty: u32, name: x"#]],
1528 check_expected_type_and_name(
1530 fn foo() { bar(&mut $0); }
1531 fn bar(x: &mut u32) {}
1533 expect![[r#"ty: u32, name: x"#]],
1535 check_expected_type_and_name(
1537 fn foo() { bar(& c$0); }
1540 expect![[r#"ty: u32, name: x"#]],
1542 check_expected_type_and_name(
1544 fn foo() { bar(&mut c$0); }
1545 fn bar(x: &mut u32) {}
1547 expect![[r#"ty: u32, name: x"#]],
1549 check_expected_type_and_name(
1551 fn foo() { bar(&c$0); }
1554 expect![[r#"ty: u32, name: x"#]],
1559 fn expected_type_struct_field_without_leading_char() {
1560 cov_mark::check!(expected_type_struct_field_without_leading_char);
1561 check_expected_type_and_name(
1563 struct Foo { a: u32 }
1568 expect![[r#"ty: u32, name: a"#]],
1573 fn expected_type_struct_field_followed_by_comma() {
1574 cov_mark::check!(expected_type_struct_field_followed_by_comma);
1575 check_expected_type_and_name(
1577 struct Foo { a: u32 }
1582 expect![[r#"ty: u32, name: a"#]],
1587 fn expected_type_generic_struct_field() {
1588 check_expected_type_and_name(
1590 struct Foo<T> { a: T }
1591 fn foo() -> Foo<u32> {
1595 expect![[r#"ty: u32, name: a"#]],
1600 fn expected_type_struct_field_with_leading_char() {
1601 cov_mark::check!(expected_type_struct_field_with_leading_char);
1602 check_expected_type_and_name(
1604 struct Foo { a: u32 }
1609 expect![[r#"ty: u32, name: a"#]],
1614 fn expected_type_match_arm_without_leading_char() {
1615 cov_mark::check!(expected_type_match_arm_without_leading_char);
1616 check_expected_type_and_name(
1623 expect![[r#"ty: E, name: ?"#]],
1628 fn expected_type_match_arm_with_leading_char() {
1629 cov_mark::check!(expected_type_match_arm_with_leading_char);
1630 check_expected_type_and_name(
1637 expect![[r#"ty: E, name: ?"#]],
1642 fn expected_type_match_arm_body_without_leading_char() {
1643 cov_mark::check!(expected_type_match_arm_body_without_leading_char);
1644 check_expected_type_and_name(
1649 match E::X { E::X => $0 }
1652 expect![[r#"ty: Foo, name: ?"#]],
1657 fn expected_type_match_body_arm_with_leading_char() {
1658 cov_mark::check!(expected_type_match_arm_body_with_leading_char);
1659 check_expected_type_and_name(
1664 match E::X { E::X => c$0 }
1667 expect![[r#"ty: Foo, name: ?"#]],
1672 fn expected_type_if_let_without_leading_char() {
1673 cov_mark::check!(expected_type_if_let_without_leading_char);
1674 check_expected_type_and_name(
1676 enum Foo { Bar, Baz, Quux }
1683 expect![[r#"ty: Foo, name: ?"#]],
1688 fn expected_type_if_let_with_leading_char() {
1689 cov_mark::check!(expected_type_if_let_with_leading_char);
1690 check_expected_type_and_name(
1692 enum Foo { Bar, Baz, Quux }
1699 expect![[r#"ty: Foo, name: ?"#]],
1704 fn expected_type_fn_ret_without_leading_char() {
1705 cov_mark::check!(expected_type_fn_ret_without_leading_char);
1706 check_expected_type_and_name(
1712 expect![[r#"ty: u32, name: ?"#]],
1717 fn expected_type_fn_ret_with_leading_char() {
1718 cov_mark::check!(expected_type_fn_ret_with_leading_char);
1719 check_expected_type_and_name(
1725 expect![[r#"ty: u32, name: ?"#]],
1730 fn expected_type_fn_ret_fn_ref_fully_typed() {
1731 check_expected_type_and_name(
1737 expect![[r#"ty: u32, name: ?"#]],
1742 fn expected_type_closure_param_return() {
1743 // FIXME: make this work with `|| $0`
1744 check_expected_type_and_name(
1751 fn bar(f: impl FnOnce() -> u32) {}
1753 expect![[r#"ty: u32, name: ?"#]],
1758 fn expected_type_generic_function() {
1759 check_expected_type_and_name(
1767 expect![[r#"ty: u32, name: t"#]],
1772 fn expected_type_generic_method() {
1773 check_expected_type_and_name(
1781 fn bar(self, t: T) {}
1784 expect![[r#"ty: u32, name: t"#]],
1789 fn expected_type_functional_update() {
1790 cov_mark::check!(expected_type_struct_func_update);
1791 check_expected_type_and_name(
1793 struct Foo { field: u32 }
1800 expect![[r#"ty: Foo, name: ?"#]],
1805 fn expected_type_param_pat() {
1806 check_expected_type_and_name(
1808 struct Foo { field: u32 }
1811 expect![[r#"ty: Foo, name: ?"#]],
1813 check_expected_type_and_name(
1815 struct Foo { field: u32 }
1818 // FIXME make this work, currently fails due to pattern recovery eating the `:`
1819 expect![[r#"ty: ?, name: ?"#]],