From 8a7e394b274d66182e45d2ea184e5b1b18d1abc7 Mon Sep 17 00:00:00 2001 From: Federico Brancasi Date: Sun, 29 Nov 2026 12:17:00 +0100 Subject: [PATCH] Decode JSON string escapes in one pass in the debug JSON parser With `VSCODE_TEXTMATE_DEBUG` set (or with the `inspect` tool from the README, which turns debug mode on), `parseRawGrammar` reads `.json` grammars with its own `parseJSON` instead of `JSON.parse`. VS Code's built-in C# grammar then fails to load: `"begin": "\\A\\u200B"` throws `Near offset 775: invalid escape sequence`. The same happens for any JSON grammar that uses Oniguruma's `\uHHHH` escape, or that matches a literal `\u` followed by four hex digits. For example, `"\\uFEFF"` should parse to the regex `\uFEFF`, but it throws instead. The decoder in `nextJSONToken` (`src/json.ts`) runs two `replace` passes: the first turns `\uXXXX` into a character even when its backslash is the second half of an escaped `\\`, and the second pass then finds a backslash before that character and fails. For the same reason `"\u005cn"` (a backslash and `n`) is decoded twice and becomes a newline. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/json.ts | 7 ++++--- src/tests/json.test.ts | 2 ++ 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/json.ts b/src/json.ts index 44883991..4bf6a68e 100644 --- a/src/json.ts +++ b/src/json.ts @@ -397,9 +397,10 @@ function nextJSONToken(_state: JSONStreamState, _out: JSONToken): boolean { } } while (true); - _out.value = source.substring(_out.offset + 1, pos - 1).replace(/\\u([0-9A-Fa-f]{4})/g, (_, m0) => { - return (String).fromCodePoint(parseInt(m0, 16)); - }).replace(/\\(.)/g, (_, m0) => { + _out.value = source.substring(_out.offset + 1, pos - 1).replace(/\\(?:u([0-9A-Fa-f]{4})|(.))/g, (_, hex, m0) => { + if (hex) { + return (String).fromCodePoint(parseInt(hex, 16)); + } switch (m0) { case '"': return '"'; case '\\': return '\\'; diff --git a/src/tests/json.test.ts b/src/tests/json.test.ts index 8ecc1bfb..c76ef6f9 100644 --- a/src/tests/json.test.ts +++ b/src/tests/json.test.ts @@ -68,6 +68,8 @@ test('JSON Strings', function () { isValid('["string"]'); isValid('["\\"\\\\\\/\\b\\f\\n\\r\\t\\u1234\\u12AB"]'); isValid('["\\\\"]'); + isValid('["\\\\A\\\\u200B"]'); + isValid('["\\u005cn"]'); isInvalid('["'); isInvalid('["]');