1 //! `render` module provides utilities for rendering completion suggestions
2 //! into code pieces that will be presented to user.
5 pub(crate) mod function;
6 pub(crate) mod enum_variant;
8 pub(crate) mod pattern;
9 pub(crate) mod type_alias;
10 pub(crate) mod struct_literal;
14 use hir::{AsAssocItem, HasAttrs, HirDisplay};
16 helpers::{item_name, SnippetCap},
17 RootDatabase, SymbolKind,
19 use syntax::{SyntaxKind, TextRange};
22 context::{PathCompletionContext, PathKind},
23 item::{CompletionRelevanceTypeMatch, ImportEdit},
24 render::{enum_variant::render_variant, function::render_fn, macro_::render_macro},
25 CompletionContext, CompletionItem, CompletionItemKind, CompletionKind, CompletionRelevance,
27 /// Interface for data and methods required for items rendering.
29 pub(crate) struct RenderContext<'a> {
30 completion: &'a CompletionContext<'a>,
33 impl<'a> RenderContext<'a> {
34 pub(crate) fn new(completion: &'a CompletionContext<'a>) -> RenderContext<'a> {
35 RenderContext { completion }
38 fn snippet_cap(&self) -> Option<SnippetCap> {
39 self.completion.config.snippet_cap
42 fn db(&self) -> &'a RootDatabase {
46 fn source_range(&self) -> TextRange {
47 self.completion.source_range()
50 fn is_deprecated(&self, node: impl HasAttrs) -> bool {
51 let attrs = node.attrs(self.db());
52 attrs.by_key("deprecated").exists() || attrs.by_key("rustc_deprecated").exists()
55 fn is_deprecated_assoc_item(&self, as_assoc_item: impl AsAssocItem) -> bool {
57 let assoc = match as_assoc_item.as_assoc_item(db) {
62 let is_assoc_deprecated = match assoc {
63 hir::AssocItem::Function(it) => self.is_deprecated(it),
64 hir::AssocItem::Const(it) => self.is_deprecated(it),
65 hir::AssocItem::TypeAlias(it) => self.is_deprecated(it),
69 .containing_trait_or_trait_impl(db)
70 .map(|trait_| self.is_deprecated(trait_))
74 fn docs(&self, node: impl HasAttrs) -> Option<hir::Documentation> {
79 pub(crate) fn render_field(
80 ctx: RenderContext<'_>,
81 receiver: Option<hir::Name>,
85 let is_deprecated = ctx.is_deprecated(field);
86 let name = field.name(ctx.db()).to_string();
87 let mut item = CompletionItem::new(
88 CompletionKind::Reference,
90 receiver.map_or_else(|| name.clone(), |receiver| format!("{}.{}", receiver, name)),
92 item.set_relevance(CompletionRelevance {
93 type_match: compute_type_match(ctx.completion, ty),
94 exact_name_match: compute_exact_name_match(ctx.completion, name.as_str()),
95 ..CompletionRelevance::default()
97 item.kind(SymbolKind::Field)
98 .detail(ty.display(ctx.db()).to_string())
99 .set_documentation(field.docs(ctx.db()))
100 .set_deprecated(is_deprecated)
101 .lookup_by(name.as_str());
102 let is_keyword = SyntaxKind::from_keyword(name.as_str()).is_some();
103 if is_keyword && !matches!(name.as_str(), "self" | "crate" | "super" | "Self") {
104 item.insert_text(format!("r#{}", name));
106 if let Some(_ref_match) = compute_ref_match(ctx.completion, ty) {
108 // For now we don't properly calculate the edits for ref match
109 // completions on struct fields, so we've disabled them. See #8058.
114 pub(crate) fn render_tuple_field(
115 ctx: RenderContext<'_>,
116 receiver: Option<hir::Name>,
119 ) -> CompletionItem {
120 let mut item = CompletionItem::new(
121 CompletionKind::Reference,
123 receiver.map_or_else(|| field.to_string(), |receiver| format!("{}.{}", receiver, field)),
125 item.kind(SymbolKind::Field)
126 .detail(ty.display(ctx.db()).to_string())
127 .lookup_by(field.to_string());
131 pub(crate) fn render_resolution(
132 ctx: RenderContext<'_>,
133 local_name: hir::Name,
134 resolution: &hir::ScopeDef,
135 ) -> Option<CompletionItem> {
136 render_resolution_(ctx, local_name, None, resolution)
139 pub(crate) fn render_resolution_with_import(
140 ctx: RenderContext<'_>,
141 import_edit: ImportEdit,
142 ) -> Option<CompletionItem> {
143 let resolution = hir::ScopeDef::from(import_edit.import.original_item);
144 let local_name = match resolution {
145 hir::ScopeDef::ModuleDef(hir::ModuleDef::Function(f)) => f.name(ctx.completion.db),
146 hir::ScopeDef::ModuleDef(hir::ModuleDef::Const(c)) => c.name(ctx.completion.db)?,
147 hir::ScopeDef::ModuleDef(hir::ModuleDef::TypeAlias(t)) => t.name(ctx.completion.db),
148 _ => item_name(ctx.db(), import_edit.import.original_item)?,
150 render_resolution_(ctx, local_name, Some(import_edit), &resolution).map(|mut item| {
151 item.completion_kind = CompletionKind::Magic;
156 fn render_resolution_(
157 ctx: RenderContext<'_>,
158 local_name: hir::Name,
159 import_to_add: Option<ImportEdit>,
160 resolution: &hir::ScopeDef,
161 ) -> Option<CompletionItem> {
162 let _p = profile::span("render_resolution");
163 use hir::ModuleDef::*;
165 let completion_kind = match resolution {
166 hir::ScopeDef::ModuleDef(BuiltinType(..)) => CompletionKind::BuiltinType,
167 _ => CompletionKind::Reference,
170 let kind = match resolution {
171 hir::ScopeDef::ModuleDef(Function(func)) => {
172 return render_fn(ctx, import_to_add, Some(local_name), *func);
174 hir::ScopeDef::ModuleDef(Variant(_)) if ctx.completion.pattern_ctx.is_some() => {
175 CompletionItemKind::SymbolKind(SymbolKind::Variant)
177 hir::ScopeDef::ModuleDef(Variant(var)) => {
178 let item = render_variant(ctx, import_to_add, Some(local_name), *var, None);
181 hir::ScopeDef::MacroDef(mac) => {
182 let item = render_macro(ctx, import_to_add, local_name, *mac);
186 hir::ScopeDef::ModuleDef(Module(..)) => CompletionItemKind::SymbolKind(SymbolKind::Module),
187 hir::ScopeDef::ModuleDef(Adt(adt)) => CompletionItemKind::SymbolKind(match adt {
188 hir::Adt::Struct(_) => SymbolKind::Struct,
189 hir::Adt::Union(_) => SymbolKind::Union,
190 hir::Adt::Enum(_) => SymbolKind::Enum,
192 hir::ScopeDef::ModuleDef(Const(..)) => CompletionItemKind::SymbolKind(SymbolKind::Const),
193 hir::ScopeDef::ModuleDef(Static(..)) => CompletionItemKind::SymbolKind(SymbolKind::Static),
194 hir::ScopeDef::ModuleDef(Trait(..)) => CompletionItemKind::SymbolKind(SymbolKind::Trait),
195 hir::ScopeDef::ModuleDef(TypeAlias(..)) => {
196 CompletionItemKind::SymbolKind(SymbolKind::TypeAlias)
198 hir::ScopeDef::ModuleDef(BuiltinType(..)) => CompletionItemKind::BuiltinType,
199 hir::ScopeDef::GenericParam(param) => CompletionItemKind::SymbolKind(match param {
200 hir::GenericParam::TypeParam(_) => SymbolKind::TypeParam,
201 hir::GenericParam::LifetimeParam(_) => SymbolKind::LifetimeParam,
202 hir::GenericParam::ConstParam(_) => SymbolKind::ConstParam,
204 hir::ScopeDef::Local(..) => CompletionItemKind::SymbolKind(SymbolKind::Local),
205 hir::ScopeDef::Label(..) => CompletionItemKind::SymbolKind(SymbolKind::Label),
206 hir::ScopeDef::AdtSelfType(..) | hir::ScopeDef::ImplSelfType(..) => {
207 CompletionItemKind::SymbolKind(SymbolKind::SelfParam)
209 hir::ScopeDef::Unknown => {
210 let mut item = CompletionItem::new(
211 CompletionKind::Reference,
213 local_name.to_string(),
215 item.kind(CompletionItemKind::UnresolvedReference);
216 if let Some(import_to_add) = import_to_add {
217 item.add_import(import_to_add);
219 return Some(item.build());
223 let local_name = local_name.to_string();
224 let mut item = CompletionItem::new(completion_kind, ctx.source_range(), local_name.clone());
225 if let hir::ScopeDef::Local(local) = resolution {
226 let ty = local.ty(ctx.db());
227 if !ty.is_unknown() {
228 item.detail(ty.display(ctx.db()).to_string());
231 item.set_relevance(CompletionRelevance {
232 type_match: compute_type_match(ctx.completion, &ty),
233 exact_name_match: compute_exact_name_match(ctx.completion, &local_name),
235 ..CompletionRelevance::default()
238 if let Some(ref_match) = compute_ref_match(ctx.completion, &ty) {
239 item.ref_match(ref_match);
243 // Add `<>` for generic types
245 ctx.completion.path_context,
246 Some(PathCompletionContext { kind: Some(PathKind::Type), has_type_args: false, .. })
247 ) && ctx.completion.config.add_call_parenthesis
249 if let Some(cap) = ctx.snippet_cap() {
250 let has_non_default_type_params = match resolution {
251 hir::ScopeDef::ModuleDef(Adt(it)) => it.has_non_default_type_params(ctx.db()),
252 hir::ScopeDef::ModuleDef(TypeAlias(it)) => it.has_non_default_type_params(ctx.db()),
255 if has_non_default_type_params {
256 cov_mark::hit!(inserts_angle_brackets_for_generics);
257 item.lookup_by(local_name.clone())
258 .label(format!("{}<…>", local_name))
259 .insert_snippet(cap, format!("{}<$0>", local_name));
264 .set_documentation(scope_def_docs(ctx.db(), resolution))
265 .set_deprecated(scope_def_is_deprecated(&ctx, resolution));
267 if let Some(import_to_add) = import_to_add {
268 item.add_import(import_to_add);
273 fn scope_def_docs(db: &RootDatabase, resolution: &hir::ScopeDef) -> Option<hir::Documentation> {
274 use hir::ModuleDef::*;
276 hir::ScopeDef::ModuleDef(Module(it)) => it.docs(db),
277 hir::ScopeDef::ModuleDef(Adt(it)) => it.docs(db),
278 hir::ScopeDef::ModuleDef(Variant(it)) => it.docs(db),
279 hir::ScopeDef::ModuleDef(Const(it)) => it.docs(db),
280 hir::ScopeDef::ModuleDef(Static(it)) => it.docs(db),
281 hir::ScopeDef::ModuleDef(Trait(it)) => it.docs(db),
282 hir::ScopeDef::ModuleDef(TypeAlias(it)) => it.docs(db),
287 fn scope_def_is_deprecated(ctx: &RenderContext<'_>, resolution: &hir::ScopeDef) -> bool {
289 hir::ScopeDef::ModuleDef(it) => ctx.is_deprecated_assoc_item(*it),
290 hir::ScopeDef::MacroDef(it) => ctx.is_deprecated(*it),
291 hir::ScopeDef::GenericParam(it) => ctx.is_deprecated(*it),
292 hir::ScopeDef::AdtSelfType(it) => ctx.is_deprecated(*it),
297 fn compute_type_match(
298 ctx: &CompletionContext,
299 completion_ty: &hir::Type,
300 ) -> Option<CompletionRelevanceTypeMatch> {
301 let expected_type = ctx.expected_type.as_ref()?;
303 // We don't ever consider unit type to be an exact type match, since
304 // nearly always this is not meaningful to the user.
305 if expected_type.is_unit() {
309 if completion_ty == expected_type {
310 Some(CompletionRelevanceTypeMatch::Exact)
311 } else if expected_type.could_unify_with(ctx.db, completion_ty) {
312 Some(CompletionRelevanceTypeMatch::CouldUnify)
318 fn compute_exact_name_match(ctx: &CompletionContext, completion_name: &str) -> bool {
319 ctx.expected_name.as_ref().map_or(false, |name| name.text() == completion_name)
322 fn compute_ref_match(
323 ctx: &CompletionContext,
324 completion_ty: &hir::Type,
325 ) -> Option<hir::Mutability> {
326 let expected_type = ctx.expected_type.as_ref()?;
327 if completion_ty != expected_type {
328 let expected_type_without_ref = expected_type.remove_ref()?;
329 if completion_ty.autoderef(ctx.db).any(|deref_ty| deref_ty == expected_type_without_ref) {
330 cov_mark::hit!(suggest_ref);
331 let mutability = if expected_type.is_mutable_reference() {
334 hir::Mutability::Shared
336 return Some(mutability);
346 use expect_test::{expect, Expect};
347 use itertools::Itertools;
350 item::CompletionRelevanceTypeMatch,
351 tests::{check_edit, do_completion, get_all_items, TEST_CONFIG},
352 CompletionKind, CompletionRelevance,
356 fn check(ra_fixture: &str, expect: Expect) {
357 let actual = do_completion(ra_fixture, CompletionKind::Reference);
358 expect.assert_debug_eq(&actual);
362 fn check_relevance(ra_fixture: &str, expect: Expect) {
363 check_relevance_for_kinds(&[CompletionKind::Reference], ra_fixture, expect)
367 fn check_relevance_for_kinds(kinds: &[CompletionKind], ra_fixture: &str, expect: Expect) {
368 let mut actual = get_all_items(TEST_CONFIG, ra_fixture);
369 actual.retain(|it| kinds.contains(&it.completion_kind));
370 actual.sort_by_key(|it| cmp::Reverse(it.relevance().score()));
375 let mut items = vec![];
377 let tag = it.kind().unwrap().tag();
378 let relevance = display_relevance(it.relevance());
379 items.push(format!("{} {} {}\n", tag, it.label(), relevance));
381 if let Some((mutability, relevance)) = it.ref_match() {
382 let label = format!("&{}{}", mutability.as_keyword_for_ref(), it.label());
383 let relevance = display_relevance(relevance);
385 items.push(format!("{} {} {}\n", tag, label, relevance));
390 .collect::<String>();
392 expect.assert_eq(&actual);
394 fn display_relevance(relevance: CompletionRelevance) -> String {
395 let relevance_factors = vec![
396 (relevance.type_match == Some(CompletionRelevanceTypeMatch::Exact), "type"),
398 relevance.type_match == Some(CompletionRelevanceTypeMatch::CouldUnify),
401 (relevance.exact_name_match, "name"),
402 (relevance.is_local, "local"),
403 (relevance.exact_postfix_snippet_match, "snippet"),
406 .filter_map(|(cond, desc)| if cond { Some(desc) } else { None })
409 format!("[{}]", relevance_factors)
414 fn enum_detail_includes_record_fields() {
417 enum Foo { Foo { x: i32, y: i32 } }
419 fn main() { Foo::Fo$0 }
425 source_range: 54..56,
431 detail: "{ x: i32, y: i32 }",
439 fn enum_detail_doesnt_include_tuple_fields() {
442 enum Foo { Foo (i32, i32) }
444 fn main() { Foo::Fo$0 }
450 source_range: 46..48,
457 detail: "(i32, i32)",
458 trigger_call_info: true,
466 fn fn_detail_includes_args_and_return_type() {
469 fn foo<T>(a: u32, b: u32, t: T) -> (u32, T) { (a, t) }
477 source_range: 68..70,
479 insert: "foo(${1:a}, ${2:b}, ${3:t})$0",
484 detail: "fn(u32, u32, T) -> (u32, T)",
485 trigger_call_info: true,
489 source_range: 68..70,
504 fn enum_detail_just_parentheses_for_unit() {
509 fn main() { Foo::Fo$0 }
515 source_range: 35..37,
529 fn lookup_enums_by_two_qualifiers() {
533 pub enum Spam { Foo, Bar(i32) }
535 fn main() { let _: m::Spam = S$0 }
540 label: "Spam::Bar(…)",
541 source_range: 75..76,
543 insert: "Spam::Bar($0)",
549 relevance: CompletionRelevance {
550 exact_name_match: false,
555 exact_postfix_snippet_match: false,
557 trigger_call_info: true,
561 source_range: 75..76,
569 label: "m::Spam::Foo",
570 source_range: 75..76,
572 insert: "m::Spam::Foo",
578 relevance: CompletionRelevance {
579 exact_name_match: false,
584 exact_postfix_snippet_match: false,
589 source_range: 75..76,
604 fn sets_deprecated_flag_in_items() {
608 fn something_deprecated() {}
609 #[rustc_deprecated(since = "1.0.0")]
610 fn something_else_deprecated() {}
618 source_range: 127..130,
628 label: "something_deprecated()",
629 source_range: 127..130,
631 insert: "something_deprecated()$0",
635 lookup: "something_deprecated",
640 label: "something_else_deprecated()",
641 source_range: 127..130,
643 insert: "something_else_deprecated()$0",
647 lookup: "something_else_deprecated",
657 struct A { #[deprecated] the_field: u32 }
658 fn foo() { A { the$0 } }
664 source_range: 57..60,
672 relevance: CompletionRelevance {
673 exact_name_match: false,
678 exact_postfix_snippet_match: false,
696 fn bar(self) { self.$0 }
702 source_range: 94..94,
708 documentation: Documentation(
714 source_range: 94..94,
721 documentation: Documentation(
747 source_range: 10..12,
753 documentation: Documentation(
759 source_range: 10..12,
766 documentation: Documentation(
772 source_range: 10..12,
778 documentation: Documentation(
788 fn dont_render_attrs() {
794 fn the_method(&self) { }
796 fn foo(s: S) { s.$0 }
801 label: "the_method()",
802 source_range: 81..81,
804 insert: "the_method()$0",
806 lookup: "the_method",
815 fn no_call_parens_if_fn_ptr_needed() {
816 cov_mark::check!(no_call_parens_if_fn_ptr_needed);
820 fn foo(foo: u8, bar: u8) {}
821 struct ManualVtable { f: fn(u8, u8) }
823 fn main() -> ManualVtable {
824 ManualVtable { f: f$0 }
828 fn foo(foo: u8, bar: u8) {}
829 struct ManualVtable { f: fn(u8, u8) }
831 fn main() -> ManualVtable {
832 ManualVtable { f: foo }
839 struct RawIdentTable { r#type: u32 }
841 fn main() -> RawIdentTable {
842 RawIdentTable { t$0: 42 }
846 struct RawIdentTable { r#type: u32 }
848 fn main() -> RawIdentTable {
849 RawIdentTable { r#type: 42 }
856 fn no_parens_in_use_item() {
857 cov_mark::check!(no_parens_in_use_item);
861 mod m { pub fn foo() {} }
865 mod m { pub fn foo() {} }
872 fn no_parens_in_call() {
888 impl Foo { fn foo(&self){} }
889 fn f(foo: &Foo) { foo.f$0(); }
893 impl Foo { fn foo(&self){} }
894 fn f(foo: &Foo) { foo.foo(); }
900 fn inserts_angle_brackets_for_generics() {
901 cov_mark::check!(inserts_angle_brackets_for_generics);
927 struct Vec<T = i128> {}
931 struct Vec<T = i128> {}
939 fn foo(xs: Ve$0<i128>)
943 fn foo(xs: Vec<i128>)
949 fn active_param_relevance() {
952 struct S { foo: i64, bar: u32, baz: u32 }
953 fn test(bar: u32) { }
954 fn foo(s: S) { test(s.$0) }
965 fn record_field_relevances() {
968 struct A { foo: i64, bar: u32, baz: u32 }
969 struct B { x: (), y: f32, bar: u32 }
970 fn foo(a: A) { B { bar: a.$0 }; }
981 fn record_field_and_call_relevances() {
984 struct A { foo: i64, bar: u32, baz: u32 }
985 struct B { x: (), y: f32, bar: u32 }
987 fn foo(a: A) { B { bar: f(a.$0) }; }
997 struct A { foo: i64, bar: u32, baz: u32 }
998 struct B { x: (), y: f32, bar: u32 }
1000 fn foo(a: A) { f(B { bar: a.$0 }); }
1011 fn prioritize_exact_ref_match() {
1014 struct WorldSnapshot { _f: () };
1015 fn go(world: &WorldSnapshot) { go(w$0) }
1018 lc world [type+name+local]
1026 fn too_many_arguments() {
1027 cov_mark::check!(too_many_arguments);
1031 fn f(foo: &Foo) { f(foo, w$0) }
1042 fn score_fn_type_and_name_match() {
1045 struct A { bar: u8 }
1046 fn baz() -> u8 { 0 }
1047 fn bar() -> u8 { 0 }
1048 fn f() { A { bar: b$0 }; }
1051 fn bar() [type+name]
1060 fn score_method_type_and_name_match() {
1066 fn aaa(&self) -> u32 { 0 }
1067 fn bbb(&self) -> u32 { 0 }
1068 fn ccc(&self) -> u64 { 0 }
1075 me aaa() [type+name]
1083 fn score_method_name_match_only() {
1089 fn aaa(&self) -> u64 { 0 }
1102 fn suggest_ref_mut() {
1103 cov_mark::check!(suggest_ref);
1107 fn foo(s: &mut S) {}
1115 lc &mut s [type+name+local]
1124 fn foo(s: &mut S) {}
1131 lc s [type+name+local]
1140 fn suggest_deref() {
1147 impl core::ops::Deref for T {
1150 fn deref(&self) -> &Self::Target {
1179 fn suggest_deref_mut() {
1182 //- minicore: deref_mut
1186 impl core::ops::Deref for T {
1189 fn deref(&self) -> &Self::Target {
1194 impl core::ops::DerefMut for T {
1195 fn deref_mut(&mut self) -> &mut Self::Target {
1200 fn foo(s: &mut S) {}
1212 lc &mut t [type+local]
1284 fn suggest_deref_fn_ret() {
1291 impl core::ops::Deref for T {
1294 fn deref(&self) -> &Self::Target {
1320 fn struct_field_method_ref() {
1323 struct Foo { bar: u32 }
1324 impl Foo { fn baz(&self) -> u32 { 0 } }
1326 fn foo(f: Foo) { let _: &u32 = f.b$0 }
1329 // Ideally we'd also suggest &f.bar and &f.baz() as exact
1330 // type matches. See #8058.
1335 source_range: 98..99,
1345 source_range: 98..99,
1350 detail: "fn(&self) -> u32",
1361 enum Foo<T> { A(T), B }
1362 // bar() should not be an exact type match
1363 // because the generic parameters are different
1364 fn bar() -> Foo<u8> { Foo::B }
1365 // FIXME baz() should be an exact type match
1366 // because the types could unify, but it currently
1367 // is not. This is due to the T here being
1368 // TyKind::Placeholder rather than TyKind::Missing.
1369 fn baz<T>() -> Foo<T> { Foo::B }
1371 let foo: Foo<u32> = Foo::B;
1372 let _: Foo<u32> = f$0;
1377 ev Foo::A(…) [type_could_unify]
1378 ev Foo::B [type_could_unify]
1388 fn postfix_completion_relevance() {
1389 check_relevance_for_kinds(
1390 &[CompletionKind::Postfix, CompletionKind::Magic],
1395 fn not(self) -> Self::Output;
1400 fn not(self) -> bool { if self { false } else { true }}
1405 let _: bool = (9 > 2).not$0;
1410 me not() (use ops::Not) [type_could_unify]