Skip to content
Open
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
47 changes: 47 additions & 0 deletions packages/typescript/test/async/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;`,
Expand Down
47 changes: 47 additions & 0 deletions packages/typescript/test/sync/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;`,
Expand Down
7 changes: 7 additions & 0 deletions tsc/internal/vfs/internal/internal.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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
}
Expand Down
43 changes: 42 additions & 1 deletion tsc/internal/vfs/vfstest/vfstest_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
//// [tests/cases/compiler/regexInvalidUtf8WithUnicodeFlag.ts] ////

//// [regexInvalidUtf8WithUnicodeFlag.ts]
/�/u
/�/u


//// [regexInvalidUtf8WithUnicodeFlag.js]
"use strict";
/�/u;
/�/u;
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@

=== regexInvalidUtf8WithUnicodeFlag.ts ===

/�/u
/�/u

Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//// [tests/cases/compiler/regexInvalidUtf8WithUnicodeFlag.ts] ////

=== regexInvalidUtf8WithUnicodeFlag.ts ===
/�/u
>/�/u : RegExp
/�/u
>/�/u : RegExp