From 0480dcb9646b0199a1c657d40984e91b26d4eb80 Mon Sep 17 00:00:00 2001 From: xazukx <> Date: Sat, 30 Aug 2025 18:55:51 -0600 Subject: [PATCH] Allow array outputs for constants. --- example/src/lib.rs | 9 +++++++++ macros/src/attr/constant.rs | 3 +++ macros/src/types/constant.rs | 10 +++++++--- 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/example/src/lib.rs b/example/src/lib.rs index ac63ae9..acae346 100644 --- a/example/src/lib.rs +++ b/example/src/lib.rs @@ -130,9 +130,18 @@ pub const IS_ADMIN: bool = true; pub struct ItemId(tiny_text::TinyText); +pub struct ItemBytes(tiny_text::TinyBytes); + mod tiny_text { pub struct TinyText(pub &'static str); + pub struct TinyBytes(pub &'static [u8]); } #[ts_constant(export_to = "constants.ts")] pub const ITEM_ID: ItemId = ItemId(tiny_text::TinyText("item_id")); + +#[ts_constant(export_to = "constants.ts", array)] +pub const ITEM_BYTES: ItemBytes = ItemBytes(tiny_text::TinyBytes(b"item_bytes")); + +#[ts_constant(export_to = "constants.ts", array)] +pub const ITEM_SCOPE: tiny_text::TinyBytes = tiny_text::TinyBytes(b"item_bytes"); diff --git a/macros/src/attr/constant.rs b/macros/src/attr/constant.rs index 14e5981..049fd79 100644 --- a/macros/src/attr/constant.rs +++ b/macros/src/attr/constant.rs @@ -8,6 +8,7 @@ pub struct ConstantAttr { pub export_to: Option, pub docs: Vec, pub rename: Option, + pub array: bool, } impl Attr for ConstantAttr { @@ -19,6 +20,7 @@ impl Attr for ConstantAttr { export_to: self.export_to.or(other.export_to), docs: other.docs, rename: self.rename.or(other.rename), + array: self.array || other.array, } } @@ -40,5 +42,6 @@ impl_parse! { "crate" => out.crate_rename = Some(parse_assign_from_str(input)?), "export_to" => out.export_to = Some(parse_assign_expr(input)?), "rename" => out.rename = Some(parse_assign_expr(input)?), + "array" => out.array = true, } } diff --git a/macros/src/types/constant.rs b/macros/src/types/constant.rs index 94d00f9..5c98127 100644 --- a/macros/src/types/constant.rs +++ b/macros/src/types/constant.rs @@ -15,7 +15,7 @@ fn type_def(attr: &ConstantAttr, ts_name: Expr, value: &Expr) -> Result Result Result { +fn extract_expr_literal(value: &Expr, attr: &ConstantAttr) -> Result { let text: String = match value { Expr::Lit(lit) => match &lit.lit { Lit::Float(float) => float.base10_digits().to_string(), Lit::Int(int) => int.base10_digits().to_string(), Lit::Str(str) => to_typescript_syntax(str.value()), Lit::ByteStr(str) => { + if attr.array { + let arr = str.value(); + return Ok(format!("{:?}", arr)); + } let token = str.token().to_string(); let quote_index = token.find('"').unwrap(); let last_quote_index = token.rfind('"').unwrap(); @@ -51,7 +55,7 @@ fn extract_expr_literal(value: &Expr) -> Result { }, Expr::Call(call) => { for arg in &call.args { - match extract_expr_literal(arg) { + match extract_expr_literal(arg, attr) { Ok(text) => return Ok(text), _ => {}, }