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).add_import(import_to_add);
216 return Some(item.build());
220 let local_name = local_name.to_string();
221 let mut item = CompletionItem::new(completion_kind, ctx.source_range(), local_name.clone());
222 if let hir::ScopeDef::Local(local) = resolution {
223 let ty = local.ty(ctx.db());
224 if !ty.is_unknown() {
225 item.detail(ty.display(ctx.db()).to_string());
228 item.set_relevance(CompletionRelevance {
229 type_match: compute_type_match(ctx.completion, &ty),
230 exact_name_match: compute_exact_name_match(ctx.completion, &local_name),
232 ..CompletionRelevance::default()
235 if let Some(ref_match) = compute_ref_match(ctx.completion, &ty) {
236 item.ref_match(ref_match);
240 // Add `<>` for generic types
242 ctx.completion.path_context,
243 Some(PathCompletionContext { kind: Some(PathKind::Type), has_type_args: false, .. })
244 ) && ctx.completion.config.add_call_parenthesis
246 if let Some(cap) = ctx.snippet_cap() {
247 let has_non_default_type_params = match resolution {
248 hir::ScopeDef::ModuleDef(Adt(it)) => it.has_non_default_type_params(ctx.db()),
249 hir::ScopeDef::ModuleDef(TypeAlias(it)) => it.has_non_default_type_params(ctx.db()),
252 if has_non_default_type_params {
253 cov_mark::hit!(inserts_angle_brackets_for_generics);
254 item.lookup_by(local_name.clone())
255 .label(format!("{}<…>", local_name))
256 .insert_snippet(cap, format!("{}<$0>", local_name));
261 .add_import(import_to_add)
262 .set_documentation(scope_def_docs(ctx.db(), resolution))
263 .set_deprecated(scope_def_is_deprecated(&ctx, resolution));
267 fn scope_def_docs(db: &RootDatabase, resolution: &hir::ScopeDef) -> Option<hir::Documentation> {
268 use hir::ModuleDef::*;
270 hir::ScopeDef::ModuleDef(Module(it)) => it.docs(db),
271 hir::ScopeDef::ModuleDef(Adt(it)) => it.docs(db),
272 hir::ScopeDef::ModuleDef(Variant(it)) => it.docs(db),
273 hir::ScopeDef::ModuleDef(Const(it)) => it.docs(db),
274 hir::ScopeDef::ModuleDef(Static(it)) => it.docs(db),
275 hir::ScopeDef::ModuleDef(Trait(it)) => it.docs(db),
276 hir::ScopeDef::ModuleDef(TypeAlias(it)) => it.docs(db),
281 fn scope_def_is_deprecated(ctx: &RenderContext<'_>, resolution: &hir::ScopeDef) -> bool {
283 hir::ScopeDef::ModuleDef(it) => ctx.is_deprecated_assoc_item(*it),
284 hir::ScopeDef::MacroDef(it) => ctx.is_deprecated(*it),
285 hir::ScopeDef::GenericParam(it) => ctx.is_deprecated(*it),
286 hir::ScopeDef::AdtSelfType(it) => ctx.is_deprecated(*it),
291 fn compute_type_match(
292 ctx: &CompletionContext,
293 completion_ty: &hir::Type,
294 ) -> Option<CompletionRelevanceTypeMatch> {
295 let expected_type = ctx.expected_type.as_ref()?;
297 // We don't ever consider unit type to be an exact type match, since
298 // nearly always this is not meaningful to the user.
299 if expected_type.is_unit() {
303 if completion_ty == expected_type {
304 Some(CompletionRelevanceTypeMatch::Exact)
305 } else if expected_type.could_unify_with(ctx.db, completion_ty) {
306 Some(CompletionRelevanceTypeMatch::CouldUnify)
312 fn compute_exact_name_match(ctx: &CompletionContext, completion_name: &str) -> bool {
313 ctx.expected_name.as_ref().map_or(false, |name| name.text() == completion_name)
316 fn compute_ref_match(
317 ctx: &CompletionContext,
318 completion_ty: &hir::Type,
319 ) -> Option<hir::Mutability> {
320 let expected_type = ctx.expected_type.as_ref()?;
321 if completion_ty != expected_type {
322 let expected_type_without_ref = expected_type.remove_ref()?;
323 if completion_ty.autoderef(ctx.db).any(|deref_ty| deref_ty == expected_type_without_ref) {
324 cov_mark::hit!(suggest_ref);
325 let mutability = if expected_type.is_mutable_reference() {
328 hir::Mutability::Shared
330 return Some(mutability);
340 use expect_test::{expect, Expect};
341 use itertools::Itertools;
344 item::CompletionRelevanceTypeMatch,
345 tests::{check_edit, do_completion, get_all_items, TEST_CONFIG},
346 CompletionKind, CompletionRelevance,
350 fn check(ra_fixture: &str, expect: Expect) {
351 let actual = do_completion(ra_fixture, CompletionKind::Reference);
352 expect.assert_debug_eq(&actual);
356 fn check_relevance(ra_fixture: &str, expect: Expect) {
357 check_relevance_for_kinds(&[CompletionKind::Reference], ra_fixture, expect)
361 fn check_relevance_for_kinds(kinds: &[CompletionKind], ra_fixture: &str, expect: Expect) {
362 let mut actual = get_all_items(TEST_CONFIG, ra_fixture);
363 actual.retain(|it| kinds.contains(&it.completion_kind));
364 actual.sort_by_key(|it| cmp::Reverse(it.relevance().score()));
369 let mut items = vec![];
371 let tag = it.kind().unwrap().tag();
372 let relevance = display_relevance(it.relevance());
373 items.push(format!("{} {} {}\n", tag, it.label(), relevance));
375 if let Some((mutability, relevance)) = it.ref_match() {
376 let label = format!("&{}{}", mutability.as_keyword_for_ref(), it.label());
377 let relevance = display_relevance(relevance);
379 items.push(format!("{} {} {}\n", tag, label, relevance));
384 .collect::<String>();
386 expect.assert_eq(&actual);
388 fn display_relevance(relevance: CompletionRelevance) -> String {
389 let relevance_factors = vec![
390 (relevance.type_match == Some(CompletionRelevanceTypeMatch::Exact), "type"),
392 relevance.type_match == Some(CompletionRelevanceTypeMatch::CouldUnify),
395 (relevance.exact_name_match, "name"),
396 (relevance.is_local, "local"),
397 (relevance.exact_postfix_snippet_match, "snippet"),
400 .filter_map(|(cond, desc)| if cond { Some(desc) } else { None })
403 format!("[{}]", relevance_factors)
408 fn enum_detail_includes_record_fields() {
411 enum Foo { Foo { x: i32, y: i32 } }
413 fn main() { Foo::Fo$0 }
419 source_range: 54..56,
425 detail: "{ x: i32, y: i32 }",
433 fn enum_detail_doesnt_include_tuple_fields() {
436 enum Foo { Foo (i32, i32) }
438 fn main() { Foo::Fo$0 }
444 source_range: 46..48,
451 detail: "(i32, i32)",
452 trigger_call_info: true,
460 fn fn_detail_includes_args_and_return_type() {
463 fn foo<T>(a: u32, b: u32, t: T) -> (u32, T) { (a, t) }
471 source_range: 68..70,
473 insert: "foo(${1:a}, ${2:b}, ${3:t})$0",
478 detail: "fn(u32, u32, T) -> (u32, T)",
479 trigger_call_info: true,
483 source_range: 68..70,
498 fn enum_detail_just_parentheses_for_unit() {
503 fn main() { Foo::Fo$0 }
509 source_range: 35..37,
523 fn lookup_enums_by_two_qualifiers() {
527 pub enum Spam { Foo, Bar(i32) }
529 fn main() { let _: m::Spam = S$0 }
534 label: "Spam::Bar(…)",
535 source_range: 75..76,
537 insert: "Spam::Bar($0)",
543 relevance: CompletionRelevance {
544 exact_name_match: false,
549 exact_postfix_snippet_match: false,
551 trigger_call_info: true,
555 source_range: 75..76,
563 label: "m::Spam::Foo",
564 source_range: 75..76,
566 insert: "m::Spam::Foo",
572 relevance: CompletionRelevance {
573 exact_name_match: false,
578 exact_postfix_snippet_match: false,
583 source_range: 75..76,
598 fn sets_deprecated_flag_in_items() {
602 fn something_deprecated() {}
603 #[rustc_deprecated(since = "1.0.0")]
604 fn something_else_deprecated() {}
612 source_range: 127..130,
622 label: "something_deprecated()",
623 source_range: 127..130,
625 insert: "something_deprecated()$0",
629 lookup: "something_deprecated",
634 label: "something_else_deprecated()",
635 source_range: 127..130,
637 insert: "something_else_deprecated()$0",
641 lookup: "something_else_deprecated",
651 struct A { #[deprecated] the_field: u32 }
652 fn foo() { A { the$0 } }
658 source_range: 57..60,
666 relevance: CompletionRelevance {
667 exact_name_match: false,
672 exact_postfix_snippet_match: false,
690 fn bar(self) { self.$0 }
696 source_range: 94..94,
702 documentation: Documentation(
708 source_range: 94..94,
715 documentation: Documentation(
741 source_range: 10..12,
747 documentation: Documentation(
753 source_range: 10..12,
760 documentation: Documentation(
766 source_range: 10..12,
772 documentation: Documentation(
782 fn dont_render_attrs() {
788 fn the_method(&self) { }
790 fn foo(s: S) { s.$0 }
795 label: "the_method()",
796 source_range: 81..81,
798 insert: "the_method()$0",
800 lookup: "the_method",
809 fn no_call_parens_if_fn_ptr_needed() {
810 cov_mark::check!(no_call_parens_if_fn_ptr_needed);
814 fn foo(foo: u8, bar: u8) {}
815 struct ManualVtable { f: fn(u8, u8) }
817 fn main() -> ManualVtable {
818 ManualVtable { f: f$0 }
822 fn foo(foo: u8, bar: u8) {}
823 struct ManualVtable { f: fn(u8, u8) }
825 fn main() -> ManualVtable {
826 ManualVtable { f: foo }
833 struct RawIdentTable { r#type: u32 }
835 fn main() -> RawIdentTable {
836 RawIdentTable { t$0: 42 }
840 struct RawIdentTable { r#type: u32 }
842 fn main() -> RawIdentTable {
843 RawIdentTable { r#type: 42 }
850 fn no_parens_in_use_item() {
851 cov_mark::check!(no_parens_in_use_item);
855 mod m { pub fn foo() {} }
859 mod m { pub fn foo() {} }
866 fn no_parens_in_call() {
882 impl Foo { fn foo(&self){} }
883 fn f(foo: &Foo) { foo.f$0(); }
887 impl Foo { fn foo(&self){} }
888 fn f(foo: &Foo) { foo.foo(); }
894 fn inserts_angle_brackets_for_generics() {
895 cov_mark::check!(inserts_angle_brackets_for_generics);
921 struct Vec<T = i128> {}
925 struct Vec<T = i128> {}
933 fn foo(xs: Ve$0<i128>)
937 fn foo(xs: Vec<i128>)
943 fn active_param_relevance() {
946 struct S { foo: i64, bar: u32, baz: u32 }
947 fn test(bar: u32) { }
948 fn foo(s: S) { test(s.$0) }
959 fn record_field_relevances() {
962 struct A { foo: i64, bar: u32, baz: u32 }
963 struct B { x: (), y: f32, bar: u32 }
964 fn foo(a: A) { B { bar: a.$0 }; }
975 fn record_field_and_call_relevances() {
978 struct A { foo: i64, bar: u32, baz: u32 }
979 struct B { x: (), y: f32, bar: u32 }
981 fn foo(a: A) { B { bar: f(a.$0) }; }
991 struct A { foo: i64, bar: u32, baz: u32 }
992 struct B { x: (), y: f32, bar: u32 }
994 fn foo(a: A) { f(B { bar: a.$0 }); }
1005 fn prioritize_exact_ref_match() {
1008 struct WorldSnapshot { _f: () };
1009 fn go(world: &WorldSnapshot) { go(w$0) }
1012 lc world [type+name+local]
1020 fn too_many_arguments() {
1021 cov_mark::check!(too_many_arguments);
1025 fn f(foo: &Foo) { f(foo, w$0) }
1036 fn score_fn_type_and_name_match() {
1039 struct A { bar: u8 }
1040 fn baz() -> u8 { 0 }
1041 fn bar() -> u8 { 0 }
1042 fn f() { A { bar: b$0 }; }
1045 fn bar() [type+name]
1054 fn score_method_type_and_name_match() {
1060 fn aaa(&self) -> u32 { 0 }
1061 fn bbb(&self) -> u32 { 0 }
1062 fn ccc(&self) -> u64 { 0 }
1069 me aaa() [type+name]
1077 fn score_method_name_match_only() {
1083 fn aaa(&self) -> u64 { 0 }
1096 fn suggest_ref_mut() {
1097 cov_mark::check!(suggest_ref);
1101 fn foo(s: &mut S) {}
1109 lc &mut s [type+name+local]
1118 fn foo(s: &mut S) {}
1125 lc s [type+name+local]
1134 fn suggest_deref() {
1141 impl core::ops::Deref for T {
1144 fn deref(&self) -> &Self::Target {
1173 fn suggest_deref_mut() {
1176 //- minicore: deref_mut
1180 impl core::ops::Deref for T {
1183 fn deref(&self) -> &Self::Target {
1188 impl core::ops::DerefMut for T {
1189 fn deref_mut(&mut self) -> &mut Self::Target {
1194 fn foo(s: &mut S) {}
1206 lc &mut t [type+local]
1278 fn suggest_deref_fn_ret() {
1285 impl core::ops::Deref for T {
1288 fn deref(&self) -> &Self::Target {
1314 fn struct_field_method_ref() {
1317 struct Foo { bar: u32 }
1318 impl Foo { fn baz(&self) -> u32 { 0 } }
1320 fn foo(f: Foo) { let _: &u32 = f.b$0 }
1323 // Ideally we'd also suggest &f.bar and &f.baz() as exact
1324 // type matches. See #8058.
1329 source_range: 98..99,
1339 source_range: 98..99,
1344 detail: "fn(&self) -> u32",
1355 enum Foo<T> { A(T), B }
1356 // bar() should not be an exact type match
1357 // because the generic parameters are different
1358 fn bar() -> Foo<u8> { Foo::B }
1359 // FIXME baz() should be an exact type match
1360 // because the types could unify, but it currently
1361 // is not. This is due to the T here being
1362 // TyKind::Placeholder rather than TyKind::Missing.
1363 fn baz<T>() -> Foo<T> { Foo::B }
1365 let foo: Foo<u32> = Foo::B;
1366 let _: Foo<u32> = f$0;
1371 ev Foo::A(…) [type_could_unify]
1372 ev Foo::B [type_could_unify]
1382 fn postfix_completion_relevance() {
1383 check_relevance_for_kinds(
1384 &[CompletionKind::Postfix, CompletionKind::Magic],
1389 fn not(self) -> Self::Output;
1394 fn not(self) -> bool { if self { false } else { true }}
1399 let _: bool = (9 > 2).not$0;
1404 me not() (use ops::Not) [type_could_unify]