1 //! See `CompletionContext` structure.
5 use base_db::SourceDatabaseExt;
6 use hir::{HasAttrs, Local, Name, ScopeDef, Semantics, SemanticsScope, Type, TypeInfo};
8 active_parameter::ActiveParameter,
9 base_db::{FilePosition, SourceDatabase},
14 algo::find_node_at_offset,
15 ast::{self, HasName, NameOrNameRef},
16 match_ast, AstNode, NodeOrToken,
17 SyntaxKind::{self, *},
18 SyntaxNode, SyntaxToken, TextRange, TextSize, T,
24 determine_location, determine_prev_sibling, for_is_prev2, inside_impl_trait_block,
25 is_in_loop_body, previous_token, ImmediateLocation, ImmediatePrevSibling,
30 const COMPLETION_MARKER: &str = "intellijRulezz";
32 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
33 pub(crate) enum PatternRefutability {
38 #[derive(Copy, Clone, Debug)]
39 pub(super) enum PathKind {
45 Vis { has_in_token: bool },
50 pub(crate) struct PathCompletionContext {
51 /// If this is a call with () already there
52 has_call_parens: bool,
53 /// A single-indent path, like `foo`. `::foo` should not be considered a trivial path.
54 pub(super) is_trivial_path: bool,
55 /// If not a trivial path, the prefix (qualifier).
56 pub(super) qualifier: Option<ast::Path>,
58 /// If not a trivial path, the suffix (parent).
59 pub(super) parent: Option<ast::Path>,
60 /// Whether the qualifier comes from a use tree parent or not
61 pub(super) use_tree_parent: bool,
62 pub(super) kind: Option<PathKind>,
63 /// Whether the path segment has type args or not.
64 pub(super) has_type_args: bool,
65 /// `true` if we are a statement or a last expr in the block.
66 pub(super) can_be_stmt: bool,
67 pub(super) in_loop_body: bool,
71 pub(super) struct PatternContext {
72 pub(super) refutability: PatternRefutability,
73 pub(super) param_ctx: Option<(ast::ParamList, ast::Param, ParamKind)>,
74 pub(super) has_type_ascription: bool,
78 pub(super) enum LifetimeContext {
79 LifetimeParam(Option<ast::LifetimeParam>),
85 #[derive(Clone, Debug, PartialEq, Eq)]
86 pub(crate) enum ParamKind {
88 Closure(ast::ClosureExpr),
91 /// `CompletionContext` is created early during completion to figure out, where
92 /// exactly is the cursor, syntax-wise.
94 pub(crate) struct CompletionContext<'a> {
95 pub(super) sema: Semantics<'a, RootDatabase>,
96 pub(super) scope: SemanticsScope<'a>,
97 pub(super) db: &'a RootDatabase,
98 pub(super) config: &'a CompletionConfig,
99 pub(super) position: FilePosition,
100 /// The token before the cursor, in the original file.
101 pub(super) original_token: SyntaxToken,
102 /// The token before the cursor, in the macro-expanded file.
103 pub(super) token: SyntaxToken,
104 /// The crate of the current file.
105 pub(super) krate: Option<hir::Crate>,
106 /// The crate of the `scope`.
107 pub(super) module: Option<hir::Module>,
108 pub(super) expected_name: Option<NameOrNameRef>,
109 pub(super) expected_type: Option<Type>,
111 /// The parent function of the cursor position if it exists.
112 pub(super) function_def: Option<ast::Fn>,
113 pub(super) attr: Option<ast::Attr>,
114 /// The parent impl of the cursor position if it exists.
115 pub(super) impl_def: Option<ast::Impl>,
116 /// The NameLike under the cursor in the original file if it exists.
117 pub(super) name_syntax: Option<ast::NameLike>,
118 pub(super) incomplete_let: bool,
120 pub(super) completion_location: Option<ImmediateLocation>,
121 pub(super) prev_sibling: Option<ImmediatePrevSibling>,
122 pub(super) fake_attribute_under_caret: Option<ast::Attr>,
123 pub(super) previous_token: Option<SyntaxToken>,
125 pub(super) lifetime_ctx: Option<LifetimeContext>,
126 pub(super) pattern_ctx: Option<PatternContext>,
127 pub(super) path_context: Option<PathCompletionContext>,
129 pub(super) locals: Vec<(Name, Local)>,
131 no_completion_required: bool,
134 impl<'a> CompletionContext<'a> {
135 /// Checks whether completions in that particular case don't make much sense.
137 /// - `fn $0` -- we expect function name, it's unlikely that "hint" will be helpful.
138 /// Exception for this case is `impl Trait for Foo`, where we would like to hint trait method names.
139 /// - `for _ i$0` -- obviously, it'll be "in" keyword.
140 pub(crate) fn no_completion_required(&self) -> bool {
141 self.no_completion_required
144 /// The range of the identifier that is being completed.
145 pub(crate) fn source_range(&self) -> TextRange {
146 // check kind of macro-expanded token, but use range of original token
147 let kind = self.token.kind();
148 if kind == IDENT || kind == LIFETIME_IDENT || kind == UNDERSCORE || kind.is_keyword() {
149 self.original_token.text_range()
150 } else if kind == CHAR {
151 // assume we are completing a lifetime but the user has only typed the '
152 cov_mark::hit!(completes_if_lifetime_without_idents);
153 TextRange::at(self.original_token.text_range().start(), TextSize::from(1))
155 TextRange::empty(self.position.offset)
159 pub(crate) fn previous_token_is(&self, kind: SyntaxKind) -> bool {
160 self.previous_token.as_ref().map_or(false, |tok| tok.kind() == kind)
163 pub(crate) fn famous_defs(&self) -> FamousDefs {
164 FamousDefs(&self.sema, self.krate)
167 pub(crate) fn dot_receiver(&self) -> Option<&ast::Expr> {
168 match &self.completion_location {
170 ImmediateLocation::MethodCall { receiver, .. }
171 | ImmediateLocation::FieldAccess { receiver, .. },
172 ) => receiver.as_ref(),
177 pub(crate) fn has_dot_receiver(&self) -> bool {
179 &self.completion_location,
180 Some(ImmediateLocation::FieldAccess { receiver, .. } | ImmediateLocation::MethodCall { receiver,.. })
181 if receiver.is_some()
185 pub(crate) fn expects_assoc_item(&self) -> bool {
186 matches!(self.completion_location, Some(ImmediateLocation::Trait | ImmediateLocation::Impl))
189 pub(crate) fn expects_variant(&self) -> bool {
190 matches!(self.completion_location, Some(ImmediateLocation::Variant))
193 pub(crate) fn expects_non_trait_assoc_item(&self) -> bool {
194 matches!(self.completion_location, Some(ImmediateLocation::Impl))
197 pub(crate) fn expects_item(&self) -> bool {
198 matches!(self.completion_location, Some(ImmediateLocation::ItemList))
201 pub(crate) fn expects_generic_arg(&self) -> bool {
202 matches!(self.completion_location, Some(ImmediateLocation::GenericArgList(_)))
205 pub(crate) fn has_block_expr_parent(&self) -> bool {
206 matches!(self.completion_location, Some(ImmediateLocation::StmtList))
209 pub(crate) fn expects_ident_pat_or_ref_expr(&self) -> bool {
211 self.completion_location,
212 Some(ImmediateLocation::IdentPat | ImmediateLocation::RefExpr)
216 pub(crate) fn expect_field(&self) -> bool {
218 self.completion_location,
219 Some(ImmediateLocation::RecordField | ImmediateLocation::TupleField)
223 pub(crate) fn has_impl_or_trait_prev_sibling(&self) -> bool {
226 Some(ImmediatePrevSibling::ImplDefType | ImmediatePrevSibling::TraitDefName)
230 pub(crate) fn has_impl_prev_sibling(&self) -> bool {
231 matches!(self.prev_sibling, Some(ImmediatePrevSibling::ImplDefType))
234 pub(crate) fn has_visibility_prev_sibling(&self) -> bool {
235 matches!(self.prev_sibling, Some(ImmediatePrevSibling::Visibility))
238 pub(crate) fn after_if(&self) -> bool {
239 matches!(self.prev_sibling, Some(ImmediatePrevSibling::IfExpr))
242 pub(crate) fn is_path_disallowed(&self) -> bool {
243 self.previous_token_is(T![unsafe])
246 Some(ImmediatePrevSibling::Attribute | ImmediatePrevSibling::Visibility)
249 self.completion_location,
251 ImmediateLocation::ModDeclaration(_)
252 | ImmediateLocation::RecordPat(_)
253 | ImmediateLocation::RecordExpr(_)
254 | ImmediateLocation::Rename
259 pub(crate) fn expects_expression(&self) -> bool {
260 matches!(self.path_context, Some(PathCompletionContext { kind: Some(PathKind::Expr), .. }))
263 pub(crate) fn expects_type(&self) -> bool {
264 matches!(self.path_context, Some(PathCompletionContext { kind: Some(PathKind::Type), .. }))
267 pub(crate) fn path_is_call(&self) -> bool {
268 self.path_context.as_ref().map_or(false, |it| it.has_call_parens)
271 pub(crate) fn is_trivial_path(&self) -> bool {
272 matches!(self.path_context, Some(PathCompletionContext { is_trivial_path: true, .. }))
275 pub(crate) fn is_non_trivial_path(&self) -> bool {
276 matches!(self.path_context, Some(PathCompletionContext { is_trivial_path: false, .. }))
279 pub(crate) fn path_qual(&self) -> Option<&ast::Path> {
280 self.path_context.as_ref().and_then(|it| it.qualifier.as_ref())
283 pub(crate) fn path_kind(&self) -> Option<PathKind> {
284 self.path_context.as_ref().and_then(|it| it.kind)
287 /// Checks if an item is visible and not `doc(hidden)` at the completion site.
288 pub(crate) fn is_visible<I>(&self, item: &I) -> bool
290 I: hir::HasVisibility + hir::HasAttrs + hir::HasCrate + Copy,
292 self.is_visible_impl(&item.visibility(self.db), &item.attrs(self.db), item.krate(self.db))
295 pub(crate) fn is_scope_def_hidden(&self, scope_def: ScopeDef) -> bool {
296 if let (Some(attrs), Some(krate)) = (scope_def.attrs(self.db), scope_def.krate(self.db)) {
297 return self.is_doc_hidden(&attrs, krate);
303 /// Check if an item is `#[doc(hidden)]`.
304 pub(crate) fn is_item_hidden(&self, item: &hir::ItemInNs) -> bool {
305 let attrs = item.attrs(self.db);
306 let krate = item.krate(self.db);
307 match (attrs, krate) {
308 (Some(attrs), Some(krate)) => self.is_doc_hidden(&attrs, krate),
313 pub(crate) fn is_immediately_after_macro_bang(&self) -> bool {
314 self.token.kind() == BANG && self.token.parent().map_or(false, |it| it.kind() == MACRO_CALL)
317 /// Whether the given trait is an operator trait or not.
318 pub(crate) fn is_ops_trait(&self, trait_: hir::Trait) -> bool {
319 match trait_.attrs(self.db).lang() {
320 Some(lang) => OP_TRAIT_LANG_NAMES.contains(&lang.as_str()),
325 /// A version of [`SemanticsScope::process_all_names`] that filters out `#[doc(hidden)]` items.
326 pub(crate) fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
327 let _p = profile::span("CompletionContext::process_all_names");
328 self.scope.process_all_names(&mut |name, def| {
329 if self.is_scope_def_hidden(def) {
339 vis: &hir::Visibility,
341 defining_crate: hir::Crate,
343 let module = match self.module {
345 None => return false,
347 if !vis.is_visible_from(self.db, module.into()) {
348 // If the definition location is editable, also show private items
349 let root_file = defining_crate.root_file(self.db);
350 let source_root_id = self.db.file_source_root(root_file);
351 let is_editable = !self.db.source_root(source_root_id).is_library;
355 !self.is_doc_hidden(attrs, defining_crate)
358 fn is_doc_hidden(&self, attrs: &hir::Attrs, defining_crate: hir::Crate) -> bool {
359 let krate = match self.krate {
363 if krate != defining_crate && attrs.has_doc_hidden() {
364 // `doc(hidden)` items are only completed within the defining crate.
372 // CompletionContext construction
373 impl<'a> CompletionContext<'a> {
375 db: &'a RootDatabase,
376 position @ FilePosition { file_id, offset }: FilePosition,
377 config: &'a CompletionConfig,
378 ) -> Option<CompletionContext<'a>> {
379 let _p = profile::span("CompletionContext::new");
380 let sema = Semantics::new(db);
382 let original_file = sema.parse(file_id);
384 // Insert a fake ident to get a valid parse tree. We will use this file
385 // to determine context, though the original_file will be used for
386 // actual completion.
387 let file_with_fake_ident = {
388 let parse = db.parse(file_id);
389 let edit = Indel::insert(offset, COMPLETION_MARKER.to_string());
390 parse.reparse(&edit).tree()
392 let fake_ident_token =
393 file_with_fake_ident.syntax().token_at_offset(offset).right_biased()?;
395 let original_token = original_file.syntax().token_at_offset(offset).left_biased()?;
396 let token = sema.descend_into_macros_single(original_token.clone());
397 let scope = sema.scope_at_offset(&token.parent()?, offset);
398 let krate = scope.krate();
399 let module = scope.module();
400 let mut locals = vec![];
401 scope.process_all_names(&mut |name, scope| {
402 if let ScopeDef::Local(local) = scope {
403 locals.push((name, local));
407 let mut ctx = CompletionContext {
425 completion_location: None,
427 fake_attribute_under_caret: None,
428 previous_token: None,
431 incomplete_let: false,
432 no_completion_required: false,
435 original_file.syntax().clone(),
436 file_with_fake_ident.syntax().clone(),
443 /// Do the attribute expansion at the current cursor position for both original file and fake file
444 /// as long as possible. As soon as one of the two expansions fail we stop to stay in sync.
447 mut original_file: SyntaxNode,
448 mut speculative_file: SyntaxNode,
449 mut offset: TextSize,
450 mut fake_ident_token: SyntaxToken,
452 let _p = profile::span("CompletionContext::expand_and_fill");
455 |item: &ast::Item| item.syntax().ancestors().skip(1).find_map(ast::Item::cast);
456 let ancestor_items = iter::successors(
458 find_node_at_offset::<ast::Item>(&original_file, offset),
459 find_node_at_offset::<ast::Item>(&speculative_file, offset),
461 |(a, b)| parent_item(a).zip(parent_item(b)),
463 for (actual_item, item_with_fake_ident) in ancestor_items {
465 self.sema.expand_attr_macro(&actual_item),
466 self.sema.speculative_expand_attr_macro(
468 &item_with_fake_ident,
469 fake_ident_token.clone(),
472 // maybe parent items have attributes
474 // successful expansions
475 (Some(actual_expansion), Some((fake_expansion, fake_mapped_token))) => {
476 let new_offset = fake_mapped_token.text_range().start();
477 if new_offset > actual_expansion.text_range().end() {
480 original_file = actual_expansion;
481 speculative_file = fake_expansion;
482 fake_ident_token = fake_mapped_token;
486 // exactly one expansion failed, inconsistent state so stop expanding completely
487 _ => break 'expansion,
491 // Expand fn-like macro calls
492 if let (Some(actual_macro_call), Some(macro_call_with_fake_ident)) = (
493 find_node_at_offset::<ast::MacroCall>(&original_file, offset),
494 find_node_at_offset::<ast::MacroCall>(&speculative_file, offset),
496 let mac_call_path0 = actual_macro_call.path().as_ref().map(|s| s.syntax().text());
498 macro_call_with_fake_ident.path().as_ref().map(|s| s.syntax().text());
499 if mac_call_path0 != mac_call_path1 {
502 let speculative_args = match macro_call_with_fake_ident.token_tree() {
508 self.sema.expand(&actual_macro_call),
509 self.sema.speculative_expand(
512 fake_ident_token.clone(),
515 // successful expansions
516 (Some(actual_expansion), Some((fake_expansion, fake_mapped_token))) => {
517 let new_offset = fake_mapped_token.text_range().start();
518 if new_offset > actual_expansion.text_range().end() {
521 original_file = actual_expansion;
522 speculative_file = fake_expansion;
523 fake_ident_token = fake_mapped_token;
534 self.fill(&original_file, speculative_file, offset);
537 fn expected_type_and_name(&self) -> (Option<Type>, Option<NameOrNameRef>) {
538 let mut node = match self.token.parent() {
540 None => return (None, None),
545 ast::LetStmt(it) => {
546 cov_mark::hit!(expected_type_let_with_leading_char);
547 cov_mark::hit!(expected_type_let_without_leading_char);
549 .and_then(|pat| self.sema.type_of_pat(&pat))
550 .or_else(|| it.initializer().and_then(|it| self.sema.type_of_expr(&it)))
551 .map(TypeInfo::original);
552 let name = match it.pat() {
553 Some(ast::Pat::IdentPat(ident)) => ident.name().map(NameOrNameRef::Name),
554 Some(_) | None => None,
560 cov_mark::hit!(expected_type_fn_param);
561 ActiveParameter::at_token(
565 let name = ap.ident().map(NameOrNameRef::Name);
566 let ty = if has_ref(&self.token) {
567 cov_mark::hit!(expected_type_fn_param_ref);
574 .unwrap_or((None, None))
576 ast::RecordExprFieldList(it) => {
577 // wouldn't try {} be nice...
579 if self.token.kind() == T![..]
580 || self.token.prev_token().map(|t| t.kind()) == Some(T![..])
582 cov_mark::hit!(expected_type_struct_func_update);
583 let record_expr = it.syntax().parent().and_then(ast::RecordExpr::cast)?;
584 let ty = self.sema.type_of_expr(&record_expr.into())?;
590 cov_mark::hit!(expected_type_struct_field_without_leading_char);
591 let expr_field = self.token.prev_sibling_or_token()?
593 .and_then(ast::RecordExprField::cast)?;
594 let (_, _, ty) = self.sema.resolve_record_field(&expr_field)?;
597 expr_field.field_name().map(NameOrNameRef::NameRef),
600 })().unwrap_or((None, None))
602 ast::RecordExprField(it) => {
603 if let Some(expr) = it.expr() {
604 cov_mark::hit!(expected_type_struct_field_with_leading_char);
606 self.sema.type_of_expr(&expr).map(TypeInfo::original),
607 it.field_name().map(NameOrNameRef::NameRef),
610 cov_mark::hit!(expected_type_struct_field_followed_by_comma);
611 let ty = self.sema.resolve_record_field(&it)
612 .map(|(_, _, ty)| ty);
615 it.field_name().map(NameOrNameRef::NameRef),
619 ast::MatchExpr(it) => {
620 cov_mark::hit!(expected_type_match_arm_without_leading_char);
621 let ty = it.expr().and_then(|e| self.sema.type_of_expr(&e)).map(TypeInfo::original);
625 cov_mark::hit!(expected_type_if_let_without_leading_char);
626 let ty = it.condition()
627 .and_then(|cond| cond.expr())
628 .and_then(|e| self.sema.type_of_expr(&e))
629 .map(TypeInfo::original);
632 ast::IdentPat(it) => {
633 cov_mark::hit!(expected_type_if_let_with_leading_char);
634 cov_mark::hit!(expected_type_match_arm_with_leading_char);
635 let ty = self.sema.type_of_pat(&ast::Pat::from(it)).map(TypeInfo::original);
639 cov_mark::hit!(expected_type_fn_ret_with_leading_char);
640 cov_mark::hit!(expected_type_fn_ret_without_leading_char);
641 let def = self.sema.to_def(&it);
642 (def.map(|def| def.ret_type(self.db)), None)
644 ast::ClosureExpr(it) => {
645 let ty = self.sema.type_of_expr(&it.into());
646 ty.and_then(|ty| ty.original.as_callable(self.db))
647 .map(|c| (Some(c.return_type()), None))
648 .unwrap_or((None, None))
650 ast::ParamList(_) => (None, None),
651 ast::Stmt(_) => (None, None),
652 ast::Item(_) => (None, None),
654 match node.parent() {
659 None => (None, None),
669 original_file: &SyntaxNode,
670 file_with_fake_ident: SyntaxNode,
673 let fake_ident_token = file_with_fake_ident.token_at_offset(offset).right_biased().unwrap();
674 let syntax_element = NodeOrToken::Token(fake_ident_token);
675 self.previous_token = previous_token(syntax_element.clone());
676 self.no_completion_required = {
677 let inside_impl_trait_block = inside_impl_trait_block(syntax_element.clone());
678 let fn_is_prev = self.previous_token_is(T![fn]);
679 let for_is_prev2 = for_is_prev2(syntax_element.clone());
680 (fn_is_prev && !inside_impl_trait_block) || for_is_prev2
685 .token_ancestors_with_macros(self.token.clone())
686 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
687 .find_map(ast::Attr::cast);
688 self.fake_attribute_under_caret = syntax_element.ancestors().find_map(ast::Attr::cast);
690 self.incomplete_let =
691 syntax_element.ancestors().take(6).find_map(ast::LetStmt::cast).map_or(false, |it| {
692 it.syntax().text_range().end() == syntax_element.text_range().end()
695 let (expected_type, expected_name) = self.expected_type_and_name();
696 self.expected_type = expected_type;
697 self.expected_name = expected_name;
699 let name_like = match find_node_at_offset(&file_with_fake_ident, offset) {
703 self.completion_location =
704 determine_location(&self.sema, original_file, offset, &name_like);
705 self.prev_sibling = determine_prev_sibling(&name_like);
707 find_node_at_offset(original_file, name_like.syntax().text_range().start());
710 .token_ancestors_with_macros(self.token.clone())
711 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
712 .find_map(ast::Impl::cast);
713 self.function_def = self
715 .token_ancestors_with_macros(self.token.clone())
716 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
717 .find_map(ast::Fn::cast);
719 ast::NameLike::Lifetime(lifetime) => {
721 Self::classify_lifetime(&self.sema, original_file, lifetime, offset);
723 ast::NameLike::NameRef(name_ref) => {
724 if let Some((path_ctx, pat_ctx)) =
725 Self::classify_name_ref(&self.sema, original_file, name_ref)
727 self.path_context = Some(path_ctx);
728 self.pattern_ctx = pat_ctx;
731 ast::NameLike::Name(name) => {
732 self.pattern_ctx = Self::classify_name(&self.sema, original_file, name);
737 fn classify_lifetime(
738 sema: &Semantics<RootDatabase>,
739 original_file: &SyntaxNode,
740 lifetime: ast::Lifetime,
742 ) -> Option<LifetimeContext> {
743 let parent = lifetime.syntax().parent()?;
744 if parent.kind() == ERROR {
750 ast::LifetimeParam(_) => LifetimeContext::LifetimeParam(sema.find_node_at_offset_with_macros(original_file, offset)),
751 ast::BreakExpr(_) => LifetimeContext::LabelRef,
752 ast::ContinueExpr(_) => LifetimeContext::LabelRef,
753 ast::Label(_) => LifetimeContext::LabelDef,
754 _ => LifetimeContext::Lifetime,
760 _sema: &Semantics<RootDatabase>,
761 original_file: &SyntaxNode,
763 ) -> Option<PatternContext> {
764 let bind_pat = name.syntax().parent().and_then(ast::IdentPat::cast)?;
765 let is_name_in_field_pat = bind_pat
768 .and_then(ast::RecordPatField::cast)
769 .map_or(false, |pat_field| pat_field.name_ref().is_none());
770 if is_name_in_field_pat {
773 if !bind_pat.is_simple_ident() {
776 Some(pattern_context_for(original_file, bind_pat.into()))
779 fn classify_name_ref(
780 _sema: &Semantics<RootDatabase>,
781 original_file: &SyntaxNode,
782 name_ref: ast::NameRef,
783 ) -> Option<(PathCompletionContext, Option<PatternContext>)> {
784 let parent = name_ref.syntax().parent()?;
785 let segment = ast::PathSegment::cast(parent)?;
786 let path = segment.parent_path();
788 let mut path_ctx = PathCompletionContext {
789 has_call_parens: false,
790 is_trivial_path: false,
793 has_type_args: false,
796 use_tree_parent: false,
799 let mut pat_ctx = None;
800 path_ctx.in_loop_body = is_in_loop_body(name_ref.syntax());
802 path_ctx.kind = path.syntax().ancestors().find_map(|it| {
805 ast::PathType(_) => Some(PathKind::Type),
806 ast::PathExpr(it) => {
807 path_ctx.has_call_parens = it.syntax().parent().map_or(false, |it| ast::CallExpr::can_cast(it.kind()));
810 ast::TupleStructPat(it) => {
811 path_ctx.has_call_parens = true;
812 pat_ctx = Some(pattern_context_for(original_file, it.into()));
815 ast::RecordPat(it) => {
816 pat_ctx = Some(pattern_context_for(original_file, it.into()));
819 ast::PathPat(it) => {
820 pat_ctx = Some(pattern_context_for(original_file, it.into()));
823 ast::MacroCall(it) => it.excl_token().and(Some(PathKind::Mac)),
824 ast::Meta(_) => Some(PathKind::Attr),
825 ast::Visibility(it) => Some(PathKind::Vis { has_in_token: it.in_token().is_some() }),
826 ast::UseTree(_) => Some(PathKind::Use),
831 path_ctx.has_type_args = segment.generic_arg_list().is_some();
833 if let Some((path, use_tree_parent)) = path_or_use_tree_qualifier(&path) {
834 path_ctx.use_tree_parent = use_tree_parent;
835 path_ctx.qualifier = path
837 .and_then(|it| find_node_in_file(original_file, &it))
838 .map(|it| it.parent_path());
839 return Some((path_ctx, pat_ctx));
842 if let Some(segment) = path.segment() {
843 if segment.coloncolon_token().is_some() {
844 return Some((path_ctx, pat_ctx));
848 path_ctx.is_trivial_path = true;
850 // Find either enclosing expr statement (thing with `;`) or a
851 // block. If block, check that we are the last expr.
852 path_ctx.can_be_stmt = name_ref
856 if let Some(stmt) = ast::ExprStmt::cast(node.clone()) {
857 return Some(stmt.syntax().text_range() == name_ref.syntax().text_range());
859 if let Some(stmt_list) = ast::StmtList::cast(node) {
861 stmt_list.tail_expr().map(|e| e.syntax().text_range())
862 == Some(name_ref.syntax().text_range()),
868 Some((path_ctx, pat_ctx))
872 fn pattern_context_for(original_file: &SyntaxNode, pat: ast::Pat) -> PatternContext {
873 let mut is_param = None;
874 let (refutability, has_type_ascription) =
878 .skip_while(|it| ast::Pat::can_cast(it.kind()))
880 .map_or((PatternRefutability::Irrefutable, false), |node| {
881 let refutability = match_ast! {
883 ast::LetStmt(let_) => return (PatternRefutability::Irrefutable, let_.ty().is_some()),
884 ast::Param(param) => {
885 let has_type_ascription = param.ty().is_some();
887 let fake_param_list = param.syntax().parent().and_then(ast::ParamList::cast)?;
888 let param_list = find_node_in_file_compensated(original_file, &fake_param_list)?;
889 let param_list_owner = param_list.syntax().parent()?;
890 let kind = match_ast! {
891 match param_list_owner {
892 ast::ClosureExpr(closure) => ParamKind::Closure(closure),
893 ast::Fn(fn_) => ParamKind::Function(fn_),
897 Some((param_list, param, kind))
899 return (PatternRefutability::Irrefutable, has_type_ascription)
901 ast::MatchArm(_) => PatternRefutability::Refutable,
902 ast::Condition(_) => PatternRefutability::Refutable,
903 ast::ForExpr(_) => PatternRefutability::Irrefutable,
904 _ => PatternRefutability::Irrefutable,
907 (refutability, false)
909 PatternContext { refutability, param_ctx: is_param, has_type_ascription }
912 fn find_node_in_file<N: AstNode>(syntax: &SyntaxNode, node: &N) -> Option<N> {
913 let syntax_range = syntax.text_range();
914 let range = node.syntax().text_range();
915 let intersection = range.intersect(syntax_range)?;
916 syntax.covering_element(intersection).ancestors().find_map(N::cast)
919 /// Compensates for the offset introduced by the fake ident
920 /// This is wrong if `node` comes before the insertion point! Use `find_node_in_file` instead.
921 fn find_node_in_file_compensated<N: AstNode>(syntax: &SyntaxNode, node: &N) -> Option<N> {
922 let syntax_range = syntax.text_range();
923 let range = node.syntax().text_range();
924 let end = range.end().checked_sub(TextSize::try_from(COMPLETION_MARKER.len()).ok()?)?;
925 if end < range.start() {
928 let range = TextRange::new(range.start(), end);
929 // our inserted ident could cause `range` to be go outside of the original syntax, so cap it
930 let intersection = range.intersect(syntax_range)?;
931 syntax.covering_element(intersection).ancestors().find_map(N::cast)
934 fn path_or_use_tree_qualifier(path: &ast::Path) -> Option<(ast::Path, bool)> {
935 if let Some(qual) = path.qualifier() {
936 return Some((qual, false));
938 let use_tree_list = path.syntax().ancestors().find_map(ast::UseTreeList::cast)?;
939 let use_tree = use_tree_list.syntax().parent().and_then(ast::UseTree::cast)?;
940 use_tree.path().zip(Some(true))
943 fn has_ref(token: &SyntaxToken) -> bool {
944 let mut token = token.clone();
945 for skip in [IDENT, WHITESPACE, T![mut]] {
946 if token.kind() == skip {
947 token = match token.prev_token() {
949 None => return false,
953 token.kind() == T![&]
956 const OP_TRAIT_LANG_NAMES: &[&str] = &[
990 use expect_test::{expect, Expect};
993 use crate::tests::{position, TEST_CONFIG};
995 use super::CompletionContext;
997 fn check_expected_type_and_name(ra_fixture: &str, expect: Expect) {
998 let (db, pos) = position(ra_fixture);
999 let config = TEST_CONFIG;
1000 let completion_context = CompletionContext::new(&db, pos, &config).unwrap();
1002 let ty = completion_context
1004 .map(|t| t.display_test(&db).to_string())
1005 .unwrap_or("?".to_owned());
1007 let name = completion_context
1009 .map_or_else(|| "?".to_owned(), |name| name.to_string());
1011 expect.assert_eq(&format!("ty: {}, name: {}", ty, name));
1015 fn expected_type_let_without_leading_char() {
1016 cov_mark::check!(expected_type_let_without_leading_char);
1017 check_expected_type_and_name(
1023 expect![[r#"ty: u32, name: x"#]],
1028 fn expected_type_let_with_leading_char() {
1029 cov_mark::check!(expected_type_let_with_leading_char);
1030 check_expected_type_and_name(
1036 expect![[r#"ty: u32, name: x"#]],
1041 fn expected_type_let_pat() {
1042 check_expected_type_and_name(
1048 expect![[r#"ty: u32, name: ?"#]],
1050 check_expected_type_and_name(
1056 expect![[r#"ty: u32, name: ?"#]],
1061 fn expected_type_fn_param() {
1062 cov_mark::check!(expected_type_fn_param);
1063 check_expected_type_and_name(
1065 fn foo() { bar($0); }
1068 expect![[r#"ty: u32, name: x"#]],
1070 check_expected_type_and_name(
1072 fn foo() { bar(c$0); }
1075 expect![[r#"ty: u32, name: x"#]],
1080 fn expected_type_fn_param_ref() {
1081 cov_mark::check!(expected_type_fn_param_ref);
1082 check_expected_type_and_name(
1084 fn foo() { bar(&$0); }
1087 expect![[r#"ty: u32, name: x"#]],
1089 check_expected_type_and_name(
1091 fn foo() { bar(&mut $0); }
1092 fn bar(x: &mut u32) {}
1094 expect![[r#"ty: u32, name: x"#]],
1096 check_expected_type_and_name(
1098 fn foo() { bar(& c$0); }
1101 expect![[r#"ty: u32, name: x"#]],
1103 check_expected_type_and_name(
1105 fn foo() { bar(&mut c$0); }
1106 fn bar(x: &mut u32) {}
1108 expect![[r#"ty: u32, name: x"#]],
1110 check_expected_type_and_name(
1112 fn foo() { bar(&c$0); }
1115 expect![[r#"ty: u32, name: x"#]],
1120 fn expected_type_struct_field_without_leading_char() {
1121 cov_mark::check!(expected_type_struct_field_without_leading_char);
1122 check_expected_type_and_name(
1124 struct Foo { a: u32 }
1129 expect![[r#"ty: u32, name: a"#]],
1134 fn expected_type_struct_field_followed_by_comma() {
1135 cov_mark::check!(expected_type_struct_field_followed_by_comma);
1136 check_expected_type_and_name(
1138 struct Foo { a: u32 }
1143 expect![[r#"ty: u32, name: a"#]],
1148 fn expected_type_generic_struct_field() {
1149 check_expected_type_and_name(
1151 struct Foo<T> { a: T }
1152 fn foo() -> Foo<u32> {
1156 expect![[r#"ty: u32, name: a"#]],
1161 fn expected_type_struct_field_with_leading_char() {
1162 cov_mark::check!(expected_type_struct_field_with_leading_char);
1163 check_expected_type_and_name(
1165 struct Foo { a: u32 }
1170 expect![[r#"ty: u32, name: a"#]],
1175 fn expected_type_match_arm_without_leading_char() {
1176 cov_mark::check!(expected_type_match_arm_without_leading_char);
1177 check_expected_type_and_name(
1184 expect![[r#"ty: E, name: ?"#]],
1189 fn expected_type_match_arm_with_leading_char() {
1190 cov_mark::check!(expected_type_match_arm_with_leading_char);
1191 check_expected_type_and_name(
1198 expect![[r#"ty: E, name: ?"#]],
1203 fn expected_type_if_let_without_leading_char() {
1204 cov_mark::check!(expected_type_if_let_without_leading_char);
1205 check_expected_type_and_name(
1207 enum Foo { Bar, Baz, Quux }
1214 expect![[r#"ty: Foo, name: ?"#]],
1219 fn expected_type_if_let_with_leading_char() {
1220 cov_mark::check!(expected_type_if_let_with_leading_char);
1221 check_expected_type_and_name(
1223 enum Foo { Bar, Baz, Quux }
1230 expect![[r#"ty: Foo, name: ?"#]],
1235 fn expected_type_fn_ret_without_leading_char() {
1236 cov_mark::check!(expected_type_fn_ret_without_leading_char);
1237 check_expected_type_and_name(
1243 expect![[r#"ty: u32, name: ?"#]],
1248 fn expected_type_fn_ret_with_leading_char() {
1249 cov_mark::check!(expected_type_fn_ret_with_leading_char);
1250 check_expected_type_and_name(
1256 expect![[r#"ty: u32, name: ?"#]],
1261 fn expected_type_fn_ret_fn_ref_fully_typed() {
1262 check_expected_type_and_name(
1268 expect![[r#"ty: u32, name: ?"#]],
1273 fn expected_type_closure_param_return() {
1274 // FIXME: make this work with `|| $0`
1275 check_expected_type_and_name(
1282 fn bar(f: impl FnOnce() -> u32) {}
1284 expect![[r#"ty: u32, name: ?"#]],
1289 fn expected_type_generic_function() {
1290 check_expected_type_and_name(
1298 expect![[r#"ty: u32, name: t"#]],
1303 fn expected_type_generic_method() {
1304 check_expected_type_and_name(
1312 fn bar(self, t: T) {}
1315 expect![[r#"ty: u32, name: t"#]],
1320 fn expected_type_functional_update() {
1321 cov_mark::check!(expected_type_struct_func_update);
1322 check_expected_type_and_name(
1324 struct Foo { field: u32 }
1331 expect![[r#"ty: Foo, name: ?"#]],
1336 fn expected_type_param_pat() {
1337 check_expected_type_and_name(
1339 struct Foo { field: u32 }
1342 expect![[r#"ty: Foo, name: ?"#]],
1344 check_expected_type_and_name(
1346 struct Foo { field: u32 }
1349 // FIXME make this work, currently fails due to pattern recovery eating the `:`
1350 expect![[r#"ty: ?, name: ?"#]],