Merge main

This commit is contained in:
Chris Tate
2026-10-20 10:22:00 -05:00
475 changed files with 17018 additions and 755 deletions
+47 -1
View File
@@ -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 }}"
+3
View File
@@ -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-&lt;target&gt;</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
-1
View File
@@ -79,7 +79,6 @@ Some code compiles but can behave differently than under Node.js. Coverage repor
- `SC6002`: values of one record type are built in different key orders, so the type keeps its declaration order, an object literal's key order differs from it, and the program observes the order through `JSON.stringify`, `Object.keys`, `Object.values`, `Object.entries`, `for...in`, or console output.
- `SC6003`: `localeCompare` compares a string literal outside the built-in Latin-script collation.
- `SC6004`: a call passes a class instance to a function that casts it to an unrelated class.
- `SC6005`: a `Date` string literal uses a form the native parser does not accept.
## Gating builds and CI
+8 -6
View File
@@ -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
+4
View File
@@ -228,6 +228,10 @@ title: "Limitations"
<include>../limitations/process-arguments-and-errors.mdx</include>
### Module path globals
<include>../limitations/module-path-globals.mdx</include>
<span id="embedded-javascript-engine" />
## Runtime code evaluation
@@ -1,5 +1,5 @@
- **Date:** Date unions, year/month constructors, setters, statically typed TypeScript identity comparisons, thrown Date values, and locale formatters are unsupported.
Zero-argument and single number/string constructors, storage and passing, `getTime`, `valueOf`, `toISOString`, `toUTCString`, `toJSON` (a `string | null`: null for an invalid date, as in Node), `toString`, `toDateString`, `toTimeString`, `String(date)` and template literal conversion, calendar getters, `getTimezoneOffset`, and single-string `Date.parse` compile.
- **Date:** Date unions, spread constructor arguments, setters, statically typed TypeScript identity comparisons, thrown Date values, and locale formatters are unsupported.
Zero-argument, single number/string, and local-time year/month field constructors, storage and passing, `getTime`, `valueOf`, `toISOString`, `toUTCString`, `toJSON` (a `string | null`: null for an invalid date, as in Node), `toString`, `toDateString`, `toTimeString`, `String(date)` and template literal conversion, calendar getters, `getTimezoneOffset`, and single-string `Date.parse` compile.
JavaScript Dates retain identity through checked storage and support Date-copy construction and JSON serialization.
A TypeScript Date converted to `unknown` becomes a Date with the same time value; each conversion creates a new Date, so two `unknown` values converted from one TypeScript Date are not `===`.
See [Dates and timezones](#dates-and-timezones) for parsing restrictions.
See [Dates and timezones](#dates-and-timezones) for timezone data.
@@ -1,3 +1,4 @@
- **Exit status:** Numeric `process.exitCode = value` writes in statement position set the implicit exit status, which `process.exit()` uses when called without an argument.
`process.exit(code)` and `process.exitCode` throw a `RangeError` (`ERR_OUT_OF_RANGE`) for a code that is not a safe integer, and convert other codes to int32, as Node does.
Reads, resets, and assignments used as values are unsupported.
Reading `process.exitCode` answers the assigned code, or `undefined` before any assignment; `process.exit(code)` assigns it before the `'exit'` listeners run.
Resets (`process.exitCode = undefined`) and assignments used as values are unsupported.
@@ -1,3 +1,8 @@
- **Object freezing:** `Object.freeze` and `Object.isFrozen` support plain checked dictionaries and primitives.
Freezing is shallow and preserves accessors.
Aliased typed records, arrays, proxies, and other native objects cannot be frozen.
Class instances support `Object.freeze`, `Object.seal`, `Object.preventExtensions`, `Object.isFrozen`, `Object.isSealed`, and `Object.isExtensible` when the static type of the argument names the class.
A write to a read-only field throws Node's `TypeError` in strict mode code and leaves the field unchanged in sloppy mode code.
`Object.defineProperty` with a string-literal key changes the value, `writable`, `enumerable`, and `configurable` attributes of a declared field; an object-literal accessor descriptor (`get` or `set`) for a declared field is refused at compile time with `SC2020`, and another accessor descriptor for a declared field throws `SC2020` when the call runs.
Freezing, sealing, or preventing extensions of a class instance held in an untyped value throws `SC2020`.
A JavaScript class field that is first created after its instance became non-extensible is added instead of throwing.
@@ -1,2 +1,6 @@
- **Prototypes:** Named properties and methods on program class prototypes support replacement, inheritance, and deletion.
Bare prototype reflection, accessor replacement, and prototype storage on local, generic, mixin, or runtime-provided classes are unsupported.
Plain objects, arrays, functions, class instances, and Date, RegExp, Map, Set, WeakMap, WeakSet, and Promise values inherit `constructor`, `valueOf`, `toString`, `hasOwnProperty`, and `propertyIsEnumerable` from `Object.prototype` as in Node, so `value.constructor === Object` and `value.valueOf === Object.prototype.valueOf` compare identities exactly.
Named reads such as `value.valueOf` answer these inherited members; computed-key reads such as `value[key]` do not.
`Object.prototype`'s own members read as values; its mutation and other reflection, such as `isPrototypeOf` and `__proto__`, are unsupported.
The constructors `Object`, `Function`, `Date`, `RegExp`, `Map`, `Set`, `WeakMap`, `WeakSet`, and `Promise` read as function values; through a stored value only `Object` can be called, and `instanceof` and `new` against them remain unsupported.
@@ -3,7 +3,8 @@
Class instances, builtin objects, and object literals whose methods use `this` throw `SC2020`.
Calls through the object record it as `this`, including calls of a method read off the object and called on its own, where Node records `undefined`.
`object.method === mock` is `false`, because the field holds a wrapper of the mock.
`mock.fn()` without an original, `mock.getter`, `mock.setter`, `mock.property`, `mock.module` and mock options throw `SC2020`.
`mock.fn()` without an original returns `undefined` and records the arguments of each call, as in Node; with a function type whose return type does not include `undefined`, such as `mock.fn<() => number>()`, it throws `SC2020`.
`mock.getter`, `mock.setter`, `mock.property`, `mock.module` and mock options throw `SC2020`.
- **Mock timers:** `mock.timers.enable`, `tick`, `runAll`, `reset`, `setTime` and `[Symbol.dispose]()` compile, on the module's `mock` and on `t.mock`, for the `setTimeout`, `setInterval`, `setImmediate`, `Date`, `scheduler.wait` and `AbortSignal.timeout` APIs.
`enable()` takes no options or an object literal whose `apis`, when given, is an array literal.
Options and `apis` lists that are not literals, and the `MockTimers` object used as a value, throw `SC2020`.
@@ -5,6 +5,10 @@ Some builtins can be stored and passed as functions:
- `util.isDeepStrictEqual`, `styleText`, `stripVTControlCharacters`, `toUSVString`, `inherits`, `deprecate`, `callbackify`, `debuglog`, and `debug`.
- `fs.existsSync`, `unlinkSync`, `chmodSync`, `chownSync`, `renameSync`, and `closeSync`, and `fs/promises.unlink`, `chmod`, and `rename`.
In JavaScript, `setTimeout`, `setInterval`, `setImmediate`, `clearTimeout`, `clearInterval`, `clearImmediate`, `queueMicrotask`, and `process.nextTick` are function values wherever they are stored, including conditional and logical expressions and assignments: `typeof` answers `"function"`, identity holds across spellings, and calls schedule as the direct calls do, returning the same numeric timer handles.
Calls through these values bypass `node:test` mock timers.
Other builtin globals stored in JavaScript remain opaque identity values.
Other immutable aliases of table-backed Node builtins support direct calls, but cannot be passed elsewhere.
`util.promisify` supports compile-time conversions of `child_process.execFile`, `child_process.exec`, `setTimeout` and `setImmediate` (to the `timers/promises` functions, as in Node), `stream.finished` and `stream.pipeline` (to the `stream/promises` functions, as in Node), the `zlib` callback one-shots `deflate`, `inflate`, `deflateRaw`, `inflateRaw`, `gzip`, `gunzip` and `unzip` (with or without options), the `crypto` callback functions `randomBytes`, `pbkdf2`, `scrypt`, `hkdf`, `randomFill`, `randomInt` and `generateKey`, `dns.lookup` (settling with `{ address, family }`, or the address array with `all: true`) and `dns.lookupService` (settling with `{ hostname, service }`), and the `fs` callback functions that have an `fs/promises` counterpart (`access`, `appendFile`, `chmod`, `chown`, `copyFile`, `lchown`, `link`, `lstat`, `lutimes`, `mkdir`, `mkdtemp`, `readFile`, `readdir`, `readlink`, `realpath`, `rename`, `rm`, `rmdir`, `stat`, `statfs`, `symlink`, `truncate`, `unlink`, `utimes`, and `writeFile`); calls through the converted function lower as the `fs/promises` call.
@@ -1,7 +1,7 @@
String constructors and `Date.parse` accept ECMAScript date-only forms, date-times with an explicit `Z` or numeric offset, and GMT certificate-validity strings from the supported X509 APIs.
Other V8-specific forms and offset-less local date-times produce an Invalid Date or `NaN`; `SC6005` reports string literals in those forms.
String constructors and `Date.parse` use V8's date-string grammar: ECMAScript date-time strings and the legacy forms Node.js accepts, such as RFC 1123 HTTP dates (`Mon, 01 Jan 2024 00:00:00 GMT`), `Date#toString` output, and `Jan 2, 2024`.
Strings without a timezone, and `new Date(year, monthIndex, ...)` fields, are local time.
Local calendar getters use the operating system's timezone database.
Local calendar getters and local-time conversions use the operating system's timezone database.
Historical results can differ from Node.js when timezone data differs.
For valid extreme years outside a platform calendar API's range, scriptc uses a calendar-equivalent year in the 400-year Gregorian cycle to obtain the timezone rule.
@@ -1,4 +1,4 @@
- **Function values:** Immutable aliases of overloaded program functions retain per-call overload resolution and identity.
A function stored in a slot with a different signature remains the same function for equality, array searches, `length`, and own properties.
Typed rest-parameter functions can be stored and called indirectly.
Typed rest-parameter functions can be stored and called indirectly, including through a slot with fixed parameters, where the slot's arguments arrive in the rest array.
Builtin function values have API-specific restrictions; see [Builtin function values](#builtin-function-values).
@@ -0,0 +1,4 @@
`__dirname` and `__filename` are compile-time constants: the absolute path of the module's source directory and file at build time, the same strings as `import.meta.dirname` and `import.meta.filename`.
A `.ts` or `.tsx` file keeps them even when it uses `import` syntax, which Node.js would load as an ES module without these globals, because TypeScript projects are commonly shipped as CommonJS bundles where they exist.
In such a file `typeof __dirname` is `"string"`, where Node.js running the source directly reports `"undefined"`.
JavaScript ES modules (`.mjs`, or `.js` in a `"type": "module"` package) do not have them, as in Node.js.
@@ -1,3 +1,4 @@
- **Null and optional values:** `undefined` and `null` compile as standalone values and union members.
Optional record and class fields and optional, default, and rest parameters also compile, including rest parameters typed `unknown[]` or `any[]`, whose functions take any number of arguments.
A function value with fixed parameters cannot be stored where such a variadic function type is expected.
A function value whose fixed parameters are all `unknown` or `any`, or that has none, can be stored where such a variadic function type without fixed parameters is expected: each call passes the arguments in order, `undefined` for the ones the caller left out.
Other function values with fixed parameters cannot be stored there.
@@ -55940,7 +55940,9 @@
"confidence": "high",
"source": "compiler-feature:process.'disconnect'",
"tests": [
"tests/corpus/2946-child-fork-ipc/main.ts"
"tests/corpus/2946-child-fork-ipc/main.ts",
"tests/corpus/6420-process-send-presence.ts",
"tests/corpus/6421-process-send-presence-fork/main.ts"
]
}
}
@@ -55982,7 +55984,9 @@
"confidence": "high",
"source": "compiler-feature:process.'message'",
"tests": [
"tests/corpus/2946-child-fork-ipc/main.ts"
"tests/corpus/2946-child-fork-ipc/main.ts",
"tests/corpus/6420-process-send-presence.ts",
"tests/corpus/6421-process-send-presence-fork/main.ts"
]
}
}
@@ -56365,7 +56369,9 @@
"confidence": "high",
"source": "compiler-feature:process.process.disconnect",
"tests": [
"tests/corpus/2946-child-fork-ipc/main.ts"
"tests/corpus/2946-child-fork-ipc/main.ts",
"tests/corpus/6420-process-send-presence.ts",
"tests/corpus/6421-process-send-presence-fork/main.ts"
]
}
}
@@ -57013,7 +57019,9 @@
"confidence": "high",
"source": "compiler-feature:process.process.send",
"tests": [
"tests/corpus/2946-child-fork-ipc/main.ts"
"tests/corpus/2946-child-fork-ipc/main.ts",
"tests/corpus/6420-process-send-presence.ts",
"tests/corpus/6421-process-send-presence-fork/main.ts"
]
}
}
@@ -57467,7 +57475,9 @@
"confidence": "high",
"source": "compiler-feature:process.connected",
"tests": [
"tests/corpus/2946-child-fork-ipc/main.ts"
"tests/corpus/2946-child-fork-ipc/main.ts",
"tests/corpus/6420-process-send-presence.ts",
"tests/corpus/6421-process-send-presence-fork/main.ts"
]
}
}
@@ -57582,7 +57592,10 @@
"tests/corpus/2941-process-exit-code.ts",
"tests/corpus/2942-process-exit-code-override.ts",
"tests/corpus/2943-process-exit-code-invalid.ts",
"tests/corpus/2944-process-exit-code-wrap.ts"
"tests/corpus/2944-process-exit-code-wrap.ts",
"tests/corpus/6422-process-exitcode-read.ts",
"tests/corpus/6423-process-exitcode-default.ts",
"tests/corpus/6424-process-exit-keeps-exitcode.ts"
]
}
}
@@ -66531,6 +66544,7 @@
"source": "compiler-feature:test.mock.fn",
"tests": [
"tests/fixtures/node-test/cases/mock-fn.ts",
"tests/fixtures/node-test/cases/mock-fn-default.ts",
"tests/harness/node-test.test.ts"
]
}
@@ -76203,6 +76217,8 @@
"tests/fixtures/node-types/promisify-crypto.ts",
"tests/corpus/5632-promisify-dns.ts",
"tests/fixtures/node-types/promisify-dns.ts",
"tests/corpus/6428-promisify-callback-functions.ts",
"tests/fixtures/node-types/promisify-callback-functions.ts",
"tests/harness/project-config.test.ts"
]
}
@@ -79409,6 +79409,11 @@
"tests/corpus/5210-process-memory-usage.ts",
"tests/corpus/5211-process-identity.ts",
"tests/corpus/5809-process-exit-and-rejections.cjs",
"tests/corpus/6420-process-send-presence.ts",
"tests/corpus/6421-process-send-presence-fork/main.ts",
"tests/corpus/6422-process-exitcode-read.ts",
"tests/corpus/6423-process-exitcode-default.ts",
"tests/corpus/6424-process-exit-keeps-exitcode.ts",
"tests/corpus/990-process-basics.ts",
"tests/corpus/node24-env-files-errors.ts",
"tests/corpus/node24-env-files.ts",
@@ -79486,7 +79491,9 @@
"status": "partial",
"evidence": "compiler-feature:process.'disconnect'",
"tests": [
"tests/corpus/2946-child-fork-ipc/main.ts"
"tests/corpus/2946-child-fork-ipc/main.ts",
"tests/corpus/6420-process-send-presence.ts",
"tests/corpus/6421-process-send-presence-fork/main.ts"
]
},
"anchorSource": "exact"
@@ -79525,7 +79532,9 @@
"status": "partial",
"evidence": "compiler-feature:process.'message'",
"tests": [
"tests/corpus/2946-child-fork-ipc/main.ts"
"tests/corpus/2946-child-fork-ipc/main.ts",
"tests/corpus/6420-process-send-presence.ts",
"tests/corpus/6421-process-send-presence-fork/main.ts"
]
},
"anchorSource": "exact"
@@ -79938,7 +79947,9 @@
"status": "partial",
"evidence": "compiler-feature:process.process.disconnect",
"tests": [
"tests/corpus/2946-child-fork-ipc/main.ts"
"tests/corpus/2946-child-fork-ipc/main.ts",
"tests/corpus/6420-process-send-presence.ts",
"tests/corpus/6421-process-send-presence-fork/main.ts"
]
},
"anchorSource": "exact"
@@ -80583,7 +80594,9 @@
"status": "partial",
"evidence": "compiler-feature:process.process.send",
"tests": [
"tests/corpus/2946-child-fork-ipc/main.ts"
"tests/corpus/2946-child-fork-ipc/main.ts",
"tests/corpus/6420-process-send-presence.ts",
"tests/corpus/6421-process-send-presence-fork/main.ts"
]
},
"anchorSource": "exact"
@@ -81002,7 +81015,9 @@
"status": "partial",
"evidence": "compiler-feature:process.connected",
"tests": [
"tests/corpus/2946-child-fork-ipc/main.ts"
"tests/corpus/2946-child-fork-ipc/main.ts",
"tests/corpus/6420-process-send-presence.ts",
"tests/corpus/6421-process-send-presence-fork/main.ts"
]
},
"anchorSource": "chapter"
@@ -81111,7 +81126,10 @@
"tests/corpus/2941-process-exit-code.ts",
"tests/corpus/2942-process-exit-code-override.ts",
"tests/corpus/2943-process-exit-code-invalid.ts",
"tests/corpus/2944-process-exit-code-wrap.ts"
"tests/corpus/2944-process-exit-code-wrap.ts",
"tests/corpus/6422-process-exitcode-read.ts",
"tests/corpus/6423-process-exitcode-default.ts",
"tests/corpus/6424-process-exit-keeps-exitcode.ts"
]
},
"anchorSource": "chapter"
@@ -91145,6 +91163,7 @@
"tests/fixtures/node-test/cases/ctx-plan.ts",
"tests/fixtures/node-test/cases/get-test-context-cancelled.ts",
"tests/fixtures/node-test/cases/get-test-context.ts",
"tests/fixtures/node-test/cases/mock-fn-default.ts",
"tests/fixtures/node-test/cases/mock-fn.ts",
"tests/fixtures/node-test/cases/mock-method.ts",
"tests/fixtures/node-test/cases/mock-timers-date.ts",
@@ -92556,6 +92575,7 @@
"evidence": "compiler-feature:test.mock.fn",
"tests": [
"tests/fixtures/node-test/cases/mock-fn.ts",
"tests/fixtures/node-test/cases/mock-fn-default.ts",
"tests/harness/node-test.test.ts"
]
},
@@ -101237,6 +101257,7 @@
"tests/corpus/5832-util-types-brands-dynamic.js",
"tests/corpus/5835-util-format-integer-specifiers.ts",
"tests/corpus/5884-inspect-layout-options.ts",
"tests/corpus/6428-promisify-callback-functions.ts",
"tests/corpus/node24-deep-equality-properties.js",
"tests/corpus/node24-deep-equality.cjs",
"tests/corpus/node24-deep-equality.ts",
@@ -101263,6 +101284,7 @@
"tests/corpus/text-codec-values/main.ts",
"tests/fixtures/node-types/deep-equality.ts",
"tests/fixtures/node-types/env-files.ts",
"tests/fixtures/node-types/promisify-callback-functions.ts",
"tests/fixtures/node-types/promisify-crypto.ts",
"tests/fixtures/node-types/promisify-dns.ts",
"tests/fixtures/node-types/promisify-fs.ts",
@@ -102921,6 +102943,8 @@
"tests/fixtures/node-types/promisify-crypto.ts",
"tests/corpus/5632-promisify-dns.ts",
"tests/fixtures/node-types/promisify-dns.ts",
"tests/corpus/6428-promisify-callback-functions.ts",
"tests/fixtures/node-types/promisify-callback-functions.ts",
"tests/harness/project-config.test.ts"
]
},
+4 -4
View File
@@ -148,7 +148,7 @@
"node-builtin.process.versions": ["tests/corpus/process-versions-storage.ts"],
"node-builtin.process.rows": ["tests/corpus/2992-stream-rows.ts", "tests/harness/terminal-geometry.test.ts"],
"node-builtin.process.columns": ["tests/corpus/1448-stream-columns.ts", "tests/harness/terminal-geometry.test.ts"],
"node-builtin.process.exitCode": ["tests/corpus/5809-process-exit-and-rejections.cjs", "tests/corpus/2941-process-exit-code.ts", "tests/corpus/2942-process-exit-code-override.ts", "tests/corpus/2943-process-exit-code-invalid.ts", "tests/corpus/2944-process-exit-code-wrap.ts"],
"node-builtin.process.exitCode": ["tests/corpus/5809-process-exit-and-rejections.cjs", "tests/corpus/2941-process-exit-code.ts", "tests/corpus/2942-process-exit-code-override.ts", "tests/corpus/2943-process-exit-code-invalid.ts", "tests/corpus/2944-process-exit-code-wrap.ts", "tests/corpus/6422-process-exitcode-read.ts", "tests/corpus/6423-process-exitcode-default.ts", "tests/corpus/6424-process-exit-keeps-exitcode.ts"],
"node-builtin.punycode": ["tests/corpus/6122-punycode-conversions.ts", "tests/corpus/6124-punycode-require-warnings.cjs", "tests/corpus/6126-punycode-dependency/main.cjs"],
"node-builtin.querystring": ["tests/corpus/957-builtins-namespace.ts", "tests/corpus/2917-builtin-callable-widths.ts"],
"node-builtin.readline": ["tests/corpus/1475-readline-closed-stdin.ts"],
@@ -341,7 +341,7 @@
{ "chapter": "fs", "signatures": ["`fsPromises.lstat(path[, options])`"], "status": "partial", "evidence": ["tests/corpus/2941-fsp-lstat-identity.ts"] },
{ "chapter": "fs", "signatures": ["`fs.globSync(pattern[, options])`", "`fs.glob(pattern[, options], callback)`", "`fsPromises.glob(pattern[, options])`"], "status": "partial", "evidence": ["tests/corpus/5448-fs-glob-patterns.ts", "tests/corpus/5449-fs-glob-options.ts", "tests/corpus/5450-fs-glob-validation.js", "tests/corpus/5451-fs-promises-glob.ts", "tests/corpus/5452-fs-glob-callback.ts", "tests/fixtures/node-types/fs-glob.ts"] },
{ "chapter": "fs", "signatures": ["`fs.cpSync(src, dest[, options])`", "`fs.cp(src, dest[, options], callback)`", "`fsPromises.cp(src, dest[, options])`"], "status": "partial", "evidence": ["tests/corpus/5567-fs-cpsync.ts", "tests/corpus/5568-fs-cp-errors.js", "tests/corpus/5569-fs-cp-symlinks.ts", "tests/corpus/5570-fs-cp-async.ts"] },
{ "chapter": "process", "signatures": ["`process.send(message[, sendHandle[, options]][, callback])`", "`process.disconnect()`", "`connected` Type: {boolean}", "Event: `'message'`", "Event: `'disconnect'`"], "status": "partial", "evidence": ["tests/corpus/2946-child-fork-ipc/main.ts"] },
{ "chapter": "process", "signatures": ["`process.send(message[, sendHandle[, options]][, callback])`", "`process.disconnect()`", "`connected` Type: {boolean}", "Event: `'message'`", "Event: `'disconnect'`"], "status": "partial", "evidence": ["tests/corpus/2946-child-fork-ipc/main.ts", "tests/corpus/6420-process-send-presence.ts", "tests/corpus/6421-process-send-presence-fork/main.ts"] },
{ "chapter": "fs", "symbols": ["fs.Stats", "stats.isBlockDevice", "stats.isCharacterDevice", "stats.isDirectory", "stats.isFIFO", "stats.isFile", "stats.isSocket", "stats.isSymbolicLink"], "status": "partial", "evidence": ["tests/corpus/5541-fs-stats-fields.cjs"] },
{ "chapter": "fs", "parent": "Class: `fs.Stats`", "signatures": ["`mode` Type: {number|bigint}", "`nlink` Type: {number|bigint}", "`uid` Type: {number|bigint}", "`gid` Type: {number|bigint}", "`rdev` Type: {number|bigint}", "`size` Type: {number|bigint}", "`blksize` Type: {number|bigint}", "`blocks` Type: {number|bigint}", "`atimeMs` Type: {number|bigint}", "`mtimeMs` Type: {number|bigint}", "`birthtimeMs` Type: {number|bigint}", "`atimeNs` Type: {bigint}", "`mtimeNs` Type: {bigint}", "`ctimeNs` Type: {bigint}", "`birthtimeNs` Type: {bigint}", "`atime` Type: {Date}", "`mtime` Type: {Date}", "`ctime` Type: {Date}", "`birthtime` Type: {Date}"], "status": "partial", "evidence": ["tests/corpus/5541-fs-stats-fields.cjs"] },
{ "chapter": "fs", "signatures": ["`dev` Type: {number|bigint}", "`ino` Type: {number|bigint}", "`ctimeMs` Type: {number|bigint}"], "status": "partial", "evidence": ["tests/corpus/2941-fsp-lstat-identity.ts"] },
@@ -370,7 +370,7 @@
{ "chapter": "test", "parent": "Class: `TestContext`", "symbols": ["context.filePath", "passed", "attempt", "tags", "workerId"], "status": "partial", "evidence": ["tests/fixtures/node-test/cases/ctx-members.ts", "tests/harness/node-test.test.ts"] },
{ "chapter": "test", "parent": "Class: `SuiteContext`", "symbols": ["context.name", "context.fullName", "context.filePath", "context.diagnostic", "passed", "attempt"], "status": "partial", "evidence": ["tests/fixtures/node-test/cases/suite-context.ts", "tests/harness/node-test.test.ts"] },
{ "chapter": "test", "parent": "Class: `TestContext`", "symbols": ["context.diagnostic", "context.name"], "status": "partial", "evidence": ["tests/harness/node-test.test.ts"] },
{ "chapter": "test", "parent": "Class: `MockTracker`", "symbols": ["mock.fn"], "status": "partial", "evidence": ["tests/fixtures/node-test/cases/mock-fn.ts", "tests/harness/node-test.test.ts"] },
{ "chapter": "test", "parent": "Class: `MockTracker`", "symbols": ["mock.fn"], "status": "partial", "evidence": ["tests/fixtures/node-test/cases/mock-fn.ts", "tests/fixtures/node-test/cases/mock-fn-default.ts", "tests/harness/node-test.test.ts"] },
{ "chapter": "test", "parent": "Class: `MockTracker`", "symbols": ["mock.method", "mock.reset", "mock.restoreAll"], "status": "partial", "evidence": ["tests/fixtures/node-test/cases/mock-method.ts", "tests/corpus/5810-mock-method-records.ts", "tests/corpus/5811-mock-tracker-restore.ts", "tests/harness/node-test.test.ts"] },
{ "chapter": "test", "parent": "Class: `MockTimers`", "symbols": ["timers.enable", "timers.reset", "timers.tick", "timers.runAll", "timers.setTime"], "status": "partial", "evidence": ["tests/fixtures/node-test/cases/mock-timers.ts", "tests/fixtures/node-test/cases/mock-timers-date.ts", "tests/corpus/5813-mock-timers-module.ts", "tests/corpus/5814-mock-timers-date.ts", "tests/harness/node-test.test.ts"] },
{ "chapter": "test", "parent": "Class: `MockTimers`", "signatures": ["`timers[Symbol.dispose]()`"], "status": "partial", "evidence": ["tests/fixtures/node-test/cases/mock-timers-date.ts", "tests/harness/node-test.test.ts"] },
@@ -378,7 +378,7 @@
{ "chapter": "test", "parent": "Class: `TestContext`", "symbols": ["context.before", "context.after", "context.beforeEach", "context.afterEach", "context.plan", "context.fullName"], "status": "partial", "evidence": ["tests/fixtures/node-test/cases/ctx-hooks.ts", "tests/fixtures/node-test/cases/ctx-plan.ts", "tests/harness/node-test.test.ts"] },
{ "chapter": "test", "symbols": ["getTestContext"], "status": "partial", "evidence": ["tests/fixtures/node-test/cases/get-test-context.ts", "tests/fixtures/node-test/cases/get-test-context-cancelled.ts", "tests/harness/node-test.test.ts"] },
{ "chapter": "test", "symbols": ["describe.skip", "describe.todo", "describe.only", "suite.skip", "suite.todo", "suite.only", "it.skip", "it.todo", "it.only"], "status": "partial", "evidence": ["tests/fixtures/node-test/cases/suite-variants.ts", "tests/fixtures/node-test/cases/only-nested.ts", "tests/fixtures/node-test/cases/todo-suites.ts", "tests/harness/node-test.test.ts"] },
{ "chapter": "util", "signatures": ["`util.promisify(original)`"], "status": "partial", "evidence": ["tests/corpus/1473-promisify-execfile.ts", "tests/corpus/1573-promisify-execfile-env-spread.ts", "tests/corpus/2912-promisify-fs-readfile.ts", "tests/corpus/5625-promisify-exec.ts", "tests/corpus/5626-promisify-forms.ts", "tests/fixtures/node-types/promisify-fs.ts", "tests/corpus/5628-promisify-timers.ts", "tests/fixtures/node-types/promisify-timers.ts", "tests/corpus/5629-promisify-stream.ts", "tests/corpus/5630-promisify-zlib.ts", "tests/fixtures/node-types/promisify-zlib.ts", "tests/corpus/5631-promisify-crypto.ts", "tests/fixtures/node-types/promisify-crypto.ts", "tests/corpus/5632-promisify-dns.ts", "tests/fixtures/node-types/promisify-dns.ts", "tests/harness/project-config.test.ts"] },
{ "chapter": "util", "signatures": ["`util.promisify(original)`"], "status": "partial", "evidence": ["tests/corpus/1473-promisify-execfile.ts", "tests/corpus/1573-promisify-execfile-env-spread.ts", "tests/corpus/2912-promisify-fs-readfile.ts", "tests/corpus/5625-promisify-exec.ts", "tests/corpus/5626-promisify-forms.ts", "tests/fixtures/node-types/promisify-fs.ts", "tests/corpus/5628-promisify-timers.ts", "tests/fixtures/node-types/promisify-timers.ts", "tests/corpus/5629-promisify-stream.ts", "tests/corpus/5630-promisify-zlib.ts", "tests/fixtures/node-types/promisify-zlib.ts", "tests/corpus/5631-promisify-crypto.ts", "tests/fixtures/node-types/promisify-crypto.ts", "tests/corpus/5632-promisify-dns.ts", "tests/fixtures/node-types/promisify-dns.ts", "tests/corpus/6428-promisify-callback-functions.ts", "tests/fixtures/node-types/promisify-callback-functions.ts", "tests/harness/project-config.test.ts"] },
{ "chapter": "typescript", "symbols": ["type"], "status": "supported", "evidence": ["tests/corpus/2702-type-import-link-static/main.ts", "tests/corpus/2703-type-import-link-static-reexport/main.ts", "tests/corpus/2704-type-import-link-static-success/main.ts", "tests/corpus/2707-type-import-link-static-default-reexport/main.ts", "tests/harness/errors.test.ts"] },
{ "chapter": "zlib", "signatures": ["Class: `zlib.Deflate`", "Class: `zlib.Inflate`", "Class: `zlib.Gzip`", "Class: `zlib.Gunzip`", "Class: `zlib.DeflateRaw`", "Class: `zlib.InflateRaw`", "Class: `zlib.Unzip`", "Class: `zlib.ZlibBase`", "`zlib.close([callback])`", "`zlib.flush([kind, ]callback)`", "`zlib.params(level, strategy, callback)`", "`zlib.reset()`", "`bytesWritten` Type: {number}", "Class: `Options`"], "status": "partial", "evidence": ["tests/corpus/5370-zlib-stream-roundtrip.ts", "tests/corpus/5371-zlib-stream-chunking.cjs", "tests/corpus/5372-zlib-stream-errors.cjs", "tests/corpus/5373-zlib-stream-options.cjs", "tests/corpus/5374-zlib-stream-flush-params.ts", "tests/corpus/5375-zlib-stream-promises.ts", "tests/corpus/5377-zlib-stream-backpressure.cjs"] },
{ "chapter": "zlib", "signatures": ["`zlib.constants`"], "status": "partial", "evidence": ["tests/corpus/5376-zlib-constants.cjs", "tests/corpus/5374-zlib-stream-flush-params.ts"] }
+1
View File
@@ -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",
+2
View File
@@ -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"),
]) {
+8
View File
@@ -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}:${
+7
View File
@@ -3372,6 +3372,13 @@ declare module "util" {
info: import("node:crypto").BinaryLike,
keylen: number,
) => Promise<ArrayBuffer>;
/* A callback-only function (`obj.close.bind(obj)`): before the targets
* whose leading parameters would otherwise capture it. Builtins that take
* arguments before their callback never match these. */
export function promisify<TResult>(
fn: (callback: (err: any, result: TResult) => void) => void,
): () => Promise<TResult>;
export function promisify(fn: (callback: (err?: any) => void) => void): () => Promise<void>;
export function promisify(
fn: typeof import("node:crypto").randomFill,
): <T extends ArrayBufferView | ArrayBufferLike>(
+1
View File
@@ -39,6 +39,7 @@
},
"dependencies": {
"@scriptc/runtime": "workspace:*",
"tsc-ts": "0.0.3",
"typescript": "7.0.2",
"typescript5": "npm:typescript@5.9.3"
},
+58 -5
View File
@@ -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.
@@ -1,6 +1,13 @@
/* Focused LLVM expression emission extracted from emitter.ts. */
import { InternalCompilerError } from "../../errors.js";
import { type IrType, isRefCounted, isUnitType, typeEquals, typeKey } from "../../ir/ir.js";
import {
type IrType,
UNDEFINED_T,
isRefCounted,
isUnitType,
typeEquals,
typeKey,
} from "../../ir/ir.js";
import { mangleGenResThunk, mangleRecordNew, mangleRecordStruct } from "../mangle.js";
import { FN_ATTRS, llFieldType, releaseSym, retainSym, traceArg, vAdapters } from "./shapes.js";
import { LlvmUnsupportedError } from "./unsupported.js";
@@ -48,6 +55,23 @@ export function raceAdapterFor(host: LlvmEmitterContext, from: IrType, to: IrTyp
if (sym) return sym;
sym = `sc_race_${host.resolveThunks.size}`;
host.resolveThunks.set(key, sym);
const toArms = to.kind === "union" ? (host.unionsById.get(to.unionId)?.arms ?? []) : [];
if (from.kind === "void" && !toArms.some((a) => a.kind === "undefinedT")) {
// A Promise<never> entry (the frontend admits void entries without an
// undefined result arm only for those): it can only reject, so its
// fulfillment adapter never runs.
host.declare(`declare void @scr_trap(ptr)`);
const msg = host.cstr("scriptc: a Promise<never> race entry fulfilled\n");
host.resolveThunkDefs.push(
`define internal void @${sym}(ptr %dst, ptr %src) ${FN_ATTRS} { ; race ${key}`,
`entry:`,
` call void @scr_trap(ptr ${msg})`,
` unreachable`,
`}`,
``,
);
return sym;
}
if (to.kind !== "union")
throw new InternalCompilerError("llvm emitter bug: race adapter to a non-union");
const toDef = host.unionsById.get(to.unionId);
@@ -68,6 +92,14 @@ export function raceAdapterFor(host: LlvmEmitterContext, from: IrType, to: IrTyp
`define internal void @${sym}(ptr %dst, ptr %src) ${FN_ATTRS} { ; race ${key}`,
`entry:`,
];
if (from.kind === "void") {
// A Promise<void> entry fulfills with undefined: the result's
// undefined arm, whatever the entry's payload slot holds.
const tag = tagOf(UNDEFINED_T);
d.push(` ${fulfill(host.unitInstanceRef(to.unionId, tag))}`, ` ret void`, `}`, ``);
host.resolveThunkDefs.push(...d);
return sym;
}
if (from.kind !== "union") {
// One arm wrap, straight off the payload accessors.
const tag = tagOf(from);
@@ -535,6 +535,27 @@ export function emitDynamicExpr(
e.key.type.kind === "dyn" ? host.dyn.dynComputedKeyGetHelper() : host.dyn.dynKeyGetHelper();
const t = B.tmp();
const generic = `call ptr @${helper}(ptr ${d.name}, ptr ${k.name}, i1 ${e.optional ? "true" : "false"})`;
const inherited = e.key.kind === "strLit" && INHERITED_OBJECT_MEMBERS.has(e.key.value);
// Object.prototype itself answers its own members before the ordinary
// read (which fences reflection on the prototype).
let prototypeJoin: { member: string; from: string; join: string } | null = null;
if (inherited) {
host.declare(`declare ptr @scr_dyn_object_prototype_member(ptr, ptr)`);
const member = B.tmp();
B.line(
`${member} = call ptr @scr_dyn_object_prototype_member(ptr ${d.name}, ptr ${k.name})`,
);
const isMember = B.tmp();
B.line(`${isMember} = icmp ne ptr ${member}, null`);
const from = B.newLabel("dkg.op");
const read = B.newLabel("dkg.rd");
const join = B.newLabel("dkg.opj");
B.condBr(isMember, from, read);
B.startBlock(from);
B.br(join);
B.startBlock(read);
prototypeJoin = { member, from, join };
}
if (e.key.kind === "strLit") {
// A constant key on an ordinary object reads through the site's
// cache; every other receiver keeps the shared helper.
@@ -560,7 +581,27 @@ export function emitDynamicExpr(
} else {
B.line(`${t} = ${generic}`);
}
const out = host.own({ name: t, type: e.type });
let result = t;
if (prototypeJoin) {
// An undefined read of an Object.prototype member name answers the
// member the receiver inherits (scr_dyn_invoke.c; the frontend
// links that unit for these reads).
host.declare(`declare ptr @scr_dyn_inherited_read(ptr, ptr, ptr)`);
const read = B.tmp();
B.line(
`${read} = call ptr @scr_dyn_inherited_read(ptr ${d.name}, ptr ${k.name}, ptr ${t})`,
);
const readEnd = B.newLabel("dkg.rde");
B.br(readEnd);
B.startBlock(readEnd);
B.br(prototypeJoin.join);
B.startBlock(prototypeJoin.join);
result = B.tmp();
B.line(
`${result} = phi ptr [ ${prototypeJoin.member}, %${prototypeJoin.from} ], [ ${read}, %${readEnd} ]`,
);
}
const out = host.own({ name: result, type: e.type });
host.emitPendingCheck();
return out;
}
@@ -1204,3 +1245,13 @@ function emitUnionEqWrappedScalar(
function wrappedStringLiteral(e: IrExpr): string | null {
return e.kind === "unionWrap" && e.value.kind === "strLit" ? e.value.value : null;
}
/** Object.prototype member names whose constant-key dynamic reads fall back
* to the inherited member (runtime-features.ts links the unit). */
export const INHERITED_OBJECT_MEMBERS: ReadonlySet<string> = new Set([
"constructor",
"valueOf",
"toString",
"hasOwnProperty",
"propertyIsEnumerable",
]);
@@ -5,14 +5,17 @@ import { streamTypedRefEligible, undefinedArmTag } from "../../ir/analysis.js";
import {
type IrRecordShape,
type IrType,
CLASS_ATTRIBUTES,
DYN_CLASS_PROPERTIES,
RUNTIME_STREAM_CLASSES,
SYMBOL_T,
classDynViewSupported,
classFieldAttributesName,
isClassOwnEnumerableFieldName,
isDirentShape,
isDynTypedRefType,
isRefCounted,
shapeHasAccessorSlots,
typeKey,
} from "../../ir/ir.js";
import { mangleFunction, mangleGlobal, mangleRecordStruct } from "../mangle.js";
@@ -766,6 +769,7 @@ export function streamTypedRefMaterializeAdapter(
host.declare(`declare ptr @scr_stream_dyn_view(ptr)`);
B.line(`${out} = call ptr @scr_stream_dyn_view(ptr %p)`);
} else B.line(`${out} = call ptr @scr_dyn_new_obj()`);
const withAttributes = meta.def.fields.some((field) => field.name === CLASS_ATTRIBUTES);
if (meta.def.tracksOwnFields) {
host.declare(`declare ptr @scr_dyn_copy_property_descriptors(ptr, ptr)`);
host.declare(`declare void @scr_dyn_release_v(ptr)`);
@@ -835,9 +839,27 @@ export function streamTypedRefMaterializeAdapter(
const nullable = host.nullableFields.get(t.className, field.name);
if (nullable) fieldValue = nullableFieldUnion(host, B, fieldValue, nullable);
const boxed = host.streamTypedRefBoxValue(B, field.type, fieldValue);
// Attributes copied from the bag do not stop the view taking the value.
const setter = withAttributes ? "scr_dyn_obj_set_field" : "scr_dyn_obj_set";
if (withAttributes)
host.declare(`declare void @scr_dyn_obj_set_field(ptr, ptr, ${host.sizeType}, ptr)`);
B.line(
`call void @scr_dyn_obj_set(ptr ${out}, ptr ${host.cstr(field.name)}, ${host.sizeType} ${Buffer.byteLength(field.name, "utf8")}, ptr ${boxed})`,
`call void @${setter}(ptr ${out}, ptr ${host.cstr(field.name)}, ${host.sizeType} ${Buffer.byteLength(field.name, "utf8")}, ptr ${boxed})`,
);
// A field redefined through Object.defineProperty keeps its attributes.
const attributesField = classFieldAttributesName(field.name);
if (meta.def.fields.some((f) => f.name === attributesField)) {
host.declare(`declare void @scr_dyn_class_field_attributes(ptr, ptr, double)`);
const slot = B.tmp(),
bits = B.tmp();
B.line(
`${slot} = getelementptr inbounds %${classStructSym(t.className)}, ptr %p, i64 0, i32 ${classFieldIndex(meta, attributesField).index}`,
);
B.line(`${bits} = load double, ptr ${slot}`);
B.line(
`call void @scr_dyn_class_field_attributes(ptr ${out}, ptr ${host.internLiteral(field.name)}, double ${bits})`,
);
}
if (nullable) {
host.declare(`declare void @scr_union_release(ptr)`);
B.line(`call void @scr_union_release(ptr ${fieldValue})`);
@@ -920,6 +942,29 @@ export function streamTypedRefMaterializeAdapter(
B.line(`${copied} = call ptr @scr_dyn_copy_property_descriptors(ptr ${out}, ptr ${bag})`);
B.line(`call void @scr_dyn_release_v(ptr ${copied})`);
}
// An Error subclass instance's own `name` sits where its class's
// construction creates it: after a field, or after every other
// property when no constructor sets it.
const nameAfter = meta.def.errorNameAfter;
if (meta.root.def.name === "%Error" && !meta.def.runtime && nameAfter !== null) {
host.declare(`declare void @scr_error_dyn_place_name(ptr, ptr, ${host.sizeType})`);
B.line(
nameAfter === undefined
? `call void @scr_error_dyn_place_name(ptr ${out}, ptr null, ${host.sizeType} 0)`
: `call void @scr_error_dyn_place_name(ptr ${out}, ptr ${host.cstr(nameAfter)}, ${host.sizeType} ${Buffer.byteLength(nameAfter, "utf8")})`,
);
}
// A frozen, sealed or non-extensible instance's view says so.
if (withAttributes) {
host.declare(`declare void @scr_dyn_class_view_attributes(ptr, double)`);
const slot = B.tmp(),
bits = B.tmp();
B.line(
`${slot} = getelementptr inbounds %${classStructSym(t.className)}, ptr %p, i64 0, i32 ${classFieldIndex(meta, CLASS_ATTRIBUTES).index}`,
);
B.line(`${bits} = load double, ptr ${slot}`);
B.line(`call void @scr_dyn_class_view_attributes(ptr ${out}, double ${bits})`);
}
B.terminate(`ret ptr ${out}`);
} else if (t.kind === "record") {
const shape = host.recordsById.get(t.shapeId);
@@ -933,6 +978,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();
@@ -294,9 +294,12 @@ export const LIB_FN_SYMS: Record<string, string> = {
"process.rusage": "scr_process_rusage",
"process.activeResources": "scr_active_resources",
"process.exiting": "scr_process_exiting",
"process.ipcOpen": "scr_process_ipc_open",
"process.exit": "scr_process_exit",
"process.setExitCode": "scr_process_set_exit_code",
"process.currentExitCode": "scr_process_exit_code_or_zero",
"process.setExitCodeTracked": "scr_process_set_exit_code_tracked",
"process.hasExitCode": "scr_process_has_exit_code",
"process.envSet": "scr_env_set",
"process.envUnset": "scr_env_unset",
"process.envPairs": "scr_env_pairs",
@@ -307,12 +310,13 @@ export const LIB_FN_SYMS: Record<string, string> = {
"date.now": "scr_date_now",
"date.newNow": "scr_date_now",
"date.newMs": "scr_date_new_ms",
"date.newString": "scr_date_parse_get_time",
"date.parse": "scr_date_parse_get_time",
"date.newString": "scr_date_parse",
"date.parse": "scr_date_parse",
"date.getTime": "scr_date_get_time",
"date.valueOf": "scr_date_get_time",
"date.parseGetTime": "scr_date_parse_get_time",
"date.parseGetTime": "scr_date_parse",
"date.utc": "scr_date_utc",
"date.newLocal": "scr_date_new_local",
"date.getFullYear": "scr_date_get_full_year_local",
"date.getUTCFullYear": "scr_date_get_full_year_utc",
"date.getMonth": "scr_date_get_month_local",
@@ -827,6 +831,7 @@ export const LIB_FN_SYMS: Record<string, string> = {
"dyn.sameValue": "scr_dyn_same_value",
"error.toString": "scr_error_to_string",
"error.stack": "scr_error_stack",
"error.setStack": "scr_error_set_stack",
"error.stackLimitGet": "scr_stack_limit_get",
"error.stackLimitSet": "scr_stack_limit_set",
"class.name": "scr_classobj_name",
@@ -922,16 +927,27 @@ export const LIB_FN_SYMS: Record<string, string> = {
"dyn.promiseAll": "scr_dyn_promise_all",
"dyn.promiseAllSettled": "scr_dyn_promise_all_settled",
"dyn.promiseAny": "scr_dyn_promise_any",
"dyn.promiseResolve": "scr_dyn_promise_resolve",
"dyn.typeof": "scr_dyn_typeof",
"dyn.objectTag": "scr_dyn_object_tag",
"dyn.objectTag": "scr_dyn_object_tag_of",
"dyn.freeze": "scr_dyn_freeze",
"dyn.isFrozen": "scr_dyn_is_frozen",
"class.defineField": "scr_class_define_field",
"class.definedBits": "scr_class_defined_bits",
"class.definedValue": "scr_class_defined_value",
"class.descriptorHasValue": "scr_class_descriptor_has_value",
"class.throwReadOnly": "scr_class_throw_read_only",
"class.throwNotExtensible": "scr_class_throw_not_extensible",
"dyn.nativeSetNew": "scr_dyn_native_set_new",
"dyn.nativeSetIs": "scr_dyn_native_set_is",
"dyn.nativeMapIs": "scr_dyn_native_map_is",
"dyn.nativeUrlIs": "scr_dyn_native_url_is",
"dyn.nativeDateIs": "scr_dyn_native_date_is",
"dyn.globalConstructor": "scr_dyn_global_constructor",
"dyn.builtinFunction": "scr_dyn_builtin_function",
"date.nativeNew": "scr_dyn_native_date_new",
"date.nativeNewFields": "scr_dyn_native_date_new_fields",
"date.nativeNewValue": "scr_dyn_native_date_new_value",
"date.checkedValue": "scr_dyn_native_date_value",
"dyn.nativeRegexIs": "scr_dyn_native_regex_is",
"dyn.toString": "scr_dyn_to_string_argument",
@@ -1655,4 +1671,5 @@ export const USES_TIMERS_LIB_FNS = new Set<string>([
"timers.queueMicrotaskDyn",
"timers.setImmediateFnValue",
"timers.immediatePromise",
"dyn.builtinFunction",
]);
@@ -1,5 +1,6 @@
import { expect, test } from "vitest";
import {
DYN,
F64,
STRING,
VOID,
@@ -49,6 +50,40 @@ test("a reachable stack read is observed", () => {
expect(observesStacks(mod([fn("%main", [call("parse")]), fn("parse", [stackRead])]))).toBe(true);
});
test("a stack read on a checked-dynamic value is observed", () => {
const value: IrExpr = { loc, kind: "varRef", localId: "d", type: DYN };
const read = (key: string): IrStmt => ({
loc,
kind: "exprStmt",
expr: {
loc,
kind: "dynKeyGet",
value,
key: { loc, kind: "strLit", value: key, type: STRING },
type: DYN,
},
});
expect(observesStacks(mod([fn("%main", [read("stack")])]))).toBe(true);
expect(observesStacks(mod([fn("%main", [read("message")])]))).toBe(false);
});
test("a computed key reads the stack when the program spells it", () => {
const value: IrExpr = { loc, kind: "varRef", localId: "d", type: DYN };
const key: IrExpr = { loc, kind: "varRef", localId: "k", type: STRING };
const computed: IrStmt = {
loc,
kind: "exprStmt",
expr: { loc, kind: "dynKeyGet", value, key, type: DYN },
};
const spelled: IrStmt = {
loc,
kind: "exprStmt",
expr: { loc, kind: "strLit", value: "stack", type: STRING },
};
expect(observesStacks(mod([fn("%main", [computed, spelled])]))).toBe(true);
expect(observesStacks(mod([fn("%main", [computed])]))).toBe(false);
});
test("programs without stack reads are not", () => {
expect(observesStacks(mod([fn("%main", [call("helper")]), fn("helper", [ret])]))).toBe(false);
});
@@ -13,12 +13,34 @@ import { writesPublished } from "./publication.js";
/** Lib calls that read a captured stack trace. */
const STACK_READS: ReadonlySet<string> = new Set(["error.stack"]);
function readsStack(expr: IrExpr): boolean {
return expr.kind === "libCall" && STACK_READS.has(expr.fn);
/** A typed `error.stack` read, or a read on a checked-dynamic value that
* can reach an error's own `stack` accessor: the constant key `stack`, or
* a computed key when `computedKeys` (the program spells "stack", so a
* computed key can name it). A key the program assembles from other
* strings or from data it reads keeps the static answer. */
function readsStack(expr: IrExpr, computedKeys: boolean): boolean {
if (expr.kind === "libCall") return STACK_READS.has(expr.fn);
if (expr.kind !== "dynKeyGet") return false;
if (expr.key.kind === "strLit") return expr.key.value === "stack";
return computedKeys;
}
function containsStackRead(fn: IrFunction): boolean {
return !everyStmtList(fn.body, { stmt: () => true, expr: (expr) => !readsStack(expr) });
/** Whether the module contains the string literal "stack". */
function spellsStack(mod: IrModule): boolean {
return mod.functions.some(
(fn) =>
!everyStmtList(fn.body, {
stmt: () => true,
expr: (expr) => !(expr.kind === "strLit" && expr.value === "stack"),
}),
);
}
function containsStackRead(fn: IrFunction, computedKeys: boolean): boolean {
return !everyStmtList(fn.body, {
stmt: () => true,
expr: (expr) => !readsStack(expr, computedKeys),
});
}
/** Visit every expression of `body` that execution can reach: statements
@@ -43,7 +65,8 @@ function visitLiveExprs(body: IrStmt[], visit: (expr: IrExpr) => void): void {
* and those reads must not cost every call of the program a frame.
* Programs without any stack read answer false without the walk. */
export function observesStacks(mod: IrModule): boolean {
if (!mod.functions.some(containsStackRead)) return false;
const computedKeys = spellsStack(mod);
if (!mod.functions.some((fn) => containsStackRead(fn, computedKeys))) return false;
const byName = new Map(mod.functions.map((fn) => [fn.name, fn]));
const classNames = new Set((mod.classes ?? []).map((cls) => cls.name));
const pending: string[] = [...moduleFunctionReferences(mod)];
@@ -67,7 +90,7 @@ export function observesStacks(mod: IrModule): boolean {
const fn = byName.get(name);
if (fn === undefined) continue;
visitLiveExprs(fn.body, (expr) => {
if (readsStack(expr)) observed = true;
if (readsStack(expr, computedKeys)) observed = true;
if (expr.kind === "call" && !reached.has(expr.callee)) pending.push(expr.callee);
const referenced = exprFunctionReference(expr);
if (referenced !== undefined && !reached.has(referenced)) pending.push(referenced);
@@ -59,8 +59,9 @@
* order that differs from insertion order where the program
* observes it (SC6002), localeCompare over text the built-in
* collation does not cover (SC6003), a call feeding an instance
* to a cast to an unrelated class (SC6004), and Date strings the native parser does not
* accept (SC6005)
* to a cast to an unrelated class (SC6004); SC6005 (Date strings
* outside the native parser's grammar) is retired — the runtime
* parses date strings with V8's grammar
* SC9xxx internal compiler errors (still source-anchored)
*/
import type { SrcLoc } from "../ir/ir.js";
@@ -200,18 +201,6 @@ export function unrelatedClassCastDivergenceDiag(
};
}
/** SC6005 — a Date string literal outside the grammar the native parser
* accepts (ISO 8601 with an explicit offset, date-only forms, and the
* certificate-time shape): Node parses many more forms. */
export function dateLiteralDivergenceDiag(text: string, loc: SrcLoc): ScrDiagnostic {
return {
code: "SC6005",
message: `the date string '${text}' parses to an invalid date (NaN) natively, while Node accepts it (the native parser takes ISO 8601 date-times with an explicit offset, such as '2024-01-02T03:04:05Z', and date-only forms)`,
loc,
hint: "write the date in ISO 8601 with an explicit offset ('Z' or '+HH:MM'), or build it from numbers with Date.UTC",
};
}
/* ── SC5xxx: native FFI ───────────────────────────────────────────────── */
/** SC5001 — the outbound native-FFI manifest is malformed or unreadable. */
@@ -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(
@@ -27,6 +27,8 @@ test.each([
['"default"', '"default;s3:foo;"'],
['"default"', '"default\\0"'],
["mod", "mod other"],
["cb[0]", "cb[1]"],
["cb[1]", "cb[10]"],
])("retains a semantic difference between %s and %s", (a, b) => {
expect(helperTokens(a)).not.toBe(helperTokens(b));
});
@@ -44,8 +46,12 @@ test.each([
"'\\8'",
"`template`",
"/regexp/",
"0",
"0x10",
"07",
"1.5",
"1e3",
"1n",
"1_000",
"a / b",
"\\u0061",
"café",
@@ -1,8 +1,8 @@
/** Token fingerprints for the fixed bundler helpers we recognize. This is
* deliberately not a JavaScript parser: regexes, templates, escaped names,
* numbers, and unknown punctuation refuse the helper. None occur in the
* canonical helpers. Every accepted token is represented in the result;
* comments and whitespace alone may disappear. */
* numbers other than plain decimal integers, and unknown punctuation refuse
* the helper. None occur in the canonical helpers. Every accepted token is
* represented in the result; comments and whitespace alone may disappear. */
const operators = [
">>>=",
"===",
@@ -157,6 +157,15 @@ export function helperTokens(text: string): string | null {
result += fingerprint("s", token.value);
i = token.end;
previous = "string";
} else if (/[0-9]/.test(ch)) {
// Plain decimal integers only (esbuild's `cb[keys(cb)[0]]`): a
// legacy octal, fraction, exponent, radix prefix, BigInt suffix or
// numeric separator refuses rather than aliasing another value.
const start = i++;
while (i < text.length && /[0-9]/.test(text.charAt(i))) i++;
if (/[A-Za-z0-9_$.\\]/.test(text.charAt(i)) || (ch === "0" && i - start > 1)) return null;
previous = text.slice(start, i);
result += fingerprint("n", previous);
} else if (/[A-Za-z_$]/.test(ch)) {
const start = i++;
while (i < text.length && /[A-Za-z0-9_$]/.test(text.charAt(i))) i++;
@@ -164,8 +164,28 @@ export function markFrontendInputsUnstable(): void {
(synchronousTracker ?? activeTracker.getStore())?.markUnstable();
}
/** Compiler-synthesized module sources (a bundle's CommonJS chunks split
* into sibling modules, npm-static-bundled-chunks.ts). They answer like
* regular files but are never recorded: each derives from the content of
* a recorded bundle read, which already keys every cache that sees it. */
const virtualSources = new Map<string, string>();
export function setVirtualSource(path: string, text: string): void {
virtualSources.set(resolve(path), text);
}
export function isVirtualSource(path: string): boolean {
return virtualSources.has(resolve(path));
}
export function clearVirtualSources(): void {
virtualSources.clear();
}
export function trackedReadFile(path: string): string | null {
path = resolve(path);
const virtual = virtualSources.get(path);
if (virtual !== undefined) return virtual;
try {
const text = readFileSync(path, "utf8");
record({ op: "file", path, digest: frontendSourceDigest(text) });
@@ -178,6 +198,7 @@ export function trackedReadFile(path: string): string | null {
export function trackedFileExists(path: string): boolean {
path = resolve(path);
if (virtualSources.has(path)) return true;
const kind = pathKind(path);
record({ op: "kind", path, kind });
return kind === "file";
@@ -185,6 +206,7 @@ export function trackedFileExists(path: string): boolean {
export function trackedDirectoryExists(path: string): boolean {
path = resolve(path);
if (virtualSources.has(path)) return false;
const kind = pathKind(path);
record({ op: "kind", path, kind });
return kind === "directory";
@@ -192,6 +214,7 @@ export function trackedDirectoryExists(path: string): boolean {
export function trackedExists(path: string): boolean {
path = resolve(path);
if (virtualSources.has(path)) return true;
const kind = pathKind(path);
record({ op: "kind", path, kind });
return kind !== "missing";
@@ -199,6 +222,7 @@ export function trackedExists(path: string): boolean {
export function trackedRealpath(path: string): string | null {
path = resolve(path);
if (virtualSources.has(path)) return path;
try {
const target = systemRealpath(path);
record({ op: "realpath", path, target });
@@ -223,9 +247,13 @@ export function trackedAccessibleEntries(
}
files.sort();
directories.sort();
const answer = { files, directories };
record({ op: "entries", path, files, directories });
return answer;
record({ op: "entries", path, files: [...files], directories });
for (const virtual of virtualSources.keys()) {
if (dirname(virtual) === path && !files.includes(basename(virtual)))
files.push(basename(virtual));
}
files.sort();
return { files, directories };
} catch {
// Enumeration can fail even while the path remains a directory. Preserve
// the failed operation itself so a permission/ACL repair invalidates the
@@ -12,6 +12,7 @@ import { lowerEventsEmitterHelper, lowerEventsOnce } from "./lower-event-emitter
import type { Lowerer } from "./lowerer.js";
import { lowerTimersMemberCall } from "./lower-timers.js";
import { lowerStreamModuleCall } from "./lower-stream.js";
import { lowerCallbackPromisify } from "./builtins/promisify-callback.js";
import { lowerNodeModuleCall } from "./builtins/module-resolution.js";
import { builtinModuleFnOf, builtinFenceHintOf } from "./surfaces.js";
@@ -87,6 +88,10 @@ export function lowerBuiltinCall(
if (testServed) return testServed;
const utilServed = lowerer.lowerUtilModuleCall(expr, bi, loc);
if (utilServed) return utilServed;
if (bi.module === "util" && bi.member === "promisify") {
const promisified = lowerCallbackPromisify(lowerer, expr, loc);
if (promisified) return promisified;
}
const streamServed = lowerStreamModuleCall(lowerer, expr, bi, loc);
if (streamServed) return streamServed;
const fsTs = lowerer.lowerFsToUnixTimestampCall(expr, bi, loc);
@@ -1,11 +1,12 @@
import * as ts from "../../ts7/adapter.js";
import { type Lowerer } from "../lowerer.js";
import { isJsSourceFile } from "../../program.js";
import { isJsSourceFile, locOf } from "../../program.js";
import { builtinModuleFnOf } from "../surfaces.js";
import { registerHttpClientFnBinding } from "../lower-server.js";
import { isPromisifiedZlibMember } from "./compression.js";
import { isPromisifiedCryptoMember } from "./crypto.js";
import { isPromisifiedDnsMember } from "../lower-dgram.js";
import { callbackPromisifyShape } from "./promisify-callback.js";
/** Compile-time util.promisify projections. The immutable result binding
* owns no runtime slot: calls rewrite to the target's promise lowering,
@@ -164,11 +165,14 @@ export function registerPromisifiedBuiltinDecl(
: target?.module === "dns" && isPromisifiedDnsMember(target.member)
? { kind: "promisified-dns" as const, member: target.member }
: null;
// A typed callback-last function value: the call lowers to a native
// promisified function, and the binding holds it like any closure.
if (!projection && callbackPromisifyShape(lowerer, e, locOf(e)) !== null) return false;
if (!projection) {
lowerer.noLowering(
"util.promisify of this target",
argNode ?? e,
"child_process.exec, child_process.execFile, setTimeout, setImmediate, stream.finished, stream.pipeline, the zlib callback one-shots, the crypto callback functions (randomBytes, pbkdf2, scrypt, hkdf, randomFill, randomInt, generateKey), dns.lookup, dns.lookupService and the fs callback functions with an fs/promises counterpart are the supported targets",
"child_process.exec, child_process.execFile, setTimeout, setImmediate, stream.finished, stream.pipeline, the zlib callback one-shots, the crypto callback functions (randomBytes, pbkdf2, scrypt, hkdf, randomFill, randomInt, generateKey), dns.lookup, dns.lookupService, the fs callback functions with an fs/promises counterpart, and typed callback-last functions whose callback takes (error?: Error | null, value?) are the supported targets",
);
}
const symbol = lowerer.checker.getSymbolAtLocation(nameNode);
@@ -58,9 +58,8 @@ export function lowerDateCall(
}
return { kind: "libCall", fn: "date.now", args: [], type: F64, loc };
}
// Date.parse uses the same bounded date-string parser as
// new Date(dateString).getTime(); keep their NaN and TimeClip behavior
// identical for the ISO timestamps used by CLI applications.
// Date.parse uses the same date-string parser as new Date(dateString)
// (V8's grammar in the runtime), so their NaN and TimeClip behavior agree.
if (lowerer.stdlibGlobalMember(access, "Date") === "parse") {
if (call.arguments.nodes.length !== 1 || ts.isSpreadElement(call.arguments.nodes[0]!)) {
lowerer.noLowering(`Date.parse with ${call.arguments.nodes.length} arguments`, call);
@@ -1,7 +1,17 @@
import * as ts from "../../ts7/adapter.js";
import { type Lowerer } from "../lowerer.js";
import { locOf } from "../../program.js";
import { BOOL, type IrExpr, type IrType, STRING, type SrcLoc } from "../../../ir/ir.js";
import {
BOOL,
type IrExpr,
type IrStmt,
type IrType,
STRING,
type SrcLoc,
UNDEFINED_T,
} from "../../../ir/ir.js";
import { nodeThrowExpr } from "../../../ir/build.js";
import { processHasIpc } from "./process.js";
/** Method calls on ChildProcess receivers: `child.on("exit"|"error", cb)`
* registers a listener with the event loop's child registry. The event
@@ -86,8 +96,54 @@ export function ipcSendCallback(lowerer: Lowerer, node: ts.Expression): IrExpr {
return cb;
}
/** process.send in a program without fork targets. This binary never opens
* a channel then, so only a Node.js parent's NODE_CHANNEL_FD can define
* process.send, and that channel has no lowering: a call fences when it runs.
* Without any channel the calls behave as Node's do on an undefined member:
* `process.send?.(...)` skips its arguments and answers undefined, and
* `process.send(...)` evaluates them and throws a TypeError. The message is
* never sent, so its type is not checked. */
function lowerChannelLessSend(lowerer: Lowerer, call: ts.CallExpression): IrExpr {
const loc = locOf(call);
const fence = (type: IrType): IrExpr =>
nodeThrowExpr(
0,
"SC2020",
"process.send over an IPC channel opened by a Node.js parent (NODE_CHANNEL_FD) is not supported yet",
type,
loc,
);
const hasIpc = processHasIpc(lowerer, loc);
if (call.questionDotToken) {
const type = lowerer.mapTypeOf(lowerer.typeOf(call)) ?? BOOL;
const absent: IrExpr =
type.kind === "bool"
? { kind: "boolLit", value: false, type: BOOL, loc }
: lowerer.coerceToExpected(
{ kind: "unitLit", unit: "undefined", type: UNDEFINED_T, loc },
type,
);
return { kind: "ternary", cond: hasIpc, then: fence(type), else_: absent, type, loc };
}
const stmts: IrStmt[] = call.arguments.nodes.map((arg) => ({
kind: "exprStmt",
expr: lowerer.lowerExpr(ts.isSpreadElement(arg) ? arg.expression : arg),
loc: locOf(arg),
}));
const result: IrExpr = {
kind: "ternary",
cond: hasIpc,
then: fence(BOOL),
else_: nodeThrowExpr(1, "", "process.send is not a function", BOOL, loc),
type: BOOL,
loc,
};
return stmts.length === 0 ? result : { kind: "seqExpr", stmts, result, type: BOOL, loc };
}
export function lowerProcessIpcSend(lowerer: Lowerer, call: ts.CallExpression): IrExpr {
const loc = locOf(call);
if (lowerer.forkTargets.length === 0) return lowerChannelLessSend(lowerer, call);
if (
call.arguments.nodes.length < 1 ||
call.arguments.nodes.length > 2 ||
@@ -17,6 +17,7 @@ import {
type IrExpr,
type IrLibFn,
type IrStmt,
type IrType,
STRING,
type SrcLoc,
UNDEFINED_T,
@@ -26,10 +27,149 @@ import {
funcOf,
} from "../../../ir/ir.js";
import { lowerBuiltinLoaderValue } from "../lower-builtin-values.js";
import { builtinFunctionValue } from "../lower-exprs.js";
import { canonicalBuiltinModule } from "../../builtin-modules.js";
import { lowerProcessIpcSend, ipcMessageListener, ipcDisconnectListener } from "./ipc.js";
import { lowerDiagnosticsSubscriber, lowerTracingArguments } from "./async-context.js";
/** Whether the process has an IPC channel, Node's test for defining
* process.send and process.disconnect: a channel this fork child opened
* (programs with fork targets only), or a non-empty NODE_CHANNEL_FD from a
* Node.js parent, the variable Node itself tests at startup. Built from the
* existing environment read, so the presence test links no runtime code. */
export function processHasIpc(lowerer: Lowerer, loc: SrcLoc): IrExpr {
const envT = lowerer.envValueType();
const unionId = (envT as IrType & { kind: "union" }).unionId;
const stringTag = lowerer.armTag(unionId, STRING);
const value = lowerer.declareHiddenLocal("%channelFd", envT);
const fromNode: IrExpr = {
kind: "seqExpr",
stmts: [
{
kind: "varDecl",
localId: value.id,
init: {
kind: "libCall",
fn: "process.envGet",
args: [strLit("NODE_CHANNEL_FD", loc)],
type: envT,
loc,
},
loc,
},
],
result: {
kind: "logical",
op: "&&",
left: {
kind: "unionIsTag",
unionId,
tag: stringTag,
negated: false,
value: varRef(value.id, envT, loc),
type: BOOL,
loc,
},
right: {
kind: "toBool",
operand: {
kind: "unionNarrow",
unionId,
tag: stringTag,
value: varRef(value.id, envT, loc),
type: STRING,
loc,
},
type: BOOL,
loc,
},
type: BOOL,
loc,
},
type: BOOL,
loc,
};
if (lowerer.forkTargets.length === 0) return fromNode;
return {
kind: "logical",
op: "||",
left: { kind: "libCall", fn: "process.ipcOpen", args: [], type: BOOL, loc },
right: fromNode,
type: BOOL,
loc,
};
}
/** True when the value of `node` is consumed only by ToBoolean: a
* condition, the operand of `!`, `Boolean(node)`, or an operand of `&&` /
* `||` whose own value is consumed that way (or discarded, for the left
* operand). */
export function isTruthinessOnlyRead(lowerer: Lowerer, node: ts.Expression): boolean {
let child: ts.Node = node;
let parent = node.parent;
while (parent !== undefined && ts.isParenthesizedExpression(parent)) {
child = parent;
parent = parent.parent;
}
if (parent === undefined) return false;
if (ts.isIfStatement(parent) || ts.isWhileStatement(parent) || ts.isDoStatement(parent))
return parent.expression === child;
if (ts.isForStatement(parent)) return parent.condition === child;
if (ts.isConditionalExpression(parent)) return parent.condition === child;
if (ts.isPrefixUnaryExpression(parent)) return parent.operator === ts.SyntaxKind.ExclamationToken;
if (ts.isCallExpression(parent)) {
return (
!parent.questionDotToken &&
parent.arguments.nodes.length === 1 &&
parent.arguments.nodes[0] === child &&
lowerer.isStdlibGlobal(parent.expression, "Boolean")
);
}
if (ts.isBinaryExpression(parent)) {
const op = parent.operatorToken.kind;
if (op !== ts.SyntaxKind.AmpersandAmpersandToken && op !== ts.SyntaxKind.BarBarToken)
return false;
if (isTruthinessOnlyRead(lowerer, parent)) return true;
let outer: ts.Node | undefined = parent.parent;
while (outer !== undefined && ts.isParenthesizedExpression(outer)) outer = outer.parent;
return parent.left === child && outer !== undefined && ts.isExpressionStatement(outer);
}
return false;
}
/** Whether a program source reads process.exitCode. Such a program
* records its exit-code assignments (process.setExitCodeTracked), so a
* read can tell an unset code from 0; other programs keep the untracked
* write. Computed once per lowering pass. */
export function programReadsExitCode(lowerer: Lowerer): boolean {
if (lowerer.readsExitCode !== null) return lowerer.readsExitCode;
let found = false;
const walk = (node: ts.Node): void => {
if (found) return;
if (
ts.isPropertyAccessExpression(node) &&
node.name.text === "exitCode" &&
!(
ts.isBinaryExpression(node.parent) &&
node.parent.left === node &&
node.parent.operatorToken.kind === ts.SyntaxKind.EqualsToken
) &&
lowerer.stdlibGlobalMember(node, "process") === "exitCode"
) {
found = true;
return;
}
ts.forEachChild(node, walk);
};
for (const sf of lowerer.program.getImplementationSourceFiles()) {
if (sf.isDeclarationFile) continue;
walk(sf);
if (found) break;
}
lowerer.readsExitCode = found;
return found;
}
/** The pinned Node release the runtime reports as process.versions.node
* (packages/runtime/src/scr_lib.c SCR_NODE_COMPAT_VERSION, kept equal to
* internal/compatibility/node-v24.json by test/node-pin.test.ts). */
@@ -374,9 +514,45 @@ export function lowerProcessProperty(
const member = lowerer.stdlibGlobalMember(expr, "process");
if (member === null) return null;
const loc = locOf(expr);
// `if (process.send)`: Node defines process.send and process.disconnect
// only when the process has an IPC channel. A read whose value only
// feeds a truthiness test answers that presence; other value uses keep
// the member fence.
if (
(member === "send" || member === "disconnect") &&
!expr.questionDotToken &&
isTruthinessOnlyRead(lowerer, expr)
) {
return processHasIpc(lowerer, loc);
}
if (member === "versions") {
return { kind: "libCall", fn: "process.versions", args: [], type: DYN, loc };
}
// process.exitCode: undefined until something assigns it, then the
// assigned code. A read the checker narrowed to number follows an
// assignment, so the code is set.
if (member === "exitCode" && !expr.questionDotToken) {
const current: IrExpr = {
kind: "libCall",
fn: "process.currentExitCode",
args: [],
type: F64,
loc,
};
if (lowerer.mapTypeOf(lowerer.typeOf(expr))?.kind === "f64") return current;
const type: IrType = { kind: "union", unionId: lowerer.unions.intern([F64, UNDEFINED_T]) };
return {
kind: "ternary",
cond: { kind: "libCall", fn: "process.hasExitCode", args: [], type: BOOL, loc },
then: lowerer.coerceToExpected(current, type),
else_: lowerer.coerceToExpected(
{ kind: "unitLit", unit: "undefined", type: UNDEFINED_T, loc },
type,
),
type,
loc,
};
}
// process.features as a value (`"sea" in process.features`): an object
// holding none of the flags, consistent with the member reads above.
if (member === "features") {
@@ -403,6 +579,11 @@ export function lowerProcessProperty(
if (member === "hrtime") {
return { kind: "libCall", fn: "process.hrtimeValue", args: [], type: DYN, loc };
}
// A stored process.nextTick in JavaScript (`cond ? setImmediate :
// process.nextTick`): the interned builtin function value.
if (member === "nextTick" && isJsSourceFile(expr.getSourceFile())) {
return builtinFunctionValue("process.nextTick", loc);
}
if (member === "getBuiltinModule") {
// Keep the native loader's argument validation when the function is
// stored. The declaration's string signature must not insert a checked
@@ -1575,10 +1756,36 @@ export function lowerProcessMethodCall(
}
if (member === "exit") {
const arg = call.arguments.nodes[0];
const code: IrExpr =
let code: IrExpr =
arg !== undefined
? lowerer.lowerExprExpecting(arg, F64)
: { kind: "libCall", fn: "process.currentExitCode", args: [], type: F64, loc };
// process.exit(code) assigns process.exitCode before the 'exit'
// listeners run. Only a program that reads the property can observe
// that, so only such a program records the assignment.
if (arg !== undefined && programReadsExitCode(lowerer)) {
const binding = lowerer.declareHiddenLocal("%exitCode", F64);
code = {
kind: "seqExpr",
stmts: [
{ kind: "varDecl", localId: binding.id, init: code, loc },
{
kind: "exprStmt",
expr: {
kind: "libCall",
fn: "process.setExitCodeTracked",
args: [varRef(binding.id, F64, loc)],
type: VOID,
loc,
},
loc,
},
],
result: varRef(binding.id, F64, loc),
type: F64,
loc,
};
}
return { kind: "libCall", fn: "process.exit", args: [code], type: VOID, loc };
}
return null; // process.argv(...) etc. are tsc errors before lowering
@@ -1594,6 +1801,16 @@ export function lowerProcessOptionalMethodCall(
lowerer: Lowerer,
expr: ts.CallExpression,
): IrExpr | null {
// `process.send!(message)`: the asserted direct call of the optional
// member (the @types/node spelling under strict null checks).
if (
!expr.questionDotToken &&
ts.isNonNullExpression(expr.expression) &&
ts.isPropertyAccessExpression(expr.expression.expression) &&
!expr.expression.expression.questionDotToken &&
lowerer.stdlibGlobalMember(expr.expression.expression, "process") === "send"
)
return lowerProcessIpcSend(lowerer, expr);
if (!expr.questionDotToken) return null;
if (!ts.isPropertyAccessExpression(expr.expression)) return null;
const member = lowerer.stdlibGlobalMember(expr.expression, "process");
@@ -1,7 +1,8 @@
import { checkedPromiseAll } from "../checked-promise-all.js";
import { checkedPromiseAll, thenReader } from "../checked-promise-all.js";
import { InternalCompilerError } from "../../../errors.js";
import * as ts from "../../ts7/adapter.js";
import { type Lowerer } from "../lowerer.js";
import { newFnCtx, type Lowerer } from "../lowerer.js";
import { varRef } from "../../../ir/build.js";
import { maybePromiseResolve, maybePromiseUnionOf } from "../maybe-promise.js";
import { isJsSourceFile, locOf } from "../../program.js";
import {
@@ -10,6 +11,7 @@ import {
type IrFunction,
type IrStmt,
type IrType,
UNDEFINED_T,
VOID,
arrayOf,
isUnitType,
@@ -17,6 +19,168 @@ import {
typeKey,
} from "../../../ir/ir.js";
/** `Promise.all([p, q, r])` over DIFFERENT promise types — the checker's
* tuple overload, `Promise<[A, B, C]>`. One interned async helper per
* entry/result signature takes the entries as arguments, awaits the
* runtime combinator over the same promises (each widened to
* Promise<void>, a type-only view), so settlement is Node's exactly: the
* first rejection in settlement order wins and every later one counts as
* handled; then it reads each (now fulfilled) entry and returns the
* tuple. Entries keep their identity — no value converts through the
* checked-dynamic tree. Non-promise entries (numbers, strings, booleans,
* unit values — never thenable) pass straight into their slot; a
* checked-dynamic entry (a JavaScript function's result) joins through
* PromiseResolve: the promise it holds, a promise that adopts a thenable,
* or a promise fulfilled with its plain value. The tuple
* fulfills one microtask turn after the combinator does. Null when the
* result type or an entry has no typed home here. */
function lowerTuplePromiseAll(
lowerer: Lowerer,
call: ts.CallExpression,
elems: IrExpr[],
): IrExpr | null {
const resultT = lowerer.mapTypeOf(lowerer.typeOf(call));
if (resultT?.kind !== "promise" || resultT.inner.kind !== "record") return null;
const shape = lowerer.shapes.get(resultT.inner.shapeId);
if (!shape?.tuple || shape.fields.length !== elems.length) return null;
const plainValue = (t: IrType): boolean =>
t.kind === "f64" || t.kind === "string" || t.kind === "bool" || isUnitType(t);
// A checked-dynamic entry (a JavaScript function's result) may hold a
// promise or a plain value at run time; it joins through its promise view.
const settles = (t: IrType): boolean => t.kind === "promise" || t.kind === "dyn";
if (!elems.some((e) => settles(e.type))) return null;
if (!elems.every((e) => settles(e.type) || plainValue(e.type))) return null;
const loc = locOf(call);
const key = `${elems.map((e) => typeKey(e.type)).join(",")}->${typeKey(resultT.inner)}`;
let name = lowerer.arrHofHelpers.get(`promise.allTuple:${key}`);
if (name === undefined) {
name = `%promise.allTuple.${lowerer.arrHofHelpers.size}`;
lowerer.arrHofHelpers.set(`promise.allTuple:${key}`, name);
const ctx = newFnCtx(false, null, null, resultT.inner);
ctx.isAsync = true;
lowerer.fnStack.push(ctx);
try {
const params = elems.map((e, i) => ({
localId: `entry.${i}`,
name: `entry${i}`,
type: e.type,
}));
const ref = (i: number): IrExpr => varRef(`entry.${i}`, elems[i]!.type, loc);
const dynPromise: IrType = { kind: "promise", inner: DYN };
const body: IrStmt[] = [];
// Each dyn entry's promise view, in entry order: the promise it
// holds, a promise that adopts a thenable's settlement, or a promise
// fulfilled with the plain value (PromiseResolve's rule).
const views = new Map<number, IrExpr>();
elems.forEach((e, i) => {
if (e.type.kind !== "dyn") return;
const view = lowerer.declareHiddenLocal("%allEntry", dynPromise);
body.push({
kind: "varDecl",
localId: view.id,
init: {
kind: "libCall",
fn: "dyn.promiseResolve",
args: [ref(i), thenReader(lowerer, loc)],
type: dynPromise,
loc,
},
loc,
});
views.set(i, varRef(view.id, dynPromise, loc));
});
const widened: IrExpr[] = [];
elems.forEach((e, i) => {
const view = views.get(i);
if (view !== undefined) {
widened.push({
kind: "promiseVoidWiden",
value: view,
type: { kind: "promise", inner: VOID },
loc,
});
return;
}
if (e.type.kind !== "promise") return;
widened.push(
e.type.inner.kind === "void"
? ref(i)
: {
kind: "promiseVoidWiden",
value: ref(i),
type: { kind: "promise", inner: VOID },
loc,
},
);
});
const settled: IrExpr = {
kind: "awaitExpr",
value: {
kind: "intrinsic",
name: "promise.all",
args: [
{
kind: "arrayLit",
elems: widened,
type: arrayOf({ kind: "promise", inner: VOID }),
loc,
},
],
type: { kind: "promise", inner: VOID },
loc,
},
type: VOID,
loc,
};
// Shape fields are sorted by name ("10" before "2"); a tuple field's
// name is its position.
const fields = shape.fields.map((field) => {
const i = Number(field.name);
const entry = elems[i]!;
let value: IrExpr;
const view = views.get(i);
if (view !== undefined) {
value = { kind: "awaitExpr", value: view, type: DYN, loc };
} else if (entry.type.kind === "promise") {
value =
entry.type.inner.kind === "void"
? { kind: "unitLit", unit: "undefined", type: UNDEFINED_T, loc }
: { kind: "awaitExpr", value: ref(i), type: entry.type.inner, loc };
} else {
value = ref(i);
}
return { name: field.name, value: lowerer.coerceToExpected(value, field.type) };
});
body.push(
{ kind: "exprStmt", expr: settled, loc },
{
kind: "return",
value: { kind: "recordLit", fields, type: resultT.inner, loc },
loc,
},
);
lowerer.liftedFns.push({
name,
params,
returnType: resultT.inner,
locals: [
...params.map((p) => ({ id: p.localId, name: p.name, type: p.type, mutable: false })),
...lowerer.ctx.locals,
],
body,
async: true,
loc,
});
} catch (e) {
lowerer.arrHofHelpers.delete(`promise.allTuple:${key}`);
throw e;
} finally {
lowerer.fnStack.pop();
}
}
return { kind: "call", callee: name, args: elems, type: resultT, loc };
}
/** `Promise.race([...])` on THE Promise global: the entries lower
* individually (the array never materializes — promise-element arrays
* have no representation) into a promise.race intrinsic; the result
@@ -65,12 +229,26 @@ export function lowerPromiseStaticCall(
const compatible = (inner: IrType): boolean => {
if (typeEquals(inner, resultT.inner)) return true;
if (!resultArms) return false;
// A Promise<void> entry fulfills with undefined, which the result
// holds when the checker folded `void` into its undefined arm.
if (inner.kind === "void") return resultArms.some((a) => a.kind === "undefinedT");
if (inner.kind === "union") {
const arms = lowerer.unions.get(inner.unionId)?.arms ?? [];
return arms.every((a) => resultArms.some((b) => typeEquals(a, b)));
}
return resultArms.some((a) => typeEquals(a, inner));
};
// A Promise<never> entry (the deadline idiom: `new Promise<never>((_,
// reject) => setTimeout(reject, ms))`) can only reject, so it races
// under any result type; its inner type maps to void.
const neverEntry = (el: ts.Expression): boolean => {
const t = lowerer.typeOf(el);
const arg =
t.getSymbol()?.name === "Promise"
? lowerer.checker.getTypeArguments(t as ts.TypeReference)[0]
: undefined;
return arg !== undefined && (arg.flags & ts.TypeFlags.Never) !== 0;
};
const entries = argNode.elements.nodes.map((el) => {
const entry = lowerer.lowerExpr(el);
if (entry.type.kind !== "promise") {
@@ -80,7 +258,7 @@ export function lowerPromiseStaticCall(
"JS would resolve plain values — wrap them: new Promise((r) => r(v))",
);
}
if (!compatible(entry.type.inner)) {
if (!compatible(entry.type.inner) && !(entry.type.inner.kind === "void" && neverEntry(el))) {
lowerer.unsupported(
"SC1090",
el,
@@ -140,6 +318,10 @@ export function lowerPromiseStaticCall(
return { kind: "intrinsic", name: "promise.all", args: [entriesArr], type: resultT, loc };
}
if (!isJsSourceFile(call.getSourceFile())) {
const tuple = lowerTuplePromiseAll(lowerer, call, elems);
if (tuple) return tuple;
}
if (
isJsSourceFile(call.getSourceFile()) &&
elems.every((entry) => lowerer.dynConvertible(entry.type))
@@ -0,0 +1,377 @@
import * as ts from "../../ts7/adapter.js";
import { type Lowerer } from "../lowerer.js";
import { varRef } from "../../../ir/build.js";
import {
BOOL,
type IrExpr,
type IrLocal,
type IrParam,
type IrStmt,
type IrType,
type SrcLoc,
VOID,
funcOf,
isUnitType,
typeEquals,
typeKey,
} from "../../../ir/ir.js";
const ERROR_T: IrType = { kind: "object", className: "%Error" };
/** The parts of `util.promisify(fn)` for a typed callback-last function:
* `fn(...args, (err, value) => void)` becomes `(...args) => Promise<T>`. */
export interface CallbackShape {
fnT: IrType & { kind: "func" };
resultT: IrType & { kind: "func" };
args: readonly IrType[];
callbackT: IrType & { kind: "func" };
/** The parameter's declared type: callbackT, or `callbackT | undefined`
* for an optional callback. */
callbackParamT: IrType;
inner: IrType;
/** The error parameter's union and the tag of its Error arm, or null when
* the callback declares no error parameter. */
error: { type: IrType; errorTag: number; unitTags: number[] } | null;
}
function callbackShape(
lowerer: Lowerer,
fnT: IrType | null,
resultT: IrType | null,
loc: SrcLoc,
): CallbackShape | null {
if (fnT?.kind !== "func" || resultT?.kind !== "func") return null;
if (fnT.rest || fnT.restAbi || fnT.argumentsAll || resultT.rest || resultT.restAbi) return null;
const callbackParamT = fnT.params[fnT.params.length - 1];
// An optional callback (`close(callback?: (err?: Error) => void)`) takes
// its function arm; the call passes the callback into the union.
const callbackT =
callbackParamT?.kind === "union"
? (() => {
const arms = lowerer.unions.get(callbackParamT.unionId)?.arms ?? [];
const fns = arms.filter((arm) => arm.kind === "func");
return fns.length === 1 &&
arms.every((arm) => arm.kind === "func" || arm.kind === "undefinedT")
? fns[0]
: undefined;
})()
: callbackParamT;
if (callbackT?.kind !== "func" || callbackT.ret.kind !== "void") return null;
if (callbackT.rest || callbackT.restAbi || callbackT.params.length > 2) return null;
const args = fnT.params.slice(0, -1);
if (
resultT.ret.kind !== "promise" ||
resultT.params.length !== args.length ||
!resultT.params.every((type, i) => typeEquals(type, args[i]!))
)
return null;
const inner = resultT.ret.inner;
let error: CallbackShape["error"] = null;
const errorT = callbackT.params[0];
if (errorT !== undefined) {
if (errorT.kind !== "union") return null;
const arms = lowerer.unions.get(errorT.unionId)?.arms ?? [];
const errorTags = arms.flatMap((arm, tag) =>
arm.kind === "object" &&
(arm.className === "%Error" || lowerer.isSubclassOf(arm.className, "%Error"))
? [tag]
: [],
);
const unitTags = arms.flatMap((arm, tag) => (isUnitType(arm) ? [tag] : []));
if (errorTags.length !== 1 || errorTags.length + unitTags.length !== arms.length) return null;
error = { type: errorT, errorTag: errorTags[0]!, unitTags };
}
if (inner.kind !== "void") {
const valueT = callbackT.params[1];
if (valueT === undefined) return null;
const probe: IrExpr = { kind: "varRef", localId: "%probe", type: valueT, loc };
if (!typeEquals(lowerer.coerceToExpected(probe, inner).type, inner)) return null;
}
return { fnT, resultT, args, callbackT, callbackParamT: callbackParamT!, inner, error };
}
/** The callback shape of a `promisify(fn)` call, or null. */
export function callbackPromisifyShape(
lowerer: Lowerer,
call: ts.CallExpression,
loc: SrcLoc,
): CallbackShape | null {
if (call.questionDotToken || call.arguments.nodes.length !== 1) return null;
const argNode = call.arguments.nodes[0]!;
if (ts.isSpreadElement(argNode)) return null;
return callbackShape(
lowerer,
lowerer.mapTypeOf(lowerer.typeOf(argNode)),
lowerer.mapTypeOf(lowerer.typeOf(call)),
loc,
);
}
function captureParam(localId: string, type: IrType): IrParam {
return { localId, name: localId, type };
}
function boxedLocal(localId: string, type: IrType): IrLocal {
return { id: localId, name: localId, type, mutable: false, boxed: true };
}
function plainLocal(localId: string, type: IrType): IrLocal {
return { id: localId, name: localId, type, mutable: false };
}
/** `util.promisify(fn)` over a typed callback-last function value (a bound
* method, a function declaration, a closure): a native function that calls
* `fn` with the arguments and a callback, and settles its promise from the
* callback like Node's wrapper: a truthy error rejects, otherwise the first
* value fulfills. A synchronous throw rejects (the executor's rule). Null
* when the argument or result does not have that typed shape. */
export function lowerCallbackPromisify(
lowerer: Lowerer,
call: ts.CallExpression,
loc: SrcLoc,
): IrExpr | null {
const shape = callbackPromisifyShape(lowerer, call, loc);
if (shape === null) return null;
const argNode = call.arguments.nodes[0]!;
let fn = lowerer.lowerExpr(argNode);
if (!typeEquals(fn.type, shape.fnT)) fn = lowerer.coerceToExpected(fn, shape.fnT);
if (!typeEquals(fn.type, shape.fnT)) return null;
return {
kind: "call",
callee: promisifyMaker(lowerer, shape, loc),
args: [fn],
type: shape.resultT,
loc,
};
}
/** Interns the helper family for one (function, result) type pair and
* answers the maker: `(fn) => closure(...args) => Promise<T>`. */
function promisifyMaker(lowerer: Lowerer, shape: CallbackShape, loc: SrcLoc): string {
const key = `promisify:${typeKey(shape.fnT)}=>${typeKey(shape.resultT)}`;
const existing = lowerer.arrHofHelpers.get(key);
if (existing) return existing;
const base = `%promisify.${lowerer.arrHofHelpers.size}`;
lowerer.arrHofHelpers.set(key, base);
const { fnT, resultT, args, callbackT, callbackParamT, inner, error } = shape;
const promiseT = resultT.ret;
const resolveT = funcOf(inner.kind === "void" ? [] : [inner], VOID);
const rejectT = funcOf([ERROR_T], VOID);
const executorT = funcOf([resolveT, rejectT], VOID);
const argIds = args.map((_, i) => `a${i}.0`);
// The callback: (err, value) => err ? reject(err) : resolve(value).
const cbParams: IrParam[] = [];
callbackT.params.forEach((type, i) =>
cbParams.push(captureParam(i === 0 ? "err.0" : "value.0", type)),
);
const cbBody: IrStmt[] = [];
if (error !== null) {
const err = varRef("err.0", error.type, loc);
let truthy: IrExpr | null = null;
for (const tag of error.unitTags) {
const part: IrExpr = {
kind: "unionIsTag",
unionId: (error.type as IrType & { kind: "union" }).unionId,
tag,
negated: true,
value: err,
type: BOOL,
loc,
};
truthy =
truthy === null
? part
: { kind: "logical", op: "&&", left: truthy, right: part, type: BOOL, loc };
}
const errorArm = lowerer.unions.get((error.type as IrType & { kind: "union" }).unionId)!.arms[
error.errorTag
]!;
let reason: IrExpr = {
kind: "unionNarrow",
unionId: (error.type as IrType & { kind: "union" }).unionId,
tag: error.errorTag,
value: err,
type: errorArm,
loc,
};
if (!typeEquals(errorArm, ERROR_T))
reason = { kind: "upcast", value: reason, type: ERROR_T, loc };
const reject: IrStmt[] = [
{
kind: "exprStmt",
expr: {
kind: "callValue",
callee: varRef("rej.0", rejectT, loc),
args: [reason],
type: VOID,
loc,
},
loc,
},
{ kind: "return", value: null, loc },
];
cbBody.push(
truthy === null ? reject[0]! : { kind: "if", cond: truthy, then: reject, else_: null, loc },
);
if (truthy === null) cbBody.push(reject[1]!);
}
const value =
inner.kind === "void"
? []
: [lowerer.coerceToExpected(varRef("value.0", callbackT.params[1]!, loc), inner)];
cbBody.push({
kind: "exprStmt",
expr: {
kind: "callValue",
callee: varRef("res.0", resolveT, loc),
args: value,
type: VOID,
loc,
},
loc,
});
lowerer.liftedFns.push({
name: `${base}.cb`,
params: cbParams,
returnType: VOID,
captures: [captureParam("res.0", resolveT), captureParam("rej.0", rejectT)],
locals: [
boxedLocal("res.0", resolveT),
boxedLocal("rej.0", rejectT),
...cbParams.map((p) => plainLocal(p.localId, p.type)),
],
body: cbBody,
loc,
});
lowerer.liftedFns.push({
name: `${base}.mkcb`,
params: [captureParam("res.0", resolveT), captureParam("rej.0", rejectT)],
returnType: callbackT,
locals: [boxedLocal("res.0", resolveT), boxedLocal("rej.0", rejectT)],
body: [
{
kind: "return",
value: {
kind: "closure",
fnName: `${base}.cb`,
captures: ["res.0", "rej.0"],
type: callbackT,
loc,
},
loc,
},
],
loc,
});
// The executor: (resolve, reject) => fn(...args, callback).
const captured: IrParam[] = [captureParam("f.0", fnT)];
args.forEach((type, i) => captured.push(captureParam(argIds[i]!, type)));
lowerer.liftedFns.push({
name: `${base}.exec`,
params: [captureParam("res.0", resolveT), captureParam("rej.0", rejectT)],
returnType: VOID,
captures: captured,
locals: [
...captured.map((p) => boxedLocal(p.localId, p.type)),
plainLocal("res.0", resolveT),
plainLocal("rej.0", rejectT),
],
body: [
{
kind: "exprStmt",
expr: {
kind: "callValue",
callee: varRef("f.0", fnT, loc),
args: [
...args.map((type, i) => varRef(argIds[i]!, type, loc)),
lowerer.coerceToExpected(
{
kind: "call",
callee: `${base}.mkcb`,
args: [varRef("res.0", resolveT, loc), varRef("rej.0", rejectT, loc)],
type: callbackT,
loc,
},
callbackParamT,
),
],
// The function's own return type; the value is discarded.
type: fnT.ret,
loc,
},
loc,
},
],
loc,
});
lowerer.liftedFns.push({
name: `${base}.mkexec`,
params: captured,
returnType: executorT,
locals: captured.map((p) => boxedLocal(p.localId, p.type)),
body: [
{
kind: "return",
value: {
kind: "closure",
fnName: `${base}.exec`,
captures: captured.map((p) => p.localId),
type: executorT,
loc,
},
loc,
},
],
loc,
});
// The promisified function: (...args) => new Promise(executor).
const implParams: IrParam[] = [];
args.forEach((type, i) => implParams.push(captureParam(argIds[i]!, type)));
lowerer.liftedFns.push({
name: `${base}.impl`,
params: implParams,
returnType: promiseT,
captures: [captureParam("f.0", fnT)],
locals: [boxedLocal("f.0", fnT), ...implParams.map((p) => plainLocal(p.localId, p.type))],
body: [
{
kind: "return",
value: {
kind: "newPromise",
executor: {
kind: "call",
callee: `${base}.mkexec`,
args: [
varRef("f.0", fnT, loc),
...implParams.map((p) => varRef(p.localId, p.type, loc)),
],
type: executorT,
loc,
},
type: promiseT,
loc,
},
loc,
},
],
loc,
});
lowerer.liftedFns.push({
name: base,
params: [captureParam("f.0", fnT)],
returnType: resultT,
locals: [boxedLocal("f.0", fnT)],
body: [
{
kind: "return",
value: { kind: "closure", fnName: `${base}.impl`, captures: ["f.0"], type: resultT, loc },
loc,
},
],
loc,
});
return base;
}
@@ -27,6 +27,7 @@ import { isStreamUndefCallExpr } from "./lower-server.js";
import { nsPathPrefix } from "./lower-namespaces.js";
import { declSymbolOf } from "./lower-modules.js";
import { npmStaticPackageOfPath } from "../npm-static.js";
import { restPackingAdapterFits } from "./coercions/function-adapters.js";
import { implicitMonoFile, implicitAnyParamSymbolsOf } from "./generic-functions.js";
/** How a parameter participates in CALL-SITE COMPLETION (the frontend
@@ -525,6 +526,21 @@ export function requireExactArityValue(
// optional/defaulted params spell their `T | undefined` slots (mapType's
// completed-signature contract), so omitted trailing args complete with
// the undefined arm like any direct call.
// A nested function declaration whose only non-required parameter is a
// typed rest: its value carries the typed-rest ABI its own type spells,
// and every use converts it at its slot (same signature, or the rest
// packing adapter for fixed parameters).
if (
contextual === null &&
ts.isFunctionDeclaration(blame) &&
blame.name !== undefined &&
funcType.kind === "func" &&
funcType.restAbi === "typed" &&
shapes.every((s) => s.mode === "required" || s.mode === "rest")
) {
const own = lowerer.mapTypeOf(lowerer.typeOf(blame.name));
if (own && typeEquals(own, funcType)) return;
}
const target = contextual ? lowerer.checker.getContextualType(contextual) : undefined;
const mapped = target
? lowerer.mapTypeOf(target)
@@ -585,6 +601,16 @@ export function requireExactArityValue(
) {
return;
}
// A typed-rest function in a slot with fixed parameters (`log(...m:
// string[])` into `(m: string) => void`): the slot coercion's packing
// adapter collects the slot's arguments into the rest array.
if (
mappedFn?.kind === "func" &&
funcType.kind === "func" &&
restPackingAdapterFits(lowerer, funcType, mappedFn)
) {
return;
}
// An uncontextualized npm-static implementation function can still
// have a declaration-backed completed ABI: the package's .d.ts
// projection supplies the body-facing parameter/return types while
@@ -11,7 +11,7 @@ const COMBINATOR_LIB_CALLS = {
/** `value.then` through the program's own property dispatch, so a class
* instance's `then` method is visible to the runtime's thenable check. */
function thenReader(lowerer: Lowerer, loc: SrcLoc): IrExpr {
export function thenReader(lowerer: Lowerer, loc: SrcLoc): IrExpr {
const name = "%promise.thenOf";
const type = funcOf([DYN], DYN);
if (!lowerer.liftedFns.some((fn) => fn.name === name)) {
@@ -0,0 +1,440 @@
import * as ts from "../ts7/adapter.js";
import {
BOOL,
CLASS_ATTRIBUTES,
CLASS_FROZEN,
CLASS_NOT_EXTENSIBLE,
CLASS_SEALED,
DYN,
F64,
FIELD_NOT_WRITABLE,
STRING,
VOID,
canConvertToDyn,
canDynCheckTo,
classFieldAttributesName,
isClassOwnEnumerableFieldName,
isDynTypedRefType,
type IrExpr,
type IrFunction,
type IrStmt,
type IrType,
type SrcLoc,
} from "../../ir/ir.js";
import { numLit, strLit, varRef } from "../../ir/build.js";
import { transformStmtList } from "../../ir/traverse.js";
import { locOf } from "../program.js";
import { type Lowerer, PoisonError } from "./lowerer.js";
import type { ClassInfo } from "./lower-classes.js";
import { classPropertiesHelper } from "./class-dynamic-dispatch.js";
import { runtimeRooted } from "./class-descriptors.js";
/* Object.freeze, Object.seal, Object.preventExtensions and
* Object.defineProperty on class instances. Only the hierarchies these calls
* name pay for them: such a hierarchy gets a CLASS_ATTRIBUTES integrity word
* per instance, an attribute word per redefined field, and a check before
* each write to a declared field (guardClassAttributeWrites). The instance's
* checked view carries the attributes, so reflection answers from it. */
type ClassObjectType = Extract<IrType, { kind: "object" }>;
function attributeClass(lowerer: Lowerer, target: IrExpr): ClassInfo | null {
if (!isDynTypedRefType(target.type)) return null;
const info = lowerer.classes.get(target.type.className);
if (!info || runtimeRooted(info) || info.decl == null) return null;
return info;
}
/** Adds a zero-initialized f64 to every class of the hierarchy, at the same
* offset, like the property bag. */
function addHiddenField(info: ClassInfo, name: string): void {
let root = info;
while (root.base && !root.base.def.runtime) root = root.base;
if (root.fields.has(name)) return;
const index = root.def.fields.length;
const add = (current: ClassInfo): void => {
if (!current.fields.has(name)) {
current.fields.set(name, F64);
current.def.fields.splice(index, 0, { name, type: F64 });
}
current.subclasses.forEach(add);
};
add(root);
}
function hiddenFieldGet(receiver: IrExpr, className: string, field: string, loc: SrcLoc): IrExpr {
return { kind: "fieldGet", obj: receiver, className, field, type: F64, loc };
}
/** Object.freeze, Object.seal and Object.preventExtensions of a class
* instance: sets the instance's integrity bits, then applies the operation to
* the properties added to the instance. Answers the instance. */
export function lowerClassIntegrity(
lowerer: Lowerer,
call: ts.CallExpression,
member: "freeze" | "seal" | "preventExtensions",
target: IrExpr,
): IrExpr | null {
const info = attributeClass(lowerer, target);
if (!info) return null;
addHiddenField(info, CLASS_ATTRIBUTES);
const loc = locOf(call);
const type = target.type as ClassObjectType;
const bits =
member === "freeze"
? CLASS_NOT_EXTENSIBLE | CLASS_SEALED | CLASS_FROZEN
: member === "seal"
? CLASS_NOT_EXTENSIBLE | CLASS_SEALED
: CLASS_NOT_EXTENSIBLE;
const slot = lowerer.declareHiddenLocal("%integrityReceiver", type);
const receiver = (): IrExpr => varRef(slot.id, type, loc);
const bag: IrExpr = {
kind: "call",
callee: classPropertiesHelper(lowerer, loc).name,
args: [lowerer.coerceToExpected(receiver(), DYN)],
type: DYN,
loc,
};
const operation = {
freeze: "dyn.freeze",
seal: "dyn.seal",
preventExtensions: "dyn.preventExtensions",
} as const;
return {
kind: "seqExpr",
stmts: [
{ kind: "varDecl", localId: slot.id, init: target, loc },
{
kind: "fieldSet",
obj: receiver(),
className: type.className,
field: CLASS_ATTRIBUTES,
value: {
kind: "bin",
op: "|",
left: hiddenFieldGet(receiver(), type.className, CLASS_ATTRIBUTES, loc),
right: numLit(bits, loc),
type: F64,
loc,
},
attributesChecked: true,
loc,
},
{
kind: "exprStmt",
expr: { kind: "libCall", fn: operation[member], args: [bag], type: DYN, loc },
loc,
},
],
result: receiver(),
type,
loc,
};
}
/** An object literal with a get or set property. */
function literalAccessorDescriptor(node: ts.Expression): boolean {
while (ts.isParenthesizedExpression(node)) node = node.expression;
return (
ts.isObjectLiteralExpression(node) &&
node.properties.nodes.some(
(property) =>
property.name !== undefined &&
(ts.isIdentifier(property.name) || ts.isStringLiteral(property.name)) &&
(property.name.text === "get" || property.name.text === "set"),
)
);
}
/** Object.defineProperty with a string-literal key naming a declared field
* of a class instance: a data descriptor changes the field's value and
* attributes, validated as Node validates ordinary objects. Answers the
* instance, or null when the call is not of that form. An object-literal
* accessor descriptor is refused at compile time; other accessor
* descriptors throw SC2020 when the call runs. */
export function lowerClassFieldDefine(
lowerer: Lowerer,
call: ts.CallExpression,
target: IrExpr,
): IrExpr | null {
const info = attributeClass(lowerer, target);
const key = call.arguments.nodes[1]!;
if (!info || !ts.isStringLiteral(key)) return null;
const field = key.text;
const fieldType = info.fields.get(field);
if (
fieldType === undefined ||
!isClassOwnEnumerableFieldName(field) ||
[...(info.symbolFields?.values() ?? [])].includes(field)
)
return null;
if (literalAccessorDescriptor(call.arguments.nodes[2]!)) {
lowerer.pushDiag({
code: "SC2020",
message: `Object.defineProperty with an accessor descriptor for the declared field '${field}' is not supported yet`,
loc: locOf(call),
});
throw new PoisonError();
}
const getRecord = (id: string) => lowerer.shapes.get(id);
const getUnion = (id: string) => lowerer.unions.get(id);
if (
!canConvertToDyn(fieldType, getRecord, getUnion) ||
!canDynCheckTo(fieldType, getRecord, getUnion)
)
return null;
const attributesField = classFieldAttributesName(field);
addHiddenField(info, CLASS_ATTRIBUTES);
addHiddenField(info, attributesField);
const loc = locOf(call);
const type = target.type as ClassObjectType;
const receiverSlot = lowerer.declareHiddenLocal("%defineReceiver", type);
const descriptorSlot = lowerer.declareHiddenLocal("%defineDescriptor", DYN);
const holderSlot = lowerer.declareHiddenLocal("%defineHolder", DYN);
const receiver = (): IrExpr => varRef(receiverSlot.id, type, loc);
const descriptor = (): IrExpr => varRef(descriptorSlot.id, DYN, loc);
const holder = (): IrExpr => varRef(holderSlot.id, DYN, loc);
const name = (): IrExpr => strLit(field, loc);
const current: IrExpr = {
kind: "fieldGet",
obj: receiver(),
className: type.className,
field,
type: fieldType,
loc,
};
const defined: IrExpr = {
kind: "libCall",
fn: "class.definedValue",
args: [holder(), name()],
type: DYN,
loc,
};
return {
kind: "seqExpr",
stmts: [
{ kind: "varDecl", localId: receiverSlot.id, init: target, loc },
{
kind: "varDecl",
localId: descriptorSlot.id,
init: lowerer.lowerExprExpecting(call.arguments.nodes[2]!, DYN),
loc,
},
{
kind: "varDecl",
localId: holderSlot.id,
init: {
kind: "libCall",
fn: "class.defineField",
args: [
lowerer.coerceToExpected(current, DYN),
hiddenFieldGet(receiver(), type.className, attributesField, loc),
hiddenFieldGet(receiver(), type.className, CLASS_ATTRIBUTES, loc),
name(),
descriptor(),
],
type: DYN,
loc,
},
loc,
},
{
kind: "if",
cond: {
kind: "libCall",
fn: "class.descriptorHasValue",
args: [descriptor()],
type: BOOL,
loc,
},
then: [
{
kind: "fieldSet",
obj: receiver(),
className: type.className,
field,
value: lowerer.coerceToExpected(defined, fieldType),
attributesChecked: true,
loc,
},
],
else_: null,
loc,
},
{
kind: "fieldSet",
obj: receiver(),
className: type.className,
field: attributesField,
value: {
kind: "libCall",
fn: "class.definedBits",
args: [holder(), name()],
type: F64,
loc,
},
attributesChecked: true,
loc,
},
],
result: receiver(),
type,
loc,
};
}
function classDisplayName(info: ClassInfo): string {
return info.def.jsName ?? info.decl?.name?.text ?? info.def.name.replace(/^%/, "");
}
/** The instance's own class name for an error message: a helper testing the
* most derived classes of the hierarchy first. */
function instanceClassName(
lowerer: Lowerer,
info: ClassInfo,
receiver: IrExpr,
helpers: Map<string, IrFunction>,
loc: SrcLoc,
): IrExpr {
if (info.subclasses.length === 0) return strLit(classDisplayName(info), loc);
let helper = helpers.get(info.def.name);
if (!helper) {
const type: IrType = { kind: "object", className: info.def.name };
const value = varRef("value", type, loc);
const descendants = (current: ClassInfo): ClassInfo[] =>
current.subclasses.flatMap((child) => [...descendants(child), child]);
const body: IrStmt[] = descendants(info).map((child): IrStmt => ({
kind: "if",
cond: { kind: "instanceOf", value, className: child.def.name, type: BOOL, loc },
then: [{ kind: "return", value: strLit(classDisplayName(child), loc), loc }],
else_: null,
loc,
}));
body.push({ kind: "return", value: strLit(classDisplayName(info), loc), loc });
helper = {
name: `%class.instanceName.${helpers.size}`,
params: [{ localId: "value", name: "value", type }],
returnType: STRING,
locals: [{ id: "value", name: "value", type, mutable: false }],
body,
loc,
};
helpers.set(info.def.name, helper);
}
return { kind: "call", callee: helper.name, args: [receiver], type: STRING, loc };
}
/** Checks the integrity word, and the field's attribute word when it has one,
* before every write to a declared field of a hierarchy that has them. A
* read-only field throws Node's TypeError in strict mode code; a sloppy-mode
* write leaves it unchanged. Other classes keep their plain stores. */
export function guardClassAttributeWrites(lowerer: Lowerer, functions: IrFunction[]): void {
const guarded = new Set(
[...lowerer.classes.values()]
.filter((info) => info.def.fields.some((field) => field.name === CLASS_ATTRIBUTES))
.map((info) => info.def.name),
);
if (guarded.size === 0) return;
const helpers = new Map<string, IrFunction>();
for (const fn of functions) {
const local = (type: IrType, loc: SrcLoc): Extract<IrExpr, { kind: "varRef" }> => {
const id = `%attributeWrite.${fn.locals.length}`;
fn.locals.push({ id, name: id, type, mutable: false });
return { kind: "varRef", localId: id, type, loc };
};
fn.body = transformStmtList(fn.body, {
stmt: (statement) => {
if (
statement.kind !== "fieldSet" ||
statement.attributesChecked ||
!guarded.has(statement.className) ||
!isClassOwnEnumerableFieldName(statement.field)
)
return statement;
const info = lowerer.classes.get(statement.className)!;
const loc = statement.loc;
const receiver = local(statement.obj.type, loc);
const value = local(statement.value.type, loc);
const masked = (field: string, bit: number): IrExpr => ({
kind: "bin",
op: "&",
left: hiddenFieldGet(receiver, statement.className, field, loc),
right: numLit(bit, loc),
type: F64,
loc,
});
const attributesField = classFieldAttributesName(statement.field);
let readOnly = masked(
CLASS_ATTRIBUTES,
statement.define ? CLASS_NOT_EXTENSIBLE : CLASS_FROZEN,
);
if (!statement.define && info.fields.has(attributesField)) {
readOnly = {
kind: "bin",
op: "|",
left: readOnly,
right: masked(attributesField, FIELD_NOT_WRITABLE),
type: F64,
loc,
};
}
const reject: IrStmt[] = statement.define
? [
{
kind: "exprStmt",
expr: {
kind: "libCall",
fn: "class.throwNotExtensible",
args: [strLit(statement.field, loc)],
type: VOID,
loc,
},
loc,
},
]
: statement.sloppy
? []
: [
{
kind: "exprStmt",
expr: {
kind: "libCall",
fn: "class.throwReadOnly",
args: [
strLit(statement.field, loc),
instanceClassName(lowerer, info, receiver, helpers, loc),
],
type: VOID,
loc,
},
loc,
},
];
return {
kind: "block",
body: [
{ kind: "varDecl", localId: receiver.localId, init: statement.obj, loc },
{ kind: "varDecl", localId: value.localId, init: statement.value, loc },
{
kind: "if",
cond: {
kind: "bin",
op: "!==",
left: readOnly,
right: numLit(0, loc),
type: BOOL,
loc,
},
then: reject,
else_: [{ ...statement, obj: receiver, value, attributesChecked: true }],
loc,
},
],
loc,
};
},
expr: (expression) => expression,
});
}
for (const helper of helpers.values()) functions.push(helper);
}
@@ -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: {
@@ -23,7 +23,7 @@ function bagOnlyProperty(owner: ClassInfo, name: string): boolean {
return !owner.fields.has(name) && owner.subclasses.every((child) => bagOnlyProperty(child, name));
}
function runtimeRooted(info: ClassInfo): boolean {
export function runtimeRooted(info: ClassInfo): boolean {
for (let current: ClassInfo | null = info; current; current = current.base) {
if (
current.def.runtime ||
@@ -1,3 +1,4 @@
import { primitiveConstructorOr } from "./lower-exprs.js";
import { dynUndefinedExpr, helperLoc, nodeThrowExpr, varRef } from "../../ir/build.js";
import { constructedValue } from "./constructor-returns.js";
import { eventTargetApiMembers, eventTargetInheritedMember } from "./lower-event-target.js";
@@ -2070,6 +2071,49 @@ export class ClassDynamicDispatch {
// A read compares the bag with the receiver and then reads it:
// evaluate it once, so each read retains the receiver once.
const bagRead = varRef("bag.0", DYN, loc);
const bagGet: IrExpr | null = read
? {
kind: "libCall",
fn: "dyn.bagGet",
args: [bagRead, read.key, varRef("p.0", DYN, loc)],
type: DYN,
loc,
}
: null;
// A class instance whose class chain declares no member of an
// Object.prototype method's name (classes that do answer in
// their own branches) inherits it unless an own property
// shadows it; a class constructor's static bag reads as before.
const instanceRead: IrExpr | null =
read && INHERITED_OBJECT_METHODS.has(name)
? {
kind: "ternary",
cond: {
kind: "dynTest",
test: "function",
value: varRef("p.0", DYN, loc),
type: BOOL,
loc,
},
then: bagGet!,
else_: {
kind: "ternary",
cond: this.readBagHas(lowerer, "dyn.hasKey", bagRead, read.key, loc),
then: bagGet!,
else_: {
kind: "libCall",
fn: "dyn.builtinMethod",
args: [{ kind: "strLit", value: "Object", type: STRING, loc }, read.key],
type: DYN,
loc,
},
type: DYN,
loc,
},
type: DYN,
loc,
}
: bagGet;
const fallback: IrExpr = read
? {
kind: "ternary",
@@ -2081,13 +2125,7 @@ export class ClassDynamicDispatch {
loc,
},
then: { ...read, value: bagRead },
else_: {
kind: "libCall",
fn: "dyn.bagGet",
args: [bagRead, read.key, varRef("p.0", DYN, loc)],
type: DYN,
loc,
},
else_: instanceRead!,
type: DYN,
loc,
}
@@ -2112,7 +2150,20 @@ export class ClassDynamicDispatch {
]
: [
{ kind: "varDecl", localId: "bag.0", init: bag, loc },
{ kind: "return", value: fallback, loc },
{
kind: "return",
// Primitives answer their wrapper constructors.
value:
name === "constructor"
? primitiveConstructorOr(
lowerer,
varRef("p.0", DYN, loc),
fallback,
loc,
)
: fallback,
loc,
},
],
loc,
};
@@ -2695,6 +2746,7 @@ export class ClassDynamicDispatch {
!findGenericMethodOn(lowerer, info, dispatch.name) &&
dispatch.name !== "constructor" &&
!info.fields.has(dispatch.name) &&
!(dispatch.name === "stack" && lowerer.isSubclassOf(info.def.name, "%Error")) &&
!findMethodOn(lowerer, info, `get:${dispatch.name}`) &&
!findMethodOn(lowerer, info, `set:${dispatch.name}`))
)
@@ -4525,6 +4577,110 @@ export class ClassDynamicDispatch {
},
];
}
// An Error's own `stack`: a string is the native error's stack, which
// typed reads share; any other value is kept with the instance's own
// properties, which a read checks first. A class whose chain declares
// a `stack` accessor answers through it (the accessor code below).
if (
name === "stack" &&
!info.fields.has(name) &&
lowerer.isSubclassOf(info.def.name, "%Error") &&
!findMethodOn(lowerer, info, "get:stack") &&
!findMethodOn(lowerer, info, "set:stack")
) {
const key: IrExpr = { kind: "strLit", value: name, type: STRING, loc };
const error = lowerer.upcastTo(receiver, "%Error");
if (write) {
const helper = classPropertiesHelper(lowerer, loc);
this.generated.add(helper);
const store: IrStmt = {
kind: "exprStmt",
expr: {
kind: "libCall",
fn: "dyn.keySet",
args: [
{
kind: "call",
callee: helper.name,
args: [lowerer.coerceToExpected(receiver, DYN)],
type: DYN,
loc,
},
key,
varRef("p.1", DYN, loc),
],
type: VOID,
loc,
},
loc,
};
return [
{
kind: "if",
cond: {
kind: "dynTest",
test: "string",
value: varRef("p.1", DYN, loc),
type: BOOL,
loc,
},
then: [
{
kind: "exprStmt",
expr: {
kind: "libCall",
fn: "error.setStack",
args: [error, lowerer.coerceToExpected(varRef("p.1", DYN, loc), STRING)],
type: VOID,
loc,
},
loc,
},
{
kind: "if",
cond: this.readBagHas(
lowerer,
"dyn.hasKey",
this.readPropertyBag(lowerer, receiver, loc),
key,
loc,
),
then: [store],
else_: null,
loc,
},
],
else_: [store],
loc,
},
{ kind: "return", value: null, loc },
];
}
const bag = this.readPropertyBag(lowerer, receiver, loc);
return [
{
kind: "return",
value: {
kind: "ternary",
cond: this.readBagHas(lowerer, "dyn.hasKey", bag, key, loc),
then: {
kind: "libCall",
fn: "dyn.bagGet",
args: [bag, key, lowerer.coerceToExpected(receiver, DYN)],
type: DYN,
loc,
},
else_: lowerer.coerceToExpected(
{ kind: "libCall", fn: "error.stack", args: [error], type: STRING, loc },
DYN,
),
type: DYN,
loc,
},
loc,
},
];
}
if ((name === "message" || name === "name") && lowerer.isSubclassOf(info.def.name, "%Error"))
return write
? [
@@ -4715,19 +4871,40 @@ export class ClassDynamicDispatch {
if (!field && !accessor) {
const instance = lowerer.coerceToExpected(receiver, DYN);
const bag = this.readPropertyBagOrEmpty(lowerer, instance, loc);
return [
{
kind: "return",
value: {
kind: "libCall",
fn: "dyn.bagGet",
args: [bag, { kind: "strLit", value: name, type: STRING, loc }, instance],
type: DYN,
const key: IrExpr = { kind: "strLit", value: name, type: STRING, loc };
const own: IrExpr = {
kind: "libCall",
fn: "dyn.bagGet",
args: [bag, key, instance],
type: DYN,
loc,
};
// An Object.prototype method no class in the chain declares: an
// own property shadows it, otherwise the read answers the same
// interned value `Object.prototype.<name>` reads.
if (INHERITED_OBJECT_METHODS.has(name) && !findMethodOn(lowerer, info, name)) {
return [
{
kind: "return",
value: {
kind: "ternary",
cond: this.readBagHas(lowerer, "dyn.hasKey", bag, key, loc),
then: own,
else_: {
kind: "libCall",
fn: "dyn.builtinMethod",
args: [{ kind: "strLit", value: "Object", type: STRING, loc }, key],
type: DYN,
loc,
},
type: DYN,
loc,
},
loc,
},
loc,
},
];
];
}
return [{ kind: "return", value: own, loc }];
}
const type = field ?? accessor!.sig.ret;
if (!canConvertToDyn(type, getRecord, getUnion)) return fence();
@@ -5250,3 +5427,12 @@ export class ClassDynamicDispatch {
return body;
}
}
/** Object.prototype methods every class instance inherits unless its class
* chain declares them. */
const INHERITED_OBJECT_METHODS: ReadonlySet<string> = new Set([
"valueOf",
"toString",
"hasOwnProperty",
"propertyIsEnumerable",
]);
@@ -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);
@@ -111,12 +111,15 @@ export function coercibleValue(lowerer: Lowerer, src: IrType, dst: IrType): bool
}
/** Whether all parameters and the result adapt without a trap-only path.
* Rest signatures are excluded; extra destination parameters are ignored. */
* Rest signatures are excluded, except a typed-rest source in a slot with
* fixed parameters (the rest packing adapter); extra destination
* parameters are ignored. */
export function cleanFuncAdaptable(
lowerer: Lowerer,
src: IrType & { kind: "func" },
dst: IrType & { kind: "func" },
): boolean {
if (restPackingAdapterFits(lowerer, src, dst)) return true;
if (src.rest === true || dst.rest === true) return false;
if (src.params.length > dst.params.length) return false;
for (let i = 0; i < src.params.length; i++) {
@@ -127,15 +130,145 @@ export function cleanFuncAdaptable(
return src.ret.kind === "void" && dst.ret.kind === "dyn";
}
/** Whether a typed-rest function (`(...m: T[]) => R`) can serve a slot
* with fixed parameters (`(m: T) => void`): the slot's parameters convert
* to the function's fixed parameters, then to the rest element type. */
export function restPackingAdapterFits(
lowerer: Lowerer,
fromT: IrType & { kind: "func" },
toT: IrType & { kind: "func" },
): boolean {
if (fromT.rest !== true || fromT.restAbi !== "typed" || toT.rest === true) return false;
const fixed = fromT.params.length - 1;
const restT = fromT.params[fixed];
if (restT?.kind !== "array" || toT.params.length < fixed) return false;
for (let i = 0; i < toT.params.length; i++) {
if (!lowerer.coercibleValue(toT.params[i]!, i < fixed ? fromT.params[i]! : restT.elem))
return false;
}
return toT.ret.kind === "void" || lowerer.coercibleValue(fromT.ret, toT.ret);
}
/** The adapter for restPackingAdapterFits: forwards the fixed arguments and
* packs the remaining ones into the rest array, as a JavaScript call of the
* function with those arguments does. */
function restPackingAdapter(
lowerer: Lowerer,
fromT: IrType & { kind: "func" },
toT: IrType & { kind: "func" },
loc: SrcLoc,
): string {
const key = `fnrestadapt:${typeKey(fromT)}:${typeKey(toT)}`;
const existing = lowerer.coercions.retags.get(key);
if (existing) return existing;
const name = `%fn.adapt.${lowerer.coercions.retags.size}`;
lowerer.coercions.retags.set(key, name);
lowerer.freshClosureAdapters.add(name);
const fixed = fromT.params.length - 1;
const restT = fromT.params[fixed] as IrType & { kind: "array" };
const params: IrParam[] = toT.params.map((t, i) => ({
localId: `a.${i}`,
name: `a${i}`,
type: t,
}));
const arg = (i: number, want: IrType): IrExpr =>
lowerer.coerceToExpected(
{ kind: "varRef", localId: `a.${i}`, type: toT.params[i]!, loc },
want,
);
const args: IrExpr[] = [];
for (let i = 0; i < fixed; i++) args.push(arg(i, fromT.params[i]!));
const packed: IrExpr[] = [];
for (let i = fixed; i < toT.params.length; i++) packed.push(arg(i, restT.elem));
args.push({ kind: "arrayLit", elems: packed, type: restT, loc });
const call: IrExpr = {
kind: "callValue",
callee: { kind: "varRef", localId: "f.0", type: fromT, loc },
receiver: { kind: "libCall", fn: "dyn.this", args: [], type: DYN, loc },
args,
type: fromT.ret,
loc,
};
const body: IrStmt[] =
toT.ret.kind === "void"
? [
{ kind: "exprStmt", expr: call, loc },
{ kind: "return", value: null, loc },
]
: [{ kind: "return", value: lowerer.coerceToExpected(call, toT.ret), loc }];
lowerer.liftedFns.push(...buildFunctionAdapter(name, fromT, toT, params, [], body, loc));
return name;
}
/** Adapt a fixed-parameter function to a checked-dynamic rest signature
* without fixed parameters (`() => {}` into mock.fn()'s `(...args: any[])
* => undefined`): the adapter receives the hidden argument array and
* passes its element i as parameter i, undefined when the caller passed
* fewer arguments, as JS does. Null unless every parameter is
* checked-dynamic, which holds a missing argument as undefined, and the
* result is discarded or converts. */
function funcIntoDynRestAdapter(
lowerer: Lowerer,
fromT: IrType & { kind: "func" },
toT: IrType & { kind: "func" },
loc: SrcLoc,
): string | null {
if (fromT.rest === true || fromT.params.some((p) => p.kind !== "dyn")) return null;
if (toT.ret.kind !== "void" && !lowerer.coercibleValue(fromT.ret, toT.ret)) return null;
const key = `fnadapt:${typeKey(fromT)}:${typeKey(toT)}`;
const existing = lowerer.coercions.retags.get(key);
if (existing) return existing;
const name = `%fn.adapt.${lowerer.coercions.retags.size}`;
lowerer.coercions.retags.set(key, name);
lowerer.freshClosureAdapters.add(name);
const params: IrParam[] = [{ localId: "rest.0", name: "args", type: DYN }];
const call: IrExpr = {
kind: "callValue",
callee: { kind: "varRef", localId: "f.0", type: fromT, loc },
receiver: { kind: "libCall", fn: "dyn.this", args: [], type: DYN, loc },
args: fromT.params.map((_, i): IrExpr => ({
kind: "dynKeyGet",
value: { kind: "varRef", localId: "rest.0", type: DYN, loc },
key: { kind: "strLit", value: String(i), type: STRING, loc },
type: DYN,
loc,
})),
type: fromT.ret,
loc,
};
let body: IrStmt[];
if (toT.ret.kind === "void") {
body = [
{ kind: "exprStmt", expr: call, loc },
{ kind: "return", value: null, loc },
];
} else {
const result = lowerer.coerceToExpected(call, toT.ret);
if (!typeEquals(result.type, toT.ret))
throw new InternalCompilerError("lowerer bug: probed fn-adapter return stopped coercing");
body = [{ kind: "return", value: result, loc }];
}
lowerer.liftedFns.push(...buildFunctionAdapter(name, fromT, toT, params, [], body, loc));
return name;
}
/** Adapt a function value to a destination signature, forwarding and
* converting its arguments and result. Unsupported parameter/result pairs
* produce checked traps when called; rest signatures remain refused. */
* produce checked traps when called. Rest signatures are refused, except a
* typed-rest source in a slot with fixed parameters, which the rest
* packing adapter serves, and a fixed-parameter function into a
* checked-dynamic rest signature without fixed parameters
* (funcIntoDynRestAdapter). */
export function funcCoerceAdapter(
lowerer: Lowerer,
fromT: IrType & { kind: "func" },
toT: IrType & { kind: "func" },
loc: SrcLoc,
): string | null {
if (restPackingAdapterFits(lowerer, fromT, toT))
return restPackingAdapter(lowerer, fromT, toT, loc);
if (toT.rest === true && toT.restAbi === undefined && toT.params.length === 0)
return funcIntoDynRestAdapter(lowerer, fromT, toT, loc);
if (fromT.rest === true || toT.rest === true) return null;
if (fromT.params.length > toT.params.length) return null;
// Piece dispositions beyond coercibleValue, all CHECKER-APPROVED
@@ -23,7 +23,19 @@ export function widthLiftPlan(lowerer: Lowerer, src: IrType, dst: IrType): Width
}
if (dst.kind === "union") {
if (src.kind === "union") {
return lowerer.unionRetagMappable(src.unionId, dst.unionId) ? { how: "retag" } : null;
if (lowerer.unionRetagMappable(src.unionId, dst.unionId)) return { how: "retag" };
// A field the checker types `undefined` alone (an object literal's
// omitted member, normalized to `?: undefined` across a union of
// literal types) carries the unit-only union. Into a slot with an
// undefined arm it lifts as that arm; its null arm cannot occur.
const srcArms = lowerer.unions.get(src.unionId)?.arms ?? [];
if (
srcArms.length > 0 &&
srcArms.every(isUnitType) &&
lowerer.armTag(dst.unionId, UNDEFINED_T) >= 0
)
return { how: "unitRetag" };
return null;
}
// A unit-typed source can't wrap here (unionWrap requires the
// LITERAL unit — and no lowered shape carries a bare unit field).
@@ -125,6 +125,19 @@ export function applyWidthLift(
throw new InternalCompilerError("lowerer bug: planned retag lift failed to intern");
return { kind: "call", callee: retag, args: [value], type: dst, loc };
}
case "unitRetag": {
if (dst.kind !== "union" || value.type.kind !== "union")
throw new InternalCompilerError("lowerer bug: unit retag lift shape");
const fromId = value.type.unionId;
const trappable = new Set<number>();
(lowerer.unions.get(fromId)?.arms ?? []).forEach((arm, tag) => {
if (lowerer.armTag(dst.unionId, arm) < 0) trappable.add(tag);
});
const retag = lowerer.unionRetagHelper(fromId, dst.unionId, loc, trappable);
if (!retag)
throw new InternalCompilerError("lowerer bug: planned unit retag lift failed to intern");
return { kind: "call", callee: retag, args: [value], type: dst, loc };
}
case "liftWrap": {
if (dst.kind !== "union")
throw new InternalCompilerError("lowerer bug: liftWrap lift against a non-union");
@@ -44,6 +44,7 @@ import {
lowerArrayCallback,
requireProducedArrayElement,
callbackArrayElement,
truthyFilterCallback,
} from "./callback-arguments.js";
import {
reverseArrayLoop,
@@ -85,7 +86,9 @@ export function lowerArrayHofCall(
const valueT = callbackValueType(lowerer, elem, present);
if (booleanFilter) {
if (valueT.kind === "union") lowerer.requireTruthyUnion(valueT.unionId, argNode);
if (valueT.kind === "dyn" || valueT.kind === "void" || isUnitType(valueT)) {
// Checked-dynamic elements (`anyText.split("\n").map(...).filter(Boolean)`)
// keep their runtime kind, so their truthiness is the runtime's.
if (valueT.kind === "void" || isUnitType(valueT)) {
lowerer.badType(argNode, lowerer.typeOf(argNode));
}
}
@@ -231,33 +234,6 @@ function filterResultElem(
return outElem;
}
/** A native closure for the ambient Boolean callback. Reifying the
* JavaScript constructor itself is unnecessary; Array#filter only observes
* its one-argument ToBoolean result. */
function truthyFilterCallback(
lowerer: Lowerer,
valueT: IrType,
loc: SrcLoc,
): IrExpr & { type: IrType & { kind: "func" } } {
const fnT: IrType & { kind: "func" } = { kind: "func", params: [valueT], ret: BOOL };
const key = `filterBoolean:${typeKey(valueT)}`;
let name = lowerer.arrHofHelpers.get(key);
if (!name) {
name = `%arr.filterBoolean.${lowerer.arrHofHelpers.size}`;
lowerer.arrHofHelpers.set(key, name);
const value = varRef("v.0", valueT, loc);
lowerer.liftedFns.push({
name,
params: [{ localId: "v.0", name: "v", type: valueT }],
returnType: BOOL,
locals: [{ id: "v.0", name: "v", type: valueT, mutable: false }],
body: [{ kind: "return", value: { kind: "toBool", operand: value, type: BOOL, loc }, loc }],
loc,
});
}
return { kind: "closure", fnName: name, captures: [], type: fnT, loc };
}
function filterPredicateOk(lowerer: Lowerer, ret: IrType): boolean {
if (ret.kind === "bool") return true;
// VOID is a TYPE erasure, not a runtime value: TS lets a value-returning
@@ -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
@@ -265,6 +266,22 @@ function appendWidenedArrayValues(
}
/** The Array constructor's element and count forms, shared by calls and new. */
/** The value of `.fill(v)` when `expr` is that call's receiver. */
function fillArgumentOfReceiver(expr: ts.Expression): ts.Expression | null {
let receiver: ts.Node = expr;
let parent = expr.parent;
while (ts.isParenthesizedExpression(parent)) {
receiver = parent;
parent = parent.parent;
}
if (!ts.isPropertyAccessExpression(parent) || parent.expression !== receiver) return null;
if (parent.name.text !== "fill" || parent.questionDotToken) return null;
const call = parent.parent;
if (!ts.isCallExpression(call) || call.expression !== parent) return null;
const value = call.arguments.nodes[0];
return value !== undefined && !ts.isSpreadElement(value) ? value : null;
}
export function lowerArrayConstructor(
lowerer: Lowerer,
expr: ts.CallExpression | ts.NewExpression,
@@ -295,6 +312,15 @@ export function lowerArrayConstructor(
const contextual = lowerer.checker.getContextualType(expr);
if (contextual) result = lowerer.mapTypeOf(contextual);
}
// `Array(n).fill(v)`: the checker types the length-constructed array as
// any[], but fill gives every element v's type.
if (result?.kind !== "array") {
const fillValue = fillArgumentOfReceiver(expr);
const elem = fillValue
? lowerer.mapTypeOf(lowerer.checker.getBaseTypeOfLiteralType(lowerer.typeOf(fillValue)))
: null;
if (elem !== null && isSupportedArrayElem(elem)) result = arrayOf(elem);
}
if (isJsSourceFile(expr.getSourceFile()) && (result === null || result.kind === "dyn"))
result = arrayOf(DYN);
if (result?.kind !== "array" || !isSupportedArrayElem(result.elem)) {
@@ -913,7 +939,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 +1034,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));
@@ -1,12 +1,18 @@
import * as ts from "../../ts7/adapter.js";
import type { Lowerer } from "../lowerer.js";
import { isJsSourceFile, locOf } from "../../program.js";
import { varRef } from "../../../ir/build.js";
import { typeKey } from "../../type-mapper.js";
import {
BOOL,
F64,
type IrExpr,
type IrType,
type SrcLoc,
UNDEFINED_T,
funcOf,
isSupportedArrayElem,
isUnitType,
typeEquals,
} from "../../../ir/ir.js";
@@ -44,6 +50,24 @@ export function lowerArrayCallback(
bindUntyped = false,
expectedReturn?: IrType,
): { fnArg: IrExpr & { type: IrType & { kind: "func" } }; arity: number } {
// The ambient `Boolean` as the callback (`flags.every(Boolean)`,
// `xs.some(Boolean)`, `xs.map(Boolean)`): Boolean(value) answers the
// ToBoolean of its FIRST argument and ignores the rest, so the callback
// is the interned one-parameter truthiness closure over the lead slot.
// The constructor's own generic signature has no compiled value form.
// JavaScript files keep their primitive-constructor closure.
if (
ts.isIdentifier(argNode) &&
argNode.text === "Boolean" &&
!isJsSourceFile(argNode.getSourceFile()) &&
lowerer.isStdlibSymbol(lowerer.resolveValueSymbol(argNode) ?? undefined)
) {
const valueT = lead[0];
if (valueT === undefined || valueT.kind === "void" || isUnitType(valueT))
lowerer.badType(argNode, lowerer.typeOf(argNode));
if (valueT.kind === "union") lowerer.requireTruthyUnion(valueT.unionId, argNode);
return { fnArg: truthyFilterCallback(lowerer, valueT, locOf(argNode)), arity: 1 };
}
const full = [...lead, F64, arrT];
// A DYN-receiver HOF's callback (`parsed.flatMap((value) => ...)`):
// the contextual signature types the unannotated param `any` (the
@@ -248,3 +272,39 @@ function runtimeOptionalPairVariant(lowerer: Lowerer, expected: IrType, mapped:
: t;
return lowerer.isRuntimeOptionalRecordVariant(strip(expected), strip(mapped));
}
/** A native closure for the ambient Boolean callback. Reifying the
* JavaScript constructor itself is unnecessary; Array#filter only observes
* its one-argument ToBoolean result. */
export function truthyFilterCallback(
lowerer: Lowerer,
valueT: IrType,
loc: SrcLoc,
): IrExpr & { type: IrType & { kind: "func" } } {
const fnT: IrType & { kind: "func" } = { kind: "func", params: [valueT], ret: BOOL };
const key = `filterBoolean:${typeKey(valueT)}`;
let name = lowerer.arrHofHelpers.get(key);
if (!name) {
name = `%arr.filterBoolean.${lowerer.arrHofHelpers.size}`;
lowerer.arrHofHelpers.set(key, name);
const value = varRef("v.0", valueT, loc);
lowerer.liftedFns.push({
name,
params: [{ localId: "v.0", name: "v", type: valueT }],
returnType: BOOL,
locals: [{ id: "v.0", name: "v", type: valueT, mutable: false }],
body: [
{
kind: "return",
value:
valueT.kind === "dyn"
? { kind: "dynTest", test: "truthy", value, type: BOOL, loc }
: { kind: "toBool", operand: value, type: BOOL, loc },
loc,
},
],
loc,
});
}
return { kind: "closure", fnName: name, captures: [], type: fnT, loc };
}
@@ -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. */
@@ -148,12 +150,29 @@ export function objectIterOverIndexShape(
}
// The overflow value must surface as the element type (identity, an
// arm of a union element, or a dyn element over a dyn signature).
// A cast that narrows the signature's union (`Object.entries(headers as
// Record<string, string | string[] | undefined>)` over a signature that
// also holds numbers): each overflow value checks into the element type,
// so a value of a dropped arm throws instead of mistyping.
let ivNarrows = false;
if (valueT) {
const ivSurfaces =
typeEquals(iv, valueT) ||
(valueT.kind === "union" && lowerer.armTag(valueT.unionId, iv) >= 0) ||
(valueT.kind === "dyn" && iv.kind === "dyn");
if (!ivSurfaces) {
if (
!ivSurfaces &&
iv.kind === "union" &&
lowerer.dynConvertible(iv) &&
lowerer.dynConvertible(valueT)
) {
const ivUnion = iv;
const narrowArms =
valueT.kind === "union" ? (lowerer.unions.get(valueT.unionId)?.arms ?? []) : [valueT];
ivNarrows =
narrowArms.length > 0 && narrowArms.every((a) => lowerer.armTag(ivUnion.unionId, a) >= 0);
}
if (!ivSurfaces && !ivNarrows) {
lowerer.unsupported(
"SC1090",
node,
@@ -267,6 +286,21 @@ export function objectIterOverIndexShape(
}
}
}
// A cast that narrows the field's type (the element type keeps
// some of its arms): the value checks into the element type, so a
// dropped arm throws instead of mistyping.
if (lowerer.dynConvertible(f.type) && lowerer.dynConvertible(valueT)) {
const armsOf = (t: IrType): IrType[] =>
t.kind === "union" ? (lowerer.unions.get(t.unionId)?.arms ?? []) : [t];
const target = armsOf(valueT);
if (armsOf(f.type).some((a) => target.some((b) => typeEquals(a, b))))
return {
kind: "dynCheck",
value: { kind: "dynFrom", value: raw, type: DYN, loc },
type: valueT,
loc,
};
}
return null;
};
const pushedOf = (element: IrExpr): IrExpr =>
@@ -337,17 +371,37 @@ export function objectIterOverIndexShape(
const ksT = arrayOf(STRING);
const ksRef = varRef("ks.0", ksT, loc);
const kRef = varRef("k.0", STRING, loc);
const readValue: IrExpr | null = valueT
? {
kind: "recordKeyGet",
obj: rRef,
shapeId: argIr.shapeId,
key: kRef,
overflowOnly: true,
type: valueT,
loc,
}
: null;
const readValue: IrExpr | null = !valueT
? null
: ivNarrows
? {
kind: "dynCheck",
value: {
kind: "dynFrom",
value: {
kind: "recordKeyGet",
obj: rRef,
shapeId: argIr.shapeId,
key: kRef,
overflowOnly: true,
type: iv,
loc,
},
type: DYN,
loc,
},
type: valueT,
loc,
}
: {
kind: "recordKeyGet",
obj: rRef,
shapeId: argIr.shapeId,
key: kRef,
overflowOnly: true,
type: valueT,
loc,
};
const loopPushed: IrExpr =
member === "keys"
? kRef
@@ -472,9 +526,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 +604,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")
@@ -302,6 +302,53 @@ function lowerMethodReceiver(
return lowerer.coerceInto(node, lowered, expected);
}
/** A `string | undefined | null` receiver of a string method: evaluated
* once, each unit arm throws the TypeError Node's member read throws
* ("Cannot read properties of undefined (reading 'replace')") before the
* arguments evaluate, and the string arm is the receiver. */
function nullableStringReceiver(lowerer: Lowerer, node: ts.Expression, member: string): IrExpr {
const lowered = lowerer.lowerExpr(node);
if (lowered.type.kind !== "union") return lowerer.coerceInto(node, lowered, STRING);
const loc = locOf(node);
const unionId = lowered.type.unionId;
const local = lowerer.declareHiddenLocal("%nullableReceiver", lowered.type);
const ref: IrExpr = { kind: "varRef", localId: local.id, type: lowered.type, loc };
const arms = lowerer.unions.get(unionId)?.arms ?? [];
let result: IrExpr = {
kind: "unionNarrow",
unionId,
tag: arms.findIndex((arm) => arm.kind === "string"),
value: ref,
type: STRING,
loc,
};
for (const [tag, arm] of arms.entries()) {
if (!isUnitType(arm)) continue;
const unit = arm.kind === "nullT" ? "null" : "undefined";
result = {
kind: "ternary",
cond: { kind: "unionIsTag", unionId, tag, value: ref, negated: false, type: BOOL, loc },
then: nodeThrowExpr(
1,
"",
`Cannot read properties of ${unit} (reading '${member}')`,
STRING,
loc,
),
else_: result,
type: STRING,
loc,
};
}
return {
kind: "seqExpr",
stmts: [{ kind: "varDecl", localId: local.id, init: lowered, loc }],
result,
type: STRING,
loc,
};
}
/** Relative string indexing and code-point decoding over the UTF-16 intrinsics. */
export function lowerStringIndexCall(
lowerer: Lowerer,
@@ -733,6 +780,15 @@ export function lowerStringPaddingCall(
return { kind: "call", callee: helper, args: values, type: STRING, loc };
}
/** String methods whose regex-argument forms lower in lowerRegexMethodCall. */
const REGEX_ARGUMENT_STRING_METHODS = new Set([
"replace",
"replaceAll",
"split",
"search",
"matchAll",
]);
export function lowerRegexMethodCall(
lowerer: Lowerer,
call: ts.CallExpression,
@@ -747,11 +803,30 @@ export function lowerRegexMethodCall(
// by construction — the symbol gate doesn't apply to `any` receivers.
if (dynReceiver === undefined && !lowerer.isStdlibMember(access)) return null;
const name = access.name.text;
const receiverKind = dynReceiver
? "string"
: lowerer.mapTypeOf(lowerer.typeOf(access.expression))?.kind;
const mappedReceiver = dynReceiver ? null : lowerer.mapTypeOf(lowerer.typeOf(access.expression));
// A nullable string receiver of a REGEX-argument call
// (`part.replace(re, "")` where an unchecked index read typed `part`
// `string | undefined`) takes the string path, as
// lowerStringMethodCall's gate does for the string-argument forms:
// lowerMethodReceiver throws Node's "Cannot read properties of
// undefined" on the unit arms. (`match` keeps its own gate below.)
const regexArgument = call.arguments.nodes[0];
const nullableString =
REGEX_ARGUMENT_STRING_METHODS.has(name) &&
regexArgument !== undefined &&
!ts.isSpreadElement(regexArgument) &&
lowerer.mapTypeOf(lowerer.typeOf(regexArgument))?.kind === "regex" &&
mappedReceiver?.kind === "union" &&
(lowerer.unions.get(mappedReceiver.unionId)?.arms.some((arm) => arm.kind === "string") ??
false) &&
(lowerer.unions
.get(mappedReceiver.unionId)
?.arms.every((arm) => arm.kind === "string" || isUnitType(arm)) ??
false);
const receiverKind = dynReceiver || nullableString ? "string" : mappedReceiver?.kind;
const lowerReceiver = (): IrExpr => {
if (dynReceiver) return dynReceiver();
if (nullableString) return nullableStringReceiver(lowerer, access.expression, name);
if (receiverKind === "string")
return lowerMethodReceiver(lowerer, access.expression, STRING, access.name.text);
if (receiverKind === "regex")
@@ -14,7 +14,6 @@ import * as ts from "../ts7/adapter.js";
import { locOf } from "../program.js";
import { isNodeModulesPath } from "../resolve.js";
import {
dateLiteralDivergenceDiag,
keyOrderDivergenceDiag,
localeCompareDivergenceDiag,
unrelatedClassCastDivergenceDiag,
@@ -57,7 +56,6 @@ export function scanDivergences(
const literals: ts.ObjectLiteralExpression[] = [];
const observers: ts.Expression[] = [];
const casts: (ts.AsExpression | ts.TypeAssertion)[] = [];
const dates: { call: ts.CallExpression | ts.NewExpression; arg: ts.Expression }[] = [];
const localeCompares: ts.CallExpression[] = [];
/** binding name → member names assigned through it (`q.a = 2`). */
const assignedMembers = new Map<string, Set<string>>();
@@ -99,20 +97,9 @@ export function scanDivergences(
member === "dir")
) {
for (const a of node.arguments.nodes) if (!isLiteralLike(a)) observers.push(a);
} else if (recv.text === "Date" && member === "parse") {
if (node.arguments.nodes[0] !== undefined)
dates.push({ call: node, arg: node.arguments.nodes[0] });
}
}
}
} else if (ts.isNewExpression(node)) {
if (
ts.isIdentifier(node.expression) &&
node.expression.text === "Date" &&
node.arguments?.nodes.length === 1
) {
dates.push({ call: node, arg: node.arguments.nodes[0]! });
}
} else if (ts.isForInStatement(node)) {
observers.push(node.expression);
} else if (ts.isVariableDeclaration(node)) {
@@ -399,55 +386,9 @@ export function scanDivergences(
}
}
// ── Date strings the native parser does not accept ────────────────
for (const { call, arg } of dates) {
const callee = ts.isNewExpression(call)
? call.expression
: ts.isPropertyAccessExpression(call.expression)
? call.expression.expression
: undefined;
if (callee === undefined || !lowerer.isStdlibGlobal(callee, "Date")) continue;
for (const literal of dateStringLiterals(checker, arg)) {
const text = stringLiteralText(literal)!;
if (nativeDateParses(text) || !/\d/.test(text)) continue;
out.push(dateLiteralDivergenceDiag(text, locOf(literal)));
}
}
return out;
}
/** The string literals a Date argument can be: the literal itself, or
* each element of a const array of literals a for-of binding iterates. */
function dateStringLiterals(checker: ts.TypeChecker, arg: ts.Expression): ts.Expression[] {
if (stringLiteralText(arg) !== null) return [arg];
if (!ts.isIdentifier(arg)) return [];
const symbol = safely(() => checker.getSymbolAtLocation(arg));
const decl = symbol === undefined ? undefined : symbol.valueDeclaration;
const list = decl?.parent;
const loop = list?.parent;
if (
decl === undefined ||
!ts.isVariableDeclaration(decl) ||
list === undefined ||
loop === undefined ||
!ts.isForOfStatement(loop) ||
loop.initializer !== list
)
return [];
let iterated: ts.Expression = loop.expression;
if (ts.isIdentifier(iterated)) {
const source = safely(() => checker.getSymbolAtLocation(iterated));
const init = source === undefined ? undefined : source.valueDeclaration;
if (init === undefined || !ts.isVariableDeclaration(init) || init.initializer === undefined)
return [];
if (init.parent === undefined || (init.parent.flags & ts.NodeFlags.Const) === 0) return [];
iterated = init.initializer;
}
if (!ts.isArrayLiteralExpression(iterated)) return [];
return iterated.elements.nodes.filter((e) => stringLiteralText(e) !== null);
}
/** A checker query that fails here only loses a warning. */
function safely<T>(f: () => T): T | undefined {
try {
@@ -870,20 +811,3 @@ function classExtends(
function className(decl: ts.ClassLikeDeclaration): string {
return decl.name?.text ?? "(anonymous class)";
}
const MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
/** The date-string grammar the native runtime accepts (scr_lib.c
* scr_date_parse_get_time): ECMAScript's date-time format with an explicit
* offset (date-only forms are UTC) and the certificate-time shape
* "Mon DD HH:MM:SS YYYY GMT". Everything else parses to NaN natively. */
export function nativeDateParses(text: string): boolean {
const iso =
/^(?:[+-]\d{6}|\d{4})(?:-(\d{2})(?:-(\d{2}))?)?$/.test(text) ||
/^(?:[+-]\d{6}|\d{4})-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{3})?)?(?:Z|[+-]\d{2}:\d{2})$/.test(
text,
);
if (iso) return true;
const cert = /^([A-Za-z]{3}) {1,2}\d{1,2} \d{2}:\d{2}:\d{2} \d{4} GMT$/.exec(text);
return cert !== null && MONTHS.includes(cert[1]!.toLowerCase());
}
@@ -0,0 +1,98 @@
import * as ts from "../ts7/adapter.js";
import { isClassOwnEnumerableFieldName } from "../../ir/ir.js";
import type { ClassInfo } from "./lower-classes.js";
type ErrorClassLink = Pick<ClassInfo, "decl" | "ctor" | "paramProps"> & {
base: ErrorClassLink | null;
};
/** The property key a member or element-access name spells statically:
* an identifier, a quoted string, a number in its canonical spelling, or a
* computed string literal. Null for other keys. */
function staticKeyText(name: ts.Node): string | null {
if (ts.isIdentifier(name) || ts.isStringLiteral(name)) return name.text;
if (ts.isNumericLiteral(name)) return String(Number(name.text));
if (ts.isComputedPropertyName(name)) return staticKeyText(name.expression);
return null;
}
/** Whether `node` is an assignment to `this.<name>` or `this["<name>"]`,
* and the name. */
function thisAssignmentName(node: ts.Node): string | null {
if (!ts.isBinaryExpression(node) || node.operatorToken.kind !== ts.SyntaxKind.EqualsToken)
return null;
const target = node.left;
if (ts.isPropertyAccessExpression(target) && target.expression.kind === ts.SyntaxKind.ThisKeyword)
return ts.isIdentifier(target.name) ? target.name.text : null;
if (ts.isElementAccessExpression(target) && target.expression.kind === ts.SyntaxKind.ThisKeyword)
return staticKeyText(target.argumentExpression);
return null;
}
/** Where an Error subclass instance's own `name` sits among its fields when
* a class of its chain gives it one during construction. A property's
* position is fixed when it is created: a `name` field takes its place
* among the fields (parameter properties first, then the declared ones),
* and `this.name = ...` in a constructor follows the fields created so far,
* including the ones that constructor created before it. The answer is the
* field `name` follows, null when it precedes every field, and undefined
* when no class of the chain sets it during construction. `fields` are the
* instance's own enumerable fields. */
export function errorNameAfterField(
info: ErrorClassLink,
fields: ReadonlySet<string>,
): string | null | undefined {
const chain: ErrorClassLink[] = [];
for (let current: ErrorClassLink | null | undefined = info; current; current = current.base)
if (current.decl) chain.unshift(current);
const created = new Set<string>();
let last: string | null = null;
const create = (name: string): void => {
if (!fields.has(name) || created.has(name)) return;
created.add(name);
last = name;
};
for (const link of chain) {
for (const property of link.paramProps ?? []) create(property.name);
for (const member of link.decl!.members.nodes) {
if (!ts.isPropertyDeclaration(member)) continue;
const key = staticKeyText(member.name);
if (key === null) continue;
if (
member.modifiers?.nodes.some(
(m) => m.kind === ts.SyntaxKind.StaticKeyword || m.kind === ts.SyntaxKind.DeclareKeyword,
)
)
continue;
if (key === "name") return last;
create(key);
}
const body = link.ctor?.body;
if (!body) continue;
let found = false;
ts.walkPreorder(body, (node) => {
if (ts.isTypeNode(node)) return "skip";
if (ts.isFunctionLike(node) && !ts.isArrowFunction(node)) return "skip";
const name = thisAssignmentName(node);
if (name === "name") {
found = true;
return "stop";
}
if (name !== null) create(name);
return undefined;
});
if (found) return last;
}
return undefined;
}
/** The fields an Error subclass's own-property view lists. */
export function errorViewFields(fields: readonly { name: string }[]): Set<string> {
return new Set(
fields
.map((field) => field.name)
.filter(
(name) => isClassOwnEnumerableFieldName(name) && name !== "name" && name !== "message",
),
);
}
@@ -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,15 +21,23 @@ 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,
} from "../lower-exprs.js";
import { runtimeOptionalReceiverRead } from "./narrowing.js";
import { builtinGlobalValueAt } from "./property-access.js";
import { varRef } from "../../../ir/build.js";
import {
ambientUndefReadType,
@@ -352,19 +360,25 @@ export function lowerIdentifierExpr(lowerer: Lowerer, expr: ts.Identifier, loc:
// MODULE compile-time constants, the containing file's location
// (Node's exact values when the same tree runs in place; WASI uses
// the equivalent guest-visible path; locals shadowing the names
// resolved above). In a file with ESM syntax Node never defines them
// (ReferenceError) — fence rather than invent a value there.
// resolved above), the same strings as import.meta.dirname/filename.
// In a JavaScript ES module Node never defines them, so the read throws
// Node's catchable ReferenceError. A .ts/.tsx file keeps them even when
// Node's strip-types rule would load it as ESM: TypeScript projects are
// commonly built as CommonJS bundles (tsc, esbuild, tsx) where these
// globals exist, and @types/node declares them for every file.
if (
(expr.text === "__dirname" || expr.text === "__filename") &&
lowerer.isStdlibGlobal(expr, expr.text)
) {
const sf = expr.getSourceFile();
if (isNodeEsmFile(sf, lowerer.program)) {
lowerer.unsupported(
"SC1090",
expr,
`'${expr.text}' in an ES module (Node defines the CJS module globals only in CommonJS modules)`,
);
if (isNodeEsmFile(sf, lowerer.program) && !/\.tsx?$/.test(sf.fileName)) {
return {
kind: "libCall",
fn: "global.undefRead",
args: [{ kind: "strLit", value: expr.text, type: STRING, loc }],
type: STRING,
loc,
};
}
// The WASI runner mounts the host cwd at guest `/` and the host temp
// directory at `/tmp`. Bake the matching GUEST spelling so resource
@@ -710,8 +724,18 @@ export function lowerIdentifierExpr(lowerer: Lowerer, expr: ts.Identifier, loc:
{
const sym = lowerer.checker.getSymbolAtLocation(expr);
if (lowerer.isStdlibSymbol(sym) || expr.text === "globalThis") {
const canonical = stdlibGlobalNameOf(lowerer, expr) ?? expr.text;
// Builtin constructors have real function values in both source
// languages (TypeScript reads them as dynamic values).
const builtinValue = builtinGlobalValueAt(
lowerer,
expr,
canonical,
loc,
isJsSourceFile(expr.getSourceFile()),
);
if (builtinValue !== null) return builtinValue;
if (isJsSourceFile(expr.getSourceFile())) {
const canonical = stdlibGlobalNameOf(lowerer, expr) ?? expr.text;
return { kind: "strLit", value: `[builtin ${canonical}]`, type: STRING, loc };
}
// The families with a WHY: each hint states what makes the
@@ -924,5 +948,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));
}
@@ -640,6 +640,74 @@ function literalUnionArmOf(
/** Object spread treats nullish sources as empty. Preserve evaluation once,
* then turn `Record<K, V> | undefined` into either that record or a fresh
* empty record of the same represented shape. */
/** `{ ...unknownValue }` into a pure index-signature record (headers
* forwarded from an untyped parameter): Node copies the source's own
* enumerable keys in order, and spreads nothing for null, undefined,
* numbers and booleans. An object source converts through the checked
* extraction into the target's own shape, which keeps its keys and order
* and checks each value against the slot type (a value outside it throws
* the catchable TypeError of every unknown-to-typed conversion). A string
* source takes the same extraction, which rejects it, rather than
* silently dropping the characters Node would spread. Null for other
* sources and targets. */
function dynIndexSpreadSource(
lowerer: Lowerer,
source: IrExpr,
target: IrType,
loc: SrcLoc,
): IrExpr | null {
if (source.type.kind !== "dyn" || target.kind !== "record") return null;
const shape = lowerer.shapes.get(target.shapeId);
if (!shape?.indexValue || shape.fields.length > 0 || shape.tuple) return null;
if (
!canDynCheckTo(
target,
(id) => lowerer.shapes.get(id),
(id) => lowerer.unions.get(id),
)
)
return null;
const local = lowerer.declareHiddenLocal("%dynSpread", DYN);
const ref = varRef(local.id, DYN, loc);
const test = (kind: "object" | "string" | "nullish"): IrExpr => ({
kind: "dynTest",
test: kind,
value: ref,
type: BOOL,
loc,
});
const extract: IrExpr = { kind: "dynCheck", value: ref, type: target, loc };
const empty: IrExpr = { kind: "recordLit", fields: [], type: target, loc };
return {
kind: "seqExpr",
stmts: [{ kind: "varDecl", localId: local.id, init: source, loc }],
result: {
kind: "ternary",
cond: test("nullish"),
then: empty,
else_: {
kind: "ternary",
cond: {
kind: "logical",
op: "||",
left: test("object"),
right: test("string"),
type: BOOL,
loc,
},
then: extract,
else_: empty,
type: target,
loc,
},
type: target,
loc,
},
type: target,
loc,
};
}
function lowerOptionalIndexSpreadSource(
lowerer: Lowerer,
source: IrExpr,
@@ -1372,7 +1440,7 @@ export function lowerObjectLiteral(
vNode,
);
contributors.push({
kind: "field",
kind: "condField",
name: csProp.name.text,
value: {
kind: "ternary",
@@ -1387,6 +1455,7 @@ export function lowerObjectLiteral(
}
let src = lowerer.lowerExpr(prop.expression);
src = lowerOptionalIndexSpreadSource(lowerer, src, locOf(prop)) ?? src;
src = dynIndexSpreadSource(lowerer, src, type, locOf(prop)) ?? src;
if (src.type.kind !== "record") {
lowerer.unsupported(
"SC1090",
@@ -1631,7 +1700,11 @@ export function lowerObjectLiteral(
}
shapeMismatch(prop);
}
const absent = lowerer.absentFieldValue(fieldType, locOf(prop));
// An 'unknown' slot holds the checked-dynamic undefined for the
// empty arm, the absent-property read the width copy uses too.
const absent =
lowerer.absentFieldValue(fieldType, locOf(prop)) ??
(fieldType.kind === "dyn" ? dynUndefinedExpr(locOf(prop)) : null);
if (!absent) {
lowerer.unsupported(
"SC1090",
@@ -2559,6 +2632,14 @@ export function andSpreadOf(
while (ts.isParenthesizedExpression(right)) right = right.expression;
if (!ts.isObjectLiteralExpression(right)) return null;
const spreadType = lowerer.mapTypeOf(lowerer.typeOf(e));
// Every falsy value is a primitive, which spreads nothing, so `c && {
// ... }` contributes the literal's members exactly when c is truthy,
// whatever c's type. The checker's union of the two decides the
// representation where it maps; where it does not (a member typed by a
// checked-dynamic value such as an AbortSignal), the syntax decides.
if (spreadType === null || spreadType.kind === "dyn") {
return syntacticAndSpread(right, e.left);
}
if (spreadType?.kind !== "union") return null;
const arms = lowerer.unions.get(spreadType.unionId)?.arms ?? [];
if (
@@ -2590,6 +2671,26 @@ export function andSpreadOf(
return { cond: e.left, props, whenTrue: true };
}
function syntacticAndSpread(
right: ts.ObjectLiteralExpression,
cond: ts.Expression,
): { cond: ts.Expression; props: CondSpreadProp[]; whenTrue: boolean } | "unsupported" {
if (right.properties.nodes.length === 0) return "unsupported";
const props: CondSpreadProp[] = [];
for (const p of right.properties.nodes) {
if (
(ts.isPropertyAssignment(p) || ts.isShorthandPropertyAssignment(p)) &&
p.name &&
(ts.isIdentifier(p.name) || ts.isStringLiteral(p.name))
) {
props.push(p as CondSpreadProp);
} else {
return "unsupported";
}
}
return { cond, props, whenTrue: true };
}
/** A conditional spread's carrier property: `name: value` or shorthand,
* with an identifier/string-literal name. */
export type CondSpreadProp = (ts.PropertyAssignment | ts.ShorthandPropertyAssignment) & {
@@ -741,6 +741,12 @@ export function lowerPropertyAccessExpr(
lowerStreamObjectProperty(lowerer, expr) ??
lowerEventObjectProperty(lowerer, expr) ??
lowerer.lowerUnionProperty(expr) ??
// A builtin constructor reached through another binding (`const D =
// Date; D.prototype`) holds its interned function value, which
// models only name, length and constructor: a static member or the
// prototype that no lowering above claimed keeps the SC2020 fence
// rather than reading undefined through the field and dynamic reads.
fenceBuiltinConstructorStaticRead(lowerer, expr) ??
lowerer.lowerFieldRead(expr);
// A union-typed field read narrows like an identifier when the
// checker has narrowed this use to one arm.
@@ -787,7 +793,14 @@ export function lowerPropertyAccessExpr(
type: DYN,
loc,
};
return { kind: "strLit", value: `[builtin ${canonical}]`, type: STRING, loc };
return (
builtinGlobalValueAt(lowerer, expr, canonical, loc, true) ?? {
kind: "strLit",
value: `[builtin ${canonical}]`,
type: STRING,
loc,
}
);
}
}
// A JS receiver whose CHECKER type has no mapping (`mustCallChecks
@@ -866,6 +879,43 @@ export function lowerPropertyAccessExpr(
};
}
}
// A plain record's inherited Object.prototype members READ as values
// (`o.constructor`, `o.valueOf`, `({}).toString`, the isPlainObject and
// deep-equal idioms): the record boxes into its dynamic view, whose
// read answers the interned Object constructor and Object.prototype
// methods — the same values `Object` and `Object.prototype.valueOf`
// read, so identity comparisons are exact. Calls keep their own
// lowerings; a record declaring the name reads its field.
if (
OBJECT_PROTOTYPE_VALUE_READS.has(expr.name.text) &&
!isCalleeOf(expr) &&
// `X.prototype.toString` keeps the builtin prototype-method lowering.
!(ts.isPropertyAccessExpression(expr.expression) && expr.expression.name.text === "prototype")
) {
const receiver = tryLowerExpression(lowerer, expr.expression);
const name = expr.name.text;
const shape =
receiver?.type.kind === "record" ? lowerer.shapes.get(receiver.type.shapeId) : undefined;
const info =
receiver?.type.kind === "object" ? lowerer.classes.get(receiver.type.className) : undefined;
const inherits =
receiver?.type.kind === "dyn" ||
(shape !== undefined && !shape.tuple && !shape.fields.some((field) => field.name === name)) ||
(info !== undefined &&
name !== "constructor" &&
!info.fields.has(name) &&
!lowerer.findMethodOn(info, name) &&
!lowerer.findMethodOn(info, `get:${name}`));
if (receiver !== null && receiver !== undefined && inherits) {
return {
kind: "dynKeyGet",
value: lowerer.coerceToExpected(receiver, DYN),
key: { kind: "strLit", value: name, type: STRING, loc },
type: DYN,
loc,
};
}
}
// `f.name` / `f.length` / own properties on a FUNCTION-typed JS
// value (the mustCall wrapper's function-instance members): read
// through the dyn box — the closure's own-property table answers
@@ -1255,6 +1305,8 @@ export function lowerPropertyAccessExpr(
const mapped = lowerer.mapTypeOf(lowerer.typeOf(expr));
return mapped && mapped.kind !== "void" ? lowerer.coerceInto(expr, read, mapped) : read;
}
const asserted = assertedMemberRead(lowerer, expr, recvLowered, loc);
if (asserted) return asserted;
lowerer.unsupported(
"SC1090",
expr,
@@ -1262,6 +1314,101 @@ export function lowerPropertyAccessExpr(
);
}
/** `(source as { repoName: string }).repoName` where the assertion names a
* member some arms of the stored union of records do not declare: Node
* reads the property off whichever object it is, so arms that declare it
* answer their slot, and the others answer undefined (native records are
* closed, so they cannot hold it). The result keeps that undefined arm
* whatever the assertion claims; a consumer that needs the asserted type
* checks it like any other narrowing. The arms that declare the member
* must agree on its type. Null when the receiver is not such an
* assertion over records, or no arm declares the member. */
function assertedMemberRead(
lowerer: Lowerer,
expr: ts.PropertyAccessExpression,
recv: IrExpr,
loc: SrcLoc,
): IrExpr | null {
let receiverNode: ts.Expression = expr.expression;
while (ts.isParenthesizedExpression(receiverNode)) receiverNode = receiverNode.expression;
if (!ts.isAsExpression(receiverNode) && !ts.isTypeAssertion(receiverNode)) return null;
if (recv.type.kind !== "union") return null;
const unionId = recv.type.unionId;
const arms = lowerer.unions.get(unionId)?.arms ?? [];
const name = expr.name.text;
let resultType: IrType | null = null;
let records = 0;
const declaring: { tag: number; shapeId: string; type: IrType }[] = [];
const units: number[] = [];
for (let tag = 0; tag < arms.length; tag++) {
const arm = arms[tag]!;
if (isUnitType(arm)) {
units.push(tag);
continue;
}
if (arm.kind !== "record") return null;
records++;
const shape = lowerer.shapes.get(arm.shapeId);
if (!shape || shape.tuple || shape.indexValue) return null;
const field = shape.fields.find((f) => f.name === name);
if (!field) continue;
// The declaring arms agree up to an undefined arm (`string` beside
// `string | undefined`).
const armResult = lowerer.withUndefinedArmOf(field.type);
if (!armResult || (resultType && !typeEquals(resultType, armResult))) return null;
resultType = armResult;
declaring.push({ tag, shapeId: arm.shapeId, type: field.type });
}
if (!resultType || declaring.length === records) return null;
const stable = lowerer.declareHiddenLocal("%assertedRecv", recv.type);
const ref = (): IrExpr => ({ kind: "varRef", localId: stable.id, type: recv.type, loc });
let result: IrExpr | null = lowerer.wrappedUndefined(resultType, loc);
if (!result) return null;
// A unit arm the checker narrowed away reads like Node would read it.
for (const tag of units) {
const unit = arms[tag]!.kind === "nullT" ? "null" : "undefined";
result = {
kind: "ternary",
cond: { kind: "unionIsTag", unionId, tag, negated: false, value: ref(), type: BOOL, loc },
then: nodeThrowExpr(
1,
"",
`Cannot read properties of ${unit} (reading '${name}')`,
resultType,
loc,
),
else_: result,
type: resultType,
loc,
};
}
for (const { tag, shapeId, type: fieldType } of declaring) {
const read: IrExpr = {
kind: "recordGet",
obj: { kind: "unionNarrow", unionId, tag, value: ref(), type: arms[tag]!, loc },
shapeId,
field: name,
type: fieldType,
loc,
};
result = {
kind: "ternary",
cond: { kind: "unionIsTag", unionId, tag, negated: false, value: ref(), type: BOOL, loc },
then: lowerer.coerceToExpected(read, resultType),
else_: result,
type: resultType,
loc,
};
}
return {
kind: "seqExpr",
stmts: [{ kind: "varDecl", localId: stable.id, init: recv, loc }],
result,
type: resultType,
loc,
};
}
function importMetaProperty(lowerer: Lowerer, expr: ts.PropertyAccessExpression): IrExpr | null {
return isImportMeta(expr.expression) ? importMetaField(lowerer, expr, expr.name.text) : null;
}
@@ -1305,6 +1452,13 @@ export function lowerIntrinsicProperty(
return { kind: "dynFrom", value, fnName: "ownKeys", type: DYN, loc: locOf(expr) };
}
if (lowerer.chainBlocked(expr)) return null;
// Object.prototype.constructor: the Object constructor value.
if (
expr.name.text === "constructor" &&
ts.isPropertyAccessExpression(expr.expression) &&
lowerer.stdlibGlobalMember(expr.expression, "Object") === "prototype"
)
return builtinGlobalValue("Object", locOf(expr));
const builtinPrototype = builtinPrototypeMethod(lowerer, expr);
if (builtinPrototype)
return {
@@ -2584,6 +2738,27 @@ export function lowerFieldRead(lowerer: Lowerer, expr: ts.PropertyAccessExpressi
loc: locOf(expr),
};
}
// A member the checker declares on the receiver, stored in a pure
// index-signature record (an object literal that spread one, see
// dictSpreadLiteralShape): the key is always present, so the keyed
// read answers the member through the slot type.
if (
actual?.type.kind === "record" &&
shape.fields.length === 0 &&
declaredMemberOf(lowerer, expr.expression, expr.name.text)
) {
return lowerer.maybeNarrow(
{
kind: "recordKeyGet",
obj: actual,
shapeId: actual.type.shapeId,
key: { kind: "strLit", value: expr.name.text, type: STRING, loc: locOf(expr.name) },
type: shape.indexValue,
loc: locOf(expr),
},
expr,
);
}
lowerer.unsupported(
"SC1090",
expr,
@@ -3557,6 +3732,223 @@ function lowerStreamObjectProperty(
return lowerStreamProperty(lowerer, expr, info);
}
/** The builtin constructors JavaScript sources read as real function
* values rather than identity tokens: the runtime interns one function per
* constructor, and dynamic values answer `.constructor` with the same one,
* so `o.constructor === Object` is an exact identity test. */
const GLOBAL_CONSTRUCTOR_VALUES: ReadonlySet<string> = new Set([
"Object",
"Function",
"Date",
"RegExp",
"Map",
"Set",
"Promise",
"WeakMap",
"WeakSet",
]);
/** The builtin global functions JavaScript sources read as interned
* function values (the `cond ? setImmediate : process.nextTick` feature
* probe of bcryptjs and async libraries): typeof answers "function",
* identity holds across spellings, and calls run the timer APIs. */
const GLOBAL_FUNCTION_VALUES: ReadonlySet<string> = new Set([
"setTimeout",
"setInterval",
"setImmediate",
"clearTimeout",
"clearInterval",
"clearImmediate",
"queueMicrotask",
]);
/** A builtin function value: one interned runtime function per name. */
export function builtinFunctionValue(name: string, loc: SrcLoc): IrExpr {
return {
kind: "libCall",
fn: "dyn.builtinFunction",
args: [{ kind: "strLit", value: name, type: STRING, loc }],
type: DYN,
loc,
};
}
/** The value a source reads for the stdlib global `canonical` (builtin
* constructors in both languages, builtin functions in JavaScript), or
* null when it stays an identity token (JavaScript) or fenced. */
export function builtinGlobalValue(canonical: string, loc: SrcLoc, js = false): IrExpr | null {
if (js && GLOBAL_FUNCTION_VALUES.has(canonical)) return builtinFunctionValue(canonical, loc);
if (GLOBAL_CONSTRUCTOR_VALUES.has(canonical)) {
return {
kind: "libCall",
fn: "dyn.globalConstructor",
args: [{ kind: "strLit", value: canonical, type: STRING, loc }],
type: DYN,
loc,
};
}
return null;
}
/** The members the interned builtin function values model (the runtime
* answers each one as Node does); any other member read through them would
* answer undefined, so it keeps its static lowering or its fence. */
const BUILTIN_VALUE_MEMBERS: ReadonlySet<string> = new Set(["name", "length", "constructor"]);
/** The Object statics whose answers for an interned builtin function value
* match Node's (identity, and the empty enumerable own-key lists). */
const BUILTIN_VALUE_REFLECTION: ReadonlySet<string> = new Set(["is", "keys", "values", "entries"]);
/** The value `builtinGlobalValue` gives the stdlib global `expr` read at its
* use site: null when the use reads the global's members (they keep their
* lowerings and fences), and SC2020 when it is the target of reflection or
* redefinition (`Object.hasOwn(Object, "hasOwn")`,
* `Object.defineProperty(Promise, ...)`, `hasOwnProperty.call(Map, ...)`),
* which would observe or change members the interned value does not
* model. */
export function builtinGlobalValueAt(
lowerer: Lowerer,
expr: ts.Expression,
canonical: string,
loc: SrcLoc,
js: boolean,
): IrExpr | null {
if (readsBuiltinGlobalMembers(expr)) return null;
const value = builtinGlobalValue(canonical, loc, js);
if (value === null) return null;
let node: ts.Node = expr;
while (node.parent !== undefined && ts.isParenthesizedExpression(node.parent)) node = node.parent;
const call = node.parent;
if (
call !== undefined &&
ts.isCallExpression(call) &&
call.expression !== node &&
ts.isPropertyAccessExpression(call.expression)
) {
const callee = call.expression;
const owner = stdlibGlobalNameOf(lowerer, callee.expression);
const reflects =
owner === "Reflect" ||
(owner === "Object" && !BUILTIN_VALUE_REFLECTION.has(callee.name.text)) ||
((callee.name.text === "call" || callee.name.text === "apply") &&
call.arguments.nodes[0] === node &&
lowerer.isStdlibSymbol(
lowerer.checker.getSymbolAtLocation(
ts.isPropertyAccessExpression(callee.expression)
? callee.expression.name
: callee.expression,
),
));
if (reflects) {
const name =
owner !== null ? `${owner}.${callee.name.text}` : callee.getText().replace(/\s+/g, "");
lowerer.noLowering(
`${name}(${canonical}, ...)`,
expr,
"builtin constructor and function values model only name, length and constructor, so reflecting on or redefining their members has no lowering",
);
}
}
return value;
}
/** Whether the stdlib global `expr` is read for its members (`Map.prototype`,
* `Date["UTC"]`, `"prototype" in Map`) rather than as a value. Those reads
* keep the global's member lowerings and fences: its interned function value
* models only BUILTIN_VALUE_MEMBERS. */
function readsBuiltinGlobalMembers(expr: ts.Expression): boolean {
let node: ts.Node = expr;
while (node.parent !== undefined && ts.isParenthesizedExpression(node.parent)) node = node.parent;
const parent = node.parent;
if (parent === undefined) return false;
if (ts.isPropertyAccessExpression(parent) && parent.expression === node)
return !BUILTIN_VALUE_MEMBERS.has(parent.name.text);
if (ts.isElementAccessExpression(parent) && parent.expression === node) return true;
return (
ts.isBinaryExpression(parent) &&
parent.operatorToken.kind === ts.SyntaxKind.InKeyword &&
parent.right === node
);
}
/** Reports SC2020 when `access` reads a stdlib static member or the
* prototype of a builtin constructor with an interned function value through
* a receiver the checker types as the constructor's static side
* (`MapConstructor`); null otherwise. Calls that lower statically never
* reach the member read. */
function fenceBuiltinConstructorStaticRead(
lowerer: Lowerer,
access: ts.PropertyAccessExpression,
): null {
if (BUILTIN_VALUE_MEMBERS.has(access.name.text)) return null;
const symbol = lowerer.typeOf(access.expression).getSymbol();
if (
symbol !== undefined &&
symbol.name.endsWith("Constructor") &&
GLOBAL_CONSTRUCTOR_VALUES.has(symbol.name.slice(0, -"Constructor".length)) &&
lowerer.isStdlibSymbol(symbol)
)
lowerer.stdlibMemberFence(access);
return null;
}
/** Object.prototype members a plain record inherits, read as values. */
const OBJECT_PROTOTYPE_VALUE_READS: ReadonlySet<string> = new Set([
"constructor",
"valueOf",
"toString",
"hasOwnProperty",
"propertyIsEnumerable",
]);
/** Whether `expr` is the callee of a call (`o.toString()`), which keeps its
* call lowering rather than reading the member as a value. */
function isCalleeOf(expr: ts.PropertyAccessExpression): boolean {
let node: ts.Node = expr;
while (node.parent !== undefined && ts.isParenthesizedExpression(node.parent)) node = node.parent;
const parent = node.parent;
return (
parent !== undefined &&
(ts.isCallExpression(parent) || ts.isNewExpression(parent)) &&
parent.expression === node
);
}
/** The constructor a primitive dynamic value answers for `.constructor`:
* the same interned closure the `Number`/`String`/`Boolean`/`BigInt`
* identifiers read (dequal's `(ctor = foo.constructor) === bar.constructor`
* over numbers), or `otherwise` for non-primitives. `value` must be safe to
* read repeatedly. */
export function primitiveConstructorOr(
lowerer: Lowerer,
value: IrExpr,
otherwise: IrExpr,
loc: SrcLoc,
): IrExpr {
let result = otherwise;
for (const [test, name] of [
["bigint", "BigInt"],
["boolean", "Boolean"],
["string", "String"],
["number", "Number"],
] as const) {
result = {
kind: "ternary",
cond: { kind: "dynTest", test, value, type: BOOL, loc },
then: {
kind: "dynFrom",
value: primitiveCtorClosure(lowerer, name, loc, true),
type: DYN,
loc,
},
else_: result,
type: DYN,
loc,
};
}
return result;
}
/** True when `access` reads a member that JavaScript sources attach to a
* function by assignment (`fn.member = value`): the receiver's type is
* callable and every declaration of the member is such an assignment in a
@@ -3581,3 +3973,10 @@ function jsFunctionExpandoMember(lowerer: Lowerer, access: ts.PropertyAccessExpr
})
);
}
/** Whether the checker declares `name` as a property of `receiver`'s type
* (as opposed to reading it through an index signature). */
export function declaredMemberOf(lowerer: Lowerer, receiver: ts.Expression, name: string): boolean {
const symbol = lowerer.checker.getPropertyOfType(lowerer.typeOf(receiver), name);
return !!symbol && symbol.declarations.length > 0;
}
@@ -13,6 +13,7 @@ import {
} from "../../../ir/ir.js";
import { lowerWebAssemblyTypeof } from "../builtins/webassembly.js";
import { isNavigatorGlobal } from "../builtins/navigator.js";
import { processHasIpc } from "../builtins/process.js";
import { lowerPerfHooksTypeof } from "../builtins/performance.js";
import { isNodeModuleValue } from "../lower-node-module.js";
import { builtinClassRefOf } from "../builtins/class-values.js";
@@ -27,7 +28,7 @@ import {
typeofAnswer,
} from "../lower-exprs.js";
import { tryLowerExpression } from "./try-lower-expression.js";
import { isJsSourceFile } from "../../program.js";
import { isJsSourceFile, isNodeEsmFile } from "../../program.js";
import { isSafeToDiscard, isSafeToRepeat } from "./evaluation-safety.js";
import { varRef } from "../../../ir/build.js";
import { isExecExceptionType, refuseExecExceptionCode } from "../builtins/errors.js";
@@ -38,8 +39,41 @@ export function lowerTypeofExpr(lowerer: Lowerer, expr: ts.TypeOfExpression, loc
if (webAssembly) return webAssembly;
if (lowerer.isStdlibGlobal(expr.expression, "process"))
return { kind: "strLit", value: "object", type: STRING, loc };
{
let operand = expr.expression;
while (ts.isParenthesizedExpression(operand)) operand = operand.expression;
const ipcMember =
ts.isPropertyAccessExpression(operand) && !operand.questionDotToken
? lowerer.stdlibGlobalMember(operand, "process")
: null;
if (ipcMember === "send" || ipcMember === "disconnect") {
return {
kind: "ternary",
cond: processHasIpc(lowerer, loc),
then: { kind: "strLit", value: "function", type: STRING, loc },
else_: { kind: "strLit", value: "undefined", type: STRING, loc },
type: STRING,
loc,
};
}
}
if (lowerer.isStdlibGlobal(expr.expression, "fetch"))
return { kind: "strLit", value: "function", type: STRING, loc };
// `__dirname` / `__filename` in a JavaScript ES module, where Node never
// defines them: typeof answers "undefined" instead of throwing.
{
let operand = expr.expression;
while (ts.isParenthesizedExpression(operand)) operand = operand.expression;
if (
ts.isIdentifier(operand) &&
(operand.text === "__dirname" || operand.text === "__filename") &&
lowerer.isStdlibGlobal(operand, operand.text)
) {
const sf = operand.getSourceFile();
if (isNodeEsmFile(sf, lowerer.program) && !/\.tsx?$/.test(sf.fileName))
return { kind: "strLit", value: "undefined", type: STRING, loc };
}
}
if (isNavigatorGlobal(lowerer, expr.expression))
return { kind: "strLit", value: "object", type: STRING, loc };
const performance = lowerPerfHooksTypeof(lowerer, expr.expression);
@@ -1,5 +1,6 @@
/* Increment, decrement and prefix unary operators, and compound field updates. */
import * as ts from "../../ts7/adapter.js";
import { isStrictCode } from "../strict-mode.js";
import { isPrivateWriteReceiver } from "../private-brands.js";
import type { Lowerer } from "../lowerer.js";
import {
@@ -751,6 +752,7 @@ export function fieldSetStmt(
className: target.className,
field: target.field,
value,
...(isStrictCode(blame) ? {} : { sloppy: true as const }),
loc,
}
: {
@@ -227,6 +227,7 @@ import {
} from "./optional-arguments.js";
import { fenceSymbolFieldCopy } from "./symbol-fields.js";
import { lowerClassDataDescriptor, lowerClassDescriptorRead } from "./class-descriptors.js";
import { lowerClassFieldDefine, lowerClassIntegrity } from "./class-attributes.js";
import { classStaticDataFor } from "./class-static-data.js";
import { lowerUrlFactory } from "./lower-url.js";
import { nullishValueUnitOf } from "./binding-analysis.js";
@@ -7717,6 +7718,8 @@ function lowerObjectStaticCall(
if (target && declaredTarget && isDynTypedRefType(declaredTarget))
target = lowerer.coerceToExpected(target, declaredTarget);
if (target && member === "defineProperty") {
const field = lowerClassFieldDefine(lowerer, call, target);
if (field) return field;
const native = lowerClassDataDescriptor(lowerer, call, member, target);
if (native) return native;
}
@@ -7859,6 +7862,19 @@ function lowerObjectStaticCall(
loc,
};
}
if (member === "preventExtensions" || member === "seal") {
const integrity = lowerClassIntegrity(lowerer, call, member, value);
if (integrity) return integrity;
} else if (isDynTypedRefType(value.type)) {
// The instance's checked view carries its integrity state.
return {
kind: "libCall",
fn: member === "isSealed" ? "dyn.isSealed" : "dyn.isExtensible",
args: [lowerer.coerceToExpected(value, DYN)],
type: BOOL,
loc: locOf(call),
};
}
if (value.type.kind === "dyn") {
const operation = {
preventExtensions: "dyn.preventExtensions",
@@ -7929,6 +7945,8 @@ function lowerObjectStaticCall(
)
)
return value;
const integrity = lowerClassIntegrity(lowerer, call, "freeze", value);
if (integrity) return integrity;
lowerer.noLowering(
"Object.freeze of a possibly-aliased value",
call,
@@ -70,6 +70,7 @@ import {
} from "./instantiation-path.js";
import { appendImplicitUndefinedReturn, hasExplicitJsDocReturn } from "./function-returns.js";
import { bodyReadsArguments } from "../arguments-usage.js";
import { errorNameAfterField, errorViewFields } from "./error-name-order.js";
import {
checkedJsDocumentedParameter,
documentedParameter,
@@ -88,7 +89,6 @@ import {
isCjsJsFile,
isJsSourceFile,
isModuleExportsAccess,
isNodeTypesPath,
locOf,
} from "../program.js";
import { PoisonError, dynFallbackType, jsFuncNameOf, newFnCtx, own } from "./lowerer.js";
@@ -1046,9 +1046,11 @@ export function builtinStreamInfoOf(
if (rec.lib === symbol.name) irName = name;
}
if (!irName) return null;
// Both the bundled declarations and @types/node declare the classes
// inside `declare module "stream"` (@types/node nests them in the module's
// `internal` namespace).
const declared = symbol.declarations.some((d) => {
if (!ts.isClassDeclaration(d)) return false;
if (isNodeTypesPath(d.getSourceFile().fileName)) return false;
let node: ts.Node | undefined = d.parent;
while (node) {
if (ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name)) {
@@ -2212,11 +2214,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,
@@ -4259,6 +4257,12 @@ export function collectClassShapeInner(
...(deferredInitFields.size > 0 ? { deferredInitFields } : {}),
...(escape.escapes ? { constructionEscapes: true as const } : {}),
};
let root: ClassInfo | null = info;
while (root?.base) root = root.base;
if (root !== info && root?.def.name === "%Error") {
const after = errorNameAfterField(info, errorViewFields(info.def.fields));
if (after !== undefined) info.def.errorNameAfter = after;
}
// GENERIC members get their declaring-class backlink now that the
// info exists (instance lowering reads it for `this` typing and the
// generic-class binding merge).
@@ -5182,16 +5186,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,
@@ -8062,6 +8061,7 @@ export function fieldInitStmts(lowerer: Lowerer, info: ClassInfo, thisLocal: IrL
className: info.def.name,
field: f.name,
value: dynUndefinedExpr(loc),
define: true,
loc,
});
}
@@ -8077,6 +8077,7 @@ export function fieldInitStmts(lowerer: Lowerer, info: ClassInfo, thisLocal: IrL
className: info.def.name,
field: f.name,
value,
define: true,
loc: locOf(f.initializer),
});
} catch (e) {
@@ -8734,6 +8735,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. */
@@ -8858,24 +8913,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)
@@ -9466,18 +9504,57 @@ export function lowerNew(lowerer: Lowerer, expr: ts.NewExpression): IrExpr {
// fenced, so copying the scalar cannot create an observable lie.
if (symbol && symbol.name === "Date" && lowerer.isStdlibSymbol(symbol)) {
const args = expr.arguments?.nodes ?? [];
if (args.some(ts.isSpreadElement) || args.length > 1) {
if (args.some(ts.isSpreadElement)) {
lowerer.noLowering(
`new Date with ${args.length} arguments`,
`new Date with spread arguments`,
expr,
"new Date(), new Date(milliseconds), and new Date(dateString) are supported; the local-time year/month field constructor has no lowering",
"new Date(), new Date(milliseconds), new Date(dateString), and new Date(year, monthIndex, ...) with listed arguments are supported",
symbol,
);
}
// new Date(year, monthIndex[, date[, hours[, minutes[, seconds[, ms]]]]]):
// local-time fields, converted to UTC in the host zone at run time.
// JavaScript callers pass their arguments to the runtime's ToNumber
// (in order, exactly the constructor's coercions); typed callers
// pass numbers, completed with the spec's defaults (date 1, time
// parts 0) for the seven-f64 ABI.
if (args.length > 1) {
if (isJsSourceFile(expr.getSourceFile())) {
return {
kind: "libCall",
fn: "date.nativeNewFields",
args: [
{
kind: "dynArrLit",
elems: args.map((arg) => lowerer.lowerExprExpecting(arg, DYN)),
type: DYN,
loc,
},
],
type: DYN,
loc,
};
}
if (args.length > 7) {
lowerer.noLowering(`new Date with ${args.length} arguments`, expr, undefined, symbol);
}
const defaults = [0, 0, 1, 0, 0, 0, 0];
const fields: IrExpr[] = [];
for (let i = 0; i < 7; i++) {
const arg = args[i];
fields.push(
arg !== undefined
? lowerer.lowerExprExpecting(arg, F64)
: { kind: "numLit", value: defaults[i]!, type: F64, loc },
);
}
return { kind: "libCall", fn: "date.newLocal", args: fields, type: DATE_T, loc };
}
if (isJsSourceFile(expr.getSourceFile())) {
return {
kind: "libCall",
fn: "date.nativeNew",
// One argument: a string parses with the full date parser.
fn: args.length === 1 ? "date.nativeNewValue" : "date.nativeNew",
args: [
{
kind: "dynArrLit",
@@ -10123,6 +10200,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 ?? [],
@@ -290,8 +290,17 @@ function lowerDnsModuleCall(
loc: SrcLoc,
): IrExpr {
const args = expr.arguments.nodes;
const dyn = (node: ts.Expression): IrExpr =>
lowerer.coerceToExpected(lowerer.lowerExpr(node), DYN);
const dyn = (node: ts.Expression): IrExpr => {
// `opts as dns.LookupOneOptions` over a checked-dynamic value (the
// overload-satisfying cast of a pass-through lookup): the cast changes
// no value, so the options reach the runtime as they are.
let inner = node;
while (ts.isAsExpression(inner) || ts.isParenthesizedExpression(inner))
inner = inner.expression;
if (inner !== node && lowerer.mapTypeOf(lowerer.typeOf(inner))?.kind === "dyn")
return lowerer.lowerExpr(inner);
return lowerer.coerceToExpected(lowerer.lowerExpr(node), DYN);
};
// A callback whose second parameter is typed (string, LookupAddress[])
// cannot take the undefined Node passes after an error.
const typedResult = (node: ts.Expression): IrExpr => {
@@ -29,7 +29,8 @@
import * as ts from "../ts7/adapter.js";
import type { Lowerer } from "./lowerer.js";
import { locOf } from "../program.js";
import { F64, type IrExpr, STRING } from "../../ir/ir.js";
import { BOOL, F64, type IrExpr, STRING, UNDEFINED_T } from "../../ir/ir.js";
import { nodeThrowExpr } from "../../ir/build.js";
/** The member's source-name text (identifiers and string-literal names —
* the only name forms tsc allows on enum members). */
@@ -182,6 +183,15 @@ function lowerEnumReverseRead(
// existence tracking; nothing needs it — fence through the generic path.
if (decls.some((d) => isAmbientEnumDecl(d))) return null;
const idx = foldConstIndex(lowerer, key);
const keyType = lowerer.typeOf(key);
if (
idx === null &&
((keyType.flags & ts.TypeFlags.StringLike) !== 0 ||
(keyType.isUnionType() &&
ts.constituentTypes(keyType).every((t) => (t.flags & ts.TypeFlags.StringLike) !== 0)))
) {
return lowerEnumKeyRead(lowerer, expr, decls, key);
}
if (idx === null) {
lowerer.unsupported(
"SC1090",
@@ -206,6 +216,109 @@ function lowerEnumReverseRead(
return { kind: "strLit", value: name, type: STRING, loc };
}
/** Object.prototype members every enum object inherits: a runtime key
* naming one reads a function, which the member value types cannot hold. */
const OBJECT_PROTOTYPE_KEYS = new Set([
"__defineGetter__",
"__defineSetter__",
"__lookupGetter__",
"__lookupSetter__",
"__proto__",
"constructor",
"hasOwnProperty",
"isPrototypeOf",
"propertyIsEnumerable",
"toLocaleString",
"toString",
"valueOf",
]);
/** `E[key]` with a RUNTIME string key (`Color[name as keyof typeof
* Color]` — the name-to-value lookup): the key evaluates once and is
* compared against every member NAME, each hit answering that member's
* constant, exactly the forward entries tsc's emit stores. A key naming no
* member is Node's undefined, so the read carries an undefined arm. Keys
* Node would answer from elsewhere on the object throw a named runtime
* refusal instead of a wrong value: a numeric member's reverse entry (its
* value spelled as a string — Node answers the member NAME) and the
* inherited Object.prototype members. */
function lowerEnumKeyRead(
lowerer: Lowerer,
expr: ts.ElementAccessExpression,
decls: readonly ts.EnumDeclaration[],
key: ts.Expression,
): IrExpr {
const loc = locOf(expr);
const enumName = decls[0]!.name.text;
const valueType = lowerer.mapTypeOf(lowerer.typeOf(expr));
if (valueType === null) lowerer.badType(expr, lowerer.typeOf(expr));
const resultType = lowerer.withUndefinedArm(valueType);
const keyValue = lowerer.coerceToExpected(lowerer.lowerExpr(key), STRING);
const keyLocal = lowerer.declareHiddenLocal("%enumKey", STRING);
const keyRef: IrExpr = { kind: "varRef", localId: keyLocal.id, type: STRING, loc };
const matches = (text: string): IrExpr => ({
kind: "strEq",
negated: false,
left: keyRef,
right: { kind: "strLit", value: text, type: STRING, loc },
type: BOOL,
loc,
});
const refusal = (what: string): IrExpr =>
nodeThrowExpr(
0,
"SC1090",
`${what} through a runtime key ('${enumName}[key]') is not supported yet`,
resultType,
loc,
);
const arms: { cond: IrExpr; value: IrExpr }[] = [];
const names = new Set<string>();
const reverse = new Set<string>();
for (const d of decls) {
for (const member of d.members.nodes) {
const name = memberNameText(member);
const constant = lowerEnumMemberRead(lowerer, expr, member);
if (constant === null)
lowerer.unsupported("SC1090", expr, `'${enumName}[key]' over this enum`);
if (!names.has(name)) {
names.add(name);
arms.push({ cond: matches(name), value: lowerer.coerceToExpected(constant, resultType) });
}
const value = lowerer.checker.getConstantValue(member);
if (typeof value === "number") reverse.add(String(value));
}
}
for (const text of reverse) {
if (names.has(text)) continue;
arms.push({ cond: matches(text), value: refusal("enum reverse lookups") });
}
for (const text of OBJECT_PROTOTYPE_KEYS) {
if (names.has(text) || reverse.has(text)) continue;
arms.push({ cond: matches(text), value: refusal("inherited enum object members") });
}
let result: IrExpr = { kind: "unitLit", unit: "undefined", type: UNDEFINED_T, loc };
result = lowerer.coerceToExpected(result, resultType);
for (let i = arms.length - 1; i >= 0; i--) {
const arm = arms[i]!;
result = {
kind: "ternary",
cond: arm.cond,
then: arm.value,
else_: result,
type: resultType,
loc,
};
}
return {
kind: "seqExpr",
stmts: [{ kind: "varDecl", localId: keyLocal.id, init: keyValue, loc }],
result,
type: resultType,
loc,
};
}
/** A compile-time-constant NUMERIC index: a numeric literal, its negation,
* or an enum member read whose constant is a number. */
function foldConstIndex(lowerer: Lowerer, e: ts.Expression): number | null {
@@ -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,
@@ -84,6 +91,8 @@ import { lowerElementCompoundParts } from "./expressions/element-access.js";
export {
DEFERRED_READ_MESSAGE,
abstractPropertyDeclOf,
builtinFunctionValue,
builtinGlobalValue,
fieldGetExpr,
fieldTarget,
isMatchSliceType,
@@ -92,6 +101,7 @@ export {
lowerIntrinsicProperty,
lowerUnionProperty,
matchResultNamedGroupsOf,
primitiveConstructorOr,
} from "./expressions/property-access.js";
export {
lowerAsExpression,
@@ -2057,6 +2067,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,
@@ -2588,6 +2694,24 @@ export function symbolFieldTarget(
};
}
/** `return Promise.reject(reason)` in an async function: the checker's
* context is the awaited return type (or its union with PromiseLike), not
* a promise, but the async function adopts the returned promise, so the
* promise of its own result type is the honest type. Null elsewhere. */
function asyncReturnPromise(lowerer: Lowerer, call: ts.CallExpression): IrType | null {
if (lowerer.ctx.isAsync !== true || lowerer.ctx.generator) return null;
let node: ts.Node = call;
while (ts.isParenthesizedExpression(node.parent)) node = node.parent;
const parent = node.parent;
const returned =
(ts.isReturnStatement(parent) && parent.expression === node) ||
(ts.isArrowFunction(parent) && parent.body === node);
if (!returned) return null;
const ret = lowerer.ctx.returnType;
if (ret.kind === "void" || ret.kind === "promise") return null;
return { kind: "promise", inner: ret };
}
/** `Promise.reject(reason)` on THE Promise global: a pre-rejected
* promise. The reason is pinned to the Error hierarchy (the executor
* reject parameter's contract — rejection payloads share the
@@ -2619,7 +2743,9 @@ export function lowerPromiseRejectCall(
// A maybe-promise context (`return Promise.reject(e)` from a function
// returning `T | Promise<T>`) names its one promise arm.
const maybePromise = contextual ? maybePromiseUnionOf(lowerer, contextual) : null;
const type = maybePromise ? maybePromise.promise : contextual;
const type = maybePromise
? maybePromise.promise
: (asyncReturnPromise(lowerer, call) ?? contextual);
const reasonNode = call.arguments.nodes[0]!;
// A CHECKED-DYNAMIC reason (`Promise.reject(value)` where value rode
// an untyped binding — the tracingChannel suite's shape): the checked-dynamic tree
@@ -21,6 +21,7 @@ import {
type SrcLoc,
canConvertToDyn,
canDynCheckTo,
CLASS_FIELD_ATTRIBUTES_PREFIX,
classDynViewSupported,
DYN_CLASS_PROPERTIES,
isClassOwnEnumerableFieldName,
@@ -500,12 +501,16 @@ function classInspectsThroughView(lowerer: Lowerer, info: ClassInfo | undefined)
);
}
/** Whether a class holds properties added outside its declared layout, which
* only its checked-dynamic view can list. Decided after lowering, when the
/** Whether a class holds properties added outside its declared layout, or
* fields Object.defineProperty can make non-enumerable, which only its
* checked-dynamic view lists as Node does. Decided after lowering, when the
* class has its final fields. */
function classInspectsAddedProperties(lowerer: Lowerer, info: ClassInfo): boolean {
return (
info.def.fields.some((field) => field.name === DYN_CLASS_PROPERTIES) &&
info.def.fields.some(
(field) =>
field.name === DYN_CLASS_PROPERTIES || field.name.startsWith(CLASS_FIELD_ATTRIBUTES_PREFIX),
) &&
classDynViewSupported(
info.def.fields,
(id) => lowerer.shapes.get(id),
@@ -154,7 +154,12 @@ function mockWrapperFactory(
const { fn, call, calls, once, onceEntry, result, args } = mockContextFields(lowerer, ctxType)!;
const impl = `${name}.impl`;
const ctx = () => varRef("ctx.0", ctxType, loc);
// A checked-dynamic rest function (mock.fn()'s default type) takes its
// arguments as one trailing dyn array, recorded as the call's arguments
// and spread into the implementation.
const dynRest = fn.rest === true && fn.restAbi === undefined;
const params = fn.params.map((type, i) => ({ localId: `p${i}.0`, name: `p${i}`, type }));
if (dynRest) params.push({ localId: "rest.0", name: "args", type: DYN });
const paramRefs = () => params.map((p) => varRef(p.localId, p.type, loc));
const argumentsValue = (): IrExpr =>
fn.rest
@@ -219,13 +224,23 @@ function mockWrapperFactory(
loc,
};
};
const invoke: IrExpr = {
kind: "callValue",
callee: varRef("f.0", fn, loc),
args: paramRefs(),
type: fn.ret,
loc,
};
const invoke: IrExpr = dynRest
? {
kind: "dynCall",
callee: { kind: "dynFrom", value: varRef("f.0", fn, loc), type: DYN, loc },
calleeName: "implementation",
args: paramRefs(),
spreads: [{ arg: 0, what: "args" }],
type: DYN,
loc,
}
: {
kind: "callValue",
callee: varRef("f.0", fn, loc),
args: paramRefs(),
type: fn.ret,
loc,
};
const tryBody: IrStmt[] = voidReturn
? [
{ kind: "exprStmt", expr: invoke, loc },
@@ -629,7 +644,37 @@ function requireUndefinedResultArm(
}
}
/** mock.fn(original, implementation?) and t.mock.fn(...). */
/** `%mock.noop.N`: mock.fn()'s original, Node's `function () {}` — it
* returns undefined. Null when the function type's return type cannot hold
* undefined. */
function mockNoopOriginal(
lowerer: Lowerer,
ctxType: IrType,
fn: FuncType,
loc: SrcLoc,
): IrExpr | null {
const voidReturn = fn.ret.kind === "void" || fn.ret.kind === "undefinedT";
const undefinedValue = voidReturn ? null : lowerer.wrappedUndefined(fn.ret, loc);
if (!voidReturn && !undefinedValue) return null;
const name = liftOnce(lowerer, ctxType, "noop", (name) => {
const params = fn.params.map((type, i) => ({ localId: `p${i}.0`, name: `p${i}`, type }));
if (fn.rest === true && fn.restAbi === undefined)
params.push({ localId: "rest.0", name: "args", type: DYN });
lowerer.liftedFns.push({
name,
params,
returnType: fn.ret,
locals: params.map((p) => local(p.localId, p.name, p.type)),
body: [{ kind: "return", value: undefinedValue, loc }],
loc,
});
});
return { kind: "closure", fnName: name, captures: [], type: fn, loc };
}
/** mock.fn(original?, implementation?) and t.mock.fn(...). Without an
* original, the mock's original and implementation are a function that
* returns undefined, as in Node. */
export function lowerMockFn(
lowerer: Lowerer,
call: ts.CallExpression,
@@ -658,11 +703,19 @@ export function lowerMockFn(
const { fn } = fields;
requireUndefinedResultArm(lowerer, fields, call, what);
const args = call.arguments.nodes;
if (args.length === 0 || args.length > 2 || args.some(ts.isSpreadElement)) {
if (args.length > 2 || args.some(ts.isSpreadElement)) {
lowerer.noLowering(
`${what} with ${args.length} arguments`,
call,
"the supported forms are mock.fn(original) and mock.fn(original, implementation); mock.fn() and mock options have no lowering",
"the supported forms are mock.fn(), mock.fn(original) and mock.fn(original, implementation); mock options have no lowering",
);
}
const noop = args.length === 0 ? mockNoopOriginal(lowerer, ctxType!, fn, loc) : null;
if (args.length === 0 && !noop) {
lowerer.noLowering(
`${what}() of a function returning '${lowerer.fmt(fn.ret)}'`,
call,
"mock.fn() without an original returns undefined: pass an original, or use a function type whose return type includes undefined",
);
}
const stmts: IrStmt[] = [];
@@ -670,7 +723,7 @@ export function lowerMockFn(
stmts.push({
kind: "varDecl",
localId: originalLocal.id,
init: lowerer.lowerExprExpecting(args[0]!, fn),
init: noop ?? lowerer.lowerExprExpecting(args[0]!, fn),
loc,
});
const implementation =
@@ -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",
@@ -1,3 +1,4 @@
import { declaredMemberOf } from "./expressions/property-access.js";
import { hostsAll } from "./expressions/hosted-narrowing.js";
import {
matchAllRowsReadByElements,
@@ -16,7 +17,7 @@ import { InternalCompilerError } from "../../errors.js";
* flow (if/while/for/for-of/do, switch, try/catch, abrupt completions),
* explicit resource management, and blocked-binding poisoning. */
import * as ts from "../ts7/adapter.js";
import { processDataMemberValue } from "./builtins/process.js";
import { processDataMemberValue, programReadsExitCode } from "./builtins/process.js";
import { requireInitFlagStmt } from "./require-initialization.js";
import { isJsonRequireDecl } from "./json-require.js";
import { bindingSource } from "../binding-source.js";
@@ -32,6 +33,7 @@ import {
import {
cjsExportMemberWriteGlobalOf,
isCjsExportsIdentifier,
isCjsModuleExports,
isFreshExportsReset,
} from "./cjs-exports-object.js";
import { isDeadTscHelperDecl, tscInteropBindingOfDecl } from "./cjs-tsc-interop.js";
@@ -87,11 +89,11 @@ import {
isCjsJsFile,
isEsModuleStamp,
isJsSourceFile,
isNodeEsmFile,
locOf,
requireEarlyReference,
requireSpecOf,
} from "../program.js";
import { isStrictCode } from "./strict-mode.js";
import {
COMPOUND_ASSIGN_OPS,
type CompoundOp,
@@ -195,6 +197,7 @@ import {
import { globalSymbolKey } from "./expressions/global-symbols.js";
import { lowerShortCircuitAssignment } from "./expressions/nullish-assignment.js";
import {
builtinGlobalValue,
jsHoldsDynObject,
lowerEnvironmentKey,
lowerNativeFunctionAssignment,
@@ -223,6 +226,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[];
@@ -3773,6 +3777,9 @@ function stdlibGlobalTokenDestructure(
const canonical = member.name === "global" ? "globalThis" : member.name;
token = `[builtin ${canonical}]`;
alias = canonical;
// Builtin constructors read as their interned function values, the
// same values the bare and `globalThis.X` spellings read.
value = builtinGlobalValue(canonical, locOf(el), true);
} else if (globalName === "console" && !CONSOLE_CALL_MEMBERS.has(propName)) {
token = `[builtin console.${propName}]`;
} else if (TOKEN_OPAQUE_GLOBALS.has(globalName)) {
@@ -3816,6 +3823,10 @@ function stdlibGlobalTokenDestructure(
const out: IrStmt[] = [];
for (const b of binds) {
const loc = locOf(b.name);
if (b.value !== undefined && b.alias !== null) {
const symbol = lowerer.checker.getSymbolAtLocation(b.name);
if (symbol) lowerer.stdlibGlobalAliases.set(symbol, b.alias);
}
if (b.value !== undefined) {
if (b.g !== undefined) {
out.push({
@@ -6176,35 +6187,6 @@ export function lowerTry(lowerer: Lowerer, stmt: ts.TryStatement): IrStmt {
};
}
function hasUseStrictDirective(statements: readonly ts.Statement[]): boolean {
for (const statement of statements) {
if (!ts.isExpressionStatement(statement) || !ts.isStringLiteral(statement.expression))
return false;
if (statement.expression.text === "use strict") return true;
}
return false;
}
function isStrictDelete(node: ts.DeleteExpression): boolean {
for (let parent: ts.Node | undefined = node.parent; parent; parent = parent.parent) {
if (ts.isClassDeclaration(parent) || ts.isClassExpression(parent)) return true;
if (
ts.isFunctionLike(parent) &&
parent.body &&
ts.isBlock(parent.body) &&
hasUseStrictDirective(parent.body.statements.nodes)
)
return true;
if (ts.isSourceFile(parent)) {
return (
hasUseStrictDirective(parent.statements.nodes) ||
(!isCjsJsFile(parent) && (isNodeEsmFile(parent) || ts.isExternalModule(parent)))
);
}
}
return false;
}
/** Statement-position `delete`: process.env keys → process.envUnset
* (unsetenv), pure `Record<string, T>` keys → recordKeyDelete (the
* overflow Map delete), declared OPTIONAL fields → the field's ABSENT
@@ -6320,7 +6302,7 @@ function lowerDeleteStatement(lowerer: Lowerer, expr: ts.DeleteExpression): IrSt
obj = lowerer.coerceToExpected(obj, DYN);
}
if (obj.type.kind === "dyn") {
const strict = { kind: "boolLit", value: isStrictDelete(expr), type: BOOL, loc } as const;
const strict = { kind: "boolLit", value: isStrictCode(expr), type: BOOL, loc } as const;
if (ts.isElementAccessExpression(target)) {
const key = lowerer.lowerExprExpecting(target.argumentExpression, DYN);
return {
@@ -6939,6 +6921,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) };
@@ -7306,9 +7307,12 @@ export function lowerExprStatement(lowerer: Lowerer, expr: ts.Expression): IrStm
) {
const loc = locOf(expr);
const value = lowerer.lowerExprExpecting(expr.right, F64);
const fn = programReadsExitCode(lowerer)
? "process.setExitCodeTracked"
: "process.setExitCode";
return {
kind: "exprStmt",
expr: { kind: "libCall", fn: "process.setExitCode", args: [value], type: VOID, loc },
expr: { kind: "libCall", fn, args: [value], type: VOID, loc },
loc,
};
}
@@ -7501,6 +7505,31 @@ export function lowerExprStatement(lowerer: Lowerer, expr: ts.Expression): IrStm
const recvIr = lowerer.mapTypeOf(lowerer.typeOf(expr.left.expression));
if (recvIr?.kind === "record") {
const shape = lowerer.shapes.get(recvIr.shapeId);
if (
shape?.indexValue &&
shape.fields.length === 0 &&
declaredMemberOf(lowerer, expr.left.expression, expr.left.name.text)
) {
// A declared member of a literal stored as a pure index-signature
// record (dictSpreadLiteralShape): a keyed write of that key.
const loc = locOf(expr);
const obj = lowerer.lowerExpr(expr.left.expression);
if (obj.type.kind === "record") {
const value = lowerer.intoIndexValueSlot(
lowerer.lowerExprExpecting(expr.right, shape.indexValue),
shape.indexValue,
expr.right,
);
return {
kind: "recordKeySet",
obj,
shapeId: obj.type.shapeId,
key: { kind: "strLit", value: expr.left.name.text, type: STRING, loc },
value,
loc,
};
}
}
if (
shape?.indexValue &&
!shape.fields.some(
@@ -9175,6 +9204,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);
@@ -999,6 +999,15 @@ export function lowerStreamNew(lowerer: Lowerer, expr: ts.NewExpression, info: C
};
}
/** True when a value of Node's argument type `passed` widens implicitly
* into the declared parameter type `declared` (one of its union arms, or a
* sub-union of it). */
function widensInto(lowerer: Lowerer, passed: IrType, declared: IrType, loc: SrcLoc): boolean {
if (declared.kind !== "union") return false;
const probe: IrExpr = { kind: "varRef", localId: "%probe", type: passed, loc };
return typeEquals(lowerer.coerceToExpected(probe, declared).type, declared);
}
/* ── user subclasses (`extends Readable`, the underscore-override form) ── */
/** The wrapper closure binding one overridden underscore method as the
@@ -1075,10 +1084,17 @@ function streamMethodWrapper(
);
}
} else if (!typeEquals(got.type, want)) {
// A declared supertype of what Node passes (`chunk: Buffer | string`)
// is sound: the wrapper takes Node's value and widens it into the
// declared parameter.
if (widensInto(lowerer, want, got.type, loc)) {
paramTypes.push(want);
continue;
}
lowerer.noLowering(
`a '${methodName}' method whose parameter ${i} is '${lowerer.fmt(got.type)}' where Node passes '${lowerer.fmt(want)}'`,
blame,
"annotate the parameter with the Node signature's type (chunks are Buffers here)",
"annotate the parameter with the Node signature's type or a supertype of it (chunks are Buffers here)",
);
}
paramTypes.push(got.type);
@@ -1094,7 +1110,11 @@ function streamMethodWrapper(
for (let i = 0; i < paramTypes.length; i++) {
const local = lowerer.declareHiddenLocal(`a${i}`, paramTypes[i]!);
params.push({ localId: local.id, name: local.name, type: paramTypes[i]! });
argRefs.push({ kind: "varRef", localId: local.id, type: paramTypes[i]!, loc });
const arg: IrExpr = { kind: "varRef", localId: local.id, type: paramTypes[i]!, loc };
const declaredType = declared[i]!.type;
argRefs.push(
typeEquals(arg.type, declaredType) ? arg : lowerer.coerceToExpected(arg, declaredType),
);
}
const thisRef: IrExpr = { kind: "varRef", localId: thisLocal.id, type: thisType, loc };
let call: IrExpr;
@@ -3654,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,
@@ -3712,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,
@@ -3978,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
);
}
@@ -117,6 +117,7 @@ import { InternalCompilerError } from "../../errors.js";
import { defaultAfterUndefined, lowerStaticallyUndefinedArgument } from "./optional-arguments.js";
import { type ProtocolDispatch } from "./class-protocol-dispatch.js";
import { ClassDynamicDispatch, trackClassFieldCreation } from "./class-dynamic-dispatch.js";
import { guardClassAttributeWrites } from "./class-attributes.js";
import { ClassProtocols } from "./class-protocols.js";
import { earlyReadVarSymbols } from "./var-hoisting.js";
import { recordTextCodecClass } from "../../ir/ir.js";
@@ -1969,6 +1970,8 @@ export class Lowerer {
readonly symbolFieldIdentities = new Map<string, ts.Symbol[]>();
readonly httpClientFnBindings = new Map<ts.Symbol, HttpClientFnBinding>();
streamPropMutatedSyms: Set<ts.Symbol> | null = null;
/** Whether some source reads process.exitCode (processReadsExitCode). */
readsExitCode: boolean | null = null;
requestInitPropMutatedSyms: Set<ts.Symbol> | null = null;
emitterEventTable: Map<string, EventSig> | null = null;
emitterComputedPatterns: ComputedEventPattern[] = [];
@@ -2571,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. */
@@ -2650,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>();
@@ -6934,6 +6945,7 @@ export class Lowerer {
finalizeClassMethodValues(this, functions);
finalizePrivateBrands(this, functions);
trackClassFieldCreation(this, functions);
guardClassAttributeWrites(this, functions);
// Globals typed by a class that never REGISTERED (a JS class whose
// collection fenced — Symbol-keyed fields, an unsupported base): the
@@ -8645,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) {
@@ -9019,6 +9042,10 @@ export class Lowerer {
return this.applyWidthLift(lift, narrowed, expected, expr.loc);
}
}
if (expr.type.kind === "union" && expected.kind === "record") {
const lifted = unionArmsWidthLift(this, expr, expected);
if (lifted) return lifted;
}
if (!typeEquals(expr.type, expected)) {
const w = this.widthCoerce(expr, expected);
if (w) return w;
@@ -9356,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
@@ -10093,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",
@@ -13092,3 +13129,180 @@ export class Lowerer {
return lowerStdlibMethodCall(this, call, access);
}
}
/** A union of record layouts flowing into one record slot: a function
* returning differently-shaped object literals (`{ ok: false }` and
* `{ ok: true, size }`, whose union the checker normalizes to arms with
* `size?: undefined`) into its declared result type. Each record arm
* width-lifts into the slot on its own tag; unit arms take the stranded
* TypeError (the checker excluded them). Null when some record arm does
* not lift, or when there is a non-record, non-unit arm. */
function unionArmsWidthLift(
lowerer: Lowerer,
expr: IrExpr,
expected: IrType & { kind: "record" },
): IrExpr | null {
if (expr.type.kind !== "union") return null;
const unionId = expr.type.unionId;
const arms = lowerer.unions.get(unionId)?.arms ?? [];
const lifts: (WidthLift | null)[] = [];
let records = 0;
for (const arm of arms) {
if (isUnitType(arm)) {
lifts.push(null);
continue;
}
if (arm.kind !== "record") return null;
const lift = lowerer.widthLiftPlan(arm, expected);
if (!lift) return null;
lifts.push(lift);
records++;
}
if (records < 2) return null;
const loc = expr.loc;
const local = lowerer.declareHiddenLocal("%unionLift", expr.type);
const ref = (): IrExpr => ({ kind: "varRef", localId: local.id, type: expr.type, loc });
let result: IrExpr | null = null;
for (let tag = arms.length - 1; tag >= 0; tag--) {
const lift = lifts[tag];
const arm = arms[tag]!;
const branch: IrExpr = lift
? lowerer.applyWidthLift(
lift,
{ kind: "unionNarrow", unionId, tag, value: ref(), type: arm, loc },
expected,
loc,
)
: nodeThrowExpr(
1,
"",
`${arm.kind === "nullT" ? "null" : "undefined"} is not representable in a '${lowerer.fmt(expected)}' slot (a value narrowed or asserted past the type still held it)`,
expected,
loc,
);
result =
result === null
? branch
: {
kind: "ternary",
cond: {
kind: "unionIsTag",
unionId,
tag,
negated: false,
value: ref(),
type: BOOL,
loc,
},
then: branch,
else_: result,
type: expected,
loc,
};
}
return {
kind: "seqExpr",
stmts: [{ kind: "varDecl", localId: local.id, init: expr, loc }],
result: result!,
type: expected,
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;
}
@@ -0,0 +1,34 @@
import * as ts from "../ts7/adapter.js";
import { isCjsJsFile, isNodeEsmFile } from "../program.js";
function hasUseStrictDirective(statements: readonly ts.Statement[]): boolean {
for (const statement of statements) {
if (!ts.isExpressionStatement(statement) || !ts.isStringLiteral(statement.expression))
return false;
if (statement.expression.text === "use strict") return true;
}
return false;
}
/** Whether `node` runs in strict mode code: inside a class body, a function
* with a "use strict" directive, a module, or a script that starts with
* "use strict". CommonJS JavaScript is sloppy otherwise. */
export function isStrictCode(node: ts.Node): boolean {
for (let parent: ts.Node | undefined = node.parent; parent; parent = parent.parent) {
if (ts.isClassDeclaration(parent) || ts.isClassExpression(parent)) return true;
if (
ts.isFunctionLike(parent) &&
parent.body &&
ts.isBlock(parent.body) &&
hasUseStrictDirective(parent.body.statements.nodes)
)
return true;
if (ts.isSourceFile(parent)) {
return (
hasUseStrictDirective(parent.statements.nodes) ||
(!isCjsJsFile(parent) && (isNodeEsmFile(parent) || ts.isExternalModule(parent)))
);
}
}
return false;
}
@@ -2221,14 +2221,22 @@ export const AMBIENT_SURFACE_FNS: readonly AmbientSurfaceRow[] = [
kind: "stdlib",
name: "Date.parse",
fns: ["date.parse"],
note: "one date string, using the bounded parser shared with new Date(dateString).getTime()",
note: "one date string, using V8's date parser shared with new Date(dateString)",
},
{
id: "stdlib.date.constructor",
kind: "stdlib",
name: "Date constructor",
fns: ["date.newNow", "date.newMs", "date.newString", "date.nativeNew"],
note: "zero arguments, or one milliseconds/date-string argument; values are the read-only TimeClip scalar slice",
fns: [
"date.newNow",
"date.newMs",
"date.newString",
"date.nativeNew",
"date.newLocal",
"date.nativeNewFields",
"date.nativeNewValue",
],
note: "zero arguments, one milliseconds/date-string argument, or local-time year/month fields; values are the read-only TimeClip scalar slice",
},
{
id: "stdlib.date.UTC",
@@ -2656,8 +2664,8 @@ export const AMBIENT_SURFACE_FNS: readonly AmbientSurfaceRow[] = [
id: "node-builtin.process.exitCode",
kind: "node-builtin",
name: "process.exitCode",
fns: ["process.setExitCode"],
note: "numeric writes in statement position set the implicit exit status; process.exit() reads it",
fns: ["process.setExitCode", "process.setExitCodeTracked", "process.hasExitCode"],
note: "numeric writes in statement position set the implicit exit status; reads answer the assigned code or undefined; process.exit() reads it",
},
// ── the tls CA store (lowerTlsCaCall / lowerTlsRootCertificates): the
// host's trust anchors, read and replaced. Dedicated paths, and
@@ -2969,7 +2977,7 @@ export const BUILTIN_MODULE_FENCE_HINTS: Record<
},
util: {
promisify:
"the lowered shapes are const bindings over child_process.execFile, child_process.exec, setTimeout, setImmediate, stream.finished, stream.pipeline, the zlib callback one-shots, the crypto callback functions, dns.lookup, dns.lookupService and the fs callback functions with an fs/promises counterpart; call the bound function directly",
"the lowered shapes are const bindings over child_process.execFile, child_process.exec, setTimeout, setImmediate, stream.finished, stream.pipeline, the zlib callback one-shots, the crypto callback functions, dns.lookup, dns.lookupService and the fs callback functions with an fs/promises counterpart, plus typed callback-last function values whose callback takes (error?: Error | null, value?); call the bound function directly",
},
"stream/consumers": {
blob:
@@ -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;
}
@@ -9,6 +9,7 @@ export type WidthLift =
| { how: "discriminantWrap" }
| { how: "discriminantRoute" }
| { how: "retag" }
| { how: "unitRetag" }
| { how: "liftWrap"; tag: number; arm: IrType }
| { how: "width" }
| { how: "unionWidth" }
+13 -6
View File
@@ -12,10 +12,11 @@
* object; empty for mock.fn
*
* A MockFunctionCall<F> is { arguments, error, result, this }: the
* arguments as a tuple of F's parameters, the result as F's return type or
* undefined (a checked-dynamic value for functions returning void or
* undefined, since a record field cannot have a unit type), and error and
* this as checked-dynamic values. */
* arguments as a tuple of F's parameters (a checked-dynamic array for
* mock.fn()'s `(...args: any[]) => undefined`), the result as F's return
* type or undefined (a checked-dynamic value for functions returning void
* or undefined, since a record field cannot have a unit type), and error
* and this as checked-dynamic values. */
import { DYN, F64, NULL_T, UNDEFINED_T, VOID, typeKey, type IrType } from "../ir/ir.js";
import type { TypeMapperCtx } from "./type-mapper.js";
@@ -34,11 +35,17 @@ function orUndefined(t: IrType, reg: MockShapeRegistries): IrType {
}
/** The arguments type of a call record: a tuple of the parameters, or the
* rest array itself for a function whose only parameter is a rest array.
* Null for other rest shapes. A function without parameters records the
* rest array itself for a function whose only parameter is a rest array,
* or a checked-dynamic array for a function returning nothing whose only
* parameter is a checked-dynamic rest (mock.fn()'s default, `(...args:
* any[]) => undefined`). Null for other rest shapes. A function without parameters records the
* empty tuple, which maps to an array of the unit-only union, as
* type-mapper.ts maps `[]`. */
function mockArgumentsType(fn: IrType & { kind: "func" }, reg: MockShapeRegistries): IrType | null {
if (fn.rest && fn.restAbi === undefined) {
const returnsNothing = fn.ret.kind === "void" || fn.ret.kind === "undefinedT";
return fn.params.length === 0 && returnsNothing ? DYN : null;
}
if (fn.rest) {
if (fn.params.length !== 1 || fn.params[0]!.kind !== "array") return null;
return fn.params[0]!;
@@ -0,0 +1,318 @@
import { spawnSync } from "node:child_process";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { basename, join } from "node:path";
import { afterAll, expect, test } from "vitest";
import { nodeFrontendServices } from "./services-node.js";
import { rewriteBundlerCjsExports } from "./npm-static-rewrite.js";
import type { BundledChunkSplit } from "./npm-static-bundled-chunks.js";
const keyedHelper = `var __getOwnPropNames = Object.getOwnPropertyNames;
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
`;
const dirs: string[] = [];
afterAll(() => {
for (const dir of dirs) rmSync(dir, { recursive: true, force: true });
});
function split(source: string, file = "/pkg/dist/index.js") {
return nodeFrontendServices().splitCjsChunks(source, file);
}
function run(file: string) {
const result = spawnSync(process.execPath, [file], { encoding: "utf8" });
return { status: result.status, stdout: result.stdout, stderr: result.stderr };
}
/** Runs the original bundle and its split modules side by side. */
function expectSameBehavior(source: string): BundledChunkSplit {
const dir = mkdtempSync(join(tmpdir(), "scriptc-chunks-"));
dirs.push(dir);
const original = join(dir, "original.js");
writeFileSync(original, source);
const bundle = join(dir, "index.js");
const result = split(source, bundle);
expect(result).not.toBeNull();
expect(result).not.toHaveProperty("degrade");
const answer = result as BundledChunkSplit;
writeFileSync(bundle, answer.text);
for (const chunk of answer.chunks) writeFileSync(chunk.path, chunk.source);
// Respelled calls and blanked declarations keep the line structure.
expect(answer.text.split("\n")).toHaveLength(source.split("\n").length);
const oracle = run(original);
expect(oracle.status).toBe(0);
expect(run(bundle)).toEqual(oracle);
return answer;
}
test("chunks run once, at their first require, with shared module instances", () => {
const answer = expectSameBehavior(`"use strict";
${keyedHelper}
var require_b = __commonJS({
"b.js"(exports2, module2) {
console.log("b init");
module2.exports = { n: 1 };
}
});
var require_a = __commonJS({
"a.js"(exports2) {
console.log("a init");
var b = require_b();
exports2.value = b.n + 1;
exports2.keys = Object.keys({ exports2 });
}
});
console.log("start");
console.log(require_a().value, require_a().value, require_b().n, require_a().keys);
`);
expect(answer.chunks.map((c) => basename(c.path))).toEqual([
"index.js.require_b.cjs",
"index.js.require_a.cjs",
]);
expect(answer.text).not.toContain("require_a()");
});
test("the arrow helper form and minified spellings split the same way", () => {
expectSameBehavior(
`var __commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);` +
`var require_x=__commonJS((exports,module)=>{module.exports={v:"x"}});` +
`console.log(require_x().v,require_x()===require_x());`,
);
});
test("esbuild 0.11's Object.keys spelling is recognized", () => {
expectSameBehavior(`var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[Object.keys(cb)[0]])((mod = {exports: {}}).exports, mod), mod.exports;
};
var require_y = __commonJS({
"y.js"(exports) {
exports.y = 3;
}
});
console.log(require_y().y);
`);
});
test("pure helpers a chunk reads travel with it", () => {
const answer = expectSameBehavior(`${keyedHelper}var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var require_named = __commonJS({
"named.js"(exports2, module2) {
module2.exports = __name(function () {}, "renamed");
}
});
console.log(require_named().name);
`);
const chunk = answer.chunks[0]!.source;
expect(chunk).toContain("var __name =");
expect(chunk).toContain("var __defProp = Object.defineProperty;");
});
test("a helper travels with a chunk whose nested scopes declare its name", () => {
const answer = expectSameBehavior(`${keyedHelper}function label(n) {
return "label " + n;
}
function wrap(n) {
function inner() {
var label = "inner";
return label;
}
return label(n) + " " + inner();
}
var require_e = __commonJS({
"e.js"(exports2, module2) {
function nested() {
var label = "nested";
return label;
}
var seen = [];
for (let label of ["loop"]) seen.push(label);
try {
throw "caught";
} catch (label) {
seen.push(label);
}
{
const label = "block";
seen.push(label);
}
module2.exports = { outer: label(1), indirect: (0, label)(3), wrapped: wrap(2), nested: nested(), seen };
}
});
var e = require_e();
console.log(e.outer, e.indirect, e.wrapped, e.nested, e.seen.join(","));
`);
const chunk = answer.chunks[0]!.source;
expect(chunk).toContain("function label(n)");
expect(chunk).toContain("function wrap(n)");
});
test("a named function expression that only calls itself travels with a chunk", () => {
const answer = expectSameBehavior(`${keyedHelper}var fact = function self(n) {
return n <= 1 ? 1 : n * self(n - 1);
};
var kind = function self(self) {
return typeof self;
};
var outer = function self() {
var self = 2;
return self;
};
var require_g = __commonJS({
"g.js"(exports2, module2) {
module2.exports = [fact(5), kind(1), outer()];
}
});
console.log(require_g().join(","));
`);
const chunk = answer.chunks[0]!.source;
expect(chunk).toContain("var fact = function self(n)");
});
test("a helper a parameter default reads travels with a chunk whose body declares its name", () => {
const answer = expectSameBehavior(`${keyedHelper}var ten = function () {
return 10;
};
var add = function (n, base = ten()) {
var ten = 1;
return n + base + ten;
};
var require_g = __commonJS({
"g.js"(exports2, module2) {
module2.exports = add(1);
}
});
console.log(require_g());
`);
const chunk = answer.chunks[0]!.source;
expect(chunk).toContain("var ten = function ()");
});
test.each([
["exports it", `function tally() {}`, `module2.exports = { tally };`],
["reads its properties", `function tally() {}`, `exports2.calls = tally.calls;`],
["constructs it", `function tally() {}`, `exports2.made = new tally();`],
["stores an arrow helper", `var tally = () => 1;`, `exports2.fn = tally;`],
[
"calls a function that reads its own name as a value",
`var tally = function self() { self.n = (self.n || 0) + 1; return self.n; };`,
`exports2.count = tally();`,
],
[
"calls a function whose parameter default reads its own name",
`var tally = function self(box = self) { box.n = (box.n || 0) + 1; return box.n; };`,
`exports2.count = tally();`,
],
[
"calls a function whose parameter default reads its own name past a body var of that name",
`var tally = function self(box = self) { var self = 0; box.n = (box.n || 0) + 1; return box.n + self; };`,
`exports2.count = tally();`,
],
])("a chunk that %s keeps the package refused", (_, declaration, statement) => {
const result = split(`${keyedHelper}${declaration}
var require_f = __commonJS({
"f.js"(exports2, module2) {
${statement}
}
});
require_f();
`);
expect(result).toEqual({
degrade: expect.stringContaining(
"uses the bundle's top-level function 'tally' as a value",
) as string,
});
});
test.each([
["reads its factory's receiver", `console.log(this);`],
["reads its factory's arguments object", `console.log(arguments.length);`],
["returns from its top level", `if (exports2) return;`],
["uses its module object beyond module.exports", `console.log(module2.id);`],
["reads __filename", `console.log(__filename);`],
["rebinds its module parameters", `function f(module2) { return module2; }`],
["reads the bundle's top-level binding 'state'", `console.log(state);`],
])("a chunk that %s keeps the package refused", (reason, statement) => {
const result = split(`${keyedHelper}var state = { n: 1 };
var require_c = __commonJS({
"c.js"(exports2, module2) {
${statement}
}
});
require_c();
`);
expect(result).toEqual({ degrade: expect.stringContaining(reason) as string });
});
test("a factory used other than as a direct call keeps the package refused", () => {
const result =
split(`${keyedHelper}var require_d = __commonJS({ "d.js"(exports2) { exports2.d = 1; } });
var load = require_d;
load();
`);
expect(result).toEqual({
degrade: expect.stringContaining("used other than as a direct call") as string,
});
});
test("an unrecognized helper body keeps the package refused", () => {
const result =
split(`var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod);
var require_e = __commonJS((exports) => { exports.e = 1; });
require_e();
`);
expect(result).toEqual({ degrade: expect.stringContaining("__commonJS helper") as string });
});
test("files without chunks and ES-module bundles are left alone", () => {
expect(split("exports.x = 1;\n")).toBeNull();
expect(
split(`${keyedHelper}var require_f = __commonJS({ "f.js"(e) { e.f = 1; } });
export default require_f();
`),
).toBeNull();
});
test("an identifier-minified bundle names its lost helper names", () => {
// esbuild --minify output: the helper shapes survive, their names do not.
const result = split(
`var c=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);` +
`var x=c((t,m)=>{m.exports={v:1}});console.log(x().v);`,
);
expect(result).toEqual({ degrade: expect.stringContaining("identifier-minified") as string });
});
test("an ES-module bundle of CommonJS chunks names the chunk interop", () => {
const result = rewriteBundlerCjsExports(
`${keyedHelper}var __toESM = (mod) => mod;
var require_g = __commonJS({ "g.js"(exports) { exports.g = 1; } });
var import_g = __toESM(require_g());
export const g = import_g.g;
`,
"/pkg/dist/index.js",
);
expect(result).toEqual({
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');
});
@@ -0,0 +1,907 @@
/* Bundled CommonJS chunks: esbuild wraps every CommonJS module it bundles
* in a lazily evaluated factory,
*
* var require_x = __commonJS({ "src/x.js"(exports, module) { BODY } });
*
* and each `require_x()` runs BODY once (later calls answer the cached
* module.exports, a call during BODY answers the partial one). That is
* exactly a CommonJS module that the bundle requires at the call's
* position, so each recognized chunk becomes its own module: a virtual
* sibling file `<bundle>.<binding>.cjs` holding BODY, its module
* parameters respelled as the CommonJS globals, and every `require_x()`
* call becomes `require("./<bundle>.<binding>.cjs")`. The program then
* compiles chunks with the ordinary CommonJS machinery: evaluation at the
* require's position, the run-once module cache, export tables, and the
* __toESM interop erasure.
*
* Only shapes whose meaning is verified move: the helper must be one of
* the recognized __commonJS spellings, every reference to a factory
* binding must be a direct call, and BODY must not observe the
* difference between a factory and a module (its `this`, `arguments`,
* `__filename`, the module object beyond `module.exports`, a top-level
* return, or a binding of the bundle other than the pure helpers copied
* 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. */
text: string;
/** Virtual sibling modules, in declaration order. */
chunks: { path: string; source: string }[];
}
export interface Edit {
start: number;
end: number;
text: string;
}
const CHUNK_SHAPE_DEGRADE =
"its shipped JS bundles CommonJS modules through the __commonJS helper in a shape the " +
"recognizer cannot verify";
/** The helper a counter-suffixed bundler name spells (`__commonJS2`). */
export function helperBase(name: string): string {
return /^__[A-Za-z]+\d+$/.test(name) ? name.replace(/\d+$/, "") : name;
}
export function unparen(e: ts.Expression): ts.Expression {
while (ts.isParenthesizedExpression(e)) e = e.expression;
return e;
}
/** 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. */
export function isReference(id: ts.Identifier): boolean {
const p = id.parent;
if (p === undefined) return false;
if (ts.isPropertyAccessExpression(p)) return p.expression === id;
if (ts.isPropertyAssignment(p)) return p.initializer === id;
if (
ts.isMethodDeclaration(p) ||
ts.isPropertyDeclaration(p) ||
ts.isGetAccessorDeclaration(p) ||
ts.isSetAccessorDeclaration(p)
)
return p.name !== id;
if (ts.isBindingElement(p)) return p.initializer === id;
if (ts.isVariableDeclaration(p) || ts.isParameter(p)) return p.initializer === id;
if (
ts.isFunctionDeclaration(p) ||
ts.isFunctionExpression(p) ||
ts.isClassDeclaration(p) ||
ts.isClassExpression(p)
)
return p.name !== id;
if (ts.isLabeledStatement(p)) return p.label !== id;
if (ts.isBreakStatement(p) || ts.isContinueStatement(p)) return false;
if (ts.isMetaProperty(p)) return false;
return true;
}
/** Names a subtree declares anywhere inside it: variables (destructuring
* included), parameters, function and class names, catch bindings. */
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) => {
if (n.kind >= ts.SyntaxKind.FirstJSDocNode && n.kind <= ts.SyntaxKind.LastJSDocNode)
return "skip";
if (ts.isVariableDeclaration(n) || ts.isParameter(n) || ts.isBindingElement(n)) {
const name = n.name;
if (name !== undefined && ts.isIdentifier(name)) names.add(name.text);
} else if (
(ts.isFunctionDeclaration(n) ||
ts.isFunctionExpression(n) ||
ts.isClassDeclaration(n) ||
ts.isClassExpression(n)) &&
n.name !== undefined
)
names.add(n.name.text);
return undefined;
});
return names;
}
/** Adds the identifiers a binding name (an identifier or a destructuring
* pattern) declares. */
function addBindingNames(name: ts.BindingName, out: Set<string>): void {
if (ts.isIdentifier(name)) {
out.add(name.text);
return;
}
for (const element of name.elements.nodes) {
if (!ts.isOmittedExpression(element) && element.name !== undefined)
addBindingNames(element.name, out);
}
}
function isFunctionScope(n: ts.Node): n is ts.SignatureDeclaration {
return (
ts.isFunctionDeclaration(n) ||
ts.isFunctionExpression(n) ||
ts.isArrowFunction(n) ||
ts.isMethodDeclaration(n) ||
ts.isGetAccessorDeclaration(n) ||
ts.isSetAccessorDeclaration(n) ||
ts.isConstructorDeclaration(n)
);
}
/** The `var` names a function body declares, without entering nested
* functions. Function declarations in nested blocks count as block-scoped
* here; treating one as free only adds an unused helper copy. */
function varScopedNames(body: ts.Node): Set<string> {
const out = new Set<string>();
ts.walkPreorder(body, (n) => {
if (n !== body && (isFunctionScope(n) || ts.isClassDeclaration(n) || ts.isClassExpression(n)))
return "skip";
if (ts.isVariableDeclarationList(n) && (n.flags & ts.NodeFlags.BlockScoped) === 0) {
for (const d of n.declarations.nodes) addBindingNames(d.name, out);
}
return undefined;
});
return out;
}
/** The names a function binds for references in its parameter list
* (default values, computed keys of destructuring patterns): its
* parameters and a function expression's own name. Parameter initializers
* run in their own scope, so the body's `var`s are not visible there. */
function parameterScopeNames(scope: ts.SignatureDeclaration): Set<string> {
const out = new Set<string>();
for (const param of scope.parameters.nodes) addBindingNames(param.name, out);
if (ts.isFunctionExpression(scope) && scope.name !== undefined) out.add(scope.name.text);
return out;
}
const NO_NAMES: ReadonlySet<string> = new Set();
/** True when `node` lies inside `ancestor` (or is it). */
function within(node: ts.Node, ancestor: ts.Node): boolean {
for (let n: ts.Node | undefined = node; n !== undefined; n = n.parent)
if (n === ancestor) return true;
return false;
}
/** The names one scope node binds for the references inside it. */
function scopeNames(scope: ts.Node): Set<string> {
const out = new Set<string>();
if (isFunctionScope(scope)) {
for (const param of scope.parameters.nodes) addBindingNames(param.name, out);
if (ts.isFunctionExpression(scope) && scope.name !== undefined) out.add(scope.name.text);
if (scope.body !== undefined) for (const name of varScopedNames(scope.body)) out.add(name);
} else if (ts.isBlock(scope) || ts.isSourceFile(scope) || ts.isCaseBlock(scope)) {
const statements = ts.isCaseBlock(scope)
? scope.clauses.nodes.flatMap((clause) => clause.statements.nodes)
: scope.statements.nodes;
for (const stmt of statements) {
if ((ts.isFunctionDeclaration(stmt) || ts.isClassDeclaration(stmt)) && stmt.name)
out.add(stmt.name.text);
else if (
ts.isVariableStatement(stmt) &&
(stmt.declarationList.flags & ts.NodeFlags.BlockScoped) !== 0
) {
for (const d of stmt.declarationList.declarations.nodes) addBindingNames(d.name, out);
}
}
} else if (ts.isCatchClause(scope) && scope.variableDeclaration !== undefined) {
addBindingNames(scope.variableDeclaration.name, out);
} else if (
(ts.isForStatement(scope) || ts.isForInStatement(scope) || ts.isForOfStatement(scope)) &&
scope.initializer !== undefined &&
ts.isVariableDeclarationList(scope.initializer) &&
(scope.initializer.flags & ts.NodeFlags.BlockScoped) !== 0
) {
for (const d of scope.initializer.declarations.nodes) addBindingNames(d.name, out);
} else if (
(ts.isClassDeclaration(scope) || ts.isClassExpression(scope)) &&
scope.name !== undefined
) {
out.add(scope.name.text);
}
return out;
}
/** Resolves references against one bundle's scopes, keeping each scope's
* names for the bundle's split. */
class BundleScopes {
private readonly names = new Map<ts.Node, Set<string>>();
private readonly parameterNames = new Map<ts.Node, Set<string>>();
private of(scope: ts.Node): Set<string> {
let names = this.names.get(scope);
if (names === undefined) {
names = scopeNames(scope);
this.names.set(scope, names);
}
return names;
}
/** The names `scope` binds for a reference reached through its child
* `from`: a function's parameter list sees its parameters and own name
* but not its body's `var`s, and a computed method name sees none of
* them. */
private visible(scope: ts.Node, from: ts.Node): ReadonlySet<string> {
if (!isFunctionScope(scope) || from === scope.body) return this.of(scope);
if (from === scope.name) return NO_NAMES;
let names = this.parameterNames.get(scope);
if (names === undefined) {
names = parameterScopeNames(scope);
this.parameterNames.set(scope, names);
}
return names;
}
/** True when a scope between the reference and `root` (inclusive)
* binds its name. */
boundWithin(id: ts.Identifier, root: ts.Node): boolean {
for (let from: ts.Node = id, n = id.parent; n !== undefined; from = n, n = n.parent) {
if (this.visible(n, from).has(id.text)) return true;
if (n === root) return false;
}
return false;
}
/** True when a scope inside `root` (exclusive) binds the reference's
* name. */
boundInside(id: ts.Identifier, root: ts.Node): boolean {
for (
let from: ts.Node = id, n = id.parent;
n !== undefined && n !== root;
from = n, n = n.parent
) {
if (this.visible(n, from).has(id.text)) return true;
}
return false;
}
/** True when the reference resolves to a top-level binding of `sf`. */
topLevel(id: ts.Identifier, sf: ts.SourceFile): boolean {
for (
let from: ts.Node = id, n = id.parent;
n !== undefined && n !== sf;
from = n, n = n.parent
) {
if (this.visible(n, from).has(id.text)) return false;
}
return true;
}
}
/** Every binding reference inside a subtree. */
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)
return "skip";
if (ts.isIdentifier(n) && isReference(n)) out.push(n);
return undefined;
});
return out;
}
/** True when the reference is written (assignment target, update operand,
* loop target, delete operand). */
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)) {
return (
p.left === child &&
p.operatorToken.kind >= ts.SyntaxKind.FirstAssignment &&
p.operatorToken.kind <= ts.SyntaxKind.LastAssignment
);
}
if (ts.isPrefixUnaryExpression(p) || ts.isPostfixUnaryExpression(p)) {
return (
p.operator === ts.SyntaxKind.PlusPlusToken || p.operator === ts.SyntaxKind.MinusMinusToken
);
}
if (ts.isForInStatement(p) || ts.isForOfStatement(p)) return p.initializer === child;
if (ts.isDeleteExpression(p)) return true;
if (
!(
ts.isParenthesizedExpression(p) ||
ts.isArrayLiteralExpression(p) ||
ts.isObjectLiteralExpression(p) ||
ts.isShorthandPropertyAssignment(p) ||
ts.isPropertyAssignment(p) ||
ts.isSpreadElement(p)
)
)
return false;
}
return false;
}
/** The recognized __commonJS helper forms, as token templates over the
* helper's own parameter names (CB, MOD) and the own-key reader (KEYS:
* esbuild's `__getOwnPropNames` alias, or `Object.keys` in esbuild 0.11):
* keyed: `(CB, MOD) => function [name]() { return <keyed>; }` — the
* factory is the only method of an object literal;
* arrow: `(CB, MOD) => () => (<arrow>)` — the factory itself. */
const KEYED_RETURN =
"MOD || (0, CB[KEYS(CB)[0]])((MOD = { exports: {} }).exports, MOD), MOD.exports";
const ARROW_BODY = "(MOD || CB((MOD = { exports: {} }).exports, MOD), MOD.exports)";
function template(text: string, cb: string, mod: string, keys: string): string | null {
return helperTokens(
text
.replace(/\bCB\b/g, cb)
.replace(/\bMOD\b/g, mod)
.replace(/\bKEYS\b/g, keys),
);
}
type HelperForm = "keyed" | "arrow";
/** The helper's form, or null when its initializer is not recognized.
* `ownNames` answers whether an identifier names the verified
* Object.getOwnPropertyNames alias. */
function helperForm(
init: ts.Expression,
sf: ts.SourceFile,
ownNames: (name: string) => boolean,
): HelperForm | null {
const fn = unparen(init);
if (!ts.isArrowFunction(fn) || fn.parameters.nodes.length !== 2) return null;
const params = fn.parameters.nodes.map((p) =>
ts.isIdentifier(p.name) && p.initializer === undefined && p.dotDotDotToken === undefined
? p.name.text
: null,
);
const [cb, mod] = params;
if (cb === null || mod === null || cb === undefined || mod === undefined || cb === mod)
return null;
if (ts.isBlock(fn.body)) return null;
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 === undefined || !ts.isReturnStatement(ret) || !ret.expression)
return null;
const actual = helperTokens(ret.expression.getText(sf));
if (actual === null) return null;
// The own-key reader: esbuild's alias or the 0.11 spelling.
const keysRef = /\[\s*([A-Za-z_$][\w$]*(?:\.keys)?)\s*\(/.exec(ret.expression.getText(sf));
const keys = keysRef?.[1];
if (keys === undefined || (keys !== "Object.keys" && !ownNames(keys))) return null;
return actual === template(KEYED_RETURN, cb, mod, 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, cb, mod, "") ? "arrow" : null;
}
return null;
}
/** A top-level declaration the virtual chunk can copy verbatim: a pure
* helper whose evaluation runs nothing (a function, or a member read of
* Object such as `Object.create` / `Object.prototype.hasOwnProperty`). */
function copyableInitializer(init: ts.Expression | undefined): boolean {
if (init === undefined) return false;
const e = unparen(init);
if (ts.isArrowFunction(e) || ts.isFunctionExpression(e)) return true;
let walk: ts.Expression = e;
let depth = 0;
while (ts.isPropertyAccessExpression(walk) && ts.isIdentifier(walk.name)) {
walk = walk.expression;
depth++;
}
return depth > 0 && ts.isIdentifier(walk) && walk.text === "Object";
}
/** A top-level declaration whose value is a function. */
function isFunctionValued(node: ts.VariableDeclaration | ts.FunctionDeclaration): boolean {
if (ts.isFunctionDeclaration(node)) return true;
const init = node.initializer && unparen(node.initializer);
return init !== undefined && (ts.isArrowFunction(init) || ts.isFunctionExpression(init));
}
/** True when a named function expression initializer (`var f = function
* self() {}`) uses its own name only as a callee: `self` is the copied
* function, so it is as observable as the top-level binding. */
function selfCalledOnly(
node: ts.VariableDeclaration | ts.FunctionDeclaration,
scopes: BundleScopes,
): boolean {
if (!ts.isVariableDeclaration(node) || node.initializer === undefined) return true;
const fn = unparen(node.initializer);
if (!ts.isFunctionExpression(fn) || fn.name === undefined || fn.body === undefined) return true;
const self = fn.name.text;
// A parameter of the same name hides the function's own name everywhere
// in it; a `var` of the same name hides it only in the body, since the
// parameter initializers do not see the body's `var`s.
if (fn.parameters.nodes.some((p) => bindsName(p.name, self))) return true;
const bodyVar = varScopedNames(fn.body).has(self);
const body = fn.body;
return references(fn).every(
(r) =>
r.text !== self || scopes.boundInside(r, fn) || (bodyVar && within(r, body)) || isCallee(r),
);
}
/** True when a binding name (an identifier or a destructuring pattern)
* declares `name`. */
function bindsName(binding: ts.BindingName, name: string): boolean {
const names = new Set<string>();
addBindingNames(binding, names);
return names.has(name);
}
/** True when a reference is the function a call invokes: `f(...)`, or the
* `(0, f)(...)` form that drops the receiver. */
function isCallee(id: ts.Identifier): boolean {
let callee: ts.Node = id;
const p = id.parent;
if (
p !== undefined &&
ts.isBinaryExpression(p) &&
p.operatorToken.kind === ts.SyntaxKind.CommaToken &&
p.right === id &&
p.parent !== undefined &&
ts.isParenthesizedExpression(p.parent)
)
callee = p.parent;
while (callee.parent !== undefined && ts.isParenthesizedExpression(callee.parent))
callee = callee.parent;
const call = callee.parent;
return call !== undefined && ts.isCallExpression(call) && call.expression === callee;
}
/** One recognized chunk declaration. */
interface Chunk {
name: string;
stmt: ts.VariableStatement;
params: string[];
body: ts.Block;
path: string;
spec: string;
}
interface TopLevel {
stmt: ts.Statement;
/** The declarator (or function declaration) itself. */
node: ts.VariableDeclaration | ts.FunctionDeclaration;
}
/** True when the file opens with a "use strict" directive prologue. */
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;
}
return false;
}
/** A cheap text probe: the helper's name, or its minified body's
* `(m={exports:{}}).exports,m` fragment. */
export function mayBundleChunks(source: string): boolean {
return (
source.includes("__commonJS") ||
/\{\s*exports\s*:\s*\{\s*\}\s*\}\s*\)\s*\.exports\s*,/.test(source)
);
}
/** Splits a CommonJS bundle's __commonJS chunks into virtual modules (see
* the header). Null: no chunks (or not a CommonJS bundle) — serve the file
* unchanged. */
export function splitBundledChunks(
sf: ts.SourceFile,
filePath: string,
): BundledChunkSplit | { degrade: string } | null {
const source = sf.text;
if (!mayBundleChunks(source)) return null;
// ES-module bundles have no require: their chunks keep the existing
// treatment (the Bun factory recognizer, or the ESM interop refusal).
if (!filePath.endsWith(".cjs") && ts.isExternalModule(sf)) return null;
const top = new Map<string, TopLevel>();
const duplicate = new Set<string>();
for (const stmt of sf.statements.nodes) {
const add = (name: string, node: TopLevel["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 helperNames = [...top.keys()].filter((n) => helperBase(n) === "__commonJS");
// Every name a recognizer relies on is written nowhere and declared
// once at the top level; `Object` itself is never rebound.
const allRefs = references(sf);
const written = new Set<string>();
for (const r of allRefs) if (isWritten(r)) written.add(r.text);
const declaredAnywhere = declaredNames(sf);
if (declaredAnywhere.has("Object") || written.has("Object"))
return { degrade: CHUNK_SHAPE_DEGRADE };
const stable = (name: string): boolean => !duplicate.has(name) && !written.has(name);
// Names whose every reference in the bundle is a callee: `f(...)` or the
// `(0, f)(...)` form.
const scopes = new BundleScopes();
const valueUsed = new Set<string>();
for (const r of allRefs) if (!isCallee(r) && scopes.topLevel(r, sf)) valueUsed.add(r.text);
const calledOnly = (name: string): boolean => !valueUsed.has(name);
const ownNames = (name: string): boolean => {
const t = top.get(name);
if (t === undefined || !stable(name) || !ts.isVariableDeclaration(t.node)) return false;
const init = t.node.initializer;
return (
init !== undefined &&
helperTokens(init.getText(sf)) === helperTokens("Object.getOwnPropertyNames")
);
};
if (helperNames.length === 0) {
// The helper's shape under another name: an identifier-minified bundle,
// whose other interop helpers lost their names as well.
for (const [name, t] of top) {
const init = ts.isVariableDeclaration(t.node) ? t.node.initializer : undefined;
if (init !== undefined && stable(name) && helperForm(init, sf, ownNames) !== null)
return {
degrade:
"its shipped JS is an identifier-minified bundle whose bundler-interop helpers " +
"(__commonJS and the rest) have lost the names the recognizers verify",
};
}
return null;
}
const forms = new Map<string, HelperForm>();
for (const name of helperNames) {
const t = top.get(name)!;
const init = ts.isVariableDeclaration(t.node) ? t.node.initializer : undefined;
const form = init !== undefined && stable(name) ? helperForm(init, sf, ownNames) : null;
if (form === null) return { degrade: CHUNK_SHAPE_DEGRADE };
forms.set(name, form);
}
// The chunk declarations: `var NAME = HELPER(factory);`, one declarator.
const chunks = new Map<string, Chunk>();
const base = filePath.replace(/^.*[\\/]/, "");
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;
const stmt = t.stmt;
if (
!ts.isVariableStatement(stmt) ||
stmt.declarationList.declarations.nodes.length !== 1 ||
call.arguments.nodes.length !== 1 ||
!stable(name)
)
return { degrade: CHUNK_SHAPE_DEGRADE };
let factory: ts.Node = call.arguments.nodes[0]!;
if (form === "keyed") {
if (!ts.isObjectLiteralExpression(factory) || factory.properties.nodes.length !== 1)
return { degrade: CHUNK_SHAPE_DEGRADE };
factory = factory.properties.nodes[0]!;
if (!ts.isMethodDeclaration(factory) || ts.isComputedPropertyName(factory.name))
return { degrade: CHUNK_SHAPE_DEGRADE };
} else {
factory = unparen(factory as ts.Expression);
if (!ts.isArrowFunction(factory) && !ts.isFunctionExpression(factory))
return { degrade: CHUNK_SHAPE_DEGRADE };
}
const fn = factory as ts.MethodDeclaration | ts.ArrowFunction | ts.FunctionExpression;
if (
fn.body === undefined ||
!ts.isBlock(fn.body) ||
fn.asteriskToken !== undefined ||
(fn.modifiers?.nodes.length ?? 0) > 0 ||
fn.parameters.nodes.length > 2
)
return { degrade: CHUNK_SHAPE_DEGRADE };
const params: string[] = [];
for (const p of fn.parameters.nodes) {
if (!ts.isIdentifier(p.name) || p.initializer !== undefined || p.dotDotDotToken)
return { degrade: CHUNK_SHAPE_DEGRADE };
params.push(p.name.text);
}
const file = `${base}.${name}.cjs`;
chunks.set(name, {
name,
stmt,
params,
body: fn.body,
path: filePath.slice(0, filePath.length - base.length) + file,
spec: `./${file}`,
});
}
if (chunks.size === 0) return null;
// Every factory reference is a direct zero-argument call. Calls inside a
// chunk body belong to that chunk's text, the rest to the bundle's.
const callEdits: Edit[] = [];
for (const r of allRefs) {
const chunk = chunks.get(r.text);
if (chunk === undefined) continue;
const call = r.parent;
if (
call === undefined ||
!ts.isCallExpression(call) ||
call.expression !== r ||
call.arguments.nodes.length !== 0 ||
call.questionDotToken !== undefined
)
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(forwarded ?? chunk.spec)})`,
});
}
for (const name of chunks.keys()) {
if (declaredAnywhere.has(name) && countDeclarations(sf, name) > 1)
return { degrade: CHUNK_SHAPE_DEGRADE };
}
const bundleStrict = strictPrologue(sf.statements.nodes);
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,
chunks,
top,
stable,
calledOnly,
scopes,
callEdits,
bundleStrict,
);
if (typeof result !== "string") return result;
out.push({ path: chunk.path, source: result });
bundleEdits.push({ start: chunk.stmt.getStart(sf), end: chunk.stmt.getEnd(), text: "" });
}
return { text: applyEdits(source, 0, source.length, bundleEdits), chunks: out };
}
export function countDeclarations(sf: ts.SourceFile, name: string): number {
let n = 0;
ts.walkPreorder(sf, (node) => {
if (
(ts.isVariableDeclaration(node) ||
ts.isParameter(node) ||
ts.isBindingElement(node) ||
ts.isFunctionDeclaration(node) ||
ts.isFunctionExpression(node) ||
ts.isClassDeclaration(node) ||
ts.isClassExpression(node)) &&
node.name !== undefined &&
ts.isIdentifier(node.name) &&
node.name.text === name
)
n++;
return undefined;
});
return n;
}
/** 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. */
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);
let text = "";
let at = from;
for (const e of inside) {
if (e.start < at) continue; // nested in an earlier edit
text += source.slice(at, e.start);
const replaced = source.slice(e.start, e.end);
// A respelled span keeps its line breaks after the replacement.
text +=
e.text === "" ? replaced.replace(/[^\r\n]/g, " ") : e.text + replaced.replace(/[^\n]/g, "");
at = e.end;
}
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,
chunk: Chunk,
chunks: ReadonlyMap<string, Chunk>,
top: ReadonlyMap<string, TopLevel>,
stable: (name: string) => boolean,
calledOnly: (name: string) => boolean,
scopes: BundleScopes,
callEdits: readonly Edit[],
bundleStrict: boolean,
): string | { degrade: string } {
const why = (reason: string): { degrade: string } => ({
degrade: `its bundled CommonJS module '${chunk.name}' ${reason}`,
});
const [exportsParam, moduleParam] = chunk.params;
const body = chunk.body;
const local = declaredNames(body);
for (const p of chunk.params) {
if (
local.has(p) ||
(p !== "exports" && local.has("exports")) ||
(p !== "module" && local.has("module"))
)
return why(
"rebinds its module parameters inside its body (an identifier-minified bundle the recognizer cannot respell)",
);
}
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);
const copied = new Set<string>();
const copyQueue: string[] = [];
for (const r of references(body)) {
const name = r.text;
if (chunks.has(name)) continue; // a call edit already respells it
if (name === exportsParam || name === moduleParam) {
if (name === moduleParam) {
const p = r.parent;
if (!ts.isPropertyAccessExpression(p) || p.expression !== r || p.name.text !== "exports")
return why("uses its module object beyond module.exports");
}
const global = name === exportsParam ? "exports" : "module";
if (name !== global) {
const p = r.parent;
edits.push(
ts.isShorthandPropertyAssignment(p)
? { start: r.getStart(sf), end: r.getEnd(), text: `${name}: ${global}` }
: { start: r.getStart(sf), end: r.getEnd(), text: global },
);
}
continue;
}
// The factory function itself binds the parameters and `var`s.
if (scopes.boundWithin(r, body.parent ?? body)) continue;
if (name === "exports" || name === "module")
return why(`reads the bundle's own '${name}' binding`);
if (name === "__filename") return why("reads __filename, which names the bundle file");
if (top.has(name)) {
if (!copied.has(name)) {
copied.add(name);
copyQueue.push(name);
}
}
}
// The pure helpers BODY reads, closed over their own top-level reads.
const header: string[] = [];
for (let i = 0; i < copyQueue.length; i++) {
const name = copyQueue[i]!;
const t = top.get(name)!;
const node = t.node;
const pure =
stable(name) &&
(ts.isFunctionDeclaration(node) ||
(ts.isVariableDeclaration(node) && copyableInitializer(node.initializer)));
if (!pure || chunks.has(name))
return why(`reads the bundle's top-level binding '${name}', which it cannot carry along`);
// Each chunk gets its own copy, so a function's identity and its
// properties must stay unobservable: the bundle only ever calls it.
if (isFunctionValued(node) && (!calledOnly(name) || !selfCalledOnly(node, scopes)))
return why(
`uses the bundle's top-level function '${name}' as a value, which its chunks cannot share`,
);
for (const r of references(node)) {
if (scopes.boundWithin(r, node) || !top.has(r.text) || copied.has(r.text)) continue;
copied.add(r.text);
copyQueue.push(r.text);
}
}
// Declaration order of the bundle: a helper reads only earlier ones.
const ordered = [...copied].sort(
(a, b) => top.get(a)!.node.getStart(sf) - top.get(b)!.node.getStart(sf),
);
for (const name of ordered) {
const node = top.get(name)!.node;
header.push(ts.isFunctionDeclaration(node) ? node.getText(sf) : `var ${node.getText(sf)};`);
}
const bodyStrict = strictPrologue(body.statements.nodes);
const text = applyEdits(sf.text, body.getStart(sf) + 1, body.getEnd() - 1, edits);
const prologue = bundleStrict || bodyStrict ? '"use strict";\n' : "";
return prologue + (header.length > 0 ? header.join("\n") + "\n" : "") + text + "\n";
}
@@ -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;
}
@@ -0,0 +1,238 @@
/* CommonJS modules that name their export object through a variable:
*
* var ip = exports;
* ip.isPrivate = function (addr) { … };
* ip.isPublic = function (addr) { return !ip.isPrivate(addr); };
*
* `ip` IS the export object, so every member read or write through it is
* an export. The pass respells those accesses as `exports.<name>`, the
* form the static export protocol models, and drops the alias declaration
* (the export object has no storage of its own to bind).
*
* Exact only while the variable is nothing but that alias: one top-level
* declaration initialized with the CommonJS `exports` global, never
* reassigned, never declared again anywhere in the file (so no nested
* binding shadows it), and used only as the object of member accesses.
* `exports` itself must be the global (never declared in the file) and is
* never reassigned. Other shapes answer null and keep their existing
* treatment. */
import * as ts from "./ts7/syntax.js";
function unparen(e: ts.Expression): ts.Expression {
let x = e;
while (ts.isParenthesizedExpression(x)) x = x.expression;
return x;
}
function isDeclarationName(id: ts.Identifier): boolean {
const p = id.parent;
return (
((ts.isVariableDeclaration(p) ||
ts.isParameter(p) ||
ts.isBindingElement(p) ||
ts.isFunctionDeclaration(p) ||
ts.isFunctionExpression(p) ||
ts.isClassDeclaration(p) ||
ts.isClassExpression(p)) &&
p.name === id) ||
(ts.isPropertyAccessExpression(p) && p.name === id) ||
((ts.isPropertyAssignment(p) || ts.isMethodDeclaration(p) || ts.isPropertyDeclaration(p)) &&
p.name === id)
);
}
function isFunctionScope(n: ts.Node): boolean {
return (
ts.isFunctionDeclaration(n) ||
ts.isFunctionExpression(n) ||
ts.isArrowFunction(n) ||
ts.isMethodDeclaration(n) ||
ts.isGetAccessorDeclaration(n) ||
ts.isSetAccessorDeclaration(n) ||
ts.isConstructorDeclaration(n)
);
}
function bindsName(name: ts.BindingName | undefined, text: string): boolean {
if (name === undefined) return false;
if (ts.isIdentifier(name)) return name.text === text;
for (const element of name.elements.nodes) {
if (!ts.isOmittedExpression(element) && bindsName(element.name, text)) return true;
}
return false;
}
/** True when one of `statements` declares `text` lexically: a let/const,
* or a class or function declaration. */
function declaresLexically(statements: readonly ts.Statement[], text: string): boolean {
for (const stmt of statements) {
if (
ts.isVariableStatement(stmt) &&
(stmt.declarationList.flags & ts.NodeFlags.BlockScoped) !== 0 &&
stmt.declarationList.declarations.nodes.some((d) => bindsName(d.name, text))
)
return true;
if ((ts.isClassDeclaration(stmt) || ts.isFunctionDeclaration(stmt)) && stmt.name?.text === text)
return true;
}
return false;
}
/** True when a function body declares `text` with `var` (or a function
* declaration in a nested block) anywhere outside nested functions. */
function declaresVar(body: ts.Node, text: string): boolean {
let found = false;
ts.walkPreorder(body, (n) => {
if (found) return "stop";
if (n === body) return undefined;
if (isFunctionScope(n)) {
if (ts.isFunctionDeclaration(n) && n.name?.text === text) found = true;
return "skip";
}
if (
ts.isVariableDeclarationList(n) &&
(n.flags & ts.NodeFlags.BlockScoped) === 0 &&
n.declarations.nodes.some((d) => bindsName(d.name, text))
)
found = true;
return undefined;
});
return found;
}
/** True when `scope` declares `text` itself, so references inside it name
* that binding instead of the module-level alias: a function's parameters,
* own name, `var`s and the let/const, class and function declarations of
* its body; a block's or case block's own let/const, class and function
* declarations; a catch binding; a for loop's let/const. A let/const in a
* nested block shadows only that block, which the walk reaches as its own
* scope. */
function shadows(scope: ts.Node, text: string): boolean {
if (isFunctionScope(scope)) {
const fn = scope as ts.SignatureDeclaration;
if (fn.parameters.nodes.some((p) => bindsName(p.name, text))) return true;
if (ts.isFunctionExpression(scope) && scope.name?.text === text) return true;
const body = (scope as { body?: ts.Node }).body;
if (body === undefined || !ts.isBlock(body)) return false;
return declaresVar(body, text) || declaresLexically(body.statements.nodes, text);
}
if (ts.isBlock(scope)) return declaresLexically(scope.statements.nodes, text);
if (ts.isCaseBlock(scope))
return declaresLexically(
scope.clauses.nodes.flatMap((clause) => clause.statements.nodes),
text,
);
if (ts.isCatchClause(scope)) return bindsName(scope.variableDeclaration?.name, text);
if (ts.isForStatement(scope) || ts.isForInStatement(scope) || ts.isForOfStatement(scope)) {
const init = scope.initializer;
return (
init !== undefined &&
ts.isVariableDeclarationList(init) &&
(init.flags & ts.NodeFlags.BlockScoped) !== 0 &&
init.declarations.nodes.some((d) => bindsName(d.name, text))
);
}
if (ts.isClassExpression(scope)) return scope.name?.text === text;
return false;
}
export function normalizeCjsExportsVar(sf: ts.SourceFile): string | null {
const source = sf.text;
if (!/\b(?:var|let|const)\s+[A-Za-z_$][\w$]*\s*=\s*exports\s*[;,\n]/.test(source)) return null;
if (!sf.fileName.endsWith(".cjs") && ts.isExternalModule(sf)) return null;
let alias: { name: string; stmt: ts.VariableStatement } | null = null;
for (const stmt of sf.statements.nodes) {
if (!ts.isVariableStatement(stmt)) continue;
const decls = stmt.declarationList.declarations.nodes;
if (decls.length !== 1) continue;
const decl = decls[0]!;
const init = decl.initializer !== undefined ? unparen(decl.initializer) : undefined;
if (
ts.isIdentifier(decl.name) &&
init !== undefined &&
ts.isIdentifier(init) &&
init.text === "exports"
) {
if (alias !== null) return null; /* two aliases: keep the plain treatment */
alias = { name: decl.name.text, stmt };
}
}
if (alias === null) return null;
const name = alias.name;
const aliasDecl = alias.stmt.declarationList.declarations.nodes[0]!;
const edits: { start: number; end: number; text: string }[] = [];
let ok = true;
ts.walkPreorder(sf, (n) => {
if (!ok) return "stop";
if (n.kind >= ts.SyntaxKind.FirstJSDocNode && n.kind <= ts.SyntaxKind.LastJSDocNode)
return "skip";
if (
ts.isBinaryExpression(n) &&
n.operatorToken.kind === ts.SyntaxKind.EqualsToken &&
ts.isPropertyAccessExpression(unparen(n.left)) &&
(unparen(n.left) as ts.PropertyAccessExpression).name.text === "exports" &&
ts.isIdentifier((unparen(n.left) as ts.PropertyAccessExpression).expression) &&
((unparen(n.left) as ts.PropertyAccessExpression).expression as ts.Identifier).text ===
"module"
) {
ok = false; /* module.exports replaced: the alias no longer names the exports */
return "stop";
}
// A scope that declares the alias's name again: its references name
// that binding, not the export object.
if (
n !== sf &&
(isFunctionScope(n) ||
ts.isBlock(n) ||
ts.isCaseBlock(n) ||
ts.isCatchClause(n) ||
ts.isForStatement(n) ||
ts.isForInStatement(n) ||
ts.isForOfStatement(n) ||
ts.isClassExpression(n)) &&
shadows(n, name)
)
return "skip";
if (!ts.isIdentifier(n)) return undefined;
if (n.text === "exports" && n !== aliasDecl.initializer) {
// `exports` declared in the file, or the export object replaced
if (isDeclarationName(n) && !ts.isPropertyAccessExpression(n.parent)) ok = false;
const p = n.parent;
if (
ts.isBinaryExpression(p) &&
p.left === n &&
p.operatorToken.kind === ts.SyntaxKind.EqualsToken
)
ok = false;
return undefined;
}
if (n.text !== name) return undefined;
if (n === aliasDecl.name) return undefined;
const p = n.parent;
if (ts.isPropertyAccessExpression(p) && p.name === n) return undefined;
if ((ts.isPropertyAssignment(p) || ts.isMethodDeclaration(p)) && p.name === n) return undefined;
if (isDeclarationName(n)) {
ok = false; /* declared again (a shadowing binding): not a plain alias */
return undefined;
}
if (
(ts.isPropertyAccessExpression(p) || ts.isElementAccessExpression(p)) &&
p.expression === n
) {
edits.push({ start: n.getStart(sf), end: n.getEnd(), text: "exports" });
return undefined;
}
ok = false; /* used as a value, assigned, or passed along */
return undefined;
});
if (!ok || edits.length === 0) return null;
edits.push({ start: alias.stmt.getStart(sf), end: alias.stmt.getEnd(), text: "" });
edits.sort((a, b) => a.start - b.start);
let out = "";
let at = 0;
for (const e of edits) {
out += source.slice(at, e.start) + e.text;
at = e.end;
}
return out + source.slice(at);
}
@@ -2,10 +2,16 @@
import { dirname, join, resolve as resolvePath } from "node:path";
import { cjsLexedExportsOfFile, cjsVisibleNames } from "./cjs-syntax.js";
import type { Ts7SourceParser } from "./ts7/source-parser.js";
import { trackedDirectoryExists, trackedFileExists, trackedReadFile } from "./input-tracker.js";
import {
isVirtualSource,
trackedDirectoryExists,
trackedFileExists,
trackedReadFile,
} from "./input-tracker.js";
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"]);
@@ -134,7 +140,7 @@ function requireTargetEsModuleStamped(
} catch {
/* unlexable — keep probing */
}
if (src.includes("__toCommonJS(")) return true;
if (/__toCommonJS\d*\(/.test(src)) return true;
const fwd = /module\.exports\s*=\s*require\(\s*["']([^"']+)["']\s*\)/.exec(src);
if (fwd !== null) return requireTargetEsModuleStamped(parser, file, fwd[1]!, depth + 1);
return false;
@@ -159,13 +165,29 @@ function starTargetNames(parser: Ts7SourceParser, file: string): Set<string> {
}
}
export function rewriteBundlerCjsWithParser(
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) => {
const target = resolveRelativeCjs(from, spec);
@@ -12,6 +12,73 @@ import { rewriteBundledFunctionImports } from "./npm-static-bundled-cjs.js";
export interface CjsRewriteHost {
requireTargetEsModuleStamped(fromFile: string, specifier: string): boolean;
starTargetNames(fromFile: string, specifier: string): Set<string>;
/** Told when the rewritten file's tail export table stands for a live
* getter table the original installed before it could run another
* module's code (liveExportTableFirst): a module of a require cycle that
* captured the export object early observes exactly that table. */
liveExportTable?: ((filePath: string) => void) | undefined;
/** True for a module only ever loaded through require() (a bundle's
* CommonJS chunk split into its own module): no ES-module importer
* 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)`
* over a getter table `__export(T, {...})`) is installed before anything
* that can run another module's code, and nothing else writes the export
* object. Every statement before the installation is then a declaration,
* a directive, or the getter-table call (whose getters run only when
* read), and variable initializers evaluate no calls outside function
* bodies. The getters read live bindings, so the object a cycle partner
* captures early answers every later read exactly like the final table. */
function liveExportTableFirst(
sf: ts.SourceFile,
installAt: number,
target: string,
exportTables: readonly { target: string }[],
): boolean {
if (!exportTables.some((t) => t.target === target)) return false;
let callsOutsideFunctions = false;
const noCalls = (root: ts.Node): boolean => {
callsOutsideFunctions = false;
ts.walkPreorder(root, (n) => {
if (callsOutsideFunctions) return "stop";
if (ts.isArrowFunction(n) || ts.isFunctionExpression(n) || ts.isFunctionDeclaration(n))
return "skip";
if (ts.isCallExpression(n) || ts.isNewExpression(n) || ts.isTaggedTemplateExpression(n))
callsOutsideFunctions = true;
return undefined;
});
return !callsOutsideFunctions;
};
let sawTable = false;
for (const stmt of sf.statements.nodes) {
if (stmt.getStart(sf) >= installAt) return sawTable;
if (ts.isFunctionDeclaration(stmt) || ts.isEmptyStatement(stmt)) continue;
if (ts.isExpressionStatement(stmt) && ts.isStringLiteral(stmt.expression)) continue;
if (ts.isVariableStatement(stmt)) {
if (
stmt.declarationList.declarations.nodes.every(
(d) => ts.isIdentifier(d.name) && (d.initializer === undefined || noCalls(d.initializer)),
)
)
continue;
return false;
}
if (ts.isExpressionStatement(stmt) && ts.isCallExpression(stmt.expression)) {
const table = exportCallOf(stmt.expression);
if (table !== null && table.target === target) {
sawTable = true;
continue;
}
}
return false;
}
return false;
}
export function isBundlerCjsCandidate(source: string): boolean {
@@ -24,24 +91,43 @@ export function isBundlerCjsCandidate(source: string): boolean {
);
}
/** The helper a bundler-emitted name spells. esbuild suffixes a helper
* that a bundled module declares again with a counter (a bundled esbuild
* dist inside another bundle carries `__export2`, `__toCommonJS2`, …); the
* recognizers below verify each call's shape, so the counter carries no
* meaning beyond the name collision it avoided. */
export function bundlerHelperBase(name: string): string {
return /^__[A-Za-z]+\d+$/.test(name) ? name.replace(/\d+$/, "") : name;
}
/** The last NAME of a callee: bare identifier or any member chain's final
* name (`tslib_1.__exportStar` → "__exportStar"). */
* name (`tslib_1.__exportStar` → "__exportStar"), helper counters dropped. */
function calleeNameOf(call: ts.CallExpression): string | null {
const callee = call.expression;
if (ts.isIdentifier(callee)) return callee.text;
if (ts.isIdentifier(callee)) return bundlerHelperBase(callee.text);
if (ts.isPropertyAccessExpression(callee) && ts.isIdentifier(callee.name))
return callee.name.text;
return bundlerHelperBase(callee.name.text);
return null;
}
/** True for an identifier spelling the named helper (counter-suffixed
* spellings included). */
function isHelperIdent(node: ts.Node, base: string): node is ts.Identifier {
return ts.isIdentifier(node) && bundlerHelperBase(node.text) === base;
}
/** An entry the canonical table can carry. */
interface EntrySpec {
/** The export name (may need string-key spelling). */
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;
}
@@ -79,6 +165,26 @@ function chaseValue(e: ts.Expression): { kind: "ident" | "hoist"; text: string }
return null;
}
/** An object literal of side-effect-free member values (`exports.default
* = { context: context_api_1.context, metrics: metrics_api_1.metrics }`,
* tsc's default-export object): the tail const can build it once, like a
* chased value. Null for any other shape (spreads, methods, accessors,
* computed keys, or a value chaseValue rejects). */
function chaseObjectLiteral(e: ts.Expression): { kind: "hoist"; text: string } | null {
let cur: ts.Expression = e;
while (ts.isParenthesizedExpression(cur)) cur = cur.expression;
if (!ts.isObjectLiteralExpression(cur)) return null;
for (const prop of cur.properties.nodes) {
if (
!ts.isPropertyAssignment(prop) ||
!(ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name)) ||
(chaseValue(prop.initializer) === null && chaseObjectLiteral(prop.initializer) === null)
)
return null;
}
return { kind: "hoist", text: cur.getText() };
}
/** The getter body's returned expression for the two descriptor getter
* spellings (`get() { return X }` / `get: function () { return X }`) and
* the arrow forms the esbuild table uses (`() => X`, `() => { return X }`). */
@@ -194,13 +300,8 @@ interface ToEsmPlan {
* __copyProps(…, mod) call copying onto a conditional that tests
* isNodeMode/__esModule and defines "default" with value mod. Comments and
* formatting are free; the SHAPE is the contract. */
function recognizedToEsmDecl(stmt: ts.Statement): boolean {
if (!ts.isVariableStatement(stmt)) return false;
const decls = stmt.declarationList.declarations.nodes;
if (decls.length !== 1) return false;
const d = decls[0]!;
if (!ts.isIdentifier(d.name) || d.name.text !== "__toESM" || d.initializer === undefined)
return false;
function recognizedToEsmDecl(d: ts.VariableDeclaration): boolean {
if (!isHelperIdent(d.name, "__toESM") || d.initializer === undefined) return false;
let init: ts.Expression = d.initializer;
while (ts.isParenthesizedExpression(init)) init = init.expression;
if (!ts.isArrowFunction(init)) return false;
@@ -218,12 +319,7 @@ function recognizedToEsmDecl(stmt: ts.Statement): boolean {
expr = expr.right;
}
while (ts.isParenthesizedExpression(expr)) expr = expr.expression;
if (
!ts.isCallExpression(expr) ||
!ts.isIdentifier(expr.expression) ||
expr.expression.text !== "__copyProps"
)
return false;
if (!ts.isCallExpression(expr) || !isHelperIdent(expr.expression, "__copyProps")) return false;
if (expr.arguments.nodes.length < 2) return false;
const from = expr.arguments.nodes[1]!;
if (!ts.isIdentifier(from) || from.text !== mod) return false;
@@ -234,12 +330,7 @@ function recognizedToEsmDecl(stmt: ts.Statement): boolean {
if (!condText.includes(isNodeMode) || !condText.includes("__esModule")) return false;
let stamp: ts.Expression = to.whenTrue;
while (ts.isParenthesizedExpression(stamp)) stamp = stamp.expression;
if (
!ts.isCallExpression(stamp) ||
!ts.isIdentifier(stamp.expression) ||
stamp.expression.text !== "__defProp"
)
return false;
if (!ts.isCallExpression(stamp) || !isHelperIdent(stamp.expression, "__defProp")) return false;
if (stamp.arguments.nodes.length !== 3) return false;
const nameArg = stamp.arguments.nodes[1]!;
if (!ts.isStringLiteral(nameArg) || nameArg.text !== "default") return false;
@@ -278,19 +369,23 @@ function planToEsmInterop(sf: ts.SourceFile, filePath: string, host: CjsRewriteH
degrade: reason,
});
const declStmts = sf.statements.nodes.filter(
(s) =>
ts.isVariableStatement(s) &&
s.declarationList.declarations.nodes.some(
(d) => ts.isIdentifier(d.name) && d.name.text === "__toESM",
),
);
// Top-level declarators of the helper, any statement shape (minified
// dists share one `var` among several helpers), by spelling.
const decls = new Map<string, ts.VariableDeclaration[]>();
for (const s of sf.statements.nodes) {
if (!ts.isVariableStatement(s)) continue;
for (const d of s.declarationList.declarations.nodes) {
if (!isHelperIdent(d.name, "__toESM")) continue;
const list = decls.get(d.name.text);
if (list === undefined) decls.set(d.name.text, [d]);
else list.push(d);
}
}
const refs: ts.Identifier[] = [];
const calls: ts.CallExpression[] = [];
const collect = (n: ts.Node): void => {
if (ts.isIdentifier(n) && n.text === "__toESM") refs.push(n);
if (ts.isCallExpression(n) && ts.isIdentifier(n.expression) && n.expression.text === "__toESM")
calls.push(n);
if (isHelperIdent(n, "__toESM")) refs.push(n);
if (ts.isCallExpression(n) && isHelperIdent(n.expression, "__toESM")) calls.push(n);
};
ts.walkPreorder(sf, collect);
if (calls.length === 0 && refs.length === 0) return plan;
@@ -298,15 +393,16 @@ function planToEsmInterop(sf: ts.SourceFile, filePath: string, host: CjsRewriteH
// a helper that escapes as a VALUE is outside the recognized shape.
const callees = new Set<ts.Node>(calls.map((c) => c.expression));
const declNames = new Set<ts.Node>();
for (const s of declStmts) {
for (const d of (s as ts.VariableStatement).declarationList.declarations.nodes) {
if (ts.isIdentifier(d.name) && d.name.text === "__toESM") declNames.add(d.name);
}
}
for (const list of decls.values()) for (const d of list) declNames.add(d.name);
if (refs.some((r) => !callees.has(r) && !declNames.has(r))) return fail(TO_ESM_ESCAPE_DEGRADE);
if (calls.length === 0) return plan; // declared but never called — dead helper
if (declStmts.length !== 1 || !recognizedToEsmDecl(declStmts[0]!))
return fail(TO_ESM_SHAPE_DEGRADE);
// Every spelling a call uses must be declared exactly once, in the
// recognized shape.
for (const call of calls) {
const list = decls.get((call.expression as ts.Identifier).text);
if (list === undefined || list.length !== 1 || !recognizedToEsmDecl(list[0]!))
return fail(TO_ESM_SHAPE_DEGRADE);
}
/** Module-scope interop bindings: name → whether `.default` IS the
* module (pad the access) rather than a member read of its `default`. */
@@ -467,16 +563,20 @@ export function rewriteBundlerCjsSyntax(
// ESM bundles can contain closed CommonJS function factories. Recognize
// those before refusing interop that needs a dynamic module namespace.
if (ts.isExternalModule(sf)) {
// TypeScript forces every `.cjs` file to be an external module
// (isFileForcedToBeModuleByFormat), yet Node always loads one as
// CommonJS: the extension, not that flag, decides the format there.
if (!filePath.endsWith(".cjs") && ts.isExternalModule(sf)) {
const bundled = rewriteBundledFunctionImports(source, sf);
if (bundled !== null) return bundled;
return source.includes("__toESM(")
? {
degrade:
"its ES-module dist routes an external dependency through the __toESM " +
"bundler-interop helper, which cannot compile natively in ESM output",
}
: null;
if (!source.includes("__toESM(")) return null;
return {
degrade: source.includes("__commonJS")
? "its ES-module bundle reaches bundled CommonJS modules through the __commonJS and " +
"__toESM bundler-interop helpers, which cannot compile natively in ESM output"
: "its ES-module dist routes an external dependency through the __toESM " +
"bundler-interop helper, which cannot compile natively in ESM output",
};
}
// The __toESM interop pass (see the section header): wrapper call sites
@@ -644,6 +744,11 @@ export function rewriteBundlerCjsSyntax(
}
const lexed = cjsLexedExportsOfFile(sf);
if (host.requireOnly?.(filePath) === true) {
for (const t of exportTables) for (const [name] of t.entries) lexed.exports.add(name);
for (const d of definePropEntries) lexed.exports.add(d.name);
for (const m of memberStmts) for (const name of m.names) lexed.exports.add(name);
}
let emitTable = sawBundleShape && (lexed.exports.size > 0 || lexed.reexports.length > 0);
const starSpecs: string[] = [];
@@ -682,7 +787,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));
@@ -714,7 +826,7 @@ export function rewriteBundlerCjsSyntax(
// anything else keeps the file untouched (the offender path owns
// it: neutralizing would drop an evaluation, keeping it meets the
// lowering's discard fence at load).
const chased = chaseValue(cur);
const chased = chaseValue(cur) ?? chaseObjectLiteral(cur);
if (chased === null) {
return toEsm.pads.length > 0 ? { degrade: TO_ESM_MIXED_DEGRADE } : null;
}
@@ -814,21 +926,36 @@ export function rewriteBundlerCjsSyntax(
"__reExport",
"__toESM",
"__toCommonJS",
"__commonJS",
"__esm",
"__exportStar",
"__createBinding",
"__setModuleDefault",
"__importStar",
"__importDefault",
]);
/* Helper declarators by name. A minified dist shares one `var` among
* several helpers (`var __getProtoOf=…,__hasOwnProp=…;`): each
* declarator is its own candidate, and the statement pads whole only
* once every declarator in it is dead. */
const helperDecls = new Map<string, { start: number; end: number }>();
const helperStmts: ts.VariableStatement[] = [];
for (const stmt of sf.statements.nodes) {
if (!ts.isVariableStatement(stmt)) continue;
const decls = stmt.declarationList.declarations.nodes;
if (decls.length !== 1) continue;
const d = decls[0]!;
if (ts.isIdentifier(d.name) && HELPER_NAMES.has(d.name.text)) {
helperDecls.set(d.name.text, { start: stmt.getStart(sf), end: stmt.getEnd() });
let anyHelper = false;
for (const d of decls) {
if (!ts.isIdentifier(d.name) || !HELPER_NAMES.has(bundlerHelperBase(d.name.text))) continue;
if (helperDecls.has(d.name.text)) continue; // redeclared: keep the first, never sweep twice
anyHelper = true;
helperDecls.set(
d.name.text,
decls.length === 1
? { start: stmt.getStart(sf), end: stmt.getEnd() }
: { start: d.getStart(sf), end: d.getEnd() },
);
}
if (anyHelper && decls.length > 1) helperStmts.push(stmt);
}
// every identifier occurrence of a helper name outside its own
// declarator name node, position-recorded for the span test
@@ -862,8 +989,39 @@ export function rewriteBundlerCjsSyntax(
}
}
}
// A swept declarator of a shared statement pads with its separating
// comma, and the statement pads whole once every declarator is dead:
// padding the bare declarator span would leave a dangling comma.
const declaratorSpans = new Set<{ start: number; end: number }>();
const declaratorPads: { start: number; end: number }[] = [];
for (const stmt of helperStmts) {
const decls = stmt.declarationList.declarations.nodes;
const deadAt = decls.map((d) => {
if (!ts.isIdentifier(d.name) || !removed.has(d.name.text)) return false;
const span = helperDecls.get(d.name.text)!;
if (span.start !== d.getStart(sf)) return false;
declaratorSpans.add(span);
return true;
});
if (deadAt.every((x) => x)) {
declaratorPads.push({ start: stmt.getStart(sf), end: stmt.getEnd() });
continue;
}
// Dead declarators before the last live one take their trailing
// comma; the dead tail after it pads from that declarator's end.
const lastLive = deadAt.lastIndexOf(false);
for (let i = 0; i < decls.length; i++) {
if (!deadAt[i]) continue;
const d = decls[i]!;
declaratorPads.push(
i < lastLive
? { start: d.getStart(sf), end: decls[i + 1]!.getStart(sf) }
: { start: decls[lastLive]!.getEnd(), end: d.getEnd() },
);
}
}
neutralize.length = 0;
neutralize.push(...dead);
neutralize.push(...dead.filter((span) => !declaratorSpans.has(span)), ...declaratorPads);
}
/* ── emission ─────────────────────────────────────────────────────── */
@@ -875,6 +1033,15 @@ export function rewriteBundlerCjsSyntax(
if (!emitTable) return text; // interop pads only — nothing appends
if (
esbuildMainTarget !== null &&
tablePos !== null &&
memberStmts.length === 0 &&
definePropEntries.length === 0 &&
liveExportTableFirst(sf, tablePos, esbuildMainTarget, exportTables)
)
host.liveExportTable?.(filePath);
const lines: string[] = [""];
const hasAnyFallback = [...entries.values()].some((s) => s.kind === "any");
if (hasAnyFallback) {
@@ -906,6 +1073,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,`);
}
@@ -931,5 +1100,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";
}
+136 -10
View File
@@ -13,7 +13,13 @@ import {
registerWorkspacePackage,
workspacePackageOfPath,
} from "./workspace-registry.js";
import { trackedExists, trackedReadFile, trackedRealpath } from "./input-tracker.js";
import {
clearVirtualSources,
setVirtualSource,
trackedExists,
trackedReadFile,
trackedRealpath,
} from "./input-tracker.js";
let activePackages: ReadonlySet<string> = new Set();
let declarationOverloads: ReadonlyMap<string, NpmStaticDeclarationOverloads> = new Map();
@@ -28,14 +34,36 @@ const offenders = new Map<string, string>();
* the host probes the same file many times, and the rewrite parses. */
const rewriteCache = new Map<string, string | null>();
/** Rewritten files whose tail export table stands for a live getter table
* installed before the file could run another module's code (the rewrite
* certifies it; require-cycle admission consults it). */
const liveExportFiles = new Set<string>();
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();
declarationProperties = new Map();
offenders.clear();
fileDegrades.clear();
rewriteCache.clear();
liveExportFiles.clear();
lexerNames.clear();
clearVirtualSources();
untypedPkgCache.clear();
realpathProbed.clear();
aliasNames.clear();
}
export function setNpmStaticDeclarationOverloads(
@@ -81,6 +109,21 @@ export function npmStaticOffenders(): ReadonlyMap<string, string> {
return offenders;
}
/** Files whose bundler interop the rewrite could not finish this attempt,
* with their package and reason. A file refuses its package only when
* the compiled program can load it (npmStaticLoadableFiles): a package is
* judged by what its imported subpaths reach, not by every file it ships. */
const fileDegrades = new Map<string, { pkg: string; reason: string }>();
export function npmStaticFileDegrades(): ReadonlyMap<string, { pkg: string; reason: string }> {
return fileDegrades;
}
function reportFileDegrade(path: string, pkg: string, reason: string): void {
const key = path.split("\\").join("/");
if (!fileDegrades.has(key)) fileDegrades.set(key, { pkg, reason });
}
/** The DefinitelyTyped name mangling ("@scope/pkg" → "scope__pkg") — the
* @types twin that must hide alongside the package's own declarations. */
function mangledTypesName(name: string): string {
@@ -135,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
@@ -362,7 +428,36 @@ export function npmStaticFsShadow(services: FrontendServices): NpmStaticFsShadow
if (hit !== undefined) return hit ?? undefined;
let rewritten: string | null = null;
try {
const original = trackedReadFile(path);
let original = trackedReadFile(path);
// A bundle's CommonJS chunks move to their own modules first, so
// every later pass (and this shadow, for each chunk) sees plain
// CommonJS module text.
const split = original === null ? null : services.splitCjsChunks(original, path);
if (split !== null && "degrade" in split) {
reportFileDegrade(path, target.pkg, split.degrade);
original = null;
} else if (split !== null) {
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;
// A module that names its export object through a variable reaches
// its members through `exports`.
const exportsVar = original === null ? null : services.cjsExportsVar(original, path);
if (exportsVar !== null) original = exportsVar;
const respelled =
split !== null || esm !== null || fnExports !== null || exportsVar !== null;
if (original !== null) {
const namepaths = services.jsDocNamepaths(path, original);
const source = namepaths ?? original;
@@ -385,9 +480,11 @@ export function npmStaticFsShadow(services: FrontendServices): NpmStaticFsShadow
classFields?.text ??
source,
path,
(live) => liveExportFiles.add(live.split("\\").join("/")),
(file, names) => lexerNames.set(file.split("\\").join("/"), names),
);
if (answer !== null && typeof answer === "object") {
reportNpmStaticOffender(target.pkg, answer.degrade);
reportFileDegrade(path, target.pkg, answer.degrade);
} else {
rewritten =
answer ??
@@ -395,7 +492,8 @@ export function npmStaticFsShadow(services: FrontendServices): NpmStaticFsShadow
propertyProjected?.text ??
findWidened?.text ??
classFields?.text ??
namepaths;
namepaths ??
(respelled ? original : null);
}
}
} catch {
@@ -434,10 +532,32 @@ function looksUnminified(source: string): boolean {
return source.length / lines.length <= 200;
}
/** A whitespace/syntax-minified bundler dist whose interop helpers keep
* their names (`var __toESM=…,__toCommonJS=mod=>…`): the recognizers
* verify those shapes and refuse the package precisely when they cannot,
* so the minification heuristic need not refuse it up front. */
function namedBundlerHelpers(source: string): boolean {
return /\b__(?:toCommonJS|commonJS|toESM)\d*\s*=\s*(?:\(|[A-Za-z_$][\w$]*\s*=>)/.test(source);
}
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
@@ -446,17 +566,23 @@ 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);
if (source === null) return `its runtime entry ${jsEntry} cannot be read`;
if (!looksUnminified(source)) return "its shipped JS looks minified";
if (!looksUnminified(source) && !namedBundlerHelpers(source))
return "its shipped JS looks minified";
if (hasTransformMarkers(source)) {
return "its shipped JS carries build-transform markers (bundled/transpiled dist)";
}
+30 -4
View File
@@ -10,11 +10,14 @@ import {
checkPreflight,
isNodeTypesPath,
locOf,
npmStaticLoadableFiles,
requiresOf,
resolveNpmImport,
type LoadResult,
} from "./program.js";
import {
definitelyTypedMismatch,
npmStaticFileDegrades,
npmStaticIneligibleReason,
npmStaticOffenders,
npmStaticPackageOfPath,
@@ -217,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;
@@ -254,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
@@ -458,6 +475,15 @@ function loadFrontend(
const typecheckRefused = new Set<string>();
while (effective.size > 0) {
const reasons = new Map<string, string>(npmStaticOffenders());
// Bundler interop the rewrite could not finish refuses its package
// only where the compiled program can load the file.
if (npmStaticFileDegrades().size > 0) {
const loadable = npmStaticLoadableFiles(load.program, load.moduleOrder);
for (const [file, { pkg, reason }] of npmStaticFileDegrades()) {
if (!reasons.has(pkg) && (loadable === null || loadable.has(file)))
reasons.set(pkg, reason);
}
}
for (const d of preflight) {
const pkg = npmStaticPackageOfPath(d.loc.file);
if (pkg !== null && !reasons.has(pkg))
+232 -2
View File
@@ -68,6 +68,8 @@ import {
isNpmStaticPackage,
npmStaticActive,
npmStaticFsShadow,
npmStaticLexerVisibleNames,
npmStaticLiveExportTable,
npmStaticPackageOfPath,
reportNpmStaticOffender,
setNpmStaticDeclarationOverloads,
@@ -1438,6 +1440,8 @@ export function requireBindingEarlyUse7(
k: number,
decl: ts.VariableDeclaration,
precedingDecls: readonly ts.VariableDeclaration[],
/** A reference of the binding whose early evaluation is known exact. */
exactEarlyRead?: (reference: ts.Identifier) => boolean,
): ts.Identifier | null {
const checker = program.getTypeChecker();
const bindings = new Set<ts.Symbol>();
@@ -1669,6 +1673,7 @@ export function requireBindingEarlyUse7(
const sym = symbolOf(n);
if (sym === undefined) return undefined;
if (bindings.has(sym)) {
if (exactEarlyRead?.(n) === true) return undefined;
hit = n;
return "stop";
}
@@ -3119,6 +3124,16 @@ function cjsCycleRefusal7(
// anything else can change what a module of the cycle observes.
let stray: ts.Node | null = null;
const settled = new Set(stmts.slice(0, firstEntry).filter(exportStatement));
// A bundler export table the rewrite certified (npmStaticLiveExportTable)
// stands for the live getter object the original installed before its
// first require: the tail table settles as if it ran there.
const tail = stmts[stmts.length - 1];
if (
tail !== undefined &&
npmStaticLiveExportTable(m.fileName) &&
cjsExportAssignmentOf(tail)?.kind === "table"
)
settled.add(tail);
ts.walkPreorder(m, (n) => {
if (stray !== null) return "stop";
if (ts.isStatement(n) && settled.has(n)) return "skip";
@@ -3171,7 +3186,9 @@ function cjsCycleRefusal7(
if (req.decl === null) continue;
const dep = resolveImport7(program, m, req.spec, "require");
if (dep === null || !members.has(dep)) continue;
const reached = requireBindingEarlyUse7(program, m, stmts.length, req.decl, []);
const reached = requireBindingEarlyUse7(program, m, stmts.length, req.decl, [], (id) =>
functionExportRead7(id, dep),
);
if (reached !== null) {
return `the top-level code of ${m.fileName} can use its binding '${reached.text}' of a module of the cycle (${lineOf(reached)}) while the cycle initializes`;
}
@@ -3181,6 +3198,161 @@ function cjsCycleRefusal7(
return null;
}
/** True when `use` initializes a top-level const whose every other
* reference is a value of an export statement (`module.exports = { … }`
* or `exports.n = …`). */
function publishedAlias7(use: ts.Node, decl: ts.Node | undefined): boolean {
if (
decl === undefined ||
!ts.isVariableDeclaration(decl) ||
decl.initializer !== use ||
!ts.isIdentifier(decl.name)
)
return false;
const list = decl.parent;
const stmt = list?.parent;
const sf = stmt?.parent;
if (
list === undefined ||
(list.flags & ts.NodeFlags.Const) === 0 ||
stmt === undefined ||
!ts.isVariableStatement(stmt) ||
sf === undefined ||
!ts.isSourceFile(sf)
)
return false;
const alias = decl.name;
const published = new Set<ts.Node>();
for (const st of sf.statements.nodes) {
const cjs = cjsExportAssignmentOf(st);
if (cjs === null) continue;
if (cjs.kind === "member") published.add(cjs.value);
else if (cjs.obj !== null) {
for (const p of cjs.obj.properties.nodes) {
if (ts.isPropertyAssignment(p) && !ts.isComputedPropertyName(p.name))
published.add(p.initializer);
else if (ts.isShorthandPropertyAssignment(p)) published.add(p.name);
}
}
}
let kept = false;
ts.walkPreorder(sf, (n) => {
if (kept) return "stop";
if (!ts.isIdentifier(n) || n === alias || n.text !== alias.text) return undefined;
const p = n.parent;
if (
p !== undefined &&
((ts.isPropertyAccessExpression(p) && p.name === n) ||
(ts.isPropertyAssignment(p) && p.name === n))
)
return undefined;
if (!published.has(n)) kept = true;
return undefined;
});
return !kept;
}
/** True for a plain read `binding.name` (not a call, not a write, not a
* value that is stored or passed on) of the cycle member `dep` whose
* export `name` is a top-level function declaration nothing reassigns.
* Every member settles its exports before entering the cycle, so Node
* reads that same function whenever the read runs, and the compiled read
* resolves to the declaration itself. */
function functionExportRead7(id: ts.Identifier, dep: ts.SourceFile): boolean {
const access = id.parent;
if (!ts.isPropertyAccessExpression(access) || access.expression !== id) return false;
// The value the read yields: through parentheses and the right operand
// of a comma, so `(0, binding.name)(...)` is the call it spells.
let use: ts.Node = access;
for (;;) {
const p = use.parent;
if (ts.isParenthesizedExpression(p)) use = p;
else if (
ts.isBinaryExpression(p) &&
p.operatorToken.kind === ts.SyntaxKind.CommaToken &&
p.right === use
)
use = p;
else break;
}
const parent = use.parent;
// Only a use that neither runs the function nor keeps it is a read: a
// stored alias (`const f = binding.name`, `{ f: binding.name }`) or an
// argument can be called while the cycle initializes. A top-level const
// that only publishes it (`module.exports = { name: f }`, the static
// rewrite's re-export spelling) runs nothing: a module that reads the
// export back checks that read itself.
const observes =
publishedAlias7(use, parent) ||
ts.isExpressionStatement(parent) ||
ts.isTypeOfExpression(parent) ||
ts.isVoidExpression(parent) ||
(ts.isPrefixUnaryExpression(parent) && parent.operator === ts.SyntaxKind.ExclamationToken) ||
(ts.isBinaryExpression(parent) &&
(parent.operatorToken.kind === ts.SyntaxKind.EqualsEqualsEqualsToken ||
parent.operatorToken.kind === ts.SyntaxKind.ExclamationEqualsEqualsToken ||
parent.operatorToken.kind === ts.SyntaxKind.EqualsEqualsToken ||
parent.operatorToken.kind === ts.SyntaxKind.ExclamationEqualsToken)) ||
((ts.isIfStatement(parent) || ts.isWhileStatement(parent) || ts.isDoStatement(parent)) &&
parent.expression === use) ||
(ts.isConditionalExpression(parent) && parent.condition === use);
if (!observes) return false;
const name = access.name.text;
// The exported value's identifier: a table entry or a member export.
const values: ts.Expression[] = [];
for (const stmt of dep.statements.nodes) {
if (!ts.isExpressionStatement(stmt) || !ts.isBinaryExpression(stmt.expression)) continue;
const e = stmt.expression;
if (e.operatorToken.kind !== ts.SyntaxKind.EqualsToken) continue;
if (isModuleExportsAccess(e.left)) {
if (!ts.isObjectLiteralExpression(e.right)) return false;
for (const p of e.right.properties.nodes) {
if (ts.isSpreadAssignment(p)) return false;
if (ts.isShorthandPropertyAssignment(p) && p.name.text === name)
values.push(p.name as ts.Identifier);
else if (
ts.isPropertyAssignment(p) &&
(ts.isIdentifier(p.name) || ts.isStringLiteral(p.name)) &&
p.name.text === name
)
values.push(p.initializer);
}
} else if (
ts.isPropertyAccessExpression(e.left) &&
e.left.name.text === name &&
((ts.isIdentifier(e.left.expression) && e.left.expression.text === "exports") ||
isModuleExportsAccess(e.left.expression))
) {
values.push(e.right);
}
}
const value = values.length === 1 ? values[0]! : null;
if (value === null || !ts.isIdentifier(value)) return false;
const fnName = value.text;
if (
!dep.statements.nodes.some(
(st) => ts.isFunctionDeclaration(st) && st.name?.text === fnName && st.body !== undefined,
)
)
return false;
let rebound = false;
ts.walkPreorder(dep, (n) => {
if (rebound) return "stop";
if (
(ts.isBinaryExpression(n) &&
ts.isIdentifier(n.left) &&
n.left.text === fnName &&
n.operatorToken.kind >= ts.SyntaxKind.FirstAssignment &&
n.operatorToken.kind <= ts.SyntaxKind.LastAssignment) ||
(ts.isVariableDeclaration(n) && ts.isIdentifier(n.name) && n.name.text === fnName) ||
(ts.isFunctionDeclaration(n) && n.name?.text === fnName && !ts.isSourceFile(n.parent))
)
rebound = true;
return undefined;
});
return !rebound;
}
/* ── exact cyclic initialization ─────────────────────────────────────────
* Cycles that fail the declaration-only rule still evaluate exactly like
* Node when their shape is representable: the guarded %init calls already
@@ -5349,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. */
@@ -5930,6 +6108,58 @@ export function orderedImportsOf(
return out;
}
/** The files a compiled program can load: the module order closed over
* every literal require() and import() call it contains (deferred and
* nested ones included) and, for opted-in package JavaScript, over every
* import and export declaration as well. A package file outside this set
* is reachable only through types, so whatever it spells cannot affect
* the compiled program. Null when a reachable file loads a computed
* specifier: then any file may load. */
export function npmStaticLoadableFiles(
program: ts.Program,
moduleOrder: readonly ts.SourceFile[],
): Set<string> | null {
const seen = new Set<ts.SourceFile>();
const work: ts.SourceFile[] = [];
const add = (sf: ts.SourceFile | null | undefined): void => {
if (sf === null || sf === undefined || seen.has(sf) || sf.isDeclarationFile) return;
seen.add(sf);
work.push(sf);
};
for (const sf of moduleOrder) add(sf);
let computed = false;
while (work.length > 0 && !computed) {
const sf = work.pop()!;
const packageJs =
npmStaticPackageOfPath(sf.fileName) !== null && isJsSourceFileName(sf.fileName);
const follow = (spec: string, kind: "import" | "require"): void => {
if (canonicalBuiltinModule(spec) !== null) return;
add(resolveImport7(program, sf, spec, kind) ?? npmStaticDepSf7(program, sf, spec, kind));
};
ts.walkPreorder(sf, (n) => {
if (computed) return "stop";
if (ts.isCallExpression(n)) {
const isImport = n.expression.kind === ts.SyntaxKind.ImportKeyword;
const isRequire = ts.isIdentifier(n.expression) && n.expression.text === "require";
if (!isImport && !isRequire) return undefined;
const arg = n.arguments.nodes[0];
if (arg !== undefined && ts.isStringLiteralLike(arg))
follow(arg.text, isImport ? "import" : "require");
else if (packageJs || isImport) computed = true;
} else if (
packageJs &&
(ts.isImportDeclaration(n) || ts.isExportDeclaration(n)) &&
n.moduleSpecifier !== undefined &&
ts.isStringLiteral(n.moduleSpecifier)
) {
follow(n.moduleSpecifier.text, "import");
}
return undefined;
});
}
return computed ? null : new Set([...seen].map((sf) => sf.fileName.split("\\").join("/")));
}
/** The program source file a bare specifier reaches when it names an
* opted-in --npm-static package (the shipped-JS entry preflight admitted
* as a module edge), else null. No offender reporting here — preflight
+23 -1
View File
@@ -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,
+51 -3
View File
@@ -1,8 +1,15 @@
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,
type BundledChunkSplit,
} from "./npm-static-bundled-chunks.js";
import * as syntax from "./npm-static-declaration-syntax.js";
import { normalizeCjsExportsVar } from "./npm-static-cjs-exports-var.js";
import type { SourceFile } from "./ts7/ast-types.js";
/** Evaluate an isolated, self-contained TypeScript callback under a finite
@@ -55,10 +62,51 @@ export class FrontendServices {
this.ensureOpen();
return new Ts7Host(this.createApi, { ...options, cwd: options?.cwd ?? this.cwd });
}
rewriteCjs(source: string, path: string): string | { degrade: string } | null {
rewriteCjs(
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);
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). */
splitCjsChunks(source: string, path: string): BundledChunkSplit | { degrade: string } | null {
this.ensureOpen();
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"));
}
/** A CommonJS module that names its export object through a variable
* (`var ip = exports`), its member accesses respelled through `exports`
* (null: none). */
cjsExportsVar(source: string, path: string): string | null {
this.ensureOpen();
if (!source.includes("exports")) return null;
return normalizeCjsExportsVar(this.parse(path, source, "js"));
}
nullableClassFields(path: string, source: string): syntax.NpmStaticOverloadRewrite | null {
return syntax.applyNpmStaticNullableClassFields(this.parse(path, source, "js"), source);

Some files were not shown because too many files have changed in this diff Show More