ide_completion/render/
pattern.rs

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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
//! Renderer for patterns.

use hir::{db::HirDatabase, Name, StructKind};
use ide_db::{documentation::HasDocs, SnippetCap};
use itertools::Itertools;
use syntax::{Edition, SmolStr, ToSmolStr};

use crate::{
    context::{ParamContext, ParamKind, PathCompletionCtx, PatternContext},
    render::{
        variant::{format_literal_label, format_literal_lookup, visible_fields},
        RenderContext,
    },
    CompletionItem, CompletionItemKind,
};

pub(crate) fn render_struct_pat(
    ctx: RenderContext<'_>,
    pattern_ctx: &PatternContext,
    strukt: hir::Struct,
    local_name: Option<Name>,
) -> Option<CompletionItem> {
    let _p = tracing::info_span!("render_struct_pat").entered();

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

    if visible_fields.is_empty() {
        // Matching a struct without matching its fields is pointless, unlike matching a Variant without its fields
        return None;
    }

    let name = local_name.unwrap_or_else(|| strukt.name(ctx.db()));
    let (name, escaped_name) = (
        name.unescaped().display(ctx.db()).to_smolstr(),
        name.display(ctx.db(), ctx.completion.edition).to_smolstr(),
    );
    let kind = strukt.kind(ctx.db());
    let label = format_literal_label(name.as_str(), kind, ctx.snippet_cap());
    let lookup = format_literal_lookup(name.as_str(), kind);
    let pat = render_pat(&ctx, pattern_ctx, &escaped_name, kind, &visible_fields, fields_omitted)?;

    let db = ctx.db();

    Some(build_completion(ctx, label, lookup, pat, strukt, strukt.ty(db), false))
}

pub(crate) fn render_variant_pat(
    ctx: RenderContext<'_>,
    pattern_ctx: &PatternContext,
    path_ctx: Option<&PathCompletionCtx>,
    variant: hir::Variant,
    local_name: Option<Name>,
    path: Option<&hir::ModPath>,
) -> Option<CompletionItem> {
    let _p = tracing::info_span!("render_variant_pat").entered();

    let fields = variant.fields(ctx.db());
    let (visible_fields, fields_omitted) = visible_fields(ctx.completion, &fields, variant)?;
    let enum_ty = variant.parent_enum(ctx.db()).ty(ctx.db());

    let (name, escaped_name) = match path {
        Some(path) => (
            path.unescaped().display(ctx.db()).to_string().into(),
            path.display(ctx.db(), ctx.completion.edition).to_string().into(),
        ),
        None => {
            let name = local_name.unwrap_or_else(|| variant.name(ctx.db()));
            let it = (
                name.unescaped().display(ctx.db()).to_smolstr(),
                name.display(ctx.db(), ctx.completion.edition).to_smolstr(),
            );
            it
        }
    };

    let (label, lookup, pat) = match path_ctx {
        Some(PathCompletionCtx { has_call_parens: true, .. }) => {
            (name.clone(), name, escaped_name.to_string())
        }
        _ => {
            let kind = variant.kind(ctx.db());
            let label = format_literal_label(name.as_str(), kind, ctx.snippet_cap());
            let lookup = format_literal_lookup(name.as_str(), kind);
            let pat = render_pat(
                &ctx,
                pattern_ctx,
                &escaped_name,
                kind,
                &visible_fields,
                fields_omitted,
            )?;
            (label, lookup, pat)
        }
    };

    Some(build_completion(
        ctx,
        label,
        lookup,
        pat,
        variant,
        enum_ty,
        pattern_ctx.missing_variants.contains(&variant),
    ))
}

fn build_completion(
    ctx: RenderContext<'_>,
    label: SmolStr,
    lookup: SmolStr,
    pat: String,
    def: impl HasDocs + Copy,
    adt_ty: hir::Type,
    // Missing in context of match statement completions
    is_variant_missing: bool,
) -> CompletionItem {
    let mut relevance = ctx.completion_relevance();

    if is_variant_missing {
        relevance.type_match = super::compute_type_match(ctx.completion, &adt_ty);
    }

    let mut item = CompletionItem::new(
        CompletionItemKind::Binding,
        ctx.source_range(),
        label,
        ctx.completion.edition,
    );
    item.set_documentation(ctx.docs(def))
        .set_deprecated(ctx.is_deprecated(def))
        .detail(&pat)
        .lookup_by(lookup)
        .set_relevance(relevance);
    match ctx.snippet_cap() {
        Some(snippet_cap) => item.insert_snippet(snippet_cap, pat),
        None => item.insert_text(pat),
    };
    item.build(ctx.db())
}

fn render_pat(
    ctx: &RenderContext<'_>,
    pattern_ctx: &PatternContext,
    name: &str,
    kind: StructKind,
    fields: &[hir::Field],
    fields_omitted: bool,
) -> Option<String> {
    let mut pat = match kind {
        StructKind::Tuple => render_tuple_as_pat(ctx.snippet_cap(), fields, name, fields_omitted),
        StructKind::Record => render_record_as_pat(
            ctx.db(),
            ctx.snippet_cap(),
            fields,
            name,
            fields_omitted,
            ctx.completion.edition,
        ),
        StructKind::Unit => name.to_owned(),
    };

    let needs_ascription = matches!(
        pattern_ctx,
        PatternContext {
            param_ctx: Some(ParamContext { kind: ParamKind::Function(_), .. }),
            has_type_ascription: false,
            ..
        }
    );
    if needs_ascription {
        pat.push(':');
        pat.push(' ');
        pat.push_str(name);
    }
    if ctx.snippet_cap().is_some() {
        pat.push_str("$0");
    }
    Some(pat)
}

fn render_record_as_pat(
    db: &dyn HirDatabase,
    snippet_cap: Option<SnippetCap>,
    fields: &[hir::Field],
    name: &str,
    fields_omitted: bool,
    edition: Edition,
) -> String {
    let fields = fields.iter();
    match snippet_cap {
        Some(_) => {
            format!(
                "{name} {{ {}{} }}",
                fields.enumerate().format_with(", ", |(idx, field), f| {
                    f(&format_args!("{}${}", field.name(db).display(db.upcast(), edition), idx + 1))
                }),
                if fields_omitted { ", .." } else { "" },
                name = name
            )
        }
        None => {
            format!(
                "{name} {{ {}{} }}",
                fields.map(|field| field.name(db).display_no_db(edition).to_smolstr()).format(", "),
                if fields_omitted { ", .." } else { "" },
                name = name
            )
        }
    }
}

fn render_tuple_as_pat(
    snippet_cap: Option<SnippetCap>,
    fields: &[hir::Field],
    name: &str,
    fields_omitted: bool,
) -> String {
    let fields = fields.iter();
    match snippet_cap {
        Some(_) => {
            format!(
                "{name}({}{})",
                fields
                    .enumerate()
                    .format_with(", ", |(idx, _), f| { f(&format_args!("${}", idx + 1)) }),
                if fields_omitted { ", .." } else { "" },
                name = name
            )
        }
        None => {
            format!(
                "{name}({}{})",
                fields.enumerate().map(|(idx, _)| idx).format(", "),
                if fields_omitted { ", .." } else { "" },
                name = name
            )
        }
    }
}