]> git.lizzy.rs Git - rust.git/blob - crates/ide_completion/src/render/struct_literal.rs
Add completion for struct literal in which all fields are visible.
[rust.git] / crates / ide_completion / src / render / struct_literal.rs
1 //! Renderer for `struct` literal.
2
3 use hir::{db::HirDatabase, HasAttrs, HasVisibility, Name, StructKind};
4 use ide_db::helpers::SnippetCap;
5 use itertools::Itertools;
6
7 use crate::{item::CompletionKind, render::RenderContext, CompletionItem, CompletionItemKind};
8
9 pub(crate) fn render_struct_literal(
10     ctx: RenderContext<'_>,
11     strukt: hir::Struct,
12     local_name: Option<Name>,
13 ) -> Option<CompletionItem> {
14     let _p = profile::span("render_struct_literal");
15
16     let fields = strukt.fields(ctx.db());
17     let (visible_fields, fields_omitted) = visible_fields(&ctx, &fields, strukt)?;
18
19     if fields_omitted {
20         // If some fields are private you can't make `struct` literal.
21         return None;
22     }
23
24     let name = local_name.unwrap_or_else(|| strukt.name(ctx.db())).to_string();
25     let literal = render_literal(&ctx, &name, strukt.kind(ctx.db()), &visible_fields)?;
26
27     Some(build_completion(ctx, name, literal, strukt))
28 }
29
30 fn build_completion(
31     ctx: RenderContext<'_>,
32     name: String,
33     literal: String,
34     def: impl HasAttrs + Copy,
35 ) -> CompletionItem {
36     let mut item = CompletionItem::new(CompletionKind::Snippet, ctx.source_range(), name + " {…}");
37     item.kind(CompletionItemKind::Snippet)
38         .set_documentation(ctx.docs(def))
39         .set_deprecated(ctx.is_deprecated(def))
40         .detail(&literal);
41     if let Some(snippet_cap) = ctx.snippet_cap() {
42         item.insert_snippet(snippet_cap, literal);
43     } else {
44         item.insert_text(literal);
45     };
46     item.build()
47 }
48
49 fn render_literal(
50     ctx: &RenderContext<'_>,
51     name: &str,
52     kind: StructKind,
53     fields: &[hir::Field],
54 ) -> Option<String> {
55     let mut literal = match kind {
56         StructKind::Tuple if ctx.snippet_cap().is_some() => render_tuple_as_literal(fields, name),
57         StructKind::Record => render_record_as_literal(ctx.db(), ctx.snippet_cap(), fields, name),
58         _ => return None,
59     };
60
61     if ctx.completion.is_param {
62         literal.push(':');
63         literal.push(' ');
64         literal.push_str(name);
65     }
66     if ctx.snippet_cap().is_some() {
67         literal.push_str("$0");
68     }
69     Some(literal)
70 }
71
72 fn render_record_as_literal(
73     db: &dyn HirDatabase,
74     snippet_cap: Option<SnippetCap>,
75     fields: &[hir::Field],
76     name: &str,
77 ) -> String {
78     let fields = fields.iter();
79     if snippet_cap.is_some() {
80         format!(
81             "{name} {{ {} }}",
82             fields
83                 .enumerate()
84                 .map(|(idx, field)| format!("{}: ${{{}:()}}", field.name(db), idx + 1))
85                 .format(", "),
86             name = name
87         )
88     } else {
89         format!(
90             "{name} {{ {} }}",
91             fields.map(|field| format!("{}: ()", field.name(db))).format(", "),
92             name = name
93         )
94     }
95 }
96
97 fn render_tuple_as_literal(fields: &[hir::Field], name: &str) -> String {
98     format!(
99         "{name}({})",
100         fields.iter().enumerate().map(|(idx, _)| format!("${}", idx + 1)).format(", "),
101         name = name
102     )
103 }
104
105 fn visible_fields(
106     ctx: &RenderContext<'_>,
107     fields: &[hir::Field],
108     item: impl HasAttrs,
109 ) -> Option<(Vec<hir::Field>, bool)> {
110     let module = ctx.completion.scope.module()?;
111     let n_fields = fields.len();
112     let fields = fields
113         .iter()
114         .filter(|field| field.is_visible_from(ctx.db(), module))
115         .copied()
116         .collect::<Vec<_>>();
117
118     let fields_omitted =
119         n_fields - fields.len() > 0 || item.attrs(ctx.db()).by_key("non_exhaustive").exists();
120     Some((fields, fields_omitted))
121 }