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, HasName, NameOrNameRef},
18 match_ast, AstNode, 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 {
52 annotated_item_kind: Option<SyntaxKind>,
55 /// Path in item position, that is inside an (Assoc)ItemList
65 pub(crate) struct PathCompletionCtx {
66 /// If this is a call with () already there (or {} in case of record patterns)
67 pub(super) has_call_parens: bool,
68 /// If this has a macro call bang !
69 pub(super) has_macro_bang: bool,
70 /// Whether this path stars with a `::`.
71 pub(super) is_absolute_path: bool,
72 /// The qualifier of the current path if it exists.
73 pub(super) qualifier: Option<PathQualifierCtx>,
76 /// The parent of the path we are completing.
77 pub(super) parent: Option<ast::Path>,
78 pub(super) kind: PathKind,
79 /// Whether the path segment has type args or not.
80 pub(super) has_type_args: bool,
81 /// `true` if we are a statement or a last expr in the block.
82 pub(super) can_be_stmt: bool,
83 pub(super) in_loop_body: bool,
87 pub(crate) struct PathQualifierCtx {
88 pub(crate) path: ast::Path,
89 pub(crate) resolution: Option<PathResolution>,
90 /// Whether this path consists solely of `super` segments
91 pub(crate) is_super_chain: bool,
92 /// Whether the qualifier comes from a use tree parent or not
93 pub(crate) use_tree_parent: bool,
95 pub(crate) is_infer_qualifier: bool,
99 pub(super) struct PatternContext {
100 pub(super) refutability: PatternRefutability,
101 pub(super) param_ctx: Option<(ast::ParamList, ast::Param, ParamKind)>,
102 pub(super) has_type_ascription: bool,
103 pub(super) parent_pat: Option<ast::Pat>,
104 pub(super) ref_token: Option<SyntaxToken>,
105 pub(super) mut_token: Option<SyntaxToken>,
109 pub(super) enum LifetimeContext {
110 LifetimeParam { is_decl: bool, param: ast::LifetimeParam },
118 pub(super) enum NameContext {
140 #[derive(Clone, Debug, PartialEq, Eq)]
141 pub(crate) enum ParamKind {
143 Closure(ast::ClosureExpr),
146 /// `CompletionContext` is created early during completion to figure out, where
147 /// exactly is the cursor, syntax-wise.
149 pub(crate) struct CompletionContext<'a> {
150 pub(super) sema: Semantics<'a, RootDatabase>,
151 pub(super) scope: SemanticsScope<'a>,
152 pub(super) db: &'a RootDatabase,
153 pub(super) config: &'a CompletionConfig,
154 pub(super) position: FilePosition,
156 /// The token before the cursor, in the original file.
157 pub(super) original_token: SyntaxToken,
158 /// The token before the cursor, in the macro-expanded file.
159 pub(super) token: SyntaxToken,
160 /// The crate of the current file.
161 pub(super) krate: hir::Crate,
162 /// The module of the `scope`.
163 pub(super) module: hir::Module,
165 /// The expected name of what we are completing.
166 /// This is usually the parameter name of the function argument we are completing.
167 pub(super) expected_name: Option<NameOrNameRef>,
168 /// The expected type of what we are completing.
169 pub(super) expected_type: Option<Type>,
171 /// The parent function of the cursor position if it exists.
172 pub(super) function_def: Option<ast::Fn>,
173 /// The parent impl of the cursor position if it exists.
174 pub(super) impl_def: Option<ast::Impl>,
175 /// The NameLike under the cursor in the original file if it exists.
176 pub(super) name_syntax: Option<ast::NameLike>,
177 /// Are we completing inside a let statement with a missing semicolon?
178 pub(super) incomplete_let: bool,
180 pub(super) completion_location: Option<ImmediateLocation>,
181 pub(super) prev_sibling: Option<ImmediatePrevSibling>,
182 pub(super) fake_attribute_under_caret: Option<ast::Attr>,
183 pub(super) previous_token: Option<SyntaxToken>,
185 pub(super) name_ctx: Option<NameContext>,
186 pub(super) lifetime_ctx: Option<LifetimeContext>,
187 pub(super) pattern_ctx: Option<PatternContext>,
188 pub(super) path_context: Option<PathCompletionCtx>,
190 pub(super) existing_derives: FxHashSet<hir::Macro>,
192 pub(super) locals: FxHashMap<Name, Local>,
195 impl<'a> CompletionContext<'a> {
196 /// The range of the identifier that is being completed.
197 pub(crate) fn source_range(&self) -> TextRange {
198 // check kind of macro-expanded token, but use range of original token
199 let kind = self.token.kind();
202 // assume we are completing a lifetime but the user has only typed the '
203 cov_mark::hit!(completes_if_lifetime_without_idents);
204 TextRange::at(self.original_token.text_range().start(), TextSize::from(1))
206 IDENT | LIFETIME_IDENT | UNDERSCORE => self.original_token.text_range(),
207 _ if kind.is_keyword() => self.original_token.text_range(),
208 _ => TextRange::empty(self.position.offset),
212 pub(crate) fn name_ref(&self) -> Option<&ast::NameRef> {
213 self.name_syntax.as_ref().and_then(ast::NameLike::as_name_ref)
216 pub(crate) fn lifetime(&self) -> Option<&ast::Lifetime> {
217 self.name_syntax.as_ref().and_then(ast::NameLike::as_lifetime)
220 pub(crate) fn previous_token_is(&self, kind: SyntaxKind) -> bool {
221 self.previous_token.as_ref().map_or(false, |tok| tok.kind() == kind)
224 pub(crate) fn famous_defs(&self) -> FamousDefs {
225 FamousDefs(&self.sema, self.krate)
228 pub(crate) fn dot_receiver(&self) -> Option<&ast::Expr> {
229 match &self.completion_location {
231 ImmediateLocation::MethodCall { receiver, .. }
232 | ImmediateLocation::FieldAccess { receiver, .. },
233 ) => receiver.as_ref(),
238 pub(crate) fn has_dot_receiver(&self) -> bool {
240 &self.completion_location,
241 Some(ImmediateLocation::FieldAccess { receiver, .. } | ImmediateLocation::MethodCall { receiver,.. })
242 if receiver.is_some()
246 pub(crate) fn expects_assoc_item(&self) -> bool {
247 matches!(self.completion_location, Some(ImmediateLocation::Trait | ImmediateLocation::Impl))
250 pub(crate) fn expects_variant(&self) -> bool {
251 matches!(self.name_ctx, Some(NameContext::Variant))
254 pub(crate) fn expects_non_trait_assoc_item(&self) -> bool {
255 matches!(self.completion_location, Some(ImmediateLocation::Impl))
258 pub(crate) fn expects_item(&self) -> bool {
259 matches!(self.completion_location, Some(ImmediateLocation::ItemList))
262 pub(crate) fn expects_generic_arg(&self) -> bool {
263 matches!(self.completion_location, Some(ImmediateLocation::GenericArgList(_)))
266 pub(crate) fn has_block_expr_parent(&self) -> bool {
267 matches!(self.completion_location, Some(ImmediateLocation::StmtList))
270 pub(crate) fn expects_ident_ref_expr(&self) -> bool {
271 matches!(self.completion_location, Some(ImmediateLocation::RefExpr))
274 pub(crate) fn expect_field(&self) -> bool {
275 matches!(self.completion_location, Some(ImmediateLocation::TupleField))
276 || matches!(self.name_ctx, Some(NameContext::RecordField))
279 /// Whether the cursor is right after a trait or impl header.
280 /// trait Foo ident$0
281 // FIXME: This probably shouldn't exist
282 pub(crate) fn has_unfinished_impl_or_trait_prev_sibling(&self) -> bool {
285 Some(ImmediatePrevSibling::ImplDefType | ImmediatePrevSibling::TraitDefName)
289 // FIXME: This probably shouldn't exist
290 pub(crate) fn has_impl_prev_sibling(&self) -> bool {
291 matches!(self.prev_sibling, Some(ImmediatePrevSibling::ImplDefType))
294 pub(crate) fn has_visibility_prev_sibling(&self) -> bool {
295 matches!(self.prev_sibling, Some(ImmediatePrevSibling::Visibility))
298 pub(crate) fn after_if(&self) -> bool {
299 matches!(self.prev_sibling, Some(ImmediatePrevSibling::IfExpr))
302 // FIXME: This shouldn't exist
303 pub(crate) fn is_path_disallowed(&self) -> bool {
304 self.previous_token_is(T![unsafe])
307 Some(ImmediatePrevSibling::Attribute | ImmediatePrevSibling::Visibility)
310 self.completion_location,
311 Some(ImmediateLocation::RecordPat(_) | ImmediateLocation::RecordExpr(_))
313 || matches!(self.name_ctx, Some(NameContext::Module(_) | NameContext::Rename))
316 pub(crate) fn expects_expression(&self) -> bool {
317 matches!(self.path_context, Some(PathCompletionCtx { kind: PathKind::Expr, .. }))
320 pub(crate) fn expects_type(&self) -> bool {
321 matches!(self.path_context, Some(PathCompletionCtx { kind: PathKind::Type, .. }))
324 pub(crate) fn path_is_call(&self) -> bool {
325 self.path_context.as_ref().map_or(false, |it| it.has_call_parens)
328 pub(crate) fn is_non_trivial_path(&self) -> bool {
332 PathCompletionCtx { is_absolute_path: true, .. }
333 | PathCompletionCtx { qualifier: Some(_), .. }
338 pub(crate) fn path_qual(&self) -> Option<&ast::Path> {
339 self.path_context.as_ref().and_then(|it| it.qualifier.as_ref().map(|it| &it.path))
342 pub(crate) fn path_kind(&self) -> Option<PathKind> {
343 self.path_context.as_ref().map(|it| it.kind)
346 pub(crate) fn is_immediately_after_macro_bang(&self) -> bool {
347 self.token.kind() == BANG && self.token.parent().map_or(false, |it| it.kind() == MACRO_CALL)
350 /// Checks if an item is visible and not `doc(hidden)` at the completion site.
351 pub(crate) fn is_visible<I>(&self, item: &I) -> Visible
353 I: hir::HasVisibility + hir::HasAttrs + hir::HasCrate + Copy,
355 self.is_visible_impl(&item.visibility(self.db), &item.attrs(self.db), item.krate(self.db))
358 pub(crate) fn is_scope_def_hidden(&self, scope_def: ScopeDef) -> bool {
359 if let (Some(attrs), Some(krate)) = (scope_def.attrs(self.db), scope_def.krate(self.db)) {
360 return self.is_doc_hidden(&attrs, krate);
366 /// Check if an item is `#[doc(hidden)]`.
367 pub(crate) fn is_item_hidden(&self, item: &hir::ItemInNs) -> bool {
368 let attrs = item.attrs(self.db);
369 let krate = item.krate(self.db);
370 match (attrs, krate) {
371 (Some(attrs), Some(krate)) => self.is_doc_hidden(&attrs, krate),
375 /// Whether the given trait is an operator trait or not.
376 pub(crate) fn is_ops_trait(&self, trait_: hir::Trait) -> bool {
377 match trait_.attrs(self.db).lang() {
378 Some(lang) => OP_TRAIT_LANG_NAMES.contains(&lang.as_str()),
383 /// Returns the traits in scope, with the [`Drop`] trait removed.
384 pub(crate) fn traits_in_scope(&self) -> hir::VisibleTraits {
385 let mut traits_in_scope = self.scope.visible_traits();
386 if let Some(drop) = self.famous_defs().core_ops_Drop() {
387 traits_in_scope.0.remove(&drop.into());
392 /// A version of [`SemanticsScope::process_all_names`] that filters out `#[doc(hidden)]` items.
393 pub(crate) fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
394 let _p = profile::span("CompletionContext::process_all_names");
395 self.scope.process_all_names(&mut |name, def| {
396 if self.is_scope_def_hidden(def) {
404 pub(crate) fn process_all_names_raw(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
405 let _p = profile::span("CompletionContext::process_all_names_raw");
406 self.scope.process_all_names(&mut |name, def| f(name, def));
411 vis: &hir::Visibility,
413 defining_crate: hir::Crate,
415 if !vis.is_visible_from(self.db, self.module.into()) {
416 if !self.config.enable_private_editable {
419 // If the definition location is editable, also show private items
420 let root_file = defining_crate.root_file(self.db);
421 let source_root_id = self.db.file_source_root(root_file);
422 let is_editable = !self.db.source_root(source_root_id).is_library;
423 return if is_editable { Visible::Editable } else { Visible::No };
426 if self.is_doc_hidden(attrs, defining_crate) {
433 fn is_doc_hidden(&self, attrs: &hir::Attrs, defining_crate: hir::Crate) -> bool {
434 // `doc(hidden)` items are only completed within the defining crate.
435 self.krate != defining_crate && attrs.has_doc_hidden()
439 // CompletionContext construction
440 impl<'a> CompletionContext<'a> {
442 db: &'a RootDatabase,
443 position @ FilePosition { file_id, offset }: FilePosition,
444 config: &'a CompletionConfig,
445 ) -> Option<CompletionContext<'a>> {
446 let _p = profile::span("CompletionContext::new");
447 let sema = Semantics::new(db);
449 let original_file = sema.parse(file_id);
451 // Insert a fake ident to get a valid parse tree. We will use this file
452 // to determine context, though the original_file will be used for
453 // actual completion.
454 let file_with_fake_ident = {
455 let parse = db.parse(file_id);
456 let edit = Indel::insert(offset, COMPLETION_MARKER.to_string());
457 parse.reparse(&edit).tree()
459 let fake_ident_token =
460 file_with_fake_ident.syntax().token_at_offset(offset).right_biased()?;
462 let original_token = original_file.syntax().token_at_offset(offset).left_biased()?;
463 let token = sema.descend_into_macros_single(original_token.clone());
464 let scope = sema.scope_at_offset(&token.parent()?, offset)?;
465 let krate = scope.krate();
466 let module = scope.module();
468 let mut locals = FxHashMap::default();
469 scope.process_all_names(&mut |name, scope| {
470 if let ScopeDef::Local(local) = scope {
471 locals.insert(name, local);
475 let mut ctx = CompletionContext {
493 completion_location: None,
495 fake_attribute_under_caret: None,
496 previous_token: None,
499 incomplete_let: false,
500 existing_derives: Default::default(),
503 original_file.syntax().clone(),
504 file_with_fake_ident.syntax().clone(),
511 /// Expand attributes and macro calls at the current cursor position for both the original file
512 /// and fake file repeatedly. As soon as one of the two expansions fail we stop so the original
513 /// and speculative states stay in sync.
516 mut original_file: SyntaxNode,
517 mut speculative_file: SyntaxNode,
518 mut offset: TextSize,
519 mut fake_ident_token: SyntaxToken,
521 let _p = profile::span("CompletionContext::expand_and_fill");
522 let mut derive_ctx = None;
526 |item: &ast::Item| item.syntax().ancestors().skip(1).find_map(ast::Item::cast);
527 let ancestor_items = iter::successors(
529 find_node_at_offset::<ast::Item>(&original_file, offset),
530 find_node_at_offset::<ast::Item>(&speculative_file, offset),
532 |(a, b)| parent_item(a).zip(parent_item(b)),
535 // first try to expand attributes as these are always the outermost macro calls
536 'ancestors: for (actual_item, item_with_fake_ident) in ancestor_items {
538 self.sema.expand_attr_macro(&actual_item),
539 self.sema.speculative_expand_attr_macro(
541 &item_with_fake_ident,
542 fake_ident_token.clone(),
545 // maybe parent items have attributes, so continue walking the ancestors
546 (None, None) => continue 'ancestors,
547 // successful expansions
548 (Some(actual_expansion), Some((fake_expansion, fake_mapped_token))) => {
549 let new_offset = fake_mapped_token.text_range().start();
550 if new_offset > actual_expansion.text_range().end() {
551 // offset outside of bounds from the original expansion,
552 // stop here to prevent problems from happening
555 original_file = actual_expansion;
556 speculative_file = fake_expansion;
557 fake_ident_token = fake_mapped_token;
561 // exactly one expansion failed, inconsistent state so stop expanding completely
562 _ => break 'expansion,
566 // No attributes have been expanded, so look for macro_call! token trees or derive token trees
567 let orig_tt = match find_node_at_offset::<ast::TokenTree>(&original_file, offset) {
569 None => break 'expansion,
571 let spec_tt = match find_node_at_offset::<ast::TokenTree>(&speculative_file, offset) {
573 None => break 'expansion,
576 // Expand pseudo-derive expansion
577 if let (Some(orig_attr), Some(spec_attr)) = (
578 orig_tt.syntax().parent().and_then(ast::Meta::cast).and_then(|it| it.parent_attr()),
579 spec_tt.syntax().parent().and_then(ast::Meta::cast).and_then(|it| it.parent_attr()),
581 if let (Some(actual_expansion), Some((fake_expansion, fake_mapped_token))) = (
582 self.sema.expand_derive_as_pseudo_attr_macro(&orig_attr),
583 self.sema.speculative_expand_derive_as_pseudo_attr_macro(
586 fake_ident_token.clone(),
592 fake_mapped_token.text_range().start(),
596 // at this point we won't have any more successful expansions, so stop
600 // Expand fn-like macro calls
601 if let (Some(actual_macro_call), Some(macro_call_with_fake_ident)) = (
602 orig_tt.syntax().ancestors().find_map(ast::MacroCall::cast),
603 spec_tt.syntax().ancestors().find_map(ast::MacroCall::cast),
605 let mac_call_path0 = actual_macro_call.path().as_ref().map(|s| s.syntax().text());
607 macro_call_with_fake_ident.path().as_ref().map(|s| s.syntax().text());
609 // inconsistent state, stop expanding
610 if mac_call_path0 != mac_call_path1 {
613 let speculative_args = match macro_call_with_fake_ident.token_tree() {
615 None => break 'expansion,
619 self.sema.expand(&actual_macro_call),
620 self.sema.speculative_expand(
623 fake_ident_token.clone(),
626 // successful expansions
627 (Some(actual_expansion), Some((fake_expansion, fake_mapped_token))) => {
628 let new_offset = fake_mapped_token.text_range().start();
629 if new_offset > actual_expansion.text_range().end() {
630 // offset outside of bounds from the original expansion,
631 // stop here to prevent problems from happening
634 original_file = actual_expansion;
635 speculative_file = fake_expansion;
636 fake_ident_token = fake_mapped_token;
640 // at least on expansion failed, we won't have anything to expand from this point
641 // onwards so break out
642 _ => break 'expansion,
646 // none of our states have changed so stop the loop
650 self.fill(&original_file, speculative_file, offset, derive_ctx);
653 /// Calculate the expected type and name of the cursor position.
654 fn expected_type_and_name(&self) -> (Option<Type>, Option<NameOrNameRef>) {
655 let mut node = match self.token.parent() {
657 None => return (None, None),
662 ast::LetStmt(it) => {
663 cov_mark::hit!(expected_type_let_with_leading_char);
664 cov_mark::hit!(expected_type_let_without_leading_char);
666 .and_then(|pat| self.sema.type_of_pat(&pat))
667 .or_else(|| it.initializer().and_then(|it| self.sema.type_of_expr(&it)))
668 .map(TypeInfo::original);
669 let name = match it.pat() {
670 Some(ast::Pat::IdentPat(ident)) => ident.name().map(NameOrNameRef::Name),
671 Some(_) | None => None,
676 ast::LetExpr(it) => {
677 cov_mark::hit!(expected_type_if_let_without_leading_char);
679 .and_then(|pat| self.sema.type_of_pat(&pat))
680 .or_else(|| it.expr().and_then(|it| self.sema.type_of_expr(&it)))
681 .map(TypeInfo::original);
685 cov_mark::hit!(expected_type_fn_param);
686 ActiveParameter::at_token(
690 let name = ap.ident().map(NameOrNameRef::Name);
691 let ty = if has_ref(&self.token) {
692 cov_mark::hit!(expected_type_fn_param_ref);
699 .unwrap_or((None, None))
701 ast::RecordExprFieldList(it) => {
702 // wouldn't try {} be nice...
704 if self.token.kind() == T![..]
705 || self.token.prev_token().map(|t| t.kind()) == Some(T![..])
707 cov_mark::hit!(expected_type_struct_func_update);
708 let record_expr = it.syntax().parent().and_then(ast::RecordExpr::cast)?;
709 let ty = self.sema.type_of_expr(&record_expr.into())?;
715 cov_mark::hit!(expected_type_struct_field_without_leading_char);
716 let expr_field = self.token.prev_sibling_or_token()?
718 .and_then(ast::RecordExprField::cast)?;
719 let (_, _, ty) = self.sema.resolve_record_field(&expr_field)?;
722 expr_field.field_name().map(NameOrNameRef::NameRef),
725 })().unwrap_or((None, None))
727 ast::RecordExprField(it) => {
728 if let Some(expr) = it.expr() {
729 cov_mark::hit!(expected_type_struct_field_with_leading_char);
731 self.sema.type_of_expr(&expr).map(TypeInfo::original),
732 it.field_name().map(NameOrNameRef::NameRef),
735 cov_mark::hit!(expected_type_struct_field_followed_by_comma);
736 let ty = self.sema.resolve_record_field(&it)
737 .map(|(_, _, ty)| ty);
740 it.field_name().map(NameOrNameRef::NameRef),
744 ast::MatchExpr(it) => {
745 cov_mark::hit!(expected_type_match_arm_without_leading_char);
746 let ty = it.expr().and_then(|e| self.sema.type_of_expr(&e)).map(TypeInfo::original);
750 let ty = it.condition()
751 .and_then(|e| self.sema.type_of_expr(&e))
752 .map(TypeInfo::original);
755 ast::IdentPat(it) => {
756 cov_mark::hit!(expected_type_if_let_with_leading_char);
757 cov_mark::hit!(expected_type_match_arm_with_leading_char);
758 let ty = self.sema.type_of_pat(&ast::Pat::from(it)).map(TypeInfo::original);
762 cov_mark::hit!(expected_type_fn_ret_with_leading_char);
763 cov_mark::hit!(expected_type_fn_ret_without_leading_char);
764 let def = self.sema.to_def(&it);
765 (def.map(|def| def.ret_type(self.db)), None)
767 ast::ClosureExpr(it) => {
768 let ty = self.sema.type_of_expr(&it.into());
769 ty.and_then(|ty| ty.original.as_callable(self.db))
770 .map(|c| (Some(c.return_type()), None))
771 .unwrap_or((None, None))
773 ast::ParamList(_) => (None, None),
774 ast::Stmt(_) => (None, None),
775 ast::Item(_) => (None, None),
777 match node.parent() {
782 None => (None, None),
790 /// Fill the completion context, this is what does semantic reasoning about the surrounding context
791 /// of the completion location.
794 original_file: &SyntaxNode,
795 file_with_fake_ident: SyntaxNode,
797 derive_ctx: Option<(SyntaxNode, SyntaxNode, TextSize, ast::Attr)>,
799 let fake_ident_token = file_with_fake_ident.token_at_offset(offset).right_biased().unwrap();
800 let syntax_element = NodeOrToken::Token(fake_ident_token);
801 if is_in_token_of_for_loop(syntax_element.clone()) {
803 // there is nothing to complete here except `in` keyword
804 // don't bother populating the context
805 // FIXME: the completion calculations should end up good enough
806 // such that this special case becomes unnecessary
810 self.previous_token = previous_token(syntax_element.clone());
811 self.fake_attribute_under_caret = syntax_element.ancestors().find_map(ast::Attr::cast);
813 self.incomplete_let =
814 syntax_element.ancestors().take(6).find_map(ast::LetStmt::cast).map_or(false, |it| {
815 it.syntax().text_range().end() == syntax_element.text_range().end()
818 (self.expected_type, self.expected_name) = self.expected_type_and_name();
820 // Overwrite the path kind for derives
821 if let Some((original_file, file_with_fake_ident, offset, origin_attr)) = derive_ctx {
822 self.existing_derives = self
824 .resolve_derive_macro(&origin_attr)
830 if let Some(ast::NameLike::NameRef(name_ref)) =
831 find_node_at_offset(&file_with_fake_ident, offset)
834 find_node_at_offset(&original_file, name_ref.syntax().text_range().start());
835 if let Some((path_ctx, _)) =
836 Self::classify_name_ref(&self.sema, &original_file, name_ref)
839 Some(PathCompletionCtx { kind: PathKind::Derive, ..path_ctx });
845 let name_like = match find_node_at_offset(&file_with_fake_ident, offset) {
849 self.completion_location =
850 determine_location(&self.sema, original_file, offset, &name_like);
851 self.prev_sibling = determine_prev_sibling(&name_like);
853 find_node_at_offset(original_file, name_like.syntax().text_range().start());
856 .token_ancestors_with_macros(self.token.clone())
857 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
858 .find_map(ast::Impl::cast);
859 self.function_def = self
861 .token_ancestors_with_macros(self.token.clone())
862 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
863 .find_map(ast::Fn::cast);
866 ast::NameLike::Lifetime(lifetime) => {
867 self.lifetime_ctx = Self::classify_lifetime(&self.sema, original_file, lifetime);
869 ast::NameLike::NameRef(name_ref) => {
870 if let Some((path_ctx, pat_ctx)) =
871 Self::classify_name_ref(&self.sema, original_file, name_ref)
873 self.path_context = Some(path_ctx);
874 self.pattern_ctx = pat_ctx;
877 ast::NameLike::Name(name) => {
878 if let Some((name_ctx, pat_ctx)) =
879 Self::classify_name(&self.sema, original_file, name)
881 self.pattern_ctx = pat_ctx;
882 self.name_ctx = Some(name_ctx);
888 fn classify_lifetime(
889 _sema: &Semantics<RootDatabase>,
890 _original_file: &SyntaxNode,
891 lifetime: ast::Lifetime,
892 ) -> Option<LifetimeContext> {
893 let parent = lifetime.syntax().parent()?;
894 if parent.kind() == ERROR {
900 ast::LifetimeParam(param) => LifetimeContext::LifetimeParam {
901 is_decl: param.lifetime().as_ref() == Some(&lifetime),
904 ast::BreakExpr(_) => LifetimeContext::LabelRef,
905 ast::ContinueExpr(_) => LifetimeContext::LabelRef,
906 ast::Label(_) => LifetimeContext::LabelDef,
907 _ => LifetimeContext::Lifetime,
913 _sema: &Semantics<RootDatabase>,
914 original_file: &SyntaxNode,
916 ) -> Option<(NameContext, Option<PatternContext>)> {
917 let parent = name.syntax().parent()?;
918 let mut pat_ctx = None;
919 let name_ctx = match_ast! {
921 ast::Const(_) => NameContext::Const,
922 ast::ConstParam(_) => NameContext::ConstParam,
923 ast::Enum(_) => NameContext::Enum,
924 ast::Fn(_) => NameContext::Function,
925 ast::IdentPat(bind_pat) => {
926 let is_name_in_field_pat = bind_pat
929 .and_then(ast::RecordPatField::cast)
930 .map_or(false, |pat_field| pat_field.name_ref().is_none());
931 if !is_name_in_field_pat {
932 pat_ctx = Some(pattern_context_for(original_file, bind_pat.into()));
935 NameContext::IdentPat
937 ast::MacroDef(_) => NameContext::MacroDef,
938 ast::MacroRules(_) => NameContext::MacroRules,
939 ast::Module(module) => NameContext::Module(module),
940 ast::RecordField(_) => NameContext::RecordField,
941 ast::Rename(_) => NameContext::Rename,
942 ast::SelfParam(_) => NameContext::SelfParam,
943 ast::Static(_) => NameContext::Static,
944 ast::Struct(_) => NameContext::Struct,
945 ast::Trait(_) => NameContext::Trait,
946 ast::TypeAlias(_) => NameContext::TypeAlias,
947 ast::TypeParam(_) => NameContext::TypeParam,
948 ast::Union(_) => NameContext::Union,
949 ast::Variant(_) => NameContext::Variant,
953 Some((name_ctx, pat_ctx))
956 fn classify_name_ref(
957 sema: &Semantics<RootDatabase>,
958 original_file: &SyntaxNode,
959 name_ref: ast::NameRef,
960 ) -> Option<(PathCompletionCtx, Option<PatternContext>)> {
961 let parent = name_ref.syntax().parent()?;
962 let segment = ast::PathSegment::cast(parent)?;
963 let path = segment.parent_path();
965 let mut path_ctx = PathCompletionCtx {
966 has_call_parens: false,
967 has_macro_bang: false,
968 is_absolute_path: false,
970 parent: path.parent_path(),
971 kind: PathKind::Item,
972 has_type_args: false,
976 let mut pat_ctx = None;
977 path_ctx.in_loop_body = is_in_loop_body(name_ref.syntax());
979 path_ctx.kind = path.syntax().ancestors().find_map(|it| {
980 // using Option<Option<PathKind>> as extra controlflow
981 let kind = match_ast! {
983 ast::PathType(_) => Some(PathKind::Type),
984 ast::PathExpr(it) => {
985 path_ctx.has_call_parens = it.syntax().parent().map_or(false, |it| ast::CallExpr::can_cast(it.kind()));
988 ast::TupleStructPat(it) => {
989 path_ctx.has_call_parens = true;
990 pat_ctx = Some(pattern_context_for(original_file, it.into()));
993 ast::RecordPat(it) => {
994 path_ctx.has_call_parens = true;
995 pat_ctx = Some(pattern_context_for(original_file, it.into()));
998 ast::PathPat(it) => {
999 pat_ctx = Some(pattern_context_for(original_file, it.into()));
1002 ast::MacroCall(it) => {
1003 path_ctx.has_macro_bang = it.excl_token().is_some();
1004 match it.syntax().parent().map(|it| it.kind()) {
1005 Some(SyntaxKind::MACRO_PAT) => Some(PathKind::Pat),
1006 Some(SyntaxKind::MACRO_TYPE) => Some(PathKind::Type),
1007 Some(SyntaxKind::MACRO_EXPR) => Some(PathKind::Expr),
1009 SyntaxKind::ITEM_LIST
1010 | SyntaxKind::ASSOC_ITEM_LIST
1011 | SyntaxKind::EXTERN_ITEM_LIST
1012 | SyntaxKind::SOURCE_FILE
1013 ) => Some(PathKind::Item),
1014 _ => return Some(None),
1017 ast::Meta(meta) => (|| {
1018 let attr = meta.parent_attr()?;
1019 let kind = attr.kind();
1020 let attached = attr.syntax().parent()?;
1021 let is_trailing_outer_attr = kind != AttrKind::Inner
1022 && non_trivia_sibling(attr.syntax().clone().into(), syntax::Direction::Next).is_none();
1023 let annotated_item_kind = if is_trailing_outer_attr {
1026 Some(attached.kind())
1028 Some(PathKind::Attr {
1030 annotated_item_kind,
1033 ast::Visibility(it) => Some(PathKind::Vis { has_in_token: it.in_token().is_some() }),
1034 ast::UseTree(_) => Some(PathKind::Use),
1035 ast::ItemList(_) => Some(PathKind::Item),
1036 ast::AssocItemList(_) => Some(PathKind::Item),
1037 ast::ExternItemList(_) => Some(PathKind::Item),
1038 ast::SourceFile(_) => Some(PathKind::Item),
1044 path_ctx.has_type_args = segment.generic_arg_list().is_some();
1046 if let Some((path, use_tree_parent)) = path_or_use_tree_qualifier(&path) {
1047 if !use_tree_parent {
1048 path_ctx.is_absolute_path =
1049 path.top_path().segment().map_or(false, |it| it.coloncolon_token().is_some());
1054 .and_then(|it| find_node_in_file(original_file, &it))
1055 .map(|it| it.parent_path());
1056 path_ctx.qualifier = path.map(|path| {
1057 let res = sema.resolve_path(&path);
1058 let is_super_chain = iter::successors(Some(path.clone()), |p| p.qualifier())
1059 .all(|p| p.segment().and_then(|s| s.super_token()).is_some());
1062 let is_infer_qualifier = path.qualifier().is_none()
1064 path.segment().and_then(|it| it.kind()),
1065 Some(ast::PathSegmentKind::Type {
1066 type_ref: Some(ast::Type::InferType(_)),
1079 return Some((path_ctx, pat_ctx));
1082 if let Some(segment) = path.segment() {
1083 if segment.coloncolon_token().is_some() {
1084 path_ctx.is_absolute_path = true;
1085 return Some((path_ctx, pat_ctx));
1089 // Find either enclosing expr statement (thing with `;`) or a
1090 // block. If block, check that we are the last expr.
1091 path_ctx.can_be_stmt = name_ref
1095 if let Some(stmt) = ast::ExprStmt::cast(node.clone()) {
1096 return Some(stmt.syntax().text_range() == name_ref.syntax().text_range());
1098 if let Some(stmt_list) = ast::StmtList::cast(node) {
1100 stmt_list.tail_expr().map(|e| e.syntax().text_range())
1101 == Some(name_ref.syntax().text_range()),
1107 Some((path_ctx, pat_ctx))
1111 fn pattern_context_for(original_file: &SyntaxNode, pat: ast::Pat) -> PatternContext {
1112 let mut is_param = None;
1113 let (refutability, has_type_ascription) =
1117 .skip_while(|it| ast::Pat::can_cast(it.kind()))
1119 .map_or((PatternRefutability::Irrefutable, false), |node| {
1120 let refutability = match_ast! {
1122 ast::LetStmt(let_) => return (PatternRefutability::Irrefutable, let_.ty().is_some()),
1123 ast::Param(param) => {
1124 let has_type_ascription = param.ty().is_some();
1126 let fake_param_list = param.syntax().parent().and_then(ast::ParamList::cast)?;
1127 let param_list = find_node_in_file_compensated(original_file, &fake_param_list)?;
1128 let param_list_owner = param_list.syntax().parent()?;
1129 let kind = match_ast! {
1130 match param_list_owner {
1131 ast::ClosureExpr(closure) => ParamKind::Closure(closure),
1132 ast::Fn(fn_) => ParamKind::Function(fn_),
1136 Some((param_list, param, kind))
1138 return (PatternRefutability::Irrefutable, has_type_ascription)
1140 ast::MatchArm(_) => PatternRefutability::Refutable,
1141 ast::LetExpr(_) => PatternRefutability::Refutable,
1142 ast::ForExpr(_) => PatternRefutability::Irrefutable,
1143 _ => PatternRefutability::Irrefutable,
1146 (refutability, false)
1148 let (ref_token, mut_token) = match &pat {
1149 ast::Pat::IdentPat(it) => (it.ref_token(), it.mut_token()),
1154 param_ctx: is_param,
1155 has_type_ascription,
1156 parent_pat: pat.syntax().parent().and_then(ast::Pat::cast),
1162 /// Attempts to find `node` inside `syntax` via `node`'s text range.
1163 fn find_node_in_file<N: AstNode>(syntax: &SyntaxNode, node: &N) -> Option<N> {
1164 let syntax_range = syntax.text_range();
1165 let range = node.syntax().text_range();
1166 let intersection = range.intersect(syntax_range)?;
1167 syntax.covering_element(intersection).ancestors().find_map(N::cast)
1170 /// Attempts to find `node` inside `syntax` via `node`'s text range while compensating
1171 /// for the offset introduced by the fake ident.
1172 /// This is wrong if `node` comes before the insertion point! Use `find_node_in_file` instead.
1173 fn find_node_in_file_compensated<N: AstNode>(syntax: &SyntaxNode, node: &N) -> Option<N> {
1174 let syntax_range = syntax.text_range();
1175 let range = node.syntax().text_range();
1176 let end = range.end().checked_sub(TextSize::try_from(COMPLETION_MARKER.len()).ok()?)?;
1177 if end < range.start() {
1180 let range = TextRange::new(range.start(), end);
1181 // our inserted ident could cause `range` to be go outside of the original syntax, so cap it
1182 let intersection = range.intersect(syntax_range)?;
1183 syntax.covering_element(intersection).ancestors().find_map(N::cast)
1186 fn path_or_use_tree_qualifier(path: &ast::Path) -> Option<(ast::Path, bool)> {
1187 if let Some(qual) = path.qualifier() {
1188 return Some((qual, false));
1190 let use_tree_list = path.syntax().ancestors().find_map(ast::UseTreeList::cast)?;
1191 let use_tree = use_tree_list.syntax().parent().and_then(ast::UseTree::cast)?;
1192 Some((use_tree.path()?, true))
1195 fn has_ref(token: &SyntaxToken) -> bool {
1196 let mut token = token.clone();
1197 for skip in [IDENT, WHITESPACE, T![mut]] {
1198 if token.kind() == skip {
1199 token = match token.prev_token() {
1201 None => return false,
1205 token.kind() == T![&]
1208 const OP_TRAIT_LANG_NAMES: &[&str] = &[
1243 use expect_test::{expect, Expect};
1244 use hir::HirDisplay;
1246 use crate::tests::{position, TEST_CONFIG};
1248 use super::CompletionContext;
1250 fn check_expected_type_and_name(ra_fixture: &str, expect: Expect) {
1251 let (db, pos) = position(ra_fixture);
1252 let config = TEST_CONFIG;
1253 let completion_context = CompletionContext::new(&db, pos, &config).unwrap();
1255 let ty = completion_context
1257 .map(|t| t.display_test(&db).to_string())
1258 .unwrap_or("?".to_owned());
1260 let name = completion_context
1262 .map_or_else(|| "?".to_owned(), |name| name.to_string());
1264 expect.assert_eq(&format!("ty: {}, name: {}", ty, name));
1268 fn expected_type_let_without_leading_char() {
1269 cov_mark::check!(expected_type_let_without_leading_char);
1270 check_expected_type_and_name(
1276 expect![[r#"ty: u32, name: x"#]],
1281 fn expected_type_let_with_leading_char() {
1282 cov_mark::check!(expected_type_let_with_leading_char);
1283 check_expected_type_and_name(
1289 expect![[r#"ty: u32, name: x"#]],
1294 fn expected_type_let_pat() {
1295 check_expected_type_and_name(
1301 expect![[r#"ty: u32, name: ?"#]],
1303 check_expected_type_and_name(
1309 expect![[r#"ty: u32, name: ?"#]],
1314 fn expected_type_fn_param() {
1315 cov_mark::check!(expected_type_fn_param);
1316 check_expected_type_and_name(
1318 fn foo() { bar($0); }
1321 expect![[r#"ty: u32, name: x"#]],
1323 check_expected_type_and_name(
1325 fn foo() { bar(c$0); }
1328 expect![[r#"ty: u32, name: x"#]],
1333 fn expected_type_fn_param_ref() {
1334 cov_mark::check!(expected_type_fn_param_ref);
1335 check_expected_type_and_name(
1337 fn foo() { bar(&$0); }
1340 expect![[r#"ty: u32, name: x"#]],
1342 check_expected_type_and_name(
1344 fn foo() { bar(&mut $0); }
1345 fn bar(x: &mut u32) {}
1347 expect![[r#"ty: u32, name: x"#]],
1349 check_expected_type_and_name(
1351 fn foo() { bar(& c$0); }
1354 expect![[r#"ty: u32, name: x"#]],
1356 check_expected_type_and_name(
1358 fn foo() { bar(&mut c$0); }
1359 fn bar(x: &mut u32) {}
1361 expect![[r#"ty: u32, name: x"#]],
1363 check_expected_type_and_name(
1365 fn foo() { bar(&c$0); }
1368 expect![[r#"ty: u32, name: x"#]],
1373 fn expected_type_struct_field_without_leading_char() {
1374 cov_mark::check!(expected_type_struct_field_without_leading_char);
1375 check_expected_type_and_name(
1377 struct Foo { a: u32 }
1382 expect![[r#"ty: u32, name: a"#]],
1387 fn expected_type_struct_field_followed_by_comma() {
1388 cov_mark::check!(expected_type_struct_field_followed_by_comma);
1389 check_expected_type_and_name(
1391 struct Foo { a: u32 }
1396 expect![[r#"ty: u32, name: a"#]],
1401 fn expected_type_generic_struct_field() {
1402 check_expected_type_and_name(
1404 struct Foo<T> { a: T }
1405 fn foo() -> Foo<u32> {
1409 expect![[r#"ty: u32, name: a"#]],
1414 fn expected_type_struct_field_with_leading_char() {
1415 cov_mark::check!(expected_type_struct_field_with_leading_char);
1416 check_expected_type_and_name(
1418 struct Foo { a: u32 }
1423 expect![[r#"ty: u32, name: a"#]],
1428 fn expected_type_match_arm_without_leading_char() {
1429 cov_mark::check!(expected_type_match_arm_without_leading_char);
1430 check_expected_type_and_name(
1437 expect![[r#"ty: E, name: ?"#]],
1442 fn expected_type_match_arm_with_leading_char() {
1443 cov_mark::check!(expected_type_match_arm_with_leading_char);
1444 check_expected_type_and_name(
1451 expect![[r#"ty: E, name: ?"#]],
1456 fn expected_type_if_let_without_leading_char() {
1457 cov_mark::check!(expected_type_if_let_without_leading_char);
1458 check_expected_type_and_name(
1460 enum Foo { Bar, Baz, Quux }
1467 expect![[r#"ty: Foo, name: ?"#]],
1472 fn expected_type_if_let_with_leading_char() {
1473 cov_mark::check!(expected_type_if_let_with_leading_char);
1474 check_expected_type_and_name(
1476 enum Foo { Bar, Baz, Quux }
1483 expect![[r#"ty: Foo, name: ?"#]],
1488 fn expected_type_fn_ret_without_leading_char() {
1489 cov_mark::check!(expected_type_fn_ret_without_leading_char);
1490 check_expected_type_and_name(
1496 expect![[r#"ty: u32, name: ?"#]],
1501 fn expected_type_fn_ret_with_leading_char() {
1502 cov_mark::check!(expected_type_fn_ret_with_leading_char);
1503 check_expected_type_and_name(
1509 expect![[r#"ty: u32, name: ?"#]],
1514 fn expected_type_fn_ret_fn_ref_fully_typed() {
1515 check_expected_type_and_name(
1521 expect![[r#"ty: u32, name: ?"#]],
1526 fn expected_type_closure_param_return() {
1527 // FIXME: make this work with `|| $0`
1528 check_expected_type_and_name(
1535 fn bar(f: impl FnOnce() -> u32) {}
1537 expect![[r#"ty: u32, name: ?"#]],
1542 fn expected_type_generic_function() {
1543 check_expected_type_and_name(
1551 expect![[r#"ty: u32, name: t"#]],
1556 fn expected_type_generic_method() {
1557 check_expected_type_and_name(
1565 fn bar(self, t: T) {}
1568 expect![[r#"ty: u32, name: t"#]],
1573 fn expected_type_functional_update() {
1574 cov_mark::check!(expected_type_struct_func_update);
1575 check_expected_type_and_name(
1577 struct Foo { field: u32 }
1584 expect![[r#"ty: Foo, name: ?"#]],
1589 fn expected_type_param_pat() {
1590 check_expected_type_and_name(
1592 struct Foo { field: u32 }
1595 expect![[r#"ty: Foo, name: ?"#]],
1597 check_expected_type_and_name(
1599 struct Foo { field: u32 }
1602 // FIXME make this work, currently fails due to pattern recovery eating the `:`
1603 expect![[r#"ty: ?, name: ?"#]],