]> git.lizzy.rs Git - rust.git/blob - crates/ide_completion/src/render/pattern.rs
clippy::redudant_borrow
[rust.git] / crates / ide_completion / src / render / pattern.rs
1 //! Renderer for patterns.
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_pat(
10     ctx: RenderContext<'_>,
11     strukt: hir::Struct,
12     local_name: Option<Name>,
13 ) -> Option<CompletionItem> {
14     let _p = profile::span("render_struct_pat");
15
16     let fields = strukt.fields(ctx.db());
17     let (visible_fields, fields_omitted) = visible_fields(&ctx, &fields, strukt)?;
18
19     if visible_fields.is_empty() {
20         // Matching a struct without matching its fields is pointless, unlike matching a Variant without its fields
21         return None;
22     }
23
24     let name = local_name.unwrap_or_else(|| strukt.name(ctx.db())).to_string();
25     let pat = render_pat(&ctx, &name, strukt.kind(ctx.db()), &visible_fields, fields_omitted)?;
26
27     Some(build_completion(ctx, name, pat, strukt))
28 }
29
30 pub(crate) fn render_variant_pat(
31     ctx: RenderContext<'_>,
32     variant: hir::Variant,
33     local_name: Option<Name>,
34     path: Option<hir::ModPath>,
35 ) -> Option<CompletionItem> {
36     let _p = profile::span("render_variant_pat");
37
38     let fields = variant.fields(ctx.db());
39     let (visible_fields, fields_omitted) = visible_fields(&ctx, &fields, variant)?;
40
41     let name = match &path {
42         Some(path) => path.to_string(),
43         None => local_name.unwrap_or_else(|| variant.name(ctx.db())).to_string(),
44     };
45     let pat = render_pat(&ctx, &name, variant.kind(ctx.db()), &visible_fields, fields_omitted)?;
46
47     Some(build_completion(ctx, name, pat, variant))
48 }
49
50 fn build_completion(
51     ctx: RenderContext<'_>,
52     name: String,
53     pat: String,
54     def: impl HasAttrs + Copy,
55 ) -> CompletionItem {
56     let mut item = CompletionItem::new(CompletionKind::Snippet, ctx.source_range(), name);
57     item.kind(CompletionItemKind::Binding)
58         .set_documentation(ctx.docs(def))
59         .set_deprecated(ctx.is_deprecated(def))
60         .detail(&pat);
61     if let Some(snippet_cap) = ctx.snippet_cap() {
62         item.insert_snippet(snippet_cap, pat);
63     } else {
64         item.insert_text(pat);
65     };
66     item.build()
67 }
68
69 fn render_pat(
70     ctx: &RenderContext<'_>,
71     name: &str,
72     kind: StructKind,
73     fields: &[hir::Field],
74     fields_omitted: bool,
75 ) -> Option<String> {
76     let mut pat = match kind {
77         StructKind::Tuple if ctx.snippet_cap().is_some() => {
78             render_tuple_as_pat(fields, name, fields_omitted)
79         }
80         StructKind::Record => {
81             render_record_as_pat(ctx.db(), ctx.snippet_cap(), fields, name, fields_omitted)
82         }
83         _ => return None,
84     };
85
86     if ctx.completion.is_param {
87         pat.push(':');
88         pat.push(' ');
89         pat.push_str(name);
90     }
91     if ctx.snippet_cap().is_some() {
92         pat.push_str("$0");
93     }
94     Some(pat)
95 }
96
97 fn render_record_as_pat(
98     db: &dyn HirDatabase,
99     snippet_cap: Option<SnippetCap>,
100     fields: &[hir::Field],
101     name: &str,
102     fields_omitted: bool,
103 ) -> String {
104     let fields = fields.iter();
105     if snippet_cap.is_some() {
106         format!(
107             "{name} {{ {}{} }}",
108             fields
109                 .enumerate()
110                 .map(|(idx, field)| format!("{}${}", field.name(db), idx + 1))
111                 .format(", "),
112             if fields_omitted { ", .." } else { "" },
113             name = name
114         )
115     } else {
116         format!(
117             "{name} {{ {}{} }}",
118             fields.map(|field| field.name(db)).format(", "),
119             if fields_omitted { ", .." } else { "" },
120             name = name
121         )
122     }
123 }
124
125 fn render_tuple_as_pat(fields: &[hir::Field], name: &str, fields_omitted: bool) -> String {
126     format!(
127         "{name}({}{})",
128         fields.iter().enumerate().map(|(idx, _)| format!("${}", idx + 1)).format(", "),
129         if fields_omitted { ", .." } else { "" },
130         name = name
131     )
132 }
133
134 fn visible_fields(
135     ctx: &RenderContext<'_>,
136     fields: &[hir::Field],
137     item: impl HasAttrs,
138 ) -> Option<(Vec<hir::Field>, bool)> {
139     let module = ctx.completion.scope.module()?;
140     let n_fields = fields.len();
141     let fields = fields
142         .into_iter()
143         .filter(|field| field.is_visible_from(ctx.db(), module))
144         .copied()
145         .collect::<Vec<_>>();
146
147     let fields_omitted =
148         n_fields - fields.len() > 0 || item.attrs(ctx.db()).by_key("non_exhaustive").exists();
149     Some((fields, fields_omitted))
150 }