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_syntax: Option<ast::NameLike>,
98 // potentially set if we are completing a lifetime
99 pub(super) lifetime_param_syntax: Option<ast::LifetimeParam>,
100 pub(super) lifetime_allowed: bool,
101 pub(super) is_label_ref: bool,
103 pub(super) completion_location: Option<ImmediateLocation>,
104 pub(super) prev_sibling: Option<ImmediatePrevSibling>,
105 pub(super) attribute_under_caret: Option<ast::Attr>,
106 pub(super) previous_token: Option<SyntaxToken>,
108 pub(super) pattern_ctx: Option<PatternContext>,
109 pub(super) path_context: Option<PathCompletionContext>,
110 pub(super) locals: Vec<(String, Local)>,
112 pub(super) incomplete_let: bool,
114 no_completion_required: bool,
117 impl<'a> CompletionContext<'a> {
119 db: &'a RootDatabase,
120 position: FilePosition,
121 config: &'a CompletionConfig,
122 ) -> Option<CompletionContext<'a>> {
123 let sema = Semantics::new(db);
125 let original_file = sema.parse(position.file_id);
127 // Insert a fake ident to get a valid parse tree. We will use this file
128 // to determine context, though the original_file will be used for
129 // actual completion.
130 let file_with_fake_ident = {
131 let parse = db.parse(position.file_id);
132 let edit = Indel::insert(position.offset, "intellijRulezz".to_string());
133 parse.reparse(&edit).tree()
135 let fake_ident_token =
136 file_with_fake_ident.syntax().token_at_offset(position.offset).right_biased().unwrap();
138 let krate = sema.to_module_def(position.file_id).map(|m| m.krate());
140 original_file.syntax().token_at_offset(position.offset).left_biased()?;
141 let token = sema.descend_into_macros(original_token.clone());
142 let scope = sema.scope_at_offset(&token, position.offset);
143 let mut locals = vec![];
144 scope.process_all_names(&mut |name, scope| {
145 if let ScopeDef::Local(local) = scope {
146 locals.push((name.to_string(), local));
149 let mut ctx = CompletionContext {
163 lifetime_param_syntax: None,
164 lifetime_allowed: false,
167 completion_location: None,
169 attribute_under_caret: None,
170 previous_token: None,
173 incomplete_let: false,
174 no_completion_required: false,
177 original_file.syntax().clone(),
178 file_with_fake_ident.syntax().clone(),
187 mut original_file: SyntaxNode,
188 mut speculative_file: SyntaxNode,
189 mut offset: TextSize,
190 mut fake_ident_token: SyntaxToken,
194 if let (Some(actual_item), Some(item_with_fake_ident)) = (
195 find_node_at_offset::<ast::Item>(&original_file, offset),
196 find_node_at_offset::<ast::Item>(&speculative_file, offset),
199 self.sema.expand_attr_macro(&actual_item),
200 self.sema.speculative_expand_attr_macro(
202 &item_with_fake_ident,
203 fake_ident_token.clone(),
206 (Some(actual_expansion), Some(speculative_expansion)) => {
207 let new_offset = speculative_expansion.1.text_range().start();
208 if new_offset > actual_expansion.text_range().end() {
211 original_file = actual_expansion;
212 speculative_file = speculative_expansion.0;
213 fake_ident_token = speculative_expansion.1;
222 // Expand fn-like macro calls
223 if let (Some(actual_macro_call), Some(macro_call_with_fake_ident)) = (
224 find_node_at_offset::<ast::MacroCall>(&original_file, offset),
225 find_node_at_offset::<ast::MacroCall>(&speculative_file, offset),
227 let mac_call_path0 = actual_macro_call.path().as_ref().map(|s| s.syntax().text());
229 macro_call_with_fake_ident.path().as_ref().map(|s| s.syntax().text());
230 if mac_call_path0 != mac_call_path1 {
233 let speculative_args = match macro_call_with_fake_ident.token_tree() {
238 if let (Some(actual_expansion), Some(speculative_expansion)) = (
239 self.sema.expand(&actual_macro_call),
240 self.sema.speculative_expand(
246 let new_offset = speculative_expansion.1.text_range().start();
247 if new_offset > actual_expansion.text_range().end() {
250 original_file = actual_expansion;
251 speculative_file = speculative_expansion.0;
252 fake_ident_token = speculative_expansion.1;
262 self.fill(&original_file, speculative_file, offset);
265 /// Checks whether completions in that particular case don't make much sense.
267 /// - `fn $0` -- we expect function name, it's unlikely that "hint" will be helpful.
268 /// Exception for this case is `impl Trait for Foo`, where we would like to hint trait method names.
269 /// - `for _ i$0` -- obviously, it'll be "in" keyword.
270 pub(crate) fn no_completion_required(&self) -> bool {
271 self.no_completion_required
274 /// The range of the identifier that is being completed.
275 pub(crate) fn source_range(&self) -> TextRange {
276 // check kind of macro-expanded token, but use range of original token
277 let kind = self.token.kind();
278 if kind == IDENT || kind == LIFETIME_IDENT || kind == UNDERSCORE || kind.is_keyword() {
279 cov_mark::hit!(completes_if_prefix_is_keyword);
280 self.original_token.text_range()
281 } else if kind == CHAR {
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 TextRange::empty(self.position.offset)
290 pub(crate) fn previous_token_is(&self, kind: SyntaxKind) -> bool {
291 self.previous_token.as_ref().map_or(false, |tok| tok.kind() == kind)
294 pub(crate) fn expects_assoc_item(&self) -> bool {
295 matches!(self.completion_location, Some(ImmediateLocation::Trait | ImmediateLocation::Impl))
298 pub(crate) fn has_dot_receiver(&self) -> bool {
300 &self.completion_location,
301 Some(ImmediateLocation::FieldAccess { receiver, .. } | ImmediateLocation::MethodCall { receiver,.. })
302 if receiver.is_some()
306 pub(crate) fn dot_receiver(&self) -> Option<&ast::Expr> {
307 match &self.completion_location {
309 ImmediateLocation::MethodCall { receiver, .. }
310 | ImmediateLocation::FieldAccess { receiver, .. },
311 ) => receiver.as_ref(),
316 pub(crate) fn expects_non_trait_assoc_item(&self) -> bool {
317 matches!(self.completion_location, Some(ImmediateLocation::Impl))
320 pub(crate) fn expects_item(&self) -> bool {
321 matches!(self.completion_location, Some(ImmediateLocation::ItemList))
324 pub(crate) fn expects_generic_arg(&self) -> bool {
325 matches!(self.completion_location, Some(ImmediateLocation::GenericArgList(_)))
328 pub(crate) fn has_block_expr_parent(&self) -> bool {
329 matches!(self.completion_location, Some(ImmediateLocation::StmtList))
332 pub(crate) fn expects_ident_pat_or_ref_expr(&self) -> bool {
334 self.completion_location,
335 Some(ImmediateLocation::IdentPat | ImmediateLocation::RefExpr)
339 pub(crate) fn expect_field(&self) -> bool {
341 self.completion_location,
342 Some(ImmediateLocation::RecordField | ImmediateLocation::TupleField)
346 pub(crate) fn in_use_tree(&self) -> bool {
348 self.completion_location,
349 Some(ImmediateLocation::Use | ImmediateLocation::UseTree)
353 pub(crate) fn has_impl_or_trait_prev_sibling(&self) -> bool {
356 Some(ImmediatePrevSibling::ImplDefType | ImmediatePrevSibling::TraitDefName)
360 pub(crate) fn has_impl_prev_sibling(&self) -> bool {
361 matches!(self.prev_sibling, Some(ImmediatePrevSibling::ImplDefType))
364 pub(crate) fn has_visibility_prev_sibling(&self) -> bool {
365 matches!(self.prev_sibling, Some(ImmediatePrevSibling::Visibility))
368 pub(crate) fn after_if(&self) -> bool {
369 matches!(self.prev_sibling, Some(ImmediatePrevSibling::IfExpr))
372 pub(crate) fn is_path_disallowed(&self) -> bool {
373 self.attribute_under_caret.is_some()
374 || self.previous_token_is(T![unsafe])
377 Some(ImmediatePrevSibling::Attribute | ImmediatePrevSibling::Visibility)
380 self.completion_location,
382 ImmediateLocation::Attribute(_)
383 | ImmediateLocation::ModDeclaration(_)
384 | ImmediateLocation::RecordPat(_)
385 | ImmediateLocation::RecordExpr(_)
390 pub(crate) fn expects_expression(&self) -> bool {
391 matches!(self.path_context, Some(PathCompletionContext { kind: Some(PathKind::Expr), .. }))
394 pub(crate) fn expects_type(&self) -> bool {
395 matches!(self.path_context, Some(PathCompletionContext { kind: Some(PathKind::Type), .. }))
398 pub(crate) fn path_call_kind(&self) -> Option<CallKind> {
399 self.path_context.as_ref().and_then(|it| it.call_kind)
402 pub(crate) fn is_trivial_path(&self) -> bool {
403 matches!(self.path_context, Some(PathCompletionContext { is_trivial_path: true, .. }))
406 pub(crate) fn is_non_trivial_path(&self) -> bool {
407 matches!(self.path_context, Some(PathCompletionContext { is_trivial_path: false, .. }))
410 pub(crate) fn path_qual(&self) -> Option<&ast::Path> {
411 self.path_context.as_ref().and_then(|it| it.qualifier.as_ref())
414 /// Checks if an item is visible and not `doc(hidden)` at the completion site.
415 pub(crate) fn is_visible<I>(&self, item: &I) -> bool
417 I: hir::HasVisibility + hir::HasAttrs + hir::HasCrate + Copy,
419 self.is_visible_impl(&item.visibility(self.db), &item.attrs(self.db), item.krate(self.db))
422 pub(crate) fn is_scope_def_hidden(&self, scope_def: &ScopeDef) -> bool {
423 if let (Some(attrs), Some(krate)) = (scope_def.attrs(self.db), scope_def.krate(self.db)) {
424 return self.is_doc_hidden(&attrs, krate);
430 pub(crate) fn is_item_hidden(&self, item: &hir::ItemInNs) -> bool {
431 let attrs = item.attrs(self.db);
432 let krate = item.krate(self.db);
433 match (attrs, krate) {
434 (Some(attrs), Some(krate)) => self.is_doc_hidden(&attrs, krate),
439 pub(crate) fn is_immediately_after_macro_bang(&self) -> bool {
440 self.token.kind() == BANG && self.token.parent().map_or(false, |it| it.kind() == MACRO_CALL)
443 /// A version of [`SemanticsScope::process_all_names`] that filters out `#[doc(hidden)]` items.
444 pub(crate) fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
445 self.scope.process_all_names(&mut |name, def| {
446 if self.is_scope_def_hidden(&def) {
456 vis: &hir::Visibility,
458 defining_crate: hir::Crate,
460 let module = match self.scope.module() {
462 None => return false,
464 if !vis.is_visible_from(self.db, module.into()) {
465 // If the definition location is editable, also show private items
466 let root_file = defining_crate.root_file(self.db);
467 let source_root_id = self.db.file_source_root(root_file);
468 let is_editable = !self.db.source_root(source_root_id).is_library;
472 !self.is_doc_hidden(attrs, defining_crate)
475 fn is_doc_hidden(&self, attrs: &hir::Attrs, defining_crate: hir::Crate) -> bool {
476 let module = match self.scope.module() {
480 if module.krate() != defining_crate && attrs.has_doc_hidden() {
481 // `doc(hidden)` items are only completed within the defining crate.
488 fn fill_impl_def(&mut self) {
491 .token_ancestors_with_macros(self.token.clone())
492 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
493 .find_map(ast::Impl::cast);
496 fn expected_type_and_name(&self) -> (Option<Type>, Option<NameOrNameRef>) {
497 let mut node = match self.token.parent() {
499 None => return (None, None),
504 ast::LetStmt(it) => {
505 cov_mark::hit!(expected_type_let_with_leading_char);
506 cov_mark::hit!(expected_type_let_without_leading_char);
508 .and_then(|pat| self.sema.type_of_pat(&pat))
509 .or_else(|| it.initializer().and_then(|it| self.sema.type_of_expr(&it)))
510 .map(TypeInfo::original);
511 let name = if let Some(ast::Pat::IdentPat(ident)) = it.pat() {
512 ident.name().map(NameOrNameRef::Name)
519 ast::ArgList(_it) => {
520 cov_mark::hit!(expected_type_fn_param);
521 ActiveParameter::at_token(
525 let name = ap.ident().map(NameOrNameRef::Name);
526 let ty = if has_ref(&self.token) {
527 cov_mark::hit!(expected_type_fn_param_ref);
534 .unwrap_or((None, None))
536 ast::RecordExprFieldList(it) => {
537 // wouldn't try {} be nice...
539 if self.token.kind() == T![..]
540 || self.token.prev_token().map(|t| t.kind()) == Some(T![..])
542 cov_mark::hit!(expected_type_struct_func_update);
543 let record_expr = it.syntax().parent().and_then(ast::RecordExpr::cast)?;
544 let ty = self.sema.type_of_expr(&record_expr.into())?;
550 cov_mark::hit!(expected_type_struct_field_without_leading_char);
551 let expr_field = self.token.prev_sibling_or_token()?
553 .and_then(ast::RecordExprField::cast)?;
554 let (_, _, ty) = self.sema.resolve_record_field(&expr_field)?;
557 expr_field.field_name().map(NameOrNameRef::NameRef),
560 })().unwrap_or((None, None))
562 ast::RecordExprField(it) => {
563 cov_mark::hit!(expected_type_struct_field_with_leading_char);
565 it.expr().as_ref().and_then(|e| self.sema.type_of_expr(e)).map(TypeInfo::original),
566 it.field_name().map(NameOrNameRef::NameRef),
569 ast::MatchExpr(it) => {
570 cov_mark::hit!(expected_type_match_arm_without_leading_char);
571 let ty = it.expr().and_then(|e| self.sema.type_of_expr(&e)).map(TypeInfo::original);
575 cov_mark::hit!(expected_type_if_let_without_leading_char);
576 let ty = it.condition()
577 .and_then(|cond| cond.expr())
578 .and_then(|e| self.sema.type_of_expr(&e))
579 .map(TypeInfo::original);
582 ast::IdentPat(it) => {
583 cov_mark::hit!(expected_type_if_let_with_leading_char);
584 cov_mark::hit!(expected_type_match_arm_with_leading_char);
585 let ty = self.sema.type_of_pat(&ast::Pat::from(it)).map(TypeInfo::original);
589 cov_mark::hit!(expected_type_fn_ret_with_leading_char);
590 cov_mark::hit!(expected_type_fn_ret_without_leading_char);
591 let def = self.sema.to_def(&it);
592 (def.map(|def| def.ret_type(self.db)), None)
594 ast::ClosureExpr(it) => {
595 let ty = self.sema.type_of_expr(&it.into());
596 ty.and_then(|ty| ty.original.as_callable(self.db))
597 .map(|c| (Some(c.return_type()), None))
598 .unwrap_or((None, None))
600 ast::Stmt(_it) => (None, None),
601 ast::Item(__) => (None, None),
603 match node.parent() {
608 None => (None, None),
618 original_file: &SyntaxNode,
619 file_with_fake_ident: SyntaxNode,
622 let fake_ident_token = file_with_fake_ident.token_at_offset(offset).right_biased().unwrap();
623 let syntax_element = NodeOrToken::Token(fake_ident_token);
624 self.previous_token = previous_token(syntax_element.clone());
625 self.attribute_under_caret = syntax_element.ancestors().find_map(ast::Attr::cast);
626 self.no_completion_required = {
627 let inside_impl_trait_block = inside_impl_trait_block(syntax_element.clone());
628 let fn_is_prev = self.previous_token_is(T![fn]);
629 let for_is_prev2 = for_is_prev2(syntax_element.clone());
630 (fn_is_prev && !inside_impl_trait_block) || for_is_prev2
633 self.incomplete_let =
634 syntax_element.ancestors().take(6).find_map(ast::LetStmt::cast).map_or(false, |it| {
635 it.syntax().text_range().end() == syntax_element.text_range().end()
638 let (expected_type, expected_name) = self.expected_type_and_name();
639 self.expected_type = expected_type;
640 self.expected_name = expected_name;
642 let name_like = match find_node_at_offset(&file_with_fake_ident, offset) {
646 self.completion_location =
647 determine_location(&self.sema, original_file, offset, &name_like);
648 self.prev_sibling = determine_prev_sibling(&name_like);
650 find_node_at_offset(original_file, name_like.syntax().text_range().start());
652 ast::NameLike::Lifetime(lifetime) => {
653 self.classify_lifetime(original_file, lifetime, offset);
655 ast::NameLike::NameRef(name_ref) => {
656 self.classify_name_ref(original_file, name_ref);
658 ast::NameLike::Name(name) => {
659 self.classify_name(name);
664 fn classify_lifetime(
666 original_file: &SyntaxNode,
667 lifetime: ast::Lifetime,
670 if let Some(parent) = lifetime.syntax().parent() {
671 if parent.kind() == ERROR {
677 ast::LifetimeParam(_it) => {
678 self.lifetime_allowed = true;
679 self.lifetime_param_syntax =
680 self.sema.find_node_at_offset_with_macros(original_file, offset);
682 ast::BreakExpr(_it) => self.is_label_ref = true,
683 ast::ContinueExpr(_it) => self.is_label_ref = true,
684 ast::Label(_it) => (),
685 _ => self.lifetime_allowed = true,
691 fn classify_name(&mut self, name: ast::Name) {
692 self.fill_impl_def();
694 if let Some(bind_pat) = name.syntax().parent().and_then(ast::IdentPat::cast) {
695 let is_name_in_field_pat = bind_pat
698 .and_then(ast::RecordPatField::cast)
699 .map_or(false, |pat_field| pat_field.name_ref().is_none());
700 if is_name_in_field_pat {
703 if bind_pat.is_simple_ident() {
704 let mut is_param = None;
705 let refutability = bind_pat
708 .skip_while(|it| ast::Pat::can_cast(it.kind()))
710 .map_or(PatternRefutability::Irrefutable, |node| {
713 ast::LetStmt(__) => PatternRefutability::Irrefutable,
714 ast::Param(param) => {
715 let is_closure_param = param
719 .and_then(ast::ClosureExpr::cast)
721 is_param = Some(if is_closure_param {
726 PatternRefutability::Irrefutable
728 ast::MatchArm(__) => PatternRefutability::Refutable,
729 ast::Condition(__) => PatternRefutability::Refutable,
730 ast::ForExpr(__) => PatternRefutability::Irrefutable,
731 _ => PatternRefutability::Irrefutable,
735 self.pattern_ctx = Some(PatternContext { refutability, is_param });
740 fn classify_name_ref(&mut self, original_file: &SyntaxNode, name_ref: ast::NameRef) {
741 self.fill_impl_def();
743 self.function_def = self
745 .token_ancestors_with_macros(self.token.clone())
746 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
747 .find_map(ast::Fn::cast);
749 let parent = match name_ref.syntax().parent() {
754 if let Some(segment) = ast::PathSegment::cast(parent) {
755 let path_ctx = self.path_context.get_or_insert(PathCompletionContext {
757 is_trivial_path: false,
759 has_type_args: false,
762 use_tree_parent: false,
765 path_ctx.in_loop_body = is_in_loop_body(name_ref.syntax());
766 let path = segment.parent_path();
768 if let Some(p) = path.syntax().parent() {
769 path_ctx.call_kind = match_ast! {
771 ast::PathExpr(it) => it.syntax().parent().and_then(ast::CallExpr::cast).map(|_| CallKind::Expr),
772 ast::MacroCall(it) => it.excl_token().and(Some(CallKind::Mac)),
773 ast::TupleStructPat(_it) => Some(CallKind::Pat),
779 if let Some(parent) = path.syntax().parent() {
780 path_ctx.kind = match_ast! {
782 ast::PathType(_it) => Some(PathKind::Type),
783 ast::PathExpr(_it) => Some(PathKind::Expr),
788 path_ctx.has_type_args = segment.generic_arg_list().is_some();
790 if let Some((path, use_tree_parent)) = path_or_use_tree_qualifier(&path) {
791 path_ctx.use_tree_parent = use_tree_parent;
792 path_ctx.qualifier = path
795 find_node_with_range::<ast::PathSegment>(
797 it.syntax().text_range(),
800 .map(|it| it.parent_path());
804 if let Some(segment) = path.segment() {
805 if segment.coloncolon_token().is_some() {
810 path_ctx.is_trivial_path = true;
812 // Find either enclosing expr statement (thing with `;`) or a
813 // block. If block, check that we are the last expr.
814 path_ctx.can_be_stmt = name_ref
818 if let Some(stmt) = ast::ExprStmt::cast(node.clone()) {
819 return Some(stmt.syntax().text_range() == name_ref.syntax().text_range());
821 if let Some(stmt_list) = ast::StmtList::cast(node) {
823 stmt_list.tail_expr().map(|e| e.syntax().text_range())
824 == Some(name_ref.syntax().text_range()),
834 fn find_node_with_range<N: AstNode>(syntax: &SyntaxNode, range: TextRange) -> Option<N> {
835 syntax.covering_element(range).ancestors().find_map(N::cast)
838 fn path_or_use_tree_qualifier(path: &ast::Path) -> Option<(ast::Path, bool)> {
839 if let Some(qual) = path.qualifier() {
840 return Some((qual, false));
842 let use_tree_list = path.syntax().ancestors().find_map(ast::UseTreeList::cast)?;
843 let use_tree = use_tree_list.syntax().parent().and_then(ast::UseTree::cast)?;
844 use_tree.path().zip(Some(true))
847 fn has_ref(token: &SyntaxToken) -> bool {
848 let mut token = token.clone();
849 for skip in [WHITESPACE, IDENT, T![mut]] {
850 if token.kind() == skip {
851 token = match token.prev_token() {
853 None => return false,
857 token.kind() == T![&]
862 use expect_test::{expect, Expect};
865 use crate::tests::{position, TEST_CONFIG};
867 use super::CompletionContext;
869 fn check_expected_type_and_name(ra_fixture: &str, expect: Expect) {
870 let (db, pos) = position(ra_fixture);
871 let completion_context = CompletionContext::new(&db, pos, &TEST_CONFIG).unwrap();
873 let ty = completion_context
875 .map(|t| t.display_test(&db).to_string())
876 .unwrap_or("?".to_owned());
878 let name = completion_context
880 .map_or_else(|| "?".to_owned(), |name| name.to_string());
882 expect.assert_eq(&format!("ty: {}, name: {}", ty, name));
886 fn expected_type_let_without_leading_char() {
887 cov_mark::check!(expected_type_let_without_leading_char);
888 check_expected_type_and_name(
894 expect![[r#"ty: u32, name: x"#]],
899 fn expected_type_let_with_leading_char() {
900 cov_mark::check!(expected_type_let_with_leading_char);
901 check_expected_type_and_name(
907 expect![[r#"ty: u32, name: x"#]],
912 fn expected_type_let_pat() {
913 check_expected_type_and_name(
919 expect![[r#"ty: u32, name: ?"#]],
921 check_expected_type_and_name(
927 expect![[r#"ty: u32, name: ?"#]],
932 fn expected_type_fn_param() {
933 cov_mark::check!(expected_type_fn_param);
934 check_expected_type_and_name(
936 fn foo() { bar($0); }
939 expect![[r#"ty: u32, name: x"#]],
941 check_expected_type_and_name(
943 fn foo() { bar(c$0); }
946 expect![[r#"ty: u32, name: x"#]],
951 fn expected_type_fn_param_ref() {
952 cov_mark::check!(expected_type_fn_param_ref);
953 check_expected_type_and_name(
955 fn foo() { bar(&$0); }
958 expect![[r#"ty: u32, name: x"#]],
960 check_expected_type_and_name(
962 fn foo() { bar(&mut $0); }
963 fn bar(x: &mut u32) {}
965 expect![[r#"ty: u32, name: x"#]],
967 check_expected_type_and_name(
969 fn foo() { bar(&c$0); }
972 expect![[r#"ty: u32, name: x"#]],
977 fn expected_type_struct_field_without_leading_char() {
978 cov_mark::check!(expected_type_struct_field_without_leading_char);
979 check_expected_type_and_name(
981 struct Foo { a: u32 }
986 expect![[r#"ty: u32, name: a"#]],
991 fn expected_type_generic_struct_field() {
992 check_expected_type_and_name(
994 struct Foo<T> { a: T }
995 fn foo() -> Foo<u32> {
999 expect![[r#"ty: u32, name: a"#]],
1004 fn expected_type_struct_field_with_leading_char() {
1005 cov_mark::check!(expected_type_struct_field_with_leading_char);
1006 check_expected_type_and_name(
1008 struct Foo { a: u32 }
1013 expect![[r#"ty: u32, name: a"#]],
1018 fn expected_type_match_arm_without_leading_char() {
1019 cov_mark::check!(expected_type_match_arm_without_leading_char);
1020 check_expected_type_and_name(
1027 expect![[r#"ty: E, name: ?"#]],
1032 fn expected_type_match_arm_with_leading_char() {
1033 cov_mark::check!(expected_type_match_arm_with_leading_char);
1034 check_expected_type_and_name(
1041 expect![[r#"ty: E, name: ?"#]],
1046 fn expected_type_if_let_without_leading_char() {
1047 cov_mark::check!(expected_type_if_let_without_leading_char);
1048 check_expected_type_and_name(
1050 enum Foo { Bar, Baz, Quux }
1057 expect![[r#"ty: Foo, name: ?"#]],
1062 fn expected_type_if_let_with_leading_char() {
1063 cov_mark::check!(expected_type_if_let_with_leading_char);
1064 check_expected_type_and_name(
1066 enum Foo { Bar, Baz, Quux }
1073 expect![[r#"ty: Foo, name: ?"#]],
1078 fn expected_type_fn_ret_without_leading_char() {
1079 cov_mark::check!(expected_type_fn_ret_without_leading_char);
1080 check_expected_type_and_name(
1086 expect![[r#"ty: u32, name: ?"#]],
1091 fn expected_type_fn_ret_with_leading_char() {
1092 cov_mark::check!(expected_type_fn_ret_with_leading_char);
1093 check_expected_type_and_name(
1099 expect![[r#"ty: u32, name: ?"#]],
1104 fn expected_type_fn_ret_fn_ref_fully_typed() {
1105 check_expected_type_and_name(
1111 expect![[r#"ty: u32, name: ?"#]],
1116 fn expected_type_closure_param_return() {
1117 // FIXME: make this work with `|| $0`
1118 check_expected_type_and_name(
1125 fn bar(f: impl FnOnce() -> u32) {}
1127 expect![[r#"ty: u32, name: ?"#]],
1132 fn expected_type_generic_function() {
1133 check_expected_type_and_name(
1141 expect![[r#"ty: u32, name: t"#]],
1146 fn expected_type_generic_method() {
1147 check_expected_type_and_name(
1155 fn bar(self, t: T) {}
1158 expect![[r#"ty: u32, name: t"#]],
1163 fn expected_type_functional_update() {
1164 cov_mark::check!(expected_type_struct_func_update);
1165 check_expected_type_and_name(
1167 struct Foo { field: u32 }
1174 expect![[r#"ty: Foo, name: ?"#]],