mirror of
https://github.com/vercel-labs/scriptc.git
synced 2026-10-27 06:43:19 +08:00
Merge main
This commit is contained in:
@@ -135,6 +135,9 @@ With `--sparse`, the profile leaves out the functions the runs never reached. Th
|
||||
<dt><code>--detached-exit</code></dt>
|
||||
<dd>On Linux, when the program calls <code>process.exit()</code>, hand the release of its memory to a helper process so the parent sees the exit sooner. The kernel otherwise frees the whole address space before the exit is reported, which takes tens of milliseconds per gigabyte. Opt in only where the trade-offs are acceptable: for up to about 100 ms after the exit, the helper keeps the executable mapped (overwriting the binary in place fails with "text file busy"), its memory stays charged to the cgroup, and the teardown CPU time no longer appears in the parent's resource usage. Valid only for executable builds; it has no effect on other platforms.</dd>
|
||||
|
||||
<dt><code>--target-cpu <baseline|x86-64-v2|x86-64-v3|x86-64-v4|native></code></dt>
|
||||
<dd>On x86-64 targets, compile the program's code for an x86-64 microarchitecture level. The default, <code>baseline</code>, runs on any x86-64 CPU. A higher level lets LLVM use more instructions, and the executable then runs only on CPUs that support that level. <code>native</code> uses the highest level the build machine supports. Valid for executable, assembly, and object output on x86-64 targets. See <a href="#target-cpu">Target CPU</a>.</dd>
|
||||
|
||||
<dt><code>--profile-generate <pattern></code></dt>
|
||||
<dd>On Linux, build an instrumented executable for profile-guided optimization. Each run writes a raw profile to the path pattern, where <code>%p</code> expands to the process ID; the <code>LLVM_PROFILE_FILE</code> environment variable overrides the pattern at run time. A relative pattern resolves from the current working directory. Instrumented programs run slower. Valid only for executable builds with <code>--optimization=release</code> or <code>speed</code>.</dd>
|
||||
|
||||
@@ -228,6 +231,43 @@ $ scriptc build app.ts --optimization=speed --profile-use app.profdata
|
||||
|
||||
Train on workloads like the ones the program will run: code the training never reached is optimized as without a profile. The profile can be committed and reused as the program changes. Functions whose control flow changed since the profile was collected lose their profile, and the rest keep theirs, so regenerate it when much of the program has changed. [Build parallelism](/docs/how-it-works#build-parallelism) describes what a profile adds to build time.
|
||||
|
||||
## Target CPU
|
||||
|
||||
By default, x86-64 executables run on any x86-64 CPU, so the compiler uses only the baseline instruction set (SSE2). `--target-cpu` compiles the program's code for a higher x86-64 microarchitecture level. Each level includes the ones below it:
|
||||
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Level</th>
|
||||
<th>Adds</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><code>x86-64-v2</code></td>
|
||||
<td>SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>x86-64-v3</code></td>
|
||||
<td>AVX, AVX2, BMI1, BMI2, F16C, FMA, LZCNT, MOVBE</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>x86-64-v4</code></td>
|
||||
<td>AVX-512 (F, BW, CD, DQ, VL)</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
```console
|
||||
$ scriptc build app.ts --target-cpu=x86-64-v3 -o app
|
||||
```
|
||||
|
||||
Loops over typed arrays and numbers gain the most, because LLVM vectorizes them with wider registers. Some loops run slower at a higher level, so measure the program on the machines it will run on.
|
||||
|
||||
An executable built for a level runs only on CPUs that support that level. On an older CPU, it crashes with an illegal-instruction signal (`SIGILL`) when it reaches an instruction the CPU lacks. A named level is portable to every machine of that level. `native` selects the highest level the build machine supports, so use it only for executables that run on the machine that built them or on identical machines.
|
||||
|
||||
The level applies to the program's own code. The runtime pack keeps its baseline code. Builds for different levels never share cached artifacts, and `baseline` builds are the same as builds without the option.
|
||||
|
||||
## LLVM backend
|
||||
|
||||
scriptc generates LLVM IR and compiles it to native code. Executable builds link the result with the matching precompiled runtime pack. Use <code>--emit=llvm</code> to inspect the generated code.
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
- **Filesystem URL paths:** Synchronous `fs` functions accept `file:` URL paths and convert them as `fileURLToPath` does.
|
||||
`existsSync` and the `fs.promises` functions refuse URL paths; pass `fileURLToPath(url)` instead.
|
||||
A URL path after a string path, or with options that are not literals, is refused, because Node checks those arguments before it converts the URL.
|
||||
- **Filesystem URL paths:** `fs` and `fs.promises` functions accept `file:` URL paths and convert them as `fileURLToPath` does; `existsSync` answers `false` and the `fs.promises` functions reject for a URL that does not convert.
|
||||
A URL path with options that are not literals is refused where Node checks those options before it converts the URL, except a `readFileSync` encoding.
|
||||
`fs.promises` functions also refuse a string path before a URL path; pass `fileURLToPath(url)` instead.
|
||||
|
||||
@@ -15,3 +15,6 @@ JavaScript argument and return conversions preserve native array references; oth
|
||||
|
||||
Supported operations on `unknown` include truthiness, `typeof` narrowing, property access, `+`, `switch`, and `throw`.
|
||||
Cast before using other operations.
|
||||
|
||||
In JavaScript, a call whose untyped argument could select an overload with another result type returns a checked value, whichever overload the type checker picks, and so do the unannotated bindings and functions that hold or return it.
|
||||
In TypeScript, an `any` argument keeps the overload the type checker picks, and a value that selects another overload at runtime throws a `TypeError` where the result is used.
|
||||
|
||||
@@ -70,6 +70,8 @@ async function tryFastPath(): Promise<number | null> {
|
||||
values["profile-generate"] !== undefined ||
|
||||
values["profile-use"] !== undefined ||
|
||||
values.sparse ||
|
||||
// The full compiler resolves `native` against the build host.
|
||||
values["target-cpu"] !== undefined ||
|
||||
(values["external-types"] ?? []).length > 0
|
||||
)
|
||||
return null;
|
||||
@@ -200,6 +202,7 @@ async function coverageFastPath(
|
||||
values.emit !== undefined ||
|
||||
values.strip ||
|
||||
values["detached-exit"] ||
|
||||
values["target-cpu"] !== undefined ||
|
||||
values.lib ||
|
||||
values.profile !== undefined ||
|
||||
values.ffi !== undefined ||
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { createRequire } from "node:module";
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
import { expect, test } from "vitest";
|
||||
import { hostTargetCpu } from "../../compiler/src/backend/target-cpu.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const require = createRequire(import.meta.url);
|
||||
const repoRoot = join(import.meta.dirname, "../../..");
|
||||
const cliEntry = join(repoRoot, "packages/cli/src/main.ts");
|
||||
const bootstrapEntry = join(repoRoot, "packages/cli/dist/bootstrap.js");
|
||||
const tsxLoader = join(dirname(require.resolve("tsx/package.json")), "dist/loader.mjs");
|
||||
const host = hostTargetCpu();
|
||||
const runsV3 = host === "x86-64-v3" || host === "x86-64-v4";
|
||||
|
||||
const program = `const a = new Int32Array(4096);
|
||||
for (let i = 0; i < a.length; i++) a[i] = (i * 2654435761) | 0;
|
||||
let s = 0;
|
||||
for (let r = 0; r < 64; r++) for (let i = 0; i < a.length; i++) s = (s + a[i]!) | 0;
|
||||
console.log(s);
|
||||
`;
|
||||
|
||||
test.runIf(process.platform === "linux" && process.arch === "x64")(
|
||||
"--target-cpu compiles the program for the level without mixing cache variants",
|
||||
async () => {
|
||||
const dir = await mkdtemp(join("/tmp", "scriptc-target-cpu-"));
|
||||
const entry = join(dir, "main.ts");
|
||||
const outPath = join(dir, "program");
|
||||
const llvmPath = join(dir, "main.ll");
|
||||
const env = { ...process.env, SCRIPTC_CACHE_DIR: join(dir, "cache") };
|
||||
const build = async (args: string[], bootstrap = false): Promise<string> => {
|
||||
await execFileAsync(
|
||||
process.execPath,
|
||||
[
|
||||
...(bootstrap ? [bootstrapEntry] : ["--import", tsxLoader, cliEntry]),
|
||||
"build",
|
||||
entry,
|
||||
"-o",
|
||||
outPath,
|
||||
...args,
|
||||
],
|
||||
{ env, maxBuffer: 4 * 1024 * 1024 },
|
||||
);
|
||||
return readFile(llvmPath, "utf8");
|
||||
};
|
||||
try {
|
||||
await writeFile(entry, program);
|
||||
const expected = `${(await execFileAsync(process.execPath, [entry])).stdout}`;
|
||||
const baseline = await build([]);
|
||||
expect(baseline).not.toContain('"target-cpu"');
|
||||
expect(await build(["--target-cpu=baseline"])).toBe(baseline);
|
||||
const v3 = await build(["--target-cpu=x86-64-v3"]);
|
||||
expect(v3).toMatch(/^attributes #0 = \{ sanitize_address "target-cpu"="x86-64-v3" \}$/m);
|
||||
if (runsV3) expect((await execFileAsync(outPath)).stdout).toBe(expected);
|
||||
// The bootstrap's cached route builds without a level.
|
||||
expect(await build([], true)).toBe(baseline);
|
||||
expect((await execFileAsync(outPath)).stdout).toBe(expected);
|
||||
await expect(build(["--target-cpu=haswell"])).rejects.toThrow(/unknown target CPU "haswell"/);
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
240_000,
|
||||
);
|
||||
|
||||
test("--target-cpu levels are refused for arm64 and WASI targets", async () => {
|
||||
const dir = await mkdtemp(join("/tmp", "scriptc-target-cpu-refusal-"));
|
||||
const entry = join(dir, "main.ts");
|
||||
try {
|
||||
await writeFile(entry, program);
|
||||
for (const target of ["aarch64-unknown-linux-gnu", "wasm32-wasi"]) {
|
||||
for (const kind of ["llvm", "asm", "obj", "exe"]) {
|
||||
const build = execFileAsync(
|
||||
process.execPath,
|
||||
[
|
||||
"--import",
|
||||
tsxLoader,
|
||||
cliEntry,
|
||||
"build",
|
||||
entry,
|
||||
`--emit=${kind}`,
|
||||
"-o",
|
||||
join(dir, `out-${kind}`),
|
||||
"--target-cpu=x86-64-v3",
|
||||
],
|
||||
{
|
||||
env: { ...process.env, SCRIPTC_TARGET: target, SCRIPTC_CACHE_DIR: join(dir, "cache") },
|
||||
},
|
||||
);
|
||||
await expect(build, `${target} ${kind}`).rejects.toThrow(
|
||||
/--target-cpu=x86-64-v3 requires an x86-64 target/,
|
||||
);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
}, 240_000);
|
||||
+31
-27
@@ -1590,7 +1590,7 @@ declare module "node:fs" {
|
||||
export function writeFileSync(path: string | URL, data: string, encoding: "utf8" | "utf-8"): void;
|
||||
export function writeFileSync(path: string | URL, data: string | Uint8Array): void;
|
||||
export function appendFileSync(path: string | URL, data: string | Uint8Array): void;
|
||||
export function existsSync(path: string): boolean;
|
||||
export function existsSync(path: string | URL): boolean;
|
||||
export function mkdirSync(path: string | URL): void;
|
||||
export function mkdirSync(
|
||||
path: string | URL,
|
||||
@@ -2231,7 +2231,7 @@ declare module "fs/promises" {
|
||||
stat(): Promise<import("node:fs").Stats>;
|
||||
[Symbol.asyncDispose](): Promise<void>;
|
||||
}
|
||||
export function open(path: string, flags?: string, mode?: number): Promise<FileHandle>;
|
||||
export function open(path: string | URL, flags?: string, mode?: number): Promise<FileHandle>;
|
||||
export function link(
|
||||
existingPath: string | Uint8Array | URL,
|
||||
newPath: string | Uint8Array | URL,
|
||||
@@ -2268,14 +2268,14 @@ declare module "fs/promises" {
|
||||
atime: number | string | Date,
|
||||
mtime: number | string | Date,
|
||||
): Promise<void>;
|
||||
export function readFile(path: string, encoding: "utf8" | "utf-8"): Promise<string>;
|
||||
export function readFile(path: string | URL, encoding: "utf8" | "utf-8"): Promise<string>;
|
||||
export function readFile(
|
||||
path: string,
|
||||
path: string | URL,
|
||||
options: BufferEncoding | { encoding: BufferEncoding },
|
||||
): Promise<string>;
|
||||
export function readFile(path: string): Promise<Buffer>;
|
||||
export function readFile(path: string | URL): Promise<Buffer>;
|
||||
export function writeFile(
|
||||
path: string,
|
||||
path: string | URL,
|
||||
data: string,
|
||||
options?: {
|
||||
mode?: number;
|
||||
@@ -2284,14 +2284,18 @@ declare module "fs/promises" {
|
||||
[option: string]: unknown;
|
||||
},
|
||||
): Promise<void>;
|
||||
export function writeFile(path: string, data: string, encoding: "utf8" | "utf-8"): Promise<void>;
|
||||
export function writeFile(
|
||||
path: string | URL,
|
||||
data: string,
|
||||
encoding: "utf8" | "utf-8",
|
||||
): Promise<void>;
|
||||
export function mkdir(
|
||||
path: string,
|
||||
path: string | URL,
|
||||
options?: { recursive?: boolean; mode?: number },
|
||||
): Promise<void>;
|
||||
export function readdir(path: string): Promise<string[]>;
|
||||
export function readdir(path: string | URL): Promise<string[]>;
|
||||
export function readdir(
|
||||
path: string,
|
||||
path: string | URL,
|
||||
options: {
|
||||
encoding?: "utf8" | "utf-8";
|
||||
withFileTypes: true;
|
||||
@@ -2308,12 +2312,12 @@ declare module "fs/promises" {
|
||||
pattern: string | readonly string[],
|
||||
options: import("node:fs").GlobOptionsWithFileTypes,
|
||||
): AsyncIterableIterator<import("node:fs").Dirent>;
|
||||
export function rm(path: string): Promise<void>;
|
||||
export function rm(path: string | URL): Promise<void>;
|
||||
export function rm(
|
||||
path: string,
|
||||
path: string | URL,
|
||||
options: { recursive?: boolean; force?: boolean; maxRetries?: number; retryDelay?: number },
|
||||
): Promise<void>;
|
||||
export function stat(path: string): Promise<import("node:fs").Stats>;
|
||||
export function stat(path: string | URL): Promise<import("node:fs").Stats>;
|
||||
export function statfs(
|
||||
path: string | Uint8Array | URL,
|
||||
options?: import("node:fs").StatFsOptions & { bigint?: false },
|
||||
@@ -2326,21 +2330,21 @@ declare module "fs/promises" {
|
||||
path: string | Uint8Array | URL,
|
||||
options?: import("node:fs").StatFsOptions,
|
||||
): Promise<import("node:fs").StatsFs | import("node:fs").BigIntStatsFs>;
|
||||
export function realpath(path: string): Promise<string>;
|
||||
export function lstat(path: string): Promise<import("node:fs").Stats>;
|
||||
export function unlink(path: string): Promise<void>;
|
||||
export function chmod(path: string, mode: number): Promise<void>;
|
||||
export function chown(path: string, uid: number, gid: number): Promise<void>;
|
||||
export function lchown(path: string, uid: number, gid: number): Promise<void>;
|
||||
export function access(path: string, mode?: number): Promise<void>;
|
||||
export function truncate(path: string, len?: number): Promise<void>;
|
||||
export function appendFile(path: string, data: string | Uint8Array): Promise<void>;
|
||||
export function copyFile(src: string, dest: string): Promise<void>;
|
||||
export function mkdtemp(prefix: string): Promise<string>;
|
||||
export function rmdir(path: string): Promise<void>;
|
||||
export function rename(oldPath: string, newPath: string): Promise<void>;
|
||||
export function realpath(path: string | URL): Promise<string>;
|
||||
export function lstat(path: string | URL): Promise<import("node:fs").Stats>;
|
||||
export function unlink(path: string | URL): Promise<void>;
|
||||
export function chmod(path: string | URL, mode: number): Promise<void>;
|
||||
export function chown(path: string | URL, uid: number, gid: number): Promise<void>;
|
||||
export function lchown(path: string | URL, uid: number, gid: number): Promise<void>;
|
||||
export function access(path: string | URL, mode?: number): Promise<void>;
|
||||
export function truncate(path: string | URL, len?: number): Promise<void>;
|
||||
export function appendFile(path: string | URL, data: string | Uint8Array): Promise<void>;
|
||||
export function copyFile(src: string | URL, dest: string | URL): Promise<void>;
|
||||
export function mkdtemp(prefix: string | URL): Promise<string>;
|
||||
export function rmdir(path: string | URL): Promise<void>;
|
||||
export function rename(oldPath: string | URL, newPath: string | URL): Promise<void>;
|
||||
export function opendir(
|
||||
path: string,
|
||||
path: string | URL,
|
||||
options?: import("node:fs").OpenDirOptions,
|
||||
): Promise<import("node:fs").Dir>;
|
||||
}
|
||||
|
||||
@@ -385,7 +385,10 @@ test("while loop counters below a bound version their accesses", () => {
|
||||
]);
|
||||
const declared = (loop: IrStmt): IrFunction =>
|
||||
fn([{ kind: "varDecl", localId: "i", init: ref("k"), loc }, loop]);
|
||||
const versionOf = (loop: IrStmt & { kind: "while" }): BytesLoopVersion | null => {
|
||||
const versionOf = (
|
||||
loop: IrStmt & { kind: "while" },
|
||||
workers = false,
|
||||
): BytesLoopVersion | null => {
|
||||
const f = declared(loop);
|
||||
const ranges = analyzeIntegerRanges(f);
|
||||
return matchBytesLoopVersion(loop, null, {
|
||||
@@ -396,7 +399,7 @@ test("while loop counters below a bound version their accesses", () => {
|
||||
initialized: findInitializedByteLoopBindings(f).get(loop) ?? new Set(),
|
||||
proven: new Set(),
|
||||
scalarStrings: new Set(),
|
||||
workers: false,
|
||||
workers,
|
||||
owned: new Set(),
|
||||
});
|
||||
};
|
||||
@@ -413,6 +416,11 @@ test("while loop counters below a bound version their accesses", () => {
|
||||
// An access after the counter advances in the same pass stays checked.
|
||||
const advanced = whileLoop([step, set(ref("out", f64s), ref("i"), num(0))]);
|
||||
expect(versionOf(advanced)).toBeNull();
|
||||
// In a worker program, a while loop versions for its counter's accesses,
|
||||
// and not for thread-owned receivers alone.
|
||||
expect(versionOf(copy, true)!.ownedReceivers).toHaveLength(2);
|
||||
const job = whileLoop([set(ref("out", f64s), ref("k"), get(ref("src", f64s), ref("k"))), step]);
|
||||
expect(versionOf(job, true)).toBeNull();
|
||||
const mod: IrModule = {
|
||||
irVersion: 17,
|
||||
sourceFile: loc.file,
|
||||
|
||||
@@ -581,6 +581,11 @@ export function matchBytesLoopVersion(
|
||||
pairedKept.length === 0
|
||||
)
|
||||
return null;
|
||||
// A while loop versions only for accesses at its counters. Its other
|
||||
// checks (thread-owned receivers, static indices) save a test or two per
|
||||
// pass, while a second copy of its body doubles the calls it makes, which
|
||||
// can keep a worker's job loop from inlining the function that runs a job.
|
||||
if (loop.kind === "while" && boundedKept.length === 0) return null;
|
||||
const bounds = new Set<Node>();
|
||||
const ownedNodes = new Set<Node>();
|
||||
const used = new Set<number>();
|
||||
|
||||
@@ -64,6 +64,7 @@ import { literalEqualityDefinition } from "./string-literal-equality.js";
|
||||
import { STRING_READ_HELPERS, stringScanDecl } from "./string-reads.js";
|
||||
import { emitLibraryIdentityLines } from "../library-identity-markers.js";
|
||||
import { InternalCompilerError } from "../../errors.js";
|
||||
import { targetCpuAttribute } from "../target-cpu.js";
|
||||
|
||||
/** The function bodies emitted in `chunks` contiguous ranges, each by its
|
||||
* own emitter (LlEmitter.chunkEmitter), then merged in function order: the
|
||||
@@ -191,6 +192,20 @@ function readRange(dir: string, range: number): { result: ChunkResult; texts: st
|
||||
}
|
||||
}
|
||||
|
||||
/** The attribute groups of the emitted functions: #0 for every function,
|
||||
* #1 for coroutine bodies and #2 for out-of-line record clones. Each carries
|
||||
* the build's `--target-cpu` level. */
|
||||
function functionAttributes(emitter: LlEmitter, hasNoInlineRecordClone: boolean): string[] {
|
||||
const cpu = targetCpuAttribute(emitter.targetCpu);
|
||||
return [
|
||||
`attributes #0 = { sanitize_address${cpu} }`,
|
||||
...(emitter.usesCoroutines
|
||||
? [`attributes #1 = { sanitize_address presplitcoroutine${cpu} }`]
|
||||
: []),
|
||||
...(hasNoInlineRecordClone ? [`attributes #2 = { noinline sanitize_address${cpu} }`] : []),
|
||||
];
|
||||
}
|
||||
|
||||
export function emitModuleParts(emitter: LlEmitter): string[] {
|
||||
// Function bodies first (the literal/unit/fn-value tables fill as they
|
||||
// emit), then the file assembles around them — the runtime ABI’s order.
|
||||
@@ -972,9 +987,7 @@ export function emitModuleParts(emitter: LlEmitter): string[] {
|
||||
// symbols specified by the library IR instead.
|
||||
for (const line of emitter.emitLibDefs(globals, globalReleaseLines, stamps)) out.push(line);
|
||||
out.push(...emitter.inlineRcTail(flushedDecls));
|
||||
out.push(`attributes #0 = { sanitize_address }`);
|
||||
if (emitter.usesCoroutines) out.push(`attributes #1 = { sanitize_address presplitcoroutine }`);
|
||||
if (hasNoInlineRecordClone) out.push(`attributes #2 = { noinline sanitize_address }`);
|
||||
out.push(...functionAttributes(emitter, hasNoInlineRecordClone));
|
||||
out.push(``);
|
||||
out.push(...emitter.fieldAliasMetadata());
|
||||
if (emitter.debug !== null) out.push(emitter.debug.render());
|
||||
@@ -1122,9 +1135,7 @@ export function emitModuleParts(emitter: LlEmitter): string[] {
|
||||
// sanitize_address is inert under the plain pipeline; the sanitized
|
||||
// lane's -fsanitize=address link activates instrumentation over the
|
||||
// emitted functions too (the runtime TUs get theirs from clang).
|
||||
`attributes #0 = { sanitize_address }`,
|
||||
...(emitter.usesCoroutines ? [`attributes #1 = { sanitize_address presplitcoroutine }`] : []),
|
||||
...(hasNoInlineRecordClone ? [`attributes #2 = { noinline sanitize_address }`] : []),
|
||||
...functionAttributes(emitter, hasNoInlineRecordClone),
|
||||
``,
|
||||
);
|
||||
if (emitter.mod.workers) {
|
||||
|
||||
@@ -201,6 +201,16 @@ test("detached exit defines the runtime opt-in symbol only when requested", () =
|
||||
expect(detached.replace("@scr_detached_exit = constant i8 1\n", "")).toBe(plain);
|
||||
});
|
||||
|
||||
test("a target CPU level reaches every function attribute group and nothing else", () => {
|
||||
const module = moduleFor([call()]);
|
||||
const plain = emitLlvmModule(module);
|
||||
expect(plain).not.toContain("target-cpu");
|
||||
const v3 = emitLlvmModule(module, { targetCpu: "x86-64-v3" });
|
||||
expect(v3).toMatch(/^attributes #0 = \{ sanitize_address "target-cpu"="x86-64-v3" \}$/m);
|
||||
expect(v3.replaceAll(' "target-cpu"="x86-64-v3"', "")).toBe(plain);
|
||||
expect(emitLlvmModule(module, { targetCpu: "baseline" })).toBe(plain);
|
||||
});
|
||||
|
||||
test("inline RC inlines every fast path at speed and keeps box releases as calls in release", () => {
|
||||
for (const boxed of [false, true]) {
|
||||
const module = moduleFor(Array.from({ length: 4 }, call), { boxed });
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { TargetCpu } from "../target-cpu.js";
|
||||
import { relieveHeapPressure } from "../../heap-pressure.js";
|
||||
import { wasmBoundsChecks } from "./wasm-modules.js";
|
||||
import { jsTruthy } from "./jsval.js";
|
||||
@@ -482,6 +483,10 @@ export interface LlvmTargetOptions {
|
||||
* store the instance's address over 8 in 32 bits (classes.ts
|
||||
* compactRefLoadLines). Elsewhere they keep 8-byte pointers. */
|
||||
lowRegion?: boolean;
|
||||
/** The x86-64 level the program's code may require (`--target-cpu`):
|
||||
* every emitted function carries it as its `target-cpu`. Unset, code
|
||||
* runs on any x86-64 CPU. */
|
||||
targetCpu?: TargetCpu;
|
||||
}
|
||||
|
||||
/** LlvmTargetOptions.lowRegion for an executable: Linux targets without
|
||||
@@ -1048,6 +1053,7 @@ export class LlEmitter {
|
||||
readonly emitLibraryIdentity: boolean;
|
||||
readonly runtimeAbiMarker: boolean;
|
||||
readonly detachedExit: boolean;
|
||||
readonly targetCpu: TargetCpu | undefined;
|
||||
readonly wasmBoundsChecks: boolean;
|
||||
/** Interned string literals: UTF-8 text → { symbol, byte length } —
|
||||
* first-use order, the runtime ABI’s determinism discipline. */
|
||||
@@ -1630,6 +1636,7 @@ export class LlEmitter {
|
||||
this.emitLibraryIdentity = options.emitLibraryIdentity !== false;
|
||||
this.runtimeAbiMarker = options.runtimeAbiMarker === true;
|
||||
this.detachedExit = options.detachedExit === true;
|
||||
this.targetCpu = options.targetCpu;
|
||||
this.wasmBoundsChecks =
|
||||
options.wasmBoundsChecks === true ||
|
||||
wasmBoundsChecks({
|
||||
@@ -3801,8 +3808,17 @@ export class LlEmitter {
|
||||
|
||||
/** A union value's tag (i32): the box's tag word, or the NULL test of a
|
||||
* nullable union's pointer. */
|
||||
/** A box's tag and payload words are written only where the box is
|
||||
* built (runtime constructors and untagged stack stores), so their loads
|
||||
* carry their own alias tags: element and field stores cannot change
|
||||
* them, and loops keep them hoisted. */
|
||||
unionTag(uName: string, unionId: string): string {
|
||||
return emitUnionTag(this.B, this.nullableUnions.get(unionId), uName);
|
||||
return emitUnionTag(
|
||||
this.B,
|
||||
this.nullableUnions.get(unionId),
|
||||
uName,
|
||||
this.memoryAliasAttachment("union.tag"),
|
||||
);
|
||||
}
|
||||
|
||||
/** Guard for helpers that build or read a union's `%ScrUnion` box
|
||||
@@ -3818,7 +3834,12 @@ export class LlEmitter {
|
||||
/** The BORROWED payload pointer of a ref arm (scr_union_peek inlined —
|
||||
* the runtime's is a static inline); a nullable union is its payload. */
|
||||
unionPeek(uName: string, unionId: string): string {
|
||||
return emitUnionPeek(this.B, this.nullableUnions.get(unionId), uName);
|
||||
return emitUnionPeek(
|
||||
this.B,
|
||||
this.nullableUnions.get(unionId),
|
||||
uName,
|
||||
this.memoryAliasAttachment("union.payload"),
|
||||
);
|
||||
}
|
||||
|
||||
/** Emits `switch` over a union's tag with one block per arm; each arm
|
||||
|
||||
@@ -4,7 +4,7 @@ import { emitBorrowedInput } from "./borrowed-inputs.js";
|
||||
import { BYTES_ELEMENT_SIZE, F64, type IrBytesElem, type IrExpr } from "../../ir/ir.js";
|
||||
import type { LlvmEmitterContext, LlValue } from "./expr-context.js";
|
||||
import { F64_INF, exactIndexLines, f64Lit, sizeToDouble } from "./common.js";
|
||||
import { exactInteger, widenInteger } from "./integer-values.js";
|
||||
import { alwaysExactInteger, exactInteger } from "./integer-values.js";
|
||||
import { byteNumberAccess } from "../../ir/byte-numbers.js";
|
||||
import { emitByteNumber } from "./byte-numbers.js";
|
||||
import { integerOrNaNIndex, integerOrNaNRange } from "./wrapping-sums.js";
|
||||
@@ -86,17 +86,18 @@ export function emitBytesIndex(
|
||||
): string {
|
||||
const B = host.B;
|
||||
const index = value.name;
|
||||
const integer = exactInteger(host, value, expr);
|
||||
if (inBounds && integer) {
|
||||
const wide = widenInteger(host, integer);
|
||||
if (host.sizeType === "i64") return wide;
|
||||
// The exact integer, or a wide view that always equals the double (such
|
||||
// as `i + 1` of a speculated counter).
|
||||
const exact = alwaysExactInteger(host, value, exactInteger(host, value, expr));
|
||||
if (inBounds && exact !== null) {
|
||||
if (host.sizeType === "i64") return exact;
|
||||
const narrow = B.tmp();
|
||||
B.line(`${narrow} = trunc i64 ${wide} to ${host.sizeType}`);
|
||||
B.line(`${narrow} = trunc i64 ${exact} to ${host.sizeType}`);
|
||||
return narrow;
|
||||
}
|
||||
const len = emitBytesHeaderLength(host, receiver);
|
||||
if (integer) {
|
||||
const wideIndex = widenInteger(host, integer);
|
||||
if (exact !== null) {
|
||||
const wideIndex = exact;
|
||||
const wideLength = host.sizeType === "i64" ? len : B.tmp();
|
||||
if (host.sizeType !== "i64") B.line(`${wideLength} = zext ${host.sizeType} ${len} to i64`);
|
||||
const inRange = B.tmp();
|
||||
@@ -936,6 +937,23 @@ export function emitBytesIntrinsic(
|
||||
B.line(`${t} = fcmp one double ${idx.name}, ${f64Lit(-1)}`);
|
||||
return { name: t, type: e.type };
|
||||
}
|
||||
case "indexOfElem":
|
||||
case "lastIndexOfElem":
|
||||
return call(
|
||||
"scr_bytes_index_of_elem",
|
||||
"double (ptr, double, double, i1 zeroext)",
|
||||
`ptr ${r.name}, double ${args[0]!.name}, double ${args[1]!.name}, i1 ${method === "lastIndexOfElem"}`,
|
||||
false,
|
||||
false,
|
||||
);
|
||||
case "includesElem":
|
||||
return call(
|
||||
"scr_bytes_includes_elem",
|
||||
"zeroext i1 (ptr, double, double)",
|
||||
`ptr ${r.name}, double ${args[0]!.name}, double ${args[1]!.name}`,
|
||||
false,
|
||||
false,
|
||||
);
|
||||
case "fillElem":
|
||||
// Per-element TypedArray fill (non-u8): slice-style index
|
||||
// defaults, never throws; the receiver comes back +1.
|
||||
|
||||
@@ -13,6 +13,7 @@ import { emitStringInputs } from "./string-lifetimes.js";
|
||||
import { emitStringParts, numberPart, stringParts } from "./string-construction.js";
|
||||
import { emitBorrowedInputs } from "./borrowed-inputs.js";
|
||||
import {
|
||||
alwaysExactInteger,
|
||||
exactInteger,
|
||||
int32Number,
|
||||
integerNumber,
|
||||
@@ -46,6 +47,16 @@ import {
|
||||
} from "./dense-array-access.js";
|
||||
import { emitWrappingSum, markWrappingOperands } from "./wrapping-sums.js";
|
||||
|
||||
/** The signed integer predicates of the number compares. */
|
||||
const INTEGER_COMPARES: Record<string, string> = {
|
||||
"<": "slt",
|
||||
"<=": "sle",
|
||||
">": "sgt",
|
||||
">=": "sge",
|
||||
"===": "eq",
|
||||
"!==": "ne",
|
||||
};
|
||||
|
||||
export function emitLiteralExpr(
|
||||
host: LlvmEmitterContext,
|
||||
e: ExprOf<"numLit" | "boolLit" | "strLit" | "moduleNsRef" | "unitLit" | "varRef">,
|
||||
@@ -318,15 +329,7 @@ export function emitOperatorExpr(
|
||||
if (integer) return integer;
|
||||
}
|
||||
if (cmp[e.op] !== undefined) {
|
||||
const integerCmp: Record<string, string> = {
|
||||
"<": "slt",
|
||||
"<=": "sle",
|
||||
">": "sgt",
|
||||
">=": "sge",
|
||||
"===": "eq",
|
||||
"!==": "ne",
|
||||
};
|
||||
B.line(`${t} = icmp ${integerCmp[e.op]} i64 ${left}, ${right}`);
|
||||
B.line(`${t} = icmp ${INTEGER_COMPARES[e.op]} i64 ${left}, ${right}`);
|
||||
return { name: t, type: e.type };
|
||||
}
|
||||
}
|
||||
@@ -356,7 +359,17 @@ export function emitOperatorExpr(
|
||||
if (wideInteger) value.wideInteger = wideInteger;
|
||||
return value;
|
||||
}
|
||||
} else B.line(`${t} = fcmp ${cmp[e.op]} double ${l.name}, ${r.name}`);
|
||||
} else {
|
||||
// An operand with only a wide view, such as `i + 1` of a speculated
|
||||
// counter: compare the integers when both always equal the doubles.
|
||||
const left = alwaysExactInteger(host, l, li),
|
||||
right = left === null ? null : alwaysExactInteger(host, r, ri);
|
||||
if (left !== null && right !== null) {
|
||||
B.line(`${t} = icmp ${INTEGER_COMPARES[e.op]} i64 ${left}, ${right}`);
|
||||
return { name: t, type: e.type };
|
||||
}
|
||||
B.line(`${t} = fcmp ${cmp[e.op]} double ${l.name}, ${r.name}`);
|
||||
}
|
||||
} else if (bit[e.op] !== undefined) {
|
||||
if (e.left.type.kind !== "f64" || e.right.type.kind !== "f64") {
|
||||
throw new LlvmUnsupportedError(
|
||||
|
||||
@@ -993,6 +993,28 @@ export function streamTypedRefMaterializeAdapter(
|
||||
: `call void @scr_error_dyn_place_name(ptr ${out}, ptr ${host.cstr(nameAfter)}, ${host.sizeType} ${Buffer.byteLength(nameAfter, "utf8")})`,
|
||||
);
|
||||
}
|
||||
// A JavaScript Error subclass's property bag records, once a dynamic
|
||||
// write has committed the view, where `name` and `message` were created
|
||||
// (zod's error factory assigns `name` before it defines `message`); the
|
||||
// slots hold their values. A `name` the class's construction sets is
|
||||
// already where errorNameAfter places it among the fields.
|
||||
if (
|
||||
meta.def.errorBagOrder &&
|
||||
meta.root.def.name === "%Error" &&
|
||||
meta.def.fields.some((field) => field.name === DYN_CLASS_PROPERTIES)
|
||||
) {
|
||||
host.declare(`declare void @scr_error_dyn_follow_bag(ptr, ptr, ptr, i1)`);
|
||||
const { index } = classFieldIndex(meta, DYN_CLASS_PROPERTIES);
|
||||
const slot = B.tmp(),
|
||||
bag = B.tmp();
|
||||
B.line(
|
||||
`${slot} = getelementptr inbounds %${classStructSym(t.className)}, ptr %p, i64 0, i32 ${index}`,
|
||||
);
|
||||
B.line(`${bag} = load ptr, ptr ${slot}`);
|
||||
B.line(
|
||||
`call void @scr_error_dyn_follow_bag(ptr ${out}, ptr ${bag}, ptr %p, i1 ${nameAfter === undefined ? "false" : "true"})`,
|
||||
);
|
||||
}
|
||||
// A frozen, sealed or non-extensible instance's view says so.
|
||||
if (withAttributes) {
|
||||
host.declare(`declare void @scr_dyn_class_view_attributes(ptr, double)`);
|
||||
|
||||
@@ -65,6 +65,22 @@ function magnitude(range: IntegerRange): number {
|
||||
return Math.max(Math.abs(range.min), Math.abs(range.max));
|
||||
}
|
||||
|
||||
/** The bounds of a sum and a product of two magnitude bounds, as doubles.
|
||||
* Below 2^53 the double result is the integer; above it the result is past
|
||||
* every exactness limit either way, and rounding moves it far less than the
|
||||
* margin from WIDE_BOUND to the i64 range. A result of exactly 2^53 may
|
||||
* stand for 2^53 + 1 (2^53 - 1 + 2 rounds to 2^53), so it moves to the next
|
||||
* double up unless the sum is exactly 2^53. */
|
||||
function sumBound(a: number, b: number): number {
|
||||
const sum = a + b;
|
||||
return sum === EXACT_DOUBLES && EXACT_DOUBLES - a !== b ? sum + 2 : sum;
|
||||
}
|
||||
|
||||
function productBound(a: number, b: number): number {
|
||||
const product = a * b;
|
||||
return product === EXACT_DOUBLES ? product + 2 : product;
|
||||
}
|
||||
|
||||
/** The wide view of `l op r` for `+`, `-` and `*` when the exact operands
|
||||
* have no proven result range (their product or sum may pass 2^53).
|
||||
*
|
||||
@@ -98,14 +114,14 @@ export function wideArithmetic(
|
||||
if (op === "*") {
|
||||
if (lv.below !== Infinity || rv.below !== Infinity) return null;
|
||||
below = EXACT_DOUBLES;
|
||||
bound = lv.bound * rv.bound;
|
||||
bound = productBound(lv.bound, rv.bound);
|
||||
} else if (lv.below === Infinity && rv.below === Infinity) {
|
||||
below = EXACT_DOUBLES;
|
||||
bound = lv.bound + rv.bound;
|
||||
bound = sumBound(lv.bound, rv.bound);
|
||||
} else if (lv.below === Infinity || rv.below === Infinity) {
|
||||
const [exact, wide] = lv.below === Infinity ? [lv, rv] : [rv, lv];
|
||||
below = Math.min(wide.below - exact.bound, EXACT_DOUBLES);
|
||||
bound = exact.bound + wide.bound;
|
||||
bound = sumBound(exact.bound, wide.bound);
|
||||
} else return null;
|
||||
if (!(bound <= WIDE_BOUND) || below < INDEX_LIMIT) return null;
|
||||
const operand = (value: LlValue, integer: LlInteger | null): string =>
|
||||
@@ -134,6 +150,20 @@ export function indexInteger(
|
||||
return wide && wide.below >= INDEX_LIMIT ? wide.name : null;
|
||||
}
|
||||
|
||||
/** An i64 equal to a value's double wherever the value can be: its exact
|
||||
* integer, or a wide view whose magnitude bound is within the magnitude below
|
||||
* which the view is exact. Every integer of magnitude at most 2^53 is a
|
||||
* double, so a bound equal to that limit is exact too. Null otherwise. */
|
||||
export function alwaysExactInteger(
|
||||
host: LlvmEmitterContext,
|
||||
value: LlValue,
|
||||
integer: LlInteger | null,
|
||||
): string | null {
|
||||
if (integer) return widenInteger(host, integer);
|
||||
const wide = value.wideInteger;
|
||||
return wide && wide.bound <= wide.below ? wide.name : null;
|
||||
}
|
||||
|
||||
export function widenInteger(host: LlvmEmitterContext, value: LlInteger): string {
|
||||
if (value.type === "i64") return value.name;
|
||||
const wide = host.B.tmp();
|
||||
|
||||
@@ -658,6 +658,7 @@ export const LIB_FN_SYMS: Record<string, string> = {
|
||||
"process.stderrWriteBytes": "scr_process_stderr_write_bytes",
|
||||
"insp.buffer": "scr_insp_buffer",
|
||||
"insp.typedArray": "scr_insp_typed_array",
|
||||
"insp.bytes": "scr_insp_bytes",
|
||||
// util.inspect (scr_inspect.c): all args borrowed; string results +1;
|
||||
// the begin/entry/key/moreItems/end accumulator drives the emitted
|
||||
// container walks. None of these throw.
|
||||
@@ -713,6 +714,9 @@ export const LIB_FN_SYMS: Record<string, string> = {
|
||||
"url.hash": "scr_url_hash",
|
||||
"url.searchParams": "scr_url_search_params",
|
||||
"url.fileURLToPathUrl": "scr_url_to_path",
|
||||
"url.fileURLToPathValue": "scr_url_to_path_value",
|
||||
"fs.checkPath": "scr_fs_check_path",
|
||||
"fs.checkReadEncoding": "scr_fs_check_read_encoding",
|
||||
"url.fileURLToPathChecked": "scr_url_checked_to_path",
|
||||
"url.fileURLToPathOptions": "scr_url_checked_to_path_options",
|
||||
"url.fileURLToPathBuffer": "scr_url_checked_to_path_buffer",
|
||||
|
||||
@@ -181,6 +181,9 @@ function expressionPreservesEdges(
|
||||
case "bytesIntrinsic":
|
||||
return (
|
||||
e.method === "get" ||
|
||||
e.method === "indexOfElem" ||
|
||||
e.method === "lastIndexOfElem" ||
|
||||
e.method === "includesElem" ||
|
||||
e.method === "length" ||
|
||||
e.method === "byteLength" ||
|
||||
e.method === "byteOffset" ||
|
||||
|
||||
@@ -8,8 +8,14 @@
|
||||
import type { BlockBuilder } from "./blocks.js";
|
||||
import { NULLABLE_NULL, shapeTagFn, type PointerUnion } from "./nullable-unions.js";
|
||||
|
||||
/** The i32 tag of a union value. */
|
||||
export function emitUnionTag(B: BlockBuilder, nullable: PointerUnion | null, u: string): string {
|
||||
/** The i32 tag of a union value. `alias` is the tag word's alias
|
||||
* attachment (", !tbaa !N"), when the caller has one. */
|
||||
export function emitUnionTag(
|
||||
B: BlockBuilder,
|
||||
nullable: PointerUnion | null,
|
||||
u: string,
|
||||
alias = "",
|
||||
): string {
|
||||
const t = B.tmp();
|
||||
if (nullable?.repr === "shapes") {
|
||||
B.line(`${t} = call i32 ${shapeTagFn(nullable.unionId)}(ptr ${u})`);
|
||||
@@ -31,7 +37,7 @@ export function emitUnionTag(B: BlockBuilder, nullable: PointerUnion | null, u:
|
||||
}
|
||||
const p = B.tmp();
|
||||
B.line(`${p} = getelementptr inbounds %ScrUnion, ptr ${u}, i64 0, i32 1`);
|
||||
B.line(`${t} = load i32, ptr ${p}`);
|
||||
B.line(`${t} = load i32, ptr ${p}${alias}`);
|
||||
return t;
|
||||
}
|
||||
|
||||
@@ -81,12 +87,17 @@ export function emitNullableIsTag(
|
||||
}
|
||||
|
||||
/** The BORROWED payload pointer of a reference arm. */
|
||||
export function emitUnionPeek(B: BlockBuilder, nullable: PointerUnion | null, u: string): string {
|
||||
export function emitUnionPeek(
|
||||
B: BlockBuilder,
|
||||
nullable: PointerUnion | null,
|
||||
u: string,
|
||||
alias = "",
|
||||
): string {
|
||||
if (nullable) return u;
|
||||
const p = B.tmp();
|
||||
const t = B.tmp();
|
||||
B.line(`${p} = getelementptr inbounds %ScrUnion, ptr ${u}, i64 0, i32 5`);
|
||||
B.line(`${t} = load ptr, ptr ${p}`);
|
||||
B.line(`${t} = load ptr, ptr ${p}${alias}`);
|
||||
return t;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { expect, test } from "vitest";
|
||||
import {
|
||||
isTargetCpuOption,
|
||||
targetCpuAttribute,
|
||||
targetCpuField,
|
||||
targetCpuKeyParts,
|
||||
targetCpuTargetRefusal,
|
||||
x86Level,
|
||||
} from "./target-cpu.js";
|
||||
|
||||
const V2 = ["cx16", "lahf_lm", "popcnt", "pni", "sse4_1", "sse4_2", "ssse3"];
|
||||
const V3 = ["avx", "avx2", "bmi1", "bmi2", "f16c", "fma", "abm", "movbe", "xsave"];
|
||||
const V4 = ["avx512f", "avx512bw", "avx512cd", "avx512dq", "avx512vl"];
|
||||
const level = (flags: string[]) => x86Level((flag) => flags.includes(flag));
|
||||
|
||||
test("a host's level is the highest one whose features and lower levels' features it has", () => {
|
||||
expect(level([])).toBe("baseline");
|
||||
expect(level(V2)).toBe("x86-64-v2");
|
||||
expect(level([...V2, ...V3])).toBe("x86-64-v3");
|
||||
expect(level([...V2, ...V3, ...V4])).toBe("x86-64-v4");
|
||||
// AVX-512 without BMI2 is still v2.
|
||||
expect(level([...V2, ...V3.filter((f) => f !== "bmi2"), ...V4])).toBe("x86-64-v2");
|
||||
expect(level([...V3, ...V4])).toBe("baseline");
|
||||
});
|
||||
|
||||
test("the baseline adds no key part, attribute or option field", () => {
|
||||
for (const cpu of [undefined, "baseline"] as const) {
|
||||
expect(targetCpuKeyParts(cpu)).toEqual([]);
|
||||
expect(targetCpuAttribute(cpu)).toBe("");
|
||||
expect(targetCpuField(cpu)).toEqual({});
|
||||
expect(targetCpuTargetRefusal(cpu, "linux", "arm64")).toBeNull();
|
||||
}
|
||||
expect(targetCpuKeyParts("x86-64-v3")).toEqual(["target-cpu-x86-64-v3"]);
|
||||
expect(targetCpuAttribute("x86-64-v4")).toBe(' "target-cpu"="x86-64-v4"');
|
||||
expect(targetCpuField("x86-64-v2")).toEqual({ targetCpu: "x86-64-v2" });
|
||||
});
|
||||
|
||||
test("a level is refused for targets that are not x86-64", () => {
|
||||
expect(targetCpuTargetRefusal("x86-64-v3", "linux", "x64")).toBeNull();
|
||||
expect(targetCpuTargetRefusal("x86-64-v3", "darwin", "arm64")).toBe(
|
||||
"--target-cpu=x86-64-v3 requires an x86-64 target",
|
||||
);
|
||||
expect(targetCpuTargetRefusal("x86-64-v3", "wasi", "x64")).not.toBeNull();
|
||||
});
|
||||
|
||||
test("the option accepts the levels and native", () => {
|
||||
for (const value of ["baseline", "x86-64-v2", "x86-64-v3", "x86-64-v4", "native"])
|
||||
expect(isTargetCpuOption(value)).toBe(true);
|
||||
for (const value of ["x86-64", "haswell", "", undefined])
|
||||
expect(isTargetCpuOption(value)).toBe(false);
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
/** The x86-64 microarchitecture levels an executable may require
|
||||
* (`--target-cpu`). `baseline` is the x86-64 baseline every release build
|
||||
* targets; the other levels are LLVM's `x86-64-v2` to `x86-64-v4`. */
|
||||
export type TargetCpu = "baseline" | "x86-64-v2" | "x86-64-v3" | "x86-64-v4";
|
||||
|
||||
/** The values `--target-cpu` accepts: a level, or `native` for the highest
|
||||
* level the build host supports. */
|
||||
export const TARGET_CPU_OPTIONS = ["baseline", "x86-64-v2", "x86-64-v3", "x86-64-v4", "native"];
|
||||
|
||||
export function isTargetCpuOption(value: unknown): value is TargetCpu | "native" {
|
||||
return typeof value === "string" && TARGET_CPU_OPTIONS.includes(value);
|
||||
}
|
||||
|
||||
/** The CPU features each level adds to the one below it, as Linux names
|
||||
* them in /proc/cpuinfo (`pni` is SSE3, `abm` includes LZCNT). */
|
||||
const LEVEL_FLAGS: readonly [TargetCpu, readonly string[]][] = [
|
||||
["x86-64-v2", ["cx16", "lahf_lm", "popcnt", "pni", "sse4_1", "sse4_2", "ssse3"]],
|
||||
["x86-64-v3", ["avx", "avx2", "bmi1", "bmi2", "f16c", "fma", "abm", "movbe", "xsave"]],
|
||||
["x86-64-v4", ["avx512f", "avx512bw", "avx512cd", "avx512dq", "avx512vl"]],
|
||||
];
|
||||
|
||||
/** The macOS `machdep.cpu` spellings of the same features. */
|
||||
const DARWIN_FLAGS: Readonly<Record<string, string>> = {
|
||||
cx16: "CX16",
|
||||
lahf_lm: "LAHF",
|
||||
popcnt: "POPCNT",
|
||||
pni: "SSE3",
|
||||
sse4_1: "SSE4.1",
|
||||
sse4_2: "SSE4.2",
|
||||
ssse3: "SSSE3",
|
||||
avx: "AVX1.0",
|
||||
avx2: "AVX2",
|
||||
bmi1: "BMI1",
|
||||
bmi2: "BMI2",
|
||||
f16c: "F16C",
|
||||
fma: "FMA",
|
||||
abm: "LZCNT",
|
||||
movbe: "MOVBE",
|
||||
xsave: "XSAVE",
|
||||
avx512f: "AVX512F",
|
||||
avx512bw: "AVX512BW",
|
||||
avx512cd: "AVX512CD",
|
||||
avx512dq: "AVX512DQ",
|
||||
avx512vl: "AVX512VL",
|
||||
};
|
||||
|
||||
/** The highest level whose features (and every lower level's) are all in
|
||||
* `has`. */
|
||||
export function x86Level(has: (flag: string) => boolean): TargetCpu {
|
||||
let level: TargetCpu = "baseline";
|
||||
for (const [next, flags] of LEVEL_FLAGS) {
|
||||
if (!flags.every(has)) break;
|
||||
level = next;
|
||||
}
|
||||
return level;
|
||||
}
|
||||
|
||||
/** The highest level the build host supports, or null when the host is not
|
||||
* an x86-64 Linux or macOS machine. */
|
||||
export function hostTargetCpu(
|
||||
platform: string = process.platform,
|
||||
arch: string = process.arch,
|
||||
): TargetCpu | null {
|
||||
if (arch !== "x64") return null;
|
||||
try {
|
||||
if (platform === "linux") {
|
||||
const info = readFileSync("/proc/cpuinfo", "utf8");
|
||||
const line = /^flags\s*:(.*)$/m.exec(info);
|
||||
if (!line) return null;
|
||||
const flags = new Set(line[1]!.trim().split(/\s+/));
|
||||
return x86Level((flag) => flags.has(flag));
|
||||
}
|
||||
if (platform === "darwin") {
|
||||
const text = execFileSync(
|
||||
"sysctl",
|
||||
["-n", "machdep.cpu.features", "machdep.cpu.leaf7_features", "machdep.cpu.extfeatures"],
|
||||
{ encoding: "utf8" },
|
||||
);
|
||||
const flags = new Set(text.trim().split(/\s+/));
|
||||
return x86Level((flag) => flags.has(DARWIN_FLAGS[flag]!));
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Cache-key parts for a target level; empty for the baseline so existing
|
||||
* keys are unchanged. */
|
||||
export function targetCpuKeyParts(cpu: TargetCpu | undefined): string[] {
|
||||
return cpu === undefined || cpu === "baseline" ? [] : [`target-cpu-${cpu}`];
|
||||
}
|
||||
|
||||
/** The function attribute that makes LLVM generate code for the level, or
|
||||
* "" for the baseline. */
|
||||
export function targetCpuAttribute(cpu: TargetCpu | undefined): string {
|
||||
return cpu === undefined || cpu === "baseline" ? "" : ` "target-cpu"="${cpu}"`;
|
||||
}
|
||||
|
||||
/** The options field for a level: omitted for the baseline. */
|
||||
export function targetCpuField(cpu: TargetCpu | undefined): { targetCpu?: TargetCpu } {
|
||||
return cpu === undefined || cpu === "baseline" ? {} : { targetCpu: cpu };
|
||||
}
|
||||
|
||||
/** The error for a level on a target that is not x86-64, or null. */
|
||||
export function targetCpuTargetRefusal(
|
||||
cpu: TargetCpu | undefined,
|
||||
platform: string,
|
||||
architecture: string,
|
||||
): string | null {
|
||||
if (cpu === undefined || cpu === "baseline") return null;
|
||||
if (architecture !== "x64" || platform === "wasi")
|
||||
return `--target-cpu=${cpu} requires an x86-64 target`;
|
||||
return null;
|
||||
}
|
||||
@@ -15,6 +15,13 @@ import { buildEnvelope } from "../diagnostics/envelope.js";
|
||||
import { renderWarnings } from "../diagnostics/render.js";
|
||||
import { isPerformanceCode, renderPerformanceWarnings } from "../diagnostics/dynamic-tier.js";
|
||||
import { isNativeOptimization } from "../backend/optimization.js";
|
||||
import {
|
||||
hostTargetCpu,
|
||||
isTargetCpuOption,
|
||||
TARGET_CPU_OPTIONS,
|
||||
targetCpuField,
|
||||
type TargetCpu,
|
||||
} from "../backend/target-cpu.js";
|
||||
import { setProvenanceSources } from "../frontend/provenance-registry.js";
|
||||
import type { CliHost, NativeCacheWarmProfile } from "./host.js";
|
||||
import { resolveOutputOptions } from "./output-options.js";
|
||||
@@ -96,6 +103,7 @@ async function main(args: string[], host: CliHost): Promise<number> {
|
||||
values.strip ||
|
||||
values["windows-subsystem"] !== undefined ||
|
||||
values["detached-exit"] ||
|
||||
values["target-cpu"] !== undefined ||
|
||||
values["profile-generate"] !== undefined ||
|
||||
values["profile-use"] !== undefined ||
|
||||
values.sparse ||
|
||||
@@ -154,6 +162,7 @@ async function main(args: string[], host: CliHost): Promise<number> {
|
||||
values.sanitize ||
|
||||
values["windows-subsystem"] !== undefined ||
|
||||
values["detached-exit"] ||
|
||||
values["target-cpu"] !== undefined ||
|
||||
values["profile-generate"] !== undefined ||
|
||||
values["profile-use"] !== undefined ||
|
||||
(values["npm-static"] ?? []).length > 0 ||
|
||||
@@ -210,6 +219,7 @@ async function main(args: string[], host: CliHost): Promise<number> {
|
||||
values.ffi !== undefined ||
|
||||
values["windows-subsystem"] !== undefined ||
|
||||
values["detached-exit"] ||
|
||||
values["target-cpu"] !== undefined ||
|
||||
values["profile-generate"] !== undefined ||
|
||||
values["profile-use"] !== undefined ||
|
||||
(values["npm-static"] ?? []).length > 0 ||
|
||||
@@ -218,7 +228,7 @@ async function main(args: string[], host: CliHost): Promise<number> {
|
||||
values["explain-dynamic"] !== undefined
|
||||
) {
|
||||
fail(
|
||||
"scriptc build --lib takes no --backend/--emit/--print/--optimization/--strip/--windows-subsystem/--detached-exit/--profile-generate/--profile-use/--npm-static/--ffi/--external-types/--tier/--explain-dynamic: the profile pins the emission and optimization, npm imports are judged automatically, outbound FFI belongs to executable builds, external type mappings belong to coverage, and library artifacts are static-tier only",
|
||||
"scriptc build --lib takes no --backend/--emit/--print/--optimization/--strip/--windows-subsystem/--detached-exit/--target-cpu/--profile-generate/--profile-use/--npm-static/--ffi/--external-types/--tier/--explain-dynamic: the profile pins the emission and optimization, npm imports are judged automatically, outbound FFI belongs to executable builds, external type mappings belong to coverage, and library artifacts are static-tier only",
|
||||
);
|
||||
}
|
||||
const profilePath = resolve(profileArg);
|
||||
@@ -261,6 +271,9 @@ async function main(args: string[], host: CliHost): Promise<number> {
|
||||
if (command === "coverage" && values.strip) {
|
||||
fail(`--strip is a build/run option\n\n${USAGE}`);
|
||||
}
|
||||
if (command === "coverage" && values["target-cpu"] !== undefined) {
|
||||
fail(`--target-cpu is a build/run option\n\n${USAGE}`);
|
||||
}
|
||||
if (command === "coverage" && values["detached-exit"]) {
|
||||
fail(`--detached-exit is a build/run option\n\n${USAGE}`);
|
||||
}
|
||||
@@ -377,6 +390,19 @@ async function main(args: string[], host: CliHost): Promise<number> {
|
||||
if (windowsSubsystem !== undefined && command === "coverage") {
|
||||
fail(`--windows-subsystem is only supported for executable builds\n\n${USAGE}`);
|
||||
}
|
||||
const targetCpuOption = values["target-cpu"];
|
||||
if (targetCpuOption !== undefined && !isTargetCpuOption(targetCpuOption)) {
|
||||
fail(
|
||||
`unknown target CPU "${targetCpuOption}" (supported: ${TARGET_CPU_OPTIONS.join(", ")})\n\n${USAGE}`,
|
||||
);
|
||||
}
|
||||
let targetCpu: TargetCpu | undefined = targetCpuOption === "native" ? undefined : targetCpuOption;
|
||||
if (targetCpuOption === "native") {
|
||||
const level = hostTargetCpu();
|
||||
if (level === null)
|
||||
fail(`--target-cpu=native needs an x86-64 Linux or macOS build host; name a level instead`);
|
||||
targetCpu = level;
|
||||
}
|
||||
const output =
|
||||
command === "coverage"
|
||||
? null
|
||||
@@ -498,6 +524,7 @@ async function main(args: string[], host: CliHost): Promise<number> {
|
||||
...(values.strip ? { strip: true } : {}),
|
||||
...(windowsSubsystem !== undefined ? { windowsSubsystem } : {}),
|
||||
...(values["detached-exit"] ? { detachedExit: true } : {}),
|
||||
...targetCpuField(targetCpu),
|
||||
// The instrumented program resolves a relative pattern against its own
|
||||
// working directory; resolve it here, where the user wrote it.
|
||||
...(values["profile-generate"] === undefined
|
||||
|
||||
@@ -54,6 +54,12 @@ Options:
|
||||
a helper process so the parent sees the exit sooner. The
|
||||
helper keeps the executable mapped and its memory charged
|
||||
for up to ~100 ms after exit (opt in; --emit=exe only)
|
||||
--target-cpu <baseline|x86-64-v2|x86-64-v3|x86-64-v4|native>
|
||||
x86-64: compile the program's code for a CPU level
|
||||
(default: baseline, which runs on any x86-64 CPU). The
|
||||
executable then requires that level: v3 adds AVX2, BMI2
|
||||
and FMA, v4 adds AVX-512. native uses the build host's
|
||||
level. The runtime keeps its baseline code
|
||||
--profile-generate <pattern>
|
||||
Linux: instrument the executable for profile-guided
|
||||
optimization. Each run writes a raw profile to the
|
||||
@@ -123,6 +129,7 @@ export const CLI_OPTIONS = {
|
||||
strip: { type: "boolean", default: false },
|
||||
"windows-subsystem": { type: "string" },
|
||||
"detached-exit": { type: "boolean", default: false },
|
||||
"target-cpu": { type: "string" },
|
||||
"profile-generate": { type: "string" },
|
||||
"profile-use": { type: "string" },
|
||||
sparse: { type: "boolean", default: false },
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { TargetCpu } from "./backend/target-cpu.js";
|
||||
import type { WindowsSubsystem } from "./backend/targets.js";
|
||||
import type { NativeLinkInfo } from "./backend/native-link-info.js";
|
||||
import type { NativeOptimization } from "./backend/optimization.js";
|
||||
@@ -36,6 +37,12 @@ export interface CompileBaseOptions {
|
||||
* executable mapped and the memory charged for up to ~100 ms after exit.
|
||||
* Executables only; no effect on other platforms. */
|
||||
detachedExit?: boolean;
|
||||
/** The x86-64 microarchitecture level the executable's code may require
|
||||
* (`x86-64-v2` to `x86-64-v4`). The program's functions are compiled for
|
||||
* that level, and the executable then runs only on CPUs that support it.
|
||||
* Unset or `baseline`, the code runs on any x86-64 CPU. x86-64 targets
|
||||
* only; the runtime pack keeps its baseline code. */
|
||||
targetCpu?: TargetCpu;
|
||||
/** Instrument the executable for profile-guided optimization. Each run
|
||||
* writes a raw profile to this path pattern (`%p` expands to the process
|
||||
* id; `LLVM_PROFILE_FILE` overrides the pattern at run time). Linux
|
||||
|
||||
@@ -236,6 +236,8 @@ test("early executable keys isolate compile modes, paths, implementation, checke
|
||||
{ ...f.options, optimization: "dev" },
|
||||
{ ...f.options, optimization: "speed" },
|
||||
{ ...f.options, detachedExit: true },
|
||||
{ ...f.options, targetCpu: "x86-64-v3" },
|
||||
{ ...f.options, targetCpu: "x86-64-v4" },
|
||||
{ ...f.options, profile: "profile-generate:/tmp/%p.profraw" },
|
||||
{ ...f.options, profile: "profile-use:digest" },
|
||||
{ ...f.options, checker: "tsc-ts-executable-identity" },
|
||||
|
||||
@@ -18,6 +18,7 @@ import { compilerReleaseVersion } from "../library/sidecar.js";
|
||||
import { nativeArtifactDependenciesStillMatch } from "../backend/native/artifact-stamps.js";
|
||||
import { type NativeArtifactDependency } from "../backend/native/contracts.js";
|
||||
import { optimizationKeyParts } from "../backend/optimization.js";
|
||||
import { type TargetCpu, targetCpuKeyParts } from "../backend/target-cpu.js";
|
||||
import { privateSiblingPath } from "../backend/build-cache.js";
|
||||
import type { CompilerImplementationDependency } from "../library/compiler-self-identity.js";
|
||||
import {
|
||||
@@ -139,6 +140,8 @@ export interface EarlyExecutableCacheOptions {
|
||||
windowsSubsystem?: "gui";
|
||||
/** Omitted unless --detached-exit is set. */
|
||||
detachedExit?: true;
|
||||
/** Omitted for the x86-64 baseline (`--target-cpu`). */
|
||||
targetCpu?: TargetCpu;
|
||||
/** Omitted without --profile-generate/--profile-use; otherwise the
|
||||
* pattern, or the digest of the profile's bytes. */
|
||||
profile?: string;
|
||||
@@ -281,6 +284,7 @@ function cacheKey(options: EarlyExecutableCacheOptions): string {
|
||||
...(options.strip ? ["strip"] : []),
|
||||
...(options.windowsSubsystem === "gui" ? ["windows-subsystem-gui"] : []),
|
||||
...(options.detachedExit ? ["detached-exit"] : []),
|
||||
...targetCpuKeyParts(options.targetCpu),
|
||||
...(options.profile !== undefined ? [options.profile] : []),
|
||||
...(options.checker !== undefined ? [`checker:${options.checker}`] : []),
|
||||
...(options.youngNursery ? ["young-nursery"] : []),
|
||||
@@ -323,6 +327,7 @@ function routeKey(options: Omit<EarlyExecutableRouteOptions, "nativeEnvironment"
|
||||
if (options.strip) hash.update("strip\0");
|
||||
if (options.windowsSubsystem === "gui") hash.update("windows-subsystem-gui\0");
|
||||
if (options.detachedExit) hash.update("detached-exit\0");
|
||||
for (const part of targetCpuKeyParts(options.targetCpu)) hash.update(`${part}\0`);
|
||||
if (options.profile !== undefined) hash.update(`${options.profile}\0`);
|
||||
if (options.checker !== undefined) hash.update(`checker:${options.checker}\0`);
|
||||
if (options.youngNursery) hash.update("young-nursery\0");
|
||||
|
||||
@@ -265,7 +265,7 @@ export function lowerFsPromisesOpenCall(
|
||||
"use open(path[, stringFlags[, numericMode]])",
|
||||
);
|
||||
}
|
||||
const path = lowerer.lowerExprExpecting(expr.arguments.nodes[0]!, STRING);
|
||||
const path = lowerFsPath(lowerer, expr.arguments.nodes[0]!);
|
||||
const defaultFlags: IrExpr = { kind: "strLit", value: "r", type: STRING, loc };
|
||||
const defaultMode: IrExpr = { kind: "numLit", value: 0o666, type: F64, loc };
|
||||
const flags = expr.arguments.nodes[1]
|
||||
@@ -705,7 +705,7 @@ export function lowerFsPromisesEncodedRead(
|
||||
)
|
||||
return null;
|
||||
}
|
||||
const path = lowerer.lowerExprExpecting(expr.arguments.nodes[0]!, STRING);
|
||||
const path = lowerFsPath(lowerer, expr.arguments.nodes[0]!);
|
||||
const encoding: IrExpr =
|
||||
optionsType.kind === "string"
|
||||
? lowerer.lowerExprExpecting(options, STRING)
|
||||
@@ -853,7 +853,7 @@ export function lowerFsPromisesMkdirCall(
|
||||
);
|
||||
}
|
||||
const { recursive, modeNode } = options;
|
||||
const path = lowerer.lowerExprExpecting(expr.arguments.nodes[0]!, STRING);
|
||||
const path = lowerFsPath(lowerer, expr.arguments.nodes[0]!);
|
||||
const mode: IrExpr | null = modeNode ? lowerer.lowerExprExpecting(modeNode, F64) : null;
|
||||
const type: IrType = { kind: "promise", inner: VOID };
|
||||
if (!recursive) {
|
||||
|
||||
@@ -22,7 +22,10 @@ import { builtinImportOf } from "./module-bindings.js";
|
||||
* lib/internal/fs/glob.js). The pattern and options cross as dyn values so
|
||||
* the runtime validates them in Node's order. The result form (strings or
|
||||
* Dirent rows) comes from the call's mapped result type, so withFileTypes
|
||||
* must be statically known; the runtime checks that the option agrees. */
|
||||
* must be statically known; the runtime checks that the option agrees.
|
||||
* Because of that check, the form follows the checker's resolved overload
|
||||
* even where an untyped options argument leaves the overload undecided
|
||||
* (dynamicOverloadChoice). */
|
||||
|
||||
/** The interned Dirent record array (type-mapper.ts), or null. */
|
||||
function direntArray(lowerer: Lowerer, type: IrType | null | undefined): boolean {
|
||||
@@ -67,7 +70,7 @@ export function lowerFsGlobSyncCall(
|
||||
loc: SrcLoc,
|
||||
): IrExpr {
|
||||
const args = globArgs(lowerer, call, "fs.globSync");
|
||||
const callType = lowerer.mapTypeOf(lowerer.typeOf(call));
|
||||
const callType = lowerer.mapTypeOf(lowerer.checker.getTypeAtLocation(call));
|
||||
const types = direntArray(lowerer, callType);
|
||||
if (types) fenceDirentExclude(lowerer, call, "fs.globSync");
|
||||
if (!types && !(callType?.kind === "array" && callType.elem.kind === "string")) {
|
||||
@@ -132,7 +135,9 @@ export function lowerFspGlobCall(lowerer: Lowerer, call: ts.CallExpression, loc:
|
||||
}
|
||||
const args = globArgs(lowerer, call, "fs/promises glob");
|
||||
// The async iterator's yielded type (its first type argument).
|
||||
const yielded = lowerer.checker.getTypeArguments(lowerer.typeOf(call) as ts.TypeReference)[0];
|
||||
const yielded = lowerer.checker.getTypeArguments(
|
||||
lowerer.checker.getTypeAtLocation(call) as ts.TypeReference,
|
||||
)[0];
|
||||
const element = yielded ? lowerer.mapTypeOf(yielded) : null;
|
||||
const rows: IrType | null = element ? { kind: "array", elem: element } : null;
|
||||
const types = direntArray(lowerer, rows);
|
||||
|
||||
@@ -5,30 +5,40 @@
|
||||
* conversion (url.fileURLToPathUrl). The later arguments through the last
|
||||
* one with side effects are evaluated into hidden locals before the
|
||||
* conversion, in source order, so they run even when it throws and each
|
||||
* reads what it reads in Node. The conversion keeps Node's error order when every
|
||||
* earlier path is a URL too and each argument Node validates before the
|
||||
* path is absent or a literal that passes that validation; other URL
|
||||
* forms fence with SC2020, as do the fs.promises functions, whose
|
||||
* conversion errors are rejections rather than throws, and existsSync,
|
||||
* which answers false for a URL it cannot convert. */
|
||||
* reads what it reads in Node. Before the conversion, an earlier string
|
||||
* path gets its null-byte check (copyFileSync, renameSync) and a runtime
|
||||
* readFileSync encoding its name check, which Node runs first. existsSync
|
||||
* and the fs.promises functions convert to a value instead
|
||||
* (url.fileURLToPathValue) and answer false or a rejected promise for a
|
||||
* conversion error. An argument Node validates before the path must
|
||||
* otherwise be absent or a literal that passes that validation; other
|
||||
* forms fence with SC2020. */
|
||||
import * as ts from "../../ts7/adapter.js";
|
||||
import { type Lowerer } from "../lowerer.js";
|
||||
import { locOf } from "../../program.js";
|
||||
import { sideEffectFreeOptionValue } from "../surfaces.js";
|
||||
import { stripTypeWrappers } from "../typed-arguments.js";
|
||||
import { type IrExpr, type IrStmt, STRING, URL_T } from "../../../ir/ir.js";
|
||||
import { boolLit, varRef } from "../../../ir/build.js";
|
||||
import { BOOL, DYN, type IrExpr, type IrStmt, STRING, URL_T, VOID } from "../../../ir/ir.js";
|
||||
import { InternalCompilerError } from "../../../errors.js";
|
||||
|
||||
/** The fs functions whose path parameters accept a URL: the path
|
||||
* parameter indexes, and whether Node validates the paths before every
|
||||
* other argument (otherwise the options come first). */
|
||||
const FS_URL_PATHS: Readonly<
|
||||
Record<string, { readonly paths: readonly number[]; readonly pathsFirst: boolean }>
|
||||
> = {
|
||||
interface FsPathRow {
|
||||
/** The path parameter indexes. */
|
||||
readonly paths: readonly number[];
|
||||
/** Whether Node validates the paths before every other argument
|
||||
* (otherwise the options come first). */
|
||||
readonly pathsFirst: boolean;
|
||||
/** The path parameters' names in Node's errors, when there are two. */
|
||||
readonly names?: readonly string[];
|
||||
}
|
||||
|
||||
/** The fs functions whose path parameters accept a URL. */
|
||||
const FS_URL_PATHS: Readonly<Record<string, FsPathRow>> = {
|
||||
accessSync: { paths: [0], pathsFirst: true },
|
||||
appendFileSync: { paths: [0], pathsFirst: false },
|
||||
chmodSync: { paths: [0], pathsFirst: true },
|
||||
chownSync: { paths: [0], pathsFirst: true },
|
||||
copyFileSync: { paths: [0, 1], pathsFirst: true },
|
||||
copyFileSync: { paths: [0, 1], pathsFirst: true, names: ["src", "dest"] },
|
||||
lchownSync: { paths: [0], pathsFirst: true },
|
||||
lstatSync: { paths: [0], pathsFirst: true },
|
||||
mkdirSync: { paths: [0], pathsFirst: false },
|
||||
@@ -39,7 +49,7 @@ const FS_URL_PATHS: Readonly<
|
||||
readdirSync: { paths: [0], pathsFirst: false },
|
||||
realpathSync: { paths: [0], pathsFirst: false },
|
||||
"realpathSync.native": { paths: [0], pathsFirst: false },
|
||||
renameSync: { paths: [0, 1], pathsFirst: true },
|
||||
renameSync: { paths: [0, 1], pathsFirst: true, names: ["oldPath", "newPath"] },
|
||||
rmSync: { paths: [0], pathsFirst: false },
|
||||
rmdirSync: { paths: [0], pathsFirst: true },
|
||||
statSync: { paths: [0], pathsFirst: true },
|
||||
@@ -48,43 +58,66 @@ const FS_URL_PATHS: Readonly<
|
||||
writeFileSync: { paths: [0], pathsFirst: false },
|
||||
};
|
||||
|
||||
/** The fs.promises functions with path parameters, by path indexes. */
|
||||
const FSP_PATHS: Readonly<Record<string, readonly number[]>> = {
|
||||
access: [0],
|
||||
appendFile: [0],
|
||||
chmod: [0],
|
||||
chown: [0],
|
||||
copyFile: [0, 1],
|
||||
lchown: [0],
|
||||
lstat: [0],
|
||||
mkdir: [0],
|
||||
mkdtemp: [0],
|
||||
open: [0],
|
||||
opendir: [0],
|
||||
readFile: [0],
|
||||
readdir: [0],
|
||||
realpath: [0],
|
||||
rename: [0, 1],
|
||||
rm: [0],
|
||||
rmdir: [0],
|
||||
stat: [0],
|
||||
truncate: [0],
|
||||
unlink: [0],
|
||||
writeFile: [0],
|
||||
/** The fs.promises functions with path parameters. */
|
||||
const FSP_PATHS: Readonly<Record<string, FsPathRow>> = {
|
||||
access: { paths: [0], pathsFirst: true },
|
||||
appendFile: { paths: [0], pathsFirst: false },
|
||||
chmod: { paths: [0], pathsFirst: true },
|
||||
chown: { paths: [0], pathsFirst: true },
|
||||
copyFile: { paths: [0, 1], pathsFirst: true },
|
||||
lchown: { paths: [0], pathsFirst: true },
|
||||
lstat: { paths: [0], pathsFirst: true },
|
||||
mkdir: { paths: [0], pathsFirst: false },
|
||||
mkdtemp: { paths: [0], pathsFirst: false },
|
||||
open: { paths: [0], pathsFirst: true },
|
||||
opendir: { paths: [0], pathsFirst: true },
|
||||
readFile: { paths: [0], pathsFirst: false },
|
||||
readdir: { paths: [0], pathsFirst: false },
|
||||
realpath: { paths: [0], pathsFirst: false },
|
||||
rename: { paths: [0, 1], pathsFirst: true },
|
||||
rm: { paths: [0], pathsFirst: true },
|
||||
rmdir: { paths: [0], pathsFirst: true },
|
||||
stat: { paths: [0], pathsFirst: true },
|
||||
truncate: { paths: [0], pathsFirst: true },
|
||||
unlink: { paths: [0], pathsFirst: true },
|
||||
writeFile: { paths: [0], pathsFirst: false },
|
||||
};
|
||||
|
||||
/** What a path argument of an fs call lowers to (Lowerer.fsPathPlans). */
|
||||
export type FsPathPlan =
|
||||
/** The first URL path: the later arguments with effects, the earlier
|
||||
* string paths to check, and a runtime encoding to check, all before the
|
||||
* conversion. */
|
||||
| {
|
||||
kind: "convert";
|
||||
staged: ts.Expression[];
|
||||
checks: { path: ts.Expression; name: string }[];
|
||||
encoding: ts.Expression | null;
|
||||
}
|
||||
/** A string path that a later URL path checks: the local that holds it,
|
||||
* once lowered. */
|
||||
| { kind: "save"; local: string | null }
|
||||
/** A URL path whose conversion error becomes false or a rejection: the
|
||||
* local that holds the conversion's value. */
|
||||
| { kind: "value"; local: string };
|
||||
|
||||
function isUrlArgument(lowerer: Lowerer, node: ts.Expression | undefined): boolean {
|
||||
return node !== undefined && lowerer.mapTypeOf(lowerer.typeOf(node))?.kind === "url";
|
||||
}
|
||||
|
||||
function stripParens(node: ts.Expression): ts.Expression {
|
||||
let e = node;
|
||||
while (ts.isParenthesizedExpression(e)) e = e.expression;
|
||||
return e;
|
||||
}
|
||||
|
||||
/** A literal that Node's option validation accepts before it reads the
|
||||
* path: a string (the checker admits only the declared encodings, flags
|
||||
* and type names), a boolean, an integer in [0, 2^31 - 1] (every numeric
|
||||
* option of these functions accepts that range), undefined or null, or an
|
||||
* object literal of those. */
|
||||
function preValidatedLiteral(node: ts.Expression): boolean {
|
||||
let e = node;
|
||||
while (ts.isParenthesizedExpression(e)) e = e.expression;
|
||||
const e = stripParens(node);
|
||||
if (ts.isStringLiteralLike(e)) return true;
|
||||
if (
|
||||
e.kind === ts.SyntaxKind.TrueKeyword ||
|
||||
@@ -108,39 +141,59 @@ function preValidatedLiteral(node: ts.Expression): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
/** SC2020 when the call passes a URL path in a form whose conversion
|
||||
* order would differ from Node's (see the file comment). */
|
||||
function checkUrlPaths(
|
||||
const HINT = "convert the URL first: fileURLToPath(url) from node:url";
|
||||
|
||||
/** SC2020 for an argument Node validates before the paths that is neither
|
||||
* absent nor a literal passing that validation, other than a string
|
||||
* readFileSync encoding (returned: it is checked before the conversion).
|
||||
* writeFileSync/appendFileSync's data is checked after the path. */
|
||||
function optionsBeforePaths(
|
||||
lowerer: Lowerer,
|
||||
call: ts.CallExpression,
|
||||
module: string,
|
||||
args: readonly ts.Expression[],
|
||||
member: string,
|
||||
): void {
|
||||
const args = call.arguments.nodes;
|
||||
const name = module === "fs/promises" ? `fs.promises.${member}` : member;
|
||||
const hint = "convert the URL first: fileURLToPath(url) from node:url";
|
||||
if (module === "fs/promises") {
|
||||
if ((FSP_PATHS[member] ?? []).some((i) => isUrlArgument(lowerer, args[i])))
|
||||
lowerer.noLowering(`${name} with a URL path`, call, hint);
|
||||
return;
|
||||
row: FsPathRow,
|
||||
name: string,
|
||||
): ts.Expression | null {
|
||||
if (row.pathsFirst) return null;
|
||||
const data = /^(writeFile|appendFile)(Sync)?$/.test(member) ? 1 : -1;
|
||||
let encoding: ts.Expression | null = null;
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const arg = args[i]!;
|
||||
if (row.paths.includes(i) || i === data || preValidatedLiteral(arg)) continue;
|
||||
if (
|
||||
member === "readFileSync" &&
|
||||
i === 1 &&
|
||||
lowerer.mapTypeOf(lowerer.typeOf(arg))?.kind === "string"
|
||||
) {
|
||||
encoding = stripTypeWrappers(arg);
|
||||
continue;
|
||||
}
|
||||
lowerer.noLowering(`${name} with a URL path and options that are not literals`, arg, HINT);
|
||||
}
|
||||
if (member === "existsSync" && isUrlArgument(lowerer, args[0]))
|
||||
lowerer.noLowering(`${name} with a URL path`, call, hint);
|
||||
const row = FS_URL_PATHS[member];
|
||||
if (!row) return;
|
||||
const first = row.paths.find((i) => isUrlArgument(lowerer, args[i]));
|
||||
if (first === undefined) return;
|
||||
if (args.some(ts.isSpreadElement))
|
||||
lowerer.noLowering(`${name} with spread arguments and a URL path`, call);
|
||||
// The runtime checks a string path after the conversion, so a string
|
||||
// path Node checks first cannot precede the URL.
|
||||
if (row.paths.some((i) => i < first && args[i] !== undefined))
|
||||
lowerer.noLowering(`${name} with a string path before a URL path`, call, hint);
|
||||
// Every argument from the URL through the last one with effects is
|
||||
// evaluated ahead of the conversion, in source order: a later argument's
|
||||
// effect (an assignment, say) must not change what an earlier one read.
|
||||
return encoding;
|
||||
}
|
||||
|
||||
/** The arguments after the URL path that are evaluated ahead of the
|
||||
* conversion: every one through the last with effects or that `force`
|
||||
* names, in source order. An object or array literal among them is
|
||||
* SC2020: its members are lowered one by one, so it cannot be evaluated
|
||||
* ahead of the conversion as one value. */
|
||||
function stagedAfter(
|
||||
lowerer: Lowerer,
|
||||
args: readonly ts.Expression[],
|
||||
first: number,
|
||||
name: string,
|
||||
force: (e: ts.Expression, i: number) => boolean,
|
||||
): ts.Expression[] {
|
||||
// Every argument from the URL through the last one with effects (or that
|
||||
// the caller forces) is evaluated ahead of the conversion, in source
|
||||
// order: a later argument's effect (an assignment, say) must not change
|
||||
// what an earlier one read.
|
||||
let last = first;
|
||||
for (let i = first + 1; i < args.length; i++) if (!sideEffectFreeOptionValue(args[i]!)) last = i;
|
||||
for (let i = first + 1; i < args.length; i++) {
|
||||
const e = stripTypeWrappers(args[i]!);
|
||||
if (!sideEffectFreeOptionValue(e) || force(e, i)) last = i;
|
||||
}
|
||||
const staged: ts.Expression[] = [];
|
||||
for (let i = first + 1; i <= last; i++) {
|
||||
// Keyed without type-only wrappers (`satisfies`, `as`, `!`), so a
|
||||
@@ -154,56 +207,190 @@ function checkUrlPaths(
|
||||
? `${name} with a URL path and a literal before a later argument that has effects`
|
||||
: `${name} with a URL path and a later literal that has effects`,
|
||||
e,
|
||||
hint,
|
||||
HINT,
|
||||
);
|
||||
}
|
||||
staged.push(e);
|
||||
}
|
||||
if (staged.length > 0) {
|
||||
lowerer.stagedAfterPath.set(args[first]!, staged);
|
||||
for (const e of staged) lowerer.stagedArguments.set(e, null);
|
||||
}
|
||||
if (row.pathsFirst) return;
|
||||
// writeFileSync/appendFileSync's data is checked after the path.
|
||||
const data = member === "writeFileSync" || member === "appendFileSync" ? 1 : -1;
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
if (row.paths.includes(i) || i === data || preValidatedLiteral(args[i]!)) continue;
|
||||
lowerer.noLowering(`${name} with a URL path and options that are not literals`, args[i]!, hint);
|
||||
}
|
||||
return staged;
|
||||
}
|
||||
|
||||
/** Fences URL paths that cannot convert in Node's order: the check every
|
||||
* fs and fs.promises call runs before lowering its arguments. */
|
||||
/** Plans the URL paths of a synchronous fs call (see the file comment):
|
||||
* the check every fs call runs before lowering its arguments. */
|
||||
export function checkFsUrlPaths(
|
||||
lowerer: Lowerer,
|
||||
call: ts.CallExpression,
|
||||
bi: { module: string; member: string },
|
||||
): void {
|
||||
if (bi.module === "fs" || bi.module === "fs/promises")
|
||||
checkUrlPaths(lowerer, call, bi.module, bi.member);
|
||||
if (bi.module !== "fs") return;
|
||||
const row = FS_URL_PATHS[bi.member];
|
||||
if (!row) return;
|
||||
const args = call.arguments.nodes;
|
||||
const first = row.paths.find((i) => isUrlArgument(lowerer, args[i]));
|
||||
if (first === undefined || lowerer.fsPathPlans.has(stripParens(args[first]!))) return;
|
||||
const name = bi.member;
|
||||
if (args.some(ts.isSpreadElement))
|
||||
lowerer.noLowering(`${name} with spread arguments and a URL path`, call);
|
||||
const checks: { path: ts.Expression; name: string }[] = [];
|
||||
for (const i of row.paths) {
|
||||
if (i >= first || args[i] === undefined) continue;
|
||||
const path = stripParens(args[i]!);
|
||||
checks.push({ path, name: row.names?.[i] ?? "path" });
|
||||
lowerer.fsPathPlans.set(path, { kind: "save", local: null });
|
||||
}
|
||||
const encoding = optionsBeforePaths(lowerer, args, bi.member, row, name);
|
||||
const staged = stagedAfter(lowerer, args, first, name, (e) => e === encoding);
|
||||
for (const e of staged) lowerer.stagedArguments.set(e, null);
|
||||
lowerer.fsPathPlans.set(stripParens(args[first]!), { kind: "convert", staged, checks, encoding });
|
||||
}
|
||||
|
||||
/** existsSync and the fs.promises functions with URL paths: each URL
|
||||
* converts to a value (url.fileURLToPathValue) after the arguments are
|
||||
* evaluated, and the call runs on the converted paths only when every
|
||||
* conversion produced a string; otherwise existsSync answers false and an
|
||||
* fs.promises function a promise rejected with the first conversion's
|
||||
* error. `lowerCall` lowers the call itself, whose URL paths then read the
|
||||
* converted values. Null for every other call. */
|
||||
export function lowerFallibleFsUrlCall(
|
||||
lowerer: Lowerer,
|
||||
call: ts.CallExpression,
|
||||
bi: { module: string; member: string },
|
||||
lowerCall: () => IrExpr,
|
||||
): IrExpr | null {
|
||||
const row =
|
||||
bi.module === "fs/promises"
|
||||
? FSP_PATHS[bi.member]
|
||||
: bi.module === "fs" && bi.member === "existsSync"
|
||||
? ({ paths: [0], pathsFirst: true } satisfies FsPathRow)
|
||||
: undefined;
|
||||
if (!row) return null;
|
||||
const args = call.arguments.nodes;
|
||||
const urls = row.paths.filter((i) => isUrlArgument(lowerer, args[i]));
|
||||
if (urls.length === 0 || lowerer.fallibleFsCalls.has(call)) return null;
|
||||
const name = bi.module === "fs/promises" ? `fs.promises.${bi.member}` : bi.member;
|
||||
if (args.some(ts.isSpreadElement))
|
||||
lowerer.noLowering(`${name} with spread arguments and a URL path`, call);
|
||||
const first = urls[0]!;
|
||||
// A string path before the URL would be checked in the call itself,
|
||||
// after the conversion.
|
||||
if (row.paths.some((i) => i < first && args[i] !== undefined))
|
||||
lowerer.noLowering(`${name} with a string path before a URL path`, call, HINT);
|
||||
if (optionsBeforePaths(lowerer, args, bi.member, row, name) !== null)
|
||||
lowerer.noLowering(`${name} with a URL path and options that are not literals`, args[1]!, HINT);
|
||||
const loc = locOf(call);
|
||||
const stmts: IrStmt[] = [];
|
||||
const values = new Map<number, string>();
|
||||
const save = (value: IrExpr, label: string, at: ts.Node): string => {
|
||||
const slot = lowerer.declareHiddenLocal(label, value.type);
|
||||
stmts.push({ kind: "varDecl", localId: slot.id, init: value, loc: locOf(at) });
|
||||
return slot.id;
|
||||
};
|
||||
values.set(first, save(lowerer.lowerExprExpecting(args[first]!, URL_T), "%fsUrl", args[first]!));
|
||||
const staged = stagedAfter(lowerer, args, first, name, (_e, i) => urls.includes(i));
|
||||
for (const e of staged) {
|
||||
// A call lowered again (an array-literal element) evaluates the
|
||||
// argument anew; the slot an earlier lowering saved it in is gone.
|
||||
lowerer.stagedArguments.delete(e);
|
||||
const value = lowerer.lowerExpr(e);
|
||||
const slot = save(value, "%fsArg", e);
|
||||
lowerer.stagedArguments.set(e, { localId: slot, type: value.type });
|
||||
const index = args.findIndex((arg) => stripTypeWrappers(arg) === e);
|
||||
if (urls.includes(index)) values.set(index, slot);
|
||||
}
|
||||
const results: string[] = [];
|
||||
for (const i of urls) {
|
||||
const url = varRef(values.get(i)!, URL_T, loc);
|
||||
const converted: IrExpr = {
|
||||
kind: "libCall",
|
||||
fn: "url.fileURLToPathValue",
|
||||
args: [url],
|
||||
type: DYN,
|
||||
loc,
|
||||
};
|
||||
const local = save(converted, "%fsPathValue", args[i]!);
|
||||
lowerer.fsPathPlans.set(stripParens(args[i]!), { kind: "value", local });
|
||||
results.push(local);
|
||||
}
|
||||
lowerer.fallibleFsCalls.add(call);
|
||||
let inner: IrExpr;
|
||||
try {
|
||||
inner = lowerCall();
|
||||
} finally {
|
||||
lowerer.fallibleFsCalls.delete(call);
|
||||
}
|
||||
let result = inner;
|
||||
for (let k = results.length - 1; k >= 0; k--) {
|
||||
const value = varRef(results[k]!, DYN, loc);
|
||||
const failed: IrExpr =
|
||||
bi.module === "fs/promises"
|
||||
? { kind: "intrinsic", name: "promise.reject", args: [value], type: inner.type, loc }
|
||||
: boolLit(false, loc);
|
||||
result = {
|
||||
kind: "ternary",
|
||||
cond: { kind: "dynTest", test: "string", value, type: BOOL, loc },
|
||||
then: result,
|
||||
else_: failed,
|
||||
type: inner.type,
|
||||
loc,
|
||||
};
|
||||
}
|
||||
return { kind: "seqExpr", stmts, result, type: inner.type, loc };
|
||||
}
|
||||
|
||||
/** An fs path argument as a string: a URL converts with fileURLToPath's
|
||||
* conversion (url.fileURLToPathUrl), which throws Node's errors for other
|
||||
* schemes, hosts and encoded separators. */
|
||||
* schemes, hosts and encoded separators, after the checks its plan names. */
|
||||
export function lowerFsPath(lowerer: Lowerer, node: ts.Expression): IrExpr {
|
||||
if (!isUrlArgument(lowerer, node)) return lowerer.lowerExprExpecting(node, STRING);
|
||||
const loc = locOf(node);
|
||||
const plan = lowerer.fsPathPlans.get(stripParens(node));
|
||||
if (plan?.kind === "value")
|
||||
return { kind: "dynCheck", value: varRef(plan.local, DYN, loc), type: STRING, loc };
|
||||
if (!isUrlArgument(lowerer, node)) {
|
||||
const value = lowerer.lowerExprExpecting(node, STRING);
|
||||
if (plan?.kind !== "save") return value;
|
||||
const slot = lowerer.declareHiddenLocal("%fsPath", STRING);
|
||||
plan.local = slot.id;
|
||||
return {
|
||||
kind: "seqExpr",
|
||||
stmts: [{ kind: "varDecl", localId: slot.id, init: value, loc }],
|
||||
result: varRef(slot.id, STRING, loc),
|
||||
type: STRING,
|
||||
loc,
|
||||
};
|
||||
}
|
||||
const url = lowerer.lowerExprExpecting(node, URL_T);
|
||||
const staged = lowerer.stagedAfterPath.get(node);
|
||||
if (staged === undefined)
|
||||
if (plan?.kind !== "convert")
|
||||
return { kind: "libCall", fn: "url.fileURLToPathUrl", args: [url], type: STRING, loc };
|
||||
// The URL and the later arguments with effects, in source order, then
|
||||
// the conversion.
|
||||
// the checks Node runs first, then the conversion.
|
||||
const saved = lowerer.declareHiddenLocal("%fsUrl", URL_T);
|
||||
const stmts: IrStmt[] = [{ kind: "varDecl", localId: saved.id, init: url, loc }];
|
||||
for (const arg of staged) {
|
||||
for (const arg of plan.staged) {
|
||||
lowerer.stagedArguments.delete(arg);
|
||||
const value = lowerer.lowerExpr(arg);
|
||||
const slot = lowerer.declareHiddenLocal("%fsArg", value.type);
|
||||
stmts.push({ kind: "varDecl", localId: slot.id, init: value, loc: locOf(arg) });
|
||||
lowerer.stagedArguments.set(arg, { localId: slot.id, type: value.type });
|
||||
}
|
||||
const check = (fn: "fs.checkPath" | "fs.checkReadEncoding", args: IrExpr[]): void => {
|
||||
stmts.push({ kind: "exprStmt", expr: { kind: "libCall", fn, args, type: VOID, loc }, loc });
|
||||
};
|
||||
for (const { path, name } of plan.checks) {
|
||||
const saved = lowerer.fsPathPlans.get(path);
|
||||
if (saved?.kind !== "save" || saved.local === null)
|
||||
throw new InternalCompilerError("an fs path checked before it was lowered");
|
||||
check("fs.checkPath", [
|
||||
varRef(saved.local, STRING, loc),
|
||||
{ kind: "strLit", value: name, type: STRING, loc },
|
||||
]);
|
||||
}
|
||||
if (plan.encoding !== null) {
|
||||
const slot = lowerer.stagedArguments.get(plan.encoding);
|
||||
if (!slot) throw new InternalCompilerError("an fs encoding checked before it was saved");
|
||||
check("fs.checkReadEncoding", [
|
||||
lowerer.coerceToExpected(varRef(slot.localId, slot.type, loc), STRING),
|
||||
]);
|
||||
}
|
||||
return {
|
||||
kind: "seqExpr",
|
||||
stmts,
|
||||
@@ -219,7 +406,12 @@ export function lowerFsPath(lowerer: Lowerer, node: ts.Expression): IrExpr {
|
||||
};
|
||||
}
|
||||
|
||||
/** Whether `index` is a path parameter of the fs function `member`. */
|
||||
export function isFsPathParam(member: string, index: number): boolean {
|
||||
return FS_URL_PATHS[member]?.paths.includes(index) === true;
|
||||
/** Whether `index` is a path parameter of the fs or fs.promises function
|
||||
* `member`. */
|
||||
export function isFsPathParam(module: string, member: string, index: number): boolean {
|
||||
if (module === "fs/promises") return FSP_PATHS[member]?.paths.includes(index) === true;
|
||||
if (module !== "fs") return false;
|
||||
return (
|
||||
(member === "existsSync" && index === 0) || FS_URL_PATHS[member]?.paths.includes(index) === true
|
||||
);
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ import {
|
||||
lowerFsWriteOptionsCall,
|
||||
lowerFsReadPathCall,
|
||||
} from "./filesystem-calls.js";
|
||||
import { checkFsUrlPaths, isFsPathParam, lowerFsPath } from "./fs-paths.js";
|
||||
import { checkFsUrlPaths, isFsPathParam, lowerFallibleFsUrlCall, lowerFsPath } from "./fs-paths.js";
|
||||
import { lowerBufferEncodingCall } from "./text-codecs.js";
|
||||
import { lowerUtilTypeCall } from "./util-types.js";
|
||||
import { InternalCompilerError } from "../../../errors.js";
|
||||
@@ -59,6 +59,10 @@ export function lowerBuiltinModuleCall(
|
||||
loc: SrcLoc,
|
||||
): IrExpr {
|
||||
const name = ts.getTextOfNode(expr.expression);
|
||||
const fallible = lowerFallibleFsUrlCall(lowerer, expr, bi, () =>
|
||||
lowerBuiltinModuleCall(lowerer, expr, bi, fn, loc),
|
||||
);
|
||||
if (fallible) return fallible;
|
||||
checkFsUrlPaths(lowerer, expr, bi);
|
||||
if (bi.module === "util/types") {
|
||||
return lowerUtilTypeCall(lowerer, expr, bi, loc, name);
|
||||
@@ -258,7 +262,7 @@ export function lowerBuiltinModuleCall(
|
||||
bi.member === "readFile" &&
|
||||
expr.arguments.nodes.length === 1
|
||||
) {
|
||||
const path = lowerer.lowerExprExpecting(expr.arguments.nodes[0]!, STRING);
|
||||
const path = lowerFsPath(lowerer, expr.arguments.nodes[0]!);
|
||||
return {
|
||||
kind: "libCall",
|
||||
fn: "fsp.readFileBytes",
|
||||
@@ -473,7 +477,7 @@ export function lowerBuiltinModuleCall(
|
||||
args = lowerer.completeArgs(expr.arguments.nodes, shapes, loc, expr);
|
||||
} else {
|
||||
args = expr.arguments.nodes.map((a, i) =>
|
||||
bi.module === "fs" && isFsPathParam(bi.member, i)
|
||||
isFsPathParam(bi.module, bi.member, i)
|
||||
? lowerFsPath(lowerer, a)
|
||||
: lowerer.lowerExprExpecting(a, fn.params[i]),
|
||||
);
|
||||
|
||||
@@ -28,8 +28,10 @@ import {
|
||||
isModuleExportsAccess,
|
||||
locOf,
|
||||
npmStaticDepSf7,
|
||||
requireBindingEarlyUse7,
|
||||
requireSpecOf,
|
||||
resolveImport,
|
||||
splitRequireCallOf,
|
||||
} from "../program.js";
|
||||
import { createRequireCalleeFileOf } from "./builtins/module-bindings.js";
|
||||
import { isCjsRequireGlobal } from "./lower-node-module.js";
|
||||
@@ -43,6 +45,332 @@ export interface InlineRequire {
|
||||
dep: ts.SourceFile;
|
||||
}
|
||||
|
||||
/** A top-level `var m; m = require("./x")` binding. Node evaluates the
|
||||
* require at the assignment; the binding is alias plumbing exactly like
|
||||
* `const m = require("./x")` for every later read. */
|
||||
export interface SplitRequireBinding {
|
||||
decl: ts.VariableDeclaration;
|
||||
assign: ts.BinaryExpression;
|
||||
call: ts.CallExpression;
|
||||
spec: string;
|
||||
dep: ts.SourceFile;
|
||||
}
|
||||
|
||||
function symbolOfIdentifierValue(lowerer: Lowerer, ident: ts.Identifier): ts.Symbol | undefined {
|
||||
const parent = ident.parent;
|
||||
// A destructuring shorthand target resolves to the property symbol at
|
||||
// the name, but reads/writes the variable through its value symbol.
|
||||
if (ts.isShorthandPropertyAssignment(parent) && parent.name === ident) {
|
||||
return (
|
||||
lowerer.checker.getShorthandAssignmentValueSymbol(parent) ??
|
||||
lowerer.checker.getSymbolAtLocation(ident)
|
||||
);
|
||||
}
|
||||
return lowerer.checker.getSymbolAtLocation(ident);
|
||||
}
|
||||
|
||||
function destructuringContainerOf(node: ts.Node): ts.Node | null {
|
||||
const parent = node.parent;
|
||||
if (ts.isShorthandPropertyAssignment(parent) && parent.name === node) return parent;
|
||||
if (ts.isPropertyAssignment(parent) && parent.initializer === node) return parent;
|
||||
if (ts.isSpreadElement(parent) && parent.expression === node) return parent;
|
||||
if (ts.isSpreadAssignment(parent) && parent.expression === node) return parent;
|
||||
return null;
|
||||
}
|
||||
|
||||
function writeTargetOf(node: ts.Node): ts.Node | null {
|
||||
let target = node;
|
||||
for (;;) {
|
||||
const parent = target.parent;
|
||||
if (
|
||||
ts.isParenthesizedExpression(parent) ||
|
||||
ts.isArrayLiteralExpression(parent) ||
|
||||
ts.isObjectLiteralExpression(parent)
|
||||
) {
|
||||
target = parent;
|
||||
continue;
|
||||
}
|
||||
const container = destructuringContainerOf(target);
|
||||
if (container === null) break;
|
||||
target = container;
|
||||
}
|
||||
const parent = target.parent;
|
||||
if (
|
||||
ts.isBinaryExpression(parent) &&
|
||||
parent.left === target &&
|
||||
ts.isAssignmentOperator(parent.operatorToken.kind)
|
||||
)
|
||||
return parent;
|
||||
if (
|
||||
(ts.isPrefixUnaryExpression(parent) || ts.isPostfixUnaryExpression(parent)) &&
|
||||
parent.operand === target &&
|
||||
(parent.operator === ts.SyntaxKind.PlusPlusToken ||
|
||||
parent.operator === ts.SyntaxKind.MinusMinusToken)
|
||||
)
|
||||
return parent;
|
||||
if ((ts.isForInStatement(parent) || ts.isForOfStatement(parent)) && parent.initializer === target)
|
||||
return parent;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The split form of a top-level require binding: `var m; m = require("./x")`.
|
||||
* Exactly one write, at a top-level `m = require("<literal>")` statement.
|
||||
* Null for the ordinary `const m = require("./x")` declaration and for
|
||||
* every form that needs runtime module selection. */
|
||||
export function splitRequireBindingOf(
|
||||
lowerer: Lowerer,
|
||||
decl: ts.VariableDeclaration,
|
||||
): SplitRequireBinding | null {
|
||||
// Cheap shape gate before the cache: ordinary declarations never enter the
|
||||
// per-Lowerer map.
|
||||
if (decl.initializer !== undefined || !ts.isIdentifier(decl.name)) return null;
|
||||
const list = decl.parent as ts.VariableDeclarationList;
|
||||
if ((list.flags & ts.NodeFlags.Const) !== 0) return null;
|
||||
const stmt = list.parent;
|
||||
if (!ts.isVariableStatement(stmt) || !ts.isSourceFile(stmt.parent)) return null;
|
||||
const cached = lowerer.cjsSplitRequireBindings.get(decl);
|
||||
if (cached !== undefined) return cached;
|
||||
const result = computeSplitRequireBinding(lowerer, decl);
|
||||
lowerer.cjsSplitRequireBindings.set(decl, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
function computeSplitRequireBinding(
|
||||
lowerer: Lowerer,
|
||||
decl: ts.VariableDeclaration,
|
||||
): SplitRequireBinding | null {
|
||||
const sf = ts.getSourceFileOfNode(decl);
|
||||
if (!isCjsJsFile(sf, lowerer.program)) return null;
|
||||
if (!sf.text.includes("require")) return null;
|
||||
const symbol = lowerer.checker.getSymbolAtLocation(decl.name);
|
||||
if (symbol === undefined) return null;
|
||||
// Merged declarations make the binding's initialization order ambiguous;
|
||||
// keep ordinary storage instead of guessing.
|
||||
let declarations = 0;
|
||||
for (const other of symbol.declarations) {
|
||||
if (!ts.isVariableDeclaration(other) || ++declarations > 1) return null;
|
||||
}
|
||||
if (declarations !== 1) return null;
|
||||
|
||||
// Find the one top-level `m = ...` statement first: most uninitialized
|
||||
// variables never reach that shape, so they avoid the full-file write scan.
|
||||
let assign: ts.BinaryExpression | null = null;
|
||||
for (const stmt of sf.statements.nodes) {
|
||||
if (!ts.isExpressionStatement(stmt)) continue;
|
||||
const expr = stmt.expression;
|
||||
if (
|
||||
!ts.isBinaryExpression(expr) ||
|
||||
expr.operatorToken.kind !== ts.SyntaxKind.EqualsToken ||
|
||||
!ts.isIdentifier(expr.left) ||
|
||||
expr.left.text !== decl.name.text ||
|
||||
lowerer.checker.getSymbolAtLocation(expr.left) !== symbol
|
||||
)
|
||||
continue;
|
||||
if (assign !== null) return null;
|
||||
assign = expr;
|
||||
}
|
||||
if (assign === null) return null;
|
||||
|
||||
const req = inlineProgramRequireOf(lowerer, assign.right);
|
||||
if (req === null) return null;
|
||||
// Preflight treats the same bindings as require declarations (module edge,
|
||||
// cycle admission, early-read fence); a binding it does not know keeps
|
||||
// ordinary storage.
|
||||
if (splitRequireCallOf(lowerer.program, decl) !== req.call) return null;
|
||||
|
||||
// Any other write makes the value depend on runtime control flow.
|
||||
let writes = 0;
|
||||
ts.walkPreorder(sf, (node) => {
|
||||
if (!ts.isIdentifier(node) || node.text !== decl.name.text) return;
|
||||
if (symbolOfIdentifierValue(lowerer, node) !== symbol) return;
|
||||
if (writeTargetOf(node) === null) return;
|
||||
if (++writes > 1) return "stop";
|
||||
});
|
||||
if (writes !== 1) return null;
|
||||
|
||||
return { decl, assign, call: req.call, spec: req.spec, dep: req.dep };
|
||||
}
|
||||
|
||||
/** The split binding an identifier names, or null. */
|
||||
export function splitRequireBindingOfIdent(
|
||||
lowerer: Lowerer,
|
||||
ident: ts.Identifier,
|
||||
): SplitRequireBinding | null {
|
||||
const symbol = symbolOfIdentifierValue(lowerer, ident);
|
||||
return symbol === undefined ? null : splitBindingOfSymbol(lowerer, symbol);
|
||||
}
|
||||
|
||||
/** The exact top-level assignment statement that initializes `expr`, or null. */
|
||||
export function splitRequireAssignmentOf(
|
||||
lowerer: Lowerer,
|
||||
expr: ts.Expression,
|
||||
): SplitRequireBinding | null {
|
||||
if (
|
||||
!ts.isBinaryExpression(expr) ||
|
||||
expr.operatorToken.kind !== ts.SyntaxKind.EqualsToken ||
|
||||
!ts.isIdentifier(expr.left)
|
||||
)
|
||||
return null;
|
||||
const bindingOfIdent = splitRequireBindingOfIdent(lowerer, expr.left);
|
||||
return bindingOfIdent !== null && bindingOfIdent.assign === expr ? bindingOfIdent : null;
|
||||
}
|
||||
|
||||
/** The whole-export symbol a module's `module.exports = <value>` names,
|
||||
* or null when the module is a table. */
|
||||
export function wholeExportSymbolOfModule(lowerer: Lowerer, dep: ts.SourceFile): ts.Symbol | null {
|
||||
const cached = lowerer.cjsWholeExportSymbols.get(dep);
|
||||
if (cached !== undefined) return cached;
|
||||
if (cjsNamespaceModule(lowerer, dep)) {
|
||||
lowerer.cjsWholeExportSymbols.set(dep, null);
|
||||
return null;
|
||||
}
|
||||
const moduleSymbol = lowerer.checker.getSymbolAtLocation(dep);
|
||||
let symbol = moduleSymbol?.getExports()?.get("export=" as ts.__String);
|
||||
if (symbol === undefined) {
|
||||
lowerer.cjsWholeExportSymbols.set(dep, null);
|
||||
return null;
|
||||
}
|
||||
if (symbol.flags & ts.SymbolFlags.Alias) symbol = lowerer.checker.getAliasedSymbol(symbol);
|
||||
lowerer.cjsWholeExportSymbols.set(dep, symbol);
|
||||
return symbol;
|
||||
}
|
||||
|
||||
function splitBindingOfSymbol(lowerer: Lowerer, symbol: ts.Symbol): SplitRequireBinding | null {
|
||||
const decl = symbol.declarations.find(ts.isVariableDeclaration);
|
||||
return decl === undefined ? null : splitRequireBindingOf(lowerer, decl);
|
||||
}
|
||||
|
||||
/** The target whole-export symbol behind a split-binding symbol. */
|
||||
function splitWholeExportSymbolOfSymbol(lowerer: Lowerer, symbol: ts.Symbol): ts.Symbol | null {
|
||||
const binding = splitBindingOfSymbol(lowerer, symbol);
|
||||
return binding === null ? null : wholeExportSymbolOfModule(lowerer, binding.dep);
|
||||
}
|
||||
|
||||
/** True when a CommonJS module has a live member export (`exports.x` or
|
||||
* `module.exports.x`) after all `module.exports =` replacements. Those
|
||||
* members need a mutable whole-export root. */
|
||||
export function cjsHasLiveMemberExports(lowerer: Lowerer, sf: ts.SourceFile): boolean {
|
||||
const cached = lowerer.cjsLiveMemberExports.get(sf);
|
||||
if (cached !== undefined) return cached;
|
||||
const stmts = sf.statements.nodes;
|
||||
let lastTable = -1;
|
||||
for (let i = 0; i < stmts.length; i++) {
|
||||
if (cjsExportAssignmentOf(stmts[i]!)?.kind === "table") lastTable = i;
|
||||
}
|
||||
let live = false;
|
||||
// Only members attached after the last replacement survive in Node.
|
||||
if (lastTable >= 0) {
|
||||
for (let i = lastTable + 1; i < stmts.length; i++) {
|
||||
const stmt = stmts[i]!;
|
||||
if (cjsExportAssignmentOf(stmt)?.kind === "member" && cjsExportDiscardReason(stmt) === null) {
|
||||
live = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
lowerer.cjsLiveMemberExports.set(sf, live);
|
||||
return live;
|
||||
}
|
||||
|
||||
/** The wrapper's export= symbol when a split binding is re-exported whole
|
||||
* (`module.exports = m`) and that assignment owns storage for later member
|
||||
* writes. Importers must read the wrapper's storage, not the split
|
||||
* binding's underlying value. */
|
||||
function splitWholeExportStorageSymbolOf(lowerer: Lowerer, symbol: ts.Symbol): ts.Symbol | null {
|
||||
const binding = splitBindingOfSymbol(lowerer, symbol);
|
||||
if (binding === null) return null;
|
||||
if (wholeExportSymbolOfModule(lowerer, binding.dep) === null) return null;
|
||||
const sf = ts.getSourceFileOfNode(binding.decl);
|
||||
if (!cjsHasLiveMemberExports(lowerer, sf)) return null;
|
||||
const whole = cjsWholeExportValueOf(sf);
|
||||
if (whole === null) return null;
|
||||
let rhs: ts.Expression = whole.rhs;
|
||||
while (ts.isParenthesizedExpression(rhs)) rhs = rhs.expression;
|
||||
if (!ts.isIdentifier(rhs) || lowerer.checker.getSymbolAtLocation(rhs) !== symbol) return null;
|
||||
const moduleSymbol = lowerer.checker.getSymbolAtLocation(sf);
|
||||
let exportSymbol = moduleSymbol?.getExports()?.get("export=" as ts.__String);
|
||||
if (exportSymbol === undefined) return null;
|
||||
if (exportSymbol.flags & ts.SymbolFlags.Alias)
|
||||
exportSymbol = lowerer.checker.getAliasedSymbol(exportSymbol);
|
||||
return exportSymbol;
|
||||
}
|
||||
|
||||
/** The source file whose `module.exports =` assignment declares `symbol`. */
|
||||
function moduleExportSourceFileOf(symbol: ts.Symbol): ts.SourceFile | null {
|
||||
for (const decl of symbol.declarations) {
|
||||
if (
|
||||
ts.isBinaryExpression(decl) &&
|
||||
isModuleExportsAccess(decl.left) &&
|
||||
ts.isExpressionStatement(decl.parent) &&
|
||||
ts.isSourceFile(decl.parent.parent)
|
||||
)
|
||||
return decl.getSourceFile();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** One hop from a wrapper's export= symbol to the value it re-exports
|
||||
* (`module.exports = require(...)` or `= <split binding>`), or null. A
|
||||
* wrapper with live members owns storage for them, so it is not followed. */
|
||||
function wholeReexportTargetOf(lowerer: Lowerer, symbol: ts.Symbol): ts.Symbol | null {
|
||||
const sf = moduleExportSourceFileOf(symbol);
|
||||
if (sf === null) return null;
|
||||
// A wrapper with live members owns storage for them; importers must keep
|
||||
// reading that root rather than the inner value.
|
||||
if (cjsHasLiveMemberExports(lowerer, sf)) return null;
|
||||
const whole = cjsWholeExportValueOf(sf);
|
||||
if (whole === null) return null;
|
||||
const inner = inlineProgramRequireOf(lowerer, whole.rhs);
|
||||
if (inner !== null) return wholeExportSymbolOfModule(lowerer, inner.dep);
|
||||
let rhs: ts.Expression = whole.rhs;
|
||||
while (ts.isParenthesizedExpression(rhs)) rhs = rhs.expression;
|
||||
if (!ts.isIdentifier(rhs)) return null;
|
||||
const rhsSymbol = lowerer.checker.getSymbolAtLocation(rhs);
|
||||
return rhsSymbol === undefined ? null : splitWholeExportSymbolOfSymbol(lowerer, rhsSymbol);
|
||||
}
|
||||
|
||||
/** Follow split bindings and whole re-exports to the ultimate value symbol. */
|
||||
function followSplitWholeTarget(lowerer: Lowerer, candidate: ts.Symbol | null): ts.Symbol | null {
|
||||
if (candidate === null) return null;
|
||||
let symbol = candidate;
|
||||
const seen = new Set<ts.Symbol>();
|
||||
for (let depth = 0; depth < 32 && !seen.has(symbol); depth++) {
|
||||
seen.add(symbol);
|
||||
const next =
|
||||
splitWholeExportSymbolOfSymbol(lowerer, symbol) ?? wholeReexportTargetOf(lowerer, symbol);
|
||||
if (next === null) break;
|
||||
symbol = next;
|
||||
}
|
||||
return symbol;
|
||||
}
|
||||
|
||||
/** The target whole-export symbol behind `module.exports = <split binding>`,
|
||||
* letting importers of that wrapper resolve to the real value symbol. */
|
||||
export function splitWholeExportAliasTargetOf(
|
||||
lowerer: Lowerer,
|
||||
symbol: ts.Symbol,
|
||||
): ts.Symbol | null {
|
||||
const storage = splitWholeExportStorageSymbolOf(lowerer, symbol);
|
||||
if (storage !== null) return followSplitWholeTarget(lowerer, storage);
|
||||
const direct = followSplitWholeTarget(lowerer, splitWholeExportSymbolOfSymbol(lowerer, symbol));
|
||||
if (direct !== null) return direct;
|
||||
return followSplitWholeTarget(lowerer, wholeReexportTargetOf(lowerer, symbol));
|
||||
}
|
||||
|
||||
/** The first read of a split binding that code before its assignment can
|
||||
* reach, using the same reachability model as ordinary require bindings. */
|
||||
export function splitRequireEarlyReadOf(
|
||||
lowerer: Lowerer,
|
||||
binding: SplitRequireBinding,
|
||||
): ts.Identifier | null {
|
||||
const sf = ts.getSourceFileOfNode(binding.decl);
|
||||
const stmt = binding.assign.parent;
|
||||
// `binding` was recognized only from a top-level `m = require(...)`
|
||||
// statement, so the statement index is always present.
|
||||
const index = sf.statements.nodes.indexOf(stmt as ts.ExpressionStatement);
|
||||
return requireBindingEarlyUse7(lowerer.program, sf, index, binding.decl, []);
|
||||
}
|
||||
|
||||
/** A `require("<literal>")` call of the CommonJS global in a CommonJS JS
|
||||
* file whose target is a compiled program module (relative, aliased, or an
|
||||
* opted-in --npm-static package). Builtins, JSON documents and
|
||||
@@ -108,13 +436,6 @@ export function inlineNamespaceRequireOf(
|
||||
/** `value` evaluated after the required module's run-once %init (and its
|
||||
* module-registry link) at the require's own position. */
|
||||
export function withRequireInit(lowerer: Lowerer, req: InlineRequire, value: IrExpr): IrExpr {
|
||||
if (lowerer.inlineRequireCycleCalls.has(req.call)) {
|
||||
lowerer.unsupported(
|
||||
"SC1090",
|
||||
req.call,
|
||||
`require() of '${req.spec}' while it is still evaluating (a require cycle: Node answers its partial exports, which the static export table does not model)`,
|
||||
);
|
||||
}
|
||||
// Every inline program require is a preflight module edge, so its module
|
||||
// has an initializer; never read its exports without evaluating it.
|
||||
if (!lowerer.initNameOf.has(req.dep)) {
|
||||
|
||||
@@ -717,6 +717,105 @@ export function classForInHasKey(
|
||||
return { kind: "call", callee: name, args: [value, key], type: BOOL, loc };
|
||||
}
|
||||
|
||||
/** Box class instances at their exact class. `%dyn.class.normalize` turns a
|
||||
* capsule of a class with subclasses into a capsule of the instance's own
|
||||
* class before any member table reads it, so every such box was followed
|
||||
* by a second capsule. Each conversion of a value whose static class has a
|
||||
* normalization branch now selects the exact class at the conversion, with
|
||||
* the same tests in the same order (%dyn.class.boxExact:C), and the
|
||||
* normalization of the resulting capsule falls through. Only JavaScript
|
||||
* class hierarchies, whose instances live in untyped code, take the exact
|
||||
* box. */
|
||||
export function boxClassInstancesExactly(lowerer: Lowerer, functions: IrFunction[]): void {
|
||||
const normalize = lowerer.liftedFnNamed("%dyn.class.normalize");
|
||||
if (!normalize) return;
|
||||
// Static class → its constructible descendants in normalization order.
|
||||
const branches = new Map<string, string[]>();
|
||||
for (const stmt of normalize.body) {
|
||||
if (stmt.kind !== "if" || stmt.cond.kind !== "libCall" || stmt.cond.fn !== "dyn.typedRefIs")
|
||||
continue;
|
||||
const key = stmt.cond.args[1];
|
||||
if (key?.kind !== "strLit" || !key.value.startsWith("object:")) continue;
|
||||
const children: string[] = [];
|
||||
for (const inner of stmt.then) {
|
||||
if (inner.kind !== "if" || inner.cond.kind !== "instanceOf") continue;
|
||||
children.push(inner.cond.className);
|
||||
}
|
||||
// TypeScript hierarchies keep their static-class capsules: their boxes
|
||||
// are rarer, and an exact box would emit each subclass's checked view.
|
||||
const className = key.value.slice("object:".length);
|
||||
const decl = lowerer.classes.get(className)?.decl;
|
||||
if (!decl || !isJsSourceFile(ts.getSourceFileOfNode(decl))) continue;
|
||||
if (children.length) branches.set(className, children);
|
||||
}
|
||||
if (branches.size === 0) return;
|
||||
const loc = normalize.loc;
|
||||
const helpers = new Map<string, string>();
|
||||
const helperFor = (className: string): string => {
|
||||
const known = helpers.get(className);
|
||||
if (known !== undefined) return known;
|
||||
const name = `%dyn.class.boxExact:${className}`;
|
||||
helpers.set(className, name);
|
||||
const type: IrType = { kind: "object", className };
|
||||
const value = varRef("value", type, loc);
|
||||
functions.push({
|
||||
name,
|
||||
params: [{ localId: "value", name: "value", type }],
|
||||
returnType: DYN,
|
||||
locals: [{ id: "value", name: "value", type, mutable: false }],
|
||||
body: [
|
||||
...branches.get(className)!.map((child): IrStmt => ({
|
||||
kind: "if",
|
||||
cond: { kind: "instanceOf", value, className: child, type: BOOL, loc },
|
||||
then: [
|
||||
{
|
||||
kind: "return",
|
||||
value: {
|
||||
kind: "dynFrom",
|
||||
value: {
|
||||
kind: "downcast",
|
||||
value,
|
||||
type: { kind: "object", className: child },
|
||||
loc,
|
||||
},
|
||||
type: DYN,
|
||||
loc,
|
||||
},
|
||||
loc,
|
||||
},
|
||||
],
|
||||
else_: null,
|
||||
loc,
|
||||
})),
|
||||
{ kind: "return", value: { kind: "dynFrom", value, type: DYN, loc }, loc },
|
||||
],
|
||||
loc,
|
||||
});
|
||||
return name;
|
||||
};
|
||||
const rewrite = (fn: IrFunction): void => {
|
||||
fn.body = transformStmtList(fn.body, {
|
||||
stmt: (statement) => statement,
|
||||
expr: (expression) =>
|
||||
expression.kind === "dynFrom" &&
|
||||
expression.value.type.kind === "object" &&
|
||||
branches.has(expression.value.type.className)
|
||||
? {
|
||||
kind: "call",
|
||||
callee: helperFor(expression.value.type.className),
|
||||
args: [expression.value],
|
||||
type: DYN,
|
||||
loc: expression.loc,
|
||||
}
|
||||
: expression,
|
||||
});
|
||||
};
|
||||
for (const fn of [...functions]) {
|
||||
if (fn === normalize || fn.name.startsWith("%dyn.class.boxExact:")) continue;
|
||||
rewrite(fn);
|
||||
}
|
||||
}
|
||||
|
||||
/** Record field creation after the dispatch worklist closes, including writes
|
||||
* in generated member tables. Native values stay in their slots; the bag
|
||||
* owns only their property presence, attributes, and insertion position. */
|
||||
@@ -1634,6 +1733,15 @@ export class ClassDynamicDispatch {
|
||||
if (this.deletedNames === undefined)
|
||||
this.deletedNames = deletedPropertyNames(lowerer.moduleOrder);
|
||||
if (!root.base?.def.runtime && !fixedFieldFamily(root, this.deletedNames)) track(root);
|
||||
// An Error family's bag records where `name` and `message` were
|
||||
// created, which the error slots do not.
|
||||
if (root.base?.def.name === "%Error") {
|
||||
const order = (current: ClassInfo): void => {
|
||||
current.def.errorBagOrder = true;
|
||||
current.subclasses.forEach(order);
|
||||
};
|
||||
order(info);
|
||||
}
|
||||
}
|
||||
const loc = this.propertyBag.loc;
|
||||
const { receiver, condition } = this.propertyReceiver(plan, loc);
|
||||
|
||||
@@ -46,6 +46,13 @@ export function collectClassMethodMutations(
|
||||
const typedClasses: (ts.ClassDeclaration | ts.ClassExpression)[] = [];
|
||||
const symbolMethods = new Set<string>();
|
||||
let unknownKey: ts.Node | undefined;
|
||||
/** Every write with an unknown key: each may install a replacement of any
|
||||
* method name, and the key-order witness asks what each one installs. */
|
||||
const unknownKeySites: ts.Node[] = [];
|
||||
const markUnknownKey = (site: ts.Node): void => {
|
||||
unknownKey = site;
|
||||
unknownKeySites.push(site);
|
||||
};
|
||||
let numericKey: ts.Node | undefined;
|
||||
let unknownOwnField = false;
|
||||
// `sym:iterator` for `Symbol.iterator`: the name a class method declared
|
||||
@@ -83,7 +90,7 @@ export function collectClassMethodMutations(
|
||||
for (const key of computedMethods)
|
||||
for (const name of literalValues(lowerer.typeOf(key)) ?? []) methods.add(String(name));
|
||||
const markName = (name: string, site: ts.Node, arrow = false): void => {
|
||||
if (name === "prototype" || name === "__proto__") unknownKey = site;
|
||||
if (name === "prototype" || name === "__proto__") markUnknownKey(site);
|
||||
if (methods.has(name)) lowerer.noteMethodAccess(name, site);
|
||||
if (!arrow) receiverFields.add(name);
|
||||
};
|
||||
@@ -449,11 +456,12 @@ export function collectClassMethodMutations(
|
||||
(lowerer.isStdlibGlobal(node, "Object") || lowerer.isStdlibGlobal(node, "Reflect")) &&
|
||||
(!ts.isPropertyAccessExpression(node.parent) || node.parent.expression !== node)
|
||||
)
|
||||
unknownKey = node;
|
||||
markUnknownKey(node);
|
||||
for (const node of reflection) {
|
||||
const objectMethod = lowerer.stdlibGlobalMember(node, "Object");
|
||||
const reflectMethod = lowerer.stdlibGlobalMember(node, "Reflect");
|
||||
if (objectMethod === "setPrototypeOf" || reflectMethod === "setPrototypeOf") unknownKey = node;
|
||||
if (objectMethod === "setPrototypeOf" || reflectMethod === "setPrototypeOf")
|
||||
markUnknownKey(node);
|
||||
const single =
|
||||
objectMethod === "defineProperty" ||
|
||||
reflectMethod === "defineProperty" ||
|
||||
@@ -463,7 +471,7 @@ export function collectClassMethodMutations(
|
||||
if (!single && !multiple) continue;
|
||||
const call = node.parent;
|
||||
if (!ts.isCallExpression(call) || call.expression !== node) {
|
||||
unknownKey = node;
|
||||
markUnknownKey(node);
|
||||
continue;
|
||||
}
|
||||
const receiver = call.arguments.nodes[0];
|
||||
@@ -618,7 +626,7 @@ export function collectClassMethodMutations(
|
||||
// Numeric writes can replace numeric names but not ordinary names.
|
||||
numericKey = site;
|
||||
} else if (!(flags & ts.TypeFlags.ESSymbolLike)) {
|
||||
unknownKey = site;
|
||||
markUnknownKey(site);
|
||||
}
|
||||
}
|
||||
if (numericKey) {
|
||||
@@ -627,7 +635,10 @@ export function collectClassMethodMutations(
|
||||
}
|
||||
}
|
||||
if (unknownKey) {
|
||||
for (const method of methods) lowerer.noteMethodAccess(method, unknownKey);
|
||||
for (const method of methods) {
|
||||
lowerer.prototypeMethodAccesses.set(method, unknownKey);
|
||||
for (const site of unknownKeySites) lowerer.noteMethodSite(method, site);
|
||||
}
|
||||
for (const method of symbolMethods) lowerer.replacedSymbolMethods.add(method);
|
||||
}
|
||||
if (!unknownKey && !unknownOwnField)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { keyedHelperName } from "../stable-names.js";
|
||||
import { indexedUnionArms, lowerIndexedUnionToArray } from "../indexed-unions.js";
|
||||
import { generatorDrain } from "../iterator-adapters.js";
|
||||
import { identityPreservingWidening } from "../coercions/identity.js";
|
||||
import { liftedFreshSpread } from "../coercions/fresh-spread.js";
|
||||
@@ -1054,6 +1055,10 @@ export function lowerArrayFromCall(
|
||||
loc,
|
||||
};
|
||||
}
|
||||
// A union of typed arrays and number arrays (indexed-unions.ts).
|
||||
const indexedArms = indexedUnionArms(lowerer, src.type);
|
||||
if (indexedArms && args.length === 1)
|
||||
return lowerIndexedUnionToArray(lowerer, src, indexedArms, loc, true);
|
||||
if (src.type.kind === "set" && args.length === 1) {
|
||||
return {
|
||||
kind: "setIntrinsic",
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { keyedHelperName } from "../stable-names.js";
|
||||
import { allBytesArms, indexedUnionArms, lowerIndexedUnionMethod } from "../indexed-unions.js";
|
||||
import { boolLit, dynUndefinedExpr, nodeThrowExpr, numLit, varRef } from "../../../ir/build.js";
|
||||
import { BUF_NUM_METHODS } from "./buffer-numeric-methods.js";
|
||||
import * as ts from "../../ts7/adapter.js";
|
||||
import { constituentTypes } from "../../ts7/checker.js";
|
||||
import {
|
||||
BIGINT_T,
|
||||
BOOL,
|
||||
@@ -42,7 +44,7 @@ import {
|
||||
lowerStaticallyUndefinedArgument,
|
||||
} from "../optional-arguments.js";
|
||||
import { lowerArraySpreadItems, lowerCheckedArrayFrom } from "./array-construction.js";
|
||||
import { lowerToNumberArgument } from "../lower-exprs.js";
|
||||
import { lowerOptionalNumber, lowerToNumberArgument } from "../lower-exprs.js";
|
||||
import { lowerBytesIteratorValue } from "../iterator-adapters.js";
|
||||
import { lowerArrayCallback } from "./callback-arguments.js";
|
||||
import { callbackSite, findPredicateOk, predicateToBoolean } from "./array-callbacks.js";
|
||||
@@ -1032,6 +1034,119 @@ export function lowerBytesPrototypeSetCall(
|
||||
* variable-width read/writeUIntLE quartet — BUF_NUM_METHODS). Everything
|
||||
* else the lib declares (fill, indexOf, reverse, ...) falls through to
|
||||
* the SC2020 member fence. Null when this isn't a bytes method call. */
|
||||
/** The [needle, fromIndex] arguments of TypedArray indexOf, lastIndexOf
|
||||
* and includes. A present fromIndex converts even when it is undefined
|
||||
* (NaN, which ToIntegerOrInfinity makes 0); an absent one is 0, or
|
||||
* +Infinity for lastIndexOf, which starts at the last element. */
|
||||
function elementSearchArgs(lowerer: Lowerer, call: ts.CallExpression, name: string): IrExpr[] {
|
||||
const nodes = call.arguments.nodes;
|
||||
const loc = locOf(call);
|
||||
const needle = lowerer.lowerExprExpecting(nodes[0]!, F64);
|
||||
const from: IrExpr = nodes[1]
|
||||
? lowerOptionalNumber(lowerer, lowerer.lowerExpr(nodes[1]), locOf(nodes[1]), nodes[1])
|
||||
: ({
|
||||
kind: "numLit",
|
||||
value: name === "lastIndexOf" ? Infinity : 0,
|
||||
type: F64,
|
||||
loc,
|
||||
} satisfies IrExpr);
|
||||
// An undefined fromIndex is NaN once converted, which starts at 0.
|
||||
if (from.kind === "unitLit") return [needle, { kind: "numLit", value: NaN, type: F64, loc }];
|
||||
if (from.type.kind === "undefinedT" || from.type.kind === "void")
|
||||
return [
|
||||
needle,
|
||||
{
|
||||
kind: "seqExpr",
|
||||
stmts: [{ kind: "exprStmt", expr: from, loc }],
|
||||
result: { kind: "numLit", value: NaN, type: F64, loc },
|
||||
type: F64,
|
||||
loc,
|
||||
},
|
||||
];
|
||||
if (from.type.kind !== "f64") lowerer.noLowering(`.${name} with a non-number fromIndex`, call);
|
||||
return [needle, from];
|
||||
}
|
||||
|
||||
const ELEMENT_SEARCHES: Readonly<Record<string, IrBytesIntrinsicMethod>> = {
|
||||
indexOf: "indexOfElem",
|
||||
lastIndexOf: "lastIndexOfElem",
|
||||
includes: "includesElem",
|
||||
};
|
||||
|
||||
/** Whether a union has a Buffer arm, under any alias name: each arm's own
|
||||
* symbol names it. */
|
||||
function hasBufferArm(type: ts.Type): boolean {
|
||||
const arms = type.flags & ts.TypeFlags.Union ? constituentTypes(type) : [type];
|
||||
return arms.some((arm) => {
|
||||
const symbol = arm.getSymbol();
|
||||
return symbol !== undefined && ts.symbolName(symbol) === "Buffer";
|
||||
});
|
||||
}
|
||||
|
||||
/** The element-kind-generic typed-array methods on a union of typed
|
||||
* arrays (indexed-unions.ts): the arguments lower as for one typed array,
|
||||
* and each arm runs the method on its own receiver. Null for the methods
|
||||
* that need a narrowing to one kind first. */
|
||||
function lowerUnionBytesMethodCall(
|
||||
lowerer: Lowerer,
|
||||
call: ts.CallExpression,
|
||||
access: ts.PropertyAccessExpression,
|
||||
name: string,
|
||||
): IrExpr | null {
|
||||
if (isJsSourceFile(ts.getSourceFileOfNode(call))) return null;
|
||||
// A Buffer arm's methods differ from a typed array's (slice aliases, fill
|
||||
// checks its range, searches take strings and wrap numbers), so such a
|
||||
// union narrows to its arms first.
|
||||
if (hasBufferArm(lowerer.typeOf(access.expression))) return null;
|
||||
const nodes = call.arguments.nodes;
|
||||
if (nodes.some(ts.isSpreadElement)) return null;
|
||||
const loc = locOf(call);
|
||||
const num = (value: number): IrExpr => ({ kind: "numLit", value, type: F64, loc });
|
||||
const optional = (i: number, fallback: IrExpr, type: IrType = F64): IrExpr =>
|
||||
nodes[i] ? lowerOptionalArgument(lowerer, nodes[i]!, type, fallback) : fallback;
|
||||
let method: IrBytesIntrinsicMethod;
|
||||
let args: () => IrExpr[];
|
||||
let result: "receiver" | IrType;
|
||||
if ((name === "slice" || name === "subarray") && nodes.length <= 2) {
|
||||
method = name;
|
||||
args = () => [optional(0, num(0)), optional(1, num(Infinity))];
|
||||
result = "receiver";
|
||||
} else if (name === "fill" && nodes.length <= 3) {
|
||||
method = "fillElem";
|
||||
args = () => [optional(0, num(0)), optional(1, num(0)), optional(2, num(Infinity))];
|
||||
result = "receiver";
|
||||
} else if (name === "copyWithin" && nodes.length <= 3) {
|
||||
method = "copyWithin";
|
||||
args = () => [optional(0, num(0)), optional(1, num(0)), optional(2, num(Infinity))];
|
||||
result = "receiver";
|
||||
} else if (name === "toReversed" && nodes.length === 0) {
|
||||
method = "toReversed";
|
||||
args = () => [];
|
||||
result = "receiver";
|
||||
} else if (Object.hasOwn(ELEMENT_SEARCHES, name) && (nodes.length === 1 || nodes.length === 2)) {
|
||||
method = ELEMENT_SEARCHES[name]!;
|
||||
args = () => elementSearchArgs(lowerer, call, name);
|
||||
result = name === "includes" ? BOOL : F64;
|
||||
} else if (name === "join" && nodes.length <= 1) {
|
||||
method = "join";
|
||||
args = () => [optional(0, { kind: "strLit", value: ",", type: STRING, loc }, STRING)];
|
||||
result = STRING;
|
||||
} else if (name === "set" && (nodes.length === 1 || nodes.length === 2)) {
|
||||
const source = lowerer.mapTypeOf(lowerer.typeOf(nodes[0]!));
|
||||
method = source?.kind === "bytes" ? "setFrom" : "setFromDyn";
|
||||
args = () => {
|
||||
const src = lowerer.lowerExpr(nodes[0]!);
|
||||
const first = src.type.kind === "bytes" ? src : lowerer.coerceInto(nodes[0]!, src, DYN);
|
||||
return nodes.length === 2 ? [first, optional(1, num(0))] : [first];
|
||||
};
|
||||
result = VOID;
|
||||
} else return null;
|
||||
const receiver = lowerer.lowerExpr(access.expression);
|
||||
const arms = indexedUnionArms(lowerer, receiver.type);
|
||||
if (!arms || !allBytesArms(arms)) return null;
|
||||
return lowerIndexedUnionMethod(lowerer, receiver, arms, method, args(), result, loc);
|
||||
}
|
||||
|
||||
export function lowerBytesMethodCall(
|
||||
lowerer: Lowerer,
|
||||
call: ts.CallExpression,
|
||||
@@ -1040,6 +1155,9 @@ export function lowerBytesMethodCall(
|
||||
if (lowerer.chainBlocked(access, call)) return null;
|
||||
const name = access.name.text;
|
||||
const receiverIr = lowerer.mapTypeOf(lowerer.typeOf(access.expression));
|
||||
const unionArms = receiverIr ? indexedUnionArms(lowerer, receiverIr) : null;
|
||||
if (unionArms && allBytesArms(unionArms) && lowerer.isStdlibMember(access))
|
||||
return lowerUnionBytesMethodCall(lowerer, call, access, name);
|
||||
if (receiverIr?.kind !== "bytes") return null;
|
||||
if (!lowerer.isStdlibMember(access)) return null;
|
||||
const loc = locOf(call);
|
||||
@@ -1086,6 +1204,29 @@ export function lowerBytesMethodCall(
|
||||
if (value) return value;
|
||||
}
|
||||
}
|
||||
// TypedArray indexOf / lastIndexOf / includes (the Buffer-declared forms,
|
||||
// which also take string and Buffer needles, lowered above).
|
||||
if (
|
||||
Object.hasOwn(ELEMENT_SEARCHES, name) &&
|
||||
!lowerer.checker
|
||||
.getSymbolAtLocation(access.name)
|
||||
?.declarations.some(
|
||||
(d) => ts.isInterfaceDeclaration(d.parent) && d.parent.name.text === "Buffer",
|
||||
)
|
||||
) {
|
||||
if (nArgs < 1 || nArgs > 2 || call.arguments.nodes.some(ts.isSpreadElement)) {
|
||||
lowerer.noLowering(`.${name} with ${nArgs} arguments on typed arrays`, call);
|
||||
}
|
||||
const receiver = lowerer.lowerExprExpecting(access.expression, receiverIr);
|
||||
return {
|
||||
kind: "bytesIntrinsic",
|
||||
method: ELEMENT_SEARCHES[name]!,
|
||||
receiver,
|
||||
args: elementSearchArgs(lowerer, call, name),
|
||||
type: name === "includes" ? BOOL : F64,
|
||||
loc,
|
||||
};
|
||||
}
|
||||
if (name === "toReversed") {
|
||||
if (nArgs !== 0) {
|
||||
lowerer.noLowering(`.toReversed with ${nArgs} arguments on typed arrays`, call);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
/* Array literals. */
|
||||
import { indexedUnionArms, lowerIndexedUnionToArray } from "../indexed-unions.js";
|
||||
import * as ts from "../../ts7/adapter.js";
|
||||
import { type Lowerer, neverTaintedJsType } from "../lowerer.js";
|
||||
import { notIterableSpelling } from "../iterable-spelling.js";
|
||||
@@ -504,6 +505,10 @@ export function lowerArrayLiteral(
|
||||
loc: locOf(el),
|
||||
};
|
||||
}
|
||||
// A union of typed arrays and number arrays (indexed-unions.ts):
|
||||
// each arm's elements as a number[].
|
||||
const indexedArms = indexedUnionArms(lowerer, src.type);
|
||||
if (indexedArms) src = lowerIndexedUnionToArray(lowerer, src, indexedArms, locOf(el));
|
||||
// `[...obj]` over a class whose [Symbol.iterator] is a generator
|
||||
// method spreads the generator that method returns.
|
||||
src = classGeneratorIterable(lowerer, src) ?? src;
|
||||
|
||||
@@ -243,37 +243,38 @@ function lowerLooseNullCompare(
|
||||
// No unit arms: never null-ish (defensive — the fold below).
|
||||
return { kind: "boolLit", value: negated, type: BOOL, loc };
|
||||
}
|
||||
const isTag = (tag: number): IrExpr => ({
|
||||
const isTag = (tag: number, value: IrExpr): IrExpr => ({
|
||||
kind: "unionIsTag",
|
||||
unionId: ut.unionId,
|
||||
tag,
|
||||
negated,
|
||||
value: other,
|
||||
value,
|
||||
type: BOOL,
|
||||
loc,
|
||||
});
|
||||
if (tags.length === 1) return isTag(tags[0]!);
|
||||
if (tags.length === 1) return isTag(tags[0]!, other);
|
||||
// Both null AND undefined arms: tag-in-set as a short-circuit pair
|
||||
// (De Morgan for `!=`). The operand IrExpr rides both tests, so the
|
||||
// backend emits it per test — restricted to re-emittable pure reads;
|
||||
// anything effectful gets its own actionable fence (the generic
|
||||
// SC1040 hint would wrongly suggest `== null` as the fix).
|
||||
// (De Morgan for `!=`). The operand rides both tests, so an operand
|
||||
// that is not a plain read (`m.get(k)! == null`) is evaluated once
|
||||
// into a hidden local first.
|
||||
let value = other;
|
||||
let prefix: IrStmt[] = [];
|
||||
if (!isSafeToRepeat(other)) {
|
||||
lowerer.unsupported(
|
||||
"SC1090",
|
||||
expr,
|
||||
`'== null' / '!= null' on a '${lowerer.fmt(ut)}' value that isn't a plain read ` +
|
||||
`(both unit arms need the operand twice — bind it to a const first)`,
|
||||
);
|
||||
const tmp = lowerer.declareHiddenLocal("%nullish", ut);
|
||||
value = varRef(tmp.id, ut, loc);
|
||||
prefix = [{ kind: "varDecl", localId: tmp.id, init: other, loc }];
|
||||
}
|
||||
return {
|
||||
const test: IrExpr = {
|
||||
kind: "logical",
|
||||
op: negated ? "&&" : "||",
|
||||
left: isTag(tags[0]!),
|
||||
right: isTag(tags[1]!),
|
||||
left: isTag(tags[0]!, value),
|
||||
right: isTag(tags[1]!, value),
|
||||
type: BOOL,
|
||||
loc,
|
||||
};
|
||||
return prefix.length === 0
|
||||
? test
|
||||
: { kind: "seqExpr", stmts: prefix, result: test, type: BOOL, loc };
|
||||
}
|
||||
if (other.type.kind === "void") {
|
||||
return null; // no static tag to test — keep the fence
|
||||
|
||||
@@ -71,6 +71,13 @@ import { isClassCallback } from "../class-callbacks.js";
|
||||
import { isKeyedFieldAccess } from "./keyed-field-targets.js";
|
||||
import { lowerFieldCompoundValue } from "./updates.js";
|
||||
import { readsHeldEvolvingArray } from "../lower-stmts.js";
|
||||
import {
|
||||
type IndexedArm,
|
||||
indexedUnionArms,
|
||||
lowerIndexedUnionNumberRead,
|
||||
lowerIndexedUnionRead,
|
||||
lowerIndexedUnionWrite,
|
||||
} from "../indexed-unions.js";
|
||||
import { lowerBufferPrototypeMember } from "../containers/bytes.js";
|
||||
|
||||
/** `a[i]` reads. Only f64 indices into array receivers are modeled; JS
|
||||
@@ -302,6 +309,31 @@ export function lowerElementAccess(lowerer: Lowerer, expr: ts.ElementAccessExpre
|
||||
}
|
||||
}
|
||||
|
||||
// An element read of a union of typed arrays and number arrays: each
|
||||
// arm's own read, dispatched on the tag (indexed-unions.ts).
|
||||
const indexedArms = receiverIr ? indexedUnionArms(lowerer, receiverIr) : null;
|
||||
if (indexedArms && receiverIr && !isJsSourceFile(ts.getSourceFileOfNode(expr))) {
|
||||
let recv = lowerer.lowerExpr(expr.expression);
|
||||
if (recv.type.kind === "dyn") recv = lowerer.coerceInto(expr.expression, recv, receiverIr);
|
||||
const arms = indexedUnionArms(lowerer, recv.type);
|
||||
if (arms) {
|
||||
const index = lowerOptionalNumber(
|
||||
lowerer,
|
||||
lowerer.lowerExpr(expr.argumentExpression),
|
||||
locOf(expr.argumentExpression),
|
||||
expr.argumentExpression,
|
||||
);
|
||||
if (index.type.kind !== "f64")
|
||||
lowerer.unsupported("SC1090", expr.argumentExpression, "indexing with non-number keys");
|
||||
if (
|
||||
(ts.isNonNullExpression(expr.parent) && expr.parent.expression === expr) ||
|
||||
lowerer.nanCodedReads?.isNumericRead(expr) === true
|
||||
)
|
||||
return lowerIndexedUnionNumberRead(lowerer, recv, arms, index, locOf(expr));
|
||||
return lowerIndexedUnionRead(lowerer, recv, arms, index, locOf(expr));
|
||||
}
|
||||
}
|
||||
|
||||
// Typed-array element read `b[i]` — like arrayGet with a scalar
|
||||
// result; any invalid index traps (the array discipline; JS would
|
||||
// read undefined — divergence 4's policy).
|
||||
@@ -1521,6 +1553,9 @@ export function lowerElementCompoundParts(
|
||||
});
|
||||
return { expr: { kind: "seqExpr", stmts, result: value, type: DYN, loc }, stmts: null };
|
||||
}
|
||||
const indexedArms = indexedUnionArms(lowerer, checked.type);
|
||||
if (indexedArms && !isJsSourceFile(ts.getSourceFileOfNode(expr)))
|
||||
return lowerIndexedUnionCompound(lowerer, expr, op, checked, indexedArms);
|
||||
const receiverType =
|
||||
checked.type.kind === "array" || checked.type.kind === "bytes"
|
||||
? checked.type
|
||||
@@ -1705,6 +1740,54 @@ export function lowerElementCompoundParts(
|
||||
};
|
||||
}
|
||||
|
||||
/** `u[i] op= v` on a union of typed arrays and number arrays: the
|
||||
* receiver and index evaluate once, the old element reads as a number (NaN
|
||||
* for an invalid index, as in the typed-array form), and the result is
|
||||
* stored through the union's element write. */
|
||||
function lowerIndexedUnionCompound(
|
||||
lowerer: Lowerer,
|
||||
expr: ts.BinaryExpression,
|
||||
op: CompoundOp,
|
||||
receiver: IrExpr,
|
||||
arms: readonly IndexedArm[],
|
||||
): { expr: IrExpr | null; stmts: IrStmt[] | null } {
|
||||
const target = expr.left as ts.ElementAccessExpression;
|
||||
const loc = locOf(expr);
|
||||
const index = lowerOptionalIndex(
|
||||
lowerer,
|
||||
lowerer.lowerExpr(target.argumentExpression),
|
||||
locOf(target.argumentExpression),
|
||||
target.argumentExpression,
|
||||
);
|
||||
if (index.type.kind !== "f64")
|
||||
lowerer.unsupported("SC1090", target.argumentExpression, "indexing with non-number keys");
|
||||
const receiverLocal = lowerer.declareHiddenLocal("%compoundArray", receiver.type);
|
||||
const indexLocal = lowerer.declareHiddenLocal("%compoundIndex", F64);
|
||||
const receiverRef = (): IrExpr => varRef(receiverLocal.id, receiver.type, loc);
|
||||
const indexRef = (): IrExpr => varRef(indexLocal.id, F64, loc);
|
||||
const oldValue = lowerIndexedUnionNumberRead(lowerer, receiverRef(), arms, indexRef(), loc);
|
||||
const rhs = lowerOptionalNumber(lowerer, lowerer.lowerExpr(expr.right), loc);
|
||||
if (rhs.type.kind !== "f64") compoundUnsupported(lowerer, expr, op, F64, rhs.type);
|
||||
const computed: IrExpr = { kind: "bin", op, left: oldValue, right: rhs, type: F64, loc };
|
||||
const resultLocal = lowerer.declareHiddenLocal("%compoundResult", F64);
|
||||
const resultRef = (): IrExpr => varRef(resultLocal.id, F64, loc);
|
||||
return {
|
||||
expr: {
|
||||
kind: "seqExpr",
|
||||
stmts: [
|
||||
{ kind: "varDecl", localId: receiverLocal.id, init: receiver, loc },
|
||||
{ kind: "varDecl", localId: indexLocal.id, init: index, loc },
|
||||
{ kind: "varDecl", localId: resultLocal.id, init: computed, loc },
|
||||
lowerIndexedUnionWrite(lowerer, receiverRef(), arms, indexRef(), resultRef(), loc),
|
||||
],
|
||||
result: resultRef(),
|
||||
type: F64,
|
||||
loc,
|
||||
},
|
||||
stmts: null,
|
||||
};
|
||||
}
|
||||
|
||||
/** ToString of one stabilized `string[]` element read for `+=`: a missing
|
||||
* element concatenates as "undefined". */
|
||||
function arrayStringOperand(arr: IrExpr, index: IrExpr, loc: SrcLoc): IrExpr {
|
||||
@@ -2246,6 +2329,26 @@ export function lowerElementWrite(lowerer: Lowerer, expr: ts.BinaryExpression):
|
||||
};
|
||||
}
|
||||
}
|
||||
// An element write into a union of typed arrays and number arrays
|
||||
// (indexed-unions.ts).
|
||||
const indexedArms = receiverIr ? indexedUnionArms(lowerer, receiverIr) : null;
|
||||
if (indexedArms && receiverIr && !isJsSourceFile(ts.getSourceFileOfNode(expr))) {
|
||||
let recv = lowerer.lowerExpr(target.expression);
|
||||
if (recv.type.kind === "dyn") recv = lowerer.coerceInto(target.expression, recv, receiverIr);
|
||||
const arms = indexedUnionArms(lowerer, recv.type);
|
||||
if (arms) {
|
||||
const index = lowerOptionalNumber(
|
||||
lowerer,
|
||||
lowerer.lowerExpr(target.argumentExpression),
|
||||
locOf(target.argumentExpression),
|
||||
target.argumentExpression,
|
||||
);
|
||||
if (index.type.kind !== "f64")
|
||||
lowerer.unsupported("SC1090", target.argumentExpression, "indexing with non-number keys");
|
||||
const value = lowerer.lowerExprExpecting(expr.right, F64);
|
||||
return lowerIndexedUnionWrite(lowerer, recv, arms, index, value, locOf(expr));
|
||||
}
|
||||
}
|
||||
if (receiverIr?.kind !== "array") {
|
||||
lowerer.unsupported("SC1090", target, "assignment to non-array elements");
|
||||
}
|
||||
|
||||
@@ -25,6 +25,11 @@ import {
|
||||
} from "../../../ir/ir.js";
|
||||
import { lowerNodeModuleIdentifier } from "../lower-node-module.js";
|
||||
import { lowerCjsExportsObjectValue } from "../cjs-exports-object.js";
|
||||
import {
|
||||
splitRequireBindingOfIdent,
|
||||
wholeExportSymbolOfModule,
|
||||
wholeExportValue,
|
||||
} from "../cjs-inline-require.js";
|
||||
import { captureContextArguments } from "../function-context.js";
|
||||
import { argumentsOwner, typedArgumentsCandidate } from "../typed-arguments.js";
|
||||
import {
|
||||
@@ -979,6 +984,27 @@ export function lowerIdentifierExpr(lowerer: Lowerer, expr: ts.Identifier, loc:
|
||||
// Client`): the member holds that binding's value.
|
||||
const memberAlias = cjsMemberAliasValueOf(lowerer, expr);
|
||||
if (memberAlias !== null) return lowerer.lowerExpr(memberAlias);
|
||||
// `var m; m = require("./x")` as a bare value: a whole-export target is
|
||||
// the exported value; a table target has no first-class module object.
|
||||
{
|
||||
const split = splitRequireBindingOfIdent(lowerer, expr);
|
||||
if (split !== null) {
|
||||
if (wholeExportSymbolOfModule(lowerer, split.dep) !== null) {
|
||||
const value = wholeExportValue(lowerer, split.dep, expr);
|
||||
if (value !== null) return value;
|
||||
lowerer.unsupported(
|
||||
"SC1090",
|
||||
expr,
|
||||
`the whole export of '${split.spec}' as a value (its 'module.exports =' value has no static representation)`,
|
||||
);
|
||||
}
|
||||
lowerer.unsupported(
|
||||
"SC1090",
|
||||
expr,
|
||||
`the exports object of '${split.spec}' as a value (its exports compile to a static table: read require(${JSON.stringify(split.spec)}).member directly)`,
|
||||
);
|
||||
}
|
||||
}
|
||||
// Preflight guarantees no unresolved identifiers; anything else here
|
||||
// is a blocked declaration's binding (the SC2004 cascade) or a
|
||||
// binding form we don't model yet.
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
/* Property reads (`a.b`): lowerExprInner's property-access branch, intrinsic and union properties, field reads and targets, and match-group reads. */
|
||||
import { indexedUnionArms, lowerIndexedUnionMember } from "../indexed-unions.js";
|
||||
import { keyedHelperName } from "../stable-names.js";
|
||||
import { staticallySelected } from "../static-typeof.js";
|
||||
import * as ts from "../../ts7/adapter.js";
|
||||
@@ -3394,6 +3395,13 @@ export function lowerUnionProperty(
|
||||
loc: locOf(expr),
|
||||
};
|
||||
}
|
||||
// A union of typed arrays and number arrays: each arm's own length
|
||||
// (and, for typed arrays only, byteLength, byteOffset, BYTES_PER_ELEMENT).
|
||||
const indexedArms = indexedUnionArms(lowerer, value.type);
|
||||
if (indexedArms) {
|
||||
const member = lowerIndexedUnionMember(lowerer, value, indexedArms, field, locOf(expr));
|
||||
if (member) return member;
|
||||
}
|
||||
lowerer.unsupported(
|
||||
"SC1090",
|
||||
expr,
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
/* Increment, decrement and prefix unary operators, and compound field updates. */
|
||||
import {
|
||||
indexedUnionArms,
|
||||
lowerIndexedUnionNumberRead,
|
||||
lowerIndexedUnionWrite,
|
||||
} from "../indexed-unions.js";
|
||||
import * as ts from "../../ts7/adapter.js";
|
||||
import {
|
||||
lowerOptionalIndex,
|
||||
@@ -390,6 +395,39 @@ export function lowerIncDec(
|
||||
loc,
|
||||
}));
|
||||
}
|
||||
// A union of typed arrays and number arrays (indexed-unions.ts): the
|
||||
// element read as a number and the union's element write.
|
||||
const indexedArms = indexedUnionArms(lowerer, raw.type);
|
||||
if (
|
||||
ts.isElementAccessExpression(access) &&
|
||||
indexedArms &&
|
||||
!isJsSourceFile(ts.getSourceFileOfNode(expr))
|
||||
) {
|
||||
const receiver = save(raw, "%incrementArray");
|
||||
const index = save(
|
||||
lowerOptionalIndex(
|
||||
lowerer,
|
||||
lowerer.lowerExpr(access.argumentExpression),
|
||||
locOf(access.argumentExpression),
|
||||
access.argumentExpression,
|
||||
),
|
||||
"%incrementIndex",
|
||||
);
|
||||
if (index.type.kind !== "f64")
|
||||
lowerer.unsupported("SC1090", access, "incrementing non-number array keys");
|
||||
return finish(
|
||||
lowerIndexedUnionNumberRead(lowerer, receiver, indexedArms, index, loc),
|
||||
(value) =>
|
||||
lowerIndexedUnionWrite(
|
||||
lowerer,
|
||||
receiver,
|
||||
indexedArms,
|
||||
index,
|
||||
lowerer.coerceInto(access, value, F64),
|
||||
loc,
|
||||
),
|
||||
);
|
||||
}
|
||||
// A TS member statically typed number on a checked-dynamic receiver (a
|
||||
// class-backed protocol view): the expanded form `o.v = o.v + 1`, its
|
||||
// read checked into number like any other read of the member.
|
||||
|
||||
@@ -17,6 +17,7 @@ import { PoisonError, dynFallbackType } from "./lowerer.js";
|
||||
import { functionCanReturnUndefined } from "../function-completion.js";
|
||||
import { jsBindingAppendsOnly, jsBindingHasOpenWrites } from "./lower-stmts.js";
|
||||
import type { FnCtx } from "./function-context.js";
|
||||
import { returnsGuessedOverloadValue } from "./overload-choice.js";
|
||||
|
||||
/** Keep the conservative completion rule shared by return construction
|
||||
* and inference. Nested control flow may still make completion unreachable. */
|
||||
@@ -256,6 +257,22 @@ export function declaredReturnType(
|
||||
return decl.modifiers?.nodes.some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword)
|
||||
? { kind: "promise", inner: DYN }
|
||||
: DYN;
|
||||
// A JS function returning a value whose type rests on an undecided
|
||||
// overload (guessedOverloadValue): the inferred result is the first
|
||||
// overload's, which the returned value need not have.
|
||||
if (
|
||||
isJsSourceFile(ts.getSourceFileOfNode(decl)) &&
|
||||
!decl.type &&
|
||||
!decl.asteriskToken &&
|
||||
!hasExplicitJsDocReturn(decl) &&
|
||||
mappedReturn !== null &&
|
||||
mappedReturn.kind !== "dyn" &&
|
||||
!(mappedReturn.kind === "promise" && mappedReturn.inner.kind === "dyn") &&
|
||||
returnsGuessedOverloadValue(lowerer, decl)
|
||||
)
|
||||
return decl.modifiers?.nodes.some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword)
|
||||
? { kind: "promise", inner: DYN }
|
||||
: DYN;
|
||||
// JS inference assigns Number to arithmetic over any, although the
|
||||
// runtime operands can both be BigInts. Preserve that native result.
|
||||
if (
|
||||
|
||||
@@ -0,0 +1,569 @@
|
||||
import { keyedHelperName } from "./stable-names.js";
|
||||
import { helperLoc, varRef } from "../../ir/build.js";
|
||||
import {
|
||||
BOOL,
|
||||
BYTES_ELEMENT_SIZE,
|
||||
F64,
|
||||
VOID,
|
||||
type IrBytesIntrinsicMethod,
|
||||
type IrExpr,
|
||||
type IrFunction,
|
||||
type IrStmt,
|
||||
type IrType,
|
||||
type SrcLoc,
|
||||
typeKey,
|
||||
} from "../../ir/ir.js";
|
||||
import { everyExprChild, everyStmtChild } from "../../ir/traverse.js";
|
||||
import { arrayNumberRead, lowerSafeBytesRead, lowerSafeIndexRead } from "./array-values.js";
|
||||
import type { Lowerer } from "./lowerer.js";
|
||||
|
||||
/** Unions of number-indexed containers: typed arrays of any element kind
|
||||
* (`Uint8Array | Uint16Array | Uint32Array`, as lru-cache picks by size)
|
||||
* and `number[]` arms.
|
||||
*
|
||||
* The union keeps its ordinary tagged representation. Each operation on it
|
||||
* lowers to a lifted helper per union and operation that tests the tag,
|
||||
* narrows to the arm and runs the arm's own operation: the inline load or
|
||||
* store of a typed array's element kind, or the dense read or write of a
|
||||
* number array. The helpers are small, so LLVM inlines them, and a loop
|
||||
* over one union value tests a loop-invariant tag. */
|
||||
|
||||
/** One arm: its tag and its type (bytes, or an array of numbers). */
|
||||
export interface IndexedArm {
|
||||
tag: number;
|
||||
type: IrType & ({ kind: "bytes" } | { kind: "array" });
|
||||
}
|
||||
|
||||
/** The arms of a union whose every arm is a typed array or a `number[]`,
|
||||
* or null. Unions with any other arm (undefined included) are not
|
||||
* indexed unions: their reads need a narrowing first. */
|
||||
export function indexedUnionArms(lowerer: Lowerer, type: IrType): IndexedArm[] | null {
|
||||
if (type.kind !== "union") return null;
|
||||
const arms = lowerer.unions.get(type.unionId)?.arms;
|
||||
if (!arms || arms.length < 2) return null;
|
||||
const result: IndexedArm[] = [];
|
||||
for (const [tag, arm] of arms.entries()) {
|
||||
if (arm.kind === "bytes") result.push({ tag, type: arm });
|
||||
else if (arm.kind === "array" && arm.elem.kind === "f64") result.push({ tag, type: arm });
|
||||
else return null;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Whether every arm is a typed array (so typed-array-only members such
|
||||
* as `byteLength` apply). */
|
||||
export function allBytesArms(arms: readonly IndexedArm[]): boolean {
|
||||
return arms.every((arm) => arm.type.kind === "bytes");
|
||||
}
|
||||
|
||||
type ArmBody = (receiver: IrExpr, arm: IndexedArm, args: readonly IrExpr[]) => IrStmt[];
|
||||
|
||||
/** The helper `name(u, ...args)`: for each arm but the last, a tag test
|
||||
* that runs the arm's statements; the last arm's statements run without a
|
||||
* test (the union holds one of its arms). */
|
||||
function dispatchHelper(
|
||||
lowerer: Lowerer,
|
||||
key: string,
|
||||
prefix: string,
|
||||
union: IrType,
|
||||
arms: readonly IndexedArm[],
|
||||
params: readonly { name: string; type: IrType }[],
|
||||
returnType: IrType,
|
||||
body: ArmBody,
|
||||
loc: SrcLoc,
|
||||
): string {
|
||||
const existing = lowerer.arrHofHelpers.get(key);
|
||||
if (existing) return existing;
|
||||
const name = keyedHelperName(lowerer, prefix, key);
|
||||
lowerer.arrHofHelpers.set(key, name);
|
||||
const at = helperLoc(loc);
|
||||
if (union.kind !== "union") throw new Error("indexed-union helper over a non-union");
|
||||
const u = varRef("u.0", union, at);
|
||||
const args = params.map((p) => varRef(`${p.name}.0`, p.type, at));
|
||||
const stmts: IrStmt[] = [];
|
||||
arms.forEach((arm, i) => {
|
||||
const receiver: IrExpr = {
|
||||
kind: "unionNarrow",
|
||||
unionId: union.unionId,
|
||||
tag: arm.tag,
|
||||
value: u,
|
||||
type: arm.type,
|
||||
loc: at,
|
||||
};
|
||||
const armStmts = body(receiver, arm, args);
|
||||
if (i === arms.length - 1) {
|
||||
stmts.push(...armStmts);
|
||||
return;
|
||||
}
|
||||
stmts.push({
|
||||
kind: "if",
|
||||
cond: {
|
||||
kind: "unionIsTag",
|
||||
unionId: union.unionId,
|
||||
tag: arm.tag,
|
||||
negated: false,
|
||||
value: u,
|
||||
type: BOOL,
|
||||
loc: at,
|
||||
},
|
||||
then: armStmts,
|
||||
else_: null,
|
||||
loc: at,
|
||||
});
|
||||
});
|
||||
const fn: IrFunction = {
|
||||
name,
|
||||
params: [
|
||||
{ localId: "u.0", name: "u", type: union },
|
||||
...params.map((p) => ({ localId: `${p.name}.0`, name: p.name, type: p.type })),
|
||||
],
|
||||
returnType,
|
||||
locals: [
|
||||
{ id: "u.0", name: "u", type: union, mutable: false },
|
||||
...params.map((p) => ({ id: `${p.name}.0`, name: p.name, type: p.type, mutable: false })),
|
||||
],
|
||||
body: stmts,
|
||||
loc: at,
|
||||
};
|
||||
lowerer.liftedFns.push(fn);
|
||||
return name;
|
||||
}
|
||||
|
||||
const returning = (value: IrExpr, loc: SrcLoc): IrStmt[] => [{ kind: "return", value, loc }];
|
||||
|
||||
/** `u[i]` read as an element or undefined (an invalid index), as the
|
||||
* typed-array and number-array reads answer. */
|
||||
export function lowerIndexedUnionRead(
|
||||
lowerer: Lowerer,
|
||||
receiver: IrExpr,
|
||||
arms: readonly IndexedArm[],
|
||||
index: IrExpr,
|
||||
loc: SrcLoc,
|
||||
): IrExpr {
|
||||
const resultT = lowerer.withUndefinedArm(F64);
|
||||
const key = `idxUnion:get:${unionKey(receiver.type)}`;
|
||||
const name = dispatchHelper(
|
||||
lowerer,
|
||||
key,
|
||||
"%union.idxOr",
|
||||
receiver.type,
|
||||
arms,
|
||||
[{ name: "i", type: F64 }],
|
||||
resultT,
|
||||
(arm, info, [i]) =>
|
||||
returning(
|
||||
info.type.kind === "bytes"
|
||||
? lowerSafeBytesRead(lowerer, arm, i!, loc)
|
||||
: lowerSafeIndexRead(lowerer, arm, i!, loc)!,
|
||||
loc,
|
||||
),
|
||||
loc,
|
||||
);
|
||||
const numeric = indexedUnionNumberHelper(lowerer, receiver.type, arms, loc);
|
||||
lowerer.indexedUnionNumericTwins.set(name, numeric);
|
||||
return { kind: "call", callee: name, args: [receiver, index], type: resultT, loc };
|
||||
}
|
||||
|
||||
/** `u[i]` read as a number: an invalid index reads as NaN, which is
|
||||
* ToNumber(undefined). */
|
||||
export function lowerIndexedUnionNumberRead(
|
||||
lowerer: Lowerer,
|
||||
receiver: IrExpr,
|
||||
arms: readonly IndexedArm[],
|
||||
index: IrExpr,
|
||||
loc: SrcLoc,
|
||||
): IrExpr {
|
||||
if (inlineDispatch(receiver, [index]))
|
||||
return inlineArms(receiver, arms, F64, (arm, info) => numberRead(arm, info, index, loc), loc);
|
||||
const name = indexedUnionNumberHelper(lowerer, receiver.type, arms, loc);
|
||||
return { kind: "call", callee: name, args: [receiver, index], type: F64, loc };
|
||||
}
|
||||
|
||||
function numberRead(arm: IrExpr, info: IndexedArm, index: IrExpr, loc: SrcLoc): IrExpr {
|
||||
return info.type.kind === "bytes"
|
||||
? {
|
||||
kind: "bytesIntrinsic",
|
||||
method: "get",
|
||||
receiver: arm,
|
||||
args: [index],
|
||||
type: F64,
|
||||
loc,
|
||||
invalidNaN: true,
|
||||
}
|
||||
: arrayNumberRead(arm, index, loc);
|
||||
}
|
||||
|
||||
function indexedUnionNumberHelper(
|
||||
lowerer: Lowerer,
|
||||
union: IrType,
|
||||
arms: readonly IndexedArm[],
|
||||
loc: SrcLoc,
|
||||
): string {
|
||||
return dispatchHelper(
|
||||
lowerer,
|
||||
`idxUnion:num:${unionKey(union)}`,
|
||||
"%union.getNumber",
|
||||
union,
|
||||
arms,
|
||||
[{ name: "i", type: F64 }],
|
||||
F64,
|
||||
(arm, info, [i]) => returning(numberRead(arm, info, i!, loc), loc),
|
||||
loc,
|
||||
);
|
||||
}
|
||||
|
||||
/** The numeric twin of an indexed-union read helper call, or null. */
|
||||
export function indexedUnionNumericTwin(lowerer: Lowerer, call: IrExpr): IrExpr | null {
|
||||
if (call.kind !== "call") return null;
|
||||
const twin = lowerer.indexedUnionNumericTwins.get(call.callee);
|
||||
return twin === undefined ? null : { ...call, callee: twin, type: F64 };
|
||||
}
|
||||
|
||||
/** `u[i] = v` for a number `v`: each arm's element store (a typed array
|
||||
* converts the number to its element kind and ignores an invalid index; a
|
||||
* number array stores at the index). */
|
||||
export function lowerIndexedUnionWrite(
|
||||
lowerer: Lowerer,
|
||||
receiver: IrExpr,
|
||||
arms: readonly IndexedArm[],
|
||||
index: IrExpr,
|
||||
value: IrExpr,
|
||||
loc: SrcLoc,
|
||||
): IrStmt {
|
||||
// In place, the value evaluates before the arms read the receiver and
|
||||
// index: only when it cannot rebind either.
|
||||
if (inlineDispatch(receiver, [index]) && !rebinds(value, [receiver, index])) {
|
||||
const union = receiver.type;
|
||||
const valueLocal = lowerer.declareHiddenLocal("%elementValue", F64);
|
||||
const v: IrExpr = { kind: "varRef", localId: valueLocal.id, type: F64, loc };
|
||||
let chain: IrStmt[] | null = null;
|
||||
for (let i = arms.length - 1; i >= 0; i--) {
|
||||
const info = arms[i]!;
|
||||
const arm: IrExpr = {
|
||||
kind: "unionNarrow",
|
||||
unionId: union.kind === "union" ? union.unionId : "",
|
||||
tag: info.tag,
|
||||
value: receiver,
|
||||
type: info.type,
|
||||
loc,
|
||||
};
|
||||
const store: IrStmt =
|
||||
info.type.kind === "bytes"
|
||||
? { kind: "bytesSet", arr: arm, index, value: v, loc }
|
||||
: { kind: "arraySet", arr: arm, index, value: v, loc };
|
||||
chain =
|
||||
chain === null
|
||||
? [store]
|
||||
: [
|
||||
{
|
||||
kind: "if",
|
||||
cond: {
|
||||
kind: "unionIsTag",
|
||||
unionId: union.kind === "union" ? union.unionId : "",
|
||||
tag: info.tag,
|
||||
negated: false,
|
||||
value: receiver,
|
||||
type: BOOL,
|
||||
loc,
|
||||
},
|
||||
then: [store],
|
||||
else_: chain,
|
||||
loc,
|
||||
},
|
||||
];
|
||||
}
|
||||
return {
|
||||
kind: "block",
|
||||
body: [{ kind: "varDecl", localId: valueLocal.id, init: value, loc }, ...chain!],
|
||||
loc,
|
||||
};
|
||||
}
|
||||
const name = dispatchHelper(
|
||||
lowerer,
|
||||
`idxUnion:set:${unionKey(receiver.type)}`,
|
||||
"%union.idxSet",
|
||||
receiver.type,
|
||||
arms,
|
||||
[
|
||||
{ name: "i", type: F64 },
|
||||
{ name: "v", type: F64 },
|
||||
],
|
||||
VOID,
|
||||
(arm, info, [i, v]) => [
|
||||
info.type.kind === "bytes"
|
||||
? { kind: "bytesSet", arr: arm, index: i!, value: v!, loc }
|
||||
: { kind: "arraySet", arr: arm, index: i!, value: v!, loc },
|
||||
{ kind: "return", value: null, loc },
|
||||
],
|
||||
loc,
|
||||
);
|
||||
return {
|
||||
kind: "exprStmt",
|
||||
expr: { kind: "call", callee: name, args: [receiver, index, value], type: VOID, loc },
|
||||
loc,
|
||||
};
|
||||
}
|
||||
|
||||
/** The members every arm answers: `length` for all, and `byteLength`,
|
||||
* `byteOffset` and `BYTES_PER_ELEMENT` when every arm is a typed array. */
|
||||
export function lowerIndexedUnionMember(
|
||||
lowerer: Lowerer,
|
||||
receiver: IrExpr,
|
||||
arms: readonly IndexedArm[],
|
||||
member: string,
|
||||
loc: SrcLoc,
|
||||
): IrExpr | null {
|
||||
const bytesOnly = member !== "length";
|
||||
if (
|
||||
member !== "length" &&
|
||||
member !== "byteLength" &&
|
||||
member !== "byteOffset" &&
|
||||
member !== "BYTES_PER_ELEMENT"
|
||||
)
|
||||
return null;
|
||||
if (bytesOnly && !allBytesArms(arms)) return null;
|
||||
const memberOf = (arm: IrExpr, info: IndexedArm): IrExpr =>
|
||||
info.type.kind === "array"
|
||||
? { kind: "arrIntrinsic", method: "length", receiver: arm, args: [], type: F64, loc }
|
||||
: member === "BYTES_PER_ELEMENT"
|
||||
? { kind: "numLit", value: BYTES_ELEMENT_SIZE[info.type.elem], type: F64, loc }
|
||||
: { kind: "bytesIntrinsic", method: member, receiver: arm, args: [], type: F64, loc };
|
||||
if (inlineDispatch(receiver, [])) return inlineArms(receiver, arms, F64, memberOf, loc);
|
||||
const name = dispatchHelper(
|
||||
lowerer,
|
||||
`idxUnion:${member}:${unionKey(receiver.type)}`,
|
||||
`%union.${member}`,
|
||||
receiver.type,
|
||||
arms,
|
||||
[],
|
||||
F64,
|
||||
(arm, info) => returning(memberOf(arm, info), loc),
|
||||
loc,
|
||||
);
|
||||
return { kind: "call", callee: name, args: [receiver], type: F64, loc };
|
||||
}
|
||||
|
||||
function unionKey(type: IrType): string {
|
||||
return type.kind === "union" ? String(type.unionId) : "?";
|
||||
}
|
||||
|
||||
/** A typed-array method on a union whose every arm is a typed array: the
|
||||
* arguments evaluate once in the caller, and each arm runs the same
|
||||
* `bytesIntrinsic` on its own receiver. `result` "receiver" is a method
|
||||
* that answers a typed array of the receiver's kind (subarray, slice,
|
||||
* fill, ...): each arm wraps its answer back into the union. */
|
||||
export function lowerIndexedUnionMethod(
|
||||
lowerer: Lowerer,
|
||||
receiver: IrExpr,
|
||||
arms: readonly IndexedArm[],
|
||||
method: IrBytesIntrinsicMethod,
|
||||
args: readonly IrExpr[],
|
||||
result: "receiver" | IrType,
|
||||
loc: SrcLoc,
|
||||
): IrExpr {
|
||||
const union = receiver.type;
|
||||
if (union.kind !== "union") throw new Error("indexed-union method over a non-union");
|
||||
const resultT = result === "receiver" ? union : result;
|
||||
const params = args.map((arg, i) => ({ name: `a${i}`, type: arg.type }));
|
||||
const signature = args.map((arg) => typeKey(arg.type)).join(",");
|
||||
const name = dispatchHelper(
|
||||
lowerer,
|
||||
`idxUnion:${method}(${signature}):${unionKey(union)}`,
|
||||
`%union.${method}`,
|
||||
union,
|
||||
arms,
|
||||
params,
|
||||
resultT,
|
||||
(arm, info, refs) => {
|
||||
const call: IrExpr = {
|
||||
kind: "bytesIntrinsic",
|
||||
method,
|
||||
receiver: arm,
|
||||
args: [...refs],
|
||||
type: result === "receiver" ? info.type : result,
|
||||
loc,
|
||||
};
|
||||
if (result === "receiver")
|
||||
return returning(
|
||||
{
|
||||
kind: "unionWrap",
|
||||
unionId: union.unionId,
|
||||
tag: info.tag,
|
||||
value: call,
|
||||
type: union,
|
||||
loc,
|
||||
},
|
||||
loc,
|
||||
);
|
||||
if (result.kind === "void")
|
||||
return [
|
||||
{ kind: "exprStmt", expr: call, loc },
|
||||
{ kind: "return", value: null, loc },
|
||||
];
|
||||
return returning(call, loc);
|
||||
},
|
||||
loc,
|
||||
);
|
||||
return { kind: "call", callee: name, args: [receiver, ...args], type: resultT, loc };
|
||||
}
|
||||
|
||||
/** The elements of `u` as a `number[]`: a typed-array arm drains its
|
||||
* elements into a fresh array. A number-array arm is the array itself for
|
||||
* consumers that copy it (spreads), or with `fresh` a dense copy whose
|
||||
* holes read as undefined (Array.from). */
|
||||
export function lowerIndexedUnionToArray(
|
||||
lowerer: Lowerer,
|
||||
receiver: IrExpr,
|
||||
arms: readonly IndexedArm[],
|
||||
loc: SrcLoc,
|
||||
fresh = false,
|
||||
): IrExpr {
|
||||
const arrayT: IrType = { kind: "array", elem: F64 };
|
||||
const name = dispatchHelper(
|
||||
lowerer,
|
||||
`idxUnion:${fresh ? "from" : "toArray"}:${unionKey(receiver.type)}`,
|
||||
fresh ? "%union.arrayFrom" : "%union.toArray",
|
||||
receiver.type,
|
||||
arms,
|
||||
[],
|
||||
arrayT,
|
||||
(arm, info) =>
|
||||
returning(
|
||||
info.type.kind === "bytes"
|
||||
? {
|
||||
kind: "bytesIntrinsic",
|
||||
method: "toArray",
|
||||
receiver: arm,
|
||||
args: [],
|
||||
type: arrayT,
|
||||
loc,
|
||||
}
|
||||
: fresh
|
||||
? {
|
||||
kind: "arrIntrinsic",
|
||||
method: "reverse",
|
||||
receiver: {
|
||||
kind: "arrIntrinsic",
|
||||
method: "toReversed",
|
||||
receiver: arm,
|
||||
args: [],
|
||||
type: arrayT,
|
||||
loc,
|
||||
},
|
||||
args: [],
|
||||
type: arrayT,
|
||||
loc,
|
||||
}
|
||||
: arm,
|
||||
loc,
|
||||
),
|
||||
loc,
|
||||
);
|
||||
return { kind: "call", callee: name, args: [receiver], type: arrayT, loc };
|
||||
}
|
||||
|
||||
/** Whether a dispatch can run in place instead of through a helper call:
|
||||
* the receiver is a plain read, so testing and narrowing it once per arm
|
||||
* reads the same value, and the other operands are plain reads or
|
||||
* literals. The arms' own reads then stay visible to the integer range
|
||||
* analysis (a loop bounded by `u.length` keeps an integer counter). */
|
||||
function inlineDispatch(receiver: IrExpr, operands: readonly IrExpr[]): boolean {
|
||||
return (
|
||||
receiver.kind === "varRef" && operands.every((e) => e.kind === "varRef" || e.kind === "numLit")
|
||||
);
|
||||
}
|
||||
|
||||
/** Expressions that run no program code: reads, literals and operators
|
||||
* over primitive values. */
|
||||
const CODE_FREE_EXPRS = new Set<IrExpr["kind"]>([
|
||||
"numLit",
|
||||
"boolLit",
|
||||
"strLit",
|
||||
"unitLit",
|
||||
"varRef",
|
||||
"unary",
|
||||
"logical",
|
||||
"ternary",
|
||||
"toBool",
|
||||
"strEq",
|
||||
"strCmp",
|
||||
"arrayGet",
|
||||
"arrayHas",
|
||||
"arrayState",
|
||||
"bytesIntrinsic",
|
||||
"fieldGet",
|
||||
"recordGet",
|
||||
"unionNarrow",
|
||||
"unionIsTag",
|
||||
"unionDisc",
|
||||
"upcast",
|
||||
"nullish",
|
||||
]);
|
||||
const PRIMITIVE_OPERANDS = new Set<IrType["kind"]>(["f64", "bool", "string", "bigint"]);
|
||||
|
||||
/** Whether evaluating `e` can rebind one of the plain reads `reads`: by
|
||||
* assigning it, or by running program code (a call, a getter, a
|
||||
* conversion) that could assign a captured binding. */
|
||||
function rebinds(e: IrExpr, reads: readonly IrExpr[]): boolean {
|
||||
const ids = new Set(reads.flatMap((r) => (r.kind === "varRef" ? [r.localId] : [])));
|
||||
let found = false;
|
||||
const expr = (x: IrExpr): boolean => {
|
||||
if ((x.kind === "assignExpr" || x.kind === "incDec") && ids.has(x.localId)) found = true;
|
||||
else if (x.kind === "bin") {
|
||||
if (!PRIMITIVE_OPERANDS.has(x.left.type.kind) || !PRIMITIVE_OPERANDS.has(x.right.type.kind))
|
||||
found = true;
|
||||
} else if (x.kind === "call") {
|
||||
// The union dispatch helpers only read and store elements.
|
||||
if (!x.callee.startsWith("%union.")) found = true;
|
||||
} else if (!CODE_FREE_EXPRS.has(x.kind)) found = true;
|
||||
return !found && everyExprChild(x, expr, stmt);
|
||||
};
|
||||
const stmt = (x: IrStmt): boolean => {
|
||||
if ((x.kind === "assign" || x.kind === "varDecl") && ids.has(x.localId)) found = true;
|
||||
return !found && everyStmtChild(x, expr, stmt);
|
||||
};
|
||||
expr(e);
|
||||
return found;
|
||||
}
|
||||
|
||||
/** The in-place form of a dispatch: a ternary chain over the arms' tags,
|
||||
* the last arm untested. */
|
||||
function inlineArms(
|
||||
receiver: IrExpr,
|
||||
arms: readonly IndexedArm[],
|
||||
type: IrType,
|
||||
arm: (narrowed: IrExpr, info: IndexedArm) => IrExpr,
|
||||
loc: SrcLoc,
|
||||
): IrExpr {
|
||||
const union = receiver.type;
|
||||
if (union.kind !== "union") throw new Error("indexed-union dispatch over a non-union");
|
||||
const narrowed = (info: IndexedArm): IrExpr => ({
|
||||
kind: "unionNarrow",
|
||||
unionId: union.unionId,
|
||||
tag: info.tag,
|
||||
value: receiver,
|
||||
type: info.type,
|
||||
loc,
|
||||
});
|
||||
let result = arm(narrowed(arms[arms.length - 1]!), arms[arms.length - 1]!);
|
||||
for (let i = arms.length - 2; i >= 0; i--) {
|
||||
const info = arms[i]!;
|
||||
result = {
|
||||
kind: "ternary",
|
||||
cond: {
|
||||
kind: "unionIsTag",
|
||||
unionId: union.unionId,
|
||||
tag: info.tag,
|
||||
negated: false,
|
||||
value: receiver,
|
||||
type: BOOL,
|
||||
loc,
|
||||
},
|
||||
then: arm(narrowed(info), info),
|
||||
else_: result,
|
||||
type,
|
||||
loc,
|
||||
};
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -29,7 +29,7 @@ interface Fixture {
|
||||
notes: KeyOrderNotes;
|
||||
record(fields: [string, IrType][], order: string[]): IrType & { kind: "record" };
|
||||
literal(type: IrType, keys: string[], segments?: KeyOrderSegment[]): IrExpr;
|
||||
run(body: IrStmt[]): IrFunction;
|
||||
run(body: IrStmt[], name?: string): IrFunction;
|
||||
order(type: IrType & { kind: "record" }): string[] | undefined;
|
||||
}
|
||||
|
||||
@@ -73,8 +73,8 @@ function fixture(): Fixture {
|
||||
segments ?? keys.map((name) => ({ kind: "key", name, definite: true })),
|
||||
);
|
||||
};
|
||||
const run = (body: IrStmt[]): IrFunction => {
|
||||
const fn: IrFunction = { name: "main", params: [], returnType: F64, locals: [], body, loc };
|
||||
const run = (body: IrStmt[], name = "main"): IrFunction => {
|
||||
const fn: IrFunction = { name, params: [], returnType: F64, locals: [], body, loc };
|
||||
applyKeyOrderWitnesses(lowerer, [fn]);
|
||||
return fn;
|
||||
};
|
||||
@@ -706,7 +706,10 @@ test("a spread reads its source's order right after the literal evaluates the so
|
||||
|
||||
/** `{ a, b }` with a declared table `["a", "b"]` and a literal `{ b, a }`
|
||||
* plus `{ ...value, a }` of the same shape, beside `extra`. */
|
||||
function selfCopy(extra: (f: Fixture, ab: IrType & { kind: "record" }) => IrStmt[]): string[] {
|
||||
function selfCopy(
|
||||
extra: (f: Fixture, ab: IrType & { kind: "record" }) => IrStmt[],
|
||||
fnName = "main",
|
||||
): string[] {
|
||||
const f = fixture();
|
||||
const ab = f.record(
|
||||
[
|
||||
@@ -716,11 +719,14 @@ function selfCopy(extra: (f: Fixture, ab: IrType & { kind: "record" }) => IrStmt
|
||||
["a", "b"],
|
||||
);
|
||||
const self: KeyOrderSegment = { kind: "spread", shapeId: ab.shapeId, maybeAbsent: false };
|
||||
f.run([
|
||||
decl("v", f.literal(ab, ["b", "a"])),
|
||||
observe(f.literal(ab, ["a", "b"], [self, { kind: "key", name: "a", definite: true }])),
|
||||
...extra(f, ab),
|
||||
]);
|
||||
f.run(
|
||||
[
|
||||
decl("v", f.literal(ab, ["b", "a"])),
|
||||
observe(f.literal(ab, ["a", "b"], [self, { kind: "key", name: "a", definite: true }])),
|
||||
...extra(f, ab),
|
||||
],
|
||||
fnName,
|
||||
);
|
||||
return f.order(ab)!;
|
||||
}
|
||||
|
||||
@@ -762,6 +768,31 @@ test("a replaceable method's checked result builds records when a replacement ma
|
||||
).toEqual(["a", "b"]);
|
||||
});
|
||||
|
||||
/** A native callback taking the shape, boxed for JavaScript. */
|
||||
const boxedCallback = (ab: IrType): IrExpr => ({
|
||||
kind: "dynFrom",
|
||||
value: {
|
||||
kind: "closure",
|
||||
fnName: "callback",
|
||||
captures: [],
|
||||
type: { kind: "func", params: [ab], ret: { kind: "void" } },
|
||||
loc,
|
||||
},
|
||||
type: { kind: "dyn" },
|
||||
loc,
|
||||
});
|
||||
|
||||
test("a native callback boxed for JavaScript receives records JavaScript builds", () => {
|
||||
expect(selfCopy((_, ab) => [observe(boxedCallback(ab))])).toEqual(["a", "b"]);
|
||||
});
|
||||
|
||||
test("a class's prototype slots box its methods without building their parameters", () => {
|
||||
expect(selfCopy((_, ab) => [observe(boxedCallback(ab))], "%prototype.data.Service")).toEqual([
|
||||
"b",
|
||||
"a",
|
||||
]);
|
||||
});
|
||||
|
||||
test("a replaceable method's result keeps its witness through an IR rewrite", () => {
|
||||
expect(
|
||||
selfCopy((f, ab) => {
|
||||
|
||||
@@ -292,6 +292,17 @@ function replacesWithoutRecords(lowerer: Lowerer, site: ts.Node): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
/** A compiler helper that boxes a class's own state for JavaScript's reads:
|
||||
* its prototype data and the property and method dispatch over boxed
|
||||
* instances. */
|
||||
function boxesOwnState(fnName: string): boolean {
|
||||
return (
|
||||
fnName.startsWith("%prototype.data.") ||
|
||||
fnName.startsWith("%dyn.class.") ||
|
||||
fnName.startsWith("%class.")
|
||||
);
|
||||
}
|
||||
|
||||
/** A type whose values are primitives (or void): it holds no record. */
|
||||
function primitiveOnly(type: ts.Type): boolean {
|
||||
if (type.isUnionType()) return ts.constituentTypes(type).every(primitiveOnly);
|
||||
@@ -357,8 +368,18 @@ export function applyKeyOrderWitnesses(lowerer: Lowerer, fns: readonly IrFunctio
|
||||
* its checked field setters, each a witness of its own. A checked
|
||||
* function's parameters receive native values: a record parameter is
|
||||
* passed out, never built, though a callback among them receives values
|
||||
* built from JavaScript again. */
|
||||
const shapesIn = (type: IrType, out: Set<string>, seen: Set<string>, produced = false): void => {
|
||||
* built from JavaScript again. `built` false starts the walk at a value
|
||||
* passed out (a native value boxed for JavaScript); `writes` false leaves
|
||||
* out what JavaScript could write into the containers passed out, so the
|
||||
* walk counts only what the functions among them receive. */
|
||||
const shapesIn = (
|
||||
type: IrType,
|
||||
out: Set<string>,
|
||||
seen: Set<string>,
|
||||
produced = false,
|
||||
built = true,
|
||||
writes = true,
|
||||
): void => {
|
||||
const visit = (t: IrType, built: boolean): boolean => {
|
||||
const mark = built ? "" : "-";
|
||||
// A container JavaScript builds converts into fresh native storage, so
|
||||
@@ -367,7 +388,7 @@ export function applyKeyOrderWitnesses(lowerer: Lowerer, fns: readonly IrFunctio
|
||||
// such as callbacks whose parameters it then builds (children passed
|
||||
// out). Those children count in both directions.
|
||||
const child = (type: IrType): boolean => {
|
||||
visit(type, true);
|
||||
if (built || writes) visit(type, true);
|
||||
if (!built) visit(type, false);
|
||||
return true;
|
||||
};
|
||||
@@ -401,7 +422,7 @@ export function applyKeyOrderWitnesses(lowerer: Lowerer, fns: readonly IrFunctio
|
||||
}
|
||||
return everyTypeChild(t, child);
|
||||
};
|
||||
visit(type, true);
|
||||
visit(type, built);
|
||||
};
|
||||
const opaqueShapes = new Set<string>();
|
||||
const opaqueSeen = new Set<string>();
|
||||
@@ -412,6 +433,7 @@ export function applyKeyOrderWitnesses(lowerer: Lowerer, fns: readonly IrFunctio
|
||||
* declaration's order, the order their table holds. */
|
||||
const declaredShapes = new Set<string>();
|
||||
const declaredSeen = new Set<string>();
|
||||
const boxedSeen = new Set<string>();
|
||||
/** The checked result of a replaceable method call while every site that
|
||||
* can replace the method installs functions that return no record. */
|
||||
const unchangedMethodResult = (node: IrExpr): boolean => {
|
||||
@@ -518,6 +540,16 @@ export function applyKeyOrderWitnesses(lowerer: Lowerer, fns: readonly IrFunctio
|
||||
case "jsonStringify":
|
||||
case "dynFrom":
|
||||
observedRoots.push(e.value.type);
|
||||
// A native value the program hands to JavaScript: the callbacks it
|
||||
// holds (itself, a field, an element) receive records JavaScript
|
||||
// builds. The helpers that box the program's own state for
|
||||
// JavaScript's reads (a class's prototype slots and property
|
||||
// dispatch) hand out the class's methods, whose arguments the
|
||||
// program's own calls pass as native values, as a replaceable
|
||||
// method's result above. Writes through the boxed value are left
|
||||
// out: reading a boxed value creates no record.
|
||||
if (!boxesOwnState(fnName))
|
||||
shapesIn(e.value.type, runtimeShapes, boxedSeen, true, false, false);
|
||||
return;
|
||||
case "recordKeyGet":
|
||||
observedRoots.push(e.obj.type);
|
||||
|
||||
@@ -1355,7 +1355,7 @@ function lowerAssertMatch(
|
||||
lowerer.noLowering(`${surface} with ${expr.arguments.nodes.length} arguments`, expr);
|
||||
}
|
||||
const s = lowerer.lowerExprExpecting(expr.arguments.nodes[0]!, STRING);
|
||||
const re = lowerer.lowerExpr(expr.arguments.nodes[1]!);
|
||||
const re = lowerExpectedValue(lowerer, expr.arguments.nodes[1]!);
|
||||
if (re.type.kind !== "regex") {
|
||||
lowerer.noLowering(
|
||||
`${surface} with a non-regex pattern`,
|
||||
@@ -1420,6 +1420,18 @@ function inErrorHierarchy(lowerer: Lowerer, className: string): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
/** An expected string or regex: a value JavaScript stores checked-dynamic
|
||||
* (an object literal's field, an untyped binding) converts to the string
|
||||
* or regex its checker type names, so the comparison takes that arm. */
|
||||
function lowerExpectedValue(lowerer: Lowerer, node: ts.Expression): IrExpr {
|
||||
const value = lowerer.lowerExpr(node);
|
||||
if (value.type.kind !== "dyn") return value;
|
||||
const expected = lowerer.mapTypeOf(lowerer.typeOf(node));
|
||||
return expected?.kind === "string" || expected?.kind === "regex"
|
||||
? lowerer.coerceToExpected(value, expected)
|
||||
: value;
|
||||
}
|
||||
|
||||
/** Classify the expected argument: string → message, regex value → the
|
||||
* regex test over String(error), an error-class identifier → instanceof,
|
||||
* an object LITERAL over name/message/code (string or regex values) →
|
||||
@@ -1436,7 +1448,7 @@ function classifyThrowsExpected(
|
||||
return { form: "message", msg: m.msg, hasMsg: m.hasMsg };
|
||||
}
|
||||
if (expectedT?.kind === "regex") {
|
||||
return { form: "regex", value: lowerer.lowerExpr(node) };
|
||||
return { form: "regex", value: lowerExpectedValue(lowerer, node) };
|
||||
}
|
||||
const sym = ts.isIdentifier(node) ? lowerer.resolveValueSymbol(node) : null;
|
||||
const info =
|
||||
@@ -1509,7 +1521,7 @@ function classifyThrowsExpected(
|
||||
);
|
||||
}
|
||||
const valueNode = ts.isPropertyAssignment(named) ? named.initializer : named.name;
|
||||
const value = lowerer.lowerExpr(valueNode);
|
||||
const value = lowerExpectedValue(lowerer, valueNode);
|
||||
if (value.type.kind === "string") {
|
||||
byId.set(id, { id, kind: "str", value, enameBake: null });
|
||||
} else if (value.type.kind === "regex") {
|
||||
|
||||
@@ -260,6 +260,7 @@ import {
|
||||
completeArgs,
|
||||
} from "./call-arguments.js";
|
||||
import { isThisParameter, type ParamShape } from "./call-signatures.js";
|
||||
import { dynamicOverloadChoice } from "./overload-choice.js";
|
||||
import { lowerStringIteratorValue } from "./iterator-adapters.js";
|
||||
import { checkedArmExtraction } from "./coercions/unions.js";
|
||||
import { maybePromiseReturnStmt, promiseArmedUnionOf } from "./maybe-promise.js";
|
||||
@@ -5506,6 +5507,9 @@ function reconcileOverloadReturn(
|
||||
expr: ts.CallExpression | ts.TaggedTemplateExpression,
|
||||
call: IrExpr,
|
||||
): IrExpr {
|
||||
// The checker's overload is a guess for a checked-dynamic argument
|
||||
// another overload accepts: the implementation's value stands.
|
||||
if (ts.isCallExpression(expr) && dynamicOverloadChoice(lowerer, expr)) return call;
|
||||
const rsig = lowerer.checker.getResolvedSignature(expr);
|
||||
const rdecl = rsig ? rsig.declaration : undefined;
|
||||
// Nominal covariant overrides share the base's return ABI, but retain
|
||||
|
||||
@@ -72,7 +72,7 @@ import {
|
||||
import { nsMemberIdentOf } from "./lower-namespaces.js";
|
||||
import { bindingNeverReassigned } from "./binding-analysis.js";
|
||||
import { implicitMonoFile } from "./generic-functions.js";
|
||||
import { lowerTaggedTemplate } from "./lower-calls.js";
|
||||
import { lowerPrimitiveUnionNumber, lowerTaggedTemplate } from "./lower-calls.js";
|
||||
import { unitOnlyUnion } from "../type-mapper.js";
|
||||
import { lowerYield } from "./lower-generators.js";
|
||||
import { unionWideningTags } from "../../ir/analysis.js";
|
||||
@@ -426,6 +426,12 @@ function lowerExprInner(lowerer: Lowerer, expr: ts.Expression): IrExpr {
|
||||
return inner;
|
||||
const use = runtimeOptionalUseOf(expr);
|
||||
if (runtimeOptionalAssertionErases(lowerer, expr, inner, use)) return inner;
|
||||
// A destination that holds null or undefined keeps the value, as `!`
|
||||
// does in JavaScript (`return cache.get(key)!` from a function that
|
||||
// returns `T | null`); the destination's own coercion re-tags it.
|
||||
if (assertionDestinationHoldsNullish(lowerer, expr, inner.type)) return inner;
|
||||
const operand = assertionOperand(lowerer, expr, inner, target ?? null, loc);
|
||||
if (operand) return operand;
|
||||
if (target && target.kind !== "union" && !typeEquals(target, inner.type)) {
|
||||
const helper = lowerer.narrowedArmHelper(inner.type.unionId, target, loc);
|
||||
if (helper) {
|
||||
@@ -933,6 +939,210 @@ export function assertedElementKeepsUndefined(
|
||||
);
|
||||
}
|
||||
|
||||
/** Whether `node!` is a returned value, an arrow function's body or a call
|
||||
* argument whose destination type (the return or parameter type) is `any`
|
||||
* or `unknown` (as for `String(x!)` and `Number(x!)`) or holds null or
|
||||
* undefined that the union `inner` holds and the assertion would remove.
|
||||
* Bindings and assignments are left out: the checker narrows them to the
|
||||
* asserted type for later reads. */
|
||||
function assertionDestinationHoldsNullish(
|
||||
lowerer: Lowerer,
|
||||
node: ts.NonNullExpression,
|
||||
inner: IrType & { kind: "union" },
|
||||
): boolean {
|
||||
const holdsNull = lowerer.armTag(inner.unionId, NULL_T) >= 0;
|
||||
const holdsUndefined = lowerer.armTag(inner.unionId, UNDEFINED_T) >= 0;
|
||||
if (!holdsNull && !holdsUndefined) return false;
|
||||
let outer: ts.Expression = node;
|
||||
while (ts.isParenthesizedExpression(outer.parent)) outer = outer.parent;
|
||||
const parent = outer.parent;
|
||||
const destination =
|
||||
(ts.isReturnStatement(parent) && parent.expression === outer) ||
|
||||
(ts.isArrowFunction(parent) && parent.body === outer) ||
|
||||
((ts.isCallExpression(parent) || ts.isNewExpression(parent)) &&
|
||||
parent.arguments?.nodes.includes(outer) === true);
|
||||
if (!destination) return false;
|
||||
const contextual = lowerer.checker.getContextualType(outer);
|
||||
if (!contextual) return false;
|
||||
const nullish =
|
||||
ts.TypeFlags.Any |
|
||||
ts.TypeFlags.Unknown |
|
||||
(holdsNull ? ts.TypeFlags.Null : 0) |
|
||||
(holdsUndefined && !optionalStdlibParameter(lowerer, parent, outer)
|
||||
? ts.TypeFlags.Undefined
|
||||
: 0);
|
||||
if ((contextual.flags & ts.TypeFlags.Union) === 0) return (contextual.flags & nullish) !== 0;
|
||||
return constituentTypes(contextual).some((type) => (type.flags & nullish) !== 0);
|
||||
}
|
||||
|
||||
/** Whether `argument` of `call` binds an optional parameter of a standard
|
||||
* library declaration (`decoder.decode(input?)`). The undefined such a
|
||||
* parameter's type holds comes from its optionality, and the builtin
|
||||
* lowerings read the argument as the declared type, so `x!` keeps the
|
||||
* checked narrowing there. */
|
||||
function optionalStdlibParameter(
|
||||
lowerer: Lowerer,
|
||||
call: ts.Node,
|
||||
argument: ts.Expression,
|
||||
): boolean {
|
||||
if (!ts.isCallExpression(call) && !ts.isNewExpression(call)) return false;
|
||||
const declaration = lowerer.checker.getResolvedSignature(call)?.declaration;
|
||||
if (declaration === undefined || !lowerer.isStdlibFile(ts.getSourceFileOfNode(declaration)))
|
||||
return false;
|
||||
const index = call.arguments?.nodes.indexOf(argument) ?? -1;
|
||||
const parameter = declaration.parameters?.nodes[index];
|
||||
return (
|
||||
parameter !== undefined &&
|
||||
parameter.dotDotDotToken === undefined &&
|
||||
(parameter.questionToken !== undefined || parameter.initializer !== undefined)
|
||||
);
|
||||
}
|
||||
|
||||
/** `x!` as the operand of an operator that converts its operands: an
|
||||
* arithmetic, bitwise, relational or equality operator, `+`, a compound
|
||||
* assignment, a unary `-`, `+`, `~` or `!`, a template span, or an argument
|
||||
* of a Math function. `!` performs no runtime check,
|
||||
* so a value that still holds undefined or null reaches the operator, which
|
||||
* converts it as JavaScript does: NaN or 0 in arithmetic, false in a
|
||||
* comparison, "undefined" or "null" in a string. Returns the operand to
|
||||
* use, or null where the assertion narrows as usual. A numeric use gets the
|
||||
* value converted with ToNumber; other uses get the union itself. */
|
||||
function assertionOperand(
|
||||
lowerer: Lowerer,
|
||||
expr: ts.NonNullExpression,
|
||||
inner: IrExpr,
|
||||
target: IrType | null,
|
||||
loc: SrcLoc,
|
||||
): IrExpr | null {
|
||||
if (inner.type.kind !== "union" || target === null || target.kind === "union") return null;
|
||||
const arms = lowerer.unions.get(inner.type.unionId)?.arms;
|
||||
if (
|
||||
!arms?.some(isUnitType) ||
|
||||
!arms.every(
|
||||
(arm) =>
|
||||
arm.kind === "f64" || arm.kind === "string" || arm.kind === "bool" || isUnitType(arm),
|
||||
)
|
||||
)
|
||||
return null;
|
||||
// Array and typed-array element reads keep their own handling of a
|
||||
// missing element.
|
||||
let operand: ts.Expression = expr.expression;
|
||||
while (ts.isParenthesizedExpression(operand)) operand = operand.expression;
|
||||
if (ts.isElementAccessExpression(operand)) {
|
||||
const kind = lowerer.mapTypeOf(lowerer.typeOf(operand.expression))?.kind;
|
||||
if (kind === "array" || kind === "bytes") return null;
|
||||
}
|
||||
const use = convertingUseOf(lowerer, expr);
|
||||
if (use === null) return null;
|
||||
if (use === "value") return inner;
|
||||
return lowerPrimitiveUnionNumber(lowerer, inner, expr, loc);
|
||||
}
|
||||
|
||||
/** How the converting use of `x!` (see assertionOperand) reads it:
|
||||
* "number" where the use applies ToNumber, "value" where the consumer
|
||||
* lowers the union itself (strings, equality, truthiness), null for other
|
||||
* uses. */
|
||||
function convertingUseOf(lowerer: Lowerer, expr: ts.NonNullExpression): "number" | "value" | null {
|
||||
let outer: ts.Expression = expr;
|
||||
while (ts.isParenthesizedExpression(outer.parent)) outer = outer.parent;
|
||||
const parent = outer.parent;
|
||||
if (ts.isTemplateSpan(parent)) return parent.expression === outer ? "value" : null;
|
||||
if (ts.isPrefixUnaryExpression(parent)) {
|
||||
if (parent.operator === ts.SyntaxKind.ExclamationToken) return "value";
|
||||
return parent.operator === ts.SyntaxKind.MinusToken ||
|
||||
parent.operator === ts.SyntaxKind.PlusToken ||
|
||||
parent.operator === ts.SyntaxKind.TildeToken
|
||||
? "number"
|
||||
: null;
|
||||
}
|
||||
if (ts.isCallExpression(parent) && parent.arguments.nodes.includes(outer)) {
|
||||
const callee = parent.expression;
|
||||
return ts.isPropertyAccessExpression(callee) &&
|
||||
stdlibGlobalNameOf(lowerer, callee.expression) === "Math"
|
||||
? "number"
|
||||
: null;
|
||||
}
|
||||
if (!ts.isBinaryExpression(parent)) return null;
|
||||
const op = parent.operatorToken.kind;
|
||||
if (EQUALITY_OPERATORS.has(op)) return "value";
|
||||
const other = parent.left === outer ? parent.right : parent.left;
|
||||
const isString = (node: ts.Expression): boolean =>
|
||||
(lowerer.typeOf(node).flags & ts.TypeFlags.StringLike) !== 0;
|
||||
// With a string on either side, `+` concatenates and a comparison
|
||||
// compares strings. `undefined + 1` and `undefined + undefined` are NaN,
|
||||
// which a string-typed result cannot hold, so `+` takes the union only
|
||||
// with a string partner that is not itself asserted. A partner that may
|
||||
// hold a string or a number at run time (`any`, `unknown`) also gets the
|
||||
// union, and `+` decides between concatenation and addition when it runs.
|
||||
if (op === ts.SyntaxKind.PlusToken || op === ts.SyntaxKind.PlusEqualsToken) {
|
||||
if (op === ts.SyntaxKind.PlusEqualsToken && parent.right !== outer) return null;
|
||||
let partner = other;
|
||||
while (ts.isParenthesizedExpression(partner)) partner = partner.expression;
|
||||
if (isString(other)) return ts.isNonNullExpression(partner) ? null : "value";
|
||||
if (!numericPartner(lowerer.typeOf(other))) return "value";
|
||||
return isString(expr) ? null : "number";
|
||||
}
|
||||
if (RELATIONAL_OPERATORS.has(op)) return isString(other) || isString(expr) ? "value" : "number";
|
||||
if (NUMERIC_OPERATORS.has(op)) return "number";
|
||||
return NUMERIC_COMPOUNDS.has(op) && parent.right === outer ? "number" : null;
|
||||
}
|
||||
|
||||
/** A `+` partner whose every value is a number, a boolean, null or
|
||||
* undefined: `+` adds with it. */
|
||||
function numericPartner(type: ts.Type): boolean {
|
||||
const numeric =
|
||||
ts.TypeFlags.NumberLike |
|
||||
ts.TypeFlags.BooleanLike |
|
||||
ts.TypeFlags.Null |
|
||||
ts.TypeFlags.Undefined |
|
||||
ts.TypeFlags.Void;
|
||||
return (type.flags & ts.TypeFlags.Union) !== 0
|
||||
? constituentTypes(type).every((part) => (part.flags & numeric) !== 0)
|
||||
: (type.flags & numeric) !== 0;
|
||||
}
|
||||
|
||||
const EQUALITY_OPERATORS = new Set<ts.SyntaxKind>([
|
||||
ts.SyntaxKind.EqualsEqualsEqualsToken,
|
||||
ts.SyntaxKind.ExclamationEqualsEqualsToken,
|
||||
ts.SyntaxKind.EqualsEqualsToken,
|
||||
ts.SyntaxKind.ExclamationEqualsToken,
|
||||
]);
|
||||
|
||||
const RELATIONAL_OPERATORS = new Set<ts.SyntaxKind>([
|
||||
ts.SyntaxKind.LessThanToken,
|
||||
ts.SyntaxKind.GreaterThanToken,
|
||||
ts.SyntaxKind.LessThanEqualsToken,
|
||||
ts.SyntaxKind.GreaterThanEqualsToken,
|
||||
]);
|
||||
|
||||
const NUMERIC_OPERATORS = new Set<ts.SyntaxKind>([
|
||||
ts.SyntaxKind.MinusToken,
|
||||
ts.SyntaxKind.AsteriskToken,
|
||||
ts.SyntaxKind.SlashToken,
|
||||
ts.SyntaxKind.PercentToken,
|
||||
ts.SyntaxKind.AsteriskAsteriskToken,
|
||||
ts.SyntaxKind.AmpersandToken,
|
||||
ts.SyntaxKind.BarToken,
|
||||
ts.SyntaxKind.CaretToken,
|
||||
ts.SyntaxKind.LessThanLessThanToken,
|
||||
ts.SyntaxKind.GreaterThanGreaterThanToken,
|
||||
ts.SyntaxKind.GreaterThanGreaterThanGreaterThanToken,
|
||||
]);
|
||||
|
||||
const NUMERIC_COMPOUNDS = new Set<ts.SyntaxKind>([
|
||||
ts.SyntaxKind.MinusEqualsToken,
|
||||
ts.SyntaxKind.AsteriskEqualsToken,
|
||||
ts.SyntaxKind.SlashEqualsToken,
|
||||
ts.SyntaxKind.PercentEqualsToken,
|
||||
ts.SyntaxKind.AsteriskAsteriskEqualsToken,
|
||||
ts.SyntaxKind.AmpersandEqualsToken,
|
||||
ts.SyntaxKind.BarEqualsToken,
|
||||
ts.SyntaxKind.CaretEqualsToken,
|
||||
ts.SyntaxKind.LessThanLessThanEqualsToken,
|
||||
ts.SyntaxKind.GreaterThanGreaterThanEqualsToken,
|
||||
ts.SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken,
|
||||
]);
|
||||
|
||||
export function runtimeOptionalAssertionErases(
|
||||
lowerer: Lowerer,
|
||||
expr: ts.Expression,
|
||||
|
||||
@@ -736,11 +736,7 @@ function inspectSupport(
|
||||
case "array":
|
||||
return inspectSupport(lowerer, t.elem, visiting, out);
|
||||
case "bytes":
|
||||
// A Uint8Array and a Buffer share the u8 representation and print
|
||||
// differently; the other element kinds are never Buffers.
|
||||
return t.elem === "u8"
|
||||
? "Uint8Array and Buffer values inside composites have no inspect lowering yet (Buffer's <Buffer ..> form vs Uint8Array's is not recorded in the static type here)"
|
||||
: null;
|
||||
return null;
|
||||
case "record": {
|
||||
if (visiting.has(t.shapeId)) {
|
||||
out.recursive = true;
|
||||
@@ -1061,7 +1057,15 @@ function inspectExprBody(
|
||||
loc,
|
||||
};
|
||||
}
|
||||
return { kind: "libCall", fn: "insp.buffer", args: [value], type: STRING, loc };
|
||||
// A Uint8Array, a Buffer and a DataView share the u8 representation
|
||||
// and print differently: the view's own flags pick.
|
||||
return {
|
||||
kind: "libCall",
|
||||
fn: "insp.bytes",
|
||||
args: [value, recurse, depth],
|
||||
type: STRING,
|
||||
loc,
|
||||
};
|
||||
case "dyn":
|
||||
return { kind: "libCall", fn: "insp.dyn", args: [value, recurse, depth], type: STRING, loc };
|
||||
case "generator":
|
||||
@@ -2292,15 +2296,17 @@ export function lowerConsoleInspectArg(
|
||||
);
|
||||
}
|
||||
if (!isBufferTypeName(tname)) {
|
||||
// A u8 value the checker types as a Uint8Array may still hold a
|
||||
// Buffer, which Node prints as one: the view's flags pick.
|
||||
return {
|
||||
kind: "libCall",
|
||||
fn: "insp.typedArray",
|
||||
fn: t.elem === "u8" ? "insp.bytes" : "insp.typedArray",
|
||||
args: [value, numLit(0, loc), numLit(2, loc)],
|
||||
type: STRING,
|
||||
loc,
|
||||
};
|
||||
}
|
||||
return inspectExpr(lowerer, t, value, numLit(0, loc), numLit(2, loc), loc);
|
||||
return { kind: "libCall", fn: "insp.buffer", args: [value], type: STRING, loc };
|
||||
}
|
||||
if (t.kind === "void") {
|
||||
// Node prints "undefined" for a void call's result; a void expression
|
||||
@@ -2653,7 +2659,10 @@ export function lowerInspectValue(
|
||||
"typedArray",
|
||||
(input) => ({
|
||||
kind: "libCall",
|
||||
fn: "insp.typedArray",
|
||||
fn:
|
||||
value.type.kind === "bytes" && value.type.elem === "u8"
|
||||
? "insp.bytes"
|
||||
: "insp.typedArray",
|
||||
args: [input, numLit(0, loc), numLit(options.depth, loc)],
|
||||
type: STRING,
|
||||
loc,
|
||||
@@ -2662,7 +2671,7 @@ export function lowerInspectValue(
|
||||
);
|
||||
}
|
||||
// Buffers render fully at any depth and on one line (custom inspect).
|
||||
return inspectExpr(lowerer, value.type, value, numLit(0, loc), numLit(2, loc), loc);
|
||||
return { kind: "libCall", fn: "insp.buffer", args: [value], type: STRING, loc };
|
||||
}
|
||||
const walk = { recursive: false };
|
||||
const reason = inspectSupport(lowerer, value.type, new Set(), walk);
|
||||
|
||||
@@ -43,10 +43,14 @@ import {
|
||||
} from "./cycle-initialization.js";
|
||||
import { markRequireEarlyBindings } from "./require-initialization.js";
|
||||
import {
|
||||
cjsHasLiveMemberExports,
|
||||
cjsTableMethodEntry,
|
||||
inlineProgramRequireOf,
|
||||
nestedCjsExportAssignmentsOf,
|
||||
requireNestedPatternsOf,
|
||||
splitRequireBindingOf,
|
||||
splitRequireBindingOfIdent,
|
||||
wholeExportSymbolOfModule,
|
||||
} from "./cjs-inline-require.js";
|
||||
import { isDeadTscHelperDecl, tscInteropBindingOfDecl } from "./cjs-tsc-interop.js";
|
||||
import { collectJsonRequires, isJsonRequireDecl } from "./json-require.js";
|
||||
@@ -1597,14 +1601,26 @@ export function collectGlobals(
|
||||
// require() of a program module is not: the exporter re-exports
|
||||
// that module's exports, which requirers resolve through the
|
||||
// checker's alias (the statement lowers to the dep's %init).
|
||||
// A split binding re-exported whole with later member writes needs
|
||||
// a mutable root: `module.exports = m; module.exports.extra = 1`
|
||||
// extends the SAME object Node exposes. Without later members the
|
||||
// binder is pure alias plumbing (no storage).
|
||||
const splitWholeBinding = ts.isIdentifier(rhs)
|
||||
? splitRequireBindingOfIdent(lowerer, rhs)
|
||||
: null;
|
||||
const hasMemberExports = cjsHasLiveMemberExports(lowerer, sf);
|
||||
const splitWhole =
|
||||
splitWholeBinding !== null &&
|
||||
wholeExportSymbolOfModule(lowerer, splitWholeBinding.dep) !== null &&
|
||||
hasMemberExports;
|
||||
const factoryValued =
|
||||
!ts.isIdentifier(rhs) &&
|
||||
(!ts.isIdentifier(rhs) || splitWhole) &&
|
||||
!ts.isClassExpression(rhs) &&
|
||||
!ts.isObjectLiteralExpression(rhs) &&
|
||||
!(
|
||||
requireSpecOf(rhs) !== null &&
|
||||
inlineProgramRequireOf(lowerer, rhs) !== null &&
|
||||
!sf.statements.nodes.some((s) => cjsExportAssignmentOf(s)?.kind === "member")
|
||||
!hasMemberExports
|
||||
) &&
|
||||
cjsExportTargetLiteral(rhs, sf) === null;
|
||||
if (cjsScalarLiteral(rhs) || fnValued || factoryValued) {
|
||||
@@ -1617,6 +1633,9 @@ export function collectGlobals(
|
||||
// A returned object remains the live CommonJS root; later
|
||||
// exports.member writes must update that same open object.
|
||||
if (factoryValued && t?.kind === "record" && lowerer.dynConvertible(t)) t = DYN;
|
||||
// A split whole-export root is extended by later member writes;
|
||||
// keep it checked-dynamic so those writes reach the same object.
|
||||
if (splitWhole && t && t.kind !== "dyn") t = DYN;
|
||||
if (t && t.kind !== "void") {
|
||||
const g: IrGlobal = {
|
||||
id: `%g.${tag}exports`,
|
||||
@@ -2361,7 +2380,6 @@ export function collectGlobals(
|
||||
// References from separately-declared functions cascade to
|
||||
// their own per-site runtime fences.
|
||||
const factoryType =
|
||||
!isLet &&
|
||||
isJsSourceFile(sf) &&
|
||||
!decl.type &&
|
||||
!hasJsTypeAnnotation(decl) &&
|
||||
@@ -2708,6 +2726,7 @@ function noteVarGlobalEntryInit(lowerer: Lowerer, sf: ts.SourceFile, g: IrGlobal
|
||||
* plumbing (lowerVarDeclarator): no storage, the reads resolve through to
|
||||
* the module. JSON documents and native FFI requires keep their storage. */
|
||||
function requireAliasDecl(lowerer: Lowerer, decl: ts.VariableDeclaration): boolean {
|
||||
if (splitRequireBindingOf(lowerer, decl) !== null) return true;
|
||||
return (
|
||||
decl.initializer !== undefined &&
|
||||
requireSpecOf(decl.initializer) !== null &&
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
import { lowerTupleAliasDecl, stripTypeWrappers } from "./typed-arguments.js";
|
||||
import {
|
||||
allBytesArms,
|
||||
indexedUnionArms,
|
||||
lowerIndexedUnionMember,
|
||||
lowerIndexedUnionNumberRead,
|
||||
lowerIndexedUnionRead,
|
||||
} from "./indexed-unions.js";
|
||||
import { declaredMemberOf, isPromisePrototypeRead } from "./expressions/property-access.js";
|
||||
import { hostsAll } from "./expressions/hosted-narrowing.js";
|
||||
import { requestGeneralStreamSurface } from "./general-streams.js";
|
||||
@@ -39,6 +46,11 @@ import {
|
||||
cjsTableMethodEntry,
|
||||
inlineProgramRequireOf,
|
||||
requireNestedPatternsOf,
|
||||
splitRequireAssignmentOf,
|
||||
splitRequireBindingOf,
|
||||
splitRequireBindingOfIdent,
|
||||
splitRequireEarlyReadOf,
|
||||
wholeExportSymbolOfModule,
|
||||
} from "./cjs-inline-require.js";
|
||||
import {
|
||||
cjsExportMemberWriteGlobalOf,
|
||||
@@ -1934,6 +1946,23 @@ function lowerVarDeclarator(
|
||||
isConst: boolean,
|
||||
isLet: boolean,
|
||||
): IrStmt[] {
|
||||
// `var m; m = require("./x")`: the declaration is alias plumbing; the
|
||||
// assignment owns the module's run-once %init (cjs-inline-require.ts).
|
||||
// A read that code before the assignment can reach keeps Node's hoisted
|
||||
// `undefined` divergence visible at build time, like a var require
|
||||
// declaration below runnable code.
|
||||
const split = splitRequireBindingOf(lowerer, decl);
|
||||
if (split !== null) {
|
||||
const early = splitRequireEarlyReadOf(lowerer, split);
|
||||
if (early !== null) {
|
||||
lowerer.unsupported(
|
||||
"SC1013",
|
||||
early,
|
||||
`var require() binding '${(decl.name as ts.Identifier).text}' below code that can reach it (Node reads undefined before the require runs, which is not modeled — assign the require above the code that can run first)`,
|
||||
);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
// The canonical ESM bridge to a compiled program module. Like a
|
||||
// top-level CommonJS require declaration, the binding is alias
|
||||
// plumbing while the dependency evaluates at this statement's
|
||||
@@ -7537,6 +7566,26 @@ function lowerCjsSingleValueExport(
|
||||
return lowerer.requireInitStmt(req.spec, req.call) ?? { kind: "block", body: [], loc };
|
||||
}
|
||||
if (ts.isIdentifier(rhs)) {
|
||||
const split = splitRequireBindingOfIdent(lowerer, rhs);
|
||||
if (split !== null) {
|
||||
if (wholeExportSymbolOfModule(lowerer, split.dep) === null) {
|
||||
lowerer.unsupported(
|
||||
"SC1090",
|
||||
rhs,
|
||||
`the exports object of '${split.spec}' as a value (its exports compile to a static table: read require(${JSON.stringify(split.spec)}).member directly)`,
|
||||
);
|
||||
}
|
||||
const root = lowerer.globalsByDeclNode.get(expr);
|
||||
if (root !== undefined) {
|
||||
return {
|
||||
kind: "assign",
|
||||
localId: root.id,
|
||||
value: lowerer.lowerExprExpecting(rhs, root.type),
|
||||
loc: locOf(rhs),
|
||||
};
|
||||
}
|
||||
return { kind: "block", body: [], loc };
|
||||
}
|
||||
const sym = lowerer.resolveValueSymbol(rhs);
|
||||
if (!sym) return null;
|
||||
if (
|
||||
@@ -8447,6 +8496,16 @@ export function lowerExprStatement(lowerer: Lowerer, expr: ts.Expression): IrStm
|
||||
if (!ts.isIdentifier(expr.left)) {
|
||||
lowerer.unsupported("SC1090", expr.left, "assignment to non-variables");
|
||||
}
|
||||
const splitAssign = splitRequireAssignmentOf(lowerer, expr);
|
||||
if (splitAssign !== null) {
|
||||
return (
|
||||
lowerer.requireInitStmt(splitAssign.spec, splitAssign.call) ?? {
|
||||
kind: "block",
|
||||
body: [],
|
||||
loc: locOf(expr),
|
||||
}
|
||||
);
|
||||
}
|
||||
const target = lowerer.resolveWritable(expr.left);
|
||||
if (!target)
|
||||
lowerer.rejectUnresolved(
|
||||
@@ -10161,13 +10220,8 @@ export function lowerForOf(lowerer: Lowerer, stmt: ts.ForOfStatement): IrStmt {
|
||||
loc: locOf(iterSrc),
|
||||
};
|
||||
}
|
||||
if (iterable.type.kind === "bytes") {
|
||||
return lowerForOfBytes(
|
||||
lowerer,
|
||||
stmt,
|
||||
iterable as IrExpr & { type: IrType & { kind: "bytes" } },
|
||||
labels,
|
||||
);
|
||||
if (iterable.type.kind === "bytes" || indexedUnionArms(lowerer, iterable.type)) {
|
||||
return lowerForOfBytes(lowerer, stmt, iterable, labels);
|
||||
}
|
||||
if (iterable.type.kind !== "array") {
|
||||
// The lib types strings as iterable too, so those for-ofs typecheck;
|
||||
@@ -10725,7 +10779,7 @@ export function lowerForOf(lowerer: Lowerer, stmt: ts.ForOfStatement): IrStmt {
|
||||
function lowerForOfBytes(
|
||||
lowerer: Lowerer,
|
||||
stmt: ts.ForOfStatement,
|
||||
iterable: IrExpr & { type: IrType & { kind: "bytes" } },
|
||||
iterable: IrExpr,
|
||||
labels?: string[],
|
||||
): IrStmt {
|
||||
const loc = locOf(stmt);
|
||||
@@ -10819,7 +10873,16 @@ function lowerForOfStoredNumericIterator(
|
||||
|
||||
const loc = locOf(stmt);
|
||||
const sourceT = state.sourceType;
|
||||
if (!((sourceT.kind === "array" && sourceT.elem.kind === "f64") || sourceT.kind === "bytes")) {
|
||||
// A union of typed arrays and number arrays (indexed-unions.ts) reads
|
||||
// through its arms' own length and element reads.
|
||||
const unionArms = indexedUnionArms(lowerer, sourceT);
|
||||
if (
|
||||
!(
|
||||
(sourceT.kind === "array" && sourceT.elem.kind === "f64") ||
|
||||
sourceT.kind === "bytes" ||
|
||||
unionArms
|
||||
)
|
||||
) {
|
||||
throw new InternalCompilerError("internal: retained numeric iterator has a non-numeric source");
|
||||
}
|
||||
|
||||
@@ -10827,35 +10890,44 @@ function lowerForOfStoredNumericIterator(
|
||||
const doneRef = (): IrExpr => varRef(state.doneLocalId, BOOL, loc);
|
||||
const sourceRef = (): IrExpr => varRef(state.sourceLocalId, sourceT, loc);
|
||||
const sourceLength = (): IrExpr =>
|
||||
sourceT.kind === "array"
|
||||
? {
|
||||
kind: "arrIntrinsic",
|
||||
method: "length",
|
||||
receiver: sourceRef(),
|
||||
args: [],
|
||||
type: F64,
|
||||
loc,
|
||||
}
|
||||
: {
|
||||
kind: "bytesIntrinsic",
|
||||
method: "length",
|
||||
receiver: sourceRef(),
|
||||
args: [],
|
||||
type: F64,
|
||||
loc,
|
||||
};
|
||||
const valueT = sourceT.kind === "array" ? arrayValueType(lowerer, F64) : F64;
|
||||
unionArms
|
||||
? lowerIndexedUnionMember(lowerer, sourceRef(), unionArms, "length", loc)!
|
||||
: sourceT.kind === "array"
|
||||
? {
|
||||
kind: "arrIntrinsic",
|
||||
method: "length",
|
||||
receiver: sourceRef(),
|
||||
args: [],
|
||||
type: F64,
|
||||
loc,
|
||||
}
|
||||
: {
|
||||
kind: "bytesIntrinsic",
|
||||
method: "length",
|
||||
receiver: sourceRef(),
|
||||
args: [],
|
||||
type: F64,
|
||||
loc,
|
||||
};
|
||||
const valueT =
|
||||
sourceT.kind === "array" || (unionArms && !allBytesArms(unionArms))
|
||||
? arrayValueType(lowerer, F64)
|
||||
: F64;
|
||||
const sourceValue = (): IrExpr =>
|
||||
sourceT.kind === "array"
|
||||
? arrayValueRead(lowerer, sourceRef(), indexRef(), F64, loc)
|
||||
: {
|
||||
kind: "bytesIntrinsic",
|
||||
method: "get",
|
||||
receiver: sourceRef(),
|
||||
args: [indexRef()],
|
||||
type: F64,
|
||||
loc,
|
||||
};
|
||||
unionArms
|
||||
? allBytesArms(unionArms)
|
||||
? lowerIndexedUnionNumberRead(lowerer, sourceRef(), unionArms, indexRef(), loc)
|
||||
: lowerIndexedUnionRead(lowerer, sourceRef(), unionArms, indexRef(), loc)
|
||||
: sourceT.kind === "array"
|
||||
? arrayValueRead(lowerer, sourceRef(), indexRef(), F64, loc)
|
||||
: {
|
||||
kind: "bytesIntrinsic",
|
||||
method: "get",
|
||||
receiver: sourceRef(),
|
||||
args: [indexRef()],
|
||||
type: F64,
|
||||
loc,
|
||||
};
|
||||
const one: IrExpr = { kind: "numLit", value: 1, type: F64, loc };
|
||||
|
||||
lowerer.scopes.push(new Map());
|
||||
|
||||
@@ -147,9 +147,14 @@ import {
|
||||
} from "./function-context.js";
|
||||
import type { FrontendServices } from "../services.js";
|
||||
import { InternalCompilerError } from "../../errors.js";
|
||||
import type { FsPathPlan } from "./builtins/fs-paths.js";
|
||||
import { defaultAfterUndefined, lowerStaticallyUndefinedArgument } from "./optional-arguments.js";
|
||||
import { type ProtocolDispatch } from "./class-protocol-dispatch.js";
|
||||
import { ClassDynamicDispatch, trackClassFieldCreation } from "./class-dynamic-dispatch.js";
|
||||
import {
|
||||
ClassDynamicDispatch,
|
||||
boxClassInstancesExactly,
|
||||
trackClassFieldCreation,
|
||||
} from "./class-dynamic-dispatch.js";
|
||||
import { guardClassAttributeWrites } from "./class-attributes.js";
|
||||
import { guardFrozenWrites, markSloppyRecordWrites } from "./frozen-records.js";
|
||||
import { applyHandleProperties } from "./handle-properties.js";
|
||||
@@ -343,10 +348,13 @@ import {
|
||||
} from "./lower-modules.js";
|
||||
import { prepareCjsModuleGraph, usesCjsTopLevelThis } from "./lower-node-module.js";
|
||||
import {
|
||||
type SplitRequireBinding,
|
||||
cjsNamespaceModule,
|
||||
cjsWholeExportValueOf,
|
||||
inlineNamespaceRequireOf,
|
||||
inlineProgramRequireOf,
|
||||
splitRequireBindingOf,
|
||||
splitWholeExportAliasTargetOf,
|
||||
} from "./cjs-inline-require.js";
|
||||
import { tscInteropModuleOf } from "./cjs-tsc-interop.js";
|
||||
import { usesCjsExportsIdentity } from "./cjs-exports-object.js";
|
||||
@@ -426,6 +434,7 @@ import {
|
||||
collectSignatureInner,
|
||||
lambdaSignature,
|
||||
} from "./call-signatures.js";
|
||||
import { dynamicOverloadChoice, guessedOverloadIdentifier } from "./overload-choice.js";
|
||||
import {
|
||||
implicitAnyParamSymbolsOf,
|
||||
implicitLocalFnNodeOf,
|
||||
@@ -2291,6 +2300,14 @@ export class Lowerer {
|
||||
/** Per CommonJS file using top-level `this`: the global holding the
|
||||
* object that stands for its original exports (lowerCjsTopLevelThis). */
|
||||
readonly cjsExportsThis = new Map<ts.SourceFile, IrGlobal>();
|
||||
/** `var m; m = require("./x")` alias bindings (cjs-inline-require.ts).
|
||||
* Null entries cache declarations that keep ordinary storage. */
|
||||
readonly cjsSplitRequireBindings = new Map<ts.VariableDeclaration, SplitRequireBinding | null>();
|
||||
/** Per-module whole-export symbol (cjs-inline-require.ts). Null means the
|
||||
* module's exports are a table. */
|
||||
readonly cjsWholeExportSymbols = new Map<ts.SourceFile, ts.Symbol | null>();
|
||||
/** Per-module live member-export classification (cjs-inline-require.ts). */
|
||||
readonly cjsLiveMemberExports = new Map<ts.SourceFile, boolean>();
|
||||
/** Inline program-module require calls whose %init the enclosing member
|
||||
* read or member call is already sequencing (cjs-inline-require.ts). */
|
||||
readonly inlineRequireInitDone = new Set<ts.CallExpression>();
|
||||
@@ -2829,6 +2846,8 @@ export class Lowerer {
|
||||
/** Parameters read as `any` in the error-path copy of an error-first
|
||||
* callback. */
|
||||
readonly anySymbols = new Set<ts.Symbol>();
|
||||
/** overload-choice's answers per call, binding and function. */
|
||||
readonly dynamicOverloadAnswers = new Map<ts.Node, boolean>();
|
||||
/** Error parameters of an error-first callback with a known value in
|
||||
* the copy being lowered: true while it holds an Error, false while it
|
||||
* holds null (staticCondition folds conditions on them). */
|
||||
@@ -2904,6 +2923,9 @@ export class Lowerer {
|
||||
/** util.inspect's per-type traversal helpers (%util.insp.N), interned
|
||||
* by typeKey — the assertHelpers pattern with its own namespace. */
|
||||
readonly inspectHelpers = new Map<string, string>();
|
||||
/** Indexed-union safe-read helpers mapped to their numeric twins, for the
|
||||
* fusion of an immediate ToNumber (tryLowerNumericIndexRead). */
|
||||
readonly indexedUnionNumericTwins = new Map<string, string>();
|
||||
private readonly unionLiteralOwners = new Map<
|
||||
string,
|
||||
{ owners: Map<string, number> | null; shapes: number; unions: number }
|
||||
@@ -3145,8 +3167,13 @@ export class Lowerer {
|
||||
* (builtins/fs-paths.ts): each lowers to the hidden local that holds its
|
||||
* value, which is null until the path's lowering has saved it. */
|
||||
readonly stagedArguments = new Map<ts.Expression, { localId: string; type: IrType } | null>();
|
||||
/** The staged arguments that follow each such URL path, in order. */
|
||||
readonly stagedAfterPath = new Map<ts.Expression, ts.Expression[]>();
|
||||
/** What each fs path argument of a URL-path call lowers to (the plans
|
||||
* of builtins/fs-paths.ts). */
|
||||
readonly fsPathPlans = new Map<ts.Expression, FsPathPlan>();
|
||||
/** The existsSync/fs.promises calls whose converted URL paths are being
|
||||
* lowered into the call itself (lowerFallibleFsUrlCall). A call may be
|
||||
* lowered more than once, and each lowering converts again. */
|
||||
readonly fallibleFsCalls = new Set<ts.CallExpression>();
|
||||
readonly moduleNsParamOverrides = new Map<
|
||||
ts.ParameterDeclaration,
|
||||
IrType & { kind: "moduleNs" }
|
||||
@@ -4130,6 +4157,11 @@ export class Lowerer {
|
||||
// registry (globals, fn signatures, classes) applies unchanged.
|
||||
const cjsValue = this.cjsExportValueSymbol(symbol);
|
||||
if (cjsValue) symbol = cjsValue;
|
||||
// `var m; m = require("./x"); module.exports = m` over a whole-export
|
||||
// target: TS types the wrapper's export= as `any`, so reconnect it to
|
||||
// the target's value symbol explicitly.
|
||||
const splitAlias = splitWholeExportAliasTargetOf(this, symbol);
|
||||
if (splitAlias) symbol = splitAlias;
|
||||
this.flushDeferred(symbol);
|
||||
return symbol;
|
||||
}
|
||||
@@ -4523,8 +4555,8 @@ export class Lowerer {
|
||||
const decl = decls.find(ts.isImportClause) ?? decls[0];
|
||||
if (!decl) return null;
|
||||
if (ts.isImportClause(decl)) return this.cjsDefaultImportDepOf(decl);
|
||||
if (!ts.isVariableDeclaration(decl) || !ts.isIdentifier(decl.name) || !decl.initializer)
|
||||
return null;
|
||||
if (!ts.isVariableDeclaration(decl) || !ts.isIdentifier(decl.name)) return null;
|
||||
if (decl.initializer === undefined) return splitRequireBindingOf(this, decl)?.dep ?? null;
|
||||
{
|
||||
const interop = tscInteropModuleOf(this, expr);
|
||||
if (interop !== null) return cjsNamespaceModule(this, interop.dep) ? interop.dep : null;
|
||||
@@ -4629,6 +4661,9 @@ export class Lowerer {
|
||||
// a binding (cjs-inline-require.ts sequences the module's %init).
|
||||
if (!ts.isIdentifier(expr)) return this.cjsModuleRefDepOf(expr) !== null;
|
||||
const sym = this.checker.getSymbolAtLocation(expr);
|
||||
const splitDecl = sym?.declarations.find(ts.isVariableDeclaration);
|
||||
const split = splitDecl === undefined ? null : splitRequireBindingOf(this, splitDecl);
|
||||
if (split !== null) return cjsNamespaceModule(this, split.dep);
|
||||
if (this.localModuleBindingDepOf(expr) === null) return false;
|
||||
if (this.createRequireWholeExportSymbolOf(expr) !== null) return false;
|
||||
// SINGLE-VALUE exporters (`module.exports = Countdown` / `= double` /
|
||||
@@ -4936,6 +4971,13 @@ export class Lowerer {
|
||||
* their external dependencies by name). Null for everything else
|
||||
* (builtins load nothing; the rest kept its preflight fence). */
|
||||
requireInitStmt(spec: string, node: ts.Node): IrStmt | null {
|
||||
if (this.inlineRequireCycleCalls.has(node)) {
|
||||
this.unsupported(
|
||||
"SC1090",
|
||||
node,
|
||||
`require() of '${spec}' while it is still evaluating (a require cycle: Node answers its partial exports, which the static export table does not model)`,
|
||||
);
|
||||
}
|
||||
if (canonicalBuiltinModule(spec) === "punycode") return this.punycodeRequireWarning(node);
|
||||
// Project requires resolve within the program; another bare require can
|
||||
// be a program-module edge when it names an opted-in --npm-static package
|
||||
@@ -7732,6 +7774,7 @@ export class Lowerer {
|
||||
finalizeClassMethodValues(this, functions);
|
||||
finalizePrivateBrands(this, functions);
|
||||
trackClassFieldCreation(this, functions);
|
||||
boxClassInstancesExactly(this, functions);
|
||||
guardClassAttributeWrites(this, functions);
|
||||
guardFrozenWrites(this, functions);
|
||||
applyHandleProperties(this, functions);
|
||||
@@ -8997,6 +9040,20 @@ export class Lowerer {
|
||||
|
||||
typeOf(node: ts.Node): ts.Type {
|
||||
if (this.anySymbols.size > 0 && this.readsAnySymbol(node)) return this.checker.getAnyType();
|
||||
// A checked-dynamic argument that another overload could take at run
|
||||
// time leaves the resolved overload's return a guess, and JS bindings
|
||||
// initialized with that result hold whatever it was.
|
||||
if (
|
||||
(ts.isCallExpression(node) || ts.isNewExpression(node)) &&
|
||||
dynamicOverloadChoice(this, node)
|
||||
)
|
||||
return this.checker.getAnyType();
|
||||
if (
|
||||
ts.isIdentifier(node) &&
|
||||
isJsSourceFile(ts.getSourceFileOfNode(node)) &&
|
||||
guessedOverloadIdentifier(this, node)
|
||||
)
|
||||
return this.checker.getAnyType();
|
||||
if (ts.isPropertyAccessExpression(node) && isJsSourceFile(ts.getSourceFileOfNode(node))) {
|
||||
const receiver =
|
||||
node.expression.kind === ts.SyntaxKind.ThisKeyword && this.fnStack.length > 0
|
||||
|
||||
@@ -6,10 +6,14 @@ import { bindingNeverReassigned } from "./binding-analysis.js";
|
||||
import { implicitDefaultInstance } from "./generic-functions.js";
|
||||
import { type FnSig } from "./call-signatures.js";
|
||||
|
||||
/** An ordinary constructor's explicit object return replaces its receiver.
|
||||
* Without observing this or new.target, it can use the function's call ABI. */
|
||||
function isObjectFactoryNew(lowerer: Lowerer, expr: ts.NewExpression): boolean {
|
||||
if (!ts.isIdentifier(expr.expression) || lowerer.peekLocal(expr.expression)) return false;
|
||||
/** The JavaScript function declaration (or never-reassigned function
|
||||
* expression binding) `new` calls, when it is an ordinary constructor: not
|
||||
* a generator or async function. */
|
||||
function jsConstructorFunctionOf(
|
||||
lowerer: Lowerer,
|
||||
expr: ts.NewExpression,
|
||||
): ts.FunctionDeclaration | ts.FunctionExpression | null {
|
||||
if (!ts.isIdentifier(expr.expression) || lowerer.peekLocal(expr.expression)) return null;
|
||||
// This probe also sees ordinary classes during global collection. Leave
|
||||
// their deferred diagnostics for the class declaration's lowering.
|
||||
const wasCollecting = lowerer.collecting;
|
||||
@@ -20,7 +24,7 @@ function isObjectFactoryNew(lowerer: Lowerer, expr: ts.NewExpression): boolean {
|
||||
} finally {
|
||||
lowerer.collecting = wasCollecting;
|
||||
}
|
||||
if (!symbol) return false;
|
||||
if (!symbol) return null;
|
||||
const owner = symbol.declarations.find(
|
||||
(node) =>
|
||||
(ts.isFunctionDeclaration(node) && node.body !== undefined) ||
|
||||
@@ -45,7 +49,15 @@ function isObjectFactoryNew(lowerer: Lowerer, expr: ts.NewExpression): boolean {
|
||||
declaration.asteriskToken ||
|
||||
declaration.modifiers?.nodes.some((m) => m.kind === ts.SyntaxKind.AsyncKeyword)
|
||||
)
|
||||
return false;
|
||||
return null;
|
||||
return declaration;
|
||||
}
|
||||
|
||||
/** An ordinary constructor's explicit object return replaces its receiver.
|
||||
* Without observing this or new.target, it can use the function's call ABI. */
|
||||
function isObjectFactoryNew(lowerer: Lowerer, expr: ts.NewExpression): boolean {
|
||||
const declaration = jsConstructorFunctionOf(lowerer, expr);
|
||||
if (!declaration?.body) return false;
|
||||
const objectReturn = (expression: ts.Expression): boolean =>
|
||||
ts.isObjectLiteralExpression(expression) ||
|
||||
ts.isArrayLiteralExpression(expression) ||
|
||||
@@ -81,8 +93,13 @@ function isObjectFactoryNew(lowerer: Lowerer, expr: ts.NewExpression): boolean {
|
||||
|
||||
/** Collection must register the shared result before reaching factory
|
||||
* bodies: those bodies can reference later globals in the same module. */
|
||||
/** The storage of a JavaScript module binding initialized with `new` of an
|
||||
* ordinary function: a factory's result and a constructor function's
|
||||
* receiver (`const head = new Segment()`) are both checked-dynamic
|
||||
* values, which functions declared elsewhere in the module read through
|
||||
* the global. */
|
||||
export function objectFactoryGlobalType(lowerer: Lowerer, expr: ts.NewExpression): IrType | null {
|
||||
return isObjectFactoryNew(lowerer, expr) ? DYN : null;
|
||||
return jsConstructorFunctionOf(lowerer, expr) !== null ? DYN : null;
|
||||
}
|
||||
|
||||
export function objectFactorySignature(lowerer: Lowerer, expr: ts.NewExpression): FnSig | null {
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
import * as ts from "../ts7/adapter.js";
|
||||
import type { Lowerer } from "./lowerer.js";
|
||||
import { typeEquals, type IrType } from "../../ir/ir.js";
|
||||
import { isJsSourceFile } from "../program.js";
|
||||
import { isThisParameter } from "./call-signatures.js";
|
||||
import { hasExplicitJsDocReturn } from "./function-returns.js";
|
||||
import { hasJsTypeAnnotation } from "./lower-stmts.js";
|
||||
|
||||
/** Whether a checked-dynamic argument leaves a JS call's overload
|
||||
* undecided.
|
||||
*
|
||||
* The checker resolves an overloaded call whose argument is `any` (an
|
||||
* untyped parameter, a value read from one) to the FIRST overload that
|
||||
* argument satisfies, but the value can match any overload at run time:
|
||||
* `generateKeyPairSync("ec", options)` answers KeyObjects or encoded
|
||||
* strings by the options' contents, `digest(encoding)` a Buffer when the
|
||||
* encoding is undefined. When another overload the call could take at
|
||||
* run time returns a different type, the resolved overload's return is a
|
||||
* guess, and the result is checked-dynamic instead.
|
||||
*
|
||||
* An overload is reachable when the arguments fit its arity (trailing
|
||||
* checked-dynamic or `undefined` arguments may be absent) and every
|
||||
* statically typed argument is assignable to its parameter. Generic
|
||||
* overloads whose return cannot be mapped without instantiation do not
|
||||
* count, so the resolved instantiation stands for them. */
|
||||
export function dynamicOverloadChoice(
|
||||
lowerer: Lowerer,
|
||||
expr: ts.CallExpression | ts.NewExpression,
|
||||
): boolean {
|
||||
return cachedAnswer(lowerer, expr, () => computeDynamicOverloadChoice(lowerer, expr));
|
||||
}
|
||||
|
||||
/** Whether a JavaScript value's checker type rests on an undecided
|
||||
* overload (dynamicOverloadChoice): the call itself, an awaited one, a
|
||||
* call to an unannotated JS function returning such a value, or a read of
|
||||
* an unannotated JS binding initialized with one (destructured or not).
|
||||
* Such a value is checked-dynamic wherever the checker's inference would
|
||||
* otherwise carry the guess into a binding or a return. */
|
||||
export function guessedOverloadValue(lowerer: Lowerer, expr: ts.Expression): boolean {
|
||||
while (ts.isParenthesizedExpression(expr) || ts.isAwaitExpression(expr)) expr = expr.expression;
|
||||
if (ts.isCallExpression(expr) || ts.isNewExpression(expr)) {
|
||||
if (!isJsSourceFile(ts.getSourceFileOfNode(expr))) return false;
|
||||
if (dynamicOverloadChoice(lowerer, expr)) return true;
|
||||
const decl = lowerer.checker.getResolvedSignature(expr)?.declaration;
|
||||
return (
|
||||
decl !== undefined &&
|
||||
(ts.isFunctionDeclaration(decl) ||
|
||||
ts.isFunctionExpression(decl) ||
|
||||
ts.isArrowFunction(decl)) &&
|
||||
isJsSourceFile(ts.getSourceFileOfNode(decl)) &&
|
||||
returnsGuessedOverloadValue(lowerer, decl)
|
||||
);
|
||||
}
|
||||
return ts.isIdentifier(expr) && guessedOverloadIdentifier(lowerer, expr);
|
||||
}
|
||||
|
||||
/** Whether a JS identifier, as a binding's declared name or as a read,
|
||||
* names a guessedOverloadBinding. */
|
||||
export function guessedOverloadIdentifier(lowerer: Lowerer, node: ts.Identifier): boolean {
|
||||
return cachedAnswer(lowerer, node, () => {
|
||||
const parent = node.parent;
|
||||
if (
|
||||
parent !== undefined &&
|
||||
(ts.isVariableDeclaration(parent) || ts.isBindingElement(parent)) &&
|
||||
parent.name === node
|
||||
)
|
||||
return guessedOverloadBinding(lowerer, parent);
|
||||
const decl = lowerer.checker.getSymbolAtLocation(node)?.valueDeclaration;
|
||||
return decl !== undefined && guessedOverloadBinding(lowerer, decl);
|
||||
});
|
||||
}
|
||||
|
||||
/** Whether `decl` is an unannotated JS variable or destructured binding
|
||||
* whose declaration's initializer is a guessedOverloadValue. */
|
||||
function guessedOverloadBinding(lowerer: Lowerer, decl: ts.Node): boolean {
|
||||
let root: ts.Node | undefined = decl;
|
||||
while (root && ts.isBindingElement(root) && root.parent && ts.isBindingPattern(root.parent)) {
|
||||
root = root.parent.parent;
|
||||
}
|
||||
if (!root) return false;
|
||||
if (!ts.isVariableDeclaration(root) || !root.initializer || root.type) return false;
|
||||
if (!isJsSourceFile(ts.getSourceFileOfNode(root)) || hasJsTypeAnnotation(root)) return false;
|
||||
const init = root.initializer;
|
||||
return cachedAnswer(lowerer, root, () => guessedOverloadValue(lowerer, init));
|
||||
}
|
||||
|
||||
/** Whether a return of the unannotated JS function `decl` itself is a
|
||||
* guessedOverloadValue. */
|
||||
export function returnsGuessedOverloadValue(
|
||||
lowerer: Lowerer,
|
||||
decl: ts.SignatureDeclaration,
|
||||
): boolean {
|
||||
if (decl.type || decl.asteriskToken || hasExplicitJsDocReturn(decl)) return false;
|
||||
return cachedAnswer(lowerer, decl, () => {
|
||||
if (ts.isArrowFunction(decl) && decl.body && !ts.isBlock(decl.body)) {
|
||||
return guessedOverloadValue(lowerer, decl.body);
|
||||
}
|
||||
let found = false;
|
||||
const scan = (node: ts.Node): void => {
|
||||
if (found || (node !== decl && ts.isFunctionLike(node))) return;
|
||||
if (ts.isReturnStatement(node) && node.expression) {
|
||||
found = guessedOverloadValue(lowerer, node.expression);
|
||||
}
|
||||
ts.forEachChild(node, scan);
|
||||
};
|
||||
scan(decl);
|
||||
return found;
|
||||
});
|
||||
}
|
||||
|
||||
/** One answer per node; a node asked again while its answer is being
|
||||
* computed (recursive functions, self-referencing bindings) answers
|
||||
* false. */
|
||||
function cachedAnswer(lowerer: Lowerer, node: ts.Node, compute: () => boolean): boolean {
|
||||
const cached = lowerer.dynamicOverloadAnswers.get(node);
|
||||
if (cached !== undefined) return cached;
|
||||
lowerer.dynamicOverloadAnswers.set(node, false);
|
||||
const answer = compute();
|
||||
lowerer.dynamicOverloadAnswers.set(node, answer);
|
||||
return answer;
|
||||
}
|
||||
|
||||
function computeDynamicOverloadChoice(
|
||||
lowerer: Lowerer,
|
||||
expr: ts.CallExpression | ts.NewExpression,
|
||||
): boolean {
|
||||
// TypeScript sources keep the resolved overload: their reads validate
|
||||
// the value against it where it is used.
|
||||
if (!isJsSourceFile(ts.getSourceFileOfNode(expr))) return false;
|
||||
const args = expr.arguments?.nodes ?? [];
|
||||
if (args.length === 0 || args.some(ts.isSpreadElement)) return false;
|
||||
const dynamic = args.map((arg) => checkedDynamicArgument(lowerer, arg));
|
||||
if (!dynamic.includes(true)) return false;
|
||||
const checker = lowerer.checker;
|
||||
const calleeType = checker.getTypeAtLocation(expr.expression);
|
||||
const signatures = ts.isNewExpression(expr)
|
||||
? checker.getConstructSignatures(calleeType)
|
||||
: checker.getCallSignatures(calleeType);
|
||||
if (signatures.length < 2) return false;
|
||||
const resolved = checker.getResolvedSignature(expr);
|
||||
if (!resolved) return false;
|
||||
const resolvedReturn = lowerer.mapTypeOf(checker.getReturnTypeOfSignature(resolved));
|
||||
if (resolvedReturn === null) return false;
|
||||
// Arguments that may be absent at run time: the trailing run of
|
||||
// checked-dynamic and `undefined` arguments.
|
||||
let present = args.length;
|
||||
while (present > 0 && (dynamic[present - 1] || isUndefinedArgument(args[present - 1]!))) {
|
||||
present--;
|
||||
}
|
||||
for (const signature of signatures) {
|
||||
const decl = signature.declaration;
|
||||
if (!decl || decl === resolved.declaration || !ts.isFunctionLike(decl)) continue;
|
||||
const generic = signature.getTypeParameters().length > 0;
|
||||
const params = decl.parameters.nodes.filter((param) => !isThisParameter(param));
|
||||
const required = params.filter(
|
||||
(param) => !param.questionToken && !param.initializer && !param.dotDotDotToken,
|
||||
).length;
|
||||
const maximum = params.some((param) => param.dotDotDotToken) ? Infinity : params.length;
|
||||
if (required > args.length || present > maximum) continue;
|
||||
const symbols = signature.getParameters();
|
||||
let fits = true;
|
||||
for (let i = 0; i < args.length && i < params.length && fits; i++) {
|
||||
if (dynamic[i] || generic || params[i]!.dotDotDotToken) continue;
|
||||
const symbol = symbols[i];
|
||||
if (!symbol) continue;
|
||||
fits = checker.isTypeAssignableTo(
|
||||
checker.getTypeAtLocation(args[i]!),
|
||||
checker.getTypeOfSymbol(symbol),
|
||||
);
|
||||
}
|
||||
if (!fits) continue;
|
||||
const candidate = lowerer.mapTypeOf(checker.getReturnTypeOfSignature(signature));
|
||||
if (candidate !== null && !holdsResult(resolvedReturn, candidate)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Whether a value of the resolved overload's mapped return also holds
|
||||
* every value of `candidate`: the same type, or a checked-dynamic one (a
|
||||
* promise of one fulfills with anything). */
|
||||
function holdsResult(resolved: IrType, candidate: IrType): boolean {
|
||||
if (resolved.kind === "dyn" || typeEquals(resolved, candidate)) return true;
|
||||
return (
|
||||
resolved.kind === "promise" &&
|
||||
candidate.kind === "promise" &&
|
||||
holdsResult(resolved.inner, candidate.inner)
|
||||
);
|
||||
}
|
||||
|
||||
function checkedDynamicArgument(lowerer: Lowerer, arg: ts.Expression): boolean {
|
||||
if (lowerer.checker.getTypeAtLocation(arg).flags & ts.TypeFlags.Any) return true;
|
||||
return (lowerer.typeOf(arg).flags & ts.TypeFlags.Any) !== 0;
|
||||
}
|
||||
|
||||
function isUndefinedArgument(arg: ts.Expression): boolean {
|
||||
return (ts.isIdentifier(arg) && arg.text === "undefined") || ts.isVoidExpression(arg);
|
||||
}
|
||||
@@ -2085,7 +2085,16 @@ export const BUILTIN_MODULE_FN_ALIASES: Record<
|
||||
"fs.readFdEncoded",
|
||||
"fs.readFdSync",
|
||||
"fs.readFdSyncBytes",
|
||||
// The runtime encoding's check before a URL path converts
|
||||
// (fs-paths.ts).
|
||||
"fs.checkReadEncoding",
|
||||
],
|
||||
// The string source's check before a URL destination converts
|
||||
// (fs-paths.ts).
|
||||
copyFileSync: ["fs.checkPath"],
|
||||
renameSync: ["fs.checkPath"],
|
||||
copyFile: ["fs.checkPath"],
|
||||
rename: ["fs.checkPath"],
|
||||
readlinkSync: ["fs.readlinkSyncStr", "fs.readlinkSyncBuffer"],
|
||||
// The bytes-data form and the { mode } options form.
|
||||
writeFileSync: ["fs.writeFileSyncBytes", "fs.writeFileModeSync"],
|
||||
|
||||
@@ -228,7 +228,8 @@ function detectAutoPackages(
|
||||
} else if (mode === "lib" && !viaTransitive) {
|
||||
// CJS packages spell their dep edges as top-level requires; the
|
||||
// import-statement scan alone would miss every one of them.
|
||||
for (const req of requiresOf(stmt)) edges.push({ spec: req.spec, loc: locOf(req.node) });
|
||||
for (const req of requiresOf(stmt, load.program))
|
||||
edges.push({ spec: req.spec, loc: locOf(req.node) });
|
||||
}
|
||||
}
|
||||
// Transitive selection counts every literal require() and import()
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type {
|
||||
CallExpression,
|
||||
ExportDeclaration,
|
||||
Identifier,
|
||||
SourceFile,
|
||||
@@ -30,6 +31,13 @@ export class ProgramAnalysis {
|
||||
readonly requireEarlyReferences = new Map<VariableDeclaration, Identifier | null>();
|
||||
/** Per file: the first top-level statement that can run user code. */
|
||||
readonly requireFirstRunnable = new Map<SourceFile, number>();
|
||||
/** Per file: split require bindings (`var m; m = require("./x")`), from
|
||||
* declaration to the require call of their one assignment
|
||||
* (splitRequireBindings7). */
|
||||
readonly splitRequireBindings = new Map<
|
||||
SourceFile,
|
||||
ReadonlyMap<VariableDeclaration, CallExpression>
|
||||
>();
|
||||
|
||||
clear(): void {
|
||||
this.createRequireReasons.clear();
|
||||
@@ -41,5 +49,6 @@ export class ProgramAnalysis {
|
||||
this.moduleEarlyBindings = null;
|
||||
this.requireEarlyReferences.clear();
|
||||
this.requireFirstRunnable.clear();
|
||||
this.splitRequireBindings.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1423,17 +1423,31 @@ function isRequireStatement7(stmt: ts.Statement): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
/** A require() occurrence of a top-level statement. `split` marks the
|
||||
* assignment of a split require binding (splitRequireBindings7): `node`
|
||||
* is its require call and `decl` the binding's declaration. */
|
||||
interface RequireOccurrence7 {
|
||||
spec: string;
|
||||
node: ts.Node;
|
||||
decl: ts.VariableDeclaration | null;
|
||||
split?: true;
|
||||
}
|
||||
|
||||
/** The require() occurrences of one top-level statement: the declaration
|
||||
* forms and the bare side-effect call. Empty for everything else. */
|
||||
function requiresOf7(
|
||||
stmt: ts.Statement,
|
||||
): { spec: string; node: ts.Node; decl: ts.VariableDeclaration | null }[] {
|
||||
* forms, the bare side-effect call, and the assignment of a split require
|
||||
* binding. Empty for everything else. */
|
||||
function requiresOf7(stmt: ts.Statement, program: ts.Program): RequireOccurrence7[] {
|
||||
if (ts.isExpressionStatement(stmt)) {
|
||||
const split = splitRequireOfStatement7(program, stmt);
|
||||
if (split !== null)
|
||||
return [
|
||||
{ spec: requireSpecOf7(split.call)!, node: split.call, decl: split.decl, split: true },
|
||||
];
|
||||
const spec = requireSpecOf7(stmt.expression);
|
||||
return spec !== null ? [{ spec, node: stmt.expression, decl: null }] : [];
|
||||
}
|
||||
if (!ts.isVariableStatement(stmt)) return [];
|
||||
const out: { spec: string; node: ts.Node; decl: ts.VariableDeclaration | null }[] = [];
|
||||
const out: RequireOccurrence7[] = [];
|
||||
for (const decl of stmt.declarationList.declarations.nodes) {
|
||||
const spec = decl.initializer !== undefined ? requireSpecOf7(decl.initializer) : null;
|
||||
if (spec !== null) out.push({ spec, node: decl, decl });
|
||||
@@ -1441,6 +1455,172 @@ function requiresOf7(
|
||||
return out;
|
||||
}
|
||||
|
||||
/** CommonJS require bindings split into a declaration and one later
|
||||
* assignment (`var m; m = require("./x")`): a top-level `var` or `let`
|
||||
* declaration without initializer in a CommonJS file, assigned by exactly one
|
||||
* top-level `m = require("<literal>")` statement of the require global over
|
||||
* a compiled program module, and written nowhere else. The binding holds the
|
||||
* module's exports from the assignment on, as `const m = require("./x")`
|
||||
* does, so preflight treats the assignment as that require: its module edge,
|
||||
* its cycle admission and its early-read fence. The lowering's recognizer
|
||||
* (splitRequireBindingOf in cjs-inline-require.ts) accepts only these
|
||||
* bindings. Keyed by declaration, with the assignment's require call. */
|
||||
function splitRequireBindings7(
|
||||
program: ts.Program,
|
||||
sf: ts.SourceFile,
|
||||
): ReadonlyMap<ts.VariableDeclaration, ts.CallExpression> {
|
||||
const memo = program.analysis.splitRequireBindings;
|
||||
const cached = memo.get(sf);
|
||||
if (cached !== undefined) return cached;
|
||||
const out = new Map<ts.VariableDeclaration, ts.CallExpression>();
|
||||
memo.set(sf, out);
|
||||
if (sf.isDeclarationFile || !isCjsJsFile7(sf, program) || !sf.text.includes("require"))
|
||||
return out;
|
||||
const checker = program.getTypeChecker();
|
||||
const stmts = sf.statements.nodes;
|
||||
const candidates = new Map<
|
||||
ts.Symbol,
|
||||
{ decl: ts.VariableDeclaration; call: ts.CallExpression | null; assigns: number }
|
||||
>();
|
||||
for (const stmt of stmts) {
|
||||
if (!ts.isVariableStatement(stmt)) continue;
|
||||
if ((stmt.declarationList.flags & (ts.NodeFlags.Const | ts.NodeFlags.Using)) !== 0) continue;
|
||||
for (const decl of stmt.declarationList.declarations.nodes) {
|
||||
if (!ts.isIdentifier(decl.name) || decl.initializer !== undefined) continue;
|
||||
const symbol = checker.getSymbolAtLocation(decl.name);
|
||||
if (symbol === undefined || symbol.declarations.length !== 1) continue;
|
||||
candidates.set(symbol, { decl, call: null, assigns: 0 });
|
||||
}
|
||||
}
|
||||
if (candidates.size === 0) return out;
|
||||
// The one top-level `m = ...` statement, whose right side is the require.
|
||||
for (const stmt of stmts) {
|
||||
if (!ts.isExpressionStatement(stmt) || !ts.isBinaryExpression(stmt.expression)) continue;
|
||||
const assign = stmt.expression;
|
||||
if (assign.operatorToken.kind !== ts.SyntaxKind.EqualsToken || !ts.isIdentifier(assign.left))
|
||||
continue;
|
||||
const symbol = checker.getSymbolAtLocation(assign.left);
|
||||
const candidate = symbol !== undefined ? candidates.get(symbol) : undefined;
|
||||
if (candidate === undefined) continue;
|
||||
candidate.assigns++;
|
||||
let right = assign.right;
|
||||
while (ts.isParenthesizedExpression(right)) right = right.expression;
|
||||
if (ts.isCallExpression(right) && splitRequireTarget7(program, sf, right))
|
||||
candidate.call = right;
|
||||
}
|
||||
const names = new Set<string>();
|
||||
for (const candidate of candidates.values()) {
|
||||
if (candidate.assigns === 1 && candidate.call !== null)
|
||||
names.add((candidate.decl.name as ts.Identifier).text);
|
||||
}
|
||||
if (names.size === 0) return out;
|
||||
// Exactly one write in the whole file: the assignment itself.
|
||||
const writes = new Map<ts.Symbol, number>();
|
||||
ts.walkPreorder(sf, (node) => {
|
||||
if (!ts.isIdentifier(node) || !names.has(node.text)) return undefined;
|
||||
const parent = node.parent;
|
||||
const symbol =
|
||||
parent !== undefined && ts.isShorthandPropertyAssignment(parent) && parent.name === node
|
||||
? (checker.getShorthandAssignmentValueSymbol(parent) ?? checker.getSymbolAtLocation(node))
|
||||
: checker.getSymbolAtLocation(node);
|
||||
if (symbol === undefined || !candidates.has(symbol) || !isWriteReference7(node))
|
||||
return undefined;
|
||||
writes.set(symbol, (writes.get(symbol) ?? 0) + 1);
|
||||
return undefined;
|
||||
});
|
||||
for (const [symbol, candidate] of candidates) {
|
||||
if (candidate.assigns === 1 && candidate.call !== null && writes.get(symbol) === 1)
|
||||
out.set(candidate.decl, candidate.call);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** True when `call` is a require of the CommonJS global over a compiled
|
||||
* program module: not a builtin, a JSON document or a declaration file. */
|
||||
function splitRequireTarget7(
|
||||
program: ts.Program,
|
||||
sf: ts.SourceFile,
|
||||
call: ts.CallExpression,
|
||||
): boolean {
|
||||
const spec = requireSpecOf7(call);
|
||||
if (spec === null || canonicalBuiltinModule(spec) !== null) return false;
|
||||
if (requireCallBindingKind7(program, call) !== "ambient") return false;
|
||||
const dep =
|
||||
resolveImport7(program, sf, spec, "require") ?? npmStaticDepSf7(program, sf, spec, "require");
|
||||
return dep !== null && !dep.isDeclarationFile && !dep.fileName.endsWith(".json");
|
||||
}
|
||||
|
||||
/** The split require binding a top-level statement assigns, or null. */
|
||||
function splitRequireOfStatement7(
|
||||
program: ts.Program,
|
||||
stmt: ts.Statement,
|
||||
): { decl: ts.VariableDeclaration; call: ts.CallExpression } | null {
|
||||
if (
|
||||
!ts.isExpressionStatement(stmt) ||
|
||||
!ts.isBinaryExpression(stmt.expression) ||
|
||||
!ts.isSourceFile(stmt.parent)
|
||||
)
|
||||
return null;
|
||||
let right = stmt.expression.right;
|
||||
while (ts.isParenthesizedExpression(right)) right = right.expression;
|
||||
for (const [decl, call] of splitRequireBindings7(program, stmt.parent))
|
||||
if (call === right) return { decl, call };
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The top-level statement of a split require binding's assignment, from
|
||||
* its require call (`m = require("./x")` or `m = (require("./x"))`). */
|
||||
function splitRequireStatementOf7(call: ts.CallExpression): ts.Node | undefined {
|
||||
let node: ts.Node = call;
|
||||
while (node.parent !== undefined && ts.isParenthesizedExpression(node.parent)) node = node.parent;
|
||||
return node.parent?.parent;
|
||||
}
|
||||
|
||||
/** The require call of a split require binding's declaration, or null. */
|
||||
function splitRequireCallOf7(
|
||||
program: ts.Program,
|
||||
decl: ts.VariableDeclaration,
|
||||
): ts.CallExpression | null {
|
||||
return splitRequireBindings7(program, ts.getSourceFileOfNode(decl)).get(decl) ?? null;
|
||||
}
|
||||
|
||||
/** True when `id` is written: an assignment target (compound and
|
||||
* destructuring included), an update operand, or a for-in/of target. */
|
||||
function isWriteReference7(id: ts.Identifier): boolean {
|
||||
let n: ts.Node = id;
|
||||
for (;;) {
|
||||
const p: ts.Node | undefined = n.parent;
|
||||
if (p === undefined) return false;
|
||||
if (ts.isBinaryExpression(p)) {
|
||||
const k = p.operatorToken.kind;
|
||||
return (
|
||||
p.left === n && k >= ts.SyntaxKind.FirstAssignment && k <= ts.SyntaxKind.LastAssignment
|
||||
);
|
||||
}
|
||||
if (ts.isPostfixUnaryExpression(p) || ts.isPrefixUnaryExpression(p)) {
|
||||
return (
|
||||
(p.operator === ts.SyntaxKind.PlusPlusToken ||
|
||||
p.operator === ts.SyntaxKind.MinusMinusToken) &&
|
||||
p.operand === n
|
||||
);
|
||||
}
|
||||
if (ts.isForOfStatement(p) || ts.isForInStatement(p)) return p.initializer === n;
|
||||
if (
|
||||
ts.isParenthesizedExpression(p) ||
|
||||
ts.isArrayLiteralExpression(p) ||
|
||||
ts.isSpreadElement(p) ||
|
||||
ts.isSpreadAssignment(p) ||
|
||||
ts.isShorthandPropertyAssignment(p) ||
|
||||
ts.isObjectLiteralExpression(p) ||
|
||||
(ts.isPropertyAssignment(p) && p.initializer === n)
|
||||
) {
|
||||
n = p;
|
||||
continue;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** `true`, or `!0`, its minified spelling. */
|
||||
function isTrueLiteral(expr: ts.Expression): boolean {
|
||||
return (
|
||||
@@ -1580,7 +1760,7 @@ function purePrefixDecl7(decl: ts.VariableDeclaration): boolean {
|
||||
function purePrefixStmt7(program: ts.Program, s: ts.Statement): boolean {
|
||||
if (ts.isEmptyStatement(s) || ts.isFunctionDeclaration(s)) return true;
|
||||
if (ts.isExpressionStatement(s) && ts.isStringLiteral(s.expression)) return true; // directive
|
||||
if (isRequireStatement7(s)) return true;
|
||||
if (isRequireStatement7(s) || splitRequireOfStatement7(program, s) !== null) return true;
|
||||
if (isCjsJsFile7(ts.getSourceFileOfNode(s), program)) {
|
||||
if (ts.isExpressionStatement(s) && isEsModuleStamp(s.expression)) {
|
||||
const call = s.expression as ts.CallExpression;
|
||||
@@ -1707,12 +1887,20 @@ function requireEarlyReference7(
|
||||
const cached = memo.get(decl);
|
||||
if (cached !== undefined) return cached;
|
||||
let found: ts.Identifier | null = null;
|
||||
const stmt = decl.parent?.parent;
|
||||
const sf = ts.getSourceFileOfNode(decl);
|
||||
if (stmt !== undefined && ts.isVariableStatement(stmt) && ts.isSourceFile(stmt.parent)) {
|
||||
// A split require binding is bound at its assignment statement.
|
||||
const splitCall = splitRequireCallOf7(program, decl);
|
||||
const stmt = splitCall !== null ? splitRequireStatementOf7(splitCall) : decl.parent?.parent;
|
||||
if (
|
||||
stmt !== undefined &&
|
||||
(ts.isVariableStatement(stmt) || splitCall !== null) &&
|
||||
ts.isSourceFile(stmt.parent)
|
||||
) {
|
||||
const stmts = sf.statements.nodes;
|
||||
const k = stmts.indexOf(stmt);
|
||||
const declarations = stmt.declarationList.declarations.nodes;
|
||||
const k = stmts.indexOf(stmt as ts.Statement);
|
||||
const declarations = ts.isVariableStatement(stmt)
|
||||
? stmt.declarationList.declarations.nodes
|
||||
: [];
|
||||
// Earlier declarators run too: `const x = read(), dep = require('./dep')`.
|
||||
const precedingDecls = declarations.slice(0, declarations.indexOf(decl));
|
||||
let firstRunnable = program.analysis.requireFirstRunnable.get(sf);
|
||||
@@ -1765,6 +1953,12 @@ export function requireBindingEarlyUse7(
|
||||
if (sym) bindings.add(sym);
|
||||
}
|
||||
if (bindings.size === 0) return null;
|
||||
// A split require binding's assignment writes the binding; it reads nothing.
|
||||
let splitWrite: ts.Node | null = splitRequireCallOf7(program, decl);
|
||||
while (splitWrite !== null && ts.isParenthesizedExpression(splitWrite.parent))
|
||||
splitWrite = splitWrite.parent;
|
||||
splitWrite =
|
||||
splitWrite !== null && ts.isBinaryExpression(splitWrite.parent) ? splitWrite.parent.left : null;
|
||||
const stmts = sf.statements.nodes;
|
||||
const cjs = isCjsJsFile7(sf, program);
|
||||
const symbolOf = (id: ts.Identifier): ts.Symbol | undefined => {
|
||||
@@ -1988,7 +2182,7 @@ export function requireBindingEarlyUse7(
|
||||
const sym = symbolOf(n);
|
||||
if (sym === undefined) return undefined;
|
||||
if (bindings.has(sym)) {
|
||||
if (exactEarlyRead?.(n) === true) return undefined;
|
||||
if (n === splitWrite || exactEarlyRead?.(n) === true) return undefined;
|
||||
hit = n;
|
||||
return "stop";
|
||||
}
|
||||
@@ -3499,7 +3693,7 @@ function cjsCycleRefusal7(
|
||||
}
|
||||
// Bindings of other members must stay unreachable from top-level code.
|
||||
for (const st of stmts) {
|
||||
for (const req of requiresOf7(st)) {
|
||||
for (const req of requiresOf7(st, program)) {
|
||||
if (req.decl === null) continue;
|
||||
const dep = resolveImport7(program, m, req.spec, "require");
|
||||
if (dep === null || !members.has(dep)) continue;
|
||||
@@ -5775,7 +5969,7 @@ function preflight7(load: LoadResult): {
|
||||
// module aliases cannot represent; createRequire bindings have no
|
||||
// checked form either.
|
||||
const earlyRequireFence = (
|
||||
req: { decl: ts.VariableDeclaration | null },
|
||||
req: RequireOccurrence7,
|
||||
bindingKind: RequireCallBindingKind7,
|
||||
loc: { file: string; start: number; end: number },
|
||||
): boolean => {
|
||||
@@ -5783,6 +5977,7 @@ function preflight7(load: LoadResult): {
|
||||
if (
|
||||
early === null ||
|
||||
(bindingKind !== "createRequire" &&
|
||||
req.split === undefined &&
|
||||
((req.decl!.parent?.flags ?? 0) & (ts.NodeFlags.Const | ts.NodeFlags.Let)) !== 0)
|
||||
) {
|
||||
return false;
|
||||
@@ -5793,14 +5988,16 @@ function preflight7(load: LoadResult): {
|
||||
loc,
|
||||
bindingKind === "createRequire"
|
||||
? `createRequire() binding '${early.text}' below code that can reach it (Node throws ReferenceError on any earlier access, which is not modeled — move the require above the code that can run first)`
|
||||
: `var require() binding '${early.text}' below code that can reach it (Node reads undefined before the require runs, which is not modeled — declare it with const or let, or move the require above the code that can run first)`,
|
||||
: req.split !== undefined
|
||||
? `require() binding '${early.text}' assigned below code that can reach it (Node reads undefined before the assignment runs, which is not modeled — move the assignment above the code that can run first)`
|
||||
: `var require() binding '${early.text}' below code that can reach it (Node reads undefined before the require runs, which is not modeled — declare it with const or let, or move the require above the code that can run first)`,
|
||||
),
|
||||
);
|
||||
return true;
|
||||
};
|
||||
for (let k = 0; k < stmts.length; k++) {
|
||||
const stmt = stmts[k]!;
|
||||
for (const req of requiresOf7(stmt)) {
|
||||
for (const req of requiresOf7(stmt, program)) {
|
||||
const loc = {
|
||||
file: sf.fileName,
|
||||
start: ts.tokenStartOfNode(req.node),
|
||||
@@ -5827,8 +6024,8 @@ function preflight7(load: LoadResult): {
|
||||
const jsonDep = resolveImport7(program, sf, req.spec, "require");
|
||||
if (jsonDep !== null && jsonDep.fileName.endsWith(".json")) {
|
||||
if (bindingKind === "createRequire") continue;
|
||||
if (ts.isVariableStatement(stmt) && requiresOf7(stmt).length > 1) {
|
||||
const others = requiresOf7(stmt).some((r) => {
|
||||
if (ts.isVariableStatement(stmt) && requiresOf7(stmt, program).length > 1) {
|
||||
const others = requiresOf7(stmt, program).some((r) => {
|
||||
const d = resolveImport7(program, sf, r.spec, "require");
|
||||
return d === null || !d.fileName.endsWith(".json");
|
||||
});
|
||||
@@ -6000,8 +6197,12 @@ function preflight7(load: LoadResult): {
|
||||
// counts, and targets outside the compiled graph add nothing here:
|
||||
// their use sites keep their existing lowering fences.
|
||||
if (jsRequireFile && !isNodeEsmFile7(sf, program)) {
|
||||
// A split require binding's assignment is a statement-level require
|
||||
// edge (requiresOf7 above), parenthesized or not.
|
||||
const splitCalls = new Set(splitRequireBindings7(program, sf).values());
|
||||
for (const call of inlineRequiresOf7(sf)) {
|
||||
if (requireCallBindingKind7(program, call) !== "ambient") continue;
|
||||
if (splitCalls.has(call)) continue;
|
||||
const spec = requireSpecOf7(call)!;
|
||||
if (load.externalTypes.has(spec) || canonicalBuiltinModule(spec) !== null) continue;
|
||||
const lazy = inDeferredPosition7(call);
|
||||
@@ -6750,6 +6951,7 @@ export {
|
||||
requireSpecOf7 as requireSpecOf,
|
||||
isRequireStatement7 as isRequireStatement,
|
||||
requiresOf7 as requiresOf,
|
||||
splitRequireCallOf7 as splitRequireCallOf,
|
||||
isNodeEsmFile7 as isNodeEsmFile,
|
||||
resolveImport7 as resolveImport,
|
||||
resolveNpmImport7 as resolveNpmImport,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { optimizationField, type NativeOptimization } from "./backend/optimization.js";
|
||||
import { targetCpuField, targetCpuTargetRefusal } from "./backend/target-cpu.js";
|
||||
import { compilationTiming, type CompilationTiming, type TimingClock } from "./timing.js";
|
||||
import { prepareExecutableModule } from "./executable/prepare.js";
|
||||
import {
|
||||
@@ -807,6 +808,7 @@ async function prepareExecutableInput(
|
||||
lowRegion: lowRegionTarget(buildPlatform, opts.sanitize === true),
|
||||
...(opts.sanitize === true ? { wasmBoundsChecks: true } : {}),
|
||||
...inlineRcOption(opts.optimization, opts.sanitize === true),
|
||||
...targetCpuField(opts.targetCpu),
|
||||
});
|
||||
} catch (err) {
|
||||
if (!(err instanceof LlvmUnsupportedError)) throw err;
|
||||
@@ -877,6 +879,7 @@ async function prepareExecutableInput(
|
||||
...(opts.sanitize === true ? { wasmBoundsChecks: true } : {}),
|
||||
...inlineRcOption(opts.optimization, opts.sanitize === true),
|
||||
...(opts.detachedExit === true ? { detachedExit: true } : {}),
|
||||
...targetCpuField(opts.targetCpu),
|
||||
});
|
||||
} catch (err) {
|
||||
if (!(err instanceof LlvmUnsupportedError)) throw err;
|
||||
@@ -1445,6 +1448,18 @@ async function compileTracked(
|
||||
}
|
||||
}
|
||||
}
|
||||
const targetCpuRefusal = targetCpuTargetRefusal(
|
||||
opts.targetCpu,
|
||||
buildPlatform,
|
||||
nativeCodegenTarget()?.architecture ?? process.arch,
|
||||
);
|
||||
if (targetCpuRefusal !== null) {
|
||||
return {
|
||||
ok: false,
|
||||
diagnostics: [nativeCodegenDiag("SC3002", targetCpuRefusal, entryPath)],
|
||||
sourceTexts: new Map(),
|
||||
};
|
||||
}
|
||||
try {
|
||||
windowsSubsystemLinkerArgs(buildPlatform, opts.windowsSubsystem);
|
||||
} catch (err) {
|
||||
@@ -1499,6 +1514,7 @@ async function compileTracked(
|
||||
...(opts.strip ? { strip: true as const } : {}),
|
||||
...(opts.windowsSubsystem === "gui" ? { windowsSubsystem: "gui" as const } : {}),
|
||||
...(opts.detachedExit === true ? { detachedExit: true as const } : {}),
|
||||
...targetCpuField(opts.targetCpu),
|
||||
...(profile === undefined ? {} : { profile: nativeProfileKey(profile) }),
|
||||
...checkerField(),
|
||||
...(youngNurseryRequested() ? { youngNursery: true as const } : {}),
|
||||
|
||||
@@ -746,6 +746,8 @@ export const MAY_THROW_LIB_FNS: ReadonlySet<IrLibFn> = new Set([
|
||||
"url.set",
|
||||
"url.setChecked",
|
||||
"url.fileURLToPathUrl",
|
||||
"fs.checkPath",
|
||||
"fs.checkReadEncoding",
|
||||
"url.fileURLToPathChecked",
|
||||
"url.fileURLToPathOptions",
|
||||
"url.fileURLToPathBuffer",
|
||||
|
||||
@@ -1006,6 +1006,14 @@ export const LIB_FN_SIGS = defineLibFnSignatures({
|
||||
"url.set": { argTypes: [URL_T, STRING, STRING], result: VOID },
|
||||
"url.setChecked": { argTypes: [URL_T, STRING, DYN], result: VOID },
|
||||
"url.fileURLToPathUrl": { argTypes: [URL_T], result: STRING },
|
||||
/** fileURLToPathUrl as a value: the path string, or the error it would
|
||||
* throw (fs.existsSync and fs.promises URL paths). Never throws. */
|
||||
"url.fileURLToPathValue": { argTypes: [URL_T], result: DYN },
|
||||
/** getValidatedPath's null-byte check on a string path, and
|
||||
* readFileSync's encoding check: what Node validates before it converts
|
||||
* a later URL path. (path, argument name) and (encoding). */
|
||||
"fs.checkPath": { argTypes: [STRING, STRING], result: VOID },
|
||||
"fs.checkReadEncoding": { argTypes: [STRING], result: VOID },
|
||||
"url.fileURLToPathChecked": { argTypes: [DYN], result: STRING },
|
||||
"url.fileURLToPathOptions": { argTypes: [DYN, DYN], result: STRING },
|
||||
/** node:url's legacy API (scr_url_legacy.c): parse(url, parseQueryString,
|
||||
@@ -4452,6 +4460,9 @@ export const LIB_FN_SIGS = defineLibFnSignatures({
|
||||
"insp.buffer": { argTypes: [BYTES_U8], result: STRING },
|
||||
/** A numeric typed array that is not a Buffer (any element kind). */
|
||||
"insp.typedArray": { argTypes: [null, F64, F64], result: STRING },
|
||||
/** A u8 byte view in a union arm, element or field: a DataView, Buffer
|
||||
* or Uint8Array by its own flags. */
|
||||
"insp.bytes": { argTypes: [null, F64, F64], result: STRING },
|
||||
"insp.error": { argTypes: [null, F64, F64], result: STRING },
|
||||
"insp.errorHasCause": { argTypes: [null], result: BOOL },
|
||||
"insp.errorBagHasProperties": { argTypes: [DYN], result: BOOL },
|
||||
|
||||
@@ -119,13 +119,26 @@ function stableLoopValue(
|
||||
stableLoopValue(value.receiver, locals, body, invariant, counter)
|
||||
);
|
||||
case "bytesIntrinsic":
|
||||
case "arrIntrinsic":
|
||||
case "arrIntrinsic": {
|
||||
// The receiver may be one arm of a union binding (indexed-unions.ts).
|
||||
const receiver =
|
||||
value.receiver.kind === "unionNarrow" ? value.receiver.value : value.receiver;
|
||||
return (
|
||||
(value.method === "length" ||
|
||||
(value.kind === "bytesIntrinsic" && value.method === "byteLength")) &&
|
||||
value.receiver.kind === "varRef" &&
|
||||
(value.kind === "bytesIntrinsic" || !invariant || stableLength(value.receiver.localId)) &&
|
||||
stableLoopValue(value.receiver, locals, body, invariant, counter)
|
||||
receiver.kind === "varRef" &&
|
||||
(value.kind === "bytesIntrinsic" || !invariant || stableLength(receiver.localId)) &&
|
||||
stableLoopValue(receiver, locals, body, invariant, counter)
|
||||
);
|
||||
}
|
||||
// A union binding dispatched on its tag (indexed-unions.ts): stable
|
||||
// when the binding is and every arm is.
|
||||
case "ternary":
|
||||
return (
|
||||
value.cond.kind === "unionIsTag" &&
|
||||
stableLoopValue(value.cond.value, locals, body, invariant, counter) &&
|
||||
stableLoopValue(value.then, locals, body, invariant, counter, stableLength) &&
|
||||
stableLoopValue(value.else_, locals, body, invariant, counter, stableLength)
|
||||
);
|
||||
default:
|
||||
return false;
|
||||
|
||||
@@ -1503,6 +1503,10 @@ export interface IrClassDef {
|
||||
* class of the chain sets `name` during construction, and then an own
|
||||
* `name` follows every other own property. */
|
||||
errorNameAfter?: string | null;
|
||||
/** JavaScript Error subclasses with a property bag: a view committed by a
|
||||
* dynamic write keeps `name` and `message` where the bag recorded them
|
||||
* (scr_error_dyn_follow_bag). */
|
||||
errorBagOrder?: boolean;
|
||||
/** Stable module symbol identities for public instance layout fields. */
|
||||
symbolFields?: { field: string; globalId: string }[];
|
||||
/** RUNTIME-PROVIDED class (the builtin Error hierarchy): the struct, RC
|
||||
@@ -2511,6 +2515,14 @@ export type IrBytesIntrinsicMethod =
|
||||
| "indexOfNum"
|
||||
| "lastIndexOfNum"
|
||||
| "includesNum"
|
||||
/** TypedArray.prototype.indexOf / lastIndexOf / includes on any element
|
||||
* kind: [f64 needle, f64 fromIndex]. indexOf and lastIndexOf compare
|
||||
* with strict equality (NaN is never found, -0 matches 0), includes with
|
||||
* SameValueZero (NaN is found). An omitted fromIndex is 0, or +Infinity
|
||||
* for lastIndexOf (which clamps to the last index). */
|
||||
| "indexOfElem"
|
||||
| "lastIndexOfElem"
|
||||
| "includesElem"
|
||||
| "fill"
|
||||
| "fillNum"
|
||||
| "fillStr"
|
||||
|
||||
@@ -2196,6 +2196,9 @@ function validateFunction(
|
||||
indexOfNum: { argTypes: [F64, F64], minArgs: 1, result: F64 },
|
||||
lastIndexOfNum: { argTypes: [F64, F64], minArgs: 1, result: F64 },
|
||||
includesNum: { argTypes: [F64, F64], minArgs: 1, result: BOOL },
|
||||
indexOfElem: { argTypes: [F64, F64], minArgs: 2, result: F64 },
|
||||
lastIndexOfElem: { argTypes: [F64, F64], minArgs: 2, result: F64 },
|
||||
includesElem: { argTypes: [F64, F64], minArgs: 2, result: BOOL },
|
||||
fill: { argTypes: [BYTES_U8, F64, F64], minArgs: 1, result: BYTES_U8 },
|
||||
fillNum: { argTypes: [F64, F64, F64], minArgs: 1, result: BYTES_U8 },
|
||||
// Per-element TypedArray fill (any elem — the non-u8 fill path).
|
||||
|
||||
@@ -2,7 +2,11 @@ import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSyn
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, expect, test } from "vitest";
|
||||
import { nativeCodegenTarget } from "../backend/targets.js";
|
||||
import {
|
||||
LINUX_ARM64_GNU_TARGET,
|
||||
nativeCodegenTarget,
|
||||
WASM32_WASI_TARGET,
|
||||
} from "../backend/targets.js";
|
||||
import { runFrontend, type FrontendFactory } from "../frontend/pipeline.js";
|
||||
import { loadProgram } from "../frontend/program-node.js";
|
||||
import { ts7Executable } from "../frontend/ts7/rpc-api.js";
|
||||
@@ -183,3 +187,24 @@ test("serialized IR travels as bounded parts through the frontend cache", () =>
|
||||
expect(payload.llvm).toBe(first.llvm.join(""));
|
||||
expect(payload.ir).toEqual(first.ir);
|
||||
});
|
||||
|
||||
test("an x86-64 level is refused for targets that are not x86-64 before the frontend runs", () => {
|
||||
const f = fixture();
|
||||
for (const target of [LINUX_ARM64_GNU_TARGET, WASM32_WASI_TARGET]) {
|
||||
const result = prepareNativeExecutable(
|
||||
f.entry,
|
||||
{ ...f.options, targetCpu: "x86-64-v3" },
|
||||
null,
|
||||
{ ...fixtureToolchain(), target },
|
||||
() => {
|
||||
throw new Error("the frontend ran");
|
||||
},
|
||||
null,
|
||||
);
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) continue;
|
||||
expect(result.diagnostics.map((d) => [d.code, d.message])).toEqual([
|
||||
["SC3002", "--target-cpu=x86-64-v3 requires an x86-64 target"],
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { ScrDiagnostic } from "../diagnostics/diagnostic.js";
|
||||
import { targetCpuField, targetCpuTargetRefusal } from "../backend/target-cpu.js";
|
||||
import { nativeCodegenDiag, type ScrDiagnostic } from "../diagnostics/diagnostic.js";
|
||||
import type { CompilationTiming } from "../timing.js";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { basename, dirname, join, resolve } from "node:path";
|
||||
@@ -316,6 +317,17 @@ export function prepareNativeExecutable(
|
||||
timing: CompilationTiming = () => {},
|
||||
): NativeExecutableInput | CompileFailure {
|
||||
const outputKind = options.outputKind ?? "exe";
|
||||
const targetCpuRefusal = targetCpuTargetRefusal(
|
||||
options.targetCpu,
|
||||
toolchain.target.platform,
|
||||
toolchain.target.architecture,
|
||||
);
|
||||
if (targetCpuRefusal !== null)
|
||||
return {
|
||||
ok: false,
|
||||
diagnostics: [nativeCodegenDiag("SC3002", targetCpuRefusal, entry)],
|
||||
sourceTexts: new Map(),
|
||||
};
|
||||
const stem = basename(entry).replace(/\.(ts|mts|cts|js|mjs|cjs)$/, "");
|
||||
const outputPaths = [
|
||||
resolve(options.outPath),
|
||||
@@ -396,6 +408,7 @@ export function prepareNativeExecutable(
|
||||
forkPrimitives: emitForkPrimitives(),
|
||||
...inlineRcOption(options.optimization, options.sanitize === true),
|
||||
...(options.detachedExit === true && outputKind === "exe" ? { detachedExit: true } : {}),
|
||||
...targetCpuField(options.targetCpu),
|
||||
...(options.optimization === "dev" && !options.strip
|
||||
? { debugSources: prepared.sourceTexts }
|
||||
: {}),
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { expect, test } from "vitest";
|
||||
import { compile, deserializeModule } from "../src/index.js";
|
||||
import { emitLlvmModule } from "../src/backend/llvm/emitter.js";
|
||||
|
||||
const source = `function siftDown(a: Int32Array, start: number, end: number): void {
|
||||
let root = start;
|
||||
while (2 * root + 1 < end) {
|
||||
let child = 2 * root + 1;
|
||||
if (child + 1 < end && a[child]! < a[child + 1]!) child++;
|
||||
if (a[root]! >= a[child]!) return;
|
||||
const t = a[root]!;
|
||||
a[root] = a[child]!;
|
||||
a[child] = t;
|
||||
root = child;
|
||||
}
|
||||
}
|
||||
const a = new Int32Array([3, 9, 1, 7, 5]);
|
||||
siftDown(a, 0, Number(process.argv[2] ?? "5"));
|
||||
console.log(Array.from(a).join());
|
||||
`;
|
||||
|
||||
test("integer sums of speculated locals compare and index as integers", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "scriptc-integer-views-"));
|
||||
try {
|
||||
const entry = join(dir, "sift.ts");
|
||||
await writeFile(entry, source);
|
||||
const outPath = join(dir, "sift.ir.json");
|
||||
const result = await compile(entry, { outPath, outDir: dir, outputKind: "ir" });
|
||||
if (!result.ok) throw new Error(result.diagnostics.map((d) => d.message).join("\n"));
|
||||
const ll = emitLlvmModule(deserializeModule(await readFile(outPath, "utf8")));
|
||||
const body = ll.match(
|
||||
/define internal [^\n]+ @sc_bf_siftDown(?:\.i32)?\([^\n]*\) #0 \{([\s\S]*?)\n\}/,
|
||||
)![1]!;
|
||||
// `child + 1`: the integer the speculated copy already adds.
|
||||
const sums = [...body.matchAll(/(%t\d+) = add nsw i64 %t\d+, 1\n/g)].map((m) => m[1]!);
|
||||
expect(sums.length).toBeGreaterThan(0);
|
||||
const uses = (op: string) =>
|
||||
sums.filter((sum) => new RegExp(`= ${op} i64 \\${sum}, %t\\d+\\n`).test(body));
|
||||
// `child + 1 < end` compares the integers,
|
||||
expect(uses("icmp slt").length).toBeGreaterThan(0);
|
||||
// and `a[child + 1]` bounds the integer index without a double round trip.
|
||||
expect(uses("icmp ult").length).toBeGreaterThan(0);
|
||||
// `2 * root + 1 < end` may pass 2^53, so it keeps the double compare.
|
||||
expect(body).toMatch(/fmul double 0x4000000000000000, %t\d+\n\s+%t\d+ = mul nsw i64 2/);
|
||||
expect(body).toContain("fcmp olt double");
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -221,3 +221,21 @@ test("a JavaScript file TypeScript checks uses its JSDoc types for class layouts
|
||||
expect(layout(unchecked, "Account").fields).toBe("owner:dyn balance:dyn");
|
||||
expect(params(unchecked, "%Account.constructor")).toBe("(object, dyn, dyn): void");
|
||||
});
|
||||
|
||||
test("instances of a class with subclasses box at their exact class", async () => {
|
||||
const module = await lower(`${SHAPES}
|
||||
/** @param {any} value */
|
||||
function keep(value) {
|
||||
return value;
|
||||
}
|
||||
/** @param {Shape} shape */
|
||||
function cross(shape) {
|
||||
return keep(shape);
|
||||
}
|
||||
console.log(cross(new Square()).size, cross(new Shape()).label);
|
||||
`);
|
||||
const helper = module.functions.find((fn) => fn.name === "%dyn.class.boxExact:Shape");
|
||||
expect(helper).toBeDefined();
|
||||
expect(calls(module, "cross")).toContain("%dyn.class.boxExact:Shape");
|
||||
expect(JSON.stringify(helper!.body)).toContain('"className":"Square"');
|
||||
});
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { expect, test } from "vitest";
|
||||
import { compile } from "../src/index.js";
|
||||
|
||||
const program = `const a = new Int32Array(4096);
|
||||
for (let i = 0; i < a.length; i++) a[i] = (i * 2654435761) | 0;
|
||||
let s = 0;
|
||||
for (let r = 0; r < 64; r++) for (let i = 0; i < a.length; i++) s = (s + a[i]!) | 0;
|
||||
console.log(s);
|
||||
`;
|
||||
|
||||
test.runIf(process.platform === "linux" && process.arch === "x64")(
|
||||
"assembly, object and LLVM builds honor the target CPU",
|
||||
async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "scriptc-target-cpu-emit-"));
|
||||
const entry = join(dir, "main.ts");
|
||||
const emit = async (
|
||||
outputKind: "llvm" | "asm" | "obj",
|
||||
targetCpu?: "x86-64-v3",
|
||||
): Promise<Buffer> => {
|
||||
const outPath = join(dir, `main-${outputKind}-${targetCpu ?? "baseline"}`);
|
||||
const result = await compile(entry, {
|
||||
outPath,
|
||||
outDir: dir,
|
||||
outputKind,
|
||||
...(targetCpu === undefined ? {} : { targetCpu }),
|
||||
});
|
||||
if (!result.ok) throw new Error(result.diagnostics.map((d) => d.message).join("\n"));
|
||||
return readFile(outPath);
|
||||
};
|
||||
try {
|
||||
await writeFile(entry, program);
|
||||
expect((await emit("llvm")).toString()).not.toContain('"target-cpu"');
|
||||
expect((await emit("llvm", "x86-64-v3")).toString()).toContain('"target-cpu"="x86-64-v3"');
|
||||
// The v3 build vectorizes the sums with AVX2's 256-bit registers.
|
||||
expect((await emit("asm")).toString()).not.toContain("%ymm");
|
||||
expect((await emit("asm", "x86-64-v3")).toString()).toContain("%ymm");
|
||||
expect((await emit("obj", "x86-64-v3")).equals(await emit("obj"))).toBe(false);
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
240_000,
|
||||
);
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/corpus/6935-fs-url-paths-ordered.ts"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/corpus/7189-non-null-assertion-nullish-destination.ts"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/corpus/7392-non-null-operands.ts"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/corpus/7453-untyped-overload-results.cjs"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/corpus/7624-key-order-boxed-callback-records/lib.js",
|
||||
"<repo>/tests/corpus/7624-key-order-boxed-callback-records/main.ts"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/corpus/7680-typed-array-search.ts"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/corpus/7681-typed-array-search-dynamic.mjs"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/corpus/7682-constructor-function-globals.js"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/corpus/7745-typed-array-unions.ts"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/corpus/7747-typed-array-class-values.ts"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/corpus/7748-typed-array-number-array-unions.ts"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/corpus/7749-typed-array-element-searches.ts"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/corpus/7750-typed-array-union-inspect.ts"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/corpus/7796-boxed-subclass-identity.js"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/corpus/7982-integer-view-compares.ts"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/corpus/8112-error-factory-own-key-order.js"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/corpus/8113-error-class-field-before-name.js"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/corpus/8160-assert-expected-from-fields.cjs"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/corpus/split-cjs-require-binding/lib.cjs",
|
||||
"<repo>/tests/corpus/split-cjs-require-binding/whole.cjs",
|
||||
"<repo>/tests/corpus/split-cjs-require-binding/reexport.cjs",
|
||||
"<repo>/tests/corpus/split-cjs-require-binding/reexport-extra.cjs",
|
||||
"<repo>/tests/corpus/split-cjs-require-binding/chain.cjs",
|
||||
"<repo>/tests/corpus/split-cjs-require-binding/chain-wrap.cjs",
|
||||
"<repo>/tests/corpus/split-cjs-require-binding/main.cjs"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/corpus/split-cjs-require-cycle/odd.cjs",
|
||||
"<repo>/tests/corpus/split-cjs-require-cycle/even.cjs",
|
||||
"<repo>/tests/corpus/split-cjs-require-cycle/main.cjs"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/corpus/typed-array-masked-index-stores.ts"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/diagnostics/split-cjs-require-cycle/b.js",
|
||||
"<repo>/tests/diagnostics/split-cjs-require-cycle/main.js"
|
||||
],
|
||||
"diags": [
|
||||
{
|
||||
"code": "SC1016",
|
||||
"message": "circular imports (<repo>/tests/diagnostics/split-cjs-require-cycle/main.js → <repo>/tests/diagnostics/split-cjs-require-cycle/b.js → <repo>/tests/diagnostics/split-cjs-require-cycle/main.js; the cycle closes through a require() edge: <repo>/tests/diagnostics/split-cjs-require-cycle/main.js uses its exports at <repo>/tests/diagnostics/split-cjs-require-cycle/main.js:10 outside the export statements that precede its first require, so a module of the cycle can observe them before they settle) are not supported yet",
|
||||
"loc": {
|
||||
"file": "<repo>/tests/diagnostics/split-cjs-require-cycle/main.js",
|
||||
"start": 0,
|
||||
"end": 0
|
||||
},
|
||||
"milestone": "later",
|
||||
"hint": "ES-module cycles of let/const/function bindings compile as-is; rewrite the named construct (a named import instead of a namespace, a const instead of a default-export expression or var, a class declared before the code that can reach it) or break the named edge"
|
||||
}
|
||||
]
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/diagnostics/split-cjs-require-early/main.js"
|
||||
],
|
||||
"diags": [
|
||||
{
|
||||
"code": "SC1013",
|
||||
"message": "require() binding 'lib' assigned below code that can reach it (Node reads undefined before the assignment runs, which is not modeled — move the assignment above the code that can run first) is not supported yet",
|
||||
"loc": {
|
||||
"file": "<repo>/tests/diagnostics/split-cjs-require-early/main.js",
|
||||
"start": 396,
|
||||
"end": 415
|
||||
},
|
||||
"milestone": "later"
|
||||
},
|
||||
{
|
||||
"code": "SC1013",
|
||||
"message": "require() binding 'wrapped' assigned below code that can reach it (Node reads undefined before the assignment runs, which is not modeled — move the assignment above the code that can run first) is not supported yet",
|
||||
"loc": {
|
||||
"file": "<repo>/tests/diagnostics/split-cjs-require-early/main.js",
|
||||
"start": 530,
|
||||
"end": 549
|
||||
},
|
||||
"milestone": "later"
|
||||
}
|
||||
]
|
||||
}
|
||||
Vendored
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/fixtures/node-types/fs-url-fallible.ts"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
-6
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/fixtures/node-types/fs-url-path-fences.ts"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/fixtures/npm/cases/hono-zod-default-hook/main.ts"
|
||||
],
|
||||
"diags": [
|
||||
{
|
||||
"code": "SC0001",
|
||||
"message": "Cannot find name 'WebSocket'.",
|
||||
"loc": {
|
||||
"file": "<repo>/tests/fixtures/npm/node_modules/hono/dist/types/client/types.d.ts",
|
||||
"start": 1398,
|
||||
"end": 1407
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": "SC0001",
|
||||
"message": "Cannot find name 'WebSocket'.",
|
||||
"loc": {
|
||||
"file": "<repo>/tests/fixtures/npm/node_modules/hono/dist/types/client/types.d.ts",
|
||||
"start": 1413,
|
||||
"end": 1422
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": "SC0001",
|
||||
"message": "Cannot find name 'WebSocket'.",
|
||||
"loc": {
|
||||
"file": "<repo>/tests/fixtures/npm/node_modules/hono/dist/types/client/types.d.ts",
|
||||
"start": 3716,
|
||||
"end": 3725
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": "SC0001",
|
||||
"message": "Cannot find name 'FormData'.",
|
||||
"loc": {
|
||||
"file": "<repo>/tests/fixtures/npm/node_modules/hono/dist/types/client/types.d.ts",
|
||||
"start": 4798,
|
||||
"end": 4806
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": "SC0001",
|
||||
"message": "Cannot find name 'FormData'.",
|
||||
"loc": {
|
||||
"file": "<repo>/tests/fixtures/npm/node_modules/hono/dist/types/request.d.ts",
|
||||
"start": 549,
|
||||
"end": 557
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": "SC0001",
|
||||
"message": "Cannot find name 'FormData'.",
|
||||
"loc": {
|
||||
"file": "<repo>/tests/fixtures/npm/node_modules/hono/dist/types/request.d.ts",
|
||||
"start": 5572,
|
||||
"end": 5580
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { expect, test } from "vitest";
|
||||
import { compile } from "../src/index.js";
|
||||
|
||||
async function emitLlvm(source: string): Promise<string> {
|
||||
const dir = await mkdtemp(join(tmpdir(), "scriptc-typed-array-unions-"));
|
||||
try {
|
||||
const entry = join(dir, "main.ts");
|
||||
const outPath = join(dir, "main.ll");
|
||||
await writeFile(entry, source);
|
||||
const result = await compile(entry, { outDir: dir, outPath, outputKind: "llvm" });
|
||||
expect(result.ok, JSON.stringify(result.diagnostics)).toBe(true);
|
||||
return await readFile(outPath, "utf8");
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
function body(llvm: string, name: string): string {
|
||||
return new RegExp(`^define [^@]*@sc_b?f_${name}(\\.i32)?\\([^]*?^}`, "m").exec(llvm)?.[0] ?? "";
|
||||
}
|
||||
|
||||
const source = `
|
||||
type UintArray = Uint8Array | Uint16Array | Uint32Array;
|
||||
const pick = (max: number, n: number): UintArray =>
|
||||
max <= 256 ? new Uint8Array(n) : max <= 65536 ? new Uint16Array(n) : new Uint32Array(n);
|
||||
function total(xs: UintArray): number {
|
||||
let s = 0;
|
||||
for (let i = 0; i < xs.length; i++) s += xs[i]!;
|
||||
return s;
|
||||
}
|
||||
function first(max: number): number {
|
||||
return pick(max, 4)[0]!;
|
||||
}
|
||||
const xs = pick(Number(process.argv.length) * 100000, 8);
|
||||
for (let i = 0; i < xs.length; i++) xs[i] = i;
|
||||
console.log(total(xs), first(10));
|
||||
`;
|
||||
|
||||
test("element reads of a union of typed arrays load each arm's own element kind in place", async () => {
|
||||
const llvm = await emitLlvm(source);
|
||||
const total = body(llvm, "total");
|
||||
// One load per arm, each of its element width, behind the union's tag.
|
||||
for (const width of ["i8", "i16", "i32"]) expect(total).toMatch(new RegExp(`load ${width}, ptr`));
|
||||
expect(total).not.toContain("@sc_bf__x25_union_getNumber");
|
||||
// The loop over the union's length keeps an integer counter.
|
||||
expect(total).toMatch(/alloca i64/);
|
||||
});
|
||||
|
||||
test("a typed-array union read through a computed receiver goes through one helper", async () => {
|
||||
const llvm = await emitLlvm(source);
|
||||
// The receiver is a call: evaluated once, then dispatched by the helper.
|
||||
expect(body(llvm, "first")).toContain("@sc_bf__x25_union_getNumber");
|
||||
});
|
||||
|
||||
const stores = `
|
||||
type Wide = Uint8Array | Uint16Array;
|
||||
const pick = (wide: boolean): Wide => (wide ? new Uint16Array(4) : new Uint8Array(4));
|
||||
function fill(xs: Wide): void {
|
||||
for (let i = 0; i < xs.length; i++) xs[i] = i + 1;
|
||||
}
|
||||
function rebind(): void {
|
||||
let u = pick(false);
|
||||
let i = 0;
|
||||
const swap = (): number => {
|
||||
u = pick(true);
|
||||
i = 2;
|
||||
return 3;
|
||||
};
|
||||
u[i] = swap();
|
||||
console.log(u, i);
|
||||
}
|
||||
fill(pick(process.argv.length > 9));
|
||||
rebind();
|
||||
`;
|
||||
|
||||
test("a typed-array union store runs in place unless its value can rebind the receiver or index", async () => {
|
||||
const llvm = await emitLlvm(stores);
|
||||
expect(body(llvm, "fill")).not.toContain("@sc_bf__x25_union_idxSet");
|
||||
// The call may assign the captured receiver and index, which the store
|
||||
// read before it: the helper evaluates them first.
|
||||
expect(body(llvm, "rebind")).toContain("@sc_bf__x25_union_idxSet");
|
||||
});
|
||||
|
||||
test("typed-array methods on a union with a Buffer arm need a narrowing first", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "scriptc-typed-array-unions-"));
|
||||
try {
|
||||
const entry = join(dir, "main.ts");
|
||||
// The Buffer arm is found by its type, also through an alias name.
|
||||
for (const [declaration, method] of [
|
||||
["const u: Buffer | Uint16Array", "slice(1)"],
|
||||
["type Bytes = Uint16Array | Buffer;\nconst u: Bytes", "slice(1)"],
|
||||
["type Bytes = Uint16Array | Buffer;\nconst u: Bytes", "fill(1)"],
|
||||
["type Bytes = Uint16Array | Buffer;\nconst u: Bytes", "indexOf(1)"],
|
||||
]) {
|
||||
await writeFile(
|
||||
entry,
|
||||
`import { Buffer } from "node:buffer";
|
||||
${declaration} = process.argv.length > 9 ? new Uint16Array(2) : Buffer.alloc(2);
|
||||
console.log(u.${method});
|
||||
`,
|
||||
);
|
||||
const result = await compile(entry, {
|
||||
outDir: dir,
|
||||
outPath: join(dir, "main.ll"),
|
||||
outputKind: "llvm",
|
||||
});
|
||||
expect(result.ok, `${declaration} ${method}`).toBe(false);
|
||||
expect(JSON.stringify(result.diagnostics)).toContain(method.slice(0, method.indexOf("(")));
|
||||
}
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -3329,6 +3329,55 @@ double scr_bytes_index_of_num(const ScrBytes *b, double v, double off, bool fwd)
|
||||
return scr_bytes_index_of(b, &needle, off, 1, fwd);
|
||||
}
|
||||
|
||||
/* The first index a TypedArray search from `from` starts at
|
||||
* (ToIntegerOrInfinity, then relative to the end when negative), or false
|
||||
* when it starts past the last element. */
|
||||
static bool scr_bytes_search_start(size_t len, double from, size_t *start) {
|
||||
double n = from != from ? 0 : trunc(from);
|
||||
if (n >= (double)len) return false;
|
||||
if (n < 0) n = n + (double)len < 0 ? 0 : n + (double)len;
|
||||
*start = (size_t)n;
|
||||
return true;
|
||||
}
|
||||
|
||||
double scr_bytes_index_of_elem(const ScrBytes *b, double x, double from, bool last) {
|
||||
/* A Buffer viewed as a Uint8Array keeps Buffer's own search: the needle
|
||||
* is taken as a byte, and a NaN byteOffset searches the whole buffer. */
|
||||
if (scr_bytes_is_buffer(b)) return scr_bytes_index_of_num(b, x, from, !last);
|
||||
SCR_BYTES_SNAPSHOT(b);
|
||||
size_t len = b->len;
|
||||
size_t size = scr_bytes_elem_size(b->elem);
|
||||
if (len == 0 || x != x) return -1;
|
||||
if (!last) {
|
||||
size_t k;
|
||||
if (!scr_bytes_search_start(len, from, &k)) return -1;
|
||||
for (; k < len; k++)
|
||||
if (scr_bytes_decode(b->elem, b->data + k * size) == x) return (double)k;
|
||||
return -1;
|
||||
}
|
||||
double n = from != from ? 0 : trunc(from);
|
||||
double k = n >= 0 ? (n < (double)len - 1 ? n : (double)len - 1) : (double)len + n;
|
||||
if (k < 0) return -1;
|
||||
for (size_t i = (size_t)k + 1; i-- > 0;)
|
||||
if (scr_bytes_decode(b->elem, b->data + i * size) == x) return (double)i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
bool scr_bytes_includes_elem(const ScrBytes *b, double x, double from) {
|
||||
if (scr_bytes_is_buffer(b)) return scr_bytes_index_of_num(b, x, from, true) >= 0;
|
||||
SCR_BYTES_SNAPSHOT(b);
|
||||
size_t len = b->len;
|
||||
size_t size = scr_bytes_elem_size(b->elem);
|
||||
size_t k;
|
||||
if (len == 0 || !scr_bytes_search_start(len, from, &k)) return false;
|
||||
bool nan = x != x;
|
||||
for (; k < len; k++) {
|
||||
double v = scr_bytes_decode(b->elem, b->data + k * size);
|
||||
if (v == x || (nan && v != v)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/* fill's shared core over a normalized byte pattern. nargs counts the
|
||||
* present offset/end args. An EMPTY pattern zero-fills when zero_ok
|
||||
* (Node's '' string) and is the constant TypeError otherwise (an empty
|
||||
|
||||
@@ -538,6 +538,16 @@ ScrEmitter *scr_emitter_set_max_chk(ScrEmitter *em, const ScrDyn *n);
|
||||
void scr_emitter_set_default_max_chk(const ScrDyn *n, const ScrStr *name);
|
||||
double scr_bytes_index_of(const ScrBytes *b, const ScrBytes *needle, double off, double align, bool fwd);
|
||||
double scr_bytes_index_of_num(const ScrBytes *b, double v, double off, bool fwd);
|
||||
/* TypedArray indexOf (last false) and lastIndexOf (last true) over any
|
||||
* element kind, with strict equality: NaN is never found and -0 matches 0.
|
||||
* `from` is the fromIndex argument (ToIntegerOrInfinity applies); the
|
||||
* caller passes 0, or +Infinity for lastIndexOf, when it is omitted. A
|
||||
* Buffer (a Uint8Array receiver can be one) searches as Buffer's
|
||||
* indexOf and lastIndexOf do. */
|
||||
double scr_bytes_index_of_elem(const ScrBytes *b, double x, double from, bool last);
|
||||
/* TypedArray includes: indexOf's search from `from` with SameValueZero,
|
||||
* so NaN is found. A Buffer searches as Buffer's includes does. */
|
||||
bool scr_bytes_includes_elem(const ScrBytes *b, double x, double from);
|
||||
ScrBytes *scr_bytes_fill(ScrBytes *b, const ScrBytes *pattern, double nargs, double offset, double end);
|
||||
ScrBytes *scr_bytes_fill_num(ScrBytes *b, double v, double nargs, double offset, double end);
|
||||
ScrBytes *scr_bytes_fill_str(ScrBytes *b, const ScrStr *s, const ScrStr *enc,
|
||||
|
||||
@@ -59,6 +59,10 @@ static bool scr_fs_read_utf8(ScrStr *encoding) {
|
||||
return encoding->len == 0 || scr_bytes_encoding_is_utf8(encoding);
|
||||
}
|
||||
|
||||
void scr_fs_check_read_encoding(ScrStr *encoding) {
|
||||
(void)scr_fs_read_encoding_valid(encoding);
|
||||
}
|
||||
|
||||
ScrStr *scr_fs_read_file_encoded(ScrStr *path, ScrStr *encoding) {
|
||||
if (!scr_fs_read_encoding_valid(encoding)) return NULL;
|
||||
if (scr_fs_read_utf8(encoding)) return scr_fs_read_file(path);
|
||||
|
||||
@@ -1330,6 +1330,11 @@ ScrDyn *scr_dyn_from_error(const ScrError *e);
|
||||
void scr_error_register_dyn(const ScrVt *vt, ScrDyn *(*box)(void *));
|
||||
ScrDyn *scr_error_dyn_fields(const ScrError *e);
|
||||
void scr_error_dyn_place_name(ScrDyn *view, const char *after, size_t after_len);
|
||||
/* An Error subclass view of an instance whose class keeps a property bag:
|
||||
* `name` and `message` take their committed positions, and data values
|
||||
* from the slots (scr_json.c). `name_placed`: the class's construction sets
|
||||
* `name`, and the view already has it in place. */
|
||||
void scr_error_dyn_follow_bag(ScrDyn *view, const ScrDyn *bag, const ScrError *e, bool name_placed);
|
||||
/* An accessor property of a fresh object: enumerable and configurable,
|
||||
* with the given getter and setter (either may be NULL). Moves both. */
|
||||
void scr_dyn_obj_set_accessor(ScrDyn *obj, const char *key, size_t key_len, ScrDyn *getter, ScrDyn *setter);
|
||||
|
||||
@@ -388,8 +388,80 @@ static SCR_TL bool scr_stdin_destroyed = false;
|
||||
static SCR_TL bool scr_stdin_paused = false;
|
||||
static SCR_TL bool scr_stdin_resumed = false;
|
||||
static SCR_TL bool scr_stdin_read_eof = false;
|
||||
static SCR_TL ScrBytes *scr_stdin_buffer;
|
||||
/* Input held for read() and later consumers, as Node's BufferList: the
|
||||
* chunks in arrival order and their total length, so an arrival appends
|
||||
* without copying what is already held. */
|
||||
static SCR_TL ScrBytes **scr_stdin_held = NULL;
|
||||
static SCR_TL size_t scr_stdin_nheld = 0, scr_stdin_held_cap = 0;
|
||||
static SCR_TL size_t scr_stdin_buffered = 0;
|
||||
static SCR_TL size_t scr_stdin_read_demand;
|
||||
/* 'readable' listeners (paused mode, as Node's once one is added): input
|
||||
* stays buffered for read(), and the event fires on the next tick when
|
||||
* input arrives while a read wanted more (`need`), and once at EOF. */
|
||||
static SCR_TL ScrStdinEndL *scr_stdin_readable = NULL;
|
||||
static SCR_TL size_t scr_stdin_nreadable = 0, scr_stdin_readable_cap = 0;
|
||||
static SCR_TL bool scr_stdin_readable_need = false;
|
||||
static SCR_TL bool scr_stdin_readable_queued = false;
|
||||
|
||||
/* Appends an arrived chunk (moves) to the held input. */
|
||||
static void scr_stdin_hold(ScrBytes *chunk) {
|
||||
if (chunk->len == 0) {
|
||||
scr_bytes_release(chunk);
|
||||
return;
|
||||
}
|
||||
if (scr_stdin_nheld == scr_stdin_held_cap) {
|
||||
scr_stdin_held_cap = scr_stdin_held_cap ? scr_stdin_held_cap * 2 : 4;
|
||||
scr_stdin_held = realloc(scr_stdin_held, scr_stdin_held_cap * sizeof *scr_stdin_held);
|
||||
if (!scr_stdin_held) scr_events_oom();
|
||||
}
|
||||
scr_stdin_held[scr_stdin_nheld++] = chunk;
|
||||
scr_stdin_buffered += chunk->len;
|
||||
}
|
||||
|
||||
/* The first n held bytes as one chunk (+1), 0 < n <= scr_stdin_buffered.
|
||||
* A whole first chunk moves out without a copy; otherwise the bytes are
|
||||
* joined once, and a partly taken chunk keeps its rest. */
|
||||
static ScrBytes *scr_stdin_take(size_t n) {
|
||||
ScrBytes *first = scr_stdin_held[0];
|
||||
size_t used = 0;
|
||||
ScrBytes *out;
|
||||
if (n == first->len) {
|
||||
out = first;
|
||||
used = 1;
|
||||
} else if (n < first->len) {
|
||||
out = scr_bytes_slice(first, 0, (double)n);
|
||||
scr_stdin_held[0] = scr_bytes_slice(first, (double)n, (double)first->len);
|
||||
scr_bytes_release(first);
|
||||
} else {
|
||||
out = scr_bytes_new(SCR_BYTES_U8, (double)n);
|
||||
size_t at = 0;
|
||||
while (at < n) {
|
||||
ScrBytes *chunk = scr_stdin_held[used];
|
||||
size_t part = chunk->len <= n - at ? chunk->len : n - at;
|
||||
memcpy(out->data + at, chunk->data, part);
|
||||
at += part;
|
||||
if (part == chunk->len) {
|
||||
scr_bytes_release(chunk);
|
||||
used++;
|
||||
} else {
|
||||
scr_stdin_held[used] = scr_bytes_slice(chunk, (double)part, (double)chunk->len);
|
||||
scr_bytes_release(chunk);
|
||||
}
|
||||
}
|
||||
}
|
||||
memmove(scr_stdin_held, scr_stdin_held + used, (scr_stdin_nheld - used) * sizeof *scr_stdin_held);
|
||||
scr_stdin_nheld -= used;
|
||||
scr_stdin_buffered -= n;
|
||||
return out;
|
||||
}
|
||||
|
||||
static void scr_stdin_drop_held(void) {
|
||||
for (size_t i = 0; i < scr_stdin_nheld; i++) scr_bytes_release(scr_stdin_held[i]);
|
||||
free(scr_stdin_held);
|
||||
scr_stdin_held = NULL;
|
||||
scr_stdin_nheld = scr_stdin_held_cap = 0;
|
||||
scr_stdin_buffered = 0;
|
||||
}
|
||||
|
||||
#ifdef SCR_STDIO_EXTENDED
|
||||
/* process.stdin.setEncoding(enc): the canonical encoding name (NULL until
|
||||
@@ -475,6 +547,78 @@ void scr_stdin_on_end(ScrClosure *cb /*moves*/, bool once) {
|
||||
scr_stdin_nend++;
|
||||
}
|
||||
|
||||
static void scr_stdin_finish(bool fire_end);
|
||||
|
||||
static void scr_stdin_emit_readable(void) {
|
||||
scr_stdin_readable_queued = false;
|
||||
size_t length = scr_stdin_buffered;
|
||||
if (scr_stdin_eof || scr_stdin_destroyed || (!length && !scr_stdin_read_eof)) return;
|
||||
size_t n = scr_stdin_nreadable;
|
||||
ScrStdinEndL *snap = malloc((n ? n : 1) * sizeof *snap);
|
||||
if (!snap) scr_events_oom();
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
snap[i] = scr_stdin_readable[i];
|
||||
scr_closure_retain(snap[i].cb);
|
||||
}
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
if (snap[i].once) {
|
||||
for (size_t j = 0; j < scr_stdin_nreadable; j++) {
|
||||
if (scr_stdin_readable[j].cb == snap[i].cb) {
|
||||
scr_closure_release(scr_stdin_readable[j].cb);
|
||||
memmove(scr_stdin_readable + j, scr_stdin_readable + j + 1,
|
||||
(scr_stdin_nreadable - j - 1) * sizeof *scr_stdin_readable);
|
||||
scr_stdin_nreadable--;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!scr_exc_pending() && !scr_stdin_eof && !scr_stdin_destroyed)
|
||||
((void (*)(ScrClosure *))snap[i].cb->fn)(snap[i].cb);
|
||||
scr_closure_release(snap[i].cb);
|
||||
}
|
||||
free(snap);
|
||||
length = scr_stdin_buffered;
|
||||
/* Another event is due once the buffer reaches the 64 KiB mark, or the
|
||||
* larger size a listener's read(size) asked for. */
|
||||
scr_stdin_readable_need =
|
||||
!scr_stdin_read_eof && (length <= 65536 || length < scr_stdin_read_demand);
|
||||
}
|
||||
|
||||
static void scr_stdin_queue_readable(void) {
|
||||
if (scr_stdin_readable_queued || !scr_stdin_nreadable) return;
|
||||
scr_stdin_readable_queued = true;
|
||||
scr_next_tick_raw(scr_stdin_emit_readable);
|
||||
}
|
||||
|
||||
/* Adding a 'readable' listener starts reading ahead to the 64 KiB mark; a
|
||||
* buffer that already holds input fires the event at once (next tick). */
|
||||
static void scr_stdin_on_readable(ScrClosure *cb /*moves*/, bool once) {
|
||||
if (scr_stdin_eof || scr_stdin_destroyed) {
|
||||
scr_closure_release(cb);
|
||||
return;
|
||||
}
|
||||
if (scr_stdin_nreadable == scr_stdin_readable_cap) {
|
||||
scr_stdin_readable_cap = scr_stdin_readable_cap ? scr_stdin_readable_cap * 2 : 2;
|
||||
scr_stdin_readable = realloc(scr_stdin_readable, scr_stdin_readable_cap * sizeof *scr_stdin_readable);
|
||||
if (!scr_stdin_readable) scr_events_oom();
|
||||
}
|
||||
scr_stdin_readable[scr_stdin_nreadable].cb = cb;
|
||||
scr_stdin_readable[scr_stdin_nreadable].once = once;
|
||||
scr_stdin_nreadable++;
|
||||
scr_stdin_readable_need = true;
|
||||
if (scr_stdin_read_demand < 65536) scr_stdin_read_demand = 65536;
|
||||
if (scr_stdin_buffered) scr_stdin_queue_readable();
|
||||
}
|
||||
|
||||
/* The input ended: with 'readable' listeners the event fires once more and
|
||||
* 'end' waits for the read that finds nothing left; otherwise 'end' fires
|
||||
* once the buffer is drained. */
|
||||
static void scr_stdin_reached_eof(void) {
|
||||
scr_stdin_read_eof = true;
|
||||
if (scr_stdin_nreadable) scr_stdin_queue_readable();
|
||||
else if (!scr_stdin_buffered) scr_stdin_finish(true);
|
||||
}
|
||||
|
||||
void scr_stdin_on_error(ScrClosure *cb /*moves*/, ScrChildErrFn fn, bool once) {
|
||||
if (scr_stdin_eof || scr_stdin_destroyed) {
|
||||
scr_closure_release(cb);
|
||||
@@ -516,10 +660,15 @@ bool scr_stdin_ended(void) { return scr_stdin_eof || scr_stdin_destroyed; }
|
||||
* alive (a paused Node stdin with only those never flows — the process
|
||||
* exits with them registered). */
|
||||
static bool scr_stdin_watching(void) {
|
||||
return !scr_stdin_eof && !scr_stdin_destroyed &&
|
||||
((!scr_stdin_paused && (scr_stdin_ndata > 0 || scr_stdin_resumed)) ||
|
||||
scr_stdin_waiter != NULL ||
|
||||
(!scr_stdin_read_eof && scr_stdin_read_demand > (scr_stdin_buffer ? scr_stdin_buffer->len : 0)));
|
||||
if (scr_stdin_eof || scr_stdin_destroyed) return false;
|
||||
/* 'readable' listeners keep the stream paused, as in Node, where
|
||||
* resume() and 'data' listeners do not make it flow: it reads ahead only
|
||||
* while a read wants more than is held (the 64 KiB mark, or a larger
|
||||
* read(size)), and stops until something drains it. */
|
||||
if (scr_stdin_nreadable) return !scr_stdin_read_eof && scr_stdin_read_demand > scr_stdin_buffered;
|
||||
return (!scr_stdin_paused && (scr_stdin_ndata > 0 || scr_stdin_resumed)) ||
|
||||
scr_stdin_waiter != NULL ||
|
||||
(!scr_stdin_read_eof && scr_stdin_read_demand > scr_stdin_buffered);
|
||||
}
|
||||
|
||||
bool scr_stdin_pending(void) { return scr_stdin_watching(); }
|
||||
@@ -528,6 +677,10 @@ static void scr_stdin_drop_listeners(void) {
|
||||
for (size_t i = 0; i < scr_stdin_ndata; i++) scr_closure_release(scr_stdin_data[i].cb);
|
||||
for (size_t i = 0; i < scr_stdin_nend; i++) scr_closure_release(scr_stdin_end[i].cb);
|
||||
for (size_t i = 0; i < scr_stdin_nerr; i++) scr_closure_release(scr_stdin_err[i].cb);
|
||||
for (size_t i = 0; i < scr_stdin_nreadable; i++) scr_closure_release(scr_stdin_readable[i].cb);
|
||||
free(scr_stdin_readable);
|
||||
scr_stdin_readable = NULL;
|
||||
scr_stdin_nreadable = scr_stdin_readable_cap = 0;
|
||||
free(scr_stdin_data);
|
||||
free(scr_stdin_end);
|
||||
free(scr_stdin_err);
|
||||
@@ -593,8 +746,7 @@ static void scr_stdin_finish(bool fire_end) {
|
||||
void scr_stdin_destroy(void) {
|
||||
if (scr_stdin_destroyed) return;
|
||||
scr_stdin_destroyed = true;
|
||||
scr_bytes_release(scr_stdin_buffer);
|
||||
scr_stdin_buffer = NULL;
|
||||
scr_stdin_drop_held();
|
||||
scr_stdin_read_demand = 0;
|
||||
scr_stdin_settle_done();
|
||||
scr_stdin_drop_listeners();
|
||||
@@ -627,16 +779,9 @@ static void scr_stdin_deliver(ScrBytes *chunk);
|
||||
/* A chunk that arrived (moves): delivered, or buffered while paused or
|
||||
* without a consumer. */
|
||||
static void scr_stdin_arrived(ScrBytes *chunk) {
|
||||
if (scr_stdin_paused || (!scr_stdin_ndata && !scr_stdin_resumed && !scr_stdin_waiter)) {
|
||||
if (scr_stdin_buffer) {
|
||||
size_t before = scr_stdin_buffer->len;
|
||||
ScrBytes *joined = scr_bytes_new(SCR_BYTES_U8, (double)(before + chunk->len));
|
||||
memcpy(joined->data, scr_stdin_buffer->data, before);
|
||||
memcpy(joined->data + before, chunk->data, chunk->len);
|
||||
scr_bytes_release(scr_stdin_buffer);
|
||||
scr_bytes_release(chunk);
|
||||
scr_stdin_buffer = joined;
|
||||
} else scr_stdin_buffer = chunk;
|
||||
if (scr_stdin_paused || scr_stdin_nreadable || (!scr_stdin_ndata && !scr_stdin_resumed && !scr_stdin_waiter)) {
|
||||
if (scr_stdin_nreadable && scr_stdin_readable_need) scr_stdin_queue_readable();
|
||||
scr_stdin_hold(chunk);
|
||||
return;
|
||||
}
|
||||
scr_stdin_deliver(chunk);
|
||||
@@ -645,15 +790,18 @@ static void scr_stdin_arrived(ScrBytes *chunk) {
|
||||
|
||||
static void scr_stdin_service(void) {
|
||||
if (!scr_stdin_watching()) return;
|
||||
if (!scr_stdin_paused && scr_stdin_buffer) {
|
||||
ScrBytes *chunk = scr_stdin_buffer;
|
||||
scr_stdin_buffer = NULL;
|
||||
/* Buffered input goes to a consumer: 'data' listeners, a resumed
|
||||
* stream, or a parked for-await read. After the last 'readable' listener
|
||||
* it stays buffered until one arrives, as in Node. */
|
||||
if (!scr_stdin_paused && !scr_stdin_nreadable && scr_stdin_buffered &&
|
||||
(scr_stdin_ndata > 0 || scr_stdin_resumed || scr_stdin_waiter != NULL)) {
|
||||
ScrBytes *chunk = scr_stdin_take(scr_stdin_buffered);
|
||||
scr_stdin_deliver(chunk);
|
||||
scr_bytes_release(chunk);
|
||||
return;
|
||||
}
|
||||
if (scr_stdin_read_eof) {
|
||||
if (!scr_stdin_buffer) scr_stdin_finish(true);
|
||||
if (!scr_stdin_buffered && !scr_stdin_nreadable) scr_stdin_finish(true);
|
||||
return;
|
||||
}
|
||||
if (scr_stdin_fed) {
|
||||
@@ -662,10 +810,7 @@ static void scr_stdin_service(void) {
|
||||
bool ended = false;
|
||||
ScrBytes *chunk = scr_stdin_fed_take(&ended);
|
||||
if (chunk) scr_stdin_arrived(chunk);
|
||||
else if (ended) {
|
||||
scr_stdin_read_eof = true;
|
||||
if (!scr_stdin_buffer) scr_stdin_finish(true);
|
||||
}
|
||||
else if (ended) scr_stdin_reached_eof();
|
||||
return;
|
||||
}
|
||||
#ifdef _WIN32
|
||||
@@ -727,8 +872,7 @@ static void scr_stdin_service(void) {
|
||||
return;
|
||||
}
|
||||
if (n == 0) {
|
||||
scr_stdin_read_eof = true;
|
||||
if (!scr_stdin_buffer) scr_stdin_finish(true);
|
||||
scr_stdin_reached_eof();
|
||||
return;
|
||||
}
|
||||
ScrBytes *chunk = scr_bytes_new(SCR_BYTES_U8, (double)n);
|
||||
@@ -802,6 +946,8 @@ static void scr_stdin_deliver(ScrBytes *chunk) {
|
||||
#endif
|
||||
ScrPromise *p = scr_stdin_waiter;
|
||||
scr_stdin_waiter = NULL;
|
||||
/* Node's stdin yields Buffers. */
|
||||
chunk->is_buffer = true;
|
||||
scr_promise_fulfill_ref(p, scr_bytes_retain(chunk), scr_bytes_retain_v,
|
||||
scr_bytes_release_v, NULL);
|
||||
scr_promise_release(p);
|
||||
@@ -878,6 +1024,7 @@ static void scr_stdio_data_text(ScrClosure *cb, ScrStr *text) {
|
||||
}
|
||||
#endif
|
||||
static void scr_stdio_end(ScrClosure *cb) { scr_stdio_fire(cb, NULL, 0); }
|
||||
static void scr_stdio_readable(ScrClosure *cb) { scr_stdio_fire(cb, NULL, 0); }
|
||||
static void scr_stdio_error(ScrClosure *cb, ScrStr *message) {
|
||||
ScrError *error = scr_error_new(SCR_ERR_ERROR, message);
|
||||
ScrDyn *arg = scr_dyn_from_error(error);
|
||||
@@ -971,7 +1118,7 @@ static void scr_stdio_queue_write_error(ScrStdio *stream, ScrDyn *callback, int
|
||||
}
|
||||
|
||||
static void scr_stdio_finish_read(void) {
|
||||
if (scr_stdin_read_eof && !scr_stdin_buffer && !scr_stdin_eof && !scr_stdin_destroyed)
|
||||
if (scr_stdin_read_eof && !scr_stdin_buffered && !scr_stdin_eof && !scr_stdin_destroyed)
|
||||
scr_stdin_finish(true);
|
||||
}
|
||||
|
||||
@@ -980,21 +1127,21 @@ static ScrDyn *scr_stdio_read(ScrDyn *size) {
|
||||
if (!all && (size->kind != SCR_DYN_NUM || !isfinite(size->v.num) ||
|
||||
size->v.num < 0 || size->v.num > 1073741824 || floor(size->v.num) != size->v.num))
|
||||
return scr_stdio_refusal("read size");
|
||||
size_t available = scr_stdin_buffer ? scr_stdin_buffer->len : 0;
|
||||
size_t available = scr_stdin_buffered;
|
||||
size_t wanted = all ? available : (size_t)size->v.num;
|
||||
if (scr_stdin_read_eof && wanted > available) wanted = available;
|
||||
if (wanted == 0 || wanted > available) {
|
||||
if (!scr_stdin_eof && !scr_stdin_destroyed) {
|
||||
scr_stdin_readable_need = true;
|
||||
scr_stdin_read_demand = wanted > 65536 ? wanted : 65536;
|
||||
if (scr_stdin_read_eof) scr_next_tick_raw(scr_stdio_finish_read);
|
||||
}
|
||||
return scr_dyn_new_null();
|
||||
}
|
||||
ScrBytes *chunk = scr_bytes_slice(scr_stdin_buffer, 0, (double)wanted);
|
||||
ScrBytes *rest = wanted < available ? scr_bytes_slice(scr_stdin_buffer, (double)wanted, (double)available) : NULL;
|
||||
scr_bytes_release(scr_stdin_buffer);
|
||||
scr_stdin_buffer = rest;
|
||||
ScrBytes *chunk = scr_stdin_take(wanted);
|
||||
bool rest = scr_stdin_buffered > 0;
|
||||
scr_stdin_read_demand = 65536;
|
||||
if (!rest && !scr_stdin_read_eof) scr_stdin_readable_need = true;
|
||||
scr_stdin_deliver(chunk);
|
||||
ScrDyn *result = scr_dyn_new_chunk(chunk);
|
||||
scr_bytes_release(chunk);
|
||||
@@ -1150,12 +1297,14 @@ static ScrDyn *scr_stdio_method(ScrClosure *cb, ScrDyn *const *args, size_t argc
|
||||
bool data = arg->kind == SCR_DYN_STR && arg->v.str->len == 4 && memcmp(event, "data", 4) == 0;
|
||||
bool end = arg->kind == SCR_DYN_STR && arg->v.str->len == 3 && memcmp(event, "end", 3) == 0;
|
||||
bool error = arg->kind == SCR_DYN_STR && arg->v.str->len == 5 && memcmp(event, "error", 5) == 0;
|
||||
bool readable = stream->fd == 0 && arg->kind == SCR_DYN_STR && arg->v.str->len == 8 &&
|
||||
memcmp(event, "readable", 8) == 0;
|
||||
#ifdef SCR_STDIO_EXTENDED
|
||||
bool resize = stream->fd != 0 && arg->kind == SCR_DYN_STR && arg->v.str->len == 6 &&
|
||||
memcmp(event, "resize", 6) == 0;
|
||||
if ((!data && !end && !error && !resize) || (stream->fd != 0 && !error && !resize)) {
|
||||
if ((!data && !end && !error && !readable && !resize) || (stream->fd != 0 && !error && !resize)) {
|
||||
#else
|
||||
if ((!data && !end && !error) || (stream->fd != 0 && !error)) {
|
||||
if ((!data && !end && !error && !readable) || (stream->fd != 0 && !error)) {
|
||||
#endif
|
||||
result = scr_stdio_refusal("event");
|
||||
goto done;
|
||||
@@ -1175,6 +1324,7 @@ static ScrDyn *scr_stdio_method(ScrClosure *cb, ScrDyn *const *args, size_t argc
|
||||
if (data) scr_stdin_on_data(scr_stdio_callback(listener, (void *)scr_stdio_data), scr_stdio_data, once);
|
||||
#endif
|
||||
if (end) scr_stdin_on_end(scr_stdio_callback(listener, (void *)scr_stdio_end), once);
|
||||
if (readable) scr_stdin_on_readable(scr_stdio_callback(listener, (void *)scr_stdio_readable), once);
|
||||
if (error) scr_stdin_on_error(scr_stdio_callback(listener, (void *)scr_stdio_error), scr_stdio_error, once);
|
||||
} else {
|
||||
#define REMOVE_STDIO_LISTENER(list, count, fire) \
|
||||
@@ -1187,6 +1337,7 @@ static ScrDyn *scr_stdio_method(ScrClosure *cb, ScrDyn *const *args, size_t argc
|
||||
}
|
||||
if (data) { REMOVE_STDIO_LISTENER(scr_stdin_data, scr_stdin_ndata, scr_stdio_data); }
|
||||
if (end) { REMOVE_STDIO_LISTENER(scr_stdin_end, scr_stdin_nend, scr_stdio_end); }
|
||||
if (readable) { REMOVE_STDIO_LISTENER(scr_stdin_readable, scr_stdin_nreadable, scr_stdio_readable); }
|
||||
if (error) { REMOVE_STDIO_LISTENER(scr_stdin_err, scr_stdin_nerr, scr_stdio_error); }
|
||||
#undef REMOVE_STDIO_LISTENER
|
||||
}
|
||||
@@ -1246,7 +1397,7 @@ static ScrDyn *scr_stdio_get(void *ptr, const char *key, size_t length) {
|
||||
return dimension < 0 ? scr_dyn_retain(scr_dyn_undefined()) : scr_dyn_new_num(dimension);
|
||||
}
|
||||
if (stream->fd == 0 && length == 14 && memcmp(key, "readableLength", 14) == 0)
|
||||
return scr_dyn_new_num(scr_stdin_buffer ? (double)scr_stdin_buffer->len : 0);
|
||||
return scr_dyn_new_num((double)scr_stdin_buffered);
|
||||
if (stream->fd == 0 && length == 5 && memcmp(key, "isRaw", 5) == 0)
|
||||
return scr_process_is_tty(0) ? scr_dyn_new_bool(scr_stdio_raw) : scr_dyn_retain(scr_dyn_undefined());
|
||||
if (stream->fd == 0 && length == 9 && memcmp(key, "destroyed", 9) == 0) return scr_dyn_new_bool(scr_stdin_destroyed);
|
||||
@@ -1531,8 +1682,7 @@ static void scr_events_cleanup_atexit(void) {
|
||||
if (scr_context_is_main()) scr_sig_cleanup();
|
||||
scr_stdin_settle_done();
|
||||
scr_stdin_drop_listeners();
|
||||
scr_bytes_release(scr_stdin_buffer);
|
||||
scr_stdin_buffer = NULL;
|
||||
scr_stdin_drop_held();
|
||||
if (scr_stdio_initialized) scr_stdio_cleanup();
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user