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::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),
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)
102 if let Some(_ref_match) = compute_ref_match(ctx.completion, ty) {
104 // For now we don't properly calculate the edits for ref match
105 // completions on struct fields, so we've disabled them. See #8058.
110 pub(crate) fn render_tuple_field(
111 ctx: RenderContext<'_>,
112 receiver: Option<hir::Name>,
115 ) -> CompletionItem {
116 let mut item = CompletionItem::new(
117 CompletionKind::Reference,
119 receiver.map_or_else(|| field.to_string(), |receiver| format!("{}.{}", receiver, field)),
121 item.kind(SymbolKind::Field)
122 .detail(ty.display(ctx.db()).to_string())
123 .lookup_by(field.to_string());
127 pub(crate) fn render_resolution(
128 ctx: RenderContext<'_>,
129 local_name: hir::Name,
130 resolution: &hir::ScopeDef,
131 ) -> Option<CompletionItem> {
132 render_resolution_(ctx, local_name, None, resolution)
135 pub(crate) fn render_resolution_with_import(
136 ctx: RenderContext<'_>,
137 import_edit: ImportEdit,
138 ) -> Option<CompletionItem> {
139 let resolution = hir::ScopeDef::from(import_edit.import.original_item);
140 let local_name = match resolution {
141 hir::ScopeDef::ModuleDef(hir::ModuleDef::Function(f)) => f.name(ctx.completion.db),
142 hir::ScopeDef::ModuleDef(hir::ModuleDef::Const(c)) => c.name(ctx.completion.db)?,
143 hir::ScopeDef::ModuleDef(hir::ModuleDef::TypeAlias(t)) => t.name(ctx.completion.db),
144 _ => item_name(ctx.db(), import_edit.import.original_item)?,
146 render_resolution_(ctx, local_name, Some(import_edit), &resolution).map(|mut item| {
147 item.completion_kind = CompletionKind::Magic;
152 fn render_resolution_(
153 ctx: RenderContext<'_>,
154 local_name: hir::Name,
155 import_to_add: Option<ImportEdit>,
156 resolution: &hir::ScopeDef,
157 ) -> Option<CompletionItem> {
158 let _p = profile::span("render_resolution");
159 use hir::ModuleDef::*;
161 let completion_kind = match resolution {
162 hir::ScopeDef::ModuleDef(BuiltinType(..)) => CompletionKind::BuiltinType,
163 _ => CompletionKind::Reference,
166 let kind = match resolution {
167 hir::ScopeDef::ModuleDef(Function(func)) => {
168 return render_fn(ctx, import_to_add, Some(local_name), *func);
170 hir::ScopeDef::ModuleDef(Variant(_)) if ctx.completion.is_pat_or_const.is_some() => {
171 CompletionItemKind::SymbolKind(SymbolKind::Variant)
173 hir::ScopeDef::ModuleDef(Variant(var)) => {
174 let item = render_variant(ctx, import_to_add, Some(local_name), *var, None);
177 hir::ScopeDef::MacroDef(mac) => {
178 let item = render_macro(ctx, import_to_add, local_name, *mac);
182 hir::ScopeDef::ModuleDef(Module(..)) => CompletionItemKind::SymbolKind(SymbolKind::Module),
183 hir::ScopeDef::ModuleDef(Adt(adt)) => CompletionItemKind::SymbolKind(match adt {
184 hir::Adt::Struct(_) => SymbolKind::Struct,
185 hir::Adt::Union(_) => SymbolKind::Union,
186 hir::Adt::Enum(_) => SymbolKind::Enum,
188 hir::ScopeDef::ModuleDef(Const(..)) => CompletionItemKind::SymbolKind(SymbolKind::Const),
189 hir::ScopeDef::ModuleDef(Static(..)) => CompletionItemKind::SymbolKind(SymbolKind::Static),
190 hir::ScopeDef::ModuleDef(Trait(..)) => CompletionItemKind::SymbolKind(SymbolKind::Trait),
191 hir::ScopeDef::ModuleDef(TypeAlias(..)) => {
192 CompletionItemKind::SymbolKind(SymbolKind::TypeAlias)
194 hir::ScopeDef::ModuleDef(BuiltinType(..)) => CompletionItemKind::BuiltinType,
195 hir::ScopeDef::GenericParam(param) => CompletionItemKind::SymbolKind(match param {
196 hir::GenericParam::TypeParam(_) => SymbolKind::TypeParam,
197 hir::GenericParam::LifetimeParam(_) => SymbolKind::LifetimeParam,
198 hir::GenericParam::ConstParam(_) => SymbolKind::ConstParam,
200 hir::ScopeDef::Local(..) => CompletionItemKind::SymbolKind(SymbolKind::Local),
201 hir::ScopeDef::Label(..) => CompletionItemKind::SymbolKind(SymbolKind::Label),
202 hir::ScopeDef::AdtSelfType(..) | hir::ScopeDef::ImplSelfType(..) => {
203 CompletionItemKind::SymbolKind(SymbolKind::SelfParam)
205 hir::ScopeDef::Unknown => {
206 let mut item = CompletionItem::new(
207 CompletionKind::Reference,
209 local_name.to_string(),
211 item.kind(CompletionItemKind::UnresolvedReference).add_import(import_to_add);
212 return Some(item.build());
216 let local_name = local_name.to_string();
217 let mut item = CompletionItem::new(completion_kind, ctx.source_range(), local_name.clone());
218 if let hir::ScopeDef::Local(local) = resolution {
219 let ty = local.ty(ctx.db());
220 if !ty.is_unknown() {
221 item.detail(ty.display(ctx.db()).to_string());
224 item.set_relevance(CompletionRelevance {
225 type_match: compute_type_match(ctx.completion, &ty),
226 exact_name_match: compute_exact_name_match(ctx.completion, &local_name),
228 ..CompletionRelevance::default()
231 if let Some(ref_match) = compute_ref_match(ctx.completion, &ty) {
232 item.ref_match(ref_match);
236 // Add `<>` for generic types
238 ctx.completion.path_context,
239 Some(PathCompletionContext { kind: Some(PathKind::Type), has_type_args: false, .. })
240 ) && ctx.completion.config.add_call_parenthesis
242 if let Some(cap) = ctx.snippet_cap() {
243 let has_non_default_type_params = match resolution {
244 hir::ScopeDef::ModuleDef(Adt(it)) => it.has_non_default_type_params(ctx.db()),
245 hir::ScopeDef::ModuleDef(TypeAlias(it)) => it.has_non_default_type_params(ctx.db()),
248 if has_non_default_type_params {
249 cov_mark::hit!(inserts_angle_brackets_for_generics);
250 item.lookup_by(local_name.clone())
251 .label(format!("{}<…>", local_name))
252 .insert_snippet(cap, format!("{}<$0>", local_name));
257 .add_import(import_to_add)
258 .set_documentation(scope_def_docs(ctx.db(), resolution))
259 .set_deprecated(scope_def_is_deprecated(&ctx, resolution));
263 fn scope_def_docs(db: &RootDatabase, resolution: &hir::ScopeDef) -> Option<hir::Documentation> {
264 use hir::ModuleDef::*;
266 hir::ScopeDef::ModuleDef(Module(it)) => it.docs(db),
267 hir::ScopeDef::ModuleDef(Adt(it)) => it.docs(db),
268 hir::ScopeDef::ModuleDef(Variant(it)) => it.docs(db),
269 hir::ScopeDef::ModuleDef(Const(it)) => it.docs(db),
270 hir::ScopeDef::ModuleDef(Static(it)) => it.docs(db),
271 hir::ScopeDef::ModuleDef(Trait(it)) => it.docs(db),
272 hir::ScopeDef::ModuleDef(TypeAlias(it)) => it.docs(db),
277 fn scope_def_is_deprecated(ctx: &RenderContext<'_>, resolution: &hir::ScopeDef) -> bool {
279 hir::ScopeDef::ModuleDef(it) => ctx.is_deprecated_assoc_item(*it),
280 hir::ScopeDef::MacroDef(it) => ctx.is_deprecated(*it),
281 hir::ScopeDef::GenericParam(it) => ctx.is_deprecated(*it),
282 hir::ScopeDef::AdtSelfType(it) => ctx.is_deprecated(*it),
287 fn compute_type_match(
288 ctx: &CompletionContext,
289 completion_ty: &hir::Type,
290 ) -> Option<CompletionRelevanceTypeMatch> {
291 let expected_type = ctx.expected_type.as_ref()?;
293 // We don't ever consider unit type to be an exact type match, since
294 // nearly always this is not meaningful to the user.
295 if expected_type.is_unit() {
299 if completion_ty == expected_type {
300 Some(CompletionRelevanceTypeMatch::Exact)
301 } else if expected_type.could_unify_with(ctx.db, completion_ty) {
302 Some(CompletionRelevanceTypeMatch::CouldUnify)
308 fn compute_exact_name_match(ctx: &CompletionContext, completion_name: &str) -> bool {
309 ctx.expected_name.as_ref().map_or(false, |name| name.text() == completion_name)
312 fn compute_ref_match(
313 ctx: &CompletionContext,
314 completion_ty: &hir::Type,
315 ) -> Option<hir::Mutability> {
316 let expected_type = ctx.expected_type.as_ref()?;
317 if completion_ty != expected_type {
318 let expected_type_without_ref = expected_type.remove_ref()?;
319 if completion_ty.autoderef(ctx.db).any(|deref_ty| deref_ty == expected_type_without_ref) {
320 cov_mark::hit!(suggest_ref);
321 let mutability = if expected_type.is_mutable_reference() {
324 hir::Mutability::Shared
326 return Some(mutability);
336 use expect_test::{expect, Expect};
337 use itertools::Itertools;
340 item::CompletionRelevanceTypeMatch,
341 tests::{check_edit, do_completion, get_all_items, TEST_CONFIG},
342 CompletionKind, CompletionRelevance,
346 fn check(ra_fixture: &str, expect: Expect) {
347 let actual = do_completion(ra_fixture, CompletionKind::Reference);
348 expect.assert_debug_eq(&actual);
352 fn check_relevance(ra_fixture: &str, expect: Expect) {
353 check_relevance_for_kinds(&[CompletionKind::Reference], ra_fixture, expect)
357 fn check_relevance_for_kinds(kinds: &[CompletionKind], ra_fixture: &str, expect: Expect) {
358 let mut actual = get_all_items(TEST_CONFIG, ra_fixture);
359 actual.retain(|it| kinds.contains(&it.completion_kind));
360 actual.sort_by_key(|it| cmp::Reverse(it.relevance().score()));
365 let mut items = vec![];
367 let tag = it.kind().unwrap().tag();
368 let relevance = display_relevance(it.relevance());
369 items.push(format!("{} {} {}\n", tag, it.label(), relevance));
371 if let Some((mutability, relevance)) = it.ref_match() {
372 let label = format!("&{}{}", mutability.as_keyword_for_ref(), it.label());
373 let relevance = display_relevance(relevance);
375 items.push(format!("{} {} {}\n", tag, label, relevance));
380 .collect::<String>();
382 expect.assert_eq(&actual);
384 fn display_relevance(relevance: CompletionRelevance) -> String {
385 let relevance_factors = vec![
386 (relevance.type_match == Some(CompletionRelevanceTypeMatch::Exact), "type"),
388 relevance.type_match == Some(CompletionRelevanceTypeMatch::CouldUnify),
391 (relevance.exact_name_match, "name"),
392 (relevance.is_local, "local"),
393 (relevance.exact_postfix_snippet_match, "snippet"),
396 .filter_map(|(cond, desc)| if cond { Some(desc) } else { None })
399 format!("[{}]", relevance_factors)
404 fn enum_detail_includes_record_fields() {
407 enum Foo { Foo { x: i32, y: i32 } }
409 fn main() { Foo::Fo$0 }
415 source_range: 54..56,
421 detail: "{ x: i32, y: i32 }",
429 fn enum_detail_doesnt_include_tuple_fields() {
432 enum Foo { Foo (i32, i32) }
434 fn main() { Foo::Fo$0 }
440 source_range: 46..48,
447 detail: "(i32, i32)",
448 trigger_call_info: true,
456 fn fn_detail_includes_args_and_return_type() {
459 fn foo<T>(a: u32, b: u32, t: T) -> (u32, T) { (a, t) }
467 source_range: 68..70,
469 insert: "foo(${1:a}, ${2:b}, ${3:t})$0",
474 detail: "fn(u32, u32, T) -> (u32, T)",
475 trigger_call_info: true,
479 source_range: 68..70,
494 fn enum_detail_just_parentheses_for_unit() {
499 fn main() { Foo::Fo$0 }
505 source_range: 35..37,
519 fn lookup_enums_by_two_qualifiers() {
523 pub enum Spam { Foo, Bar(i32) }
525 fn main() { let _: m::Spam = S$0 }
530 label: "Spam::Bar(…)",
531 source_range: 75..76,
533 insert: "Spam::Bar($0)",
539 relevance: CompletionRelevance {
540 exact_name_match: false,
545 exact_postfix_snippet_match: false,
547 trigger_call_info: true,
551 source_range: 75..76,
559 label: "m::Spam::Foo",
560 source_range: 75..76,
562 insert: "m::Spam::Foo",
568 relevance: CompletionRelevance {
569 exact_name_match: false,
574 exact_postfix_snippet_match: false,
579 source_range: 75..76,
594 fn sets_deprecated_flag_in_items() {
598 fn something_deprecated() {}
599 #[rustc_deprecated(since = "1.0.0")]
600 fn something_else_deprecated() {}
608 source_range: 127..130,
618 label: "something_deprecated()",
619 source_range: 127..130,
621 insert: "something_deprecated()$0",
625 lookup: "something_deprecated",
630 label: "something_else_deprecated()",
631 source_range: 127..130,
633 insert: "something_else_deprecated()$0",
637 lookup: "something_else_deprecated",
647 struct A { #[deprecated] the_field: u32 }
648 fn foo() { A { the$0 } }
654 source_range: 57..60,
662 relevance: CompletionRelevance {
663 exact_name_match: false,
668 exact_postfix_snippet_match: false,
686 fn bar(self) { self.$0 }
692 source_range: 94..94,
698 documentation: Documentation(
704 source_range: 94..94,
711 documentation: Documentation(
737 source_range: 10..12,
743 documentation: Documentation(
749 source_range: 10..12,
756 documentation: Documentation(
762 source_range: 10..12,
768 documentation: Documentation(
778 fn dont_render_attrs() {
784 fn the_method(&self) { }
786 fn foo(s: S) { s.$0 }
791 label: "the_method()",
792 source_range: 81..81,
794 insert: "the_method()$0",
796 lookup: "the_method",
805 fn no_call_parens_if_fn_ptr_needed() {
806 cov_mark::check!(no_call_parens_if_fn_ptr_needed);
810 fn foo(foo: u8, bar: u8) {}
811 struct ManualVtable { f: fn(u8, u8) }
813 fn main() -> ManualVtable {
814 ManualVtable { f: f$0 }
818 fn foo(foo: u8, bar: u8) {}
819 struct ManualVtable { f: fn(u8, u8) }
821 fn main() -> ManualVtable {
822 ManualVtable { f: foo }
829 fn no_parens_in_use_item() {
830 cov_mark::check!(no_parens_in_use_item);
834 mod m { pub fn foo() {} }
838 mod m { pub fn foo() {} }
845 fn no_parens_in_call() {
861 impl Foo { fn foo(&self){} }
862 fn f(foo: &Foo) { foo.f$0(); }
866 impl Foo { fn foo(&self){} }
867 fn f(foo: &Foo) { foo.foo(); }
873 fn inserts_angle_brackets_for_generics() {
874 cov_mark::check!(inserts_angle_brackets_for_generics);
900 struct Vec<T = i128> {}
904 struct Vec<T = i128> {}
912 fn foo(xs: Ve$0<i128>)
916 fn foo(xs: Vec<i128>)
922 fn active_param_relevance() {
925 struct S { foo: i64, bar: u32, baz: u32 }
926 fn test(bar: u32) { }
927 fn foo(s: S) { test(s.$0) }
938 fn record_field_relevances() {
941 struct A { foo: i64, bar: u32, baz: u32 }
942 struct B { x: (), y: f32, bar: u32 }
943 fn foo(a: A) { B { bar: a.$0 }; }
954 fn record_field_and_call_relevances() {
957 struct A { foo: i64, bar: u32, baz: u32 }
958 struct B { x: (), y: f32, bar: u32 }
960 fn foo(a: A) { B { bar: f(a.$0) }; }
970 struct A { foo: i64, bar: u32, baz: u32 }
971 struct B { x: (), y: f32, bar: u32 }
973 fn foo(a: A) { f(B { bar: a.$0 }); }
984 fn prioritize_exact_ref_match() {
987 struct WorldSnapshot { _f: () };
988 fn go(world: &WorldSnapshot) { go(w$0) }
991 lc world [type+name+local]
999 fn too_many_arguments() {
1000 cov_mark::check!(too_many_arguments);
1004 fn f(foo: &Foo) { f(foo, w$0) }
1015 fn score_fn_type_and_name_match() {
1018 struct A { bar: u8 }
1019 fn baz() -> u8 { 0 }
1020 fn bar() -> u8 { 0 }
1021 fn f() { A { bar: b$0 }; }
1024 fn bar() [type+name]
1033 fn score_method_type_and_name_match() {
1039 fn aaa(&self) -> u32 { 0 }
1040 fn bbb(&self) -> u32 { 0 }
1041 fn ccc(&self) -> u64 { 0 }
1048 me aaa() [type+name]
1056 fn score_method_name_match_only() {
1062 fn aaa(&self) -> u64 { 0 }
1075 fn suggest_ref_mut() {
1076 cov_mark::check!(suggest_ref);
1080 fn foo(s: &mut S) {}
1088 lc &mut s [type+name+local]
1097 fn foo(s: &mut S) {}
1104 lc s [type+name+local]
1113 fn suggest_deref() {
1120 impl core::ops::Deref for T {
1123 fn deref(&self) -> &Self::Target {
1152 fn suggest_deref_mut() {
1155 //- minicore: deref_mut
1159 impl core::ops::Deref for T {
1162 fn deref(&self) -> &Self::Target {
1167 impl core::ops::DerefMut for T {
1168 fn deref_mut(&mut self) -> &mut Self::Target {
1173 fn foo(s: &mut S) {}
1185 lc &mut t [type+local]
1257 fn suggest_deref_fn_ret() {
1264 impl core::ops::Deref for T {
1267 fn deref(&self) -> &Self::Target {
1293 fn struct_field_method_ref() {
1296 struct Foo { bar: u32 }
1297 impl Foo { fn baz(&self) -> u32 { 0 } }
1299 fn foo(f: Foo) { let _: &u32 = f.b$0 }
1302 // Ideally we'd also suggest &f.bar and &f.baz() as exact
1303 // type matches. See #8058.
1308 source_range: 98..99,
1318 source_range: 98..99,
1323 detail: "fn(&self) -> u32",
1334 enum Foo<T> { A(T), B }
1335 // bar() should not be an exact type match
1336 // because the generic parameters are different
1337 fn bar() -> Foo<u8> { Foo::B }
1338 // FIXME baz() should be an exact type match
1339 // because the types could unify, but it currently
1340 // is not. This is due to the T here being
1341 // TyKind::Placeholder rather than TyKind::Missing.
1342 fn baz<T>() -> Foo<T> { Foo::B }
1344 let foo: Foo<u32> = Foo::B;
1345 let _: Foo<u32> = f$0;
1350 ev Foo::A(…) [type_could_unify]
1351 ev Foo::B [type_could_unify]
1361 fn postfix_completion_relevance() {
1362 check_relevance_for_kinds(
1363 &[CompletionKind::Postfix, CompletionKind::Magic],
1368 fn not(self) -> Self::Output;
1373 fn not(self) -> bool { if self { false } else { true }}
1378 let _: bool = (9 > 2).not$0;
1383 me not() (use ops::Not) [type_could_unify]