1 //! See `CompletionContext` structure.
5 use base_db::SourceDatabaseExt;
7 HasAttrs, Local, Name, PathResolution, ScopeDef, Semantics, SemanticsScope, Type, TypeInfo,
10 active_parameter::ActiveParameter,
11 base_db::{FilePosition, SourceDatabase},
12 famous_defs::FamousDefs,
13 FxHashMap, FxHashSet, RootDatabase,
16 algo::{find_node_at_offset, non_trivia_sibling},
17 ast::{self, AttrKind, HasArgList, HasName, NameOrNameRef},
18 match_ast, AstNode, AstToken, NodeOrToken,
19 SyntaxKind::{self, *},
20 SyntaxNode, SyntaxToken, TextRange, TextSize, T,
26 determine_location, determine_prev_sibling, is_in_loop_body, is_in_token_of_for_loop,
27 previous_token, ImmediateLocation, ImmediatePrevSibling,
32 const COMPLETION_MARKER: &str = "intellijRulezz";
34 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
35 pub(crate) enum PatternRefutability {
40 pub(crate) enum Visible {
46 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
47 pub(super) enum PathKind {
55 annotated_item_kind: Option<SyntaxKind>,
58 /// Path in item position, that is inside an (Assoc)ItemList
69 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
70 pub(super) enum ItemListKind {
79 pub(crate) struct PathCompletionCtx {
80 /// If this is a call with () already there (or {} in case of record patterns)
81 pub(super) has_call_parens: bool,
82 /// If this has a macro call bang !
83 pub(super) has_macro_bang: bool,
84 /// Whether this path stars with a `::`.
85 pub(super) is_absolute_path: bool,
86 /// The qualifier of the current path if it exists.
87 pub(super) qualifier: Option<PathQualifierCtx>,
90 /// The parent of the path we are completing.
91 pub(super) parent: Option<ast::Path>,
92 pub(super) kind: PathKind,
93 /// Whether the path segment has type args or not.
94 pub(super) has_type_args: bool,
98 pub(crate) struct PathQualifierCtx {
99 pub(crate) path: ast::Path,
100 pub(crate) resolution: Option<PathResolution>,
101 /// Whether this path consists solely of `super` segments
102 pub(crate) is_super_chain: bool,
103 /// Whether the qualifier comes from a use tree parent or not
104 pub(crate) use_tree_parent: bool,
106 pub(crate) is_infer_qualifier: bool,
110 pub(super) struct PatternContext {
111 pub(super) refutability: PatternRefutability,
112 pub(super) param_ctx: Option<(ast::ParamList, ast::Param, ParamKind)>,
113 pub(super) has_type_ascription: bool,
114 pub(super) parent_pat: Option<ast::Pat>,
115 pub(super) ref_token: Option<SyntaxToken>,
116 pub(super) mut_token: Option<SyntaxToken>,
120 pub(super) struct LifetimeContext {
121 pub(super) lifetime: Option<ast::Lifetime>,
122 pub(super) kind: LifetimeKind,
126 pub(super) enum LifetimeKind {
127 LifetimeParam { is_decl: bool, param: ast::LifetimeParam },
134 pub(super) struct NameContext {
136 pub(super) name: Option<ast::Name>,
137 pub(super) kind: NameKind,
142 pub(super) enum NameKind {
165 pub(super) struct NameRefContext {
166 /// NameRef syntax in the original file
167 pub(super) nameref: Option<ast::NameRef>,
168 pub(super) dot_access: Option<DotAccess>,
169 pub(super) path_ctx: Option<PathCompletionCtx>,
173 pub(super) enum IdentContext {
175 NameRef(NameRefContext),
176 Lifetime(LifetimeContext),
177 /// Original token, fake token
179 original: ast::String,
180 expanded: Option<ast::String>,
183 fake_attribute_under_caret: Option<ast::Attr>,
188 pub(super) enum DotAccess {
190 receiver: Option<ast::Expr>,
191 /// True if the receiver is an integer and there is no ident in the original file after it yet
193 receiver_is_ambiguous_float_literal: bool,
196 receiver: Option<ast::Expr>,
201 #[derive(Clone, Debug, PartialEq, Eq)]
202 pub(crate) enum ParamKind {
204 Closure(ast::ClosureExpr),
207 /// `CompletionContext` is created early during completion to figure out, where
208 /// exactly is the cursor, syntax-wise.
210 pub(crate) struct CompletionContext<'a> {
211 pub(super) sema: Semantics<'a, RootDatabase>,
212 pub(super) scope: SemanticsScope<'a>,
213 pub(super) db: &'a RootDatabase,
214 pub(super) config: &'a CompletionConfig,
215 pub(super) position: FilePosition,
217 /// The token before the cursor, in the original file.
218 pub(super) original_token: SyntaxToken,
219 /// The token before the cursor, in the macro-expanded file.
220 pub(super) token: SyntaxToken,
221 /// The crate of the current file.
222 pub(super) krate: hir::Crate,
223 /// The module of the `scope`.
224 pub(super) module: hir::Module,
226 /// The expected name of what we are completing.
227 /// This is usually the parameter name of the function argument we are completing.
228 pub(super) expected_name: Option<NameOrNameRef>,
229 /// The expected type of what we are completing.
230 pub(super) expected_type: Option<Type>,
232 /// The parent function of the cursor position if it exists.
233 pub(super) function_def: Option<ast::Fn>,
234 /// The parent impl of the cursor position if it exists.
235 pub(super) impl_def: Option<ast::Impl>,
236 /// Are we completing inside a let statement with a missing semicolon?
237 pub(super) incomplete_let: bool,
239 pub(super) completion_location: Option<ImmediateLocation>,
240 pub(super) prev_sibling: Option<ImmediatePrevSibling>,
241 pub(super) previous_token: Option<SyntaxToken>,
243 pub(super) ident_ctx: IdentContext,
245 pub(super) pattern_ctx: Option<PatternContext>,
247 pub(super) existing_derives: FxHashSet<hir::Macro>,
249 pub(super) locals: FxHashMap<Name, Local>,
252 impl<'a> CompletionContext<'a> {
253 /// The range of the identifier that is being completed.
254 pub(crate) fn source_range(&self) -> TextRange {
255 // check kind of macro-expanded token, but use range of original token
256 let kind = self.token.kind();
259 // assume we are completing a lifetime but the user has only typed the '
260 cov_mark::hit!(completes_if_lifetime_without_idents);
261 TextRange::at(self.original_token.text_range().start(), TextSize::from(1))
263 IDENT | LIFETIME_IDENT | UNDERSCORE => self.original_token.text_range(),
264 _ if kind.is_keyword() => self.original_token.text_range(),
265 _ => TextRange::empty(self.position.offset),
269 pub(crate) fn previous_token_is(&self, kind: SyntaxKind) -> bool {
270 self.previous_token.as_ref().map_or(false, |tok| tok.kind() == kind)
273 pub(crate) fn famous_defs(&self) -> FamousDefs {
274 FamousDefs(&self.sema, self.krate)
277 pub(super) fn nameref_ctx(&self) -> Option<&NameRefContext> {
278 match &self.ident_ctx {
279 IdentContext::NameRef(it) => Some(it),
284 pub(super) fn name_ctx(&self) -> Option<&NameContext> {
285 match &self.ident_ctx {
286 IdentContext::Name(it) => Some(it),
291 pub(super) fn lifetime_ctx(&self) -> Option<&LifetimeContext> {
292 match &self.ident_ctx {
293 IdentContext::Lifetime(it) => Some(it),
298 pub(crate) fn dot_receiver(&self) -> Option<&ast::Expr> {
299 match self.nameref_ctx() {
300 Some(NameRefContext {
302 Some(DotAccess::Method { receiver, .. } | DotAccess::Field { receiver, .. }),
304 }) => receiver.as_ref(),
309 pub(crate) fn has_dot_receiver(&self) -> bool {
310 self.dot_receiver().is_some()
313 pub(crate) fn expects_assoc_item(&self) -> bool {
314 matches!(self.completion_location, Some(ImmediateLocation::Trait | ImmediateLocation::Impl))
317 pub(crate) fn expects_variant(&self) -> bool {
318 matches!(self.name_ctx(), Some(NameContext { kind: NameKind::Variant, .. }))
321 pub(crate) fn expects_non_trait_assoc_item(&self) -> bool {
322 matches!(self.completion_location, Some(ImmediateLocation::Impl))
325 pub(crate) fn expects_item(&self) -> bool {
326 matches!(self.completion_location, Some(ImmediateLocation::ItemList))
329 pub(crate) fn expects_generic_arg(&self) -> bool {
330 matches!(self.completion_location, Some(ImmediateLocation::GenericArgList(_)))
333 pub(crate) fn has_block_expr_parent(&self) -> bool {
334 matches!(self.completion_location, Some(ImmediateLocation::StmtList))
337 pub(crate) fn expects_ident_ref_expr(&self) -> bool {
338 matches!(self.completion_location, Some(ImmediateLocation::RefExpr))
341 pub(crate) fn expect_field(&self) -> bool {
342 matches!(self.completion_location, Some(ImmediateLocation::TupleField))
343 || matches!(self.name_ctx(), Some(NameContext { kind: NameKind::RecordField, .. }))
346 /// Whether the cursor is right after a trait or impl header.
347 /// trait Foo ident$0
348 // FIXME: This probably shouldn't exist
349 pub(crate) fn has_unfinished_impl_or_trait_prev_sibling(&self) -> bool {
352 Some(ImmediatePrevSibling::ImplDefType | ImmediatePrevSibling::TraitDefName)
356 // FIXME: This probably shouldn't exist
357 pub(crate) fn has_impl_prev_sibling(&self) -> bool {
358 matches!(self.prev_sibling, Some(ImmediatePrevSibling::ImplDefType))
361 pub(crate) fn has_visibility_prev_sibling(&self) -> bool {
362 matches!(self.prev_sibling, Some(ImmediatePrevSibling::Visibility))
365 pub(crate) fn after_if(&self) -> bool {
366 matches!(self.prev_sibling, Some(ImmediatePrevSibling::IfExpr))
369 // FIXME: This shouldn't exist
370 pub(crate) fn is_path_disallowed(&self) -> bool {
371 self.previous_token_is(T![unsafe])
374 Some(ImmediatePrevSibling::Attribute | ImmediatePrevSibling::Visibility)
377 self.completion_location,
378 Some(ImmediateLocation::RecordPat(_) | ImmediateLocation::RecordExpr(_))
382 Some(NameContext { kind: NameKind::Module(_) | NameKind::Rename, .. })
386 pub(crate) fn path_context(&self) -> Option<&PathCompletionCtx> {
387 self.nameref_ctx().and_then(|ctx| ctx.path_ctx.as_ref())
390 pub(crate) fn expects_expression(&self) -> bool {
391 matches!(self.path_context(), Some(PathCompletionCtx { kind: PathKind::Expr { .. }, .. }))
394 pub(crate) fn expects_type(&self) -> bool {
395 matches!(self.path_context(), Some(PathCompletionCtx { kind: PathKind::Type, .. }))
398 pub(crate) fn path_is_call(&self) -> bool {
399 self.path_context().map_or(false, |it| it.has_call_parens)
402 pub(crate) fn is_non_trivial_path(&self) -> bool {
406 PathCompletionCtx { is_absolute_path: true, .. }
407 | PathCompletionCtx { qualifier: Some(_), .. }
412 pub(crate) fn path_qual(&self) -> Option<&ast::Path> {
413 self.path_context().and_then(|it| it.qualifier.as_ref().map(|it| &it.path))
416 pub(crate) fn path_kind(&self) -> Option<PathKind> {
417 self.path_context().map(|it| it.kind)
420 pub(crate) fn is_immediately_after_macro_bang(&self) -> bool {
421 self.token.kind() == BANG && self.token.parent().map_or(false, |it| it.kind() == MACRO_CALL)
424 /// Checks if an item is visible and not `doc(hidden)` at the completion site.
425 pub(crate) fn is_visible<I>(&self, item: &I) -> Visible
427 I: hir::HasVisibility + hir::HasAttrs + hir::HasCrate + Copy,
429 self.is_visible_impl(&item.visibility(self.db), &item.attrs(self.db), item.krate(self.db))
432 pub(crate) fn is_scope_def_hidden(&self, scope_def: ScopeDef) -> bool {
433 if let (Some(attrs), Some(krate)) = (scope_def.attrs(self.db), scope_def.krate(self.db)) {
434 return self.is_doc_hidden(&attrs, krate);
440 /// Check if an item is `#[doc(hidden)]`.
441 pub(crate) fn is_item_hidden(&self, item: &hir::ItemInNs) -> bool {
442 let attrs = item.attrs(self.db);
443 let krate = item.krate(self.db);
444 match (attrs, krate) {
445 (Some(attrs), Some(krate)) => self.is_doc_hidden(&attrs, krate),
449 /// Whether the given trait is an operator trait or not.
450 pub(crate) fn is_ops_trait(&self, trait_: hir::Trait) -> bool {
451 match trait_.attrs(self.db).lang() {
452 Some(lang) => OP_TRAIT_LANG_NAMES.contains(&lang.as_str()),
457 /// Returns the traits in scope, with the [`Drop`] trait removed.
458 pub(crate) fn traits_in_scope(&self) -> hir::VisibleTraits {
459 let mut traits_in_scope = self.scope.visible_traits();
460 if let Some(drop) = self.famous_defs().core_ops_Drop() {
461 traits_in_scope.0.remove(&drop.into());
466 /// A version of [`SemanticsScope::process_all_names`] that filters out `#[doc(hidden)]` items.
467 pub(crate) fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
468 let _p = profile::span("CompletionContext::process_all_names");
469 self.scope.process_all_names(&mut |name, def| {
470 if self.is_scope_def_hidden(def) {
478 pub(crate) fn process_all_names_raw(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
479 let _p = profile::span("CompletionContext::process_all_names_raw");
480 self.scope.process_all_names(&mut |name, def| f(name, def));
485 vis: &hir::Visibility,
487 defining_crate: hir::Crate,
489 if !vis.is_visible_from(self.db, self.module.into()) {
490 if !self.config.enable_private_editable {
493 // If the definition location is editable, also show private items
494 let root_file = defining_crate.root_file(self.db);
495 let source_root_id = self.db.file_source_root(root_file);
496 let is_editable = !self.db.source_root(source_root_id).is_library;
497 return if is_editable { Visible::Editable } else { Visible::No };
500 if self.is_doc_hidden(attrs, defining_crate) {
507 fn is_doc_hidden(&self, attrs: &hir::Attrs, defining_crate: hir::Crate) -> bool {
508 // `doc(hidden)` items are only completed within the defining crate.
509 self.krate != defining_crate && attrs.has_doc_hidden()
513 // CompletionContext construction
514 impl<'a> CompletionContext<'a> {
516 db: &'a RootDatabase,
517 position @ FilePosition { file_id, offset }: FilePosition,
518 config: &'a CompletionConfig,
519 ) -> Option<CompletionContext<'a>> {
520 let _p = profile::span("CompletionContext::new");
521 let sema = Semantics::new(db);
523 let original_file = sema.parse(file_id);
525 // Insert a fake ident to get a valid parse tree. We will use this file
526 // to determine context, though the original_file will be used for
527 // actual completion.
528 let file_with_fake_ident = {
529 let parse = db.parse(file_id);
530 let edit = Indel::insert(offset, COMPLETION_MARKER.to_string());
531 parse.reparse(&edit).tree()
533 let fake_ident_token =
534 file_with_fake_ident.syntax().token_at_offset(offset).right_biased()?;
536 let original_token = original_file.syntax().token_at_offset(offset).left_biased()?;
537 let token = sema.descend_into_macros_single(original_token.clone());
538 let scope = sema.scope_at_offset(&token.parent()?, offset)?;
539 let krate = scope.krate();
540 let module = scope.module();
542 let mut locals = FxHashMap::default();
543 scope.process_all_names(&mut |name, scope| {
544 if let ScopeDef::Local(local) = scope {
545 locals.insert(name, local);
549 let mut ctx = CompletionContext {
563 incomplete_let: false,
564 completion_location: None,
566 previous_token: None,
567 // dummy value, will be overwritten
568 ident_ctx: IdentContext::UnexpandedAttrTT { fake_attribute_under_caret: None },
570 existing_derives: Default::default(),
574 original_file.syntax().clone(),
575 file_with_fake_ident.syntax().clone(),
582 /// Expand attributes and macro calls at the current cursor position for both the original file
583 /// and fake file repeatedly. As soon as one of the two expansions fail we stop so the original
584 /// and speculative states stay in sync.
587 mut original_file: SyntaxNode,
588 mut speculative_file: SyntaxNode,
589 mut offset: TextSize,
590 mut fake_ident_token: SyntaxToken,
592 let _p = profile::span("CompletionContext::expand_and_fill");
593 let mut derive_ctx = None;
597 |item: &ast::Item| item.syntax().ancestors().skip(1).find_map(ast::Item::cast);
598 let ancestor_items = iter::successors(
600 find_node_at_offset::<ast::Item>(&original_file, offset),
601 find_node_at_offset::<ast::Item>(&speculative_file, offset),
603 |(a, b)| parent_item(a).zip(parent_item(b)),
606 // first try to expand attributes as these are always the outermost macro calls
607 'ancestors: for (actual_item, item_with_fake_ident) in ancestor_items {
609 self.sema.expand_attr_macro(&actual_item),
610 self.sema.speculative_expand_attr_macro(
612 &item_with_fake_ident,
613 fake_ident_token.clone(),
616 // maybe parent items have attributes, so continue walking the ancestors
617 (None, None) => continue 'ancestors,
618 // successful expansions
619 (Some(actual_expansion), Some((fake_expansion, fake_mapped_token))) => {
620 let new_offset = fake_mapped_token.text_range().start();
621 if new_offset > actual_expansion.text_range().end() {
622 // offset outside of bounds from the original expansion,
623 // stop here to prevent problems from happening
626 original_file = actual_expansion;
627 speculative_file = fake_expansion;
628 fake_ident_token = fake_mapped_token;
632 // exactly one expansion failed, inconsistent state so stop expanding completely
633 _ => break 'expansion,
637 // No attributes have been expanded, so look for macro_call! token trees or derive token trees
638 let orig_tt = match find_node_at_offset::<ast::TokenTree>(&original_file, offset) {
640 None => break 'expansion,
642 let spec_tt = match find_node_at_offset::<ast::TokenTree>(&speculative_file, offset) {
644 None => break 'expansion,
647 // Expand pseudo-derive expansion
648 if let (Some(orig_attr), Some(spec_attr)) = (
649 orig_tt.syntax().parent().and_then(ast::Meta::cast).and_then(|it| it.parent_attr()),
650 spec_tt.syntax().parent().and_then(ast::Meta::cast).and_then(|it| it.parent_attr()),
652 if let (Some(actual_expansion), Some((fake_expansion, fake_mapped_token))) = (
653 self.sema.expand_derive_as_pseudo_attr_macro(&orig_attr),
654 self.sema.speculative_expand_derive_as_pseudo_attr_macro(
657 fake_ident_token.clone(),
663 fake_mapped_token.text_range().start(),
667 // at this point we won't have any more successful expansions, so stop
671 // Expand fn-like macro calls
672 if let (Some(actual_macro_call), Some(macro_call_with_fake_ident)) = (
673 orig_tt.syntax().ancestors().find_map(ast::MacroCall::cast),
674 spec_tt.syntax().ancestors().find_map(ast::MacroCall::cast),
676 let mac_call_path0 = actual_macro_call.path().as_ref().map(|s| s.syntax().text());
678 macro_call_with_fake_ident.path().as_ref().map(|s| s.syntax().text());
680 // inconsistent state, stop expanding
681 if mac_call_path0 != mac_call_path1 {
684 let speculative_args = match macro_call_with_fake_ident.token_tree() {
686 None => break 'expansion,
690 self.sema.expand(&actual_macro_call),
691 self.sema.speculative_expand(
694 fake_ident_token.clone(),
697 // successful expansions
698 (Some(actual_expansion), Some((fake_expansion, fake_mapped_token))) => {
699 let new_offset = fake_mapped_token.text_range().start();
700 if new_offset > actual_expansion.text_range().end() {
701 // offset outside of bounds from the original expansion,
702 // stop here to prevent problems from happening
705 original_file = actual_expansion;
706 speculative_file = fake_expansion;
707 fake_ident_token = fake_mapped_token;
711 // at least on expansion failed, we won't have anything to expand from this point
712 // onwards so break out
713 _ => break 'expansion,
717 // none of our states have changed so stop the loop
721 self.fill(&original_file, speculative_file, offset, derive_ctx)
724 /// Calculate the expected type and name of the cursor position.
725 fn expected_type_and_name(&self) -> (Option<Type>, Option<NameOrNameRef>) {
726 let mut node = match self.token.parent() {
728 None => return (None, None),
733 ast::LetStmt(it) => {
734 cov_mark::hit!(expected_type_let_with_leading_char);
735 cov_mark::hit!(expected_type_let_without_leading_char);
737 .and_then(|pat| self.sema.type_of_pat(&pat))
738 .or_else(|| it.initializer().and_then(|it| self.sema.type_of_expr(&it)))
739 .map(TypeInfo::original);
740 let name = match it.pat() {
741 Some(ast::Pat::IdentPat(ident)) => ident.name().map(NameOrNameRef::Name),
742 Some(_) | None => None,
747 ast::LetExpr(it) => {
748 cov_mark::hit!(expected_type_if_let_without_leading_char);
750 .and_then(|pat| self.sema.type_of_pat(&pat))
751 .or_else(|| it.expr().and_then(|it| self.sema.type_of_expr(&it)))
752 .map(TypeInfo::original);
756 cov_mark::hit!(expected_type_fn_param);
757 ActiveParameter::at_token(
761 let name = ap.ident().map(NameOrNameRef::Name);
762 let ty = if has_ref(&self.token) {
763 cov_mark::hit!(expected_type_fn_param_ref);
770 .unwrap_or((None, None))
772 ast::RecordExprFieldList(it) => {
773 // wouldn't try {} be nice...
775 if self.token.kind() == T![..]
776 || self.token.prev_token().map(|t| t.kind()) == Some(T![..])
778 cov_mark::hit!(expected_type_struct_func_update);
779 let record_expr = it.syntax().parent().and_then(ast::RecordExpr::cast)?;
780 let ty = self.sema.type_of_expr(&record_expr.into())?;
786 cov_mark::hit!(expected_type_struct_field_without_leading_char);
787 let expr_field = self.token.prev_sibling_or_token()?
789 .and_then(ast::RecordExprField::cast)?;
790 let (_, _, ty) = self.sema.resolve_record_field(&expr_field)?;
793 expr_field.field_name().map(NameOrNameRef::NameRef),
796 })().unwrap_or((None, None))
798 ast::RecordExprField(it) => {
799 if let Some(expr) = it.expr() {
800 cov_mark::hit!(expected_type_struct_field_with_leading_char);
802 self.sema.type_of_expr(&expr).map(TypeInfo::original),
803 it.field_name().map(NameOrNameRef::NameRef),
806 cov_mark::hit!(expected_type_struct_field_followed_by_comma);
807 let ty = self.sema.resolve_record_field(&it)
808 .map(|(_, _, ty)| ty);
811 it.field_name().map(NameOrNameRef::NameRef),
815 ast::MatchExpr(it) => {
816 cov_mark::hit!(expected_type_match_arm_without_leading_char);
817 let ty = it.expr().and_then(|e| self.sema.type_of_expr(&e)).map(TypeInfo::original);
821 let ty = it.condition()
822 .and_then(|e| self.sema.type_of_expr(&e))
823 .map(TypeInfo::original);
826 ast::IdentPat(it) => {
827 cov_mark::hit!(expected_type_if_let_with_leading_char);
828 cov_mark::hit!(expected_type_match_arm_with_leading_char);
829 let ty = self.sema.type_of_pat(&ast::Pat::from(it)).map(TypeInfo::original);
833 cov_mark::hit!(expected_type_fn_ret_with_leading_char);
834 cov_mark::hit!(expected_type_fn_ret_without_leading_char);
835 let def = self.sema.to_def(&it);
836 (def.map(|def| def.ret_type(self.db)), None)
838 ast::ClosureExpr(it) => {
839 let ty = self.sema.type_of_expr(&it.into());
840 ty.and_then(|ty| ty.original.as_callable(self.db))
841 .map(|c| (Some(c.return_type()), None))
842 .unwrap_or((None, None))
844 ast::ParamList(_) => (None, None),
845 ast::Stmt(_) => (None, None),
846 ast::Item(_) => (None, None),
848 match node.parent() {
853 None => (None, None),
861 /// Fill the completion context, this is what does semantic reasoning about the surrounding context
862 /// of the completion location.
865 original_file: &SyntaxNode,
866 file_with_fake_ident: SyntaxNode,
868 derive_ctx: Option<(SyntaxNode, SyntaxNode, TextSize, ast::Attr)>,
870 let fake_ident_token = file_with_fake_ident.token_at_offset(offset).right_biased().unwrap();
871 let syntax_element = NodeOrToken::Token(fake_ident_token);
872 if is_in_token_of_for_loop(syntax_element.clone()) {
874 // there is nothing to complete here except `in` keyword
875 // don't bother populating the context
876 // FIXME: the completion calculations should end up good enough
877 // such that this special case becomes unnecessary
881 self.previous_token = previous_token(syntax_element.clone());
883 self.incomplete_let =
884 syntax_element.ancestors().take(6).find_map(ast::LetStmt::cast).map_or(false, |it| {
885 it.syntax().text_range().end() == syntax_element.text_range().end()
888 (self.expected_type, self.expected_name) = self.expected_type_and_name();
890 // Overwrite the path kind for derives
891 if let Some((original_file, file_with_fake_ident, offset, origin_attr)) = derive_ctx {
892 self.existing_derives = self
894 .resolve_derive_macro(&origin_attr)
900 if let Some(ast::NameLike::NameRef(name_ref)) =
901 find_node_at_offset(&file_with_fake_ident, offset)
903 let parent = name_ref.syntax().parent()?;
904 let (mut nameref_ctx, _) =
905 Self::classify_name_ref(&self.sema, &original_file, name_ref, parent);
906 if let Some(path_ctx) = &mut nameref_ctx.path_ctx {
907 path_ctx.kind = PathKind::Derive;
909 self.ident_ctx = IdentContext::NameRef(nameref_ctx);
915 let name_like = match find_node_at_offset(&file_with_fake_ident, offset) {
918 if let Some(original) = ast::String::cast(self.original_token.clone()) {
919 self.ident_ctx = IdentContext::String {
921 expanded: ast::String::cast(self.token.clone()),
924 // Fix up trailing whitespace problem
926 let token = if self.token.kind() == SyntaxKind::WHITESPACE {
927 self.previous_token.as_ref()?
931 let p = token.parent()?;
932 if p.kind() == SyntaxKind::TOKEN_TREE
933 && p.ancestors().any(|it| it.kind() == SyntaxKind::META)
935 self.ident_ctx = IdentContext::UnexpandedAttrTT {
936 fake_attribute_under_caret: syntax_element
938 .find_map(ast::Attr::cast),
947 self.completion_location =
948 determine_location(&self.sema, original_file, offset, &name_like);
949 self.prev_sibling = determine_prev_sibling(&name_like);
952 .token_ancestors_with_macros(self.token.clone())
953 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
954 .find_map(ast::Impl::cast);
955 self.function_def = self
957 .token_ancestors_with_macros(self.token.clone())
958 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
959 .find_map(ast::Fn::cast);
962 ast::NameLike::Lifetime(lifetime) => {
963 self.ident_ctx = IdentContext::Lifetime(Self::classify_lifetime(
969 ast::NameLike::NameRef(name_ref) => {
970 let parent = name_ref.syntax().parent()?;
971 let (nameref_ctx, pat_ctx) =
972 Self::classify_name_ref(&self.sema, &original_file, name_ref, parent);
973 self.ident_ctx = IdentContext::NameRef(nameref_ctx);
974 self.pattern_ctx = pat_ctx;
976 ast::NameLike::Name(name) => {
977 let (name_ctx, pat_ctx) = Self::classify_name(&self.sema, original_file, name)?;
978 self.pattern_ctx = pat_ctx;
979 self.ident_ctx = IdentContext::Name(name_ctx);
985 fn classify_lifetime(
986 _sema: &Semantics<RootDatabase>,
987 original_file: &SyntaxNode,
988 lifetime: ast::Lifetime,
989 ) -> Option<LifetimeContext> {
990 let parent = lifetime.syntax().parent()?;
991 if parent.kind() == ERROR {
995 let kind = match_ast! {
997 ast::LifetimeParam(param) => LifetimeKind::LifetimeParam {
998 is_decl: param.lifetime().as_ref() == Some(&lifetime),
1001 ast::BreakExpr(_) => LifetimeKind::LabelRef,
1002 ast::ContinueExpr(_) => LifetimeKind::LabelRef,
1003 ast::Label(_) => LifetimeKind::LabelDef,
1004 _ => LifetimeKind::Lifetime,
1007 let lifetime = find_node_at_offset(&original_file, lifetime.syntax().text_range().start());
1009 Some(LifetimeContext { lifetime, kind })
1013 _sema: &Semantics<RootDatabase>,
1014 original_file: &SyntaxNode,
1016 ) -> Option<(NameContext, Option<PatternContext>)> {
1017 let parent = name.syntax().parent()?;
1018 let mut pat_ctx = None;
1019 let kind = match_ast! {
1021 ast::Const(_) => NameKind::Const,
1022 ast::ConstParam(_) => NameKind::ConstParam,
1023 ast::Enum(_) => NameKind::Enum,
1024 ast::Fn(_) => NameKind::Function,
1025 ast::IdentPat(bind_pat) => {
1026 let is_name_in_field_pat = bind_pat
1029 .and_then(ast::RecordPatField::cast)
1030 .map_or(false, |pat_field| pat_field.name_ref().is_none());
1031 if !is_name_in_field_pat {
1032 pat_ctx = Some(pattern_context_for(original_file, bind_pat.into()));
1037 ast::MacroDef(_) => NameKind::MacroDef,
1038 ast::MacroRules(_) => NameKind::MacroRules,
1039 ast::Module(module) => NameKind::Module(module),
1040 ast::RecordField(_) => NameKind::RecordField,
1041 ast::Rename(_) => NameKind::Rename,
1042 ast::SelfParam(_) => NameKind::SelfParam,
1043 ast::Static(_) => NameKind::Static,
1044 ast::Struct(_) => NameKind::Struct,
1045 ast::Trait(_) => NameKind::Trait,
1046 ast::TypeAlias(_) => NameKind::TypeAlias,
1047 ast::TypeParam(_) => NameKind::TypeParam,
1048 ast::Union(_) => NameKind::Union,
1049 ast::Variant(_) => NameKind::Variant,
1053 let name = find_node_at_offset(&original_file, name.syntax().text_range().start());
1054 Some((NameContext { name, kind }, pat_ctx))
1057 fn classify_name_ref(
1058 sema: &Semantics<RootDatabase>,
1059 original_file: &SyntaxNode,
1060 name_ref: ast::NameRef,
1062 ) -> (NameRefContext, Option<PatternContext>) {
1063 let nameref = find_node_at_offset(&original_file, name_ref.syntax().text_range().start());
1065 let mut nameref_ctx = NameRefContext { dot_access: None, path_ctx: None, nameref };
1067 let segment = match_ast! {
1069 ast::PathSegment(segment) => segment,
1070 ast::FieldExpr(field) => {
1071 let receiver = find_in_original_file(field.expr(), original_file);
1072 let receiver_is_ambiguous_float_literal = match &receiver {
1073 Some(ast::Expr::Literal(l)) => matches! {
1075 ast::LiteralKind::FloatNumber { .. } if l.syntax().last_token().map_or(false, |it| it.kind() == T![.])
1079 nameref_ctx.dot_access = Some(DotAccess::Field { receiver, receiver_is_ambiguous_float_literal });
1080 return (nameref_ctx, None);
1082 ast::MethodCallExpr(method) => {
1083 nameref_ctx.dot_access = Some(
1085 receiver: find_in_original_file(method.receiver(), original_file),
1086 has_parens: method.arg_list().map_or(false, |it| it.l_paren_token().is_some())
1089 return (nameref_ctx, None);
1091 _ => return (nameref_ctx, None),
1095 let path = segment.parent_path();
1096 let mut path_ctx = PathCompletionCtx {
1097 has_call_parens: false,
1098 has_macro_bang: false,
1099 is_absolute_path: false,
1101 parent: path.parent_path(),
1102 kind: PathKind::Item { kind: ItemListKind::SourceFile },
1103 has_type_args: false,
1105 let mut pat_ctx = None;
1107 let is_in_block = |it: &SyntaxNode| {
1110 ast::ExprStmt::can_cast(node.kind()) || ast::StmtList::can_cast(node.kind())
1115 let kind = path.syntax().ancestors().find_map(|it| {
1116 // using Option<Option<PathKind>> as extra controlflow
1117 let kind = match_ast! {
1119 ast::PathType(_) => Some(PathKind::Type),
1120 ast::PathExpr(it) => {
1121 path_ctx.has_call_parens = it.syntax().parent().map_or(false, |it| ast::CallExpr::can_cast(it.kind()));
1122 let in_block_expr = is_in_block(it.syntax());
1123 let in_loop_body = is_in_loop_body(it.syntax());
1125 Some(PathKind::Expr { in_block_expr, in_loop_body })
1127 ast::TupleStructPat(it) => {
1128 path_ctx.has_call_parens = true;
1129 pat_ctx = Some(pattern_context_for(original_file, it.into()));
1132 ast::RecordPat(it) => {
1133 path_ctx.has_call_parens = true;
1134 pat_ctx = Some(pattern_context_for(original_file, it.into()));
1137 ast::PathPat(it) => {
1138 pat_ctx = Some(pattern_context_for(original_file, it.into()));
1141 ast::MacroCall(it) => {
1142 path_ctx.has_macro_bang = it.excl_token().is_some();
1143 let parent = it.syntax().parent();
1144 match parent.as_ref().map(|it| it.kind()) {
1145 Some(SyntaxKind::MACRO_PAT) => Some(PathKind::Pat),
1146 Some(SyntaxKind::MACRO_TYPE) => Some(PathKind::Type),
1147 Some(SyntaxKind::ITEM_LIST) => Some(PathKind::Item { kind: ItemListKind::Module }),
1148 Some(SyntaxKind::ASSOC_ITEM_LIST) => Some(PathKind::Item { kind: match parent.and_then(|it| it.parent()).map(|it| it.kind()) {
1149 Some(SyntaxKind::TRAIT) => ItemListKind::Trait,
1150 Some(SyntaxKind::IMPL) => ItemListKind::Impl,
1151 _ => return Some(None),
1153 Some(SyntaxKind::EXTERN_ITEM_LIST) => Some(PathKind::Item { kind: ItemListKind::ExternBlock }),
1154 Some(SyntaxKind::SOURCE_FILE) => Some(PathKind::Item { kind: ItemListKind::SourceFile }),
1156 return Some(parent.and_then(ast::MacroExpr::cast).map(|it| {
1157 let in_loop_body = is_in_loop_body(it.syntax());
1158 let in_block_expr = is_in_block(it.syntax());
1159 PathKind::Expr { in_block_expr, in_loop_body }
1164 ast::Meta(meta) => (|| {
1165 let attr = meta.parent_attr()?;
1166 let kind = attr.kind();
1167 let attached = attr.syntax().parent()?;
1168 let is_trailing_outer_attr = kind != AttrKind::Inner
1169 && non_trivia_sibling(attr.syntax().clone().into(), syntax::Direction::Next).is_none();
1170 let annotated_item_kind = if is_trailing_outer_attr {
1173 Some(attached.kind())
1175 Some(PathKind::Attr {
1177 annotated_item_kind,
1180 ast::Visibility(it) => Some(PathKind::Vis { has_in_token: it.in_token().is_some() }),
1181 ast::UseTree(_) => Some(PathKind::Use),
1182 ast::ItemList(_) => Some(PathKind::Item { kind: ItemListKind::Module }),
1183 ast::AssocItemList(it) => Some(PathKind::Item { kind: {
1184 match it.syntax().parent()?.kind() {
1185 SyntaxKind::TRAIT => ItemListKind::Trait,
1186 SyntaxKind::IMPL => ItemListKind::Impl,
1190 ast::ExternItemList(_) => Some(PathKind::Item { kind: ItemListKind::ExternBlock }),
1191 ast::SourceFile(_) => Some(PathKind::Item { kind: ItemListKind::SourceFile }),
1198 Some(kind) => path_ctx.kind = kind,
1199 None => return (nameref_ctx, pat_ctx),
1201 path_ctx.has_type_args = segment.generic_arg_list().is_some();
1203 if let Some((path, use_tree_parent)) = path_or_use_tree_qualifier(&path) {
1204 if !use_tree_parent {
1205 path_ctx.is_absolute_path =
1206 path.top_path().segment().map_or(false, |it| it.coloncolon_token().is_some());
1211 .and_then(|it| find_node_in_file(original_file, &it))
1212 .map(|it| it.parent_path());
1213 path_ctx.qualifier = path.map(|path| {
1214 let res = sema.resolve_path(&path);
1215 let is_super_chain = iter::successors(Some(path.clone()), |p| p.qualifier())
1216 .all(|p| p.segment().and_then(|s| s.super_token()).is_some());
1219 let is_infer_qualifier = path.qualifier().is_none()
1221 path.segment().and_then(|it| it.kind()),
1222 Some(ast::PathSegmentKind::Type {
1223 type_ref: Some(ast::Type::InferType(_)),
1236 } else if let Some(segment) = path.segment() {
1237 if segment.coloncolon_token().is_some() {
1238 path_ctx.is_absolute_path = true;
1241 nameref_ctx.path_ctx = Some(path_ctx);
1242 (nameref_ctx, pat_ctx)
1246 fn pattern_context_for(original_file: &SyntaxNode, pat: ast::Pat) -> PatternContext {
1247 let mut is_param = None;
1248 let (refutability, has_type_ascription) =
1252 .skip_while(|it| ast::Pat::can_cast(it.kind()))
1254 .map_or((PatternRefutability::Irrefutable, false), |node| {
1255 let refutability = match_ast! {
1257 ast::LetStmt(let_) => return (PatternRefutability::Irrefutable, let_.ty().is_some()),
1258 ast::Param(param) => {
1259 let has_type_ascription = param.ty().is_some();
1261 let fake_param_list = param.syntax().parent().and_then(ast::ParamList::cast)?;
1262 let param_list = find_node_in_file_compensated(original_file, &fake_param_list)?;
1263 let param_list_owner = param_list.syntax().parent()?;
1264 let kind = match_ast! {
1265 match param_list_owner {
1266 ast::ClosureExpr(closure) => ParamKind::Closure(closure),
1267 ast::Fn(fn_) => ParamKind::Function(fn_),
1271 Some((param_list, param, kind))
1273 return (PatternRefutability::Irrefutable, has_type_ascription)
1275 ast::MatchArm(_) => PatternRefutability::Refutable,
1276 ast::LetExpr(_) => PatternRefutability::Refutable,
1277 ast::ForExpr(_) => PatternRefutability::Irrefutable,
1278 _ => PatternRefutability::Irrefutable,
1281 (refutability, false)
1283 let (ref_token, mut_token) = match &pat {
1284 ast::Pat::IdentPat(it) => (it.ref_token(), it.mut_token()),
1289 param_ctx: is_param,
1290 has_type_ascription,
1291 parent_pat: pat.syntax().parent().and_then(ast::Pat::cast),
1297 fn find_in_original_file<N: AstNode>(x: Option<N>, original_file: &SyntaxNode) -> Option<N> {
1298 fn find_node_with_range<N: AstNode>(syntax: &SyntaxNode, range: TextRange) -> Option<N> {
1299 let range = syntax.text_range().intersect(range)?;
1300 syntax.covering_element(range).ancestors().find_map(N::cast)
1302 x.map(|e| e.syntax().text_range()).and_then(|r| find_node_with_range(original_file, r))
1305 /// Attempts to find `node` inside `syntax` via `node`'s text range.
1306 fn find_node_in_file<N: AstNode>(syntax: &SyntaxNode, node: &N) -> Option<N> {
1307 let syntax_range = syntax.text_range();
1308 let range = node.syntax().text_range();
1309 let intersection = range.intersect(syntax_range)?;
1310 syntax.covering_element(intersection).ancestors().find_map(N::cast)
1313 /// Attempts to find `node` inside `syntax` via `node`'s text range while compensating
1314 /// for the offset introduced by the fake ident.
1315 /// This is wrong if `node` comes before the insertion point! Use `find_node_in_file` instead.
1316 fn find_node_in_file_compensated<N: AstNode>(syntax: &SyntaxNode, node: &N) -> Option<N> {
1317 let syntax_range = syntax.text_range();
1318 let range = node.syntax().text_range();
1319 let end = range.end().checked_sub(TextSize::try_from(COMPLETION_MARKER.len()).ok()?)?;
1320 if end < range.start() {
1323 let range = TextRange::new(range.start(), end);
1324 // our inserted ident could cause `range` to be go outside of the original syntax, so cap it
1325 let intersection = range.intersect(syntax_range)?;
1326 syntax.covering_element(intersection).ancestors().find_map(N::cast)
1329 fn path_or_use_tree_qualifier(path: &ast::Path) -> Option<(ast::Path, bool)> {
1330 if let Some(qual) = path.qualifier() {
1331 return Some((qual, false));
1333 let use_tree_list = path.syntax().ancestors().find_map(ast::UseTreeList::cast)?;
1334 let use_tree = use_tree_list.syntax().parent().and_then(ast::UseTree::cast)?;
1335 Some((use_tree.path()?, true))
1338 fn has_ref(token: &SyntaxToken) -> bool {
1339 let mut token = token.clone();
1340 for skip in [IDENT, WHITESPACE, T![mut]] {
1341 if token.kind() == skip {
1342 token = match token.prev_token() {
1344 None => return false,
1348 token.kind() == T![&]
1351 const OP_TRAIT_LANG_NAMES: &[&str] = &[
1386 use expect_test::{expect, Expect};
1387 use hir::HirDisplay;
1389 use crate::tests::{position, TEST_CONFIG};
1391 use super::CompletionContext;
1393 fn check_expected_type_and_name(ra_fixture: &str, expect: Expect) {
1394 let (db, pos) = position(ra_fixture);
1395 let config = TEST_CONFIG;
1396 let completion_context = CompletionContext::new(&db, pos, &config).unwrap();
1398 let ty = completion_context
1400 .map(|t| t.display_test(&db).to_string())
1401 .unwrap_or("?".to_owned());
1403 let name = completion_context
1405 .map_or_else(|| "?".to_owned(), |name| name.to_string());
1407 expect.assert_eq(&format!("ty: {}, name: {}", ty, name));
1411 fn expected_type_let_without_leading_char() {
1412 cov_mark::check!(expected_type_let_without_leading_char);
1413 check_expected_type_and_name(
1419 expect![[r#"ty: u32, name: x"#]],
1424 fn expected_type_let_with_leading_char() {
1425 cov_mark::check!(expected_type_let_with_leading_char);
1426 check_expected_type_and_name(
1432 expect![[r#"ty: u32, name: x"#]],
1437 fn expected_type_let_pat() {
1438 check_expected_type_and_name(
1444 expect![[r#"ty: u32, name: ?"#]],
1446 check_expected_type_and_name(
1452 expect![[r#"ty: u32, name: ?"#]],
1457 fn expected_type_fn_param() {
1458 cov_mark::check!(expected_type_fn_param);
1459 check_expected_type_and_name(
1461 fn foo() { bar($0); }
1464 expect![[r#"ty: u32, name: x"#]],
1466 check_expected_type_and_name(
1468 fn foo() { bar(c$0); }
1471 expect![[r#"ty: u32, name: x"#]],
1476 fn expected_type_fn_param_ref() {
1477 cov_mark::check!(expected_type_fn_param_ref);
1478 check_expected_type_and_name(
1480 fn foo() { bar(&$0); }
1483 expect![[r#"ty: u32, name: x"#]],
1485 check_expected_type_and_name(
1487 fn foo() { bar(&mut $0); }
1488 fn bar(x: &mut u32) {}
1490 expect![[r#"ty: u32, name: x"#]],
1492 check_expected_type_and_name(
1494 fn foo() { bar(& c$0); }
1497 expect![[r#"ty: u32, name: x"#]],
1499 check_expected_type_and_name(
1501 fn foo() { bar(&mut c$0); }
1502 fn bar(x: &mut u32) {}
1504 expect![[r#"ty: u32, name: x"#]],
1506 check_expected_type_and_name(
1508 fn foo() { bar(&c$0); }
1511 expect![[r#"ty: u32, name: x"#]],
1516 fn expected_type_struct_field_without_leading_char() {
1517 cov_mark::check!(expected_type_struct_field_without_leading_char);
1518 check_expected_type_and_name(
1520 struct Foo { a: u32 }
1525 expect![[r#"ty: u32, name: a"#]],
1530 fn expected_type_struct_field_followed_by_comma() {
1531 cov_mark::check!(expected_type_struct_field_followed_by_comma);
1532 check_expected_type_and_name(
1534 struct Foo { a: u32 }
1539 expect![[r#"ty: u32, name: a"#]],
1544 fn expected_type_generic_struct_field() {
1545 check_expected_type_and_name(
1547 struct Foo<T> { a: T }
1548 fn foo() -> Foo<u32> {
1552 expect![[r#"ty: u32, name: a"#]],
1557 fn expected_type_struct_field_with_leading_char() {
1558 cov_mark::check!(expected_type_struct_field_with_leading_char);
1559 check_expected_type_and_name(
1561 struct Foo { a: u32 }
1566 expect![[r#"ty: u32, name: a"#]],
1571 fn expected_type_match_arm_without_leading_char() {
1572 cov_mark::check!(expected_type_match_arm_without_leading_char);
1573 check_expected_type_and_name(
1580 expect![[r#"ty: E, name: ?"#]],
1585 fn expected_type_match_arm_with_leading_char() {
1586 cov_mark::check!(expected_type_match_arm_with_leading_char);
1587 check_expected_type_and_name(
1594 expect![[r#"ty: E, name: ?"#]],
1599 fn expected_type_if_let_without_leading_char() {
1600 cov_mark::check!(expected_type_if_let_without_leading_char);
1601 check_expected_type_and_name(
1603 enum Foo { Bar, Baz, Quux }
1610 expect![[r#"ty: Foo, name: ?"#]],
1615 fn expected_type_if_let_with_leading_char() {
1616 cov_mark::check!(expected_type_if_let_with_leading_char);
1617 check_expected_type_and_name(
1619 enum Foo { Bar, Baz, Quux }
1626 expect![[r#"ty: Foo, name: ?"#]],
1631 fn expected_type_fn_ret_without_leading_char() {
1632 cov_mark::check!(expected_type_fn_ret_without_leading_char);
1633 check_expected_type_and_name(
1639 expect![[r#"ty: u32, name: ?"#]],
1644 fn expected_type_fn_ret_with_leading_char() {
1645 cov_mark::check!(expected_type_fn_ret_with_leading_char);
1646 check_expected_type_and_name(
1652 expect![[r#"ty: u32, name: ?"#]],
1657 fn expected_type_fn_ret_fn_ref_fully_typed() {
1658 check_expected_type_and_name(
1664 expect![[r#"ty: u32, name: ?"#]],
1669 fn expected_type_closure_param_return() {
1670 // FIXME: make this work with `|| $0`
1671 check_expected_type_and_name(
1678 fn bar(f: impl FnOnce() -> u32) {}
1680 expect![[r#"ty: u32, name: ?"#]],
1685 fn expected_type_generic_function() {
1686 check_expected_type_and_name(
1694 expect![[r#"ty: u32, name: t"#]],
1699 fn expected_type_generic_method() {
1700 check_expected_type_and_name(
1708 fn bar(self, t: T) {}
1711 expect![[r#"ty: u32, name: t"#]],
1716 fn expected_type_functional_update() {
1717 cov_mark::check!(expected_type_struct_func_update);
1718 check_expected_type_and_name(
1720 struct Foo { field: u32 }
1727 expect![[r#"ty: Foo, name: ?"#]],
1732 fn expected_type_param_pat() {
1733 check_expected_type_and_name(
1735 struct Foo { field: u32 }
1738 expect![[r#"ty: Foo, name: ?"#]],
1740 check_expected_type_and_name(
1742 struct Foo { field: u32 }
1745 // FIXME make this work, currently fails due to pattern recovery eating the `:`
1746 expect![[r#"ty: ?, name: ?"#]],