From 2b694aba774d831a675a941e6567efb967d843bf Mon Sep 17 00:00:00 2001 From: Pistonight Date: Fri, 13 Oct 2023 10:40:53 -0700 Subject: [PATCH] update is_js_ident to cover most cases --- tests/rename.rs | 57 ++++++++++++++++++++++++++++++++++ tsify-macros/src/typescript.rs | 2 +- 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/tests/rename.rs b/tests/rename.rs index cb55db1..ddd27c8 100644 --- a/tests/rename.rs +++ b/tests/rename.rs @@ -119,3 +119,60 @@ fn test_rename_all() { } ); } + +#[test] +fn test_quote_non_identifiers() { + #[derive(Tsify)] + struct NonIdentifierRenameStruct { + #[serde(rename = "1")] + x: i32, + #[serde(rename = "1x")] + y: i32, + #[serde(rename = "-")] + z: i32, + #[serde(rename = " ")] + w: i32, + #[serde(rename = "#")] + q: i32, + #[serde(rename = "should_not_quote")] + p: i32, + #[serde(rename = "should$not$quote")] + r: i32, + } + + assert_eq!( + NonIdentifierRenameStruct::DECL, + indoc! {" + export interface NonIdentifierRenameStruct { + \"1\": number; + \"1x\": number; + \"-\": number; + \" \": number; + \"#\": number; + should_not_quote: number; + should$not$quote: number; + }" + } + ); + + #[derive(Tsify)] + enum NonIdentifierRenameEnum { + #[serde(rename = "hello-world")] + A(bool), + #[serde(rename = "hel#&*world")] + B(i64), + #[serde(rename = "hello world")] + C(String), + #[serde(rename = "")] + D(i32), + #[serde(rename = "should_not_quote")] + E(String), + } + + let expected = indoc! {r#" + export type NonIdentifierRenameEnum = { "hello-world": boolean } | { "hel#&*world": number } | { "hello world": string } | { "": number } | { should_not_quote: string };"# + + }; + + assert_eq!(NonIdentifierRenameEnum::DECL, expected); +} \ No newline at end of file diff --git a/tsify-macros/src/typescript.rs b/tsify-macros/src/typescript.rs index 25fd6ae..00183ef 100644 --- a/tsify-macros/src/typescript.rs +++ b/tsify-macros/src/typescript.rs @@ -575,7 +575,7 @@ fn parse_len(expr: &syn::Expr) -> Option { } fn is_js_ident(string: &str) -> bool { - !string.contains('-') + !string.is_empty() && !string.starts_with(|c: char| c.is_ascii_digit()) && !string.contains(|c: char| !c.is_ascii_alphanumeric() && c != '_' && c != '$') } impl Display for TsTypeElement {