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 pub(super) expected_name: Option<NameOrNameRef>,
107 pub(super) expected_type: Option<Type>,
109 /// The parent function of the cursor position if it exists.
110 pub(super) function_def: Option<ast::Fn>,
111 pub(super) attr: Option<ast::Attr>,
112 /// The parent impl of the cursor position if it exists.
113 pub(super) impl_def: Option<ast::Impl>,
114 /// The NameLike under the cursor in the original file if it exists.
115 pub(super) name_syntax: Option<ast::NameLike>,
116 pub(super) incomplete_let: bool,
118 pub(super) completion_location: Option<ImmediateLocation>,
119 pub(super) prev_sibling: Option<ImmediatePrevSibling>,
120 pub(super) fake_attribute_under_caret: Option<ast::Attr>,
121 pub(super) previous_token: Option<SyntaxToken>,
123 pub(super) lifetime_ctx: Option<LifetimeContext>,
124 pub(super) pattern_ctx: Option<PatternContext>,
125 pub(super) path_context: Option<PathCompletionContext>,
127 pub(super) locals: Vec<(Name, Local)>,
129 no_completion_required: bool,
132 impl<'a> CompletionContext<'a> {
133 /// Checks whether completions in that particular case don't make much sense.
135 /// - `fn $0` -- we expect function name, it's unlikely that "hint" will be helpful.
136 /// Exception for this case is `impl Trait for Foo`, where we would like to hint trait method names.
137 /// - `for _ i$0` -- obviously, it'll be "in" keyword.
138 pub(crate) fn no_completion_required(&self) -> bool {
139 self.no_completion_required
142 /// The range of the identifier that is being completed.
143 pub(crate) fn source_range(&self) -> TextRange {
144 // check kind of macro-expanded token, but use range of original token
145 let kind = self.token.kind();
146 if kind == IDENT || kind == LIFETIME_IDENT || kind == UNDERSCORE || kind.is_keyword() {
147 self.original_token.text_range()
148 } else if kind == CHAR {
149 // assume we are completing a lifetime but the user has only typed the '
150 cov_mark::hit!(completes_if_lifetime_without_idents);
151 TextRange::at(self.original_token.text_range().start(), TextSize::from(1))
153 TextRange::empty(self.position.offset)
157 pub(crate) fn previous_token_is(&self, kind: SyntaxKind) -> bool {
158 self.previous_token.as_ref().map_or(false, |tok| tok.kind() == kind)
161 pub(crate) fn famous_defs(&self) -> FamousDefs {
162 FamousDefs(&self.sema, self.krate)
165 pub(crate) fn dot_receiver(&self) -> Option<&ast::Expr> {
166 match &self.completion_location {
168 ImmediateLocation::MethodCall { receiver, .. }
169 | ImmediateLocation::FieldAccess { receiver, .. },
170 ) => receiver.as_ref(),
175 pub(crate) fn has_dot_receiver(&self) -> bool {
177 &self.completion_location,
178 Some(ImmediateLocation::FieldAccess { receiver, .. } | ImmediateLocation::MethodCall { receiver,.. })
179 if receiver.is_some()
183 pub(crate) fn expects_assoc_item(&self) -> bool {
184 matches!(self.completion_location, Some(ImmediateLocation::Trait | ImmediateLocation::Impl))
187 pub(crate) fn expects_variant(&self) -> bool {
188 matches!(self.completion_location, Some(ImmediateLocation::Variant))
191 pub(crate) fn expects_non_trait_assoc_item(&self) -> bool {
192 matches!(self.completion_location, Some(ImmediateLocation::Impl))
195 pub(crate) fn expects_item(&self) -> bool {
196 matches!(self.completion_location, Some(ImmediateLocation::ItemList))
199 pub(crate) fn expects_generic_arg(&self) -> bool {
200 matches!(self.completion_location, Some(ImmediateLocation::GenericArgList(_)))
203 pub(crate) fn has_block_expr_parent(&self) -> bool {
204 matches!(self.completion_location, Some(ImmediateLocation::StmtList))
207 pub(crate) fn expects_ident_pat_or_ref_expr(&self) -> bool {
209 self.completion_location,
210 Some(ImmediateLocation::IdentPat | ImmediateLocation::RefExpr)
214 pub(crate) fn expect_field(&self) -> bool {
216 self.completion_location,
217 Some(ImmediateLocation::RecordField | ImmediateLocation::TupleField)
221 pub(crate) fn has_impl_or_trait_prev_sibling(&self) -> bool {
224 Some(ImmediatePrevSibling::ImplDefType | ImmediatePrevSibling::TraitDefName)
228 pub(crate) fn has_impl_prev_sibling(&self) -> bool {
229 matches!(self.prev_sibling, Some(ImmediatePrevSibling::ImplDefType))
232 pub(crate) fn has_visibility_prev_sibling(&self) -> bool {
233 matches!(self.prev_sibling, Some(ImmediatePrevSibling::Visibility))
236 pub(crate) fn after_if(&self) -> bool {
237 matches!(self.prev_sibling, Some(ImmediatePrevSibling::IfExpr))
240 pub(crate) fn is_path_disallowed(&self) -> bool {
241 self.previous_token_is(T![unsafe])
244 Some(ImmediatePrevSibling::Attribute | ImmediatePrevSibling::Visibility)
247 self.completion_location,
249 ImmediateLocation::ModDeclaration(_)
250 | ImmediateLocation::RecordPat(_)
251 | ImmediateLocation::RecordExpr(_)
252 | ImmediateLocation::Rename
257 pub(crate) fn expects_expression(&self) -> bool {
258 matches!(self.path_context, Some(PathCompletionContext { kind: Some(PathKind::Expr), .. }))
261 pub(crate) fn expects_type(&self) -> bool {
262 matches!(self.path_context, Some(PathCompletionContext { kind: Some(PathKind::Type), .. }))
265 pub(crate) fn path_is_call(&self) -> bool {
266 self.path_context.as_ref().map_or(false, |it| it.has_call_parens)
269 pub(crate) fn is_trivial_path(&self) -> bool {
270 matches!(self.path_context, Some(PathCompletionContext { is_trivial_path: true, .. }))
273 pub(crate) fn is_non_trivial_path(&self) -> bool {
274 matches!(self.path_context, Some(PathCompletionContext { is_trivial_path: false, .. }))
277 pub(crate) fn path_qual(&self) -> Option<&ast::Path> {
278 self.path_context.as_ref().and_then(|it| it.qualifier.as_ref())
281 pub(crate) fn path_kind(&self) -> Option<PathKind> {
282 self.path_context.as_ref().and_then(|it| it.kind)
285 /// Checks if an item is visible and not `doc(hidden)` at the completion site.
286 pub(crate) fn is_visible<I>(&self, item: &I) -> bool
288 I: hir::HasVisibility + hir::HasAttrs + hir::HasCrate + Copy,
290 self.is_visible_impl(&item.visibility(self.db), &item.attrs(self.db), item.krate(self.db))
293 pub(crate) fn is_scope_def_hidden(&self, scope_def: ScopeDef) -> bool {
294 if let (Some(attrs), Some(krate)) = (scope_def.attrs(self.db), scope_def.krate(self.db)) {
295 return self.is_doc_hidden(&attrs, krate);
301 /// Check if an item is `#[doc(hidden)]`.
302 pub(crate) fn is_item_hidden(&self, item: &hir::ItemInNs) -> bool {
303 let attrs = item.attrs(self.db);
304 let krate = item.krate(self.db);
305 match (attrs, krate) {
306 (Some(attrs), Some(krate)) => self.is_doc_hidden(&attrs, krate),
311 pub(crate) fn is_immediately_after_macro_bang(&self) -> bool {
312 self.token.kind() == BANG && self.token.parent().map_or(false, |it| it.kind() == MACRO_CALL)
315 /// Whether the given trait is an operator trait or not.
316 pub(crate) fn is_ops_trait(&self, trait_: hir::Trait) -> bool {
317 match trait_.attrs(self.db).lang() {
318 Some(lang) => OP_TRAIT_LANG_NAMES.contains(&lang.as_str()),
323 /// A version of [`SemanticsScope::process_all_names`] that filters out `#[doc(hidden)]` items.
324 pub(crate) fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
325 let _p = profile::span("CompletionContext::process_all_names");
326 self.scope.process_all_names(&mut |name, def| {
327 if self.is_scope_def_hidden(def) {
337 vis: &hir::Visibility,
339 defining_crate: hir::Crate,
341 let module = match self.scope.module() {
343 None => return false,
345 if !vis.is_visible_from(self.db, module.into()) {
346 // If the definition location is editable, also show private items
347 let root_file = defining_crate.root_file(self.db);
348 let source_root_id = self.db.file_source_root(root_file);
349 let is_editable = !self.db.source_root(source_root_id).is_library;
353 !self.is_doc_hidden(attrs, defining_crate)
356 fn is_doc_hidden(&self, attrs: &hir::Attrs, defining_crate: hir::Crate) -> bool {
357 let krate = match self.krate {
361 if krate != defining_crate && attrs.has_doc_hidden() {
362 // `doc(hidden)` items are only completed within the defining crate.
370 // CompletionContext construction
371 impl<'a> CompletionContext<'a> {
373 db: &'a RootDatabase,
374 position @ FilePosition { file_id, offset }: FilePosition,
375 config: &'a CompletionConfig,
376 ) -> Option<CompletionContext<'a>> {
377 let _p = profile::span("CompletionContext::new");
378 let sema = Semantics::new(db);
380 let original_file = sema.parse(file_id);
382 // Insert a fake ident to get a valid parse tree. We will use this file
383 // to determine context, though the original_file will be used for
384 // actual completion.
385 let file_with_fake_ident = {
386 let parse = db.parse(file_id);
387 let edit = Indel::insert(offset, COMPLETION_MARKER.to_string());
388 parse.reparse(&edit).tree()
390 let fake_ident_token =
391 file_with_fake_ident.syntax().token_at_offset(offset).right_biased()?;
393 let original_token = original_file.syntax().token_at_offset(offset).left_biased()?;
394 let token = sema.descend_into_macros_single(original_token.clone());
395 let scope = sema.scope_at_offset(&token.parent()?, offset);
396 let krate = scope.krate();
397 let mut locals = vec![];
398 scope.process_all_names(&mut |name, scope| {
399 if let ScopeDef::Local(local) = scope {
400 locals.push((name, local));
404 let mut ctx = CompletionContext {
421 completion_location: None,
423 fake_attribute_under_caret: None,
424 previous_token: None,
427 incomplete_let: false,
428 no_completion_required: false,
431 original_file.syntax().clone(),
432 file_with_fake_ident.syntax().clone(),
439 /// Do the attribute expansion at the current cursor position for both original file and fake file
440 /// as long as possible. As soon as one of the two expansions fail we stop to stay in sync.
443 mut original_file: SyntaxNode,
444 mut speculative_file: SyntaxNode,
445 mut offset: TextSize,
446 mut fake_ident_token: SyntaxToken,
448 let _p = profile::span("CompletionContext::expand_and_fill");
451 |item: &ast::Item| item.syntax().ancestors().skip(1).find_map(ast::Item::cast);
452 let ancestor_items = iter::successors(
454 find_node_at_offset::<ast::Item>(&original_file, offset),
455 find_node_at_offset::<ast::Item>(&speculative_file, offset),
457 |(a, b)| parent_item(a).zip(parent_item(b)),
459 for (actual_item, item_with_fake_ident) in ancestor_items {
461 self.sema.expand_attr_macro(&actual_item),
462 self.sema.speculative_expand_attr_macro(
464 &item_with_fake_ident,
465 fake_ident_token.clone(),
468 // maybe parent items have attributes
470 // successful expansions
471 (Some(actual_expansion), Some((fake_expansion, fake_mapped_token))) => {
472 let new_offset = fake_mapped_token.text_range().start();
473 if new_offset > actual_expansion.text_range().end() {
476 original_file = actual_expansion;
477 speculative_file = fake_expansion;
478 fake_ident_token = fake_mapped_token;
482 // exactly one expansion failed, inconsistent state so stop expanding completely
483 _ => break 'expansion,
487 // Expand fn-like macro calls
488 if let (Some(actual_macro_call), Some(macro_call_with_fake_ident)) = (
489 find_node_at_offset::<ast::MacroCall>(&original_file, offset),
490 find_node_at_offset::<ast::MacroCall>(&speculative_file, offset),
492 let mac_call_path0 = actual_macro_call.path().as_ref().map(|s| s.syntax().text());
494 macro_call_with_fake_ident.path().as_ref().map(|s| s.syntax().text());
495 if mac_call_path0 != mac_call_path1 {
498 let speculative_args = match macro_call_with_fake_ident.token_tree() {
504 self.sema.expand(&actual_macro_call),
505 self.sema.speculative_expand(
508 fake_ident_token.clone(),
511 // successful expansions
512 (Some(actual_expansion), Some((fake_expansion, fake_mapped_token))) => {
513 let new_offset = fake_mapped_token.text_range().start();
514 if new_offset > actual_expansion.text_range().end() {
517 original_file = actual_expansion;
518 speculative_file = fake_expansion;
519 fake_ident_token = fake_mapped_token;
530 self.fill(&original_file, speculative_file, offset);
533 fn expected_type_and_name(&self) -> (Option<Type>, Option<NameOrNameRef>) {
534 let mut node = match self.token.parent() {
536 None => return (None, None),
541 ast::LetStmt(it) => {
542 cov_mark::hit!(expected_type_let_with_leading_char);
543 cov_mark::hit!(expected_type_let_without_leading_char);
545 .and_then(|pat| self.sema.type_of_pat(&pat))
546 .or_else(|| it.initializer().and_then(|it| self.sema.type_of_expr(&it)))
547 .map(TypeInfo::original);
548 let name = match it.pat() {
549 Some(ast::Pat::IdentPat(ident)) => ident.name().map(NameOrNameRef::Name),
550 Some(_) | None => None,
556 cov_mark::hit!(expected_type_fn_param);
557 ActiveParameter::at_token(
561 let name = ap.ident().map(NameOrNameRef::Name);
562 let ty = if has_ref(&self.token) {
563 cov_mark::hit!(expected_type_fn_param_ref);
570 .unwrap_or((None, None))
572 ast::RecordExprFieldList(it) => {
573 // wouldn't try {} be nice...
575 if self.token.kind() == T![..]
576 || self.token.prev_token().map(|t| t.kind()) == Some(T![..])
578 cov_mark::hit!(expected_type_struct_func_update);
579 let record_expr = it.syntax().parent().and_then(ast::RecordExpr::cast)?;
580 let ty = self.sema.type_of_expr(&record_expr.into())?;
586 cov_mark::hit!(expected_type_struct_field_without_leading_char);
587 let expr_field = self.token.prev_sibling_or_token()?
589 .and_then(ast::RecordExprField::cast)?;
590 let (_, _, ty) = self.sema.resolve_record_field(&expr_field)?;
593 expr_field.field_name().map(NameOrNameRef::NameRef),
596 })().unwrap_or((None, None))
598 ast::RecordExprField(it) => {
599 if let Some(expr) = it.expr() {
600 cov_mark::hit!(expected_type_struct_field_with_leading_char);
602 self.sema.type_of_expr(&expr).map(TypeInfo::original),
603 it.field_name().map(NameOrNameRef::NameRef),
606 cov_mark::hit!(expected_type_struct_field_followed_by_comma);
607 let ty = self.sema.resolve_record_field(&it)
608 .map(|(_, _, ty)| ty);
611 it.field_name().map(NameOrNameRef::NameRef),
615 ast::MatchExpr(it) => {
616 cov_mark::hit!(expected_type_match_arm_without_leading_char);
617 let ty = it.expr().and_then(|e| self.sema.type_of_expr(&e)).map(TypeInfo::original);
621 cov_mark::hit!(expected_type_if_let_without_leading_char);
622 let ty = it.condition()
623 .and_then(|cond| cond.expr())
624 .and_then(|e| self.sema.type_of_expr(&e))
625 .map(TypeInfo::original);
628 ast::IdentPat(it) => {
629 cov_mark::hit!(expected_type_if_let_with_leading_char);
630 cov_mark::hit!(expected_type_match_arm_with_leading_char);
631 let ty = self.sema.type_of_pat(&ast::Pat::from(it)).map(TypeInfo::original);
635 cov_mark::hit!(expected_type_fn_ret_with_leading_char);
636 cov_mark::hit!(expected_type_fn_ret_without_leading_char);
637 let def = self.sema.to_def(&it);
638 (def.map(|def| def.ret_type(self.db)), None)
640 ast::ClosureExpr(it) => {
641 let ty = self.sema.type_of_expr(&it.into());
642 ty.and_then(|ty| ty.original.as_callable(self.db))
643 .map(|c| (Some(c.return_type()), None))
644 .unwrap_or((None, None))
646 ast::ParamList(_) => (None, None),
647 ast::Stmt(_) => (None, None),
648 ast::Item(_) => (None, None),
650 match node.parent() {
655 None => (None, None),
665 original_file: &SyntaxNode,
666 file_with_fake_ident: SyntaxNode,
669 let fake_ident_token = file_with_fake_ident.token_at_offset(offset).right_biased().unwrap();
670 let syntax_element = NodeOrToken::Token(fake_ident_token);
671 self.previous_token = previous_token(syntax_element.clone());
672 self.no_completion_required = {
673 let inside_impl_trait_block = inside_impl_trait_block(syntax_element.clone());
674 let fn_is_prev = self.previous_token_is(T![fn]);
675 let for_is_prev2 = for_is_prev2(syntax_element.clone());
676 (fn_is_prev && !inside_impl_trait_block) || for_is_prev2
681 .token_ancestors_with_macros(self.token.clone())
682 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
683 .find_map(ast::Attr::cast);
684 self.fake_attribute_under_caret = syntax_element.ancestors().find_map(ast::Attr::cast);
686 self.incomplete_let =
687 syntax_element.ancestors().take(6).find_map(ast::LetStmt::cast).map_or(false, |it| {
688 it.syntax().text_range().end() == syntax_element.text_range().end()
691 let (expected_type, expected_name) = self.expected_type_and_name();
692 self.expected_type = expected_type;
693 self.expected_name = expected_name;
695 let name_like = match find_node_at_offset(&file_with_fake_ident, offset) {
699 self.completion_location =
700 determine_location(&self.sema, original_file, offset, &name_like);
701 self.prev_sibling = determine_prev_sibling(&name_like);
703 find_node_at_offset(original_file, name_like.syntax().text_range().start());
706 .token_ancestors_with_macros(self.token.clone())
707 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
708 .find_map(ast::Impl::cast);
709 self.function_def = self
711 .token_ancestors_with_macros(self.token.clone())
712 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
713 .find_map(ast::Fn::cast);
715 ast::NameLike::Lifetime(lifetime) => {
717 Self::classify_lifetime(&self.sema, original_file, lifetime, offset);
719 ast::NameLike::NameRef(name_ref) => {
720 if let Some((path_ctx, pat_ctx)) =
721 Self::classify_name_ref(&self.sema, original_file, name_ref)
723 self.path_context = Some(path_ctx);
724 self.pattern_ctx = pat_ctx;
727 ast::NameLike::Name(name) => {
728 self.pattern_ctx = Self::classify_name(&self.sema, original_file, name);
733 fn classify_lifetime(
734 sema: &Semantics<RootDatabase>,
735 original_file: &SyntaxNode,
736 lifetime: ast::Lifetime,
738 ) -> Option<LifetimeContext> {
739 let parent = lifetime.syntax().parent()?;
740 if parent.kind() == ERROR {
746 ast::LifetimeParam(_) => LifetimeContext::LifetimeParam(sema.find_node_at_offset_with_macros(original_file, offset)),
747 ast::BreakExpr(_) => LifetimeContext::LabelRef,
748 ast::ContinueExpr(_) => LifetimeContext::LabelRef,
749 ast::Label(_) => LifetimeContext::LabelDef,
750 _ => LifetimeContext::Lifetime,
756 _sema: &Semantics<RootDatabase>,
757 original_file: &SyntaxNode,
759 ) -> Option<PatternContext> {
760 let bind_pat = name.syntax().parent().and_then(ast::IdentPat::cast)?;
761 let is_name_in_field_pat = bind_pat
764 .and_then(ast::RecordPatField::cast)
765 .map_or(false, |pat_field| pat_field.name_ref().is_none());
766 if is_name_in_field_pat {
769 if !bind_pat.is_simple_ident() {
772 Some(pattern_context_for(original_file, bind_pat.into()))
775 fn classify_name_ref(
776 _sema: &Semantics<RootDatabase>,
777 original_file: &SyntaxNode,
778 name_ref: ast::NameRef,
779 ) -> Option<(PathCompletionContext, Option<PatternContext>)> {
780 let parent = name_ref.syntax().parent()?;
781 let segment = ast::PathSegment::cast(parent)?;
782 let path = segment.parent_path();
784 let mut path_ctx = PathCompletionContext {
785 has_call_parens: false,
786 is_trivial_path: false,
789 has_type_args: false,
792 use_tree_parent: false,
795 let mut pat_ctx = None;
796 path_ctx.in_loop_body = is_in_loop_body(name_ref.syntax());
798 path_ctx.kind = path.syntax().ancestors().find_map(|it| {
801 ast::PathType(_) => Some(PathKind::Type),
802 ast::PathExpr(it) => {
803 path_ctx.has_call_parens = it.syntax().parent().map_or(false, |it| ast::CallExpr::can_cast(it.kind()));
806 ast::TupleStructPat(it) => {
807 path_ctx.has_call_parens = true;
808 pat_ctx = Some(pattern_context_for(original_file, it.into()));
811 ast::RecordPat(it) => {
812 pat_ctx = Some(pattern_context_for(original_file, it.into()));
815 ast::PathPat(it) => {
816 pat_ctx = Some(pattern_context_for(original_file, it.into()));
819 ast::MacroCall(it) => it.excl_token().and(Some(PathKind::Mac)),
820 ast::Meta(_) => Some(PathKind::Attr),
821 ast::Visibility(it) => Some(PathKind::Vis { has_in_token: it.in_token().is_some() }),
822 ast::UseTree(_) => Some(PathKind::Use),
827 path_ctx.has_type_args = segment.generic_arg_list().is_some();
829 if let Some((path, use_tree_parent)) = path_or_use_tree_qualifier(&path) {
830 path_ctx.use_tree_parent = use_tree_parent;
831 path_ctx.qualifier = path
833 .and_then(|it| find_node_in_file(original_file, &it))
834 .map(|it| it.parent_path());
835 return Some((path_ctx, pat_ctx));
838 if let Some(segment) = path.segment() {
839 if segment.coloncolon_token().is_some() {
840 return Some((path_ctx, pat_ctx));
844 path_ctx.is_trivial_path = true;
846 // Find either enclosing expr statement (thing with `;`) or a
847 // block. If block, check that we are the last expr.
848 path_ctx.can_be_stmt = name_ref
852 if let Some(stmt) = ast::ExprStmt::cast(node.clone()) {
853 return Some(stmt.syntax().text_range() == name_ref.syntax().text_range());
855 if let Some(stmt_list) = ast::StmtList::cast(node) {
857 stmt_list.tail_expr().map(|e| e.syntax().text_range())
858 == Some(name_ref.syntax().text_range()),
864 Some((path_ctx, pat_ctx))
868 fn pattern_context_for(original_file: &SyntaxNode, pat: ast::Pat) -> PatternContext {
869 let mut is_param = None;
870 let (refutability, has_type_ascription) =
874 .skip_while(|it| ast::Pat::can_cast(it.kind()))
876 .map_or((PatternRefutability::Irrefutable, false), |node| {
877 let refutability = match_ast! {
879 ast::LetStmt(let_) => return (PatternRefutability::Irrefutable, let_.ty().is_some()),
880 ast::Param(param) => {
881 let has_type_ascription = param.ty().is_some();
883 let fake_param_list = param.syntax().parent().and_then(ast::ParamList::cast)?;
884 let param_list = find_node_in_file_compensated(original_file, &fake_param_list)?;
885 let param_list_owner = param_list.syntax().parent()?;
886 let kind = match_ast! {
887 match param_list_owner {
888 ast::ClosureExpr(closure) => ParamKind::Closure(closure),
889 ast::Fn(fn_) => ParamKind::Function(fn_),
893 Some((param_list, param, kind))
895 return (PatternRefutability::Irrefutable, has_type_ascription)
897 ast::MatchArm(_) => PatternRefutability::Refutable,
898 ast::Condition(_) => PatternRefutability::Refutable,
899 ast::ForExpr(_) => PatternRefutability::Irrefutable,
900 _ => PatternRefutability::Irrefutable,
903 (refutability, false)
905 PatternContext { refutability, param_ctx: is_param, has_type_ascription }
908 fn find_node_in_file<N: AstNode>(syntax: &SyntaxNode, node: &N) -> Option<N> {
909 let syntax_range = syntax.text_range();
910 let range = node.syntax().text_range();
911 let intersection = range.intersect(syntax_range)?;
912 syntax.covering_element(intersection).ancestors().find_map(N::cast)
915 /// Compensates for the offset introduced by the fake ident
916 /// This is wrong if `node` comes before the insertion point! Use `find_node_in_file` instead.
917 fn find_node_in_file_compensated<N: AstNode>(syntax: &SyntaxNode, node: &N) -> Option<N> {
918 let syntax_range = syntax.text_range();
919 let range = node.syntax().text_range();
920 let end = range.end().checked_sub(TextSize::try_from(COMPLETION_MARKER.len()).ok()?)?;
921 if end < range.start() {
924 let range = TextRange::new(range.start(), end);
925 // our inserted ident could cause `range` to be go outside of the original syntax, so cap it
926 let intersection = range.intersect(syntax_range)?;
927 syntax.covering_element(intersection).ancestors().find_map(N::cast)
930 fn path_or_use_tree_qualifier(path: &ast::Path) -> Option<(ast::Path, bool)> {
931 if let Some(qual) = path.qualifier() {
932 return Some((qual, false));
934 let use_tree_list = path.syntax().ancestors().find_map(ast::UseTreeList::cast)?;
935 let use_tree = use_tree_list.syntax().parent().and_then(ast::UseTree::cast)?;
936 use_tree.path().zip(Some(true))
939 fn has_ref(token: &SyntaxToken) -> bool {
940 let mut token = token.clone();
941 for skip in [IDENT, WHITESPACE, T![mut]] {
942 if token.kind() == skip {
943 token = match token.prev_token() {
945 None => return false,
949 token.kind() == T![&]
952 const OP_TRAIT_LANG_NAMES: &[&str] = &[
986 use expect_test::{expect, Expect};
989 use crate::tests::{position, TEST_CONFIG};
991 use super::CompletionContext;
993 fn check_expected_type_and_name(ra_fixture: &str, expect: Expect) {
994 let (db, pos) = position(ra_fixture);
995 let config = TEST_CONFIG;
996 let completion_context = CompletionContext::new(&db, pos, &config).unwrap();
998 let ty = completion_context
1000 .map(|t| t.display_test(&db).to_string())
1001 .unwrap_or("?".to_owned());
1003 let name = completion_context
1005 .map_or_else(|| "?".to_owned(), |name| name.to_string());
1007 expect.assert_eq(&format!("ty: {}, name: {}", ty, name));
1011 fn expected_type_let_without_leading_char() {
1012 cov_mark::check!(expected_type_let_without_leading_char);
1013 check_expected_type_and_name(
1019 expect![[r#"ty: u32, name: x"#]],
1024 fn expected_type_let_with_leading_char() {
1025 cov_mark::check!(expected_type_let_with_leading_char);
1026 check_expected_type_and_name(
1032 expect![[r#"ty: u32, name: x"#]],
1037 fn expected_type_let_pat() {
1038 check_expected_type_and_name(
1044 expect![[r#"ty: u32, name: ?"#]],
1046 check_expected_type_and_name(
1052 expect![[r#"ty: u32, name: ?"#]],
1057 fn expected_type_fn_param() {
1058 cov_mark::check!(expected_type_fn_param);
1059 check_expected_type_and_name(
1061 fn foo() { bar($0); }
1064 expect![[r#"ty: u32, name: x"#]],
1066 check_expected_type_and_name(
1068 fn foo() { bar(c$0); }
1071 expect![[r#"ty: u32, name: x"#]],
1076 fn expected_type_fn_param_ref() {
1077 cov_mark::check!(expected_type_fn_param_ref);
1078 check_expected_type_and_name(
1080 fn foo() { bar(&$0); }
1083 expect![[r#"ty: u32, name: x"#]],
1085 check_expected_type_and_name(
1087 fn foo() { bar(&mut $0); }
1088 fn bar(x: &mut u32) {}
1090 expect![[r#"ty: u32, name: x"#]],
1092 check_expected_type_and_name(
1094 fn foo() { bar(& c$0); }
1097 expect![[r#"ty: u32, name: x"#]],
1099 check_expected_type_and_name(
1101 fn foo() { bar(&mut c$0); }
1102 fn bar(x: &mut u32) {}
1104 expect![[r#"ty: u32, name: x"#]],
1106 check_expected_type_and_name(
1108 fn foo() { bar(&c$0); }
1111 expect![[r#"ty: u32, name: x"#]],
1116 fn expected_type_struct_field_without_leading_char() {
1117 cov_mark::check!(expected_type_struct_field_without_leading_char);
1118 check_expected_type_and_name(
1120 struct Foo { a: u32 }
1125 expect![[r#"ty: u32, name: a"#]],
1130 fn expected_type_struct_field_followed_by_comma() {
1131 cov_mark::check!(expected_type_struct_field_followed_by_comma);
1132 check_expected_type_and_name(
1134 struct Foo { a: u32 }
1139 expect![[r#"ty: u32, name: a"#]],
1144 fn expected_type_generic_struct_field() {
1145 check_expected_type_and_name(
1147 struct Foo<T> { a: T }
1148 fn foo() -> Foo<u32> {
1152 expect![[r#"ty: u32, name: a"#]],
1157 fn expected_type_struct_field_with_leading_char() {
1158 cov_mark::check!(expected_type_struct_field_with_leading_char);
1159 check_expected_type_and_name(
1161 struct Foo { a: u32 }
1166 expect![[r#"ty: u32, name: a"#]],
1171 fn expected_type_match_arm_without_leading_char() {
1172 cov_mark::check!(expected_type_match_arm_without_leading_char);
1173 check_expected_type_and_name(
1180 expect![[r#"ty: E, name: ?"#]],
1185 fn expected_type_match_arm_with_leading_char() {
1186 cov_mark::check!(expected_type_match_arm_with_leading_char);
1187 check_expected_type_and_name(
1194 expect![[r#"ty: E, name: ?"#]],
1199 fn expected_type_if_let_without_leading_char() {
1200 cov_mark::check!(expected_type_if_let_without_leading_char);
1201 check_expected_type_and_name(
1203 enum Foo { Bar, Baz, Quux }
1210 expect![[r#"ty: Foo, name: ?"#]],
1215 fn expected_type_if_let_with_leading_char() {
1216 cov_mark::check!(expected_type_if_let_with_leading_char);
1217 check_expected_type_and_name(
1219 enum Foo { Bar, Baz, Quux }
1226 expect![[r#"ty: Foo, name: ?"#]],
1231 fn expected_type_fn_ret_without_leading_char() {
1232 cov_mark::check!(expected_type_fn_ret_without_leading_char);
1233 check_expected_type_and_name(
1239 expect![[r#"ty: u32, name: ?"#]],
1244 fn expected_type_fn_ret_with_leading_char() {
1245 cov_mark::check!(expected_type_fn_ret_with_leading_char);
1246 check_expected_type_and_name(
1252 expect![[r#"ty: u32, name: ?"#]],
1257 fn expected_type_fn_ret_fn_ref_fully_typed() {
1258 check_expected_type_and_name(
1264 expect![[r#"ty: u32, name: ?"#]],
1269 fn expected_type_closure_param_return() {
1270 // FIXME: make this work with `|| $0`
1271 check_expected_type_and_name(
1278 fn bar(f: impl FnOnce() -> u32) {}
1280 expect![[r#"ty: u32, name: ?"#]],
1285 fn expected_type_generic_function() {
1286 check_expected_type_and_name(
1294 expect![[r#"ty: u32, name: t"#]],
1299 fn expected_type_generic_method() {
1300 check_expected_type_and_name(
1308 fn bar(self, t: T) {}
1311 expect![[r#"ty: u32, name: t"#]],
1316 fn expected_type_functional_update() {
1317 cov_mark::check!(expected_type_struct_func_update);
1318 check_expected_type_and_name(
1320 struct Foo { field: u32 }
1327 expect![[r#"ty: Foo, name: ?"#]],
1332 fn expected_type_param_pat() {
1333 check_expected_type_and_name(
1335 struct Foo { field: u32 }
1338 expect![[r#"ty: Foo, name: ?"#]],
1340 check_expected_type_and_name(
1342 struct Foo { field: u32 }
1345 // FIXME make this work, currently fails due to pattern recovery eating the `:`
1346 expect![[r#"ty: ?, name: ?"#]],