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) active_parameter: Option<ActiveParameter>,
111 pub(super) locals: Vec<(String, Local)>,
113 pub(super) incomplete_let: bool,
115 no_completion_required: bool,
118 impl<'a> CompletionContext<'a> {
120 db: &'a RootDatabase,
121 position: FilePosition,
122 config: &'a CompletionConfig,
123 ) -> Option<CompletionContext<'a>> {
124 let sema = Semantics::new(db);
126 let original_file = sema.parse(position.file_id);
128 // Insert a fake ident to get a valid parse tree. We will use this file
129 // to determine context, though the original_file will be used for
130 // actual completion.
131 let file_with_fake_ident = {
132 let parse = db.parse(position.file_id);
133 let edit = Indel::insert(position.offset, "intellijRulezz".to_string());
134 parse.reparse(&edit).tree()
136 let fake_ident_token =
137 file_with_fake_ident.syntax().token_at_offset(position.offset).right_biased().unwrap();
139 let krate = sema.to_module_def(position.file_id).map(|m| m.krate());
141 original_file.syntax().token_at_offset(position.offset).left_biased()?;
142 let token = sema.descend_into_macros(original_token.clone());
143 let scope = sema.scope_at_offset(&token, position.offset);
144 let mut locals = vec![];
145 scope.process_all_names(&mut |name, scope| {
146 if let ScopeDef::Local(local) = scope {
147 locals.push((name.to_string(), local));
150 let mut ctx = CompletionContext {
164 lifetime_param_syntax: None,
165 lifetime_allowed: false,
168 completion_location: None,
170 attribute_under_caret: None,
171 previous_token: None,
173 active_parameter: ActiveParameter::at(db, position),
175 incomplete_let: false,
176 no_completion_required: false,
179 original_file.syntax().clone(),
180 file_with_fake_ident.syntax().clone(),
189 mut original_file: SyntaxNode,
190 mut speculative_file: SyntaxNode,
191 mut offset: TextSize,
192 mut fake_ident_token: SyntaxToken,
196 if let (Some(actual_item), Some(item_with_fake_ident)) = (
197 find_node_at_offset::<ast::Item>(&original_file, offset),
198 find_node_at_offset::<ast::Item>(&speculative_file, offset),
201 self.sema.expand_attr_macro(&actual_item),
202 self.sema.speculative_expand_attr_macro(
204 &item_with_fake_ident,
205 fake_ident_token.clone(),
208 (Some(actual_expansion), Some(speculative_expansion)) => {
209 let new_offset = speculative_expansion.1.text_range().start();
210 if new_offset > actual_expansion.text_range().end() {
213 original_file = actual_expansion;
214 speculative_file = speculative_expansion.0;
215 fake_ident_token = speculative_expansion.1;
224 // Expand fn-like macro calls
225 if let (Some(actual_macro_call), Some(macro_call_with_fake_ident)) = (
226 find_node_at_offset::<ast::MacroCall>(&original_file, offset),
227 find_node_at_offset::<ast::MacroCall>(&speculative_file, offset),
229 let mac_call_path0 = actual_macro_call.path().as_ref().map(|s| s.syntax().text());
231 macro_call_with_fake_ident.path().as_ref().map(|s| s.syntax().text());
232 if mac_call_path0 != mac_call_path1 {
235 let speculative_args = match macro_call_with_fake_ident.token_tree() {
240 if let (Some(actual_expansion), Some(speculative_expansion)) = (
241 self.sema.expand(&actual_macro_call),
242 self.sema.speculative_expand(
248 let new_offset = speculative_expansion.1.text_range().start();
249 if new_offset > actual_expansion.text_range().end() {
252 original_file = actual_expansion;
253 speculative_file = speculative_expansion.0;
254 fake_ident_token = speculative_expansion.1;
264 self.fill(&original_file, speculative_file, offset);
267 /// Checks whether completions in that particular case don't make much sense.
269 /// - `fn $0` -- we expect function name, it's unlikely that "hint" will be helpful.
270 /// Exception for this case is `impl Trait for Foo`, where we would like to hint trait method names.
271 /// - `for _ i$0` -- obviously, it'll be "in" keyword.
272 pub(crate) fn no_completion_required(&self) -> bool {
273 self.no_completion_required
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();
280 if kind == IDENT || kind == LIFETIME_IDENT || kind == UNDERSCORE || kind.is_keyword() {
281 cov_mark::hit!(completes_if_prefix_is_keyword);
282 self.original_token.text_range()
283 } else if kind == CHAR {
284 // assume we are completing a lifetime but the user has only typed the '
285 cov_mark::hit!(completes_if_lifetime_without_idents);
286 TextRange::at(self.original_token.text_range().start(), TextSize::from(1))
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 expects_assoc_item(&self) -> bool {
297 matches!(self.completion_location, Some(ImmediateLocation::Trait | ImmediateLocation::Impl))
300 pub(crate) fn has_dot_receiver(&self) -> bool {
302 &self.completion_location,
303 Some(ImmediateLocation::FieldAccess { receiver, .. } | ImmediateLocation::MethodCall { receiver,.. })
304 if receiver.is_some()
308 pub(crate) fn dot_receiver(&self) -> Option<&ast::Expr> {
309 match &self.completion_location {
311 ImmediateLocation::MethodCall { receiver, .. }
312 | ImmediateLocation::FieldAccess { receiver, .. },
313 ) => receiver.as_ref(),
318 pub(crate) fn expects_non_trait_assoc_item(&self) -> bool {
319 matches!(self.completion_location, Some(ImmediateLocation::Impl))
322 pub(crate) fn expects_item(&self) -> bool {
323 matches!(self.completion_location, Some(ImmediateLocation::ItemList))
326 pub(crate) fn expects_generic_arg(&self) -> bool {
327 matches!(self.completion_location, Some(ImmediateLocation::GenericArgList(_)))
330 pub(crate) fn has_block_expr_parent(&self) -> bool {
331 matches!(self.completion_location, Some(ImmediateLocation::BlockExpr))
334 pub(crate) fn expects_ident_pat_or_ref_expr(&self) -> bool {
336 self.completion_location,
337 Some(ImmediateLocation::IdentPat | ImmediateLocation::RefExpr)
341 pub(crate) fn expect_field(&self) -> bool {
343 self.completion_location,
344 Some(ImmediateLocation::RecordField | ImmediateLocation::TupleField)
348 pub(crate) fn in_use_tree(&self) -> bool {
350 self.completion_location,
351 Some(ImmediateLocation::Use | ImmediateLocation::UseTree)
355 pub(crate) fn has_impl_or_trait_prev_sibling(&self) -> bool {
358 Some(ImmediatePrevSibling::ImplDefType | ImmediatePrevSibling::TraitDefName)
362 pub(crate) fn has_impl_prev_sibling(&self) -> bool {
363 matches!(self.prev_sibling, Some(ImmediatePrevSibling::ImplDefType))
366 pub(crate) fn has_visibility_prev_sibling(&self) -> bool {
367 matches!(self.prev_sibling, Some(ImmediatePrevSibling::Visibility))
370 pub(crate) fn after_if(&self) -> bool {
371 matches!(self.prev_sibling, Some(ImmediatePrevSibling::IfExpr))
374 pub(crate) fn is_path_disallowed(&self) -> bool {
375 self.attribute_under_caret.is_some()
376 || self.previous_token_is(T![unsafe])
379 Some(ImmediatePrevSibling::Attribute | ImmediatePrevSibling::Visibility)
382 self.completion_location,
384 ImmediateLocation::Attribute(_)
385 | ImmediateLocation::ModDeclaration(_)
386 | ImmediateLocation::RecordPat(_)
387 | ImmediateLocation::RecordExpr(_)
392 pub(crate) fn expects_expression(&self) -> bool {
393 matches!(self.path_context, Some(PathCompletionContext { kind: Some(PathKind::Expr), .. }))
396 pub(crate) fn expects_type(&self) -> bool {
397 matches!(self.path_context, Some(PathCompletionContext { kind: Some(PathKind::Type), .. }))
400 pub(crate) fn path_call_kind(&self) -> Option<CallKind> {
401 self.path_context.as_ref().and_then(|it| it.call_kind)
404 pub(crate) fn is_trivial_path(&self) -> bool {
405 matches!(self.path_context, Some(PathCompletionContext { is_trivial_path: true, .. }))
408 pub(crate) fn is_non_trivial_path(&self) -> bool {
409 matches!(self.path_context, Some(PathCompletionContext { is_trivial_path: false, .. }))
412 pub(crate) fn path_qual(&self) -> Option<&ast::Path> {
413 self.path_context.as_ref().and_then(|it| it.qualifier.as_ref())
416 /// Checks if an item is visible and not `doc(hidden)` at the completion site.
417 pub(crate) fn is_visible<I>(&self, item: &I) -> bool
419 I: hir::HasVisibility + hir::HasAttrs + hir::HasCrate + Copy,
421 self.is_visible_impl(&item.visibility(self.db), &item.attrs(self.db), item.krate(self.db))
424 pub(crate) fn is_scope_def_hidden(&self, scope_def: &ScopeDef) -> bool {
425 if let (Some(attrs), Some(krate)) = (scope_def.attrs(self.db), scope_def.krate(self.db)) {
426 return self.is_doc_hidden(&attrs, krate);
432 pub(crate) fn is_item_hidden(&self, item: &hir::ItemInNs) -> bool {
433 let attrs = item.attrs(self.db);
434 let krate = item.krate(self.db);
435 match (attrs, krate) {
436 (Some(attrs), Some(krate)) => self.is_doc_hidden(&attrs, krate),
441 /// A version of [`SemanticsScope::process_all_names`] that filters out `#[doc(hidden)]` items.
442 pub(crate) fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
443 self.scope.process_all_names(&mut |name, def| {
444 if self.is_scope_def_hidden(&def) {
454 vis: &hir::Visibility,
456 defining_crate: hir::Crate,
458 let module = match self.scope.module() {
460 None => return false,
462 if !vis.is_visible_from(self.db, module.into()) {
463 // If the definition location is editable, also show private items
464 let root_file = defining_crate.root_file(self.db);
465 let source_root_id = self.db.file_source_root(root_file);
466 let is_editable = !self.db.source_root(source_root_id).is_library;
470 !self.is_doc_hidden(attrs, defining_crate)
473 fn is_doc_hidden(&self, attrs: &hir::Attrs, defining_crate: hir::Crate) -> bool {
474 let module = match self.scope.module() {
478 if module.krate() != defining_crate && attrs.has_doc_hidden() {
479 // `doc(hidden)` items are only completed within the defining crate.
486 fn fill_impl_def(&mut self) {
489 .token_ancestors_with_macros(self.token.clone())
490 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
491 .find_map(ast::Impl::cast);
494 fn expected_type_and_name(&self) -> (Option<Type>, Option<NameOrNameRef>) {
495 let mut node = match self.token.parent() {
497 None => return (None, None),
502 ast::LetStmt(it) => {
503 cov_mark::hit!(expected_type_let_with_leading_char);
504 cov_mark::hit!(expected_type_let_without_leading_char);
506 .and_then(|pat| self.sema.type_of_pat(&pat))
507 .or_else(|| it.initializer().and_then(|it| self.sema.type_of_expr(&it)))
508 .map(TypeInfo::original);
509 let name = if let Some(ast::Pat::IdentPat(ident)) = it.pat() {
510 ident.name().map(NameOrNameRef::Name)
517 ast::ArgList(_it) => {
518 cov_mark::hit!(expected_type_fn_param);
519 ActiveParameter::at_token(
523 let name = ap.ident().map(NameOrNameRef::Name);
524 let ty = if has_ref(&self.token) {
525 cov_mark::hit!(expected_type_fn_param_ref);
532 .unwrap_or((None, None))
534 ast::RecordExprFieldList(it) => {
535 // wouldn't try {} be nice...
537 if self.token.kind() == T![..]
538 || self.token.prev_token().map(|t| t.kind()) == Some(T![..])
540 cov_mark::hit!(expected_type_struct_func_update);
541 let record_expr = it.syntax().parent().and_then(ast::RecordExpr::cast)?;
542 let ty = self.sema.type_of_expr(&record_expr.into())?;
548 cov_mark::hit!(expected_type_struct_field_without_leading_char);
549 let expr_field = self.token.prev_sibling_or_token()?
551 .and_then(ast::RecordExprField::cast)?;
552 let (_, _, ty) = self.sema.resolve_record_field(&expr_field)?;
555 expr_field.field_name().map(NameOrNameRef::NameRef),
558 })().unwrap_or((None, None))
560 ast::RecordExprField(it) => {
561 cov_mark::hit!(expected_type_struct_field_with_leading_char);
563 it.expr().as_ref().and_then(|e| self.sema.type_of_expr(e)).map(TypeInfo::original),
564 it.field_name().map(NameOrNameRef::NameRef),
567 ast::MatchExpr(it) => {
568 cov_mark::hit!(expected_type_match_arm_without_leading_char);
569 let ty = it.expr().and_then(|e| self.sema.type_of_expr(&e)).map(TypeInfo::original);
573 cov_mark::hit!(expected_type_if_let_without_leading_char);
574 let ty = it.condition()
575 .and_then(|cond| cond.expr())
576 .and_then(|e| self.sema.type_of_expr(&e))
577 .map(TypeInfo::original);
580 ast::IdentPat(it) => {
581 cov_mark::hit!(expected_type_if_let_with_leading_char);
582 cov_mark::hit!(expected_type_match_arm_with_leading_char);
583 let ty = self.sema.type_of_pat(&ast::Pat::from(it)).map(TypeInfo::original);
587 cov_mark::hit!(expected_type_fn_ret_with_leading_char);
588 cov_mark::hit!(expected_type_fn_ret_without_leading_char);
589 let def = self.sema.to_def(&it);
590 (def.map(|def| def.ret_type(self.db)), None)
592 ast::ClosureExpr(it) => {
593 let ty = self.sema.type_of_expr(&it.into());
594 ty.and_then(|ty| ty.original.as_callable(self.db))
595 .map(|c| (Some(c.return_type()), None))
596 .unwrap_or((None, None))
598 ast::Stmt(_it) => (None, None),
599 ast::Item(__) => (None, None),
601 match node.parent() {
606 None => (None, None),
616 original_file: &SyntaxNode,
617 file_with_fake_ident: SyntaxNode,
620 let fake_ident_token = file_with_fake_ident.token_at_offset(offset).right_biased().unwrap();
621 let syntax_element = NodeOrToken::Token(fake_ident_token);
622 self.previous_token = previous_token(syntax_element.clone());
623 self.attribute_under_caret = syntax_element.ancestors().find_map(ast::Attr::cast);
624 self.no_completion_required = {
625 let inside_impl_trait_block = inside_impl_trait_block(syntax_element.clone());
626 let fn_is_prev = self.previous_token_is(T![fn]);
627 let for_is_prev2 = for_is_prev2(syntax_element.clone());
628 (fn_is_prev && !inside_impl_trait_block) || for_is_prev2
631 self.incomplete_let =
632 syntax_element.ancestors().take(6).find_map(ast::LetStmt::cast).map_or(false, |it| {
633 it.syntax().text_range().end() == syntax_element.text_range().end()
636 let (expected_type, expected_name) = self.expected_type_and_name();
637 self.expected_type = expected_type;
638 self.expected_name = expected_name;
640 let name_like = match find_node_at_offset(&file_with_fake_ident, offset) {
644 self.completion_location =
645 determine_location(&self.sema, original_file, offset, &name_like);
646 self.prev_sibling = determine_prev_sibling(&name_like);
648 find_node_at_offset(original_file, name_like.syntax().text_range().start());
650 ast::NameLike::Lifetime(lifetime) => {
651 self.classify_lifetime(original_file, lifetime, offset);
653 ast::NameLike::NameRef(name_ref) => {
654 self.classify_name_ref(original_file, name_ref);
656 ast::NameLike::Name(name) => {
657 self.classify_name(name);
662 fn classify_lifetime(
664 original_file: &SyntaxNode,
665 lifetime: ast::Lifetime,
668 if let Some(parent) = lifetime.syntax().parent() {
669 if parent.kind() == ERROR {
675 ast::LifetimeParam(_it) => {
676 self.lifetime_allowed = true;
677 self.lifetime_param_syntax =
678 self.sema.find_node_at_offset_with_macros(original_file, offset);
680 ast::BreakExpr(_it) => self.is_label_ref = true,
681 ast::ContinueExpr(_it) => self.is_label_ref = true,
682 ast::Label(_it) => (),
683 _ => self.lifetime_allowed = true,
689 fn classify_name(&mut self, name: ast::Name) {
690 self.fill_impl_def();
692 if let Some(bind_pat) = name.syntax().parent().and_then(ast::IdentPat::cast) {
693 let is_name_in_field_pat = bind_pat
696 .and_then(ast::RecordPatField::cast)
697 .map_or(false, |pat_field| pat_field.name_ref().is_none());
698 if is_name_in_field_pat {
701 if bind_pat.is_simple_ident() {
702 let mut is_param = None;
703 let refutability = bind_pat
706 .skip_while(|it| ast::Pat::can_cast(it.kind()))
708 .map_or(PatternRefutability::Irrefutable, |node| {
711 ast::LetStmt(__) => PatternRefutability::Irrefutable,
712 ast::Param(param) => {
713 let is_closure_param = param
717 .and_then(ast::ClosureExpr::cast)
719 is_param = Some(if is_closure_param {
724 PatternRefutability::Irrefutable
726 ast::MatchArm(__) => PatternRefutability::Refutable,
727 ast::Condition(__) => PatternRefutability::Refutable,
728 ast::ForExpr(__) => PatternRefutability::Irrefutable,
729 _ => PatternRefutability::Irrefutable,
733 self.pattern_ctx = Some(PatternContext { refutability, is_param });
738 fn classify_name_ref(&mut self, original_file: &SyntaxNode, name_ref: ast::NameRef) {
739 self.fill_impl_def();
741 self.function_def = self
743 .token_ancestors_with_macros(self.token.clone())
744 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
745 .find_map(ast::Fn::cast);
747 let parent = match name_ref.syntax().parent() {
752 if let Some(segment) = ast::PathSegment::cast(parent) {
753 let path_ctx = self.path_context.get_or_insert(PathCompletionContext {
755 is_trivial_path: false,
757 has_type_args: false,
760 use_tree_parent: false,
763 path_ctx.in_loop_body = is_in_loop_body(name_ref.syntax());
764 let path = segment.parent_path();
766 if let Some(p) = path.syntax().parent() {
767 path_ctx.call_kind = match_ast! {
769 ast::PathExpr(it) => it.syntax().parent().and_then(ast::CallExpr::cast).map(|_| CallKind::Expr),
770 ast::MacroCall(it) => it.excl_token().and(Some(CallKind::Mac)),
771 ast::TupleStructPat(_it) => Some(CallKind::Pat),
777 if let Some(parent) = path.syntax().parent() {
778 path_ctx.kind = match_ast! {
780 ast::PathType(_it) => Some(PathKind::Type),
781 ast::PathExpr(_it) => Some(PathKind::Expr),
786 path_ctx.has_type_args = segment.generic_arg_list().is_some();
788 if let Some((path, use_tree_parent)) = path_or_use_tree_qualifier(&path) {
789 path_ctx.use_tree_parent = use_tree_parent;
790 path_ctx.qualifier = path
793 find_node_with_range::<ast::PathSegment>(
795 it.syntax().text_range(),
798 .map(|it| it.parent_path());
802 if let Some(segment) = path.segment() {
803 if segment.coloncolon_token().is_some() {
808 path_ctx.is_trivial_path = true;
810 // Find either enclosing expr statement (thing with `;`) or a
811 // block. If block, check that we are the last expr.
812 path_ctx.can_be_stmt = name_ref
816 if let Some(stmt) = ast::ExprStmt::cast(node.clone()) {
817 return Some(stmt.syntax().text_range() == name_ref.syntax().text_range());
819 if let Some(block) = ast::BlockExpr::cast(node) {
821 block.tail_expr().map(|e| e.syntax().text_range())
822 == Some(name_ref.syntax().text_range()),
832 fn find_node_with_range<N: AstNode>(syntax: &SyntaxNode, range: TextRange) -> Option<N> {
833 syntax.covering_element(range).ancestors().find_map(N::cast)
836 fn path_or_use_tree_qualifier(path: &ast::Path) -> Option<(ast::Path, bool)> {
837 if let Some(qual) = path.qualifier() {
838 return Some((qual, false));
840 let use_tree_list = path.syntax().ancestors().find_map(ast::UseTreeList::cast)?;
841 let use_tree = use_tree_list.syntax().parent().and_then(ast::UseTree::cast)?;
842 use_tree.path().zip(Some(true))
845 fn has_ref(token: &SyntaxToken) -> bool {
846 let mut token = token.clone();
847 for skip in [WHITESPACE, IDENT, T![mut]] {
848 if token.kind() == skip {
849 token = match token.prev_token() {
851 None => return false,
855 token.kind() == T![&]
860 use expect_test::{expect, Expect};
863 use crate::tests::{position, TEST_CONFIG};
865 use super::CompletionContext;
867 fn check_expected_type_and_name(ra_fixture: &str, expect: Expect) {
868 let (db, pos) = position(ra_fixture);
869 let completion_context = CompletionContext::new(&db, pos, &TEST_CONFIG).unwrap();
871 let ty = completion_context
873 .map(|t| t.display_test(&db).to_string())
874 .unwrap_or("?".to_owned());
876 let name = completion_context
878 .map_or_else(|| "?".to_owned(), |name| name.to_string());
880 expect.assert_eq(&format!("ty: {}, name: {}", ty, name));
884 fn expected_type_let_without_leading_char() {
885 cov_mark::check!(expected_type_let_without_leading_char);
886 check_expected_type_and_name(
892 expect![[r#"ty: u32, name: x"#]],
897 fn expected_type_let_with_leading_char() {
898 cov_mark::check!(expected_type_let_with_leading_char);
899 check_expected_type_and_name(
905 expect![[r#"ty: u32, name: x"#]],
910 fn expected_type_let_pat() {
911 check_expected_type_and_name(
917 expect![[r#"ty: u32, name: ?"#]],
919 check_expected_type_and_name(
925 expect![[r#"ty: u32, name: ?"#]],
930 fn expected_type_fn_param() {
931 cov_mark::check!(expected_type_fn_param);
932 check_expected_type_and_name(
934 fn foo() { bar($0); }
937 expect![[r#"ty: u32, name: x"#]],
939 check_expected_type_and_name(
941 fn foo() { bar(c$0); }
944 expect![[r#"ty: u32, name: x"#]],
949 fn expected_type_fn_param_ref() {
950 cov_mark::check!(expected_type_fn_param_ref);
951 check_expected_type_and_name(
953 fn foo() { bar(&$0); }
956 expect![[r#"ty: u32, name: x"#]],
958 check_expected_type_and_name(
960 fn foo() { bar(&mut $0); }
961 fn bar(x: &mut u32) {}
963 expect![[r#"ty: u32, name: x"#]],
965 check_expected_type_and_name(
967 fn foo() { bar(&c$0); }
970 expect![[r#"ty: u32, name: x"#]],
975 fn expected_type_struct_field_without_leading_char() {
976 cov_mark::check!(expected_type_struct_field_without_leading_char);
977 check_expected_type_and_name(
979 struct Foo { a: u32 }
984 expect![[r#"ty: u32, name: a"#]],
989 fn expected_type_generic_struct_field() {
990 check_expected_type_and_name(
992 struct Foo<T> { a: T }
993 fn foo() -> Foo<u32> {
997 expect![[r#"ty: u32, name: a"#]],
1002 fn expected_type_struct_field_with_leading_char() {
1003 cov_mark::check!(expected_type_struct_field_with_leading_char);
1004 check_expected_type_and_name(
1006 struct Foo { a: u32 }
1011 expect![[r#"ty: u32, name: a"#]],
1016 fn expected_type_match_arm_without_leading_char() {
1017 cov_mark::check!(expected_type_match_arm_without_leading_char);
1018 check_expected_type_and_name(
1025 expect![[r#"ty: E, name: ?"#]],
1030 fn expected_type_match_arm_with_leading_char() {
1031 cov_mark::check!(expected_type_match_arm_with_leading_char);
1032 check_expected_type_and_name(
1039 expect![[r#"ty: E, name: ?"#]],
1044 fn expected_type_if_let_without_leading_char() {
1045 cov_mark::check!(expected_type_if_let_without_leading_char);
1046 check_expected_type_and_name(
1048 enum Foo { Bar, Baz, Quux }
1055 expect![[r#"ty: Foo, name: ?"#]],
1060 fn expected_type_if_let_with_leading_char() {
1061 cov_mark::check!(expected_type_if_let_with_leading_char);
1062 check_expected_type_and_name(
1064 enum Foo { Bar, Baz, Quux }
1071 expect![[r#"ty: Foo, name: ?"#]],
1076 fn expected_type_fn_ret_without_leading_char() {
1077 cov_mark::check!(expected_type_fn_ret_without_leading_char);
1078 check_expected_type_and_name(
1084 expect![[r#"ty: u32, name: ?"#]],
1089 fn expected_type_fn_ret_with_leading_char() {
1090 cov_mark::check!(expected_type_fn_ret_with_leading_char);
1091 check_expected_type_and_name(
1097 expect![[r#"ty: u32, name: ?"#]],
1102 fn expected_type_fn_ret_fn_ref_fully_typed() {
1103 check_expected_type_and_name(
1109 expect![[r#"ty: u32, name: ?"#]],
1114 fn expected_type_closure_param_return() {
1115 // FIXME: make this work with `|| $0`
1116 check_expected_type_and_name(
1123 fn bar(f: impl FnOnce() -> u32) {}
1125 expect![[r#"ty: u32, name: ?"#]],
1130 fn expected_type_generic_function() {
1131 check_expected_type_and_name(
1139 expect![[r#"ty: u32, name: t"#]],
1144 fn expected_type_generic_method() {
1145 check_expected_type_and_name(
1153 fn bar(self, t: T) {}
1156 expect![[r#"ty: u32, name: t"#]],
1161 fn expected_type_functional_update() {
1162 cov_mark::check!(expected_type_struct_func_update);
1163 check_expected_type_and_name(
1165 struct Foo { field: u32 }
1172 expect![[r#"ty: Foo, name: ?"#]],