1 //! See `CompletionContext` structure.
3 use base_db::SourceDatabaseExt;
4 use hir::{Local, Name, ScopeDef, Semantics, SemanticsScope, Type, TypeInfo};
6 base_db::{FilePosition, SourceDatabase},
7 call_info::ActiveParameter,
11 algo::find_node_at_offset,
12 ast::{self, NameOrNameRef, NameOwner},
13 match_ast, AstNode, NodeOrToken,
14 SyntaxKind::{self, *},
15 SyntaxNode, SyntaxToken, TextRange, TextSize, T,
21 determine_location, determine_prev_sibling, for_is_prev2, inside_impl_trait_block,
22 is_in_loop_body, previous_token, ImmediateLocation, ImmediatePrevSibling,
27 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
28 pub(crate) enum PatternRefutability {
34 pub(super) enum PathKind {
40 pub(crate) struct PathCompletionContext {
41 /// If this is a call with () already there
42 call_kind: Option<CallKind>,
43 /// A single-indent path, like `foo`. `::foo` should not be considered a trivial path.
44 pub(super) is_trivial_path: bool,
45 /// If not a trivial path, the prefix (qualifier).
46 pub(super) qualifier: Option<ast::Path>,
47 /// Whether the qualifier comes from a use tree parent or not
48 pub(super) use_tree_parent: bool,
49 pub(super) kind: Option<PathKind>,
50 /// Whether the path segment has type args or not.
51 pub(super) has_type_args: bool,
52 /// `true` if we are a statement or a last expr in the block.
53 pub(super) can_be_stmt: bool,
54 pub(super) in_loop_body: bool,
58 pub(super) struct PatternContext {
59 pub(super) refutability: PatternRefutability,
60 pub(super) is_param: Option<ParamKind>,
63 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
64 pub(crate) enum CallKind {
70 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
71 pub(crate) enum ParamKind {
75 /// `CompletionContext` is created early during completion to figure out, where
76 /// exactly is the cursor, syntax-wise.
78 pub(crate) struct CompletionContext<'a> {
79 pub(super) sema: Semantics<'a, RootDatabase>,
80 pub(super) scope: SemanticsScope<'a>,
81 pub(super) db: &'a RootDatabase,
82 pub(super) config: &'a CompletionConfig,
83 pub(super) position: FilePosition,
84 /// The token before the cursor, in the original file.
85 pub(super) original_token: SyntaxToken,
86 /// The token before the cursor, in the macro-expanded file.
87 pub(super) token: SyntaxToken,
88 pub(super) krate: Option<hir::Crate>,
89 pub(super) expected_name: Option<NameOrNameRef>,
90 pub(super) expected_type: Option<Type>,
92 /// The parent function of the cursor position if it exists.
93 pub(super) function_def: Option<ast::Fn>,
94 /// The parent impl of the cursor position if it exists.
95 pub(super) impl_def: Option<ast::Impl>,
96 pub(super) name_ref_syntax: Option<ast::NameRef>,
98 // potentially set if we are completing a lifetime
99 pub(super) lifetime_syntax: Option<ast::Lifetime>,
100 pub(super) lifetime_param_syntax: Option<ast::LifetimeParam>,
101 pub(super) lifetime_allowed: bool,
102 pub(super) is_label_ref: bool,
104 pub(super) completion_location: Option<ImmediateLocation>,
105 pub(super) prev_sibling: Option<ImmediatePrevSibling>,
106 pub(super) attribute_under_caret: Option<ast::Attr>,
107 pub(super) previous_token: Option<SyntaxToken>,
109 pub(super) pattern_ctx: Option<PatternContext>,
110 pub(super) path_context: Option<PathCompletionContext>,
111 pub(super) active_parameter: Option<ActiveParameter>,
112 pub(super) locals: Vec<(String, Local)>,
114 pub(super) incomplete_let: bool,
116 no_completion_required: bool,
119 impl<'a> CompletionContext<'a> {
121 db: &'a RootDatabase,
122 position: FilePosition,
123 config: &'a CompletionConfig,
124 ) -> Option<CompletionContext<'a>> {
125 let sema = Semantics::new(db);
127 let original_file = sema.parse(position.file_id);
129 // Insert a fake ident to get a valid parse tree. We will use this file
130 // to determine context, though the original_file will be used for
131 // actual completion.
132 let file_with_fake_ident = {
133 let parse = db.parse(position.file_id);
134 let edit = Indel::insert(position.offset, "intellijRulezz".to_string());
135 parse.reparse(&edit).tree()
137 let fake_ident_token =
138 file_with_fake_ident.syntax().token_at_offset(position.offset).right_biased().unwrap();
140 let krate = sema.to_module_def(position.file_id).map(|m| m.krate());
142 original_file.syntax().token_at_offset(position.offset).left_biased()?;
143 let token = sema.descend_into_macros(original_token.clone());
144 let scope = sema.scope_at_offset(&token, position.offset);
145 let mut locals = vec![];
146 scope.process_all_names(&mut |name, scope| {
147 if let ScopeDef::Local(local) = scope {
148 locals.push((name.to_string(), local));
151 let mut ctx = CompletionContext {
164 name_ref_syntax: None,
165 lifetime_syntax: None,
166 lifetime_param_syntax: None,
167 lifetime_allowed: false,
170 completion_location: None,
172 attribute_under_caret: None,
173 previous_token: None,
175 active_parameter: ActiveParameter::at(db, position),
177 incomplete_let: false,
178 no_completion_required: false,
181 let mut original_file = original_file.syntax().clone();
182 let mut speculative_file = file_with_fake_ident.syntax().clone();
183 let mut offset = position.offset;
184 let mut fake_ident_token = fake_ident_token;
186 // Are we inside a macro call?
187 while let (Some(actual_macro_call), Some(macro_call_with_fake_ident)) = (
188 find_node_at_offset::<ast::MacroCall>(&original_file, offset),
189 find_node_at_offset::<ast::MacroCall>(&speculative_file, offset),
191 if actual_macro_call.path().as_ref().map(|s| s.syntax().text())
192 != macro_call_with_fake_ident.path().as_ref().map(|s| s.syntax().text())
196 let speculative_args = match macro_call_with_fake_ident.token_tree() {
200 if let (Some(actual_expansion), Some(speculative_expansion)) = (
201 ctx.sema.expand(&actual_macro_call),
202 ctx.sema.speculative_expand(
208 let new_offset = speculative_expansion.1.text_range().start();
209 if new_offset > actual_expansion.text_range().end() {
212 original_file = actual_expansion;
213 speculative_file = speculative_expansion.0;
214 fake_ident_token = speculative_expansion.1;
220 ctx.fill(&original_file, speculative_file, offset);
224 /// Checks whether completions in that particular case don't make much sense.
226 /// - `fn $0` -- we expect function name, it's unlikely that "hint" will be helpful.
227 /// Exception for this case is `impl Trait for Foo`, where we would like to hint trait method names.
228 /// - `for _ i$0` -- obviously, it'll be "in" keyword.
229 pub(crate) fn no_completion_required(&self) -> bool {
230 self.no_completion_required
233 /// The range of the identifier that is being completed.
234 pub(crate) fn source_range(&self) -> TextRange {
235 // check kind of macro-expanded token, but use range of original token
236 let kind = self.token.kind();
237 if kind == IDENT || kind == LIFETIME_IDENT || kind == UNDERSCORE || kind.is_keyword() {
238 cov_mark::hit!(completes_if_prefix_is_keyword);
239 self.original_token.text_range()
240 } else if kind == CHAR {
241 // assume we are completing a lifetime but the user has only typed the '
242 cov_mark::hit!(completes_if_lifetime_without_idents);
243 TextRange::at(self.original_token.text_range().start(), TextSize::from(1))
245 TextRange::empty(self.position.offset)
249 pub(crate) fn previous_token_is(&self, kind: SyntaxKind) -> bool {
250 self.previous_token.as_ref().map_or(false, |tok| tok.kind() == kind)
253 pub(crate) fn expects_assoc_item(&self) -> bool {
254 matches!(self.completion_location, Some(ImmediateLocation::Trait | ImmediateLocation::Impl))
257 pub(crate) fn has_dot_receiver(&self) -> bool {
259 &self.completion_location,
260 Some(ImmediateLocation::FieldAccess { receiver, .. } | ImmediateLocation::MethodCall { receiver,.. })
261 if receiver.is_some()
265 pub(crate) fn dot_receiver(&self) -> Option<&ast::Expr> {
266 match &self.completion_location {
268 ImmediateLocation::MethodCall { receiver, .. }
269 | ImmediateLocation::FieldAccess { receiver, .. },
270 ) => receiver.as_ref(),
275 pub(crate) fn expects_non_trait_assoc_item(&self) -> bool {
276 matches!(self.completion_location, Some(ImmediateLocation::Impl))
279 pub(crate) fn expects_item(&self) -> bool {
280 matches!(self.completion_location, Some(ImmediateLocation::ItemList))
283 pub(crate) fn expects_generic_arg(&self) -> bool {
284 matches!(self.completion_location, Some(ImmediateLocation::GenericArgList(_)))
287 pub(crate) fn has_block_expr_parent(&self) -> bool {
288 matches!(self.completion_location, Some(ImmediateLocation::BlockExpr))
291 pub(crate) fn expects_ident_pat_or_ref_expr(&self) -> bool {
293 self.completion_location,
294 Some(ImmediateLocation::IdentPat | ImmediateLocation::RefExpr)
298 pub(crate) fn expect_field(&self) -> bool {
300 self.completion_location,
301 Some(ImmediateLocation::RecordField | ImmediateLocation::TupleField)
305 pub(crate) fn in_use_tree(&self) -> bool {
307 self.completion_location,
308 Some(ImmediateLocation::Use | ImmediateLocation::UseTree)
312 pub(crate) fn has_impl_or_trait_prev_sibling(&self) -> bool {
315 Some(ImmediatePrevSibling::ImplDefType | ImmediatePrevSibling::TraitDefName)
319 pub(crate) fn has_impl_prev_sibling(&self) -> bool {
320 matches!(self.prev_sibling, Some(ImmediatePrevSibling::ImplDefType))
323 pub(crate) fn has_visibility_prev_sibling(&self) -> bool {
324 matches!(self.prev_sibling, Some(ImmediatePrevSibling::Visibility))
327 pub(crate) fn after_if(&self) -> bool {
328 matches!(self.prev_sibling, Some(ImmediatePrevSibling::IfExpr))
331 pub(crate) fn is_path_disallowed(&self) -> bool {
332 self.attribute_under_caret.is_some()
333 || self.previous_token_is(T![unsafe])
336 Some(ImmediatePrevSibling::Attribute | ImmediatePrevSibling::Visibility)
339 self.completion_location,
341 ImmediateLocation::Attribute(_)
342 | ImmediateLocation::ModDeclaration(_)
343 | ImmediateLocation::RecordPat(_)
344 | ImmediateLocation::RecordExpr(_)
349 pub(crate) fn expects_expression(&self) -> bool {
350 matches!(self.path_context, Some(PathCompletionContext { kind: Some(PathKind::Expr), .. }))
353 pub(crate) fn expects_type(&self) -> bool {
354 matches!(self.path_context, Some(PathCompletionContext { kind: Some(PathKind::Type), .. }))
357 pub(crate) fn path_call_kind(&self) -> Option<CallKind> {
358 self.path_context.as_ref().and_then(|it| it.call_kind)
361 pub(crate) fn is_trivial_path(&self) -> bool {
362 matches!(self.path_context, Some(PathCompletionContext { is_trivial_path: true, .. }))
365 pub(crate) fn is_non_trivial_path(&self) -> bool {
366 matches!(self.path_context, Some(PathCompletionContext { is_trivial_path: false, .. }))
369 pub(crate) fn path_qual(&self) -> Option<&ast::Path> {
370 self.path_context.as_ref().and_then(|it| it.qualifier.as_ref())
373 /// Checks if an item is visible and not `doc(hidden)` at the completion site.
374 pub(crate) fn is_visible<I>(&self, item: &I) -> bool
376 I: hir::HasVisibility + hir::HasAttrs + hir::HasCrate + Copy,
378 self.is_visible_impl(&item.visibility(self.db), &item.attrs(self.db), item.krate(self.db))
381 pub(crate) fn is_scope_def_hidden(&self, scope_def: &ScopeDef) -> bool {
382 if let (Some(attrs), Some(krate)) = (scope_def.attrs(self.db), scope_def.krate(self.db)) {
383 return self.is_doc_hidden(&attrs, krate);
389 pub(crate) fn is_item_hidden(&self, item: &hir::ItemInNs) -> bool {
390 let attrs = item.attrs(self.db);
391 let krate = item.krate(self.db);
392 match (attrs, krate) {
393 (Some(attrs), Some(krate)) => self.is_doc_hidden(&attrs, krate),
398 pub(crate) fn is_immediately_after_macro_bang(&self) -> bool {
399 self.token.kind() == BANG && self.token.parent().map_or(false, |it| it.kind() == MACRO_CALL)
402 /// A version of [`SemanticsScope::process_all_names`] that filters out `#[doc(hidden)]` items.
403 pub(crate) fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
404 self.scope.process_all_names(&mut |name, def| {
405 if self.is_scope_def_hidden(&def) {
415 vis: &hir::Visibility,
417 defining_crate: hir::Crate,
419 let module = match self.scope.module() {
421 None => return false,
423 if !vis.is_visible_from(self.db, module.into()) {
424 // If the definition location is editable, also show private items
425 let root_file = defining_crate.root_file(self.db);
426 let source_root_id = self.db.file_source_root(root_file);
427 let is_editable = !self.db.source_root(source_root_id).is_library;
431 !self.is_doc_hidden(attrs, defining_crate)
434 fn is_doc_hidden(&self, attrs: &hir::Attrs, defining_crate: hir::Crate) -> bool {
435 let module = match self.scope.module() {
439 if module.krate() != defining_crate && attrs.has_doc_hidden() {
440 // `doc(hidden)` items are only completed within the defining crate.
447 fn fill_impl_def(&mut self) {
450 .token_ancestors_with_macros(self.token.clone())
451 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
452 .find_map(ast::Impl::cast);
455 fn expected_type_and_name(&self) -> (Option<Type>, Option<NameOrNameRef>) {
456 let mut node = match self.token.parent() {
458 None => return (None, None),
463 ast::LetStmt(it) => {
464 cov_mark::hit!(expected_type_let_with_leading_char);
465 cov_mark::hit!(expected_type_let_without_leading_char);
467 .and_then(|pat| self.sema.type_of_pat(&pat))
468 .or_else(|| it.initializer().and_then(|it| self.sema.type_of_expr(&it)))
469 .map(TypeInfo::original);
470 let name = if let Some(ast::Pat::IdentPat(ident)) = it.pat() {
471 ident.name().map(NameOrNameRef::Name)
478 ast::ArgList(_it) => {
479 cov_mark::hit!(expected_type_fn_param);
480 ActiveParameter::at_token(
484 let name = ap.ident().map(NameOrNameRef::Name);
485 let ty = if has_ref(&self.token) {
486 cov_mark::hit!(expected_type_fn_param_ref);
493 .unwrap_or((None, None))
495 ast::RecordExprFieldList(it) => {
496 // wouldn't try {} be nice...
498 if self.token.kind() == T![..]
499 || self.token.prev_token().map(|t| t.kind()) == Some(T![..])
501 cov_mark::hit!(expected_type_struct_func_update);
502 let record_expr = it.syntax().parent().and_then(ast::RecordExpr::cast)?;
503 let ty = self.sema.type_of_expr(&record_expr.into())?;
509 cov_mark::hit!(expected_type_struct_field_without_leading_char);
510 let expr_field = self.token.prev_sibling_or_token()?
512 .and_then(ast::RecordExprField::cast)?;
513 let (_, _, ty) = self.sema.resolve_record_field(&expr_field)?;
516 expr_field.field_name().map(NameOrNameRef::NameRef),
519 })().unwrap_or((None, None))
521 ast::RecordExprField(it) => {
522 cov_mark::hit!(expected_type_struct_field_with_leading_char);
524 it.expr().as_ref().and_then(|e| self.sema.type_of_expr(e)).map(TypeInfo::original),
525 it.field_name().map(NameOrNameRef::NameRef),
528 ast::MatchExpr(it) => {
529 cov_mark::hit!(expected_type_match_arm_without_leading_char);
530 let ty = it.expr().and_then(|e| self.sema.type_of_expr(&e)).map(TypeInfo::original);
534 cov_mark::hit!(expected_type_if_let_without_leading_char);
535 let ty = it.condition()
536 .and_then(|cond| cond.expr())
537 .and_then(|e| self.sema.type_of_expr(&e))
538 .map(TypeInfo::original);
541 ast::IdentPat(it) => {
542 cov_mark::hit!(expected_type_if_let_with_leading_char);
543 cov_mark::hit!(expected_type_match_arm_with_leading_char);
544 let ty = self.sema.type_of_pat(&ast::Pat::from(it)).map(TypeInfo::original);
548 cov_mark::hit!(expected_type_fn_ret_with_leading_char);
549 cov_mark::hit!(expected_type_fn_ret_without_leading_char);
550 let def = self.sema.to_def(&it);
551 (def.map(|def| def.ret_type(self.db)), None)
553 ast::ClosureExpr(it) => {
554 let ty = self.sema.type_of_expr(&it.into());
555 ty.and_then(|ty| ty.original.as_callable(self.db))
556 .map(|c| (Some(c.return_type()), None))
557 .unwrap_or((None, None))
559 ast::Stmt(_it) => (None, None),
560 ast::Item(__) => (None, None),
562 match node.parent() {
567 None => (None, None),
577 original_file: &SyntaxNode,
578 file_with_fake_ident: SyntaxNode,
581 let fake_ident_token = file_with_fake_ident.token_at_offset(offset).right_biased().unwrap();
582 let syntax_element = NodeOrToken::Token(fake_ident_token);
583 self.previous_token = previous_token(syntax_element.clone());
584 self.attribute_under_caret = syntax_element.ancestors().find_map(ast::Attr::cast);
585 self.no_completion_required = {
586 let inside_impl_trait_block = inside_impl_trait_block(syntax_element.clone());
587 let fn_is_prev = self.previous_token_is(T![fn]);
588 let for_is_prev2 = for_is_prev2(syntax_element.clone());
589 (fn_is_prev && !inside_impl_trait_block) || for_is_prev2
592 self.incomplete_let =
593 syntax_element.ancestors().take(6).find_map(ast::LetStmt::cast).map_or(false, |it| {
594 it.syntax().text_range().end() == syntax_element.text_range().end()
597 let (expected_type, expected_name) = self.expected_type_and_name();
598 self.expected_type = expected_type;
599 self.expected_name = expected_name;
601 let name_like = match find_node_at_offset(&file_with_fake_ident, offset) {
605 self.completion_location =
606 determine_location(&self.sema, original_file, offset, &name_like);
607 self.prev_sibling = determine_prev_sibling(&name_like);
609 ast::NameLike::Lifetime(lifetime) => {
610 self.classify_lifetime(original_file, lifetime, offset);
612 ast::NameLike::NameRef(name_ref) => {
613 self.classify_name_ref(original_file, name_ref);
615 ast::NameLike::Name(name) => {
616 self.classify_name(name);
621 fn classify_lifetime(
623 original_file: &SyntaxNode,
624 lifetime: ast::Lifetime,
627 self.lifetime_syntax =
628 find_node_at_offset(original_file, lifetime.syntax().text_range().start());
629 if let Some(parent) = lifetime.syntax().parent() {
630 if parent.kind() == ERROR {
636 ast::LifetimeParam(_it) => {
637 self.lifetime_allowed = true;
638 self.lifetime_param_syntax =
639 self.sema.find_node_at_offset_with_macros(original_file, offset);
641 ast::BreakExpr(_it) => self.is_label_ref = true,
642 ast::ContinueExpr(_it) => self.is_label_ref = true,
643 ast::Label(_it) => (),
644 _ => self.lifetime_allowed = true,
650 fn classify_name(&mut self, name: ast::Name) {
651 self.fill_impl_def();
653 if let Some(bind_pat) = name.syntax().parent().and_then(ast::IdentPat::cast) {
654 let is_name_in_field_pat = bind_pat
657 .and_then(ast::RecordPatField::cast)
658 .map_or(false, |pat_field| pat_field.name_ref().is_none());
659 if is_name_in_field_pat {
662 if bind_pat.is_simple_ident() {
663 let mut is_param = None;
664 let refutability = bind_pat
667 .skip_while(|it| ast::Pat::can_cast(it.kind()))
669 .map_or(PatternRefutability::Irrefutable, |node| {
672 ast::LetStmt(__) => PatternRefutability::Irrefutable,
673 ast::Param(param) => {
674 let is_closure_param = param
678 .and_then(ast::ClosureExpr::cast)
680 is_param = Some(if is_closure_param {
685 PatternRefutability::Irrefutable
687 ast::MatchArm(__) => PatternRefutability::Refutable,
688 ast::Condition(__) => PatternRefutability::Refutable,
689 ast::ForExpr(__) => PatternRefutability::Irrefutable,
690 _ => PatternRefutability::Irrefutable,
694 self.pattern_ctx = Some(PatternContext { refutability, is_param });
699 fn classify_name_ref(&mut self, original_file: &SyntaxNode, name_ref: ast::NameRef) {
700 self.fill_impl_def();
702 self.name_ref_syntax =
703 find_node_at_offset(original_file, name_ref.syntax().text_range().start());
705 self.function_def = self
707 .token_ancestors_with_macros(self.token.clone())
708 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
709 .find_map(ast::Fn::cast);
711 let parent = match name_ref.syntax().parent() {
716 if let Some(segment) = ast::PathSegment::cast(parent) {
717 let path_ctx = self.path_context.get_or_insert(PathCompletionContext {
719 is_trivial_path: false,
721 has_type_args: false,
724 use_tree_parent: false,
727 path_ctx.in_loop_body = is_in_loop_body(name_ref.syntax());
728 let path = segment.parent_path();
730 if let Some(p) = path.syntax().parent() {
731 path_ctx.call_kind = match_ast! {
733 ast::PathExpr(it) => it.syntax().parent().and_then(ast::CallExpr::cast).map(|_| CallKind::Expr),
734 ast::MacroCall(it) => it.excl_token().and(Some(CallKind::Mac)),
735 ast::TupleStructPat(_it) => Some(CallKind::Pat),
741 if let Some(parent) = path.syntax().parent() {
742 path_ctx.kind = match_ast! {
744 ast::PathType(_it) => Some(PathKind::Type),
745 ast::PathExpr(_it) => Some(PathKind::Expr),
750 path_ctx.has_type_args = segment.generic_arg_list().is_some();
752 if let Some((path, use_tree_parent)) = path_or_use_tree_qualifier(&path) {
753 path_ctx.use_tree_parent = use_tree_parent;
754 path_ctx.qualifier = path
757 find_node_with_range::<ast::PathSegment>(
759 it.syntax().text_range(),
762 .map(|it| it.parent_path());
766 if let Some(segment) = path.segment() {
767 if segment.coloncolon_token().is_some() {
772 path_ctx.is_trivial_path = true;
774 // Find either enclosing expr statement (thing with `;`) or a
775 // block. If block, check that we are the last expr.
776 path_ctx.can_be_stmt = name_ref
780 if let Some(stmt) = ast::ExprStmt::cast(node.clone()) {
781 return Some(stmt.syntax().text_range() == name_ref.syntax().text_range());
783 if let Some(block) = ast::BlockExpr::cast(node) {
785 block.tail_expr().map(|e| e.syntax().text_range())
786 == Some(name_ref.syntax().text_range()),
796 fn find_node_with_range<N: AstNode>(syntax: &SyntaxNode, range: TextRange) -> Option<N> {
797 syntax.covering_element(range).ancestors().find_map(N::cast)
800 fn path_or_use_tree_qualifier(path: &ast::Path) -> Option<(ast::Path, bool)> {
801 if let Some(qual) = path.qualifier() {
802 return Some((qual, false));
804 let use_tree_list = path.syntax().ancestors().find_map(ast::UseTreeList::cast)?;
805 let use_tree = use_tree_list.syntax().parent().and_then(ast::UseTree::cast)?;
806 use_tree.path().zip(Some(true))
809 fn has_ref(token: &SyntaxToken) -> bool {
810 let mut token = token.clone();
811 for skip in [WHITESPACE, IDENT, T![mut]] {
812 if token.kind() == skip {
813 token = match token.prev_token() {
815 None => return false,
819 token.kind() == T![&]
824 use expect_test::{expect, Expect};
827 use crate::tests::{position, TEST_CONFIG};
829 use super::CompletionContext;
831 fn check_expected_type_and_name(ra_fixture: &str, expect: Expect) {
832 let (db, pos) = position(ra_fixture);
833 let completion_context = CompletionContext::new(&db, pos, &TEST_CONFIG).unwrap();
835 let ty = completion_context
837 .map(|t| t.display_test(&db).to_string())
838 .unwrap_or("?".to_owned());
840 let name = completion_context
842 .map_or_else(|| "?".to_owned(), |name| name.to_string());
844 expect.assert_eq(&format!("ty: {}, name: {}", ty, name));
848 fn expected_type_let_without_leading_char() {
849 cov_mark::check!(expected_type_let_without_leading_char);
850 check_expected_type_and_name(
856 expect![[r#"ty: u32, name: x"#]],
861 fn expected_type_let_with_leading_char() {
862 cov_mark::check!(expected_type_let_with_leading_char);
863 check_expected_type_and_name(
869 expect![[r#"ty: u32, name: x"#]],
874 fn expected_type_let_pat() {
875 check_expected_type_and_name(
881 expect![[r#"ty: u32, name: ?"#]],
883 check_expected_type_and_name(
889 expect![[r#"ty: u32, name: ?"#]],
894 fn expected_type_fn_param() {
895 cov_mark::check!(expected_type_fn_param);
896 check_expected_type_and_name(
898 fn foo() { bar($0); }
901 expect![[r#"ty: u32, name: x"#]],
903 check_expected_type_and_name(
905 fn foo() { bar(c$0); }
908 expect![[r#"ty: u32, name: x"#]],
913 fn expected_type_fn_param_ref() {
914 cov_mark::check!(expected_type_fn_param_ref);
915 check_expected_type_and_name(
917 fn foo() { bar(&$0); }
920 expect![[r#"ty: u32, name: x"#]],
922 check_expected_type_and_name(
924 fn foo() { bar(&mut $0); }
925 fn bar(x: &mut u32) {}
927 expect![[r#"ty: u32, name: x"#]],
929 check_expected_type_and_name(
931 fn foo() { bar(&c$0); }
934 expect![[r#"ty: u32, name: x"#]],
939 fn expected_type_struct_field_without_leading_char() {
940 cov_mark::check!(expected_type_struct_field_without_leading_char);
941 check_expected_type_and_name(
943 struct Foo { a: u32 }
948 expect![[r#"ty: u32, name: a"#]],
953 fn expected_type_generic_struct_field() {
954 check_expected_type_and_name(
956 struct Foo<T> { a: T }
957 fn foo() -> Foo<u32> {
961 expect![[r#"ty: u32, name: a"#]],
966 fn expected_type_struct_field_with_leading_char() {
967 cov_mark::check!(expected_type_struct_field_with_leading_char);
968 check_expected_type_and_name(
970 struct Foo { a: u32 }
975 expect![[r#"ty: u32, name: a"#]],
980 fn expected_type_match_arm_without_leading_char() {
981 cov_mark::check!(expected_type_match_arm_without_leading_char);
982 check_expected_type_and_name(
989 expect![[r#"ty: E, name: ?"#]],
994 fn expected_type_match_arm_with_leading_char() {
995 cov_mark::check!(expected_type_match_arm_with_leading_char);
996 check_expected_type_and_name(
1003 expect![[r#"ty: E, name: ?"#]],
1008 fn expected_type_if_let_without_leading_char() {
1009 cov_mark::check!(expected_type_if_let_without_leading_char);
1010 check_expected_type_and_name(
1012 enum Foo { Bar, Baz, Quux }
1019 expect![[r#"ty: Foo, name: ?"#]],
1024 fn expected_type_if_let_with_leading_char() {
1025 cov_mark::check!(expected_type_if_let_with_leading_char);
1026 check_expected_type_and_name(
1028 enum Foo { Bar, Baz, Quux }
1035 expect![[r#"ty: Foo, name: ?"#]],
1040 fn expected_type_fn_ret_without_leading_char() {
1041 cov_mark::check!(expected_type_fn_ret_without_leading_char);
1042 check_expected_type_and_name(
1048 expect![[r#"ty: u32, name: ?"#]],
1053 fn expected_type_fn_ret_with_leading_char() {
1054 cov_mark::check!(expected_type_fn_ret_with_leading_char);
1055 check_expected_type_and_name(
1061 expect![[r#"ty: u32, name: ?"#]],
1066 fn expected_type_fn_ret_fn_ref_fully_typed() {
1067 check_expected_type_and_name(
1073 expect![[r#"ty: u32, name: ?"#]],
1078 fn expected_type_closure_param_return() {
1079 // FIXME: make this work with `|| $0`
1080 check_expected_type_and_name(
1087 fn bar(f: impl FnOnce() -> u32) {}
1089 expect![[r#"ty: u32, name: ?"#]],
1094 fn expected_type_generic_function() {
1095 check_expected_type_and_name(
1103 expect![[r#"ty: u32, name: t"#]],
1108 fn expected_type_generic_method() {
1109 check_expected_type_and_name(
1117 fn bar(self, t: T) {}
1120 expect![[r#"ty: u32, name: t"#]],
1125 fn expected_type_functional_update() {
1126 cov_mark::check!(expected_type_struct_func_update);
1127 check_expected_type_and_name(
1129 struct Foo { field: u32 }
1136 expect![[r#"ty: Foo, name: ?"#]],