Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 11 additions & 14 deletions src/goTranspiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,22 +170,19 @@ export class GoTranspiler extends BaseTranspiler {
return this.StringLiteralReplacements[text];
}
// skip the replaceAll passes when there is nothing to escape
if (/['"\n]/.test(text)) {
text = text.replaceAll("'", "\\\\" + "'");
text = text.replaceAll("\"", "\\" + "\"");
// note: single quotes must NOT be escaped — \' is an invalid escape in Go string literals
if (/[\\"\b\f\n\r\t]/.test(text)) {
// Preserve real backslashes
const backslashPlaceholder = "\x00";
text = text.replaceAll("\\", backslashPlaceholder);
text = text.replaceAll("\b", "\\b");
text = text.replaceAll("\f", "\\f");
text = text.replaceAll("\n", "\\n");
text = text.replaceAll("\r", "\\r");
text = text.replaceAll("\t", "\\t");
text = text.replaceAll(backslashPlaceholder, "\\\\");
text = text.replaceAll("\"", "\\\"");
}
// Preserve real backslashes
const backslashPlaceholder = "\x00";
text = text.replaceAll("\\", backslashPlaceholder);
text = text.replaceAll("\b", "\\b");
text = text.replaceAll("\f", "\\f");
text = text.replaceAll("\n", "\\n");
text = text.replaceAll("\r", "\\r");
text = text.replaceAll("\t", "\\t");
text = text.replaceAll(backslashPlaceholder, "\\\\");
text = text.replaceAll("'", "\\'");
text = text.replaceAll("\"", "\\\"");
return token + text + token;
}

Expand Down
6 changes: 6 additions & 0 deletions tests/goTranspiler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@ describe('go transpiling tests', () => {
const output = transpiler.transpileGo(ts).content;
expect(output).toBe(go);
});
test('string literal escaping', () => {
const ts = 'const x = "foo, \'single\', \\"double\\" \\t \\n \\r \\b \\f \\\\ ";'
const go = 'var x any = "foo, \'single\', \\"double\\" \\t \\n \\r \\b \\f \\\\ "'
const output = transpiler.transpileGo(ts).content;
expect(output).toBe(go);
});
test('basic while loop', () => {
const ts =
"while (true) {\n" +
Expand Down
Loading