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;
13 use hir::{AsAssocItem, HasAttrs, HirDisplay};
15 helpers::{item_name, SnippetCap},
16 RootDatabase, SymbolKind,
18 use syntax::TextRange;
21 context::{PathCompletionContext, PathKind},
22 item::{CompletionRelevanceTypeMatch, ImportEdit},
23 render::{enum_variant::render_variant, function::render_fn, macro_::render_macro},
24 CompletionContext, CompletionItem, CompletionItemKind, CompletionKind, CompletionRelevance,
26 /// Interface for data and methods required for items rendering.
28 pub(crate) struct RenderContext<'a> {
29 completion: &'a CompletionContext<'a>,
32 impl<'a> RenderContext<'a> {
33 pub(crate) fn new(completion: &'a CompletionContext<'a>) -> RenderContext<'a> {
34 RenderContext { completion }
37 fn snippet_cap(&self) -> Option<SnippetCap> {
38 self.completion.config.snippet_cap
41 fn db(&self) -> &'a RootDatabase {
45 fn source_range(&self) -> TextRange {
46 self.completion.source_range()
49 fn is_deprecated(&self, node: impl HasAttrs) -> bool {
50 let attrs = node.attrs(self.db());
51 attrs.by_key("deprecated").exists() || attrs.by_key("rustc_deprecated").exists()
54 fn is_deprecated_assoc_item(&self, as_assoc_item: impl AsAssocItem) -> bool {
56 let assoc = match as_assoc_item.as_assoc_item(db) {
61 let is_assoc_deprecated = match assoc {
62 hir::AssocItem::Function(it) => self.is_deprecated(it),
63 hir::AssocItem::Const(it) => self.is_deprecated(it),
64 hir::AssocItem::TypeAlias(it) => self.is_deprecated(it),
68 .containing_trait_or_trait_impl(db)
69 .map(|trait_| self.is_deprecated(trait_))
73 fn docs(&self, node: impl HasAttrs) -> Option<hir::Documentation> {
78 pub(crate) fn render_field(
79 ctx: RenderContext<'_>,
80 receiver: Option<hir::Name>,
84 let is_deprecated = ctx.is_deprecated(field);
85 let name = field.name(ctx.db()).to_string();
86 let mut item = CompletionItem::new(
87 CompletionKind::Reference,
89 receiver.map_or_else(|| name.clone(), |receiver| format!("{}.{}", receiver, name)),
91 item.set_relevance(CompletionRelevance {
92 type_match: compute_type_match(ctx.completion, ty),
93 exact_name_match: compute_exact_name_match(ctx.completion, &name),
94 ..CompletionRelevance::default()
96 item.kind(SymbolKind::Field)
97 .detail(ty.display(ctx.db()).to_string())
98 .set_documentation(field.docs(ctx.db()))
99 .set_deprecated(is_deprecated)
101 if let Some(_ref_match) = compute_ref_match(ctx.completion, ty) {
103 // For now we don't properly calculate the edits for ref match
104 // completions on struct fields, so we've disabled them. See #8058.
109 pub(crate) fn render_tuple_field(
110 ctx: RenderContext<'_>,
111 receiver: Option<hir::Name>,
114 ) -> CompletionItem {
115 let mut item = CompletionItem::new(
116 CompletionKind::Reference,
118 receiver.map_or_else(|| field.to_string(), |receiver| format!("{}.{}", receiver, field)),
120 item.kind(SymbolKind::Field)
121 .detail(ty.display(ctx.db()).to_string())
122 .lookup_by(field.to_string());
126 pub(crate) fn render_resolution(
127 ctx: RenderContext<'_>,
128 local_name: hir::Name,
129 resolution: &hir::ScopeDef,
130 ) -> Option<CompletionItem> {
131 render_resolution_(ctx, local_name, None, resolution)
134 pub(crate) fn render_resolution_with_import(
135 ctx: RenderContext<'_>,
136 import_edit: ImportEdit,
137 ) -> Option<CompletionItem> {
138 let resolution = hir::ScopeDef::from(import_edit.import.original_item);
139 let local_name = match resolution {
140 hir::ScopeDef::ModuleDef(hir::ModuleDef::Function(f)) => f.name(ctx.completion.db),
141 hir::ScopeDef::ModuleDef(hir::ModuleDef::Const(c)) => c.name(ctx.completion.db)?,
142 hir::ScopeDef::ModuleDef(hir::ModuleDef::TypeAlias(t)) => t.name(ctx.completion.db),
143 _ => item_name(ctx.db(), import_edit.import.original_item)?,
145 render_resolution_(ctx, local_name, Some(import_edit), &resolution).map(|mut item| {
146 item.completion_kind = CompletionKind::Magic;
151 fn render_resolution_(
152 ctx: RenderContext<'_>,
153 local_name: hir::Name,
154 import_to_add: Option<ImportEdit>,
155 resolution: &hir::ScopeDef,
156 ) -> Option<CompletionItem> {
157 let _p = profile::span("render_resolution");
158 use hir::ModuleDef::*;
160 let completion_kind = match resolution {
161 hir::ScopeDef::ModuleDef(BuiltinType(..)) => CompletionKind::BuiltinType,
162 _ => CompletionKind::Reference,
165 let kind = match resolution {
166 hir::ScopeDef::ModuleDef(Function(func)) => {
167 return render_fn(ctx, import_to_add, Some(local_name), *func);
169 hir::ScopeDef::ModuleDef(Variant(_)) if ctx.completion.is_pat_or_const.is_some() => {
170 CompletionItemKind::SymbolKind(SymbolKind::Variant)
172 hir::ScopeDef::ModuleDef(Variant(var)) => {
173 let item = render_variant(ctx, import_to_add, Some(local_name), *var, None);
176 hir::ScopeDef::MacroDef(mac) => {
177 let item = render_macro(ctx, import_to_add, local_name, *mac);
181 hir::ScopeDef::ModuleDef(Module(..)) => CompletionItemKind::SymbolKind(SymbolKind::Module),
182 hir::ScopeDef::ModuleDef(Adt(adt)) => CompletionItemKind::SymbolKind(match adt {
183 hir::Adt::Struct(_) => SymbolKind::Struct,
184 hir::Adt::Union(_) => SymbolKind::Union,
185 hir::Adt::Enum(_) => SymbolKind::Enum,
187 hir::ScopeDef::ModuleDef(Const(..)) => CompletionItemKind::SymbolKind(SymbolKind::Const),
188 hir::ScopeDef::ModuleDef(Static(..)) => CompletionItemKind::SymbolKind(SymbolKind::Static),
189 hir::ScopeDef::ModuleDef(Trait(..)) => CompletionItemKind::SymbolKind(SymbolKind::Trait),
190 hir::ScopeDef::ModuleDef(TypeAlias(..)) => {
191 CompletionItemKind::SymbolKind(SymbolKind::TypeAlias)
193 hir::ScopeDef::ModuleDef(BuiltinType(..)) => CompletionItemKind::BuiltinType,
194 hir::ScopeDef::GenericParam(param) => CompletionItemKind::SymbolKind(match param {
195 hir::GenericParam::TypeParam(_) => SymbolKind::TypeParam,
196 hir::GenericParam::LifetimeParam(_) => SymbolKind::LifetimeParam,
197 hir::GenericParam::ConstParam(_) => SymbolKind::ConstParam,
199 hir::ScopeDef::Local(..) => CompletionItemKind::SymbolKind(SymbolKind::Local),
200 hir::ScopeDef::Label(..) => CompletionItemKind::SymbolKind(SymbolKind::Label),
201 hir::ScopeDef::AdtSelfType(..) | hir::ScopeDef::ImplSelfType(..) => {
202 CompletionItemKind::SymbolKind(SymbolKind::SelfParam)
204 hir::ScopeDef::Unknown => {
205 let mut item = CompletionItem::new(
206 CompletionKind::Reference,
208 local_name.to_string(),
210 item.kind(CompletionItemKind::UnresolvedReference).add_import(import_to_add);
211 return Some(item.build());
215 let local_name = local_name.to_string();
216 let mut item = CompletionItem::new(completion_kind, ctx.source_range(), local_name.clone());
217 if let hir::ScopeDef::Local(local) = resolution {
218 let ty = local.ty(ctx.db());
219 if !ty.is_unknown() {
220 item.detail(ty.display(ctx.db()).to_string());
223 item.set_relevance(CompletionRelevance {
224 type_match: compute_type_match(ctx.completion, &ty),
225 exact_name_match: compute_exact_name_match(ctx.completion, &local_name),
227 ..CompletionRelevance::default()
230 if let Some(ref_match) = compute_ref_match(ctx.completion, &ty) {
231 item.ref_match(ref_match);
235 // Add `<>` for generic types
237 ctx.completion.path_context,
238 Some(PathCompletionContext { kind: Some(PathKind::Type), has_type_args: false, .. })
239 ) && ctx.completion.config.add_call_parenthesis
241 if let Some(cap) = ctx.snippet_cap() {
242 let has_non_default_type_params = match resolution {
243 hir::ScopeDef::ModuleDef(Adt(it)) => it.has_non_default_type_params(ctx.db()),
244 hir::ScopeDef::ModuleDef(TypeAlias(it)) => it.has_non_default_type_params(ctx.db()),
247 if has_non_default_type_params {
248 cov_mark::hit!(inserts_angle_brackets_for_generics);
249 item.lookup_by(local_name.clone())
250 .label(format!("{}<…>", local_name))
251 .insert_snippet(cap, format!("{}<$0>", local_name));
256 .add_import(import_to_add)
257 .set_documentation(scope_def_docs(ctx.db(), resolution))
258 .set_deprecated(scope_def_is_deprecated(&ctx, resolution));
262 fn scope_def_docs(db: &RootDatabase, resolution: &hir::ScopeDef) -> Option<hir::Documentation> {
263 use hir::ModuleDef::*;
265 hir::ScopeDef::ModuleDef(Module(it)) => it.docs(db),
266 hir::ScopeDef::ModuleDef(Adt(it)) => it.docs(db),
267 hir::ScopeDef::ModuleDef(Variant(it)) => it.docs(db),
268 hir::ScopeDef::ModuleDef(Const(it)) => it.docs(db),
269 hir::ScopeDef::ModuleDef(Static(it)) => it.docs(db),
270 hir::ScopeDef::ModuleDef(Trait(it)) => it.docs(db),
271 hir::ScopeDef::ModuleDef(TypeAlias(it)) => it.docs(db),
276 fn scope_def_is_deprecated(ctx: &RenderContext<'_>, resolution: &hir::ScopeDef) -> bool {
278 hir::ScopeDef::ModuleDef(it) => ctx.is_deprecated_assoc_item(*it),
279 hir::ScopeDef::MacroDef(it) => ctx.is_deprecated(*it),
280 hir::ScopeDef::GenericParam(it) => ctx.is_deprecated(*it),
281 hir::ScopeDef::AdtSelfType(it) => ctx.is_deprecated(*it),
286 fn compute_type_match(
287 ctx: &CompletionContext,
288 completion_ty: &hir::Type,
289 ) -> Option<CompletionRelevanceTypeMatch> {
290 let expected_type = ctx.expected_type.as_ref()?;
292 // We don't ever consider unit type to be an exact type match, since
293 // nearly always this is not meaningful to the user.
294 if expected_type.is_unit() {
298 if completion_ty == expected_type {
299 Some(CompletionRelevanceTypeMatch::Exact)
300 } else if expected_type.could_unify_with(ctx.db, completion_ty) {
301 Some(CompletionRelevanceTypeMatch::CouldUnify)
307 fn compute_exact_name_match(ctx: &CompletionContext, completion_name: &str) -> bool {
308 ctx.expected_name.as_ref().map_or(false, |name| name.text() == completion_name)
311 fn compute_ref_match(
312 ctx: &CompletionContext,
313 completion_ty: &hir::Type,
314 ) -> Option<hir::Mutability> {
315 let expected_type = ctx.expected_type.as_ref()?;
316 if completion_ty != expected_type {
317 let expected_type_without_ref = expected_type.remove_ref()?;
318 if completion_ty.autoderef(ctx.db).any(|deref_ty| deref_ty == expected_type_without_ref) {
319 cov_mark::hit!(suggest_ref);
320 let mutability = if expected_type.is_mutable_reference() {
323 hir::Mutability::Shared
325 return Some(mutability);
333 use expect_test::{expect, Expect};
334 use itertools::Itertools;
337 item::CompletionRelevanceTypeMatch,
338 tests::{check_edit, do_completion, get_all_items, TEST_CONFIG},
339 CompletionKind, CompletionRelevance,
343 fn check(ra_fixture: &str, expect: Expect) {
344 let actual = do_completion(ra_fixture, CompletionKind::Reference);
345 expect.assert_debug_eq(&actual);
349 fn check_relevance(ra_fixture: &str, expect: Expect) {
350 check_relevance_for_kinds(&[CompletionKind::Reference], ra_fixture, expect)
354 fn check_relevance_for_kinds(kinds: &[CompletionKind], ra_fixture: &str, expect: Expect) {
355 let actual = get_all_items(TEST_CONFIG, ra_fixture)
357 .filter(|it| kinds.contains(&it.completion_kind))
359 let mut items = vec![];
361 let tag = it.kind().unwrap().tag();
362 let relevance = display_relevance(it.relevance());
363 items.push(format!("{} {} {}\n", tag, it.label(), relevance));
365 if let Some((mutability, relevance)) = it.ref_match() {
366 let label = format!("&{}{}", mutability.as_keyword_for_ref(), it.label());
367 let relevance = display_relevance(relevance);
369 items.push(format!("{} {} {}\n", tag, label, relevance));
374 .collect::<String>();
376 expect.assert_eq(&actual);
378 fn display_relevance(relevance: CompletionRelevance) -> String {
379 let relevance_factors = vec![
380 (relevance.type_match == Some(CompletionRelevanceTypeMatch::Exact), "type"),
382 relevance.type_match == Some(CompletionRelevanceTypeMatch::CouldUnify),
385 (relevance.exact_name_match, "name"),
386 (relevance.is_local, "local"),
387 (relevance.exact_postfix_snippet_match, "snippet"),
390 .filter_map(|(cond, desc)| if cond { Some(desc) } else { None })
393 format!("[{}]", relevance_factors)
398 fn enum_detail_includes_record_fields() {
401 enum Foo { Foo { x: i32, y: i32 } }
403 fn main() { Foo::Fo$0 }
409 source_range: 54..56,
415 detail: "{ x: i32, y: i32 }",
423 fn enum_detail_doesnt_include_tuple_fields() {
426 enum Foo { Foo (i32, i32) }
428 fn main() { Foo::Fo$0 }
434 source_range: 46..48,
441 detail: "(i32, i32)",
442 trigger_call_info: true,
450 fn fn_detail_includes_args_and_return_type() {
453 fn foo<T>(a: u32, b: u32, t: T) -> (u32, T) { (a, t) }
461 source_range: 68..70,
463 insert: "foo(${1:a}, ${2:b}, ${3:t})$0",
468 detail: "fn(u32, u32, T) -> (u32, T)",
469 trigger_call_info: true,
473 source_range: 68..70,
488 fn enum_detail_just_parentheses_for_unit() {
493 fn main() { Foo::Fo$0 }
499 source_range: 35..37,
513 fn lookup_enums_by_two_qualifiers() {
517 pub enum Spam { Foo, Bar(i32) }
519 fn main() { let _: m::Spam = S$0 }
524 label: "Spam::Bar(…)",
525 source_range: 75..76,
527 insert: "Spam::Bar($0)",
533 relevance: CompletionRelevance {
534 exact_name_match: false,
539 exact_postfix_snippet_match: false,
541 trigger_call_info: true,
545 source_range: 75..76,
553 label: "m::Spam::Foo",
554 source_range: 75..76,
556 insert: "m::Spam::Foo",
562 relevance: CompletionRelevance {
563 exact_name_match: false,
568 exact_postfix_snippet_match: false,
573 source_range: 75..76,
588 fn sets_deprecated_flag_in_items() {
592 fn something_deprecated() {}
593 #[rustc_deprecated(since = "1.0.0")]
594 fn something_else_deprecated() {}
602 source_range: 127..130,
612 label: "something_deprecated()",
613 source_range: 127..130,
615 insert: "something_deprecated()$0",
619 lookup: "something_deprecated",
624 label: "something_else_deprecated()",
625 source_range: 127..130,
627 insert: "something_else_deprecated()$0",
631 lookup: "something_else_deprecated",
641 struct A { #[deprecated] the_field: u32 }
642 fn foo() { A { the$0 } }
648 source_range: 57..60,
656 relevance: CompletionRelevance {
657 exact_name_match: false,
662 exact_postfix_snippet_match: false,
680 fn bar(self) { self.$0 }
686 source_range: 94..94,
692 documentation: Documentation(
698 source_range: 94..94,
705 documentation: Documentation(
731 source_range: 10..12,
737 documentation: Documentation(
743 source_range: 10..12,
750 documentation: Documentation(
756 source_range: 10..12,
762 documentation: Documentation(
772 fn dont_render_attrs() {
778 fn the_method(&self) { }
780 fn foo(s: S) { s.$0 }
785 label: "the_method()",
786 source_range: 81..81,
788 insert: "the_method()$0",
790 lookup: "the_method",
799 fn no_call_parens_if_fn_ptr_needed() {
800 cov_mark::check!(no_call_parens_if_fn_ptr_needed);
804 fn foo(foo: u8, bar: u8) {}
805 struct ManualVtable { f: fn(u8, u8) }
807 fn main() -> ManualVtable {
808 ManualVtable { f: f$0 }
812 fn foo(foo: u8, bar: u8) {}
813 struct ManualVtable { f: fn(u8, u8) }
815 fn main() -> ManualVtable {
816 ManualVtable { f: foo }
823 fn no_parens_in_use_item() {
824 cov_mark::check!(no_parens_in_use_item);
828 mod m { pub fn foo() {} }
832 mod m { pub fn foo() {} }
839 fn no_parens_in_call() {
855 impl Foo { fn foo(&self){} }
856 fn f(foo: &Foo) { foo.f$0(); }
860 impl Foo { fn foo(&self){} }
861 fn f(foo: &Foo) { foo.foo(); }
867 fn inserts_angle_brackets_for_generics() {
868 cov_mark::check!(inserts_angle_brackets_for_generics);
894 struct Vec<T = i128> {}
898 struct Vec<T = i128> {}
906 fn foo(xs: Ve$0<i128>)
910 fn foo(xs: Vec<i128>)
916 fn active_param_relevance() {
919 struct S { foo: i64, bar: u32, baz: u32 }
920 fn test(bar: u32) { }
921 fn foo(s: S) { test(s.$0) }
932 fn record_field_relevances() {
935 struct A { foo: i64, bar: u32, baz: u32 }
936 struct B { x: (), y: f32, bar: u32 }
937 fn foo(a: A) { B { bar: a.$0 }; }
948 fn record_field_and_call_relevances() {
951 struct A { foo: i64, bar: u32, baz: u32 }
952 struct B { x: (), y: f32, bar: u32 }
954 fn foo(a: A) { B { bar: f(a.$0) }; }
964 struct A { foo: i64, bar: u32, baz: u32 }
965 struct B { x: (), y: f32, bar: u32 }
967 fn foo(a: A) { f(B { bar: a.$0 }); }
978 fn prioritize_exact_ref_match() {
981 struct WorldSnapshot { _f: () };
982 fn go(world: &WorldSnapshot) { go(w$0) }
985 lc world [type+name+local]
993 fn too_many_arguments() {
994 cov_mark::check!(too_many_arguments);
998 fn f(foo: &Foo) { f(foo, w$0) }
1009 fn score_fn_type_and_name_match() {
1012 struct A { bar: u8 }
1013 fn baz() -> u8 { 0 }
1014 fn bar() -> u8 { 0 }
1015 fn f() { A { bar: b$0 }; }
1020 fn bar() [type+name]
1027 fn score_method_type_and_name_match() {
1033 fn aaa(&self) -> u32 { 0 }
1034 fn bbb(&self) -> u32 { 0 }
1035 fn ccc(&self) -> u64 { 0 }
1042 me aaa() [type+name]
1050 fn score_method_name_match_only() {
1056 fn aaa(&self) -> u64 { 0 }
1069 fn suggest_ref_mut() {
1070 cov_mark::check!(suggest_ref);
1074 fn foo(s: &mut S) {}
1082 lc &mut s [type+name+local]
1091 fn foo(s: &mut S) {}
1098 lc s [type+name+local]
1107 fn suggest_deref() {
1114 impl core::ops::Deref for T {
1117 fn deref(&self) -> &Self::Target {
1146 fn suggest_deref_mut() {
1149 //- minicore: deref_mut
1153 impl core::ops::Deref for T {
1156 fn deref(&self) -> &Self::Target {
1161 impl core::ops::DerefMut for T {
1162 fn deref_mut(&mut self) -> &mut Self::Target {
1167 fn foo(s: &mut S) {}
1179 lc &mut t [type+local]
1251 fn suggest_deref_fn_ret() {
1258 impl core::ops::Deref for T {
1261 fn deref(&self) -> &Self::Target {
1287 fn struct_field_method_ref() {
1290 struct Foo { bar: u32 }
1291 impl Foo { fn baz(&self) -> u32 { 0 } }
1293 fn foo(f: Foo) { let _: &u32 = f.b$0 }
1296 // Ideally we'd also suggest &f.bar and &f.baz() as exact
1297 // type matches. See #8058.
1302 source_range: 98..99,
1312 source_range: 98..99,
1317 detail: "fn(&self) -> u32",
1328 enum Foo<T> { A(T), B }
1329 // bar() should not be an exact type match
1330 // because the generic parameters are different
1331 fn bar() -> Foo<u8> { Foo::B }
1332 // FIXME baz() should be an exact type match
1333 // because the types could unify, but it currently
1334 // is not. This is due to the T here being
1335 // TyKind::Placeholder rather than TyKind::Missing.
1336 fn baz<T>() -> Foo<T> { Foo::B }
1338 let foo: Foo<u32> = Foo::B;
1339 let _: Foo<u32> = f$0;
1343 ev Foo::A(…) [type_could_unify]
1344 ev Foo::B [type_could_unify]
1355 fn postfix_completion_relevance() {
1356 check_relevance_for_kinds(
1357 &[CompletionKind::Postfix, CompletionKind::Magic],
1362 fn not(self) -> Self::Output;
1367 fn not(self) -> bool { if self { false } else { true }}
1372 let _: bool = (9 > 2).not$0;
1389 me not() (ops::Not) [type_could_unify]