Unnamed repository; edit this file 'description' to name the repository.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
//! Renderer for `struct` literal.

use hir::{db::HirDatabase, HasAttrs, HasVisibility, Name, StructKind};
use ide_db::SnippetCap;
use itertools::Itertools;
use syntax::SmolStr;

use crate::{render::RenderContext, CompletionItem, CompletionItemKind};

pub(crate) fn render_struct_literal(
    ctx: RenderContext<'_>,
    strukt: hir::Struct,
    path: Option<hir::ModPath>,
    local_name: Option<Name>,
) -> Option<CompletionItem> {
    let _p = profile::span("render_struct_literal");

    let fields = strukt.fields(ctx.db());
    let (visible_fields, fields_omitted) = visible_fields(&ctx, &fields, strukt)?;

    if fields_omitted {
        // If some fields are private you can't make `struct` literal.
        return None;
    }

    let name = local_name.unwrap_or_else(|| strukt.name(ctx.db())).to_smol_str();

    let literal = render_literal(&ctx, path, &name, strukt.kind(ctx.db()), &visible_fields)?;

    Some(build_completion(ctx, name, literal, strukt))
}

fn build_completion(
    ctx: RenderContext<'_>,
    name: SmolStr,
    literal: String,
    def: impl HasAttrs + Copy,
) -> CompletionItem {
    let mut item = CompletionItem::new(
        CompletionItemKind::Snippet,
        ctx.source_range(),
        SmolStr::from_iter([&name, " {…}"]),
    );
    item.set_documentation(ctx.docs(def))
        .set_deprecated(ctx.is_deprecated(def))
        .detail(&literal)
        .set_relevance(ctx.completion_relevance());
    match ctx.snippet_cap() {
        Some(snippet_cap) => item.insert_snippet(snippet_cap, literal),
        None => item.insert_text(literal),
    };
    item.build()
}

fn render_literal(
    ctx: &RenderContext<'_>,
    path: Option<hir::ModPath>,
    name: &str,
    kind: StructKind,
    fields: &[hir::Field],
) -> Option<String> {
    let path_string;

    let qualified_name = if let Some(path) = path {
        path_string = path.to_string();
        &path_string
    } else {
        name
    };

    let mut literal = match kind {
        StructKind::Tuple if ctx.snippet_cap().is_some() => {
            render_tuple_as_literal(fields, qualified_name)
        }
        StructKind::Record => {
            render_record_as_literal(ctx.db(), ctx.snippet_cap(), fields, qualified_name)
        }
        _ => return None,
    };

    if ctx.snippet_cap().is_some() {
        literal.push_str("$0");
    }
    Some(literal)
}

fn render_record_as_literal(
    db: &dyn HirDatabase,
    snippet_cap: Option<SnippetCap>,
    fields: &[hir::Field],
    name: &str,
) -> String {
    let fields = fields.iter();
    if snippet_cap.is_some() {
        format!(
            "{name} {{ {} }}",
            fields
                .enumerate()
                .map(|(idx, field)| format!("{}: ${{{}:()}}", field.name(db), idx + 1))
                .format(", "),
            name = name
        )
    } else {
        format!(
            "{name} {{ {} }}",
            fields.map(|field| format!("{}: ()", field.name(db))).format(", "),
            name = name
        )
    }
}

fn render_tuple_as_literal(fields: &[hir::Field], name: &str) -> String {
    format!(
        "{name}({})",
        fields.iter().enumerate().map(|(idx, _)| format!("${}", idx + 1)).format(", "),
        name = name
    )
}

fn visible_fields(
    ctx: &RenderContext<'_>,
    fields: &[hir::Field],
    item: impl HasAttrs,
) -> Option<(Vec<hir::Field>, bool)> {
    let module = ctx.completion.module?;
    let n_fields = fields.len();
    let fields = fields
        .iter()
        .filter(|field| field.is_visible_from(ctx.db(), module))
        .copied()
        .collect::<Vec<_>>();

    let fields_omitted =
        n_fields - fields.len() > 0 || item.attrs(ctx.db()).by_key("non_exhaustive").exists();
    Some((fields, fields_omitted))
}