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,
342 fn check(ra_fixture: &str, expect: Expect) {
343 let actual = do_completion(ra_fixture, CompletionKind::Reference);
344 expect.assert_debug_eq(&actual);
347 fn check_relevance(ra_fixture: &str, expect: Expect) {
348 fn display_relevance(relevance: CompletionRelevance) -> String {
349 let relevance_factors = vec![
350 (relevance.type_match == Some(CompletionRelevanceTypeMatch::Exact), "type"),
352 relevance.type_match == Some(CompletionRelevanceTypeMatch::CouldUnify),
355 (relevance.exact_name_match, "name"),
356 (relevance.is_local, "local"),
359 .filter_map(|(cond, desc)| if cond { Some(desc) } else { None })
362 format!("[{}]", relevance_factors)
365 let actual = get_all_items(TEST_CONFIG, ra_fixture)
367 .filter(|it| it.completion_kind == CompletionKind::Reference)
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);
390 fn enum_detail_includes_record_fields() {
393 enum Foo { Foo { x: i32, y: i32 } }
395 fn main() { Foo::Fo$0 }
401 source_range: 54..56,
407 detail: "{ x: i32, y: i32 }",
415 fn enum_detail_doesnt_include_tuple_fields() {
418 enum Foo { Foo (i32, i32) }
420 fn main() { Foo::Fo$0 }
426 source_range: 46..48,
433 detail: "(i32, i32)",
434 trigger_call_info: true,
442 fn fn_detail_includes_args_and_return_type() {
445 fn foo<T>(a: u32, b: u32, t: T) -> (u32, T) { (a, t) }
453 source_range: 68..70,
455 insert: "foo(${1:a}, ${2:b}, ${3:t})$0",
460 detail: "fn(u32, u32, T) -> (u32, T)",
461 trigger_call_info: true,
465 source_range: 68..70,
480 fn enum_detail_just_parentheses_for_unit() {
485 fn main() { Foo::Fo$0 }
491 source_range: 35..37,
505 fn lookup_enums_by_two_qualifiers() {
509 pub enum Spam { Foo, Bar(i32) }
511 fn main() { let _: m::Spam = S$0 }
516 label: "Spam::Bar(…)",
517 source_range: 75..76,
519 insert: "Spam::Bar($0)",
525 relevance: CompletionRelevance {
526 exact_name_match: false,
532 trigger_call_info: true,
536 source_range: 75..76,
544 label: "m::Spam::Foo",
545 source_range: 75..76,
547 insert: "m::Spam::Foo",
553 relevance: CompletionRelevance {
554 exact_name_match: false,
563 source_range: 75..76,
578 fn sets_deprecated_flag_in_items() {
582 fn something_deprecated() {}
583 #[rustc_deprecated(since = "1.0.0")]
584 fn something_else_deprecated() {}
592 source_range: 127..130,
602 label: "something_deprecated()",
603 source_range: 127..130,
605 insert: "something_deprecated()$0",
609 lookup: "something_deprecated",
614 label: "something_else_deprecated()",
615 source_range: 127..130,
617 insert: "something_else_deprecated()$0",
621 lookup: "something_else_deprecated",
631 struct A { #[deprecated] the_field: u32 }
632 fn foo() { A { the$0 } }
638 source_range: 57..60,
646 relevance: CompletionRelevance {
647 exact_name_match: false,
669 fn bar(self) { self.$0 }
675 source_range: 94..94,
681 documentation: Documentation(
687 source_range: 94..94,
694 documentation: Documentation(
720 source_range: 10..12,
726 documentation: Documentation(
732 source_range: 10..12,
739 documentation: Documentation(
745 source_range: 10..12,
751 documentation: Documentation(
761 fn dont_render_attrs() {
767 fn the_method(&self) { }
769 fn foo(s: S) { s.$0 }
774 label: "the_method()",
775 source_range: 81..81,
777 insert: "the_method()$0",
779 lookup: "the_method",
788 fn no_call_parens_if_fn_ptr_needed() {
789 cov_mark::check!(no_call_parens_if_fn_ptr_needed);
793 fn foo(foo: u8, bar: u8) {}
794 struct ManualVtable { f: fn(u8, u8) }
796 fn main() -> ManualVtable {
797 ManualVtable { f: f$0 }
801 fn foo(foo: u8, bar: u8) {}
802 struct ManualVtable { f: fn(u8, u8) }
804 fn main() -> ManualVtable {
805 ManualVtable { f: foo }
812 fn no_parens_in_use_item() {
813 cov_mark::check!(no_parens_in_use_item);
817 mod m { pub fn foo() {} }
821 mod m { pub fn foo() {} }
828 fn no_parens_in_call() {
844 impl Foo { fn foo(&self){} }
845 fn f(foo: &Foo) { foo.f$0(); }
849 impl Foo { fn foo(&self){} }
850 fn f(foo: &Foo) { foo.foo(); }
856 fn inserts_angle_brackets_for_generics() {
857 cov_mark::check!(inserts_angle_brackets_for_generics);
883 struct Vec<T = i128> {}
887 struct Vec<T = i128> {}
895 fn foo(xs: Ve$0<i128>)
899 fn foo(xs: Vec<i128>)
905 fn active_param_relevance() {
908 struct S { foo: i64, bar: u32, baz: u32 }
909 fn test(bar: u32) { }
910 fn foo(s: S) { test(s.$0) }
921 fn record_field_relevances() {
924 struct A { foo: i64, bar: u32, baz: u32 }
925 struct B { x: (), y: f32, bar: u32 }
926 fn foo(a: A) { B { bar: a.$0 }; }
937 fn record_field_and_call_relevances() {
940 struct A { foo: i64, bar: u32, baz: u32 }
941 struct B { x: (), y: f32, bar: u32 }
943 fn foo(a: A) { B { bar: f(a.$0) }; }
953 struct A { foo: i64, bar: u32, baz: u32 }
954 struct B { x: (), y: f32, bar: u32 }
956 fn foo(a: A) { f(B { bar: a.$0 }); }
967 fn prioritize_exact_ref_match() {
970 struct WorldSnapshot { _f: () };
971 fn go(world: &WorldSnapshot) { go(w$0) }
974 lc world [type+name+local]
982 fn too_many_arguments() {
983 cov_mark::check!(too_many_arguments);
987 fn f(foo: &Foo) { f(foo, w$0) }
998 fn score_fn_type_and_name_match() {
1001 struct A { bar: u8 }
1002 fn baz() -> u8 { 0 }
1003 fn bar() -> u8 { 0 }
1004 fn f() { A { bar: b$0 }; }
1009 fn bar() [type+name]
1016 fn score_method_type_and_name_match() {
1022 fn aaa(&self) -> u32 { 0 }
1023 fn bbb(&self) -> u32 { 0 }
1024 fn ccc(&self) -> u64 { 0 }
1031 me aaa() [type+name]
1039 fn score_method_name_match_only() {
1045 fn aaa(&self) -> u64 { 0 }
1058 fn suggest_ref_mut() {
1059 cov_mark::check!(suggest_ref);
1063 fn foo(s: &mut S) {}
1071 lc &mut s [type+name+local]
1080 fn foo(s: &mut S) {}
1087 lc s [type+name+local]
1096 fn suggest_deref() {
1103 impl core::ops::Deref for T {
1106 fn deref(&self) -> &Self::Target {
1135 fn suggest_deref_mut() {
1138 //- minicore: deref_mut
1142 impl core::ops::Deref for T {
1145 fn deref(&self) -> &Self::Target {
1150 impl core::ops::DerefMut for T {
1151 fn deref_mut(&mut self) -> &mut Self::Target {
1156 fn foo(s: &mut S) {}
1168 lc &mut t [type+local]
1240 fn suggest_deref_fn_ret() {
1247 impl core::ops::Deref for T {
1250 fn deref(&self) -> &Self::Target {
1276 fn struct_field_method_ref() {
1279 struct Foo { bar: u32 }
1280 impl Foo { fn baz(&self) -> u32 { 0 } }
1282 fn foo(f: Foo) { let _: &u32 = f.b$0 }
1285 // Ideally we'd also suggest &f.bar and &f.baz() as exact
1286 // type matches. See #8058.
1291 source_range: 98..99,
1301 source_range: 98..99,
1306 detail: "fn(&self) -> u32",
1317 enum Foo<T> { A(T), B }
1318 // bar() should not be an exact type match
1319 // because the generic parameters are different
1320 fn bar() -> Foo<u8> { Foo::B }
1321 // FIXME baz() should be an exact type match
1322 // because the types could unify, but it currently
1323 // is not. This is due to the T here being
1324 // TyKind::Placeholder rather than TyKind::Missing.
1325 fn baz<T>() -> Foo<T> { Foo::B }
1327 let foo: Foo<u32> = Foo::B;
1328 let _: Foo<u32> = f$0;
1332 ev Foo::A(…) [type_could_unify]
1333 ev Foo::B [type_could_unify]