1 //! See `CompletionContext` structure.
3 use base_db::SourceDatabaseExt;
4 use hir::{Local, Name, ScopeDef, Semantics, SemanticsScope, Type, TypeInfo};
6 active_parameter::ActiveParameter,
7 base_db::{FilePosition, SourceDatabase},
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_variant(&self) -> bool {
175 matches!(self.completion_location, Some(ImmediateLocation::Variant))
178 pub(crate) fn expects_non_trait_assoc_item(&self) -> bool {
179 matches!(self.completion_location, Some(ImmediateLocation::Impl))
182 pub(crate) fn expects_item(&self) -> bool {
183 matches!(self.completion_location, Some(ImmediateLocation::ItemList))
186 pub(crate) fn expects_generic_arg(&self) -> bool {
187 matches!(self.completion_location, Some(ImmediateLocation::GenericArgList(_)))
190 pub(crate) fn has_block_expr_parent(&self) -> bool {
191 matches!(self.completion_location, Some(ImmediateLocation::StmtList))
194 pub(crate) fn expects_ident_pat_or_ref_expr(&self) -> bool {
196 self.completion_location,
197 Some(ImmediateLocation::IdentPat | ImmediateLocation::RefExpr)
201 pub(crate) fn expect_field(&self) -> bool {
203 self.completion_location,
204 Some(ImmediateLocation::RecordField | ImmediateLocation::TupleField)
208 pub(crate) fn in_use_tree(&self) -> bool {
210 self.completion_location,
211 Some(ImmediateLocation::Use | ImmediateLocation::UseTree)
215 pub(crate) fn has_impl_or_trait_prev_sibling(&self) -> bool {
218 Some(ImmediatePrevSibling::ImplDefType | ImmediatePrevSibling::TraitDefName)
222 pub(crate) fn has_impl_prev_sibling(&self) -> bool {
223 matches!(self.prev_sibling, Some(ImmediatePrevSibling::ImplDefType))
226 pub(crate) fn has_visibility_prev_sibling(&self) -> bool {
227 matches!(self.prev_sibling, Some(ImmediatePrevSibling::Visibility))
230 pub(crate) fn after_if(&self) -> bool {
231 matches!(self.prev_sibling, Some(ImmediatePrevSibling::IfExpr))
234 pub(crate) fn is_path_disallowed(&self) -> bool {
235 self.attribute_under_caret.is_some()
236 || self.previous_token_is(T![unsafe])
239 Some(ImmediatePrevSibling::Attribute | ImmediatePrevSibling::Visibility)
242 self.completion_location,
244 ImmediateLocation::Attribute(_)
245 | ImmediateLocation::ModDeclaration(_)
246 | ImmediateLocation::RecordPat(_)
247 | ImmediateLocation::RecordExpr(_)
248 | ImmediateLocation::Rename
253 pub(crate) fn expects_expression(&self) -> bool {
254 matches!(self.path_context, Some(PathCompletionContext { kind: Some(PathKind::Expr), .. }))
257 pub(crate) fn expects_type(&self) -> bool {
258 matches!(self.path_context, Some(PathCompletionContext { kind: Some(PathKind::Type), .. }))
261 pub(crate) fn path_call_kind(&self) -> Option<CallKind> {
262 self.path_context.as_ref().and_then(|it| it.call_kind)
265 pub(crate) fn is_trivial_path(&self) -> bool {
266 matches!(self.path_context, Some(PathCompletionContext { is_trivial_path: true, .. }))
269 pub(crate) fn is_non_trivial_path(&self) -> bool {
270 matches!(self.path_context, Some(PathCompletionContext { is_trivial_path: false, .. }))
273 pub(crate) fn path_qual(&self) -> Option<&ast::Path> {
274 self.path_context.as_ref().and_then(|it| it.qualifier.as_ref())
277 /// Checks if an item is visible and not `doc(hidden)` at the completion site.
278 pub(crate) fn is_visible<I>(&self, item: &I) -> bool
280 I: hir::HasVisibility + hir::HasAttrs + hir::HasCrate + Copy,
282 self.is_visible_impl(&item.visibility(self.db), &item.attrs(self.db), item.krate(self.db))
285 pub(crate) fn is_scope_def_hidden(&self, scope_def: &ScopeDef) -> bool {
286 if let (Some(attrs), Some(krate)) = (scope_def.attrs(self.db), scope_def.krate(self.db)) {
287 return self.is_doc_hidden(&attrs, krate);
293 /// Check if an item is `#[doc(hidden)]`.
294 pub(crate) fn is_item_hidden(&self, item: &hir::ItemInNs) -> bool {
295 let attrs = item.attrs(self.db);
296 let krate = item.krate(self.db);
297 match (attrs, krate) {
298 (Some(attrs), Some(krate)) => self.is_doc_hidden(&attrs, krate),
303 pub(crate) fn is_immediately_after_macro_bang(&self) -> bool {
304 self.token.kind() == BANG && self.token.parent().map_or(false, |it| it.kind() == MACRO_CALL)
307 /// A version of [`SemanticsScope::process_all_names`] that filters out `#[doc(hidden)]` items.
308 pub(crate) fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
309 self.scope.process_all_names(&mut |name, def| {
310 if self.is_scope_def_hidden(&def) {
320 vis: &hir::Visibility,
322 defining_crate: hir::Crate,
324 let module = match self.scope.module() {
326 None => return false,
328 if !vis.is_visible_from(self.db, module.into()) {
329 // If the definition location is editable, also show private items
330 let root_file = defining_crate.root_file(self.db);
331 let source_root_id = self.db.file_source_root(root_file);
332 let is_editable = !self.db.source_root(source_root_id).is_library;
336 !self.is_doc_hidden(attrs, defining_crate)
339 fn is_doc_hidden(&self, attrs: &hir::Attrs, defining_crate: hir::Crate) -> bool {
340 let krate = match self.krate {
344 if krate != defining_crate && attrs.has_doc_hidden() {
345 // `doc(hidden)` items are only completed within the defining crate.
353 // CompletionContext construction
354 impl<'a> CompletionContext<'a> {
356 db: &'a RootDatabase,
357 position @ FilePosition { file_id, offset }: FilePosition,
358 config: &'a CompletionConfig,
359 ) -> Option<CompletionContext<'a>> {
360 let _p = profile::span("CompletionContext::new");
361 let sema = Semantics::new(db);
363 let original_file = sema.parse(file_id);
365 // Insert a fake ident to get a valid parse tree. We will use this file
366 // to determine context, though the original_file will be used for
367 // actual completion.
368 let file_with_fake_ident = {
369 let parse = db.parse(file_id);
370 let edit = Indel::insert(offset, "intellijRulezz".to_string());
371 parse.reparse(&edit).tree()
373 let fake_ident_token =
374 file_with_fake_ident.syntax().token_at_offset(offset).right_biased().unwrap();
376 let original_token = original_file.syntax().token_at_offset(offset).left_biased()?;
377 let token = sema.descend_into_macros_single(original_token.clone());
378 let scope = sema.scope_at_offset(&token, offset);
379 let krate = scope.krate();
380 let mut locals = vec![];
381 scope.process_all_names(&mut |name, scope| {
382 if let ScopeDef::Local(local) = scope {
383 locals.push((name, local));
386 let mut ctx = CompletionContext {
402 completion_location: None,
404 attribute_under_caret: None,
405 previous_token: None,
408 incomplete_let: false,
409 no_completion_required: false,
412 original_file.syntax().clone(),
413 file_with_fake_ident.syntax().clone(),
420 /// Do the attribute expansion at the current cursor position for both original file and fake file
421 /// as long as possible. As soon as one of the two expansions fail we stop to stay in sync.
424 mut original_file: SyntaxNode,
425 mut speculative_file: SyntaxNode,
426 mut offset: TextSize,
427 mut fake_ident_token: SyntaxToken,
431 if let (Some(actual_item), Some(item_with_fake_ident)) = (
432 find_node_at_offset::<ast::Item>(&original_file, offset),
433 find_node_at_offset::<ast::Item>(&speculative_file, offset),
436 self.sema.expand_attr_macro(&actual_item),
437 self.sema.speculative_expand_attr_macro(
439 &item_with_fake_ident,
440 fake_ident_token.clone(),
443 (Some(actual_expansion), Some(speculative_expansion)) => {
444 let new_offset = speculative_expansion.1.text_range().start();
445 if new_offset > actual_expansion.text_range().end() {
448 original_file = actual_expansion;
449 speculative_file = speculative_expansion.0;
450 fake_ident_token = speculative_expansion.1;
459 // Expand fn-like macro calls
460 if let (Some(actual_macro_call), Some(macro_call_with_fake_ident)) = (
461 find_node_at_offset::<ast::MacroCall>(&original_file, offset),
462 find_node_at_offset::<ast::MacroCall>(&speculative_file, offset),
464 let mac_call_path0 = actual_macro_call.path().as_ref().map(|s| s.syntax().text());
466 macro_call_with_fake_ident.path().as_ref().map(|s| s.syntax().text());
467 if mac_call_path0 != mac_call_path1 {
470 let speculative_args = match macro_call_with_fake_ident.token_tree() {
475 if let (Some(actual_expansion), Some(speculative_expansion)) = (
476 self.sema.expand(&actual_macro_call),
477 self.sema.speculative_expand(
483 let new_offset = speculative_expansion.1.text_range().start();
484 if new_offset > actual_expansion.text_range().end() {
487 original_file = actual_expansion;
488 speculative_file = speculative_expansion.0;
489 fake_ident_token = speculative_expansion.1;
499 self.fill(&original_file, speculative_file, offset);
502 fn expected_type_and_name(&self) -> (Option<Type>, Option<NameOrNameRef>) {
503 let mut node = match self.token.parent() {
505 None => return (None, None),
510 ast::LetStmt(it) => {
511 cov_mark::hit!(expected_type_let_with_leading_char);
512 cov_mark::hit!(expected_type_let_without_leading_char);
514 .and_then(|pat| self.sema.type_of_pat(&pat))
515 .or_else(|| it.initializer().and_then(|it| self.sema.type_of_expr(&it)))
516 .map(TypeInfo::original);
517 let name = match it.pat() {
518 Some(ast::Pat::IdentPat(ident)) => ident.name().map(NameOrNameRef::Name),
519 Some(_) | None => None,
524 ast::ArgList(_it) => {
525 cov_mark::hit!(expected_type_fn_param);
526 ActiveParameter::at_token(
530 let name = ap.ident().map(NameOrNameRef::Name);
531 let ty = if has_ref(&self.token) {
532 cov_mark::hit!(expected_type_fn_param_ref);
539 .unwrap_or((None, None))
541 ast::RecordExprFieldList(it) => {
542 // wouldn't try {} be nice...
544 if self.token.kind() == T![..]
545 || self.token.prev_token().map(|t| t.kind()) == Some(T![..])
547 cov_mark::hit!(expected_type_struct_func_update);
548 let record_expr = it.syntax().parent().and_then(ast::RecordExpr::cast)?;
549 let ty = self.sema.type_of_expr(&record_expr.into())?;
555 cov_mark::hit!(expected_type_struct_field_without_leading_char);
556 let expr_field = self.token.prev_sibling_or_token()?
558 .and_then(ast::RecordExprField::cast)?;
559 let (_, _, ty) = self.sema.resolve_record_field(&expr_field)?;
562 expr_field.field_name().map(NameOrNameRef::NameRef),
565 })().unwrap_or((None, None))
567 ast::RecordExprField(it) => {
568 cov_mark::hit!(expected_type_struct_field_with_leading_char);
570 it.expr().as_ref().and_then(|e| self.sema.type_of_expr(e)).map(TypeInfo::original),
571 it.field_name().map(NameOrNameRef::NameRef),
574 ast::MatchExpr(it) => {
575 cov_mark::hit!(expected_type_match_arm_without_leading_char);
576 let ty = it.expr().and_then(|e| self.sema.type_of_expr(&e)).map(TypeInfo::original);
580 cov_mark::hit!(expected_type_if_let_without_leading_char);
581 let ty = it.condition()
582 .and_then(|cond| cond.expr())
583 .and_then(|e| self.sema.type_of_expr(&e))
584 .map(TypeInfo::original);
587 ast::IdentPat(it) => {
588 cov_mark::hit!(expected_type_if_let_with_leading_char);
589 cov_mark::hit!(expected_type_match_arm_with_leading_char);
590 let ty = self.sema.type_of_pat(&ast::Pat::from(it)).map(TypeInfo::original);
594 cov_mark::hit!(expected_type_fn_ret_with_leading_char);
595 cov_mark::hit!(expected_type_fn_ret_without_leading_char);
596 let def = self.sema.to_def(&it);
597 (def.map(|def| def.ret_type(self.db)), None)
599 ast::ClosureExpr(it) => {
600 let ty = self.sema.type_of_expr(&it.into());
601 ty.and_then(|ty| ty.original.as_callable(self.db))
602 .map(|c| (Some(c.return_type()), None))
603 .unwrap_or((None, None))
605 ast::ParamList(__) => (None, None),
606 ast::Stmt(__) => (None, None),
607 ast::Item(__) => (None, None),
609 match node.parent() {
614 None => (None, None),
624 original_file: &SyntaxNode,
625 file_with_fake_ident: SyntaxNode,
628 let fake_ident_token = file_with_fake_ident.token_at_offset(offset).right_biased().unwrap();
629 let syntax_element = NodeOrToken::Token(fake_ident_token);
630 self.previous_token = previous_token(syntax_element.clone());
631 self.attribute_under_caret = syntax_element.ancestors().find_map(ast::Attr::cast);
632 self.no_completion_required = {
633 let inside_impl_trait_block = inside_impl_trait_block(syntax_element.clone());
634 let fn_is_prev = self.previous_token_is(T![fn]);
635 let for_is_prev2 = for_is_prev2(syntax_element.clone());
636 (fn_is_prev && !inside_impl_trait_block) || for_is_prev2
639 self.incomplete_let =
640 syntax_element.ancestors().take(6).find_map(ast::LetStmt::cast).map_or(false, |it| {
641 it.syntax().text_range().end() == syntax_element.text_range().end()
644 let (expected_type, expected_name) = self.expected_type_and_name();
645 self.expected_type = expected_type;
646 self.expected_name = expected_name;
648 let name_like = match find_node_at_offset(&file_with_fake_ident, offset) {
652 self.completion_location =
653 determine_location(&self.sema, original_file, offset, &name_like);
654 self.prev_sibling = determine_prev_sibling(&name_like);
656 find_node_at_offset(original_file, name_like.syntax().text_range().start());
659 .token_ancestors_with_macros(self.token.clone())
660 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
661 .find_map(ast::Impl::cast);
662 self.function_def = self
664 .token_ancestors_with_macros(self.token.clone())
665 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
666 .find_map(ast::Fn::cast);
668 ast::NameLike::Lifetime(lifetime) => {
670 Self::classify_lifetime(&self.sema, original_file, lifetime, offset);
672 ast::NameLike::NameRef(name_ref) => {
673 self.path_context = Self::classify_name_ref(&self.sema, original_file, name_ref);
675 ast::NameLike::Name(name) => {
676 self.pattern_ctx = Self::classify_name(&self.sema, name);
681 fn classify_lifetime(
682 sema: &Semantics<RootDatabase>,
683 original_file: &SyntaxNode,
684 lifetime: ast::Lifetime,
686 ) -> Option<LifetimeContext> {
687 let parent = lifetime.syntax().parent()?;
688 if parent.kind() == ERROR {
694 ast::LifetimeParam(_it) => LifetimeContext::LifetimeParam(sema.find_node_at_offset_with_macros(original_file, offset)),
695 ast::BreakExpr(_it) => LifetimeContext::LabelRef,
696 ast::ContinueExpr(_it) => LifetimeContext::LabelRef,
697 ast::Label(_it) => LifetimeContext::LabelDef,
698 _ => LifetimeContext::Lifetime,
703 fn classify_name(_sema: &Semantics<RootDatabase>, name: ast::Name) -> Option<PatternContext> {
704 let bind_pat = name.syntax().parent().and_then(ast::IdentPat::cast)?;
705 let is_name_in_field_pat = bind_pat
708 .and_then(ast::RecordPatField::cast)
709 .map_or(false, |pat_field| pat_field.name_ref().is_none());
710 if is_name_in_field_pat {
713 if !bind_pat.is_simple_ident() {
716 let mut is_param = None;
717 let (refutability, has_type_ascription) = bind_pat
720 .skip_while(|it| ast::Pat::can_cast(it.kind()))
722 .map_or((PatternRefutability::Irrefutable, false), |node| {
723 let refutability = match_ast! {
725 ast::LetStmt(let_) => return (PatternRefutability::Irrefutable, let_.ty().is_some()),
726 ast::Param(param) => {
727 let is_closure_param = param
731 .and_then(ast::ClosureExpr::cast)
733 is_param = Some(if is_closure_param {
738 return (PatternRefutability::Irrefutable, param.ty().is_some())
740 ast::MatchArm(__) => PatternRefutability::Refutable,
741 ast::Condition(__) => PatternRefutability::Refutable,
742 ast::ForExpr(__) => PatternRefutability::Irrefutable,
743 _ => PatternRefutability::Irrefutable,
746 (refutability, false)
748 Some(PatternContext { refutability, is_param, has_type_ascription })
751 fn classify_name_ref(
752 _sema: &Semantics<RootDatabase>,
753 original_file: &SyntaxNode,
754 name_ref: ast::NameRef,
755 ) -> Option<PathCompletionContext> {
756 let parent = name_ref.syntax().parent()?;
757 let segment = ast::PathSegment::cast(parent)?;
759 let mut path_ctx = PathCompletionContext {
761 is_trivial_path: false,
763 has_type_args: false,
766 use_tree_parent: false,
769 path_ctx.in_loop_body = is_in_loop_body(name_ref.syntax());
770 let path = segment.parent_path();
772 if let Some(p) = path.syntax().parent() {
773 path_ctx.call_kind = match_ast! {
775 ast::PathExpr(it) => it.syntax().parent().and_then(ast::CallExpr::cast).map(|_| CallKind::Expr),
776 ast::MacroCall(it) => it.excl_token().and(Some(CallKind::Mac)),
777 ast::TupleStructPat(_it) => Some(CallKind::Pat),
783 if let Some(parent) = path.syntax().parent() {
784 path_ctx.kind = match_ast! {
786 ast::PathType(_it) => Some(PathKind::Type),
787 ast::PathExpr(_it) => Some(PathKind::Expr),
792 path_ctx.has_type_args = segment.generic_arg_list().is_some();
794 if let Some((path, use_tree_parent)) = path_or_use_tree_qualifier(&path) {
795 path_ctx.use_tree_parent = use_tree_parent;
796 path_ctx.qualifier = path
799 find_node_with_range::<ast::PathSegment>(
801 it.syntax().text_range(),
804 .map(|it| it.parent_path());
805 return Some(path_ctx);
808 if let Some(segment) = path.segment() {
809 if segment.coloncolon_token().is_some() {
810 return Some(path_ctx);
814 path_ctx.is_trivial_path = true;
816 // Find either enclosing expr statement (thing with `;`) or a
817 // block. If block, check that we are the last expr.
818 path_ctx.can_be_stmt = name_ref
822 if let Some(stmt) = ast::ExprStmt::cast(node.clone()) {
823 return Some(stmt.syntax().text_range() == name_ref.syntax().text_range());
825 if let Some(stmt_list) = ast::StmtList::cast(node) {
827 stmt_list.tail_expr().map(|e| e.syntax().text_range())
828 == Some(name_ref.syntax().text_range()),
838 fn find_node_with_range<N: AstNode>(syntax: &SyntaxNode, range: TextRange) -> Option<N> {
839 syntax.covering_element(range).ancestors().find_map(N::cast)
842 fn path_or_use_tree_qualifier(path: &ast::Path) -> Option<(ast::Path, bool)> {
843 if let Some(qual) = path.qualifier() {
844 return Some((qual, false));
846 let use_tree_list = path.syntax().ancestors().find_map(ast::UseTreeList::cast)?;
847 let use_tree = use_tree_list.syntax().parent().and_then(ast::UseTree::cast)?;
848 use_tree.path().zip(Some(true))
851 fn has_ref(token: &SyntaxToken) -> bool {
852 let mut token = token.clone();
853 for skip in [WHITESPACE, IDENT, T![mut]] {
854 if token.kind() == skip {
855 token = match token.prev_token() {
857 None => return false,
861 token.kind() == T![&]
866 use expect_test::{expect, Expect};
869 use crate::tests::{position, TEST_CONFIG};
871 use super::CompletionContext;
873 fn check_expected_type_and_name(ra_fixture: &str, expect: Expect) {
874 let (db, pos) = position(ra_fixture);
875 let config = TEST_CONFIG;
876 let completion_context = CompletionContext::new(&db, pos, &config).unwrap();
878 let ty = completion_context
880 .map(|t| t.display_test(&db).to_string())
881 .unwrap_or("?".to_owned());
883 let name = completion_context
885 .map_or_else(|| "?".to_owned(), |name| name.to_string());
887 expect.assert_eq(&format!("ty: {}, name: {}", ty, name));
891 fn expected_type_let_without_leading_char() {
892 cov_mark::check!(expected_type_let_without_leading_char);
893 check_expected_type_and_name(
899 expect![[r#"ty: u32, name: x"#]],
904 fn expected_type_let_with_leading_char() {
905 cov_mark::check!(expected_type_let_with_leading_char);
906 check_expected_type_and_name(
912 expect![[r#"ty: u32, name: x"#]],
917 fn expected_type_let_pat() {
918 check_expected_type_and_name(
924 expect![[r#"ty: u32, name: ?"#]],
926 check_expected_type_and_name(
932 expect![[r#"ty: u32, name: ?"#]],
937 fn expected_type_fn_param() {
938 cov_mark::check!(expected_type_fn_param);
939 check_expected_type_and_name(
941 fn foo() { bar($0); }
944 expect![[r#"ty: u32, name: x"#]],
946 check_expected_type_and_name(
948 fn foo() { bar(c$0); }
951 expect![[r#"ty: u32, name: x"#]],
956 fn expected_type_fn_param_ref() {
957 cov_mark::check!(expected_type_fn_param_ref);
958 check_expected_type_and_name(
960 fn foo() { bar(&$0); }
963 expect![[r#"ty: u32, name: x"#]],
965 check_expected_type_and_name(
967 fn foo() { bar(&mut $0); }
968 fn bar(x: &mut u32) {}
970 expect![[r#"ty: u32, name: x"#]],
972 check_expected_type_and_name(
974 fn foo() { bar(&c$0); }
977 expect![[r#"ty: u32, name: x"#]],
982 fn expected_type_struct_field_without_leading_char() {
983 cov_mark::check!(expected_type_struct_field_without_leading_char);
984 check_expected_type_and_name(
986 struct Foo { a: u32 }
991 expect![[r#"ty: u32, name: a"#]],
996 fn expected_type_generic_struct_field() {
997 check_expected_type_and_name(
999 struct Foo<T> { a: T }
1000 fn foo() -> Foo<u32> {
1004 expect![[r#"ty: u32, name: a"#]],
1009 fn expected_type_struct_field_with_leading_char() {
1010 cov_mark::check!(expected_type_struct_field_with_leading_char);
1011 check_expected_type_and_name(
1013 struct Foo { a: u32 }
1018 expect![[r#"ty: u32, name: a"#]],
1023 fn expected_type_match_arm_without_leading_char() {
1024 cov_mark::check!(expected_type_match_arm_without_leading_char);
1025 check_expected_type_and_name(
1032 expect![[r#"ty: E, name: ?"#]],
1037 fn expected_type_match_arm_with_leading_char() {
1038 cov_mark::check!(expected_type_match_arm_with_leading_char);
1039 check_expected_type_and_name(
1046 expect![[r#"ty: E, name: ?"#]],
1051 fn expected_type_if_let_without_leading_char() {
1052 cov_mark::check!(expected_type_if_let_without_leading_char);
1053 check_expected_type_and_name(
1055 enum Foo { Bar, Baz, Quux }
1062 expect![[r#"ty: Foo, name: ?"#]],
1067 fn expected_type_if_let_with_leading_char() {
1068 cov_mark::check!(expected_type_if_let_with_leading_char);
1069 check_expected_type_and_name(
1071 enum Foo { Bar, Baz, Quux }
1078 expect![[r#"ty: Foo, name: ?"#]],
1083 fn expected_type_fn_ret_without_leading_char() {
1084 cov_mark::check!(expected_type_fn_ret_without_leading_char);
1085 check_expected_type_and_name(
1091 expect![[r#"ty: u32, name: ?"#]],
1096 fn expected_type_fn_ret_with_leading_char() {
1097 cov_mark::check!(expected_type_fn_ret_with_leading_char);
1098 check_expected_type_and_name(
1104 expect![[r#"ty: u32, name: ?"#]],
1109 fn expected_type_fn_ret_fn_ref_fully_typed() {
1110 check_expected_type_and_name(
1116 expect![[r#"ty: u32, name: ?"#]],
1121 fn expected_type_closure_param_return() {
1122 // FIXME: make this work with `|| $0`
1123 check_expected_type_and_name(
1130 fn bar(f: impl FnOnce() -> u32) {}
1132 expect![[r#"ty: u32, name: ?"#]],
1137 fn expected_type_generic_function() {
1138 check_expected_type_and_name(
1146 expect![[r#"ty: u32, name: t"#]],
1151 fn expected_type_generic_method() {
1152 check_expected_type_and_name(
1160 fn bar(self, t: T) {}
1163 expect![[r#"ty: u32, name: t"#]],
1168 fn expected_type_functional_update() {
1169 cov_mark::check!(expected_type_struct_func_update);
1170 check_expected_type_and_name(
1172 struct Foo { field: u32 }
1179 expect![[r#"ty: Foo, name: ?"#]],
1184 fn expected_type_param_pat() {
1185 check_expected_type_and_name(
1187 struct Foo { field: u32 }
1190 expect![[r#"ty: Foo, name: ?"#]],
1192 check_expected_type_and_name(
1194 struct Foo { field: u32 }
1197 // FIXME make this work, currently fails due to pattern recovery eating the `:`
1198 expect![[r#"ty: ?, name: ?"#]],