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, HasName, NameOrNameRef},
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>,
61 pub(super) has_type_ascription: bool,
65 pub(super) enum LifetimeContext {
66 LifetimeParam(Option<ast::LifetimeParam>),
72 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
73 pub(crate) enum CallKind {
79 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
80 pub(crate) enum ParamKind {
84 /// `CompletionContext` is created early during completion to figure out, where
85 /// exactly is the cursor, syntax-wise.
87 pub(crate) struct CompletionContext<'a> {
88 pub(super) sema: Semantics<'a, RootDatabase>,
89 pub(super) scope: SemanticsScope<'a>,
90 pub(super) db: &'a RootDatabase,
91 pub(super) config: &'a CompletionConfig,
92 pub(super) position: FilePosition,
93 /// The token before the cursor, in the original file.
94 pub(super) original_token: SyntaxToken,
95 /// The token before the cursor, in the macro-expanded file.
96 pub(super) token: SyntaxToken,
97 /// The crate of the current file.
98 pub(super) krate: Option<hir::Crate>,
99 pub(super) expected_name: Option<NameOrNameRef>,
100 pub(super) expected_type: Option<Type>,
102 /// The parent function of the cursor position if it exists.
103 pub(super) function_def: Option<ast::Fn>,
104 /// The parent impl of the cursor position if it exists.
105 pub(super) impl_def: Option<ast::Impl>,
106 /// The NameLike under the cursor in the original file if it exists.
107 pub(super) name_syntax: Option<ast::NameLike>,
108 pub(super) incomplete_let: bool,
110 pub(super) completion_location: Option<ImmediateLocation>,
111 pub(super) prev_sibling: Option<ImmediatePrevSibling>,
112 pub(super) attribute_under_caret: Option<ast::Attr>,
113 pub(super) previous_token: Option<SyntaxToken>,
115 pub(super) lifetime_ctx: Option<LifetimeContext>,
116 pub(super) pattern_ctx: Option<PatternContext>,
117 pub(super) path_context: Option<PathCompletionContext>,
118 pub(super) locals: Vec<(Name, Local)>,
120 no_completion_required: bool,
123 impl<'a> CompletionContext<'a> {
124 /// Checks whether completions in that particular case don't make much sense.
126 /// - `fn $0` -- we expect function name, it's unlikely that "hint" will be helpful.
127 /// Exception for this case is `impl Trait for Foo`, where we would like to hint trait method names.
128 /// - `for _ i$0` -- obviously, it'll be "in" keyword.
129 pub(crate) fn no_completion_required(&self) -> bool {
130 self.no_completion_required
133 /// The range of the identifier that is being completed.
134 pub(crate) fn source_range(&self) -> TextRange {
135 // check kind of macro-expanded token, but use range of original token
136 let kind = self.token.kind();
137 if kind == IDENT || kind == LIFETIME_IDENT || kind == UNDERSCORE || kind.is_keyword() {
138 self.original_token.text_range()
139 } else if kind == CHAR {
140 // assume we are completing a lifetime but the user has only typed the '
141 cov_mark::hit!(completes_if_lifetime_without_idents);
142 TextRange::at(self.original_token.text_range().start(), TextSize::from(1))
144 TextRange::empty(self.position.offset)
148 pub(crate) fn previous_token_is(&self, kind: SyntaxKind) -> bool {
149 self.previous_token.as_ref().map_or(false, |tok| tok.kind() == kind)
152 pub(crate) fn dot_receiver(&self) -> Option<&ast::Expr> {
153 match &self.completion_location {
155 ImmediateLocation::MethodCall { receiver, .. }
156 | ImmediateLocation::FieldAccess { receiver, .. },
157 ) => receiver.as_ref(),
162 pub(crate) fn has_dot_receiver(&self) -> bool {
164 &self.completion_location,
165 Some(ImmediateLocation::FieldAccess { receiver, .. } | ImmediateLocation::MethodCall { receiver,.. })
166 if receiver.is_some()
170 pub(crate) fn expects_assoc_item(&self) -> bool {
171 matches!(self.completion_location, Some(ImmediateLocation::Trait | ImmediateLocation::Impl))
174 pub(crate) fn expects_non_trait_assoc_item(&self) -> bool {
175 matches!(self.completion_location, Some(ImmediateLocation::Impl))
178 pub(crate) fn expects_item(&self) -> bool {
179 matches!(self.completion_location, Some(ImmediateLocation::ItemList))
182 pub(crate) fn expects_generic_arg(&self) -> bool {
183 matches!(self.completion_location, Some(ImmediateLocation::GenericArgList(_)))
186 pub(crate) fn has_block_expr_parent(&self) -> bool {
187 matches!(self.completion_location, Some(ImmediateLocation::StmtList))
190 pub(crate) fn expects_ident_pat_or_ref_expr(&self) -> bool {
192 self.completion_location,
193 Some(ImmediateLocation::IdentPat | ImmediateLocation::RefExpr)
197 pub(crate) fn expect_field(&self) -> bool {
199 self.completion_location,
200 Some(ImmediateLocation::RecordField | ImmediateLocation::TupleField)
204 pub(crate) fn in_use_tree(&self) -> bool {
206 self.completion_location,
207 Some(ImmediateLocation::Use | ImmediateLocation::UseTree)
211 pub(crate) fn has_impl_or_trait_prev_sibling(&self) -> bool {
214 Some(ImmediatePrevSibling::ImplDefType | ImmediatePrevSibling::TraitDefName)
218 pub(crate) fn has_impl_prev_sibling(&self) -> bool {
219 matches!(self.prev_sibling, Some(ImmediatePrevSibling::ImplDefType))
222 pub(crate) fn has_visibility_prev_sibling(&self) -> bool {
223 matches!(self.prev_sibling, Some(ImmediatePrevSibling::Visibility))
226 pub(crate) fn after_if(&self) -> bool {
227 matches!(self.prev_sibling, Some(ImmediatePrevSibling::IfExpr))
230 pub(crate) fn is_path_disallowed(&self) -> bool {
231 self.attribute_under_caret.is_some()
232 || self.previous_token_is(T![unsafe])
235 Some(ImmediatePrevSibling::Attribute | ImmediatePrevSibling::Visibility)
238 self.completion_location,
240 ImmediateLocation::Attribute(_)
241 | ImmediateLocation::ModDeclaration(_)
242 | ImmediateLocation::RecordPat(_)
243 | ImmediateLocation::RecordExpr(_)
244 | ImmediateLocation::Rename
249 pub(crate) fn expects_expression(&self) -> bool {
250 matches!(self.path_context, Some(PathCompletionContext { kind: Some(PathKind::Expr), .. }))
253 pub(crate) fn expects_type(&self) -> bool {
254 matches!(self.path_context, Some(PathCompletionContext { kind: Some(PathKind::Type), .. }))
257 pub(crate) fn path_call_kind(&self) -> Option<CallKind> {
258 self.path_context.as_ref().and_then(|it| it.call_kind)
261 pub(crate) fn is_trivial_path(&self) -> bool {
262 matches!(self.path_context, Some(PathCompletionContext { is_trivial_path: true, .. }))
265 pub(crate) fn is_non_trivial_path(&self) -> bool {
266 matches!(self.path_context, Some(PathCompletionContext { is_trivial_path: false, .. }))
269 pub(crate) fn path_qual(&self) -> Option<&ast::Path> {
270 self.path_context.as_ref().and_then(|it| it.qualifier.as_ref())
273 /// Checks if an item is visible and not `doc(hidden)` at the completion site.
274 pub(crate) fn is_visible<I>(&self, item: &I) -> bool
276 I: hir::HasVisibility + hir::HasAttrs + hir::HasCrate + Copy,
278 self.is_visible_impl(&item.visibility(self.db), &item.attrs(self.db), item.krate(self.db))
281 pub(crate) fn is_scope_def_hidden(&self, scope_def: &ScopeDef) -> bool {
282 if let (Some(attrs), Some(krate)) = (scope_def.attrs(self.db), scope_def.krate(self.db)) {
283 return self.is_doc_hidden(&attrs, krate);
289 /// Check if an item is `#[doc(hidden)]`.
290 pub(crate) fn is_item_hidden(&self, item: &hir::ItemInNs) -> bool {
291 let attrs = item.attrs(self.db);
292 let krate = item.krate(self.db);
293 match (attrs, krate) {
294 (Some(attrs), Some(krate)) => self.is_doc_hidden(&attrs, krate),
299 pub(crate) fn is_immediately_after_macro_bang(&self) -> bool {
300 self.token.kind() == BANG && self.token.parent().map_or(false, |it| it.kind() == MACRO_CALL)
303 /// A version of [`SemanticsScope::process_all_names`] that filters out `#[doc(hidden)]` items.
304 pub(crate) fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
305 self.scope.process_all_names(&mut |name, def| {
306 if self.is_scope_def_hidden(&def) {
316 vis: &hir::Visibility,
318 defining_crate: hir::Crate,
320 let module = match self.scope.module() {
322 None => return false,
324 if !vis.is_visible_from(self.db, module.into()) {
325 // If the definition location is editable, also show private items
326 let root_file = defining_crate.root_file(self.db);
327 let source_root_id = self.db.file_source_root(root_file);
328 let is_editable = !self.db.source_root(source_root_id).is_library;
332 !self.is_doc_hidden(attrs, defining_crate)
335 fn is_doc_hidden(&self, attrs: &hir::Attrs, defining_crate: hir::Crate) -> bool {
336 let krate = match self.krate {
340 if krate != defining_crate && attrs.has_doc_hidden() {
341 // `doc(hidden)` items are only completed within the defining crate.
349 // CompletionContext construction
350 impl<'a> CompletionContext<'a> {
352 db: &'a RootDatabase,
353 position: FilePosition,
354 config: &'a CompletionConfig,
355 ) -> Option<CompletionContext<'a>> {
356 let sema = Semantics::new(db);
358 let original_file = sema.parse(position.file_id);
360 // Insert a fake ident to get a valid parse tree. We will use this file
361 // to determine context, though the original_file will be used for
362 // actual completion.
363 let file_with_fake_ident = {
364 let parse = db.parse(position.file_id);
365 let edit = Indel::insert(position.offset, "intellijRulezz".to_string());
366 parse.reparse(&edit).tree()
368 let fake_ident_token =
369 file_with_fake_ident.syntax().token_at_offset(position.offset).right_biased().unwrap();
372 original_file.syntax().token_at_offset(position.offset).left_biased()?;
373 let token = sema.descend_into_macros_single(original_token.clone());
374 let scope = sema.scope_at_offset(&token, position.offset);
375 let krate = scope.krate();
376 let mut locals = vec![];
377 scope.process_all_names(&mut |name, scope| {
378 if let ScopeDef::Local(local) = scope {
379 locals.push((name, local));
382 let mut ctx = CompletionContext {
398 completion_location: None,
400 attribute_under_caret: None,
401 previous_token: None,
404 incomplete_let: false,
405 no_completion_required: false,
408 original_file.syntax().clone(),
409 file_with_fake_ident.syntax().clone(),
416 /// Do the attribute expansion at the current cursor position for both original file and fake file
417 /// as long as possible. As soon as one of the two expansions fail we stop to stay in sync.
420 mut original_file: SyntaxNode,
421 mut speculative_file: SyntaxNode,
422 mut offset: TextSize,
423 mut fake_ident_token: SyntaxToken,
427 if let (Some(actual_item), Some(item_with_fake_ident)) = (
428 find_node_at_offset::<ast::Item>(&original_file, offset),
429 find_node_at_offset::<ast::Item>(&speculative_file, offset),
432 self.sema.expand_attr_macro(&actual_item),
433 self.sema.speculative_expand_attr_macro(
435 &item_with_fake_ident,
436 fake_ident_token.clone(),
439 (Some(actual_expansion), Some(speculative_expansion)) => {
440 let new_offset = speculative_expansion.1.text_range().start();
441 if new_offset > actual_expansion.text_range().end() {
444 original_file = actual_expansion;
445 speculative_file = speculative_expansion.0;
446 fake_ident_token = speculative_expansion.1;
455 // Expand fn-like macro calls
456 if let (Some(actual_macro_call), Some(macro_call_with_fake_ident)) = (
457 find_node_at_offset::<ast::MacroCall>(&original_file, offset),
458 find_node_at_offset::<ast::MacroCall>(&speculative_file, offset),
460 let mac_call_path0 = actual_macro_call.path().as_ref().map(|s| s.syntax().text());
462 macro_call_with_fake_ident.path().as_ref().map(|s| s.syntax().text());
463 if mac_call_path0 != mac_call_path1 {
466 let speculative_args = match macro_call_with_fake_ident.token_tree() {
471 if let (Some(actual_expansion), Some(speculative_expansion)) = (
472 self.sema.expand(&actual_macro_call),
473 self.sema.speculative_expand(
479 let new_offset = speculative_expansion.1.text_range().start();
480 if new_offset > actual_expansion.text_range().end() {
483 original_file = actual_expansion;
484 speculative_file = speculative_expansion.0;
485 fake_ident_token = speculative_expansion.1;
495 self.fill(&original_file, speculative_file, offset);
498 fn expected_type_and_name(&self) -> (Option<Type>, Option<NameOrNameRef>) {
499 let mut node = match self.token.parent() {
501 None => return (None, None),
506 ast::LetStmt(it) => {
507 cov_mark::hit!(expected_type_let_with_leading_char);
508 cov_mark::hit!(expected_type_let_without_leading_char);
510 .and_then(|pat| self.sema.type_of_pat(&pat))
511 .or_else(|| it.initializer().and_then(|it| self.sema.type_of_expr(&it)))
512 .map(TypeInfo::original);
513 let name = match it.pat() {
514 Some(ast::Pat::IdentPat(ident)) => ident.name().map(NameOrNameRef::Name),
515 Some(_) | None => None,
520 ast::ArgList(_it) => {
521 cov_mark::hit!(expected_type_fn_param);
522 ActiveParameter::at_token(
526 let name = ap.ident().map(NameOrNameRef::Name);
527 let ty = if has_ref(&self.token) {
528 cov_mark::hit!(expected_type_fn_param_ref);
535 .unwrap_or((None, None))
537 ast::RecordExprFieldList(it) => {
538 // wouldn't try {} be nice...
540 if self.token.kind() == T![..]
541 || self.token.prev_token().map(|t| t.kind()) == Some(T![..])
543 cov_mark::hit!(expected_type_struct_func_update);
544 let record_expr = it.syntax().parent().and_then(ast::RecordExpr::cast)?;
545 let ty = self.sema.type_of_expr(&record_expr.into())?;
551 cov_mark::hit!(expected_type_struct_field_without_leading_char);
552 let expr_field = self.token.prev_sibling_or_token()?
554 .and_then(ast::RecordExprField::cast)?;
555 let (_, _, ty) = self.sema.resolve_record_field(&expr_field)?;
558 expr_field.field_name().map(NameOrNameRef::NameRef),
561 })().unwrap_or((None, None))
563 ast::RecordExprField(it) => {
564 cov_mark::hit!(expected_type_struct_field_with_leading_char);
566 it.expr().as_ref().and_then(|e| self.sema.type_of_expr(e)).map(TypeInfo::original),
567 it.field_name().map(NameOrNameRef::NameRef),
570 ast::MatchExpr(it) => {
571 cov_mark::hit!(expected_type_match_arm_without_leading_char);
572 let ty = it.expr().and_then(|e| self.sema.type_of_expr(&e)).map(TypeInfo::original);
576 cov_mark::hit!(expected_type_if_let_without_leading_char);
577 let ty = it.condition()
578 .and_then(|cond| cond.expr())
579 .and_then(|e| self.sema.type_of_expr(&e))
580 .map(TypeInfo::original);
583 ast::IdentPat(it) => {
584 cov_mark::hit!(expected_type_if_let_with_leading_char);
585 cov_mark::hit!(expected_type_match_arm_with_leading_char);
586 let ty = self.sema.type_of_pat(&ast::Pat::from(it)).map(TypeInfo::original);
590 cov_mark::hit!(expected_type_fn_ret_with_leading_char);
591 cov_mark::hit!(expected_type_fn_ret_without_leading_char);
592 let def = self.sema.to_def(&it);
593 (def.map(|def| def.ret_type(self.db)), None)
595 ast::ClosureExpr(it) => {
596 let ty = self.sema.type_of_expr(&it.into());
597 ty.and_then(|ty| ty.original.as_callable(self.db))
598 .map(|c| (Some(c.return_type()), None))
599 .unwrap_or((None, None))
601 ast::Stmt(_it) => (None, None),
602 ast::Item(__) => (None, None),
604 match node.parent() {
609 None => (None, None),
619 original_file: &SyntaxNode,
620 file_with_fake_ident: SyntaxNode,
623 let fake_ident_token = file_with_fake_ident.token_at_offset(offset).right_biased().unwrap();
624 let syntax_element = NodeOrToken::Token(fake_ident_token);
625 self.previous_token = previous_token(syntax_element.clone());
626 self.attribute_under_caret = syntax_element.ancestors().find_map(ast::Attr::cast);
627 self.no_completion_required = {
628 let inside_impl_trait_block = inside_impl_trait_block(syntax_element.clone());
629 let fn_is_prev = self.previous_token_is(T![fn]);
630 let for_is_prev2 = for_is_prev2(syntax_element.clone());
631 (fn_is_prev && !inside_impl_trait_block) || for_is_prev2
634 self.incomplete_let =
635 syntax_element.ancestors().take(6).find_map(ast::LetStmt::cast).map_or(false, |it| {
636 it.syntax().text_range().end() == syntax_element.text_range().end()
639 let (expected_type, expected_name) = self.expected_type_and_name();
640 self.expected_type = expected_type;
641 self.expected_name = expected_name;
643 let name_like = match find_node_at_offset(&file_with_fake_ident, offset) {
647 self.completion_location =
648 determine_location(&self.sema, original_file, offset, &name_like);
649 self.prev_sibling = determine_prev_sibling(&name_like);
651 find_node_at_offset(original_file, name_like.syntax().text_range().start());
654 .token_ancestors_with_macros(self.token.clone())
655 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
656 .find_map(ast::Impl::cast);
657 self.function_def = self
659 .token_ancestors_with_macros(self.token.clone())
660 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
661 .find_map(ast::Fn::cast);
663 ast::NameLike::Lifetime(lifetime) => {
665 Self::classify_lifetime(&self.sema, original_file, lifetime, offset);
667 ast::NameLike::NameRef(name_ref) => {
668 self.path_context = Self::classify_name_ref(&self.sema, original_file, name_ref);
670 ast::NameLike::Name(name) => {
671 self.pattern_ctx = Self::classify_name(&self.sema, name);
676 fn classify_lifetime(
677 sema: &Semantics<RootDatabase>,
678 original_file: &SyntaxNode,
679 lifetime: ast::Lifetime,
681 ) -> Option<LifetimeContext> {
682 let parent = lifetime.syntax().parent()?;
683 if parent.kind() == ERROR {
689 ast::LifetimeParam(_it) => LifetimeContext::LifetimeParam(sema.find_node_at_offset_with_macros(original_file, offset)),
690 ast::BreakExpr(_it) => LifetimeContext::LabelRef,
691 ast::ContinueExpr(_it) => LifetimeContext::LabelRef,
692 ast::Label(_it) => LifetimeContext::LabelDef,
693 _ => LifetimeContext::Lifetime,
698 fn classify_name(_sema: &Semantics<RootDatabase>, name: ast::Name) -> Option<PatternContext> {
699 let bind_pat = name.syntax().parent().and_then(ast::IdentPat::cast)?;
700 let is_name_in_field_pat = bind_pat
703 .and_then(ast::RecordPatField::cast)
704 .map_or(false, |pat_field| pat_field.name_ref().is_none());
705 if is_name_in_field_pat {
708 if !bind_pat.is_simple_ident() {
711 let mut is_param = None;
712 let (refutability, has_type_ascription) = bind_pat
715 .skip_while(|it| ast::Pat::can_cast(it.kind()))
717 .map_or((PatternRefutability::Irrefutable, false), |node| {
718 let refutability = match_ast! {
720 ast::LetStmt(let_) => return (PatternRefutability::Irrefutable, let_.ty().is_some()),
721 ast::Param(param) => {
722 let is_closure_param = param
726 .and_then(ast::ClosureExpr::cast)
728 is_param = Some(if is_closure_param {
733 return (PatternRefutability::Irrefutable, param.ty().is_some())
735 ast::MatchArm(__) => PatternRefutability::Refutable,
736 ast::Condition(__) => PatternRefutability::Refutable,
737 ast::ForExpr(__) => PatternRefutability::Irrefutable,
738 _ => PatternRefutability::Irrefutable,
741 (refutability, false)
743 Some(PatternContext { refutability, is_param, has_type_ascription })
746 fn classify_name_ref(
747 _sema: &Semantics<RootDatabase>,
748 original_file: &SyntaxNode,
749 name_ref: ast::NameRef,
750 ) -> Option<PathCompletionContext> {
751 let parent = name_ref.syntax().parent()?;
752 let segment = ast::PathSegment::cast(parent)?;
754 let mut path_ctx = PathCompletionContext {
756 is_trivial_path: false,
758 has_type_args: false,
761 use_tree_parent: false,
764 path_ctx.in_loop_body = is_in_loop_body(name_ref.syntax());
765 let path = segment.parent_path();
767 if let Some(p) = path.syntax().parent() {
768 path_ctx.call_kind = match_ast! {
770 ast::PathExpr(it) => it.syntax().parent().and_then(ast::CallExpr::cast).map(|_| CallKind::Expr),
771 ast::MacroCall(it) => it.excl_token().and(Some(CallKind::Mac)),
772 ast::TupleStructPat(_it) => Some(CallKind::Pat),
778 if let Some(parent) = path.syntax().parent() {
779 path_ctx.kind = match_ast! {
781 ast::PathType(_it) => Some(PathKind::Type),
782 ast::PathExpr(_it) => Some(PathKind::Expr),
787 path_ctx.has_type_args = segment.generic_arg_list().is_some();
789 if let Some((path, use_tree_parent)) = path_or_use_tree_qualifier(&path) {
790 path_ctx.use_tree_parent = use_tree_parent;
791 path_ctx.qualifier = path
794 find_node_with_range::<ast::PathSegment>(
796 it.syntax().text_range(),
799 .map(|it| it.parent_path());
800 return Some(path_ctx);
803 if let Some(segment) = path.segment() {
804 if segment.coloncolon_token().is_some() {
805 return Some(path_ctx);
809 path_ctx.is_trivial_path = true;
811 // Find either enclosing expr statement (thing with `;`) or a
812 // block. If block, check that we are the last expr.
813 path_ctx.can_be_stmt = name_ref
817 if let Some(stmt) = ast::ExprStmt::cast(node.clone()) {
818 return Some(stmt.syntax().text_range() == name_ref.syntax().text_range());
820 if let Some(stmt_list) = ast::StmtList::cast(node) {
822 stmt_list.tail_expr().map(|e| e.syntax().text_range())
823 == Some(name_ref.syntax().text_range()),
833 fn find_node_with_range<N: AstNode>(syntax: &SyntaxNode, range: TextRange) -> Option<N> {
834 syntax.covering_element(range).ancestors().find_map(N::cast)
837 fn path_or_use_tree_qualifier(path: &ast::Path) -> Option<(ast::Path, bool)> {
838 if let Some(qual) = path.qualifier() {
839 return Some((qual, false));
841 let use_tree_list = path.syntax().ancestors().find_map(ast::UseTreeList::cast)?;
842 let use_tree = use_tree_list.syntax().parent().and_then(ast::UseTree::cast)?;
843 use_tree.path().zip(Some(true))
846 fn has_ref(token: &SyntaxToken) -> bool {
847 let mut token = token.clone();
848 for skip in [WHITESPACE, IDENT, T![mut]] {
849 if token.kind() == skip {
850 token = match token.prev_token() {
852 None => return false,
856 token.kind() == T![&]
861 use expect_test::{expect, Expect};
864 use crate::tests::{position, TEST_CONFIG};
866 use super::CompletionContext;
868 fn check_expected_type_and_name(ra_fixture: &str, expect: Expect) {
869 let (db, pos) = position(ra_fixture);
870 let config = TEST_CONFIG;
871 let completion_context = CompletionContext::new(&db, pos, &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: ?"#]],