From 7acbd094d498f5807662f0b4c5d9b374f8e7d90f Mon Sep 17 00:00:00 2001 From: ben Date: Sun, 29 Nov 2026 05:47:56 +1100 Subject: [PATCH] Decode malformed UTF-8 before parsing source files Fixes #65637. --- packages/typescript/test/async/api.test.ts | 47 +++++++++++++++++++ packages/typescript/test/sync/api.test.ts | 47 +++++++++++++++++++ tsc/internal/vfs/internal/internal.go | 7 +++ tsc/internal/vfs/vfstest/vfstest_test.go | 43 ++++++++++++++++- .../regexInvalidUtf8WithUnicodeFlag.js | 4 +- .../regexInvalidUtf8WithUnicodeFlag.symbols | 2 +- .../regexInvalidUtf8WithUnicodeFlag.types | 4 +- 7 files changed, 148 insertions(+), 6 deletions(-) diff --git a/packages/typescript/test/async/api.test.ts b/packages/typescript/test/async/api.test.ts index 223dbe6dc2637..3304025329758 100644 --- a/packages/typescript/test/async/api.test.ts +++ b/packages/typescript/test/async/api.test.ts @@ -1141,6 +1141,53 @@ describe("API", { concurrency }, () => { await assert.rejects(api.createSourceFileFromFile("/missing.ts"), /could not read file "\/missing\.ts"/); // @sync: assert.throws(() => api.createSourceFileFromFile("/missing.ts"), /could not read file "\/missing\.ts"/); }); + test("source files keep positions consistent with decoded UTF-8", async t => { + const directory = mkdtempSync(join(tmpdir(), "ts-source-utf8-")); + t.after(() => rmSync(directory, { recursive: true, force: true })); + await using api = new API({ cwd: directory }); + const comments = [ + Buffer.from([0xE7, 0xB9, 0x20, 0xF3, 0xB5]), + Buffer.from([0xF0, 0x90, 0x80, 0xFF, 0x80]), + Buffer.from([0xED, 0xA0, 0x80]), + Buffer.from("ASCII é 日本語 😀 \uFFFD"), + ]; + for (const [index, comment] of comments.entries()) { + const fileName = join(directory, `input${index}.ts`); + const bytes = Buffer.concat([Buffer.from("// "), comment, Buffer.from("\nconst value = 1 + 2;\n")]); + writeFileSync(fileName, bytes); + await using program = await api.createProgram([fileName], { noLib: true, noResolve: true }); + const fromProgram = await program.getSourceFile(fileName); + assert.ok(fromProgram); + await using retained = await api.createSourceFileFromFile(fileName); + const text = bytes.toString("utf8"); + for (const sourceFile of [fromProgram, retained.sourceFile]) { + assert.equal(sourceFile.text, text); + const statement = cast(sourceFile.statements[0], isVariableStatement); + const expression = cast(statement.declarationList.declarations[0].initializer, isBinaryExpression); + assert.equal(expression.operatorToken.getStart(), text.indexOf("+")); + assert.equal(expression.operatorToken.end, text.indexOf("+") + 1); + assert.equal(expression.operatorToken.getText(), "+"); + assert.equal(expression.right.getText(), "2"); + assert.equal(sourceFile.end, text.length); + } + } + }); + + test("source text and filesystem callbacks preserve escaped lone surrogates", async () => { + const text = "const value = '\\uD800 \\uDC00';"; + await using api = spawnAPI({ "/input.ts": text }); + await using fromText = await api.createSourceFile("/input.ts", text); + await using fromFile = await api.createSourceFileFromFile("/input.ts"); + for (const sourceFile of [fromText.sourceFile, fromFile.sourceFile]) { + assert.equal(sourceFile.text, text); + assert.equal(sourceFile.end, text.length); + const statement = cast(sourceFile.statements[0], isVariableStatement); + const literal = cast(statement.declarationList.declarations[0].initializer, isStringLiteral); + assert.equal(literal.text, "\uD800 \uDC00"); + assert.equal(literal.getText(), "'\\uD800 \\uDC00'"); + } + }); + test("createProgram", async () => { await using api = spawnAPI({ "/src/index.ts": `export const value: string = 1;`, diff --git a/packages/typescript/test/sync/api.test.ts b/packages/typescript/test/sync/api.test.ts index cdc3075d129f8..0ebd0ab6087cc 100644 --- a/packages/typescript/test/sync/api.test.ts +++ b/packages/typescript/test/sync/api.test.ts @@ -1128,6 +1128,53 @@ describe("API", { concurrency }, () => { assert.throws(() => api.createSourceFileFromFile("/missing.ts"), /could not read file "\/missing\.ts"/); }); + test("source files keep positions consistent with decoded UTF-8", t => { + const directory = mkdtempSync(join(tmpdir(), "ts-source-utf8-")); + t.after(() => rmSync(directory, { recursive: true, force: true })); + using api = new API({ cwd: directory }); + const comments = [ + Buffer.from([0xE7, 0xB9, 0x20, 0xF3, 0xB5]), + Buffer.from([0xF0, 0x90, 0x80, 0xFF, 0x80]), + Buffer.from([0xED, 0xA0, 0x80]), + Buffer.from("ASCII é 日本語 😀 \uFFFD"), + ]; + for (const [index, comment] of comments.entries()) { + const fileName = join(directory, `input${index}.ts`); + const bytes = Buffer.concat([Buffer.from("// "), comment, Buffer.from("\nconst value = 1 + 2;\n")]); + writeFileSync(fileName, bytes); + using program = api.createProgram([fileName], { noLib: true, noResolve: true }); + const fromProgram = program.getSourceFile(fileName); + assert.ok(fromProgram); + using retained = api.createSourceFileFromFile(fileName); + const text = bytes.toString("utf8"); + for (const sourceFile of [fromProgram, retained.sourceFile]) { + assert.equal(sourceFile.text, text); + const statement = cast(sourceFile.statements[0], isVariableStatement); + const expression = cast(statement.declarationList.declarations[0].initializer, isBinaryExpression); + assert.equal(expression.operatorToken.getStart(), text.indexOf("+")); + assert.equal(expression.operatorToken.end, text.indexOf("+") + 1); + assert.equal(expression.operatorToken.getText(), "+"); + assert.equal(expression.right.getText(), "2"); + assert.equal(sourceFile.end, text.length); + } + } + }); + + test("source text and filesystem callbacks preserve escaped lone surrogates", () => { + const text = "const value = '\\uD800 \\uDC00';"; + using api = spawnAPI({ "/input.ts": text }); + using fromText = api.createSourceFile("/input.ts", text); + using fromFile = api.createSourceFileFromFile("/input.ts"); + for (const sourceFile of [fromText.sourceFile, fromFile.sourceFile]) { + assert.equal(sourceFile.text, text); + assert.equal(sourceFile.end, text.length); + const statement = cast(sourceFile.statements[0], isVariableStatement); + const literal = cast(statement.declarationList.declarations[0].initializer, isStringLiteral); + assert.equal(literal.text, "\uD800 \uDC00"); + assert.equal(literal.getText(), "'\\uD800 \\uDC00'"); + } + }); + test("createProgram", () => { using api = spawnAPI({ "/src/index.ts": `export const value: string = 1;`, diff --git a/tsc/internal/vfs/internal/internal.go b/tsc/internal/vfs/internal/internal.go index d8465cf9a9cdd..55fbc0a0b1a4e 100644 --- a/tsc/internal/vfs/internal/internal.go +++ b/tsc/internal/vfs/internal/internal.go @@ -6,10 +6,12 @@ import ( "io/fs" "strings" "unicode/utf16" + "unicode/utf8" "unsafe" "github.com/microsoft/TypeScript/tsc/internal/tspath" "github.com/microsoft/TypeScript/tsc/internal/vfs" + "golang.org/x/text/encoding/unicode" ) type Common struct { @@ -170,6 +172,11 @@ func decodeBytes(s string) (contents string, ok bool) { if len(s) >= 3 && s[0] == 0xEF && s[1] == 0xBB && s[2] == 0xBF { s = s[3:] } + if !utf8.ValidString(s) { + // Use the same replacement semantics as JavaScript's UTF-8 decoder. + contents, err := unicode.UTF8.NewDecoder().String(s) + return contents, err == nil + } return s, true } diff --git a/tsc/internal/vfs/vfstest/vfstest_test.go b/tsc/internal/vfs/vfstest/vfstest_test.go index 815cbd4da6658..f4e3481f38273 100644 --- a/tsc/internal/vfs/vfstest/vfstest_test.go +++ b/tsc/internal/vfs/vfstest/vfstest_test.go @@ -478,10 +478,51 @@ func TestVFSTestMapFSWindows(t *testing.T) { }) } +func TestReadFileUTF8(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + input string + expected string + }{ + {"empty", "", ""}, + {"ASCII", "hello, world", "hello, world"}, + {"Unicode", "é 日本語 😀 \uFFFD", "é 日本語 😀 \uFFFD"}, + {"truncated two-byte sequence", "\xC2", "\uFFFD"}, + {"truncated three-byte sequence", "\xE7\xB9", "\uFFFD"}, + {"truncated four-byte sequence", "\xF0\x90\x80", "\uFFFD"}, + {"invalid second byte", "\xC2+", "\uFFFD+"}, + {"invalid third byte", "\xE7\xB9+", "\uFFFD+"}, + {"invalid fourth byte", "\xF0\x90\x80+", "\uFFFD+"}, + {"invalid lead bytes", "a\xFF\xFE", "a\uFFFD\uFFFD"}, + {"isolated continuation bytes", "\x80\xBF", "\uFFFD\uFFFD"}, + {"overlong sequence", "\xE0\x80\x80", "\uFFFD\uFFFD\uFFFD"}, + {"surrogate", "\xED\xA0\x80", "\uFFFD\uFFFD\uFFFD"}, + {"above Unicode maximum", "\xF4\x90\x80\x80", "\uFFFD\uFFFD\uFFFD\uFFFD"}, + {"adjacent errors", "\xE7\xB9\xF3\xB5", "\uFFFD\uFFFD"}, + {"comment", "// \xE7\xB9 \xF3\xB5\nconst value = 1 + 2;", "// \uFFFD \uFFFD\nconst value = 1 + 2;"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + fs := FromMap(map[string]string{ + "/input.ts": tt.input, + "/with-bom.ts": "\uFEFF" + tt.input, + }, tspath.CaseSensitive) + for _, path := range []tspath.RootedFilePath{"/input.ts", "/with-bom.ts"} { + content, ok := fs.ReadFile(path) + assert.Assert(t, ok) + assert.Equal(t, content, tt.expected) + } + }) + } +} + func TestBOM(t *testing.T) { t.Parallel() - const expected = "hello, world" + const expected = "hello, world é 日本語 😀" tests := []struct { name string diff --git a/tsc/testdata/baselines/reference/compiler/regexInvalidUtf8WithUnicodeFlag.js b/tsc/testdata/baselines/reference/compiler/regexInvalidUtf8WithUnicodeFlag.js index 7f5163bd992e9..f11025a59a7b4 100644 --- a/tsc/testdata/baselines/reference/compiler/regexInvalidUtf8WithUnicodeFlag.js +++ b/tsc/testdata/baselines/reference/compiler/regexInvalidUtf8WithUnicodeFlag.js @@ -1,9 +1,9 @@ //// [tests/cases/compiler/regexInvalidUtf8WithUnicodeFlag.ts] //// //// [regexInvalidUtf8WithUnicodeFlag.ts] -/€/u +/�/u //// [regexInvalidUtf8WithUnicodeFlag.js] "use strict"; -/€/u; +/�/u; diff --git a/tsc/testdata/baselines/reference/compiler/regexInvalidUtf8WithUnicodeFlag.symbols b/tsc/testdata/baselines/reference/compiler/regexInvalidUtf8WithUnicodeFlag.symbols index 7852089941fa0..14650672def5d 100644 --- a/tsc/testdata/baselines/reference/compiler/regexInvalidUtf8WithUnicodeFlag.symbols +++ b/tsc/testdata/baselines/reference/compiler/regexInvalidUtf8WithUnicodeFlag.symbols @@ -2,5 +2,5 @@ === regexInvalidUtf8WithUnicodeFlag.ts === -/€/u +/�/u diff --git a/tsc/testdata/baselines/reference/compiler/regexInvalidUtf8WithUnicodeFlag.types b/tsc/testdata/baselines/reference/compiler/regexInvalidUtf8WithUnicodeFlag.types index d836c760f4eba..254d5447544a4 100644 --- a/tsc/testdata/baselines/reference/compiler/regexInvalidUtf8WithUnicodeFlag.types +++ b/tsc/testdata/baselines/reference/compiler/regexInvalidUtf8WithUnicodeFlag.types @@ -1,6 +1,6 @@ //// [tests/cases/compiler/regexInvalidUtf8WithUnicodeFlag.ts] //// === regexInvalidUtf8WithUnicodeFlag.ts === -/€/u ->/€/u : RegExp +/�/u +>/�/u : RegExp