diff --git a/crates/backend/src/typegen.rs b/crates/backend/src/typegen.rs index 123f6dc9..c8417a1a 100644 --- a/crates/backend/src/typegen.rs +++ b/crates/backend/src/typegen.rs @@ -51,7 +51,16 @@ fn escape_json(src: &str) -> String { use std::fmt::Write; let mut escaped = String::with_capacity(src.len()); let mut utf16_buf = [0u16; 2]; + let mut pending_backslash = false; for c in src.chars() { + if pending_backslash { + match c { + 'b' | 'f' | 'n' | 'r' | 't' | 'u' | '"' => escaped += "\\", + _ => escaped += "\\\\", + } + pending_backslash = false; + } + match c { '\x08' => escaped += "\\b", '\x0c' => escaped += "\\f", @@ -59,7 +68,10 @@ fn escape_json(src: &str) -> String { '\r' => escaped += "\\r", '\t' => escaped += "\\t", '"' => escaped += "\\\"", - '\\' => escaped += "\\", + '\\' => { + pending_backslash = true; + } + ' ' => escaped += " ", c if c.is_ascii_graphic() => escaped.push(c), c => { let encoded = c.encode_utf16(&mut utf16_buf); @@ -69,6 +81,12 @@ fn escape_json(src: &str) -> String { } } } + + // cater for trailing backslash + if pending_backslash { + escaped += "\\\\" + } + escaped } diff --git a/examples/napi/__test__/typegen.spec.ts.md b/examples/napi/__test__/typegen.spec.ts.md index d698d541..eb49d821 100644 --- a/examples/napi/__test__/typegen.spec.ts.md +++ b/examples/napi/__test__/typegen.spec.ts.md @@ -151,6 +151,11 @@ Generated by [AVA](https://avajs.dev). whoami(): string␊ /** This is static... */␊ static getDogKind(): Kind␊ + /**␊ + * Here are some characters and character sequences␊ + * that should be escaped correctly:␊ + * \\[]{}/\\:""␊ + */␊ returnOtherClass(): Dog␊ returnOtherClassWithCustomConstructor(): Bird␊ }␊ diff --git a/examples/napi/__test__/typegen.spec.ts.snap b/examples/napi/__test__/typegen.spec.ts.snap index 5fc4cad1..68d623b1 100644 Binary files a/examples/napi/__test__/typegen.spec.ts.snap and b/examples/napi/__test__/typegen.spec.ts.snap differ diff --git a/examples/napi/index.d.ts b/examples/napi/index.d.ts index 09c4b881..4883f0e7 100644 --- a/examples/napi/index.d.ts +++ b/examples/napi/index.d.ts @@ -141,6 +141,11 @@ export class Animal { whoami(): string /** This is static... */ static getDogKind(): Kind + /** + * Here are some characters and character sequences + * that should be escaped correctly: + * \[]{}/\:"" + */ returnOtherClass(): Dog returnOtherClassWithCustomConstructor(): Bird } diff --git a/examples/napi/src/class.rs b/examples/napi/src/class.rs index 554d417d..53aa221c 100644 --- a/examples/napi/src/class.rs +++ b/examples/napi/src/class.rs @@ -62,6 +62,9 @@ impl Animal { } #[napi] + /// Here are some characters and character sequences + /// that should be escaped correctly: + /// \[]{}/\:"" pub fn return_other_class(&self) -> Dog { Dog { name: "Doge".to_owned(),