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 {
78 #[derive(Debug, Default)]
79 pub(super) struct QualifierCtx {
80 pub(super) unsafe_tok: Option<SyntaxToken>,
81 pub(super) vis_node: Option<ast::Visibility>,
85 pub(super) fn none(&self) -> bool {
86 self.unsafe_tok.is_none() && self.vis_node.is_none()
91 pub(crate) struct PathCompletionCtx {
92 /// If this is a call with () already there (or {} in case of record patterns)
93 pub(super) has_call_parens: bool,
94 /// If this has a macro call bang !
95 pub(super) has_macro_bang: bool,
96 /// Whether this path stars with a `::`.
97 pub(super) is_absolute_path: bool,
98 /// The qualifier of the current path if it exists.
99 pub(super) qualifier: Option<PathQualifierCtx>,
102 /// The parent of the path we are completing.
103 pub(super) parent: Option<ast::Path>,
104 pub(super) kind: PathKind,
105 /// Whether the path segment has type args or not.
106 pub(super) has_type_args: bool,
110 pub(crate) struct PathQualifierCtx {
111 pub(crate) path: ast::Path,
112 pub(crate) resolution: Option<PathResolution>,
113 /// Whether this path consists solely of `super` segments
114 pub(crate) is_super_chain: bool,
115 /// Whether the qualifier comes from a use tree parent or not
116 pub(crate) use_tree_parent: bool,
118 pub(crate) is_infer_qualifier: bool,
122 pub(super) struct PatternContext {
123 pub(super) refutability: PatternRefutability,
124 pub(super) param_ctx: Option<(ast::ParamList, ast::Param, ParamKind)>,
125 pub(super) has_type_ascription: bool,
126 pub(super) parent_pat: Option<ast::Pat>,
127 pub(super) ref_token: Option<SyntaxToken>,
128 pub(super) mut_token: Option<SyntaxToken>,
129 /// The record pattern this name or ref is a field of
130 pub(super) record_pat: Option<ast::RecordPat>,
134 pub(super) struct LifetimeContext {
135 pub(super) lifetime: Option<ast::Lifetime>,
136 pub(super) kind: LifetimeKind,
140 pub(super) enum LifetimeKind {
141 LifetimeParam { is_decl: bool, param: ast::LifetimeParam },
148 pub(super) struct NameContext {
150 pub(super) name: Option<ast::Name>,
151 pub(super) kind: NameKind,
156 pub(super) enum NameKind {
179 pub(super) struct NameRefContext {
180 /// NameRef syntax in the original file
181 pub(super) nameref: Option<ast::NameRef>,
182 // FIXME: these fields are actually disjoint -> enum
183 pub(super) dot_access: Option<DotAccess>,
184 pub(super) path_ctx: Option<PathCompletionCtx>,
185 /// The record expression this nameref is a field of
186 pub(super) record_expr: Option<(ast::RecordExpr, bool)>,
190 pub(super) enum IdentContext {
192 NameRef(NameRefContext),
193 Lifetime(LifetimeContext),
194 /// Original token, fake token
196 original: ast::String,
197 expanded: Option<ast::String>,
200 fake_attribute_under_caret: Option<ast::Attr>,
205 pub(super) struct DotAccess {
206 pub(super) receiver: Option<ast::Expr>,
207 pub(super) receiver_ty: Option<TypeInfo>,
208 pub(super) kind: DotAccessKind,
212 pub(super) enum DotAccessKind {
214 /// True if the receiver is an integer and there is no ident in the original file after it yet
216 receiver_is_ambiguous_float_literal: bool,
223 #[derive(Clone, Debug, PartialEq, Eq)]
224 pub(crate) enum ParamKind {
226 Closure(ast::ClosureExpr),
229 /// `CompletionContext` is created early during completion to figure out, where
230 /// exactly is the cursor, syntax-wise.
232 pub(crate) struct CompletionContext<'a> {
233 pub(super) sema: Semantics<'a, RootDatabase>,
234 pub(super) scope: SemanticsScope<'a>,
235 pub(super) db: &'a RootDatabase,
236 pub(super) config: &'a CompletionConfig,
237 pub(super) position: FilePosition,
239 /// The token before the cursor, in the original file.
240 pub(super) original_token: SyntaxToken,
241 /// The token before the cursor, in the macro-expanded file.
242 pub(super) token: SyntaxToken,
243 /// The crate of the current file.
244 pub(super) krate: hir::Crate,
245 /// The module of the `scope`.
246 pub(super) module: hir::Module,
248 /// The expected name of what we are completing.
249 /// This is usually the parameter name of the function argument we are completing.
250 pub(super) expected_name: Option<NameOrNameRef>,
251 /// The expected type of what we are completing.
252 pub(super) expected_type: Option<Type>,
254 /// The parent function of the cursor position if it exists.
255 pub(super) function_def: Option<ast::Fn>,
256 /// The parent impl of the cursor position if it exists.
257 pub(super) impl_def: Option<ast::Impl>,
258 /// Are we completing inside a let statement with a missing semicolon?
259 pub(super) incomplete_let: bool,
261 pub(super) completion_location: Option<ImmediateLocation>,
262 pub(super) prev_sibling: Option<ImmediatePrevSibling>,
263 pub(super) previous_token: Option<SyntaxToken>,
265 pub(super) ident_ctx: IdentContext,
267 pub(super) pattern_ctx: Option<PatternContext>,
268 pub(super) qualifier_ctx: QualifierCtx,
270 pub(super) existing_derives: FxHashSet<hir::Macro>,
272 pub(super) locals: FxHashMap<Name, Local>,
275 impl<'a> CompletionContext<'a> {
276 /// The range of the identifier that is being completed.
277 pub(crate) fn source_range(&self) -> TextRange {
278 // check kind of macro-expanded token, but use range of original token
279 let kind = self.token.kind();
282 // assume we are completing a lifetime but the user has only typed the '
283 cov_mark::hit!(completes_if_lifetime_without_idents);
284 TextRange::at(self.original_token.text_range().start(), TextSize::from(1))
286 IDENT | LIFETIME_IDENT | UNDERSCORE => self.original_token.text_range(),
287 _ if kind.is_keyword() => self.original_token.text_range(),
288 _ => TextRange::empty(self.position.offset),
292 pub(crate) fn previous_token_is(&self, kind: SyntaxKind) -> bool {
293 self.previous_token.as_ref().map_or(false, |tok| tok.kind() == kind)
296 pub(crate) fn famous_defs(&self) -> FamousDefs {
297 FamousDefs(&self.sema, self.krate)
300 pub(super) fn nameref_ctx(&self) -> Option<&NameRefContext> {
301 match &self.ident_ctx {
302 IdentContext::NameRef(it) => Some(it),
307 pub(super) fn name_ctx(&self) -> Option<&NameContext> {
308 match &self.ident_ctx {
309 IdentContext::Name(it) => Some(it),
314 pub(super) fn lifetime_ctx(&self) -> Option<&LifetimeContext> {
315 match &self.ident_ctx {
316 IdentContext::Lifetime(it) => Some(it),
321 pub(crate) fn dot_receiver(&self) -> Option<&ast::Expr> {
322 match self.nameref_ctx() {
323 Some(NameRefContext { dot_access: Some(DotAccess { receiver, .. }), .. }) => {
330 pub(crate) fn has_dot_receiver(&self) -> bool {
331 self.dot_receiver().is_some()
334 pub(crate) fn expects_assoc_item(&self) -> bool {
335 matches!(self.completion_location, Some(ImmediateLocation::Trait | ImmediateLocation::Impl))
338 pub(crate) fn expects_non_trait_assoc_item(&self) -> bool {
339 matches!(self.completion_location, Some(ImmediateLocation::Impl))
342 pub(crate) fn expects_item(&self) -> bool {
343 matches!(self.completion_location, Some(ImmediateLocation::ItemList))
346 // FIXME: This shouldn't exist
347 pub(crate) fn expects_generic_arg(&self) -> bool {
348 matches!(self.completion_location, Some(ImmediateLocation::GenericArgList(_)))
351 pub(crate) fn has_block_expr_parent(&self) -> bool {
352 matches!(self.completion_location, Some(ImmediateLocation::StmtList))
355 pub(crate) fn expects_ident_ref_expr(&self) -> bool {
356 matches!(self.completion_location, Some(ImmediateLocation::RefExpr))
359 pub(crate) fn expect_field(&self) -> bool {
360 matches!(self.completion_location, Some(ImmediateLocation::TupleField))
361 || matches!(self.name_ctx(), Some(NameContext { kind: NameKind::RecordField, .. }))
364 /// Whether the cursor is right after a trait or impl header.
365 /// trait Foo ident$0
366 // FIXME: This probably shouldn't exist
367 pub(crate) fn has_unfinished_impl_or_trait_prev_sibling(&self) -> bool {
370 Some(ImmediatePrevSibling::ImplDefType | ImmediatePrevSibling::TraitDefName)
374 // FIXME: This probably shouldn't exist
375 pub(crate) fn has_impl_prev_sibling(&self) -> bool {
376 matches!(self.prev_sibling, Some(ImmediatePrevSibling::ImplDefType))
379 pub(crate) fn after_if(&self) -> bool {
380 matches!(self.prev_sibling, Some(ImmediatePrevSibling::IfExpr))
383 // FIXME: This shouldn't exist
384 pub(crate) fn is_path_disallowed(&self) -> bool {
385 !self.qualifier_ctx.none()
386 || (matches!(self.name_ctx(), Some(NameContext { .. })) && self.pattern_ctx.is_none())
387 || matches!(self.pattern_ctx, Some(PatternContext { record_pat: Some(_), .. }))
390 Some(NameRefContext { record_expr: Some((_, false)), .. })
394 pub(crate) fn path_context(&self) -> Option<&PathCompletionCtx> {
395 self.nameref_ctx().and_then(|ctx| ctx.path_ctx.as_ref())
398 pub(crate) fn expects_expression(&self) -> bool {
399 matches!(self.path_context(), Some(PathCompletionCtx { kind: PathKind::Expr { .. }, .. }))
402 pub(crate) fn is_non_trivial_path(&self) -> bool {
406 PathCompletionCtx { is_absolute_path: true, .. }
407 | PathCompletionCtx { qualifier: Some(_), .. }
412 pub(crate) fn path_qual(&self) -> Option<&ast::Path> {
413 self.path_context().and_then(|it| it.qualifier.as_ref().map(|it| &it.path))
416 pub(crate) fn path_kind(&self) -> Option<PathKind> {
417 self.path_context().map(|it| it.kind)
420 /// Checks if an item is visible and not `doc(hidden)` at the completion site.
421 pub(crate) fn is_visible<I>(&self, item: &I) -> Visible
423 I: hir::HasVisibility + hir::HasAttrs + hir::HasCrate + Copy,
425 self.is_visible_impl(&item.visibility(self.db), &item.attrs(self.db), item.krate(self.db))
428 pub(crate) fn is_scope_def_hidden(&self, scope_def: ScopeDef) -> bool {
429 if let (Some(attrs), Some(krate)) = (scope_def.attrs(self.db), scope_def.krate(self.db)) {
430 return self.is_doc_hidden(&attrs, krate);
436 /// Check if an item is `#[doc(hidden)]`.
437 pub(crate) fn is_item_hidden(&self, item: &hir::ItemInNs) -> bool {
438 let attrs = item.attrs(self.db);
439 let krate = item.krate(self.db);
440 match (attrs, krate) {
441 (Some(attrs), Some(krate)) => self.is_doc_hidden(&attrs, krate),
445 /// Whether the given trait is an operator trait or not.
446 pub(crate) fn is_ops_trait(&self, trait_: hir::Trait) -> bool {
447 match trait_.attrs(self.db).lang() {
448 Some(lang) => OP_TRAIT_LANG_NAMES.contains(&lang.as_str()),
453 /// Returns the traits in scope, with the [`Drop`] trait removed.
454 pub(crate) fn traits_in_scope(&self) -> hir::VisibleTraits {
455 let mut traits_in_scope = self.scope.visible_traits();
456 if let Some(drop) = self.famous_defs().core_ops_Drop() {
457 traits_in_scope.0.remove(&drop.into());
462 /// A version of [`SemanticsScope::process_all_names`] that filters out `#[doc(hidden)]` items.
463 pub(crate) fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
464 let _p = profile::span("CompletionContext::process_all_names");
465 self.scope.process_all_names(&mut |name, def| {
466 if self.is_scope_def_hidden(def) {
474 pub(crate) fn process_all_names_raw(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
475 let _p = profile::span("CompletionContext::process_all_names_raw");
476 self.scope.process_all_names(&mut |name, def| f(name, def));
481 vis: &hir::Visibility,
483 defining_crate: hir::Crate,
485 if !vis.is_visible_from(self.db, self.module.into()) {
486 if !self.config.enable_private_editable {
489 // If the definition location is editable, also show private items
490 let root_file = defining_crate.root_file(self.db);
491 let source_root_id = self.db.file_source_root(root_file);
492 let is_editable = !self.db.source_root(source_root_id).is_library;
493 return if is_editable { Visible::Editable } else { Visible::No };
496 if self.is_doc_hidden(attrs, defining_crate) {
503 fn is_doc_hidden(&self, attrs: &hir::Attrs, defining_crate: hir::Crate) -> bool {
504 // `doc(hidden)` items are only completed within the defining crate.
505 self.krate != defining_crate && attrs.has_doc_hidden()
509 // CompletionContext construction
510 impl<'a> CompletionContext<'a> {
512 db: &'a RootDatabase,
513 position @ FilePosition { file_id, offset }: FilePosition,
514 config: &'a CompletionConfig,
515 ) -> Option<CompletionContext<'a>> {
516 let _p = profile::span("CompletionContext::new");
517 let sema = Semantics::new(db);
519 let original_file = sema.parse(file_id);
521 // Insert a fake ident to get a valid parse tree. We will use this file
522 // to determine context, though the original_file will be used for
523 // actual completion.
524 let file_with_fake_ident = {
525 let parse = db.parse(file_id);
526 let edit = Indel::insert(offset, COMPLETION_MARKER.to_string());
527 parse.reparse(&edit).tree()
529 let fake_ident_token =
530 file_with_fake_ident.syntax().token_at_offset(offset).right_biased()?;
532 let original_token = original_file.syntax().token_at_offset(offset).left_biased()?;
533 let token = sema.descend_into_macros_single(original_token.clone());
534 let scope = sema.scope_at_offset(&token.parent()?, offset)?;
535 let krate = scope.krate();
536 let module = scope.module();
538 let mut locals = FxHashMap::default();
539 scope.process_all_names(&mut |name, scope| {
540 if let ScopeDef::Local(local) = scope {
541 locals.insert(name, local);
545 let mut ctx = CompletionContext {
559 incomplete_let: false,
560 completion_location: None,
562 previous_token: None,
563 // dummy value, will be overwritten
564 ident_ctx: IdentContext::UnexpandedAttrTT { fake_attribute_under_caret: None },
566 qualifier_ctx: Default::default(),
567 existing_derives: Default::default(),
571 original_file.syntax().clone(),
572 file_with_fake_ident.syntax().clone(),
579 /// Expand attributes and macro calls at the current cursor position for both the original file
580 /// and fake file repeatedly. As soon as one of the two expansions fail we stop so the original
581 /// and speculative states stay in sync.
584 mut original_file: SyntaxNode,
585 mut speculative_file: SyntaxNode,
586 mut offset: TextSize,
587 mut fake_ident_token: SyntaxToken,
589 let _p = profile::span("CompletionContext::expand_and_fill");
590 let mut derive_ctx = None;
594 |item: &ast::Item| item.syntax().ancestors().skip(1).find_map(ast::Item::cast);
595 let ancestor_items = iter::successors(
597 find_node_at_offset::<ast::Item>(&original_file, offset),
598 find_node_at_offset::<ast::Item>(&speculative_file, offset),
600 |(a, b)| parent_item(a).zip(parent_item(b)),
603 // first try to expand attributes as these are always the outermost macro calls
604 'ancestors: for (actual_item, item_with_fake_ident) in ancestor_items {
606 self.sema.expand_attr_macro(&actual_item),
607 self.sema.speculative_expand_attr_macro(
609 &item_with_fake_ident,
610 fake_ident_token.clone(),
613 // maybe parent items have attributes, so continue walking the ancestors
614 (None, None) => continue 'ancestors,
615 // successful expansions
616 (Some(actual_expansion), Some((fake_expansion, fake_mapped_token))) => {
617 let new_offset = fake_mapped_token.text_range().start();
618 if new_offset > actual_expansion.text_range().end() {
619 // offset outside of bounds from the original expansion,
620 // stop here to prevent problems from happening
623 original_file = actual_expansion;
624 speculative_file = fake_expansion;
625 fake_ident_token = fake_mapped_token;
629 // exactly one expansion failed, inconsistent state so stop expanding completely
630 _ => break 'expansion,
634 // No attributes have been expanded, so look for macro_call! token trees or derive token trees
635 let orig_tt = match find_node_at_offset::<ast::TokenTree>(&original_file, offset) {
637 None => break 'expansion,
639 let spec_tt = match find_node_at_offset::<ast::TokenTree>(&speculative_file, offset) {
641 None => break 'expansion,
644 // Expand pseudo-derive expansion
645 if let (Some(orig_attr), Some(spec_attr)) = (
646 orig_tt.syntax().parent().and_then(ast::Meta::cast).and_then(|it| it.parent_attr()),
647 spec_tt.syntax().parent().and_then(ast::Meta::cast).and_then(|it| it.parent_attr()),
649 if let (Some(actual_expansion), Some((fake_expansion, fake_mapped_token))) = (
650 self.sema.expand_derive_as_pseudo_attr_macro(&orig_attr),
651 self.sema.speculative_expand_derive_as_pseudo_attr_macro(
654 fake_ident_token.clone(),
660 fake_mapped_token.text_range().start(),
664 // at this point we won't have any more successful expansions, so stop
668 // Expand fn-like macro calls
669 if let (Some(actual_macro_call), Some(macro_call_with_fake_ident)) = (
670 orig_tt.syntax().ancestors().find_map(ast::MacroCall::cast),
671 spec_tt.syntax().ancestors().find_map(ast::MacroCall::cast),
673 let mac_call_path0 = actual_macro_call.path().as_ref().map(|s| s.syntax().text());
675 macro_call_with_fake_ident.path().as_ref().map(|s| s.syntax().text());
677 // inconsistent state, stop expanding
678 if mac_call_path0 != mac_call_path1 {
681 let speculative_args = match macro_call_with_fake_ident.token_tree() {
683 None => break 'expansion,
687 self.sema.expand(&actual_macro_call),
688 self.sema.speculative_expand(
691 fake_ident_token.clone(),
694 // successful expansions
695 (Some(actual_expansion), Some((fake_expansion, fake_mapped_token))) => {
696 let new_offset = fake_mapped_token.text_range().start();
697 if new_offset > actual_expansion.text_range().end() {
698 // offset outside of bounds from the original expansion,
699 // stop here to prevent problems from happening
702 original_file = actual_expansion;
703 speculative_file = fake_expansion;
704 fake_ident_token = fake_mapped_token;
708 // at least on expansion failed, we won't have anything to expand from this point
709 // onwards so break out
710 _ => break 'expansion,
714 // none of our states have changed so stop the loop
718 self.fill(&original_file, speculative_file, offset, derive_ctx)
721 /// Calculate the expected type and name of the cursor position.
722 fn expected_type_and_name(&self) -> (Option<Type>, Option<NameOrNameRef>) {
723 let mut node = match self.token.parent() {
725 None => return (None, None),
730 ast::LetStmt(it) => {
731 cov_mark::hit!(expected_type_let_with_leading_char);
732 cov_mark::hit!(expected_type_let_without_leading_char);
734 .and_then(|pat| self.sema.type_of_pat(&pat))
735 .or_else(|| it.initializer().and_then(|it| self.sema.type_of_expr(&it)))
736 .map(TypeInfo::original);
737 let name = match it.pat() {
738 Some(ast::Pat::IdentPat(ident)) => ident.name().map(NameOrNameRef::Name),
739 Some(_) | None => None,
744 ast::LetExpr(it) => {
745 cov_mark::hit!(expected_type_if_let_without_leading_char);
747 .and_then(|pat| self.sema.type_of_pat(&pat))
748 .or_else(|| it.expr().and_then(|it| self.sema.type_of_expr(&it)))
749 .map(TypeInfo::original);
753 cov_mark::hit!(expected_type_fn_param);
754 ActiveParameter::at_token(
758 let name = ap.ident().map(NameOrNameRef::Name);
759 let ty = if has_ref(&self.token) {
760 cov_mark::hit!(expected_type_fn_param_ref);
767 .unwrap_or((None, None))
769 ast::RecordExprFieldList(it) => {
770 // wouldn't try {} be nice...
772 if self.token.kind() == T![..]
773 || self.token.prev_token().map(|t| t.kind()) == Some(T![..])
775 cov_mark::hit!(expected_type_struct_func_update);
776 let record_expr = it.syntax().parent().and_then(ast::RecordExpr::cast)?;
777 let ty = self.sema.type_of_expr(&record_expr.into())?;
783 cov_mark::hit!(expected_type_struct_field_without_leading_char);
784 let expr_field = self.token.prev_sibling_or_token()?
786 .and_then(ast::RecordExprField::cast)?;
787 let (_, _, ty) = self.sema.resolve_record_field(&expr_field)?;
790 expr_field.field_name().map(NameOrNameRef::NameRef),
793 })().unwrap_or((None, None))
795 ast::RecordExprField(it) => {
796 if let Some(expr) = it.expr() {
797 cov_mark::hit!(expected_type_struct_field_with_leading_char);
799 self.sema.type_of_expr(&expr).map(TypeInfo::original),
800 it.field_name().map(NameOrNameRef::NameRef),
803 cov_mark::hit!(expected_type_struct_field_followed_by_comma);
804 let ty = self.sema.resolve_record_field(&it)
805 .map(|(_, _, ty)| ty);
808 it.field_name().map(NameOrNameRef::NameRef),
813 // match foo { ..., pat => $0 }
814 ast::MatchExpr(it) => {
815 let ty = if self.previous_token_is(T![=>]) {
816 // match foo { ..., pat => $0 }
817 cov_mark::hit!(expected_type_match_arm_body_without_leading_char);
818 cov_mark::hit!(expected_type_match_arm_body_with_leading_char);
819 self.sema.type_of_expr(&it.into())
822 cov_mark::hit!(expected_type_match_arm_without_leading_char);
823 it.expr().and_then(|e| self.sema.type_of_expr(&e))
824 }.map(TypeInfo::original);
828 let ty = it.condition()
829 .and_then(|e| self.sema.type_of_expr(&e))
830 .map(TypeInfo::original);
833 ast::IdentPat(it) => {
834 cov_mark::hit!(expected_type_if_let_with_leading_char);
835 cov_mark::hit!(expected_type_match_arm_with_leading_char);
836 let ty = self.sema.type_of_pat(&ast::Pat::from(it)).map(TypeInfo::original);
840 cov_mark::hit!(expected_type_fn_ret_with_leading_char);
841 cov_mark::hit!(expected_type_fn_ret_without_leading_char);
842 let def = self.sema.to_def(&it);
843 (def.map(|def| def.ret_type(self.db)), None)
845 ast::ClosureExpr(it) => {
846 let ty = self.sema.type_of_expr(&it.into());
847 ty.and_then(|ty| ty.original.as_callable(self.db))
848 .map(|c| (Some(c.return_type()), None))
849 .unwrap_or((None, None))
851 ast::ParamList(_) => (None, None),
852 ast::Stmt(_) => (None, None),
853 ast::Item(_) => (None, None),
855 match node.parent() {
860 None => (None, None),
868 /// Fill the completion context, this is what does semantic reasoning about the surrounding context
869 /// of the completion location.
872 original_file: &SyntaxNode,
873 file_with_fake_ident: SyntaxNode,
875 derive_ctx: Option<(SyntaxNode, SyntaxNode, TextSize, ast::Attr)>,
877 let fake_ident_token = file_with_fake_ident.token_at_offset(offset).right_biased()?;
878 let syntax_element = NodeOrToken::Token(fake_ident_token);
879 if is_in_token_of_for_loop(syntax_element.clone()) {
881 // there is nothing to complete here except `in` keyword
882 // don't bother populating the context
883 // FIXME: the completion calculations should end up good enough
884 // such that this special case becomes unnecessary
888 self.previous_token = previous_token(syntax_element.clone());
890 self.incomplete_let =
891 syntax_element.ancestors().take(6).find_map(ast::LetStmt::cast).map_or(false, |it| {
892 it.syntax().text_range().end() == syntax_element.text_range().end()
895 (self.expected_type, self.expected_name) = self.expected_type_and_name();
897 // Overwrite the path kind for derives
898 if let Some((original_file, file_with_fake_ident, offset, origin_attr)) = derive_ctx {
899 self.existing_derives = self
901 .resolve_derive_macro(&origin_attr)
907 if let Some(ast::NameLike::NameRef(name_ref)) =
908 find_node_at_offset(&file_with_fake_ident, offset)
910 let parent = name_ref.syntax().parent()?;
911 let (mut nameref_ctx, _) =
912 Self::classify_name_ref(&self.sema, &original_file, name_ref, parent);
913 if let Some(path_ctx) = &mut nameref_ctx.path_ctx {
914 path_ctx.kind = PathKind::Derive;
916 self.ident_ctx = IdentContext::NameRef(nameref_ctx);
922 let name_like = match find_node_at_offset(&file_with_fake_ident, offset) {
925 if let Some(original) = ast::String::cast(self.original_token.clone()) {
926 self.ident_ctx = IdentContext::String {
928 expanded: ast::String::cast(self.token.clone()),
931 // Fix up trailing whitespace problem
933 let token = if self.token.kind() == SyntaxKind::WHITESPACE {
934 self.previous_token.as_ref()?
938 let p = token.parent()?;
939 if p.kind() == SyntaxKind::TOKEN_TREE
940 && p.ancestors().any(|it| it.kind() == SyntaxKind::META)
942 self.ident_ctx = IdentContext::UnexpandedAttrTT {
943 fake_attribute_under_caret: syntax_element
945 .find_map(ast::Attr::cast),
954 self.completion_location =
955 determine_location(&self.sema, original_file, offset, &name_like);
956 self.prev_sibling = determine_prev_sibling(&name_like);
959 .token_ancestors_with_macros(self.token.clone())
960 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
961 .find_map(ast::Impl::cast);
962 self.function_def = self
964 .token_ancestors_with_macros(self.token.clone())
965 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
966 .find_map(ast::Fn::cast);
969 ast::NameLike::Lifetime(lifetime) => {
970 self.ident_ctx = IdentContext::Lifetime(Self::classify_lifetime(
976 ast::NameLike::NameRef(name_ref) => {
977 let parent = name_ref.syntax().parent()?;
978 let (nameref_ctx, pat_ctx) =
979 Self::classify_name_ref(&self.sema, &original_file, name_ref, parent.clone());
981 // Extract qualifiers
982 if let Some(path_ctx) = &nameref_ctx.path_ctx {
983 if path_ctx.qualifier.is_none() {
984 let top = match path_ctx.kind {
985 PathKind::Expr { in_block_expr: true, .. } => parent
987 .find(|it| ast::PathExpr::can_cast(it.kind()))
989 let parent = p.parent()?;
990 if ast::StmtList::can_cast(parent.kind()) {
992 } else if ast::ExprStmt::can_cast(parent.kind()) {
998 PathKind::Item { .. } => {
999 parent.ancestors().find(|it| ast::MacroCall::can_cast(it.kind()))
1003 if let Some(top) = top {
1004 if let Some(NodeOrToken::Node(error_node)) =
1005 syntax::algo::non_trivia_sibling(
1007 syntax::Direction::Prev,
1010 if error_node.kind() == SyntaxKind::ERROR {
1011 self.qualifier_ctx.unsafe_tok = error_node
1012 .children_with_tokens()
1013 .filter_map(NodeOrToken::into_token)
1014 .find(|it| it.kind() == T![unsafe]);
1015 self.qualifier_ctx.vis_node =
1016 error_node.children().find_map(ast::Visibility::cast);
1022 self.ident_ctx = IdentContext::NameRef(nameref_ctx);
1023 self.pattern_ctx = pat_ctx;
1025 ast::NameLike::Name(name) => {
1026 let (name_ctx, pat_ctx) = Self::classify_name(&self.sema, original_file, name)?;
1027 self.pattern_ctx = pat_ctx;
1028 self.ident_ctx = IdentContext::Name(name_ctx);
1034 fn classify_lifetime(
1035 _sema: &Semantics<RootDatabase>,
1036 original_file: &SyntaxNode,
1037 lifetime: ast::Lifetime,
1038 ) -> Option<LifetimeContext> {
1039 let parent = lifetime.syntax().parent()?;
1040 if parent.kind() == ERROR {
1044 let kind = match_ast! {
1046 ast::LifetimeParam(param) => LifetimeKind::LifetimeParam {
1047 is_decl: param.lifetime().as_ref() == Some(&lifetime),
1050 ast::BreakExpr(_) => LifetimeKind::LabelRef,
1051 ast::ContinueExpr(_) => LifetimeKind::LabelRef,
1052 ast::Label(_) => LifetimeKind::LabelDef,
1053 _ => LifetimeKind::Lifetime,
1056 let lifetime = find_node_at_offset(&original_file, lifetime.syntax().text_range().start());
1058 Some(LifetimeContext { lifetime, kind })
1062 _sema: &Semantics<RootDatabase>,
1063 original_file: &SyntaxNode,
1065 ) -> Option<(NameContext, Option<PatternContext>)> {
1066 let parent = name.syntax().parent()?;
1067 let mut pat_ctx = None;
1068 let kind = match_ast! {
1070 ast::Const(_) => NameKind::Const,
1071 ast::ConstParam(_) => NameKind::ConstParam,
1072 ast::Enum(_) => NameKind::Enum,
1073 ast::Fn(_) => NameKind::Function,
1074 ast::IdentPat(bind_pat) => {
1076 let mut pat_ctx = pattern_context_for(original_file, bind_pat.into());
1077 if let Some(record_field) = ast::RecordPatField::for_field_name(&name) {
1078 pat_ctx.record_pat = find_node_in_file_compensated(original_file, &record_field.parent_record_pat());
1085 ast::MacroDef(_) => NameKind::MacroDef,
1086 ast::MacroRules(_) => NameKind::MacroRules,
1087 ast::Module(module) => NameKind::Module(module),
1088 ast::RecordField(_) => NameKind::RecordField,
1089 ast::Rename(_) => NameKind::Rename,
1090 ast::SelfParam(_) => NameKind::SelfParam,
1091 ast::Static(_) => NameKind::Static,
1092 ast::Struct(_) => NameKind::Struct,
1093 ast::Trait(_) => NameKind::Trait,
1094 ast::TypeAlias(_) => NameKind::TypeAlias,
1095 ast::TypeParam(_) => NameKind::TypeParam,
1096 ast::Union(_) => NameKind::Union,
1097 ast::Variant(_) => NameKind::Variant,
1101 let name = find_node_at_offset(&original_file, name.syntax().text_range().start());
1102 Some((NameContext { name, kind }, pat_ctx))
1105 fn classify_name_ref(
1106 sema: &Semantics<RootDatabase>,
1107 original_file: &SyntaxNode,
1108 name_ref: ast::NameRef,
1110 ) -> (NameRefContext, Option<PatternContext>) {
1111 let nameref = find_node_at_offset(&original_file, name_ref.syntax().text_range().start());
1113 let mut nameref_ctx =
1114 NameRefContext { dot_access: None, path_ctx: None, nameref, record_expr: None };
1116 if let Some(record_field) = ast::RecordExprField::for_field_name(&name_ref) {
1117 nameref_ctx.record_expr =
1118 find_node_in_file_compensated(original_file, &record_field.parent_record_lit())
1120 return (nameref_ctx, None);
1122 if let Some(record_field) = ast::RecordPatField::for_field_name_ref(&name_ref) {
1124 pattern_context_for(original_file, record_field.parent_record_pat().clone().into());
1127 Some(PatternContext {
1129 has_type_ascription: false,
1132 record_pat: find_node_in_file_compensated(
1134 &record_field.parent_record_pat(),
1141 let segment = match_ast! {
1143 ast::PathSegment(segment) => segment,
1144 ast::FieldExpr(field) => {
1145 let receiver = find_in_original_file(field.expr(), original_file);
1146 let receiver_is_ambiguous_float_literal = match &receiver {
1147 Some(ast::Expr::Literal(l)) => matches! {
1149 ast::LiteralKind::FloatNumber { .. } if l.syntax().last_token().map_or(false, |it| it.text().ends_with('.'))
1153 nameref_ctx.dot_access = Some(DotAccess {
1154 receiver_ty: receiver.as_ref().and_then(|it| sema.type_of_expr(it)),
1155 kind: DotAccessKind::Field { receiver_is_ambiguous_float_literal },
1158 return (nameref_ctx, None);
1160 ast::MethodCallExpr(method) => {
1161 let receiver = find_in_original_file(method.receiver(), original_file);
1162 nameref_ctx.dot_access = Some(DotAccess {
1163 receiver_ty: receiver.as_ref().and_then(|it| sema.type_of_expr(it)),
1164 kind: DotAccessKind::Method { has_parens: method.arg_list().map_or(false, |it| it.l_paren_token().is_some()) },
1167 return (nameref_ctx, None);
1169 _ => return (nameref_ctx, None),
1173 let path = segment.parent_path();
1174 let mut path_ctx = PathCompletionCtx {
1175 has_call_parens: false,
1176 has_macro_bang: false,
1177 is_absolute_path: false,
1179 parent: path.parent_path(),
1180 kind: PathKind::Item { kind: ItemListKind::SourceFile },
1181 has_type_args: false,
1183 let mut pat_ctx = None;
1185 let is_in_block = |it: &SyntaxNode| {
1188 ast::ExprStmt::can_cast(node.kind()) || ast::StmtList::can_cast(node.kind())
1192 let mut fill_record_expr = |syn: &SyntaxNode| {
1193 if let Some(record_expr) = syn.ancestors().nth(2).and_then(ast::RecordExpr::cast) {
1194 nameref_ctx.record_expr =
1195 find_node_in_file_compensated(original_file, &record_expr).zip(Some(true));
1199 // We do not want to generate path completions when we are sandwiched between an item decl signature and its body.
1200 // ex. trait Foo $0 {}
1201 // in these cases parser recovery usually kicks in for our inserted identifier, causing it
1202 // to either be parsed as an ExprStmt or a MacroCall, depending on whether it is in a block
1203 // expression or an item list.
1204 // The following code checks if the body is missing, if it is we either cut off the body
1205 // from the item or it was missing in the first place
1206 let inbetween_body_and_decl_check = |node: SyntaxNode| {
1207 if let Some(NodeOrToken::Node(n)) =
1208 syntax::algo::non_trivia_sibling(node.into(), syntax::Direction::Prev)
1210 if let Some(item) = ast::Item::cast(n) {
1212 ast::Item::Const(it) => it.body().is_none(),
1213 ast::Item::Enum(it) => it.variant_list().is_none(),
1214 ast::Item::ExternBlock(it) => it.extern_item_list().is_none(),
1215 ast::Item::Fn(it) => it.body().is_none(),
1216 ast::Item::Impl(it) => it.assoc_item_list().is_none(),
1217 ast::Item::Module(it) => it.item_list().is_none(),
1218 ast::Item::Static(it) => it.body().is_none(),
1219 ast::Item::Struct(it) => it.field_list().is_none(),
1220 ast::Item::Trait(it) => it.assoc_item_list().is_none(),
1221 ast::Item::TypeAlias(it) => it.ty().is_none(),
1222 ast::Item::Union(it) => it.record_field_list().is_none(),
1233 let kind = path.syntax().ancestors().find_map(|it| {
1234 // using Option<Option<PathKind>> as extra controlflow
1235 let kind = match_ast! {
1237 ast::PathType(_) => Some(PathKind::Type),
1238 ast::PathExpr(it) => {
1239 if let Some(p) = it.syntax().parent() {
1240 if ast::ExprStmt::can_cast(p.kind()) {
1241 if inbetween_body_and_decl_check(p) {
1247 fill_record_expr(it.syntax());
1249 path_ctx.has_call_parens = it.syntax().parent().map_or(false, |it| ast::CallExpr::can_cast(it.kind()));
1250 let in_block_expr = is_in_block(it.syntax());
1251 let in_loop_body = is_in_loop_body(it.syntax());
1252 Some(PathKind::Expr { in_block_expr, in_loop_body })
1254 ast::TupleStructPat(it) => {
1255 path_ctx.has_call_parens = true;
1256 pat_ctx = Some(pattern_context_for(original_file, it.into()));
1259 ast::RecordPat(it) => {
1260 path_ctx.has_call_parens = true;
1261 pat_ctx = Some(pattern_context_for(original_file, it.into()));
1264 ast::PathPat(it) => {
1265 pat_ctx = Some(pattern_context_for(original_file, it.into()));
1268 ast::MacroCall(it) => {
1269 if inbetween_body_and_decl_check(it.syntax().clone()) {
1273 path_ctx.has_macro_bang = it.excl_token().is_some();
1274 let parent = it.syntax().parent();
1275 match parent.as_ref().map(|it| it.kind()) {
1276 Some(SyntaxKind::MACRO_PAT) => Some(PathKind::Pat),
1277 Some(SyntaxKind::MACRO_TYPE) => Some(PathKind::Type),
1278 Some(SyntaxKind::ITEM_LIST) => Some(PathKind::Item { kind: ItemListKind::Module }),
1279 Some(SyntaxKind::ASSOC_ITEM_LIST) => Some(PathKind::Item { kind: match parent.and_then(|it| it.parent()).map(|it| it.kind()) {
1280 Some(SyntaxKind::TRAIT) => ItemListKind::Trait,
1281 Some(SyntaxKind::IMPL) => ItemListKind::Impl,
1282 _ => return Some(None),
1284 Some(SyntaxKind::EXTERN_ITEM_LIST) => Some(PathKind::Item { kind: ItemListKind::ExternBlock }),
1285 Some(SyntaxKind::SOURCE_FILE) => Some(PathKind::Item { kind: ItemListKind::SourceFile }),
1287 return Some(parent.and_then(ast::MacroExpr::cast).map(|it| {
1288 let in_loop_body = is_in_loop_body(it.syntax());
1289 let in_block_expr = is_in_block(it.syntax());
1290 fill_record_expr(it.syntax());
1291 PathKind::Expr { in_block_expr, in_loop_body }
1296 ast::Meta(meta) => (|| {
1297 let attr = meta.parent_attr()?;
1298 let kind = attr.kind();
1299 let attached = attr.syntax().parent()?;
1300 let is_trailing_outer_attr = kind != AttrKind::Inner
1301 && non_trivia_sibling(attr.syntax().clone().into(), syntax::Direction::Next).is_none();
1302 let annotated_item_kind = if is_trailing_outer_attr {
1305 Some(attached.kind())
1307 Some(PathKind::Attr {
1309 annotated_item_kind,
1312 ast::Visibility(it) => Some(PathKind::Vis { has_in_token: it.in_token().is_some() }),
1313 ast::UseTree(_) => Some(PathKind::Use),
1314 ast::ItemList(_) => Some(PathKind::Item { kind: ItemListKind::Module }),
1315 ast::AssocItemList(it) => Some(PathKind::Item { kind: {
1316 match it.syntax().parent()?.kind() {
1317 SyntaxKind::TRAIT => ItemListKind::Trait,
1318 SyntaxKind::IMPL => ItemListKind::Impl,
1322 ast::ExternItemList(_) => Some(PathKind::Item { kind: ItemListKind::ExternBlock }),
1323 ast::SourceFile(_) => Some(PathKind::Item { kind: ItemListKind::SourceFile }),
1330 Some(kind) => path_ctx.kind = kind,
1331 None => return (nameref_ctx, pat_ctx),
1333 path_ctx.has_type_args = segment.generic_arg_list().is_some();
1335 if let Some((path, use_tree_parent)) = path_or_use_tree_qualifier(&path) {
1336 if !use_tree_parent {
1337 path_ctx.is_absolute_path =
1338 path.top_path().segment().map_or(false, |it| it.coloncolon_token().is_some());
1343 .and_then(|it| find_node_in_file(original_file, &it))
1344 .map(|it| it.parent_path());
1345 path_ctx.qualifier = path.map(|path| {
1346 let res = sema.resolve_path(&path);
1347 let is_super_chain = iter::successors(Some(path.clone()), |p| p.qualifier())
1348 .all(|p| p.segment().and_then(|s| s.super_token()).is_some());
1351 let is_infer_qualifier = path.qualifier().is_none()
1353 path.segment().and_then(|it| it.kind()),
1354 Some(ast::PathSegmentKind::Type {
1355 type_ref: Some(ast::Type::InferType(_)),
1368 } else if let Some(segment) = path.segment() {
1369 if segment.coloncolon_token().is_some() {
1370 path_ctx.is_absolute_path = true;
1373 nameref_ctx.path_ctx = Some(path_ctx);
1374 (nameref_ctx, pat_ctx)
1378 fn pattern_context_for(original_file: &SyntaxNode, pat: ast::Pat) -> PatternContext {
1379 let mut is_param = None;
1380 let (refutability, has_type_ascription) =
1384 .skip_while(|it| ast::Pat::can_cast(it.kind()))
1386 .map_or((PatternRefutability::Irrefutable, false), |node| {
1387 let refutability = match_ast! {
1389 ast::LetStmt(let_) => return (PatternRefutability::Irrefutable, let_.ty().is_some()),
1390 ast::Param(param) => {
1391 let has_type_ascription = param.ty().is_some();
1393 let fake_param_list = param.syntax().parent().and_then(ast::ParamList::cast)?;
1394 let param_list = find_node_in_file_compensated(original_file, &fake_param_list)?;
1395 let param_list_owner = param_list.syntax().parent()?;
1396 let kind = match_ast! {
1397 match param_list_owner {
1398 ast::ClosureExpr(closure) => ParamKind::Closure(closure),
1399 ast::Fn(fn_) => ParamKind::Function(fn_),
1403 Some((param_list, param, kind))
1405 return (PatternRefutability::Irrefutable, has_type_ascription)
1407 ast::MatchArm(_) => PatternRefutability::Refutable,
1408 ast::LetExpr(_) => PatternRefutability::Refutable,
1409 ast::ForExpr(_) => PatternRefutability::Irrefutable,
1410 _ => PatternRefutability::Irrefutable,
1413 (refutability, false)
1415 let (ref_token, mut_token) = match &pat {
1416 ast::Pat::IdentPat(it) => (it.ref_token(), it.mut_token()),
1421 param_ctx: is_param,
1422 has_type_ascription,
1423 parent_pat: pat.syntax().parent().and_then(ast::Pat::cast),
1430 fn find_in_original_file<N: AstNode>(x: Option<N>, original_file: &SyntaxNode) -> Option<N> {
1431 fn find_node_with_range<N: AstNode>(syntax: &SyntaxNode, range: TextRange) -> Option<N> {
1432 let range = syntax.text_range().intersect(range)?;
1433 syntax.covering_element(range).ancestors().find_map(N::cast)
1435 x.map(|e| e.syntax().text_range()).and_then(|r| find_node_with_range(original_file, r))
1438 /// Attempts to find `node` inside `syntax` via `node`'s text range.
1439 fn find_node_in_file<N: AstNode>(syntax: &SyntaxNode, node: &N) -> Option<N> {
1440 let syntax_range = syntax.text_range();
1441 let range = node.syntax().text_range();
1442 let intersection = range.intersect(syntax_range)?;
1443 syntax.covering_element(intersection).ancestors().find_map(N::cast)
1446 /// Attempts to find `node` inside `syntax` via `node`'s text range while compensating
1447 /// for the offset introduced by the fake ident.
1448 /// This is wrong if `node` comes before the insertion point! Use `find_node_in_file` instead.
1449 fn find_node_in_file_compensated<N: AstNode>(syntax: &SyntaxNode, node: &N) -> Option<N> {
1450 let syntax_range = syntax.text_range();
1451 let range = node.syntax().text_range();
1452 let end = range.end().checked_sub(TextSize::try_from(COMPLETION_MARKER.len()).ok()?)?;
1453 if end < range.start() {
1456 let range = TextRange::new(range.start(), end);
1457 // our inserted ident could cause `range` to be go outside of the original syntax, so cap it
1458 let intersection = range.intersect(syntax_range)?;
1459 syntax.covering_element(intersection).ancestors().find_map(N::cast)
1462 fn path_or_use_tree_qualifier(path: &ast::Path) -> Option<(ast::Path, bool)> {
1463 if let Some(qual) = path.qualifier() {
1464 return Some((qual, false));
1466 let use_tree_list = path.syntax().ancestors().find_map(ast::UseTreeList::cast)?;
1467 let use_tree = use_tree_list.syntax().parent().and_then(ast::UseTree::cast)?;
1468 Some((use_tree.path()?, true))
1471 fn has_ref(token: &SyntaxToken) -> bool {
1472 let mut token = token.clone();
1473 for skip in [IDENT, WHITESPACE, T![mut]] {
1474 if token.kind() == skip {
1475 token = match token.prev_token() {
1477 None => return false,
1481 token.kind() == T![&]
1484 const OP_TRAIT_LANG_NAMES: &[&str] = &[
1519 use expect_test::{expect, Expect};
1520 use hir::HirDisplay;
1522 use crate::tests::{position, TEST_CONFIG};
1524 use super::CompletionContext;
1526 fn check_expected_type_and_name(ra_fixture: &str, expect: Expect) {
1527 let (db, pos) = position(ra_fixture);
1528 let config = TEST_CONFIG;
1529 let completion_context = CompletionContext::new(&db, pos, &config).unwrap();
1531 let ty = completion_context
1533 .map(|t| t.display_test(&db).to_string())
1534 .unwrap_or("?".to_owned());
1536 let name = completion_context
1538 .map_or_else(|| "?".to_owned(), |name| name.to_string());
1540 expect.assert_eq(&format!("ty: {}, name: {}", ty, name));
1544 fn expected_type_let_without_leading_char() {
1545 cov_mark::check!(expected_type_let_without_leading_char);
1546 check_expected_type_and_name(
1552 expect![[r#"ty: u32, name: x"#]],
1557 fn expected_type_let_with_leading_char() {
1558 cov_mark::check!(expected_type_let_with_leading_char);
1559 check_expected_type_and_name(
1565 expect![[r#"ty: u32, name: x"#]],
1570 fn expected_type_let_pat() {
1571 check_expected_type_and_name(
1577 expect![[r#"ty: u32, name: ?"#]],
1579 check_expected_type_and_name(
1585 expect![[r#"ty: u32, name: ?"#]],
1590 fn expected_type_fn_param() {
1591 cov_mark::check!(expected_type_fn_param);
1592 check_expected_type_and_name(
1594 fn foo() { bar($0); }
1597 expect![[r#"ty: u32, name: x"#]],
1599 check_expected_type_and_name(
1601 fn foo() { bar(c$0); }
1604 expect![[r#"ty: u32, name: x"#]],
1609 fn expected_type_fn_param_ref() {
1610 cov_mark::check!(expected_type_fn_param_ref);
1611 check_expected_type_and_name(
1613 fn foo() { bar(&$0); }
1616 expect![[r#"ty: u32, name: x"#]],
1618 check_expected_type_and_name(
1620 fn foo() { bar(&mut $0); }
1621 fn bar(x: &mut u32) {}
1623 expect![[r#"ty: u32, name: x"#]],
1625 check_expected_type_and_name(
1627 fn foo() { bar(& c$0); }
1630 expect![[r#"ty: u32, name: x"#]],
1632 check_expected_type_and_name(
1634 fn foo() { bar(&mut c$0); }
1635 fn bar(x: &mut u32) {}
1637 expect![[r#"ty: u32, name: x"#]],
1639 check_expected_type_and_name(
1641 fn foo() { bar(&c$0); }
1644 expect![[r#"ty: u32, name: x"#]],
1649 fn expected_type_struct_field_without_leading_char() {
1650 cov_mark::check!(expected_type_struct_field_without_leading_char);
1651 check_expected_type_and_name(
1653 struct Foo { a: u32 }
1658 expect![[r#"ty: u32, name: a"#]],
1663 fn expected_type_struct_field_followed_by_comma() {
1664 cov_mark::check!(expected_type_struct_field_followed_by_comma);
1665 check_expected_type_and_name(
1667 struct Foo { a: u32 }
1672 expect![[r#"ty: u32, name: a"#]],
1677 fn expected_type_generic_struct_field() {
1678 check_expected_type_and_name(
1680 struct Foo<T> { a: T }
1681 fn foo() -> Foo<u32> {
1685 expect![[r#"ty: u32, name: a"#]],
1690 fn expected_type_struct_field_with_leading_char() {
1691 cov_mark::check!(expected_type_struct_field_with_leading_char);
1692 check_expected_type_and_name(
1694 struct Foo { a: u32 }
1699 expect![[r#"ty: u32, name: a"#]],
1704 fn expected_type_match_arm_without_leading_char() {
1705 cov_mark::check!(expected_type_match_arm_without_leading_char);
1706 check_expected_type_and_name(
1713 expect![[r#"ty: E, name: ?"#]],
1718 fn expected_type_match_arm_with_leading_char() {
1719 cov_mark::check!(expected_type_match_arm_with_leading_char);
1720 check_expected_type_and_name(
1727 expect![[r#"ty: E, name: ?"#]],
1732 fn expected_type_match_arm_body_without_leading_char() {
1733 cov_mark::check!(expected_type_match_arm_body_without_leading_char);
1734 check_expected_type_and_name(
1739 match E::X { E::X => $0 }
1742 expect![[r#"ty: Foo, name: ?"#]],
1747 fn expected_type_match_body_arm_with_leading_char() {
1748 cov_mark::check!(expected_type_match_arm_body_with_leading_char);
1749 check_expected_type_and_name(
1754 match E::X { E::X => c$0 }
1757 expect![[r#"ty: Foo, name: ?"#]],
1762 fn expected_type_if_let_without_leading_char() {
1763 cov_mark::check!(expected_type_if_let_without_leading_char);
1764 check_expected_type_and_name(
1766 enum Foo { Bar, Baz, Quux }
1773 expect![[r#"ty: Foo, name: ?"#]],
1778 fn expected_type_if_let_with_leading_char() {
1779 cov_mark::check!(expected_type_if_let_with_leading_char);
1780 check_expected_type_and_name(
1782 enum Foo { Bar, Baz, Quux }
1789 expect![[r#"ty: Foo, name: ?"#]],
1794 fn expected_type_fn_ret_without_leading_char() {
1795 cov_mark::check!(expected_type_fn_ret_without_leading_char);
1796 check_expected_type_and_name(
1802 expect![[r#"ty: u32, name: ?"#]],
1807 fn expected_type_fn_ret_with_leading_char() {
1808 cov_mark::check!(expected_type_fn_ret_with_leading_char);
1809 check_expected_type_and_name(
1815 expect![[r#"ty: u32, name: ?"#]],
1820 fn expected_type_fn_ret_fn_ref_fully_typed() {
1821 check_expected_type_and_name(
1827 expect![[r#"ty: u32, name: ?"#]],
1832 fn expected_type_closure_param_return() {
1833 // FIXME: make this work with `|| $0`
1834 check_expected_type_and_name(
1841 fn bar(f: impl FnOnce() -> u32) {}
1843 expect![[r#"ty: u32, name: ?"#]],
1848 fn expected_type_generic_function() {
1849 check_expected_type_and_name(
1857 expect![[r#"ty: u32, name: t"#]],
1862 fn expected_type_generic_method() {
1863 check_expected_type_and_name(
1871 fn bar(self, t: T) {}
1874 expect![[r#"ty: u32, name: t"#]],
1879 fn expected_type_functional_update() {
1880 cov_mark::check!(expected_type_struct_func_update);
1881 check_expected_type_and_name(
1883 struct Foo { field: u32 }
1890 expect![[r#"ty: Foo, name: ?"#]],
1895 fn expected_type_param_pat() {
1896 check_expected_type_and_name(
1898 struct Foo { field: u32 }
1901 expect![[r#"ty: Foo, name: ?"#]],
1903 check_expected_type_and_name(
1905 struct Foo { field: u32 }
1908 // FIXME make this work, currently fails due to pattern recovery eating the `:`
1909 expect![[r#"ty: ?, name: ?"#]],