1 //! Renderer for `struct` literal.
3 use hir::{db::HirDatabase, HasAttrs, HasVisibility, Name, StructKind};
4 use ide_db::helpers::SnippetCap;
5 use itertools::Itertools;
8 use crate::{render::RenderContext, CompletionItem, CompletionItemKind};
10 pub(crate) fn render_struct_literal(
11 ctx: RenderContext<'_>,
13 local_name: Option<Name>,
14 ) -> Option<CompletionItem> {
15 let _p = profile::span("render_struct_literal");
17 let fields = strukt.fields(ctx.db());
18 let (visible_fields, fields_omitted) = visible_fields(&ctx, &fields, strukt)?;
21 // If some fields are private you can't make `struct` literal.
25 let name = local_name.unwrap_or_else(|| strukt.name(ctx.db())).to_smol_str();
26 let literal = render_literal(&ctx, &name, strukt.kind(ctx.db()), &visible_fields)?;
28 Some(build_completion(ctx, name, literal, strukt))
32 ctx: RenderContext<'_>,
35 def: impl HasAttrs + Copy,
37 let mut item = CompletionItem::new(
38 CompletionItemKind::Snippet,
40 SmolStr::from_iter([&name, " {…}"]),
42 item.set_documentation(ctx.docs(def)).set_deprecated(ctx.is_deprecated(def)).detail(&literal);
43 match ctx.snippet_cap() {
44 Some(snippet_cap) => item.insert_snippet(snippet_cap, literal),
45 None => item.insert_text(literal),
51 ctx: &RenderContext<'_>,
54 fields: &[hir::Field],
56 let mut literal = match kind {
57 StructKind::Tuple if ctx.snippet_cap().is_some() => render_tuple_as_literal(fields, name),
58 StructKind::Record => render_record_as_literal(ctx.db(), ctx.snippet_cap(), fields, name),
62 if ctx.snippet_cap().is_some() {
63 literal.push_str("$0");
68 fn render_record_as_literal(
70 snippet_cap: Option<SnippetCap>,
71 fields: &[hir::Field],
74 let fields = fields.iter();
75 if snippet_cap.is_some() {
80 .map(|(idx, field)| format!("{}: ${{{}:()}}", field.name(db), idx + 1))
87 fields.map(|field| format!("{}: ()", field.name(db))).format(", "),
93 fn render_tuple_as_literal(fields: &[hir::Field], name: &str) -> String {
96 fields.iter().enumerate().map(|(idx, _)| format!("${}", idx + 1)).format(", "),
102 ctx: &RenderContext<'_>,
103 fields: &[hir::Field],
105 ) -> Option<(Vec<hir::Field>, bool)> {
106 let module = ctx.completion.scope.module()?;
107 let n_fields = fields.len();
110 .filter(|field| field.is_visible_from(ctx.db(), module))
112 .collect::<Vec<_>>();
115 n_fields - fields.len() > 0 || item.attrs(ctx.db()).by_key("non_exhaustive").exists();
116 Some((fields, fields_omitted))