From 59a214dea40e4adbf98864aebfb6aeb0332a7b0b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=B6ren?= Date: Mon, 14 Aug 2023 13:54:17 +0200 Subject: [PATCH] Clean up, reduce repetition when writing comments --- tsify-macros/src/comments.rs | 11 +++++++++-- tsify-macros/src/decl.rs | 15 +++------------ tsify-macros/src/typescript.rs | 4 +--- 3 files changed, 13 insertions(+), 17 deletions(-) diff --git a/tsify-macros/src/comments.rs b/tsify-macros/src/comments.rs index e9aede3..498e1e8 100644 --- a/tsify-macros/src/comments.rs +++ b/tsify-macros/src/comments.rs @@ -48,14 +48,21 @@ pub fn extract_doc_comments(attrs: &[syn::Attribute]) -> Vec { }) } -pub fn format_doc_comments(comments: &Vec) -> String { +pub fn format_doc_comments( + f: &mut std::fmt::Formatter<'_>, + comments: &Vec, +) -> Result<(), std::fmt::Error> { + if comments.is_empty() { + return Ok(()); + } + let comment = comments .iter() .map(|line| format!(" *{}\n", line.trim_matches('"'))) .collect::>() .join(""); - format!("/**\n{} */\n", comment) + write!(f, "{}", format!("/**\n{} */\n", comment)) } pub fn clean_comments(typ: &mut TsType) -> () { diff --git a/tsify-macros/src/decl.rs b/tsify-macros/src/decl.rs index 5984585..65aa74f 100644 --- a/tsify-macros/src/decl.rs +++ b/tsify-macros/src/decl.rs @@ -36,9 +36,7 @@ impl Display for TsTypeAliasDecl { format!("{}<{}>", self.id, type_params) }; - if !self.comments.is_empty() { - write!(f, "{}", format_doc_comments(&self.comments))?; - } + format_doc_comments(f, &self.comments)?; if self.export { write!(f, "export ")?; @@ -57,9 +55,7 @@ pub struct TsInterfaceDecl { impl Display for TsInterfaceDecl { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - if !self.comments.is_empty() { - write!(f, "{}", format_doc_comments(&self.comments))?; - } + format_doc_comments(f, &self.comments)?; write!(f, "export interface {}", self.id)?; @@ -226,9 +222,7 @@ impl Display for TsEnumDecl { writeln!(f, "{}", type_ref)?; } - if !self.comments.is_empty() { - write!(f, "{}", format_doc_comments(&self.comments))?; - } + format_doc_comments(f, &self.comments)?; write!(f, "declare namespace {}", self.id)?; @@ -267,9 +261,6 @@ impl Display for TsEnumDecl { self.members .iter() .map(|member| { - // let mut type_refs = Vec::new(); - // TsEnumDecl::replace_type_params(member.type_ann.clone(), &mut type_refs) - let mut clone = member.type_ann.clone(); clean_comments(&mut clone); clone diff --git a/tsify-macros/src/typescript.rs b/tsify-macros/src/typescript.rs index 5518b0a..b22402a 100644 --- a/tsify-macros/src/typescript.rs +++ b/tsify-macros/src/typescript.rs @@ -606,9 +606,7 @@ impl Display for TsTypeElement { let optional_ann = if self.optional { "?" } else { "" }; - if !self.comments.is_empty() { - write!(f, "{}", format_doc_comments(&self.comments))?; - } + format_doc_comments(f, &self.comments)?; if is_js_ident(key) { write!(f, "{key}{optional_ann}: {type_ann}")