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:
@@ -498,6 +498,30 @@ jobs:
|
||||
- name: TypeScript 7 full parity sweep
|
||||
run: pnpm test:ts7
|
||||
|
||||
# tsc-ts, the default checker, and tsgo (SCRIPTC_CHECKER=tsgo) serve the same TypeScript 7 API. Every corpus
|
||||
# program must compile to the same LLVM IR, with the same diagnostics, with either checker.
|
||||
checker_identity:
|
||||
needs: [validation_scope, lanes]
|
||||
if: ${{ needs.validation_scope.outputs.full == 'true' && needs.lanes.outputs.linux == 'true' }}
|
||||
name: test (tsgo and tsc-ts give the same IR)
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 11.1.3
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: .node-version
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm build
|
||||
- name: Corpus LLVM IR with tsgo and with tsc-ts (release)
|
||||
run: pnpm test:checker-identity --optimization release
|
||||
- name: Corpus LLVM IR with tsgo and with tsc-ts (dev)
|
||||
run: pnpm test:checker-identity --optimization dev
|
||||
|
||||
llvm_artifacts_linux_x64:
|
||||
needs: [validation_scope, lanes]
|
||||
if: ${{ needs.validation_scope.outputs.full == 'true' && needs.lanes.outputs.linux == 'true' }}
|
||||
@@ -863,7 +887,28 @@ jobs:
|
||||
# Require this check on the stack base. Upper layers must not pass before
|
||||
# full validation, so untested groups cannot merge. Merge bottom-up.
|
||||
test:
|
||||
needs: [validation_scope, lanes, code_quality, native_macos, tests, tests_macos, native_linux, effects, bootstrap_seed, bootstrap, linux_host_clang, ts7_parity, llvm_artifacts_linux_x64, llvm_artifacts_macos_arm64, llvm_artifacts_macos_x64, windows_cli, llvm_artifacts_windows_x64, mobile_runtime_packs]
|
||||
needs:
|
||||
[
|
||||
validation_scope,
|
||||
lanes,
|
||||
code_quality,
|
||||
native_macos,
|
||||
tests,
|
||||
tests_macos,
|
||||
native_linux,
|
||||
effects,
|
||||
bootstrap_seed,
|
||||
bootstrap,
|
||||
linux_host_clang,
|
||||
ts7_parity,
|
||||
checker_identity,
|
||||
llvm_artifacts_linux_x64,
|
||||
llvm_artifacts_macos_arm64,
|
||||
llvm_artifacts_macos_x64,
|
||||
windows_cli,
|
||||
llvm_artifacts_windows_x64,
|
||||
mobile_runtime_packs,
|
||||
]
|
||||
# Run even after failed or cancelled lanes: skipped required jobs allow merging.
|
||||
if: ${{ always() }}
|
||||
runs-on: ubuntu-latest
|
||||
@@ -887,6 +932,7 @@ jobs:
|
||||
lane bootstrap "${{ needs.bootstrap.result }}" "${{ needs.lanes.outputs.bootstrap }}"
|
||||
lane linux_host_clang "${{ needs.linux_host_clang.result }}" "${{ needs.lanes.outputs.linux }}"
|
||||
lane ts7_parity "${{ needs.ts7_parity.result }}" "${{ needs.lanes.outputs.linux }}"
|
||||
lane checker_identity "${{ needs.checker_identity.result }}" "${{ needs.lanes.outputs.linux }}"
|
||||
lane llvm_artifacts_linux_x64 "${{ needs.llvm_artifacts_linux_x64.result }}" "${{ needs.lanes.outputs.linux }}"
|
||||
lane llvm_artifacts_macos_arm64 "${{ needs.llvm_artifacts_macos_arm64.result }}" "${{ needs.lanes.outputs.macos }}"
|
||||
lane llvm_artifacts_macos_x64 "${{ needs.llvm_artifacts_macos_x64.result }}" "${{ needs.lanes.outputs.macos }}"
|
||||
|
||||
@@ -178,6 +178,9 @@ Verifies and loads the installed precompiled runtime objects and vendored librar
|
||||
|
||||
<dt><code>SCRIPTC_RUNTIME_PACK</code></dt>
|
||||
<dd>A runtime pack directory to use instead of an installed <code>@scriptc/runtime-<target></code> package.</dd>
|
||||
|
||||
<dt><code>SCRIPTC_CHECKER</code></dt>
|
||||
<dd>The TypeScript 7 API server that checks the program: <code>tsc-ts</code> (the default), which scriptc includes, or <code>tsgo</code>, from the <code>typescript</code> package scriptc also includes. Both give the same diagnostics and generated code. On Windows the default is <code>tsgo</code>, because tsc-ts's API server does not yet accept the named pipe scriptc connects over there.</dd>
|
||||
</dl>
|
||||
|
||||
```console
|
||||
|
||||
@@ -52,10 +52,12 @@ Type-only imports follow Node.js's type stripping. `import type` and `export typ
|
||||
|
||||
scriptc compiles a package automatically when it:
|
||||
|
||||
- ships its own type declarations, and
|
||||
- ships readable, unminified JavaScript.
|
||||
- ships its own type declarations, or is typed by its DefinitelyTyped `@types/` package, or is a dependency of another package that has no declarations at all, and
|
||||
- ships readable JavaScript: unminified, or minified by a bundler whose helpers keep their names.
|
||||
|
||||
A package that doesn't meet these requirements, or that uses something scriptc can't compile, gets a package-specific diagnostic that explains why. The usual fixes are to switch to a version or alternative package that compiles, or to replace the call with code you write yourself. A package whose declarations come from a separate `@types/` package doesn't ship its own; its diagnostic names the package and the `--npm-static` option that compiles it anyway.
|
||||
The declarations check your program; the package's JavaScript compiles with the types scriptc infers from it. A program that doesn't typecheck against the inferred types, for example because an `@types/` package describes another release, fails the build at that use.
|
||||
|
||||
A package that doesn't meet these requirements, or that uses something scriptc can't compile, gets a package-specific diagnostic that explains why. The usual fixes are to switch to a version or alternative package that compiles, or to replace the call with code you write yourself.
|
||||
|
||||
<span id="value-conversion" />
|
||||
<span id="static-package-compilation-experimental" />
|
||||
@@ -63,17 +65,17 @@ A package that doesn't meet these requirements, or that uses something scriptc c
|
||||
|
||||
## Explicit package selection
|
||||
|
||||
Some packages rely on separately installed declarations, such as an `@types/` package, or on types inferred from their JavaScript. To try compiling one of them, name it with `--npm-static`:
|
||||
Some packages your program imports directly ship no declarations, so their types can only be inferred from their JavaScript. To try compiling one of them, name it with `--npm-static`:
|
||||
|
||||
```console
|
||||
$ scriptc build app.ts --npm-static=three -o app >/dev/null
|
||||
```
|
||||
|
||||
Naming a package skips the declaration requirement above, but the package still has to compile. The option selects only the packages it names: a dependency of a named package that doesn't ship its own declarations is still refused. Add a trailing `...` to select a package together with every package it depends on, for example `--npm-static=fs-extra...`. `--npm-static=auto` uses the default automatic selection. The option accepts a comma-separated list and can be repeated.
|
||||
Naming a package skips the declaration requirement above, but the package still has to compile. Add a trailing `...` to select a package together with every package it depends on, for example `--npm-static=fs-extra...`. `--npm-static=auto` uses the default automatic selection. The option accepts a comma-separated list and can be repeated.
|
||||
|
||||
## CommonJS packages
|
||||
|
||||
CommonJS packages compile with Node.js's module semantics. Each `require()` evaluates its module at the call, once, and later calls return the cached exports. A package can assign `module.exports` and run code before it requires its dependencies. If that code reads a `const` or `let` require binding before its `require` runs, the read throws the same `ReferenceError` as Node.js. A `var` binding that earlier code can reach is reported at build time. A `require()` of a JSON file, such as a package's own `package.json`, returns one object parsed at build time, shared by every module that requires it. A require cycle compiles when each of its modules assigns its exports before requiring anything, as semver's classes do, and uses the other modules only inside functions that its top-level code can't call. Other require cycles are reported at build time. The [limitations](/docs/limitations) page lists the supported `require` forms.
|
||||
CommonJS packages compile with Node.js's module semantics. Each `require()` evaluates its module at the call, once, and later calls return the cached exports. A package can assign `module.exports` and run code before it requires its dependencies. If that code reads a `const` or `let` require binding before its `require` runs, the read throws the same `ReferenceError` as Node.js. A `var` binding that earlier code can reach is reported at build time. A `require()` of a JSON file, such as a package's own `package.json`, returns one object parsed at build time, shared by every module that requires it. A require cycle compiles when each of its modules assigns its exports before requiring anything, as semver's classes and esbuild's per-file output do, and uses the other modules only inside functions that its top-level code can't call. Bundles built by esbuild compile with their bundled CommonJS modules and lazily initialized ES modules, each evaluated once, at its first use, as under Node.js. Other require cycles are reported at build time. The [limitations](/docs/limitations) page lists the supported `require` forms.
|
||||
|
||||
## Unsupported code inside a package
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
"bench:backend-analysis": "node scripts/bench-backend-analysis.mjs",
|
||||
"test": "vitest run",
|
||||
"test:ts7": "node scripts/test-ts7.mjs",
|
||||
"test:checker-identity": "node scripts/checker-identity.mjs",
|
||||
"generate:ts7-ast": "node scripts/generate-ts7-ast-schema.mjs",
|
||||
"test:fetch-conformance": "vitest run tests/harness/fetch-conformance.test.ts",
|
||||
"test:test262": "tsx tests/test262/run.ts",
|
||||
|
||||
@@ -42,6 +42,7 @@ export function relocateToolchain(manifest, sourceDirectory, destinationDirector
|
||||
const pathFrom = (value) => relative(destinationDirectory, resolve(sourceDirectory, value));
|
||||
for (const name of [
|
||||
"ts7",
|
||||
"tsc_ts",
|
||||
"llvm_package",
|
||||
"runtime_pack",
|
||||
"runtime_sources",
|
||||
@@ -96,6 +97,7 @@ export function installNativeCli(
|
||||
if (process.platform !== "win32") {
|
||||
for (const path of [
|
||||
manifest.ts7,
|
||||
...(manifest.tsc_ts === undefined ? [] : [manifest.tsc_ts]),
|
||||
manifest.comptime,
|
||||
join(manifest.llvm_package, "bin/scriptc-llvm-codegen"),
|
||||
]) {
|
||||
|
||||
@@ -116,6 +116,13 @@ async function tryFastPath(): Promise<number | null> {
|
||||
// the whole compiler graph to rediscover it.
|
||||
const helperRuntimePackTarget = !values.sanitize ? startup.precompiledRuntimePackTarget() : null;
|
||||
const helperObjectRoute = helperRuntimePackTarget !== null;
|
||||
// The full compiler reports a checker it cannot find.
|
||||
let checker: string | undefined;
|
||||
try {
|
||||
checker = startup.checkerCacheIdentity();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const hit = await startup.readRoutedExecutableCache(root, {
|
||||
entryPath: input,
|
||||
outDir,
|
||||
@@ -126,6 +133,7 @@ async function tryFastPath(): Promise<number | null> {
|
||||
...(optimization === "dev" || optimization === "speed" ? { optimization } : {}),
|
||||
...(values.strip ? { strip: true as const } : {}),
|
||||
...(values["detached-exit"] ? { detachedExit: true as const } : {}),
|
||||
...(checker === undefined ? {} : { checker }),
|
||||
npmStatic,
|
||||
ffiProfile: ffiPath === null ? null : { path: ffiPath, bytes: ffiBytes! },
|
||||
target: `${process.env["SCRIPTC_TARGET"] ?? "native"}:${buildPlatform}:${process.arch}:${
|
||||
|
||||
@@ -39,6 +39,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@scriptc/runtime": "workspace:*",
|
||||
"tsc-ts": "0.0.3",
|
||||
"typescript": "7.0.2",
|
||||
"typescript5": "npm:typescript@5.9.3"
|
||||
},
|
||||
|
||||
@@ -34,6 +34,7 @@ import { InternalCompilerError } from "../../errors.js";
|
||||
* ScrDynPath { parent, key, index } — the %ScrDynPath type. */
|
||||
import type { IrRecordShape, IrType, IrUnionDef } from "../../ir/ir.js";
|
||||
import {
|
||||
accessorSlotProp,
|
||||
DYN_HANDLE_KINDS,
|
||||
isDirentShape,
|
||||
isDynTypedRefType,
|
||||
@@ -613,6 +614,18 @@ export class LlDyn {
|
||||
* tracking does not count the read's reference. Returns the value and
|
||||
* the matching release. */
|
||||
private memberRead(B: BlockBuilder, key: string, t: IrType): { value: string; release: string } {
|
||||
// An accessor slot reads the getter or setter of the accessor property
|
||||
// the checked-dynamic copy holds for it (see accessorSlotProp).
|
||||
const slot = accessorSlotProp(key);
|
||||
if (slot !== null) {
|
||||
this.host.declare(`declare ptr @scr_dyn_obj_accessor_fn(ptr, ptr, ${this.S}, i1 zeroext)`);
|
||||
this.host.declare(`declare void @scr_dyn_release(ptr)`);
|
||||
const fn = B.tmp();
|
||||
B.line(
|
||||
`${fn} = call ptr @scr_dyn_obj_accessor_fn(ptr %d, ptr ${this.host.cstr(slot.prop)}, ${this.S} ${Buffer.byteLength(slot.prop, "utf8")}, i1 ${slot.kind === "set" ? "true" : "false"})`,
|
||||
);
|
||||
return { value: fn, release: "scr_dyn_release" };
|
||||
}
|
||||
const held = this.isRecursiveShape(t) || this.holdsRecursiveShape(t);
|
||||
const release = held ? "scr_dyn_release_held" : "scr_dyn_release";
|
||||
this.host.declare(`declare void @${release}(ptr)`);
|
||||
@@ -2687,13 +2700,53 @@ export class LlDyn {
|
||||
// Keys insert in DECLARED order (JS insertion order); internal
|
||||
// '%'-fields follow so a record→dyn→record round trip keeps them.
|
||||
const byName = new Map(shape.fields.map((f) => [f.name, f]));
|
||||
const order = shape.declaredOrder ?? shape.fields.map((f) => f.name);
|
||||
// An accessor property is one key whose getter and setter are the
|
||||
// slot closures (see accessorSlotProp), in accessorOrder's place.
|
||||
const order = shape.accessorOrder ?? shape.declaredOrder ?? shape.fields.map((f) => f.name);
|
||||
const inOrder = new Set(order);
|
||||
const dynFields = [
|
||||
...order.map((n) => byName.get(n)).filter((f) => f !== undefined),
|
||||
...shape.fields.filter((f) => !inOrder.has(f.name)),
|
||||
const accessors = new Set(
|
||||
shape.accessorOrder === undefined
|
||||
? []
|
||||
: shape.fields.flatMap((f) => {
|
||||
const slot = accessorSlotProp(f.name);
|
||||
return slot === null ? [] : [slot.prop];
|
||||
}),
|
||||
);
|
||||
type DynField = { name: string; type: IrType } | { accessor: string };
|
||||
const dynFields: DynField[] = [
|
||||
...order.flatMap((n) => {
|
||||
if (accessors.has(n)) return [{ accessor: n } as DynField];
|
||||
const f = byName.get(n);
|
||||
return f === undefined ? [] : [f as DynField];
|
||||
}),
|
||||
...shape.fields.filter(
|
||||
(f) =>
|
||||
!inOrder.has(f.name) && !(accessors.size > 0 && accessorSlotProp(f.name) !== null),
|
||||
),
|
||||
];
|
||||
for (const f of dynFields) {
|
||||
for (const entry of dynFields) {
|
||||
if ("accessor" in entry) {
|
||||
host.declare(
|
||||
`declare void @scr_dyn_obj_set_accessor(ptr, ptr, ${host.sizeType}, ptr, ptr)`,
|
||||
);
|
||||
const boxed = (kind: "get" | "set"): string => {
|
||||
const slot = byName.get(`%${kind}:${entry.accessor}`);
|
||||
if (slot === undefined) return "null";
|
||||
const fv = loadFieldOf(slot.name, slot.type);
|
||||
const conv = B.tmp();
|
||||
B.line(
|
||||
`${conv} = call ptr @${this.toDynHelper(slot.type)}(${this.valTy(slot.type)} ${fv})`,
|
||||
);
|
||||
return conv;
|
||||
};
|
||||
const getter = boxed("get");
|
||||
const setter = boxed("set");
|
||||
B.line(
|
||||
`call void @scr_dyn_obj_set_accessor(ptr ${d}, ptr ${host.cstr(entry.accessor)}, ${host.sizeType} ${Buffer.byteLength(entry.accessor, "utf8")}, ptr ${getter}, ptr ${setter}) ; ${llvmCommentText(entry.accessor)}`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const f = entry;
|
||||
const klen = Buffer.byteLength(f.name, "utf8");
|
||||
const fv = loadFieldOf(f.name, f.type);
|
||||
// An ABSENT optional field contributes no key.
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
isDirentShape,
|
||||
isDynTypedRefType,
|
||||
isRefCounted,
|
||||
shapeHasAccessorSlots,
|
||||
typeKey,
|
||||
} from "../../ir/ir.js";
|
||||
import { mangleFunction, mangleGlobal, mangleRecordStruct } from "../mangle.js";
|
||||
@@ -965,6 +966,7 @@ export function streamTypedRefMaterializeAdapter(
|
||||
* Declared-field records and tuples cover the live stream values. */
|
||||
const ordinary =
|
||||
shape.indexValue ||
|
||||
shapeHasAccessorSlots(shape) ||
|
||||
shape.fields.some((field) => field.name === "handleEvent" && field.type.kind === "func");
|
||||
if (ordinary) {
|
||||
const out = B.tmp();
|
||||
|
||||
@@ -199,7 +199,7 @@ test("early executable cache misses on source and resolution changes", async ()
|
||||
expect(await readEarlyExecutableCache(f.root, f.options)).toBeNull();
|
||||
});
|
||||
|
||||
test("early executable keys isolate compile modes, paths, implementation, and FFI manifests", async () => {
|
||||
test("early executable keys isolate compile modes, paths, implementation, checker, and FFI manifests", async () => {
|
||||
const f = await fixture();
|
||||
const tracker = new FrontendInputTracker();
|
||||
tracker.run(() => trackedReadFile(f.source));
|
||||
@@ -216,6 +216,7 @@ test("early executable keys isolate compile modes, paths, implementation, and FF
|
||||
{ ...f.options, optimization: "dev" },
|
||||
{ ...f.options, optimization: "speed" },
|
||||
{ ...f.options, detachedExit: true },
|
||||
{ ...f.options, checker: "tsc-ts-executable-identity" },
|
||||
{ ...f.options, npmStatic: "auto" },
|
||||
{ ...f.options, npmStatic: ["commander"] },
|
||||
{ ...f.options, outPath: join(f.options.outDir, "other") },
|
||||
|
||||
@@ -116,6 +116,9 @@ export interface EarlyExecutableCacheOptions {
|
||||
windowsSubsystem?: "gui";
|
||||
/** Omitted unless --detached-exit is set. */
|
||||
detachedExit?: true;
|
||||
/** Omitted for the default tsgo checker; with SCRIPTC_CHECKER=tsc-ts, the
|
||||
* tsc-ts executable's file identity. */
|
||||
checker?: string;
|
||||
/** Omitted unless SCRIPTC_YOUNG_NURSERY=1 (backend/young-nursery.ts). */
|
||||
youngNursery?: true;
|
||||
npmStatic: readonly string[] | "auto" | null;
|
||||
@@ -230,6 +233,7 @@ function cacheKey(options: EarlyExecutableCacheOptions): string {
|
||||
...(options.strip ? ["strip"] : []),
|
||||
...(options.windowsSubsystem === "gui" ? ["windows-subsystem-gui"] : []),
|
||||
...(options.detachedExit ? ["detached-exit"] : []),
|
||||
...(options.checker !== undefined ? [`checker:${options.checker}`] : []),
|
||||
...(options.youngNursery ? ["young-nursery"] : []),
|
||||
options.npmStatic === null
|
||||
? "<npm-static-off>"
|
||||
@@ -270,6 +274,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");
|
||||
if (options.checker !== undefined) hash.update(`checker:${options.checker}\0`);
|
||||
if (options.youngNursery) hash.update("young-nursery\0");
|
||||
hash
|
||||
.update(
|
||||
|
||||
@@ -18,6 +18,7 @@ import type { Lowerer } from "./lowerer.js";
|
||||
import type { ParamShape } from "./call-signatures.js";
|
||||
import { classPrototypeData } from "./class-prototypes.js";
|
||||
import { classInstanceOf } from "./class-dynamic-dispatch.js";
|
||||
import { inheritedBuiltinCtorFence } from "./lower-classes.js";
|
||||
|
||||
const PREFIX = "%class.construct:";
|
||||
const PACKED = `${PREFIX}packed`;
|
||||
@@ -380,6 +381,29 @@ export class ClassConstructionDispatch {
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
const type: IrType = { kind: "classval", className: name };
|
||||
const callee = varRef("p.0", DYN, loc);
|
||||
// A constructor inherited from a runtime stream or EventEmitter
|
||||
// takes no arguments here: arguments report at run time, as they do
|
||||
// at compile time for typed construction.
|
||||
const fence = inheritedBuiltinCtorFence(lowerer, info, loc);
|
||||
if (fence !== null && fn.name !== PACKED && fn.params.length > 1) {
|
||||
fn.body.unshift({
|
||||
kind: "if",
|
||||
cond: {
|
||||
kind: "libCall",
|
||||
fn: "dyn.classIs",
|
||||
args: [callee, { kind: "strLit", value: typeKey(type), type: STRING, loc }],
|
||||
type: BOOL,
|
||||
loc,
|
||||
},
|
||||
then: [fence],
|
||||
else_: null,
|
||||
loc,
|
||||
});
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
const args = constructorArguments(
|
||||
lowerer,
|
||||
info.ctorParams,
|
||||
@@ -388,8 +412,6 @@ export class ClassConstructionDispatch {
|
||||
fn.name === PACKED ? varRef("p.1", DYN, loc) : undefined,
|
||||
);
|
||||
if (!args) continue;
|
||||
const type: IrType = { kind: "classval", className: name };
|
||||
const callee = varRef("p.0", DYN, loc);
|
||||
const value = constructedValue(lowerer, info, {
|
||||
kind: "newValue",
|
||||
callee: { kind: "dynCheck", value: callee, type, loc },
|
||||
@@ -400,6 +422,28 @@ export class ClassConstructionDispatch {
|
||||
const body: IrStmt[] = [
|
||||
{ kind: "return", value: lowerer.coerceToExpected(value, DYN), loc },
|
||||
];
|
||||
// A spread call's argument count is known only at run time.
|
||||
if (fence !== null && fn.name === PACKED)
|
||||
body.unshift({
|
||||
kind: "if",
|
||||
cond: {
|
||||
kind: "bin",
|
||||
op: ">",
|
||||
left: {
|
||||
kind: "libCall",
|
||||
fn: "dyn.arrLen",
|
||||
args: [varRef("p.1", DYN, loc)],
|
||||
type: F64,
|
||||
loc,
|
||||
},
|
||||
right: { kind: "numLit", value: 0, type: F64, loc },
|
||||
type: BOOL,
|
||||
loc,
|
||||
},
|
||||
then: [fence],
|
||||
else_: null,
|
||||
loc,
|
||||
});
|
||||
fn.body.unshift({
|
||||
kind: "if",
|
||||
cond: {
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { IrExpr, IrType } from "../../ir/ir.js";
|
||||
import type { Lowerer } from "./lowerer.js";
|
||||
import { accessorCall } from "./lower-classes.js";
|
||||
|
||||
/** The generator a class instance's `[Symbol.iterator]` returns, when that
|
||||
* method is a generator method taking no arguments: `obj[Symbol.iterator]()`,
|
||||
* called once, as for-of, spread and Array.from call it. Null for other
|
||||
* values, and for classes whose iterator the program can replace at run
|
||||
* time (an instance property, a prototype write). */
|
||||
export function classGeneratorIterable(lowerer: Lowerer, value: IrExpr): IrExpr | null {
|
||||
if (value.type.kind !== "object" || !iteratesThroughGenerator(lowerer, value.type)) return null;
|
||||
const className = value.type.className;
|
||||
const ret = lowerer.findMethodOn(lowerer.classes.get(className)!, "sym:iterator")!.sig.ret;
|
||||
return accessorCall(lowerer, className, "sym:iterator", value, [], ret, value.loc);
|
||||
}
|
||||
|
||||
/** Whether values of `type` iterate through a generator method (the check
|
||||
* classGeneratorIterable makes, from the type alone). */
|
||||
export function iteratesThroughGenerator(lowerer: Lowerer, type: IrType): boolean {
|
||||
if (type.kind !== "object") return false;
|
||||
const info = lowerer.classes.get(type.className);
|
||||
if (!info || info.def.runtime || info.fields.has("sym:iterator")) return false;
|
||||
if (
|
||||
lowerer.prototypeMethodAccesses.has("sym:iterator") ||
|
||||
lowerer.replacedSymbolMethods.has("sym:iterator")
|
||||
)
|
||||
return false;
|
||||
const found = lowerer.findMethodOn(info, "sym:iterator");
|
||||
return (
|
||||
!!found &&
|
||||
found.sig.params.length === 0 &&
|
||||
found.sig.ret.kind === "generator" &&
|
||||
!found.sig.ret.async
|
||||
);
|
||||
}
|
||||
@@ -43,9 +43,19 @@ export function collectClassMethodMutations(
|
||||
const jsAssignments: (ts.PropertyAccessExpression | ts.ElementAccessExpression)[] = [];
|
||||
const computedMethods: ts.Expression[] = [];
|
||||
const typedClasses: (ts.ClassDeclaration | ts.ClassExpression)[] = [];
|
||||
const symbolMethods = new Set<string>();
|
||||
let unknownKey: ts.Node | undefined;
|
||||
let numericKey: ts.Node | undefined;
|
||||
let unknownOwnField = false;
|
||||
// `sym:iterator` for `Symbol.iterator`: the name a class method declared
|
||||
// with a well-known symbol key takes.
|
||||
const wellKnownMethodName = (key: ts.Expression): string | null => {
|
||||
while (ts.isParenthesizedExpression(key)) key = key.expression;
|
||||
if (!ts.isPropertyAccessExpression(key)) return null;
|
||||
const member = lowerer.stdlibGlobalMember(key, "Symbol");
|
||||
if (member === null || !(lowerer.typeOf(key).flags & ts.TypeFlags.ESSymbolLike)) return null;
|
||||
return `sym:${member}`;
|
||||
};
|
||||
// JavaScript method inference and dynamic class factories keep their
|
||||
// existing dispatch contract. The native-call proof applies to typed
|
||||
// declarations (including JavaScript files TypeScript checks), while
|
||||
@@ -555,6 +565,19 @@ export function collectClassMethodMutations(
|
||||
lowerer.prototypeMethodAccesses.set(name, site);
|
||||
}
|
||||
for (const { key, receiver, site } of computedWrites) {
|
||||
// A class method declared with a well-known symbol key is not a write;
|
||||
// any other write with one can replace that method.
|
||||
const symbolName = key ? wellKnownMethodName(unwrap(key)) : null;
|
||||
if (symbolName) {
|
||||
const declaration =
|
||||
(ts.isMethodDeclaration(site) ||
|
||||
ts.isGetAccessorDeclaration(site) ||
|
||||
ts.isSetAccessorDeclaration(site)) &&
|
||||
(ts.isClassDeclaration(site.parent) || ts.isClassExpression(site.parent));
|
||||
if (declaration) symbolMethods.add(symbolName);
|
||||
else lowerer.replacedSymbolMethods.add(symbolName);
|
||||
continue;
|
||||
}
|
||||
const type = key ? lowerer.typeOf(key) : undefined;
|
||||
const names = type && (literalValues(type) ?? (key ? literalLoopKeys(unwrap(key)) : null));
|
||||
if (names) {
|
||||
@@ -585,8 +608,10 @@ export function collectClassMethodMutations(
|
||||
if (String(Number(name)) === name) markName(name, numericKey);
|
||||
}
|
||||
}
|
||||
if (unknownKey)
|
||||
if (unknownKey) {
|
||||
for (const method of methods) lowerer.prototypeMethodAccesses.set(method, unknownKey);
|
||||
for (const method of symbolMethods) lowerer.replacedSymbolMethods.add(method);
|
||||
}
|
||||
if (!unknownKey && !unknownOwnField)
|
||||
for (const field of arrowFields) {
|
||||
if (!receiverFields.has(field)) lowerer.receiverFreeCallbackFields.add(field);
|
||||
|
||||
@@ -44,6 +44,7 @@ import {
|
||||
lowerArrayCallback,
|
||||
callbackArrayElement,
|
||||
} from "./callback-arguments.js";
|
||||
import { classGeneratorIterable } from "../class-iterables.js";
|
||||
|
||||
/** Build the argument array for a mutating/copying operation while keeping
|
||||
* the receiver's scalar payload ABI. A missing read is represented as the
|
||||
@@ -913,7 +914,7 @@ export function lowerArrayFromCall(
|
||||
// and materializes holes while keeping element reference identity.
|
||||
if ((args.length === 1 || args.length === 2) && !ts.isObjectLiteralExpression(args[0]!)) {
|
||||
const source = lowerer.lowerExpr(args[0]!);
|
||||
const src =
|
||||
let src =
|
||||
source.type.kind === "string" && args.length === 2
|
||||
? strCharsCall(lowerer, source, loc)
|
||||
: source;
|
||||
@@ -1008,6 +1009,9 @@ export function lowerArrayFromCall(
|
||||
if (src.type.kind === "searchParams" && args.length === 1) {
|
||||
return lowerCheckedArrayFrom(lowerer, lowerer.coerceInto(args[0]!, src, DYN), loc);
|
||||
}
|
||||
// A class whose [Symbol.iterator] is a generator method iterates the
|
||||
// generator that method returns.
|
||||
src = classGeneratorIterable(lowerer, src) ?? src;
|
||||
// A generator (or an iterator adapted into one) drains in order.
|
||||
if (src.type.kind === "generator" && args.length === 1) {
|
||||
const arrT = lowerer.mapTypeOf(lowerer.typeOf(call));
|
||||
|
||||
@@ -42,6 +42,8 @@ import {
|
||||
import { strCharsCall } from "./array-construction.js";
|
||||
import { arrayElementRead } from "./array-iteration.js";
|
||||
import { isSearchParamsIterable } from "../builtins/url.js";
|
||||
import { classGeneratorIterable } from "../class-iterables.js";
|
||||
import { generatorDrain } from "../iterator-adapters.js";
|
||||
|
||||
/** Ambient Map method calls. `get`/`set`/`has`/`delete`/`clear` lower to
|
||||
* mapIntrinsic; `forEach` desugars to a direct call of a synthetic loop
|
||||
@@ -1048,6 +1050,14 @@ function setFromSeedValue(
|
||||
}
|
||||
: null;
|
||||
}
|
||||
// A generator, or a class whose [Symbol.iterator] is a generator method:
|
||||
// the Set takes every value it yields, in order.
|
||||
const generator =
|
||||
classGeneratorIterable(lowerer, source) ?? (source.type.kind === "generator" ? source : null);
|
||||
if (generator) {
|
||||
const drained = generatorDrain(lowerer, generator, setT.elem, loc);
|
||||
return drained ? { kind: "setNew", seed: drained, type: setT, loc } : null;
|
||||
}
|
||||
let seed: IrExpr;
|
||||
if (source.type.kind === "set" && typeEquals(source.type, setT)) {
|
||||
return { kind: "setIntrinsic", method: "clone", receiver: source, args: [], type: setT, loc };
|
||||
@@ -1246,6 +1256,24 @@ export function mapFromSeedValue(
|
||||
}
|
||||
: null;
|
||||
}
|
||||
// A generator of entries, or a class whose [Symbol.iterator] is one: the
|
||||
// Map takes every [key, value] pair it yields, in order.
|
||||
const generator =
|
||||
classGeneratorIterable(lowerer, seed) ?? (seed.type.kind === "generator" ? seed : null);
|
||||
if (generator) {
|
||||
const entry: IrType = {
|
||||
kind: "record",
|
||||
shapeId: lowerer.shapes.intern(
|
||||
[
|
||||
{ name: "0", type: mapT.key },
|
||||
{ name: "1", type: mapT.value },
|
||||
],
|
||||
true,
|
||||
),
|
||||
};
|
||||
const drained = generatorDrain(lowerer, generator, entry, loc);
|
||||
return drained ? mapFromSeedValue(lowerer, drained, mapT) : null;
|
||||
}
|
||||
if (seed.type.kind === "map") {
|
||||
if (!typeEquals(seed.type, mapT)) return null;
|
||||
return { kind: "mapIntrinsic", method: "clone", receiver: seed, args: [], type: mapT, loc };
|
||||
|
||||
@@ -28,6 +28,8 @@ import { tryLowerExpression } from "../expressions/try-lower-expression.js";
|
||||
import { locOf } from "../../program.js";
|
||||
import { typeKey } from "../../type-mapper.js";
|
||||
import { type WidthLift } from "../lowerer.js";
|
||||
import { classGeneratorIterable, iteratesThroughGenerator } from "../class-iterables.js";
|
||||
import { generatorDrain } from "../iterator-adapters.js";
|
||||
|
||||
/** Object() and new Object() preserve known object inputs. Primitive
|
||||
* boxing and unproven checked-dynamic values retain their refusal. */
|
||||
@@ -472,9 +474,37 @@ function lowerTypedObjectFromEntriesCall(
|
||||
if (call.arguments.nodes.length !== 1 || ts.isSpreadElement(call.arguments.nodes[0]!))
|
||||
return null;
|
||||
const argNode = call.arguments.nodes[0]!;
|
||||
const argIr = lowerer.mapTypeOf(lowerer.typeOf(argNode));
|
||||
let argIr = lowerer.mapTypeOf(lowerer.typeOf(argNode));
|
||||
// A generator of entries, or a class whose [Symbol.iterator] is one,
|
||||
// drains into the entry array the object is built from.
|
||||
let drained: IrExpr | null = null;
|
||||
if (argIr?.kind === "generator" || (argIr && iteratesThroughGenerator(lowerer, argIr))) {
|
||||
const value = lowerer.lowerExpr(argNode);
|
||||
const generator =
|
||||
classGeneratorIterable(lowerer, value) ?? (value.type.kind === "generator" ? value : null);
|
||||
if (generator?.type.kind !== "generator") return null;
|
||||
// The entries take the result's value type: `[string, V]` for an
|
||||
// object `{ [k: string]: V }`.
|
||||
const result = lowerer.mapTypeOf(lowerer.typeOf(call));
|
||||
const valueT =
|
||||
result?.kind === "record" ? lowerer.shapes.get(result.shapeId)?.indexValue : undefined;
|
||||
if (!valueT) return null;
|
||||
const entry: IrType = {
|
||||
kind: "record",
|
||||
shapeId: lowerer.shapes.intern(
|
||||
[
|
||||
{ name: "0", type: STRING },
|
||||
{ name: "1", type: valueT },
|
||||
],
|
||||
true,
|
||||
),
|
||||
};
|
||||
drained = generatorDrain(lowerer, generator, entry, locOf(call));
|
||||
if (!drained) return null;
|
||||
argIr = drained.type;
|
||||
}
|
||||
if (argIr?.kind !== "array") return null;
|
||||
const represented = tryLowerExpression(lowerer, argNode);
|
||||
const represented = drained ?? tryLowerExpression(lowerer, argNode);
|
||||
if (represented && !typeEquals(represented.type, argIr)) return null;
|
||||
// `Object.fromEntries(rows)` over a `string[][]` VALUE — the env-line
|
||||
// idiom (`envArray.map((env) => env.split('='))`). The checker has no
|
||||
@@ -522,7 +552,7 @@ function lowerTypedObjectFromEntriesCall(
|
||||
// Enumeration/filtering may keep the array in checked-dynamic storage.
|
||||
// Validate its tuple layout before calling a helper with a native-array
|
||||
// ABI; opaque tuple values themselves retain their original references.
|
||||
const receiver = lowerer.lowerExprExpecting(argNode, argIr);
|
||||
const receiver = drained ?? lowerer.lowerExprExpecting(argNode, argIr);
|
||||
const key = `obj.fromEntries:${argIr.elem.shapeId}:${resultT.shapeId}`;
|
||||
let helper = lowerer.arrHofHelpers.get(key);
|
||||
if (!helper) {
|
||||
|
||||
@@ -34,6 +34,7 @@ import {
|
||||
genValue,
|
||||
stepDrivable,
|
||||
} from "../lower-generators.js";
|
||||
import { classGeneratorIterable, iteratesThroughGenerator } from "../class-iterables.js";
|
||||
import { exitBeforeReturns } from "./for-of.js";
|
||||
import {
|
||||
iteratorSlotAdapter,
|
||||
@@ -317,9 +318,11 @@ function isHelperObject(lowerer: Lowerer, expr: ts.Expression): boolean {
|
||||
* it rather than a wrapper. A generator (including a helper object or an
|
||||
* array iterator) is itself; an array, string or typed array gives its
|
||||
* values iterator; a Set its values and a Map its entries, as a generator
|
||||
* over the live collection. The result converts into the call's
|
||||
* IteratorObject type. Null for other arguments (objects with their own
|
||||
* next method, untyped values), which keep the Iterator fence. */
|
||||
* over the live collection; a class instance whose `[Symbol.iterator]` is
|
||||
* a generator method gives the generator it returns. The result converts
|
||||
* into the call's IteratorObject type. Null for other arguments (objects
|
||||
* with their own next method, untyped values), which keep the Iterator
|
||||
* fence. */
|
||||
export function lowerIteratorFromCall(
|
||||
lowerer: Lowerer,
|
||||
call: ts.CallExpression,
|
||||
@@ -332,7 +335,9 @@ export function lowerIteratorFromCall(
|
||||
const argT = lowerer.mapTypeOf(lowerer.typeOf(argNode));
|
||||
if (resultT?.kind !== "generator" || resultT.async || argT === null) return null;
|
||||
const iterableKinds = ["generator", "array", "string", "bytes", "set", "map"];
|
||||
if (!iterableKinds.includes(argT.kind) || (argT.kind === "generator" && argT.async)) return null;
|
||||
const classIterable = iteratesThroughGenerator(lowerer, argT);
|
||||
if (!classIterable && !iterableKinds.includes(argT.kind)) return null;
|
||||
if (argT.kind === "generator" && argT.async) return null;
|
||||
const loc = locOf(call);
|
||||
const value = lowerer.lowerExpr(argNode);
|
||||
const own = (yieldT: IrType): GenType => ({
|
||||
@@ -344,6 +349,7 @@ export function lowerIteratorFromCall(
|
||||
let iterator: IrExpr | null = null;
|
||||
const t = value.type;
|
||||
if (t.kind === "generator") iterator = value;
|
||||
else if (classIterable) iterator = classGeneratorIterable(lowerer, value);
|
||||
else if (t.kind === "array")
|
||||
iterator = lowerArrayIteratorValue(lowerer, value, "values", own(t.elem), loc);
|
||||
else if (t.kind === "string")
|
||||
|
||||
@@ -30,6 +30,7 @@ import { generatorDrain } from "../iterator-adapters.js";
|
||||
import { isSearchParamsIterable } from "../builtins/url.js";
|
||||
import { varRef } from "../../../ir/build.js";
|
||||
import { arrayValueStore } from "../array-values.js";
|
||||
import { classGeneratorIterable } from "../class-iterables.js";
|
||||
|
||||
/** JavaScript: whether `expr` is or holds an existing checked-dynamic
|
||||
* object — a binding stored as a dyn value whose checker type is an
|
||||
@@ -431,6 +432,9 @@ export function lowerArrayLiteral(
|
||||
loc: locOf(el),
|
||||
};
|
||||
}
|
||||
// `[...obj]` over a class whose [Symbol.iterator] is a generator
|
||||
// method spreads the generator that method returns.
|
||||
src = classGeneratorIterable(lowerer, src) ?? src;
|
||||
// `[...it]` over a generator (or an iterator adapted into one):
|
||||
// drain it once, in order, into a fresh element array.
|
||||
if (src.type.kind === "generator") {
|
||||
|
||||
@@ -21,10 +21,17 @@ import {
|
||||
import { lowerNodeModuleIdentifier } from "../lower-node-module.js";
|
||||
import { lowerCjsExportsObjectValue } from "../cjs-exports-object.js";
|
||||
import { captureContextArguments } from "../function-context.js";
|
||||
import { isCjsExportTableLiteral, isJsSourceFile, isNodeEsmFile, locOf } from "../../program.js";
|
||||
import {
|
||||
isCjsExportTableLiteral,
|
||||
isCjsJsFile,
|
||||
isJsSourceFile,
|
||||
isNodeEsmFile,
|
||||
locOf,
|
||||
} from "../../program.js";
|
||||
import { builtinClassAliasOwnsNoSlot, runtimeClassValueOf } from "../builtins/class-values.js";
|
||||
import {
|
||||
cjsAccessorCall,
|
||||
cjsAccessorSnapshotOf,
|
||||
primitiveCtorClosure,
|
||||
runtimeOptionalElementKey,
|
||||
runtimeOptionalUseOf,
|
||||
@@ -930,5 +937,18 @@ function cjsExportAccessorRead(lowerer: Lowerer, ident: ts.Identifier): IrExpr |
|
||||
if (!ts.isObjectLiteralExpression(getter.parent) || !isCjsExportTableLiteral(getter.parent)) {
|
||||
return null;
|
||||
}
|
||||
// An ES-module import binding reads the value Node copied when the
|
||||
// importer linked the CommonJS module (cjsAccessorSnapshotStores).
|
||||
const raw = lowerer.checker.getSymbolAtLocation(ident);
|
||||
const binding = raw ? raw.declarations[0] : undefined;
|
||||
if (
|
||||
binding !== undefined &&
|
||||
(ts.isImportSpecifier(binding) || ts.isExportSpecifier(binding)) &&
|
||||
!isCjsJsFile(binding.getSourceFile(), lowerer.program)
|
||||
) {
|
||||
const snapshot = cjsAccessorSnapshotOf(lowerer, getter);
|
||||
if (snapshot !== null)
|
||||
return { kind: "varRef", localId: snapshot.id, type: snapshot.type, loc: locOf(ident) };
|
||||
}
|
||||
return cjsAccessorCall(lowerer, getter, locOf(ident));
|
||||
}
|
||||
|
||||
@@ -2213,11 +2213,7 @@ export function collectClassShapeInner(
|
||||
}
|
||||
if (lowerer.collectingExprClasses.has(decl)) {
|
||||
for (let parent = base; parent; parent = parent.base) {
|
||||
if (
|
||||
parent.builtinEmitter ||
|
||||
parent.builtinStream !== undefined ||
|
||||
parent.builtinEventTarget !== undefined
|
||||
) {
|
||||
if (parent.builtinEventTarget !== undefined) {
|
||||
lowerer.unsupported(
|
||||
"SC1090",
|
||||
decl,
|
||||
@@ -5183,16 +5179,11 @@ export function classValueRef(lowerer: Lowerer, info: ClassInfo, blame: ts.Node)
|
||||
loc: locOf(blame),
|
||||
};
|
||||
}
|
||||
if (
|
||||
lowerer.inheritsBuiltinEmitterCtor(info) ||
|
||||
inheritsBuiltinStreamCtor(lowerer, info) ||
|
||||
eventTargetRootOf(info) !== null ||
|
||||
(() => {
|
||||
for (let c = info.base; c; c = c.base)
|
||||
if (c.builtinEmitter || c.builtinStream !== undefined) return true;
|
||||
return false;
|
||||
})()
|
||||
) {
|
||||
// Classes extending EventEmitter or a stream class construct through
|
||||
// their own (or synthesized) `%C.constructor`, whose super call runs the
|
||||
// runtime initializer, so the class object's construct thunk serves them
|
||||
// like any program class. EventTarget subclasses keep the refusal.
|
||||
if (eventTargetRootOf(info) !== null) {
|
||||
lowerer.unsupported(
|
||||
"SC1090",
|
||||
blame,
|
||||
@@ -8737,6 +8728,60 @@ function inheritsBuiltinStreamCtor(lowerer: Lowerer, info: ClassInfo): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
/** The run-time form of refuseInheritedBuiltinCtorArgs, for construction
|
||||
* from checked-dynamic code (`new F(options)` with F an untyped value
|
||||
* holding C), whose argument count is known only to the caller: a
|
||||
* runtimeFence located at C, or null when C's constructor takes its
|
||||
* arguments. */
|
||||
export function inheritedBuiltinCtorFence(
|
||||
lowerer: Lowerer,
|
||||
info: ClassInfo,
|
||||
loc: SrcLoc,
|
||||
): IrStmt | null {
|
||||
let feature: string | null = null;
|
||||
if (inheritsBuiltinStreamCtor(lowerer, info))
|
||||
feature = `new ${info.def.name.replace(/^%/, "")} with arguments through an inherited stream constructor (declare a constructor that passes an inline options object to super(...))`;
|
||||
else if (lowerer.inheritsBuiltinEmitterCtor(info))
|
||||
feature = "EventEmitter constructor options ('captureRejections')";
|
||||
if (feature === null) return null;
|
||||
// Located at the class, whose constructor takes no arguments.
|
||||
const at = info.decl !== null ? locOf(info.decl) : loc;
|
||||
const diag = unsupportedDiag("SC1090", at, feature);
|
||||
lowerer.runtimeFences.push(diag);
|
||||
const line =
|
||||
info.decl !== null
|
||||
? ts.getLineAndCharacterOfPosition(info.decl.getSourceFile(), at.start).line + 1
|
||||
: null;
|
||||
const where = line !== null ? ` [${diag.code} at ${at.file}:${line}]` : "";
|
||||
return { kind: "runtimeFence", code: diag.code, message: `${diag.message}${where}`, loc };
|
||||
}
|
||||
|
||||
/** `new C(args)` where C's constructor is the inherited runtime stream or
|
||||
* EventEmitter constructor (a ctor-less chain into the base): that
|
||||
* constructor takes zero arguments here (the options bag fences, like the
|
||||
* super() form), so arguments report at the first one. Applies to direct
|
||||
* construction and to construction through a class value of C. Stream
|
||||
* subclasses come first: their chain roots at the emitter too, but the
|
||||
* message should name the stream story. */
|
||||
function refuseInheritedBuiltinCtorArgs(
|
||||
lowerer: Lowerer,
|
||||
info: ClassInfo,
|
||||
expr: ts.NewExpression,
|
||||
): void {
|
||||
const first = expr.arguments?.nodes[0];
|
||||
if (first === undefined) return;
|
||||
if (inheritsBuiltinStreamCtor(lowerer, info)) {
|
||||
lowerer.noLowering(
|
||||
`new ${info.def.name.replace(/^%/, "")} with arguments through an inherited stream constructor`,
|
||||
first,
|
||||
"declare a constructor that passes an inline options object to super(...)",
|
||||
);
|
||||
}
|
||||
if (lowerer.inheritsBuiltinEmitterCtor(info)) {
|
||||
lowerer.unsupported("SC1090", first, "EventEmitter constructor options ('captureRejections')");
|
||||
}
|
||||
}
|
||||
|
||||
/** Preserve argument evaluation order and option presence through builtin
|
||||
* and inherited Error constructors. Checked-dynamic conversion retains
|
||||
* Error identity and distinguishes a missing cause from undefined. */
|
||||
@@ -8861,24 +8906,7 @@ function lowerProgramClassNew(
|
||||
"construction through a function-local class's internal name",
|
||||
);
|
||||
lowerer.noteEdge(`%${info.def.name}.constructor`);
|
||||
// A ctor-less chain into an EventEmitter base inherits `new C()` —
|
||||
// zero arguments (the options bag fences, like the super() form).
|
||||
// Stream subclasses come first: their chain roots at the emitter
|
||||
// too, but the message should name the stream story.
|
||||
if (inheritsBuiltinStreamCtor(lowerer, info) && (expr.arguments?.nodes ?? []).length > 0) {
|
||||
lowerer.noLowering(
|
||||
`new ${info.def.name.replace(/^%/, "")} with arguments through an inherited stream constructor`,
|
||||
expr.arguments!.nodes[0]!,
|
||||
"declare a constructor that passes an inline options object to super(...)",
|
||||
);
|
||||
}
|
||||
if (lowerer.inheritsBuiltinEmitterCtor(info) && (expr.arguments?.nodes ?? []).length > 0) {
|
||||
lowerer.unsupported(
|
||||
"SC1090",
|
||||
expr.arguments!.nodes[0]!,
|
||||
"EventEmitter constructor options ('captureRejections')",
|
||||
);
|
||||
}
|
||||
refuseInheritedBuiltinCtorArgs(lowerer, info, expr);
|
||||
// A ctor-less chain into a builtin error base inherits both arguments;
|
||||
// each synthesized constructor forwards the same pair to its base.
|
||||
const args = lowerer.inheritsBuiltinErrorCtor(info)
|
||||
@@ -10126,6 +10154,9 @@ export function lowerNew(lowerer: Lowerer, expr: ts.NewExpression): IrExpr {
|
||||
`EventEmitter and stream class values constructed with options (construct with 'new ${info.def.name.slice(1)}({ ... })' directly)`,
|
||||
);
|
||||
}
|
||||
// A program class whose constructor is the inherited runtime one
|
||||
// takes no arguments through its class value either.
|
||||
refuseInheritedBuiltinCtorArgs(lowerer, info, expr);
|
||||
defineClassValueConstruct(lowerer, info);
|
||||
const args = lowerer.completeArgs(
|
||||
expr.arguments?.nodes ?? [],
|
||||
|
||||
@@ -38,7 +38,14 @@ import {
|
||||
typeEquals,
|
||||
typeKey,
|
||||
} from "../../ir/ir.js";
|
||||
import { isJsSourceFile, locOf } from "../program.js";
|
||||
import {
|
||||
cjsExportAssignmentOf,
|
||||
cjsExportDiscardReason,
|
||||
cjsExportTargetLiteral,
|
||||
isJsSourceFile,
|
||||
locOf,
|
||||
} from "../program.js";
|
||||
import { npmStaticLexerVisibleNames } from "../npm-static.js";
|
||||
import {
|
||||
type CompoundOp,
|
||||
NARROW_FIRST,
|
||||
@@ -2057,6 +2064,102 @@ function aliasTypeofArmOf(
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The names Node's ES-module loader copies off a CommonJS module that a
|
||||
* bundler rewrite spells as accessors (npmStaticLexerVisibleNames), with
|
||||
* their getters in that order; empty for every other module. */
|
||||
function lexerVisibleAccessors(dep: ts.SourceFile): ts.GetAccessorDeclaration[] {
|
||||
const names = npmStaticLexerVisibleNames(dep.fileName);
|
||||
if (names.length === 0) return [];
|
||||
let table: ts.ObjectLiteralExpression | null = null;
|
||||
for (const stmt of dep.statements.nodes) {
|
||||
const cjs = cjsExportAssignmentOf(stmt);
|
||||
if (cjs?.kind === "table" && cjsExportDiscardReason(stmt) === null) {
|
||||
table = cjsExportTargetLiteral(cjs.expr.right, dep);
|
||||
}
|
||||
}
|
||||
if (table === null) return [];
|
||||
const getters = new Map<string, ts.GetAccessorDeclaration>();
|
||||
for (const p of table.properties.nodes) {
|
||||
if (ts.isGetAccessorDeclaration(p) && (ts.isIdentifier(p.name) || ts.isStringLiteral(p.name)))
|
||||
getters.set(p.name.text, p);
|
||||
}
|
||||
return names.flatMap((n) => {
|
||||
const g = getters.get(n);
|
||||
return g === undefined ? [] : [g];
|
||||
});
|
||||
}
|
||||
|
||||
/** The module global holding the value an accessor export had when an
|
||||
* ES-module importer first linked its CommonJS module. */
|
||||
export function cjsAccessorSnapshotOf(
|
||||
lowerer: Lowerer,
|
||||
getter: ts.GetAccessorDeclaration,
|
||||
): { id: string; type: IrType } | null {
|
||||
const hit = lowerer.cjsAccessorSnapshots.get(getter);
|
||||
if (hit !== undefined) return hit;
|
||||
if (!lexerVisibleAccessors(getter.getSourceFile()).includes(getter)) return null;
|
||||
const call = cjsAccessorCall(lowerer, getter, locOf(getter));
|
||||
if (call === null) return null;
|
||||
const snapshot = { id: `%g.cjsSnapshot.${lowerer.cjsAccessorSnapshots.size}`, type: call.type };
|
||||
lowerer.globalsList.push({
|
||||
id: snapshot.id,
|
||||
name: "%cjsSnapshot",
|
||||
type: call.type,
|
||||
mutable: true,
|
||||
});
|
||||
lowerer.cjsAccessorSnapshots.set(getter, snapshot);
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
/** Node's ES-module loader reads every lexer-visible export of a CommonJS
|
||||
* module once, when an importer first links it, and the import bindings
|
||||
* keep those values. For the accessors a bundler rewrite introduced, the
|
||||
* importer's link point runs each getter once, in the lexer's order, and
|
||||
* stores the values its bindings read. Empty when the module has none. */
|
||||
export function cjsAccessorSnapshotStores(
|
||||
lowerer: Lowerer,
|
||||
dep: ts.SourceFile,
|
||||
loc: SrcLoc,
|
||||
): IrStmt[] {
|
||||
const getters = lexerVisibleAccessors(dep);
|
||||
if (getters.length === 0) return [];
|
||||
let readyId = lowerer.cjsSnapshotReady.get(dep);
|
||||
if (readyId === undefined) {
|
||||
readyId = `%g.cjsSnapshotReady.${lowerer.cjsSnapshotReady.size}`;
|
||||
lowerer.globalsList.push({ id: readyId, name: "%cjsSnapshotReady", type: BOOL, mutable: true });
|
||||
lowerer.cjsSnapshotReady.set(dep, readyId);
|
||||
}
|
||||
const stores: IrStmt[] = [
|
||||
{
|
||||
kind: "assign",
|
||||
localId: readyId,
|
||||
value: { kind: "boolLit", value: true, type: BOOL, loc },
|
||||
loc,
|
||||
},
|
||||
];
|
||||
for (const getter of getters) {
|
||||
const snapshot = cjsAccessorSnapshotOf(lowerer, getter);
|
||||
const call = cjsAccessorCall(lowerer, getter, loc);
|
||||
if (snapshot === null || call === null) return [];
|
||||
stores.push({ kind: "assign", localId: snapshot.id, value: call, loc });
|
||||
}
|
||||
return [
|
||||
{
|
||||
kind: "if",
|
||||
cond: {
|
||||
kind: "unary",
|
||||
op: "!",
|
||||
operand: { kind: "varRef", localId: readyId, type: BOOL, loc },
|
||||
type: BOOL,
|
||||
loc,
|
||||
},
|
||||
then: stores,
|
||||
else_: null,
|
||||
loc,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
/** The interned lifted-getter call both accessor-read paths share. */
|
||||
export function cjsAccessorCall(
|
||||
lowerer: Lowerer,
|
||||
|
||||
@@ -145,7 +145,7 @@ import { forkTargetPaths } from "../fork-target.js";
|
||||
import { workerTargetPaths } from "../worker-target.js";
|
||||
import { isNativeProxyInitializer } from "./expressions/native-proxy.js";
|
||||
import { handleEventReaderPrelude } from "./lower-event-target.js";
|
||||
import { jsHoldsDynObject } from "./lower-exprs.js";
|
||||
import { cjsAccessorSnapshotStores, jsHoldsDynObject } from "./lower-exprs.js";
|
||||
import { keptIdentityAssertion } from "./assertion-identity.js";
|
||||
|
||||
/** One file's declarations, split for collection and init-body lowering. */
|
||||
@@ -2851,6 +2851,14 @@ export function lowerFileInit(
|
||||
});
|
||||
} else {
|
||||
header.push({ kind: "exprStmt", expr: call, loc });
|
||||
// An ES-module importer links a CommonJS dependency: Node
|
||||
// copies its lexer-visible exports here.
|
||||
if (
|
||||
(ts.isImportDeclaration(stmt) || ts.isExportDeclaration(stmt)) &&
|
||||
!isCjsJsFile(sf, lowerer.program) &&
|
||||
isCjsJsFile(dep, lowerer.program)
|
||||
)
|
||||
header.push(...cjsAccessorSnapshotStores(lowerer, dep, loc));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,6 +42,8 @@ import {
|
||||
STATIC_RESPONSE_CALLS,
|
||||
STATIC_RESPONSE_READS,
|
||||
} from "../../compat/fetch-profile.js";
|
||||
import { classGeneratorIterable } from "./class-iterables.js";
|
||||
import { generatorDrain } from "./iterator-adapters.js";
|
||||
|
||||
export function refuseUnsupportedApi(
|
||||
lowerer: Lowerer,
|
||||
@@ -2436,6 +2438,10 @@ export function lowerStdlibMethodCall(
|
||||
src = lowerer.coerceInto(spread.expression, src, inferred);
|
||||
}
|
||||
}
|
||||
// A generator, or a class whose [Symbol.iterator] is a generator
|
||||
// method, drains into the number[] the fold reads.
|
||||
src = classGeneratorIterable(lowerer, src) ?? src;
|
||||
if (src.type.kind === "generator") src = generatorDrain(lowerer, src, F64, loc) ?? src;
|
||||
if (src.type.kind !== "array" || src.type.elem.kind !== "f64") {
|
||||
lowerer.unsupported(
|
||||
"SC1090",
|
||||
|
||||
@@ -33,6 +33,7 @@ import {
|
||||
import {
|
||||
cjsExportMemberWriteGlobalOf,
|
||||
isCjsExportsIdentifier,
|
||||
isCjsModuleExports,
|
||||
isFreshExportsReset,
|
||||
} from "./cjs-exports-object.js";
|
||||
import { isDeadTscHelperDecl, tscInteropBindingOfDecl } from "./cjs-tsc-interop.js";
|
||||
@@ -224,6 +225,7 @@ import { constituentTypes } from "../ts7/checker.js";
|
||||
import { npmStaticPackageOfPath } from "../npm-static.js";
|
||||
import { fenceNodeModuleMutation } from "./lower-node-module.js";
|
||||
import { fencePerfEntryKeyWalk } from "./builtins/performance.js";
|
||||
import { classGeneratorIterable } from "./class-iterables.js";
|
||||
|
||||
interface UsingRegistration {
|
||||
acquire: IrStmt[];
|
||||
@@ -6911,6 +6913,25 @@ export function lowerExprStatement(lowerer: Lowerer, expr: ts.Expression): IrStm
|
||||
"require() outside the module's top level (move it to the top of the file)",
|
||||
);
|
||||
}
|
||||
// Replacing the export object (or rebinding `exports`) anywhere but a
|
||||
// top-level statement makes the module's exports depend on which path
|
||||
// ran (`cond ? module.exports = a : module.exports = b`, an
|
||||
// environment-dependent branch); the static export table has one shape.
|
||||
if (
|
||||
!topLevelJs &&
|
||||
isJsSourceFile(expr.getSourceFile()) &&
|
||||
ts.isBinaryExpression(expr) &&
|
||||
expr.operatorToken.kind === ts.SyntaxKind.EqualsToken &&
|
||||
(isCjsModuleExports(lowerer, expr.left) || isCjsExportsIdentifier(lowerer, expr.left))
|
||||
) {
|
||||
lowerer.unsupported(
|
||||
"SC1090",
|
||||
expr.left,
|
||||
isCjsModuleExports(lowerer, expr.left)
|
||||
? "replacing module.exports outside a top-level statement (a conditional or environment-dependent export object)"
|
||||
: "rebinding 'exports' outside a top-level statement (a conditional or environment-dependent export object)",
|
||||
);
|
||||
}
|
||||
if (topLevelJs && ts.isExpressionStatement(stmtNode)) {
|
||||
if (isFreshExportsReset(lowerer, stmtNode))
|
||||
return { kind: "block", body: [], loc: locOf(expr) };
|
||||
@@ -9175,6 +9196,16 @@ export function lowerForOf(lowerer: Lowerer, stmt: ts.ForOfStatement): IrStmt {
|
||||
);
|
||||
}
|
||||
if (iterable.type.kind === "object") {
|
||||
// A [Symbol.iterator] generator method: the loop drives the
|
||||
// generator it returns.
|
||||
const generator = classGeneratorIterable(lowerer, iterable);
|
||||
if (generator)
|
||||
return lowerForOfGenerator(
|
||||
lowerer,
|
||||
stmt,
|
||||
generator as IrExpr & { type: IrType & { kind: "generator" } },
|
||||
labels,
|
||||
);
|
||||
// Class iterables ([Symbol.iterator]() + next() — classIteratorOf)
|
||||
// drive the same protocol with ordinary method calls.
|
||||
const cit = lowerer.classIteratorOf(iterable.type);
|
||||
|
||||
@@ -3674,8 +3674,10 @@ export function lowerStreamMethodCall(
|
||||
: lowerer.lowerExprExpecting(args[0]!, STRING);
|
||||
const fn = kind === "bytes" ? "writable.write" : "writable.writeStr";
|
||||
if (cbArg !== undefined) {
|
||||
const cb = lowerer.lowerExprExpecting(cbArg, funcOf([], VOID));
|
||||
if (cb.type.kind !== "func" || cb.type.params.length > 0) {
|
||||
const cb = callbackDeclaresParameters(cbArg)
|
||||
? null
|
||||
: lowerer.lowerExprExpecting(cbArg, funcOf([], VOID));
|
||||
if (cb === null || cb.type.kind !== "func" || cb.type.params.length > 0) {
|
||||
lowerer.noLowering(
|
||||
"write completion callbacks taking the error argument",
|
||||
cbArg,
|
||||
@@ -3732,8 +3734,10 @@ export function lowerStreamMethodCall(
|
||||
);
|
||||
}
|
||||
if (cbArg !== undefined) {
|
||||
const cb = lowerer.lowerExprExpecting(cbArg, funcOf([], VOID));
|
||||
if (cb.type.kind !== "func" || cb.type.params.length > 0) {
|
||||
const cb = callbackDeclaresParameters(cbArg)
|
||||
? null
|
||||
: lowerer.lowerExprExpecting(cbArg, funcOf([], VOID));
|
||||
if (cb === null || cb.type.kind !== "func" || cb.type.params.length > 0) {
|
||||
lowerer.noLowering(
|
||||
"end callbacks with parameters",
|
||||
cbArg,
|
||||
@@ -3998,3 +4002,17 @@ export function lowerStreamProperty(
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Whether an inline completion callback declares a parameter. Node calls
|
||||
* write and end callbacks with an error argument (null on success), but the
|
||||
* native callback receives none, so the parameter would read undefined
|
||||
* where Node passes null or the error. A function literal with parameters
|
||||
* would otherwise adapt to the zero-parameter slot silently. */
|
||||
function callbackDeclaresParameters(node: ts.Expression): boolean {
|
||||
let callback = node;
|
||||
while (ts.isParenthesizedExpression(callback)) callback = callback.expression;
|
||||
return (
|
||||
(ts.isArrowFunction(callback) || ts.isFunctionExpression(callback)) &&
|
||||
callback.parameters.nodes.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2574,6 +2574,10 @@ export class Lowerer {
|
||||
* lifted lazily as module-level functions and interned per accessor
|
||||
* declaration: member reads call the getter (lower-exprs). */
|
||||
readonly cjsAccessorFns = new Map<ts.Node, { fnName: string; type: IrType & { kind: "func" } }>();
|
||||
/** Accessor exports' link-time values for ES-module importers, and the
|
||||
* per-module flag that the copy already ran (cjsAccessorSnapshotStores). */
|
||||
readonly cjsAccessorSnapshots = new Map<ts.Node, { id: string; type: IrType }>();
|
||||
readonly cjsSnapshotReady = new Map<ts.SourceFile, string>();
|
||||
/** Interned `%iter.drain.<n>` helpers (classIteratorDrainCall): one per
|
||||
* receiver class — the eager drain of a class iterable's protocol into
|
||||
* a fresh element array, behind array/call spreads. */
|
||||
@@ -2653,6 +2657,10 @@ export class Lowerer {
|
||||
/** Named method slots observed before class collection need a callable
|
||||
* ABI and shared prototype descriptors instead of call-site specialization. */
|
||||
readonly prototypeMethodAccesses = new Map<string, ts.Node>();
|
||||
/** Well-known symbol methods (`sym:iterator`) the program may replace
|
||||
* through a symbol-keyed write: an instance or prototype property, or a
|
||||
* reflection call. */
|
||||
readonly replacedSymbolMethods = new Set<string>();
|
||||
/** Typed calls through class-backed protocols, by signature; class
|
||||
* dynamic dispatch adds their native arms (class-protocol-dispatch.ts). */
|
||||
readonly protocolDispatches = new Map<string, ProtocolDispatch>();
|
||||
@@ -8649,6 +8657,17 @@ export class Lowerer {
|
||||
* else (including a DIFFERENT union) is left for requireExactShape, which
|
||||
* rejects union mismatches with SC2003. */
|
||||
coerceToExpected(expr: IrExpr, expected: IrType): IrExpr {
|
||||
// A comma expression ending in a unit literal (`return log(), null`):
|
||||
// its effects run first, unchanged, and the unit value takes the
|
||||
// destination's representation (a bare unit literal has none).
|
||||
if (
|
||||
expr.kind === "seqExpr" &&
|
||||
expr.result.kind === "unitLit" &&
|
||||
!typeEquals(expr.type, expected)
|
||||
) {
|
||||
const result = this.coerceToExpected(expr.result, expected);
|
||||
return { ...expr, result, type: result.type };
|
||||
}
|
||||
// A destination that holds undefined takes an unassigned deferred-init
|
||||
// field's slot as is (Node passes the undefined along).
|
||||
if (expected.kind === "union" && this.armTag(expected.unionId, UNDEFINED_T) >= 0) {
|
||||
@@ -9364,6 +9383,7 @@ export class Lowerer {
|
||||
* lowering goes through here (via lowerExprExpecting) or calls this
|
||||
* directly when the expression was already lowered. */
|
||||
coerceInto(node: ts.Node, expr: IrExpr, expected: IrType): IrExpr {
|
||||
refuseInferredCallbackDrops(this, node, expr.type, expected);
|
||||
// A union destination can accept the binding's tagged storage directly.
|
||||
// The checker's single-arm flow type can be stale after a callback writes
|
||||
// the binding. Extracting that arm and wrapping it again would discard the
|
||||
@@ -10101,6 +10121,15 @@ export class Lowerer {
|
||||
e = this.returnedPromiseAwait(e);
|
||||
}
|
||||
if (e.kind === "unitLit") return { kind: "return", value: null, loc };
|
||||
// `return c ? f() : g()` over void calls: a void conditional has no
|
||||
// value representation, so its branch selection becomes control flow.
|
||||
if (e.kind === "ternary" && e.type.kind === "void") {
|
||||
const branch = (x: IrExpr): IrStmt =>
|
||||
x.kind === "ternary" && x.type.kind === "void"
|
||||
? { kind: "if", cond: x.cond, then: [branch(x.then)], else_: [branch(x.else_)], loc }
|
||||
: { kind: "exprStmt", expr: x, loc };
|
||||
return { kind: "block", body: [branch(e), { kind: "return", value: null, loc }], loc };
|
||||
}
|
||||
if (e.type.kind === "void") return { kind: "return", value: e, loc };
|
||||
return {
|
||||
kind: "block",
|
||||
@@ -13179,3 +13208,101 @@ function unionArmsWidthLift(
|
||||
loc,
|
||||
};
|
||||
}
|
||||
|
||||
/** A callback passed to a generic call without a return annotation, whose
|
||||
* returns the checker unified into a narrower result type: `trace(name,
|
||||
* async () => (cond ? items : items.map((i) => ({ ...i, sum }))))` infers
|
||||
* `T` from the narrower `Item[]`, though at run time the extended objects
|
||||
* keep `sum`. Converting such a return into the inferred type copies the
|
||||
* records and drops the members the narrower type lacks, which Node keeps
|
||||
* and any later wider view (`Promise<ItemWithSum[]>`) reads back. Refuse
|
||||
* that conversion by name rather than lose the members silently; an
|
||||
* annotation on the callback's return type or on the call's type argument
|
||||
* names a type that keeps them. */
|
||||
function refuseInferredCallbackDrops(
|
||||
lowerer: Lowerer,
|
||||
node: ts.Node,
|
||||
actual: IrType,
|
||||
expected: IrType,
|
||||
): void {
|
||||
if (typeEquals(actual, expected)) return;
|
||||
const structured = (t: IrType): boolean =>
|
||||
t.kind === "record" || t.kind === "array" || t.kind === "promise";
|
||||
if (!structured(actual) || !structured(expected)) return;
|
||||
let site: ts.Node = node;
|
||||
while (yieldsOperand(site)) site = site.parent!;
|
||||
let fn: ts.Node | undefined;
|
||||
if (ts.isReturnStatement(site.parent) && site.parent.expression === site) {
|
||||
fn = site.parent.parent;
|
||||
while (fn && !ts.isFunctionLike(fn)) fn = fn.parent;
|
||||
} else if (ts.isArrowFunction(site.parent) && site.parent.body === site) {
|
||||
fn = site.parent;
|
||||
}
|
||||
if (!fn || !(ts.isArrowFunction(fn) || ts.isFunctionExpression(fn)) || fn.type) return;
|
||||
let arg: ts.Node = fn;
|
||||
while (ts.isParenthesizedExpression(arg.parent)) arg = arg.parent;
|
||||
const call = arg.parent;
|
||||
if (!(ts.isCallExpression(call) || ts.isNewExpression(call))) return;
|
||||
if (!call.arguments?.nodes.includes(arg as ts.Expression)) return;
|
||||
const dropped = droppedMembers(lowerer, actual, expected, new Set());
|
||||
if (dropped.length === 0) return;
|
||||
lowerer.unsupported(
|
||||
"SC1090",
|
||||
node,
|
||||
`returning '${lowerer.fmt(actual)}' from a callback whose result the checker infers as the narrower '${lowerer.fmt(expected)}' (the conversion would drop ${dropped.map((d) => `'${d}'`).join(", ")}, which the object keeps at run time — annotate the callback's return type or the call's type argument with a type that declares them)`,
|
||||
);
|
||||
}
|
||||
|
||||
/** True when the value of `node`'s parent can be `node`'s own value:
|
||||
* parentheses, `await`, `satisfies`, a non-null assertion, a conditional's
|
||||
* branch, either operand of `??`, `||` and `&&`, and the right operand of a
|
||||
* comma. */
|
||||
function yieldsOperand(node: ts.Node): boolean {
|
||||
const p = node.parent;
|
||||
if (p === undefined) return false;
|
||||
if (
|
||||
ts.isParenthesizedExpression(p) ||
|
||||
ts.isAwaitExpression(p) ||
|
||||
ts.isSatisfiesExpression(p) ||
|
||||
ts.isNonNullExpression(p)
|
||||
)
|
||||
return true;
|
||||
if (ts.isConditionalExpression(p)) return p.whenTrue === node || p.whenFalse === node;
|
||||
if (ts.isBinaryExpression(p)) {
|
||||
const op = p.operatorToken.kind;
|
||||
if (
|
||||
op === ts.SyntaxKind.QuestionQuestionToken ||
|
||||
op === ts.SyntaxKind.BarBarToken ||
|
||||
op === ts.SyntaxKind.AmpersandAmpersandToken
|
||||
)
|
||||
return true;
|
||||
return op === ts.SyntaxKind.CommaToken && p.right === node;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Member names a structural conversion from `from` into `to` drops:
|
||||
* declared fields of a source record the target record lacks, through
|
||||
* array elements and promise payloads. */
|
||||
function droppedMembers(lowerer: Lowerer, from: IrType, to: IrType, seen: Set<string>): string[] {
|
||||
if (typeEquals(from, to)) return [];
|
||||
if (from.kind === "array" && to.kind === "array")
|
||||
return droppedMembers(lowerer, from.elem, to.elem, seen);
|
||||
if (from.kind === "promise" && to.kind === "promise")
|
||||
return droppedMembers(lowerer, from.inner, to.inner, seen);
|
||||
if (from.kind !== "record" || to.kind !== "record") return [];
|
||||
const key = `${from.shapeId}>${to.shapeId}`;
|
||||
if (seen.has(key)) return [];
|
||||
seen.add(key);
|
||||
const source = lowerer.shapes.get(from.shapeId);
|
||||
const target = lowerer.shapes.get(to.shapeId);
|
||||
if (!source || !target || source.tuple || target.tuple || target.indexValue) return [];
|
||||
const out: string[] = [];
|
||||
for (const f of source.fields) {
|
||||
if (f.name.startsWith("%")) continue;
|
||||
const t = target.fields.find((x) => x.name === f.name);
|
||||
if (!t) out.push(f.name);
|
||||
else out.push(...droppedMembers(lowerer, f.type, t.type, seen).map((n) => `${f.name}.${n}`));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -2,10 +2,11 @@ import * as ts from "../ts7/adapter.js";
|
||||
import { locOf } from "../program.js";
|
||||
import type { IrExpr } from "../../ir/ir.js";
|
||||
import type { Lowerer } from "./lowerer.js";
|
||||
import { accessorCall } from "./lower-classes.js";
|
||||
import { accessorCall, type ClassInfo } from "./lower-classes.js";
|
||||
import { classSymbolKeyOf } from "./symbol-fields.js";
|
||||
|
||||
/** A stable symbol method uses the same completed arguments and virtual
|
||||
/** A stable symbol method (a module-scope symbol, or a well-known symbol
|
||||
* such as `Symbol.iterator`) uses the same completed arguments and virtual
|
||||
* dispatch as a string-named class method. Runtime-selected keys stay on
|
||||
* the checked-property path. */
|
||||
export function lowerClassSymbolMethodCall(
|
||||
@@ -15,12 +16,13 @@ export function lowerClassSymbolMethodCall(
|
||||
const access = call.expression;
|
||||
if (!ts.isElementAccessExpression(access) || access.questionDotToken || call.questionDotToken)
|
||||
return null;
|
||||
const key = classSymbolKeyOf(lowerer, access.argumentExpression);
|
||||
if (!key) return null;
|
||||
const type = lowerer.mapTypeOf(lowerer.typeOf(access.expression));
|
||||
if (type?.kind !== "object") return null;
|
||||
const info = lowerer.classes.get(type.className);
|
||||
const name = info?.symbolMethods?.get(key.identity);
|
||||
const key = classSymbolKeyOf(lowerer, access.argumentExpression);
|
||||
const name = key
|
||||
? info?.symbolMethods?.get(key.identity)
|
||||
: wellKnownSymbolMethod(lowerer, info, access.argumentExpression);
|
||||
if (!name) return null;
|
||||
const method = lowerer.findMethodOn(info ?? null, name);
|
||||
if (!method) return null;
|
||||
@@ -29,3 +31,21 @@ export function lowerClassSymbolMethodCall(
|
||||
const args = lowerer.completeArgs(call.arguments.nodes, method.sig.params, loc, call);
|
||||
return accessorCall(lowerer, type.className, name, receiver, args, method.sig.ret, loc);
|
||||
}
|
||||
|
||||
/** The `sym:<name>` method a well-known symbol key such as `Symbol.iterator`
|
||||
* names, when the class declares it as a method and the program cannot
|
||||
* replace it at run time (an instance property of that name, a prototype
|
||||
* write). */
|
||||
function wellKnownSymbolMethod(
|
||||
lowerer: Lowerer,
|
||||
info: ClassInfo | undefined,
|
||||
key: ts.Expression,
|
||||
): string | null {
|
||||
while (ts.isParenthesizedExpression(key)) key = key.expression;
|
||||
if (!info || info.def.runtime || !ts.isPropertyAccessExpression(key)) return null;
|
||||
const member = lowerer.stdlibGlobalMember(key, "Symbol");
|
||||
if (member === null) return null;
|
||||
const name = `sym:${member}`;
|
||||
if (info.fields.has(name) || lowerer.replacedSymbolMethods.has(name)) return null;
|
||||
return name;
|
||||
}
|
||||
|
||||
@@ -298,3 +298,21 @@ export const g = import_g.g;
|
||||
degrade: expect.stringContaining("bundled CommonJS modules") as string,
|
||||
});
|
||||
});
|
||||
|
||||
test("a chunk that only re-exports a builtin module becomes that module", () => {
|
||||
const answer = expectSameBehavior(`${keyedHelper}var require_stream = __commonJS({
|
||||
"lib/stream.js"(exports2, module2) {
|
||||
module2.exports = require("stream");
|
||||
}
|
||||
});
|
||||
var require_user = __commonJS({
|
||||
"lib/user.js"(exports2) {
|
||||
var Stream = require_stream();
|
||||
exports2.same = Stream === require("stream");
|
||||
}
|
||||
});
|
||||
console.log(typeof require_stream().PassThrough, require_user().same);
|
||||
`);
|
||||
expect(answer.chunks.map((c) => basename(c.path))).toEqual(["index.js.require_user.cjs"]);
|
||||
expect(answer.text).toContain('typeof require("stream").PassThrough');
|
||||
});
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
* beside it). Anything else answers a degrade reason. */
|
||||
import * as ts from "./ts7/syntax.js";
|
||||
import { helperTokens } from "./helper-tokens.js";
|
||||
import { canonicalBuiltinModule } from "./builtin-modules.js";
|
||||
|
||||
export interface BundledChunkSplit {
|
||||
/** The bundle with chunk declarations blanked and calls respelled. */
|
||||
@@ -31,7 +32,7 @@ export interface BundledChunkSplit {
|
||||
chunks: { path: string; source: string }[];
|
||||
}
|
||||
|
||||
interface Edit {
|
||||
export interface Edit {
|
||||
start: number;
|
||||
end: number;
|
||||
text: string;
|
||||
@@ -42,11 +43,11 @@ const CHUNK_SHAPE_DEGRADE =
|
||||
"recognizer cannot verify";
|
||||
|
||||
/** The helper a counter-suffixed bundler name spells (`__commonJS2`). */
|
||||
function helperBase(name: string): string {
|
||||
export function helperBase(name: string): string {
|
||||
return /^__[A-Za-z]+\d+$/.test(name) ? name.replace(/\d+$/, "") : name;
|
||||
}
|
||||
|
||||
function unparen(e: ts.Expression): ts.Expression {
|
||||
export function unparen(e: ts.Expression): ts.Expression {
|
||||
while (ts.isParenthesizedExpression(e)) e = e.expression;
|
||||
return e;
|
||||
}
|
||||
@@ -54,7 +55,7 @@ function unparen(e: ts.Expression): ts.Expression {
|
||||
/** True for an identifier occurrence that reads or writes a binding (as
|
||||
* opposed to a property name, a label, or a declaration's own name).
|
||||
* Shorthand property values count: `{ x }` reads x. */
|
||||
function isReference(id: ts.Identifier): boolean {
|
||||
export function isReference(id: ts.Identifier): boolean {
|
||||
const p = id.parent;
|
||||
if (p === undefined) return false;
|
||||
if (ts.isPropertyAccessExpression(p)) return p.expression === id;
|
||||
@@ -83,7 +84,7 @@ function isReference(id: ts.Identifier): boolean {
|
||||
|
||||
/** Names a subtree declares anywhere inside it: variables (destructuring
|
||||
* included), parameters, function and class names, catch bindings. */
|
||||
function declaredNames(root: ts.Node): Set<string> {
|
||||
export function declaredNames(root: ts.Node): Set<string> {
|
||||
const names = new Set<string>();
|
||||
// Binding patterns nest BindingElements, which the walk visits too.
|
||||
ts.walkPreorder(root, (n) => {
|
||||
@@ -272,7 +273,7 @@ class BundleScopes {
|
||||
}
|
||||
|
||||
/** Every binding reference inside a subtree. */
|
||||
function references(root: ts.Node): ts.Identifier[] {
|
||||
export function references(root: ts.Node): ts.Identifier[] {
|
||||
const out: ts.Identifier[] = [];
|
||||
ts.walkPreorder(root, (n) => {
|
||||
if (n.kind >= ts.SyntaxKind.FirstJSDocNode && n.kind <= ts.SyntaxKind.LastJSDocNode)
|
||||
@@ -285,7 +286,7 @@ function references(root: ts.Node): ts.Identifier[] {
|
||||
|
||||
/** True when the reference is written (assignment target, update operand,
|
||||
* loop target, delete operand). */
|
||||
function isWritten(id: ts.Identifier): boolean {
|
||||
export function isWritten(id: ts.Identifier): boolean {
|
||||
let child: ts.Node = id;
|
||||
for (let p = child.parent; p !== undefined; child = p, p = p.parent) {
|
||||
if (ts.isBinaryExpression(p)) {
|
||||
@@ -471,7 +472,7 @@ interface TopLevel {
|
||||
}
|
||||
|
||||
/** True when the file opens with a "use strict" directive prologue. */
|
||||
function strictPrologue(stmts: readonly ts.Statement[]): boolean {
|
||||
export function strictPrologue(stmts: readonly ts.Statement[]): boolean {
|
||||
for (const s of stmts) {
|
||||
if (!ts.isExpressionStatement(s) || !ts.isStringLiteral(s.expression)) return false;
|
||||
if (s.expression.text === "use strict") return true;
|
||||
@@ -637,10 +638,11 @@ export function splitBundledChunks(
|
||||
return {
|
||||
degrade: `its bundled CommonJS module factory '${r.text}' is used other than as a direct call`,
|
||||
};
|
||||
const forwarded = forwarderSpec(chunk);
|
||||
callEdits.push({
|
||||
start: call.getStart(sf),
|
||||
end: call.getEnd(),
|
||||
text: `require(${JSON.stringify(chunk.spec)})`,
|
||||
text: `require(${JSON.stringify(forwarded ?? chunk.spec)})`,
|
||||
});
|
||||
}
|
||||
for (const name of chunks.keys()) {
|
||||
@@ -652,6 +654,11 @@ export function splitBundledChunks(
|
||||
const out: BundledChunkSplit["chunks"] = [];
|
||||
const bundleEdits: Edit[] = [...callEdits];
|
||||
for (const chunk of chunks.values()) {
|
||||
if (forwarderSpec(chunk) !== null) {
|
||||
// A chunk that only re-exports a builtin module is that module.
|
||||
bundleEdits.push({ start: chunk.stmt.getStart(sf), end: chunk.stmt.getEnd(), text: "" });
|
||||
continue;
|
||||
}
|
||||
const result = chunkSource(
|
||||
sf,
|
||||
chunk,
|
||||
@@ -670,7 +677,7 @@ export function splitBundledChunks(
|
||||
return { text: applyEdits(source, 0, source.length, bundleEdits), chunks: out };
|
||||
}
|
||||
|
||||
function countDeclarations(sf: ts.SourceFile, name: string): number {
|
||||
export function countDeclarations(sf: ts.SourceFile, name: string): number {
|
||||
let n = 0;
|
||||
ts.walkPreorder(sf, (node) => {
|
||||
if (
|
||||
@@ -694,7 +701,7 @@ function countDeclarations(sf: ts.SourceFile, name: string): number {
|
||||
/** Applies non-overlapping edits inside [from, to): replaced spans keep
|
||||
* their newlines (blanked text stays line-aligned); edits nested in a
|
||||
* blanked span vanish with it. */
|
||||
function applyEdits(source: string, from: number, to: number, edits: Edit[]): string {
|
||||
export function applyEdits(source: string, from: number, to: number, edits: Edit[]): string {
|
||||
const inside = edits
|
||||
.filter((e) => e.start >= from && e.end <= to)
|
||||
.sort((a, b) => a.start - b.start || b.end - a.end);
|
||||
@@ -712,6 +719,86 @@ function applyEdits(source: string, from: number, to: number, edits: Edit[]): st
|
||||
return text + source.slice(at, to);
|
||||
}
|
||||
|
||||
/** The builtin module a chunk forwards, or null: a body that is exactly
|
||||
* `module.exports = require("<builtin>")` (readable-stream's
|
||||
* internal/streams/stream.js). Requiring the chunk is then requiring the
|
||||
* builtin itself (same object, and loading a builtin runs no code). */
|
||||
function forwarderSpec(chunk: Chunk): string | null {
|
||||
const moduleParam = chunk.params[1];
|
||||
if (moduleParam === undefined) return null;
|
||||
const stmts = chunk.body.statements.nodes.filter(
|
||||
(st) => !(ts.isExpressionStatement(st) && ts.isStringLiteral(st.expression)),
|
||||
);
|
||||
const only = stmts[0];
|
||||
if (stmts.length !== 1 || only === undefined || !ts.isExpressionStatement(only)) return null;
|
||||
const e = unparen(only.expression);
|
||||
if (
|
||||
!ts.isBinaryExpression(e) ||
|
||||
e.operatorToken.kind !== ts.SyntaxKind.EqualsToken ||
|
||||
!ts.isPropertyAccessExpression(e.left) ||
|
||||
!ts.isIdentifier(e.left.expression) ||
|
||||
e.left.expression.text !== moduleParam ||
|
||||
e.left.name.text !== "exports"
|
||||
)
|
||||
return null;
|
||||
const call = unparen(e.right);
|
||||
if (
|
||||
!ts.isCallExpression(call) ||
|
||||
!ts.isIdentifier(call.expression) ||
|
||||
call.expression.text !== "require" ||
|
||||
call.arguments.nodes.length !== 1 ||
|
||||
!ts.isStringLiteral(call.arguments.nodes[0]!)
|
||||
)
|
||||
return null;
|
||||
const spec = (call.arguments.nodes[0] as ts.StringLiteral).text;
|
||||
return canonicalBuiltinModule(spec) !== null ? spec : null;
|
||||
}
|
||||
|
||||
/** How code in a factory body (a chunk or a lazy ES-module initializer)
|
||||
* observes the factory's own frame, or null: its receiver, its arguments
|
||||
* object, `super`, a meta property, or (when `returns`) a top-level
|
||||
* return have no module-scope equivalent. */
|
||||
export function factoryFrameUse(body: ts.Block, returns: boolean): string | null {
|
||||
let frameUse: string | null = null;
|
||||
/** The innermost frame boundary between a node and the factory body. */
|
||||
const frameOf = (n: ts.Node): "factory" | "arrow" | "function" => {
|
||||
let arrow = false;
|
||||
for (let p = n.parent; p !== undefined && p !== body; p = p.parent) {
|
||||
if (
|
||||
ts.isFunctionDeclaration(p) ||
|
||||
ts.isFunctionExpression(p) ||
|
||||
ts.isMethodDeclaration(p) ||
|
||||
ts.isGetAccessorDeclaration(p) ||
|
||||
ts.isSetAccessorDeclaration(p) ||
|
||||
ts.isConstructorDeclaration(p) ||
|
||||
ts.isClassDeclaration(p) ||
|
||||
ts.isClassExpression(p)
|
||||
)
|
||||
return "function";
|
||||
if (ts.isArrowFunction(p)) arrow = true;
|
||||
}
|
||||
return arrow ? "arrow" : "factory";
|
||||
};
|
||||
ts.walkPreorder(body, (n) => {
|
||||
if (frameUse !== null) return "stop";
|
||||
if (n.kind >= ts.SyntaxKind.FirstJSDocNode && n.kind <= ts.SyntaxKind.LastJSDocNode)
|
||||
return "skip";
|
||||
let use: string | null = null;
|
||||
if (n.kind === ts.SyntaxKind.ThisKeyword) use = "reads its factory's receiver (`this`)";
|
||||
else if (n.kind === ts.SyntaxKind.SuperKeyword) use = "reads `super` at its top level";
|
||||
else if (ts.isIdentifier(n) && n.text === "arguments" && isReference(n))
|
||||
use = "reads its factory's arguments object";
|
||||
else if (ts.isMetaProperty(n)) use = "reads a meta property at its top level";
|
||||
else if (ts.isReturnStatement(n)) {
|
||||
if (returns && frameOf(n) === "factory") frameUse = "returns from its top level";
|
||||
return undefined;
|
||||
}
|
||||
if (use !== null && frameOf(n) !== "function") frameUse = use;
|
||||
return undefined;
|
||||
});
|
||||
return frameUse;
|
||||
}
|
||||
|
||||
/** The virtual module text for one chunk, or a degrade reason. */
|
||||
function chunkSource(
|
||||
sf: ts.SourceFile,
|
||||
@@ -741,45 +828,7 @@ function chunkSource(
|
||||
);
|
||||
}
|
||||
|
||||
/* The factory's own frame must stay unobservable: its receiver, its
|
||||
* arguments object, and a top-level return have no module equivalent. */
|
||||
let frameUse: string | null = null;
|
||||
/** The innermost frame boundary between a node and the chunk body. */
|
||||
const frameOf = (n: ts.Node): "factory" | "arrow" | "function" => {
|
||||
let arrow = false;
|
||||
for (let p = n.parent; p !== undefined && p !== body; p = p.parent) {
|
||||
if (
|
||||
ts.isFunctionDeclaration(p) ||
|
||||
ts.isFunctionExpression(p) ||
|
||||
ts.isMethodDeclaration(p) ||
|
||||
ts.isGetAccessorDeclaration(p) ||
|
||||
ts.isSetAccessorDeclaration(p) ||
|
||||
ts.isConstructorDeclaration(p) ||
|
||||
ts.isClassDeclaration(p) ||
|
||||
ts.isClassExpression(p)
|
||||
)
|
||||
return "function";
|
||||
if (ts.isArrowFunction(p)) arrow = true;
|
||||
}
|
||||
return arrow ? "arrow" : "factory";
|
||||
};
|
||||
ts.walkPreorder(body, (n) => {
|
||||
if (frameUse !== null) return "stop";
|
||||
if (n.kind >= ts.SyntaxKind.FirstJSDocNode && n.kind <= ts.SyntaxKind.LastJSDocNode)
|
||||
return "skip";
|
||||
let use: string | null = null;
|
||||
if (n.kind === ts.SyntaxKind.ThisKeyword) use = "reads its factory's receiver (`this`)";
|
||||
else if (n.kind === ts.SyntaxKind.SuperKeyword) use = "reads `super` at its top level";
|
||||
else if (ts.isIdentifier(n) && n.text === "arguments" && isReference(n))
|
||||
use = "reads its factory's arguments object";
|
||||
else if (ts.isMetaProperty(n)) use = "reads a meta property at its top level";
|
||||
else if (ts.isReturnStatement(n)) {
|
||||
if (frameOf(n) === "factory") frameUse = "returns from its top level";
|
||||
return undefined;
|
||||
}
|
||||
if (use !== null && frameOf(n) !== "function") frameUse = use;
|
||||
return undefined;
|
||||
});
|
||||
const frameUse = factoryFrameUse(body, true);
|
||||
if (frameUse !== null) return why(frameUse);
|
||||
|
||||
const edits: Edit[] = callEdits.filter((e) => e.start >= body.pos && e.end <= body.end);
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterAll, expect, test } from "vitest";
|
||||
import { nodeFrontendServices } from "./services-node.js";
|
||||
|
||||
const helpers = `var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __esm = (fn, res) => function __init() {
|
||||
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
||||
};
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __create = Object.create;
|
||||
var __getProtoOf = Object.getPrototypeOf;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
||||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
||||
mod
|
||||
));
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
`;
|
||||
|
||||
const dirs: string[] = [];
|
||||
afterAll(() => {
|
||||
for (const dir of dirs) rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function lower(source: string, file = "/pkg/dist/index.js") {
|
||||
return nodeFrontendServices().lowerEsmInits(source, file);
|
||||
}
|
||||
|
||||
function run(file: string) {
|
||||
const result = spawnSync(process.execPath, [file], { encoding: "utf8" });
|
||||
return { status: result.status, stdout: result.stdout, stderr: result.stderr };
|
||||
}
|
||||
|
||||
function expectSameBehavior(source: string): string {
|
||||
const dir = mkdtempSync(join(tmpdir(), "scriptc-esm-inits-"));
|
||||
dirs.push(dir);
|
||||
const original = join(dir, "original.js");
|
||||
const lowered = join(dir, "index.js");
|
||||
writeFileSync(original, source);
|
||||
const result = lower(source, lowered);
|
||||
expect(typeof result).toBe("string");
|
||||
writeFileSync(lowered, result as string);
|
||||
const oracle = run(original);
|
||||
expect(oracle.status).toBe(0);
|
||||
expect(run(lowered)).toEqual(oracle);
|
||||
return result as string;
|
||||
}
|
||||
|
||||
const lazyModule = `
|
||||
function helper(x) { COUNT++; return "[" + x + "]"; }
|
||||
var COUNT;
|
||||
var init_helper = __esm({
|
||||
"src/helper.ts"() {
|
||||
console.log("helper init");
|
||||
COUNT = 0;
|
||||
}
|
||||
});
|
||||
var lazy_exports = {};
|
||||
__export(lazy_exports, {
|
||||
VALUE: () => VALUE,
|
||||
value: () => value
|
||||
});
|
||||
function value() {
|
||||
return VALUE + ":" + COUNT + ":" + import_os.default.EOL.length;
|
||||
}
|
||||
var path, import_os, VALUE;
|
||||
var init_lazy = __esm({
|
||||
"src/lazy.ts"() {
|
||||
path = __toESM(require("path"));
|
||||
import_os = __toESM(require("os"));
|
||||
init_helper();
|
||||
console.log("lazy init");
|
||||
VALUE = helper(path.basename("/a/b.txt"));
|
||||
}
|
||||
});
|
||||
`;
|
||||
|
||||
test("initializers run once, at their first call, and namespaces read live bindings", () => {
|
||||
const lowered = expectSameBehavior(`"use strict";
|
||||
${helpers}${lazyModule}
|
||||
console.log("start");
|
||||
function load() {
|
||||
const lazy = (init_lazy(), __toCommonJS(lazy_exports));
|
||||
return lazy.value() + " " + lazy.VALUE;
|
||||
}
|
||||
console.log(load());
|
||||
COUNT = 5;
|
||||
console.log(load(), (init_lazy(), __toCommonJS(lazy_exports)).value());
|
||||
`);
|
||||
expect(lowered).not.toContain("__esm({");
|
||||
expect(lowered).not.toContain("import_os");
|
||||
expect(lowered).toContain('(require("os")).EOL');
|
||||
});
|
||||
|
||||
test("calls of exported functions that never read their own `this` still lower", () => {
|
||||
const lowered = expectSameBehavior(`${helpers}var t_exports = {};
|
||||
__export(t_exports, { plain: () => plain, inner: () => inner });
|
||||
function plain(x) { return "plain " + x; }
|
||||
function inner() {
|
||||
function own() { return typeof this; }
|
||||
return "inner " + own.call(1);
|
||||
}
|
||||
var init_t = __esm({ "t.ts"() {} });
|
||||
const t = (init_t(), __toCommonJS(t_exports));
|
||||
console.log(t.plain(1), (t.plain)(2), t.inner());
|
||||
`);
|
||||
expect(lowered).not.toContain("__toCommonJS(t_exports)");
|
||||
});
|
||||
|
||||
test.each([
|
||||
["a direct call", `NS.who()`],
|
||||
["a parenthesized callee", `(NS.who)()`],
|
||||
["a tagged template", "NS.who`x`"],
|
||||
["a call through a local", `(() => { const m = NS; return m.who(); })()`],
|
||||
["an arrow inside the function", `NS.arrow()()`],
|
||||
])("%s that passes the namespace as `this` keeps the package refused", (_, use) => {
|
||||
const result = lower(`${helpers}var w_exports = {};
|
||||
__export(w_exports, { who: () => who, arrow: () => arrow });
|
||||
function who() { return this.__esModule; }
|
||||
function arrow() { return () => this; }
|
||||
var init_w = __esm({ "w.ts"() {} });
|
||||
console.log(${use.replaceAll("NS", "(init_w(), __toCommonJS(w_exports))")});
|
||||
`);
|
||||
expect(result).toEqual({
|
||||
degrade: expect.stringContaining(
|
||||
"calls only of exported functions that do not read 'this'",
|
||||
) as string,
|
||||
});
|
||||
});
|
||||
|
||||
test("an export that reads `this` in a parameter's default value keeps the package refused", () => {
|
||||
const result = lower(`${helpers}var p_exports = {};
|
||||
__export(p_exports, { who: () => who });
|
||||
function who(value = this.__esModule) { return value; }
|
||||
var init_p = __esm({ "p.ts"() {} });
|
||||
console.log((init_p(), __toCommonJS(p_exports)).who());
|
||||
`);
|
||||
expect(result).toEqual({
|
||||
degrade: expect.stringContaining(
|
||||
"calls only of exported functions that do not read 'this'",
|
||||
) as string,
|
||||
});
|
||||
});
|
||||
|
||||
test("minified initializers sharing a var statement lower the same way", () => {
|
||||
expectSameBehavior(
|
||||
helpers +
|
||||
`var x_exports={};__export(x_exports,{v:()=>v});var v,import_path,init_x=__esm({"x.ts"(){"use strict";import_path=__toESM(require("path")),v=import_path.default.sep}});` +
|
||||
`console.log((init_x(),__toCommonJS(x_exports)).v);`,
|
||||
);
|
||||
});
|
||||
|
||||
test("memoized lazy loaders sharing a var statement lower together", () => {
|
||||
const lowered = expectSameBehavior(`${helpers}var a_exports = {};
|
||||
__export(a_exports, { v: () => v });
|
||||
var v, init_a = __esm({ "a.ts"() { console.log("a init"); v = 1; } });
|
||||
var b_exports = {};
|
||||
__export(b_exports, { default: () => w });
|
||||
var w, init_b = __esm({ "b.ts"() { console.log("b init"); w = 2; } });
|
||||
var nsA, loadA = () => nsA ??= (init_a(), __toCommonJS(a_exports)), nsB, loadB = () => nsB ??= __toESM((init_b(), __toCommonJS(b_exports)));
|
||||
console.log(loadA().v, loadB().default, loadA().v);
|
||||
`);
|
||||
expect(lowered).not.toContain("loadA");
|
||||
expect(lowered).not.toContain("loadB");
|
||||
});
|
||||
|
||||
test("calls through a memoized lazy loader keep the receiver rule", () => {
|
||||
const source = (use: string): string => `${helpers}var w_exports = {};
|
||||
__export(w_exports, { who: () => who, plain: () => plain });
|
||||
function who() { return this.__esModule; }
|
||||
function plain(x) { return "plain " + x; }
|
||||
var init_w = __esm({ "w.ts"() {} });
|
||||
var ns, load = () => ns ??= (init_w(), __toCommonJS(w_exports));
|
||||
console.log(${use});
|
||||
`;
|
||||
expect(lower(source("load().who()"))).toEqual({
|
||||
degrade: expect.stringContaining(
|
||||
"calls only of exported functions that do not read 'this'",
|
||||
) as string,
|
||||
});
|
||||
const lowered = expectSameBehavior(source("load().plain(1), (load().plain)(2)"));
|
||||
expect(lowered).not.toContain("load()");
|
||||
});
|
||||
|
||||
test.each([
|
||||
["is asynchronous", `var init_a = __esm({ async "a.ts"() { await 0; } });\ninit_a();`],
|
||||
[
|
||||
"is used other than as a statement call",
|
||||
`var init_a = __esm({ "a.ts"() {} });\nvar r = init_a();`,
|
||||
],
|
||||
[
|
||||
"reads its factory's receiver",
|
||||
`var init_a = __esm({ "a.ts"() { console.log(this); } });\ninit_a();`,
|
||||
],
|
||||
[
|
||||
"memoized lazy loader 'load' returns the namespace of a bundled ES module as a value",
|
||||
`var a_exports = {};\n__export(a_exports, { v: () => v });\nvar v, init_a = __esm({ "a.ts"() { v = 1; } });\nvar ns, load = () => ns ??= __toESM((init_a(), __toCommonJS(a_exports)));\nload();`,
|
||||
],
|
||||
[
|
||||
"reads the namespace of a bundled ES module ('a_exports')",
|
||||
`var a_exports = {};\n__export(a_exports, { v: () => v });\nvar v, init_a = __esm({ "a.ts"() { v = 1; } });\nconsole.log(Object.keys((init_a(), __toCommonJS(a_exports))));`,
|
||||
],
|
||||
])("an initializer that %s keeps the package refused", (reason, code) => {
|
||||
expect(lower(`${helpers}${code}\n`)).toEqual({
|
||||
degrade: expect.stringContaining(reason) as string,
|
||||
});
|
||||
});
|
||||
|
||||
test("files without __esm initializers and ES-module bundles are left alone", () => {
|
||||
expect(lower("exports.x = 1;\n")).toBeNull();
|
||||
expect(
|
||||
lower(`${helpers}var init_a = __esm({ "a.ts"() {} });\ninit_a();\nexport {};\n`),
|
||||
).toBeNull();
|
||||
});
|
||||
@@ -0,0 +1,825 @@
|
||||
/* Lazily initialized ES modules in a CommonJS bundle. esbuild scope-hoists
|
||||
* every ES module it bundles into the bundle's own scope; one that some
|
||||
* code require()s instead of importing runs from a lazy initializer,
|
||||
*
|
||||
* var COUNT, import_fs;
|
||||
* var init_x = __esm({ "src/x.ts"() { import_fs = __toESM(require("fs")); COUNT = 0; } });
|
||||
*
|
||||
* and the requiring site reads its namespace as
|
||||
* `(init_x(), __toCommonJS(x_exports))`. `init_x()` runs the body once (a
|
||||
* call during the body answers immediately). The pass below keeps that
|
||||
* shape in the bundle's scope and respells only what has no static
|
||||
* representation:
|
||||
*
|
||||
* - the initializer becomes a run-once closure over the same body;
|
||||
* - an interop binding the body assigns once from require() (`import_fs`
|
||||
* above) becomes that require at the assignment's position, and its
|
||||
* member reads become member reads of the required module, exactly
|
||||
* like the top-level interop erasure (npm-static-rewrite-syntax.ts);
|
||||
* - a namespace read only through member reads becomes an object
|
||||
* literal of getters over the module's live bindings (what
|
||||
* __toCommonJS copies, minus the non-enumerable __esModule mark no
|
||||
* member read can reach).
|
||||
*
|
||||
* The respelled interop reads resolve the required module even if they
|
||||
* ran before the initializer, where Node would read a member of
|
||||
* undefined and throw; esbuild only reaches them through the module's
|
||||
* own code, which runs after its initializer. Shapes outside the
|
||||
* recognized forms answer a degrade reason. */
|
||||
import * as ts from "./ts7/syntax.js";
|
||||
import { bareRequireSpecOf } from "./cjs-syntax.js";
|
||||
import { helperTokens } from "./helper-tokens.js";
|
||||
import {
|
||||
applyEdits,
|
||||
countDeclarations,
|
||||
declaredNames,
|
||||
factoryFrameUse,
|
||||
helperBase,
|
||||
isWritten,
|
||||
references,
|
||||
unparen,
|
||||
type Edit,
|
||||
} from "./npm-static-bundled-chunks.js";
|
||||
|
||||
export interface EsmInitHost {
|
||||
requireTargetEsModuleStamped(fromFile: string, specifier: string): boolean;
|
||||
}
|
||||
|
||||
const ESM_SHAPE_DEGRADE =
|
||||
"its shipped JS initializes bundled ES modules through the __esm helper in a shape the " +
|
||||
"recognizer cannot verify";
|
||||
|
||||
/* The recognized __esm forms over its parameter names (FN, RES) and the
|
||||
* own-key reader (KEYS): keyed `(FN, RES) => function [name]() { return
|
||||
* <keyed>; }` with a one-method object argument, and arrow
|
||||
* `(FN, RES) => () => (<arrow>)` with a function argument. */
|
||||
const KEYED_RETURN = "FN && (RES = (0, FN[KEYS(FN)[0]])(FN = 0)), RES";
|
||||
const ARROW_BODY = "(FN && (RES = FN(FN = 0)), RES)";
|
||||
|
||||
function template(text: string, fn: string, res: string, keys: string): string | null {
|
||||
return helperTokens(
|
||||
text
|
||||
.replace(/\bFN\b/g, fn)
|
||||
.replace(/\bRES\b/g, res)
|
||||
.replace(/\bKEYS\b/g, keys),
|
||||
);
|
||||
}
|
||||
|
||||
function esmHelperForm(
|
||||
init: ts.Expression,
|
||||
sf: ts.SourceFile,
|
||||
ownNames: (name: string) => boolean,
|
||||
): "keyed" | "arrow" | null {
|
||||
const fn = unparen(init);
|
||||
if (!ts.isArrowFunction(fn) || fn.parameters.nodes.length !== 2 || ts.isBlock(fn.body))
|
||||
return null;
|
||||
const [p0, p1] = fn.parameters.nodes;
|
||||
if (
|
||||
!p0 ||
|
||||
!p1 ||
|
||||
!ts.isIdentifier(p0.name) ||
|
||||
!ts.isIdentifier(p1.name) ||
|
||||
p0.initializer ||
|
||||
p1.initializer ||
|
||||
p0.name.text === p1.name.text
|
||||
)
|
||||
return null;
|
||||
const [f, r] = [p0.name.text, p1.name.text];
|
||||
const body = unparen(fn.body);
|
||||
if (ts.isFunctionExpression(body)) {
|
||||
if (body.parameters.nodes.length !== 0 || body.asteriskToken || body.modifiers?.nodes.length)
|
||||
return null;
|
||||
const stmts = body.body.statements.nodes;
|
||||
const ret = stmts[0];
|
||||
if (stmts.length !== 1 || !ret || !ts.isReturnStatement(ret) || !ret.expression) return null;
|
||||
const text = ret.expression.getText(sf);
|
||||
const keys = /\[\s*([A-Za-z_$][\w$]*(?:\.keys)?)\s*\(/.exec(text)?.[1];
|
||||
if (keys === undefined || (keys !== "Object.keys" && !ownNames(keys))) return null;
|
||||
return helperTokens(text) === template(KEYED_RETURN, f, r, keys) ? "keyed" : null;
|
||||
}
|
||||
if (ts.isArrowFunction(body) && body.parameters.nodes.length === 0 && !ts.isBlock(body.body)) {
|
||||
const actual = helperTokens(body.body.getText(sf));
|
||||
return actual !== null && actual === template(ARROW_BODY, f, r, "") ? "arrow" : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Pads the given declarators out of their statements (separating commas
|
||||
* included; a statement whose declarators all go pads whole). */
|
||||
function removeDeclarators(sf: ts.SourceFile, dead: ReadonlySet<ts.VariableDeclaration>): Edit[] {
|
||||
const edits: Edit[] = [];
|
||||
const stmts = new Set<ts.VariableStatement>();
|
||||
for (const d of dead) {
|
||||
const stmt = d.parent?.parent;
|
||||
if (stmt !== undefined && ts.isVariableStatement(stmt)) stmts.add(stmt);
|
||||
}
|
||||
for (const stmt of stmts) {
|
||||
const decls = stmt.declarationList.declarations.nodes;
|
||||
const deadAt = decls.map((d) => dead.has(d));
|
||||
if (deadAt.every((x) => x)) {
|
||||
edits.push({ start: stmt.getStart(sf), end: stmt.getEnd(), text: "" });
|
||||
continue;
|
||||
}
|
||||
const lastLive = deadAt.lastIndexOf(false);
|
||||
for (let i = 0; i < decls.length; i++) {
|
||||
if (!deadAt[i]) continue;
|
||||
edits.push(
|
||||
i < lastLive
|
||||
? { start: decls[i]!.getStart(sf), end: decls[i + 1]!.getStart(sf), text: "" }
|
||||
: { start: decls[lastLive]!.getEnd(), end: decls[i]!.getEnd(), text: "" },
|
||||
);
|
||||
}
|
||||
}
|
||||
return edits;
|
||||
}
|
||||
|
||||
/** The elements of an expression statement's comma chain, in order. */
|
||||
function commaElements(e: ts.Expression): ts.Expression[] {
|
||||
const out: ts.Expression[] = [];
|
||||
const visit = (x: ts.Expression): void => {
|
||||
if (ts.isBinaryExpression(x) && x.operatorToken.kind === ts.SyntaxKind.CommaToken) {
|
||||
visit(x.left);
|
||||
visit(x.right);
|
||||
} else out.push(x);
|
||||
};
|
||||
visit(e);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** True when a call's result is discarded: an expression statement or a
|
||||
* non-final comma operand (parentheses included). */
|
||||
function resultUnused(call: ts.Expression): boolean {
|
||||
let child: ts.Node = call;
|
||||
let p = call.parent;
|
||||
while (p !== undefined && ts.isParenthesizedExpression(p)) {
|
||||
child = p;
|
||||
p = p.parent;
|
||||
}
|
||||
if (p === undefined) return false;
|
||||
if (ts.isExpressionStatement(p)) return true;
|
||||
if (ts.isBinaryExpression(p) && p.operatorToken.kind === ts.SyntaxKind.CommaToken) {
|
||||
if (p.left === child) return true;
|
||||
return resultUnused(p);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** True when a member access is a plain read (not written, deleted or
|
||||
* updated). */
|
||||
function plainRead(access: ts.Expression): boolean {
|
||||
const p = access.parent;
|
||||
if (p === undefined) return true;
|
||||
if (ts.isDeleteExpression(p)) return false;
|
||||
if (
|
||||
ts.isBinaryExpression(p) &&
|
||||
p.left === access &&
|
||||
p.operatorToken.kind >= ts.SyntaxKind.FirstAssignment &&
|
||||
p.operatorToken.kind <= ts.SyntaxKind.LastAssignment
|
||||
)
|
||||
return false;
|
||||
if (
|
||||
(ts.isPrefixUnaryExpression(p) || ts.isPostfixUnaryExpression(p)) &&
|
||||
(p.operator === ts.SyntaxKind.PlusPlusToken || p.operator === ts.SyntaxKind.MinusMinusToken)
|
||||
)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/** True when a member read is the callee of a call or a tag, which receives
|
||||
* the object it was read from as `this`. */
|
||||
function calledWithReceiver(access: ts.Expression): boolean {
|
||||
let callee: ts.Node = access;
|
||||
while (callee.parent !== undefined && ts.isParenthesizedExpression(callee.parent))
|
||||
callee = callee.parent;
|
||||
const p = callee.parent;
|
||||
return (
|
||||
p !== undefined &&
|
||||
((ts.isCallExpression(p) && p.expression === callee) ||
|
||||
(ts.isTaggedTemplateExpression(p) && p.tag === callee))
|
||||
);
|
||||
}
|
||||
|
||||
/** True when a function reads its own `this`: in its body or a parameter's
|
||||
* default value, or in an arrow function inside them. */
|
||||
function readsThis(fn: ts.FunctionDeclaration): boolean {
|
||||
let found = false;
|
||||
if (fn.body === undefined) return false;
|
||||
const visit = (n: ts.Node): "stop" | "skip" | undefined => {
|
||||
if (found) return "stop";
|
||||
if (
|
||||
ts.isFunctionDeclaration(n) ||
|
||||
ts.isFunctionExpression(n) ||
|
||||
ts.isMethodDeclaration(n) ||
|
||||
ts.isGetAccessorDeclaration(n) ||
|
||||
ts.isSetAccessorDeclaration(n) ||
|
||||
ts.isConstructorDeclaration(n) ||
|
||||
ts.isClassDeclaration(n) ||
|
||||
ts.isClassExpression(n)
|
||||
)
|
||||
return "skip";
|
||||
if (n.kind === ts.SyntaxKind.ThisKeyword) found = true;
|
||||
return undefined;
|
||||
};
|
||||
for (const parameter of fn.parameters.nodes) ts.walkPreorder(parameter, visit);
|
||||
ts.walkPreorder(fn.body, visit);
|
||||
return found;
|
||||
}
|
||||
|
||||
/** The `__export(T, { name: () => value, … })` getter table of T, or null. */
|
||||
function exportTableOf(
|
||||
call: ts.CallExpression,
|
||||
): { target: string; entries: [string, ts.Expression][] } | null {
|
||||
if (!ts.isIdentifier(call.expression) || helperBase(call.expression.text) !== "__export")
|
||||
return null;
|
||||
const [target, table] = call.arguments.nodes;
|
||||
if (
|
||||
call.arguments.nodes.length !== 2 ||
|
||||
!target ||
|
||||
!table ||
|
||||
!ts.isIdentifier(target) ||
|
||||
!ts.isObjectLiteralExpression(table)
|
||||
)
|
||||
return null;
|
||||
const entries: [string, ts.Expression][] = [];
|
||||
for (const prop of table.properties.nodes) {
|
||||
if (!ts.isPropertyAssignment(prop)) return null;
|
||||
if (!ts.isIdentifier(prop.name) && !ts.isStringLiteral(prop.name)) return null;
|
||||
const getter = unparen(prop.initializer);
|
||||
if (!ts.isArrowFunction(getter) || getter.parameters.nodes.length !== 0) return null;
|
||||
if (ts.isBlock(getter.body)) return null;
|
||||
entries.push([prop.name.text, getter.body]);
|
||||
}
|
||||
return { target: target.text, entries };
|
||||
}
|
||||
|
||||
/** Lowers a CommonJS bundle's __esm initializers (see the header). Null:
|
||||
* nothing to lower. */
|
||||
export function lowerBundledEsmInits(
|
||||
sf: ts.SourceFile,
|
||||
filePath: string,
|
||||
host: EsmInitHost,
|
||||
): string | { degrade: string } | null {
|
||||
const source = sf.text;
|
||||
if (!source.includes("__esm")) return null;
|
||||
if (!filePath.endsWith(".cjs") && ts.isExternalModule(sf)) return null;
|
||||
|
||||
interface Top {
|
||||
stmt: ts.Statement;
|
||||
node: ts.VariableDeclaration | ts.FunctionDeclaration;
|
||||
}
|
||||
const top = new Map<string, Top>();
|
||||
const duplicate = new Set<string>();
|
||||
for (const stmt of sf.statements.nodes) {
|
||||
const add = (name: string, node: Top["node"]): void => {
|
||||
if (top.has(name)) duplicate.add(name);
|
||||
else top.set(name, { stmt, node });
|
||||
};
|
||||
if (ts.isFunctionDeclaration(stmt) && stmt.name !== undefined) add(stmt.name.text, stmt);
|
||||
else if (ts.isVariableStatement(stmt)) {
|
||||
for (const d of stmt.declarationList.declarations.nodes) {
|
||||
if (ts.isIdentifier(d.name)) add(d.name.text, d);
|
||||
}
|
||||
}
|
||||
}
|
||||
const helpers = [...top.keys()].filter((n) => helperBase(n) === "__esm");
|
||||
if (helpers.length === 0) return null;
|
||||
|
||||
const allRefs = references(sf);
|
||||
const writes = new Map<string, number>();
|
||||
for (const r of allRefs) if (isWritten(r)) writes.set(r.text, (writes.get(r.text) ?? 0) + 1);
|
||||
const declaredAnywhere = declaredNames(sf);
|
||||
if (declaredAnywhere.has("Object") || writes.has("Object")) return { degrade: ESM_SHAPE_DEGRADE };
|
||||
const stable = (name: string): boolean => !duplicate.has(name) && !writes.has(name);
|
||||
const ownNames = (name: string): boolean => {
|
||||
const t = top.get(name);
|
||||
const init =
|
||||
t !== undefined && ts.isVariableDeclaration(t.node) ? t.node.initializer : undefined;
|
||||
return (
|
||||
init !== undefined &&
|
||||
stable(name) &&
|
||||
helperTokens(init.getText(sf)) === helperTokens("Object.getOwnPropertyNames")
|
||||
);
|
||||
};
|
||||
const forms = new Map<string, "keyed" | "arrow">();
|
||||
for (const name of helpers) {
|
||||
const t = top.get(name)!;
|
||||
const init = ts.isVariableDeclaration(t.node) ? t.node.initializer : undefined;
|
||||
const form = init !== undefined && stable(name) ? esmHelperForm(init, sf, ownNames) : null;
|
||||
if (form === null) return { degrade: ESM_SHAPE_DEGRADE };
|
||||
forms.set(name, form);
|
||||
}
|
||||
|
||||
// The initializers: `NAME = HELPER(factory)` declarators.
|
||||
interface Init {
|
||||
name: string;
|
||||
call: ts.CallExpression;
|
||||
body: ts.Block;
|
||||
}
|
||||
const inits = new Map<string, Init>();
|
||||
for (const [name, t] of top) {
|
||||
if (!ts.isVariableDeclaration(t.node) || t.node.initializer === undefined) continue;
|
||||
const call = unparen(t.node.initializer);
|
||||
if (!ts.isCallExpression(call) || !ts.isIdentifier(call.expression)) continue;
|
||||
const form = forms.get(call.expression.text);
|
||||
if (form === undefined) continue;
|
||||
if (call.arguments.nodes.length !== 1 || !stable(name)) return { degrade: ESM_SHAPE_DEGRADE };
|
||||
let factory: ts.Node = call.arguments.nodes[0]!;
|
||||
if (form === "keyed") {
|
||||
if (!ts.isObjectLiteralExpression(factory) || factory.properties.nodes.length !== 1)
|
||||
return { degrade: ESM_SHAPE_DEGRADE };
|
||||
factory = factory.properties.nodes[0]!;
|
||||
if (!ts.isMethodDeclaration(factory) || ts.isComputedPropertyName(factory.name))
|
||||
return { degrade: ESM_SHAPE_DEGRADE };
|
||||
} else {
|
||||
factory = unparen(factory as ts.Expression);
|
||||
if (!ts.isArrowFunction(factory) && !ts.isFunctionExpression(factory))
|
||||
return { degrade: ESM_SHAPE_DEGRADE };
|
||||
}
|
||||
const fn = factory as ts.MethodDeclaration | ts.ArrowFunction | ts.FunctionExpression;
|
||||
if (fn.modifiers?.nodes.some((m) => m.kind === ts.SyntaxKind.AsyncKeyword))
|
||||
return {
|
||||
degrade: `its bundled ES module initializer '${name}' is asynchronous (top-level await), which the lazy initialization rewrite does not cover`,
|
||||
};
|
||||
if (
|
||||
fn.body === undefined ||
|
||||
!ts.isBlock(fn.body) ||
|
||||
fn.asteriskToken !== undefined ||
|
||||
(fn.modifiers?.nodes.length ?? 0) > 0 ||
|
||||
fn.parameters.nodes.length > 0
|
||||
)
|
||||
return { degrade: ESM_SHAPE_DEGRADE };
|
||||
const frame = factoryFrameUse(fn.body, false);
|
||||
if (frame !== null) return { degrade: `its bundled ES module initializer '${name}' ${frame}` };
|
||||
inits.set(name, { name, call, body: fn.body });
|
||||
}
|
||||
if (inits.size === 0) return null;
|
||||
|
||||
const edits: Edit[] = [];
|
||||
// Every initializer reference is a direct call whose result is unused.
|
||||
for (const r of allRefs) {
|
||||
if (!inits.has(r.text)) continue;
|
||||
const call = r.parent;
|
||||
if (
|
||||
call === undefined ||
|
||||
!ts.isCallExpression(call) ||
|
||||
call.expression !== r ||
|
||||
call.arguments.nodes.length !== 0 ||
|
||||
!resultUnused(call)
|
||||
)
|
||||
return {
|
||||
degrade: `its bundled ES module initializer '${r.text}' is used other than as a statement call`,
|
||||
};
|
||||
}
|
||||
for (const name of inits.keys()) {
|
||||
if (countDeclarations(sf, name) !== 1) return { degrade: ESM_SHAPE_DEGRADE };
|
||||
}
|
||||
|
||||
/* Interop bindings an initializer assigns once from require(). */
|
||||
const refsByName = new Map<string, ts.Identifier[]>();
|
||||
for (const r of allRefs) {
|
||||
const list = refsByName.get(r.text);
|
||||
if (list === undefined) refsByName.set(r.text, [r]);
|
||||
else list.push(r);
|
||||
}
|
||||
const deadDeclarators = new Set<ts.VariableDeclaration>();
|
||||
for (const init of inits.values()) {
|
||||
for (const stmt of init.body.statements.nodes) {
|
||||
if (!ts.isExpressionStatement(stmt)) continue;
|
||||
for (const el of commaElements(stmt.expression)) {
|
||||
if (
|
||||
!ts.isBinaryExpression(el) ||
|
||||
el.operatorToken.kind !== ts.SyntaxKind.EqualsToken ||
|
||||
!ts.isIdentifier(el.left)
|
||||
)
|
||||
continue;
|
||||
const name = el.left.text;
|
||||
const decl = top.get(name)?.node;
|
||||
if (
|
||||
decl === undefined ||
|
||||
!ts.isVariableDeclaration(decl) ||
|
||||
decl.initializer !== undefined ||
|
||||
duplicate.has(name) ||
|
||||
writes.get(name) !== 1 ||
|
||||
countDeclarations(sf, name) !== 1
|
||||
)
|
||||
continue;
|
||||
let rhs = unparen(el.right);
|
||||
let isNodeMode = false;
|
||||
let interop = false;
|
||||
if (
|
||||
ts.isCallExpression(rhs) &&
|
||||
ts.isIdentifier(rhs.expression) &&
|
||||
helperBase(rhs.expression.text) === "__toESM"
|
||||
) {
|
||||
const [arg, mode] = rhs.arguments.nodes;
|
||||
if (!arg || rhs.arguments.nodes.length > 2) continue;
|
||||
if (mode !== undefined) {
|
||||
if (ts.isNumericLiteral(mode)) isNodeMode = Number(mode.text) !== 0;
|
||||
else if (mode.kind === ts.SyntaxKind.TrueKeyword) isNodeMode = true;
|
||||
else if (mode.kind !== ts.SyntaxKind.FalseKeyword) continue;
|
||||
}
|
||||
rhs = unparen(arg);
|
||||
interop = true;
|
||||
}
|
||||
const spec = bareRequireSpecOf(rhs);
|
||||
if (spec === null) continue;
|
||||
const req = rhs.getText(sf);
|
||||
const defaultIsModule =
|
||||
interop && (isNodeMode || !host.requireTargetEsModuleStamped(filePath, spec));
|
||||
// Every other reference must be a plain member read.
|
||||
const uses: Edit[] = [];
|
||||
let ok = true;
|
||||
for (const r of refsByName.get(name) ?? []) {
|
||||
if (r === el.left) continue;
|
||||
const access = r.parent;
|
||||
if (
|
||||
access === undefined ||
|
||||
!ts.isPropertyAccessExpression(access) ||
|
||||
access.expression !== r ||
|
||||
!plainRead(access)
|
||||
) {
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
if (defaultIsModule && access.name.text === "default")
|
||||
uses.push({ start: access.getStart(sf), end: access.getEnd(), text: `(${req})` });
|
||||
else uses.push({ start: r.getStart(sf), end: r.getEnd(), text: req });
|
||||
}
|
||||
if (!ok) continue;
|
||||
edits.push({ start: el.getStart(sf), end: el.getEnd(), text: req }, ...uses);
|
||||
deadDeclarators.add(decl);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Namespaces of lazily initialized modules read through members. */
|
||||
let mainTarget: string | null = null;
|
||||
for (const stmt of sf.statements.nodes) {
|
||||
if (!ts.isExpressionStatement(stmt) || !ts.isBinaryExpression(stmt.expression)) continue;
|
||||
const e = stmt.expression;
|
||||
const rhs = e.right;
|
||||
if (
|
||||
e.operatorToken.kind === ts.SyntaxKind.EqualsToken &&
|
||||
ts.isPropertyAccessExpression(e.left) &&
|
||||
ts.isIdentifier(e.left.expression) &&
|
||||
e.left.expression.text === "module" &&
|
||||
e.left.name.text === "exports" &&
|
||||
ts.isCallExpression(rhs) &&
|
||||
ts.isIdentifier(rhs.expression) &&
|
||||
helperBase(rhs.expression.text) === "__toCommonJS" &&
|
||||
rhs.arguments.nodes.length === 1 &&
|
||||
ts.isIdentifier(rhs.arguments.nodes[0]!)
|
||||
)
|
||||
mainTarget = (rhs.arguments.nodes[0] as ts.Identifier).text;
|
||||
}
|
||||
const tables = new Map<string, { stmt: ts.Statement; entries: [string, ts.Expression][] }>();
|
||||
for (const stmt of sf.statements.nodes) {
|
||||
if (!ts.isExpressionStatement(stmt) || !ts.isCallExpression(stmt.expression)) continue;
|
||||
const table = exportTableOf(stmt.expression);
|
||||
if (table !== null && table.target !== mainTarget) {
|
||||
if (tables.has(table.target)) return { degrade: ESM_SHAPE_DEGRADE };
|
||||
tables.set(table.target, { stmt, entries: table.entries });
|
||||
}
|
||||
}
|
||||
const lowered = new Set<string>();
|
||||
/** Some binding between the use site and the top level rebinds a name
|
||||
* the table's getters read. */
|
||||
const shadowed = (site: ts.Node, entries: readonly [string, ts.Expression][]): boolean => {
|
||||
const read = new Set<string>();
|
||||
for (const [, value] of entries) for (const x of references(value)) read.add(x.text);
|
||||
for (let a = site.parent; a !== undefined && !ts.isSourceFile(a); a = a.parent) {
|
||||
if (
|
||||
ts.isFunctionLike(a) ||
|
||||
ts.isBlock(a) ||
|
||||
ts.isClassDeclaration(a) ||
|
||||
ts.isClassExpression(a)
|
||||
) {
|
||||
for (const n of declaredNames(a)) if (read.has(n)) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
const getterText = (value: ts.Expression): string =>
|
||||
applyEdits(source, value.getStart(sf), value.getEnd(), edits);
|
||||
/** A call through the namespace (`ns.fn()`, `L().fn()`) passes the object
|
||||
* the read came from as `this`; the lowered object differs from Node's
|
||||
* module object (`__esModule`, property attributes), so it must stay
|
||||
* unobservable: the callee is a top-level function that never reads
|
||||
* `this`. */
|
||||
const receiverHidden = (values: ReadonlyMap<string, ts.Expression>, name: string): boolean => {
|
||||
const value = values.get(name);
|
||||
if (value === undefined || !ts.isIdentifier(value) || !stable(value.text)) return false;
|
||||
const decl = top.get(value.text)?.node;
|
||||
return decl !== undefined && ts.isFunctionDeclaration(decl) && !readsThis(decl);
|
||||
};
|
||||
|
||||
/* Memoized lazy loaders of those namespaces, `L = () => M ??= NS` (a
|
||||
* bundle plugin's lazy re-exports): every `L().name` becomes the
|
||||
* initializer call followed by the export's live read, so the first
|
||||
* access still initializes the module, once, and later accesses read
|
||||
* the binding. */
|
||||
const loaderSpans: { start: number; end: number }[] = [];
|
||||
for (const [name, t] of top) {
|
||||
const d = t.node;
|
||||
if (!ts.isVariableDeclaration(d) || d.initializer === undefined) continue;
|
||||
const fn = unparen(d.initializer);
|
||||
if (!ts.isArrowFunction(fn) || fn.parameters.nodes.length !== 0 || ts.isBlock(fn.body))
|
||||
continue;
|
||||
const memoize = unparen(fn.body);
|
||||
if (
|
||||
!ts.isBinaryExpression(memoize) ||
|
||||
(memoize.operatorToken.kind !== ts.SyntaxKind.QuestionQuestionEqualsToken &&
|
||||
memoize.operatorToken.kind !== ts.SyntaxKind.BarBarEqualsToken) ||
|
||||
!ts.isIdentifier(memoize.left)
|
||||
)
|
||||
continue;
|
||||
let w = unparen(memoize.right);
|
||||
let interop = false;
|
||||
let nodeMode = false;
|
||||
if (
|
||||
ts.isCallExpression(w) &&
|
||||
ts.isIdentifier(w.expression) &&
|
||||
helperBase(w.expression.text) === "__toESM"
|
||||
) {
|
||||
const [arg, mode] = w.arguments.nodes;
|
||||
if (!arg || w.arguments.nodes.length > 2) continue;
|
||||
if (mode !== undefined) {
|
||||
if (ts.isNumericLiteral(mode)) nodeMode = Number(mode.text) !== 0;
|
||||
else if (mode.kind === ts.SyntaxKind.TrueKeyword) nodeMode = true;
|
||||
else if (mode.kind !== ts.SyntaxKind.FalseKeyword) continue;
|
||||
}
|
||||
interop = true;
|
||||
w = unparen(arg);
|
||||
}
|
||||
let initCall: ts.CallExpression | null = null;
|
||||
if (ts.isBinaryExpression(w) && w.operatorToken.kind === ts.SyntaxKind.CommaToken) {
|
||||
const left = unparen(w.left);
|
||||
if (
|
||||
!ts.isCallExpression(left) ||
|
||||
!ts.isIdentifier(left.expression) ||
|
||||
!inits.has(left.expression.text) ||
|
||||
left.arguments.nodes.length !== 0
|
||||
)
|
||||
continue;
|
||||
initCall = left;
|
||||
w = unparen(w.right);
|
||||
}
|
||||
if (
|
||||
!ts.isCallExpression(w) ||
|
||||
!ts.isIdentifier(w.expression) ||
|
||||
helperBase(w.expression.text) !== "__toCommonJS" ||
|
||||
w.arguments.nodes.length !== 1 ||
|
||||
!ts.isIdentifier(w.arguments.nodes[0]!)
|
||||
)
|
||||
continue;
|
||||
const target = (w.arguments.nodes[0] as ts.Identifier).text;
|
||||
const table = tables.get(target);
|
||||
if (table === undefined) continue;
|
||||
const loaderWhy = {
|
||||
degrade: `its memoized lazy loader '${name}' returns the namespace of a bundled ES module as a value, a module object the static rewrite cannot represent (only member reads of its result compile, and calls only of exported functions that do not read 'this')`,
|
||||
};
|
||||
const memo = memoize.left.text;
|
||||
const memoDecl = top.get(memo)?.node;
|
||||
if (
|
||||
memoDecl === undefined ||
|
||||
!ts.isVariableDeclaration(memoDecl) ||
|
||||
memoDecl.initializer !== undefined ||
|
||||
writes.get(memo) !== 1 ||
|
||||
countDeclarations(sf, memo) !== 1 ||
|
||||
(refsByName.get(memo) ?? []).some((x) => x !== memoize.left) ||
|
||||
writes.has(name) ||
|
||||
countDeclarations(sf, name) !== 1
|
||||
)
|
||||
return loaderWhy;
|
||||
const entries = new Map(table.entries);
|
||||
for (const ref of refsByName.get(name) ?? []) {
|
||||
const call = ref.parent;
|
||||
if (
|
||||
call === undefined ||
|
||||
!ts.isCallExpression(call) ||
|
||||
call.expression !== ref ||
|
||||
call.arguments.nodes.length !== 0
|
||||
)
|
||||
return loaderWhy;
|
||||
let access: ts.Node | undefined = call.parent;
|
||||
if (
|
||||
access === undefined ||
|
||||
!ts.isPropertyAccessExpression(access) ||
|
||||
access.expression !== call ||
|
||||
!plainRead(access)
|
||||
)
|
||||
return loaderWhy;
|
||||
// Node mode binds `default` to the namespace object itself.
|
||||
if (interop && nodeMode && access.name.text === "default") {
|
||||
const outer: ts.Node | undefined = access.parent;
|
||||
if (
|
||||
outer === undefined ||
|
||||
!ts.isPropertyAccessExpression(outer) ||
|
||||
outer.expression !== access ||
|
||||
!plainRead(outer)
|
||||
)
|
||||
return loaderWhy;
|
||||
access = outer;
|
||||
}
|
||||
const member = (access as ts.PropertyAccessExpression).name.text;
|
||||
const value = entries.get(member);
|
||||
if (value === undefined || shadowed(access, table.entries)) return loaderWhy;
|
||||
// The rewrite reads the export without the namespace object, so a
|
||||
// call through it (`L().fn()`) loses its receiver.
|
||||
if (calledWithReceiver(access as ts.Expression) && !receiverHidden(entries, member))
|
||||
return loaderWhy;
|
||||
const init = initCall === null ? "" : `${initCall.getText(sf)}, `;
|
||||
edits.push({
|
||||
start: access.getStart(sf),
|
||||
end: access.getEnd(),
|
||||
text: `(${init}${getterText(value)})`,
|
||||
});
|
||||
}
|
||||
deadDeclarators.add(d);
|
||||
deadDeclarators.add(memoDecl);
|
||||
loaderSpans.push({ start: d.getStart(sf), end: d.getEnd() });
|
||||
lowered.add(target);
|
||||
}
|
||||
|
||||
for (const r of allRefs) {
|
||||
const table = tables.get(r.text);
|
||||
if (table === undefined) continue;
|
||||
if (loaderSpans.some((span) => r.getStart(sf) >= span.start && r.getEnd() <= span.end))
|
||||
continue;
|
||||
const p = r.parent;
|
||||
// The table's own declaration and __export call are handled below.
|
||||
if (p !== undefined && ts.isVariableDeclaration(p) && p.name === r) continue;
|
||||
if (
|
||||
p !== undefined &&
|
||||
ts.isCallExpression(p) &&
|
||||
p.arguments.nodes[0] === r &&
|
||||
ts.isExpressionStatement(p.parent) &&
|
||||
p.parent === table.stmt
|
||||
)
|
||||
continue;
|
||||
const why = `reads the namespace of a bundled ES module ('${r.text}') in a way the static rewrite cannot follow (only member reads of its exports compile, and calls only of exported functions that do not read 'this')`;
|
||||
if (
|
||||
p === undefined ||
|
||||
!ts.isCallExpression(p) ||
|
||||
!ts.isIdentifier(p.expression) ||
|
||||
helperBase(p.expression.text) !== "__toCommonJS" ||
|
||||
p.arguments.nodes.length !== 1
|
||||
)
|
||||
return { degrade: `its shipped JS ${why}` };
|
||||
// The namespace expression: `(init_x(), __toCommonJS(T))` or the call.
|
||||
let ns: ts.Expression = p;
|
||||
for (;;) {
|
||||
const up = ns.parent;
|
||||
if (up !== undefined && ts.isParenthesizedExpression(up)) ns = up;
|
||||
else if (
|
||||
up !== undefined &&
|
||||
ts.isBinaryExpression(up) &&
|
||||
up.operatorToken.kind === ts.SyntaxKind.CommaToken &&
|
||||
up.right === ns
|
||||
)
|
||||
ns = up;
|
||||
else break;
|
||||
}
|
||||
const values = new Map(table.entries);
|
||||
const memberRead = (access: ts.Node | undefined, of: ts.Node): boolean =>
|
||||
access !== undefined &&
|
||||
ts.isPropertyAccessExpression(access) &&
|
||||
access.expression === of &&
|
||||
values.has(access.name.text) &&
|
||||
plainRead(access) &&
|
||||
(!calledWithReceiver(access) || receiverHidden(values, access.name.text));
|
||||
const holder = ns.parent;
|
||||
// `__reExport(main, ns, module.exports)`: a star re-export of the
|
||||
// module into the bundle's own exports (`export * from` in its entry).
|
||||
// The initializer runs at the statement; the names become live getter
|
||||
// entries of the export table, after its explicit ones (first wins)
|
||||
// and without `default`, exactly the names __reExport copies.
|
||||
if (
|
||||
holder !== undefined &&
|
||||
ts.isCallExpression(holder) &&
|
||||
ts.isIdentifier(holder.expression) &&
|
||||
helperBase(holder.expression.text) === "__reExport" &&
|
||||
holder.arguments.nodes[1] === ns &&
|
||||
holder.arguments.nodes.length <= 3 &&
|
||||
ts.isExpressionStatement(holder.parent) &&
|
||||
mainTarget !== null &&
|
||||
ts.isIdentifier(holder.arguments.nodes[0]!) &&
|
||||
(holder.arguments.nodes[0] as ts.Identifier).text === mainTarget
|
||||
) {
|
||||
const inner = unparen(ns);
|
||||
const init =
|
||||
ts.isBinaryExpression(inner) && inner.operatorToken.kind === ts.SyntaxKind.CommaToken
|
||||
? `${unparen(inner.left).getText(sf)}; `
|
||||
: "";
|
||||
if (shadowed(holder, table.entries)) return { degrade: `its shipped JS ${why}` };
|
||||
const entries = table.entries
|
||||
.filter(([n]) => n !== "default")
|
||||
.map(([n, value]) => `${JSON.stringify(n)}: () => ${getterText(value)}`)
|
||||
.join(", ");
|
||||
edits.push({
|
||||
start: holder.parent.getStart(sf),
|
||||
end: holder.parent.getEnd(),
|
||||
text: `${init}__export(${mainTarget}, { ${entries} });`,
|
||||
});
|
||||
lowered.add(r.text);
|
||||
continue;
|
||||
}
|
||||
let readable = memberRead(holder, ns);
|
||||
if (
|
||||
!readable &&
|
||||
holder !== undefined &&
|
||||
ts.isVariableDeclaration(holder) &&
|
||||
holder.initializer === ns &&
|
||||
ts.isIdentifier(holder.name)
|
||||
) {
|
||||
const local = holder.name.text;
|
||||
const localRefs = (refsByName.get(local) ?? []).filter((x) => x !== holder.name);
|
||||
readable =
|
||||
countDeclarations(sf, local) === 1 &&
|
||||
!writes.has(local) &&
|
||||
localRefs.every((x) => memberRead(x.parent, x));
|
||||
}
|
||||
if (!readable) {
|
||||
// A namespace kept for later (`x ??= __toESM(ns)`, a hand-rolled
|
||||
// lazy loader) is a value with no static representation.
|
||||
let outer: ts.Node | undefined = holder;
|
||||
while (
|
||||
outer !== undefined &&
|
||||
(ts.isParenthesizedExpression(outer) ||
|
||||
(ts.isCallExpression(outer) &&
|
||||
ts.isIdentifier(outer.expression) &&
|
||||
helperBase(outer.expression.text) === "__toESM"))
|
||||
)
|
||||
outer = outer.parent;
|
||||
if (
|
||||
outer !== undefined &&
|
||||
ts.isBinaryExpression(outer) &&
|
||||
outer.operatorToken.kind >= ts.SyntaxKind.FirstAssignment &&
|
||||
outer.operatorToken.kind <= ts.SyntaxKind.LastAssignment
|
||||
)
|
||||
return {
|
||||
degrade: `its shipped JS stores the namespace of a bundled ES module ('${r.text}') in a variable (a memoized lazy loader), a module object the static rewrite cannot represent`,
|
||||
};
|
||||
return { degrade: `its shipped JS ${why}` };
|
||||
}
|
||||
// The getters read top-level bindings: nothing between the use site
|
||||
// and the top level may rebind one of their names.
|
||||
if (shadowed(p, table.entries)) return { degrade: `its shipped JS ${why}` };
|
||||
const getters = table.entries
|
||||
.map(
|
||||
([n, value]) =>
|
||||
`get ${/^[A-Za-z_$][\w$]*$/.test(n) ? n : JSON.stringify(n)}() { return ${getterText(value)}; }`,
|
||||
)
|
||||
.join(", ");
|
||||
edits.push({ start: p.getStart(sf), end: p.getEnd(), text: `{ ${getters} }` });
|
||||
lowered.add(r.text);
|
||||
}
|
||||
// A table nothing reads (its module is never required) goes too: its
|
||||
// names are no exports of the bundle.
|
||||
for (const [target, table] of tables) {
|
||||
if (lowered.has(target)) continue;
|
||||
const live = (refsByName.get(target) ?? []).some((x) => {
|
||||
const p = x.parent;
|
||||
if (p !== undefined && ts.isVariableDeclaration(p) && p.name === x) return false;
|
||||
return !(x.getStart(sf) >= table.stmt.getStart(sf) && x.getEnd() <= table.stmt.getEnd());
|
||||
});
|
||||
if (!live) lowered.add(target);
|
||||
}
|
||||
for (const target of lowered) {
|
||||
const table = tables.get(target)!;
|
||||
const decl = top.get(target)?.node;
|
||||
if (
|
||||
decl === undefined ||
|
||||
!ts.isVariableDeclaration(decl) ||
|
||||
decl.initializer === undefined ||
|
||||
!ts.isObjectLiteralExpression(unparen(decl.initializer)) ||
|
||||
(unparen(decl.initializer) as ts.ObjectLiteralExpression).properties.nodes.length !== 0 ||
|
||||
writes.has(target)
|
||||
)
|
||||
return { degrade: ESM_SHAPE_DEGRADE };
|
||||
edits.push({ start: table.stmt.getStart(sf), end: table.stmt.getEnd(), text: "" });
|
||||
deadDeclarators.add(decl);
|
||||
}
|
||||
// Every removed declarator in one pass: declarators of one statement
|
||||
// removed separately would leave overlapping edits, and applyEdits keeps
|
||||
// only the first of them.
|
||||
edits.push(...removeDeclarators(sf, deadDeclarators));
|
||||
|
||||
/* The run-once closures. */
|
||||
for (const init of inits.values()) {
|
||||
const { call, body } = init;
|
||||
edits.push(
|
||||
{
|
||||
start: call.getStart(sf),
|
||||
end: body.getStart(sf) + 1,
|
||||
text: "(() => { let __scriptc_done = false; function __scriptc_init() {",
|
||||
},
|
||||
{
|
||||
start: body.getEnd() - 1,
|
||||
end: call.getEnd(),
|
||||
text: "} return function () { if (__scriptc_done) return; __scriptc_done = true; __scriptc_init(); }; })()",
|
||||
},
|
||||
);
|
||||
}
|
||||
return applyEdits(source, 0, source.length, edits);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterAll, expect, test } from "vitest";
|
||||
import { nodeFrontendServices } from "./services-node.js";
|
||||
|
||||
const dirs: string[] = [];
|
||||
afterAll(() => {
|
||||
for (const dir of dirs) rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function rewrite(source: string): string | null {
|
||||
return nodeFrontendServices().cjsFunctionExports(source, "/pkg/index.js");
|
||||
}
|
||||
|
||||
function run(file: string) {
|
||||
const result = spawnSync(process.execPath, [file], { encoding: "utf8" });
|
||||
return { status: result.status, stdout: result.stdout, stderr: result.stderr };
|
||||
}
|
||||
|
||||
/** The rewritten module prints what the original prints. */
|
||||
function expectSameBehavior(source: string): string {
|
||||
const result = rewrite(source);
|
||||
expect(typeof result).toBe("string");
|
||||
const dir = mkdtempSync(join(tmpdir(), "scriptc-cjs-function-exports-"));
|
||||
dirs.push(dir);
|
||||
const original = join(dir, "original.cjs");
|
||||
const rewritten = join(dir, "rewritten.cjs");
|
||||
writeFileSync(original, source);
|
||||
writeFileSync(rewritten, result as string);
|
||||
const oracle = run(original);
|
||||
expect(oracle.status).toBe(0);
|
||||
expect(run(rewritten)).toEqual(oracle);
|
||||
return result as string;
|
||||
}
|
||||
|
||||
const report = `
|
||||
console.log(typeof module.exports, module.exports === Version, Object.keys(Version).join(","));
|
||||
`;
|
||||
|
||||
test("members of a function export object read and write the function", () => {
|
||||
const rewritten = expectSameBehavior(`exports = module.exports = Version;
|
||||
exports.parse = parse;
|
||||
module.exports.major = (v) => parse(v)[0];
|
||||
function Version(v) { return { v }; }
|
||||
function parse(v) { return v.split(".").map(Number); }
|
||||
console.log(exports.major("2.1.0"), module.exports.parse("1.2").length);
|
||||
${report}`);
|
||||
expect(rewritten).toContain("Version.parse = parse");
|
||||
expect(rewritten).not.toContain("exports = module.exports");
|
||||
});
|
||||
|
||||
test.each([
|
||||
["a parameter", "function inner(Version) { return exports.parse; }"],
|
||||
["a local", "function inner() { const Version = {}; return exports.parse; }"],
|
||||
["a nested function", "function inner() { function Version() {} return exports.parse; }"],
|
||||
[
|
||||
"a catch binding",
|
||||
"function inner() { try { throw 0; } catch (Version) { return exports.parse; } }",
|
||||
],
|
||||
])("a nested binding of the function's name (%s) keeps the module as it is", (_, inner) => {
|
||||
expect(
|
||||
rewrite(`exports = module.exports = Version;
|
||||
exports.parse = parse;
|
||||
function Version() {}
|
||||
function parse() {}
|
||||
${inner}
|
||||
`),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
test("an `exports` shorthand property keeps its key", () => {
|
||||
const rewritten = expectSameBehavior(`exports = module.exports = Version;
|
||||
exports.tag = "v";
|
||||
function Version() {}
|
||||
const holder = { exports };
|
||||
console.log(Object.keys(holder).join(","), holder.exports === Version, holder.exports.tag);
|
||||
${report}`);
|
||||
expect(rewritten).toContain("{ exports: Version }");
|
||||
});
|
||||
@@ -0,0 +1,191 @@
|
||||
/* CommonJS modules whose export object is one of their own functions:
|
||||
*
|
||||
* exports = module.exports = SemVer; // or module.exports = SemVer;
|
||||
* exports.parse = parse; // or module.exports.parse = …
|
||||
* function SemVer(version) { … }
|
||||
*
|
||||
* After that statement `module.exports` (and, after the rebinding form,
|
||||
* `exports`) IS the function, so every member read or write through them
|
||||
* is a member of the function itself. The pass respells those accesses
|
||||
* through the function's name, the expando form both resolvers model
|
||||
* (members on a function declaration), and drops the `exports =`
|
||||
* rebinding the static export protocol has no storage for.
|
||||
*
|
||||
* Exact only while nothing can observe the module before the statement
|
||||
* runs and nothing replaces the export object again: the statement is a
|
||||
* top-level statement preceded only by inert declarations, it is the
|
||||
* file's only write of `module.exports` and `exports`, the function is a
|
||||
* top-level declaration nothing reassigns and the file's only binding of
|
||||
* its name, and `exports`/`module` are the CommonJS globals (never
|
||||
* declared in the file). Other shapes answer
|
||||
* null and keep their existing treatment. */
|
||||
import * as ts from "./ts7/syntax.js";
|
||||
import {
|
||||
applyEdits,
|
||||
countDeclarations,
|
||||
declaredNames,
|
||||
isWritten,
|
||||
references,
|
||||
unparen,
|
||||
type Edit,
|
||||
} from "./npm-static-bundled-chunks.js";
|
||||
|
||||
function isModuleExports(e: ts.Expression): e is ts.PropertyAccessExpression {
|
||||
const x = unparen(e);
|
||||
return (
|
||||
ts.isPropertyAccessExpression(x) &&
|
||||
!x.questionDotToken &&
|
||||
ts.isIdentifier(x.expression) &&
|
||||
x.expression.text === "module" &&
|
||||
x.name.text === "exports"
|
||||
);
|
||||
}
|
||||
|
||||
/** True for a statement whose evaluation runs no code that could observe
|
||||
* the export object: declarations and member writes (`F.prototype.m =
|
||||
* function …`) without calls, and directives. */
|
||||
function inert(stmt: ts.Statement): boolean {
|
||||
if (ts.isFunctionDeclaration(stmt) || ts.isEmptyStatement(stmt)) return true;
|
||||
if (ts.isExpressionStatement(stmt) && ts.isStringLiteral(stmt.expression)) return true;
|
||||
if (ts.isExpressionStatement(stmt)) {
|
||||
const e = unparen(stmt.expression);
|
||||
if (
|
||||
!ts.isBinaryExpression(e) ||
|
||||
e.operatorToken.kind !== ts.SyntaxKind.EqualsToken ||
|
||||
!(ts.isPropertyAccessExpression(e.left) || ts.isElementAccessExpression(e.left))
|
||||
)
|
||||
return false;
|
||||
let root: ts.Expression = e.left;
|
||||
while (ts.isPropertyAccessExpression(root) || ts.isElementAccessExpression(root))
|
||||
root = root.expression;
|
||||
if (!ts.isIdentifier(root) || root.text === "module" || root.text === "exports") return false;
|
||||
} else if (!ts.isVariableStatement(stmt)) return false;
|
||||
let calls = false;
|
||||
ts.walkPreorder(stmt, (n) => {
|
||||
if (calls) return "stop";
|
||||
if (ts.isArrowFunction(n) || ts.isFunctionExpression(n)) return "skip";
|
||||
if (ts.isCallExpression(n) || ts.isNewExpression(n) || ts.isTaggedTemplateExpression(n))
|
||||
calls = true;
|
||||
return undefined;
|
||||
});
|
||||
return !calls;
|
||||
}
|
||||
|
||||
export function normalizeCjsFunctionExports(sf: ts.SourceFile): string | null {
|
||||
const source = sf.text;
|
||||
if (!source.includes("module.exports")) return null;
|
||||
if (!sf.fileName.endsWith(".cjs") && ts.isExternalModule(sf)) return null;
|
||||
const declared = declaredNames(sf);
|
||||
if (declared.has("exports") || declared.has("module")) return null;
|
||||
|
||||
// The whole-export statement: `[exports =] module.exports = W;`.
|
||||
let whole: { stmt: ts.ExpressionStatement; fn: string; rebinds: boolean } | null = null;
|
||||
const stmts = sf.statements.nodes;
|
||||
for (let i = 0; i < stmts.length; i++) {
|
||||
const stmt = stmts[i]!;
|
||||
if (!ts.isExpressionStatement(stmt)) continue;
|
||||
const top = unparen(stmt.expression);
|
||||
if (!ts.isBinaryExpression(top) || top.operatorToken.kind !== ts.SyntaxKind.EqualsToken)
|
||||
continue;
|
||||
let e: ts.BinaryExpression = top;
|
||||
let rebinds = false;
|
||||
if (ts.isIdentifier(top.left) && top.left.text === "exports") {
|
||||
const inner = unparen(top.right);
|
||||
if (!ts.isBinaryExpression(inner) || inner.operatorToken.kind !== ts.SyntaxKind.EqualsToken)
|
||||
continue;
|
||||
rebinds = true;
|
||||
e = inner;
|
||||
}
|
||||
if (!isModuleExports(e.left)) continue;
|
||||
const value = unparen(e.right);
|
||||
if (!ts.isIdentifier(value)) return null;
|
||||
if (whole !== null || !stmts.slice(0, i).every(inert)) return null;
|
||||
whole = { stmt, fn: value.text, rebinds };
|
||||
}
|
||||
if (whole === null) return null;
|
||||
const fnName = whole.fn;
|
||||
const fnDecls = stmts.filter(
|
||||
(st) => ts.isFunctionDeclaration(st) && st.name?.text === fnName && st.body !== undefined,
|
||||
);
|
||||
// The respelled reads name the function from wherever they sit, so no
|
||||
// other binding of its name (a parameter, a local, a nested function)
|
||||
// may exist anywhere in the file.
|
||||
if (fnDecls.length !== 1 || countDeclarations(sf, fnName) !== 1) return null;
|
||||
|
||||
const edits: Edit[] = [];
|
||||
let unsafe = false;
|
||||
const refs = references(sf);
|
||||
for (const r of refs) {
|
||||
if (r.text === fnName && isWritten(r)) unsafe = true;
|
||||
if (r.text === "exports") {
|
||||
if (isWritten(r)) {
|
||||
// Only the whole statement's own rebinding.
|
||||
const assign = r.parent;
|
||||
if (
|
||||
!whole.rebinds ||
|
||||
assign === undefined ||
|
||||
!ts.isBinaryExpression(assign) ||
|
||||
assign.parent !== whole.stmt ||
|
||||
assign.left !== r
|
||||
)
|
||||
unsafe = true;
|
||||
continue;
|
||||
}
|
||||
// Without the rebinding, `exports` keeps the replaced object.
|
||||
if (!whole.rebinds || r.getStart(sf) < whole.stmt.getEnd()) {
|
||||
unsafe = true;
|
||||
continue;
|
||||
}
|
||||
// `{ exports }` keeps its key: the shorthand spells out the value.
|
||||
const shorthand =
|
||||
r.parent !== undefined && ts.isShorthandPropertyAssignment(r.parent) && r.parent.name === r;
|
||||
edits.push({
|
||||
start: r.getStart(sf),
|
||||
end: r.getEnd(),
|
||||
text: shorthand ? `exports: ${fnName}` : fnName,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (r.text === "module") {
|
||||
const access = r.parent;
|
||||
if (access === undefined || !isModuleExports(access as ts.Expression)) continue;
|
||||
const outer = access.parent;
|
||||
if (outer !== undefined && ts.isBinaryExpression(outer) && outer.left === access) {
|
||||
if (
|
||||
outer.operatorToken.kind >= ts.SyntaxKind.FirstAssignment &&
|
||||
outer.operatorToken.kind <= ts.SyntaxKind.LastAssignment &&
|
||||
!(
|
||||
(outer.parent === whole.stmt && !whole.rebinds) ||
|
||||
(whole.rebinds && outer.parent?.parent === whole.stmt)
|
||||
)
|
||||
)
|
||||
unsafe = true;
|
||||
continue;
|
||||
}
|
||||
// A member access through module.exports: a member of the function.
|
||||
if (
|
||||
outer !== undefined &&
|
||||
(ts.isPropertyAccessExpression(outer) || ts.isElementAccessExpression(outer)) &&
|
||||
outer.expression === access
|
||||
) {
|
||||
if (access.getStart(sf) < whole.stmt.getEnd() && !insideFunction(access)) unsafe = true;
|
||||
edits.push({ start: access.getStart(sf), end: access.getEnd(), text: fnName });
|
||||
}
|
||||
}
|
||||
}
|
||||
if (unsafe) return null;
|
||||
if (whole.rebinds) {
|
||||
// `exports = module.exports = W` → `module.exports = W`.
|
||||
const e = unparen(whole.stmt.expression) as ts.BinaryExpression;
|
||||
edits.push({ start: e.getStart(sf), end: unparen(e.right).getStart(sf), text: "" });
|
||||
}
|
||||
if (edits.length === 0) return null;
|
||||
return applyEdits(source, 0, source.length, edits);
|
||||
}
|
||||
|
||||
function insideFunction(node: ts.Node): boolean {
|
||||
for (let p = node.parent; p !== undefined && !ts.isSourceFile(p); p = p.parent) {
|
||||
if (ts.isFunctionLike(p)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
import { resolveExports } from "./resolve.js";
|
||||
import { packageNameOfSpecifier } from "./workspace-registry.js";
|
||||
import { isBundlerCjsCandidate, rewriteBundlerCjsSyntax } from "./npm-static-rewrite-syntax.js";
|
||||
import { lowerBundledEsmInits } from "./npm-static-bundled-esm.js";
|
||||
|
||||
const NODE_REQUIRE_CONDITIONS = new Set(["require", "node", "default"]);
|
||||
|
||||
@@ -164,15 +165,28 @@ function starTargetNames(parser: Ts7SourceParser, file: string): Set<string> {
|
||||
}
|
||||
}
|
||||
|
||||
export function lowerEsmInitsWithParser(
|
||||
parser: Ts7SourceParser,
|
||||
source: string,
|
||||
filePath: string,
|
||||
): string | { degrade: string } | null {
|
||||
if (!source.includes("__esm")) return null;
|
||||
return lowerBundledEsmInits(parser.parse(filePath, source, "js"), filePath, {
|
||||
requireTargetEsModuleStamped: (from, spec) => requireTargetEsModuleStamped(parser, from, spec),
|
||||
});
|
||||
}
|
||||
|
||||
export function rewriteBundlerCjsWithParser(
|
||||
parser: Ts7SourceParser,
|
||||
source: string,
|
||||
filePath: string,
|
||||
liveExportTable?: (filePath: string) => void,
|
||||
lexerVisibleNames?: (filePath: string, names: readonly string[]) => void,
|
||||
): string | { degrade: string } | null {
|
||||
if (!isBundlerCjsCandidate(source)) return null;
|
||||
return rewriteBundlerCjsSyntax(parser.parse(filePath, source, "js"), filePath, {
|
||||
liveExportTable,
|
||||
lexerVisibleNames,
|
||||
requireOnly: isVirtualSource,
|
||||
requireTargetEsModuleStamped: (from, spec) => requireTargetEsModuleStamped(parser, from, spec),
|
||||
starTargetNames: (from, spec) => {
|
||||
|
||||
@@ -22,6 +22,9 @@ export interface CjsRewriteHost {
|
||||
* exists, so Node's lexer-visible name set bounds nothing and every
|
||||
* name the export plumbing defines is part of its surface. */
|
||||
requireOnly?: ((filePath: string) => boolean) | undefined;
|
||||
/** Told the names Node's lexer detects in the original file that the
|
||||
* rewritten text spells only as accessors (which the lexer skips). */
|
||||
lexerVisibleNames?: ((filePath: string, names: readonly string[]) => void) | undefined;
|
||||
}
|
||||
|
||||
/** True when esbuild's export object (`module.exports = __toCommonJS(T)`
|
||||
@@ -119,8 +122,12 @@ interface EntrySpec {
|
||||
name: string;
|
||||
/** "ident": VALUE is a plain identifier spelled directly in the table.
|
||||
* "hoist": VALUE is an expression text hoisted to a tail const first.
|
||||
* "getter": VALUE is a getter body's returned expression the table
|
||||
* keeps as a live accessor (read on every access, like the original
|
||||
* getter, so a lazily initialized module still initializes at the
|
||||
* first read).
|
||||
* "any": the checked-dynamic fallback (`__scriptc_any`). */
|
||||
kind: "ident" | "hoist" | "any";
|
||||
kind: "ident" | "hoist" | "getter" | "any";
|
||||
value?: string;
|
||||
}
|
||||
|
||||
@@ -760,7 +767,14 @@ export function rewriteBundlerCjsSyntax(
|
||||
...exportTables.filter((t) => t.target !== esbuildMainTarget),
|
||||
];
|
||||
for (const t of tablesOrdered) {
|
||||
for (const [name, value] of t.entries) claim(name, classify(name, value));
|
||||
for (const [name, value] of t.entries) {
|
||||
const spec = classify(name, value);
|
||||
// The table feeding module.exports keeps a getter it cannot chase
|
||||
// as a live accessor rather than a snapshot.
|
||||
if (spec.kind === "any" && value !== null && t.target === esbuildMainTarget)
|
||||
claim(name, { name, kind: "getter", value: value.getText() });
|
||||
else claim(name, spec);
|
||||
}
|
||||
}
|
||||
for (const d of definePropEntries) claim(d.name, classify(d.name, d.value));
|
||||
|
||||
@@ -893,6 +907,7 @@ export function rewriteBundlerCjsSyntax(
|
||||
"__toESM",
|
||||
"__toCommonJS",
|
||||
"__commonJS",
|
||||
"__esm",
|
||||
"__exportStar",
|
||||
"__createBinding",
|
||||
"__setModuleDefault",
|
||||
@@ -1038,6 +1053,8 @@ export function rewriteBundlerCjsSyntax(
|
||||
const v = `__scriptc_e${hoistN++}`;
|
||||
hoists.push(`const ${v} = ${dropInteropDefault(spec.value!)};`);
|
||||
plainParts.push(`${keyOf(spec.name)}: ${v},`);
|
||||
} else if (spec.kind === "getter") {
|
||||
plainParts.push(`get ${keyOf(spec.name)}() { return ${dropInteropDefault(spec.value!)}; },`);
|
||||
} else {
|
||||
plainParts.push(`${keyOf(spec.name)}: __scriptc_any,`);
|
||||
}
|
||||
@@ -1063,5 +1080,12 @@ export function rewriteBundlerCjsSyntax(
|
||||
lines.push(
|
||||
`module.exports = {${spreadParts.join("")}${plainParts.join("")}${esModulePart}${memberParts.join("")}};`,
|
||||
);
|
||||
/* Node's lexer skips accessors (and stops reading an object literal at
|
||||
* the first one), so a canonical table with accessor entries hides
|
||||
* names the original showed it (esbuild's dead annotation): the host
|
||||
* keeps the original's lexer answer, so ES-module importers link
|
||||
* exactly as they do against the original. */
|
||||
if ([...entries.values()].some((spec) => spec.kind === "getter"))
|
||||
host.lexerVisibleNames?.(filePath, [...lexed.exports]);
|
||||
return text + lines.join("\n") + "\n";
|
||||
}
|
||||
|
||||
@@ -43,6 +43,14 @@ export function npmStaticLiveExportTable(path: string): boolean {
|
||||
return liveExportFiles.has(path.split("\\").join("/"));
|
||||
}
|
||||
|
||||
/** Names Node's lexer detects in a rewritten file's original text that
|
||||
* its rewrite spells only as accessors (the lexer skips those). */
|
||||
const lexerNames = new Map<string, readonly string[]>();
|
||||
|
||||
export function npmStaticLexerVisibleNames(path: string): readonly string[] {
|
||||
return lexerNames.get(path.split("\\").join("/")) ?? [];
|
||||
}
|
||||
|
||||
export function setNpmStaticPackages<T extends Iterable<string>>(packages: T): void {
|
||||
activePackages = new Set(packages);
|
||||
declarationOverloads = new Map();
|
||||
@@ -51,9 +59,11 @@ export function setNpmStaticPackages<T extends Iterable<string>>(packages: T): v
|
||||
fileDegrades.clear();
|
||||
rewriteCache.clear();
|
||||
liveExportFiles.clear();
|
||||
lexerNames.clear();
|
||||
clearVirtualSources();
|
||||
untypedPkgCache.clear();
|
||||
realpathProbed.clear();
|
||||
aliasNames.clear();
|
||||
}
|
||||
|
||||
export function setNpmStaticDeclarationOverloads(
|
||||
@@ -168,9 +178,32 @@ function shadowTargetOf(path: string): { pkg: string; viaTypes: boolean } | null
|
||||
if (mangledTypesName(pkg) === mangled) return { pkg, viaTypes: true };
|
||||
}
|
||||
}
|
||||
// An npm alias (`"x-updated": "npm:x@6.3.0"`) installs the package under
|
||||
// another directory name: its own manifest names the package.
|
||||
const aliased = aliasedPackageName(`${norm.slice(0, idx)}/node_modules/${dirName}`);
|
||||
if (aliased !== null && aliased !== dirName && activePackages.has(aliased))
|
||||
return { pkg: aliased, viaTypes: false };
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The "name" a node_modules directory's own package.json declares, or
|
||||
* null (cached per load). */
|
||||
const aliasNames = new Map<string, string | null>();
|
||||
function aliasedPackageName(pkgDir: string): string | null {
|
||||
const hit = aliasNames.get(pkgDir);
|
||||
if (hit !== undefined) return hit;
|
||||
let name: string | null = null;
|
||||
try {
|
||||
const text = trackedReadFile(`${pkgDir}/package.json`);
|
||||
const declared = text === null ? undefined : (JSON.parse(text) as { name?: unknown }).name;
|
||||
if (typeof declared === "string") name = declared;
|
||||
} catch {
|
||||
name = null;
|
||||
}
|
||||
aliasNames.set(pkgDir, name);
|
||||
return name;
|
||||
}
|
||||
|
||||
/** The opted-in package.json transform, applied identically in BOTH
|
||||
* resolution worlds (the tsgo host's fs shadow and resolve.ts):
|
||||
* 1. every types claim goes — the top-level "types"/"typings" fields
|
||||
@@ -407,6 +440,19 @@ export function npmStaticFsShadow(services: FrontendServices): NpmStaticFsShadow
|
||||
for (const chunk of split.chunks) setVirtualSource(chunk.path, chunk.source);
|
||||
original = split.text;
|
||||
}
|
||||
// Then its lazily initialized ES modules become run-once closures.
|
||||
const esm = original === null ? null : services.lowerEsmInits(original, path);
|
||||
if (esm !== null && typeof esm === "object") {
|
||||
reportFileDegrade(path, target.pkg, esm.degrade);
|
||||
original = null;
|
||||
} else if (esm !== null) {
|
||||
original = esm;
|
||||
}
|
||||
// A module exporting one of its functions reaches its members
|
||||
// through that function.
|
||||
const fnExports = original === null ? null : services.cjsFunctionExports(original, path);
|
||||
if (fnExports !== null) original = fnExports;
|
||||
const respelled = split !== null || esm !== null || fnExports !== null;
|
||||
if (original !== null) {
|
||||
const namepaths = services.jsDocNamepaths(path, original);
|
||||
const source = namepaths ?? original;
|
||||
@@ -430,6 +476,7 @@ export function npmStaticFsShadow(services: FrontendServices): NpmStaticFsShadow
|
||||
source,
|
||||
path,
|
||||
(live) => liveExportFiles.add(live.split("\\").join("/")),
|
||||
(file, names) => lexerNames.set(file.split("\\").join("/"), names),
|
||||
);
|
||||
if (answer !== null && typeof answer === "object") {
|
||||
reportFileDegrade(path, target.pkg, answer.degrade);
|
||||
@@ -441,7 +488,7 @@ export function npmStaticFsShadow(services: FrontendServices): NpmStaticFsShadow
|
||||
findWidened?.text ??
|
||||
classFields?.text ??
|
||||
namepaths ??
|
||||
(split !== null ? original : null);
|
||||
(respelled ? original : null);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
@@ -492,6 +539,20 @@ function hasTransformMarkers(source: string): boolean {
|
||||
return TRANSFORM_MARKERS.some((m) => source.includes(m));
|
||||
}
|
||||
|
||||
/** Why the declarations at `typesFile` cannot stand for the runtime
|
||||
* package `pkg`, or null when they are its DefinitelyTyped twin
|
||||
* (`@types/<mangled pkg>`). The declarations only check the importing
|
||||
* program; the JavaScript compiles with its inferred types, and an
|
||||
* inferred surface the program does not typecheck against refuses the
|
||||
* package afterwards, whatever release the twin describes. */
|
||||
export function definitelyTypedMismatch(pkg: string, typesFile: string): string | null {
|
||||
const owner = npmPackageNameOf(typesFile.split("\\").join("/"));
|
||||
const twin = `@types/${mangledTypesName(pkg)}`;
|
||||
return owner === twin
|
||||
? null
|
||||
: `its declared types come from ${owner ?? typesFile}, which is not ${pkg}'s DefinitelyTyped package ${twin}`;
|
||||
}
|
||||
|
||||
/** Auto-mode eligibility for one candidate package: `typesFile` is what
|
||||
* the ordinary (types-first) resolution answered for the import,
|
||||
* `jsEntry` what the js-only resolution answers. Returns null when
|
||||
@@ -500,12 +561,17 @@ export function npmStaticIneligibleReason(
|
||||
pkgName: string,
|
||||
typesFile: string,
|
||||
jsEntry: string | null,
|
||||
/** A dependency another package's JavaScript imports: no declarations
|
||||
* check that importer, so the package need not ship its own. */
|
||||
untypedDependency = false,
|
||||
): string | null {
|
||||
if (npmPackageNameOf(typesFile) !== pkgName) {
|
||||
return "its declared types come from a third-party @types package, not the package itself";
|
||||
}
|
||||
if (!/\.d\.(ts|mts|cts)$/.test(typesFile)) {
|
||||
return "it ships no own .d.ts declaration surface";
|
||||
if (!untypedDependency) {
|
||||
if (npmPackageNameOf(typesFile) !== pkgName) {
|
||||
return "its declared types come from a third-party @types package, not the package itself";
|
||||
}
|
||||
if (!/\.d\.(ts|mts|cts)$/.test(typesFile)) {
|
||||
return "it ships no own .d.ts declaration surface";
|
||||
}
|
||||
}
|
||||
if (jsEntry === null) return "no runtime JS entry resolves";
|
||||
const source = trackedReadFile(jsEntry);
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
type LoadResult,
|
||||
} from "./program.js";
|
||||
import {
|
||||
definitelyTypedMismatch,
|
||||
npmStaticFileDegrades,
|
||||
npmStaticIneligibleReason,
|
||||
npmStaticOffenders,
|
||||
@@ -219,13 +220,26 @@ function detectAutoPackages(
|
||||
chosen.push(runtimePkg);
|
||||
continue;
|
||||
}
|
||||
// Both answers compile the JavaScript with inferred types; the
|
||||
// declarations only check the importer, and an inferred surface
|
||||
// the program does not typecheck against still refuses the package
|
||||
// below. A DefinitelyTyped twin qualifies; a package without
|
||||
// declarations qualifies as a dependency of another package, whose
|
||||
// JavaScript importer has no declarations to check.
|
||||
const refusal =
|
||||
npm === null
|
||||
? owner === null && !sf.fileName.includes("/node_modules/")
|
||||
? "it ships no own .d.ts declaration surface"
|
||||
: null
|
||||
: definitelyTypedMismatch(runtimePkg, npm.typesFile);
|
||||
if (refusal === null) {
|
||||
chosen.push(runtimePkg);
|
||||
continue;
|
||||
}
|
||||
statuses.push({
|
||||
package: runtimePkg,
|
||||
status: "refused",
|
||||
detail:
|
||||
npm === null
|
||||
? "it ships no own .d.ts declaration surface"
|
||||
: `its declared types come from the separate ${npm.packageName} package, not the package itself`,
|
||||
detail: refusal,
|
||||
hint: npmStaticOptInHint(runtimePkg, owner),
|
||||
});
|
||||
continue;
|
||||
@@ -256,6 +270,7 @@ function detectAutoPackages(
|
||||
pkg,
|
||||
typesFile,
|
||||
jsEntry !== null && isJsSourceFileName(jsEntry.typesFile) ? jsEntry.typesFile : null,
|
||||
mode === "lib" && isJsSourceFileName(typesFile) && fromFile.includes("/node_modules/"),
|
||||
);
|
||||
if (reason === null) chosen.push(pkg);
|
||||
else
|
||||
|
||||
@@ -68,6 +68,7 @@ import {
|
||||
isNpmStaticPackage,
|
||||
npmStaticActive,
|
||||
npmStaticFsShadow,
|
||||
npmStaticLexerVisibleNames,
|
||||
npmStaticLiveExportTable,
|
||||
npmStaticPackageOfPath,
|
||||
reportNpmStaticOffender,
|
||||
@@ -5520,12 +5521,18 @@ function cjsNamedImportLinkCheck(
|
||||
npmStaticDepSf7(program, from, spec, "require");
|
||||
return dep !== null && isCjsJsFile7(dep, program) ? dep : null;
|
||||
};
|
||||
// A bundler rewrite spells some lexer-visible names as accessors.
|
||||
const lexWithAccessorNames = (sf: ts.SourceFile): ReturnType<typeof cjsLexedExportsOfFile> => {
|
||||
const lexed = cjsLexedExportsOfFile(sf);
|
||||
for (const name of npmStaticLexerVisibleNames(sf.fileName)) lexed.exports.add(name);
|
||||
return lexed;
|
||||
};
|
||||
const visible = (dep: ts.SourceFile, name: string): boolean =>
|
||||
// `default` is the module.exports binding itself — always provided.
|
||||
// The program already owns native source ASTs; reuse them without
|
||||
// starting another syntax session or reparsing their source text.
|
||||
name === "default" ||
|
||||
cjsVisibleNames(dep, cjsLexedExportsOfFile, resolveCjsDep, lexMemo).has(name);
|
||||
cjsVisibleNames(dep, lexWithAccessorNames, resolveCjsDep, lexMemo).has(name);
|
||||
|
||||
/** The statement's resolved LOCAL CommonJS dependency, when it is an
|
||||
* import/re-export from one. */
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
import { dirname, isAbsolute, join, resolve } from "node:path";
|
||||
import {
|
||||
isNpmStaticPackage,
|
||||
npmStaticActive,
|
||||
npmStaticPackageOfPath,
|
||||
npmStaticTransformPkgJson,
|
||||
} from "./npm-static.js";
|
||||
@@ -868,7 +869,11 @@ export function resolveBareModule(
|
||||
// never consulted — mirroring the shadowed world the tsgo host serves.
|
||||
const runtimeImport = mode === "runtime-js" || mode === "runtime-source";
|
||||
const npmStatic =
|
||||
mode === "js-only" || (!runtimeImport && mode !== "types-only" && isNpmStaticPackage(pkgName));
|
||||
mode === "js-only" ||
|
||||
(!runtimeImport &&
|
||||
mode !== "types-only" &&
|
||||
(isNpmStaticPackage(pkgName) ||
|
||||
(npmStaticActive() && isNpmStaticPackage(aliasedPackageOf(fromFile, pkgName)))));
|
||||
const conditions = runtimeImport
|
||||
? RUNTIME_IMPORT_CONDITIONS
|
||||
: npmStatic
|
||||
@@ -970,6 +975,23 @@ export function resolveBareModule(
|
||||
return npmStatic ? passOnce("js") : (passOnce("types") ?? passOnce("js"));
|
||||
}
|
||||
|
||||
/** The package an npm alias directory installs (`"x-updated":
|
||||
* "npm:x@6.3.0"` puts package x under node_modules/x-updated): the name
|
||||
* the nearest node_modules/<dirName>/package.json declares when it
|
||||
* differs from the directory name, else null. */
|
||||
function aliasedPackageOf(fromFile: string, dirName: string): string | null {
|
||||
for (let dir = dirname(resolve(fromFile)); ;) {
|
||||
const pkgDir = join(dir, "node_modules", dirName);
|
||||
if (isDirectory(pkgDir)) {
|
||||
const name = pkgJsonOf(pkgDir)?.name;
|
||||
return typeof name === "string" && name !== dirName ? name : null;
|
||||
}
|
||||
const parent = dirname(dir);
|
||||
if (parent === dir) return null;
|
||||
dir = parent;
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveWorkspaceSourceModule(
|
||||
fromFile: string,
|
||||
specifier: string,
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { Ts7SourceParser, type Ts7SourceKind } from "./ts7/source-parser.js";
|
||||
import { Ts7Host, type Ts7ApiFactory, type Ts7HostOptions } from "./ts7/program-host.js";
|
||||
import { rewriteBundlerCjsWithParser } from "./npm-static-rewrite-host.js";
|
||||
import { lowerEsmInitsWithParser, rewriteBundlerCjsWithParser } from "./npm-static-rewrite-host.js";
|
||||
import { isBundlerCjsCandidate } from "./npm-static-rewrite-syntax.js";
|
||||
import { normalizeCjsFunctionExports } from "./npm-static-cjs-exports-alias.js";
|
||||
import {
|
||||
mayBundleChunks,
|
||||
splitBundledChunks,
|
||||
@@ -64,10 +65,17 @@ export class FrontendServices {
|
||||
source: string,
|
||||
path: string,
|
||||
liveExportTable?: (path: string) => void,
|
||||
lexerVisibleNames?: (path: string, names: readonly string[]) => void,
|
||||
): string | { degrade: string } | null {
|
||||
this.ensureOpen();
|
||||
if (!isBundlerCjsCandidate(source)) return null;
|
||||
return rewriteBundlerCjsWithParser(this.sourceParser(), source, path, liveExportTable);
|
||||
return rewriteBundlerCjsWithParser(
|
||||
this.sourceParser(),
|
||||
source,
|
||||
path,
|
||||
liveExportTable,
|
||||
lexerVisibleNames,
|
||||
);
|
||||
}
|
||||
/** A CommonJS bundle's __commonJS chunks as their own modules (null: no
|
||||
* chunks; a degrade reason: chunks the recognizer cannot move). */
|
||||
@@ -76,6 +84,21 @@ export class FrontendServices {
|
||||
if (!mayBundleChunks(source)) return null;
|
||||
return splitBundledChunks(this.parse(path, source, "js"), path);
|
||||
}
|
||||
/** A CommonJS bundle's lazily initialized ES modules (__esm) lowered to
|
||||
* run-once closures (null: none; a degrade reason: shapes the rewrite
|
||||
* cannot lower). */
|
||||
lowerEsmInits(source: string, path: string): string | { degrade: string } | null {
|
||||
this.ensureOpen();
|
||||
if (!source.includes("__esm")) return null;
|
||||
return lowerEsmInitsWithParser(this.sourceParser(), source, path);
|
||||
}
|
||||
/** A CommonJS module whose export object is one of its functions, with
|
||||
* its member accesses respelled through that function (null: none). */
|
||||
cjsFunctionExports(source: string, path: string): string | null {
|
||||
this.ensureOpen();
|
||||
if (!source.includes("module.exports")) return null;
|
||||
return normalizeCjsFunctionExports(this.parse(path, source, "js"));
|
||||
}
|
||||
nullableClassFields(path: string, source: string): syntax.NpmStaticOverloadRewrite | null {
|
||||
return syntax.applyNpmStaticNullableClassFields(this.parse(path, source, "js"), source);
|
||||
}
|
||||
|
||||
@@ -19,13 +19,22 @@ import { SyntaxKind, NodeFlags } from "./enums.js";
|
||||
/** A list of child nodes with the list's own position, the shape of tsc-ts's
|
||||
* NodeList. The file keeps the nodes array, not this object: each read of a
|
||||
* list field returns a new AstNodeList over the same array, so `nodes` keeps
|
||||
* its identity and a decoded file holds no list objects. */
|
||||
* its identity and a decoded file holds no list objects. The position is
|
||||
* decoded from the wire when it is read; most readers only use `nodes`. */
|
||||
export class AstNodeList<T extends AstNode = AstNode> {
|
||||
constructor(
|
||||
readonly pos: number,
|
||||
readonly end: number,
|
||||
private readonly wire: AstWireFile,
|
||||
private readonly index: number,
|
||||
readonly nodes: readonly T[],
|
||||
) {}
|
||||
|
||||
get pos(): number {
|
||||
return this.wire.pos(this.index) >>> 0;
|
||||
}
|
||||
|
||||
get end(): number {
|
||||
return this.wire.end(this.index) >>> 0;
|
||||
}
|
||||
}
|
||||
|
||||
/** One immutable AST response owns one object per node and one array per
|
||||
@@ -83,7 +92,7 @@ export class AstFile {
|
||||
this.lists[index] = nodes;
|
||||
this.materialized?.();
|
||||
}
|
||||
return new AstNodeList(this.wire.pos(index) >>> 0, this.wire.end(index) >>> 0, nodes);
|
||||
return new AstNodeList(this.wire, index, nodes);
|
||||
}
|
||||
|
||||
namedChild(node: AstNode, name: string): number {
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, expect, test } from "vitest";
|
||||
import { checkerBackend, tscTsExecutable, tscTsPlatformPackage } from "./checker-backend.js";
|
||||
|
||||
const roots: string[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function tempRoot(): string {
|
||||
const root = realpathSync(mkdtempSync(join(tmpdir(), "scriptc-checker-")));
|
||||
roots.push(root);
|
||||
return root;
|
||||
}
|
||||
|
||||
function writePackage(directory: string, name: string, executable?: string): void {
|
||||
mkdirSync(directory, { recursive: true });
|
||||
writeFileSync(join(directory, "package.json"), JSON.stringify({ name }));
|
||||
if (executable === undefined) return;
|
||||
mkdirSync(join(directory, "lib"), { recursive: true });
|
||||
writeFileSync(join(directory, "lib", executable), "");
|
||||
}
|
||||
|
||||
test("tsc-ts is the default checker except on Windows, and SCRIPTC_CHECKER selects one", () => {
|
||||
expect(checkerBackend({}, "linux")).toBe("tsc-ts");
|
||||
expect(checkerBackend({ SCRIPTC_CHECKER: "" }, "linux")).toBe("tsc-ts");
|
||||
expect(checkerBackend({}, "darwin")).toBe("tsc-ts");
|
||||
expect(checkerBackend({}, "win32")).toBe("tsgo");
|
||||
expect(checkerBackend({ SCRIPTC_CHECKER: "" }, "win32")).toBe("tsgo");
|
||||
expect(checkerBackend({ SCRIPTC_CHECKER: "tsc-ts" }, "linux")).toBe("tsc-ts");
|
||||
expect(checkerBackend({ SCRIPTC_CHECKER: "tsc-ts" }, "win32")).toBe("tsc-ts");
|
||||
expect(checkerBackend({ SCRIPTC_CHECKER: "tsgo" }, "linux")).toBe("tsgo");
|
||||
expect(() => checkerBackend({ SCRIPTC_CHECKER: "tsc" })).toThrow(
|
||||
'SCRIPTC_CHECKER must be tsgo or tsc-ts, not "tsc"',
|
||||
);
|
||||
});
|
||||
|
||||
test("tsc-ts platform packages are named for the host", () => {
|
||||
expect(tscTsPlatformPackage("linux", "x64", false)).toBe("@tsc-ts/linux-x64-gnu");
|
||||
expect(tscTsPlatformPackage("linux", "arm64", true)).toBe("@tsc-ts/linux-arm64-musl");
|
||||
expect(tscTsPlatformPackage("darwin", "arm64", false)).toBe("@tsc-ts/darwin-arm64");
|
||||
expect(tscTsPlatformPackage("win32", "x64", false)).toBe("@tsc-ts/win32-x64-msvc");
|
||||
});
|
||||
|
||||
test("the tsc-ts executable is found next to an npm install of tsc-ts", () => {
|
||||
const root = tempRoot();
|
||||
writePackage(join(root, "node_modules/tsc-ts"), "tsc-ts");
|
||||
writePackage(join(root, "node_modules/@tsc-ts/linux-x64-gnu"), "@tsc-ts/linux-x64-gnu", "tsc-ts");
|
||||
mkdirSync(join(root, "src/deep"), { recursive: true });
|
||||
expect(tscTsExecutable([join(root, "src/deep")], "@tsc-ts/linux-x64-gnu", "linux")).toBe(
|
||||
join(root, "node_modules/@tsc-ts/linux-x64-gnu/lib/tsc-ts"),
|
||||
);
|
||||
});
|
||||
|
||||
test("the tsc-ts executable is found in a pnpm install of tsc-ts", () => {
|
||||
const root = tempRoot();
|
||||
const store = join(root, "node_modules/.pnpm/tsc-ts@0.0.3/node_modules");
|
||||
writePackage(join(store, "tsc-ts"), "tsc-ts");
|
||||
writePackage(join(store, "@tsc-ts/win32-x64-msvc"), "@tsc-ts/win32-x64-msvc", "tsc-ts.exe");
|
||||
mkdirSync(join(root, "app/node_modules"), { recursive: true });
|
||||
symlinkSync(join(store, "tsc-ts"), join(root, "app/node_modules/tsc-ts"));
|
||||
expect(tscTsExecutable([join(root, "app")], "@tsc-ts/win32-x64-msvc", "win32")).toBe(
|
||||
join(store, "@tsc-ts/win32-x64-msvc/lib/tsc-ts.exe"),
|
||||
);
|
||||
});
|
||||
|
||||
test("a missing tsc-ts install or platform package is an error", () => {
|
||||
const root = tempRoot();
|
||||
expect(() => tscTsExecutable([root], "@tsc-ts/linux-x64-gnu", "linux")).toThrow(
|
||||
"the tsc-ts package is not installed",
|
||||
);
|
||||
writePackage(join(root, "node_modules/tsc-ts"), "tsc-ts");
|
||||
expect(() => tscTsExecutable([root], "@tsc-ts/linux-x64-gnu", "linux")).toThrow(
|
||||
"has no @tsc-ts/linux-x64-gnu executable",
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
import { existsSync, realpathSync, statSync } from "node:fs";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
/** The TypeScript 7 API servers a compile can check with: tsc-ts, the default,
|
||||
* and tsgo from the `typescript` package, selected with `SCRIPTC_CHECKER=tsgo`.
|
||||
* Both serve the same API and give the same results. On Windows the default is
|
||||
* tsgo: the compiler connects to the server over a named pipe there, and tsc-ts's
|
||||
* API server has no named-pipe transport yet. */
|
||||
export type CheckerBackend = "tsgo" | "tsc-ts";
|
||||
|
||||
export function checkerBackend(
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
platform: string = process.platform,
|
||||
): CheckerBackend {
|
||||
const value = env["SCRIPTC_CHECKER"];
|
||||
if (value === undefined || value === "") return platform === "win32" ? "tsgo" : "tsc-ts";
|
||||
if (value === "tsc-ts") return "tsc-ts";
|
||||
if (value === "tsgo") return "tsgo";
|
||||
throw new Error(`SCRIPTC_CHECKER must be tsgo or tsc-ts, not ${JSON.stringify(value)}`);
|
||||
}
|
||||
|
||||
/** tsc-ts's platform package for a host: `@tsc-ts/linux-x64-gnu`,
|
||||
* `@tsc-ts/darwin-arm64`, `@tsc-ts/win32-x64-msvc`, and so on. */
|
||||
export function tscTsPlatformPackage(
|
||||
platform: string,
|
||||
architecture: string,
|
||||
musl: boolean,
|
||||
): string {
|
||||
const abi =
|
||||
platform === "linux" ? (musl ? "-musl" : "-gnu") : platform === "win32" ? "-msvc" : "";
|
||||
return `@tsc-ts/${platform}-${architecture}${abi}`;
|
||||
}
|
||||
|
||||
let hostMusl: boolean | undefined;
|
||||
|
||||
/** Whether this process runs on musl, the libc of tsc-ts's `-musl` Linux packages: Node reports no glibc
|
||||
* runtime version there. The libc cannot change within a process, and a report is costly to generate. */
|
||||
export function hostIsMusl(): boolean {
|
||||
if (process.platform !== "linux") return false;
|
||||
if (hostMusl === undefined) {
|
||||
const report = process.report?.getReport() as
|
||||
| { header?: { glibcVersionRuntime?: unknown } }
|
||||
| undefined;
|
||||
hostMusl = typeof report?.header?.glibcVersionRuntime !== "string";
|
||||
}
|
||||
return hostMusl;
|
||||
}
|
||||
|
||||
/** The checker's part of an executable cache key: the identity of the tsc-ts
|
||||
* executable, or undefined for tsgo, whose keys predate the choice. */
|
||||
export function checkerCacheIdentity(env: NodeJS.ProcessEnv = process.env): string | undefined {
|
||||
if (checkerBackend(env) === "tsgo") return undefined;
|
||||
const path = hostTscTsExecutable();
|
||||
const info = statSync(path);
|
||||
return JSON.stringify({
|
||||
path,
|
||||
canonical: realpathSync(path),
|
||||
dev: info.dev,
|
||||
ino: info.ino,
|
||||
size: info.size,
|
||||
mtime: info.mtimeMs,
|
||||
ctime: info.ctimeMs,
|
||||
});
|
||||
}
|
||||
|
||||
/** The Node host's tsc-ts executable: that of the `tsc-ts` package installed
|
||||
* with this compiler, or else for the working directory. */
|
||||
export function hostTscTsExecutable(): string {
|
||||
return tscTsExecutable(
|
||||
[dirname(fileURLToPath(import.meta.url)), process.cwd()],
|
||||
tscTsPlatformPackage(process.platform, process.arch, hostIsMusl()),
|
||||
process.platform,
|
||||
);
|
||||
}
|
||||
|
||||
/** The tsc-ts executable of the `tsc-ts` package in the nearest
|
||||
* `node_modules` above each of `starts`, in order. The platform package is
|
||||
* installed next to `tsc-ts` (npm) or in the directory that holds it (pnpm). */
|
||||
export function tscTsExecutable(
|
||||
starts: readonly string[],
|
||||
platformPackage: string,
|
||||
platform: string,
|
||||
): string {
|
||||
const name = platform === "win32" ? "tsc-ts.exe" : "tsc-ts";
|
||||
for (const start of starts) {
|
||||
const packageRoot = installedPackage(start, "tsc-ts");
|
||||
if (packageRoot === undefined) continue;
|
||||
const root = realpathSync(packageRoot);
|
||||
for (const candidate of [
|
||||
join(root, "node_modules", platformPackage),
|
||||
join(dirname(root), platformPackage),
|
||||
]) {
|
||||
const executable = join(candidate, "lib", name);
|
||||
if (existsSync(executable)) return executable;
|
||||
}
|
||||
throw new Error(`tsc-ts checker: ${root} has no ${platformPackage} executable`);
|
||||
}
|
||||
throw new Error("tsc-ts checker: the tsc-ts package is not installed");
|
||||
}
|
||||
|
||||
function installedPackage(start: string, name: string): string | undefined {
|
||||
let directory = resolve(start);
|
||||
for (;;) {
|
||||
const candidate = join(directory, "node_modules", name);
|
||||
if (existsSync(join(candidate, "package.json"))) return candidate;
|
||||
const parent = dirname(directory);
|
||||
if (parent === directory) return undefined;
|
||||
directory = parent;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createRequire } from "node:module";
|
||||
import { dirname, join } from "node:path";
|
||||
import { Ts7Api as ConnectedTs7Api } from "./api.js";
|
||||
import { checkerBackend, hostTscTsExecutable } from "./checker-backend.js";
|
||||
import { Ts7RpcClient } from "./rpc-client.js";
|
||||
import { TS7_FILE_SYSTEM_CALLBACKS, type Ts7FileSystem } from "./rpc-filesystem.js";
|
||||
import { spawnTs7Wire } from "./rpc-process.js";
|
||||
@@ -12,8 +13,15 @@ const { default: getExePath } = require(join(packageRoot, "lib/getExePath.js"))
|
||||
};
|
||||
|
||||
/** Platform-package discovery and process creation remain at the host
|
||||
* boundary. The session itself uses no SDK implementation or Node process. */
|
||||
* boundary. The session itself uses no SDK implementation or Node process.
|
||||
* The executable is tsc-ts's (`hostTscTsExecutable`), or tsgo's with
|
||||
* `SCRIPTC_CHECKER=tsgo`. */
|
||||
export function ts7Executable(): string {
|
||||
return checkerBackend() === "tsgo" ? getExePath() : hostTscTsExecutable();
|
||||
}
|
||||
|
||||
/** tsgo's executable, from the `typescript` package, whichever checker compiles. */
|
||||
export function tsgoExecutable(): string {
|
||||
return getExePath();
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ import { API } from "typescript/unstable/sync";
|
||||
import type { Node as SdkNode } from "typescript/unstable/ast";
|
||||
import { AstNode } from "./ast-node.js";
|
||||
import { Ts7RpcClient } from "./rpc-client.js";
|
||||
import { ts7Executable } from "./rpc-api.js";
|
||||
import { tsgoExecutable } from "./rpc-api.js";
|
||||
import { spawnTs7Wire } from "./rpc-process.js";
|
||||
import { Ts7Session } from "./session.js";
|
||||
import { SyntaxKind } from "./enums.js";
|
||||
@@ -45,8 +45,9 @@ beforeAll(() => {
|
||||
files: [file],
|
||||
}),
|
||||
);
|
||||
// Compared with the pinned SDK, which runs tsgo.
|
||||
session = new Ts7Session(
|
||||
new Ts7RpcClient(spawnTs7Wire(ts7Executable(), ["--api", "--cwd", directory])),
|
||||
new Ts7RpcClient(spawnTs7Wire(tsgoExecutable(), ["--api", "--cwd", directory])),
|
||||
);
|
||||
oracle = new API({ cwd: directory });
|
||||
});
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
type Ts7FileSystem,
|
||||
} from "./rpc-filesystem.js";
|
||||
import { spawnTs7Wire } from "./rpc-process.js";
|
||||
import { ts7Executable } from "./rpc-api.js";
|
||||
import { tsgoExecutable } from "./rpc-api.js";
|
||||
import { Ts7Session, Ts7SessionProject, Ts7SessionSnapshot } from "./session.js";
|
||||
import { AstNode } from "./ast-node.js";
|
||||
|
||||
@@ -25,9 +25,10 @@ const fallback: Ts7FileSystem = {
|
||||
getAccessibleEntries: () => undefined,
|
||||
};
|
||||
|
||||
// These tests compare the session with the pinned SDK, which runs tsgo, so the session runs tsgo too.
|
||||
function transport(cwd: string, fs: Ts7FileSystem = fallback, timing = false) {
|
||||
const rpc = new Ts7RpcClient(
|
||||
spawnTs7Wire(ts7Executable(), [
|
||||
spawnTs7Wire(tsgoExecutable(), [
|
||||
"--api",
|
||||
"--cwd",
|
||||
cwd,
|
||||
|
||||
@@ -208,3 +208,30 @@ test("JSDoc callable types cannot replace method body views", () => {
|
||||
expect(member.body?.parent).toBe(member);
|
||||
}
|
||||
});
|
||||
|
||||
test("a parser starts a new server once it has parsed its source budget, and earlier results stay usable", () => {
|
||||
const directory = mkdtempSync(
|
||||
join(process.platform === "win32" ? tmpdir() : "/tmp", "scriptc-source-parser-"),
|
||||
);
|
||||
directories.push(directory);
|
||||
const servers: Ts7Api[] = [];
|
||||
const parser = new Ts7SourceParser(
|
||||
(options) => {
|
||||
const api = new Ts7Api(options);
|
||||
servers.push(api);
|
||||
return api;
|
||||
},
|
||||
directory,
|
||||
64,
|
||||
);
|
||||
parsers.push(parser);
|
||||
const first = parser.parse("a.ts", `export const a = ${"1 + ".repeat(20)}1;`, "ts");
|
||||
expect(servers).toHaveLength(1);
|
||||
const second = parser.parse("b.ts", "export const b = 2;", "ts");
|
||||
expect(servers).toHaveLength(2);
|
||||
const third = parser.parse("b.ts", "export const b = 3;", "ts");
|
||||
expect(servers).toHaveLength(2);
|
||||
expect(first.statements.nodes[0]!.getText()).toBe(`export const a = ${"1 + ".repeat(20)}1;`);
|
||||
expect(second.statements.nodes[0]!.getText()).toBe("export const b = 2;");
|
||||
expect(third.statements.nodes[0]!.getText()).toBe("export const b = 3;");
|
||||
});
|
||||
|
||||
@@ -7,12 +7,21 @@ import { tsgoPath } from "./session-path.js";
|
||||
export type Ts7SourceKind = "js" | "jsx" | "ts" | "tsx";
|
||||
export type Ts7SourceApiFactory = (options: { cwd: string; fs: Ts7FileSystem }) => Ts7Api;
|
||||
|
||||
/** The source text, in UTF-16 code units, one parser server parses before a
|
||||
* new server replaces it. tsc-ts keeps the syntax trees it builds for the
|
||||
* life of its process, so a server that parses many files grows with them; a
|
||||
* new one starts empty. Results are detached ASTs and outlive the server that
|
||||
* made them. */
|
||||
const SERVER_SOURCE_BUDGET = 256 * 1024;
|
||||
|
||||
/** A syntax-only session with a closed, in-memory filesystem. Parsing a
|
||||
* source string never reads imports, project configuration, or libraries
|
||||
* from disk. The returned AST owns its wire data and outlives the session.
|
||||
* Only one project and one input are retained between requests. */
|
||||
export class Ts7SourceParser {
|
||||
private readonly api: Ts7Api;
|
||||
private api: Ts7Api;
|
||||
private readonly createApi: Ts7SourceApiFactory;
|
||||
private parsedSource = 0;
|
||||
private readonly files = new Map<string, string>();
|
||||
private readonly configPath: string;
|
||||
private previousPath: string | undefined;
|
||||
@@ -21,10 +30,19 @@ export class Ts7SourceParser {
|
||||
private closed = false;
|
||||
private readonly cwd: string;
|
||||
|
||||
constructor(createApi: Ts7SourceApiFactory, cwd = process.cwd()) {
|
||||
constructor(
|
||||
createApi: Ts7SourceApiFactory,
|
||||
cwd = process.cwd(),
|
||||
private readonly sourceBudget = SERVER_SOURCE_BUDGET,
|
||||
) {
|
||||
this.cwd = resolve(cwd);
|
||||
this.configPath = tsgoPath(resolve(this.cwd, "__scriptc-source-parser.tsconfig.json"));
|
||||
this.api = createApi({
|
||||
this.createApi = createApi;
|
||||
this.api = this.connect();
|
||||
}
|
||||
|
||||
private connect(): Ts7Api {
|
||||
return this.createApi({
|
||||
cwd: this.cwd,
|
||||
fs: {
|
||||
readFile: (path) => this.files.get(tsgoPath(path)) ?? null,
|
||||
@@ -61,7 +79,14 @@ export class Ts7SourceParser {
|
||||
this.previousFile !== undefined
|
||||
)
|
||||
return this.previousFile;
|
||||
const previousPath = this.previousPath;
|
||||
let previousPath = this.previousPath;
|
||||
if (this.parsedSource >= this.sourceBudget) {
|
||||
this.api.close();
|
||||
this.api = this.connect();
|
||||
this.parsedSource = 0;
|
||||
previousPath = undefined;
|
||||
}
|
||||
this.parsedSource += source.length;
|
||||
this.files.clear();
|
||||
this.files.set(path, source);
|
||||
this.files.set(
|
||||
|
||||
@@ -5898,6 +5898,7 @@ interface RecordShapeParts {
|
||||
fields: { name: string; type: IrType }[];
|
||||
indexValue?: IrType;
|
||||
declaredOrder?: string[];
|
||||
accessorOrder?: string[];
|
||||
}
|
||||
|
||||
function mapRecordType(widened: ts.Type, ctx: TypeMapperCtx): IrType | null {
|
||||
@@ -5934,15 +5935,14 @@ function mapRecordType(widened: ts.Type, ctx: TypeMapperCtx): IrType | null {
|
||||
// (generic type parameters, mixin instantiations) cannot intern by
|
||||
// checker-type identity — fence recursive generic-open shapes.
|
||||
if (contextResolutions !== sensitivityAtEntry) return null;
|
||||
return {
|
||||
kind: "record",
|
||||
shapeId: shapes.finalizeRecursive(
|
||||
widened,
|
||||
inner.fields,
|
||||
inner.indexValue,
|
||||
inner.declaredOrder,
|
||||
),
|
||||
};
|
||||
const recursive = shapes.finalizeRecursive(
|
||||
widened,
|
||||
inner.fields,
|
||||
inner.indexValue,
|
||||
inner.declaredOrder,
|
||||
);
|
||||
adoptAccessorOrder(shapes.get(recursive), inner.accessorOrder);
|
||||
return { kind: "record", shapeId: recursive };
|
||||
}
|
||||
// A record with no typed payload contract is a view of an existing
|
||||
// object, including across parameters and returns. Building a native
|
||||
@@ -5960,10 +5960,9 @@ function mapRecordType(widened: ts.Type, ctx: TypeMapperCtx): IrType | null {
|
||||
if (merged !== null) return { kind: "record", shapeId: merged };
|
||||
const refined = refinedConstituentShape(widened, inner, ctx);
|
||||
if (refined !== null) return { kind: "record", shapeId: refined };
|
||||
return {
|
||||
kind: "record",
|
||||
shapeId: shapes.intern(inner.fields, false, inner.indexValue, inner.declaredOrder),
|
||||
};
|
||||
const shapeId = shapes.intern(inner.fields, false, inner.indexValue, inner.declaredOrder);
|
||||
adoptAccessorOrder(shapes.get(shapeId), inner.accessorOrder);
|
||||
return { kind: "record", shapeId };
|
||||
} finally {
|
||||
shapes.inProgress.delete(widened);
|
||||
}
|
||||
@@ -6193,6 +6192,12 @@ function dictSpreadSourceTs(checker: ts.TypeChecker, e: ts.Expression, depth: nu
|
||||
);
|
||||
}
|
||||
|
||||
/** The first-seen accessor key order of a shape with accessor slots. */
|
||||
function adoptAccessorOrder(shape: IrRecordShape | undefined, order: string[] | undefined): void {
|
||||
if (shape !== undefined && order !== undefined && shape.accessorOrder === undefined)
|
||||
shape.accessorOrder = order;
|
||||
}
|
||||
|
||||
/** A refinement intersection (`Expr & { kind: "mul" }`, which the checker
|
||||
* reduces to `Mul & { kind: "mul" }`) keeps the shape of the constituent it
|
||||
* refines when the refinement changes no field's representation. Recursive
|
||||
@@ -6552,8 +6557,18 @@ function mapRecordTypeInner(
|
||||
const declaredOrder = esOwnKeyOrder(
|
||||
fields.filter((f) => accessorSlotProp(f.name) === null).map((f) => f.name),
|
||||
);
|
||||
// With accessors: every own key in that order, an accessor property
|
||||
// named once for its get/set pair (the checked-dynamic copy lists it).
|
||||
const accessorOrder = fields.some((f) => accessorSlotProp(f.name) !== null)
|
||||
? esOwnKeyOrder([...new Set(fields.map((f) => accessorSlotProp(f.name)?.prop ?? f.name))])
|
||||
: undefined;
|
||||
fields.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
||||
return { fields, ...(indexValue ? { indexValue } : {}), declaredOrder };
|
||||
return {
|
||||
fields,
|
||||
...(indexValue ? { indexValue } : {}),
|
||||
declaredOrder,
|
||||
...(accessorOrder ? { accessorOrder } : {}),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
libraryWasmRefusal,
|
||||
} from "./library/prepare.js";
|
||||
import { analyzeWithFrontend } from "./frontend/analysis.js";
|
||||
import { checkerCacheIdentity } from "./frontend/ts7/checker-backend.js";
|
||||
import { analyzeWithVerdictCache, fileVerdictStore } from "./coverage/verdict-cache.js";
|
||||
import { coverageCompilerIdentity } from "./coverage/verdict-startup.js";
|
||||
import { commentOnlyReplay } from "./coverage/verdict-semantic.js";
|
||||
@@ -379,6 +380,12 @@ export async function analyzeCached(
|
||||
const nodeFrontend: FrontendFactory = (entry, npmStatic, externalTypes, libraryNpmStatic) =>
|
||||
runFrontend(entry, loadProgram, npmStatic, externalTypes, libraryNpmStatic);
|
||||
|
||||
/** The checker's part of the executable cache key (`checkerCacheIdentity`), as the CLI's startup route computes it. */
|
||||
function checkerField(): { checker?: string } {
|
||||
const checker = checkerCacheIdentity();
|
||||
return checker === undefined ? {} : { checker };
|
||||
}
|
||||
|
||||
/** The whole pipeline: load → preflight → lower → validate → emit LLVM → link. */
|
||||
function clearCompileSessionCaches(): void {
|
||||
clearResolveCaches();
|
||||
@@ -1052,6 +1059,7 @@ async function compileTracked(
|
||||
...(opts.strip ? { strip: true as const } : {}),
|
||||
...(opts.windowsSubsystem === "gui" ? { windowsSubsystem: "gui" as const } : {}),
|
||||
...(opts.detachedExit === true ? { detachedExit: true as const } : {}),
|
||||
...checkerField(),
|
||||
...(youngNurseryRequested() ? { youngNursery: true as const } : {}),
|
||||
npmStatic: opts.npmStatic ?? null,
|
||||
ffiProfile:
|
||||
|
||||
@@ -170,6 +170,7 @@ const MODULE_FIELDS: Record<StringFields<Omit<IrModule, "functions">>, Role> = {
|
||||
"records[].id": "other",
|
||||
"records[].fields[].name": "other",
|
||||
"records[].declaredOrder[]": "other",
|
||||
"records[].accessorOrder[]": "other",
|
||||
"unions[].id": "other",
|
||||
"unions[].discriminant.field": "other",
|
||||
"unions[].discriminant.cases[].values[]": "other",
|
||||
|
||||
@@ -1621,6 +1621,10 @@ export interface IrRecordShape {
|
||||
* fields carry that declaredOrder OMITS are internal '%'-fields (Dirent's
|
||||
* %dtype) — hidden from every key-order surface, JSON included. */
|
||||
declaredOrder?: string[];
|
||||
/** Shapes with accessor slots: every own key in declaration order, with
|
||||
* an accessor property named once (see accessorSlotProp). The
|
||||
* checked-dynamic copy lists its keys in this order. */
|
||||
accessorOrder?: string[];
|
||||
}
|
||||
|
||||
/** fs.Dirent rows: the hidden %dtype entry kind (libuv's UV_DIRENT
|
||||
@@ -4267,9 +4271,6 @@ function canBoxDynCompositeAt(
|
||||
const shape = getRecord(t.shapeId);
|
||||
if (!shape) return false;
|
||||
if (recordTextCodecClass(shape) !== null) return false;
|
||||
// Accessor slots hold the getter and setter closures, not property
|
||||
// values (see accessorSlotProp).
|
||||
if (shapeHasAccessorSlots(shape)) return false;
|
||||
// Recursive shapes answer coinductively, like isJsonSafeType.
|
||||
if (visiting.has(t.shapeId)) return true;
|
||||
visiting.add(t.shapeId);
|
||||
|
||||
@@ -14,6 +14,7 @@ test("native toolchain installation paths relocate with the manifest", () => {
|
||||
compiler_version: "1.2.3",
|
||||
target: "macos-arm64",
|
||||
ts7: "typescript/tsc",
|
||||
tsc_ts: "tsc-ts/lib/tsc-ts",
|
||||
llvm_package: "llvm",
|
||||
runtime_pack: "runtime",
|
||||
linker: "tools/linker",
|
||||
@@ -23,7 +24,10 @@ test("native toolchain installation paths relocate with the manifest", () => {
|
||||
try {
|
||||
writeFileSync(path, JSON.stringify(manifest));
|
||||
const toolchain = loadNativeToolchain(path);
|
||||
expect(toolchain.ts7Executable).toBe(join(root, "typescript/tsc"));
|
||||
expect(toolchain.ts7Executable).toBe(join(root, "tsc-ts/lib/tsc-ts"));
|
||||
expect(loadNativeToolchain(path, { SCRIPTC_CHECKER: "tsgo" }).ts7Executable).toBe(
|
||||
join(root, "typescript/tsc"),
|
||||
);
|
||||
expect(toolchain.helperExecutable).toBe(join(root, "llvm/bin/scriptc-llvm-codegen"));
|
||||
expect(toolchain.runtimePackRoot).toBe(join(root, "runtime"));
|
||||
expect(toolchain.linker).toBe(join(root, "tools/linker"));
|
||||
@@ -39,6 +43,7 @@ test("native toolchain installation paths relocate with the manifest", () => {
|
||||
{ ...manifest, schema: "other" },
|
||||
{ ...manifest, target: "other" },
|
||||
{ ...manifest, ts7: "" },
|
||||
{ ...manifest, tsc_ts: "" },
|
||||
{ ...manifest, linker_args: [1] },
|
||||
]) {
|
||||
writeFileSync(path, JSON.stringify(invalid));
|
||||
@@ -71,6 +76,7 @@ test("native toolchain assets resolve from the physical manifest through package
|
||||
compiler_version: "1.2.3",
|
||||
target: "windows-x64-msvc",
|
||||
ts7: asset("typescript/lib/tsc.exe"),
|
||||
tsc_ts: asset("tsc-ts/lib/tsc-ts.exe"),
|
||||
llvm_package: asset("llvm"),
|
||||
runtime_pack: asset("runtime"),
|
||||
runtime_packs: [{ target: "windows-x64-msvc", path: asset("runtime") }],
|
||||
@@ -94,6 +100,10 @@ test("native toolchain assets resolve from the physical manifest through package
|
||||
const viaLink = loadNativeToolchain(join(linked, "bin", "scriptc.exe.json"));
|
||||
expect(viaLink).toEqual(direct);
|
||||
expect(viaLink.ts7Executable).toBe(join(assets, "typescript/lib/tsc.exe"));
|
||||
expect(
|
||||
loadNativeToolchain(join(linked, "bin", "scriptc.exe.json"), { SCRIPTC_CHECKER: "tsc-ts" })
|
||||
.ts7Executable,
|
||||
).toBe(join(assets, "tsc-ts/lib/tsc-ts.exe"));
|
||||
expect(viaLink.helperExecutable).toBe(join(assets, "llvm/bin/scriptc-llvm-codegen.exe"));
|
||||
expect(
|
||||
loadNativeToolchain(join(linked, "bin", "scriptc.exe.json"), {
|
||||
@@ -126,6 +136,7 @@ test("cross-target packs can be added to a project after the compiler is install
|
||||
compiler_version: "1.2.3",
|
||||
target: "macos-arm64",
|
||||
ts7: "../lib/typescript/tsc",
|
||||
tsc_ts: "../lib/tsc-ts/lib/tsc-ts",
|
||||
llvm_package: "../lib/llvm",
|
||||
runtime_pack: "../lib/runtime-darwin-arm64",
|
||||
linker: "clang",
|
||||
@@ -174,6 +185,7 @@ test("versioned GNU targets select Zig while ordinary host builds keep the insta
|
||||
compiler_version: "1.2.3",
|
||||
target: "linux-x64-gnu",
|
||||
ts7: "tsc",
|
||||
tsc_ts: "tsc-ts",
|
||||
llvm_package: "llvm",
|
||||
runtime_pack: "runtime",
|
||||
linker: "clang",
|
||||
@@ -192,3 +204,41 @@ test("versioned GNU targets select Zig while ordinary host builds keep the insta
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("a manifest without tsc_ts takes the host's tsc-ts executable from the installed package", () => {
|
||||
const root = realpathSync(
|
||||
mkdtempSync(join(process.platform === "win32" ? tmpdir() : "/tmp", "scriptc-checker-tools-")),
|
||||
);
|
||||
const path = join(root, "toolchain.json");
|
||||
const manifest: NativeToolchainManifest = {
|
||||
schema: "scriptc.native-toolchain.v1",
|
||||
compiler_version: "1.2.3",
|
||||
target: "linux-x64-musl",
|
||||
ts7: "typescript/tsc",
|
||||
llvm_package: "llvm",
|
||||
runtime_pack: "runtime",
|
||||
linker: "tools/linker",
|
||||
linker_args: ["cc"],
|
||||
dsymutil: "dsymutil",
|
||||
};
|
||||
try {
|
||||
writeFileSync(path, JSON.stringify(manifest));
|
||||
const project = join(root, "project");
|
||||
const platformPackage = join(project, "node_modules/@tsc-ts/linux-x64-musl");
|
||||
mkdirSync(join(project, "node_modules/tsc-ts"), { recursive: true });
|
||||
writeFileSync(join(project, "node_modules/tsc-ts/package.json"), '{"name":"tsc-ts"}');
|
||||
mkdirSync(join(platformPackage, "lib"), { recursive: true });
|
||||
writeFileSync(join(platformPackage, "lib/tsc-ts"), "");
|
||||
expect(loadNativeToolchain(path, {}, project).ts7Executable).toBe(
|
||||
join(platformPackage, "lib/tsc-ts"),
|
||||
);
|
||||
expect(loadNativeToolchain(path, { SCRIPTC_CHECKER: "tsgo" }, project).ts7Executable).toBe(
|
||||
join(root, "typescript/tsc"),
|
||||
);
|
||||
expect(() => loadNativeToolchain(path, {}, root)).toThrow(
|
||||
"the tsc-ts package is not installed",
|
||||
);
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -6,6 +6,11 @@ import {
|
||||
type NativeTargetSpec,
|
||||
type NativeHelperSpec,
|
||||
} from "../backend/targets.js";
|
||||
import {
|
||||
checkerBackend,
|
||||
tscTsExecutable,
|
||||
tscTsPlatformPackage,
|
||||
} from "../frontend/ts7/checker-backend.js";
|
||||
|
||||
export interface NativeToolchain {
|
||||
compilerVersion: string;
|
||||
@@ -34,6 +39,8 @@ export interface NativeToolchainManifest {
|
||||
compiler_version: string;
|
||||
target: string;
|
||||
ts7: string;
|
||||
/** The tsc-ts executable, the default checker; without it, an installed `tsc-ts` package's. */
|
||||
tsc_ts?: string;
|
||||
llvm_package: string;
|
||||
runtime_pack: string;
|
||||
runtime_sources?: string;
|
||||
@@ -106,6 +113,7 @@ export function loadNativeToolchain(
|
||||
}
|
||||
const manifest = raw as NativeToolchainManifest;
|
||||
for (const name of [
|
||||
"tsc_ts",
|
||||
"runtime_sources",
|
||||
"declarations",
|
||||
"archiver",
|
||||
@@ -169,7 +177,19 @@ export function loadNativeToolchain(
|
||||
: [...target.defaultLinkerArgs];
|
||||
return {
|
||||
compilerVersion: manifest.compiler_version,
|
||||
ts7Executable: pathFrom(root, manifest.ts7),
|
||||
// tsc-ts, the default checker except on Windows, comes with the distribution;
|
||||
// a development build takes it from the tsc-ts package installed with the
|
||||
// compiler or for the working directory. SCRIPTC_CHECKER selects a checker.
|
||||
ts7Executable:
|
||||
checkerBackend(env, host.platform) === "tsgo"
|
||||
? pathFrom(root, manifest.ts7)
|
||||
: manifest.tsc_ts !== undefined
|
||||
? pathFrom(root, manifest.tsc_ts)
|
||||
: tscTsExecutable(
|
||||
[root, cwd],
|
||||
tscTsPlatformPackage(host.platform, host.architecture, host.name.endsWith("-musl")),
|
||||
host.platform,
|
||||
),
|
||||
target,
|
||||
helper: host.helper,
|
||||
helperPackageRoot,
|
||||
|
||||
@@ -22,5 +22,6 @@ export function precompiledRuntimePackTarget(
|
||||
): NativeTargetSpec | null {
|
||||
return nativeCodegenTarget(env);
|
||||
}
|
||||
export { checkerCacheIdentity } from "./frontend/ts7/checker-backend.js";
|
||||
export { readCoverageVerdict } from "./coverage/verdict-startup.js";
|
||||
export { coverageEnvelope, coveragePasses, renderCoverage } from "./coverage/report.js";
|
||||
|
||||
@@ -114,3 +114,24 @@ test("a computed key in an Object.assign source keeps checked dispatch", async (
|
||||
.replace("LITERAL", "Object.assign(target, { [key]: value })");
|
||||
expect(await callersOf(source, "%dyn.class.properties")).not.toEqual([]);
|
||||
});
|
||||
|
||||
const range = `
|
||||
class Range {
|
||||
hi: number;
|
||||
constructor(hi: number) { this.hi = hi; }
|
||||
*[Symbol.iterator](): Generator<number> { for (let i = 0; i < this.hi; i++) yield i; }
|
||||
}
|
||||
const r = new Range(3);
|
||||
console.log(r[Symbol.iterator]().next().value);
|
||||
`;
|
||||
|
||||
test("a well-known symbol method call lowers to the class's method", async () => {
|
||||
expect(await callersOf(range, "%Range.sym:iterator")).not.toEqual([]);
|
||||
});
|
||||
|
||||
test("a reflection call with a well-known symbol key keeps checked dispatch", async () => {
|
||||
const write = "Object.defineProperty(r, Symbol.iterator, { value: function* () {} });\n";
|
||||
// The checked path reads the declared method through its value thunk.
|
||||
const callers = await callersOf(`${range}${write}`, "%Range.sym:iterator");
|
||||
expect(callers.filter((name) => !name.startsWith("%method.value:"))).toEqual([]);
|
||||
});
|
||||
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/corpus/5779-sha512-lengths.ts"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/corpus/6055-class-generator-iterables.ts"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/corpus/6056-class-symbol-method-calls.ts"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/corpus/6450-builtin-base-class-values.ts"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/corpus/6451-builtin-base-class-expressions.cjs"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/corpus/6480-generic-callback-extended-results.ts"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/corpus/comma-null-union-return.cjs"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/corpus/local-class-detached-method.ts"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/corpus/object-literal-accessors-dyn.ts"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/corpus/required-module-truthiness.cjs"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/corpus/strict-arguments-parameters.cjs"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/diagnostics/builtin-base-class-value-arguments.ts"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/diagnostics/inferred-callback-drops-conditional.ts"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/diagnostics/inferred-callback-drops-satisfies.ts"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/diagnostics/inferred-callback-drops.ts"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/diagnostics/stream-completion-callback-error.ts"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/fixtures/npm/cases/2563-bundled-esm-inits/main.ts"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/fixtures/npm/cases/2567-esm-namespace-this/main.ts"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/fixtures/npm/cases/2580-lazy-barrel/main.ts"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/fixtures/npm/cases/2581-lazy-barrel-require/main.ts"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/fixtures/npm/cases/2582-npm-alias-two-releases/main.ts"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/fixtures/npm/cases/2583-cjs-function-exports/main.ts"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"order": [
|
||||
"<repo>/tests/fixtures/npm/cases/2584-cjs-conditional-exports/main.ts"
|
||||
],
|
||||
"diags": []
|
||||
}
|
||||
@@ -71,7 +71,16 @@ test("production RPC bridge preserves pinned SDK parser/checker behavior", () =>
|
||||
JSON.stringify({ compilerOptions: { strict: true, noEmit: true, types: [] }, files: [path] }),
|
||||
);
|
||||
writeFileSync(path, 'export const answer = 42;\nexport const invalid: number = "wrong";\n');
|
||||
const nativeClient = new Ts7Api({ cwd: dir, fs: fallback });
|
||||
// Compared with the pinned SDK, which runs tsgo, so the bridge runs tsgo too.
|
||||
const checker = process.env["SCRIPTC_CHECKER"];
|
||||
process.env["SCRIPTC_CHECKER"] = "tsgo";
|
||||
let nativeClient: Ts7Api;
|
||||
try {
|
||||
nativeClient = new Ts7Api({ cwd: dir, fs: fallback });
|
||||
} finally {
|
||||
if (checker === undefined) delete process.env["SCRIPTC_CHECKER"];
|
||||
else process.env["SCRIPTC_CHECKER"] = checker;
|
||||
}
|
||||
const sdk = new API({ cwd: dir });
|
||||
try {
|
||||
expect(nativeClient.parseConfigFile(config)).toEqual(sdk.parseConfigFile(config));
|
||||
|
||||
@@ -1076,6 +1076,11 @@ extern SCR_TL size_t scr_uncloneable_count;
|
||||
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);
|
||||
/* 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);
|
||||
/* The getter or setter of an own accessor property, +1 (undefined when none). */
|
||||
ScrDyn *scr_dyn_obj_accessor_fn(const ScrDyn *obj, const char *key, size_t key_len, bool setter);
|
||||
void scr_error_commit_dyn(ScrError *e, const ScrDyn *view);
|
||||
/* The reverse extraction, riding the same identity cache: a dyn error
|
||||
* that came from a runtime ScrError answers THAT instance (+1;
|
||||
|
||||
@@ -4356,6 +4356,31 @@ void scr_dyn_obj_set(ScrDyn *obj, const char *key, size_t key_len, ScrDyn *value
|
||||
scr_dyn_obj_put(obj, key, key_len, value);
|
||||
}
|
||||
|
||||
/* The getter (or, with `setter`, the setter) of the own accessor property
|
||||
* `key`: +1, or the undefined value when the property is not an accessor
|
||||
* or has none. */
|
||||
ScrDyn *scr_dyn_obj_accessor_fn(const ScrDyn *obj, const char *key, size_t key_len, bool setter) {
|
||||
const ScrDynEntry *entry = obj->kind == SCR_DYN_OBJ ? scr_dyn_find_entry(obj, key, key_len) : NULL;
|
||||
ScrDyn *fn = entry && entry->accessor ? (setter ? entry->setter : entry->getter) : NULL;
|
||||
return scr_dyn_retain(fn ? fn : scr_dyn_undefined());
|
||||
}
|
||||
|
||||
/* An object literal's get/set accessor property on a fresh copy:
|
||||
* enumerable and configurable, with the given getter and setter functions
|
||||
* (either NULL when the literal declares none). Moves both. */
|
||||
void scr_dyn_obj_set_accessor(ScrDyn *obj, const char *key, size_t key_len, ScrDyn *getter, ScrDyn *setter) {
|
||||
scr_dyn_obj_put(obj, key, key_len, scr_dyn_retain(scr_dyn_undefined()));
|
||||
ScrDynEntry *entry = scr_dyn_find_entry(obj, key, key_len);
|
||||
if (!entry) {
|
||||
scr_dyn_release(getter);
|
||||
scr_dyn_release(setter);
|
||||
return;
|
||||
}
|
||||
entry->accessor = true;
|
||||
entry->getter = getter;
|
||||
entry->setter = setter;
|
||||
}
|
||||
|
||||
/* A class instance's view takes its native field values whatever the
|
||||
* attributes copied into it (a frozen instance's view is built the same way
|
||||
* as any other). Consumes value. */
|
||||
|
||||
+317
-27
@@ -7485,29 +7485,319 @@ static uint64_t scr_sha512_rotr(uint64_t x, unsigned n) {
|
||||
return (x >> n) | (x << (64 - n));
|
||||
}
|
||||
|
||||
SCR_DIGEST_ALIGNED static void scr_sha512_block(uint64_t h[8], const unsigned char *data) {
|
||||
uint64_t w[80];
|
||||
for (size_t i = 0; i < 16; i++) {
|
||||
w[i] = 0;
|
||||
for (size_t b = 0; b < 8; b++) w[i] = (w[i] << 8) | data[i * 8 + b];
|
||||
#define SCR_SHA512_BSIG0(x) \
|
||||
(scr_sha512_rotr(x, 28) ^ scr_sha512_rotr(x, 34) ^ scr_sha512_rotr(x, 39))
|
||||
#define SCR_SHA512_BSIG1(x) \
|
||||
(scr_sha512_rotr(x, 14) ^ scr_sha512_rotr(x, 18) ^ scr_sha512_rotr(x, 41))
|
||||
#define SCR_SHA512_SSIG0(x) (scr_sha512_rotr(x, 1) ^ scr_sha512_rotr(x, 8) ^ ((x) >> 7))
|
||||
#define SCR_SHA512_SSIG1(x) (scr_sha512_rotr(x, 19) ^ scr_sha512_rotr(x, 61) ^ ((x) >> 6))
|
||||
|
||||
/* One round with the eight working variables passed in rotated order, so
|
||||
* an unrolled sequence of rounds needs no register moves. */
|
||||
#define SCR_SHA512_ROUND(a, b, c, d, e, f, g, h, k, w) \
|
||||
do { \
|
||||
uint64_t t1 = (h) + SCR_SHA512_BSIG1(e) + ((g) ^ ((e) & ((f) ^ (g)))) + (k) + (w); \
|
||||
(d) += t1; \
|
||||
(h) = t1 + SCR_SHA512_BSIG0(a) + (((a) & (b)) | ((c) & ((a) | (b)))); \
|
||||
} while (0)
|
||||
|
||||
static uint64_t scr_sha512_load(const unsigned char *p) {
|
||||
uint64_t v = 0;
|
||||
for (size_t b = 0; b < 8; b++) v = (v << 8) | p[b];
|
||||
return v;
|
||||
}
|
||||
|
||||
/* The message schedule is kept as a 16-word ring and extended 16 words
|
||||
* at a time between groups of 16 rounds. */
|
||||
SCR_DIGEST_ALIGNED static void scr_sha512_blocks_portable(uint64_t state[8], const unsigned char *p,
|
||||
size_t blocks) {
|
||||
uint64_t a = state[0], b = state[1], c = state[2], d = state[3];
|
||||
uint64_t e = state[4], f = state[5], g = state[6], h = state[7];
|
||||
for (; blocks != 0; blocks--, p += 128) {
|
||||
uint64_t w[16];
|
||||
for (size_t i = 0; i < 16; i++) w[i] = scr_sha512_load(p + i * 8);
|
||||
for (size_t i = 0; i < 80; i += 16) {
|
||||
if (i != 0) {
|
||||
for (size_t j = 0; j < 16; j++) {
|
||||
w[j] += SCR_SHA512_SSIG1(w[(j + 14) & 15]) + w[(j + 9) & 15] +
|
||||
SCR_SHA512_SSIG0(w[(j + 1) & 15]);
|
||||
}
|
||||
}
|
||||
const uint64_t *k = scr_sha512_k + i;
|
||||
SCR_SHA512_ROUND(a, b, c, d, e, f, g, h, k[0], w[0]);
|
||||
SCR_SHA512_ROUND(h, a, b, c, d, e, f, g, k[1], w[1]);
|
||||
SCR_SHA512_ROUND(g, h, a, b, c, d, e, f, k[2], w[2]);
|
||||
SCR_SHA512_ROUND(f, g, h, a, b, c, d, e, k[3], w[3]);
|
||||
SCR_SHA512_ROUND(e, f, g, h, a, b, c, d, k[4], w[4]);
|
||||
SCR_SHA512_ROUND(d, e, f, g, h, a, b, c, k[5], w[5]);
|
||||
SCR_SHA512_ROUND(c, d, e, f, g, h, a, b, k[6], w[6]);
|
||||
SCR_SHA512_ROUND(b, c, d, e, f, g, h, a, k[7], w[7]);
|
||||
SCR_SHA512_ROUND(a, b, c, d, e, f, g, h, k[8], w[8]);
|
||||
SCR_SHA512_ROUND(h, a, b, c, d, e, f, g, k[9], w[9]);
|
||||
SCR_SHA512_ROUND(g, h, a, b, c, d, e, f, k[10], w[10]);
|
||||
SCR_SHA512_ROUND(f, g, h, a, b, c, d, e, k[11], w[11]);
|
||||
SCR_SHA512_ROUND(e, f, g, h, a, b, c, d, k[12], w[12]);
|
||||
SCR_SHA512_ROUND(d, e, f, g, h, a, b, c, k[13], w[13]);
|
||||
SCR_SHA512_ROUND(c, d, e, f, g, h, a, b, k[14], w[14]);
|
||||
SCR_SHA512_ROUND(b, c, d, e, f, g, h, a, k[15], w[15]);
|
||||
}
|
||||
a = state[0] += a; b = state[1] += b; c = state[2] += c; d = state[3] += d;
|
||||
e = state[4] += e; f = state[5] += f; g = state[6] += g; h = state[7] += h;
|
||||
}
|
||||
for (size_t i = 16; i < 80; i++) {
|
||||
uint64_t s0 = scr_sha512_rotr(w[i - 15], 1) ^ scr_sha512_rotr(w[i - 15], 8) ^ (w[i - 15] >> 7);
|
||||
uint64_t s1 = scr_sha512_rotr(w[i - 2], 19) ^ scr_sha512_rotr(w[i - 2], 61) ^ (w[i - 2] >> 6);
|
||||
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
|
||||
}
|
||||
|
||||
#ifdef SCR_SHA_NI
|
||||
/* ── SHA-512 kernels (x86-64) ─────────────────────────────────────────
|
||||
* With AVX2 and BMI2, the message schedule is computed two words at a
|
||||
* time in vector registers, interleaved with the scalar rounds, and the
|
||||
* rounds rotate with RORX. With AVX-512VL the schedule uses vector
|
||||
* rotates and three-input XOR. The CPU and OS state checks run once and
|
||||
* are cached. */
|
||||
static int scr_sha512_x86_state; /* 0 unknown, 1 portable, 2 AVX2, 3 AVX-512VL */
|
||||
|
||||
static int scr_sha512_x86(void) {
|
||||
if (scr_sha512_x86_state == 0) {
|
||||
unsigned a, b, c, d;
|
||||
int kind = 1;
|
||||
if (__get_cpuid(1, &a, &b, &c, &d) && (c & bit_OSXSAVE) && (c & bit_AVX)) {
|
||||
unsigned lo, hi;
|
||||
__asm__ volatile("xgetbv" : "=a"(lo), "=d"(hi) : "c"(0));
|
||||
(void)hi;
|
||||
/* XMM and YMM state enabled. */
|
||||
if ((lo & 6) == 6 && __get_cpuid_count(7, 0, &a, &b, &c, &d) && (b & bit_AVX2) &&
|
||||
(b & bit_BMI2)) {
|
||||
kind = 2;
|
||||
/* Opmask, ZMM0-15 upper halves and ZMM16-31 state enabled. */
|
||||
if ((b & bit_AVX512F) && (b & bit_AVX512VL) && (lo & 0xe0) == 0xe0) kind = 3;
|
||||
}
|
||||
}
|
||||
scr_sha512_x86_state = kind;
|
||||
}
|
||||
uint64_t a = h[0], b = h[1], c = h[2], d = h[3];
|
||||
uint64_t e = h[4], f = h[5], g = h[6], v = h[7];
|
||||
for (size_t i = 0; i < 80; i++) {
|
||||
uint64_t s1 = scr_sha512_rotr(e, 14) ^ scr_sha512_rotr(e, 18) ^ scr_sha512_rotr(e, 41);
|
||||
uint64_t t1 = v + s1 + ((e & f) ^ (~e & g)) + scr_sha512_k[i] + w[i];
|
||||
uint64_t s0 = scr_sha512_rotr(a, 28) ^ scr_sha512_rotr(a, 34) ^ scr_sha512_rotr(a, 39);
|
||||
uint64_t t2 = s0 + ((a & b) ^ (a & c) ^ (b & c));
|
||||
v = g; g = f; f = e; e = d + t1;
|
||||
d = c; c = b; b = a; a = t1 + t2;
|
||||
return scr_sha512_x86_state;
|
||||
}
|
||||
|
||||
__attribute__((target("avx2,bmi2"))) static inline __m128i scr_sha512_ssig0_avx2(__m128i x) {
|
||||
return _mm_xor_si128(_mm_xor_si128(_mm_or_si128(_mm_srli_epi64(x, 1), _mm_slli_epi64(x, 63)),
|
||||
_mm_or_si128(_mm_srli_epi64(x, 8), _mm_slli_epi64(x, 56))),
|
||||
_mm_srli_epi64(x, 7));
|
||||
}
|
||||
|
||||
__attribute__((target("avx2,bmi2"))) static inline __m128i scr_sha512_ssig1_avx2(__m128i x) {
|
||||
return _mm_xor_si128(_mm_xor_si128(_mm_or_si128(_mm_srli_epi64(x, 19), _mm_slli_epi64(x, 45)),
|
||||
_mm_or_si128(_mm_srli_epi64(x, 61), _mm_slli_epi64(x, 3))),
|
||||
_mm_srli_epi64(x, 6));
|
||||
}
|
||||
|
||||
__attribute__((target("avx512f,avx512vl,bmi2"))) static inline __m128i
|
||||
scr_sha512_ssig0_avx512(__m128i x) {
|
||||
return _mm_ternarylogic_epi64(_mm_ror_epi64(x, 1), _mm_ror_epi64(x, 8), _mm_srli_epi64(x, 7),
|
||||
0x96);
|
||||
}
|
||||
|
||||
__attribute__((target("avx512f,avx512vl,bmi2"))) static inline __m128i
|
||||
scr_sha512_ssig1_avx512(__m128i x) {
|
||||
return _mm_ternarylogic_epi64(_mm_ror_epi64(x, 19), _mm_ror_epi64(x, 61), _mm_srli_epi64(x, 6),
|
||||
0x96);
|
||||
}
|
||||
|
||||
/* A round for the vector kernels. wk is the schedule word plus its
|
||||
* constant. Maj(a, b, c) is ((a ^ b) & (b ^ c)) ^ b, where b ^ c is the
|
||||
* previous round's a ^ b. The empty asm statements keep the compiler from
|
||||
* reassociating the additions: adding Sigma1(e) last keeps the sum of h,
|
||||
* wk and Ch off the dependency chain through e. */
|
||||
#define SCR_SHA512_PIN(v) __asm__("" : "+r"(v))
|
||||
#define SCR_SHA512_ROUND_WK(a, b, c, d, e, f, g, h, wk, ab, bc) \
|
||||
do { \
|
||||
uint64_t t1 = (h) + (wk); \
|
||||
SCR_SHA512_PIN(t1); \
|
||||
t1 += (g) ^ ((e) & ((f) ^ (g))); \
|
||||
SCR_SHA512_PIN(t1); \
|
||||
t1 += SCR_SHA512_BSIG1(e); \
|
||||
SCR_SHA512_PIN(t1); \
|
||||
(d) += t1; \
|
||||
(ab) = (a) ^ (b); \
|
||||
uint64_t m = t1 + (((ab) & (bc)) ^ (b)); \
|
||||
SCR_SHA512_PIN(m); \
|
||||
(h) = m + SCR_SHA512_BSIG0(a); \
|
||||
} while (0)
|
||||
|
||||
/* Words 2j and 2j+1 of the schedule, in the ring slot of words 2j-16 and
|
||||
* 2j-15, and their sum with the round constants into wk. */
|
||||
#define SCR_SHA512_SCHEDULE(j, ssig0, ssig1) \
|
||||
do { \
|
||||
if ((j) < 40) { \
|
||||
__m128i s15 = _mm_alignr_epi8(w[((j) + 1) & 7], w[(j) & 7], 8); \
|
||||
__m128i s7 = _mm_alignr_epi8(w[((j) + 5) & 7], w[((j) + 4) & 7], 8); \
|
||||
__m128i next = _mm_add_epi64(_mm_add_epi64(w[(j) & 7], ssig0(s15)), \
|
||||
_mm_add_epi64(s7, ssig1(w[((j) + 7) & 7]))); \
|
||||
w[(j) & 7] = next; \
|
||||
_mm_store_si128((__m128i *)&wk[(j) * 2], \
|
||||
_mm_add_epi64(next, _mm_loadu_si128((const __m128i *)&scr_sha512_k[(j) * 2]))); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
/* Rounds 2i to 2i+7 compute the schedule words 2i+16 to 2i+23. */
|
||||
#define SCR_SHA512_VECTOR_BODY(ssig0, ssig1) \
|
||||
const __m128i bswap = _mm_set_epi64x(0x08090a0b0c0d0e0fULL, 0x0001020304050607ULL); \
|
||||
uint64_t a = state[0], b = state[1], c = state[2], d = state[3]; \
|
||||
uint64_t e = state[4], f = state[5], g = state[6], h = state[7]; \
|
||||
for (; blocks != 0; blocks--, p += 128) { \
|
||||
__m128i w[8]; \
|
||||
uint64_t wk[80] __attribute__((aligned(16))); \
|
||||
_Pragma("GCC unroll 8") for (int i = 0; i < 8; i++) { \
|
||||
w[i] = _mm_shuffle_epi8(_mm_loadu_si128((const __m128i *)(p + i * 16)), bswap); \
|
||||
_mm_store_si128((__m128i *)&wk[i * 2], \
|
||||
_mm_add_epi64(w[i], _mm_loadu_si128((const __m128i *)&scr_sha512_k[i * 2]))); \
|
||||
} \
|
||||
uint64_t x = b ^ c, y; \
|
||||
_Pragma("GCC unroll 10") for (int i = 0; i < 40; i += 4) { \
|
||||
SCR_SHA512_SCHEDULE(i + 8, ssig0, ssig1); \
|
||||
SCR_SHA512_ROUND_WK(a, b, c, d, e, f, g, h, wk[2 * i + 0], y, x); \
|
||||
SCR_SHA512_ROUND_WK(h, a, b, c, d, e, f, g, wk[2 * i + 1], x, y); \
|
||||
SCR_SHA512_SCHEDULE(i + 9, ssig0, ssig1); \
|
||||
SCR_SHA512_ROUND_WK(g, h, a, b, c, d, e, f, wk[2 * i + 2], y, x); \
|
||||
SCR_SHA512_ROUND_WK(f, g, h, a, b, c, d, e, wk[2 * i + 3], x, y); \
|
||||
SCR_SHA512_SCHEDULE(i + 10, ssig0, ssig1); \
|
||||
SCR_SHA512_ROUND_WK(e, f, g, h, a, b, c, d, wk[2 * i + 4], y, x); \
|
||||
SCR_SHA512_ROUND_WK(d, e, f, g, h, a, b, c, wk[2 * i + 5], x, y); \
|
||||
SCR_SHA512_SCHEDULE(i + 11, ssig0, ssig1); \
|
||||
SCR_SHA512_ROUND_WK(c, d, e, f, g, h, a, b, wk[2 * i + 6], y, x); \
|
||||
SCR_SHA512_ROUND_WK(b, c, d, e, f, g, h, a, wk[2 * i + 7], x, y); \
|
||||
} \
|
||||
a = state[0] += a; b = state[1] += b; c = state[2] += c; d = state[3] += d; \
|
||||
e = state[4] += e; f = state[5] += f; g = state[6] += g; h = state[7] += h; \
|
||||
}
|
||||
h[0] += a; h[1] += b; h[2] += c; h[3] += d;
|
||||
h[4] += e; h[5] += f; h[6] += g; h[7] += v;
|
||||
|
||||
__attribute__((target("avx2,bmi2"), aligned(64))) static void
|
||||
scr_sha512_blocks_avx2(uint64_t state[8], const unsigned char *p, size_t blocks) {
|
||||
SCR_SHA512_VECTOR_BODY(scr_sha512_ssig0_avx2, scr_sha512_ssig1_avx2)
|
||||
}
|
||||
|
||||
__attribute__((target("avx512f,avx512vl,bmi2"), aligned(64))) static void
|
||||
scr_sha512_blocks_avx512(uint64_t state[8], const unsigned char *p, size_t blocks) {
|
||||
SCR_SHA512_VECTOR_BODY(scr_sha512_ssig0_avx512, scr_sha512_ssig1_avx512)
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
#if defined(__aarch64__) && (defined(__clang__) || defined(__GNUC__)) && !defined(_WIN32)
|
||||
/* ── SHA-512 kernel (arm64) ───────────────────────────────────────────
|
||||
* On CPUs with the SHA-512 extension (FEAT_SHA512), the blocks run with
|
||||
* SHA512H, SHA512H2, SHA512SU0 and SHA512SU1; other CPUs use the portable
|
||||
* blocks. The CPU check runs once and is cached. */
|
||||
#include <arm_neon.h>
|
||||
#if defined(__APPLE__)
|
||||
#include <sys/sysctl.h>
|
||||
#else
|
||||
#include <sys/auxv.h>
|
||||
#endif
|
||||
#define SCR_SHA512_ARM 1
|
||||
#if defined(__clang__)
|
||||
#define SCR_SHA512_ARM_TARGET __attribute__((target("sha3")))
|
||||
#else
|
||||
#define SCR_SHA512_ARM_TARGET __attribute__((target("+sha3")))
|
||||
#endif
|
||||
|
||||
static int scr_sha512_arm_state; /* 0 unknown, 1 available, 2 absent */
|
||||
|
||||
static bool scr_sha512_arm(void) {
|
||||
if (scr_sha512_arm_state == 0) {
|
||||
bool ok;
|
||||
#if defined(__APPLE__)
|
||||
int value = 0;
|
||||
size_t size = sizeof value;
|
||||
ok = sysctlbyname("hw.optional.armv8_2_sha512", &value, &size, NULL, 0) == 0 && value != 0;
|
||||
#else
|
||||
ok = (getauxval(AT_HWCAP) & (1ul << 21)) != 0; /* HWCAP_SHA512 */
|
||||
#endif
|
||||
scr_sha512_arm_state = ok ? 1 : 2;
|
||||
}
|
||||
return scr_sha512_arm_state == 1;
|
||||
}
|
||||
|
||||
/* Two rounds per step. With the state pairs in the roles (A, B, C, D) =
|
||||
* (ab, cd, ef, gh), a step computes I = SHA512H(swap(K + W) + D, ext(C, D),
|
||||
* ext(B, C)), D = SHA512H2(I, B, A) and B += I; the roles then rotate to
|
||||
* (D, A, B, C). */
|
||||
#define SCR_SHA512_ARM_STEP(A, B, C, D, msg, k) \
|
||||
do { \
|
||||
uint64x2_t kw = vaddq_u64((msg), vld1q_u64(k)); \
|
||||
uint64x2_t sum = vaddq_u64(vextq_u64(kw, kw, 1), (D)); \
|
||||
uint64x2_t i = vsha512hq_u64(sum, vextq_u64((C), (D), 1), vextq_u64((B), (C), 1)); \
|
||||
(D) = vsha512h2q_u64(i, (B), (A)); \
|
||||
(B) = vaddq_u64((B), i); \
|
||||
} while (0)
|
||||
|
||||
/* Message words 2j and 2j+1 from the eight pairs before them. */
|
||||
#define SCR_SHA512_ARM_SCHEDULE(m0, m1, m4, m5, m7) \
|
||||
(m0) = vsha512su1q_u64(vsha512su0q_u64((m0), (m1)), (m7), vextq_u64((m4), (m5), 1))
|
||||
|
||||
SCR_SHA512_ARM_TARGET static void scr_sha512_blocks_arm(uint64_t state[8], const unsigned char *p,
|
||||
size_t blocks) {
|
||||
uint64x2_t ab = vld1q_u64(&state[0]), cd = vld1q_u64(&state[2]);
|
||||
uint64x2_t ef = vld1q_u64(&state[4]), gh = vld1q_u64(&state[6]);
|
||||
for (; blocks != 0; blocks--, p += 128) {
|
||||
uint64x2_t ab0 = ab, cd0 = cd, ef0 = ef, gh0 = gh;
|
||||
uint64x2_t m0 = vreinterpretq_u64_u8(vrev64q_u8(vld1q_u8(p + 0)));
|
||||
uint64x2_t m1 = vreinterpretq_u64_u8(vrev64q_u8(vld1q_u8(p + 16)));
|
||||
uint64x2_t m2 = vreinterpretq_u64_u8(vrev64q_u8(vld1q_u8(p + 32)));
|
||||
uint64x2_t m3 = vreinterpretq_u64_u8(vrev64q_u8(vld1q_u8(p + 48)));
|
||||
uint64x2_t m4 = vreinterpretq_u64_u8(vrev64q_u8(vld1q_u8(p + 64)));
|
||||
uint64x2_t m5 = vreinterpretq_u64_u8(vrev64q_u8(vld1q_u8(p + 80)));
|
||||
uint64x2_t m6 = vreinterpretq_u64_u8(vrev64q_u8(vld1q_u8(p + 96)));
|
||||
uint64x2_t m7 = vreinterpretq_u64_u8(vrev64q_u8(vld1q_u8(p + 112)));
|
||||
const uint64_t *k = scr_sha512_k;
|
||||
for (int i = 0; i < 5; i++, k += 16) {
|
||||
SCR_SHA512_ARM_STEP(ab, cd, ef, gh, m0, k + 0);
|
||||
SCR_SHA512_ARM_STEP(gh, ab, cd, ef, m1, k + 2);
|
||||
SCR_SHA512_ARM_STEP(ef, gh, ab, cd, m2, k + 4);
|
||||
SCR_SHA512_ARM_STEP(cd, ef, gh, ab, m3, k + 6);
|
||||
SCR_SHA512_ARM_STEP(ab, cd, ef, gh, m4, k + 8);
|
||||
SCR_SHA512_ARM_STEP(gh, ab, cd, ef, m5, k + 10);
|
||||
SCR_SHA512_ARM_STEP(ef, gh, ab, cd, m6, k + 12);
|
||||
SCR_SHA512_ARM_STEP(cd, ef, gh, ab, m7, k + 14);
|
||||
if (i == 4) break;
|
||||
SCR_SHA512_ARM_SCHEDULE(m0, m1, m4, m5, m7);
|
||||
SCR_SHA512_ARM_SCHEDULE(m1, m2, m5, m6, m0);
|
||||
SCR_SHA512_ARM_SCHEDULE(m2, m3, m6, m7, m1);
|
||||
SCR_SHA512_ARM_SCHEDULE(m3, m4, m7, m0, m2);
|
||||
SCR_SHA512_ARM_SCHEDULE(m4, m5, m0, m1, m3);
|
||||
SCR_SHA512_ARM_SCHEDULE(m5, m6, m1, m2, m4);
|
||||
SCR_SHA512_ARM_SCHEDULE(m6, m7, m2, m3, m5);
|
||||
SCR_SHA512_ARM_SCHEDULE(m7, m0, m3, m4, m6);
|
||||
}
|
||||
ab = vaddq_u64(ab, ab0);
|
||||
cd = vaddq_u64(cd, cd0);
|
||||
ef = vaddq_u64(ef, ef0);
|
||||
gh = vaddq_u64(gh, gh0);
|
||||
}
|
||||
vst1q_u64(&state[0], ab);
|
||||
vst1q_u64(&state[2], cd);
|
||||
vst1q_u64(&state[4], ef);
|
||||
vst1q_u64(&state[6], gh);
|
||||
}
|
||||
#endif
|
||||
|
||||
static void scr_sha512_blocks(uint64_t h[8], const unsigned char *p, size_t blocks) {
|
||||
#ifdef SCR_SHA_NI
|
||||
switch (scr_sha512_x86()) {
|
||||
case 3:
|
||||
scr_sha512_blocks_avx512(h, p, blocks);
|
||||
return;
|
||||
case 2:
|
||||
scr_sha512_blocks_avx2(h, p, blocks);
|
||||
return;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
#endif
|
||||
#ifdef SCR_SHA512_ARM
|
||||
if (scr_sha512_arm()) {
|
||||
scr_sha512_blocks_arm(h, p, blocks);
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
scr_sha512_blocks_portable(h, p, blocks);
|
||||
}
|
||||
|
||||
static void scr_sha512_init(ScrSha512Ctx *ctx, bool sha384) {
|
||||
@@ -7536,14 +7826,15 @@ static void scr_sha512_update(ScrSha512Ctx *ctx, const unsigned char *data, size
|
||||
data += take;
|
||||
len -= take;
|
||||
if (ctx->tail_len == 128) {
|
||||
scr_sha512_block(ctx->h, ctx->tail);
|
||||
scr_sha512_blocks(ctx->h, ctx->tail, 1);
|
||||
ctx->tail_len = 0;
|
||||
}
|
||||
}
|
||||
while (len >= 128) {
|
||||
scr_sha512_block(ctx->h, data);
|
||||
data += 128;
|
||||
len -= 128;
|
||||
if (len >= 128) {
|
||||
size_t blocks = len / 128;
|
||||
scr_sha512_blocks(ctx->h, data, blocks);
|
||||
data += blocks * 128;
|
||||
len -= blocks * 128;
|
||||
}
|
||||
if (len != 0) {
|
||||
memcpy(ctx->tail, data, len);
|
||||
@@ -7562,8 +7853,7 @@ static size_t scr_sha512_final(const ScrSha512Ctx *source, unsigned char out[64]
|
||||
tail[pad - 1 - b] = (unsigned char)(low >> (8 * b));
|
||||
tail[pad - 9 - b] = (unsigned char)(high >> (8 * b));
|
||||
}
|
||||
scr_sha512_block(ctx.h, tail);
|
||||
if (pad == 256) scr_sha512_block(ctx.h, tail + 128);
|
||||
scr_sha512_blocks(ctx.h, tail, pad / 128);
|
||||
size_t len = sha384 ? 48 : 64;
|
||||
for (size_t i = 0; i < len; i++) out[i] = (unsigned char)(ctx.h[i / 8] >> (56 - 8 * (i % 8)));
|
||||
return len;
|
||||
|
||||
@@ -42,7 +42,7 @@ const runtimeSources = [
|
||||
];
|
||||
|
||||
// Compiled once with ASan, UBSan and the RC audit. The test runs the SHA-NI and portable
|
||||
// SHA-1/SHA-256 blocks over the same inputs and checks known vectors.
|
||||
// SHA-1/SHA-256 blocks and the SHA-512 kernels over the same inputs and checks known vectors.
|
||||
beforeAll(async () => {
|
||||
await mkdir(join(testDir, "build"), { recursive: true });
|
||||
await execFileAsync("clang", [
|
||||
@@ -64,7 +64,7 @@ beforeAll(async () => {
|
||||
]);
|
||||
}, 300_000);
|
||||
|
||||
test("SHA-1 and SHA-256: the SHA-NI blocks match the portable blocks", async () => {
|
||||
test("SHA-1, SHA-256, SHA-384 and SHA-512: the CPU kernels match the portable blocks", async () => {
|
||||
const { stderr } = await execFileAsync(bin, [], {
|
||||
env: { ...process.env, UBSAN_OPTIONS: "halt_on_error=1" },
|
||||
});
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
/* SHA-1 and SHA-256 block kernels (scr_lib.c), built by
|
||||
/* SHA-1, SHA-256, SHA-384 and SHA-512 block kernels (scr_lib.c), built by
|
||||
* sha-kernels.test.ts. The unit is included directly so the test can run
|
||||
* the SHA-NI blocks and the portable blocks over the same inputs: known
|
||||
* vectors, every length from 0 to 1100 bytes, and 1 MiB, each fed whole
|
||||
* and in 1-, 7-, 64- and 100-byte updates. On CPUs without the SHA
|
||||
* extensions only the portable blocks run. */
|
||||
* each kernel the CPU supports and the portable blocks over the same
|
||||
* inputs: known vectors, every length from 0 to 1100 bytes, and 1 MiB,
|
||||
* each fed whole and in 1-, 7-, 64- and 100-byte updates. The SHA-1 and
|
||||
* SHA-256 kernels use the SHA extensions; the SHA-512 kernels use AVX2 or
|
||||
* AVX-512VL on x86-64 and the SHA-512 extension on arm64. On CPUs without
|
||||
* them only the portable blocks run. */
|
||||
#include "../src/scr_lib.c"
|
||||
|
||||
#include <stdio.h>
|
||||
@@ -45,6 +47,71 @@ static void sha1_of(const unsigned char *data, size_t len, size_t chunk, unsigne
|
||||
scr_sha1_final(&ctx, out);
|
||||
}
|
||||
|
||||
static void sha512_of(const unsigned char *data, size_t len, size_t chunk, bool sha384,
|
||||
unsigned char out[64]) {
|
||||
ScrSha512Ctx ctx;
|
||||
scr_sha512_init(&ctx, sha384);
|
||||
for (size_t at = 0; at < len;) {
|
||||
size_t take = chunk == 0 || chunk > len - at ? len - at : chunk;
|
||||
scr_sha512_update(&ctx, data + at, take);
|
||||
at += take;
|
||||
}
|
||||
scr_sha512_final(&ctx, out, sha384);
|
||||
}
|
||||
|
||||
/* FIPS 180-4 example vectors for SHA-384 and SHA-512. */
|
||||
static void vectors512(const char *path) {
|
||||
unsigned char d[64];
|
||||
char text[129];
|
||||
static const char two_block[] =
|
||||
"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu";
|
||||
sha512_of((const unsigned char *)"abc", 3, 0, false, d);
|
||||
hex(d, 64, text);
|
||||
check(strcmp(text, "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f") == 0, path, 3, 0);
|
||||
sha512_of((const unsigned char *)"", 0, 0, false, d);
|
||||
hex(d, 64, text);
|
||||
check(strcmp(text, "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e") == 0, path, 0, 0);
|
||||
sha512_of((const unsigned char *)two_block, sizeof two_block - 1, 0, false, d);
|
||||
hex(d, 64, text);
|
||||
check(strcmp(text, "8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909") == 0, path, sizeof two_block - 1, 0);
|
||||
sha512_of((const unsigned char *)"abc", 3, 0, true, d);
|
||||
hex(d, 48, text);
|
||||
check(strcmp(text, "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7") == 0, path, 3, 0);
|
||||
sha512_of((const unsigned char *)two_block, sizeof two_block - 1, 0, true, d);
|
||||
hex(d, 48, text);
|
||||
check(strcmp(text, "09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712fcc7c71a557e2db966c3e9fa91746039") == 0, path, sizeof two_block - 1, 0);
|
||||
static unsigned char million[1000000];
|
||||
memset(million, 'a', sizeof million);
|
||||
sha512_of(million, sizeof million, 0, false, d);
|
||||
hex(d, 64, text);
|
||||
check(strcmp(text, "e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973ebde0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b") == 0, path, sizeof million, 0);
|
||||
sha512_of(million, sizeof million, 0, true, d);
|
||||
hex(d, 48, text);
|
||||
check(strcmp(text, "9d0e1809716474cb086e834e310a4a1ced149e9c00f248527972cec5704c2a5b07b8b3dc38ecc4ebae97ddd87f3d8985") == 0, path, sizeof million, 0);
|
||||
}
|
||||
|
||||
/* Selects the SHA-512 kernel: 0 the portable blocks, otherwise the CPU's
|
||||
* kernel. Returns false when the CPU has none. */
|
||||
static bool select512(int kernel) {
|
||||
#ifdef SCR_SHA_NI
|
||||
scr_sha512_x86_state = 0;
|
||||
int best = scr_sha512_x86();
|
||||
if (kernel > best - 1) return false;
|
||||
scr_sha512_x86_state = kernel == 0 ? 1 : kernel + 1;
|
||||
return true;
|
||||
#elif defined(SCR_SHA512_ARM)
|
||||
scr_sha512_arm_state = 0;
|
||||
bool available = scr_sha512_arm();
|
||||
if (kernel > (available ? 1 : 0)) return false;
|
||||
scr_sha512_arm_state = kernel == 0 ? 2 : 1;
|
||||
return true;
|
||||
#else
|
||||
return kernel == 0;
|
||||
#endif
|
||||
}
|
||||
|
||||
static const char *const kernel512_names[] = {"portable", "avx2-or-arm", "avx512"};
|
||||
|
||||
static void vectors(const char *path) {
|
||||
unsigned char d[32];
|
||||
char text[65];
|
||||
@@ -108,8 +175,31 @@ int main(void) {
|
||||
vectors("ni");
|
||||
}
|
||||
#endif
|
||||
/* SHA-512 and SHA-384: every kernel against the portable blocks, and
|
||||
* the known vectors through each. */
|
||||
int kernels512 = 0;
|
||||
for (int k = 0; k < 3 && select512(k); k++) {
|
||||
kernels512 = k + 1;
|
||||
vectors512(kernel512_names[k]);
|
||||
}
|
||||
for (int k = 1; k < kernels512; k++) {
|
||||
for (size_t len = 0; len <= 1100 + 1; len++) {
|
||||
size_t n = len == 1101 ? BIG : len;
|
||||
for (size_t c = 0; c < sizeof chunks / sizeof chunks[0]; c++) {
|
||||
for (int sha384 = 0; sha384 < 2; sha384++) {
|
||||
unsigned char a[64], b[64];
|
||||
select512(k);
|
||||
sha512_of(data, n, chunks[c], sha384, a);
|
||||
select512(0);
|
||||
sha512_of(data, n, chunks[c], sha384, b);
|
||||
check(memcmp(a, b, sha384 ? 48 : 64) == 0, kernel512_names[k], n, chunks[c]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
free(data);
|
||||
fprintf(stderr, "sha-ni %s\n", ni ? "available" : "absent");
|
||||
fprintf(stderr, "sha-512 kernels %d\n", kernels512);
|
||||
fprintf(stderr, "%ld/%ld cases passed\n", total - failed, total);
|
||||
return failed != 0;
|
||||
}
|
||||
|
||||
Generated
+78
@@ -106,6 +106,9 @@ importers:
|
||||
'@scriptc/runtime':
|
||||
specifier: workspace:*
|
||||
version: link:../runtime
|
||||
tsc-ts:
|
||||
specifier: 0.0.3
|
||||
version: 0.0.3
|
||||
typescript:
|
||||
specifier: 7.0.2
|
||||
version: 7.0.2
|
||||
@@ -1367,6 +1370,45 @@ packages:
|
||||
'@ts-morph/common@0.11.1':
|
||||
resolution: {integrity: sha512-7hWZS0NRpEsNV8vWJzg7FEz6V8MaLNeJOmwmghqUXTpzk16V1LLZhdo+4QvE/+zv4cVci0OviuJFnqhEfoV3+g==}
|
||||
|
||||
'@tsc-ts/darwin-arm64@0.0.3':
|
||||
resolution: {integrity: sha512-NSP4IhLx658tY21ub3ruraZwUwAC3GCbIf1eM0eOKUHfOBBXqq7LU/Loj3zvlvn/tJUyv2VdIDmzrWI/mxp5sA==}
|
||||
cpu: [arm64]
|
||||
os: [darwin]
|
||||
|
||||
'@tsc-ts/darwin-x64@0.0.3':
|
||||
resolution: {integrity: sha512-+BNvqyygkMx0/oHkjK8AmsPrE2+OcE/hGzT0wa2dndiH8lCSDBs+77C7Kmy/FSTWi9ItJShp1+AuWKgQPEOztg==}
|
||||
cpu: [x64]
|
||||
os: [darwin]
|
||||
|
||||
'@tsc-ts/linux-arm64-gnu@0.0.3':
|
||||
resolution: {integrity: sha512-I3v0J0L387TEkau0BTGiVx2GdstYfOrwVYwb0pJ/LbFURhrcGcsUODP5bdSOIYCtsp3aAX6e2afdqSIlpsxtbw==}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@tsc-ts/linux-arm64-musl@0.0.3':
|
||||
resolution: {integrity: sha512-f7wD9D6fC1xL7+ifvMAbJ0TqxOuZP04R2/7c8lb7Gor5SFKe85udJoxf0gocK7mbzWzmEiOJ53J1PujJLBVIxA==}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@tsc-ts/linux-x64-gnu@0.0.3':
|
||||
resolution: {integrity: sha512-BL9zownW4tHv/qqQkF8OlurHNDXi7xtGtJ6PV4qMeRYPMKsivTIGFRoZLW023KcLOr1Zptaof6X3zpv1nJEIpA==}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@tsc-ts/linux-x64-musl@0.0.3':
|
||||
resolution: {integrity: sha512-g4/lE5sULNGUVLM0Px/jrsjLsQQAYSiL+Rl+JZ+l5JE2k1dXroCejT2+IRB/NucVcz6N8EOUiCRZ13zl+Wtpcg==}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@tsc-ts/win32-x64-msvc@0.0.3':
|
||||
resolution: {integrity: sha512-oGtboSHgpuQP1dHAHqWyGjAWCpvHDpciYCi/2ywcp6MT+oOHxC99X48H/PZr29fzYVxCVeaEqWZ/VFU9qLZaKg==}
|
||||
cpu: [x64]
|
||||
os: [win32]
|
||||
|
||||
'@tybys/wasm-util@0.10.3':
|
||||
resolution: {integrity: sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==}
|
||||
|
||||
@@ -2524,6 +2566,11 @@ packages:
|
||||
ts-toolbelt@6.15.5:
|
||||
resolution: {integrity: sha512-FZIXf1ksVyLcfr7M317jbB67XFJhOO1YqdTcuGaq9q5jLUoTikukZ+98TPjKiP2jC5CgmYdWWYs0s2nLSU0/1A==}
|
||||
|
||||
tsc-ts@0.0.3:
|
||||
resolution: {integrity: sha512-Qr0i/BxP3ULIPDfr38vRb02x7sj6Q0r70Gubgu4ty2J4CEDCUKzT8RT2KMNqLXI3ZAhl7cncJq7a4LjKYZ1+0g==}
|
||||
engines: {node: '>=20'}
|
||||
hasBin: true
|
||||
|
||||
tslib@2.8.1:
|
||||
resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}
|
||||
|
||||
@@ -3394,6 +3441,27 @@ snapshots:
|
||||
mkdirp: 1.0.4
|
||||
path-browserify: 1.0.1
|
||||
|
||||
'@tsc-ts/darwin-arm64@0.0.3':
|
||||
optional: true
|
||||
|
||||
'@tsc-ts/darwin-x64@0.0.3':
|
||||
optional: true
|
||||
|
||||
'@tsc-ts/linux-arm64-gnu@0.0.3':
|
||||
optional: true
|
||||
|
||||
'@tsc-ts/linux-arm64-musl@0.0.3':
|
||||
optional: true
|
||||
|
||||
'@tsc-ts/linux-x64-gnu@0.0.3':
|
||||
optional: true
|
||||
|
||||
'@tsc-ts/linux-x64-musl@0.0.3':
|
||||
optional: true
|
||||
|
||||
'@tsc-ts/win32-x64-msvc@0.0.3':
|
||||
optional: true
|
||||
|
||||
'@tybys/wasm-util@0.10.3':
|
||||
dependencies:
|
||||
tslib: 2.8.1
|
||||
@@ -4730,6 +4798,16 @@ snapshots:
|
||||
|
||||
ts-toolbelt@6.15.5: {}
|
||||
|
||||
tsc-ts@0.0.3:
|
||||
optionalDependencies:
|
||||
'@tsc-ts/darwin-arm64': 0.0.3
|
||||
'@tsc-ts/darwin-x64': 0.0.3
|
||||
'@tsc-ts/linux-arm64-gnu': 0.0.3
|
||||
'@tsc-ts/linux-arm64-musl': 0.0.3
|
||||
'@tsc-ts/linux-x64-gnu': 0.0.3
|
||||
'@tsc-ts/linux-x64-musl': 0.0.3
|
||||
'@tsc-ts/win32-x64-msvc': 0.0.3
|
||||
|
||||
tslib@2.8.1:
|
||||
optional: true
|
||||
|
||||
|
||||
@@ -7,6 +7,14 @@ minimumReleaseAgeExclude:
|
||||
- "effect@4.0.0"
|
||||
- "@effect/platform-node@4.0.0"
|
||||
- "@effect/platform-node-shared@4.0.0"
|
||||
- "@tsc-ts/darwin-arm64@0.0.3"
|
||||
- "@tsc-ts/darwin-x64@0.0.3"
|
||||
- "@tsc-ts/linux-arm64-gnu@0.0.3"
|
||||
- "@tsc-ts/linux-arm64-musl@0.0.3"
|
||||
- "@tsc-ts/linux-x64-gnu@0.0.3"
|
||||
- "@tsc-ts/linux-x64-musl@0.0.3"
|
||||
- "@tsc-ts/win32-x64-msvc@0.0.3"
|
||||
- "tsc-ts@0.0.3"
|
||||
allowBuilds:
|
||||
esbuild: true
|
||||
overrides:
|
||||
|
||||
@@ -5,7 +5,7 @@ import { basename, dirname, join, relative, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { compile } from "../packages/compiler/src/index.js";
|
||||
import { NATIVE_TARGETS, nativeCodegenTarget } from "../packages/compiler/src/backend/targets.js";
|
||||
import { ts7Executable } from "../packages/compiler/src/frontend/ts7/rpc-api.js";
|
||||
import { tsgoExecutable } from "../packages/compiler/src/frontend/ts7/rpc-api.js";
|
||||
import { stageNativeCliAssets } from "./native-cli-assets.mjs";
|
||||
import type { NativeToolchainManifest } from "../packages/compiler/src/native/toolchain.js";
|
||||
|
||||
@@ -108,7 +108,7 @@ const assets = stageNativeCliAssets({
|
||||
repository: root,
|
||||
output,
|
||||
target,
|
||||
ts7: ts7Executable(),
|
||||
ts7: tsgoExecutable(),
|
||||
compilerVersion,
|
||||
});
|
||||
// A cross-libc seed may use Zig on the build host. The installed compiler
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
#!/usr/bin/env node
|
||||
// Compiles every corpus program to LLVM IR with each TypeScript 7 API server (tsc-ts, the default, and tsgo with
|
||||
// SCRIPTC_CHECKER=tsgo) and fails unless both give the same IR and the same diagnostics. The text of a checker panic
|
||||
// is the checker's own (Go's runtime error for tsgo, tsc-ts's for tsc-ts), so it is compared as `panic: …`.
|
||||
//
|
||||
// Usage: node scripts/checker-identity.mjs [--jobs <n>] [--optimization release|dev] [--filter <substring>]
|
||||
//
|
||||
// It needs `pnpm build`. Each checker compiles in its own worker processes, which read SCRIPTC_CHECKER when they
|
||||
// start their servers.
|
||||
import { fork } from "node:child_process";
|
||||
import { globSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
import { availableParallelism, tmpdir } from "node:os";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
import { parseArgs } from "node:util";
|
||||
|
||||
const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const corpusDir = join(repoRoot, "tests/corpus");
|
||||
const checkers = ["tsgo", "tsc-ts"];
|
||||
|
||||
if (process.argv[2] === "--worker") await worker(process.argv.slice(3));
|
||||
else await main();
|
||||
|
||||
async function main() {
|
||||
const { values } = parseArgs({
|
||||
options: {
|
||||
jobs: {
|
||||
type: "string",
|
||||
default: String(Math.max(1, Math.floor(availableParallelism() / 2))),
|
||||
},
|
||||
optimization: { type: "string", default: "release" },
|
||||
filter: { type: "string", default: "" },
|
||||
},
|
||||
});
|
||||
if (values.optimization !== "release" && values.optimization !== "dev")
|
||||
throw new Error("--optimization must be release or dev");
|
||||
// The entries llvm-differential.test.ts compiles.
|
||||
const entries = ["ts", "js", "mjs", "cjs"]
|
||||
.flatMap((ext) => [
|
||||
...globSync(join(corpusDir, `*.${ext}`)),
|
||||
...globSync(join(corpusDir, `*/main.${ext}`)),
|
||||
])
|
||||
.filter((file) => file.includes(values.filter))
|
||||
.sort();
|
||||
const jobs = Math.max(1, Number(values.jobs));
|
||||
const outRoot = mkdtempSync(join(tmpdir(), "scriptc-checker-identity-"));
|
||||
try {
|
||||
const results = new Map(checkers.map((checker) => [checker, new Map()]));
|
||||
const runs = [];
|
||||
for (const checker of checkers)
|
||||
for (let index = 0; index < jobs; index++)
|
||||
runs.push(
|
||||
new Promise((done, fail) => {
|
||||
const child = fork(
|
||||
fileURLToPath(import.meta.url),
|
||||
[
|
||||
"--worker",
|
||||
join(outRoot, checker),
|
||||
values.optimization,
|
||||
...entries.filter((_, i) => i % jobs === index),
|
||||
],
|
||||
{ env: { ...process.env, SCRIPTC_CHECKER: checker } },
|
||||
);
|
||||
child.on("message", (record) => results.get(checker).set(record.file, record));
|
||||
child.on("error", fail);
|
||||
child.on("exit", (code) =>
|
||||
code === 0 ? done() : fail(new Error(`${checker} worker exited with ${code}`)),
|
||||
);
|
||||
}),
|
||||
);
|
||||
await Promise.all(runs);
|
||||
const differences = [];
|
||||
for (const file of entries) {
|
||||
const [a, b] = checkers.map((checker) => results.get(checker).get(file));
|
||||
const name = file.slice(corpusDir.length + 1);
|
||||
if (a === undefined || b === undefined) differences.push(`${name}: not compiled`);
|
||||
else if (a.ok !== b.ok || withoutPanicText(a.diagnostics) !== withoutPanicText(b.diagnostics))
|
||||
differences.push(
|
||||
`${name}: tsgo ${a.ok ? "compiles" : a.diagnostics}; tsc-ts ${b.ok ? "compiles" : b.diagnostics}`,
|
||||
);
|
||||
else if (a.ok && irWithoutPanicText(a.llvm) !== irWithoutPanicText(b.llvm))
|
||||
differences.push(`${name}: LLVM IR differs`);
|
||||
}
|
||||
if (differences.length > 0) {
|
||||
console.error(
|
||||
`${differences.length} of ${entries.length} programs differ between tsgo and tsc-ts:`,
|
||||
);
|
||||
for (const line of differences) console.error(` ${line}`);
|
||||
process.exitCode = 1;
|
||||
} else {
|
||||
console.log(
|
||||
`${entries.length} programs: tsgo and tsc-ts give the same LLVM IR and diagnostics (${values.optimization}).`,
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
rmSync(outRoot, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
/** A diagnostic list with each SC0004 checker panic's text replaced by `…`. */
|
||||
function withoutPanicText(diagnostics) {
|
||||
return diagnostics?.replace(/(SC0004: [^;]*?: panic: )[^;]*/g, "$1…");
|
||||
}
|
||||
|
||||
/** A module's LLVM IR with each SC0004 checker panic's text replaced by `…`. A fence statement keeps the
|
||||
* diagnostic's message in a string constant named for a hash of its contents, and passes its length. */
|
||||
function irWithoutPanicText(llvm) {
|
||||
let ir = readFileSync(llvm, "utf8");
|
||||
const constant =
|
||||
/^(@sc_cs_\d+) = internal constant \[\d+ x i8\] c"(the TypeScript checker crashed answering a query here [^"]*?: panic: )[^"]*?( \[SC0004 at [^"]*)"$/gm;
|
||||
const names = [];
|
||||
ir = ir.replace(constant, (_, name, head, tail) => {
|
||||
names.push(name);
|
||||
return `@checker_panic_${names.length} = internal constant c"${head}…${tail}"`;
|
||||
});
|
||||
names.forEach((name, index) => {
|
||||
ir = ir.replace(
|
||||
new RegExp(`${name}\\b(, i64 \\d+)?`, "g"),
|
||||
(_, length) => `@checker_panic_${index + 1}${length === undefined ? "" : ", i64 …"}`,
|
||||
);
|
||||
});
|
||||
return ir;
|
||||
}
|
||||
|
||||
async function worker([outDir, optimization, ...files]) {
|
||||
const { compile } = await import(
|
||||
pathToFileURL(join(repoRoot, "packages/compiler/dist/index.js")).href
|
||||
);
|
||||
for (const file of files) {
|
||||
const name = file.slice(corpusDir.length + 1);
|
||||
const llvm = join(outDir, `${name}.ll`);
|
||||
let record;
|
||||
try {
|
||||
const result = await compile(file, {
|
||||
outputKind: "llvm",
|
||||
outPath: llvm,
|
||||
outDir: join(outDir, ".work", name),
|
||||
optimization,
|
||||
});
|
||||
record = result.ok
|
||||
? { file, ok: true, llvm }
|
||||
: {
|
||||
file,
|
||||
ok: false,
|
||||
diagnostics: result.diagnostics.map((d) => `${d.code}: ${d.message}`).join("; "),
|
||||
};
|
||||
} catch (error) {
|
||||
record = {
|
||||
file,
|
||||
ok: false,
|
||||
diagnostics: `threw ${error instanceof Error ? error.message : String(error)}`,
|
||||
};
|
||||
}
|
||||
process.send(record);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,10 @@ import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync
|
||||
import { basename, dirname, join, relative } from "node:path";
|
||||
import type { NativeTargetSpec } from "../packages/compiler/src/backend/targets.js";
|
||||
import type { NativeToolchainManifest } from "../packages/compiler/src/native/toolchain.js";
|
||||
import {
|
||||
tscTsExecutable,
|
||||
tscTsPlatformPackage,
|
||||
} from "../packages/compiler/src/frontend/ts7/checker-backend.js";
|
||||
|
||||
/** Copy release payloads explicitly; development caches and build trees never ship. */
|
||||
function copyPackage(source: string, destination: string, members: readonly string[]): void {
|
||||
@@ -28,6 +32,7 @@ export function stageNativeCliAssets(options: {
|
||||
}): Pick<
|
||||
NativeToolchainManifest,
|
||||
| "ts7"
|
||||
| "tsc_ts"
|
||||
| "llvm_package"
|
||||
| "runtime_pack"
|
||||
| "runtime_packs"
|
||||
@@ -54,6 +59,14 @@ export function stageNativeCliAssets(options: {
|
||||
);
|
||||
const typescript = join(lib, "typescript");
|
||||
copyPackage(dirname(dirname(options.ts7)), typescript, ["lib"]);
|
||||
// tsc-ts, the default checker, from the tsc-ts package the compiler depends on.
|
||||
const tscTsSource = tscTsExecutable(
|
||||
[join(repository, "packages/compiler")],
|
||||
tscTsPlatformPackage(target.platform, target.architecture, target.name.endsWith("-musl")),
|
||||
target.platform,
|
||||
);
|
||||
const tscTs = join(lib, "tsc-ts");
|
||||
copyPackage(dirname(dirname(tscTsSource)), tscTs, ["lib"]);
|
||||
const sources = join(lib, "runtime-sources");
|
||||
copyPackage(join(repository, "packages/runtime"), sources, ["src", "vendor"]);
|
||||
const declarations = join(lib, "declarations");
|
||||
@@ -74,11 +87,15 @@ export function stageNativeCliAssets(options: {
|
||||
const identity = JSON.parse(readFileSync(join(typescript, "package.json"), "utf8")) as {
|
||||
version: string;
|
||||
};
|
||||
const tscTsIdentity = JSON.parse(readFileSync(join(tscTs, "package.json"), "utf8")) as {
|
||||
version: string;
|
||||
};
|
||||
writeFileSync(
|
||||
join(output, "THIRD_PARTY_NOTICES"),
|
||||
[
|
||||
`scriptc ${options.compilerVersion} includes the existing TypeScript ${identity.version}, LLVM, and C runtime dependencies.`,
|
||||
`scriptc ${options.compilerVersion} includes the existing TypeScript ${identity.version}, tsc-ts ${tscTsIdentity.version}, LLVM, and C runtime dependencies.`,
|
||||
"TypeScript licensing: lib/typescript/LICENSE and lib/typescript/NOTICE.txt.",
|
||||
"tsc-ts licensing and notices: lib/tsc-ts/LICENSE and lib/tsc-ts/THIRD_PARTY_NOTICES.md.",
|
||||
"LLVM licensing and notices: lib/llvm/LICENSE and lib/llvm/THIRD_PARTY_NOTICES.",
|
||||
"Runtime dependency licenses: lib/runtime-sources/vendor/*/LICENSE*.",
|
||||
"",
|
||||
@@ -86,6 +103,7 @@ export function stageNativeCliAssets(options: {
|
||||
);
|
||||
return {
|
||||
ts7: relative(bin, join(typescript, "lib", basename(options.ts7))),
|
||||
tsc_ts: relative(bin, join(tscTs, "lib", basename(tscTsSource))),
|
||||
llvm_package: relative(bin, helper),
|
||||
runtime_pack: relative(bin, runtime),
|
||||
runtime_packs: [{ target: target.name, path: relative(bin, runtime) }],
|
||||
|
||||
@@ -44,6 +44,7 @@ for (const name of readdirSync(packages)
|
||||
for (const path of [
|
||||
binary,
|
||||
resolve(bin, hostPath(manifest.ts7)),
|
||||
resolve(bin, hostPath(manifest.tsc_ts)),
|
||||
resolve(bin, hostPath(manifest.comptime)),
|
||||
join(
|
||||
resolve(bin, hostPath(manifest.llvm_package)),
|
||||
|
||||
@@ -28,6 +28,7 @@ const within = (path) => {
|
||||
};
|
||||
for (const name of [
|
||||
"ts7",
|
||||
"tsc_ts",
|
||||
"llvm_package",
|
||||
"runtime_pack",
|
||||
"runtime_sources",
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
// SHA-384 and SHA-512 over every length from 0 to 520 bytes, fed whole and
|
||||
// in 1-, 7-, 100- and 128-byte updates, then over 1 MiB, and HMAC-SHA512
|
||||
// over a few lengths. Each length's digests are folded into one running
|
||||
// SHA-512 so the output stays short. The CPU's SHA-512 kernel (vector or
|
||||
// SHA-512 instructions) and the portable blocks give the same digests.
|
||||
import { createHash, createHmac } from "node:crypto";
|
||||
|
||||
const data = Buffer.alloc(1 << 20);
|
||||
let x = 0x9e3779b9;
|
||||
for (let i = 0; i < data.length; i++) {
|
||||
x ^= x << 13;
|
||||
x ^= x >>> 17;
|
||||
x ^= x << 5;
|
||||
data[i] = x & 0xff;
|
||||
}
|
||||
|
||||
function digest(algorithm: string, input: Buffer, chunk: number): Buffer {
|
||||
const hash = createHash(algorithm);
|
||||
if (chunk === 0) hash.update(input);
|
||||
else for (let at = 0; at < input.length; at += chunk) hash.update(input.subarray(at, at + chunk));
|
||||
return hash.digest();
|
||||
}
|
||||
|
||||
for (const algorithm of ["sha384", "sha512"]) {
|
||||
for (const chunk of [0, 1, 7, 100, 128]) {
|
||||
const fold = createHash("sha512");
|
||||
for (let length = 0; length <= 520; length++) fold.update(digest(algorithm, data.subarray(0, length), chunk));
|
||||
console.log(algorithm, "chunk", chunk, fold.digest("hex").slice(0, 32));
|
||||
}
|
||||
console.log(algorithm, "1 MiB", digest(algorithm, data, 0).toString("hex").slice(0, 32), digest(algorithm, data, 4096).toString("hex").slice(0, 32));
|
||||
}
|
||||
console.log("abc", createHash("sha512").update("abc").digest("hex"));
|
||||
for (const length of [0, 1, 111, 112, 127, 128, 129, 255, 256, 1000]) {
|
||||
console.log("hmac", length, createHmac("sha512", "key").update(data.subarray(0, length)).digest("hex").slice(0, 32));
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
// Classes whose [Symbol.iterator] is a generator method iterate the
|
||||
// generator it returns, called once: in for-of (an early exit closes it),
|
||||
// array and Math.max spreads, Array.from, new Set, new Map,
|
||||
// Object.fromEntries and yield*.
|
||||
class Counter implements Iterable<number> {
|
||||
n: number;
|
||||
constructor(n: number) {
|
||||
this.n = n;
|
||||
}
|
||||
*[Symbol.iterator](): Generator<number> {
|
||||
for (let i = 0; i < this.n; i++) yield i;
|
||||
}
|
||||
}
|
||||
const c = new Counter(3);
|
||||
for (const v of c) console.log("of", v);
|
||||
console.log([...c], Array.from(c), Math.max(...c));
|
||||
for (const v of c) {
|
||||
if (v === 1) break;
|
||||
console.log("early", v);
|
||||
}
|
||||
|
||||
class Pairs implements Iterable<[string, number]> {
|
||||
*[Symbol.iterator](): Generator<[string, number]> {
|
||||
yield ["a", 1];
|
||||
yield ["b", 2];
|
||||
}
|
||||
}
|
||||
class Nums implements Iterable<number> {
|
||||
*[Symbol.iterator](): Generator<number> {
|
||||
yield 1;
|
||||
yield 2;
|
||||
yield 2;
|
||||
}
|
||||
}
|
||||
const p = new Pairs();
|
||||
const n = new Nums();
|
||||
console.log(new Set(n).size);
|
||||
console.log(new Map(p).get("b"));
|
||||
|
||||
console.log(Object.fromEntries(p));
|
||||
function* outer(): Generator<number> {
|
||||
yield 0;
|
||||
yield* n;
|
||||
}
|
||||
console.log([...outer()]);
|
||||
function* plain(): Generator<number> {
|
||||
yield 3;
|
||||
yield 3;
|
||||
yield 4;
|
||||
}
|
||||
console.log(new Set(plain()).size, [...new Set(n)]);
|
||||
|
||||
class Tracked implements Iterable<string> {
|
||||
log: string[] = [];
|
||||
*[Symbol.iterator](): Generator<string> {
|
||||
try {
|
||||
for (const word of ["a", "b", "c"]) {
|
||||
this.log.push("yield " + word);
|
||||
yield word;
|
||||
}
|
||||
} finally {
|
||||
this.log.push("closed");
|
||||
}
|
||||
}
|
||||
}
|
||||
const t = new Tracked();
|
||||
for (const w of t) {
|
||||
if (w === "b") break;
|
||||
t.log.push("saw " + w);
|
||||
}
|
||||
console.log(t.log.join(", "));
|
||||
class Tree implements Iterable<number> {
|
||||
value: number;
|
||||
children: Tree[];
|
||||
constructor(value: number, children: Tree[] = []) {
|
||||
this.value = value;
|
||||
this.children = children;
|
||||
}
|
||||
*[Symbol.iterator](): Generator<number> {
|
||||
yield this.value;
|
||||
for (const child of this.children) yield* child;
|
||||
}
|
||||
}
|
||||
class Leafy extends Tree {}
|
||||
const tree = new Tree(1, [new Tree(2, [new Tree(3)]), new Leafy(4)]);
|
||||
console.log([...tree], Array.from(new Leafy(9)), Math.min(...tree));
|
||||
@@ -0,0 +1,78 @@
|
||||
// Well-known symbol methods called through element access, and
|
||||
// Iterator.from over a class whose [Symbol.iterator] is a generator method:
|
||||
// both give the class's own generator, so iterator helpers apply to it.
|
||||
class Range {
|
||||
lo: number;
|
||||
hi: number;
|
||||
constructor(lo: number, hi: number) {
|
||||
this.lo = lo;
|
||||
this.hi = hi;
|
||||
}
|
||||
*[Symbol.iterator](): Generator<number> {
|
||||
for (let i = this.lo; i < this.hi; i++) yield i;
|
||||
}
|
||||
}
|
||||
class Labeled extends Range {
|
||||
label = "l";
|
||||
}
|
||||
class Words {
|
||||
text: string;
|
||||
constructor(text: string) {
|
||||
this.text = text;
|
||||
}
|
||||
*[Symbol.iterator](): Generator<string> {
|
||||
for (const w of this.text.split(" ")) yield w;
|
||||
}
|
||||
}
|
||||
class Money {
|
||||
cents: number;
|
||||
constructor(cents: number) {
|
||||
this.cents = cents;
|
||||
}
|
||||
[Symbol.toPrimitive](hint: string): string | number {
|
||||
return hint === "number" ? this.cents / 100 : `$${(this.cents / 100).toFixed(2)}`;
|
||||
}
|
||||
}
|
||||
class Handle {
|
||||
name: string;
|
||||
constructor(name: string) {
|
||||
this.name = name;
|
||||
}
|
||||
[Symbol.dispose](): void {
|
||||
console.log("dispose", this.name);
|
||||
}
|
||||
}
|
||||
|
||||
const r = new Range(1, 6);
|
||||
const direct = r[Symbol.iterator]();
|
||||
console.log(direct.next(), direct.next());
|
||||
console.log(r[Symbol.iterator]().map((x) => x + 1).toArray());
|
||||
const ranges: Range[] = [new Range(0, 3), new Labeled(5, 7)];
|
||||
for (const x of ranges) console.log(x[Symbol.iterator]().toArray());
|
||||
console.log(r[Symbol.iterator]().filter((x) => x > 3).toArray());
|
||||
|
||||
const it = Iterator.from(r);
|
||||
console.log(it.next().value, it.next().value);
|
||||
console.log([...it]);
|
||||
console.log(Iterator.from(r).map((x) => x * 10).toArray());
|
||||
console.log(Iterator.from(r).filter((x) => x % 2 === 1).toArray());
|
||||
console.log(Iterator.from(r).take(2).toArray(), Iterator.from(r).drop(3).toArray());
|
||||
console.log(Iterator.from(r).reduce((a, b) => a + b, 0));
|
||||
console.log(Iterator.from(r).some((x) => x > 4), Iterator.from(r).every((x) => x > 0));
|
||||
console.log(Iterator.from(r).find((x) => x > 2));
|
||||
console.log(Iterator.from(new Words("a bb ccc")).map((w) => w.length).toArray());
|
||||
Iterator.from(r).forEach((x) => console.log("each", x));
|
||||
for (const x of Iterator.from(r).flatMap((x) => [x, -x]).take(4)) console.log(x);
|
||||
const g = Iterator.from(r);
|
||||
for (const x of g) {
|
||||
if (x === 2) break;
|
||||
}
|
||||
console.log(g.next());
|
||||
|
||||
console.log(Iterator.from(r), r[Symbol.iterator](), Iterator.from(r).map((x) => x));
|
||||
console.log(Iterator.from(r).flatMap((x) => new Set([x, x + 10])).toArray());
|
||||
console.log(r[Symbol.iterator]().flatMap((x) => new Map([[x, String(x)]])).toArray());
|
||||
|
||||
const m = new Money(1234);
|
||||
console.log(m[Symbol.toPrimitive]("number"), m[Symbol.toPrimitive]("default"));
|
||||
new Handle("h")[Symbol.dispose]();
|
||||
@@ -0,0 +1,63 @@
|
||||
// Classes extending Node builtin bases (Writable, Transform, EventEmitter)
|
||||
// used as values: through a variable, a generic factory, an object table and
|
||||
// an array, with instanceof against the class and its base.
|
||||
import { EventEmitter } from "node:events";
|
||||
import { Readable, Transform, Writable } from "node:stream";
|
||||
|
||||
class Sink extends Writable {
|
||||
readonly lines: string[] = [];
|
||||
private readonly tag: string;
|
||||
constructor(tag: string) {
|
||||
super();
|
||||
this.tag = tag;
|
||||
}
|
||||
_write(chunk: Buffer, _enc: BufferEncoding, cb: (err?: Error | null) => void): void {
|
||||
this.lines.push(this.tag + chunk.toString());
|
||||
cb();
|
||||
}
|
||||
}
|
||||
|
||||
class Upper extends Transform {
|
||||
_transform(chunk: Buffer, _enc: BufferEncoding, cb: (err?: Error | null, data?: string) => void): void {
|
||||
cb(null, chunk.toString().toUpperCase());
|
||||
}
|
||||
}
|
||||
|
||||
class Ticker extends EventEmitter {
|
||||
count = 0;
|
||||
tick(): void {
|
||||
this.count++;
|
||||
this.emit("tick", this.count);
|
||||
}
|
||||
}
|
||||
|
||||
class Plain extends EventEmitter {}
|
||||
|
||||
function build<T>(ctor: new () => T): T {
|
||||
return new ctor();
|
||||
}
|
||||
|
||||
const SinkClass = Sink;
|
||||
const s = new SinkClass("> ");
|
||||
s.write("a");
|
||||
s.end("b", () => console.log("sink", JSON.stringify(s.lines), s instanceof Sink, s instanceof Writable));
|
||||
|
||||
const t = build(Ticker);
|
||||
t.on("tick", (n: number) => console.log("tick", n));
|
||||
t.tick();
|
||||
t.tick();
|
||||
console.log("ticker", t instanceof Ticker, t instanceof EventEmitter, t.count);
|
||||
|
||||
const p = build(Plain);
|
||||
p.on("x", () => console.log("plain x"));
|
||||
p.emit("x");
|
||||
|
||||
const registry = { upper: Upper };
|
||||
const u = new registry.upper();
|
||||
u.on("data", (d: Buffer) => console.log("upper", d.toString()));
|
||||
u.end("hello");
|
||||
|
||||
const kinds = [Ticker, Ticker];
|
||||
console.log("names", kinds.map((k) => k.name).join(","), typeof Sink, Sink.name);
|
||||
const r = Readable.from(["x"]);
|
||||
console.log("readable", r instanceof Readable);
|
||||
@@ -0,0 +1,46 @@
|
||||
// Class expressions extending Node builtin bases (a bundler's output shape).
|
||||
"use strict";
|
||||
const { Readable, Transform } = require("stream");
|
||||
const { EventEmitter } = require("events");
|
||||
|
||||
const Wrap = class extends Readable {
|
||||
constructor(parts) {
|
||||
super();
|
||||
this.parts = parts;
|
||||
}
|
||||
_read() {
|
||||
const next = this.parts.shift();
|
||||
this.push(next === undefined ? null : next);
|
||||
}
|
||||
};
|
||||
const Bus = class extends EventEmitter {};
|
||||
const Lower = class extends Transform {
|
||||
_transform(chunk, _enc, cb) {
|
||||
cb(null, chunk.toString().toLowerCase());
|
||||
}
|
||||
};
|
||||
|
||||
const r = new Wrap(["a", "b"]);
|
||||
const chunks = [];
|
||||
r.on("data", (c) => chunks.push(c.toString()));
|
||||
r.on("end", () => console.log("wrap", chunks.join("+"), r instanceof Readable));
|
||||
const bus = new Bus();
|
||||
bus.on("ping", (n) => console.log("ping", n));
|
||||
bus.emit("ping", 1);
|
||||
const l = new Lower();
|
||||
l.on("data", (d) => console.log("lower", d.toString()));
|
||||
l.end("HeLLo");
|
||||
console.log(Wrap.name, Bus.name, typeof Lower);
|
||||
{
|
||||
// A class declared in a block is collected like a class expression.
|
||||
class Once extends Readable {
|
||||
_read() {
|
||||
this.push(null);
|
||||
}
|
||||
}
|
||||
function onReadable() {
|
||||
console.log("block", stream.read() === null);
|
||||
}
|
||||
const stream = new Once();
|
||||
stream.once("readable", onReadable);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
// A callback whose returns extend the elements it was given keeps the
|
||||
// added members once its result type names them (an annotation on the
|
||||
// callback or on the type argument), as Node keeps them on the objects.
|
||||
type Plain = { name: string; n: number };
|
||||
type Item = Plain & { extra?: boolean };
|
||||
const plain: Plain[] = [
|
||||
{ name: "a", n: 1 },
|
||||
{ name: "b", n: 2 },
|
||||
];
|
||||
|
||||
function run<T>(fn: () => T): T {
|
||||
return fn();
|
||||
}
|
||||
async function runAsync<T>(fn: () => Promise<T>): Promise<T> {
|
||||
return fn();
|
||||
}
|
||||
|
||||
const annotated = run((): Item[] => {
|
||||
if (plain.length === 0) return plain;
|
||||
return plain.map((x) => ({ ...x, extra: x.n > 1 }));
|
||||
});
|
||||
console.log(JSON.stringify(annotated));
|
||||
|
||||
const viaTypeArgument = run<Item[]>(() => {
|
||||
if (plain.length > 5) return plain;
|
||||
return plain.map((x) => ({ ...x, extra: true }));
|
||||
});
|
||||
console.log(JSON.stringify(viaTypeArgument), viaTypeArgument[0]!.extra);
|
||||
|
||||
runAsync(async (): Promise<Item[]> => {
|
||||
if (plain.length === 0) return plain;
|
||||
return plain.map((x) => ({ ...x, extra: false }));
|
||||
}).then((items) => console.log(items));
|
||||
|
||||
// Callbacks whose results the checker types by their own returns keep
|
||||
// every member already.
|
||||
const mapped = plain.map((x) => (x.n > 1 ? x : { ...x, extra: true }));
|
||||
const asItems: Item[] = mapped;
|
||||
console.log(JSON.stringify(asItems));
|
||||
const summed = plain.reduce((acc, x) => ({ ...acc, total: acc.total + x.n }), { total: 0, label: "sum" });
|
||||
console.log(JSON.stringify(summed));
|
||||
@@ -0,0 +1,15 @@
|
||||
// `return log(), null` from a function that otherwise returns a list: the
|
||||
// comma expression's effects run, then null takes the result's
|
||||
// representation.
|
||||
"use strict";
|
||||
async function promote(list) {
|
||||
if (list.length === 0) return console.log("no static mounts"), null;
|
||||
return list.map((x) => x * 2);
|
||||
}
|
||||
function first(list) {
|
||||
if (list.length === 0) return console.log("empty"), undefined;
|
||||
return list[0];
|
||||
}
|
||||
promote([]).then((v) => console.log("promoted", v));
|
||||
promote([1, 2]).then((v) => console.log("promoted", v));
|
||||
console.log(first([]), first([7]));
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user