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},
12 algo::find_node_at_offset,
13 ast::{self, HasName, NameOrNameRef},
14 match_ast, AstNode, NodeOrToken,
15 SyntaxKind::{self, *},
16 SyntaxNode, SyntaxToken, TextRange, TextSize, T,
22 determine_location, determine_prev_sibling, for_is_prev2, inside_impl_trait_block,
23 is_in_loop_body, previous_token, ImmediateLocation, ImmediatePrevSibling,
28 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
29 pub(crate) enum PatternRefutability {
34 #[derive(Copy, Clone, Debug)]
35 pub(super) enum PathKind {
41 Vis { has_in_token: bool },
46 pub(crate) struct PathCompletionContext {
47 /// If this is a call with () already there
48 has_call_parens: bool,
49 /// A single-indent path, like `foo`. `::foo` should not be considered a trivial path.
50 pub(super) is_trivial_path: bool,
51 /// If not a trivial path, the prefix (qualifier).
52 pub(super) qualifier: Option<ast::Path>,
54 /// If not a trivial path, the suffix (parent).
55 pub(super) parent: Option<ast::Path>,
56 /// Whether the qualifier comes from a use tree parent or not
57 pub(super) use_tree_parent: bool,
58 pub(super) kind: Option<PathKind>,
59 /// Whether the path segment has type args or not.
60 pub(super) has_type_args: bool,
61 /// `true` if we are a statement or a last expr in the block.
62 pub(super) can_be_stmt: bool,
63 pub(super) in_loop_body: bool,
67 pub(super) struct PatternContext {
68 pub(super) refutability: PatternRefutability,
69 pub(super) is_param: Option<ParamKind>,
70 pub(super) has_type_ascription: bool,
74 pub(super) enum LifetimeContext {
75 LifetimeParam(Option<ast::LifetimeParam>),
81 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
82 pub(crate) enum ParamKind {
86 /// `CompletionContext` is created early during completion to figure out, where
87 /// exactly is the cursor, syntax-wise.
89 pub(crate) struct CompletionContext<'a> {
90 pub(super) sema: Semantics<'a, RootDatabase>,
91 pub(super) scope: SemanticsScope<'a>,
92 pub(super) db: &'a RootDatabase,
93 pub(super) config: &'a CompletionConfig,
94 pub(super) position: FilePosition,
95 /// The token before the cursor, in the original file.
96 pub(super) original_token: SyntaxToken,
97 /// The token before the cursor, in the macro-expanded file.
98 pub(super) token: SyntaxToken,
99 /// The crate of the current file.
100 pub(super) krate: Option<hir::Crate>,
101 pub(super) expected_name: Option<NameOrNameRef>,
102 pub(super) expected_type: Option<Type>,
104 /// The parent function of the cursor position if it exists.
105 pub(super) function_def: Option<ast::Fn>,
106 /// The parent impl of the cursor position if it exists.
107 pub(super) impl_def: Option<ast::Impl>,
108 /// The NameLike under the cursor in the original file if it exists.
109 pub(super) name_syntax: Option<ast::NameLike>,
110 pub(super) incomplete_let: bool,
112 pub(super) completion_location: Option<ImmediateLocation>,
113 pub(super) prev_sibling: Option<ImmediatePrevSibling>,
114 pub(super) attribute_under_caret: Option<ast::Attr>,
115 pub(super) previous_token: Option<SyntaxToken>,
117 pub(super) lifetime_ctx: Option<LifetimeContext>,
118 pub(super) pattern_ctx: Option<PatternContext>,
119 pub(super) path_context: Option<PathCompletionContext>,
120 pub(super) locals: Vec<(Name, Local)>,
122 no_completion_required: bool,
125 impl<'a> CompletionContext<'a> {
126 /// Checks whether completions in that particular case don't make much sense.
128 /// - `fn $0` -- we expect function name, it's unlikely that "hint" will be helpful.
129 /// Exception for this case is `impl Trait for Foo`, where we would like to hint trait method names.
130 /// - `for _ i$0` -- obviously, it'll be "in" keyword.
131 pub(crate) fn no_completion_required(&self) -> bool {
132 self.no_completion_required
135 /// The range of the identifier that is being completed.
136 pub(crate) fn source_range(&self) -> TextRange {
137 // check kind of macro-expanded token, but use range of original token
138 let kind = self.token.kind();
139 if kind == IDENT || kind == LIFETIME_IDENT || kind == UNDERSCORE || kind.is_keyword() {
140 self.original_token.text_range()
141 } else if kind == CHAR {
142 // assume we are completing a lifetime but the user has only typed the '
143 cov_mark::hit!(completes_if_lifetime_without_idents);
144 TextRange::at(self.original_token.text_range().start(), TextSize::from(1))
146 TextRange::empty(self.position.offset)
150 pub(crate) fn previous_token_is(&self, kind: SyntaxKind) -> bool {
151 self.previous_token.as_ref().map_or(false, |tok| tok.kind() == kind)
154 pub(crate) fn famous_defs(&self) -> FamousDefs {
155 FamousDefs(&self.sema, self.krate)
158 pub(crate) fn dot_receiver(&self) -> Option<&ast::Expr> {
159 match &self.completion_location {
161 ImmediateLocation::MethodCall { receiver, .. }
162 | ImmediateLocation::FieldAccess { receiver, .. },
163 ) => receiver.as_ref(),
168 pub(crate) fn has_dot_receiver(&self) -> bool {
170 &self.completion_location,
171 Some(ImmediateLocation::FieldAccess { receiver, .. } | ImmediateLocation::MethodCall { receiver,.. })
172 if receiver.is_some()
176 pub(crate) fn expects_assoc_item(&self) -> bool {
177 matches!(self.completion_location, Some(ImmediateLocation::Trait | ImmediateLocation::Impl))
180 pub(crate) fn expects_variant(&self) -> bool {
181 matches!(self.completion_location, Some(ImmediateLocation::Variant))
184 pub(crate) fn expects_non_trait_assoc_item(&self) -> bool {
185 matches!(self.completion_location, Some(ImmediateLocation::Impl))
188 pub(crate) fn expects_item(&self) -> bool {
189 matches!(self.completion_location, Some(ImmediateLocation::ItemList))
192 pub(crate) fn expects_generic_arg(&self) -> bool {
193 matches!(self.completion_location, Some(ImmediateLocation::GenericArgList(_)))
196 pub(crate) fn has_block_expr_parent(&self) -> bool {
197 matches!(self.completion_location, Some(ImmediateLocation::StmtList))
200 pub(crate) fn expects_ident_pat_or_ref_expr(&self) -> bool {
202 self.completion_location,
203 Some(ImmediateLocation::IdentPat | ImmediateLocation::RefExpr)
207 pub(crate) fn expect_field(&self) -> bool {
209 self.completion_location,
210 Some(ImmediateLocation::RecordField | ImmediateLocation::TupleField)
214 pub(crate) fn has_impl_or_trait_prev_sibling(&self) -> bool {
217 Some(ImmediatePrevSibling::ImplDefType | ImmediatePrevSibling::TraitDefName)
221 pub(crate) fn has_impl_prev_sibling(&self) -> bool {
222 matches!(self.prev_sibling, Some(ImmediatePrevSibling::ImplDefType))
225 pub(crate) fn has_visibility_prev_sibling(&self) -> bool {
226 matches!(self.prev_sibling, Some(ImmediatePrevSibling::Visibility))
229 pub(crate) fn after_if(&self) -> bool {
230 matches!(self.prev_sibling, Some(ImmediatePrevSibling::IfExpr))
233 pub(crate) fn is_path_disallowed(&self) -> bool {
234 self.previous_token_is(T![unsafe])
237 Some(ImmediatePrevSibling::Attribute | ImmediatePrevSibling::Visibility)
240 self.completion_location,
242 ImmediateLocation::ModDeclaration(_)
243 | ImmediateLocation::RecordPat(_)
244 | ImmediateLocation::RecordExpr(_)
245 | ImmediateLocation::Rename
250 pub(crate) fn expects_expression(&self) -> bool {
251 matches!(self.path_context, Some(PathCompletionContext { kind: Some(PathKind::Expr), .. }))
254 pub(crate) fn expects_type(&self) -> bool {
255 matches!(self.path_context, Some(PathCompletionContext { kind: Some(PathKind::Type), .. }))
258 pub(crate) fn path_is_call(&self) -> bool {
259 self.path_context.as_ref().map_or(false, |it| it.has_call_parens)
262 pub(crate) fn is_trivial_path(&self) -> bool {
263 matches!(self.path_context, Some(PathCompletionContext { is_trivial_path: true, .. }))
266 pub(crate) fn is_non_trivial_path(&self) -> bool {
267 matches!(self.path_context, Some(PathCompletionContext { is_trivial_path: false, .. }))
270 pub(crate) fn path_qual(&self) -> Option<&ast::Path> {
271 self.path_context.as_ref().and_then(|it| it.qualifier.as_ref())
274 pub(crate) fn path_kind(&self) -> Option<PathKind> {
275 self.path_context.as_ref().and_then(|it| it.kind)
278 /// Checks if an item is visible and not `doc(hidden)` at the completion site.
279 pub(crate) fn is_visible<I>(&self, item: &I) -> bool
281 I: hir::HasVisibility + hir::HasAttrs + hir::HasCrate + Copy,
283 self.is_visible_impl(&item.visibility(self.db), &item.attrs(self.db), item.krate(self.db))
286 pub(crate) fn is_scope_def_hidden(&self, scope_def: ScopeDef) -> bool {
287 if let (Some(attrs), Some(krate)) = (scope_def.attrs(self.db), scope_def.krate(self.db)) {
288 return self.is_doc_hidden(&attrs, krate);
294 /// Check if an item is `#[doc(hidden)]`.
295 pub(crate) fn is_item_hidden(&self, item: &hir::ItemInNs) -> bool {
296 let attrs = item.attrs(self.db);
297 let krate = item.krate(self.db);
298 match (attrs, krate) {
299 (Some(attrs), Some(krate)) => self.is_doc_hidden(&attrs, krate),
304 pub(crate) fn is_immediately_after_macro_bang(&self) -> bool {
305 self.token.kind() == BANG && self.token.parent().map_or(false, |it| it.kind() == MACRO_CALL)
308 /// A version of [`SemanticsScope::process_all_names`] that filters out `#[doc(hidden)]` items.
309 pub(crate) fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
310 self.scope.process_all_names(&mut |name, def| {
311 if self.is_scope_def_hidden(def) {
321 vis: &hir::Visibility,
323 defining_crate: hir::Crate,
325 let module = match self.scope.module() {
327 None => return false,
329 if !vis.is_visible_from(self.db, module.into()) {
330 // If the definition location is editable, also show private items
331 let root_file = defining_crate.root_file(self.db);
332 let source_root_id = self.db.file_source_root(root_file);
333 let is_editable = !self.db.source_root(source_root_id).is_library;
337 !self.is_doc_hidden(attrs, defining_crate)
340 fn is_doc_hidden(&self, attrs: &hir::Attrs, defining_crate: hir::Crate) -> bool {
341 let krate = match self.krate {
345 if krate != defining_crate && attrs.has_doc_hidden() {
346 // `doc(hidden)` items are only completed within the defining crate.
354 // CompletionContext construction
355 impl<'a> CompletionContext<'a> {
357 db: &'a RootDatabase,
358 position @ FilePosition { file_id, offset }: FilePosition,
359 config: &'a CompletionConfig,
360 ) -> Option<CompletionContext<'a>> {
361 let _p = profile::span("CompletionContext::new");
362 let sema = Semantics::new(db);
364 let original_file = sema.parse(file_id);
366 // Insert a fake ident to get a valid parse tree. We will use this file
367 // to determine context, though the original_file will be used for
368 // actual completion.
369 let file_with_fake_ident = {
370 let parse = db.parse(file_id);
371 let edit = Indel::insert(offset, "intellijRulezz".to_string());
372 parse.reparse(&edit).tree()
374 let fake_ident_token =
375 file_with_fake_ident.syntax().token_at_offset(offset).right_biased()?;
377 let original_token = original_file.syntax().token_at_offset(offset).left_biased()?;
378 let token = sema.descend_into_macros_single(original_token.clone());
379 let scope = sema.scope_at_offset(&token, offset);
380 let krate = scope.krate();
381 let mut locals = vec![];
382 scope.process_all_names(&mut |name, scope| {
383 if let ScopeDef::Local(local) = scope {
384 locals.push((name, local));
387 let mut ctx = CompletionContext {
403 completion_location: None,
405 attribute_under_caret: None,
406 previous_token: None,
409 incomplete_let: false,
410 no_completion_required: false,
413 original_file.syntax().clone(),
414 file_with_fake_ident.syntax().clone(),
421 /// Do the attribute expansion at the current cursor position for both original file and fake file
422 /// as long as possible. As soon as one of the two expansions fail we stop to stay in sync.
425 mut original_file: SyntaxNode,
426 mut speculative_file: SyntaxNode,
427 mut offset: TextSize,
428 mut fake_ident_token: SyntaxToken,
432 if let (Some(actual_item), Some(item_with_fake_ident)) = (
433 find_node_at_offset::<ast::Item>(&original_file, offset),
434 find_node_at_offset::<ast::Item>(&speculative_file, offset),
437 self.sema.expand_attr_macro(&actual_item),
438 self.sema.speculative_expand_attr_macro(
440 &item_with_fake_ident,
441 fake_ident_token.clone(),
444 (Some(actual_expansion), Some(speculative_expansion)) => {
445 let new_offset = speculative_expansion.1.text_range().start();
446 if new_offset > actual_expansion.text_range().end() {
449 original_file = actual_expansion;
450 speculative_file = speculative_expansion.0;
451 fake_ident_token = speculative_expansion.1;
460 // Expand fn-like macro calls
461 if let (Some(actual_macro_call), Some(macro_call_with_fake_ident)) = (
462 find_node_at_offset::<ast::MacroCall>(&original_file, offset),
463 find_node_at_offset::<ast::MacroCall>(&speculative_file, offset),
465 let mac_call_path0 = actual_macro_call.path().as_ref().map(|s| s.syntax().text());
467 macro_call_with_fake_ident.path().as_ref().map(|s| s.syntax().text());
468 if mac_call_path0 != mac_call_path1 {
471 let speculative_args = match macro_call_with_fake_ident.token_tree() {
476 if let (Some(actual_expansion), Some(speculative_expansion)) = (
477 self.sema.expand(&actual_macro_call),
478 self.sema.speculative_expand(
484 let new_offset = speculative_expansion.1.text_range().start();
485 if new_offset > actual_expansion.text_range().end() {
488 original_file = actual_expansion;
489 speculative_file = speculative_expansion.0;
490 fake_ident_token = speculative_expansion.1;
500 self.fill(&original_file, speculative_file, offset);
503 fn expected_type_and_name(&self) -> (Option<Type>, Option<NameOrNameRef>) {
504 let mut node = match self.token.parent() {
506 None => return (None, None),
511 ast::LetStmt(it) => {
512 cov_mark::hit!(expected_type_let_with_leading_char);
513 cov_mark::hit!(expected_type_let_without_leading_char);
515 .and_then(|pat| self.sema.type_of_pat(&pat))
516 .or_else(|| it.initializer().and_then(|it| self.sema.type_of_expr(&it)))
517 .map(TypeInfo::original);
518 let name = match it.pat() {
519 Some(ast::Pat::IdentPat(ident)) => ident.name().map(NameOrNameRef::Name),
520 Some(_) | None => None,
526 cov_mark::hit!(expected_type_fn_param);
527 ActiveParameter::at_token(
531 let name = ap.ident().map(NameOrNameRef::Name);
532 let ty = if has_ref(&self.token) {
533 cov_mark::hit!(expected_type_fn_param_ref);
540 .unwrap_or((None, None))
542 ast::RecordExprFieldList(it) => {
543 // wouldn't try {} be nice...
545 if self.token.kind() == T![..]
546 || self.token.prev_token().map(|t| t.kind()) == Some(T![..])
548 cov_mark::hit!(expected_type_struct_func_update);
549 let record_expr = it.syntax().parent().and_then(ast::RecordExpr::cast)?;
550 let ty = self.sema.type_of_expr(&record_expr.into())?;
556 cov_mark::hit!(expected_type_struct_field_without_leading_char);
557 let expr_field = self.token.prev_sibling_or_token()?
559 .and_then(ast::RecordExprField::cast)?;
560 let (_, _, ty) = self.sema.resolve_record_field(&expr_field)?;
563 expr_field.field_name().map(NameOrNameRef::NameRef),
566 })().unwrap_or((None, None))
568 ast::RecordExprField(it) => {
569 if let Some(expr) = it.expr() {
570 cov_mark::hit!(expected_type_struct_field_with_leading_char);
572 self.sema.type_of_expr(&expr).map(TypeInfo::original),
573 it.field_name().map(NameOrNameRef::NameRef),
576 cov_mark::hit!(expected_type_struct_field_followed_by_comma);
577 let ty = self.sema.resolve_record_field(&it)
578 .map(|(_, _, ty)| ty);
581 it.field_name().map(NameOrNameRef::NameRef),
585 ast::MatchExpr(it) => {
586 cov_mark::hit!(expected_type_match_arm_without_leading_char);
587 let ty = it.expr().and_then(|e| self.sema.type_of_expr(&e)).map(TypeInfo::original);
591 cov_mark::hit!(expected_type_if_let_without_leading_char);
592 let ty = it.condition()
593 .and_then(|cond| cond.expr())
594 .and_then(|e| self.sema.type_of_expr(&e))
595 .map(TypeInfo::original);
598 ast::IdentPat(it) => {
599 cov_mark::hit!(expected_type_if_let_with_leading_char);
600 cov_mark::hit!(expected_type_match_arm_with_leading_char);
601 let ty = self.sema.type_of_pat(&ast::Pat::from(it)).map(TypeInfo::original);
605 cov_mark::hit!(expected_type_fn_ret_with_leading_char);
606 cov_mark::hit!(expected_type_fn_ret_without_leading_char);
607 let def = self.sema.to_def(&it);
608 (def.map(|def| def.ret_type(self.db)), None)
610 ast::ClosureExpr(it) => {
611 let ty = self.sema.type_of_expr(&it.into());
612 ty.and_then(|ty| ty.original.as_callable(self.db))
613 .map(|c| (Some(c.return_type()), None))
614 .unwrap_or((None, None))
616 ast::ParamList(_) => (None, None),
617 ast::Stmt(_) => (None, None),
618 ast::Item(_) => (None, None),
620 match node.parent() {
625 None => (None, None),
635 original_file: &SyntaxNode,
636 file_with_fake_ident: SyntaxNode,
639 let fake_ident_token = file_with_fake_ident.token_at_offset(offset).right_biased().unwrap();
640 let syntax_element = NodeOrToken::Token(fake_ident_token);
641 self.previous_token = previous_token(syntax_element.clone());
642 self.attribute_under_caret = syntax_element.ancestors().find_map(ast::Attr::cast);
643 self.no_completion_required = {
644 let inside_impl_trait_block = inside_impl_trait_block(syntax_element.clone());
645 let fn_is_prev = self.previous_token_is(T![fn]);
646 let for_is_prev2 = for_is_prev2(syntax_element.clone());
647 (fn_is_prev && !inside_impl_trait_block) || for_is_prev2
650 self.incomplete_let =
651 syntax_element.ancestors().take(6).find_map(ast::LetStmt::cast).map_or(false, |it| {
652 it.syntax().text_range().end() == syntax_element.text_range().end()
655 let (expected_type, expected_name) = self.expected_type_and_name();
656 self.expected_type = expected_type;
657 self.expected_name = expected_name;
659 let name_like = match find_node_at_offset(&file_with_fake_ident, offset) {
663 self.completion_location =
664 determine_location(&self.sema, original_file, offset, &name_like);
665 self.prev_sibling = determine_prev_sibling(&name_like);
667 find_node_at_offset(original_file, name_like.syntax().text_range().start());
670 .token_ancestors_with_macros(self.token.clone())
671 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
672 .find_map(ast::Impl::cast);
673 self.function_def = self
675 .token_ancestors_with_macros(self.token.clone())
676 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
677 .find_map(ast::Fn::cast);
679 ast::NameLike::Lifetime(lifetime) => {
681 Self::classify_lifetime(&self.sema, original_file, lifetime, offset);
683 ast::NameLike::NameRef(name_ref) => {
684 if let Some((path_ctx, pat_ctx)) =
685 Self::classify_name_ref(&self.sema, original_file, name_ref)
687 self.path_context = Some(path_ctx);
688 self.pattern_ctx = pat_ctx;
691 ast::NameLike::Name(name) => {
692 self.pattern_ctx = Self::classify_name(&self.sema, name);
697 fn classify_lifetime(
698 sema: &Semantics<RootDatabase>,
699 original_file: &SyntaxNode,
700 lifetime: ast::Lifetime,
702 ) -> Option<LifetimeContext> {
703 let parent = lifetime.syntax().parent()?;
704 if parent.kind() == ERROR {
710 ast::LifetimeParam(_) => LifetimeContext::LifetimeParam(sema.find_node_at_offset_with_macros(original_file, offset)),
711 ast::BreakExpr(_) => LifetimeContext::LabelRef,
712 ast::ContinueExpr(_) => LifetimeContext::LabelRef,
713 ast::Label(_) => LifetimeContext::LabelDef,
714 _ => LifetimeContext::Lifetime,
719 fn classify_name(_sema: &Semantics<RootDatabase>, name: ast::Name) -> Option<PatternContext> {
720 let bind_pat = name.syntax().parent().and_then(ast::IdentPat::cast)?;
721 let is_name_in_field_pat = bind_pat
724 .and_then(ast::RecordPatField::cast)
725 .map_or(false, |pat_field| pat_field.name_ref().is_none());
726 if is_name_in_field_pat {
729 if !bind_pat.is_simple_ident() {
732 Some(pattern_context_for(bind_pat.into()))
735 fn classify_name_ref(
736 _sema: &Semantics<RootDatabase>,
737 original_file: &SyntaxNode,
738 name_ref: ast::NameRef,
739 ) -> Option<(PathCompletionContext, Option<PatternContext>)> {
740 let parent = name_ref.syntax().parent()?;
741 let segment = ast::PathSegment::cast(parent)?;
742 let path = segment.parent_path();
744 let mut path_ctx = PathCompletionContext {
745 has_call_parens: false,
746 is_trivial_path: false,
749 has_type_args: false,
752 use_tree_parent: false,
755 let mut pat_ctx = None;
756 path_ctx.in_loop_body = is_in_loop_body(name_ref.syntax());
758 path_ctx.kind = path.syntax().ancestors().find_map(|it| {
761 ast::PathType(_) => Some(PathKind::Type),
762 ast::PathExpr(it) => {
763 path_ctx.has_call_parens = it.syntax().parent().map_or(false, |it| ast::CallExpr::can_cast(it.kind()));
766 ast::TupleStructPat(it) => {
767 path_ctx.has_call_parens = true;
768 pat_ctx = Some(pattern_context_for(it.into()));
771 ast::RecordPat(it) => {
772 pat_ctx = Some(pattern_context_for(it.into()));
775 ast::PathPat(it) => {
776 pat_ctx = Some(pattern_context_for(it.into()));
779 ast::MacroCall(it) => it.excl_token().and(Some(PathKind::Mac)),
780 ast::Meta(_) => Some(PathKind::Attr),
781 ast::Visibility(it) => Some(PathKind::Vis { has_in_token: it.in_token().is_some() }),
782 ast::UseTree(_) => Some(PathKind::Use),
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, pat_ctx));
803 if let Some(segment) = path.segment() {
804 if segment.coloncolon_token().is_some() {
805 return Some((path_ctx, pat_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()),
829 Some((path_ctx, pat_ctx))
833 fn pattern_context_for(pat: ast::Pat) -> PatternContext {
834 let mut is_param = None;
835 let (refutability, has_type_ascription) =
839 .skip_while(|it| ast::Pat::can_cast(it.kind()))
841 .map_or((PatternRefutability::Irrefutable, false), |node| {
842 let refutability = match_ast! {
844 ast::LetStmt(let_) => return (PatternRefutability::Irrefutable, let_.ty().is_some()),
845 ast::Param(param) => {
846 let is_closure_param = param
850 .and_then(ast::ClosureExpr::cast)
852 is_param = Some(if is_closure_param {
857 return (PatternRefutability::Irrefutable, param.ty().is_some())
859 ast::MatchArm(_) => PatternRefutability::Refutable,
860 ast::Condition(_) => PatternRefutability::Refutable,
861 ast::ForExpr(_) => PatternRefutability::Irrefutable,
862 _ => PatternRefutability::Irrefutable,
865 (refutability, false)
867 PatternContext { refutability, is_param, has_type_ascription }
869 fn find_node_with_range<N: AstNode>(syntax: &SyntaxNode, range: TextRange) -> Option<N> {
870 syntax.covering_element(range).ancestors().find_map(N::cast)
873 fn path_or_use_tree_qualifier(path: &ast::Path) -> Option<(ast::Path, bool)> {
874 if let Some(qual) = path.qualifier() {
875 return Some((qual, false));
877 let use_tree_list = path.syntax().ancestors().find_map(ast::UseTreeList::cast)?;
878 let use_tree = use_tree_list.syntax().parent().and_then(ast::UseTree::cast)?;
879 use_tree.path().zip(Some(true))
882 fn has_ref(token: &SyntaxToken) -> bool {
883 let mut token = token.clone();
884 for skip in [WHITESPACE, IDENT, T![mut]] {
885 if token.kind() == skip {
886 token = match token.prev_token() {
888 None => return false,
892 token.kind() == T![&]
897 use expect_test::{expect, Expect};
900 use crate::tests::{position, TEST_CONFIG};
902 use super::CompletionContext;
904 fn check_expected_type_and_name(ra_fixture: &str, expect: Expect) {
905 let (db, pos) = position(ra_fixture);
906 let config = TEST_CONFIG;
907 let completion_context = CompletionContext::new(&db, pos, &config).unwrap();
909 let ty = completion_context
911 .map(|t| t.display_test(&db).to_string())
912 .unwrap_or("?".to_owned());
914 let name = completion_context
916 .map_or_else(|| "?".to_owned(), |name| name.to_string());
918 expect.assert_eq(&format!("ty: {}, name: {}", ty, name));
922 fn expected_type_let_without_leading_char() {
923 cov_mark::check!(expected_type_let_without_leading_char);
924 check_expected_type_and_name(
930 expect![[r#"ty: u32, name: x"#]],
935 fn expected_type_let_with_leading_char() {
936 cov_mark::check!(expected_type_let_with_leading_char);
937 check_expected_type_and_name(
943 expect![[r#"ty: u32, name: x"#]],
948 fn expected_type_let_pat() {
949 check_expected_type_and_name(
955 expect![[r#"ty: u32, name: ?"#]],
957 check_expected_type_and_name(
963 expect![[r#"ty: u32, name: ?"#]],
968 fn expected_type_fn_param() {
969 cov_mark::check!(expected_type_fn_param);
970 check_expected_type_and_name(
972 fn foo() { bar($0); }
975 expect![[r#"ty: u32, name: x"#]],
977 check_expected_type_and_name(
979 fn foo() { bar(c$0); }
982 expect![[r#"ty: u32, name: x"#]],
987 fn expected_type_fn_param_ref() {
988 cov_mark::check!(expected_type_fn_param_ref);
989 check_expected_type_and_name(
991 fn foo() { bar(&$0); }
994 expect![[r#"ty: u32, name: x"#]],
996 check_expected_type_and_name(
998 fn foo() { bar(&mut $0); }
999 fn bar(x: &mut u32) {}
1001 expect![[r#"ty: u32, name: x"#]],
1003 check_expected_type_and_name(
1005 fn foo() { bar(&c$0); }
1008 expect![[r#"ty: u32, name: x"#]],
1013 fn expected_type_struct_field_without_leading_char() {
1014 cov_mark::check!(expected_type_struct_field_without_leading_char);
1015 check_expected_type_and_name(
1017 struct Foo { a: u32 }
1022 expect![[r#"ty: u32, name: a"#]],
1027 fn expected_type_struct_field_followed_by_comma() {
1028 cov_mark::check!(expected_type_struct_field_followed_by_comma);
1029 check_expected_type_and_name(
1031 struct Foo { a: u32 }
1036 expect![[r#"ty: u32, name: a"#]],
1041 fn expected_type_generic_struct_field() {
1042 check_expected_type_and_name(
1044 struct Foo<T> { a: T }
1045 fn foo() -> Foo<u32> {
1049 expect![[r#"ty: u32, name: a"#]],
1054 fn expected_type_struct_field_with_leading_char() {
1055 cov_mark::check!(expected_type_struct_field_with_leading_char);
1056 check_expected_type_and_name(
1058 struct Foo { a: u32 }
1063 expect![[r#"ty: u32, name: a"#]],
1068 fn expected_type_match_arm_without_leading_char() {
1069 cov_mark::check!(expected_type_match_arm_without_leading_char);
1070 check_expected_type_and_name(
1077 expect![[r#"ty: E, name: ?"#]],
1082 fn expected_type_match_arm_with_leading_char() {
1083 cov_mark::check!(expected_type_match_arm_with_leading_char);
1084 check_expected_type_and_name(
1091 expect![[r#"ty: E, name: ?"#]],
1096 fn expected_type_if_let_without_leading_char() {
1097 cov_mark::check!(expected_type_if_let_without_leading_char);
1098 check_expected_type_and_name(
1100 enum Foo { Bar, Baz, Quux }
1107 expect![[r#"ty: Foo, name: ?"#]],
1112 fn expected_type_if_let_with_leading_char() {
1113 cov_mark::check!(expected_type_if_let_with_leading_char);
1114 check_expected_type_and_name(
1116 enum Foo { Bar, Baz, Quux }
1123 expect![[r#"ty: Foo, name: ?"#]],
1128 fn expected_type_fn_ret_without_leading_char() {
1129 cov_mark::check!(expected_type_fn_ret_without_leading_char);
1130 check_expected_type_and_name(
1136 expect![[r#"ty: u32, name: ?"#]],
1141 fn expected_type_fn_ret_with_leading_char() {
1142 cov_mark::check!(expected_type_fn_ret_with_leading_char);
1143 check_expected_type_and_name(
1149 expect![[r#"ty: u32, name: ?"#]],
1154 fn expected_type_fn_ret_fn_ref_fully_typed() {
1155 check_expected_type_and_name(
1161 expect![[r#"ty: u32, name: ?"#]],
1166 fn expected_type_closure_param_return() {
1167 // FIXME: make this work with `|| $0`
1168 check_expected_type_and_name(
1175 fn bar(f: impl FnOnce() -> u32) {}
1177 expect![[r#"ty: u32, name: ?"#]],
1182 fn expected_type_generic_function() {
1183 check_expected_type_and_name(
1191 expect![[r#"ty: u32, name: t"#]],
1196 fn expected_type_generic_method() {
1197 check_expected_type_and_name(
1205 fn bar(self, t: T) {}
1208 expect![[r#"ty: u32, name: t"#]],
1213 fn expected_type_functional_update() {
1214 cov_mark::check!(expected_type_struct_func_update);
1215 check_expected_type_and_name(
1217 struct Foo { field: u32 }
1224 expect![[r#"ty: Foo, name: ?"#]],
1229 fn expected_type_param_pat() {
1230 check_expected_type_and_name(
1232 struct Foo { field: u32 }
1235 expect![[r#"ty: Foo, name: ?"#]],
1237 check_expected_type_and_name(
1239 struct Foo { field: u32 }
1242 // FIXME make this work, currently fails due to pattern recovery eating the `:`
1243 expect![[r#"ty: ?, name: ?"#]],