1 //! Code common to structs, unions, and enum variants.
3 use crate::render::RenderContext;
4 use hir::{db::HirDatabase, HasAttrs, HasVisibility, HirDisplay};
5 use ide_db::SnippetCap;
6 use itertools::Itertools;
8 /// A rendered struct, union, or enum variant, split into fields for actual
9 /// auto-completion (`literal`, using `field: ()`) and display in the
10 /// completions menu (`detail`, using `field: type`).
11 pub(crate) struct RenderedCompound {
16 /// Render a record type (or sub-type) to a `RenderedCompound`. Use `None` for
17 /// the `name` argument for an anonymous type.
18 pub(crate) fn render_record(
20 snippet_cap: Option<SnippetCap>,
21 fields: &[hir::Field],
23 ) -> RenderedCompound {
24 let fields = fields.iter();
26 let (completions, types): (Vec<_>, Vec<_>) = fields
30 if snippet_cap.is_some() {
31 format!("{}: ${{{}:()}}", field.name(db), idx + 1)
33 format!("{}: ()", field.name(db))
35 format!("{}: {}", field.name(db), field.ty(db).display(db)),
40 literal: format!("{} {{ {} }}", name.unwrap_or(""), completions.iter().format(", ")),
41 detail: format!("{} {{ {} }}", name.unwrap_or(""), types.iter().format(", ")),
45 /// Render a tuple type (or sub-type) to a `RenderedCompound`. Use `None` for
46 /// the `name` argument for an anonymous type.
47 pub(crate) fn render_tuple(
49 snippet_cap: Option<SnippetCap>,
50 fields: &[hir::Field],
52 ) -> RenderedCompound {
53 let fields = fields.iter();
55 let (completions, types): (Vec<_>, Vec<_>) = fields
59 if snippet_cap.is_some() {
60 format!("${{{}:()}}", (idx + 1).to_string())
64 field.ty(db).display(db).to_string(),
69 literal: format!("{}({})", name.unwrap_or(""), completions.iter().format(", ")),
70 detail: format!("{}({})", name.unwrap_or(""), types.iter().format(", ")),
74 /// Find all the visible fields in a `HasAttrs`. Returns the list of visible
75 /// fields, plus a boolean for whether the list is comprehensive (contains no
76 /// private fields and is not marked `#[non_exhaustive]`).
77 pub(crate) fn visible_fields(
78 ctx: &RenderContext<'_>,
79 fields: &[hir::Field],
81 ) -> Option<(Vec<hir::Field>, bool)> {
82 let module = ctx.completion.module?;
83 let n_fields = fields.len();
86 .filter(|field| field.is_visible_from(ctx.db(), module))
91 n_fields - fields.len() > 0 || item.attrs(ctx.db()).by_key("non_exhaustive").exists();
92 Some((fields, fields_omitted))