use convert_case::{Case, Casing as _};
use crate::{
parse_utils,
types::{
DiscriminatedUnionType, RecordType, TopLevelDocs,
discriminated_union_type::DiscriminatedUnionVariant,
},
};
pub fn parse(commands_md: &str) -> impl Iterator<Item = Result<CommandResponse, String>> {
let mut parser = Parser::default();
commands_md
.split("---")
.skip(1)
.filter_map(|s| {
let trimmed = s.trim();
(!trimmed.is_empty()).then_some(trimmed)
})
.map(move |blk| parser.parse_block(blk))
}
pub struct CommandResponse {
pub command: RecordType,
pub response: DiscriminatedUnionType,
}
pub struct CommandResponseTraitMethod<'a> {
pub command: &'a RecordType,
pub response: &'a DiscriminatedUnionType,
pub shapes: &'a [RecordType],
}
impl<'a> CommandResponseTraitMethod<'a> {
pub fn new(
command: &'a RecordType,
response: &'a DiscriminatedUnionType,
shapes: &'a [RecordType],
) -> Self {
Self {
command,
response,
shapes,
}
}
}
impl<'a> CommandResponseTraitMethod<'a> {
fn can_inline_args(&self) -> bool {
!self
.command
.fields
.iter()
.any(|f| f.is_optional() || f.is_bool())
}
fn can_inline_response(&self) -> Option<&DiscriminatedUnionVariant> {
if self.responses().count() == 1 {
self.responses().next()
} else {
None
}
}
fn responses(&self) -> impl Iterator<Item = &'_ DiscriminatedUnionVariant> {
self.response.variants.iter()
}
}
impl<'a> std::fmt::Display for CommandResponseTraitMethod<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.command.write_docs_fmt(f)?;
write!(
f,
" fn {}(&self",
self.command.name.remove_empty().to_case(Case::Snake)
)?;
let (ret_type, is_response_inlined) =
if let Some(inlined_variant) = self.can_inline_response() {
let typename = inlined_variant.fields[0].typ.clone();
(format!("Arc<{typename}>"), true)
} else {
(self.response.name.clone(), false)
};
if self.can_inline_args() {
for field in self.command.fields.iter() {
write!(f, ", {}: {}", field.rust_name, field.typ)?;
}
writeln!(
f,
") -> impl Future<Output = Result<{ret_type}, Self::Error>> + Send {{ async move {{",
)?;
write!(f, " let command = {} {{", self.command.name)?;
for (ix, field) in self.command.fields.iter().enumerate() {
if ix > 0 {
write!(f, ", ")?;
}
write!(f, "{}", field.rust_name)?;
}
writeln!(f, "}};")?;
} else {
writeln!(
f,
", command: {}) -> impl Future<Output = Result<{ret_type}, Self::Error>> + Send {{ async move {{",
self.command.name,
)?;
}
writeln!(
f,
" let response: {} = self.send(command).await?;",
self.response.name
)?;
let into_inner = if is_response_inlined {
".into_inner()"
} else {
""
};
writeln!(f, " Ok(response{})", into_inner)?;
writeln!(f, " }}")?;
writeln!(f, " }}")
}
}
pub struct CommandFmt<'a>(pub &'a RecordType);
impl std::fmt::Display for CommandFmt<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.write_docs_fmt(f)?;
writeln!(f, "#[derive(Debug, Clone, PartialEq)]")?;
writeln!(f, "#[cfg_attr(feature = \"bon\", derive(::bon::Builder))]")?;
writeln!(f, "pub struct {} {{", self.0.name)?;
for field in self.0.fields.iter() {
writeln!(f, " pub {}: {},", field.rust_name, field.typ)?;
}
writeln!(f, "}}")?;
if self.0.fields.iter().any(|f| f.is_optional() || f.is_bool()) {
writeln!(f)?;
writeln!(f, "impl {} {{", self.0.name)?;
writeln!(
f,
" /// Creates a command with all `Option` parameters set to `None` and all `bool` parameters set to false"
)?;
write!(f, " pub fn new(")?;
for (i, field) in self
.0
.fields
.iter()
.filter(|f| !f.is_optional() && !f.is_bool())
.enumerate()
{
if i > 0 {
write!(f, ", ")?;
}
write!(f, "{}: {}", field.rust_name, field.typ)?;
}
writeln!(f, ") -> Self {{")?;
writeln!(f, " Self {{")?;
for field in self.0.fields.iter() {
if field.is_optional() {
writeln!(f, " {}: None,", field.rust_name)?;
} else if field.is_bool() {
writeln!(f, " {}: false,", field.rust_name)?;
} else {
writeln!(f, " {},", field.rust_name)?;
}
}
writeln!(f, " }}")?;
writeln!(f, " }}")?;
writeln!(f, "}}")?;
}
Ok(())
}
}
pub struct ResponseFmt<'a>(pub &'a DiscriminatedUnionType);
impl std::fmt::Display for ResponseFmt<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(
f,
"#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]"
)?;
writeln!(f, "#[serde(tag = \"type\")]")?;
writeln!(f, "pub enum {} {{", self.0.name)?;
for variant in &self.0.variants {
for comment_line in &variant.doc_comments {
writeln!(
f,
" /// {}",
crate::types::convert_doc_links(comment_line)
)?;
}
writeln!(f, " #[serde(rename = \"{}\")]", variant.api_name)?;
writeln!(
f,
" {}(Arc<{}>),",
variant.rust_name, variant.fields[0].typ
)?;
}
writeln!(f, "}}\n")?;
writeln!(f, "impl {} {{", self.0.name)?;
if self.0.variants.len() > 1 {
for var in self.0.variants.iter() {
assert_eq!(var.fields.len(), 1, "Discriminated union is not disjointed");
assert!(
var.fields[0].rust_name.is_empty(),
"Discriminated union is not disjointed"
);
writeln!(
f,
" pub fn {}(&self) -> Option<&{}> {{",
var.rust_name.remove_empty().to_case(Case::Snake),
var.fields[0].typ
)?;
writeln!(f, " if let Self::{}(ret) = self {{", var.rust_name)?;
writeln!(f, " Some(ret)",)?;
writeln!(f, " }} else {{ None }}",)?;
writeln!(f, " }}\n")?;
}
} else {
let var = &self.0.variants[0];
assert_eq!(var.fields.len(), 1, "Discriminated union is not disjointed");
assert!(
var.fields[0].rust_name.is_empty(),
"Discriminated union is not disjointed"
);
writeln!(
f,
" pub fn into_inner(self) -> Arc<{}> {{",
var.fields[0].typ
)?;
writeln!(f, " match self {{")?;
writeln!(f, " Self::{}(inner) => inner, ", var.rust_name)?;
writeln!(f, " }}",)?;
writeln!(f, " }}\n")?;
}
writeln!(f, "}}")
}
}
#[derive(Default)]
struct Parser {
current_doc_section: Option<DocSection>,
}
impl Parser {
pub fn parse_block(&mut self, block: &str) -> Result<CommandResponse, String> {
self.parser(block.lines().map(str::trim))
.map_err(|e| format!("{e} in block\n```\n{block}\n```"))
}
fn parser<'a>(
&mut self,
mut lines: impl Iterator<Item = &'a str>,
) -> Result<CommandResponse, String> {
const DOC_SECTION_PAT: &str = parse_utils::H2;
const TYPENAME_PAT: &str = parse_utils::H3;
const TYPEKINDS_PAT: &str = parse_utils::BOLD;
let mut next =
parse_utils::skip_empty(&mut lines).ok_or_else(|| "Got an empty block".to_owned())?;
let mut command_docs: Vec<String> = Vec::new();
let (typename, mut typekind) = loop {
if let Some(section_name) = next.strip_prefix(DOC_SECTION_PAT) {
let mut doc_section = DocSection::new(section_name.to_owned());
next = parse_utils::parse_doc_lines(&mut lines, &mut doc_section.contents, |s| {
s.starts_with(TYPENAME_PAT)
})
.ok_or_else(|| format!("Failed to find a typename by pattern {TYPENAME_PAT:?} after the doc section"))?;
self.current_doc_section.replace(doc_section);
} else if let Some(name) = next.strip_prefix(TYPENAME_PAT) {
next = parse_utils::parse_doc_lines(&mut lines, &mut command_docs, |s| {
s.starts_with(TYPEKINDS_PAT)
})
.map(|s| s.strip_prefix(TYPEKINDS_PAT).unwrap())
.ok_or_else(|| format!("Failed to find a typekind by pattern {TYPEKINDS_PAT:?} after the inner docs "))?;
break (name, next);
}
};
let command_name = typename.to_case(Case::Pascal);
let mut command = RecordType::new(command_name.clone(), vec![]);
loop {
if typekind.starts_with("Parameters") {
typekind = parse_utils::parse_record_fields(
&mut lines,
&mut command.fields,
|s| s.starts_with(TYPEKINDS_PAT),
)?
.map(|s| s.strip_prefix(TYPEKINDS_PAT).unwrap())
.ok_or_else(|| format!(
"Failed to find a command syntax after parameters by pattern {TYPENAME_PAT:?}"
))?;
} else if typekind.starts_with("Syntax") {
parse_utils::parse_syntax(&mut lines, &mut command.syntax)?;
break;
}
}
let mut response_variants: Vec<DiscriminatedUnionVariant> = Vec::with_capacity(4);
parse_utils::skip_while(&mut lines, |s| !s.starts_with("**Response")).ok_or_else(|| {
"Failed to find responses section by pattern \"**Response\"".to_owned()
})?;
let mut variant_docline = Vec::new();
while let Some(docline) = parse_utils::skip_empty(&mut lines) {
if docline.starts_with(TYPEKINDS_PAT) {
break;
} else {
variant_docline.push(docline.to_owned());
}
let (mut variant, next) = parse_utils::parse_discriminated_union_variant(&mut lines)?;
assert!(next.map(|s| s.is_empty()).unwrap_or(true));
variant.doc_comments = std::mem::take(&mut variant_docline);
response_variants.push(variant);
}
let response =
DiscriminatedUnionType::new(format!("{command_name}Response"), response_variants);
if let Some(ref outer_docs) = self.current_doc_section {
command
.doc_comments
.push(format!("### {}", outer_docs.header.clone()));
command.doc_comments.push(String::new());
command
.doc_comments
.extend(outer_docs.contents.iter().cloned());
command.doc_comments.push(String::new());
command.doc_comments.push("----".to_owned());
command.doc_comments.push(String::new());
}
command.doc_comments.extend(command_docs);
Ok(CommandResponse { command, response })
}
}
#[derive(Default, Clone)]
struct DocSection {
header: String,
contents: Vec<String>,
}
impl DocSection {
fn new(header: String) -> Self {
Self {
header,
contents: Vec::new(),
}
}
}