rust-analyzer/crates/ide-completion/src/render/pattern.rs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

179 lines
5.3 KiB
Rust
Raw Normal View History

2020-12-20 17:19:23 +00:00
//! Renderer for patterns.
use hir::{db::HirDatabase, HasAttrs, Name, StructKind};
2022-03-06 18:01:30 +00:00
use ide_db::SnippetCap;
2020-12-20 17:19:23 +00:00
use itertools::Itertools;
use syntax::SmolStr;
2020-12-20 17:19:23 +00:00
use crate::{
context::{ParamKind, PatternContext},
render::{
variant::{format_literal_label, visible_fields},
RenderContext,
},
2021-08-14 17:06:35 +00:00
CompletionItem, CompletionItemKind,
};
2020-12-20 17:19:23 +00:00
pub(crate) fn render_struct_pat(
ctx: RenderContext<'_>,
pattern_ctx: &PatternContext,
2020-12-20 17:19:23 +00:00
strukt: hir::Struct,
local_name: Option<Name>,
) -> Option<CompletionItem> {
let _p = profile::span("render_struct_pat");
let fields = strukt.fields(ctx.db());
let (visible_fields, fields_omitted) = visible_fields(ctx.completion, &fields, strukt)?;
2020-12-20 17:19:23 +00:00
2020-12-22 18:00:38 +00:00
if visible_fields.is_empty() {
2020-12-20 17:19:23 +00:00
// 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.to_smol_str(), name.escaped().to_smol_str());
let kind = strukt.kind(ctx.db());
let label = format_literal_label(name.as_str(), kind);
let pat = render_pat(&ctx, pattern_ctx, &escaped_name, kind, &visible_fields, fields_omitted)?;
2020-12-20 17:19:23 +00:00
Some(build_completion(ctx, label, pat, strukt))
2020-12-20 17:19:23 +00:00
}
pub(crate) fn render_variant_pat(
ctx: RenderContext<'_>,
pattern_ctx: &PatternContext,
2020-12-20 17:19:23 +00:00
variant: hir::Variant,
local_name: Option<Name>,
path: Option<&hir::ModPath>,
2020-12-20 17:19:23 +00:00
) -> Option<CompletionItem> {
let _p = profile::span("render_variant_pat");
let fields = variant.fields(ctx.db());
2022-03-16 15:41:35 +00:00
let (visible_fields, fields_omitted) = visible_fields(ctx.completion, &fields, variant)?;
2020-12-20 17:19:23 +00:00
let (name, escaped_name) = match path {
Some(path) => (path.to_string().into(), path.escaped().to_string().into()),
None => {
let name = local_name.unwrap_or_else(|| variant.name(ctx.db()));
(name.to_smol_str(), name.escaped().to_smol_str())
}
};
let kind = variant.kind(ctx.db());
let label = format_literal_label(name.as_str(), kind);
let pat = render_pat(&ctx, pattern_ctx, &escaped_name, kind, &visible_fields, fields_omitted)?;
Some(build_completion(ctx, label, pat, variant))
2020-12-22 18:00:38 +00:00
}
fn build_completion(
ctx: RenderContext<'_>,
label: SmolStr,
2020-12-22 18:00:38 +00:00
pat: String,
2021-03-12 09:12:32 +00:00
def: impl HasAttrs + Copy,
2020-12-22 18:00:38 +00:00
) -> CompletionItem {
let mut item = CompletionItem::new(CompletionItemKind::Binding, ctx.source_range(), label);
item.set_documentation(ctx.docs(def))
.set_deprecated(ctx.is_deprecated(def))
.detail(&pat)
.set_relevance(ctx.completion_relevance());
match ctx.snippet_cap() {
Some(snippet_cap) => item.insert_snippet(snippet_cap, pat),
None => item.insert_text(pat),
2020-12-22 18:00:38 +00:00
};
2021-03-12 09:12:32 +00:00
item.build()
}
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 => {
2021-06-13 03:54:16 +00:00
render_record_as_pat(ctx.db(), ctx.snippet_cap(), fields, name, fields_omitted)
}
2022-07-02 14:17:29 +00:00
StructKind::Unit => name.to_string(),
2020-12-20 17:19:23 +00:00
};
let needs_ascription = matches!(
pattern_ctx,
PatternContext {
param_ctx: Some((.., ParamKind::Function(_))),
has_type_ascription: false,
..
}
);
if needs_ascription {
2020-12-20 17:19:23 +00:00
pat.push(':');
pat.push(' ');
2021-06-13 03:54:16 +00:00
pat.push_str(name);
2020-12-20 17:19:23 +00:00
}
if ctx.snippet_cap().is_some() {
pat.push_str("$0");
}
Some(pat)
2020-12-20 17:19:23 +00:00
}
fn render_record_as_pat(
db: &dyn HirDatabase,
snippet_cap: Option<SnippetCap>,
2020-12-20 17:19:23 +00:00
fields: &[hir::Field],
name: &str,
fields_omitted: bool,
) -> String {
let fields = fields.iter();
match snippet_cap {
Some(_) => {
format!(
"{name} {{ {}{} }}",
fields.enumerate().format_with(", ", |(idx, field), f| {
2022-07-02 14:17:29 +00:00
f(&format_args!("{}${}", field.name(db).escaped(), idx + 1))
}),
if fields_omitted { ", .." } else { "" },
name = name
)
}
None => {
format!(
"{name} {{ {}{} }}",
2022-07-02 14:17:29 +00:00
fields.map(|field| field.name(db).escaped().to_smol_str()).format(", "),
if fields_omitted { ", .." } else { "" },
name = name
)
}
}
2020-12-20 17:19:23 +00:00
}
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
)
}
}
}