diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bbc9ddb10..5a100e374 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -364,6 +364,20 @@ jobs: target: wasm32-wasi helper: "false" - run: pnpm build + # The sanitized seed compiles the compiler's 700 MB module with one clang + # process under AddressSanitizer. It peaks near 14 GB while the Node + # process that emitted the module still holds about 6 GB. Together they + # exceed the runner's 16 GB of memory, so back them with swap. + - name: Enlarge swap for the sanitized seed + if: matrix.flavor == 'san' + run: | + sudo swapoff -a + sudo rm -f /mnt/swapfile + sudo fallocate -l 24G /mnt/swapfile + sudo chmod 600 /mnt/swapfile + sudo mkswap /mnt/swapfile + sudo swapon /mnt/swapfile + free -h - name: Prepare bootstrap seed run: node scripts/bootstrap-seed.mjs env: diff --git a/.oxlintrc.jsonc b/.oxlintrc.jsonc index 0c5cad25f..b0acea28a 100644 --- a/.oxlintrc.jsonc +++ b/.oxlintrc.jsonc @@ -241,6 +241,7 @@ "packages/compiler/src/frontend/comptime-node.ts", "packages/compiler/src/frontend/ts7/world-check.ts", "packages/compiler/src/frontend/ts7/source-parser.test.ts", + "packages/compiler/src/frontend/jsx-source.test.ts", "packages/compiler/src/frontend/npm-static-rewrite.ts", "packages/compiler/src/frontend/npm-static-bundled-cjs.ts", "packages/compiler/src/library/semantic-source.ts", diff --git a/CHANGELOG.md b/CHANGELOG.md index 31d34e8db..ec0b27dbf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,161 @@ All notable changes to scriptc will be documented in this file. +## 0.4.2 + +### Highlights + +- **Faster builds of large programs:** + - scriptc checks with tsc-ts 0.0.7, which answers contextual types and resolved signatures in batches, so lowering asks for them in one request per chunk instead of one per node. A native build of tsc-ts is 7% faster (110.5 → 103.5 s on 8 vCPUs, lowering 12% faster), with an identical executable. + - The native compiler is built with profile-guided optimization, so tsc-ts builds 6.9% faster cold and 10.7% faster after an edit. + - The native compiler's optimization profile is refreshed, so a native build of tsc-ts is a further 10% faster (124.7 → 111.7 s on 16 vCPUs), with lowering 17% faster. + - The class dispatch passes index their receivers by name instead of testing each one, and they reuse their per-function scans while a function's body is unchanged. + - Checker replies resolve objects the compiler already holds from their ids without decoding them. +- **Leaner builds:** + - The frontend of an optimized executable's first build runs in a child process, so the native code generator starts after its memory is released. The cold build of tsc-ts peaks at 2.21 GB instead of 3.30 GB. + - The compiler collects its heap as lowering and LLVM emission grow it. +- **WebCrypto:** + - The `crypto` global, `node:crypto`'s `webcrypto` and `crypto.subtle` are one object. + - `generateKey`, `importKey`, `exportKey`, `encrypt`, `decrypt`, `deriveBits`, `deriveKey`, `wrapKey` and `unwrapKey` cover HMAC, AES-GCM, AES-CBC, AES-CTR, AES-KW, PBKDF2, HKDF and JSON Web Keys. + - `crypto.subtle` signs and verifies with ECDSA, RSASSA-PKCS1-v1_5, RSA-PSS and Ed25519. + - All of it follows Node 24's argument conversion, algorithm normalization and `DOMException`s. jose's symmetric JWE paths run as in Node. +- **JSX:** `.tsx`, `.jsx` and JavaScript files with JSX compile under the project's `jsx` options. + - `react`, `react-jsx` and `react-jsxdev` lower to the factory calls TypeScript emits, with the same keys, fallbacks and source positions. + - `preserve` and `react-native` are refused with a named diagnostic. +- **Faster worker messages:** + - A message is encoded into one block sized to its contents. + - A typed record is posted from its fields. + - A `'message'` listener with a typed parameter builds it from the message, without a checked-dynamic copy. + - Messages between `MessageChannel` ports take 90 ms where they took 250 ms in 0.4.1 (Node: 337 ms), with a peak RSS of 45 MB instead of 115 MB. +- **Loops over typed arrays vectorize:** a loop to a typed array's length keeps one bounds test for every typed array it indexes. + - Index temporaries such as `const j = i * 4` are computed as integers. + - Uint8ClampedArray stores convert inline. + - Row-major index terms such as `r * cols + j` are tested once before the loop. + - Typed-array callback methods call a literal callback directly on an integer counter. + - An 896 × 896 matrix-vector product with four accumulators takes 55 ms instead of 396 ms (Node: 275 ms). `Uint8Array.map` is 4.5 times as fast and `Int32Array.some` 7.8 times as fast as in 0.4.1. + +### Features + +- **Asymmetric keys and signatures in `node:crypto`:** + - `generateKeyPair`, `generateKeyPairSync`, `createPrivateKey` and `createPublicKey` handle RSA, EC and Ed25519 keys in PEM, DER and JWK. + - `sign`, `verify`, `createSign` and `createVerify` sign and verify with those keys, with Node's output and errors. + - Ed25519 verification matches Node on 2,083 test vectors, including small-order and mixed-order keys. +- **`crypto.createDiffieHellman`, `crypto.getDiffieHellman` and `crypto.createDiffieHellmanGroup`:** + - The modp1, modp2 and modp5 to modp18 groups, explicit primes and generators, and generated safe primes are supported, with Node 24's key widths, `verifyError` bits, key range checks and errors. + - Secrets of 0, 1 and p − 1 are rejected, and so are peer keys outside the RFC 5114 subgroups. + - Primes longer than 8192 bits are refused. +- **TLS:** + - `tls.connect` and `tls.createServer` negotiate `ALPNProtocols`, and both sockets report `alpnProtocol`. `minVersion` and `maxVersion` bound the handshake, and `getProtocol()` reports the version it picked. + - `tls.createServer` takes an `SNICallback` that answers a `SecureContext` synchronously or later. + - `new tls.TLSSocket(socket, { isServer: true, ... })` and `tls.connect({ socket })` run the handshake on an open socket, such as an HTTP `CONNECT` tunnel. + - A client whose peer closes before the handshake completes fails with Node's `ECONNRESET`. +- **Streams:** + - Readable, Writable, Duplex, Transform and PassThrough streams take `objectMode`, `readableObjectMode` and `writableObjectMode`, and an object-mode side carries any value through `push`, `write`, `pipe`, `pipeline`, `for await` and `'data'` listeners. + - `_write` and `_transform` receive the encoding argument as Node passes it. + - `Cipheriv` and `Decipheriv` are Transforms: they can be piped, used as `pipeline()` stages, read and iterated. + - `pipeline()` accepts function stages anywhere among its streams, and an array, a string or a synchronous generator as its source. +- **Packages compiled from their JavaScript:** + - js-yaml and smol-toml compile statically and match Node: ES5 error constructors (`Object.create(Error.prototype)`, `Error.call(this)`, `Error.captureStackTrace`) and classes extending `Date` behave as in Node. + - TypeScript's UMD module wrapper compiles as the module body, and tsc's `__importDefault` and `__importStar` helpers around builtin modules compile as plain `require()` calls. + - Interfaces, type aliases and enums that only a package's `.d.ts` declares keep their types. +- **JavaScript sources:** + - Error constructors can be read as values, so `err.constructor === TypeError` works. + - `workerData` can be destructured. + - Unary `+` converts unions of strings, numbers, booleans, `null` and `undefined` as `Number()` does, so `+process.argv[2]` compiles. + - These compile and behave as in Node: + - chained readline listener registration; + - `Number.parseInt` without a radix; + - `match` and `search` with a possibly undefined regular expression; + - `Buffer.from` over an untyped `ArrayBuffer`, with its byte offset; + - Atomics on untyped arrays. + - Buffer methods run on Buffers held as untyped values. +- **`fs`:** + - The synchronous functions (`readFileSync`, `writeFileSync`, `statSync`, `readdirSync`, `mkdirSync`, `rmSync`, `openSync` and the others) accept `file:` URLs wherever they accept a path, with Node's conversion errors. + - `fs.promises.rm` takes `recursive`, `force`, `maxRetries` and `retryDelay`, and removing a directory without `recursive` throws Node's `ERR_FS_EISDIR`. +- **`TypedArray.of`** creates a typed array of its arguments, and a dynamic iterable spread into `Array.of`, `push` or `TypedArray.of` is drained through the iterator protocol. +- **Global `isFinite` converts its argument with ToNumber,** as `isNaN` does. The Math functions and `String.fromCharCode` evaluate every argument before converting any. +- **`Object.freeze`, `Object.seal` and `Object.preventExtensions` of a function** act on its own properties, and `Object.isFrozen`, `Object.isSealed` and `Object.isExtensible` answer for functions. @noble/hashes' frozen hashers work. +- **EventEmitters used through both typed and untyped references** share one listener list. An untyped `emit` reaches typed listeners, an untyped `emit('error')` follows Node's contract, and `listenerCount`, `eventNames`, `listeners`, `rawListeners`, `removeAllListeners`, `setMaxListeners` and `getMaxListeners` work on untyped values. +- **Template literals, `join`, `Array.prototype.toString` and the default `sort()`** call an object's own or inherited `toString`, as `String()` does, instead of printing `[object Object]`. +- **Classes and generics:** + - A generic factory declared to return a constructor type can return one of its local classes, including an anonymous class expression, and `class X extends factory(...)` extends it. + - Static methods of a function-local class compile. + - Constructor types declared in the program (`new () => unknown`, types that also name static members, construct overloads) hold class values. + - Members typed by a conditional type over a literal class type argument (`Field`) resolve. + - Object literals under an erased generic member may hold callbacks with optional or defaulted parameters. +- **Assignment and update targets wrapped in parentheses or non-null assertions** (`(x) = 1`, `h.sums[k]! += 10`) compile. +- **Untyped values keep what JavaScript code adds:** + - Properties that untyped code adds to a typed object literal stay on it. + - Named properties written to an array through an `unknown` view stay on the array, and `for...in` visits them after the indices. + - An `unknown` value asserted to a structural type with methods keeps its class's methods. + - The type inferred from an empty object literal holds any non-nullish value, as TypeScript's `{}` does. +- **A WebAssembly module the build finds but does not translate** rejects with a `CompileError` that names the reason, for example a proposal outside the translated feature set. +- **SC6101 names the functions that likely run often and use untyped values:** + - It shows up to five, most likely hot first, with why their values are untyped: an `any`, an untyped `JSON.parse` result or an untyped JavaScript file. + - `scriptc coverage --fail-on=dynamic` fails on it, and `--no-dynamic-tier-warning` leaves it out. + +### Performance + +- **Regular expressions skip start positions that their leading character sets rule out,** testing 16 positions at once. Searching 50 MB of text for nine case-insensitive alternations takes 0.83 s instead of 3.88 s (Node: 4.38 s). +- **Loop counters stay integers in more loops:** + - Counters that step beside a counted loop's counter (`for (let i = 0, p = 0; i < n; i++, p += 4)`) stay integers: a pixel-stride loop takes 114 ms instead of 340 ms (Node: 190 ms). + - So do two counters that close in on each other (`lo++, hi--`), 17% faster on a permutation-reversal loop. + - So do counters of loops bounded by a string's length or by an invariant limit other than an array's length, and while-loop counters that nested scans advance. A non-ASCII lexer is 9.5% faster. +- **Loops that call a known callback** test its closure once before the loop and call the function directly, so captured `let` bindings stay in registers. `forEach` sums with a captured accumulator are 25 to 55% faster. +- **A speculative integer loop whose check fails** finishes the iteration outside the ordinary loop, which stays optimizable, and a loop site that keeps failing stops trying. With the hole-free-prefix test that element reads now take first, a pairwise loop over an array of class instances with number fields is about 1.25 times as fast as in 0.4.1. +- **Typed arrays over a SharedArrayBuffer** read and write elements inline as relaxed atomic accesses. A numeric kernel over shared `Float64Array`s takes 0.78 s instead of 1.56 s (Node: 0.84 s). +- **`Math.pow(2, n)` for integer exponents** builds the result from its bits. A counter that masks with `Math.pow(2, length)` takes 11.0 s instead of 20.4 s. +- **Async calls that never suspend run in place,** and so does `await Promise.all` of such calls, with Node's microtask turns and rejection handling. An async pipeline takes 5.5 ms instead of 9.7 ms. +- **Strings:** + - `Number()` of a short integer string returns the integer directly. + - `split` builds its result in one inline block, and `indexOf` and `slice` on ASCII strings skip the UTF-16 index map. A log summary is 20% faster. + - `charAt` and `s[i]` on ASCII strings read the character from a table. + - Chains of one-character `replace` calls (the HTML-escape idiom) replace a block of 16 bytes at a time, 12.8% faster on a template renderer. +- **`JSON.parse` and `JSON.stringify`** scan whole words and append parsed typed arrays in bulk, 22% faster to parse and 10% faster to stringify records. +- **Smaller arrays, maps and program-lifetime instances:** + - The array header is 32 bytes instead of 48. + - Arrays of up to 16 known elements keep their slots in their own block. + - Arrays of a known final length get exactly that capacity. + - Small map entry arrays grow in finer steps. + - On Linux, `ProgramLifetime` instances take a 32-bit header and are referenced in 4 bytes. + - They lower the peak memory of a large TypeScript type checker: the 4-byte references alone take a large project's check from 4.13 GB to 3.75 GB, and the 32-bit header saves a further 5%. +- **Worker messages queued together are delivered in one batch** before immediates run. 20,000 messages interleaved with a worker's output drain in 0.5 s instead of 5.6 s (Node: 0.57 s). +- **The cycle collector** never buffers instances of classes whose fields hold nothing cycle-capable, and its per-object paths are shorter. A workload of cyclic graphs is about 5% faster. +- **Array helpers specialized for a callback that cannot throw** skip the pending-exception test, 4.5% faster on a functional pipeline. +- **Compile time:** + - A file's function declarations are walked once for their references, so lowering a 10 MB single-module bundle takes 69 s instead of 219 s. + - LLVM emission computes its module facts once, 6.9% faster on tsc-ts. + - AST walks visit subtrees by their node ranges and read node words through a `Uint32Array`. + - Program builds no longer import runtime bitcode, so builds through Node and through the native compiler produce identical executables. + +### Fixes + +- **Member reads and method calls on an array hole** held in a binding narrowed to one arm of a wide union throw Node's `Cannot read properties of undefined` TypeError. +- **`AsyncLocalStorage`:** + - A store entered before an async function's first await, or in a body that never suspends, is the caller's store after the call. + - Each synchronous generator step runs in its resumer's context, as in Node. +- **Generic arrow and function-expression bindings used before their declarations** behave as in Node, including the `ReferenceError` of a `let` or `const`. +- **Assignment expressions into a module `let` declared without an initializer** (`new Promise((r) => (resolve = r))`) store the value instead of throwing a `ReferenceError`. +- **The `extends` expression of a class defined inside a function** is evaluated each time the definition runs. +- **A `super()` call that leads an `if` condition's comma chain** compiles. +- **A catch binding tests `instanceof`** correctly for values thrown as `unknown`, rejected promises and runtime errors. +- **zlib callbacks receive `undefined` as their result when the operation fails,** as in Node, and a callback may assign a fallback to it. +- **`Readable.push` and `Writable.write` with `string | null` or `Buffer | null` chunks** no longer crash. +- **Object literals keep their key order** through compiler rewrites and on shapes a typed `JSON.parse` also builds, so `JSON.stringify`, `Object.keys` and `console.log` match Node. +- **`console.log` prints class instances with their class name** in programs that test `instanceof` on unknown values. +- **`String`, `Number` and `Boolean` passed to array methods** convert as their direct calls do, and nested array literals in a recursive JSON-style union build. +- **A dynamic method call that the program also reads through a prototype** finds the method when the instance's property bag does not hold it. +- **Storing an element on `Array.prototype`** fails with SC2020, because holes in native arrays do not read inherited elements. +- **A recursive type alias in a generic signature** no longer crashes the compiler. +- **A `Buffer` view of an untyped typed array** compiles. +- **JSX programs checked with tsgo** compile as they do with tsc-ts. +- **Two programs whose entries share a name and build into one directory** no longer share a cached translation unit, so a later cache hit always relinks the right program. +- **A warm build whose cached LLVM exceeds the engine's string limit** reads it in parts instead of failing with `Invalid string length`. +- **The same program compiles to the same executable wherever it sits on disk** and whatever order its functions lower in, and edits outside a declaration do not rename the helpers and closures inside it. +- **Libraries that use untyped byte arrays** link. + + + ## 0.4.1 ### Highlights @@ -77,8 +232,6 @@ All notable changes to scriptc will be documented in this file. - **TypeScript enum exports in compiled packages stay `undefined` until they are assigned,** as in Node. - **Element writes accept a possibly undefined index** (typed-array writes, compound and update writes, element assignments used as values and destructuring targets) and convert it with ToNumber, as element reads already did. - - ## 0.4.0 ### Breaking changes diff --git a/benchmarks/runtime/README.md b/benchmarks/runtime/README.md index cbf47675a..e177e36c0 100644 --- a/benchmarks/runtime/README.md +++ b/benchmarks/runtime/README.md @@ -11,6 +11,7 @@ Application-shaped workloads for measuring the speed of compiled executables. Ea | `channel-messages` | cpu | 200,000 MessageChannel messages in one thread, half numbers and half small objects, all posted before the port delivers any | | `csv-numbers` | cpu | `split`, `Number`, `parseInt`, `toFixed` | | `cyclic-graphs` | cpu | object graphs with back references built and dropped: trees with parent and sibling links, rings of records sharing a long-lived registry, closures capturing their owner | +| `dictionary-walks` | cpu | `Record` dictionaries walked with for-in and `Object.keys`/`values`/`entries` while entries are added, updated and deleted | | `functional-pipeline` | cpu | `filter`/`map`/`reduce`/`flatMap` chains, closures, small records | | `intern-table`, `intern-table-map`, `intern-table-1`, `intern-table-map-1` | cpu | worker threads interning the same type-like objects under string keys and records under number keys, then hits and misses: one shared `InternTable` per kind of key, or a module-level `Map` per thread (the `-map` entries), with 8 threads or 1 (the `-1` entries); under Node.js every thread has its own tables | | `json-records` | cpu | `JSON.stringify`, typed `JSON.parse`, Map aggregation | @@ -26,7 +27,7 @@ Application-shaped workloads for measuring the speed of compiled executables. Ea | `region-builds` | cpu | a watch-mode build loop over `LifetimeRegion`: each build binds a program in a new region and releases the previous one, which a cache keeps referenced for two builds | | `template-render` | cpu | template literals, escaping, `map`/`join` | | `thread-slots`, `thread-slots-cache` | cpu | worker threads reading one published type graph from an `InternTable` and keeping per-thread state for each type they visit: a `ThreadSlots` family, or a direct-mapped cache by id in front of a `Map` by id (the `-cache` entry); under Node.js both are per thread | -| `typed-array-kernels` | cpu | element-wise loops that run to one typed array's length and index others at the same position: `Float64Array` axpy, `Float32Array` blend, `Uint8Array` mask, wrapping `Int32Array` add, `Uint8ClampedArray` brighten, RGBA to gray | +| `typed-array-kernels` | cpu | element-wise loops that run to one typed array's length and index others at the same position: `Float64Array` axpy, `Float32Array` blend, `Uint8Array` mask, wrapping `Int32Array` add, `Uint8ClampedArray` brighten, RGBA to gray, a row-major `Float32Array` matrix-vector product, and `reduce`/`some`/`map` callbacks | | `typed-array-scan`, `typed-array-scan-workers` | cpu | element-by-element scan loops over `Uint8Array`, `Uint16Array`, `Int32Array` and `Float64Array`; the second entry is a worker-enabled executable (it can start a worker), so each access also checks for shared storage | | `unicode-lexer` | cpu | a hand-written lexer over a 2.7M-unit bundled module whose comments and strings are in several languages: `charCodeAt` scans, line starts | | `validate-errors` | cpu | throw/catch on a fraction of inputs, small call chains | diff --git a/benchmarks/runtime/workloads/dictionary-walks.json b/benchmarks/runtime/workloads/dictionary-walks.json new file mode 100644 index 000000000..ebfb6ea3f --- /dev/null +++ b/benchmarks/runtime/workloads/dictionary-walks.json @@ -0,0 +1,6 @@ +{ + "entry": "workloads/dictionary-walks.ts", + "args": [ + "1" + ] +} diff --git a/benchmarks/runtime/workloads/dictionary-walks.ts b/benchmarks/runtime/workloads/dictionary-walks.ts new file mode 100644 index 000000000..30b18be63 --- /dev/null +++ b/benchmarks/runtime/workloads/dictionary-walks.ts @@ -0,0 +1,53 @@ +// String-keyed dictionaries (`Record`) walked with for-in, +// Object.keys, Object.values and Object.entries while entries are added, +// updated and deleted: per-category totals, a pruning pass and a merge. +let seed = 777; +function random(): number { + seed = (Math.imul(seed, 1103515245) + 12345) >>> 0; + return seed / 4294967296; +} + +const scale = Number(process.argv[2] ?? "1"); +const categories = 4000; +const counts: Record = {}; +for (let i = 0; i < Math.floor(200000 * scale); i++) { + const key = "c" + Math.floor(random() * categories); + counts[key] = (counts[key] ?? 0) + 1; +} + +let walked = 0; +let sum = 0; +for (let pass = 0; pass < 40; pass++) { + for (const key in counts) { + walked++; + sum += counts[key]!; + } +} + +// Prune: delete the small categories during the walk, including keys the +// walk has not reached yet. +let pruned = 0; +for (const key in counts) { + const n = counts[key]!; + if (n < 45) { + delete counts[key]; + pruned++; + } + const ahead = "c" + ((Number(key.slice(1)) + 1) % categories); + if (n > 60 && ahead in counts && counts[ahead]! < 45) { + delete counts[ahead]; + pruned++; + } +} + +// Merge into a second dictionary and read it back every way. +const merged: Record = {}; +for (const key of Object.keys(counts)) merged[key.toUpperCase()] = counts[key]! * 2; +let values = 0; +for (const v of Object.values(merged)) values += v; +let entries = 0; +for (const [key, v] of Object.entries(merged)) entries += key.length + v; + +console.log( + `walked ${walked}, sum ${sum}, pruned ${pruned}, kept ${Object.keys(counts).length}, values ${values}, entries ${entries}`, +); diff --git a/benchmarks/runtime/workloads/typed-array-kernels.ts b/benchmarks/runtime/workloads/typed-array-kernels.ts index ba68f7241..a17c09708 100644 --- a/benchmarks/runtime/workloads/typed-array-kernels.ts +++ b/benchmarks/runtime/workloads/typed-array-kernels.ts @@ -1,5 +1,6 @@ // Element-wise loops over several typed arrays: each loop runs to one -// array's length and reads or writes the others at the same index. +// array's length and reads or writes the others at the same index. Also a +// row-major matrix-vector product with four accumulators per row. function axpy(a: number, x: Float64Array, y: Float64Array, out: Float64Array): void { for (let i = 0; i < out.length; i++) out[i] = a * x[i]! + y[i]!; @@ -21,6 +22,31 @@ function brighten(src: Uint8ClampedArray, gain: number, out: Uint8ClampedArray): for (let i = 0; i < out.length; i++) out[i] = src[i]! * gain + 8; } +function matvec(w: Float32Array, x: Float32Array, out: Float32Array, cols: number): void { + for (let r = 0; r < out.length; r++) { + const base = r * cols; + let s0 = 0; + let s1 = 0; + let s2 = 0; + let s3 = 0; + for (let j = 0; j < cols; j += 4) { + s0 += w[base + j]! * x[j]!; + s1 += w[base + j + 1]! * x[j + 1]!; + s2 += w[base + j + 2]! * x[j + 2]!; + s3 += w[base + j + 3]! * x[j + 3]!; + } + out[r] = s0 + s1 + s2 + s3; + } +} + +// Callback methods over a whole typed array. +function callbacks(samples: Float32Array, limit: number, data: Uint8Array): number { + const energy = samples.reduce((sum, v) => sum + v * v, 0); + const loud = samples.some((v) => v > limit) ? 1 : 0; + const halved = data.map((v) => v >> 1); + return energy / samples.length + loud + halved[halved.length >> 1]!; +} + function gray(rgba: Uint8Array, out: Uint8Array): void { for (let i = 0; i < out.length; i++) { const j = i * 4; @@ -45,6 +71,10 @@ const io = new Int32Array(n); const pixels = new Uint8ClampedArray(n); const bright = new Uint8ClampedArray(n); const rgba = new Uint8Array(n * 4); +const side = 256; +const weights = new Float32Array(side * side); +const vector = new Float32Array(side); +const product = new Float32Array(side); const luma = new Uint8Array(n); let state = 2463534242; const next = (): number => { @@ -65,6 +95,8 @@ for (let i = 0; i < n; i++) { pixels[i] = next() & 255; } for (let i = 0; i < rgba.length; i++) rgba[i] = next() & 255; +for (let i = 0; i < weights.length; i++) weights[i] = (next() % 2001) / 1000 - 1; +for (let i = 0; i < side; i++) vector[i] = (next() % 1001) / 1000; const rounds = Math.round(1200 * scale); let f64Sum = 0; @@ -73,6 +105,8 @@ let byteSum = 0; let intSum = 0; let brightSum = 0; let lumaSum = 0; +let productSum = 0; +let callbackSum = 0; for (let r = 0; r < rounds; r++) { // Change one input element per round so no round repeats the last. const at = (r * 7919) & (n - 1); @@ -82,12 +116,15 @@ for (let r = 0; r < rounds; r++) { ia[at] = r * 65537; pixels[at] = r & 255; rgba[at * 4] = r & 255; + vector[r & (side - 1)] = (r % 1001) / 1000; axpy(1.5, x, y, d); blend((r & 15) / 16, fa, fb, fo); mask(data, key, masked); addWrap(ia, ib, io); brighten(pixels, 0.75 + (r & 7) / 8, bright); gray(rgba, luma); + matvec(weights, vector, product, side); + if ((r & 3) === 0) callbackSum += callbacks(fo, 140 + (r & 12), masked); const probe = (r * 104729) & (n - 1); f64Sum += d[probe]!; f32Sum += fo[probe]!; @@ -95,6 +132,7 @@ for (let r = 0; r < rounds; r++) { intSum = (intSum + io[probe]!) | 0; brightSum += bright[probe]!; lumaSum += luma[probe]!; + productSum += product[probe & (side - 1)]!; } console.log(`float64 ${f64Sum.toFixed(3)}`); console.log(`float32 ${f32Sum.toFixed(3)}`); @@ -102,3 +140,5 @@ console.log(`uint8 ${byteSum}`); console.log(`int32 ${intSum}`); console.log(`clamped ${brightSum}`); console.log(`gray ${lumaSum}`); +console.log(`matvec ${productSum.toFixed(3)}`); +console.log(`callbacks ${callbackSum.toFixed(3)}`); diff --git a/docs/content/docs/contracts.mdx b/docs/content/docs/contracts.mdx index 5af1cad2f..948fe7960 100644 --- a/docs/content/docs/contracts.mdx +++ b/docs/content/docs/contracts.mdx @@ -349,7 +349,7 @@ class Identifier extends SyntaxNode { } ``` -On Linux, except in builds with sanitizers, the instances also take less memory. An executable keeps them in one address range below 32 GiB that it reserves at startup (only the pages in use take memory), and a field typed `C`, `C | undefined` or `C | null`, where `C` is a program-lifetime class, stores the instance's address in 4 bytes instead of 8. In the example, `parent` takes 4 bytes. +On Linux, except in builds with sanitizers, the instances also take less memory. An executable keeps them in one address range below 32 GiB that it reserves at startup (only the pages in use take memory), and a field typed `C`, `C | undefined` or `C | null`, where `C` is a program-lifetime class, stores the instance's address in 4 bytes instead of 8, as does each element of an array of such a type and each value of a `Map` with `string` keys and such a value type. In the example, `parent` takes 4 bytes. scriptc checks that the promise cannot change what the program computes (SC7008): @@ -360,7 +360,7 @@ A class can be both `ProgramLifetime` and `Acyclic`. `Acyclic` is still checked Instances can be published to other threads with `@scriptc/threads` like other class instances: `publish()` makes them immutable and shares them by reference, writes to a published instance throw the same `TypeError` as under Node.js, and instances that were not published stay writable and are cloned by `postMessage` and `workerData`. -Static code has no `WeakRef` or `FinalizationRegistry`, and a `WeakMap` or `WeakSet` entry whose key is never freed is never observable as removed, so nothing else can tell the difference. +Static code has no `WeakRef`, a `FinalizationRegistry` never runs its cleanup callbacks, and a `WeakMap` or `WeakSet` entry whose key is never freed is never observable as removed, so nothing else can tell the difference. ### Lifetime regions diff --git a/docs/content/docs/coverage.mdx b/docs/content/docs/coverage.mdx index ae36f736d..954b040db 100644 --- a/docs/content/docs/coverage.mdx +++ b/docs/content/docs/coverage.mdx @@ -38,6 +38,8 @@ When a program has unsupported operations, the report adds a group for each root compile staticallyStatements that compile to native instructions. in dynamic tierOf those, the statements in functions that operate on values typed only at runtime, such as any values and untyped JavaScript. Shown when there are any. See Dynamic tier. blockersUnsupported operations with counts, diagnostic codes, reasons, locations, and hints. + runs at startupDeferred operations in a JavaScript module's top-level code, which runs when the module loads: at startup for a module the program imports. + deferred to runtimeOther deferred operations in JavaScript code. Each throws only if it runs. in unreached codeBlockers in code the entry never reaches. A build never compiles that code, so these cannot fail it. differs from NodeSites that compile but can behave differently from Node.js. See Node divergences. npm package compilationNative package compilation outcomes and refusal reasons. @@ -46,7 +48,7 @@ When a program has unsupported operations, the report adds a group for each root Blockers in unreached code and deferred operations in JavaScript packages are listed separately because they don't fail a build. A deferred operation throws a runtime error if it runs, so a successful build doesn't mean every API of a package works; see [unsupported code inside a package](/docs/dependencies#unsupported-code-inside-a-package). -If a function's signature can't compile, the statements in its body count as not compiling, so the percentage reflects how much of the program compiles. +If a function's signature can't compile, the statements in its body count as not compiling, so the percentage reflects how much of the program compiles. The report still lists the diagnostics of those statements; a use of a parameter whose type can't compile reports `SC2004` back to the signature. @@ -211,6 +213,10 @@ For editors, CI annotations, and other tools, `scriptc coverage --print=diagnost group The id of the root-cause group the diagnostic belongs to. A group's primary site is its first in source order. + + startup + true on a deferred diagnostic in a module's top-level code, which runs when the module loads. Absent otherwise. + diff --git a/docs/content/docs/dependencies.mdx b/docs/content/docs/dependencies.mdx index 85a232bb2..409b9cb30 100644 --- a/docs/content/docs/dependencies.mdx +++ b/docs/content/docs/dependencies.mdx @@ -132,7 +132,7 @@ CommonJS packages compile with Node.js's module semantics. Each `require()` eval ## Unsupported code inside a package -A JavaScript package can contain operations scriptc can't compile, often in functions your program never calls. These don't fail the build: each one compiles to code that throws a runtime error if it ever runs. Coverage reports list them as deferred sites, so review the list and test the parts of the package your program uses. +A JavaScript package can contain operations scriptc can't compile, often in functions your program never calls. These don't fail the build: each one compiles to code that throws a runtime error if it ever runs. Coverage reports list them as deferred sites, so review the list and test the parts of the package your program uses. Sites in a module's top-level code are listed under `runs at startup`: that code runs when the module loads, at startup for a module the program imports. ## Provenance sources (experimental) diff --git a/docs/content/docs/limitations.mdx b/docs/content/docs/limitations.mdx index 5be38a924..a86ed217e 100644 --- a/docs/content/docs/limitations.mdx +++ b/docs/content/docs/limitations.mdx @@ -24,6 +24,8 @@ title: "Limitations" ../limitations/language-features/async-iteration.mdx +../limitations/language-features/iterable-values.mdx + ../limitations/language-features/generics.mdx ../limitations/language-features/function-values.mdx @@ -34,6 +36,8 @@ title: "Limitations" ../limitations/language-features/commonjs-require.mdx +../limitations/language-features/jsx.mdx + ### Types and class definitions ../limitations/types-and-class-definitions/bigint.mdx diff --git a/docs/content/limitations/builtin-apis/crypto.mdx b/docs/content/limitations/builtin-apis/crypto.mdx index 3c830c63d..971065408 100644 --- a/docs/content/limitations/builtin-apis/crypto.mdx +++ b/docs/content/limitations/builtin-apis/crypto.mdx @@ -4,16 +4,45 @@ `copy()` of a Hash whose stream flushed, and stream use of a value after its stream closed, throw a coded SC2020 error. Through `unknown` and `any` slots and untyped JavaScript, Hash and Hmac values keep their identity and support `update()`, `digest()`, and Hash's `copy()`, called or read as values; their stream and event members there throw a coded SC2020 error. `timingSafeEqual` compares any view or ArrayBuffer. - Secret KeyObjects (`createSecretKey`, `generateKey` and `generateKeySync` for `hmac` and `aes`) support `type`, `symmetricKeySize`, `export()`, `equals()`, and `instanceof KeyObject`, and createHmac, hkdf, createCipheriv, and createDecipheriv accept them; asymmetric keys, `KeyObject.from()`, and `toCryptoKey()` are not available. + Secret KeyObjects (`createSecretKey`, `generateKey` and `generateKeySync` for `hmac` and `aes`) support `type`, `symmetricKeySize`, `export()`, `equals()`, and `instanceof KeyObject`, and createHmac, hkdf, createCipheriv, and createDecipheriv accept them; `KeyObject.from()` and `toCryptoKey()` are not available. `randomFill`, `randomFillSync` (every view kind and ArrayBuffer), `randomInt`, `randomUUID`, and `randomUUIDv7` follow Node 24.22, including callback timing; a `randomInt` callback whose error parameter is typed `Error | null` receives `null` where Node passes `undefined`. Scrypt supports its default parameters, numeric options, aliases, and memory limit. Both KDFs accept strings, Buffers, numeric typed arrays, DataViews, and fixed-length ArrayBuffers. - `createCipheriv` and `createDecipheriv` support aes-128, aes-192, and aes-256 in CBC, CTR, and GCM modes and chacha20-poly1305, on native targets, through `update()`, `final()`, `setAAD()`, `setAutoPadding()`, `getAuthTag()`, and `setAuthTag()`; other ciphers, cipher streams, and wasm32-wasi builds are refused. + `createCipheriv` and `createDecipheriv` support aes-128, aes-192, and aes-256 in CBC, CTR, GCM, ECB, CFB, CFB8, CFB1, and OFB modes, des-ede3 in CBC, ECB, CFB, CFB8, CFB1, and OFB modes, des-ede in CBC, ECB, CFB, and OFB modes, chacha20, and chacha20-poly1305, on native targets, through `update()`, `final()`, `setAAD()`, `setAutoPadding()`, `getAuthTag()`, and `setAuthTag()`; other ciphers and wasm32-wasi builds are refused. + Cipheriv and Decipheriv values are also Transforms: they can be written, piped into, used as `pipeline()` stages, read, iterated with `for await`, and listened to, and their stream properties read as in Node; written chunks go through `update()`, and the end pushes `final()` or reports its error through `'error'`. + Through `unknown` and `any` slots and untyped JavaScript, in a program that uses streams, their stream properties and their `on`, `once`, `off`, `pipe`, `unpipe`, `read`, `pause`, `resume`, `setEncoding`, `write`, `end`, `destroy`, `cork`, and `uncork` members work; `write` and `end` take no encoding or callback there, and the other stream members throw a coded SC2020 error. + Hash, Hmac, Cipheriv, and Decipheriv streams count a written string's bytes in `writableLength`, where Node counts the string's length. Decrypting chacha20-poly1305 without an authentication tag fails in `final()`; Node 24.22 returns unverified plaintext. After `update()` fails, for example past the AES-GCM limit of 2^36 - 32 bytes per message, every later call on that cipher throws; Node still lets `final()` run. An output encoding that is a function or an instance of a class defining `toString` throws a coded SC2020 error. `createECDH` and `ECDH.convertKey` support prime192v1, secp224r1, prime256v1, secp384r1, secp521r1, secp192k1, secp224k1, secp256k1, brainpoolP256r1, brainpoolP384r1, and brainpoolP512r1, on native targets, through `generateKeys()`, `computeSecret()`, `getPublicKey()`, `getPrivateKey()`, `setPrivateKey()`, and `setPublicKey()`, in compressed, uncompressed, and hybrid forms; the other curves `crypto.getCurves()` lists and wasm32-wasi builds are refused. A call on an ECDH value whose arguments no @types/node overload accepts (`getPublicKey("HEX")`) is refused at compile time, as is `computeSecret(view, encoding)`: Node reads that encoding as the input encoding and answers a Buffer where @types/node declares a string. ECDH property reads and writes throw a coded SC2020 error. - Other public-key operations remain unsupported. + `createDiffieHellman`, `getDiffieHellman`, and `createDiffieHellmanGroup` support the modp1, modp2, modp5, and modp14 through modp18 groups, explicit primes and generators, and generated safe primes, on native targets, through `generateKeys()`, `computeSecret()`, `getPrime()`, `getGenerator()`, `getPublicKey()`, `getPrivateKey()`, `setPublicKey()`, `setPrivateKey()`, and `verifyError`, with Node's private key lengths, DH_check results, and errors; wasm32-wasi builds are refused. + Primes longer than 8192 bits throw a coded SC2020 error; Node accepts primes up to 10000 bits for key generation and secrets. + `setPublicKey()` and `setPrivateKey()` keys longer than 80000 bytes, not counting leading zero bytes, throw a coded SC2020 error, as does a generator that long with a prime below 512 bits; Node accepts them. + A call on a DiffieHellman value whose arguments no @types/node overload accepts, or whose output encoding is typed `any`, is refused at compile time, as are its `Object.prototype` methods; other property reads, and property writes, throw a coded SC2020 error. + `Object.keys()` and `in` do not see a DiffieHellman's own `verifyError` property, and `JSON.stringify()` and `instanceof` are refused. + After `createDiffieHellman(primeLength)` throws `Invalid DH parameters`, the next OpenSSL error Node throws can list the failed generation's errors in `opensslErrorStack`; errors in a compiled binary list only their own. + `crypto.diffieHellman`, which takes DH, EC, or X25519 KeyObjects, and the `DiffieHellman` and `DiffieHellmanGroup` constructors are not available. + `checkPrime`, `checkPrimeSync`, `generatePrime`, and `generatePrimeSync` support bigint, ArrayBuffer, typed-array, Buffer, and DataView values and the `checks`, `safe`, `add`, `rem`, and `bigint` options on native targets, with Node's errors; the callback forms compute before they return and call back in a later macrotask. + Candidates and sizes longer than 262144 bits throw a coded SC2020 error, and wasm32-wasi builds are refused. + Node calls their callbacks with `undefined` as the error, which a callback whose error parameter is typed `Error | null`, as @types/node declares it, receives as `null`. + RSA, EC, and Ed25519 private and public KeyObjects come from `generateKeyPairSync`, `generateKeyPair`, `createPrivateKey`, and `createPublicKey`, on native targets. + The EC curves are prime256v1 (P-256), secp384r1 (P-384), secp521r1 (P-521), and secp256k1. + Keys read and write PEM and DER as PKCS#1, SEC1, PKCS#8, and SubjectPublicKeyInfo, and JWK (Ed25519 keys use PKCS#8, SubjectPublicKeyInfo, and JWK); `createPublicKey` also takes a private key or an X.509 certificate. + They support `type`, `asymmetricKeyType`, `asymmetricKeyDetails`, `export()`, `equals()`, and `instanceof KeyObject`. + `crypto.sign`, `crypto.verify`, `createSign`, and `createVerify` support RSA PKCS#1 v1.5 and PSS padding and ECDSA with DER and IEEE P1363 encodings over SHA-1 and SHA-2 digests, and Ed25519 through `crypto.sign` and `crypto.verify` with a `null` or `undefined` algorithm. + Ed25519 signing, verification, and private keys link when a string literal in the program names `ed25519` (in any case); without one they throw a coded SC2020 error, while Ed25519 public keys still import and export. + Sign and Verify values accumulate `update()` data and are not writable streams. + Encrypted private keys (`passphrase`, `cipher`), the other key types (`rsa-pss`, `dsa`, `ed448`, `x25519`, and the rest), and wasm32-wasi builds throw a coded SC2020 error or are refused. + Comparing keys of different types with `equals()` answers false; Node also leaves an OpenSSL error queued, which a later key operation can report. + `publicEncrypt`/`privateDecrypt` remain unsupported. + The WebCrypto `crypto` global, which node:crypto also exports as `webcrypto`, supports `randomUUID()` and `getRandomValues()`, also read as values from untyped JavaScript. + Its `subtle` object, also node:crypto's `subtle` export, supports `generateKey()` and `exportKey()` for HMAC and AES keys, `importKey()` for HMAC, AES, PBKDF2, and HKDF keys, `encrypt()` and `decrypt()` with AES-GCM, AES-CBC, and AES-CTR and `wrapKey()` and `unwrapKey()` of secret keys with AES-KW or those ciphers on native targets, `deriveBits()` and `deriveKey()` with PBKDF2 and HKDF, HMAC `sign()` and `verify()`, and SHA-1 and SHA-2 `digest()`. + Secret keys import and export in the `raw`, `raw-secret`, and `jwk` formats. + `generateKey()`, `importKey()`, `exportKey()`, `sign()`, and `verify()` also support ECDSA (P-256, P-384, and P-521), Ed25519, RSASSA-PKCS1-v1_5, and RSA-PSS, with the `spki`, `pkcs8`, and `jwk` formats and `raw` for ECDSA and Ed25519 public keys; ECDSA, Ed25519, and RSA are refused in wasm32-wasi builds. + ECDSA, Ed25519, and RSA link when a string literal in the program names the algorithm; a name built only at run time throws a coded SC2020 error. + `wrapKey()` and `unwrapKey()` of ECDSA, Ed25519, and RSA keys throw a coded SC2020 error. + Other SubtleCrypto methods, algorithms, and key formats are refused or throw a coded SC2020 error. Native derivations finish before their deferred callbacks, so computation blocks the caller. diff --git a/docs/content/limitations/builtin-apis/map-and-set.mdx b/docs/content/limitations/builtin-apis/map-and-set.mdx index bf77001ee..ee7435b2d 100644 --- a/docs/content/limitations/builtin-apis/map-and-set.mdx +++ b/docs/content/limitations/builtin-apis/map-and-set.mdx @@ -7,4 +7,6 @@ They support `.next()`, `for...of`, array spreads, and mapper-less `Array.from`. They also support the iterator helper methods, such as `.map()` and `.take()`. Detached collection methods are unsupported. + Constructing a Map, Set, WeakMap or WeakSet, or calling `Object.fromEntries`, with a checked-dynamic iterable (a native iterator, a generator, or an object with a `Symbol.iterator` method) takes all of its values before adding the first one. + When an entry of a Map seed is not an object, the TypeError comes after the iterable is exhausted; Node closes the iterator at that entry. The Set composition methods (`union`, `intersection`, `difference`, `symmetricDifference`, `isSubsetOf`, `isSupersetOf`, `isDisjointFrom`) accept a Set of the same element type or a Map keyed by it; other set-like arguments are unsupported. diff --git a/docs/content/limitations/builtin-apis/prototypes.mdx b/docs/content/limitations/builtin-apis/prototypes.mdx index 3e0b5789d..170b11793 100644 --- a/docs/content/limitations/builtin-apis/prototypes.mdx +++ b/docs/content/limitations/builtin-apis/prototypes.mdx @@ -3,4 +3,6 @@ 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. + 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. + `new` through a stored `Object`, `Date`, `Map`, `Set`, `WeakMap`, or `WeakSet` builds the same value as the `new` expression. + `new` through a stored `RegExp` or `Promise`, `new` of a stored `Object` with a primitive argument, and `instanceof` against these constructors are unsupported. diff --git a/docs/content/limitations/builtin-apis/streams-and-readline.mdx b/docs/content/limitations/builtin-apis/streams-and-readline.mdx index a21f7a617..fe6bb2dfb 100644 --- a/docs/content/limitations/builtin-apis/streams-and-readline.mdx +++ b/docs/content/limitations/builtin-apis/streams-and-readline.mdx @@ -1,24 +1,42 @@ -- **Streams and readline:** Stream chunks are Buffers or strings. +- **Streams and readline:** Stream chunks are Buffers or strings, and on an object-mode side any value that converts to a checked-dynamic value. `NodeJS.ReadableStream` and `NodeJS.WritableStream`, and `stream.Readable` and `stream.Writable` under `@types/node`, accept every stream: when a program passes file, zlib, or `node:stream` streams through them, child-process pipes and `process.stdout` and `process.stderr` join those streams as `Readable` and `Writable` instances. `readable.pipe(process.stdout)` and `readable.pipe(process.stderr)` compile and, as in Node, do not end the process stream. When an untyped value reaches `NodeJS.ReadableStream` or `NodeJS.WritableStream`, those two interfaces hold any value, so JavaScript stream objects (constructor-function streams, plain objects with `on` and `pipe`) pass through TypeScript functions typed with them and come back to JavaScript as the same objects. Member calls on such a value use the native stream when it is one and call the object's own members otherwise; `readable.pipe()` into a JavaScript destination follows Node's pipe protocol. - A `pipeline` stage and a `for await` source that arrive as untyped values must be native streams at run time; other values throw a not-supported error. + A `pipeline` stage and a `for await` source that arrive as untyped values must be native streams, or `Cipheriv` and `Decipheriv` values, at run time; other values throw a not-supported error. Native streams expose no `emit` to JavaScript, so a JavaScript stream whose own `pipe()` emits on its destination (the legacy `Stream` pipe) cannot pipe into one. - `Readable.from` accepts arrays, Sets, Map and Set iterators, generators, async generators, and class iterables and async iterables whose values are strings or Buffers, and in JavaScript any iterable or async iterable of them; a stream that mixes strings and Buffers is unsupported. + `Readable.from` accepts strings, Buffers, arrays, Sets, Maps, Map and Set iterators, generators, async generators, and class iterables and async iterables, and in JavaScript any iterable or async iterable. In JavaScript, a sync iterator value with a `then` method that is not a promise, and an object whose `[Symbol.asyncIterator]` or `[Symbol.iterator]` method is a generator method, are unsupported. - Object-mode streams of other values (including `Readable.from` over a `Map`, whose values are entry arrays) are unsupported. - `pipeline` accepts one run of function stages: async generator functions between streams (`async function* (source)`, iterating `source` with `for await`), an async generator source function (`async function* ({ signal })`), and an async function destination whose value resolves the promise form and reaches the callback's second argument. + The `objectMode` option, and the `readableObjectMode` and `writableObjectMode` options of a `Duplex`, `Transform`, or `PassThrough`, take `true` or `false` literals in an options object literal; options passed as a value are read when the stream is built. + In typed code, a `write` or `transform` callback, or a `_write` or `_transform` method, may declare its chunk with any type that converts to a checked-dynamic value: the chunk converts when the callback runs, and a value of another type throws a TypeError there. + An object-mode write passes its encoding argument to `write` and `transform` as Node does (`undefined` when absent, `null` when a callback took its place); a parameter declared `string` receives `""` for `undefined` and `null`, and one declared `string | null | undefined` receives Node's value. + `readable.read()` on an object-mode stream answers any value it holds. + `node:stream/consumers` and readline interfaces read object-mode streams of strings and Buffers; other values throw a not-supported error. + `pipeline` accepts function stages anywhere among its streams: async generator functions (`async function* (source)`, iterating `source` with `for await`), an async generator source function (`async function* ({ signal })`), an async generator function as the destination, and an async function destination whose value resolves the promise form and reaches the callback's second argument. + A stage is written inline, or named by a function declaration or a `const` bound to a function expression that nothing reassigns. + The source may also be an array, a string, a synchronous generator object, or a synchronous generator function without parameters; their elements reach the next stage on the same ticks as in Node. Stages may take the `{ signal }` argument. - An async generator function as the destination, using the PassThrough that `pipeline()` returns for a function destination, several runs of function stages, and function stages together with pipeline options are unsupported. + With a function destination, `pipeline()` returns an object-mode PassThrough that receives an async generator destination's values, or an async function destination's value unless it is `null` or `undefined`. + `@types/node` types that result as `NodeJS.WritableStream`, so `for await` over it needs the `PassThrough` type (`pipeline(...) as PassThrough`, or a JSDoc `@type`). + In typed code, the callback of a pipeline with an async function destination receives `null` instead of `undefined` when there is no error. `Readable.from` accepts `objectMode` and `highWaterMark` options. - The `Readable` operators (`map`, `filter`, `forEach`, `toArray`, `some`, `find`, `every`, `flatMap`, `drop`, `take`, and `reduce`) accept `concurrency`, `highWaterMark`, and `signal` options; their callbacks take only the chunk, `map` returns strings or Buffers, and `flatMap` returns strings or arrays of them. - `readable.compose` is unsupported. - `stream.compose` accepts two or more streams, or one `Duplex`; functions, iterables, and web streams as stages are unsupported, and the `ERR_INVALID_ARG_VALUE` message for a stream that is no longer readable or writable names the stream's class instead of printing the stream. - `pipeline` from `node:stream/promises` accepts a trailing `{ signal, end }` object, and `finished` accepts `readable`, `writable`, `error`, `cleanup`, and `signal` options, with boolean literals for the flags. + The `Readable` operators (`map`, `filter`, `forEach`, `toArray`, `some`, `find`, `every`, `flatMap`, `drop`, `take`, and `reduce`) accept `concurrency`, `highWaterMark`, and `signal` options. + Their callbacks may take the `{ signal }` argument, `map` may return any value, and `flatMap` may return any iterable, async iterable, or stream. + `Duplex.from` accepts an async generator function, which reads what is written to the Duplex, a `Duplex`, `Transform` or `PassThrough`, which it returns, and the values `Readable.from` accepts, which give a Duplex that is not writable. + It also accepts a lone `Readable` or `Writable` and a `{ readable, writable }` pair, which the Duplex reads and writes through, a promise, whose value it reads, and an async function, which reads what is written and must resolve to `null` or `undefined`. + A `Duplex.from` body function may take the `{ signal }` argument, which is aborted with the error the Duplex is destroyed with. + `stream.compose` accepts streams and async generator functions in any position, an async function as the last stage, and an array, a string, or a generator as the first stage; one stage is `Duplex.from` of it. + A web `ReadableStream` is read as an async iterable by `Readable.from` and as the first stage of `compose` or `pipeline`, and through its reader by `Readable.fromWeb` (with `objectMode`, `highWaterMark`, `encoding`, and `signal` in an options object literal) and `Duplex.from`. + A web stream in a later compose stage, `Readable.toWeb`, and web `WritableStream` and `TransformStream` interop are unsupported. + The `ERR_INVALID_ARG_VALUE` message for a stream that is no longer readable or writable names the stream's class instead of printing the stream. + `readable.compose(stage, { signal })` is `stream.compose(readable, stage)` with the signal added; the options are an object literal whose `signal` is a variable or a property read. + `pipeline` from `node:stream/promises` accepts a trailing `{ signal, end }` object, with or without function stages, and `finished` accepts `readable`, `writable`, `error`, `cleanup`, and `signal` options, with boolean literals for the flags. Stream constructors accept a `signal` option in an options object literal, and `stream.addAbortSignal` accepts any stream. + The `construct` option and `_construct` method, `decodeStrings`, and `defaultEncoding` work on every stream class, and the `writev` option and `_writev` method on Writable and Duplex; `writev` on a Transform or PassThrough, assigning `_construct` after construction, and a non-literal `decodeStrings` or `defaultEncoding` in an options object literal are unsupported. + `setDefaultEncoding()` takes any encoding Node knows. A `transform` or `flush` option callback whose completion callback types `data` as `any`, as @types/node's `TransformCallback` does, may pass a Buffer, a string, or nothing; any other value throws a TypeError where the callback is called, instead of Node's `ERR_INVALID_ARG_TYPE` stream error. `node:readline` and `node:readline/promises` (also reached as `readline.promises`) interfaces, from `createInterface(options)` or `createInterface(input, output, completer, terminal)`, read `process.stdin` or a readable stream: `question`, `prompt`, `write` (with a key object literal of `name`, `ctrl`, `meta`, and `shift`), `pause`, `resume`, `'line'`/`'close'`/`'pause'`/`'resume'`/`'error'`/`'history'`/`'SIGINT'`/`'SIGTSTP'`/`'SIGCONT'` listeners, and `for await` compile. + `on`, `once`, and `addListener` return the interface, so registrations chain. The `history`, `historySize`, `removeHistoryDuplicates`, `completer`, `tabSize`, and `escapeCodeTimeout` options are validated as in Node. With `terminal: true`, or with no `terminal` option and `process.stdout` as the output when it is a TTY, the interface runs Node's terminal mode: the editing keys, the kill ring, undo and redo, history recording and recall, Tab completion through the completer, Ctrl+C, Ctrl+D, and Ctrl+Z, `TERM=dumb`, and the same escape sequences written to the output. The output's `'resize'` event does not redraw the line. diff --git a/docs/content/limitations/builtin-function-values.mdx b/docs/content/limitations/builtin-function-values.mdx index 37ed8eb48..0fa62e558 100644 --- a/docs/content/limitations/builtin-function-values.mdx +++ b/docs/content/limitations/builtin-function-values.mdx @@ -28,7 +28,8 @@ The `captureRejections` option and `events.errorMonitor` listeners are not suppo The stream calls the object's `_read`, `_write`, `_final`, `_transform`, `_flush`, and `_destroy` with the object as `this`, and the stream prototypes' methods and accessors work on it. Its listeners live in the native stream rather than in `_events`, and `_readableState` and `_writableState` are read-only views that answer the commonly read fields. Typed code that receives such an object as a stream class uses its native stream, and piping a native stream into it works. -The options the native streams refuse (`objectMode`, `decodeStrings: false`, `signal`, and others) are refused here too, as are `_writev`, `_construct`, symbol event names, `listeners()`, `rawListeners()`, `wrap()`, strings written in encodings other than UTF-8, and pipes into a destination that overrides `write()` or `end()`. +The options the native streams refuse (`signal` and others) are refused here too, as are `_writev` on a Transform, `_final` on a Transform, symbol event names, `listeners()`, `rawListeners()`, `wrap()`, and pipes into a destination that overrides `write()` or `end()`. +`_construct` and `_writev` are read when `Readable.call(this, options)` or `Writable.call(this, options)` runs, as Node's constructors read them. Other class constructors passed to `util.inherits` or `util.deprecate` are refused. Deprecation warnings are emitted on the next tick and follow assignments to `process.noDeprecation` and `process.throwDeprecation`; compiled binaries take no Node command-line flags such as `--no-deprecation` or `--trace-deprecation`, and `process.traceDeprecation` is unsupported. A stored `util.deprecate` reports a `length` of 4, where Node reports 3. diff --git a/docs/content/limitations/language-features/iterable-values.mdx b/docs/content/limitations/language-features/iterable-values.mdx new file mode 100644 index 000000000..2feedc02f --- /dev/null +++ b/docs/content/limitations/language-features/iterable-values.mdx @@ -0,0 +1,2 @@ +- **Iterable values:** A value typed `Iterable` can hold an array, a Set, a Map (for `Iterable<[K, V]>`), a string (for `Iterable`), a generator, or a Map, Set or array iterator. + Class instances with their own `[Symbol.iterator]` method and typed arrays can't be stored in an `Iterable` and are reported at the conversion. diff --git a/docs/content/limitations/language-features/jsx.mdx b/docs/content/limitations/language-features/jsx.mdx new file mode 100644 index 000000000..a491dc995 --- /dev/null +++ b/docs/content/limitations/language-features/jsx.mdx @@ -0,0 +1,5 @@ +- **JSX:** JSX in `.tsx`, `.jsx` and JavaScript files compiles with the project's `jsx` setting: `"react"` with `jsxFactory`, `jsxFragmentFactory` or `reactNamespace`, and `"react-jsx"` or `"react-jsxdev"` with `jsxImportSource`, as well as the `@jsx`, `@jsxFrag`, `@jsxImportSource` and `@jsxRuntime` pragmas. + The checker types JSX with these settings, and each element becomes the call TypeScript emits for it, importing the automatic runtime's functions from `/jsx-runtime` or `jsx-dev-runtime`. + `"jsx": "preserve"` and `"react-native"`, which keep JSX in the output, are refused. + The call an element becomes must type-check: a factory or runtime function whose parameters do not accept what an element passes is reported at the element. + With `"react-jsxdev"`, `jsxDEV` receives `undefined` as `self` where `this` has no declared type (in a function that is not a method), which is the value such a function observes when called without a receiver. diff --git a/docs/content/limitations/types-and-class-definitions/local-class-expressions.mdx b/docs/content/limitations/types-and-class-definitions/local-class-expressions.mdx index 8b653b25e..de24038cc 100644 --- a/docs/content/limitations/types-and-class-definitions/local-class-expressions.mdx +++ b/docs/content/limitations/types-and-class-definitions/local-class-expressions.mdx @@ -1,4 +1,6 @@ -- **Local class expressions:** Static members, decorators, private brands, generic members, and references through the class's internal name are unsupported. +- **Local class expressions:** Static fields and static blocks in TypeScript files, decorators, private brands, and generic members are unsupported. + Static methods read the enclosing function's bindings and are inherited by subclasses. + A named class expression's methods and static members can refer to the class by its name. Supported expressions preserve fresh constructor identity and shared captures across constructors, methods, accessors, and arrow fields. Local inheritance requires a compiled base class. Constructors retain identity, `typeof`, `name`, and `length` through `unknown`; cast back to their exact type before construction. diff --git a/docs/content/limitations/weak-collections-and-memory.mdx b/docs/content/limitations/weak-collections-and-memory.mdx index 97ee20d7b..21c6128d9 100644 --- a/docs/content/limitations/weak-collections-and-memory.mdx +++ b/docs/content/limitations/weak-collections-and-memory.mdx @@ -3,6 +3,15 @@ Copied values, other native handles, and symbol keys are unsupported. Constructor seeds support arrays; custom iterators and detached methods are unsupported. Weak collections do not retain their keys, but values that refer back to a key can keep it alive until deletion or collection release. +`FinalizationRegistry` keeps its registrations: `register` and `unregister` check their arguments and answer as in Node.js. +Its cleanup callbacks never run, which the ECMAScript specification allows. +Program output matches Node.js, which runs cleanup callbacks only when its garbage collector decides to. +Memory that a package frees only from a cleanup callback is not reclaimed until the program exits. +For example, a wasm-bindgen package frees the WebAssembly memory behind a wrapper object from its cleanup callback, so a long-running server that drops such wrappers without calling their `free()` method keeps that memory. +Call `free()` on wrappers the program no longer needs. +Symbol targets and unregister tokens are unsupported. +`WeakRef` is unsupported. + Memory uses reference counting. Acyclic values are freed deterministically, and cycles are collected at defined collection points. Native checked objects, arrays, Sets, and captured closures participate in cycle collection. diff --git a/docs/src/generated/node-v24-compatibility.json b/docs/src/generated/node-v24-compatibility.json index 66b0ba3dd..c341da852 100644 --- a/docs/src/generated/node-v24-compatibility.json +++ b/docs/src/generated/node-v24-compatibility.json @@ -11085,9 +11085,9 @@ "inherited": true }, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Implemented for the call shapes accepted by the compiler lowering.", + "verification": "test-backed" } }, { @@ -11108,9 +11108,9 @@ "inherited": true }, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Implemented for the call shapes accepted by the compiler lowering.", + "verification": "test-backed" } }, { @@ -11177,9 +11177,9 @@ "inherited": true }, "static": { - "status": "refused", - "detail": "Explicitly rejected by a named compiler diagnostic.", - "verification": "explicit-refusal" + "status": "partial", + "detail": "Supports the modp groups, explicit primes and generators, and generated safe primes up to 8192 bits with Node's argument, generator and modulus errors.", + "verification": "test-backed" } }, { @@ -11200,9 +11200,9 @@ "inherited": true }, "static": { - "status": "refused", - "detail": "Explicitly rejected by a named compiler diagnostic.", - "verification": "explicit-refusal" + "status": "partial", + "detail": "Supports the modp groups, explicit primes and generators, and generated safe primes up to 8192 bits with Node's argument, generator and modulus errors.", + "verification": "test-backed" } }, { @@ -11223,9 +11223,9 @@ "inherited": true }, "static": { - "status": "refused", - "detail": "Explicitly rejected by a named compiler diagnostic.", - "verification": "explicit-refusal" + "status": "partial", + "detail": "Supports the modp groups, explicit primes and generators, and generated safe primes up to 8192 bits with Node's argument, generator and modulus errors.", + "verification": "test-backed" } }, { @@ -11247,7 +11247,7 @@ }, "static": { "status": "partial", - "detail": "Implemented for the call shapes accepted by the compiler lowering.", + "detail": "Supports prime192v1, secp224r1, prime256v1, secp384r1, secp521r1, secp192k1, secp224k1, secp256k1, brainpoolP256r1, brainpoolP384r1 and brainpoolP512r1 with Node's curve, key, point, format and encoding errors; other curves Node knows are refused.", "verification": "test-backed" } }, @@ -11338,9 +11338,9 @@ "inherited": true }, "static": { - "status": "refused", - "detail": "Explicitly rejected by a named compiler diagnostic.", - "verification": "explicit-refusal" + "status": "partial", + "detail": "Implemented by a dedicated static compiler/runtime path.", + "verification": "test-backed" } }, { @@ -11361,9 +11361,9 @@ "inherited": true }, "static": { - "status": "refused", - "detail": "Explicitly rejected by a named compiler diagnostic.", - "verification": "explicit-refusal" + "status": "partial", + "detail": "Implemented by a dedicated static compiler/runtime path.", + "verification": "test-backed" } }, { @@ -11407,9 +11407,9 @@ "inherited": true }, "static": { - "status": "refused", - "detail": "Explicitly rejected by a named compiler diagnostic.", - "verification": "explicit-refusal" + "status": "partial", + "detail": "Implemented by a dedicated static compiler/runtime path.", + "verification": "test-backed" } }, { @@ -11430,9 +11430,9 @@ "inherited": true }, "static": { - "status": "refused", - "detail": "Explicitly rejected by a named compiler diagnostic.", - "verification": "explicit-refusal" + "status": "partial", + "detail": "Implemented by a dedicated static compiler/runtime path.", + "verification": "test-backed" } }, { @@ -11545,9 +11545,9 @@ "inherited": true }, "static": { - "status": "refused", - "detail": "Explicitly rejected by a named compiler diagnostic.", - "verification": "explicit-refusal" + "status": "partial", + "detail": "Implemented by a dedicated static compiler/runtime path.", + "verification": "test-backed" } }, { @@ -11568,9 +11568,9 @@ "inherited": true }, "static": { - "status": "refused", - "detail": "Explicitly rejected by a named compiler diagnostic.", - "verification": "explicit-refusal" + "status": "partial", + "detail": "Implemented by a dedicated static compiler/runtime path.", + "verification": "test-backed" } }, { @@ -11614,9 +11614,9 @@ "inherited": true }, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Implemented for the call shapes accepted by the compiler lowering.", + "verification": "test-backed" } }, { @@ -11637,9 +11637,9 @@ "inherited": true }, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Implemented for the call shapes accepted by the compiler lowering.", + "verification": "test-backed" } }, { @@ -11729,9 +11729,9 @@ "inherited": true }, "static": { - "status": "refused", - "detail": "Explicitly rejected by a named compiler diagnostic.", - "verification": "explicit-refusal" + "status": "partial", + "detail": "Supports the modp groups, explicit primes and generators, and generated safe primes up to 8192 bits with Node's argument, generator and modulus errors.", + "verification": "test-backed" } }, { @@ -12327,9 +12327,9 @@ "inherited": true }, "static": { - "status": "refused", - "detail": "Explicitly rejected by a named compiler diagnostic.", - "verification": "explicit-refusal" + "status": "partial", + "detail": "Implemented by a dedicated static compiler/runtime path.", + "verification": "test-backed" } }, { @@ -12373,9 +12373,9 @@ "inherited": true }, "static": { - "status": "refused", - "detail": "Explicitly rejected by a named compiler diagnostic.", - "verification": "explicit-refusal" + "status": "partial", + "detail": "Implemented by a dedicated static compiler/runtime path.", + "verification": "test-backed" } }, { @@ -12442,9 +12442,9 @@ "inherited": true }, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Implemented by a dedicated static compiler/runtime path.", + "verification": "test-backed" } }, { @@ -12465,9 +12465,9 @@ "inherited": true }, "static": { - "status": "refused", - "detail": "Explicitly rejected by a named compiler diagnostic.", - "verification": "explicit-refusal" + "status": "partial", + "detail": "Implemented by a dedicated static compiler/runtime path.", + "verification": "test-backed" } }, { @@ -12581,7 +12581,7 @@ }, "static": { "status": "partial", - "detail": "Matches Node's update() output lengths, padding, authentication tags, string encodings, and state errors for the supported ciphers; the stream.Transform interface is refused.", + "detail": "Matches Node's update() output lengths, padding, authentication tags, string encodings, and state errors for the supported ciphers, and its stream.Transform behavior: chunks written through update(), final() pushed at the end, and its errors reported through 'error'.", "verification": "test-backed" } }, @@ -12604,7 +12604,7 @@ }, "static": { "status": "partial", - "detail": "Matches Node's update() output lengths, padding, authentication tags, string encodings, and state errors for the supported ciphers; the stream.Transform interface is refused.", + "detail": "Matches Node's update() output lengths, padding, authentication tags, string encodings, and state errors for the supported ciphers, and its stream.Transform behavior: chunks written through update(), final() pushed at the end, and its errors reported through 'error'.", "verification": "test-backed" } }, @@ -12627,7 +12627,7 @@ }, "static": { "status": "partial", - "detail": "Matches Node's update() output lengths, padding, authentication tags, string encodings, and state errors for the supported ciphers; the stream.Transform interface is refused.", + "detail": "Matches Node's update() output lengths, padding, authentication tags, string encodings, and state errors for the supported ciphers, and its stream.Transform behavior: chunks written through update(), final() pushed at the end, and its errors reported through 'error'.", "verification": "test-backed" } }, @@ -12650,7 +12650,7 @@ }, "static": { "status": "partial", - "detail": "Matches Node's update() output lengths, padding, authentication tags, string encodings, and state errors for the supported ciphers; the stream.Transform interface is refused.", + "detail": "Matches Node's update() output lengths, padding, authentication tags, string encodings, and state errors for the supported ciphers, and its stream.Transform behavior: chunks written through update(), final() pushed at the end, and its errors reported through 'error'.", "verification": "test-backed" } }, @@ -12673,7 +12673,7 @@ }, "static": { "status": "partial", - "detail": "Matches Node's update() output lengths, padding, authentication tags, string encodings, and state errors for the supported ciphers; the stream.Transform interface is refused.", + "detail": "Matches Node's update() output lengths, padding, authentication tags, string encodings, and state errors for the supported ciphers, and its stream.Transform behavior: chunks written through update(), final() pushed at the end, and its errors reported through 'error'.", "verification": "test-backed" } }, @@ -12696,7 +12696,7 @@ }, "static": { "status": "partial", - "detail": "Matches Node's update() output lengths, padding, authentication tags, string encodings, and state errors for the supported ciphers; the stream.Transform interface is refused.", + "detail": "Matches Node's update() output lengths, padding, authentication tags, string encodings, and state errors for the supported ciphers, and its stream.Transform behavior: chunks written through update(), final() pushed at the end, and its errors reported through 'error'.", "verification": "test-backed" } }, @@ -12719,7 +12719,7 @@ }, "static": { "status": "partial", - "detail": "Matches Node's update() output lengths, padding, authentication tags, string encodings, and state errors for the supported ciphers; the stream.Transform interface is refused.", + "detail": "Matches Node's update() output lengths, padding, authentication tags, string encodings, and state errors for the supported ciphers, and its stream.Transform behavior: chunks written through update(), final() pushed at the end, and its errors reported through 'error'.", "verification": "test-backed" } }, @@ -12742,7 +12742,7 @@ }, "static": { "status": "partial", - "detail": "Matches Node's update() output lengths, padding, authentication tags, string encodings, and state errors for the supported ciphers; the stream.Transform interface is refused.", + "detail": "Matches Node's update() output lengths, padding, authentication tags, string encodings, and state errors for the supported ciphers, and its stream.Transform behavior: chunks written through update(), final() pushed at the end, and its errors reported through 'error'.", "verification": "test-backed" } }, @@ -12765,7 +12765,7 @@ }, "static": { "status": "partial", - "detail": "Matches Node's update() output lengths, padding, authentication tags, string encodings, and state errors for the supported ciphers; the stream.Transform interface is refused.", + "detail": "Matches Node's update() output lengths, padding, authentication tags, string encodings, and state errors for the supported ciphers, and its stream.Transform behavior: chunks written through update(), final() pushed at the end, and its errors reported through 'error'.", "verification": "test-backed" } }, @@ -12788,7 +12788,7 @@ }, "static": { "status": "partial", - "detail": "Matches Node's update() output lengths, padding, authentication tags, string encodings, and state errors for the supported ciphers; the stream.Transform interface is refused.", + "detail": "Matches Node's update() output lengths, padding, authentication tags, string encodings, and state errors for the supported ciphers, and its stream.Transform behavior: chunks written through update(), final() pushed at the end, and its errors reported through 'error'.", "verification": "test-backed" } }, @@ -12811,7 +12811,7 @@ }, "static": { "status": "partial", - "detail": "Matches Node's update() output lengths, padding, authentication tags, string encodings, and state errors for the supported ciphers; the stream.Transform interface is refused.", + "detail": "Matches Node's update() output lengths, padding, authentication tags, string encodings, and state errors for the supported ciphers, and its stream.Transform behavior: chunks written through update(), final() pushed at the end, and its errors reported through 'error'.", "verification": "test-backed" } }, @@ -12834,7 +12834,7 @@ }, "static": { "status": "partial", - "detail": "Matches Node's update() output lengths, padding, authentication tags, string encodings, and state errors for the supported ciphers; the stream.Transform interface is refused.", + "detail": "Matches Node's update() output lengths, padding, authentication tags, string encodings, and state errors for the supported ciphers, and its stream.Transform behavior: chunks written through update(), final() pushed at the end, and its errors reported through 'error'.", "verification": "test-backed" } }, @@ -12856,9 +12856,9 @@ "inherited": true }, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Matches Node's private key lengths, DH_check results, public key range checks, secret padding and errors; primes longer than 8192 bits, property writes and property reads other than verifyError are refused.", + "verification": "test-backed" } }, { @@ -12879,9 +12879,9 @@ "inherited": true }, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Matches Node's private key lengths, DH_check results, public key range checks, secret padding and errors; primes longer than 8192 bits, property writes and property reads other than verifyError are refused.", + "verification": "test-backed" } }, { @@ -12902,9 +12902,9 @@ "inherited": true }, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Matches Node's private key lengths, DH_check results, public key range checks, secret padding and errors; primes longer than 8192 bits, property writes and property reads other than verifyError are refused.", + "verification": "test-backed" } }, { @@ -12925,9 +12925,9 @@ "inherited": true }, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Matches Node's private key lengths, DH_check results, public key range checks, secret padding and errors; primes longer than 8192 bits, property writes and property reads other than verifyError are refused.", + "verification": "test-backed" } }, { @@ -12948,9 +12948,9 @@ "inherited": true }, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Matches Node's private key lengths, DH_check results, public key range checks, secret padding and errors; primes longer than 8192 bits, property writes and property reads other than verifyError are refused.", + "verification": "test-backed" } }, { @@ -12971,9 +12971,9 @@ "inherited": true }, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Matches Node's private key lengths, DH_check results, public key range checks, secret padding and errors; primes longer than 8192 bits, property writes and property reads other than verifyError are refused.", + "verification": "test-backed" } }, { @@ -12994,9 +12994,9 @@ "inherited": true }, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Matches Node's private key lengths, DH_check results, public key range checks, secret padding and errors; primes longer than 8192 bits, property writes and property reads other than verifyError are refused.", + "verification": "test-backed" } }, { @@ -13017,9 +13017,9 @@ "inherited": true }, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Matches Node's private key lengths, DH_check results, public key range checks, secret padding and errors; primes longer than 8192 bits, property writes and property reads other than verifyError are refused.", + "verification": "test-backed" } }, { @@ -13040,9 +13040,9 @@ "inherited": true }, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Matches Node's private key lengths, DH_check results, public key range checks, secret padding and errors; primes longer than 8192 bits, property writes and property reads other than verifyError are refused.", + "verification": "test-backed" } }, { @@ -13063,9 +13063,9 @@ "inherited": true }, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Matches Node's private key lengths, DH_check results, public key range checks, secret padding and errors; primes longer than 8192 bits, property writes and property reads other than verifyError are refused.", + "verification": "test-backed" } }, { @@ -13086,9 +13086,9 @@ "inherited": true }, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Matches Node's private key lengths, DH_check results, public key range checks, secret padding and errors; primes longer than 8192 bits, property writes and property reads other than verifyError are refused.", + "verification": "test-backed" } }, { @@ -13523,9 +13523,9 @@ "inherited": true }, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Implemented by a dedicated static compiler/runtime path.", + "verification": "test-backed" } }, { @@ -13546,9 +13546,9 @@ "inherited": true }, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Implemented by a dedicated static compiler/runtime path.", + "verification": "test-backed" } }, { @@ -13684,9 +13684,9 @@ "inherited": true }, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Implemented by a dedicated static compiler/runtime path.", + "verification": "test-backed" } }, { @@ -13707,9 +13707,9 @@ "inherited": true }, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Implemented by a dedicated static compiler/runtime path.", + "verification": "test-backed" } }, { @@ -13730,9 +13730,9 @@ "inherited": true }, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Implemented by a dedicated static compiler/runtime path.", + "verification": "test-backed" } }, { @@ -13753,9 +13753,9 @@ "inherited": true }, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Implemented by a dedicated static compiler/runtime path.", + "verification": "test-backed" } }, { @@ -13776,9 +13776,9 @@ "inherited": true }, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Implemented by a dedicated static compiler/runtime path.", + "verification": "test-backed" } }, { @@ -13799,9 +13799,9 @@ "inherited": true }, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Implemented by a dedicated static compiler/runtime path.", + "verification": "test-backed" } }, { @@ -18880,9 +18880,9 @@ "anchor": "err_crypto_invalid_keylen", "nodeStability": null, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Implemented by a dedicated static compiler/runtime path.", + "verification": "test-backed" } }, { @@ -19006,9 +19006,9 @@ "anchor": "err_crypto_invalid_state", "nodeStability": null, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Implemented by a dedicated static compiler/runtime path.", + "verification": "test-backed" } }, { @@ -19276,9 +19276,9 @@ "anchor": "err_crypto_unknown_dh_group", "nodeStability": null, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Implemented by a dedicated static compiler/runtime path.", + "verification": "test-backed" } }, { @@ -67806,9 +67806,9 @@ "inherited": true }, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Implemented for the documented scriptc module-loader subset.", + "verification": "test-backed" } }, { @@ -68565,9 +68565,9 @@ "inherited": true }, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Implemented for the documented scriptc module-loader subset.", + "verification": "test-backed" } }, { @@ -79656,9 +79656,9 @@ "inherited": true }, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Implemented for the documented scriptc module-loader subset.", + "verification": "test-backed" } }, { @@ -79680,7 +79680,7 @@ }, "static": { "status": "supported", - "detail": "Implemented by a dedicated static compiler/runtime path.", + "detail": "Implemented for the documented scriptc module-loader subset.", "verification": "test-backed" } }, @@ -79703,7 +79703,7 @@ }, "static": { "status": "supported", - "detail": "Implemented by a dedicated static compiler/runtime path.", + "detail": "Implemented for the documented scriptc module-loader subset.", "verification": "test-backed" } }, @@ -80001,9 +80001,9 @@ "inherited": true }, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Implemented for the documented scriptc module-loader subset.", + "verification": "test-backed" } }, { @@ -80024,9 +80024,9 @@ "inherited": true }, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Implemented for the documented scriptc module-loader subset.", + "verification": "test-backed" } }, { @@ -80047,9 +80047,9 @@ "inherited": true }, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Implemented for the documented scriptc module-loader subset.", + "verification": "test-backed" } }, { @@ -80139,9 +80139,9 @@ "inherited": true }, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Implemented for the documented scriptc module-loader subset.", + "verification": "test-backed" } }, { @@ -80162,9 +80162,9 @@ "inherited": true }, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Implemented for the documented scriptc module-loader subset.", + "verification": "test-backed" } }, { @@ -80208,9 +80208,9 @@ "inherited": true }, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Implemented for the documented scriptc module-loader subset.", + "verification": "test-backed" } }, { @@ -80277,9 +80277,9 @@ "inherited": true }, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Implemented for the documented scriptc module-loader subset.", + "verification": "test-backed" } }, { @@ -80323,9 +80323,9 @@ "inherited": true }, "static": { - "status": "not-implemented", - "detail": "No static compiler lowering is registered for this API yet.", - "verification": "registry-gap" + "status": "partial", + "detail": "Implemented for the documented scriptc module-loader subset.", + "verification": "test-backed" } }, { diff --git a/internal/compatibility/generated/node-v24-internal.json b/internal/compatibility/generated/node-v24-internal.json index c6a7a102c..9393fcaa8 100644 --- a/internal/compatibility/generated/node-v24-internal.json +++ b/internal/compatibility/generated/node-v24-internal.json @@ -19313,12 +19313,33 @@ "tests/corpus/6703-ecdh-private-keys.ts", "tests/corpus/6704-ecdh-set-public-key.cjs", "tests/corpus/6705-ecdh-handles.ts", + "tests/corpus/6706-dh-groups.ts", + "tests/corpus/6707-dh-explicit-params.ts", + "tests/corpus/6708-dh-errors.js", + "tests/corpus/6709-dh-generate.ts", + "tests/corpus/6710-dh-encodings.cjs", + "tests/corpus/6711-dh-handles.ts", + "tests/corpus/7055-cipher-streams.ts", + "tests/corpus/7056-cipher-stream-errors.ts", + "tests/corpus/7057-cipher-streams.mjs", + "tests/corpus/7080-crypto-ed25519.mjs", + "tests/corpus/7082-crypto-key-objects.ts", + "tests/corpus/7083-crypto-sign-verify.ts", + "tests/corpus/7084-crypto-key-pairs.cjs", + "tests/corpus/7122-webcrypto-node-crypto.ts", + "tests/corpus/7123-webcrypto-node-crypto.cjs", + "tests/corpus/7150-cipher-legacy-modes.ts", + "tests/corpus/7151-cipher-legacy-errors.cjs", + "tests/corpus/7152-crypto-prime.ts", + "tests/corpus/7153-crypto-prime-errors.cjs", "tests/corpus/node24-crypto-kdf-errors.ts", "tests/corpus/node24-crypto-kdf-options.ts", "tests/corpus/node24-crypto-kdf.ts", "tests/corpus/node24-crypto-sha2.ts", "tests/fixtures/node-types/cipher.ts", + "tests/fixtures/node-types/dh.ts", "tests/fixtures/node-types/ecdh.ts", + "tests/fixtures/node-types/keys.ts", "tests/harness/npm-static.test.ts" ] }, @@ -19641,8 +19662,12 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:crypto" + "status": "partial", + "evidence": "surface-manifest:node-builtin.crypto.checkPrime", + "tests": [ + "tests/corpus/7152-crypto-prime.ts", + "tests/corpus/7153-crypto-prime-errors.cjs" + ] }, "anchorSource": "exact" }, @@ -19664,8 +19689,12 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:crypto" + "status": "partial", + "evidence": "surface-manifest:node-builtin.crypto.checkPrimeSync", + "tests": [ + "tests/corpus/7152-crypto-prime.ts", + "tests/corpus/7153-crypto-prime-errors.cjs" + ] }, "anchorSource": "exact" }, @@ -19690,6 +19719,8 @@ "status": "partial", "evidence": "surface-manifest:node-builtin.crypto.createCipheriv", "tests": [ + "tests/corpus/7150-cipher-legacy-modes.ts", + "tests/corpus/7151-cipher-legacy-errors.cjs", "tests/corpus/5250-cipher-aes-gcm.ts", "tests/corpus/5251-cipher-aes-cbc.ts", "tests/corpus/5252-cipher-aes-ctr.ts", @@ -19700,6 +19731,9 @@ "tests/corpus/5257-cipher-vectors.ts", "tests/corpus/5258-cipher-handles.js", "tests/corpus/5259-cipher-chunked.ts", + "tests/corpus/7055-cipher-streams.ts", + "tests/corpus/7056-cipher-stream-errors.ts", + "tests/corpus/7057-cipher-streams.mjs", "tests/fixtures/node-types/cipher.ts" ] }, @@ -19726,6 +19760,8 @@ "status": "partial", "evidence": "surface-manifest:node-builtin.crypto.createDecipheriv", "tests": [ + "tests/corpus/7150-cipher-legacy-modes.ts", + "tests/corpus/7151-cipher-legacy-errors.cjs", "tests/corpus/5250-cipher-aes-gcm.ts", "tests/corpus/5251-cipher-aes-cbc.ts", "tests/corpus/5252-cipher-aes-ctr.ts", @@ -19736,6 +19772,9 @@ "tests/corpus/5257-cipher-vectors.ts", "tests/corpus/5258-cipher-handles.js", "tests/corpus/5259-cipher-chunked.ts", + "tests/corpus/7055-cipher-streams.ts", + "tests/corpus/7056-cipher-stream-errors.ts", + "tests/corpus/7057-cipher-streams.mjs", "tests/fixtures/node-types/cipher.ts" ] }, @@ -19759,8 +19798,17 @@ "inherited": true }, "static": { - "status": "refused", - "evidence": "surface-manifest:unsupported:node-builtin.crypto.createDiffieHellman" + "status": "partial", + "evidence": "surface-manifest:node-builtin.crypto.createDiffieHellman", + "tests": [ + "tests/corpus/6706-dh-groups.ts", + "tests/corpus/6707-dh-explicit-params.ts", + "tests/corpus/6708-dh-errors.js", + "tests/corpus/6709-dh-generate.ts", + "tests/corpus/6710-dh-encodings.cjs", + "tests/corpus/6711-dh-handles.ts", + "tests/fixtures/node-types/dh.ts" + ] }, "anchorSource": "exact" }, @@ -19782,8 +19830,17 @@ "inherited": true }, "static": { - "status": "refused", - "evidence": "surface-manifest:unsupported:node-builtin.crypto.createDiffieHellman" + "status": "partial", + "evidence": "surface-manifest:node-builtin.crypto.createDiffieHellman", + "tests": [ + "tests/corpus/6706-dh-groups.ts", + "tests/corpus/6707-dh-explicit-params.ts", + "tests/corpus/6708-dh-errors.js", + "tests/corpus/6709-dh-generate.ts", + "tests/corpus/6710-dh-encodings.cjs", + "tests/corpus/6711-dh-handles.ts", + "tests/fixtures/node-types/dh.ts" + ] }, "anchorSource": "exact" }, @@ -19805,8 +19862,17 @@ "inherited": true }, "static": { - "status": "refused", - "evidence": "surface-manifest:unsupported:node-builtin.crypto.createDiffieHellmanGroup" + "status": "partial", + "evidence": "surface-manifest:node-builtin.crypto.createDiffieHellmanGroup", + "tests": [ + "tests/corpus/6706-dh-groups.ts", + "tests/corpus/6707-dh-explicit-params.ts", + "tests/corpus/6708-dh-errors.js", + "tests/corpus/6709-dh-generate.ts", + "tests/corpus/6710-dh-encodings.cjs", + "tests/corpus/6711-dh-handles.ts", + "tests/fixtures/node-types/dh.ts" + ] }, "anchorSource": "exact" }, @@ -19961,8 +20027,15 @@ "inherited": true }, "static": { - "status": "refused", - "evidence": "surface-manifest:unsupported:node-builtin.crypto.createPrivateKey" + "status": "partial", + "evidence": "compiler-dedicated:crypto.createPrivateKey", + "tests": [ + "tests/corpus/7080-crypto-ed25519.mjs", + "tests/corpus/7082-crypto-key-objects.ts", + "tests/corpus/7083-crypto-sign-verify.ts", + "tests/corpus/7084-crypto-key-pairs.cjs", + "tests/fixtures/node-types/keys.ts" + ] }, "anchorSource": "exact" }, @@ -20007,8 +20080,15 @@ "inherited": true }, "static": { - "status": "refused", - "evidence": "surface-manifest:unsupported:node-builtin.crypto.createPublicKey" + "status": "partial", + "evidence": "compiler-dedicated:crypto.createPublicKey", + "tests": [ + "tests/corpus/7080-crypto-ed25519.mjs", + "tests/corpus/7082-crypto-key-objects.ts", + "tests/corpus/7083-crypto-sign-verify.ts", + "tests/corpus/7084-crypto-key-pairs.cjs", + "tests/fixtures/node-types/keys.ts" + ] }, "anchorSource": "exact" }, @@ -20057,8 +20137,15 @@ "inherited": true }, "static": { - "status": "refused", - "evidence": "surface-manifest:unsupported:node-builtin.crypto.createSign" + "status": "partial", + "evidence": "compiler-dedicated:crypto.createSign", + "tests": [ + "tests/corpus/7080-crypto-ed25519.mjs", + "tests/corpus/7082-crypto-key-objects.ts", + "tests/corpus/7083-crypto-sign-verify.ts", + "tests/corpus/7084-crypto-key-pairs.cjs", + "tests/fixtures/node-types/keys.ts" + ] }, "anchorSource": "exact" }, @@ -20080,8 +20167,15 @@ "inherited": true }, "static": { - "status": "refused", - "evidence": "surface-manifest:unsupported:node-builtin.crypto.createVerify" + "status": "partial", + "evidence": "compiler-dedicated:crypto.createVerify", + "tests": [ + "tests/corpus/7080-crypto-ed25519.mjs", + "tests/corpus/7082-crypto-key-objects.ts", + "tests/corpus/7083-crypto-sign-verify.ts", + "tests/corpus/7084-crypto-key-pairs.cjs", + "tests/fixtures/node-types/keys.ts" + ] }, "anchorSource": "exact" }, @@ -20199,8 +20293,15 @@ "inherited": true }, "static": { - "status": "refused", - "evidence": "surface-manifest:unsupported:node-builtin.crypto.generateKeyPair" + "status": "partial", + "evidence": "compiler-dedicated:crypto.generateKeyPair", + "tests": [ + "tests/corpus/7080-crypto-ed25519.mjs", + "tests/corpus/7082-crypto-key-objects.ts", + "tests/corpus/7083-crypto-sign-verify.ts", + "tests/corpus/7084-crypto-key-pairs.cjs", + "tests/fixtures/node-types/keys.ts" + ] }, "anchorSource": "exact" }, @@ -20222,8 +20323,15 @@ "inherited": true }, "static": { - "status": "refused", - "evidence": "surface-manifest:unsupported:node-builtin.crypto.generateKeyPairSync" + "status": "partial", + "evidence": "compiler-dedicated:crypto.generateKeyPairSync", + "tests": [ + "tests/corpus/7080-crypto-ed25519.mjs", + "tests/corpus/7082-crypto-key-objects.ts", + "tests/corpus/7083-crypto-sign-verify.ts", + "tests/corpus/7084-crypto-key-pairs.cjs", + "tests/fixtures/node-types/keys.ts" + ] }, "anchorSource": "exact" }, @@ -20272,8 +20380,12 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:crypto" + "status": "partial", + "evidence": "surface-manifest:node-builtin.crypto.generatePrime", + "tests": [ + "tests/corpus/7152-crypto-prime.ts", + "tests/corpus/7153-crypto-prime-errors.cjs" + ] }, "anchorSource": "exact" }, @@ -20295,8 +20407,12 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:crypto" + "status": "partial", + "evidence": "surface-manifest:node-builtin.crypto.generatePrimeSync", + "tests": [ + "tests/corpus/7152-crypto-prime.ts", + "tests/corpus/7153-crypto-prime-errors.cjs" + ] }, "anchorSource": "exact" }, @@ -20387,8 +20503,17 @@ "inherited": true }, "static": { - "status": "refused", - "evidence": "surface-manifest:unsupported:node-builtin.crypto.getDiffieHellman" + "status": "partial", + "evidence": "surface-manifest:node-builtin.crypto.getDiffieHellman", + "tests": [ + "tests/corpus/6706-dh-groups.ts", + "tests/corpus/6707-dh-explicit-params.ts", + "tests/corpus/6708-dh-errors.js", + "tests/corpus/6709-dh-generate.ts", + "tests/corpus/6710-dh-encodings.cjs", + "tests/corpus/6711-dh-handles.ts", + "tests/fixtures/node-types/dh.ts" + ] }, "anchorSource": "exact" }, @@ -21096,8 +21221,15 @@ "inherited": true }, "static": { - "status": "refused", - "evidence": "surface-manifest:unsupported:node-builtin.crypto.sign" + "status": "partial", + "evidence": "compiler-dedicated:crypto.sign", + "tests": [ + "tests/corpus/7080-crypto-ed25519.mjs", + "tests/corpus/7082-crypto-key-objects.ts", + "tests/corpus/7083-crypto-sign-verify.ts", + "tests/corpus/7084-crypto-key-pairs.cjs", + "tests/fixtures/node-types/keys.ts" + ] }, "anchorSource": "exact" }, @@ -21146,8 +21278,15 @@ "inherited": true }, "static": { - "status": "refused", - "evidence": "surface-manifest:unsupported:node-builtin.crypto.verify" + "status": "partial", + "evidence": "compiler-dedicated:crypto.verify", + "tests": [ + "tests/corpus/7080-crypto-ed25519.mjs", + "tests/corpus/7082-crypto-key-objects.ts", + "tests/corpus/7083-crypto-sign-verify.ts", + "tests/corpus/7084-crypto-key-pairs.cjs", + "tests/fixtures/node-types/keys.ts" + ] }, "anchorSource": "exact" }, @@ -21215,8 +21354,12 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:crypto" + "status": "partial", + "evidence": "compiler-dedicated:subtle", + "tests": [ + "tests/corpus/7122-webcrypto-node-crypto.ts", + "tests/corpus/7123-webcrypto-node-crypto.cjs" + ] }, "anchorSource": "ancestor" }, @@ -21238,8 +21381,12 @@ "inherited": true }, "static": { - "status": "refused", - "evidence": "surface-manifest:unsupported:node-builtin.crypto.webcrypto" + "status": "partial", + "evidence": "compiler-dedicated:crypto.webcrypto", + "tests": [ + "tests/corpus/7122-webcrypto-node-crypto.ts", + "tests/corpus/7123-webcrypto-node-crypto.cjs" + ] }, "anchorSource": "exact" }, @@ -21734,6 +21881,9 @@ "tests/corpus/5257-cipher-vectors.ts", "tests/corpus/5258-cipher-handles.js", "tests/corpus/5259-cipher-chunked.ts", + "tests/corpus/7055-cipher-streams.ts", + "tests/corpus/7056-cipher-stream-errors.ts", + "tests/corpus/7057-cipher-streams.mjs", "tests/fixtures/node-types/cipher.ts" ] }, @@ -21770,6 +21920,9 @@ "tests/corpus/5257-cipher-vectors.ts", "tests/corpus/5258-cipher-handles.js", "tests/corpus/5259-cipher-chunked.ts", + "tests/corpus/7055-cipher-streams.ts", + "tests/corpus/7056-cipher-stream-errors.ts", + "tests/corpus/7057-cipher-streams.mjs", "tests/fixtures/node-types/cipher.ts" ] }, @@ -21806,6 +21959,9 @@ "tests/corpus/5257-cipher-vectors.ts", "tests/corpus/5258-cipher-handles.js", "tests/corpus/5259-cipher-chunked.ts", + "tests/corpus/7055-cipher-streams.ts", + "tests/corpus/7056-cipher-stream-errors.ts", + "tests/corpus/7057-cipher-streams.mjs", "tests/fixtures/node-types/cipher.ts" ] }, @@ -21842,6 +21998,9 @@ "tests/corpus/5257-cipher-vectors.ts", "tests/corpus/5258-cipher-handles.js", "tests/corpus/5259-cipher-chunked.ts", + "tests/corpus/7055-cipher-streams.ts", + "tests/corpus/7056-cipher-stream-errors.ts", + "tests/corpus/7057-cipher-streams.mjs", "tests/fixtures/node-types/cipher.ts" ] }, @@ -21878,6 +22037,9 @@ "tests/corpus/5257-cipher-vectors.ts", "tests/corpus/5258-cipher-handles.js", "tests/corpus/5259-cipher-chunked.ts", + "tests/corpus/7055-cipher-streams.ts", + "tests/corpus/7056-cipher-stream-errors.ts", + "tests/corpus/7057-cipher-streams.mjs", "tests/fixtures/node-types/cipher.ts" ] }, @@ -21914,6 +22076,9 @@ "tests/corpus/5257-cipher-vectors.ts", "tests/corpus/5258-cipher-handles.js", "tests/corpus/5259-cipher-chunked.ts", + "tests/corpus/7055-cipher-streams.ts", + "tests/corpus/7056-cipher-stream-errors.ts", + "tests/corpus/7057-cipher-streams.mjs", "tests/fixtures/node-types/cipher.ts" ] }, @@ -21950,6 +22115,9 @@ "tests/corpus/5257-cipher-vectors.ts", "tests/corpus/5258-cipher-handles.js", "tests/corpus/5259-cipher-chunked.ts", + "tests/corpus/7055-cipher-streams.ts", + "tests/corpus/7056-cipher-stream-errors.ts", + "tests/corpus/7057-cipher-streams.mjs", "tests/fixtures/node-types/cipher.ts" ] }, @@ -21986,6 +22154,9 @@ "tests/corpus/5257-cipher-vectors.ts", "tests/corpus/5258-cipher-handles.js", "tests/corpus/5259-cipher-chunked.ts", + "tests/corpus/7055-cipher-streams.ts", + "tests/corpus/7056-cipher-stream-errors.ts", + "tests/corpus/7057-cipher-streams.mjs", "tests/fixtures/node-types/cipher.ts" ] }, @@ -22022,6 +22193,9 @@ "tests/corpus/5257-cipher-vectors.ts", "tests/corpus/5258-cipher-handles.js", "tests/corpus/5259-cipher-chunked.ts", + "tests/corpus/7055-cipher-streams.ts", + "tests/corpus/7056-cipher-stream-errors.ts", + "tests/corpus/7057-cipher-streams.mjs", "tests/fixtures/node-types/cipher.ts" ] }, @@ -22058,6 +22232,9 @@ "tests/corpus/5257-cipher-vectors.ts", "tests/corpus/5258-cipher-handles.js", "tests/corpus/5259-cipher-chunked.ts", + "tests/corpus/7055-cipher-streams.ts", + "tests/corpus/7056-cipher-stream-errors.ts", + "tests/corpus/7057-cipher-streams.mjs", "tests/fixtures/node-types/cipher.ts" ] }, @@ -22094,6 +22271,9 @@ "tests/corpus/5257-cipher-vectors.ts", "tests/corpus/5258-cipher-handles.js", "tests/corpus/5259-cipher-chunked.ts", + "tests/corpus/7055-cipher-streams.ts", + "tests/corpus/7056-cipher-stream-errors.ts", + "tests/corpus/7057-cipher-streams.mjs", "tests/fixtures/node-types/cipher.ts" ] }, @@ -22130,6 +22310,9 @@ "tests/corpus/5257-cipher-vectors.ts", "tests/corpus/5258-cipher-handles.js", "tests/corpus/5259-cipher-chunked.ts", + "tests/corpus/7055-cipher-streams.ts", + "tests/corpus/7056-cipher-stream-errors.ts", + "tests/corpus/7057-cipher-streams.mjs", "tests/fixtures/node-types/cipher.ts" ] }, @@ -22153,8 +22336,17 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:crypto" + "status": "partial", + "evidence": "compiler-dedicated:DiffieHellman", + "tests": [ + "tests/corpus/6706-dh-groups.ts", + "tests/corpus/6707-dh-explicit-params.ts", + "tests/corpus/6708-dh-errors.js", + "tests/corpus/6709-dh-generate.ts", + "tests/corpus/6710-dh-encodings.cjs", + "tests/corpus/6711-dh-handles.ts", + "tests/fixtures/node-types/dh.ts" + ] }, "anchorSource": "exact" }, @@ -22176,8 +22368,17 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:crypto" + "status": "partial", + "evidence": "compiler-dedicated:diffieHellman.computeSecret", + "tests": [ + "tests/corpus/6706-dh-groups.ts", + "tests/corpus/6707-dh-explicit-params.ts", + "tests/corpus/6708-dh-errors.js", + "tests/corpus/6709-dh-generate.ts", + "tests/corpus/6710-dh-encodings.cjs", + "tests/corpus/6711-dh-handles.ts", + "tests/fixtures/node-types/dh.ts" + ] }, "anchorSource": "exact" }, @@ -22199,8 +22400,17 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:crypto" + "status": "partial", + "evidence": "compiler-dedicated:diffieHellman.generateKeys", + "tests": [ + "tests/corpus/6706-dh-groups.ts", + "tests/corpus/6707-dh-explicit-params.ts", + "tests/corpus/6708-dh-errors.js", + "tests/corpus/6709-dh-generate.ts", + "tests/corpus/6710-dh-encodings.cjs", + "tests/corpus/6711-dh-handles.ts", + "tests/fixtures/node-types/dh.ts" + ] }, "anchorSource": "exact" }, @@ -22222,8 +22432,17 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:crypto" + "status": "partial", + "evidence": "compiler-dedicated:diffieHellman.getGenerator", + "tests": [ + "tests/corpus/6706-dh-groups.ts", + "tests/corpus/6707-dh-explicit-params.ts", + "tests/corpus/6708-dh-errors.js", + "tests/corpus/6709-dh-generate.ts", + "tests/corpus/6710-dh-encodings.cjs", + "tests/corpus/6711-dh-handles.ts", + "tests/fixtures/node-types/dh.ts" + ] }, "anchorSource": "exact" }, @@ -22245,8 +22464,17 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:crypto" + "status": "partial", + "evidence": "compiler-dedicated:diffieHellman.getPrime", + "tests": [ + "tests/corpus/6706-dh-groups.ts", + "tests/corpus/6707-dh-explicit-params.ts", + "tests/corpus/6708-dh-errors.js", + "tests/corpus/6709-dh-generate.ts", + "tests/corpus/6710-dh-encodings.cjs", + "tests/corpus/6711-dh-handles.ts", + "tests/fixtures/node-types/dh.ts" + ] }, "anchorSource": "exact" }, @@ -22268,8 +22496,17 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:crypto" + "status": "partial", + "evidence": "compiler-dedicated:diffieHellman.getPrivateKey", + "tests": [ + "tests/corpus/6706-dh-groups.ts", + "tests/corpus/6707-dh-explicit-params.ts", + "tests/corpus/6708-dh-errors.js", + "tests/corpus/6709-dh-generate.ts", + "tests/corpus/6710-dh-encodings.cjs", + "tests/corpus/6711-dh-handles.ts", + "tests/fixtures/node-types/dh.ts" + ] }, "anchorSource": "exact" }, @@ -22291,8 +22528,17 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:crypto" + "status": "partial", + "evidence": "compiler-dedicated:diffieHellman.getPublicKey", + "tests": [ + "tests/corpus/6706-dh-groups.ts", + "tests/corpus/6707-dh-explicit-params.ts", + "tests/corpus/6708-dh-errors.js", + "tests/corpus/6709-dh-generate.ts", + "tests/corpus/6710-dh-encodings.cjs", + "tests/corpus/6711-dh-handles.ts", + "tests/fixtures/node-types/dh.ts" + ] }, "anchorSource": "exact" }, @@ -22314,8 +22560,17 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:crypto" + "status": "partial", + "evidence": "compiler-dedicated:diffieHellman.setPrivateKey", + "tests": [ + "tests/corpus/6706-dh-groups.ts", + "tests/corpus/6707-dh-explicit-params.ts", + "tests/corpus/6708-dh-errors.js", + "tests/corpus/6709-dh-generate.ts", + "tests/corpus/6710-dh-encodings.cjs", + "tests/corpus/6711-dh-handles.ts", + "tests/fixtures/node-types/dh.ts" + ] }, "anchorSource": "exact" }, @@ -22337,8 +22592,17 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:crypto" + "status": "partial", + "evidence": "compiler-dedicated:diffieHellman.setPublicKey", + "tests": [ + "tests/corpus/6706-dh-groups.ts", + "tests/corpus/6707-dh-explicit-params.ts", + "tests/corpus/6708-dh-errors.js", + "tests/corpus/6709-dh-generate.ts", + "tests/corpus/6710-dh-encodings.cjs", + "tests/corpus/6711-dh-handles.ts", + "tests/fixtures/node-types/dh.ts" + ] }, "anchorSource": "exact" }, @@ -22360,8 +22624,17 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:crypto" + "status": "partial", + "evidence": "compiler-dedicated:diffieHellman.verifyError", + "tests": [ + "tests/corpus/6706-dh-groups.ts", + "tests/corpus/6707-dh-explicit-params.ts", + "tests/corpus/6708-dh-errors.js", + "tests/corpus/6709-dh-generate.ts", + "tests/corpus/6710-dh-encodings.cjs", + "tests/corpus/6711-dh-handles.ts", + "tests/fixtures/node-types/dh.ts" + ] }, "anchorSource": "exact" }, @@ -22383,8 +22656,17 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:crypto" + "status": "partial", + "evidence": "compiler-dedicated:DiffieHellmanGroup", + "tests": [ + "tests/corpus/6706-dh-groups.ts", + "tests/corpus/6707-dh-explicit-params.ts", + "tests/corpus/6708-dh-errors.js", + "tests/corpus/6709-dh-generate.ts", + "tests/corpus/6710-dh-encodings.cjs", + "tests/corpus/6711-dh-handles.ts", + "tests/fixtures/node-types/dh.ts" + ] }, "anchorSource": "exact" }, @@ -23007,8 +23289,15 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:crypto" + "status": "partial", + "evidence": "compiler-dedicated:asymmetricKeyDetails", + "tests": [ + "tests/corpus/7080-crypto-ed25519.mjs", + "tests/corpus/7082-crypto-key-objects.ts", + "tests/corpus/7083-crypto-sign-verify.ts", + "tests/corpus/7084-crypto-key-pairs.cjs", + "tests/fixtures/node-types/keys.ts" + ] }, "anchorSource": "ancestor" }, @@ -23030,8 +23319,15 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:crypto" + "status": "partial", + "evidence": "compiler-dedicated:asymmetricKeyType", + "tests": [ + "tests/corpus/7080-crypto-ed25519.mjs", + "tests/corpus/7082-crypto-key-objects.ts", + "tests/corpus/7083-crypto-sign-verify.ts", + "tests/corpus/7084-crypto-key-pairs.cjs", + "tests/fixtures/node-types/keys.ts" + ] }, "anchorSource": "ancestor" }, @@ -23168,8 +23464,15 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:crypto" + "status": "partial", + "evidence": "compiler-dedicated:Sign", + "tests": [ + "tests/corpus/7080-crypto-ed25519.mjs", + "tests/corpus/7082-crypto-key-objects.ts", + "tests/corpus/7083-crypto-sign-verify.ts", + "tests/corpus/7084-crypto-key-pairs.cjs", + "tests/fixtures/node-types/keys.ts" + ] }, "anchorSource": "exact" }, @@ -23191,8 +23494,15 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:crypto" + "status": "partial", + "evidence": "compiler-dedicated:sign.sign", + "tests": [ + "tests/corpus/7080-crypto-ed25519.mjs", + "tests/corpus/7082-crypto-key-objects.ts", + "tests/corpus/7083-crypto-sign-verify.ts", + "tests/corpus/7084-crypto-key-pairs.cjs", + "tests/fixtures/node-types/keys.ts" + ] }, "anchorSource": "exact" }, @@ -23214,8 +23524,15 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:crypto" + "status": "partial", + "evidence": "compiler-dedicated:sign.update", + "tests": [ + "tests/corpus/7080-crypto-ed25519.mjs", + "tests/corpus/7082-crypto-key-objects.ts", + "tests/corpus/7083-crypto-sign-verify.ts", + "tests/corpus/7084-crypto-key-pairs.cjs", + "tests/fixtures/node-types/keys.ts" + ] }, "anchorSource": "exact" }, @@ -23237,8 +23554,15 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:crypto" + "status": "partial", + "evidence": "compiler-dedicated:Verify", + "tests": [ + "tests/corpus/7080-crypto-ed25519.mjs", + "tests/corpus/7082-crypto-key-objects.ts", + "tests/corpus/7083-crypto-sign-verify.ts", + "tests/corpus/7084-crypto-key-pairs.cjs", + "tests/fixtures/node-types/keys.ts" + ] }, "anchorSource": "exact" }, @@ -23260,8 +23584,15 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:crypto" + "status": "partial", + "evidence": "compiler-dedicated:verify.update", + "tests": [ + "tests/corpus/7080-crypto-ed25519.mjs", + "tests/corpus/7082-crypto-key-objects.ts", + "tests/corpus/7083-crypto-sign-verify.ts", + "tests/corpus/7084-crypto-key-pairs.cjs", + "tests/fixtures/node-types/keys.ts" + ] }, "anchorSource": "exact" }, @@ -23283,8 +23614,15 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:crypto" + "status": "partial", + "evidence": "compiler-dedicated:verify.verify", + "tests": [ + "tests/corpus/7080-crypto-ed25519.mjs", + "tests/corpus/7082-crypto-key-objects.ts", + "tests/corpus/7083-crypto-sign-verify.ts", + "tests/corpus/7084-crypto-key-pairs.cjs", + "tests/fixtures/node-types/keys.ts" + ] }, "anchorSource": "exact" }, @@ -27448,8 +27786,17 @@ "anchor": "dep0167-weak-diffiehellmangroup-instances-modp1-modp2-modp5", "nodeStability": null, "static": { - "status": "not-applicable", - "evidence": "compiler-chapter-policy:deprecations" + "status": "partial", + "evidence": "compiler-dedicated:DiffieHellmanGroup", + "tests": [ + "tests/corpus/6706-dh-groups.ts", + "tests/corpus/6707-dh-explicit-params.ts", + "tests/corpus/6708-dh-errors.js", + "tests/corpus/6709-dh-generate.ts", + "tests/corpus/6710-dh-encodings.cjs", + "tests/corpus/6711-dh-handles.ts", + "tests/fixtures/node-types/dh.ts" + ] }, "anchorSource": "exact" }, @@ -32191,6 +32538,7 @@ "evidence": "derived:descendants", "tests": [ "tests/corpus/6702-ecdh-errors.js", + "tests/corpus/6708-dh-errors.js", "tests/corpus/caught-system-error-fields.ts", "tests/corpus/error-stack-frames.ts", "tests/corpus/error-stack-limit.ts", @@ -33601,8 +33949,11 @@ "anchor": "err_crypto_invalid_keylen", "nodeStability": null, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:errors" + "status": "partial", + "evidence": "compiler-dedicated:ERR_CRYPTO_INVALID_KEYLEN", + "tests": [ + "tests/corpus/6708-dh-errors.js" + ] }, "anchorSource": "exact" }, @@ -33727,8 +34078,11 @@ "anchor": "err_crypto_invalid_state", "nodeStability": null, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:errors" + "status": "partial", + "evidence": "compiler-dedicated:ERR_CRYPTO_INVALID_STATE", + "tests": [ + "tests/corpus/6708-dh-errors.js" + ] }, "anchorSource": "exact" }, @@ -33997,8 +34351,11 @@ "anchor": "err_crypto_unknown_dh_group", "nodeStability": null, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:errors" + "status": "partial", + "evidence": "compiler-dedicated:ERR_CRYPTO_UNKNOWN_DH_GROUP", + "tests": [ + "tests/corpus/6708-dh-errors.js" + ] }, "anchorSource": "exact" }, @@ -95366,7 +95723,10 @@ "tests/corpus/2557-tls-ca-store.ts", "tests/corpus/2596-net-arg-ladders.cjs", "tests/corpus/6721-tls-alpn-protocols.ts", - "tests/corpus/6722-tls-min-max-version.ts" + "tests/corpus/6722-tls-min-max-version.ts", + "tests/corpus/7087-tls-socket-wrap.ts", + "tests/corpus/7088-tls-socket-connect-tunnel.ts", + "tests/fixtures/node-types/tls-socket-wrap.ts" ] }, "anchorSource": "chapter" @@ -96068,8 +96428,13 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:tls" + "status": "partial", + "evidence": "compiler-feature:tls.tls.TLSSocket", + "tests": [ + "tests/corpus/7087-tls-socket-wrap.ts", + "tests/corpus/7088-tls-socket-connect-tunnel.ts", + "tests/fixtures/node-types/tls-socket-wrap.ts" + ] }, "anchorSource": "exact" }, @@ -96856,8 +97221,13 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:tls" + "status": "partial", + "evidence": "compiler-feature:tls.'secure'", + "tests": [ + "tests/corpus/7087-tls-socket-wrap.ts", + "tests/corpus/7088-tls-socket-connect-tunnel.ts", + "tests/fixtures/node-types/tls-socket-wrap.ts" + ] }, "anchorSource": "exact" }, @@ -106607,8 +106977,6 @@ "tests/corpus/1534-crypto-hash-chain.ts", "tests/corpus/2556-crypto-introspection.ts", "tests/corpus/2890-crypto-static-utility.ts", - "tests/corpus/5442-crypto-random-values.ts", - "tests/corpus/5443-crypto-random-arguments.js", "tests/corpus/6204-crypto-get-random-values.ts", "tests/corpus/6205-crypto-get-random-values.js", "tests/corpus/6291-webcrypto-hmac-sign-verify.ts", @@ -106616,11 +106984,26 @@ "tests/corpus/6293-webcrypto-digest.ts", "tests/corpus/6294-webcrypto-js-values.mjs", "tests/corpus/6295-jose-hs256/main.mjs", + "tests/corpus/7081-webcrypto-ed25519.mjs", + "tests/corpus/7085-webcrypto-ecdsa-rsa.ts", + "tests/corpus/7086-webcrypto-ecdsa-rsa-errors.mjs", + "tests/corpus/7120-webcrypto-random-uuid.ts", + "tests/corpus/7121-webcrypto-crypto-object.mjs", + "tests/corpus/7124-webcrypto-secret-keys.ts", + "tests/corpus/7125-webcrypto-key-errors.mjs", + "tests/corpus/7126-webcrypto-aes.ts", + "tests/corpus/7127-webcrypto-aes-errors.mjs", + "tests/corpus/7128-webcrypto-derive.ts", + "tests/corpus/7129-webcrypto-derive-errors.mjs", + "tests/corpus/7130-webcrypto-wrap-key.ts", + "tests/corpus/7131-webcrypto-wrap-key-errors.mjs", + "tests/corpus/7132-jose-pbes2/main.mjs", "tests/corpus/node24-crypto-kdf-errors.ts", "tests/corpus/node24-crypto-kdf-options.ts", "tests/corpus/node24-crypto-kdf.ts", "tests/corpus/node24-crypto-sha2.ts", "tests/fixtures/node-types/webcrypto-hmac.ts", + "tests/fixtures/node-types/webcrypto-keys.ts", "tests/harness/npm-static.test.ts" ] }, @@ -110078,8 +110461,13 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:webcrypto" + "status": "partial", + "evidence": "compiler-feature:webcrypto.Crypto", + "tests": [ + "tests/corpus/7120-webcrypto-random-uuid.ts", + "tests/corpus/7121-webcrypto-crypto-object.mjs", + "tests/corpus/6293-webcrypto-digest.ts" + ] }, "anchorSource": "exact" }, @@ -110102,8 +110490,10 @@ }, "static": { "status": "supported", - "evidence": "compiler-dedicated:crypto.getRandomValues", + "evidence": "compiler-feature:webcrypto.crypto.getRandomValues", "tests": [ + "tests/corpus/7120-webcrypto-random-uuid.ts", + "tests/corpus/7121-webcrypto-crypto-object.mjs", "tests/corpus/6204-crypto-get-random-values.ts", "tests/corpus/6205-crypto-get-random-values.js" ] @@ -110129,11 +110519,12 @@ }, "static": { "status": "supported", - "evidence": "compiler-dedicated:crypto.randomUUID", + "evidence": "compiler-feature:webcrypto.crypto.randomUUID", "tests": [ - "tests/corpus/5442-crypto-random-values.ts", - "tests/corpus/5443-crypto-random-arguments.js", - "tests/corpus/1358-crypto-random.ts" + "tests/corpus/7120-webcrypto-random-uuid.ts", + "tests/corpus/7121-webcrypto-crypto-object.mjs", + "tests/corpus/6204-crypto-get-random-values.ts", + "tests/corpus/6205-crypto-get-random-values.js" ] }, "anchorSource": "exact" @@ -110189,6 +110580,7 @@ "status": "partial", "evidence": "compiler-feature:webcrypto.CryptoKey", "tests": [ + "tests/corpus/7124-webcrypto-secret-keys.ts", "tests/corpus/6291-webcrypto-hmac-sign-verify.ts", "tests/corpus/6294-webcrypto-js-values.mjs", "tests/corpus/6295-jose-hs256/main.mjs" @@ -110217,6 +110609,7 @@ "status": "partial", "evidence": "compiler-feature:webcrypto.cryptoKey.algorithm", "tests": [ + "tests/corpus/7124-webcrypto-secret-keys.ts", "tests/corpus/6291-webcrypto-hmac-sign-verify.ts", "tests/corpus/6294-webcrypto-js-values.mjs", "tests/corpus/6295-jose-hs256/main.mjs" @@ -110245,6 +110638,7 @@ "status": "partial", "evidence": "compiler-feature:webcrypto.extractable", "tests": [ + "tests/corpus/7124-webcrypto-secret-keys.ts", "tests/corpus/6291-webcrypto-hmac-sign-verify.ts", "tests/corpus/6294-webcrypto-js-values.mjs", "tests/corpus/6295-jose-hs256/main.mjs" @@ -110273,6 +110667,7 @@ "status": "partial", "evidence": "compiler-feature:webcrypto.type", "tests": [ + "tests/corpus/7124-webcrypto-secret-keys.ts", "tests/corpus/6291-webcrypto-hmac-sign-verify.ts", "tests/corpus/6294-webcrypto-js-values.mjs", "tests/corpus/6295-jose-hs256/main.mjs" @@ -110301,6 +110696,7 @@ "status": "partial", "evidence": "compiler-feature:webcrypto.usages", "tests": [ + "tests/corpus/7124-webcrypto-secret-keys.ts", "tests/corpus/6291-webcrypto-hmac-sign-verify.ts", "tests/corpus/6294-webcrypto-js-values.mjs", "tests/corpus/6295-jose-hs256/main.mjs" @@ -110471,8 +110867,29 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:webcrypto" + "status": "partial", + "evidence": "compiler-feature:webcrypto.subtle.decrypt", + "tests": [ + "tests/corpus/7130-webcrypto-wrap-key.ts", + "tests/corpus/7131-webcrypto-wrap-key-errors.mjs", + "tests/corpus/7132-jose-pbes2/main.mjs", + "tests/corpus/7128-webcrypto-derive.ts", + "tests/corpus/7129-webcrypto-derive-errors.mjs", + "tests/corpus/7126-webcrypto-aes.ts", + "tests/corpus/7127-webcrypto-aes-errors.mjs", + "tests/corpus/7124-webcrypto-secret-keys.ts", + "tests/corpus/7125-webcrypto-key-errors.mjs", + "tests/fixtures/node-types/webcrypto-keys.ts", + "tests/corpus/6291-webcrypto-hmac-sign-verify.ts", + "tests/corpus/6292-webcrypto-hmac-errors.ts", + "tests/corpus/6293-webcrypto-digest.ts", + "tests/corpus/6294-webcrypto-js-values.mjs", + "tests/corpus/6295-jose-hs256/main.mjs", + "tests/fixtures/node-types/webcrypto-hmac.ts", + "tests/corpus/7081-webcrypto-ed25519.mjs", + "tests/corpus/7085-webcrypto-ecdsa-rsa.ts", + "tests/corpus/7086-webcrypto-ecdsa-rsa-errors.mjs" + ] }, "anchorSource": "exact" }, @@ -110494,8 +110911,29 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:webcrypto" + "status": "partial", + "evidence": "compiler-feature:webcrypto.subtle.deriveBits", + "tests": [ + "tests/corpus/7130-webcrypto-wrap-key.ts", + "tests/corpus/7131-webcrypto-wrap-key-errors.mjs", + "tests/corpus/7132-jose-pbes2/main.mjs", + "tests/corpus/7128-webcrypto-derive.ts", + "tests/corpus/7129-webcrypto-derive-errors.mjs", + "tests/corpus/7126-webcrypto-aes.ts", + "tests/corpus/7127-webcrypto-aes-errors.mjs", + "tests/corpus/7124-webcrypto-secret-keys.ts", + "tests/corpus/7125-webcrypto-key-errors.mjs", + "tests/fixtures/node-types/webcrypto-keys.ts", + "tests/corpus/6291-webcrypto-hmac-sign-verify.ts", + "tests/corpus/6292-webcrypto-hmac-errors.ts", + "tests/corpus/6293-webcrypto-digest.ts", + "tests/corpus/6294-webcrypto-js-values.mjs", + "tests/corpus/6295-jose-hs256/main.mjs", + "tests/fixtures/node-types/webcrypto-hmac.ts", + "tests/corpus/7081-webcrypto-ed25519.mjs", + "tests/corpus/7085-webcrypto-ecdsa-rsa.ts", + "tests/corpus/7086-webcrypto-ecdsa-rsa-errors.mjs" + ] }, "anchorSource": "exact" }, @@ -110517,8 +110955,29 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:webcrypto" + "status": "partial", + "evidence": "compiler-feature:webcrypto.subtle.deriveKey", + "tests": [ + "tests/corpus/7130-webcrypto-wrap-key.ts", + "tests/corpus/7131-webcrypto-wrap-key-errors.mjs", + "tests/corpus/7132-jose-pbes2/main.mjs", + "tests/corpus/7128-webcrypto-derive.ts", + "tests/corpus/7129-webcrypto-derive-errors.mjs", + "tests/corpus/7126-webcrypto-aes.ts", + "tests/corpus/7127-webcrypto-aes-errors.mjs", + "tests/corpus/7124-webcrypto-secret-keys.ts", + "tests/corpus/7125-webcrypto-key-errors.mjs", + "tests/fixtures/node-types/webcrypto-keys.ts", + "tests/corpus/6291-webcrypto-hmac-sign-verify.ts", + "tests/corpus/6292-webcrypto-hmac-errors.ts", + "tests/corpus/6293-webcrypto-digest.ts", + "tests/corpus/6294-webcrypto-js-values.mjs", + "tests/corpus/6295-jose-hs256/main.mjs", + "tests/fixtures/node-types/webcrypto-hmac.ts", + "tests/corpus/7081-webcrypto-ed25519.mjs", + "tests/corpus/7085-webcrypto-ecdsa-rsa.ts", + "tests/corpus/7086-webcrypto-ecdsa-rsa-errors.mjs" + ] }, "anchorSource": "exact" }, @@ -110543,12 +111002,25 @@ "status": "partial", "evidence": "compiler-feature:webcrypto.subtle.digest", "tests": [ + "tests/corpus/7130-webcrypto-wrap-key.ts", + "tests/corpus/7131-webcrypto-wrap-key-errors.mjs", + "tests/corpus/7132-jose-pbes2/main.mjs", + "tests/corpus/7128-webcrypto-derive.ts", + "tests/corpus/7129-webcrypto-derive-errors.mjs", + "tests/corpus/7126-webcrypto-aes.ts", + "tests/corpus/7127-webcrypto-aes-errors.mjs", + "tests/corpus/7124-webcrypto-secret-keys.ts", + "tests/corpus/7125-webcrypto-key-errors.mjs", + "tests/fixtures/node-types/webcrypto-keys.ts", "tests/corpus/6291-webcrypto-hmac-sign-verify.ts", "tests/corpus/6292-webcrypto-hmac-errors.ts", "tests/corpus/6293-webcrypto-digest.ts", "tests/corpus/6294-webcrypto-js-values.mjs", "tests/corpus/6295-jose-hs256/main.mjs", - "tests/fixtures/node-types/webcrypto-hmac.ts" + "tests/fixtures/node-types/webcrypto-hmac.ts", + "tests/corpus/7081-webcrypto-ed25519.mjs", + "tests/corpus/7085-webcrypto-ecdsa-rsa.ts", + "tests/corpus/7086-webcrypto-ecdsa-rsa-errors.mjs" ] }, "anchorSource": "exact" @@ -110617,8 +111089,29 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:webcrypto" + "status": "partial", + "evidence": "compiler-feature:webcrypto.subtle.encrypt", + "tests": [ + "tests/corpus/7130-webcrypto-wrap-key.ts", + "tests/corpus/7131-webcrypto-wrap-key-errors.mjs", + "tests/corpus/7132-jose-pbes2/main.mjs", + "tests/corpus/7128-webcrypto-derive.ts", + "tests/corpus/7129-webcrypto-derive-errors.mjs", + "tests/corpus/7126-webcrypto-aes.ts", + "tests/corpus/7127-webcrypto-aes-errors.mjs", + "tests/corpus/7124-webcrypto-secret-keys.ts", + "tests/corpus/7125-webcrypto-key-errors.mjs", + "tests/fixtures/node-types/webcrypto-keys.ts", + "tests/corpus/6291-webcrypto-hmac-sign-verify.ts", + "tests/corpus/6292-webcrypto-hmac-errors.ts", + "tests/corpus/6293-webcrypto-digest.ts", + "tests/corpus/6294-webcrypto-js-values.mjs", + "tests/corpus/6295-jose-hs256/main.mjs", + "tests/fixtures/node-types/webcrypto-hmac.ts", + "tests/corpus/7081-webcrypto-ed25519.mjs", + "tests/corpus/7085-webcrypto-ecdsa-rsa.ts", + "tests/corpus/7086-webcrypto-ecdsa-rsa-errors.mjs" + ] }, "anchorSource": "exact" }, @@ -110640,8 +111133,29 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:webcrypto" + "status": "partial", + "evidence": "compiler-feature:webcrypto.subtle.exportKey", + "tests": [ + "tests/corpus/7130-webcrypto-wrap-key.ts", + "tests/corpus/7131-webcrypto-wrap-key-errors.mjs", + "tests/corpus/7132-jose-pbes2/main.mjs", + "tests/corpus/7128-webcrypto-derive.ts", + "tests/corpus/7129-webcrypto-derive-errors.mjs", + "tests/corpus/7126-webcrypto-aes.ts", + "tests/corpus/7127-webcrypto-aes-errors.mjs", + "tests/corpus/7124-webcrypto-secret-keys.ts", + "tests/corpus/7125-webcrypto-key-errors.mjs", + "tests/fixtures/node-types/webcrypto-keys.ts", + "tests/corpus/6291-webcrypto-hmac-sign-verify.ts", + "tests/corpus/6292-webcrypto-hmac-errors.ts", + "tests/corpus/6293-webcrypto-digest.ts", + "tests/corpus/6294-webcrypto-js-values.mjs", + "tests/corpus/6295-jose-hs256/main.mjs", + "tests/fixtures/node-types/webcrypto-hmac.ts", + "tests/corpus/7081-webcrypto-ed25519.mjs", + "tests/corpus/7085-webcrypto-ecdsa-rsa.ts", + "tests/corpus/7086-webcrypto-ecdsa-rsa-errors.mjs" + ] }, "anchorSource": "exact" }, @@ -110686,8 +111200,29 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:webcrypto" + "status": "partial", + "evidence": "compiler-feature:webcrypto.subtle.generateKey", + "tests": [ + "tests/corpus/7130-webcrypto-wrap-key.ts", + "tests/corpus/7131-webcrypto-wrap-key-errors.mjs", + "tests/corpus/7132-jose-pbes2/main.mjs", + "tests/corpus/7128-webcrypto-derive.ts", + "tests/corpus/7129-webcrypto-derive-errors.mjs", + "tests/corpus/7126-webcrypto-aes.ts", + "tests/corpus/7127-webcrypto-aes-errors.mjs", + "tests/corpus/7124-webcrypto-secret-keys.ts", + "tests/corpus/7125-webcrypto-key-errors.mjs", + "tests/fixtures/node-types/webcrypto-keys.ts", + "tests/corpus/6291-webcrypto-hmac-sign-verify.ts", + "tests/corpus/6292-webcrypto-hmac-errors.ts", + "tests/corpus/6293-webcrypto-digest.ts", + "tests/corpus/6294-webcrypto-js-values.mjs", + "tests/corpus/6295-jose-hs256/main.mjs", + "tests/fixtures/node-types/webcrypto-hmac.ts", + "tests/corpus/7081-webcrypto-ed25519.mjs", + "tests/corpus/7085-webcrypto-ecdsa-rsa.ts", + "tests/corpus/7086-webcrypto-ecdsa-rsa-errors.mjs" + ] }, "anchorSource": "exact" }, @@ -110712,12 +111247,25 @@ "status": "partial", "evidence": "compiler-feature:webcrypto.subtle.importKey", "tests": [ + "tests/corpus/7130-webcrypto-wrap-key.ts", + "tests/corpus/7131-webcrypto-wrap-key-errors.mjs", + "tests/corpus/7132-jose-pbes2/main.mjs", + "tests/corpus/7128-webcrypto-derive.ts", + "tests/corpus/7129-webcrypto-derive-errors.mjs", + "tests/corpus/7126-webcrypto-aes.ts", + "tests/corpus/7127-webcrypto-aes-errors.mjs", + "tests/corpus/7124-webcrypto-secret-keys.ts", + "tests/corpus/7125-webcrypto-key-errors.mjs", + "tests/fixtures/node-types/webcrypto-keys.ts", "tests/corpus/6291-webcrypto-hmac-sign-verify.ts", "tests/corpus/6292-webcrypto-hmac-errors.ts", "tests/corpus/6293-webcrypto-digest.ts", "tests/corpus/6294-webcrypto-js-values.mjs", "tests/corpus/6295-jose-hs256/main.mjs", - "tests/fixtures/node-types/webcrypto-hmac.ts" + "tests/fixtures/node-types/webcrypto-hmac.ts", + "tests/corpus/7081-webcrypto-ed25519.mjs", + "tests/corpus/7085-webcrypto-ecdsa-rsa.ts", + "tests/corpus/7086-webcrypto-ecdsa-rsa-errors.mjs" ] }, "anchorSource": "exact" @@ -110743,12 +111291,25 @@ "status": "partial", "evidence": "compiler-feature:webcrypto.subtle.sign", "tests": [ + "tests/corpus/7130-webcrypto-wrap-key.ts", + "tests/corpus/7131-webcrypto-wrap-key-errors.mjs", + "tests/corpus/7132-jose-pbes2/main.mjs", + "tests/corpus/7128-webcrypto-derive.ts", + "tests/corpus/7129-webcrypto-derive-errors.mjs", + "tests/corpus/7126-webcrypto-aes.ts", + "tests/corpus/7127-webcrypto-aes-errors.mjs", + "tests/corpus/7124-webcrypto-secret-keys.ts", + "tests/corpus/7125-webcrypto-key-errors.mjs", + "tests/fixtures/node-types/webcrypto-keys.ts", "tests/corpus/6291-webcrypto-hmac-sign-verify.ts", "tests/corpus/6292-webcrypto-hmac-errors.ts", "tests/corpus/6293-webcrypto-digest.ts", "tests/corpus/6294-webcrypto-js-values.mjs", "tests/corpus/6295-jose-hs256/main.mjs", - "tests/fixtures/node-types/webcrypto-hmac.ts" + "tests/fixtures/node-types/webcrypto-hmac.ts", + "tests/corpus/7081-webcrypto-ed25519.mjs", + "tests/corpus/7085-webcrypto-ecdsa-rsa.ts", + "tests/corpus/7086-webcrypto-ecdsa-rsa-errors.mjs" ] }, "anchorSource": "exact" @@ -110771,8 +111332,29 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:webcrypto" + "status": "partial", + "evidence": "compiler-feature:webcrypto.subtle.unwrapKey", + "tests": [ + "tests/corpus/7130-webcrypto-wrap-key.ts", + "tests/corpus/7131-webcrypto-wrap-key-errors.mjs", + "tests/corpus/7132-jose-pbes2/main.mjs", + "tests/corpus/7128-webcrypto-derive.ts", + "tests/corpus/7129-webcrypto-derive-errors.mjs", + "tests/corpus/7126-webcrypto-aes.ts", + "tests/corpus/7127-webcrypto-aes-errors.mjs", + "tests/corpus/7124-webcrypto-secret-keys.ts", + "tests/corpus/7125-webcrypto-key-errors.mjs", + "tests/fixtures/node-types/webcrypto-keys.ts", + "tests/corpus/6291-webcrypto-hmac-sign-verify.ts", + "tests/corpus/6292-webcrypto-hmac-errors.ts", + "tests/corpus/6293-webcrypto-digest.ts", + "tests/corpus/6294-webcrypto-js-values.mjs", + "tests/corpus/6295-jose-hs256/main.mjs", + "tests/fixtures/node-types/webcrypto-hmac.ts", + "tests/corpus/7081-webcrypto-ed25519.mjs", + "tests/corpus/7085-webcrypto-ecdsa-rsa.ts", + "tests/corpus/7086-webcrypto-ecdsa-rsa-errors.mjs" + ] }, "anchorSource": "exact" }, @@ -110797,12 +111379,25 @@ "status": "partial", "evidence": "compiler-feature:webcrypto.subtle.verify", "tests": [ + "tests/corpus/7130-webcrypto-wrap-key.ts", + "tests/corpus/7131-webcrypto-wrap-key-errors.mjs", + "tests/corpus/7132-jose-pbes2/main.mjs", + "tests/corpus/7128-webcrypto-derive.ts", + "tests/corpus/7129-webcrypto-derive-errors.mjs", + "tests/corpus/7126-webcrypto-aes.ts", + "tests/corpus/7127-webcrypto-aes-errors.mjs", + "tests/corpus/7124-webcrypto-secret-keys.ts", + "tests/corpus/7125-webcrypto-key-errors.mjs", + "tests/fixtures/node-types/webcrypto-keys.ts", "tests/corpus/6291-webcrypto-hmac-sign-verify.ts", "tests/corpus/6292-webcrypto-hmac-errors.ts", "tests/corpus/6293-webcrypto-digest.ts", "tests/corpus/6294-webcrypto-js-values.mjs", "tests/corpus/6295-jose-hs256/main.mjs", - "tests/fixtures/node-types/webcrypto-hmac.ts" + "tests/fixtures/node-types/webcrypto-hmac.ts", + "tests/corpus/7081-webcrypto-ed25519.mjs", + "tests/corpus/7085-webcrypto-ecdsa-rsa.ts", + "tests/corpus/7086-webcrypto-ecdsa-rsa-errors.mjs" ] }, "anchorSource": "exact" @@ -110825,8 +111420,29 @@ "inherited": true }, "static": { - "status": "not-implemented", - "evidence": "compiler-unmatched:webcrypto" + "status": "partial", + "evidence": "compiler-feature:webcrypto.subtle.wrapKey", + "tests": [ + "tests/corpus/7130-webcrypto-wrap-key.ts", + "tests/corpus/7131-webcrypto-wrap-key-errors.mjs", + "tests/corpus/7132-jose-pbes2/main.mjs", + "tests/corpus/7128-webcrypto-derive.ts", + "tests/corpus/7129-webcrypto-derive-errors.mjs", + "tests/corpus/7126-webcrypto-aes.ts", + "tests/corpus/7127-webcrypto-aes-errors.mjs", + "tests/corpus/7124-webcrypto-secret-keys.ts", + "tests/corpus/7125-webcrypto-key-errors.mjs", + "tests/fixtures/node-types/webcrypto-keys.ts", + "tests/corpus/6291-webcrypto-hmac-sign-verify.ts", + "tests/corpus/6292-webcrypto-hmac-errors.ts", + "tests/corpus/6293-webcrypto-digest.ts", + "tests/corpus/6294-webcrypto-js-values.mjs", + "tests/corpus/6295-jose-hs256/main.mjs", + "tests/fixtures/node-types/webcrypto-hmac.ts", + "tests/corpus/7081-webcrypto-ed25519.mjs", + "tests/corpus/7085-webcrypto-ecdsa-rsa.ts", + "tests/corpus/7086-webcrypto-ecdsa-rsa-errors.mjs" + ] }, "anchorSource": "exact" }, diff --git a/internal/compatibility/src/generate.mjs b/internal/compatibility/src/generate.mjs index 9bd3927b8..662c0abd6 100644 --- a/internal/compatibility/src/generate.mjs +++ b/internal/compatibility/src/generate.mjs @@ -582,19 +582,29 @@ function publicDetail(tier) { if (/^surface-manifest:node-builtin\.crypto\.create(?:Cipheriv|Decipheriv)$/.test(source)) { return "Supports aes-128/192/256 in cbc, ctr, and gcm modes and chacha20-poly1305 with Node's argument, IV, tag-length, and key-length errors; other OpenSSL ciphers and KeyObject keys are refused."; } + if (/^surface-manifest:node-builtin\.crypto\.createECDH$/.test(source)) { + return "Supports prime192v1, secp224r1, prime256v1, secp384r1, secp521r1, secp192k1, secp224k1, secp256k1, brainpoolP256r1, brainpoolP384r1 and brainpoolP512r1 with Node's curve, key, point, format and encoding errors; other curves Node knows are refused."; + } + if ( + /^surface-manifest:node-builtin\.crypto\.(?:createDiffieHellman|createDiffieHellmanGroup|getDiffieHellman)$/.test( + source, + ) + ) { + return "Supports the modp groups, explicit primes and generators, and generated safe primes up to 8192 bits with Node's argument, generator and modulus errors."; + } if (source.startsWith("surface-manifest:")) return "Implemented for the call shapes accepted by the compiler lowering."; if (/^compiler-dedicated:assert\.doesNot(?:Throw|Reject)$/.test(source)) { return "Supports callbacks or native promises with messages, Error classes, regular expressions, and validators accepting unknown values; object expectations and complete AssertionError metadata remain unsupported."; } - if (/^surface-manifest:node-builtin\.crypto\.createECDH$/.test(source)) { - return "Supports prime192v1, secp224r1, prime256v1, secp384r1, secp521r1, secp192k1, secp224k1, secp256k1, brainpoolP256r1, brainpoolP384r1 and brainpoolP512r1 with Node's curve, key, point, format and encoding errors; other curves Node knows are refused."; - } if (/^compiler-dedicated:(?:ECDH|ecdh\.)/.test(source)) { return "Matches Node's key formats, point encodings, private-key range checks, key-pair checks and errors on the supported curves; ECDH.convertKey is supported, and property reads and writes are refused."; } + if (/^compiler-dedicated:(?:DiffieHellman|diffieHellman\.)/.test(source)) { + return "Matches Node's private key lengths, DH_check results, public key range checks, secret padding and errors; primes longer than 8192 bits, property writes and property reads other than verifyError are refused."; + } if (/^compiler-dedicated:(?:Cipheriv|Decipheriv|cipher\.|decipher\.)/.test(source)) { - return "Matches Node's update() output lengths, padding, authentication tags, string encodings, and state errors for the supported ciphers; the stream.Transform interface is refused."; + return "Matches Node's update() output lengths, padding, authentication tags, string encodings, and state errors for the supported ciphers, and its stream.Transform behavior: chunks written through update(), final() pushed at the end, and its errors reported through 'error'."; } if (source.startsWith("compiler-dedicated:")) return "Implemented by a dedicated static compiler/runtime path."; diff --git a/internal/compatibility/static-support.json b/internal/compatibility/static-support.json index 23c7a159b..06aad26cf 100644 --- a/internal/compatibility/static-support.json +++ b/internal/compatibility/static-support.json @@ -42,8 +42,12 @@ "node-builtin.child_process": ["tests/corpus/1361-spawn-events.ts", "tests/corpus/1565-spawn-pipe-streams.ts", "tests/corpus/2911-execfile-callback.ts", "tests/corpus/2939-child-shell-text.ts", "tests/corpus/2946-child-fork-ipc/main.ts", "tests/corpus/3127-spawn-runtime-options.ts", "tests/corpus/3130-child-generic-streams.ts", "tests/corpus/3131-child-rest-listeners.js", "tests/corpus/3132-child-generic-stream-completion.ts"], "node-builtin.cluster": ["tests/corpus/957-builtins-namespace.ts"], "node-builtin.console": ["tests/corpus/console-imports.cjs", "tests/corpus/2440-console-inspect-args.ts", "tests/corpus/console-native-value.js", "tests/harness/npm-static.test.ts"], - "node-builtin.crypto.createCipheriv": ["tests/corpus/5250-cipher-aes-gcm.ts", "tests/corpus/5251-cipher-aes-cbc.ts", "tests/corpus/5252-cipher-aes-ctr.ts", "tests/corpus/5253-cipher-chacha20-poly1305.ts", "tests/corpus/5254-cipher-errors.js", "tests/corpus/5255-cipher-encodings.cjs", "tests/corpus/5256-cipher-deprecation.cjs", "tests/corpus/5257-cipher-vectors.ts", "tests/corpus/5258-cipher-handles.js", "tests/corpus/5259-cipher-chunked.ts", "tests/fixtures/node-types/cipher.ts"], - "node-builtin.crypto.createDecipheriv": ["tests/corpus/5250-cipher-aes-gcm.ts", "tests/corpus/5251-cipher-aes-cbc.ts", "tests/corpus/5252-cipher-aes-ctr.ts", "tests/corpus/5253-cipher-chacha20-poly1305.ts", "tests/corpus/5254-cipher-errors.js", "tests/corpus/5255-cipher-encodings.cjs", "tests/corpus/5256-cipher-deprecation.cjs", "tests/corpus/5257-cipher-vectors.ts", "tests/corpus/5258-cipher-handles.js", "tests/corpus/5259-cipher-chunked.ts", "tests/fixtures/node-types/cipher.ts"], + "node-builtin.crypto.checkPrime": ["tests/corpus/7152-crypto-prime.ts", "tests/corpus/7153-crypto-prime-errors.cjs"], + "node-builtin.crypto.checkPrimeSync": ["tests/corpus/7152-crypto-prime.ts", "tests/corpus/7153-crypto-prime-errors.cjs"], + "node-builtin.crypto.createCipheriv": ["tests/corpus/7150-cipher-legacy-modes.ts", "tests/corpus/7151-cipher-legacy-errors.cjs", "tests/corpus/5250-cipher-aes-gcm.ts", "tests/corpus/5251-cipher-aes-cbc.ts", "tests/corpus/5252-cipher-aes-ctr.ts", "tests/corpus/5253-cipher-chacha20-poly1305.ts", "tests/corpus/5254-cipher-errors.js", "tests/corpus/5255-cipher-encodings.cjs", "tests/corpus/5256-cipher-deprecation.cjs", "tests/corpus/5257-cipher-vectors.ts", "tests/corpus/5258-cipher-handles.js", "tests/corpus/5259-cipher-chunked.ts", "tests/corpus/7055-cipher-streams.ts", "tests/corpus/7056-cipher-stream-errors.ts", "tests/corpus/7057-cipher-streams.mjs", "tests/fixtures/node-types/cipher.ts"], + "node-builtin.crypto.createDecipheriv": ["tests/corpus/7150-cipher-legacy-modes.ts", "tests/corpus/7151-cipher-legacy-errors.cjs", "tests/corpus/5250-cipher-aes-gcm.ts", "tests/corpus/5251-cipher-aes-cbc.ts", "tests/corpus/5252-cipher-aes-ctr.ts", "tests/corpus/5253-cipher-chacha20-poly1305.ts", "tests/corpus/5254-cipher-errors.js", "tests/corpus/5255-cipher-encodings.cjs", "tests/corpus/5256-cipher-deprecation.cjs", "tests/corpus/5257-cipher-vectors.ts", "tests/corpus/5258-cipher-handles.js", "tests/corpus/5259-cipher-chunked.ts", "tests/corpus/7055-cipher-streams.ts", "tests/corpus/7056-cipher-stream-errors.ts", "tests/corpus/7057-cipher-streams.mjs", "tests/fixtures/node-types/cipher.ts"], + "node-builtin.crypto.createDiffieHellman": ["tests/corpus/6706-dh-groups.ts", "tests/corpus/6707-dh-explicit-params.ts", "tests/corpus/6708-dh-errors.js", "tests/corpus/6709-dh-generate.ts", "tests/corpus/6710-dh-encodings.cjs", "tests/corpus/6711-dh-handles.ts", "tests/fixtures/node-types/dh.ts"], + "node-builtin.crypto.createDiffieHellmanGroup": ["tests/corpus/6706-dh-groups.ts", "tests/corpus/6707-dh-explicit-params.ts", "tests/corpus/6708-dh-errors.js", "tests/corpus/6709-dh-generate.ts", "tests/corpus/6710-dh-encodings.cjs", "tests/corpus/6711-dh-handles.ts", "tests/fixtures/node-types/dh.ts"], "node-builtin.crypto.createECDH": ["tests/corpus/6700-ecdh-shared-secret.ts", "tests/corpus/6701-ecdh-formats.ts", "tests/corpus/6702-ecdh-errors.js", "tests/corpus/6703-ecdh-private-keys.ts", "tests/corpus/6704-ecdh-set-public-key.cjs", "tests/corpus/6705-ecdh-handles.ts", "tests/fixtures/node-types/ecdh.ts"], "node-builtin.crypto": ["tests/corpus/1358-crypto-random.ts", "tests/corpus/1534-crypto-hash-chain.ts", "tests/corpus/2556-crypto-introspection.ts", "tests/corpus/2890-crypto-static-utility.ts", "tests/harness/npm-static.test.ts", "tests/corpus/node24-crypto-sha2.ts", "tests/corpus/node24-crypto-kdf.ts", "tests/corpus/node24-crypto-kdf-errors.ts", "tests/corpus/node24-crypto-kdf-options.ts"], "node-builtin.dgram": ["tests/corpus/2597-dgram-send-ladders.cjs"], @@ -118,6 +122,9 @@ "node-builtin.os.version": ["tests/corpus/5140-os-host-facts.ts"], "node-builtin.os.constants": ["tests/corpus/5141-os-constants.ts"], "node-builtin.fs.constants": ["tests/corpus/6207-fs-constants-object.ts", "tests/corpus/6208-fs-constants-require.cjs"], + "node-builtin.crypto.generatePrime": ["tests/corpus/7152-crypto-prime.ts", "tests/corpus/7153-crypto-prime-errors.cjs"], + "node-builtin.crypto.generatePrimeSync": ["tests/corpus/7152-crypto-prime.ts", "tests/corpus/7153-crypto-prime-errors.cjs"], + "node-builtin.crypto.getDiffieHellman": ["tests/corpus/6706-dh-groups.ts", "tests/corpus/6707-dh-explicit-params.ts", "tests/corpus/6708-dh-errors.js", "tests/corpus/6709-dh-generate.ts", "tests/corpus/6710-dh-encodings.cjs", "tests/corpus/6711-dh-handles.ts", "tests/fixtures/node-types/dh.ts"], "node-builtin.crypto.getRandomValues": ["tests/corpus/6204-crypto-get-random-values.ts", "tests/corpus/6205-crypto-get-random-values.js"], "node-builtin.url.parse": ["tests/corpus/5220-url-parse-warnings.ts", "tests/corpus/5221-url-parse-shapes.ts", "tests/corpus/5222-url-parse-hosts.ts", "tests/corpus/5223-url-parse-query.ts", "tests/corpus/5227-url-legacy-dependency/main.ts", "tests/corpus/5229-url-legacy-errors.cjs", "packages/runtime/test/url-legacy.test.ts", "tests/fixtures/node-types/url-legacy.ts"], "node-builtin.url.format": ["tests/corpus/5224-url-format-objects.ts", "tests/corpus/5225-url-format-whatwg.ts", "tests/corpus/5227-url-legacy-dependency/main.ts", "tests/corpus/5229-url-legacy-errors.cjs", "packages/runtime/test/url-legacy.test.ts", "tests/fixtures/node-types/url-legacy.ts"], @@ -187,16 +194,18 @@ "stdlib.set": ["tests/corpus/typed-collection-iterators.ts", "tests/corpus/typed-collection-iterator-references.ts", "tests/corpus/checked-collection-iterators.ts"], "stdlib.headers": ["tests/harness/fetch-conformance.test.ts"], "stdlib.request": ["tests/harness/fetch-conformance.test.ts"], - "stdlib.webcrypto.subtle": ["tests/corpus/6291-webcrypto-hmac-sign-verify.ts", "tests/corpus/6292-webcrypto-hmac-errors.ts", "tests/corpus/6293-webcrypto-digest.ts", "tests/corpus/6294-webcrypto-js-values.mjs", "tests/corpus/6295-jose-hs256/main.mjs"], - "stdlib.webcrypto.CryptoKey": ["tests/corpus/6291-webcrypto-hmac-sign-verify.ts", "tests/corpus/6294-webcrypto-js-values.mjs", "tests/corpus/6295-jose-hs256/main.mjs"], + "stdlib.webcrypto.subtle": ["tests/corpus/7130-webcrypto-wrap-key.ts", "tests/corpus/7131-webcrypto-wrap-key-errors.mjs", "tests/corpus/7132-jose-pbes2/main.mjs", "tests/corpus/7128-webcrypto-derive.ts", "tests/corpus/7129-webcrypto-derive-errors.mjs", "tests/corpus/7126-webcrypto-aes.ts", "tests/corpus/7127-webcrypto-aes-errors.mjs", "tests/corpus/7124-webcrypto-secret-keys.ts", "tests/corpus/7125-webcrypto-key-errors.mjs", "tests/corpus/6291-webcrypto-hmac-sign-verify.ts", "tests/corpus/6292-webcrypto-hmac-errors.ts", "tests/corpus/6293-webcrypto-digest.ts", "tests/corpus/6294-webcrypto-js-values.mjs", "tests/corpus/6295-jose-hs256/main.mjs"], + "stdlib.webcrypto.CryptoKey": ["tests/corpus/7124-webcrypto-secret-keys.ts", "tests/corpus/6291-webcrypto-hmac-sign-verify.ts", "tests/corpus/6294-webcrypto-js-values.mjs", "tests/corpus/6295-jose-hs256/main.mjs"], "stdlib.response": ["tests/harness/fetch-conformance.test.ts"], "stdlib.readable-stream": ["tests/harness/fetch-conformance.test.ts"], "stdlib.abort": ["tests/harness/fetch-conformance.test.ts"] }, "features": [ - { "chapter": "webcrypto", "symbols": ["subtle.importKey", "subtle.sign", "subtle.verify", "subtle.digest"], "status": "partial", "evidence": ["tests/corpus/6291-webcrypto-hmac-sign-verify.ts", "tests/corpus/6292-webcrypto-hmac-errors.ts", "tests/corpus/6293-webcrypto-digest.ts", "tests/corpus/6294-webcrypto-js-values.mjs", "tests/corpus/6295-jose-hs256/main.mjs", "tests/fixtures/node-types/webcrypto-hmac.ts"] }, + { "chapter": "webcrypto", "symbols": ["subtle.importKey", "subtle.generateKey", "subtle.exportKey", "subtle.encrypt", "subtle.decrypt", "subtle.wrapKey", "subtle.unwrapKey", "subtle.deriveBits", "subtle.deriveKey", "subtle.sign", "subtle.verify", "subtle.digest"], "status": "partial", "evidence": ["tests/corpus/7130-webcrypto-wrap-key.ts", "tests/corpus/7131-webcrypto-wrap-key-errors.mjs", "tests/corpus/7132-jose-pbes2/main.mjs", "tests/corpus/7128-webcrypto-derive.ts", "tests/corpus/7129-webcrypto-derive-errors.mjs", "tests/corpus/7126-webcrypto-aes.ts", "tests/corpus/7127-webcrypto-aes-errors.mjs", "tests/corpus/7124-webcrypto-secret-keys.ts", "tests/corpus/7125-webcrypto-key-errors.mjs", "tests/fixtures/node-types/webcrypto-keys.ts", "tests/corpus/6291-webcrypto-hmac-sign-verify.ts", "tests/corpus/6292-webcrypto-hmac-errors.ts", "tests/corpus/6293-webcrypto-digest.ts", "tests/corpus/6294-webcrypto-js-values.mjs", "tests/corpus/6295-jose-hs256/main.mjs", "tests/fixtures/node-types/webcrypto-hmac.ts", "tests/corpus/7081-webcrypto-ed25519.mjs", "tests/corpus/7085-webcrypto-ecdsa-rsa.ts", "tests/corpus/7086-webcrypto-ecdsa-rsa-errors.mjs"] }, { "chapter": "webcrypto", "signatures": ["Class: `SubtleCrypto`", "`subtle` Type: {SubtleCrypto}"], "status": "partial", "evidence": ["tests/corpus/6291-webcrypto-hmac-sign-verify.ts", "tests/corpus/6292-webcrypto-hmac-errors.ts", "tests/corpus/6293-webcrypto-digest.ts", "tests/corpus/6294-webcrypto-js-values.mjs", "tests/corpus/6295-jose-hs256/main.mjs"] }, - { "chapter": "webcrypto", "signatures": ["Class: `CryptoKey`", "`cryptoKey.algorithm`", "`extractable` Type: {boolean}", "`type` Type: {string} One of `'secret'`, `'private'`, or `'public'`.", "`usages` Type: {string\\[]}"], "status": "partial", "evidence": ["tests/corpus/6291-webcrypto-hmac-sign-verify.ts", "tests/corpus/6294-webcrypto-js-values.mjs", "tests/corpus/6295-jose-hs256/main.mjs"] }, + { "chapter": "webcrypto", "signatures": ["Class: `CryptoKey`", "`cryptoKey.algorithm`", "`extractable` Type: {boolean}", "`type` Type: {string} One of `'secret'`, `'private'`, or `'public'`.", "`usages` Type: {string\\[]}"], "status": "partial", "evidence": ["tests/corpus/7124-webcrypto-secret-keys.ts", "tests/corpus/6291-webcrypto-hmac-sign-verify.ts", "tests/corpus/6294-webcrypto-js-values.mjs", "tests/corpus/6295-jose-hs256/main.mjs"] }, + { "chapter": "webcrypto", "signatures": ["Class: `Crypto`"], "status": "partial", "evidence": ["tests/corpus/7120-webcrypto-random-uuid.ts", "tests/corpus/7121-webcrypto-crypto-object.mjs", "tests/corpus/6293-webcrypto-digest.ts"] }, + { "chapter": "webcrypto", "symbols": ["crypto.randomUUID", "crypto.getRandomValues"], "status": "supported", "evidence": ["tests/corpus/7120-webcrypto-random-uuid.ts", "tests/corpus/7121-webcrypto-crypto-object.mjs", "tests/corpus/6204-crypto-get-random-values.ts", "tests/corpus/6205-crypto-get-random-values.js"] }, { "chapter": "globals", "signatures": ["`navigator`"], "status": "partial", "evidence": ["tests/fixtures/node-types/navigator.ts", "tests/harness/project-config.test.ts", "tests/corpus/6331-jose-root-entry/main.ts"] }, { "chapter": "globals", "signatures": ["`userAgent` Type: {string}"], "status": "supported", "evidence": ["tests/fixtures/node-types/navigator.ts", "tests/harness/project-config.test.ts"] }, { "chapter": "globals", "signatures": ["Class: `CryptoKey`", "Class: `SubtleCrypto`"], "status": "partial", "evidence": ["tests/corpus/6291-webcrypto-hmac-sign-verify.ts", "tests/corpus/6292-webcrypto-hmac-errors.ts", "tests/corpus/6293-webcrypto-digest.ts", "tests/corpus/6294-webcrypto-js-values.mjs", "tests/corpus/6295-jose-hs256/main.mjs"] }, @@ -367,6 +376,7 @@ { "chapter": "console", "signatures": ["Class: `Console`"], "status": "partial", "evidence": ["tests/corpus/4900-console-instances.ts", "tests/corpus/4901-console-instance-errors.ts"] }, { "chapter": "tls", "signatures": ["`alpnProtocol` Type: {string|boolean|null}"], "status": "partial", "evidence": ["tests/corpus/6721-tls-alpn-protocols.ts"] }, { "chapter": "tls", "signatures": ["`tlsSocket.getProtocol()`"], "status": "partial", "evidence": ["tests/corpus/6722-tls-min-max-version.ts"] }, + { "chapter": "tls", "signatures": ["Class: `tls.TLSSocket`", "Event: `'secure'`"], "status": "partial", "evidence": ["tests/corpus/7087-tls-socket-wrap.ts", "tests/corpus/7088-tls-socket-connect-tunnel.ts", "tests/fixtures/node-types/tls-socket-wrap.ts"] }, { "chapter": "webstreams", "signatures": ["`readableStream.values([options])`"], "status": "partial", "evidence": ["tests/corpus/2862-web-readable-async-iteration.ts"] }, { "chapter": "webstreams", "signatures": ["`streamConsumers.text(stream)`", "`streamConsumers.json(stream)`", "`streamConsumers.buffer(stream)`"], "status": "partial", "evidence": ["tests/corpus/2629-stream-consumers.ts", "tests/corpus/2630-stream-consumers-errors.ts"] }, { "chapter": "webstreams", "signatures": ["`streamConsumers.arrayBuffer(stream)`"], "status": "partial", "evidence": ["tests/corpus/4875-stream-consumers-array-buffer.ts"] }, @@ -412,12 +422,16 @@ { "symbols": ["assert.partialDeepStrictEqual"], "status": "partial", "evidence": ["tests/corpus/5517-assert-partial-deep-equal.js", "tests/corpus/5518-assert-partial-deep-typed.ts", "tests/corpus/5519-assert-partial-deep-typed-edges.ts"] }, { "symbols": ["assert.deepEqual", "assert.notDeepEqual"], "status": "partial", "evidence": ["tests/corpus/5513-assert-deep-equal-loose.js", "tests/corpus/5514-assert-deep-equal-typed.ts", "tests/corpus/5516-assert-deep-equal-edges.js"] }, { "symbols": ["assert", "assert.ok", "assert.equal", "assert.notEqual", "assert.strictEqual", "assert.notStrictEqual", "assert.deepStrictEqual", "assert.notDeepStrictEqual", "assert.fail", "assert.match", "assert.doesNotMatch", "assert.throws", "assert.rejects", "assert.ifError"], "status": "partial", "evidence": ["tests/corpus/1600-assert-passing.ts", "tests/corpus/1604-assert-deep-structures.ts", "tests/corpus/1609-assert-async.ts", "tests/corpus/1721-assert-throws-regex-class.ts", "tests/corpus/2936-static-loose-equality.ts", "tests/corpus/5515-assert-deep-strict-typed-messages.ts"] }, - { "chapter": "crypto", "symbols": ["Cipheriv", "cipher.update", "cipher.final", "cipher.setAAD", "cipher.getAuthTag", "cipher.setAutoPadding", "Decipheriv", "decipher.update", "decipher.final", "decipher.setAAD", "decipher.setAuthTag", "decipher.setAutoPadding"], "status": "partial", "evidence": ["tests/corpus/5250-cipher-aes-gcm.ts", "tests/corpus/5251-cipher-aes-cbc.ts", "tests/corpus/5252-cipher-aes-ctr.ts", "tests/corpus/5253-cipher-chacha20-poly1305.ts", "tests/corpus/5254-cipher-errors.js", "tests/corpus/5255-cipher-encodings.cjs", "tests/corpus/5256-cipher-deprecation.cjs", "tests/corpus/5257-cipher-vectors.ts", "tests/corpus/5258-cipher-handles.js", "tests/corpus/5259-cipher-chunked.ts", "tests/fixtures/node-types/cipher.ts"] }, + { "chapter": "crypto", "symbols": ["Cipheriv", "cipher.update", "cipher.final", "cipher.setAAD", "cipher.getAuthTag", "cipher.setAutoPadding", "Decipheriv", "decipher.update", "decipher.final", "decipher.setAAD", "decipher.setAuthTag", "decipher.setAutoPadding"], "status": "partial", "evidence": ["tests/corpus/5250-cipher-aes-gcm.ts", "tests/corpus/5251-cipher-aes-cbc.ts", "tests/corpus/5252-cipher-aes-ctr.ts", "tests/corpus/5253-cipher-chacha20-poly1305.ts", "tests/corpus/5254-cipher-errors.js", "tests/corpus/5255-cipher-encodings.cjs", "tests/corpus/5256-cipher-deprecation.cjs", "tests/corpus/5257-cipher-vectors.ts", "tests/corpus/5258-cipher-handles.js", "tests/corpus/5259-cipher-chunked.ts", "tests/corpus/7055-cipher-streams.ts", "tests/corpus/7056-cipher-stream-errors.ts", "tests/corpus/7057-cipher-streams.mjs", "tests/fixtures/node-types/cipher.ts"] }, + { "chapter": "crypto", "symbols": ["crypto.webcrypto", "subtle"], "status": "partial", "evidence": ["tests/corpus/7122-webcrypto-node-crypto.ts", "tests/corpus/7123-webcrypto-node-crypto.cjs"] }, { "chapter": "crypto", "symbols": ["ECDH", "ecdh.computeSecret", "ecdh.generateKeys", "ecdh.getPrivateKey", "ecdh.getPublicKey", "ecdh.setPrivateKey", "ecdh.setPublicKey"], "status": "partial", "evidence": ["tests/corpus/6700-ecdh-shared-secret.ts", "tests/corpus/6701-ecdh-formats.ts", "tests/corpus/6702-ecdh-errors.js", "tests/corpus/6703-ecdh-private-keys.ts", "tests/corpus/6704-ecdh-set-public-key.cjs", "tests/corpus/6705-ecdh-handles.ts", "tests/fixtures/node-types/ecdh.ts"] }, + { "chapter": "crypto", "symbols": ["DiffieHellman", "DiffieHellmanGroup", "diffieHellman.computeSecret", "diffieHellman.generateKeys", "diffieHellman.getGenerator", "diffieHellman.getPrime", "diffieHellman.getPrivateKey", "diffieHellman.getPublicKey", "diffieHellman.setPrivateKey", "diffieHellman.setPublicKey", "diffieHellman.verifyError"], "status": "partial", "evidence": ["tests/corpus/6706-dh-groups.ts", "tests/corpus/6707-dh-explicit-params.ts", "tests/corpus/6708-dh-errors.js", "tests/corpus/6709-dh-generate.ts", "tests/corpus/6710-dh-encodings.cjs", "tests/corpus/6711-dh-handles.ts", "tests/fixtures/node-types/dh.ts"] }, + { "chapter": "errors", "symbols": ["ERR_CRYPTO_UNKNOWN_DH_GROUP", "ERR_CRYPTO_INVALID_KEYLEN", "ERR_CRYPTO_INVALID_STATE"], "status": "partial", "evidence": ["tests/corpus/6708-dh-errors.js"] }, { "chapter": "errors", "symbols": ["ERR_CRYPTO_ECDH_INVALID_FORMAT", "ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY"], "status": "partial", "evidence": ["tests/corpus/6702-ecdh-errors.js"] }, { "symbols": ["crypto.createHash", "Hash", "hash.update", "hash.digest", "hash.copy", "crypto.createHmac", "Hmac", "hmac.update", "hmac.digest", "crypto.hash", "crypto.pbkdf2", "crypto.pbkdf2Sync"], "status": "partial", "evidence": ["tests/corpus/5760-crypto-hash-stream.ts", "tests/corpus/5768-crypto-hash-unknown.ts", "tests/corpus/5769-crypto-hash-unknown.cjs", "tests/corpus/5761-crypto-hash-stream-states.ts", "tests/corpus/5762-crypto-hash-stream.cjs", "tests/corpus/2890-crypto-static-utility.ts", "tests/corpus/node24-crypto-sha2.ts", "tests/corpus/5435-crypto-hash-algorithms.ts", "tests/corpus/5436-crypto-hash-names.js", "tests/corpus/5437-crypto-hmac-algorithms.ts", "tests/corpus/5438-crypto-kdf-digests.ts", "tests/corpus/5440-crypto-hash-encodings.js", "tests/corpus/5441-crypto-hash-output-length.ts", "tests/harness/npm-static.test.ts"] }, { "symbols": ["crypto.randomFill", "crypto.randomFillSync", "crypto.randomUUID", "crypto.randomUUIDv7"], "status": "supported", "evidence": ["tests/corpus/5442-crypto-random-values.ts", "tests/corpus/5443-crypto-random-arguments.js", "tests/corpus/1358-crypto-random.ts"] }, { "symbols": ["crypto.createSecretKey", "crypto.generateKey", "crypto.generateKeySync", "KeyObject", "keyObject.export", "keyObject.equals", "keyObject.symmetricKeySize", "keyObject.type"], "status": "partial", "evidence": ["tests/corpus/5445-crypto-secret-key-objects.ts", "tests/corpus/5446-crypto-secret-key-errors.js"] }, + { "symbols": ["crypto.createPrivateKey", "crypto.createPublicKey", "crypto.generateKeyPair", "crypto.generateKeyPairSync", "crypto.sign", "crypto.verify", "crypto.createSign", "crypto.createVerify", "Sign", "sign.update", "sign.sign", "Verify", "verify.update", "verify.verify", "asymmetricKeyType", "asymmetricKeyDetails"], "status": "partial", "evidence": ["tests/corpus/7080-crypto-ed25519.mjs", "tests/corpus/7082-crypto-key-objects.ts", "tests/corpus/7083-crypto-sign-verify.ts", "tests/corpus/7084-crypto-key-pairs.cjs", "tests/fixtures/node-types/keys.ts"] }, { "symbols": ["crypto.getRandomValues"], "status": "supported", "evidence": ["tests/corpus/6204-crypto-get-random-values.ts", "tests/corpus/6205-crypto-get-random-values.js"] }, { "symbols": ["crypto.timingSafeEqual"], "status": "supported", "evidence": ["tests/corpus/5444-crypto-timing-safe-equal.js", "tests/corpus/2890-crypto-static-utility.ts"] }, { "symbols": ["crypto.randomInt"], "status": "partial", "evidence": ["tests/corpus/5442-crypto-random-values.ts", "tests/corpus/2890-crypto-static-utility.ts"] }, diff --git a/package.json b/package.json index 5cc30d9f8..a3cc42fc7 100644 --- a/package.json +++ b/package.json @@ -20,7 +20,7 @@ "test:test262": "tsx tests/test262/run.ts", "test:test262:fetch": "node tests/test262/fetch.mjs", "test:cache-identity": "node tests/harness/cache-identity.mjs", - "test:lowering-order": "node scripts/lowering-order.mjs --fail-on content", + "test:lowering-order": "node scripts/lowering-order.mjs --fail-on names", "test:sandbox": "node scripts/sandbox-test.mjs", "test:sandbox:image": "node scripts/sandbox-image.mjs", "test:watch": "vitest", @@ -40,10 +40,11 @@ "@scriptc/types": "workspace:*", "@types/node": "^24.0.0", "effect": "3.22.2", - "js-yaml": "4.3.0", + "js-yaml": "4.3.2", "oxfmt": "0.71.0", "oxlint": "1.86.0", "rollup": "4.62.2", + "smol-toml": "1.7.1", "three": "0.186.1", "tsx": "^4.19.0", "typescript": "5.9.3", diff --git a/packages/cli-darwin-arm64/package.json b/packages/cli-darwin-arm64/package.json index 482e5f1e5..23584b60a 100644 --- a/packages/cli-darwin-arm64/package.json +++ b/packages/cli-darwin-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@scriptc/cli-darwin-arm64", - "version": "0.4.1", + "version": "0.4.2", "description": "Native scriptc compiler for darwin-arm64", "license": "Apache-2.0", "homepage": "https://scriptc.dev", diff --git a/packages/cli-darwin-x64/package.json b/packages/cli-darwin-x64/package.json index b1ced2c03..d9e6dafc6 100644 --- a/packages/cli-darwin-x64/package.json +++ b/packages/cli-darwin-x64/package.json @@ -1,6 +1,6 @@ { "name": "@scriptc/cli-darwin-x64", - "version": "0.4.1", + "version": "0.4.2", "description": "Native scriptc compiler for darwin-x64", "license": "Apache-2.0", "homepage": "https://scriptc.dev", diff --git a/packages/cli-linux-arm64-gnu/package.json b/packages/cli-linux-arm64-gnu/package.json index 0aa213279..5b8cb4db2 100644 --- a/packages/cli-linux-arm64-gnu/package.json +++ b/packages/cli-linux-arm64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@scriptc/cli-linux-arm64-gnu", - "version": "0.4.1", + "version": "0.4.2", "description": "Native scriptc compiler for linux-arm64-gnu", "license": "Apache-2.0", "homepage": "https://scriptc.dev", diff --git a/packages/cli-linux-arm64-musl/package.json b/packages/cli-linux-arm64-musl/package.json index 4ac5434ae..0901602ec 100644 --- a/packages/cli-linux-arm64-musl/package.json +++ b/packages/cli-linux-arm64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@scriptc/cli-linux-arm64-musl", - "version": "0.4.1", + "version": "0.4.2", "description": "Native scriptc compiler for linux-arm64-musl", "license": "Apache-2.0", "homepage": "https://scriptc.dev", diff --git a/packages/cli-linux-x64-gnu/package.json b/packages/cli-linux-x64-gnu/package.json index 7473c36bc..f01478aad 100644 --- a/packages/cli-linux-x64-gnu/package.json +++ b/packages/cli-linux-x64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@scriptc/cli-linux-x64-gnu", - "version": "0.4.1", + "version": "0.4.2", "description": "Native scriptc compiler for linux-x64-gnu", "license": "Apache-2.0", "homepage": "https://scriptc.dev", diff --git a/packages/cli-linux-x64-musl/package.json b/packages/cli-linux-x64-musl/package.json index 08e048cd1..a6986a66a 100644 --- a/packages/cli-linux-x64-musl/package.json +++ b/packages/cli-linux-x64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@scriptc/cli-linux-x64-musl", - "version": "0.4.1", + "version": "0.4.2", "description": "Native scriptc compiler for linux-x64-musl", "license": "Apache-2.0", "homepage": "https://scriptc.dev", diff --git a/packages/cli-win32-x64-msvc/package.json b/packages/cli-win32-x64-msvc/package.json index 54e323839..6b03811b8 100644 --- a/packages/cli-win32-x64-msvc/package.json +++ b/packages/cli-win32-x64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@scriptc/cli-win32-x64-msvc", - "version": "0.4.1", + "version": "0.4.2", "description": "Native scriptc compiler for win32-x64-msvc", "license": "Apache-2.0", "homepage": "https://scriptc.dev", diff --git a/packages/cli/package.json b/packages/cli/package.json index d66ba3247..034747c29 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "scriptc", - "version": "0.4.1", + "version": "0.4.2", "description": "Compile ordinary TypeScript and JavaScript to small, fast native executables and WebAssembly modules that run without Node.js", "license": "Apache-2.0", "homepage": "https://scriptc.dev", diff --git a/packages/cli/test/executable-cache.test.ts b/packages/cli/test/executable-cache.test.ts index a0131f14f..ee8027765 100644 --- a/packages/cli/test/executable-cache.test.ts +++ b/packages/cli/test/executable-cache.test.ts @@ -1,12 +1,13 @@ import { execFile } from "node:child_process"; import { createRequire } from "node:module"; -import { chmod, mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { chmod, mkdir, mkdtemp, readdir, readFile, rm, stat, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { delimiter, dirname, join } from "node:path"; import { promisify } from "node:util"; import { expect, test } from "vitest"; import { precompiledRuntimePackTarget } from "../../compiler/src/startup-cache.js"; import { platformLinkerSupportsPersistentCache } from "../../compiler/src/backend/linker.js"; +import { toolchainEnvironmentCachePolicy } from "../../compiler/src/backend/toolchain-environment.js"; const execFileAsync = promisify(execFile); const require = createRequire(import.meta.url); @@ -102,6 +103,59 @@ test("exact executable repeats skip lowering while edits and damaged outputs sta } }, 120_000); +// Sanitize builds compile the LLVM text with the C driver rather than linking a precompiled +// runtime pack, and that route's native cache proof records the output directory. +test.skipIf(process.platform === "win32")( + "sanitize builds compile uncached and keep the executable on unchanged repeats", + async () => { + const dir = await mkdtemp(join(tmpdir(), "scriptc-cli-executable-sanitize-")); + const cacheRoot = join(dir, "cache"); + const entry = join(dir, "main.ts"); + const outPath = join(dir, "program"); + const build = async (env: NodeJS.ProcessEnv = {}): Promise<{ stderr: string }> => { + const { stderr } = await execFileAsync( + process.execPath, + ["--import", tsxLoader, cliEntry, "build", entry, "--sanitize", "-o", outPath], + { + env: { ...process.env, SCRIPTC_CACHE_DIR: cacheRoot, SCRIPTC_TIMING: "1", ...env }, + maxBuffer: 4 * 1024 * 1024, + }, + ); + return { stderr }; + }; + const run = async (): Promise => + (await execFileAsync(outPath, [], { maxBuffer: 1024 * 1024 })).stdout; + try { + await mkdir(cacheRoot, { mode: 0o700 }); + await writeFile(entry, 'console.log("sanitized");\n'); + + // With the native cache off, clang compiles the build's private copy of the LLVM text. + await build({ SCRIPTC_NO_CACHE: "1" }); + expect(await run()).toBe("sanitized\n"); + + expect((await build()).stderr).toContain("scriptc lowering"); + expect(await run()).toBe("sanitized\n"); + const built = await stat(outPath); + const tuTime = (await stat(join(dir, "main.ll"))).mtimeMs; + + // The output directory does not change after the native cache proof is recorded, so an + // unchanged repeat keeps the executable instead of linking it again. + expect((await build()).stderr).not.toContain("scriptc lowering"); + if (toolchainEnvironmentCachePolicy(process.env).completeArtifacts) { + const repeated = await stat(outPath); + expect(repeated.ino).toBe(built.ino); + expect(repeated.mtimeMs).toBe(built.mtimeMs); + } + expect(await run()).toBe("sanitized\n"); + expect((await stat(join(dir, "main.ll"))).mtimeMs).toBe(tuTime); + expect((await readdir(dir)).sort()).toEqual(["cache", "main.ll", "main.ts", "program"]); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }, + 240_000, +); + test.skipIf(process.platform === "win32")( "an executable appearing earlier on unchanged PATH invalidates the early binary", async () => { diff --git a/packages/cli/test/native-link-info.test.ts b/packages/cli/test/native-link-info.test.ts index f5ff2642e..bf5b3be14 100644 --- a/packages/cli/test/native-link-info.test.ts +++ b/packages/cli/test/native-link-info.test.ts @@ -72,7 +72,7 @@ describe.runIf(supported)("macOS arm64 native link info", () => { minimum_os: "14.0", }, program: { object, entry_symbol: "main" }, - runtime_abi: { version: 24, marker: "scr_runtime_abi_v24" }, + runtime_abi: { version: 33, marker: "scr_runtime_abi_v33" }, runtime_pack: { kind: "precompiled", package: "@scriptc/runtime-darwin-arm64", @@ -165,6 +165,6 @@ describe.runIf(supported)("macOS arm64 native link info", () => { () => null, (failure: { stderr?: string }) => failure, ); - expect(error?.stderr).toContain("scr_runtime_abi_v24"); + expect(error?.stderr).toContain("scr_runtime_abi_v33"); }); }); diff --git a/packages/compiler/ambient/scriptc-node-fallback.d.ts b/packages/compiler/ambient/scriptc-node-fallback.d.ts index dbb3cd8fd..b195c3fbb 100644 --- a/packages/compiler/ambient/scriptc-node-fallback.d.ts +++ b/packages/compiler/ambient/scriptc-node-fallback.d.ts @@ -544,12 +544,17 @@ declare var DOMException: { readonly prototype: DOMException; }; -/* WebCrypto's HMAC slice (scr_webcrypto.c): crypto.subtle's importKey for - * raw HMAC keys, HMAC sign/verify and the SHA-1/SHA-2 digests, typed as - * exactly that surface (the declarations mirror @types/node's webcrypto - * shapes). Every other SubtleCrypto method and crypto member is absent, - * so a use is an honest type error. CryptoKey values are native handles - * whose four members read through the handle. */ +/* WebCrypto (scr_webcrypto.c): crypto.subtle's importKey, generateKey and + * exportKey for HMAC and AES keys (importKey also for PBKDF2 and HKDF + * keys), AES-GCM/CBC/CTR encrypt and decrypt, wrapKey and unwrapKey of + * secret keys (AES-KW or those ciphers), PBKDF2 and HKDF deriveBits and + * deriveKey, HMAC sign/verify, generateKey, importKey, exportKey, sign + * and verify for ECDSA, Ed25519, RSASSA-PKCS1-v1_5 and RSA-PSS, and the + * SHA-1/SHA-2 digests, typed as exactly that surface (the declarations + * mirror @types/node's webcrypto shapes), plus the global's randomUUID and + * getRandomValues. Every other SubtleCrypto method and crypto member is + * absent, so a use is an honest type error. CryptoKey values are native + * handles whose four members read through the handle. */ declare var crypto: Crypto; /* The Crypto and SubtleCrypto constructors (feature probes only) stay * `unknown`; the values keep this declaration order. */ @@ -582,9 +587,44 @@ interface HmacImportParams extends Algorithm { hash: HashAlgorithmIdentifier; length?: number; } +interface HmacKeyGenParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; +} +interface AesKeyGenParams extends Algorithm { + length: number; +} +interface AesGcmParams extends Algorithm { + additionalData?: BufferSource; + iv: BufferSource; + tagLength?: number; +} +interface AesCbcParams extends Algorithm { + iv: BufferSource; +} +interface AesCtrParams extends Algorithm { + counter: BufferSource; + length: number; +} +interface Pbkdf2Params extends Algorithm { + hash: HashAlgorithmIdentifier; + iterations: number; + salt: BufferSource; +} +interface HkdfParams extends Algorithm { + hash: HashAlgorithmIdentifier; + info: BufferSource; + salt: BufferSource; +} +interface AesDerivedKeyParams extends Algorithm { + length: number; +} interface KeyAlgorithm { name: string; } +interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; +} interface HmacKeyAlgorithm extends KeyAlgorithm { hash: KeyAlgorithm; length: number; @@ -623,34 +663,136 @@ interface JsonWebKey { x?: string; y?: string; } -/* The 'jwk' form type-checks like @types/node's; the compiler refuses it - * (the JsonWebKey import is not implemented). */ +interface EcKeyGenParams extends Algorithm { + namedCurve: string; +} +interface EcKeyImportParams extends Algorithm { + namedCurve: string; +} +interface EcdsaParams extends Algorithm { + hash: HashAlgorithmIdentifier; +} +interface RsaHashedKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: Uint8Array; + hash: HashAlgorithmIdentifier; +} +interface RsaHashedImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; +} +interface RsaPssParams extends Algorithm { + saltLength: number; +} +interface EcKeyAlgorithm extends KeyAlgorithm { + namedCurve: string; +} +interface RsaHashedKeyAlgorithm extends KeyAlgorithm { + modulusLength: number; + publicExponent: Uint8Array; + hash: KeyAlgorithm; +} +interface CryptoKeyPair { + privateKey: CryptoKey; + publicKey: CryptoKey; +} +/* HMAC and AES keys generate, import and export as 'raw' and 'jwk' + * (PBKDF2 and HKDF keys import as 'raw'); ECDSA and RSA keys generate, + * import and export as 'spki', 'pkcs8' and 'jwk', and ECDSA public keys as + * 'raw'. */ interface SubtleCrypto { + decrypt( + algorithm: AesGcmParams | AesCbcParams | AesCtrParams, + key: CryptoKey, + data: BufferSource, + ): Promise; + deriveBits( + algorithm: Pbkdf2Params | HkdfParams, + baseKey: CryptoKey, + length?: number | null, + ): Promise; + deriveKey( + algorithm: Pbkdf2Params | HkdfParams, + baseKey: CryptoKey, + derivedKeyType: AlgorithmIdentifier | AesDerivedKeyParams | HmacImportParams, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; digest(algorithm: AlgorithmIdentifier, data: BufferSource): Promise; + encrypt( + algorithm: AesGcmParams | AesCbcParams | AesCtrParams, + key: CryptoKey, + data: BufferSource, + ): Promise; + exportKey(format: "jwk", key: CryptoKey): Promise; + exportKey(format: Exclude, key: CryptoKey): Promise; + generateKey( + algorithm: EcKeyGenParams | RsaHashedKeyGenParams | "Ed25519" | { name: "Ed25519" }, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + generateKey( + algorithm: AesKeyGenParams | HmacKeyGenParams, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; importKey( format: "jwk", keyData: JsonWebKey, - algorithm: AlgorithmIdentifier | HmacImportParams, + algorithm: AlgorithmIdentifier | HmacImportParams | EcKeyImportParams | RsaHashedImportParams, extractable: boolean, keyUsages: readonly KeyUsage[], ): Promise; importKey( format: Exclude, keyData: BufferSource, - algorithm: AlgorithmIdentifier | HmacImportParams, + algorithm: AlgorithmIdentifier | HmacImportParams | EcKeyImportParams | RsaHashedImportParams, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + sign( + algorithm: AlgorithmIdentifier | EcdsaParams | RsaPssParams, + key: CryptoKey, + data: BufferSource, + ): Promise; + unwrapKey( + format: KeyFormat, + wrappedKey: BufferSource, + unwrappingKey: CryptoKey, + unwrapAlgorithm: AlgorithmIdentifier | AesGcmParams | AesCbcParams | AesCtrParams, + unwrappedKeyAlgorithm: AlgorithmIdentifier | HmacImportParams, extractable: boolean, keyUsages: readonly KeyUsage[], ): Promise; - sign(algorithm: AlgorithmIdentifier, key: CryptoKey, data: BufferSource): Promise; verify( - algorithm: AlgorithmIdentifier, + algorithm: AlgorithmIdentifier | EcdsaParams | RsaPssParams, key: CryptoKey, signature: BufferSource, data: BufferSource, ): Promise; + wrapKey( + format: KeyFormat, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: AlgorithmIdentifier | AesGcmParams | AesCbcParams | AesCtrParams, + ): Promise; } interface Crypto { readonly subtle: SubtleCrypto; + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Uint8ClampedArray + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array, + >( + typedArray: T, + ): T; + randomUUID(): `${string}-${string}-${string}-${string}-${string}`; } /* Capability-gated globals harness code probes behind feature guards @@ -2693,8 +2835,20 @@ declare module "crypto" { import { Transform } from "stream"; export type KeyObjectType = "secret" | "public" | "private"; export interface JsonWebKey { - kty?: string; + crv?: string; + d?: string; + dp?: string; + dq?: string; + e?: string; k?: string; + kty?: string; + n?: string; + p?: string; + q?: string; + qi?: string; + x?: string; + y?: string; + [key: string]: unknown; } export interface JwkKeyExportOptions { format: "jwk"; @@ -2702,16 +2856,183 @@ declare module "crypto" { export interface KeyExportOptions { format?: "buffer" | undefined; } - /** Secret keys only; the asymmetric key types are not available. */ + export type KeyFormat = "pem" | "der" | "jwk"; + export interface AsymmetricKeyExportOptions { + type: "pkcs1" | "spki" | "pkcs8" | "sec1"; + format: T; + } + export interface AsymmetricKeyDetails { + modulusLength?: number; + publicExponent?: bigint; + namedCurve?: string; + } + /* Secret keys, and RSA and EC private and public keys. */ export class KeyObject { private constructor(); type: KeyObjectType; symmetricKeySize?: number; asymmetricKeyType?: string; + asymmetricKeyDetails?: AsymmetricKeyDetails; + export(options: AsymmetricKeyExportOptions<"pem">): string | Buffer; + export(options: AsymmetricKeyExportOptions<"der">): Buffer; export(options?: KeyExportOptions): Buffer; export(options: JwkKeyExportOptions): JsonWebKey; equals(otherKeyObject: KeyObject): boolean; } + export interface PrivateKeyInput { + key: string | Buffer; + format?: "pem" | "der" | undefined; + type?: "pkcs1" | "pkcs8" | "sec1" | undefined; + encoding?: string | undefined; + } + export interface PublicKeyInput { + key: string | Buffer; + format?: "pem" | "der" | undefined; + type?: "pkcs1" | "spki" | undefined; + encoding?: string | undefined; + } + export interface JsonWebKeyInput { + key: JsonWebKey; + format: "jwk"; + } + export function createPrivateKey( + key: PrivateKeyInput | string | Buffer | JsonWebKeyInput, + ): KeyObject; + export function createPublicKey( + key: PublicKeyInput | string | Buffer | KeyObject | JsonWebKeyInput, + ): KeyObject; + export interface KeyPairKeyObjectResult { + publicKey: KeyObject; + privateKey: KeyObject; + } + export interface KeyPairSyncResult { + publicKey: T1; + privateKey: T2; + } + export interface RSAKeyPairKeyObjectOptions { + modulusLength: number; + publicExponent?: number | undefined; + } + export interface ECKeyPairKeyObjectOptions { + namedCurve: string; + } + export interface RSAKeyPairOptions { + modulusLength: number; + publicExponent?: number | undefined; + publicKeyEncoding: { type: "pkcs1" | "spki"; format: PubF }; + privateKeyEncoding: { type: "pkcs1" | "pkcs8"; format: PrivF }; + } + export interface ECKeyPairOptions { + namedCurve: string; + publicKeyEncoding: { type: "pkcs1" | "spki"; format: PubF }; + privateKeyEncoding: { type: "sec1" | "pkcs8"; format: PrivF }; + } + export function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + export function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + export function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairKeyObjectOptions, + ): KeyPairKeyObjectResult; + export function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + export function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + export function generateKeyPairSync( + type: "ec", + options: ECKeyPairKeyObjectOptions, + ): KeyPairKeyObjectResult; + export interface ED25519KeyPairOptions { + publicKeyEncoding: { type: "spki"; format: PubF }; + privateKeyEncoding: { type: "pkcs8"; format: PrivF }; + } + export function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + export function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + export function generateKeyPairSync(type: "ed25519", options?: {}): KeyPairKeyObjectResult; + export function generateKeyPair( + type: "ed25519", + options: {} | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + export function generateKeyPair( + type: "rsa", + options: RSAKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + export function generateKeyPair( + type: "ec", + options: ECKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + export interface SigningOptions { + padding?: number | undefined; + saltLength?: number | undefined; + dsaEncoding?: "der" | "ieee-p1363" | undefined; + } + export interface SignPrivateKeyInput extends PrivateKeyInput, SigningOptions {} + export interface SignKeyObjectInput extends SigningOptions { + key: KeyObject; + } + export interface VerifyPublicKeyInput extends PublicKeyInput, SigningOptions {} + export interface VerifyKeyObjectInput extends SigningOptions { + key: KeyObject; + } + export function sign( + algorithm: string | null | undefined, + data: ArrayBufferView, + key: KeyObject | string | Buffer | SignKeyObjectInput | SignPrivateKeyInput, + ): Buffer; + export function verify( + algorithm: string | null | undefined, + data: ArrayBufferView, + key: KeyObject | string | Buffer | VerifyKeyObjectInput | VerifyPublicKeyInput, + signature: ArrayBufferView, + ): boolean; + /* Sign and Verify accumulate update() data; they are not usable as + * writable streams. */ + export class Sign { + private constructor(); + update(data: string | ArrayBufferView): this; + update(data: string, inputEncoding: Encoding): this; + sign( + privateKey: KeyObject | string | Buffer | SignKeyObjectInput | SignPrivateKeyInput, + ): Buffer; + sign( + privateKey: KeyObject | string | Buffer | SignKeyObjectInput | SignPrivateKeyInput, + outputFormat: BinaryToTextEncoding, + ): string; + } + export class Verify { + private constructor(); + update(data: string | ArrayBufferView): this; + update(data: string, inputEncoding: Encoding): this; + verify( + object: KeyObject | string | Buffer | VerifyKeyObjectInput | VerifyPublicKeyInput, + signature: ArrayBufferView, + ): boolean; + verify( + object: KeyObject | string | Buffer | VerifyKeyObjectInput | VerifyPublicKeyInput, + signature: string, + signatureEncoding?: BinaryToTextEncoding, + ): boolean; + } + export function createSign(algorithm: string): Sign; + export function createVerify(algorithm: string): Verify; export function createSecretKey(key: ArrayBufferView | ArrayBufferLike): KeyObject; export function createSecretKey(key: string, encoding: BufferEncoding): KeyObject; export function generateKeySync(type: "hmac" | "aes", options: { length: number }): KeyObject; @@ -2784,8 +3105,7 @@ declare module "crypto" { b: ArrayBufferView | ArrayBufferLike, ): boolean; /* WebCrypto's getRandomValues (also the webcrypto object's): integer - * typed arrays, filled in place and returned. The crypto GLOBAL stays - * unknown in fallback builds. */ + * typed arrays, filled in place and returned. */ type RandomValuesArray = | Int8Array | Uint8Array @@ -2797,9 +3117,9 @@ declare module "crypto" { | BigInt64Array | BigUint64Array; export function getRandomValues(typedArray: T): T; - export const webcrypto: { - getRandomValues(typedArray: T): T; - }; + /* The WebCrypto global's object and its SubtleCrypto. */ + export const webcrypto: Crypto; + export const subtle: SubtleCrypto; export function randomFillSync( buffer: T, offset?: number, @@ -2851,8 +3171,10 @@ declare module "crypto" { callback: (error: Error | null, buffer: Buffer) => void, ): void; export type BinaryLike = string | ArrayBuffer | ArrayBufferView; - /* Cipheriv/Decipheriv: aes-128/192/256 in cbc, ctr, and gcm modes and - * chacha20-poly1305. The stream.Transform members are not declared. */ + /* Cipheriv/Decipheriv: aes-128/192/256 in cbc, ctr, gcm, ecb, cfb, cfb8, + * cfb1, and ofb modes, des-ede3 and des-ede, chacha20, and + * chacha20-poly1305. Both are Transforms: written chunks go through + * update(), and the end pushes final(). */ export type CipherGCMTypes = "aes-128-gcm" | "aes-192-gcm" | "aes-256-gcm"; export type CipherChaCha20Poly1305Types = "chacha20-poly1305"; export type CipherKey = BinaryLike | KeyObject; @@ -2862,7 +3184,7 @@ declare module "crypto" { export interface CipherChaCha20Poly1305Options { authTagLength?: number; } - export interface Cipheriv { + export interface Cipheriv extends Transform { update(data: string | ArrayBufferView): Buffer; update(data: string, inputEncoding: BufferEncoding): Buffer; update(data: ArrayBufferView, inputEncoding: undefined, outputEncoding: BufferEncoding): string; @@ -2883,7 +3205,7 @@ declare module "crypto" { setAAD(buffer: ArrayBufferView, options?: { plaintextLength: number }): this; getAuthTag(): Buffer; } - export interface Decipheriv { + export interface Decipheriv extends Transform { update(data: ArrayBufferView): Buffer; update(data: string, inputEncoding: BufferEncoding): Buffer; update(data: ArrayBufferView, inputEncoding: undefined, outputEncoding: BufferEncoding): string; @@ -2968,6 +3290,123 @@ declare module "crypto" { setPrivateKey(privateKey: string, encoding: BinaryToTextEncoding): void; } export function createECDH(curveName: string): ECDH; + export class DiffieHellman { + private constructor(); + generateKeys(): Buffer; + generateKeys(encoding: BinaryToTextEncoding): string; + computeSecret( + otherPublicKey: ArrayBufferView, + inputEncoding?: null, + outputEncoding?: null, + ): Buffer; + computeSecret( + otherPublicKey: string, + inputEncoding: BinaryToTextEncoding, + outputEncoding?: null, + ): Buffer; + computeSecret( + otherPublicKey: ArrayBufferView, + inputEncoding: null, + outputEncoding: BinaryToTextEncoding, + ): string; + computeSecret( + otherPublicKey: string, + inputEncoding: BinaryToTextEncoding, + outputEncoding: BinaryToTextEncoding, + ): string; + getPrime(): Buffer; + getPrime(encoding: BinaryToTextEncoding): string; + getGenerator(): Buffer; + getGenerator(encoding: BinaryToTextEncoding): string; + getPublicKey(): Buffer; + getPublicKey(encoding: BinaryToTextEncoding): string; + getPrivateKey(): Buffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + setPublicKey(publicKey: ArrayBufferView): void; + setPublicKey(publicKey: string, encoding: BufferEncoding): void; + setPrivateKey(privateKey: ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BufferEncoding): void; + verifyError: number; + } + export type DiffieHellmanGroup = Omit; + export function createDiffieHellman(primeLength: number, generator?: number): DiffieHellman; + export function createDiffieHellman( + prime: ArrayBuffer | ArrayBufferView, + generator?: number | ArrayBuffer | ArrayBufferView, + ): DiffieHellman; + export function createDiffieHellman( + prime: ArrayBuffer | ArrayBufferView, + generator: string, + generatorEncoding: BinaryToTextEncoding, + ): DiffieHellman; + export function createDiffieHellman( + prime: string, + primeEncoding: BinaryToTextEncoding, + generator?: number | ArrayBuffer | ArrayBufferView, + ): DiffieHellman; + export function createDiffieHellman( + prime: string, + primeEncoding: BinaryToTextEncoding, + generator: string, + generatorEncoding: BinaryToTextEncoding, + ): DiffieHellman; + export function getDiffieHellman(groupName: string): DiffieHellmanGroup; + export function createDiffieHellmanGroup(name: string): DiffieHellmanGroup; + export type LargeNumberLike = ArrayBufferView | SharedArrayBuffer | ArrayBuffer | bigint; + export interface GeneratePrimeOptions { + add?: LargeNumberLike | undefined; + rem?: LargeNumberLike | undefined; + safe?: boolean | undefined; + bigint?: boolean | undefined; + } + export interface GeneratePrimeOptionsBigInt extends GeneratePrimeOptions { + bigint: true; + } + export interface GeneratePrimeOptionsArrayBuffer extends GeneratePrimeOptions { + bigint?: false | undefined; + } + export function generatePrime( + size: number, + callback: (err: Error | null, prime: ArrayBuffer) => void, + ): void; + export function generatePrime( + size: number, + options: GeneratePrimeOptionsBigInt, + callback: (err: Error | null, prime: bigint) => void, + ): void; + export function generatePrime( + size: number, + options: GeneratePrimeOptionsArrayBuffer, + callback: (err: Error | null, prime: ArrayBuffer) => void, + ): void; + export function generatePrime( + size: number, + options: GeneratePrimeOptions, + callback: (err: Error | null, prime: ArrayBuffer | bigint) => void, + ): void; + export function generatePrimeSync(size: number): ArrayBuffer; + export function generatePrimeSync(size: number, options: GeneratePrimeOptionsBigInt): bigint; + export function generatePrimeSync( + size: number, + options: GeneratePrimeOptionsArrayBuffer, + ): ArrayBuffer; + export function generatePrimeSync( + size: number, + options: GeneratePrimeOptions, + ): ArrayBuffer | bigint; + export interface CheckPrimeOptions { + checks?: number | undefined; + } + export function checkPrime( + value: LargeNumberLike, + callback: (err: Error | null, result: boolean) => void, + ): void; + export function checkPrime( + value: LargeNumberLike, + options: CheckPrimeOptions, + callback: (err: Error | null, result: boolean) => void, + ): void; + export function checkPrimeSync(candidate: LargeNumberLike, options?: CheckPrimeOptions): boolean; export interface ScryptOptions { N?: number; r?: number; @@ -3129,7 +3568,8 @@ declare module "child_process" { * killSignal at the deadline and the result carries error: ETIMEDOUT + * the signal, never a throw), killSignal (a signal NAME literal), * stdio ("ignore"/"inherit"/"pipe" or a 3-tuple of those — captures - * read "" for non-piped streams), and windowsHide (a POSIX no-op). */ + * read "" for non-piped streams), env (replaces the child's + * environment), and windowsHide (a POSIX no-op). */ export function spawnSync( command: string, args?: string[], @@ -3138,6 +3578,7 @@ declare module "child_process" { timeout?: number; killSignal?: string; stdio?: "pipe" | "ignore" | "inherit" | ("pipe" | "ignore" | "inherit")[]; + env?: { [k: string]: string | undefined }; windowsHide?: boolean; }, ): SpawnSyncReturns; @@ -3171,20 +3612,20 @@ declare module "child_process" { export interface ChildProcess extends Disposable { ref(): void; - on(event: "spawn", listener: () => void): void; - once(event: "spawn", listener: () => void): void; + on(event: "spawn", listener: () => void): this; + once(event: "spawn", listener: () => void): this; /* The exit listener may also take Node's second parameter — the * terminating signal's name, null for a normal exit. */ - on(event: "exit", listener: (code: number | null, signal: string | null) => void): void; - on(event: "close", listener: (code: number | null, signal: string | null) => void): void; - on(event: "error", listener: (err: Error) => void): void; - once(event: "exit", listener: (code: number | null, signal: string | null) => void): void; - once(event: "close", listener: (code: number | null, signal: string | null) => void): void; - once(event: "error", listener: (err: Error) => void): void; - on(event: "message", listener: (message: any) => void): void; - on(event: "disconnect", listener: () => void): void; - once(event: "message", listener: (message: any) => void): void; - once(event: "disconnect", listener: () => void): void; + on(event: "exit", listener: (code: number | null, signal: string | null) => void): this; + on(event: "close", listener: (code: number | null, signal: string | null) => void): this; + on(event: "error", listener: (err: Error) => void): this; + once(event: "exit", listener: (code: number | null, signal: string | null) => void): this; + once(event: "close", listener: (code: number | null, signal: string | null) => void): this; + once(event: "error", listener: (err: Error) => void): this; + on(event: "message", listener: (message: any) => void): this; + on(event: "disconnect", listener: () => void): this; + once(event: "message", listener: (message: any) => void): this; + once(event: "disconnect", listener: () => void): this; /* The lifecycle members, Node's exact shapes: pid is undefined exactly * when the spawn failed; exitCode is null while running, the code * after a normal exit, null for a signal death, and -errno once a @@ -3397,9 +3838,8 @@ declare module "util" { export type TextDecoder = globalThis.TextDecoder; export var TextEncoder: typeof globalThis.TextEncoder; export var TextDecoder: typeof globalThis.TextDecoder; - /* stream.pipeline's (...streams: unknown[]) => unknown is assignable to - * every other target's parameter type, so its overload comes first; no - * other target is assignable to it. */ + /* stream.pipeline's overload comes first: its __promisify__ member keeps + * every other target out of it. */ export function promisify( fn: typeof import("node:stream").pipeline, ): typeof import("node:stream/promises").pipeline; @@ -4778,8 +5218,8 @@ declare module "net" { * unshift — read answers exactly n buffered bytes or null. */ read(size?: number): Buffer | null; unshift(chunk: Uint8Array): void; - /* secureConnect/session are TLS-socket events declared on the shared - * socket surface (the lowering collapses TLSSocket onto this kind): + /* secureConnect/secure/session are TLS-socket events declared on the + * shared socket surface (the lowering collapses TLSSocket onto this kind): * the runtime gates on the transport, so a plain socket's * registration never fires — Node's exact split. 'session' fires * once with the serialized session (the received-ticket event). */ @@ -4787,7 +5227,15 @@ declare module "net" { /* After setEncoding the chunk is a string. */ on(event: "data", listener: (chunk: string) => void): void; on( - event: "end" | "connect" | "ready" | "timeout" | "readable" | "finish" | "secureConnect", + event: + | "end" + | "connect" + | "ready" + | "timeout" + | "readable" + | "finish" + | "secureConnect" + | "secure", listener: () => void, ): void; on(event: "close", listener: (hadError: boolean) => void): void; @@ -4803,7 +5251,15 @@ declare module "net" { /* After setEncoding the chunk is a string. */ addListener(event: "data", listener: (chunk: string) => void): void; addListener( - event: "end" | "connect" | "ready" | "timeout" | "readable" | "finish" | "secureConnect", + event: + | "end" + | "connect" + | "ready" + | "timeout" + | "readable" + | "finish" + | "secureConnect" + | "secure", listener: () => void, ): void; addListener(event: "close", listener: (hadError: boolean) => void): void; @@ -4818,7 +5274,15 @@ declare module "net" { /* After setEncoding the chunk is a string. */ once(event: "data", listener: (chunk: string) => void): void; once( - event: "end" | "connect" | "ready" | "timeout" | "readable" | "finish" | "secureConnect", + event: + | "end" + | "connect" + | "ready" + | "timeout" + | "readable" + | "finish" + | "secureConnect" + | "secure", listener: () => void, ): void; once(event: "close", listener: (hadError: boolean) => void): void; @@ -4869,9 +5333,10 @@ declare module "net" { on(event: "timeout", listener: (socket: Socket) => void): void; on(event: "error", listener: (err: Error) => void): void; /* The WebSocket handover: fires INSTEAD of 'request' for - * Connection: upgrade requests, with the raw socket + head bytes. */ + * Connection: upgrade requests, with the raw socket + head bytes; + * 'connect' is its twin for CONNECT requests (HTTP tunneling). */ on( - event: "upgrade", + event: "upgrade" | "connect", listener: (req: import("http").IncomingMessage, socket: Socket, head: Buffer) => void, ): void; /* http.createServer(handler)'s event twin (a no-parser net server @@ -4887,7 +5352,7 @@ declare module "net" { addListener(event: "timeout", listener: (socket: Socket) => void): void; addListener(event: "error", listener: (err: Error) => void): void; addListener( - event: "upgrade", + event: "upgrade" | "connect", listener: (req: import("http").IncomingMessage, socket: Socket, head: Buffer) => void, ): void; addListener( @@ -4900,7 +5365,7 @@ declare module "net" { once(event: "timeout", listener: (socket: Socket) => void): void; once(event: "error", listener: (err: Error) => void): void; once( - event: "upgrade", + event: "upgrade" | "connect", listener: (req: import("http").IncomingMessage, socket: Socket, head: Buffer) => void, ): void; once( @@ -5371,6 +5836,7 @@ declare module "tls" { * split — authorizationError is the verify-failure CODE STRING * (DEPTH_ZERO_SELF_SIGNED_CERT, ...), or null. */ export interface TLSSocket extends Socket { + readonly encrypted: true; authorized: boolean; authorizationError: string | null; /* null before the handshake, then the negotiated protocol or false */ @@ -5382,6 +5848,21 @@ declare module "tls" { /* whether the handshake resumed a cached session */ isSessionReused(): boolean; } + /** new tls.TLSSocket(socket, options): the server-mode wrap of an open + * socket (a server connection or an http CONNECT socket). The options + * record reads at runtime; isServer, cert, key, secureContext, + * ALPNProtocols, minVersion and maxVersion are implemented. */ + export interface TLSSocketOptions { + isServer?: boolean; + cert?: string | Uint8Array; + key?: string | Uint8Array; + secureContext?: SecureContext; + ALPNProtocols?: string[] | Uint8Array; + minVersion?: string; + maxVersion?: string; + [option: string]: unknown; + } + export const TLSSocket: new (socket: Socket, options: TLSSocketOptions) => TLSSocket; export interface CipherNameAndProtocol { name: string; standardName: string; @@ -5390,12 +5871,14 @@ declare module "tls" { export const DEFAULT_MIN_VERSION: string; export const DEFAULT_MAX_VERSION: string; /** tls.connect options — the RUNTIME options record (members read at - * runtime; port/host/rejectUnauthorized/ca/servername are the + * runtime; port/host/socket/rejectUnauthorized/ca/servername are the * honestly-implemented set, every other documented member throws the * runtime fence — the options-record stance's divergence-66 shape). */ export interface ConnectionOptions { port?: number; host?: string; + /* an open socket to run the client handshake over */ + socket?: Socket; rejectUnauthorized?: boolean; ca?: string | Uint8Array | ReadonlyArray; servername?: string; @@ -6630,11 +7113,10 @@ declare module "node:events" { * write(chunk, enc, cb) {} })`, Duplex/Transform/PassThrough, push/read, * flowing vs paused, write/end backpressure + 'drain', pipe/unpipe, and * destroy — with Node's event orderings. Chunks are BYTES (Buffer), with - * utf8 strings converted at push/write like Node; objectMode and - * setEncoding are declared so uses fence at their sites with their own - * words. `class My extends Readable` (the _read override form) is a - * separate feature and fences at the class declaration. The runtime-fired - * events carry per-class FORCED argument tuples ('data' is one Buffer, + * strings converted at push/write like Node, and any value on an + * object-mode side (objectMode, readableObjectMode, writableObjectMode — + * the object-mode constructor overloads come first). The runtime-fired + * events carry per-class FORCED argument tuples ('data' is one chunk, * 'error' one Error, 'pipe'/'unpipe' one Readable, the rest empty) — the * overloads below hand tsc the same contract so unannotated listener * parameters contextually type in .js sources. */ @@ -6665,7 +7147,11 @@ declare module "stream" { encoding: string, callback: (error?: Error | null) => void, ): void; - writev?(this: Writable, chunks: unknown[], callback: (error?: Error | null) => void): void; + writev?( + this: Writable, + chunks: Array<{ chunk: any; encoding: string }>, + callback: (error?: Error | null) => void, + ): void; final?(this: Writable, callback: (error?: Error | null) => void): void; destroy?(this: Writable, error: Error | null, callback: (error?: Error | null) => void): void; construct?(this: Writable, callback: (error?: Error | null) => void): void; @@ -6700,7 +7186,11 @@ declare module "stream" { readable?: boolean; writable?: boolean; defaultEncoding?: string; - writev?(this: Duplex, chunks: unknown[], callback: (error?: Error | null) => void): void; + writev?( + this: Duplex, + chunks: Array<{ chunk: any; encoding: string }>, + callback: (error?: Error | null) => void, + ): void; signal?: AbortSignal; } interface TransformOptions { @@ -6740,6 +7230,81 @@ declare module "stream" { signal?: AbortSignal; } + /* Object-mode options (objectMode: true, or a Duplex's or Transform's + * readableObjectMode / writableObjectMode): chunks and completion data + * are any values, and an object-mode write's encoding argument reaches + * write/transform as passed (undefined when absent, null when a + * callback took its place). The constructors take these before the + * byte-mode options, so a byte-mode stream's callbacks keep Buffer + * chunks. */ + type ObjectModeEncoding = string | null | undefined; + type ObjectModeFlag = + | { objectMode: true } + | { readableObjectMode: true } + | { writableObjectMode: true }; + interface ObjectWritableOptions extends Omit { + objectMode: true; + write?( + this: Writable, + chunk: any, + encoding: ObjectModeEncoding, + callback: (error?: Error | null) => void, + ): void; + } + type ObjectDuplexOptions = Omit & { + write?( + this: Duplex, + chunk: any, + encoding: ObjectModeEncoding, + callback: (error?: Error | null) => void, + ): void; + } & ObjectModeFlag; + type ObjectTransformOptions = Omit & { + transform?( + this: Transform, + chunk: any, + encoding: ObjectModeEncoding, + callback: (error?: Error | null, data?: any) => void, + ): void; + flush?(this: Transform, callback: (error?: Error | null, data?: any) => void): void; + write?( + this: Transform, + chunk: any, + encoding: ObjectModeEncoding, + callback: (error?: Error | null) => void, + ): void; + } & ObjectModeFlag; + + /* decodeStrings: false — a string write reaches write/transform as the + * string with its encoding (Buffers keep 'buffer'). */ + interface StringWritableOptions extends Omit { + decodeStrings: false; + write?( + this: Writable, + chunk: string | Buffer, + encoding: string, + callback: (error?: Error | null) => void, + ): void; + } + type StringDuplexOptions = Omit & { + decodeStrings: false; + write?( + this: Duplex, + chunk: string | Buffer, + encoding: string, + callback: (error?: Error | null) => void, + ): void; + }; + type StringTransformOptions = Omit & { + decodeStrings: false; + transform?( + this: Transform, + chunk: string | Buffer, + encoding: string, + callback: (error?: Error | null, data?: Buffer | string) => void, + ): void; + }; + /* The operators' options: concurrency and highWaterMark bound map's * in-flight callbacks and queued results. */ interface ArrayOptions { @@ -6758,9 +7323,16 @@ declare module "stream" { _destroy(error: Error | null, callback: (error?: Error | null) => void): void; [Symbol.asyncIterator](): AsyncIterableIterator; iterator(options?: { destroyOnReturn?: boolean }): AsyncIterableIterator; + /* compose(this, stage), destroyed when options.signal aborts. */ + compose(stage: ComposeStage, options?: { signal: AbortSignal }): Duplex; push(chunk: Buffer | string | null, encoding?: string): boolean; + /* An object-mode stream's values. */ + push(chunk: any, encoding?: string): boolean; unshift(chunk: Buffer | string, encoding?: string): void; - read(size?: number): Buffer | null; + unshift(chunk: any, encoding?: string): void; + /* A Buffer, a string once encoded, an object-mode value, or null (as + * @types/node types it). */ + read(size?: number): any; pause(): this; resume(): this; isPaused(): boolean; @@ -6778,6 +7350,16 @@ declare module "stream" { readonly destroyed: boolean; readonly errored: Error | null; static from(iterable: unknown, options?: ReadableOptions): Readable; + /* A Readable over a web ReadableStream's reader. */ + static fromWeb( + readableStream: globalThis.ReadableStream, + options?: { + encoding?: string; + highWaterMark?: number; + objectMode?: boolean; + signal?: AbortSignal; + }, + ): Readable; /* The Readable operators: chunks are strings or Buffers, map and * flatMap callbacks return strings or Buffers (flatMap: arrays of * them, or strings), and callbacks that declare the options argument @@ -6866,6 +7448,8 @@ declare module "stream" { } class Writable extends EventEmitter { + constructor(opts: ObjectWritableOptions); + constructor(opts: StringWritableOptions); constructor(opts?: WritableOptions); /* The underscore-method surface (see Readable). */ _write(chunk: any, encoding: string, callback: (error?: Error | null) => void): void; @@ -6881,9 +7465,19 @@ declare module "stream" { encoding: string, callback?: (error?: Error | null) => void, ): boolean; + /* An object-mode stream's values (the encoding argument reaches + * _write as passed). */ + write(chunk: any, callback?: (error?: Error | null) => void): boolean; + write( + chunk: any, + encoding: ObjectModeEncoding, + callback?: (error?: Error | null) => void, + ): boolean; end(callback?: () => void): this; end(chunk: Buffer | string, callback?: () => void): this; end(chunk: Buffer | string, encoding: string, callback?: () => void): this; + end(chunk: any, callback?: () => void): this; + end(chunk: any, encoding: ObjectModeEncoding, callback?: () => void): this; cork(): void; uncork(): void; setDefaultEncoding(encoding: string): this; @@ -6933,6 +7527,11 @@ declare module "stream" { * mirrors @types/node: extends Readable, the writable half declared * again. The lowering treats both halves as first-class. */ class Duplex extends Readable { + /* Duplex.from: an async generator function, an iterable, a string or + * a stream (duplexify.js). */ + static from(body: unknown): Duplex; + constructor(opts: ObjectDuplexOptions); + constructor(opts: StringDuplexOptions); constructor(opts?: DuplexOptions); /* The underscore-method surface (see Readable). */ _write(chunk: any, encoding: string, callback: (error?: Error | null) => void): void; @@ -6947,9 +7546,19 @@ declare module "stream" { encoding: string, callback?: (error?: Error | null) => void, ): boolean; + /* An object-mode stream's values (the encoding argument reaches + * _write as passed). */ + write(chunk: any, callback?: (error?: Error | null) => void): boolean; + write( + chunk: any, + encoding: ObjectModeEncoding, + callback?: (error?: Error | null) => void, + ): boolean; end(callback?: () => void): this; end(chunk: Buffer | string, callback?: () => void): this; end(chunk: Buffer | string, encoding: string, callback?: () => void): this; + end(chunk: any, callback?: () => void): this; + end(chunk: any, encoding: ObjectModeEncoding, callback?: () => void): this; cork(): void; uncork(): void; setDefaultEncoding(encoding: string): this; @@ -7021,27 +7630,56 @@ declare module "stream" { } class Transform extends Duplex { + constructor(opts: ObjectTransformOptions); + constructor(opts: StringTransformOptions); constructor(opts?: TransformOptions); /* The underscore-method surface (see Readable). */ _transform( chunk: any, encoding: string, - callback: (error?: Error | null, data?: Buffer | string) => void, + callback: (error?: Error | null, data?: any) => void, ): void; - _flush(callback: (error?: Error | null, data?: Buffer | string) => void): void; + _flush(callback: (error?: Error | null, data?: any) => void): void; } class PassThrough extends Transform { + constructor(opts: ObjectTransformOptions); + constructor(opts: StringTransformOptions); constructor(opts?: TransformOptions); } /* addAbortSignal(signal, stream): the stream, destroyed with an * AbortError (cause: signal.reason) when the signal aborts. */ function addAbortSignal(signal: AbortSignal, stream: T): T; - /* Declared so requires typecheck; each fences at its use site. */ - function pipeline(...streams: unknown[]): unknown; - /* compose(...streams): a Duplex that writes to the first stream and - * reads from the last, with the streams running as a pipeline. */ - function compose(...streams: Array): Duplex; + /* pipeline(...stages, callback): the last stream, or the object-mode + * PassThrough that a function destination feeds. */ + type PipelineResult = T extends [ + ...unknown[], + infer D, + (...args: any[]) => unknown, + ] + ? D extends (...args: any[]) => unknown + ? PassThrough + : D + : unknown; + function pipeline(...streams: T): PipelineResult; + /* util.promisify's pipeline overload matches only pipeline itself: a + * generic signature alone admits every function. */ + namespace pipeline { + const __promisify__: typeof promises.pipeline; + } + /* A compose stage: a stream, an async generator function over the + * previous stage, or (first) an iterable, async iterable or web + * ReadableStream. */ + type ComposeStage = + | Readable + | Writable + | Iterable + | AsyncIterable + | globalThis.ReadableStream + | ((source: any, options?: { signal: AbortSignal }) => unknown); + /* compose(...streams): a Duplex that writes to the first stage and + * reads from the last, with the stages running as a pipeline. */ + function compose(...streams: ComposeStage[]): Duplex; /* finished's options: readable/writable choose which ends count, * error: false ignores 'error' events, signal aborts the wait. */ interface FinishedOptions { @@ -7060,13 +7698,20 @@ declare module "stream" { * else 65536 — Node's own state.js split); literal argument only. */ function getDefaultHighWaterMark(objectMode: boolean): number; /* The promise pipeline's result: a last stage that is an async - * function resolves the promise with its value. */ + * function resolves the promise with its value (before the options + * argument, when one follows). */ type PipelinePromise = T extends [ ...unknown[], (...args: any[]) => Promise, ] ? Promise

- : Promise; + : T extends [ + ...unknown[], + (...args: any[]) => Promise, + { signal?: AbortSignal; end?: boolean }, + ] + ? Promise

+ : Promise; namespace promises { function pipeline(...streams: T): PipelinePromise; function finished( @@ -7096,6 +7741,7 @@ declare module "stream" { DuplexOptions, TransformOptions, FinishedOptions, + PipelinePromise, }; } declare module "node:stream" { @@ -7110,9 +7756,7 @@ declare module "stream/promises" { * pipeline's trailing { signal, end } object and finished's options * (readable, writable, error, cleanup, signal) are supported. A last * stage that is an async function resolves the promise with its value. */ - function pipeline( - ...streams: T - ): T extends [...unknown[], (...args: any[]) => Promise] ? Promise

: Promise; + function pipeline(...streams: T): import("stream").PipelinePromise; function finished( stream: unknown, options?: { diff --git a/packages/compiler/native/cli.profdata.gz b/packages/compiler/native/cli.profdata.gz index 55523e765..aa0e9c36b 100644 Binary files a/packages/compiler/native/cli.profdata.gz and b/packages/compiler/native/cli.profdata.gz differ diff --git a/packages/compiler/native/host.c b/packages/compiler/native/host.c index 6aa1b2a28..eeead7eff 100644 --- a/packages/compiler/native/host.c +++ b/packages/compiler/native/host.c @@ -56,3 +56,78 @@ void scr_collect_cycles_phase(void); void scriptc_native_collect_cycles(void) { scr_collect_cycles_phase(); } + +/* Forked lowering workers (frontend/process-fork.ts). A worker shares the + * parent's heap copy-on-write, writes its results to a file and leaves with + * _exit, so no buffered output or exit handler of the parent runs twice. + * Checker requests from workers hold an exclusive flock on a file each + * worker opens after the fork, so every worker has its own open file + * description and the lock excludes the other workers. */ +#ifdef _WIN32 +int32_t scriptc_native_fork(void) { return -1; } +void scriptc_native_exit(int32_t code) { ExitProcess((UINT)code); } +int32_t scriptc_native_wait(int32_t pid) { (void)pid; return -1; } +uint8_t scriptc_native_lock_open(const uint8_t *bytes, size_t size) { (void)bytes; (void)size; return 0; } +void scriptc_native_lock(void) {} +void scriptc_native_unlock(void) {} +#else +#include +#include +#include +#include + +int32_t scriptc_native_fork(void) { return (int32_t)fork(); } + +void scriptc_native_exit(int32_t code) { _exit(code); } + +/* The worker's exit status, 128 plus the signal for a worker a signal + * ended, or -1 when waitpid fails. */ +int32_t scriptc_native_wait(int32_t pid) { + int status = 0; + while (waitpid((pid_t)pid, &status, 0) < 0) { + if (errno != EINTR) return -1; + } + if (WIFEXITED(status)) return WEXITSTATUS(status); + if (WIFSIGNALED(status)) return 128 + WTERMSIG(status); + return -1; +} + +static int scriptc_native_lock_fd = -1; + +uint8_t scriptc_native_lock_open(const uint8_t *bytes, size_t size) { + if (size == 0 || memchr(bytes, 0, size) != NULL) return 0; + char *path = malloc(size + 1); + if (!path) return 0; + memcpy(path, bytes, size); + path[size] = 0; + if (scriptc_native_lock_fd >= 0) close(scriptc_native_lock_fd); + scriptc_native_lock_fd = open(path, O_CREAT | O_RDWR | O_CLOEXEC, 0600); + free(path); + return scriptc_native_lock_fd >= 0; +} + +void scriptc_native_lock(void) { + if (scriptc_native_lock_fd < 0) return; + while (flock(scriptc_native_lock_fd, LOCK_EX) < 0 && errno == EINTR) { + } +} + +void scriptc_native_unlock(void) { + if (scriptc_native_lock_fd >= 0) flock(scriptc_native_lock_fd, LOCK_UN); +} +#endif + +/* The runtime's growth cap for full cycle passes (scr_rc.h). */ +void scr_cyc_set_growth_cap(long cap); + +/* Bounds the cyclic garbage a build can hold to twice its live heap. + * Lowering a large program leaves hundreds of megabytes of cyclic garbage, + * and whether a scheduled full pass reclaims it before the build's peak + * depends on where the growth rule fires: with the default cap of 16, small + * changes to the compiler moved the peak of one build by 390 MB. With a cap + * of 2 a full pass runs once the heap has grown to three times its size + * after the last one; a cap of 1 bounds the garbage further but runs more + * passes over the live heap. SCR_CYCLE_GROWTH_CAP still overrides it. */ +void scriptc_native_bound_cycle_growth(void) { + scr_cyc_set_growth_cap(2); +} diff --git a/packages/compiler/native/host.ffi.json b/packages/compiler/native/host.ffi.json index d7e0e92aa..e7ecbca60 100644 --- a/packages/compiler/native/host.ffi.json +++ b/packages/compiler/native/host.ffi.json @@ -2,6 +2,13 @@ "ffi_format": 6, "functions": [ { "name": "compilerNativePrivateDirectory", "symbol": "scriptc_native_private_directory", "params": ["string", "bool"], "returns": "bool" }, - { "name": "compilerNativeCollectCycles", "symbol": "scriptc_native_collect_cycles", "params": [], "returns": "void" } + { "name": "compilerNativeCollectCycles", "symbol": "scriptc_native_collect_cycles", "params": [], "returns": "void" }, + { "name": "compilerNativeFork", "symbol": "scriptc_native_fork", "params": [], "returns": "i32" }, + { "name": "compilerNativeExit", "symbol": "scriptc_native_exit", "params": ["i32"], "returns": "void" }, + { "name": "compilerNativeWait", "symbol": "scriptc_native_wait", "params": ["i32"], "returns": "i32" }, + { "name": "compilerNativeLockOpen", "symbol": "scriptc_native_lock_open", "params": ["string"], "returns": "bool" }, + { "name": "compilerNativeLock", "symbol": "scriptc_native_lock", "params": [], "returns": "void" }, + { "name": "compilerNativeUnlock", "symbol": "scriptc_native_unlock", "params": [], "returns": "void" }, + { "name": "compilerNativeBoundCycleGrowth", "symbol": "scriptc_native_bound_cycle_growth", "params": [], "returns": "void" } ] } diff --git a/packages/compiler/package.json b/packages/compiler/package.json index 98d984d4f..a1d66963d 100644 --- a/packages/compiler/package.json +++ b/packages/compiler/package.json @@ -1,6 +1,6 @@ { "name": "@scriptc/compiler", - "version": "0.4.1", + "version": "0.4.2", "description": "The scriptc compiler — TypeScript/JavaScript frontend, typed IR, LLVM backend", "license": "Apache-2.0", "homepage": "https://scriptc.dev", @@ -40,7 +40,7 @@ }, "dependencies": { "@scriptc/runtime": "workspace:*", - "tsc-ts": "0.0.5", + "tsc-ts": "0.0.7", "typescript": "7.0.2", "typescript5": "npm:typescript@5.9.3" }, diff --git a/packages/compiler/shims/chalk/v5.ts b/packages/compiler/shims/chalk/v5.ts new file mode 100644 index 000000000..2d34c5c53 --- /dev/null +++ b/packages/compiler/shims/chalk/v5.ts @@ -0,0 +1,688 @@ +// scriptc's built-in implementation of the `chalk` package, 5.x API. +// +// Programs whose installed chalk is 5.x compile this module in its place +// (packages/compiler/src/frontend/package-shims.ts). chalk builds its +// styles as functions whose prototypes it swaps at run time; here a style +// chain is an instance of one class whose style members are cached +// getters, and the instance is callable through its `%call` field (the +// merged interface below gives it chalk's call signature; the lowerer calls +// the field). The output, color-level detection (supports-color 10: +// FORCE_COLOR, the --color/--no-color flags, TTY, TERM, CI variables) and +// the shared, settable `level` follow chalk 5.6 byte for byte. +import * as os from "node:os"; +import * as tty from "node:tty"; + +export type ColorSupportLevel = 0 | 1 | 2 | 3; + +export interface ColorSupport { + level: ColorSupportLevel; + hasBasic: boolean; + has256: boolean; + has16m: boolean; +} + +export type ColorInfo = ColorSupport | false; + +export interface Options { + readonly level?: ColorSupportLevel; +} + +export type ModifierName = + | "reset" + | "bold" + | "dim" + | "italic" + | "underline" + | "overline" + | "inverse" + | "hidden" + | "strikethrough"; + +export type ForegroundColorName = + | "black" + | "red" + | "green" + | "yellow" + | "blue" + | "cyan" + | "magenta" + | "white" + | "gray" + | "grey" + | "blackBright" + | "redBright" + | "greenBright" + | "yellowBright" + | "blueBright" + | "cyanBright" + | "magentaBright" + | "whiteBright"; + +export type BackgroundColorName = + | "bgBlack" + | "bgRed" + | "bgGreen" + | "bgYellow" + | "bgBlue" + | "bgCyan" + | "bgMagenta" + | "bgWhite" + | "bgGray" + | "bgGrey" + | "bgBlackBright" + | "bgRedBright" + | "bgGreenBright" + | "bgYellowBright" + | "bgBlueBright" + | "bgCyanBright" + | "bgMagentaBright" + | "bgWhiteBright"; + +export type ColorName = ForegroundColorName | BackgroundColorName; + +export type Modifiers = ModifierName; +export type ForegroundColor = ForegroundColorName; +export type BackgroundColor = BackgroundColorName; +export type Color = ColorName; + +// ── ansi-styles ────────────────────────────────────────────────────────── + +export const modifierNames: ModifierName[] = [ + "reset", + "bold", + "dim", + "italic", + "underline", + "overline", + "inverse", + "hidden", + "strikethrough", +]; +export const foregroundColorNames: ForegroundColorName[] = [ + "black", + "red", + "green", + "yellow", + "blue", + "magenta", + "cyan", + "white", + "blackBright", + "gray", + "grey", + "redBright", + "greenBright", + "yellowBright", + "blueBright", + "magentaBright", + "cyanBright", + "whiteBright", +]; +export const backgroundColorNames: BackgroundColorName[] = [ + "bgBlack", + "bgRed", + "bgGreen", + "bgYellow", + "bgBlue", + "bgMagenta", + "bgCyan", + "bgWhite", + "bgBlackBright", + "bgGray", + "bgGrey", + "bgRedBright", + "bgGreenBright", + "bgYellowBright", + "bgBlueBright", + "bgMagentaBright", + "bgCyanBright", + "bgWhiteBright", +]; +export const colorNames: ColorName[] = [...foregroundColorNames, ...backgroundColorNames]; +export const modifiers: Modifiers[] = modifierNames; +export const foregroundColors: ForegroundColor[] = foregroundColorNames; +export const backgroundColors: BackgroundColor[] = backgroundColorNames; +export const colors: Color[] = colorNames; + +const ESC = "\u001B["; + +/** Open and close codes, indexed by style id (the order of the getters). */ +const OPEN_CODES: number[] = [ + 0, 1, 2, 3, 4, 53, 7, 8, 9, 30, 31, 32, 33, 34, 35, 36, 37, 90, 90, 90, 91, 92, 93, 94, 95, 96, + 97, 40, 41, 42, 43, 44, 45, 46, 47, 100, 100, 100, 101, 102, 103, 104, 105, 106, 107, +]; +const CLOSE_CODES: number[] = [ + 0, 22, 22, 23, 24, 55, 27, 28, 29, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, + 39, 39, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, +]; +const VISIBLE = 45; + +function rgbToAnsi256(red: number, green: number, blue: number): number { + if (red === green && green === blue) { + if (red < 8) return 16; + if (red > 248) return 231; + return Math.round(((red - 8) / 247) * 24) + 232; + } + return ( + 16 + + 36 * Math.round((red / 255) * 5) + + 6 * Math.round((green / 255) * 5) + + Math.round((blue / 255) * 5) + ); +} + +function hexToRgb(hex: string): number[] { + const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex); + if (matches === null) return [0, 0, 0]; + let colorString = matches[0]; + if (colorString.length === 3) { + let doubled = ""; + for (const character of colorString) doubled += character + character; + colorString = doubled; + } + const integer = Number.parseInt(colorString, 16); + return [(integer >> 16) & 0xff, (integer >> 8) & 0xff, integer & 0xff]; +} + +function ansi256ToAnsi(code: number): number { + if (code < 8) return 30 + code; + if (code < 16) return 90 + (code - 8); + let red: number; + let green: number; + let blue: number; + if (code >= 232) { + red = ((code - 232) * 10 + 8) / 255; + green = red; + blue = red; + } else { + code -= 16; + const remainder = code % 36; + red = Math.floor(code / 36) / 5; + green = Math.floor(remainder / 6) / 5; + blue = (remainder % 6) / 5; + } + const value = Math.max(red, green, blue) * 2; + if (value === 0) return 30; + let result = 30 + ((Math.round(blue) << 2) | (Math.round(green) << 1) | Math.round(red)); + if (value === 2) result += 60; + return result; +} + +/** The open code of a color model at a level: offset 0 is the foreground, + * 10 the background (ansi-styles' wrapAnsi16/256/16m). */ +function rgbOpen(level: number, offset: number, red: number, green: number, blue: number): string { + if (level === 3) return `${ESC}${38 + offset};2;${red};${green};${blue}m`; + if (level === 2) return `${ESC}${38 + offset};5;${rgbToAnsi256(red, green, blue)}m`; + return `${ESC}${ansi256ToAnsi(rgbToAnsi256(red, green, blue)) + offset}m`; +} + +/** chalk's ansi256 model emits the 256-color code at every level (only + * the rgb and hex models downsample). */ +function ansi256Open(offset: number, code: number): string { + return `${ESC}${38 + offset};5;${code}m`; +} + +// ── supports-color ─────────────────────────────────────────────────────── + +function hasFlag(flag: string): boolean { + const argv = process.argv; + const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--"; + const position = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf("--"); + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); +} + +let flagForceColor: number | undefined = undefined; +if ( + hasFlag("no-color") || + hasFlag("no-colors") || + hasFlag("color=false") || + hasFlag("color=never") +) { + flagForceColor = 0; +} else if ( + hasFlag("color") || + hasFlag("colors") || + hasFlag("color=true") || + hasFlag("color=always") +) { + flagForceColor = 1; +} + +function envForceColor(): number | undefined { + const force = process.env["FORCE_COLOR"]; + if (force !== undefined) { + if (force === "true") return 1; + if (force === "false") return 0; + return force.length === 0 ? 1 : Math.min(Number.parseInt(force, 10), 3); + } + return undefined; +} + +function translateLevel(level: number): ColorInfo { + if (level === 0) return false; + return { + level: level as ColorSupportLevel, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3, + }; +} + +function inEnv(name: string): boolean { + return process.env[name] !== undefined; +} + +function detectLevel(streamIsTTY: boolean): number { + const noFlagForceColor = envForceColor(); + if (noFlagForceColor !== undefined) flagForceColor = noFlagForceColor; + const forceColor = flagForceColor; + if (forceColor === 0) return 0; + if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) return 3; + if (hasFlag("color=256")) return 2; + if (inEnv("TF_BUILD") && inEnv("AGENT_NAME")) return 1; + if (!streamIsTTY && forceColor === undefined) return 0; + const min = + forceColor === undefined || forceColor === 0 || Number.isNaN(forceColor) ? 0 : forceColor; + const env = process.env; + const term = env["TERM"]; + if (term === "dumb") return min; + if (process.platform === "win32") { + const osRelease = os.release().split("."); + if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10_586) { + return Number(osRelease[2]) >= 14_931 ? 3 : 2; + } + return 1; + } + if (inEnv("CI")) { + if (inEnv("GITHUB_ACTIONS") || inEnv("GITEA_ACTIONS") || inEnv("CIRCLECI")) return 3; + if ( + inEnv("TRAVIS") || + inEnv("APPVEYOR") || + inEnv("GITLAB_CI") || + inEnv("BUILDKITE") || + inEnv("DRONE") || + env["CI_NAME"] === "codeship" + ) { + return 1; + } + return min; + } + const teamcity = env["TEAMCITY_VERSION"]; + if (teamcity !== undefined) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(teamcity) ? 1 : 0; + } + if (env["COLORTERM"] === "truecolor") return 3; + if (term === "xterm-kitty") return 3; + if (term === "xterm-ghostty") return 3; + if (term === "wezterm") return 3; + const termProgram = env["TERM_PROGRAM"]; + if (termProgram !== undefined) { + const version = Number.parseInt((env["TERM_PROGRAM_VERSION"] || "").split(".")[0]!, 10); + if (termProgram === "iTerm.app") return version >= 3 ? 3 : 2; + if (termProgram === "Apple_Terminal") return 2; + } + // supports-color tests these against `env.TERM`, which is the string + // "undefined" when TERM is unset. + const termText = term === undefined ? "undefined" : term; + if (/-256(color)?$/i.test(termText)) return 2; + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(termText)) return 1; + if (inEnv("COLORTERM")) return 1; + return min; +} + +const stdoutColor: ColorInfo = translateLevel(detectLevel(tty.isatty(1))); +const stderrColor: ColorInfo = translateLevel(detectLevel(tty.isatty(2))); + +export const supportsColor: ColorInfo = stdoutColor; +export const supportsColorStderr: ColorInfo = stderrColor; + +// ── the builder ────────────────────────────────────────────────────────── + +/** One link of a style chain (chalk's styler). */ +class Styler { + open: string; + close: string; + openAll: string; + closeAll: string; + parent: Styler | undefined; + constructor(open: string, close: string, parent: Styler | undefined) { + this.open = open; + this.close = close; + this.parent = parent; + if (parent === undefined) { + this.openAll = open; + this.closeAll = close; + } else { + this.openAll = parent.openAll + open; + this.closeAll = close + parent.closeAll; + } + } +} + +/** The level every builder of one chalk instance shares. */ +class LevelBox { + level: number; + constructor(level: number) { + this.level = level; + } +} + +function stringReplaceAll(string: string, substring: string, replacer: string): string { + let index = string.indexOf(substring); + if (index === -1) return string; + const substringLength = substring.length; + let endIndex = 0; + let returnValue = ""; + do { + returnValue += string.slice(endIndex, index) + substring + replacer; + endIndex = index + substringLength; + index = string.indexOf(substring, endIndex); + } while (index !== -1); + returnValue += string.slice(endIndex); + return returnValue; +} + +function stringEncaseCRLFWithFirstIndex( + string: string, + prefix: string, + postfix: string, + index: number, +): string { + let endIndex = 0; + let returnValue = ""; + do { + const gotCR = string[index - 1] === "\r"; + returnValue += + string.slice(endIndex, gotCR ? index - 1 : index) + + prefix + + (gotCR ? "\r\n" : "\n") + + postfix; + endIndex = index + 1; + index = string.indexOf("\n", endIndex); + } while (index !== -1); + returnValue += string.slice(endIndex); + return returnValue; +} + +function applyStyle(self: ChalkInstance, string: string): string { + if (self.box.level <= 0 || !string) return self.isEmpty ? "" : string; + let styler = self.styler; + if (styler === undefined) return string; + const openAll = styler.openAll; + const closeAll = styler.closeAll; + if (string.includes("\u001B")) { + while (styler !== undefined) { + string = stringReplaceAll(string, styler.close, styler.open); + styler = styler.parent; + } + } + const lfIndex = string.indexOf("\n"); + if (lfIndex !== -1) string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex); + return openAll + string + closeAll; +} + +function joinArguments(args: unknown[]): string { + let out = ""; + for (let i = 0; i < args.length; i++) { + if (i > 0) out += " "; + const value = args[i]; + if (value !== undefined && value !== null) out += String(value); + } + return out; +} + +/** A chalk instance or one of its style chains: callable (chalk's call + * signature merges in from the interface), with every style a cached + * getter. */ +// The merge is the point: the interface gives instances chalk's call +// signature, and the class's `%call` field implements it. +// oxlint-disable-next-line typescript/no-unsafe-declaration-merging +export interface ChalkInstance { + (...text: unknown[]): string; +} + +// oxlint-disable-next-line typescript/no-unsafe-declaration-merging +export class ChalkInstance { + "%call": (...text: unknown[]) => string = (...text: unknown[]): string => + this.root + ? joinArguments(text) + : applyStyle(this, text.length === 1 ? "" + String(text[0]) : joinArguments(text)); + box: LevelBox; + styler: Styler | undefined; + isEmpty: boolean; + private readonly root: boolean; + private readonly cache: (ChalkInstance | undefined)[] = []; + + constructor(box: LevelBox, styler: Styler | undefined, isEmpty: boolean, root: boolean) { + this.box = box; + this.styler = styler; + this.isEmpty = isEmpty; + this.root = root; + } + + /** One string argument: the compiler calls this instead of `%call` + * (no variadic arguments to box). */ + "%call1"(text: string): string { + return this.root ? text : applyStyle(this, text); + } + + get level(): ColorSupportLevel { + return this.box.level as ColorSupportLevel; + } + + set level(level: ColorSupportLevel) { + this.box.level = level; + } + + private style(id: number): ChalkInstance { + const cached = this.cache[id]; + if (cached !== undefined) return cached; + let builder: ChalkInstance; + if (id === VISIBLE) { + builder = new ChalkInstance(this.box, this.styler, true, false); + } else { + const styler = new Styler( + `${ESC}${OPEN_CODES[id]!}m`, + `${ESC}${CLOSE_CODES[id]!}m`, + this.styler, + ); + builder = new ChalkInstance(this.box, styler, this.isEmpty, false); + } + while (this.cache.length <= id) this.cache.push(undefined); + this.cache[id] = builder; + return builder; + } + + private model(open: string, background: boolean): ChalkInstance { + const styler = new Styler(open, background ? `${ESC}49m` : `${ESC}39m`, this.styler); + return new ChalkInstance(this.box, styler, this.isEmpty, false); + } + + rgb(red: number, green: number, blue: number): ChalkInstance { + return this.model(rgbOpen(this.box.level, 0, red, green, blue), false); + } + hex(color: string): ChalkInstance { + const [red, green, blue] = hexToRgb(color); + return this.model(rgbOpen(this.box.level, 0, red!, green!, blue!), false); + } + ansi256(index: number): ChalkInstance { + return this.model(ansi256Open(0, index), false); + } + bgRgb(red: number, green: number, blue: number): ChalkInstance { + return this.model(rgbOpen(this.box.level, 10, red, green, blue), true); + } + bgHex(color: string): ChalkInstance { + const [red, green, blue] = hexToRgb(color); + return this.model(rgbOpen(this.box.level, 10, red!, green!, blue!), true); + } + bgAnsi256(index: number): ChalkInstance { + return this.model(ansi256Open(10, index), true); + } + + get reset(): ChalkInstance { + return this.style(0); + } + get bold(): ChalkInstance { + return this.style(1); + } + get dim(): ChalkInstance { + return this.style(2); + } + get italic(): ChalkInstance { + return this.style(3); + } + get underline(): ChalkInstance { + return this.style(4); + } + get overline(): ChalkInstance { + return this.style(5); + } + get inverse(): ChalkInstance { + return this.style(6); + } + get hidden(): ChalkInstance { + return this.style(7); + } + get strikethrough(): ChalkInstance { + return this.style(8); + } + get visible(): ChalkInstance { + return this.style(VISIBLE); + } + get black(): ChalkInstance { + return this.style(9); + } + get red(): ChalkInstance { + return this.style(10); + } + get green(): ChalkInstance { + return this.style(11); + } + get yellow(): ChalkInstance { + return this.style(12); + } + get blue(): ChalkInstance { + return this.style(13); + } + get magenta(): ChalkInstance { + return this.style(14); + } + get cyan(): ChalkInstance { + return this.style(15); + } + get white(): ChalkInstance { + return this.style(16); + } + get blackBright(): ChalkInstance { + return this.style(17); + } + get gray(): ChalkInstance { + return this.style(18); + } + get grey(): ChalkInstance { + return this.style(19); + } + get redBright(): ChalkInstance { + return this.style(20); + } + get greenBright(): ChalkInstance { + return this.style(21); + } + get yellowBright(): ChalkInstance { + return this.style(22); + } + get blueBright(): ChalkInstance { + return this.style(23); + } + get magentaBright(): ChalkInstance { + return this.style(24); + } + get cyanBright(): ChalkInstance { + return this.style(25); + } + get whiteBright(): ChalkInstance { + return this.style(26); + } + get bgBlack(): ChalkInstance { + return this.style(27); + } + get bgRed(): ChalkInstance { + return this.style(28); + } + get bgGreen(): ChalkInstance { + return this.style(29); + } + get bgYellow(): ChalkInstance { + return this.style(30); + } + get bgBlue(): ChalkInstance { + return this.style(31); + } + get bgMagenta(): ChalkInstance { + return this.style(32); + } + get bgCyan(): ChalkInstance { + return this.style(33); + } + get bgWhite(): ChalkInstance { + return this.style(34); + } + get bgBlackBright(): ChalkInstance { + return this.style(35); + } + get bgGray(): ChalkInstance { + return this.style(36); + } + get bgGrey(): ChalkInstance { + return this.style(37); + } + get bgRedBright(): ChalkInstance { + return this.style(38); + } + get bgGreenBright(): ChalkInstance { + return this.style(39); + } + get bgYellowBright(): ChalkInstance { + return this.style(40); + } + get bgBlueBright(): ChalkInstance { + return this.style(41); + } + get bgMagentaBright(): ChalkInstance { + return this.style(42); + } + get bgCyanBright(): ChalkInstance { + return this.style(43); + } + get bgWhiteBright(): ChalkInstance { + return this.style(44); + } +} + +function optionsLevel(options: Options | undefined): number { + const level = options === undefined ? undefined : options.level; + if ( + level !== undefined && + level !== 0 && + !(Number.isInteger(level) && level >= 0 && level <= 3) + ) { + throw new Error("The `level` option should be an integer from 0 to 3"); + } + if (level === undefined) return stdoutColor === false ? 0 : stdoutColor.level; + return level; +} + +/** `new Chalk(options)`: a fresh chalk instance with its own level. */ +export class Chalk extends ChalkInstance { + constructor(options?: Options) { + super(new LevelBox(optionsLevel(options)), undefined, false, true); + } +} + +const chalk: ChalkInstance = new Chalk(); +export const chalkStderr: ChalkInstance = new Chalk({ + level: stderrColor === false ? 0 : stderrColor.level, +}); + +export default chalk; diff --git a/packages/compiler/shims/hot-shots/client.ts b/packages/compiler/shims/hot-shots/client.ts new file mode 100644 index 000000000..354744e7b --- /dev/null +++ b/packages/compiler/shims/hot-shots/client.ts @@ -0,0 +1,1126 @@ +// scriptc's built-in implementation of the `hot-shots` package, 8.x API: +// a typed port of hot-shots 8.5's StatsD client with the same datagrams, +// callbacks, error messages and child-client sharing, over node:dgram +// (udp), node:net (tcp) and a native Unix datagram socket (uds). The +// entry modules (v8.ts, v8-unix-dgram.ts) say whether the optional +// unix-dgram addon that hot-shots' uds protocol loads is installed. +import * as dgram from "node:dgram"; +import * as dns from "node:dns"; +import * as net from "node:net"; +import * as os from "node:os"; + +export type Tags = { [key: string]: string } | string[]; + +export interface ClientOptions { + bufferFlushInterval?: number; + bufferHolder?: { buffer: string }; + cacheDns?: boolean; + cacheDnsTtl?: number; + errorHandler?: (err: Error) => void; + globalTags?: Tags; + globalize?: boolean; + host?: string; + isChild?: boolean; + maxBufferSize?: number; + mock?: boolean; + path?: string; + port?: number; + prefix?: string; + protocol?: "tcp" | "udp" | "uds"; + sampleRate?: number; + suffix?: string; + telegraf?: boolean; + useDefaultRoute?: boolean; + tagPrefix?: string; + tagSeparator?: string; + udsGracefulErrorHandling?: boolean; + udsGracefulRestartRateLimit?: number; + closingFlushInterval?: number; +} + +export interface ChildClientOptions { + globalTags?: Tags; + prefix?: string; + suffix?: string; + errorHandler?: (err: Error) => void; +} + +export interface CheckOptions { + /** A Unix timestamp; hot-shots also takes a Date, which this shim's + * option records cannot hold yet. */ + date_happened?: number; + hostname?: string; + message?: string; +} + +export interface DatadogChecks { + OK: 0; + WARNING: 1; + CRITICAL: 2; + UNKNOWN: 3; +} + +export type DatadogChecksValues = 0 | 1 | 2 | 3; + +export interface EventOptions { + aggregation_key?: string; + alert_type?: "info" | "warning" | "success" | "error"; + /** A Unix timestamp; hot-shots also takes a Date, which this shim's + * option records cannot hold yet. */ + date_happened?: number; + hostname?: string; + priority?: "low" | "normal"; + source_type_name?: string; +} + +/** A send's completion: hot-shots passes `null` on success. */ +export type StatsCb = (error: Error | null | undefined, bytes?: any) => void; + +type SampleArg = number | Tags | StatsCb | undefined; +type TagsArg = Tags | StatsCb | undefined; + +const PROTOCOL_TCP = "tcp"; +const PROTOCOL_UDS = "uds"; +const PROTOCOL_UDP = "udp"; +const UDS_DEFAULT_GRACEFUL_RESTART_LIMIT = 1000; +const CACHE_DNS_TTL_DEFAULT = 60000; + +function udsErrorCodes(): number[] { + if (process.platform === "linux") { + return [os.constants.errno.ENOTCONN, os.constants.errno.ECONNREFUSED]; + } + if (process.platform === "darwin") { + return [os.constants.errno.EDESTADDRREQ, os.constants.errno.ECONNRESET]; + } + return []; +} +const UDS_ERROR_CODES = udsErrorCodes(); + +// ── helpers ────────────────────────────────────────────────────────────── + +function sanitizeTags(value: string, telegraf: boolean): string { + const blacklist = telegraf ? /:|\||,/g : /:|\||@|,/g; + return String(value).replace(blacklist, "_"); +} + +function formatTags(tags: Tags, telegraf: boolean): string[] { + if (Array.isArray(tags)) return tags; + const out: string[] = []; + for (const key of Object.keys(tags)) { + out.push(`${sanitizeTags(key, telegraf)}:${sanitizeTags(tags[key]!, telegraf)}`); + } + return out; +} + +function isArrayIndexKey(key: string): boolean { + return /^(0|[1-9]\d*)$/.test(key) && Number(key) < 4294967295; +} + +function overrideTags(parent: string[], child: Tags, telegraf: boolean): string[] { + const childKeys: string[] = []; + const childValues = new Map(); + const toAppend: string[] = []; + for (const tag of formatTags(child, telegraf)) { + const idx = tag.indexOf(":"); + if (idx < 1) { + toAppend.push(tag); + } else { + const key = tag.substring(0, idx); + const value = tag.substring(idx + 1); + let values = childValues.get(key); + if (values === undefined) { + values = []; + childValues.set(key, values); + childKeys.push(key); + } + values.push(value); + } + } + const result = parent.filter((tag) => { + const idx = tag.indexOf(":"); + if (idx < 1) return true; + return !childValues.has(tag.substring(0, idx)); + }); + // hot-shots walks an object's keys: array-index keys ascending first, + // then the rest in insertion order. + const indexKeys = childKeys.filter(isArrayIndexKey).sort((a, b) => Number(a) - Number(b)); + const ordered = indexKeys.concat(childKeys.filter((key) => !isArrayIndexKey(key))); + for (const key of ordered) { + for (const value of childValues.get(key)!) result.push(`${key}:${value}`); + } + return result.concat(toAppend); +} + +function formatDate(date: number): number { + return Math.round(date); +} + +/** console.error of an arbitrary value, as hot-shots logs errors. The + * value crosses as unknown: the typed Error path has no inspect lowering + * in programs whose Error subclasses define accessors. */ +function logError(value: unknown): void { + console.error(value); +} + +function errorWithCode(message: string, code: string | undefined): Error { + const error: NodeJS.ErrnoException = new Error(message); + error.code = code; + return error; +} + +// ── transports ─────────────────────────────────────────────────────────── + +type SendCallback = (err: Error | null, bytes?: number) => void; + +/** The socket a client sends through (hot-shots' transport interface). */ +interface Transport { + createdAt: number; + send(buf: Buffer, callback: SendCallback): void; + close(): void; + onError(listener: (err: Error) => void): void; + offError(listener: (err: Error) => void): void; + /** Emits 'error' on the socket, as hot-shots' `socket.emit('error')`. */ + emitError(err: Error): void; + onClose(listener: () => void): void; +} + +/** A socket's 'error' listeners, kept by the transport (the typed + * sockets have no removeListener): one socket listener dispatches to a + * snapshot, and an error nobody listens for throws, as an unhandled + * 'error' event does. */ +class ErrorListeners { + private listeners: ((err: Error) => void)[] = []; + add(listener: (err: Error) => void): void { + this.listeners.push(listener); + } + remove(listener: (err: Error) => void): void { + const index = this.listeners.indexOf(listener); + if (index !== -1) this.listeners.splice(index, 1); + } + emit(err: Error): void { + const snapshot = this.listeners.slice(); + if (snapshot.length === 0) throw err; + for (const listener of snapshot) listener(err); + } +} + +function addEol(buf: Buffer): string { + let msg = buf.toString(); + if (msg.length > 0 && msg[msg.length - 1] !== "\n") msg += "\n"; + return msg; +} + +class UdpTransport implements Transport { + createdAt = 0; + private readonly socket: dgram.Socket; + private readonly errors = new ErrorListeners(); + private resolvedAddress: string | undefined = undefined; + private resolvedAt = 0; + private readonly host: string | undefined; + private readonly port: number; + private readonly cacheDns: boolean; + private readonly cacheDnsTtl: number; + constructor(host: string | undefined, port: number, cacheDns: boolean, cacheDnsTtl: number) { + this.host = host; + this.port = port; + this.cacheDns = cacheDns; + this.cacheDnsTtl = cacheDnsTtl; + this.socket = dgram.createSocket("udp4"); + this.socket.unref(); + // The listener captures the list, not the transport: a socket that is + // never closed keeps its listener, and a capture of `this` would make + // a cycle the reference counts cannot free at exit. + const errors = this.errors; + this.socket.on("error", (err) => errors.emit(err)); + } + send(buf: Buffer, callback: SendCallback): void { + if (!this.cacheDns) { + this.socket.send(buf, this.port, this.host || "127.0.0.1", callback); + return; + } + const now = Date.now(); + const cached = this.resolvedAddress; + if (cached === undefined || now - this.resolvedAt > this.cacheDnsTtl) { + dns.lookup(this.host ?? "localhost", (error, address) => { + if (error) { + callback(error); + return; + } + this.resolvedAddress = address; + this.resolvedAt = now; + this.socket.send(buf, this.port, address, callback); + }); + } else { + this.socket.send(buf, this.port, cached, callback); + } + } + close(): void { + this.socket.close(); + } + onError(listener: (err: Error) => void): void { + this.errors.add(listener); + } + offError(listener: (err: Error) => void): void { + this.errors.remove(listener); + } + emitError(err: Error): void { + this.errors.emit(err); + } + onClose(listener: () => void): void { + this.socket.on("close", listener); + } +} + +class TcpTransport implements Transport { + createdAt = 0; + private readonly socket: net.Socket; + private readonly errors = new ErrorListeners(); + constructor(host: string | undefined, port: number) { + this.socket = net.connect(port, host ?? "localhost"); + this.socket.setKeepAlive(true); + this.socket.unref(); + // The listener captures the list, not the transport: a socket that is + // never closed keeps its listener, and a capture of `this` would make + // a cycle the reference counts cannot free at exit. + const errors = this.errors; + this.socket.on("error", (err) => errors.emit(err)); + } + send(buf: Buffer, callback: SendCallback): void { + // hot-shots writes the line with the 'ascii' encoding, which encodes + // strings as 'latin1' does. The callback runs once the data is written, + // so a message held back by a full socket buffer stays in flight. + this.socket.write(Buffer.from(addEol(buf), "latin1"), (err) => callback(err ?? null)); + } + close(): void { + this.socket.destroy(); + } + onError(listener: (err: Error) => void): void { + this.errors.add(listener); + } + offError(listener: (err: Error) => void): void { + this.errors.remove(listener); + } + emitError(err: Error): void { + this.errors.emit(err); + } + onClose(listener: () => void): void { + this.socket.on("close", () => listener()); + } +} + +// The runtime's AF_UNIX datagram calls (the unix-dgram addon's binding): +// results >= 0, or a negative errno; send answers 1 when it would block. +declare function scriptcUnixDgramSocket(): number; +declare function scriptcUnixDgramConnect(fd: number, path: string): number; +declare function scriptcUnixDgramSend(fd: number, data: Buffer): number; +declare function scriptcUnixDgramClose(fd: number): number; + +let unixDgramInstalled = false; + +/** Whether the unix-dgram addon is installed beside hot-shots (set by the + * entry module). */ +export function configureUnixDgram(installed: boolean): void { + unixDgramInstalled = installed; +} + +const UDS_PATH_DEFAULT = "/var/run/datadog/dsd.socket"; + +/** unix-dgram's errnoException: " " (the code is the + * negative errno; this Error's code field holds its decimal string). */ +function errnoException(errorno: number, syscall: string): Error { + const error: NodeJS.ErrnoException = new Error(`${syscall} ${errorno}`); + error.errno = errorno; + error.code = String(errorno); + error.syscall = syscall; + return error; +} + +/** hot-shots' uds transport over unix-dgram: a connected, non-blocking + * AF_UNIX datagram socket. Sends complete synchronously, as the addon's + * do. The addon polls the socket for reads, which holds the event loop + * until close; a ref'd timer stands in for that poll. */ +class UdsTransport implements Transport { + createdAt = 0; + private fd: number; + private readonly errors = new ErrorListeners(); + private readonly closeListeners: (() => void)[] = []; + private readonly stopHold: () => void; + constructor(path: string) { + const fd = scriptcUnixDgramSocket(); + if (fd < 0) throw errnoException(fd, "socket"); + this.fd = fd; + const hold = setInterval(() => {}, 2147483647); + this.stopHold = () => clearInterval(hold); + const err = scriptcUnixDgramConnect(fd, path); + if (err < 0) { + // The addon emits the connect failure as 'error' before anyone + // listens, which throws; hot-shots closes the socket and rethrows. + this.close(); + throw errnoException(err, "connect"); + } + } + send(buf: Buffer, callback: SendCallback): void { + const result = scriptcUnixDgramSend(this.fd, buf); + if (result < 0) { + callback(errnoException(result, "send")); + } else if (result === 1) { + const congestion: NodeJS.ErrnoException = new Error("congestion"); + congestion.code = "1"; + callback(congestion); + } else { + callback(null); + } + } + close(): void { + const result = scriptcUnixDgramClose(this.fd); + if (result < 0) throw errnoException(result, "close"); + this.fd = -1; + this.stopHold(); + for (const listener of this.closeListeners.slice()) listener(); + } + onError(listener: (err: Error) => void): void { + this.errors.add(listener); + } + offError(listener: (err: Error) => void): void { + this.errors.remove(listener); + } + emitError(err: Error): void { + this.errors.emit(err); + } + onClose(listener: () => void): void { + this.closeListeners.push(listener); + } +} + +/** hot-shots' createUdsTransport: without the unix-dgram addon the + * protocol reports it missing. */ +function createUdsTransport(path: string | undefined): Transport { + if (!unixDgramInstalled) { + throw new Error( + "The library `unix_dgram`, needed for the uds protocol to work, is not installed. " + + "You need to pick another protocol to use hot-shots. " + + "See the hot-shots README for additional details.", + ); + } + return new UdsTransport(path ? path : UDS_PATH_DEFAULT); +} + +function createTransport(client: StatsD): Transport | null { + let transport: Transport | null = null; + const protocol = client.protocol; + try { + if (protocol === PROTOCOL_TCP) { + transport = new TcpTransport(client.host, client.port); + } else if (protocol === PROTOCOL_UDS) { + transport = createUdsTransport(client.path); + } else if (protocol === PROTOCOL_UDP) { + transport = new UdpTransport(client.host, client.port, client.cacheDns, client.cacheDnsTtl); + } else { + throw new Error(`Unsupported protocol '${protocol}'`); + } + transport.createdAt = Date.now(); + } catch (e) { + const handler = client.errorHandler; + if (handler) { + handler(e as Error); + } else { + console.error(e); + } + } + return transport; +} + +// ── the client ─────────────────────────────────────────────────────────── + +class BufferHolder { + buffer = ""; +} + +/** What a child client inherits from its parent. */ +class ChildInit { + socket: Transport | null; + bufferHolder: BufferHolder; + dnsError: Error | undefined; + constructor(socket: Transport | null, bufferHolder: BufferHolder, dnsError: Error | undefined) { + this.socket = socket; + this.bufferHolder = bufferHolder; + this.dnsError = dnsError; + } +} + +export class StatsD { + protocol: string; + cacheDns: boolean; + cacheDnsTtl: number; + host: string | undefined; + port: number; + path: string | undefined; + prefix: string; + suffix: string; + tagPrefix: string; + tagSeparator: string; + mock: boolean; + globalTags: string[]; + telegraf: boolean; + maxBufferSize: number; + sampleRate: number; + bufferFlushInterval: number; + errorHandler: ((err: Error) => void) | undefined; + udsGracefulErrorHandling: boolean; + udsGracefulRestartRateLimit: number; + isChild: boolean; + closingFlushInterval: number; + mockBuffer: string[] | undefined = undefined; + messagesInFlight = 0; + CHECKS: DatadogChecks = { OK: 0, WARNING: 1, CRITICAL: 2, UNKNOWN: 3 }; + private bufferHolder: BufferHolder; + private transport: Transport | null = null; + private dnsError: Error | undefined = undefined; + private stopFlushInterval: (() => void) | undefined = undefined; + + constructor(options?: ClientOptions, child?: ChildInit) { + const o: ClientOptions = options ?? {}; + const protocol = o.protocol ? o.protocol.toLowerCase() : ""; + this.protocol = protocol ? protocol : PROTOCOL_UDP; + this.cacheDns = o.cacheDns === true; + this.cacheDnsTtl = o.cacheDnsTtl || CACHE_DNS_TTL_DEFAULT; + this.host = o.host || process.env["DD_AGENT_HOST"]; + this.port = o.port || parseInt(process.env["DD_DOGSTATSD_PORT"] ?? "", 10) || 8125; + this.path = o.path; + this.prefix = o.prefix || ""; + this.suffix = o.suffix || ""; + this.tagPrefix = o.tagPrefix || "#"; + this.tagSeparator = o.tagSeparator || ","; + this.mock = o.mock === true; + this.telegraf = o.telegraf || false; + const globalTags = o.globalTags; + this.globalTags = globalTags !== undefined ? formatTags(globalTags, this.telegraf) : []; + const entityId = process.env["DD_ENTITY_ID"]; + if (entityId) { + this.globalTags = this.globalTags.filter( + (item) => item.indexOf("dd.internal.entity_id:") !== 0, + ); + this.globalTags.push("dd.internal.entity_id:".concat(sanitizeTags(entityId, false))); + } + this.maxBufferSize = o.maxBufferSize || 0; + this.sampleRate = o.sampleRate || 1; + this.bufferFlushInterval = o.bufferFlushInterval || 1000; + this.bufferHolder = child !== undefined ? child.bufferHolder : new BufferHolder(); + this.errorHandler = o.errorHandler; + const graceful = o.udsGracefulErrorHandling; + this.udsGracefulErrorHandling = graceful === undefined ? true : graceful; + this.udsGracefulRestartRateLimit = + o.udsGracefulRestartRateLimit || UDS_DEFAULT_GRACEFUL_RESTART_LIMIT; + this.isChild = child !== undefined; + this.closingFlushInterval = o.closingFlushInterval || 50; + if (this.mock) this.mockBuffer = []; + if (child === undefined && this.maxBufferSize > 0) { + const handle = setInterval(() => this.onBufferFlushInterval(), this.bufferFlushInterval); + handle.unref(); + this.stopFlushInterval = () => clearInterval(handle); + } + if (child !== undefined) { + if (child.dnsError) this.dnsError = child.dnsError; + this.transport = child.socket; + } + if (!this.transport) this.transport = createTransport(this); + const handler = o.errorHandler; + const transport = this.transport; + if (transport !== null && child === undefined && handler) transport.onError(handler); + if (transport !== null && o.protocol === PROTOCOL_UDS) this.maybeAddUDSErrorHandler(); + } + + private maybeAddUDSErrorHandler(): void { + if (this.isChild || !this.udsGracefulErrorHandling) return; + const transport = this.transport; + if (transport !== null) transport.onError((err) => this.udsErrorHandler(err)); + } + + private udsErrorHandler(err: Error): void { + const code = Number((err as NodeJS.ErrnoException).code); + if (!UDS_ERROR_CODES.includes(-code)) return; + const socket = this.transport; + if (socket === null) return; + if (!socket.createdAt || Date.now() - socket.createdAt < this.udsGracefulRestartRateLimit) { + return; + } + const handler = this.errorHandler; + if (handler) socket.offError(handler); + const newSocket = createTransport(this); + if (newSocket === null) { + const errorMessage = "Could not replace UDS connection with new socket"; + if (handler) { + handler(new Error(errorMessage)); + } else { + console.error(errorMessage); + } + return; + } + socket.close(); + this.transport = newSocket; + this.maybeAddUDSErrorHandler(); + if (handler) { + newSocket.onError(handler); + } else { + newSocket.onError((error) => console.error(`hot-shots UDS error: ${String(error)}`)); + } + } + + // ── stats functions ── + + timing( + stat: string | string[], + time: number, + sampleRate?: number, + tags?: Tags, + callback?: StatsCb, + ): void; + timing(stat: string | string[], time: number, tags?: Tags, callback?: StatsCb): void; + timing(stat: string | string[], time: number, callback?: StatsCb): void; + timing(stat: string | string[], time: number, sampleRate?: number, callback?: StatsCb): void; + timing( + stat: string | string[], + time: number, + sampleRate?: SampleArg, + tags?: TagsArg, + callback?: StatsCb, + ): void { + this.sendAll(stat, time, "ms", sampleRate, tags, callback); + } + + increment(stat: string, tags?: Tags): void; + increment( + stat: string | string[], + value: number, + sampleRate?: number, + tags?: Tags, + callback?: StatsCb, + ): void; + increment(stat: string | string[], value: number, tags?: Tags, callback?: StatsCb): void; + increment(stat: string | string[], value: number, callback?: StatsCb): void; + increment(stat: string | string[], value: number, sampleRate?: number, callback?: StatsCb): void; + increment( + stat: string | string[], + value?: number | Tags, + sampleRate?: SampleArg, + tags?: TagsArg, + callback?: StatsCb, + ): void { + // A non-number second argument of a two-argument call is the tags. + let amount = 1; + let tagArg: TagsArg = tags; + if (typeof value === "number") { + amount = value; + } else if (sampleRate === undefined && tags === undefined && callback === undefined) { + tagArg = value; + } + this.sendAll(stat, amount, "c", sampleRate, tagArg, callback); + } + + decrement(stat: string, tags?: Tags): void; + decrement( + stat: string | string[], + value: number, + sampleRate?: number, + tags?: Tags, + callback?: StatsCb, + ): void; + decrement(stat: string | string[], value: number, tags?: Tags, callback?: StatsCb): void; + decrement(stat: string | string[], value: number, callback?: StatsCb): void; + decrement(stat: string | string[], value: number, sampleRate?: number, callback?: StatsCb): void; + decrement( + stat: string | string[], + value?: number | Tags, + sampleRate?: SampleArg, + tags?: TagsArg, + callback?: StatsCb, + ): void { + let amount = 1; + let tagArg: TagsArg = tags; + if (typeof value === "number") { + amount = value; + } else if (sampleRate === undefined && tags === undefined && callback === undefined) { + tagArg = value; + } + this.sendAll(stat, -amount, "c", sampleRate, tagArg, callback); + } + + histogram( + stat: string | string[], + value: number, + sampleRate?: number, + tags?: Tags, + callback?: StatsCb, + ): void; + histogram(stat: string | string[], value: number, tags?: Tags, callback?: StatsCb): void; + histogram(stat: string | string[], value: number, callback?: StatsCb): void; + histogram(stat: string | string[], value: number, sampleRate?: number, callback?: StatsCb): void; + histogram( + stat: string | string[], + value: number, + sampleRate?: SampleArg, + tags?: TagsArg, + callback?: StatsCb, + ): void { + this.sendAll(stat, value, "h", sampleRate, tags, callback); + } + + distribution( + stat: string | string[], + value: number, + sampleRate?: number, + tags?: Tags, + callback?: StatsCb, + ): void; + distribution(stat: string | string[], value: number, tags?: Tags, callback?: StatsCb): void; + distribution(stat: string | string[], value: number, callback?: StatsCb): void; + distribution( + stat: string | string[], + value: number, + sampleRate?: number, + callback?: StatsCb, + ): void; + distribution( + stat: string | string[], + value: number, + sampleRate?: SampleArg, + tags?: TagsArg, + callback?: StatsCb, + ): void { + this.sendAll(stat, value, "d", sampleRate, tags, callback); + } + + gauge( + stat: string | string[], + value: number, + sampleRate?: number, + tags?: Tags, + callback?: StatsCb, + ): void; + gauge(stat: string | string[], value: number, tags?: Tags, callback?: StatsCb): void; + gauge(stat: string | string[], value: number, callback?: StatsCb): void; + gauge(stat: string | string[], value: number, sampleRate?: number, callback?: StatsCb): void; + gauge( + stat: string | string[], + value: number, + sampleRate?: SampleArg, + tags?: TagsArg, + callback?: StatsCb, + ): void { + this.sendAll(stat, value, "g", sampleRate, tags, callback); + } + + set( + stat: string | string[], + value: number | string, + sampleRate?: number, + tags?: Tags, + callback?: StatsCb, + ): void; + set(stat: string | string[], value: number | string, tags?: Tags, callback?: StatsCb): void; + set(stat: string | string[], value: number | string, callback?: StatsCb): void; + set( + stat: string | string[], + value: number | string, + sampleRate?: number, + callback?: StatsCb, + ): void; + set( + stat: string | string[], + value: number | string, + sampleRate?: SampleArg, + tags?: TagsArg, + callback?: StatsCb, + ): void { + this.sendAll(stat, value, "s", sampleRate, tags, callback); + } + + unique( + stat: string | string[], + value: number | string, + sampleRate?: number, + tags?: Tags, + callback?: StatsCb, + ): void; + unique(stat: string | string[], value: number | string, tags?: Tags, callback?: StatsCb): void; + unique(stat: string | string[], value: number | string, callback?: StatsCb): void; + unique( + stat: string | string[], + value: number | string, + sampleRate?: number, + callback?: StatsCb, + ): void; + unique( + stat: string | string[], + value: number | string, + sampleRate?: SampleArg, + tags?: TagsArg, + callback?: StatsCb, + ): void { + this.sendAll(stat, value, "s", sampleRate, tags, callback); + } + + check( + name: string, + status: DatadogChecksValues, + options?: CheckOptions, + tags?: Tags | StatsCb, + callback?: StatsCb, + ): void { + if (this.telegraf) { + const err = new Error("Not supported by Telegraf / InfluxDB"); + if (callback) return callback(err); + const handler = this.errorHandler; + if (handler) return handler(err); + throw err; + } + const check: string[] = ["_sc", this.prefix + name + this.suffix, String(status)]; + const metadata: CheckOptions = options ?? {}; + const happened = metadata.date_happened; + if (happened) { + const timestamp = formatDate(happened); + if (timestamp) check.push(`d:${timestamp}`); + } + if (metadata.hostname) check.push(`h:${metadata.hostname}`); + let mergedTags = this.globalTags; + if (tags !== undefined && typeof tags !== "function") { + mergedTags = overrideTags(mergedTags, tags, this.telegraf); + } + if (mergedTags.length > 0) check.push(`#${mergedTags.join(",")}`); + if (metadata.message) check.push(`m:${metadata.message}`); + let cb = callback; + if (typeof tags === "function" && callback === undefined) cb = tags; + this.sendRaw(check.join("|"), cb); + } + + event( + title: string, + text?: string, + options?: EventOptions, + tags?: Tags | StatsCb, + callback?: StatsCb, + ): void { + if (this.telegraf) { + const err = new Error("Not supported by Telegraf / InfluxDB"); + if (callback) return callback(err); + const handler = this.errorHandler; + if (handler) return handler(err); + throw err; + } + const msgTitle = String(title ? title : ""); + let msgText = String(text ? text : msgTitle); + msgText = msgText.replace(/\n/g, "\\n"); + let message = `_e{${msgTitle.length},${msgText.length}}:${msgTitle}|${msgText}`; + if (options) { + const happened = options.date_happened; + if (happened) { + const timestamp = formatDate(happened); + if (timestamp) message += `|d:${timestamp}`; + } + if (options.hostname) message += `|h:${options.hostname}`; + if (options.aggregation_key) message += `|k:${options.aggregation_key}`; + if (options.priority) message += `|p:${options.priority}`; + if (options.source_type_name) message += `|s:${options.source_type_name}`; + if (options.alert_type) message += `|t:${options.alert_type}`; + } + let cb = callback; + let tagList: Tags | undefined = undefined; + if (typeof tags === "function") { + if (callback === undefined) cb = tags; + } else { + tagList = tags; + } + this.send(message, tagList, cb); + } + + // ── sending ── + + private sendAll( + stat: string | string[], + value: number | string, + type: string, + sampleRateArg: SampleArg, + tagsArg: TagsArg, + callbackArg: StatsCb | undefined, + ): void { + let sampleRate: number | undefined = undefined; + let tags: Tags | undefined = undefined; + let callback: StatsCb | undefined = callbackArg; + if (typeof sampleRateArg === "number") { + sampleRate = sampleRateArg; + if (typeof tagsArg === "function") { + callback = tagsArg; + } else { + tags = tagsArg; + } + } else if (sampleRateArg !== undefined) { + // A non-number sample rate shifts into the tags, and the tags + // argument into the callback. + if (typeof sampleRateArg === "function") { + callback = sampleRateArg; + } else { + tags = sampleRateArg; + callback = typeof tagsArg === "function" ? tagsArg : undefined; + } + } else if (typeof tagsArg === "function") { + callback = tagsArg; + } else { + tags = tagsArg; + } + + if (!Array.isArray(stat)) { + this.sendStat(stat, value, type, sampleRate, tags, callback); + return; + } + let completed = 0; + let calledback = false; + let sentBytes = 0; + const count = stat.length; + const onSend: StatsCb = (error, bytes) => { + completed += 1; + if (calledback) return; + if (error) { + if (callback !== undefined) { + calledback = true; + callback(error); + } else { + const handler = this.errorHandler; + if (handler) { + calledback = true; + handler(error); + } + } + return; + } + if (bytes) sentBytes += bytes as number; + if (completed === count && callback !== undefined) callback(null, sentBytes); + }; + for (const item of stat) this.sendStat(item, value, type, sampleRate, tags, onSend); + } + + private sendStat( + stat: string, + value: number | string, + type: string, + sampleRateArg: number | undefined, + tags: Tags | undefined, + callback: StatsCb | undefined, + ): void { + let message = `${this.prefix + stat + this.suffix}:${value}|${type}`; + const sampleRate = sampleRateArg || this.sampleRate; + if (sampleRate && sampleRate < 1) { + if (Math.random() < sampleRate) { + message += `|@${sampleRate}`; + } else { + if (callback) callback(undefined); + return; + } + } + this.send(message, tags, callback); + } + + private send(message: string, tags: Tags | undefined, callback: StatsCb | undefined): void { + let mergedTags = this.globalTags; + if (tags !== undefined) mergedTags = overrideTags(mergedTags, tags, this.telegraf); + if (mergedTags.length > 0) { + if (this.telegraf) { + const parts = message.split(":"); + message = `${parts[0]!},${mergedTags.join(",").replace(/:/g, "=")}:${parts.slice(1).join(":")}`; + } else { + message += `|${this.tagPrefix}${mergedTags.join(this.tagSeparator)}`; + } + } + this.sendRaw(message, callback); + } + + /** hot-shots' `_send`: the message with its tags. */ + private sendRaw(message: string, callback: StatsCb | undefined): void { + const dnsError = this.dnsError; + if (dnsError) { + if (callback) return callback(dnsError); + const handler = this.errorHandler; + if (handler) return handler(dnsError); + throw dnsError; + } + if (!this.mock) { + if (this.maxBufferSize === 0) { + this.sendMessage(message, callback); + } else { + this.enqueue(message, callback); + } + } else { + const buffer = this.mockBuffer; + if (buffer !== undefined) buffer.push(message); + if (callback) callback(null, 0); + } + } + + private enqueue(message: string, callback: StatsCb | undefined): void { + message += "\n"; + if (this.bufferHolder.buffer.length + message.length > this.maxBufferSize) { + this.flushQueue(callback); + this.bufferHolder.buffer += message; + } else { + this.bufferHolder.buffer += message; + if (callback) callback(null); + } + } + + private flushQueue(callback?: StatsCb): void { + this.sendMessage(this.bufferHolder.buffer, callback); + this.bufferHolder.buffer = ""; + } + + private sendMessage(message: string, callback: StatsCb | undefined): void { + if (message === "") { + if (callback) callback(null); + return; + } + const socketWasMissing = this.transport === null; + if (socketWasMissing && this.protocol === PROTOCOL_UDS) { + this.transport = createTransport(this); + if (this.transport !== null) this.maybeAddUDSErrorHandler(); + } + const socket = this.transport; + if (socketWasMissing || socket === null) { + const error = new Error("Socket not created properly. Check previous errors for details."); + if (callback) return callback(error); + const handler = this.errorHandler; + if (handler) return handler(error); + console.error(String(error)); + return; + } + const handleCallback = (err: Error | null, bytes?: number): void => { + this.messagesInFlight--; + let errFormatted: Error | null = null; + if (err) { + errFormatted = errorWithCode( + `Error sending hot-shots message: ${String(err)}`, + (err as NodeJS.ErrnoException).code, + ); + if (this.protocol === PROTOCOL_UDS && (callback || this.errorHandler)) { + this.udsErrorHandler(err); + } + } + if (callback) { + callback(errFormatted, bytes); + } else if (errFormatted) { + const handler = this.errorHandler; + if (handler) { + handler(errFormatted); + } else { + console.error(String(errFormatted)); + // hot-shots also emits the error on the current socket, where the + // uds reconnection handler listens; with no listener it throws. + const current = this.transport; + if (current !== null) current.emitError(errFormatted); + } + } + }; + try { + this.messagesInFlight++; + socket.send(Buffer.from(message), handleCallback); + } catch (err) { + handleCallback(err as Error); + } + } + + private onBufferFlushInterval(): void { + this.flushQueue(); + } + + close(callback?: (error?: Error) => void): void { + const stop = this.stopFlushInterval; + if (stop !== undefined) stop(); + this.flushQueue((err) => { + if (err) { + if (callback) return callback(err); + logError(err); + return; + } + let intervalAttempts = 0; + const waitForMessages = setInterval(() => { + intervalAttempts++; + if (intervalAttempts > 10) { + console.log("hot-shots could not clear out messages in flight but closing anyways"); + this.messagesInFlight = 0; + } + if (this.messagesInFlight <= 0) { + clearInterval(waitForMessages); + this.closeSocket(callback); + } + }, this.closingFlushInterval); + }); + } + + private closeSocket(callback: ((error?: Error) => void) | undefined): void { + let handledError = false; + const handleErr = (err: unknown): void => { + const errMessage = `Error closing hot-shots socket: ${String(err)}`; + if (handledError) { + console.error(errMessage); + } else { + handledError = true; + if (callback) { + callback(new Error(errMessage)); + } else { + const handler = this.errorHandler; + if (handler) { + handler(new Error(errMessage)); + } else { + console.error(errMessage); + } + } + } + }; + const socket = this.transport; + if (socket === null) { + handleErr(new TypeError("Cannot read properties of null (reading 'removeListener')")); + return; + } + const handler = this.errorHandler; + if (handler) socket.offError(handler); + socket.onError(handleErr); + if (callback) { + socket.onClose(() => { + if (!handledError) callback(undefined); + }); + } + try { + socket.close(); + } catch (err) { + handleErr(err); + } + } + + childClient(options?: ChildClientOptions): StatsD { + const o: ChildClientOptions = options ?? {}; + const childTags = o.globalTags; + return new StatsD( + { + isChild: true, + errorHandler: o.errorHandler || this.errorHandler, + host: this.host, + port: this.port, + tagPrefix: this.tagPrefix, + tagSeparator: this.tagSeparator, + prefix: (o.prefix || "") + this.prefix, + suffix: this.suffix + (o.suffix || ""), + globalize: false, + mock: this.mock, + globalTags: + childTags !== undefined + ? overrideTags(this.globalTags, childTags, this.telegraf) + : this.globalTags, + maxBufferSize: this.maxBufferSize, + bufferFlushInterval: this.bufferFlushInterval, + telegraf: this.telegraf, + protocol: this.protocol === "tcp" ? "tcp" : this.protocol === "uds" ? "uds" : "udp", + closingFlushInterval: this.closingFlushInterval, + }, + new ChildInit(this.transport, this.bufferHolder, this.dnsError), + ); + } +} + +export default StatsD; diff --git a/packages/compiler/shims/hot-shots/v8-unix-dgram.ts b/packages/compiler/shims/hot-shots/v8-unix-dgram.ts new file mode 100644 index 000000000..f4bfb180e --- /dev/null +++ b/packages/compiler/shims/hot-shots/v8-unix-dgram.ts @@ -0,0 +1,8 @@ +// The hot-shots 8.x shim for installations with the optional unix-dgram +// addon: the uds protocol sends through a native Unix datagram socket. +import { configureUnixDgram } from "./client.ts"; + +configureUnixDgram(true); + +export * from "./client.ts"; +export { default } from "./client.ts"; diff --git a/packages/compiler/shims/hot-shots/v8.ts b/packages/compiler/shims/hot-shots/v8.ts new file mode 100644 index 000000000..0d1871170 --- /dev/null +++ b/packages/compiler/shims/hot-shots/v8.ts @@ -0,0 +1,8 @@ +// The hot-shots 8.x shim for installations without the optional unix-dgram +// addon: the uds protocol reports it missing, as hot-shots does under Node. +import { configureUnixDgram } from "./client.ts"; + +configureUnixDgram(false); + +export * from "./client.ts"; +export { default } from "./client.ts"; diff --git a/packages/compiler/src/backend/cycle-analysis.test.ts b/packages/compiler/src/backend/cycle-analysis.test.ts index c78420f73..340ffa8f9 100644 --- a/packages/compiler/src/backend/cycle-analysis.test.ts +++ b/packages/compiler/src/backend/cycle-analysis.test.ts @@ -17,6 +17,7 @@ import { } from "../ir/ir.js"; import { computeTraced, explainCycle } from "./cycle-analysis.js"; import { computeTraced as llvmTraced } from "./llvm/shapes.js"; +import { addRecordResultEntries } from "./llvm/record-results.js"; const loc = { file: "cycles.ts", start: 0, end: 1 }; function module(): IrModule { @@ -404,6 +405,61 @@ test("a later write through any alias makes the edge mutable", () => { checkExact(record, ["record:list"]); }); +test("a result-slot entry's stores into its destination are not writes", () => { + const next: IrType = { kind: "union", unionId: "next" }; + const listModule = (): IrModule => { + const mod = module(); + mod.records = [shape("list", [next, F64])]; + mod.unions = [{ id: "next", arms: [ref("list"), { kind: "nullT" }] }]; + mod.functions.push({ + name: "cell", + params: [{ localId: "rest", name: "rest", type: next }], + locals: [], + returnType: ref("list"), + body: [ + { + kind: "return", + value: { + kind: "recordLit", + fields: [ + { name: "field0", value: { kind: "varRef", localId: "rest", type: next, loc } }, + { name: "field1", value: { kind: "numLit", value: 1, type: F64, loc } }, + ], + type: ref("list"), + loc, + }, + loc, + }, + ], + loc, + }); + return addRecordResultEntries(mod); + }; + // The entry stores the literal's fields into caller frame storage that + // nothing can point to: the list stays acyclic. + const entries = listModule(); + expect(entries.functions.map((fn) => fn.name)).toContain("%into.cell"); + checkExact(entries, []); + // The same store into the destination's local id outside an entry, and a + // store into any other binding of the shape inside one, are writes. + const store = (localId: string): IrStmt => ({ + kind: "recordSet", + obj: { kind: "varRef", localId, type: ref("list"), loc }, + shapeId: "list", + field: "field0", + value: value(next), + loc, + }); + for (const [fn, localId] of [ + ["main", "%into.dst"], + ["%into.cell", "v"], + ] as const) { + const written = listModule(); + written.functions.find((f) => f.name === fn)!.body.unshift(store(localId)); + checkExact(written, ["record:list"], ["next"]); + } +}); + test("field increments count as writes", () => { const mod = tree(); mod.functions[0]!.body.push({ diff --git a/packages/compiler/src/backend/cycle-analysis.ts b/packages/compiler/src/backend/cycle-analysis.ts index aa624579f..fbd96e854 100644 --- a/packages/compiler/src/backend/cycle-analysis.ts +++ b/packages/compiler/src/backend/cycle-analysis.ts @@ -11,7 +11,7 @@ import { STRING, VOID, } from "../ir/ir.js"; -import { computeCycleMutability, fieldKey } from "./cycle-mutability.js"; +import { type CycleMutability, computeCycleMutability, fieldKey } from "./cycle-mutability.js"; /** Cycle capability for native code generation. * Nodes are shape units and unions; edges are the references their fields @@ -38,8 +38,10 @@ import { computeCycleMutability, fieldKey } from "./cycle-mutability.js"; export function computeTraced( mod: IrModule, stores?: DynamicFieldStores, + /** computeCycleMutability's answer for this module, when the caller has it. */ + precomputed?: CycleMutability, ): { shapes: Set; unions: Set } { - const { shapes, unions } = analyzeCycles(mod, false, stores); + const { shapes, unions } = analyzeCycles(mod, false, stores, precomputed); return { shapes, unions }; } @@ -93,6 +95,7 @@ function analyzeCycles( mod: IrModule, labels: boolean, stores?: DynamicFieldStores, + precomputed?: CycleMutability, ): { shapes: Set; unions: Set; @@ -125,7 +128,7 @@ function analyzeCycles( const lifetimeRoots = new Set(mod.contracts?.programLifetime ?? []); const programLifetime = (className: string): boolean => lifetimeRoots.size > 0 && lifetimeRoots.has(rootOf(className)); - const mutability = computeCycleMutability(mod, unitOfClass, stores); + const mutability = precomputed ?? computeCycleMutability(mod, unitOfClass, stores); const shapeDefs = [ ...classes.map((c) => ({ key: `object:${c.name}`, diff --git a/packages/compiler/src/backend/cycle-mutability.ts b/packages/compiler/src/backend/cycle-mutability.ts index 78daa6204..541a1312f 100644 --- a/packages/compiler/src/backend/cycle-mutability.ts +++ b/packages/compiler/src/backend/cycle-mutability.ts @@ -2,6 +2,7 @@ import type { IrExpr, IrFunction, IrModule, IrStmt, IrType } from "../ir/ir.js"; import { RUNTIME_EMITTER_CLASS, RUNTIME_STREAM_CLASSES, typeKey } from "../ir/ir.js"; import { dynamicFieldStores, type DynamicFieldStores } from "../ir/int32-slots.js"; import { everyExprChild, everyStmtChild, everyTypeChild } from "../ir/traverse.js"; +import { resultSlotStore } from "./result-slots.js"; /** Which shape fields can be written after their object escapes. * @@ -17,6 +18,10 @@ import { everyExprChild, everyStmtChild, everyTypeChild } from "../ir/traverse.j * - every `fieldSet` outside a constructor's own `this`, `fieldIncDec`, and * `recordSet` makes its (unit, field) mutable; `recordKeySet` on declared * fields and `recordKeyDelete` make the whole record mutable; + * - a result-slot entry's stores into its destination (result-slots.ts) are + * not writes: the destination is frame storage of a caller that only + * projects the value, so no object can point to it and its fields cannot + * lie on a cycle; * - a constructor's stores into its own `this` are construction-only up to * the first top-level statement in which `this` escapes (any use other * than a field store target, a field read, or the receiver of the direct @@ -69,6 +74,22 @@ export function fieldKey(unit: string, field: string): string { return `${unit}\0${field}`; } +/** The cycle unit of a class: `object:`, the root of its hierarchy, + * as computeImmutableFields and computeTraced group classes. */ +export function hierarchyUnitOfClass(mod: IrModule): (className: string) => string { + const baseOf = new Map((mod.classes ?? []).map((c) => [c.name, c.base ?? null] as const)); + const roots = new Map(); + return (name) => { + const known = roots.get(name); + if (known !== undefined) return `object:${known}`; + let cur = name; + for (let base = baseOf.get(cur); base !== null && base !== undefined; base = baseOf.get(cur)) + cur = base; + roots.set(name, cur); + return `object:${cur}`; + }; +} + export function computeCycleMutability( mod: IrModule, unitOfClass: (className: string) => string, @@ -296,7 +317,8 @@ export function computeCycleMutability( result.fields.add(fieldKey(unitOfClass(s.className), s.field)); break; case "recordSet": - result.fields.add(fieldKey(`record:${s.shapeId}`, s.field)); + if (!resultSlotStore(fn.name, s)) + result.fields.add(fieldKey(`record:${s.shapeId}`, s.field)); break; case "recordKeySet": if (s.overflowOnly !== true) result.units.add(`record:${s.shapeId}`); diff --git a/packages/compiler/src/backend/executable-features.ts b/packages/compiler/src/backend/executable-features.ts index f7cae8508..672fddd96 100644 --- a/packages/compiler/src/backend/executable-features.ts +++ b/packages/compiler/src/backend/executable-features.ts @@ -56,6 +56,9 @@ export function executableLinkFeatures(mod: IrModule): NativeLinkFeatures { tlsCa: features.tlsCa, cipher: features.cipher, ecdh: features.ecdh, + dh: features.dh, + pki: features.pki, + ed25519: features.ed25519, webcrypto: features.webcrypto, perfLoop: features.perfLoop, }; diff --git a/packages/compiler/src/backend/immutability.ts b/packages/compiler/src/backend/immutability.ts index 6c37731e3..21380de8f 100644 --- a/packages/compiler/src/backend/immutability.ts +++ b/packages/compiler/src/backend/immutability.ts @@ -48,6 +48,8 @@ export class ImmutableFields { export function computeImmutableFields( mod: IrModule, stores?: DynamicFieldStores, + /** computeCycleMutability's answer for this module, when the caller has it. */ + precomputed?: CycleMutability, ): ImmutableFields | null { if (mod.lib !== undefined) return null; const baseOf = new Map((mod.classes ?? []).map((c) => [c.name, c.base ?? null] as const)); @@ -62,7 +64,7 @@ export function computeImmutableFields( return cur; }; const unitOfClass = (name: string): string => `object:${rootOf(name)}`; - const mutability = computeCycleMutability(mod, unitOfClass, stores); + const mutability = precomputed ?? computeCycleMutability(mod, unitOfClass, stores); return mutability.all ? null : new ImmutableFields(mutability, unitOfClass); } @@ -213,6 +215,9 @@ export function stableGlobals(mod: IrModule): Set { } return everyStmtChild(s, expr, stmt); }; - for (const fn of mod.functions) fn.body.every(stmt); + for (const fn of mod.functions) { + if (candidates.size === 0) break; + fn.body.every(stmt); + } return candidates; } diff --git a/packages/compiler/src/backend/library-pack.ts b/packages/compiler/src/backend/library-pack.ts index 805198df1..e9f52f7a0 100644 --- a/packages/compiler/src/backend/library-pack.ts +++ b/packages/compiler/src/backend/library-pack.ts @@ -60,6 +60,9 @@ export async function compilePackedLibrary( tls: false, cipher: false, ecdh: false, + dh: false, + pki: false, + ed25519: false, webcrypto: false, perfLoop: false, tlsCa: false, diff --git a/packages/compiler/src/backend/llvm/appended-array-literals.ts b/packages/compiler/src/backend/llvm/appended-array-literals.ts index 1d4577ae6..09a2976de 100644 --- a/packages/compiler/src/backend/llvm/appended-array-literals.ts +++ b/packages/compiler/src/backend/llvm/appended-array-literals.ts @@ -85,6 +85,7 @@ export function findAppendedArrayLiterals(module: IrModule): ReadonlySet for (const field of fieldAliases.get(binding) ?? []) appendedFields.add(field); const result = new Set(); + if (appendedBindings.size === 0 && appendedFields.size === 0) return result; const consider = (value: IrExpr | null, appended: boolean): void => { if (value && appended && isEmptyLiteral(value)) result.add(value); }; diff --git a/packages/compiler/src/backend/llvm/array-search.ts b/packages/compiler/src/backend/llvm/array-search.ts index d61d91e5c..41b64d418 100644 --- a/packages/compiler/src/backend/llvm/array-search.ts +++ b/packages/compiler/src/backend/llvm/array-search.ts @@ -10,6 +10,8 @@ * SameValueZero are both pointer identity (class instances, records, * arrays, maps, sets, typed arrays): 64-bit compares, four slots per * branch. + * - sc_arr_index_of_cref, the same over the 4-byte slots of compact class + * references (SCR_ELEM_CREF), against the needle's 32-bit reference. * - sc_arr_index_of_str, for strings: pointer identity, then the length, * then the bytes. Strings of up to 16 bytes compare as two words; a short * string's word is the eight bytes ending at its last byte, which start @@ -26,10 +28,12 @@ import type { IrType } from "../../ir/ir.js"; import { SCR_ARR_FIELD } from "./common.js"; import { FN_ATTRS } from "./shapes.js"; -export type ArraySearchKind = "ptr" | "str"; +export type ArraySearchKind = "ptr" | "cref" | "str"; -/** The inline search for arrays of `elem`, or null for the runtime search. */ -export function arraySearchKind(elem: IrType): ArraySearchKind | null { +/** The inline search for arrays of `elem`, or null for the runtime search. + * `compact`: the arrays hold compact class references (SCR_ELEM_CREF). */ +export function arraySearchKind(elem: IrType, compact: boolean): ArraySearchKind | null { + if (compact) return elem.kind === "object" ? "cref" : null; switch (elem.kind) { case "object": case "record": @@ -46,7 +50,7 @@ export function arraySearchKind(elem: IrType): ArraySearchKind | null { } export function arraySearchHelperName(kind: ArraySearchKind): string { - return kind === "ptr" ? "sc_arr_index_of_ptr" : "sc_arr_index_of_str"; + return `sc_arr_index_of_${kind}`; } /** The definitions of the helpers in `kinds`; they declare their slow paths @@ -76,9 +80,18 @@ export function emitArraySearchHelpers( ` %dp = getelementptr inbounds %ScrArr, ptr %a, i32 0, i32 ${SCR_ARR_FIELD.data}`, ` %data = load ptr, ptr %dp`, ); - if (kind === "ptr") { + if (kind === "ptr" || kind === "cref") { + // A compact reference is the address over 8 (classes.ts + // compactRefLoadLines). + const slot = kind === "ptr" ? "i64" : "i32"; defs.push( - ` %needle = ptrtoint ptr %v to i64`, + ...(kind === "ptr" + ? [` %needle = ptrtoint ptr %v to i64`] + : [ + ` %vaddr = ptrtoint ptr %v to i64`, + ` %vref = lshr i64 %vaddr, 3`, + ` %needle = trunc i64 %vref to i32`, + ]), // Four slots per step with one branch, then one at a time. ` br label %quad`, `quad:`, @@ -89,9 +102,9 @@ export function emitArraySearchHelpers( `quadbody:`, ...[0, 1, 2, 3].flatMap((k) => [ ` %qi${k} = add ${sz} %q, ${k}`, - ` %qp${k} = getelementptr inbounds i64, ptr %data, ${sz} %qi${k}`, - ` %qs${k} = load i64, ptr %qp${k}`, - ` %qh${k} = icmp eq i64 %qs${k}, %needle`, + ` %qp${k} = getelementptr inbounds ${slot}, ptr %data, ${sz} %qi${k}`, + ` %qs${k} = load ${slot}, ptr %qp${k}`, + ` %qh${k} = icmp eq ${slot} %qs${k}, %needle`, ]), ` %qh01 = or i1 %qh0, %qh1`, ` %qh23 = or i1 %qh2, %qh3`, @@ -107,9 +120,9 @@ export function emitArraySearchHelpers( ` %done = icmp eq ${sz} %i, %len`, ` br i1 %done, label %miss, label %body`, `body:`, - ` %sp = getelementptr inbounds i64, ptr %data, ${sz} %i`, - ` %s = load i64, ptr %sp`, - ` %hit = icmp eq i64 %s, %needle`, + ` %sp = getelementptr inbounds ${slot}, ptr %data, ${sz} %i`, + ` %s = load ${slot}, ptr %sp`, + ` %hit = icmp eq ${slot} %s, %needle`, ` br i1 %hit, label %found, label %cont`, ); } else { diff --git a/packages/compiler/src/backend/llvm/blocks.ts b/packages/compiler/src/backend/llvm/blocks.ts index 6d22bf3bf..354e631c6 100644 --- a/packages/compiler/src/backend/llvm/blocks.ts +++ b/packages/compiler/src/backend/llvm/blocks.ts @@ -95,8 +95,8 @@ export class BlockBuilder { this.terminate(`br label %${label}`); } - condBr(v: string, t: string, f: string): void { - this.terminate(`br i1 ${v}, label %${t}, label %${f}`); + condBr(v: string, t: string, f: string, attachment = ""): void { + this.terminate(`br i1 ${v}, label %${t}, label %${f}${attachment}`); } /** Emit a double-indexed `for (i = 0; i < len; i++)` loop. `next` is diff --git a/packages/compiler/src/backend/llvm/byte-windows.ts b/packages/compiler/src/backend/llvm/byte-windows.ts index 5fffa1428..9741cc547 100644 --- a/packages/compiler/src/backend/llvm/byte-windows.ts +++ b/packages/compiler/src/backend/llvm/byte-windows.ts @@ -43,6 +43,7 @@ export function findInitializedByteLoopBindings( if (stmt.init) list([stmt.init], inner); list(stmt.body, inner); } + if (stmt.kind === "while") entries.set(stmt, new Set(known)); if (stmt.kind === "while" || stmt.kind === "doWhile") list(stmt.body, new Set(known)); } } diff --git a/packages/compiler/src/backend/llvm/bytes-loop-versions.test.ts b/packages/compiler/src/backend/llvm/bytes-loop-versions.test.ts index 3fbc01cc5..cee91c66d 100644 --- a/packages/compiler/src/backend/llvm/bytes-loop-versions.test.ts +++ b/packages/compiler/src/backend/llvm/bytes-loop-versions.test.ts @@ -99,6 +99,7 @@ function match( f: IrFunction, loop: IrStmt & { kind: "for" }, captured: string[] = [], + scalarStrings: string[] = [], ): BytesLoopVersion | null { const ranges = analyzeIntegerRanges(f); const locals = new Map(f.locals.map((l) => [l.id, l])); @@ -111,6 +112,7 @@ function match( proven: new Set(), workers: false, owned: new Set(), + scalarStrings: new Set(scalarStrings), }); } @@ -134,6 +136,39 @@ test("a counted loop's affine accesses get one guard and exact operand ranges", expect(version.ranges.get(shifted)).toEqual({ min: 1, max: Number.MAX_SAFE_INTEGER }); }); +test("invariant terms without a range are tested by the guard", () => { + // for (let i = 0; i < n; i++) out[i] = src[k + i], with `k` a parameter + const shifted = bin("+", ref("k"), ref("i")); + const loop = counted([set(ref("out", f64s), ref("i"), get(ref("src", f64s), shifted))]); + const kernel = fn([loop]); + const version = match(kernel, loop)!; + expect([...version.guarded]).toEqual(["v1:k"]); + expect(version.affine.map((c) => c.terms.map((t) => t.key))).toEqual([[], ["v1:k"]]); + // In the fast copy the term has the range the guard tests. + expect(version.ranges.get(shifted.kind === "bin" ? shifted.left : shifted)).toEqual({ + min: -(2 ** 32), + max: 2 ** 32, + }); + const mod: IrModule = { + irVersion: 17, + sourceFile: loc.file, + entry: "__main", + functions: [ + { name: "__main", params: [], returnType: VOID, locals: [], body: [], loc }, + kernel, + ], + }; + const body = /^define internal [^\n]*@sc_bf_kernel[^]*?^}/m.exec(emitLlvmModule(mod))![0]; + const guard = body.slice(0, body.search(/^bytes\.version\.(fast|slow)\d+:$/m)); + // -2^32 <= k <= 2^32, and k is the double of its frozen integer. + expect(guard).toMatch(/fcmp oge double %\S+, 0xC1F0000000000000/); + expect(guard).toMatch(/fcmp ole double %\S+, 0x41F0000000000000/); + expect(guard).toMatch(/freeze i64/); + const fast = /^bytes\.version\.fast\d+:$[^]*?^bytes\.version\.done\d+:$/m.exec(body)![0]; + expect(fast).not.toContain("bytes.index"); + expect(body.slice(0, body.indexOf(fast))).toContain("bytes.index.invalid"); +}); + test("statically ranged indices compare one constant with the length", () => { const masked = bin("&", bin("^", ref("i"), ref("k")), num(255)); const loop = counted([set(ref("out", f64s), num(0), get(ref("table", i32s), masked))]); @@ -144,6 +179,11 @@ test("statically ranged indices compare one constant with the length", () => { ]); expect(version.affine).toEqual([]); expect(version.counted).toBeNull(); + // A uint32 index (an array counter's range) gets no guard: no typed array + // in practice has 2^31 elements. + const wide = bin(">>>", bin("^", ref("i"), ref("k")), num(0)); + const unbounded = counted([set(ref("out", f64s), num(0), get(ref("table", i32s), wide))]); + expect(match(fn([unbounded]), unbounded)!.fixed).toEqual([{ receiver: 0, end: 0 }]); }); test("scaled counters and body temps resolve to their receiver and index", () => { @@ -281,6 +321,108 @@ test("worker programs test each receiver's shared storage once in the guard", () expect(slow).toContain("store atomic double"); }); +test("index temps of a version's counter are integers in the fast copy", () => { + // for (let i = 0; i < out.length; i++) { const j = i * 4; out[i] = src[j] + src[j + 1] } + const length: IrExpr = { + kind: "bytesIntrinsic", + method: "length", + receiver: ref("out", f64s), + args: [], + type: F64, + loc, + }; + const loop = counted( + [ + { kind: "varDecl", localId: "at", init: bin("*", ref("i"), num(4)), loc }, + set( + ref("out", f64s), + ref("i"), + bin( + "+", + get(ref("src", f64s), ref("at")), + get(ref("src", f64s), bin("+", ref("at"), num(1))), + ), + ), + ], + length, + ); + const mod: IrModule = { + irVersion: 17, + sourceFile: loc.file, + entry: "__main", + functions: [ + { name: "__main", params: [], returnType: VOID, locals: [], body: [], loc }, + fn([loop], [local("at", F64)]), + ], + }; + const body = /^define internal [^\n]*@sc_bf_kernel[^]*?^}/m.exec(emitLlvmModule(mod))![0]; + const fast = /^bytes\.version\.fast\d+:$[^]*?^bytes\.version\.done\d+:$/m.exec(body)![0]; + expect(body).toContain("alloca i64 ; integer at"); + expect(fast).toMatch(/mul nsw i64 %\S+, 4/); + expect(fast).toMatch(/add nsw i64 %\S+, 1/); + expect(fast).not.toContain("fmul"); + expect(fast).not.toContain("fptosi"); + expect(fast).not.toContain("bytes.index"); +}); + +test("while loop counters below a bound version their accesses", () => { + // while (i < n) { out[i] = src[i + 1]; i = i + 1 } + const step: IrStmt = { kind: "assign", localId: "i", value: bin("+", ref("i"), num(1)), loc }; + const whileLoop = (body: IrStmt[]): IrStmt & { kind: "while" } => ({ + kind: "while", + cond: { kind: "bin", op: "<", left: ref("i"), right: ref("n"), type: BOOL, loc }, + body, + loc, + }); + const copy = whileLoop([ + set(ref("out", f64s), ref("i"), get(ref("src", f64s), bin("+", ref("i"), num(1)))), + step, + ]); + const declared = (loop: IrStmt): IrFunction => + fn([{ kind: "varDecl", localId: "i", init: ref("k"), loc }, loop]); + const versionOf = (loop: IrStmt & { kind: "while" }): BytesLoopVersion | null => { + const f = declared(loop); + const ranges = analyzeIntegerRanges(f); + return matchBytesLoopVersion(loop, null, { + locals: new Map(f.locals.map((l) => [l.id, l])), + invariantGlobals: new Set(), + captured: new Set(), + ranges, + initialized: findInitializedByteLoopBindings(f).get(loop) ?? new Set(), + proven: new Set(), + scalarStrings: new Set(), + workers: false, + owned: new Set(), + }); + }; + const version = versionOf(copy)!; + expect(version.bounds.size).toBe(2); + expect(version.bounded.map((c) => [version.receivers[c.receiver]!.ref, c.slack])).toEqual([ + [ref("out", f64s), 0], + [ref("src", f64s), 1], + ]); + // `out[i]` needs `i` to start at 0 or above (`src[i + 1]` only at -1). + expect(version.counters.map((c) => [c.ref.kind === "varRef" && c.ref.localId, c.min])).toEqual([ + ["i", 0], + ]); + // An access after the counter advances in the same pass stays checked. + const advanced = whileLoop([step, set(ref("out", f64s), ref("i"), num(0))]); + expect(versionOf(advanced)).toBeNull(); + const mod: IrModule = { + irVersion: 17, + sourceFile: loc.file, + entry: "__main", + functions: [ + { name: "__main", params: [], returnType: VOID, locals: [], body: [], loc }, + declared(copy), + ], + }; + const body = /^define internal [^\n]*@sc_bf_kernel[^]*?^}/m.exec(emitLlvmModule(mod))![0]; + const fast = /^bytes\.version\.fast\d+:$[^]*?^bytes\.version\.done\d+:$/m.exec(body)![0]; + expect(fast).not.toContain("bytes.index"); + expect(body.slice(0, body.indexOf(fast))).toContain("bytes.index.invalid"); +}); + test("Float16Array accesses version in elements and share the element tag", () => { const f16s: IrType = { kind: "bytes", elem: "f16" }; const withHalves = (body: IrStmt[]): IrFunction => { @@ -348,3 +490,131 @@ test("bodies compiled without optimization keep one checked loop", () => { expect(body).not.toContain("bytes.version"); expect(body).toContain("bytes.index.invalid"); }); + +const STR: IrType = { kind: "string" }; +const charCode = (receiver: IrExpr, index: IrExpr): IrExpr => ({ + kind: "strIntrinsic", + method: "charCodeAt", + receiver, + args: [index], + type: F64, + loc, +}); + +/** The kernel with a string parameter `text`. */ +function textKernel(body: IrStmt[], mutable = false): IrFunction { + const kernel = fn(body, [local("text", STR, mutable)]); + kernel.params.push({ localId: "text", name: "text", type: STR }); + return kernel; +} + +test("charCodeAt reads of a string binding version with the typed-array reads", () => { + const read = charCode(ref("text", STR), bin("+", ref("i"), num(1))); + const loop = counted([set(ref("out", f64s), ref("i"), read)]); + const version = match(textKernel([loop]), loop)!; + expect(version.bounds.has(read)).toBe(true); + expect( + version.receivers.map((r) => [r.ref.kind === "varRef" && r.ref.localId, r.string]), + ).toEqual([ + ["out", false], + ["text", true], + ]); + expect(version.affine.map((c) => [c.receiver, c.minOffset, c.maxEnd])).toEqual([ + [0, 0, 0], + [1, 1, 1], + ]); + // A string the loop rebinds keeps its checked reads. + const rebinding = counted([ + set(ref("out", f64s), ref("i"), charCode(ref("text", STR), ref("i"))), + { kind: "assign", localId: "text", value: ref("text", STR), loc }, + ]); + const rebound = match(textKernel([rebinding], true), rebinding)!; + expect(rebound.receivers.map((r) => r.string)).toEqual([false]); + // A string held as a slice of another string has no header to test. + const sliced = match(textKernel([loop]), loop, [], ["text"])!; + expect(sliced.receivers.map((r) => r.string)).toEqual([false]); + expect(sliced.bounds.has(read)).toBe(false); +}); + +test("charAt reads of a string binding version as one-unit reads", () => { + const read: IrExpr = { + kind: "strIntrinsic", + method: "charAt", + receiver: ref("text", STR), + args: [bin("-", ref("i"), num(1))], + type: STR, + loc, + }; + const loop = counted([{ kind: "exprStmt", expr: read, loc }]); + const version = match(textKernel([loop]), loop)!; + expect(version.bounds.has(read)).toBe(true); + expect(version.receivers.map((r) => r.string)).toEqual([true]); + expect(version.affine.map((c) => [c.receiver, c.minOffset, c.maxEnd])).toEqual([[0, -1, -1]]); +}); + +test("the guard tests a string's ASCII bit and the fast copy reads bytes", () => { + const loop = counted([set(ref("out", f64s), ref("i"), charCode(ref("text", STR), ref("i")))]); + const kernel = textKernel([loop]); + const mod: IrModule = { + irVersion: 17, + sourceFile: loc.file, + entry: "__main", + functions: [ + { name: "__main", params: [], returnType: VOID, locals: [], body: [], loc }, + kernel, + ], + }; + const body = /^define internal [^\n]*@sc_bf_kernel[^]*?^}/m.exec(emitLlvmModule(mod))![0]; + const guard = body.slice(0, body.search(/^bytes\.version\.slow\d*:/m)); + expect(guard).toMatch(/load i32, ptr %\S+\n\s+%\S+ = icmp slt i32 %\S+, 0/); + const fast = body.slice(body.lastIndexOf("bytes.version.fast")); + expect(fast).toMatch(/load i8, ptr %\S+\n\s+%\S+ = uitofp i8/); + expect(fast).not.toContain("@sc_str_char_code_at_int"); + // The checked copy keeps the inline helper and its fallback. + expect(body).toContain("@sc_str_char_code_at_int"); +}); + +test("while loop counters below a string's length version its reads", () => { + // while (i < text.length && text.charCodeAt(i) === 32) i = i + 1 + const text = ref("text", STR); + const read = charCode(text, ref("i")); + const length: IrExpr = { + kind: "strIntrinsic", + method: "length", + receiver: text, + args: [], + type: F64, + loc, + }; + const loop: IrStmt & { kind: "while" } = { + kind: "while", + cond: { + kind: "logical", + op: "&&", + left: { kind: "bin", op: "<", left: ref("i"), right: length, type: BOOL, loc }, + right: { kind: "bin", op: "===", left: read, right: num(32), type: BOOL, loc }, + type: BOOL, + loc, + }, + body: [{ kind: "assign", localId: "i", value: bin("+", ref("i"), num(1)), loc }], + loc, + }; + const f = textKernel([{ kind: "varDecl", localId: "i", init: ref("k"), loc }, loop]); + const version = matchBytesLoopVersion(loop, null, { + locals: new Map(f.locals.map((l) => [l.id, l])), + invariantGlobals: new Set(), + captured: new Set(), + ranges: analyzeIntegerRanges(f), + initialized: findInitializedByteLoopBindings(f).get(loop) ?? new Set(), + proven: new Set(), + scalarStrings: new Set(), + workers: false, + owned: new Set(), + })!; + // The read is bounded by the counter's test against the length, not by + // a static range the guard could not meet. + expect(version.bounds.has(read)).toBe(true); + expect(version.receivers.map((r) => r.string)).toEqual([true]); + expect(version.bounded.map((c) => c.slack)).toEqual([0]); + expect(version.fixed).toEqual([]); +}); diff --git a/packages/compiler/src/backend/llvm/bytes-loop-versions.ts b/packages/compiler/src/backend/llvm/bytes-loop-versions.ts index dcb735e61..704b6723a 100644 --- a/packages/compiler/src/backend/llvm/bytes-loop-versions.ts +++ b/packages/compiler/src/backend/llvm/bytes-loop-versions.ts @@ -1,4 +1,4 @@ -import type { IrExpr, IrLocal, IrStmt } from "../../ir/ir.js"; +import { F64, type IrExpr, type IrLocal, type IrStmt } from "../../ir/ir.js"; import type { IntegerRange, IntegerRanges } from "../../ir/integer-ranges.js"; import type { IntegerCountedForLoop } from "../../ir/integer-loops.js"; import type { LlvmEmitterContext } from "./expr-context.js"; @@ -7,6 +7,8 @@ import { everyExprChild, everyStmtChild } from "../../ir/traverse.js"; import { exactInteger, widenInteger } from "./integer-values.js"; import { emitCountedLoopLimit, emitCountedLoopSafety } from "./counted-loops.js"; import { emitBytesHeaderLength, emitBytesSharedStorage } from "./expr-bytes.js"; +import { f64Lit } from "./common.js"; +import { emitStringAsciiFlag, emitStringByteLength } from "./string-reads.js"; type Node = IrExpr | IrStmt; type VarRef = IrExpr & { kind: "varRef" }; @@ -22,6 +24,24 @@ interface KeyedTerm extends Term { key: string; } +/** Every access of `receiver` at a while loop counter `c + d` happens while + * `c < bound` (`c <= bound` when `inclusive`) holds and before the counter + * advances, so it is in bounds when `bound + slack <= length`. */ +interface BoundedCheck { + receiver: number; + bound: IrExpr; + slack: number; +} + +/** A while loop counter whose entry value the guard tests: an exact + * integer of at least `min`. A counter that `| 0` wraps also needs every + * bound of its loops at most `wrapLimit`, so that it never reaches 2^31. */ +interface CounterCheck { + ref: VarRef; + min: number; + wrapBounds: { bound: IrExpr; limit: number }[]; +} + /** Every access of `receiver` at a static index range ends below `end + 1`. */ interface FixedCheck { receiver: number; @@ -44,12 +64,19 @@ export interface BytesLoopVersion { /** Worker programs: typed-array accesses whose views the guard proves * thread-owned (no shared storage). */ owned: ReadonlySet; - /** Root receiver bindings, read once before the loop. */ - receivers: { ref: VarRef; global: boolean }[]; + /** Root receiver bindings, read once before the loop; `string` marks a + * string whose `charCodeAt` and `charAt` reads the version covers. */ + receivers: { ref: VarRef; global: boolean; string: boolean }[]; /** Receivers the guard requires to have no shared storage. */ ownedReceivers: number[]; fixed: FixedCheck[]; affine: AffineCheck[]; + /** While loops: accesses at a counter below a loop-invariant bound. */ + bounded: BoundedCheck[]; + counters: CounterCheck[]; + /** Keys of affine terms the guard tests at run time: exact integers + * within GUARDED_TERM. */ + guarded: ReadonlySet; /** The counted loop whose iteration space the affine checks cover. */ counted: IntegerCountedForLoop | null; /** The guard also requires every counter value within [-bound, bound]. */ @@ -76,13 +103,19 @@ export interface BytesLoopFacts { workers: boolean; /** Accesses already proved thread-owned by an enclosing version. */ owned: ReadonlySet; + /** String bindings held as a slice of another string (string-slices.ts): + * they have no string header for the guard to read. */ + scalarStrings: ReadonlySet; } const MAX_COST = 400; -const MAX_FIXED_END = 2 ** 32; +const MAX_FIXED_END = 2 ** 31; const MAX_CHECKS = 8; const MAX_OFFSET = 2 ** 31; const SAFE = Number.MAX_SAFE_INTEGER; +/** The range the guard requires of an invariant index term without a + * proven one: every index of a typed array of at most 2^32 elements. */ +const GUARDED_TERM: IntegerRange = { min: -(2 ** 32), max: 2 ** 32 }; const INVARIANT_OPS = new Set(["+", "-", "*", "&", "|", "^", "<<", ">>", ">>>"]); /** Loop versioning for typed-array bounds. A typed array's length and data @@ -95,7 +128,17 @@ const INVARIANT_OPS = new Set(["+", "-", "*", "&", "|", "^", "<<", ">>", ">>>"]) * `hi < length`, such as `table[x & 0xff]` or a constant-trip counter; * - an index `k * counter + invariant + c` of a counted loop needs its first * and last values in bounds, such as `out[base + i]` for `i < n` or - * `view.getUint32(i * 4)`. + * `view.getUint32(i * 4)`. An invariant without a proven integer range, + * such as `base` for `const base = r * cols`, must also be an exact + * integer between -2^32 and 2^32, which the guard tests. + * + * `s.charCodeAt(index)` and `s.charAt(index)` (so `s[index]`) of a string + * binding qualify the same way. A string is immutable: its bytes, its + * length and the capacity-word bit that proves it ASCII (string-reads.ts) + * are fixed when it is built. The guard also requires that bit, so each + * UTF-16 unit is one byte and the length is the byte length. The fast copy + * reads each unit with one byte load, and each character as the immortal + * one-character string for its byte. * * In worker programs, every access of a view that may be shared tests its * shared storage. A view's storage is also fixed at construction, so the @@ -107,7 +150,7 @@ const INVARIANT_OPS = new Set(["+", "-", "*", "&", "|", "^", "<<", ">>", ">>>"]) * whenever the guard fails, and keeps every out-of-bounds read, ignored * write and NaN-index behavior. */ export function matchBytesLoopVersion( - loop: IrStmt & { kind: "for" }, + loop: IrStmt & { kind: "for" | "while" }, counted: IntegerCountedForLoop | null, facts: BytesLoopFacts, ): BytesLoopVersion | null { @@ -146,10 +189,10 @@ export function matchBytesLoopVersion( // writes is not invariant either: `for (let i = (a = b, 0); ...)` must // not keep the bounds the guard proved for the old `a`. if ( - (loop.init !== null && !scanStmt(loop.init)) || + (loop.kind === "for" && loop.init !== null && !scanStmt(loop.init)) || !loop.body.every(scanStmt) || (loop.cond !== null && !scanExpr(loop.cond)) || - (loop.update !== null && !scanStmt(loop.update)) + (loop.kind === "for" && loop.update !== null && !scanStmt(loop.update)) ) return null; // A body temp stands for its initializer only when it is a constant @@ -187,7 +230,8 @@ export function matchBytesLoopVersion( }; const resolving = new Set(); const root = (e: IrExpr): VarRef | null => { - if (e.kind !== "varRef" || e.type.kind !== "bytes") return null; + if (e.kind !== "varRef" || (e.type.kind !== "bytes" && e.type.kind !== "string")) return null; + if (facts.scalarStrings.has(e.localId)) return null; const init = temp(e.localId); if (init) { if (resolving.has(e.localId)) return null; @@ -198,9 +242,8 @@ export function matchBytesLoopVersion( } return invariant(e.localId) ? e : null; }; - // A pure integer operand evaluated again before the loop. - const invariantKey = (e: IrExpr): string | null => { - if (!facts.ranges.get(e)) return null; + // A pure loop-invariant number, evaluated again before the loop. + const pureKey = (e: IrExpr): string | null => { if (e.kind === "numLit") return Number.isSafeInteger(e.value) ? `n${e.value}` : null; if (e.kind === "varRef") return invariant(e.localId) ? `v${e.localId.length}:${e.localId}` : null; @@ -210,12 +253,27 @@ export function matchBytesLoopVersion( e.left.type.kind === "f64" && e.right.type.kind === "f64" ) { - const left = invariantKey(e.left), - right = invariantKey(e.right); + const left = pureKey(e.left), + right = pureKey(e.right); return left !== null && right !== null ? `(${e.op} ${left} ${right})` : null; } return null; }; + // Invariant terms without a proven range, such as `base` in + // `w[base + j]` with `const base = r * cols` for a parameter `cols`. The + // guard tests each one: an exact integer (not -0) within GUARDED_TERM. + const guardedRanges = new Map(); + const guardedNodes = new Map(); + // The key of a loop-invariant index term, with a proven range or guarded. + const invariantKey = (e: IrExpr): string | null => { + const key = pureKey(e); + if (key === null || facts.ranges.get(e)) return key; + if (e.kind === "numLit") return null; + guardedRanges.set(e, GUARDED_TERM); + guardedNodes.set(e, key); + return key; + }; + const termRange = (e: IrExpr): IntegerRange => facts.ranges.get(e) ?? guardedRanges.get(e)!; interface Affine { /** The counter's coefficient; 0 when the value is loop-invariant. */ counter: number; @@ -223,9 +281,10 @@ export function matchBytesLoopVersion( offset: number; } // Every operand of an affine index is `counter * k + Σ terms + offset`. - // Invariant terms need proven ranges. Operands that involve the counter - // need none: the guard bounds the counter so that each of them is a safe - // integer, which makes the index's double arithmetic exact. + // Invariant terms need proven ranges or the guard's test (guarded terms). + // Operands that involve the counter need none: the guard bounds the + // counter so that each of them is a safe integer, which makes the index's + // double arithmetic exact. const shapes = new Map(); const affine = (e: IrExpr): Affine | null => { if (shapes.has(e)) return shapes.get(e)!; @@ -309,11 +368,49 @@ export function matchBytesLoopVersion( }; const termMagnitude = (terms: Term[]): number => terms.reduce((sum, t) => { - const r = facts.ranges.get(t.expr)!; + const r = termRange(t.expr); return sum + Math.max(Math.abs(r.min), Math.abs(r.max)); }, 0); - const receivers: { ref: VarRef; global: boolean }[] = []; + const whileAccesses = loop.kind === "while" ? whileCounterAccesses(loop) : null; + function whileCounterAccesses(loop: IrStmt & { kind: "while" }) { + return findWhileCounterAccesses(loop, { + counterLocal: (id) => { + const local = facts.locals.get(id); + return ( + local?.type.kind === "f64" && + !local.boxed && + !local.tdz && + !facts.captured.has(id) && + facts.initialized.has(id) + ); + }, + boundKey: (e) => { + if (e.type.kind !== "f64") return null; + // The guard evaluates the bound before the loop: a typed array's + // length needs the binding itself, not a temp the body declares. + if ( + e.kind === "bytesIntrinsic" && + e.method === "length" && + e.receiver.kind === "varRef" && + e.receiver.type.kind === "bytes" && + invariant(e.receiver.localId) + ) + return `bytes-length:${e.receiver.localId}`; + if ( + e.kind === "strIntrinsic" && + e.method === "length" && + e.args.length === 0 && + e.receiver.kind === "varRef" && + e.receiver.type.kind === "string" && + invariant(e.receiver.localId) + ) + return `string-length:${e.receiver.localId}`; + return pureKey(e); + }, + }); + } + const receivers: { ref: VarRef; global: boolean; string: boolean }[] = []; const receiverIndex = new Map(); const fixed = new Map(); const affineChecks = new Map< @@ -325,17 +422,26 @@ export function matchBytesLoopVersion( if (index === undefined) { index = receivers.length; receiverIndex.set(ref.localId, index); - receivers.push({ ref, global: !facts.locals.has(ref.localId) }); + receivers.push({ + ref, + global: !facts.locals.has(ref.localId), + string: ref.type.kind === "string", + }); } return index; }; // Worker programs: accesses through invariant receivers, proven or not, // become thread-owned when the guard finds no shared storage. const owned = new Map(); + // While loops: accesses at a counter below a bound, by receiver and bound. + const boundedChecks = new Map< + string, + { check: BoundedCheck; nodes: { node: Node; access: WhileAccess }[] } + >(); const access = (node: Node, array: IrExpr, index: IrExpr, width: number): void => { const ref = root(array); if (!ref) return; - if (facts.workers && !facts.owned.has(node)) { + if (facts.workers && ref.type.kind === "bytes" && !facts.owned.has(node)) { const receiver = receiverOf(ref); const nodes = owned.get(receiver); if (nodes) nodes.push(node); @@ -366,11 +472,30 @@ export function matchBytesLoopVersion( }); return; } + const bounded = whileAccesses?.accesses.get(node); + const loopCounter = bounded && whileAccesses!.counters.get(bounded.counter); + if (bounded && loopCounter && (!loopCounter.wraps || loopCounter.bounds !== null)) { + const receiver = receiverOf(ref); + const key = `${receiver}|${bounded.key}|${bounded.adj}`; + const slack = bounded.offset + width - 1 + bounded.adj; + const group = boundedChecks.get(key); + if (group) { + group.check.slack = Math.max(group.check.slack, slack); + group.nodes.push({ node, access: bounded }); + } else + boundedChecks.set(key, { + check: { receiver, bound: bounded.bound, slack }, + nodes: [{ node, access: bounded }], + }); + return; + } const range = facts.ranges.get(index); if (!range) return; const end = range.max + width - 1; - // Only a length a buffer can have: an outer loop must not pay for a - // guard that bounds an inner loop's unbounded counter. + // Only an end below 2^31: an outer loop must not pay for a guard that + // bounds an inner loop's unbounded counter, and the counter of a loop to + // an array's length reaches 2^32 - 2, a length no typed array in + // practice has. if (range.min < 0 || end >= MAX_FIXED_END) return; const receiver = receiverOf(ref); const group = fixed.get(receiver); @@ -384,7 +509,12 @@ export function matchBytesLoopVersion( const numeric = byteNumberAccess(e); if (numeric) access(e, e.receiver, e.args[numeric.offsetArg]!, numeric.width); else if (e.method === "get" && e.args[0]) access(e, e.receiver, e.args[0], 1); - } + } else if ( + e.kind === "strIntrinsic" && + (e.method === "charCodeAt" || e.method === "charAt") && + e.args[0] + ) + access(e, e.receiver, e.args[0], 1); return everyExprChild(e, visitExpr, visitStmt); }; const visitStmt = (s: IrStmt): boolean => { @@ -392,6 +522,7 @@ export function matchBytesLoopVersion( return everyStmtChild(s, visitExpr, visitStmt); }; loop.body.every(visitStmt); + if (loop.kind === "while") visitExpr(loop.cond); // Bound the counter so every counter operand stays a safe integer. let bound = SAFE; const affineGroups = [...affineChecks.values()].filter((group) => { @@ -407,8 +538,18 @@ export function matchBytesLoopVersion( }); const fixedKept = [...fixed.values()].slice(0, MAX_CHECKS); const affineKept = affineGroups.slice(0, MAX_CHECKS - fixedKept.length); + const boundedKept = [...boundedChecks.values()].slice( + 0, + Math.max(0, MAX_CHECKS - fixedKept.length - affineKept.length), + ); const ownedKept = [...owned.entries()].slice(0, MAX_CHECKS); - if (fixedKept.length === 0 && affineKept.length === 0 && ownedKept.length === 0) return null; + if ( + fixedKept.length === 0 && + affineKept.length === 0 && + boundedKept.length === 0 && + ownedKept.length === 0 + ) + return null; const bounds = new Set(); const ownedNodes = new Set(); const used = new Set(); @@ -427,20 +568,65 @@ export function matchBytesLoopVersion( used.add(group.check.receiver); for (const node of group.nodes) bounds.add(node); for (const operand of group.operands) { - if (facts.ranges.get(operand)) continue; const shape = shapes.get(operand)!; const a = shape.counter * counterLow, b = shape.counter * counterHigh; let min = Math.min(a, b) + shape.offset, max = Math.max(a, b) + shape.offset; for (const term of shape.terms) { - const r = facts.ranges.get(term.expr)!; + const r = termRange(term.expr); min += term.sign > 0 ? r.min : -r.max; max += term.sign > 0 ? r.max : -r.min; } - if (counterLow <= counterHigh) ranges.set(operand, { min, max }); + if (counterLow > counterHigh) continue; + // The guard's bound on the counter can narrow a range the operand + // already has (a loop to a length proves only `i < 2^53`), so that + // `i * 4` in the fast copy is exact integer arithmetic. + const known = facts.ranges.get(operand); + if (!known) ranges.set(operand, { min, max }); + else if (min > known.min || max < known.max) + ranges.set(operand, { min: Math.max(min, known.min), max: Math.min(max, known.max) }); } } + // Guarded terms of the kept checks, and the range the guard proves for + // every node of each in the fast copy. + const guarded = new Set(); + for (const group of affineKept) + for (const term of group.check.terms) if (guardedRanges.has(term.expr)) guarded.add(term.key); + for (const [node, key] of guardedNodes) if (guarded.has(key)) ranges.set(node, GUARDED_TERM); + // While loop counters of the kept checks: each entry value is an exact + // integer that no access offset takes below 0. In the fast copy each + // access's index is below its length, and its counter read at least the + // most negative offset. + const narrow = (e: IrExpr, range: IntegerRange): void => { + const known = ranges.get(e) ?? facts.ranges.get(e); + ranges.set( + e, + known ? { min: Math.max(known.min, range.min), max: Math.min(known.max, range.max) } : range, + ); + }; + const counterMins = new Map(); + for (const group of boundedKept) { + used.add(group.check.receiver); + for (const { node, access } of group.nodes) { + bounds.add(node); + const min = 0 - access.offset; + counterMins.set(access.counter, Math.max(counterMins.get(access.counter) ?? -SAFE, min)); + narrow(access.ref, { min: -MAX_OFFSET, max: SAFE }); + if (access.index !== access.ref) narrow(access.index, { min: 0, max: SAFE }); + } + } + const counterChecks: CounterCheck[] = []; + for (const [id, min] of counterMins) { + const info = whileAccesses!.counters.get(id)!; + counterChecks.push({ + ref: { kind: "varRef", localId: id, type: F64, loc: loop.loc }, + min, + wrapBounds: info.wraps + ? info.bounds!.map((b) => ({ bound: b.bound, limit: 2 ** 31 - info.sum - b.adj })) + : [], + }); + } // Renumber the receivers the kept checks use. const order = [...used].sort((a, b) => a - b); const renumber = new Map(order.map((old, index) => [old, index])); @@ -464,12 +650,327 @@ export function matchBytesLoopVersion( minOffset: g.check.minOffset, maxEnd: g.check.maxEnd, })), + bounded: boundedKept.map((g) => ({ + receiver: renumber.get(g.check.receiver)!, + bound: g.check.bound, + slack: g.check.slack, + })), + counters: counterChecks, + guarded, counted: affineKept.length > 0 ? counted : null, counterBound: needsBound ? bound : null, ranges, }; } +/** A typed-array access at a while loop counter: `counter + offset`, read + * or written while `counter < bound` (`<=` when `adj` is 1) holds. */ +interface WhileAccess { + counter: string; + /** The index, and the counter's read in it. */ + index: IrExpr; + ref: IrExpr; + bound: IrExpr; + key: string; + adj: number; + offset: number; +} + +interface WhileCounter { + /** Some increment is `c = (c + k) | 0`. */ + wraps: boolean; + /** The sum of every increment literal in the loop. */ + sum: number; + /** One bound from the condition of the loop and of every nested while + * loop that advances the counter; null when one of them has none. */ + bounds: { bound: IrExpr; adj: number }[] | null; +} + +/** `counter = counter + k`, `counter = (counter + k) | 0` or `counter++`. */ +function counterStep(s: IrStmt): { id: string; k: number; wraps: boolean } | null { + if (s.kind === "exprStmt" && s.expr.kind === "incDec" && s.expr.op === "+") + return { id: s.expr.localId, k: 1, wraps: false }; + if (s.kind !== "assign") return null; + let value = s.value, + wraps = false; + if ( + value.kind === "bin" && + value.op === "|" && + value.right.kind === "numLit" && + value.right.value === 0 && + value.left.kind === "bin" + ) { + value = value.left; + wraps = true; + } + if ( + value.kind !== "bin" || + value.op !== "+" || + value.left.kind !== "varRef" || + value.left.localId !== s.localId || + value.right.kind !== "numLit" || + !Number.isSafeInteger(value.right.value) || + value.right.value <= 0 || + value.right.value > MAX_OFFSET + ) + return null; + return { id: s.localId, k: value.right.value, wraps }; +} + +/** Typed-array and string accesses of a while loop that happen at a + * counter below a loop-invariant bound. A counter is a number local that + * the loop changes only by positive integer increments, written as + * statements of the body, of its blocks and branches, or of nested while + * loops. The condition of the loop, an `if` or a `&&` chain that compares + * the counter below a bound (`while (pos < end && bytes[pos] === 32) + * pos++`, or `s.charCodeAt(pos)` of a string) makes it below that bound + * until the next increment on the path. The counter starts at its entry + * value and only grows (a `| 0` increment never wraps when every bound is + * at most 2^31 minus the increments), so an access at `counter + d` is in + * bounds for the whole loop when the entry value is at least `-d` and + * `bound + d < length` (`+ 1` for `<=`). */ +function findWhileCounterAccesses( + loop: IrStmt & { kind: "while" }, + host: { + counterLocal: (id: string) => boolean; + /** A key for a bound expression whose value the loop never changes. */ + boundKey: (e: IrExpr) => string | null; + }, +): { accesses: Map; counters: Map } { + const steps = new Map(); + const refused = new Set(); + // Increments count only as statements of the loop's straight-line + // structure; any other write refuses the binding. + const writes = (list: readonly IrStmt[], direct: boolean): void => { + for (const s of list) { + const step = counterStep(s); + if (step && direct) { + const prior = steps.get(step.id); + steps.set(step.id, { + sum: (prior?.sum ?? 0) + step.k, + wraps: (prior?.wraps ?? false) || step.wraps, + }); + continue; + } + if (step) refused.add(step.id); + const nested = + direct && + (s.kind === "if" || s.kind === "while" || (s.kind === "block" && !s.labels?.length)); + if (s.kind === "assign" || s.kind === "varDecl" || s.kind === "forOf") refused.add(s.localId); + if (s.kind === "tryCatch" && s.catchLocalId) refused.add(s.catchLocalId); + everyStmtChild( + s, + (e) => (exprWrites(e), true), + (c) => (writes([c], nested), true), + ); + } + }; + const exprWrites = (e: IrExpr): void => { + if (e.kind === "assignExpr" || e.kind === "incDec") refused.add(e.localId); + everyExprChild( + e, + (c) => (exprWrites(c), true), + (c) => (writes([c], false), true), + ); + }; + exprWrites(loop.cond); + writes(loop.body, true); + const counter = (id: string): boolean => + steps.has(id) && !refused.has(id) && host.counterLocal(id); + + type Fact = { bound: IrExpr; key: string; adj: number }; + type Clean = ReadonlyMap; + // The bounds a condition puts on counters while it holds. + const facts = (cond: IrExpr, into: Map): void => { + if (cond.kind === "toBool") return facts(cond.operand, into); + if (cond.kind === "logical" && cond.op === "&&") { + facts(cond.left, into); + facts(cond.right, into); + return; + } + if (cond.kind !== "bin") return; + const below = cond.op === "<" || cond.op === "<=", + above = cond.op === ">" || cond.op === ">="; + const c = below ? cond.left : above ? cond.right : null, + bound = below ? cond.right : cond.left; + if (c?.kind !== "varRef" || !counter(c.localId) || into.has(c.localId)) return; + const key = host.boundKey(bound); + if (key === null) return; + into.set(c.localId, { bound, key, adj: cond.op === "<=" || cond.op === ">=" ? 1 : 0 }); + }; + // The facts that hold after either of two paths. + const meet = (a: Clean | null, b: Clean | null): Clean | null => { + if (a === null) return b; + if (b === null) return a; + const out = new Map(); + for (const [id, fact] of a) if (b.get(id) === fact) out.set(id, fact); + return out; + }; + const withFacts = (clean: Clean, cond: IrExpr): Clean => { + const out = new Map(clean); + facts(cond, out); + return out; + }; + const accesses = new Map(); + const record = (node: Node, index: IrExpr, clean: Clean): void => { + let ref: IrExpr = index, + offset = 0; + if (index.kind === "bin" && (index.op === "+" || index.op === "-")) { + const literal = + index.right.kind === "numLit" ? index.right : index.op === "+" ? index.left : null; + const other = literal === index.right ? index.left : index.right; + if (literal?.kind !== "numLit" || !Number.isSafeInteger(literal.value)) return; + if (Math.abs(literal.value) > MAX_OFFSET || Object.is(literal.value, -0)) return; + offset = index.op === "-" ? -literal.value : literal.value; + ref = other; + } + if (ref.kind !== "varRef") return; + const fact = clean.get(ref.localId); + if (fact) accesses.set(node, { counter: ref.localId, index, ref, ...fact, offset }); + }; + const expr = (e: IrExpr, clean: Clean): void => { + if (e.kind === "bytesIntrinsic") { + const numeric = byteNumberAccess(e); + const index = numeric + ? e.args[numeric.offsetArg] + : e.method === "get" + ? e.args[0] + : undefined; + if (index) record(e, index, clean); + } + if ( + e.kind === "strIntrinsic" && + (e.method === "charCodeAt" || e.method === "charAt") && + e.args[0] + ) + record(e, e.args[0], clean); + if (e.kind === "logical" && e.op === "&&") { + expr(e.left, clean); + expr(e.right, withFacts(clean, e.left)); + return; + } + if (e.kind === "ternary") { + expr(e.cond, clean); + expr(e.then, withFacts(clean, e.cond)); + expr(e.else_, clean); + return; + } + everyExprChild( + e, + (c) => (expr(c, clean), true), + (c) => (stmts([c], clean), true), + ); + }; + // Walks statements in order; the result is the clean state where the + // list falls through, or null when it never does. + const stmts = (list: readonly IrStmt[], clean: Clean): Clean | null => { + let current: Clean | null = clean; + for (const s of list) { + if (current === null) return null; + const step = counterStep(s); + if (step) { + const next: Map = new Map(current); + next.delete(step.id); + current = next; + continue; + } + switch (s.kind) { + case "if": { + expr(s.cond, current); + const then = stmts(s.then, withFacts(current, s.cond)); + const otherwise = stmts(s.else_ ?? [], current); + current = meet(then, otherwise); + break; + } + case "while": { + // A pass of the nested loop may follow its own increments. + const advanced: Map = new Map(current); + for (const id of writtenCounters(s.body)) advanced.delete(id); + expr(s.cond, advanced); + stmts(s.body, withFacts(advanced, s.cond)); + current = advanced; + break; + } + case "block": + if (!s.labels?.length) { + current = stmts(s.body, current); + break; + } + everyStmtChild( + s, + (e) => (expr(e, current!), true), + (c) => (stmts([c], current!), true), + ); + break; + case "bytesSet": + record(s, s.index, current); + everyStmtChild( + s, + (e) => (expr(e, current!), true), + (c) => (stmts([c], current!), true), + ); + break; + case "break": + case "continue": + case "return": + case "throw": + everyStmtChild( + s, + (e) => (expr(e, current!), true), + (c) => (stmts([c], current!), true), + ); + current = null; + break; + default: + everyStmtChild( + s, + (e) => (expr(e, current!), true), + (c) => (stmts([c], current!), true), + ); + break; + } + } + return current; + }; + const writtenCounters = (list: readonly IrStmt[]): Set => { + const out = new Set(); + const visit = (s: IrStmt): boolean => { + const step = counterStep(s); + if (step) out.add(step.id); + return everyStmtChild(s, () => true, visit); + }; + list.every(visit); + return out; + }; + expr(loop.cond, new Map()); + stmts(loop.body, withFacts(new Map(), loop.cond)); + + // Each counter's bounds: the loop's and those of nested while loops that + // advance it. + const counters = new Map(); + const loops: (IrStmt & { kind: "while" })[] = [loop]; + const collectLoops = (s: IrStmt): boolean => { + if (s.kind === "while") loops.push(s); + return everyStmtChild(s, () => true, collectLoops); + }; + loop.body.every(collectLoops); + for (const [id, step] of steps) { + if (!counter(id)) continue; + let bounds: WhileCounter["bounds"] = []; + for (const l of loops) { + if (l !== loop && !writtenCounters(l.body).has(id)) continue; + const fact = withFacts(new Map(), l.cond).get(id); + if (!fact) { + bounds = null; + break; + } + bounds.push({ bound: fact.bound, adj: fact.adj }); + } + counters.set(id, { ...step, bounds }); + } + return { accesses, counters }; +} + /** Branches to `fast` when every access the version proves is in bounds for * every iteration and every view it proves thread-owned has no shared * storage, and to `slow` otherwise (including a counted loop whose @@ -498,14 +999,20 @@ export function emitBytesLoopVersionGuard( } return value; }); - const lengths = receivers.map((receiver) => { - const len = emitBytesHeaderLength(host, receiver); + const lengths = receivers.map((receiver, index) => { + const len = version.receivers[index]!.string + ? emitStringByteLength(host, receiver) + : emitBytesHeaderLength(host, receiver); if (host.sizeType === "i64") return len; const wide = B.tmp(); B.line(`${wide} = zext ${host.sizeType} ${len} to i64`); return wide; }); const conditions: string[] = []; + // A string's byte length is its UTF-16 length when it is ASCII. + version.receivers.forEach(({ string }, index) => { + if (string) conditions.push(emitStringAsciiFlag(host, receivers[index]!)); + }); for (const index of version.ownedReceivers) { const owned = B.tmp(); B.line(`${owned} = icmp eq ptr ${emitBytesSharedStorage(host, receivers[index]!)}, null`); @@ -516,6 +1023,39 @@ export function emitBytesLoopVersionGuard( B.line(`${ok} = icmp ugt i64 ${lengths[check.receiver]}, ${check.end}`); conditions.push(ok); } + for (const counter of version.counters) { + const value = host.emitExpr(counter.ref); + // A counter held as an integer (an int32 slot) is exact already and + // needs at most its lower bound tested. + const integer = exactInteger(host, value, counter.ref); + if (integer && integer.range.max <= SAFE) { + if (integer.range.min < counter.min) { + const ok = B.tmp(); + B.line(`${ok} = icmp sge i64 ${widenInteger(host, integer)}, ${counter.min}`); + conditions.push(ok); + } + } else conditions.push(emitExactIntegerTest(host, value.name, counter.min, SAFE).ok); + for (const wrap of counter.wrapBounds) { + const bound = host.emitExpr(wrap.bound); + const boundInteger = exactInteger(host, bound, wrap.bound); + if (boundInteger && boundInteger.range.max <= wrap.limit) continue; + const ok = B.tmp(); + B.line(`${ok} = fcmp ole double ${bound.name}, ${f64Lit(wrap.limit)}`); + conditions.push(ok); + } + } + for (const check of version.bounded) { + // `bound <= length - slack` in doubles: both sides are exact (a length + // is below 2^53 and a slack below 2^32), and NaN fails. + const bound = host.emitExpr(check.bound).name; + const length = B.tmp(), + room = B.tmp(), + ok = B.tmp(); + B.line(`${length} = uitofp i64 ${lengths[check.receiver]} to double`); + B.line(`${room} = fsub double ${length}, ${f64Lit(check.slack)}`); + B.line(`${ok} = fcmp ole double ${bound}, ${room}`); + conditions.push(ok); + } if (counted && version.affine.length > 0) { // The first and last counter values, in ascending order. The last value // of a non-unit step is exact: `start + ⌊(limit ∓ 1 - start) / step⌋ * @@ -561,6 +1101,14 @@ export function emitBytesLoopVersionGuard( let base = "0"; for (const term of check.terms) { const value = host.emitExpr(term.expr); + if (version.guarded.has(term.key)) { + const tested = emitExactIntegerTest(host, value.name, GUARDED_TERM.min, GUARDED_TERM.max); + conditions.push(tested.ok); + const sum = B.tmp(); + B.line(`${sum} = ${term.sign > 0 ? "add" : "sub"} i64 ${base}, ${tested.integer}`); + base = sum; + continue; + } const integer = exactInteger(host, value, term.expr); if (!integer) { // Unreachable: every term has a proven range. Stay checked. @@ -608,6 +1156,39 @@ export function emitBytesLoopVersionGuard( else B.condBr(valid, fast, slow); } +/** Tests that a double is an exact integer within [min, max] (not -0; NaN + * fails the ordered comparisons) and gives its i64. The integer is frozen, + * so it is a fixed value even when the test fails. */ +function emitExactIntegerTest( + host: LlvmEmitterContext, + value: string, + min: number, + max: number, +): { ok: string; integer: string } { + const B = host.B; + const low = B.tmp(), + high = B.tmp(), + inRange = B.tmp(), + raw = B.tmp(), + integer = B.tmp(), + back = B.tmp(), + bits = B.tmp(), + backBits = B.tmp(), + exact = B.tmp(), + ok = B.tmp(); + B.line(`${low} = fcmp oge double ${value}, ${f64Lit(min)}`); + B.line(`${high} = fcmp ole double ${value}, ${f64Lit(max)}`); + B.line(`${inRange} = and i1 ${low}, ${high}`); + B.line(`${raw} = fptosi double ${value} to i64`); + B.line(`${integer} = freeze i64 ${raw}`); + B.line(`${back} = sitofp i64 ${integer} to double`); + B.line(`${bits} = bitcast double ${value} to i64`); + B.line(`${backBits} = bitcast double ${back} to i64`); + B.line(`${exact} = icmp eq i64 ${bits}, ${backBits}`); + B.line(`${ok} = and i1 ${inRange}, ${exact}`); + return { ok, integer }; +} + function scaleCounter(host: LlvmEmitterContext, value: string, scale: number): string { if (scale === 1) return value; const scaled = host.B.tmp(); diff --git a/packages/compiler/src/backend/llvm/classes.test.ts b/packages/compiler/src/backend/llvm/classes.test.ts index 2d95e942c..bee954afb 100644 --- a/packages/compiler/src/backend/llvm/classes.test.ts +++ b/packages/compiler/src/backend/llvm/classes.test.ts @@ -1,5 +1,14 @@ import { expect, test } from "vitest"; -import { DYN, F64, STRING, VOID, type IrModule } from "../../ir/ir.js"; +import { + DYN, + F64, + STRING, + VOID, + type IrExpr, + type IrFunction, + type IrModule, + type IrType, +} from "../../ir/ir.js"; import { assignCompactLayouts, buildClassGraph, @@ -159,6 +168,43 @@ test("ProgramLifetime hierarchies are never freed and take no reference counts", expect(body(mangleClassRelease("Owner"))).toContain("load i32, ptr %bufp"); }); +test("arrays of ProgramLifetime instances tell the runtime their teardown releases nothing", () => { + const kids = { kind: "array" as const, elem: { kind: "object" as const, className: "Node" } }; + const owners = { kind: "array" as const, elem: { kind: "object" as const, className: "Owner" } }; + const mod: IrModule = { + irVersion: 17, + sourceFile: loc.file, + entry: "main", + functions: [ + { + name: "main", + params: [], + returnType: VOID, + locals: [], + body: [ + { kind: "exprStmt", expr: { kind: "arrayLit", elems: [], type: kids, loc }, loc }, + { kind: "exprStmt", expr: { kind: "arrayLit", elems: [], type: owners, loc }, loc }, + ], + loc, + }, + ], + classes: [ + { name: "Node", fields: [], methods: [], loc }, + { name: "Owner", fields: [{ name: "nodes", type: kids }], methods: [], loc }, + ], + contracts: { programLifetime: ["Node"] }, + }; + const llvm = emitLlvmModule(mod, { pointerBits: 64 }); + const ops = (cls: string): string => + new RegExp(`^@sc_arrops\\.[^\\n]*${mangleClassRelease(cls)}[^\\n]*$`, "m").exec(llvm)?.[0] ?? + ""; + // SCR_ARR_OPS_RELEASE_NOTHING for Node; Owner's elements are released. + expect(ops("Node")).toMatch( + /= internal global \{ ptr, ptr, ptr, i32, i32 \} .*, i32 0, i32 2 \}$/, + ); + expect(ops("Owner")).toMatch(/= internal global %ScrArrOps .*, i32 0 \}$/); +}); + test("classes whose trace visits nothing start acyclic in a traced hierarchy", () => { const mapper = { kind: "object" as const, className: "Mapper" }; const mod: IrModule = { @@ -222,12 +268,13 @@ test("ProgramLifetime classes pack their fields after a 32-bit header", () => { contracts: { programLifetime: ["Node"] }, }; const llvm = emitLlvmModule(mod, { pointerBits: 64 }); - // Fields go widest first, each at the first offset that fits it. Node's - // weight (an int32 slot: nothing stores a fraction) takes the word the - // header shares (24 bytes, not 32); Leaf keeps Node's offsets and puts its - // bool next to Node's (32 bytes, not 48). - expect(llvm).toContain(`%${mangleClassStruct("Node")} = type { i32, i32, ptr, i8 }`); - expect(llvm).toContain(`%${mangleClassStruct("Leaf")} = type { i32, i32, ptr, i8, i8, ptr }`); + // Scalars narrower than 8 bytes go first, then the rest, widest first, + // each at the first offset that fits it. Node's weight (an int32 slot: + // nothing stores a fraction) takes the word the header shares and its + // flag the next one (24 bytes, not 32); Leaf keeps Node's offsets and puts + // its bool next to Node's (32 bytes, not 48). + expect(llvm).toContain(`%${mangleClassStruct("Node")} = type { i32, i32, i8, ptr }`); + expect(llvm).toContain(`%${mangleClassStruct("Leaf")} = type { i32, i32, i8, i8, ptr, ptr }`); // Without the contract, the layout is the declared one. const mortal = emitLlvmModule({ ...mod, contracts: {} }, { pointerBits: 64 }); expect(mortal).toContain(`%${mangleClassStruct("Leaf")} = type { i64, ptr, i8, i32, ptr, i8 }`); @@ -332,6 +379,99 @@ test("references between ProgramLifetime instances are 32-bit indexes into their expect(classFieldIndex(leafMeta, "label").compressed).toBe(false); }); +test("arrays of ProgramLifetime instances keep 32-bit references in 4-byte slots", () => { + const node = { kind: "object" as const, className: "Node" }; + const nodes = { kind: "array" as const, elem: node }; + const ref = (localId: string, type: IrType): IrExpr => ({ kind: "varRef", localId, type, loc }); + const fn = (name: string, body: IrExpr, returnType: IrType): IrFunction => ({ + name, + params: [ + { name: "a", localId: "a", type: nodes }, + { name: "v", localId: "v", type: node }, + ], + returnType, + locals: [ + { id: "a", name: "a", type: nodes, mutable: false }, + { id: "v", name: "v", type: node, mutable: false }, + ], + body: [{ kind: "return", value: body, loc }], + loc, + }); + const mod: IrModule = { + irVersion: 17, + sourceFile: loc.file, + entry: "main", + functions: [ + { name: "main", params: [], returnType: VOID, locals: [], body: [], loc }, + fn( + "first", + { + kind: "arrayGet", + arr: ref("a", nodes), + index: { kind: "numLit", value: 0, type: F64, loc }, + type: node, + loc, + }, + node, + ), + fn( + "add", + { + kind: "arrIntrinsic", + method: "push", + receiver: ref("a", nodes), + args: [ref("v", node)], + type: F64, + loc, + }, + F64, + ), + fn("make", { kind: "arrayLit", elems: [ref("v", node)], type: nodes, loc }, nodes), + fn( + "find", + { + kind: "arrIntrinsic", + method: "indexOf", + receiver: ref("a", nodes), + args: [ref("v", node)], + type: F64, + loc, + }, + F64, + ), + ], + classes: [{ name: "Node", fields: [{ name: "kids", type: nodes }], methods: [], loc }], + contracts: { programLifetime: ["Node"] }, + }; + const body = (llvm: string, name: string): string => + llvm.split(/^define /m).find((f) => f.includes(`; ${name}\n`)) ?? ""; + const llvm = emitLlvmModule(mod, { pointerBits: 64, objectAudit: false, lowRegion: true }); + // The element type's ops say so (SCR_ARR_OPS_COMPACT), so the runtime makes + // the arrays SCR_ELEM_CREF. + expect(llvm).toMatch( + /^@sc_arrops\.\S+\.c = internal global \{ ptr, ptr, ptr, i32, i32 \} \{ [^}]*, i32 0, i32 1 \}$/m, + ); + // A read loads the 32-bit reference and shifts it; an append stores one. + const first = body(llvm, "first"); + expect(first).toMatch(/getelementptr inbounds i32, ptr %\S+, i64 \S+\n\s+%\S+ = load i32/); + // The states follow 4-byte slots. + expect(first).toContain("getelementptr inbounds [5 x i8]"); + expect(first).toMatch(/= inttoptr i64 %\S+ to ptr/); + expect(body(llvm, "add")).toMatch( + /= lshr i64 %\S+, 3\n\s+%\S+ = trunc i64 %\S+ to i32\n\s+store i32/, + ); + // indexOf scans the 4-byte slots for the needle's reference. + expect(llvm).toMatch(/call double @sc_arr_index_of_cref\(ptr %\S+, ptr %\S+\)/); + expect(/^define internal double @sc_arr_index_of_cref[^]*?^}/m.exec(llvm)?.[0]).toContain( + "load i32, ptr %qp0", + ); + // Elsewhere the arrays keep 8-byte slots. + const elsewhere = emitLlvmModule(mod, { pointerBits: 64, objectAudit: false }); + expect(elsewhere).not.toMatch(/sc_arrops\.\S+\.c /); + expect(body(elsewhere, "first")).not.toContain("inttoptr"); + expect(elsewhere).not.toContain("sc_arr_index_of_cref"); +}); + test("a recycled block is cleared from the end of a ProgramLifetime instance's 32-bit header", () => { const BOOL = { kind: "bool" as const }; const mod: IrModule = { diff --git a/packages/compiler/src/backend/llvm/classes.ts b/packages/compiler/src/backend/llvm/classes.ts index 3073bd1bd..8f179828d 100644 --- a/packages/compiler/src/backend/llvm/classes.ts +++ b/packages/compiler/src/backend/llvm/classes.ts @@ -703,11 +703,13 @@ export function classFieldTypes(host: ShapeHost, cls: IrClassDef, int32?: Int32S /** Gives the classes `compact` admits (whole hierarchies: the test is the * root's) the 32-bit header and packed fields. A class keeps its base's - * field offsets, and places each of its own fields, widest first, at the - * first offset after the header that fits it: in a hole another field's - * alignment left, in the base's tail padding, or at the end. So 32-bit and - * smaller fields share 8-byte words. The struct lists the header and the - * fields by offset, which LLVM's layout of the type reproduces (checked). */ + * field offsets, and places each of its own fields at the first offset + * after the header that fits it: in a hole another field's alignment left, + * in the base's tail padding, or at the end. Scalars narrower than 8 bytes + * (flags, ids, counts) go first, widest first, so they share the header's + * cache line; then the other fields, widest first. So 32-bit and smaller + * fields share 8-byte words. The struct lists the header and the fields by + * offset, which LLVM's layout of the type reproduces (checked). */ export function assignCompactLayouts( metaMap: ReadonlyMap, compact: (root: LlClassMeta) => boolean, @@ -751,10 +753,12 @@ export function assignCompactLayouts( ); return COMPACT_REF; }); + const smallScalar = (f: { type: string; field: number; size: number }): number => + f.size < 8 && f.type !== "ptr" && !compressed[f.field] ? 0 : 1; const own = types .map((type, field) => ({ type, field, ...fieldStorage(type) })) .slice(baseCount) - .sort((a, b) => b.size - a.size || a.field - b.field); + .sort((a, b) => smallScalar(a) - smallScalar(b) || b.size - a.size || a.field - b.field); for (const f of own) { const sorted = [...elems].sort((a, b) => a.offset - b.offset); let at = -1; @@ -860,9 +864,9 @@ export function emitClassShapes( nullable?: NullableRefFields, int32?: Int32Slots, ): { typeDefs: string[]; defs: string[] } { - // Whether compact instances live in the program-lifetime region (any - // field holds a 32-bit reference to one; emitter.ts assignCompactLayouts). - const regionRefs = [...metaMap.values()].some((m) => m.compressed.some(Boolean)); + // Whether compact instances live in the program-lifetime region, where + // fields and arrays can refer to them in 32 bits (LlEmitter.compactRegion). + const regionRefs = host.compactRegion?.() === true; const typeDefs: string[] = []; const defs: string[] = []; const emitted = (mod.classes ?? []).filter((c) => !c.runtime); diff --git a/packages/compiler/src/backend/llvm/common.ts b/packages/compiler/src/backend/llvm/common.ts index 822ee29e2..ac4e28708 100644 --- a/packages/compiler/src/backend/llvm/common.ts +++ b/packages/compiler/src/backend/llvm/common.ts @@ -10,9 +10,10 @@ import type { import type { LlvmEmitterContext } from "./expr-context.js"; /** Field numbers of %ScrArr, which mirrors scr_runtime.h's ScrArr field for - * field (its static assertions pin `len`, `cap`, `cyc`, `filled` and - * `data`). `len` and `cap` are i32 on every target; the dense states end - * the allocation after the `cap` value slots at `data` (scrArrStates). */ + * field (its static assertions pin `len`, `cap`, `cyc`, `spare`, `filled` + * and `data`). `len` and `cap` are i32 on every target; the dense states of + * an array with states (SCR_ARR_STATES in `spare`) end the allocation after + * the `cap` value slots at `data` (scrArrStates). */ export const SCR_ARR_FIELD = { rc: 0, len: 1, @@ -24,6 +25,10 @@ export const SCR_ARR_FIELD = { data: 7, } as const; +/** The `spare` flag of a %ScrArr whose dense slots carry state bytes + * (SCR_ARR_STATES in scr_array.h). */ +export const SCR_ARR_STATES = 16; + /** Loads the i32 `len` or `cap` of a %ScrArr at `ptr` into `dest` as a * size-type count. */ export function loadArrCount( diff --git a/packages/compiler/src/backend/llvm/constant-callbacks.test.ts b/packages/compiler/src/backend/llvm/constant-callbacks.test.ts index aa491c711..e8ca5571f 100644 --- a/packages/compiler/src/backend/llvm/constant-callbacks.test.ts +++ b/packages/compiler/src/backend/llvm/constant-callbacks.test.ts @@ -314,16 +314,19 @@ test("virtual calls admit every same-named method", () => { expect(new AmbientReceiverReaders(functions).ignores(caller)).toBe(false); }); -test("synthetic array HOF helpers are constant-callback consumers", () => { - const mod = fixture(); - const consumer = mod.functions[1]!; - const entry = mod.functions[2]!; - delete consumer.ownsPrototype; - consumer.name = "%arr.some.0"; - const call = entry.body[0]!; - if (call.kind === "exprStmt" && call.expr.kind === "call") call.expr.callee = "%arr.some.0"; - expect(facts(mod).get("%arr.some.0")?.get("test")).toBe("predicate"); -}); +test.each(["%arr.some.0", "%bytes.some.0"])( + "synthetic array and typed-array HOF helpers are constant-callback consumers (%s)", + (name) => { + const mod = fixture(); + const consumer = mod.functions[1]!; + const entry = mod.functions[2]!; + delete consumer.ownsPrototype; + consumer.name = name; + const call = entry.body[0]!; + if (call.kind === "exprStmt" && call.expr.kind === "call") call.expr.callee = name; + expect(facts(mod).get(name)?.get("test")).toBe("predicate"); + }, +); function factory(name: string, returns: IrExpr[]): IrFunction { return { diff --git a/packages/compiler/src/backend/llvm/constant-callbacks.ts b/packages/compiler/src/backend/llvm/constant-callbacks.ts index 6e6155460..cf5c1b062 100644 --- a/packages/compiler/src/backend/llvm/constant-callbacks.ts +++ b/packages/compiler/src/backend/llvm/constant-callbacks.ts @@ -29,12 +29,16 @@ export function findConstantCallbacks( mod.functions .filter( (fn) => - // Authored declarations, plus the frontend's synthetic array - // HOF loops (`%arr..`): those are plain direct-call - // functions, and a literal callback gets a helper of its own. + // Authored declarations, plus the frontend's synthetic array and + // typed-array HOF loops (`%arr..`, `%bytes..`): + // those are plain direct-call functions, and a literal callback + // gets a helper of its own. // Generator declarations are entered through their spawn wrapper, // which moves the same arguments into the generator's frame. - (fn.ownsPrototype || fn.name.startsWith("%arr.") || fn.generator !== undefined) && + (fn.ownsPrototype || + fn.name.startsWith("%arr.") || + fn.name.startsWith("%bytes.") || + fn.generator !== undefined) && (!fn.async || fn.generator !== undefined) && !fn.captures && !fn.classCaptures && @@ -248,11 +252,13 @@ export function findConstantCallbacks( // entries actually used as indirect callees in each body. A module-wide // global/function cross product would dominate large-source emission. const globalTargets = new Map(); + const result = new Map>(); + // Only indirect callees get targets: without one, nothing resolves. + if (![...indirectCallees.values()].some((callees) => callees.size > 0)) return result; for (const [id, value] of globals) { const target = resolve(null, value); if (target) globalTargets.set(id, target); } - const result = new Map>(); for (const fn of mod.functions) { const needed = indirectCallees.get(fn.name)!; if (!needed.size) continue; diff --git a/packages/compiler/src/backend/llvm/counted-loops.ts b/packages/compiler/src/backend/llvm/counted-loops.ts index 02943b852..ca2dd6b92 100644 --- a/packages/compiler/src/backend/llvm/counted-loops.ts +++ b/packages/compiler/src/backend/llvm/counted-loops.ts @@ -1,4 +1,9 @@ -import type { IntegerCountedForLoop, IntegerPairedForLoop } from "../../ir/integer-loops.js"; +import type { + IntegerCountedForLoop, + IntegerLoopFollower, + IntegerPairedForLoop, +} from "../../ir/integer-loops.js"; +import { FOLLOWER_GUARD_LIMIT } from "../../ir/integer-loops.js"; import type { IrExpr } from "../../ir/ir.js"; import type { LlvmEmitterContext } from "./expr-context.js"; import { f64Lit } from "./common.js"; @@ -61,9 +66,47 @@ export function emitCountedLoopSafety( ); } if (loop.startGuarded) safe = andSafe(host, safe, emitExactStart(host, loop.start)); + for (const follower of loop.followers) { + if (follower.startGuarded) safe = andSafe(host, safe, emitExactStart(host, follower.start)); + if (follower.tripGuarded) safe = andSafe(host, safe, emitFollowerReach(host, loop, follower)); + } return safe; } +/** `|start| + |step| * span / |driver step| <= 2^52` for a follower, where + * `span` is the distance from the driver's start to the limit. The body runs + * at most `span / |driver step| + 1` times, so every value the follower holds + * on a body entry is within the bound. NaN and infinities fail the ordered + * test. */ +function emitFollowerReach( + host: LlvmEmitterContext, + loop: IntegerCountedForLoop, + follower: IntegerLoopFollower, +): string { + const B = host.B; + const start = host.emitExpr(loop.start), + limit = host.emitExpr(loop.limit), + from = host.emitExpr(follower.start); + const span = B.tmp(), + reach = B.tmp(), + magnitude = B.tmp(), + total = B.tmp(), + ok = B.tmp(); + B.line( + loop.step > 0 + ? `${span} = fsub double ${limit.name}, ${start.name}` + : `${span} = fsub double ${start.name}, ${limit.name}`, + ); + B.line( + `${reach} = fmul double ${span}, ${f64Lit(Math.abs(follower.step) / Math.abs(loop.step))}`, + ); + host.declare(`declare double @llvm.fabs.f64(double)`); + B.line(`${magnitude} = call double @llvm.fabs.f64(double ${from.name})`); + B.line(`${total} = fadd double ${magnitude}, ${reach}`); + B.line(`${ok} = fcmp ole double ${total}, ${f64Lit(FOLLOWER_GUARD_LIMIT)}`); + return ok; +} + /** The run-time test of a guarded paired loop: each unproven start is an * exact safe integer. */ export function emitPairedLoopSafety(host: LlvmEmitterContext, loop: IntegerPairedForLoop): string { diff --git a/packages/compiler/src/backend/llvm/dense-array-access.test.ts b/packages/compiler/src/backend/llvm/dense-array-access.test.ts index 1b84cf0a0..6a0123559 100644 --- a/packages/compiler/src/backend/llvm/dense-array-access.test.ts +++ b/packages/compiler/src/backend/llvm/dense-array-access.test.ts @@ -316,6 +316,55 @@ test.each([32, 64] as const)( }, ); +test("arrays without state bytes skip the state stores", () => { + const read: IrExpr = { kind: "arrayGet", arr: ref("s", words), index, type: STRING, loc }; + const write: IrStmt = { + kind: "arraySet", + arr: ref("s", words), + index, + value: { kind: "strLit", value: "x", type: STRING, loc }, + loc, + }; + const push: IrStmt = { + kind: "exprStmt", + expr: { + kind: "arrIntrinsic", + method: "push", + receiver: ref("a", nums), + args: [{ kind: "numLit", value: 2.5, type: F64, loc }], + type: F64, + loc, + }, + loc, + }; + const llvm = emitLlvmModule( + module("plain", STRING, [push, write, { kind: "return", value: read, loc }]), + ); + const fn = body(llvm, "plain"); + // SCR_ARR_STATES (16) in `spare`, field 5. + const flag = String.raw`getelementptr inbounds %ScrArr, ptr %t\d+, i32 0, i32 5\n %t\d+ = load i16, ptr %t\d+, !tbaa !\d+\n %t\d+ = and i16 %t\d+, 16\n %t\d+ = icmp ne i16 %t\d+, 0\n`; + // A push marks the state only when the array has states. + expect(fn).toMatch( + new RegExp( + `${flag} br i1 %t\\d+, label %arr\\.push\\.state\\d+, label %arr\\.push\\.marked\\d+\\narr\\.push\\.state\\d+:\\n store i8 1, ptr `, + ), + ); + // Above the prefix, an array without states has no elements (its prefix + // is its length): a store there appends at the length and replaces no + // value. + expect(fn).toMatch( + new RegExp( + `${flag} br i1 %t\\d+, label %arr\\.set\\.states\\d+, label %arr\\.set\\.plain\\d+`, + ), + ); + expect(fn).toMatch( + /^arr\.set\.plain\d+:\n %t\d+ = icmp eq i64 .*\n br i1 %t\d+, label %arr\.set\.values\d+, label %arr\.set\.slow\d+$/m, + ); + expect(fn).toMatch(/phi i1 \[ %t\d+, %arr\.set\.states\d+ \], \[ false, %arr\.set\.values\d+ \]/); + // Reads test no flag: they reach the state check only above the prefix. + expect(fn).not.toMatch(/label %arr\.get\.state\d+/); +}); + test("state and presence queries answer dense slots inline", () => { const state: IrExpr = { kind: "arrayState", arr: ref("b", flags), index, type: F64, loc }; const has: IrExpr = { kind: "arrayHas", arr: ref("s", words), index, type: BOOL, loc }; diff --git a/packages/compiler/src/backend/llvm/dense-array-access.ts b/packages/compiler/src/backend/llvm/dense-array-access.ts index 4488f90cb..9158d12cd 100644 --- a/packages/compiler/src/backend/llvm/dense-array-access.ts +++ b/packages/compiler/src/backend/llvm/dense-array-access.ts @@ -14,23 +14,48 @@ * state bytes altogether: the runtime keeps every state below it a present * value, so reads load the slot directly and writes replace it without * touching its state. Other dense indices take the state-checked path, - * whose writes extend the bound when they continue it. */ + * whose writes extend the bound when they continue it. An array without + * state bytes (SCR_ARR_STATES clear in `spare`) keeps its bound at its + * length, so reads never reach the state check for it; a write past the + * bound tests the flag and, without states, appends at the length. */ import { isRefCounted, type IrExpr, type IrType } from "../../ir/ir.js"; import { f64Lit, loadArrCount, SCR_ARR_FIELD, + SCR_ARR_STATES, scrArrStatePtr, scrArrStates, sizeToDouble, storeArrCount, } from "./common.js"; import type { LlValue, LlvmEmitterContext } from "./expr-context.js"; +import { compactRefLoadLines, compactRefStoreLines } from "./classes.js"; +import { elemAccess } from "./shapes.js"; import { exactInteger, widenInteger } from "./integer-values.js"; +import { integerOrNaNIndex } from "./wrapping-sums.js"; const SCR_ARR_VALUE = 1; +/** Whether the array at `array` has state bytes, as an i1. `spare` changes + * only in runtime calls, so its loads take their own alias tag. */ +export function emitArrayHasStates(host: LlvmEmitterContext, array: string): string { + const B = host.B; + const sparePtr = B.tmp(), + spare = B.tmp(), + bit = B.tmp(), + has = B.tmp(); + B.line( + `${sparePtr} = getelementptr inbounds %ScrArr, ptr ${array}, i32 0, i32 ${SCR_ARR_FIELD.spare}`, + ); + host.markMemoryPointer(sparePtr, "array:spare"); + B.line(`${spare} = load i16, ptr ${sparePtr}${host.fieldAliasAttachment(sparePtr)}`); + B.line(`${bit} = and i16 ${spare}, ${SCR_ARR_STATES}`); + B.line(`${has} = icmp ne i16 ${bit}, 0`); + return has; +} + /** Call-site effects of the non-retaining read fallbacks: they only read * module-visible memory, or trap without returning to the caller (the trap * writes runtime-private stderr/TLS state). Declaring this lets LLVM keep @@ -75,12 +100,17 @@ function emitDenseGuard( const B = host.B; const size = host.sizeType; const integer = exactInteger(host, index, indexExpr); + const nanIndex = integer ? null : integerOrNaNIndex(host, index, indexExpr); let wide: string; let integral: string | null = null; if (integer) { // A proven integer needs no double round-trip. Negative signed values // compare above any length or capacity as unsigned 64-bit integers. wide = widenInteger(host, integer); + } else if (nanIndex) { + // An exact integer or NaN is an index exactly when it is ordered. + wide = nanIndex.wide; + integral = nanIndex.ordered; } else { // freeze keeps NaN/out-of-range conversions from producing poison; the // exact round-trip comparison then rejects every value that is not an @@ -209,26 +239,40 @@ function statePointer( return statePtr; } -/** The dense slot type: boolean arrays store one byte per element, every - * other element kind an 8-byte slot. */ -function slotType(acc: ArrayAccess): "i8" | "i64" { - return acc === "bool" ? "i8" : "i64"; +/** How an array's dense slots hold its elements: the access kind, or + * `cref` for references to compact class instances (SCR_ELEM_CREF: a 4-byte + * slot holding the address over 8; LlEmitter.compactArrayElem). */ +type SlotKind = ArrayAccess | "cref"; + +function slotKind(host: LlvmEmitterContext, acc: ArrayAccess, element: IrType): SlotKind { + return acc === "ref" && host.compactArrayElem(element) ? "cref" : acc; +} + +/** The dense slot type: boolean arrays store one byte per element, compact + * references four, every other element kind an 8-byte slot. */ +function slotType(kind: SlotKind): "i8" | "i32" | "i64" { + return kind === "bool" ? "i8" : kind === "cref" ? "i32" : "i64"; } /** Bytes per dense slot (scr_arr_slot_width). */ -export function slotWidth(acc: ArrayAccess): number { - return acc === "bool" ? 1 : 8; +function slotWidth(kind: SlotKind): number { + return kind === "bool" ? 1 : kind === "cref" ? 4 : 8; +} + +/** Bytes per dense slot of an array of `element` (scr_arr_slot_width). */ +export function denseSlotWidth(host: LlvmEmitterContext, element: IrType): number { + return slotWidth(slotKind(host, elemAccess(element), element)); } function valuePointer( host: LlvmEmitterContext, guard: Pick, - acc: ArrayAccess, + kind: SlotKind, ): string { const B = host.B; const valuePtr = B.tmp(); B.line( - `${valuePtr} = getelementptr inbounds ${slotType(acc)}, ptr ${guard.data}, ${host.sizeType} ${guard.offset}`, + `${valuePtr} = getelementptr inbounds ${slotType(kind)}, ptr ${guard.data}, ${host.sizeType} ${guard.offset}`, ); host.markMemoryPointer(valuePtr, "array:elements"); return valuePtr; @@ -300,6 +344,7 @@ export function emitDenseArrayGet( const B = host.B; const ty = acc === "f64" ? "double" : acc === "bool" ? "i1" : "ptr"; const ret = acc === "bool" ? "zeroext i1" : ty; + const kind = slotKind(host, acc, element); host.declare(`declare ${ret} @${getter}(ptr, double)`); if (acc === "ref" && retain && !isRefCounted(element)) { const t = B.tmp(); @@ -322,7 +367,7 @@ export function emitDenseArrayGet( slow, true, valueLabel, - slotWidth(acc), + slotWidth(kind), proven, induction, ); @@ -333,7 +378,7 @@ export function emitDenseArrayGet( B.condBr(present, valueLabel, slow); } B.startBlock(valueLabel); - const ptr = valuePointer(host, guard, acc); + const ptr = valuePointer(host, guard, kind); let fast: string; let fastLabel = valueLabel; if (acc === "f64") { @@ -347,7 +392,13 @@ export function emitDenseArrayGet( } else { const raw = B.tmp(), nonnull = B.tmp(); - B.line(`${raw} = load ptr, ptr ${ptr}${host.fieldAliasAttachment(ptr)}`); + if (kind === "cref") { + const ref = B.tmp(); + B.line(`${ref} = load i32, ptr ${ptr}${host.fieldAliasAttachment(ptr)}`); + for (const line of compactRefLoadLines(ref, raw, `${raw}.r`)) B.line(line.trimStart()); + } else { + B.line(`${raw} = load ptr, ptr ${ptr}${host.fieldAliasAttachment(ptr)}`); + } B.line(`${nonnull} = icmp ne ptr ${raw}, null`); fastLabel = B.newLabel("arr.get.ref"); B.condBr(nonnull, fastLabel, slow); @@ -448,6 +499,7 @@ export function emitDenseArraySet( ): void { const B = host.B; const ty = acc === "f64" ? "double" : acc === "bool" ? "i1" : "ptr"; + const kind = slotKind(host, acc, element); const setter = `scr_arr_set_${acc}`; host.declare(`declare void @${setter}(ptr, double, ${acc === "bool" ? "i1 zeroext" : ty})`); const call = (attrs: string): void => @@ -467,7 +519,7 @@ export function emitDenseArraySet( slow, false, filledLabel, - slotWidth(acc), + slotWidth(kind), proven, ); const { offset, len } = guard; @@ -478,22 +530,57 @@ export function emitDenseArraySet( const bits = B.tmp(); B.line(`${bits} = zext i1 ${value} to i8`); B.line(`store i8 ${bits}, ptr ${valuePtr}${host.fieldAliasAttachment(valuePtr)}`); + } else if (kind === "cref") { + const ref = B.tmp(); + for (const line of compactRefStoreLines(value, ref, `${ref}.r`)) B.line(line.trimStart()); + B.line(`store i32 ${ref}, ptr ${valuePtr}${host.fieldAliasAttachment(valuePtr)}`); } else { B.line(`store ptr ${value}, ptr ${valuePtr}${host.fieldAliasAttachment(valuePtr)}`); } }; + const stated = B.newLabel("arr.set.states"), + plain = B.newLabel("arr.set.plain"), + plainStore = B.newLabel("arr.set.values"), + stored = B.newLabel("arr.set.stored.slot"); + B.condBr(emitArrayHasStates(host, array), stated, plain); + B.startBlock(stated); const statePtr = statePointer(host, guard); - const valuePtr = valuePointer(host, guard, acc); - let oldState: string | null = null; - let old: string | null = null; - if (acc === "ref") { - oldState = B.tmp(); - old = B.tmp(); + const valuePtr = valuePointer(host, guard, kind); + let statedOld: string | null = null; + let statedHad: string | null = null; + // Compact instances are never released: a replaced one needs nothing. + if (kind === "ref") { + const oldState = B.tmp(); + statedOld = B.tmp(); + statedHad = B.tmp(); B.line(`${oldState} = load i8, ptr ${statePtr}${host.fieldAliasAttachment(statePtr)}`); - B.line(`${old} = load ptr, ptr ${valuePtr}${host.fieldAliasAttachment(valuePtr)}`); + B.line(`${statedOld} = load ptr, ptr ${valuePtr}${host.fieldAliasAttachment(valuePtr)}`); + B.line(`${statedHad} = icmp eq i8 ${oldState}, ${SCR_ARR_VALUE}`); } storeValue(valuePtr); B.line(`store i8 ${SCR_ARR_VALUE}, ptr ${statePtr}${host.fieldAliasAttachment(statePtr)}`); + const statedEnd = B.currentLabel(); + B.br(stored); + // Without states the bound is the length, so a store here appends at + // the length (it replaces no value) or leaves holes, which the runtime + // gives states. + B.startBlock(plain); + const appends = B.tmp(); + B.line(`${appends} = icmp eq ${host.sizeType} ${offset}, ${len}`); + B.condBr(appends, plainStore, slow); + B.startBlock(plainStore); + storeValue(valuePointer(host, guard, kind)); + const plainEnd = B.currentLabel(); + B.br(stored); + B.startBlock(stored); + let old: string | null = null; + let hadValue: string | null = null; + if (kind === "ref") { + old = B.tmp(); + hadValue = B.tmp(); + B.line(`${old} = phi ptr [ ${statedOld}, %${statedEnd} ], [ null, %${plainEnd} ]`); + B.line(`${hadValue} = phi i1 [ ${statedHad}, %${statedEnd} ], [ false, %${plainEnd} ]`); + } // A store at the bound continues the hole-free prefix. const filledWide = sizedFilled(host, guard.filled), continues = B.tmp(); @@ -537,9 +624,7 @@ export function emitDenseArraySet( storeArrCount(host, nextLen, lenPtr, host.fieldAliasAttachment(lenPtr)); B.br(storedLabel); B.startBlock(storedLabel); - if (acc === "ref" && oldState && old) { - const hadValue = B.tmp(); - B.line(`${hadValue} = icmp eq i8 ${oldState}, ${SCR_ARR_VALUE}`); + if (kind === "ref" && hadValue && old) { const releaseLabel = B.newLabel("arr.set.release"); B.condBr(hadValue, releaseLabel, join); B.startBlock(releaseLabel); @@ -549,9 +634,9 @@ export function emitDenseArraySet( // Below the bound the slot holds a present value: replace it, leaving // the state alone, and release a replaced reference after the store. B.startBlock(filledLabel); - const filledValuePtr = valuePointer(host, guard, acc); + const filledValuePtr = valuePointer(host, guard, kind); let filledOld: string | null = null; - if (acc === "ref") { + if (kind === "ref") { filledOld = B.tmp(); B.line( `${filledOld} = load ptr, ptr ${filledValuePtr}${host.fieldAliasAttachment(filledValuePtr)}`, @@ -578,10 +663,12 @@ export function emitDenseArrayPop( host: LlvmEmitterContext, array: string, acc: ArrayAccess, + element: IrType, empty: string, slow: string, ): string { const B = host.B; + const kind = slotKind(host, acc, element); const size = host.sizeType; const header = (field: number): string => { const ptr = B.tmp(); @@ -615,19 +702,33 @@ export function emitDenseArrayPop( states = B.tmp(); B.line(`${data} = load ptr, ptr ${dataPtr}${host.fieldAliasAttachment(dataPtr)}`); loadArrCount(host, cap, capPtr, host.fieldAliasAttachment(capPtr)); - scrArrStates(host, states, data, cap, slotWidth(acc)); - const valuePtr = valuePointer(host, { offset: last, data }, acc); + scrArrStates(host, states, data, cap, slotWidth(kind)); + const valuePtr = valuePointer(host, { offset: last, data }, kind); const statePtr = statePointer(host, { offset: last, states }); - const slotTy = slotType(acc); + const slotTy = slotType(kind); let raw = B.tmp(); B.line(`${raw} = load ${slotTy}, ptr ${valuePtr}${host.fieldAliasAttachment(valuePtr)}`); if (slotTy === "i8") { const wide = B.tmp(); B.line(`${wide} = zext i8 ${raw} to i64`); raw = wide; + } else if (slotTy === "i32") { + // The 8-byte slot of a compact reference is its address. + const wide = B.tmp(), + address = B.tmp(); + B.line(`${wide} = zext i32 ${raw} to i64`); + B.line(`${address} = shl nuw nsw i64 ${wide}, 3`); + raw = address; } B.line(`store ${slotTy} 0, ptr ${valuePtr}${host.fieldAliasAttachment(valuePtr)}`); + // Only an array with states has a state byte to clear. + const clear = B.newLabel("arr.pop.state"), + cleared = B.newLabel("arr.pop.cleared"); + B.condBr(emitArrayHasStates(host, array), clear, cleared); + B.startBlock(clear); B.line(`store i8 0, ptr ${statePtr}${host.fieldAliasAttachment(statePtr)}`); + B.br(cleared); + B.startBlock(cleared); let last32 = last; if (size === "i64") { last32 = B.tmp(); @@ -648,10 +749,12 @@ export function emitDenseArrayPush( host: LlvmEmitterContext, array: string, acc: ArrayAccess, + element: IrType | null, value: string, ): string { const B = host.B; const size = host.sizeType; + const kind = element === null ? acc : slotKind(host, acc, element); const ty = acc === "f64" ? "double" : acc === "bool" ? "i1" : "ptr"; const pusher = `scr_arr_push_${acc}`; host.declare(`declare double @${pusher}(ptr, ${acc === "bool" ? "i1 zeroext" : ty})`); @@ -685,20 +788,31 @@ export function emitDenseArrayPush( B.line(`${spare} = sub nuw ${size} ${cap}, ${len}`); B.line(`${near} = getelementptr inbounds i8, ptr ${data}, ${size} ${spare}`); B.line( - `${statePtr} = getelementptr inbounds [${slotWidth(acc)} x i8], ptr ${near}, ${size} ${cap}, ${size} -1`, + `${statePtr} = getelementptr inbounds [${slotWidth(kind)} x i8], ptr ${near}, ${size} ${cap}, ${size} -1`, ); host.markMemoryPointer(statePtr, "array:present"); - const valuePtr = valuePointer(host, { offset: len, data }, acc); + const valuePtr = valuePointer(host, { offset: len, data }, kind); if (acc === "f64") { B.line(`store double ${value}, ptr ${valuePtr}${host.fieldAliasAttachment(valuePtr)}`); } else if (acc === "bool") { const bits = B.tmp(); B.line(`${bits} = zext i1 ${value} to i8`); B.line(`store i8 ${bits}, ptr ${valuePtr}${host.fieldAliasAttachment(valuePtr)}`); + } else if (kind === "cref") { + const ref = B.tmp(); + for (const line of compactRefStoreLines(value, ref, `${ref}.r`)) B.line(line.trimStart()); + B.line(`store i32 ${ref}, ptr ${valuePtr}${host.fieldAliasAttachment(valuePtr)}`); } else { B.line(`store ptr ${value}, ptr ${valuePtr}${host.fieldAliasAttachment(valuePtr)}`); } + // Only an array with states has a state byte to mark. + const mark = B.newLabel("arr.push.state"), + marked = B.newLabel("arr.push.marked"); + B.condBr(emitArrayHasStates(host, array), mark, marked); + B.startBlock(mark); B.line(`store i8 ${SCR_ARR_VALUE}, ptr ${statePtr}${host.fieldAliasAttachment(statePtr)}`); + B.br(marked); + B.startBlock(marked); const next = B.tmp(), fastValue = B.tmp(); B.line(`${next} = add nuw ${size} ${len}, 1`); @@ -716,6 +830,7 @@ export function emitDenseArrayPush( B.line(`${bumped} = select i1 ${packed}, i32 ${nextFilled}, i32 ${filled}`); B.line(`store i32 ${bumped}, ptr ${filledPtr}${host.fieldAliasAttachment(filledPtr)}`); B.line(`${fastValue} = ${sizeToDouble(size)} ${size} ${next} to double`); + const fastEnd = B.currentLabel(); B.br(join); B.startBlock(slow); const slowValue = B.tmp(); @@ -723,6 +838,6 @@ export function emitDenseArrayPush( B.br(join); B.startBlock(join); const result = B.tmp(); - B.line(`${result} = phi double [ ${fastValue}, %${fast} ], [ ${slowValue}, %${slow} ]`); + B.line(`${result} = phi double [ ${fastValue}, %${fastEnd} ], [ ${slowValue}, %${slow} ]`); return result; } diff --git a/packages/compiler/src/backend/llvm/dense-array-loops.test.ts b/packages/compiler/src/backend/llvm/dense-array-loops.test.ts index 405ad67e7..f7a4bc892 100644 --- a/packages/compiler/src/backend/llvm/dense-array-loops.test.ts +++ b/packages/compiler/src/backend/llvm/dense-array-loops.test.ts @@ -1,5 +1,6 @@ import { expect, test } from "vitest"; import { BOOL, F64, arrayOf, type IrExpr, type IrLocal, type IrStmt } from "../../ir/ir.js"; +import type { IntegerCountedForLoop } from "../../ir/integer-loops.js"; import { countedDenseShape, matchDenseArrayLoop, @@ -111,16 +112,24 @@ test("loops that may resize, rebind or move storage keep the ordinary copy only" expect([...rebound!.arrays.keys()]).toEqual(["a"]); }); +const counted = ( + fields: Pick, +): IntegerCountedForLoop => ({ + localId: "i", + guarded: false, + limitGuarded: false, + startGuarded: false, + guardLimit: 0, + followers: [], + ...fields, +}); + test("counted shapes need a non-negative counter strictly below the length", () => { const ascending = (limit: IrExpr, inclusive: boolean, min = 0) => - countedDenseShape(loop([]), { - localId: "i", - start: num(min), - limit, - step: 1, - inclusive, - range: { min, max: 100 }, - }); + countedDenseShape( + loop([]), + counted({ start: num(min), limit, step: 1, inclusive, range: { min, max: 100 } }), + ); const minus = (offset: number): IrExpr => ({ kind: "bin", op: "-", @@ -129,19 +138,58 @@ test("counted shapes need a non-negative counter strictly below the length", () type: F64, loc, }); - expect(ascending(method("a", "length"), false)?.length.localId).toBe("a"); - expect(ascending(minus(1), true)?.length.localId).toBe("a"); + expect(ascending(method("a", "length"), false)?.length?.localId).toBe("a"); + expect(ascending(minus(1), true)?.length?.localId).toBe("a"); expect(ascending(method("a", "length"), true)).toBeNull(); expect(ascending(minus(1), false, -1)).toBeNull(); + // Another invariant limit bounds the counter itself; the entry test + // compares it with every indexed array's hole-free prefix. + const limited = ascending(ref("n"), false); + expect(limited?.length).toBeNull(); + expect(limited?.limit?.limit).toEqual(ref("n")); + expect(ascending(ref("n"), false, -1)).toBeNull(); const descending = (offset: number) => - countedDenseShape(loop([]), { - localId: "i", - start: minus(offset), - limit: num(0), - step: -1, - inclusive: true, - range: { min: 0, max: 100 }, - }); - expect(descending(1)?.length.localId).toBe("a"); + countedDenseShape( + loop([]), + counted({ + start: minus(offset), + limit: num(0), + step: -1, + inclusive: true, + range: { min: 0, max: 100 }, + }), + ); + expect(descending(1)?.length?.localId).toBe("a"); expect(descending(0)).toBeNull(); }); + +test("a loop to another invariant limit covers each array whose length it keeps", () => { + const limited: DenseLoopShape = { + counter: "i", + length: null, + limit: counted({ + start: num(0), + limit: ref("n"), + step: 1, + inclusive: false, + range: { min: 0, max: 100 }, + }), + range: { min: 0, max: 100 }, + }; + const matchLimited = (body: IrStmt[], unaliased = new Set()) => + matchDenseArrayLoop(loop(body), limited, locals, unaliased, new Set(["a", "b"])); + const copy = write("b", read("a")); + const dense = matchLimited([copy]); + expect([...dense!.arrays.keys()].sort()).toEqual(["a", "b"]); + expect(dense!.length).toBeNull(); + expect(dense!.limit?.limit).toEqual(ref("n")); + // An array the loop may resize is not covered; neither is one it may + // share storage with. + const resizing = [ + { kind: "exprStmt" as const, expr: read("a"), loc }, + { kind: "exprStmt" as const, expr: method("b", "getNumber", [ref("i")]), loc }, + { kind: "exprStmt" as const, expr: method("b", "push", [num(1)]), loc }, + ]; + expect([...matchLimited(resizing, new Set(["b"]))!.arrays.keys()]).toEqual(["a"]); + expect(matchLimited(resizing)).toBeNull(); +}); diff --git a/packages/compiler/src/backend/llvm/dense-array-loops.ts b/packages/compiler/src/backend/llvm/dense-array-loops.ts index 708825344..184ff1353 100644 --- a/packages/compiler/src/backend/llvm/dense-array-loops.ts +++ b/packages/compiler/src/backend/llvm/dense-array-loops.ts @@ -15,22 +15,33 @@ * test bounds `a.length` by 2^31 - 1, so the fast copy's counter is an int32. * Arrays longer than that are sparse in practice (a dense one would need * 16 GB of slots) and take the ordinary copy, as does every array with a - * hole, present undefined or sparse storage below `a.length`. */ + * hole, present undefined or sparse storage below `a.length`. + * + * A counted loop with another invariant limit, such as `j < n` after + * `const n = a.length` or `j < 5`, is covered the same way: the test bounds + * the loop's exclusive limit by 2^31 - 1 and by each indexed array's + * `filled`, and the loop must provably never change any of their lengths. */ import type { IrExpr, IrLocal, IrStmt } from "../../ir/ir.js"; import type { IntegerRange } from "../../ir/integer-ranges.js"; import { preservesArrayLength } from "../../ir/array-length-stability.js"; import { everyExprChild, everyStmtChild } from "../../ir/traverse.js"; +import type { IntegerCountedForLoop } from "../../ir/integer-loops.js"; import type { LlvmEmitterContext } from "./expr-context.js"; import { loadArrCount, SCR_ARR_FIELD } from "./common.js"; +import { emitCountedLoopLimit } from "./counted-loops.js"; export const INT32_MAX = 2147483647; export interface DenseArrayLoop { /** The loop's counter binding. */ counter: string; - /** The array whose length bounds the counter. */ - length: IrExpr & { kind: "varRef" }; + /** The array whose length bounds the counter, or null for a counted loop + * bounded by `limit`. */ + length: (IrExpr & { kind: "varRef" }) | null; + /** The ascending counted loop whose invariant limit bounds the counter, + * when `length` is null. */ + limit: IntegerCountedForLoop | null; /** Arrays whose accesses at the counter are proven to be inside the * hole-free prefix in the fast copy, with a read of each binding. */ arrays: ReadonlyMap; @@ -39,12 +50,15 @@ export interface DenseArrayLoop { } /** The fast copy duplicates the loop; keep the duplicated code small. */ -const MAX_LOOP_NODES = 120; +const MAX_LOOP_NODES = 160; /** How a matched integer loop bounds its counter below `length.length`. */ export interface DenseLoopShape { counter: string; - length: IrExpr & { kind: "varRef" }; + /** The array whose length bounds the counter, or null for `limit`. */ + length: (IrExpr & { kind: "varRef" }) | null; + /** An ascending counted loop bounded by another invariant limit. */ + limit?: IntegerCountedForLoop; /** The counter's proven range on every pass of the ordinary loop; the * fast copy keeps its minimum, which must be at least 0. */ range: IntegerRange; @@ -73,22 +87,18 @@ function lengthOffset(e: IrExpr): { receiver: IrExpr & { kind: "varRef" }; offse /** The array bounding a counted loop's counter below its length: an * ascending loop compared below `a.length - c`, or a descending one starting - * at `a.length - c` (c >= 1). */ + * at `a.length - c` (c >= 1). Another ascending loop is bounded by its own + * invariant limit. */ export function countedDenseShape( loop: IrStmt & { kind: "for" }, - counted: { - localId: string; - start: IrExpr; - limit: IrExpr; - step: number; - inclusive: boolean; - range: IntegerRange; - }, + counted: IntegerCountedForLoop, ): DenseLoopShape | null { if (counted.range.min < 0) return null; if (counted.step > 0) { const bound = lengthOffset(counted.limit); - if (!bound || bound.offset < (counted.inclusive ? 1 : 0)) return null; + if (!bound) + return { counter: counted.localId, length: null, limit: counted, range: counted.range }; + if (bound.offset < (counted.inclusive ? 1 : 0)) return null; return { counter: counted.localId, length: bound.receiver, range: counted.range }; } // The start is evaluated once, before the loop; the counter only falls. @@ -143,9 +153,11 @@ export function matchDenseArrayLoop( return everyStmtChild(s, expr, stmt); }; if (!loop.body.every(stmt) || !expr(loop.cond) || nested) return null; + const nodesOfLoop = [loop.cond, ...loop.body]; if ( + length !== null && !preservesArrayLength( - [loop.cond, ...loop.body], + nodesOfLoop, { receiver: length.localId, inRange: counter }, locals, unaliased, @@ -161,7 +173,14 @@ export function matchDenseArrayLoop( local.boxed || local.tdz || disturbed.has(id) || - (id !== length.localId && !initialized.has(id)) + (id !== length?.localId && !initialized.has(id)) + ) + continue; + // Without a bounding array, the entry test reads each array's `filled` + // once: the loop must not change any of their lengths. + if ( + length === null && + !preservesArrayLength(nodesOfLoop, { receiver: id, inRange: counter }, locals, unaliased) ) continue; arrays.set(id, ref); @@ -170,13 +189,15 @@ export function matchDenseArrayLoop( return { counter, length, + limit: length === null ? (shape.limit ?? null) : null, arrays, range: { min: shape.range.min, max: Math.min(shape.range.max, INT32_MAX - 1) }, }; } -/** The fast copy's entry test: the bounding length is at most 2^31 - 1 and - * at most every indexed array's hole-free prefix bound. */ +/** The fast copy's entry test: the bounding length (or the counted loop's + * exclusive limit) is at most 2^31 - 1 and at most every indexed array's + * hole-free prefix bound. */ export function emitDenseLoopGuard(host: LlvmEmitterContext, loop: DenseArrayLoop): string { const B = host.B; const size = host.sizeType; @@ -186,7 +207,29 @@ export function emitDenseLoopGuard(host: LlvmEmitterContext, loop: DenseArrayLoo host.markMemoryPointer(ptr, "array:header"); return ptr; }; - const receiver = host.emitStableReceiver(loop.length, []); + if (loop.length === null) { + // A limit at or below the start runs no pass, and passes the test. + const limit = emitCountedLoopLimit(host, loop.limit!); + const small = B.tmp(); + B.line(`${small} = icmp sle i64 ${limit}, ${INT32_MAX}`); + let valid = small; + for (const ref of loop.arrays.values()) { + const array = host.emitStableReceiver(ref, []); + const filledPtr = header(array.name, SCR_ARR_FIELD.filled), + filled = B.tmp(), + wide = B.tmp(), + covered = B.tmp(), + both = B.tmp(); + B.line(`${filled} = load i32, ptr ${filledPtr}${host.fieldAliasAttachment(filledPtr)}`); + B.line(`${wide} = zext i32 ${filled} to i64`); + B.line(`${covered} = icmp sle i64 ${limit}, ${wide}`); + B.line(`${both} = and i1 ${valid}, ${covered}`); + valid = both; + } + return valid; + } + const length = loop.length; + const receiver = host.emitStableReceiver(length, []); const lenPtr = header(receiver.name, SCR_ARR_FIELD.len), len = B.tmp(), small = B.tmp(); @@ -194,7 +237,7 @@ export function emitDenseLoopGuard(host: LlvmEmitterContext, loop: DenseArrayLoo B.line(`${small} = icmp ule ${size} ${len}, ${INT32_MAX}`); let valid = small; for (const [id, ref] of loop.arrays) { - const array = id === loop.length.localId ? receiver : host.emitStableReceiver(ref, []); + const array = id === length.localId ? receiver : host.emitStableReceiver(ref, []); const filledPtr = header(array.name, SCR_ARR_FIELD.filled), filled = B.tmp(), covered = B.tmp(), diff --git a/packages/compiler/src/backend/llvm/dyn.ts b/packages/compiler/src/backend/llvm/dyn.ts index 6911ef98b..bb00e4563 100644 --- a/packages/compiler/src/backend/llvm/dyn.ts +++ b/packages/compiler/src/backend/llvm/dyn.ts @@ -1,6 +1,6 @@ import { typedRefConstructor } from "./shapes.js"; import { bindLiveArrayOps } from "./expr-stream-bridges.js"; -import { BYTES_ELEM_NUM, SCR_ARR_FIELD, f64Lit, sizeToDouble } from "./common.js"; +import { BYTES_ELEM_NUM, SCR_ARR_FIELD, SCR_ARR_STATES, f64Lit, sizeToDouble } from "./common.js"; import { emitUnionPeek, emitUnionTag } from "./union-repr.js"; import { INLINE_UNION_FIELD, @@ -108,6 +108,15 @@ const DYN_HANDLE_UNBOX_FN: Record = { dgramSocket: "scr_dgram_from_dyn", }; +/** ScrMessageKind (scr_message.h): the node kinds message readers test. */ +const MESSAGE_KIND = { + UNDEFINED: 0, + NULL: 1, + BOOL: 2, + NUMBER: 3, + STRING: 4, +} as const; + export const DYN_KIND = { NULL: 0, BOOL: 1, @@ -173,6 +182,8 @@ export class LlDyn { private readonly dynFuncThunks = new Map(); private readonly dynFuncBoxes = new Map(); private readonly dynFuncAdapters = new Map(); + private readonly messageListeners = new Map(); + private readonly messageReaders = new Map(); private readonly promiseDynAdapters = new Map(); private readonly mapDynOps = new Map(); private dynToStrFn: string | null = null; @@ -185,6 +196,55 @@ export class LlDyn { constructor(private readonly host: DynHost) {} + /** Journal replay (emit-journal.ts): builds or finds the helper a chunk + * emitter recorded, and answers its name. */ + replayHelper(op: string, args: readonly unknown[]): string { + switch (op) { + case "dyn.collectionDynOps": + return this.collectionDynOps(args[0] as IrType & { kind: "map" | "set" }); + case "dyn.dynMatchHelper": + return this.dynMatchHelper(args[0] as IrType, args[1] as boolean); + case "dyn.jsonSchema": + return this.jsonSchema(args[0] as IrType); + case "dyn.recordNameTable": { + const shapeId = args[0] as string; + return this.recordNameTable(shapeId, this.host.recordsById.get(shapeId)!).names; + } + case "dyn.jsonParseHelper": + return this.jsonParseHelper(args[0] as IrType)!; + case "dyn.dynCheckHelper": + return this.dynCheckHelper(args[0] as IrType, args[1] as boolean); + case "dyn.toDynHelper": + return this.toDynHelper(args[0] as IrType); + case "dyn.promiseDynAdapterHelper": + return this.promiseDynAdapterHelper(args[0] as IrType); + case "dyn.dynFuncThunkHelper": + return this.dynFuncThunkHelper(args[0] as IrType & { kind: "func" }); + case "dyn.dynFuncBoxHelper": + return this.dynFuncBoxHelper(args[0] as IrType & { kind: "func" }); + case "dyn.dynFuncAdapterHelper": + return this.dynFuncAdapterHelper(args[0] as IrType & { kind: "func" }); + case "dyn.dynToStrHelper": + return this.dynToStrHelper(); + case "dyn.dynIterNHelper": + return this.dynIterNHelper(); + case "dyn.dynDestrCheckHelper": + return this.dynDestrCheckHelper(); + case "dyn.dynKeyGetHelper": + return this.dynKeyGetHelper(); + case "dyn.dynComputedKeyGetHelper": + return this.dynComputedKeyGetHelper(); + case "dyn.caughtToDynHelper": + return this.caughtToDynHelper(); + case "dyn.messageListenerHelper": + return this.messageListenerHelper(args[0] as IrType & { kind: "func" }) ?? ""; + case "dyn.messageReaderHelper": + return this.messageReaderHelper(args[0] as IrType); + default: + throw new InternalCompilerError(`llvm emitter bug: no dyn helper replay ${op}`); + } + } + /** The types a dyn matcher or builder for `t` checks structurally: record * fields and index values, array elements and union arms. */ private structuralChildren(t: IrType): readonly IrType[] { @@ -374,6 +434,7 @@ export class LlDyn { if (prior) return prior; const name = `sc_map_dyn_${this.mapDynOps.size}`; this.mapDynOps.set(key, name); + this.host.journalAllocated?.(name, "dyn.collectionDynOps", [t]); const keyType = t.kind === "map" ? t.key : t.elem; const valueType: IrType = t.kind === "map" ? t.value : { kind: "f64" }; const emitSlot = (type: IrType, role: string): void => { @@ -431,6 +492,7 @@ export class LlDyn { `@${name} = internal constant { ptr, ptr, ptr, ptr, ptr, ptr } { ptr ${this.host.cstr(key)}, ptr @${name}_key_box, ptr @${name}_key_unbox, ptr @${this.dynMatchHelper(keyType)}, ptr @${name}_value_box, ptr @${name}_value_unbox }`, "", ); + this.host.journalBuilt?.(); return name; } @@ -829,6 +891,7 @@ export class LlDyn { if (existing) return existing; const name = `sc_dm_${this.dynMatchers.size}`; this.dynMatchers.set(matcherKey, name); + this.host.journalAllocated?.(name, "dyn.dynMatchHelper", [t, preserveRefs]); const recursive = this.isRecursiveShape(t); const wrapped = recursive || this.holdsRecursiveShape(t); const B = new BlockBuilder(); @@ -1189,6 +1252,7 @@ export class LlDyn { ``, ); if (wrapped) this.emitVisitWrapper(name, t, recursive ? "match" : "visit"); + this.host.journalBuilt?.(); return name; } @@ -1282,6 +1346,7 @@ export class LlDyn { const S = host.sizeType; const name = `sc_jsch_${this.jsonSchemas.size}`; this.jsonSchemas.set(key, name); + this.host.journalAllocated?.(name, "dyn.jsonSchema", [t]); let body: string; switch (t.kind) { case "f64": @@ -1353,6 +1418,7 @@ export class LlDyn { `@${name} = internal constant { ${S}, ${S}, ptr, ptr, ptr, ptr, ptr, ptr, ${S} } { ${body} }`, ``, ); + this.host.journalBuilt?.(); return name; } @@ -1442,6 +1508,7 @@ export class LlDyn { const base = `sc_rnames_${this.recordNameTables.size}`; const table = { names: `@${base}`, lens: `@${base}_lens` }; this.recordNameTables.set(shapeId, table); + this.host.journalAllocated?.(base, "dyn.recordNameTable", [shapeId]); const n = shape.fields.length; const names = recordSourceFieldOrder(shape); this.defs.push( @@ -1449,6 +1516,7 @@ export class LlDyn { `@${base}_lens = internal constant [${n} x ${S}] [${names.map((name) => `${S} ${Buffer.byteLength(name, "utf8")}`).join(", ")}]`, ``, ); + this.host.journalBuilt?.(); return table; } @@ -1467,6 +1535,7 @@ export class LlDyn { const host = this.host; const name = `sc_jp_${this.jsonParsers.size}`; this.jsonParsers.set(key, name); + this.host.journalAllocated?.(name, "dyn.jsonParseHelper", [t]); const schema = this.jsonSchema(t); const check = this.dynCheckHelper(t); host.declare(`declare ptr @scr_json_parse_schema(ptr, ptr)`); @@ -1493,6 +1562,7 @@ export class LlDyn { `}`, ``, ); + this.host.journalBuilt?.(); return name; } @@ -1508,6 +1578,7 @@ export class LlDyn { if (existing) return existing; const name = `sc_dc_${this.dynBuilders.size}`; this.dynBuilders.set(builderKey, name); + this.host.journalAllocated?.(name, "dyn.dynCheckHelper", [t, preserveRefs]); const recursive = this.isRecursiveShape(t); const memo = !recursive && this.holdsRecursiveShape(t) && this.valTy(t) === "ptr"; const host = this.host; @@ -1530,6 +1601,7 @@ export class LlDyn { `}`, ``, ); + this.host.journalBuilt?.(); return name; } if (isRefCounted(t) && t.kind !== "dyn") { @@ -1708,6 +1780,32 @@ export class LlDyn { B.line(`store ${member.type} ${oldValue}, ptr ${checkedPtr}`); }); if (t.kind !== "record") { + // Whether the dense slots carry states (SCR_ARR_STATES in + // `spare`) moves with them; the rest of `spare` stays. + const cachedSpare = B.tmp(), + checkedSpare = B.tmp(); + const sparePtr = (array: string): string => { + const ptr = B.tmp(); + B.line( + `${ptr} = getelementptr inbounds %ScrArr, ptr ${array}, i64 0, i32 ${SCR_ARR_FIELD.spare}`, + ); + return ptr; + }; + const cachedSparePtr = sparePtr(cached), + checkedSparePtr = sparePtr(checked); + B.line(`${cachedSpare} = load i16, ptr ${cachedSparePtr}`); + B.line(`${checkedSpare} = load i16, ptr ${checkedSparePtr}`); + const exchange = (own: string, other: string, ptr: string): void => { + const kept = B.tmp(), + moved = B.tmp(), + next = B.tmp(); + B.line(`${kept} = and i16 ${own}, ${~SCR_ARR_STATES}`); + B.line(`${moved} = and i16 ${other}, ${SCR_ARR_STATES}`); + B.line(`${next} = or i16 ${kept}, ${moved}`); + B.line(`store i16 ${next}, ptr ${ptr}`); + }; + exchange(cachedSpare, checkedSpare, cachedSparePtr); + exchange(checkedSpare, cachedSpare, checkedSparePtr); // Sparse slots and numeric properties live out of line; each // array keeps its own match metadata. host.declare("declare void @scr_arr_swap_indexed_ext(ptr, ptr)"); @@ -2526,6 +2624,7 @@ export class LlDyn { ``, ); if (recursive || memo) this.emitVisitWrapper(name, t, recursive ? "build" : "memo"); + this.host.journalBuilt?.(); return name; } @@ -2540,6 +2639,7 @@ export class LlDyn { if (existing) return existing; const name = `sc_td_${this.toDynFns.size}`; this.toDynFns.set(key, name); + this.host.journalAllocated?.(name, "dyn.toDynHelper", [t]); const host = this.host; const B = new BlockBuilder(); let sourceAccessor: { name: string; release: string } | null = null; @@ -3146,6 +3246,7 @@ export class LlDyn { ``, ); } + this.host.journalBuilt?.(); return name; } @@ -3162,6 +3263,7 @@ export class LlDyn { if (existing) return existing; const name = `sc_pda_${this.promiseDynAdapters.size}`; this.promiseDynAdapters.set(key, name); + this.host.journalAllocated?.(name, "dyn.promiseDynAdapterHelper", [inner]); const host = this.host; const B = new BlockBuilder(); host.declare(`declare void @scr_promise_fulfill_ref(ptr, ptr, ptr, ptr, ptr)`); @@ -3239,6 +3341,7 @@ export class LlDyn { `}`, ``, ); + this.host.journalBuilt?.(); return name; } @@ -3251,6 +3354,7 @@ export class LlDyn { if (this.dynToStrFn) return this.dynToStrFn; const name = "sc_ds"; this.dynToStrFn = name; + this.host.journalAllocated?.(name, "dyn.dynToStrHelper", []); const host = this.host; host.declare(`declare void @scr_jb_init(ptr)`); host.declare(`declare ptr @scr_jb_finish(ptr)`); @@ -3555,6 +3659,7 @@ export class LlDyn { ``, ); } + this.host.journalBuilt?.(); return name; } @@ -3566,6 +3671,7 @@ export class LlDyn { if (this.caughtToDynFn) return this.caughtToDynFn; const name = "sc_cd"; this.caughtToDynFn = name; + this.host.journalAllocated?.(name, "dyn.caughtToDynHelper", []); const host = this.host; const B = new BlockBuilder(); const kp = B.tmp(); @@ -3671,6 +3777,7 @@ export class LlDyn { `}`, ``, ); + this.host.journalBuilt?.(); return name; } @@ -3684,6 +3791,7 @@ export class LlDyn { this.helperMemo.set(name, name); const B = new BlockBuilder(); const host = this.host; + this.host.journalAllocated?.(name, "dyn.dynComputedKeyGetHelper", []); const stringHelper = this.dynKeyGetHelper(); host.declare(`declare ptr @scr_dyn_property_key_value(ptr)`); host.declare(`declare ptr @scr_dyn_symbol_key_get(ptr, ptr, i1 zeroext)`); @@ -3721,6 +3829,7 @@ export class LlDyn { "}", "", ); + this.host.journalBuilt?.(); return name; } @@ -3730,6 +3839,7 @@ export class LlDyn { if (existing) return existing; const name = "sc_dyn_key_get"; this.dynBuilders.set(memoKey, name); + this.host.journalAllocated?.(name, "dyn.dynKeyGetHelper", []); const host = this.host; const B = new BlockBuilder(); const kd = this.kindOf(B, "%d"); @@ -4123,6 +4233,7 @@ export class LlDyn { `}`, ``, ); + this.host.journalBuilt?.(); return name; } @@ -4134,6 +4245,7 @@ export class LlDyn { if (existing) return existing; const name = "sc_dyn_destr_check"; this.dynBuilders.set(memoKey, name); + this.host.journalAllocated?.(name, "dyn.dynDestrCheckHelper", []); const host = this.host; host.declare(`declare void @scr_jb_init(ptr)`); host.declare(`declare ptr @scr_jb_finish(ptr)`); @@ -4188,6 +4300,7 @@ export class LlDyn { `}`, ``, ); + this.host.journalBuilt?.(); return name; } @@ -4199,6 +4312,7 @@ export class LlDyn { if (existing) return existing; const name = "sc_dyn_iter_n"; this.dynBuilders.set(memoKey, name); + this.host.journalAllocated?.(name, "dyn.dynIterNHelper", []); const host = this.host; host.declare(`declare ptr @scr_dyn_new_arr()`); host.declare(`declare void @scr_dyn_arr_push(ptr, ptr)`); @@ -4403,6 +4517,7 @@ export class LlDyn { `}`, ``, ); + this.host.journalBuilt?.(); return name; } @@ -4434,6 +4549,7 @@ export class LlDyn { if (existing) return existing; const name = `sc_dfk_${this.dynFuncThunks.size}`; this.dynFuncThunks.set(key, name); + this.host.journalAllocated?.(name, "dyn.dynFuncThunkHelper", [t]); const host = this.host; const B = new BlockBuilder(); const argNames: string[] = []; @@ -4583,6 +4699,7 @@ export class LlDyn { `}`, ``, ); + this.host.journalBuilt?.(); return name; } @@ -4593,6 +4710,7 @@ export class LlDyn { if (existing) return existing; const name = `sc_dfb_${this.dynFuncBoxes.size}`; this.dynFuncBoxes.set(key, name); + this.host.journalAllocated?.(name, "dyn.dynFuncBoxHelper", [t]); const host = this.host; const thunk = this.dynFuncThunkHelper(t); host.declare(`declare ptr @scr_closure_retain_v(ptr)`); @@ -4607,6 +4725,305 @@ export class LlDyn { `}`, ``, ); + this.host.journalBuilt?.(); + return name; + } + + /** `sc_dml_(ptr c, ptr message) -> i1`, the typed message entry of a + * closure registered as a 'message' listener (ScrDynMessageListener): + * builds the closure's parameter from the message's nodes and calls the + * closure. It answers false, without calling it, when the message does + * not have the parameter's exact layout, and the listener then runs + * through its thunk on the decoded message, as before. Null when the + * signature's parameter has no message reader (messageReadable). */ + messageListenerHelper(t: IrType & { kind: "func" }): string | null { + const key = typeKey(t); + const existing = this.messageListeners.get(key); + if (existing !== undefined) return existing; + const param = t.params[0]; + const supported = + t.params.length === 1 && + t.rest !== true && + param !== undefined && + (t.ret.kind === "void" || t.ret.kind === "f64" || t.ret.kind === "bool") && + this.messageReadable(param, new Set()); + if (!supported) { + // A signature without an entry still takes a number. + this.messageListeners.set(key, null); + this.host.journalAllocated?.("", "dyn.messageListenerHelper", [t]); + this.host.journalBuilt?.(); + return null; + } + const name = `sc_dml_${this.messageListeners.size}`; + this.messageListeners.set(key, name); + this.host.journalAllocated?.(name, "dyn.messageListenerHelper", [t]); + const B = new BlockBuilder(); + B.entryAllocas.push(`%fail = alloca i1`); + B.line(`store i1 false, ptr %fail`); + const value = B.tmp(); + B.line( + `${value} = call ${this.valTy(param)} @${this.messageReaderHelper(param)}(ptr %m, ${this.host.sizeType} 0, ptr %fail)`, + ); + const failed = B.tmp(); + B.line(`${failed} = load i1, ptr %fail`); + const lMiss = B.newLabel("dml.miss"); + const lCall = B.newLabel("dml.call"); + B.condBr(failed, lMiss, lCall); + B.startBlock(lMiss); + B.terminate(`ret i1 false`); + B.startBlock(lCall); + // The closure consumes its parameter; a pending exception stays for + // the emitter, as after the thunk. + const fnp = B.tmp(); + const fn = B.tmp(); + B.line(`${fnp} = getelementptr inbounds %ScrClosure, ptr %c, i64 0, i32 1`); + B.line(`${fn} = load ptr, ptr ${fnp}`); + const args = `ptr %c, ${this.valTy(param)} ${value}`; + if (t.ret.kind === "void") B.line(`call void ${fn}(${args})`); + else B.line(`${B.tmp()} = call ${this.valTy(t.ret)} ${fn}(${args})`); + B.terminate(`ret i1 true`); + this.defs.push( + `define internal zeroext i1 @${name}(ptr %c, ptr %m) ${FN_ATTRS} { ; message entry for ${llvmCommentText(key)}`, + B.render(), + `}`, + ``, + ); + this.host.journalBuilt?.(); + return name; + } + + /** Whether a message reader can build T: numbers, booleans and strings; + * records of them with only declared fields, none of union type; and + * boxed unions of those arms and null or undefined without a literal + * discriminator, with at most one number, boolean and string arm. */ + private messageReadable(t: IrType, seen: Set): boolean { + switch (t.kind) { + case "f64": + case "bool": + case "string": + return true; + case "record": { + const shape = this.host.recordsById.get(t.shapeId); + if (!shape || shape.tuple || shape.indexValue || shape.fields.length === 0) return false; + if (seen.has(t.shapeId) || this.isRecursiveShape(t)) return false; + seen.add(t.shapeId); + const readable = shape.fields.every( + (f) => + !f.name.startsWith("%") && + f.type.kind !== "union" && + llFieldType(f.type, this.host.inlineUnions.record(f.type)) !== INLINE_UNION_FIELD && + this.messageReadable(f.type, seen), + ); + seen.delete(t.shapeId); + return readable; + } + case "union": { + const def = this.host.unionsById.get(t.unionId); + // A discriminated union's checked conversion also tests the arm's + // literal discriminator, which the readers do not. + if (!def || def.discriminant || this.host.nullableUnions.has(t.unionId)) return false; + const scalars = new Set(); + for (const arm of def.arms) { + if (arm.kind === "nullT" || arm.kind === "undefinedT") continue; + if (arm.kind === "f64" || arm.kind === "bool" || arm.kind === "string") { + if (scalars.has(arm.kind)) return false; + scalars.add(arm.kind); + continue; + } + if (arm.kind !== "record" || !this.messageReadable(arm, seen)) return false; + } + return true; + } + default: + return false; + } + } + + /** `sc_dmr_(ptr message, size node, ptr fail) -> T`: T (+1) built + * from a message node, for a type messageReadable accepts. Sets *fail + * and returns a dummy when the node does not have T's layout: the arm + * the checked conversion would choose, a record's declared keys in + * declaration order and no others. */ + private messageReaderHelper(t: IrType): string { + const key = typeKey(t); + const existing = this.messageReaders.get(key); + if (existing) return existing; + const name = `sc_dmr_${this.messageReaders.size}`; + this.messageReaders.set(key, name); + this.host.journalAllocated?.(name, "dyn.messageReaderHelper", [t]); + const host = this.host; + const S = host.sizeType; + if (t.kind !== "record") host.declare(`declare i32 @scr_message_kind(ptr, ${S})`); + const retTy = this.valTy(t); + const dummy = retTy === "double" ? f64Lit(0) : retTy === "i1" ? "false" : "null"; + const B = new BlockBuilder(); + const lFail = B.newLabel("dmr.fail"); + // scr_message_fields tests a record's kind itself. + const kind = B.tmp(); + if (t.kind !== "record") B.line(`${kind} = call i32 @scr_message_kind(ptr %m, ${S} %n)`); + const requireKind = (want: number): void => { + const ok = B.tmp(); + B.line(`${ok} = icmp eq i32 ${kind}, ${want}`); + const lOk = B.newLabel("dmr.kind"); + B.condBr(ok, lOk, lFail); + B.startBlock(lOk); + }; + switch (t.kind) { + case "f64": + case "bool": { + host.declare(`declare double @scr_message_number(ptr, ${S})`); + requireKind(t.kind === "f64" ? MESSAGE_KIND.NUMBER : MESSAGE_KIND.BOOL); + const n = B.tmp(); + B.line(`${n} = call double @scr_message_number(ptr %m, ${S} %n)`); + if (t.kind === "f64") B.terminate(`ret double ${n}`); + else { + const b = B.tmp(); + B.line(`${b} = fcmp une double ${n}, ${f64Lit(0)}`); + B.terminate(`ret i1 ${b}`); + } + break; + } + case "string": { + host.declare(`declare ptr @scr_message_string(ptr, ${S})`); + requireKind(MESSAGE_KIND.STRING); + const str = B.tmp(); + B.line(`${str} = call ptr @scr_message_string(ptr %m, ${S} %n)`); + B.terminate(`ret ptr ${str}`); + break; + } + case "record": { + const shape = host.recordsById.get(t.shapeId)!; + const order = recordSourceFieldOrder(shape); + const fields = new Map(shape.fields.map((f, i) => [f.name, { field: f, index: i }])); + const base = host.nullableUnions.fieldBase(t.shapeId); + const struct = mangleRecordStruct(t.shapeId); + const names = this.recordNameTable(t.shapeId, shape); + host.declare(`declare zeroext i1 @scr_message_fields(ptr, ${S}, ptr, ptr, ${S}, ptr)`); + B.entryAllocas.push(`%kids = alloca [${order.length} x ${S}]`); + const matched = B.tmp(); + B.line( + `${matched} = call zeroext i1 @scr_message_fields(ptr %m, ${S} %n, ptr ${names.names}, ptr ${names.lens}, ${S} ${order.length}, ptr %kids)`, + ); + const lBuild = B.newLabel("dmr.build"); + B.condBr(matched, lBuild, lFail); + B.startBlock(lBuild); + B.line(`%r0 = call ptr @${mangleRecordNew(t.shapeId)}()`); + order.forEach((fieldName, i) => { + const { field, index } = fields.get(fieldName)!; + const kidp = B.tmp(); + const kid = B.tmp(); + B.line( + `${kidp} = getelementptr inbounds [${order.length} x ${S}], ptr %kids, i64 0, i64 ${i}`, + ); + B.line(`${kid} = load ${S}, ptr ${kidp}`); + const v = B.tmp(); + B.line( + `${v} = call ${this.valTy(field.type)} @${this.messageReaderHelper(field.type)}(ptr %m, ${S} ${kid}, ptr %fail)`, + ); + const failed = B.tmp(); + B.line(`${failed} = load i1, ptr %fail`); + const lDrop = B.newLabel("dmr.drop"); + const lStore = B.newLabel("dmr.store"); + B.condBr(failed, lDrop, lStore); + B.startBlock(lDrop); + B.line(`call void ${releaseSym(host, t)}(ptr %r0)`); + B.terminate(`ret ptr null`); + B.startBlock(lStore); + const p = B.tmp(); + B.line( + `${p} = getelementptr inbounds %${struct}, ptr %r0, i64 0, i32 ${index + base} ; .${llvmCommentText(fieldName)}`, + ); + const fieldTy = llFieldType(field.type, host.inlineUnions.record(field.type)); + if (fieldTy === "i8") { + const z = B.tmp(); + B.line(`${z} = zext i1 ${v} to i8`); + B.line(`store i8 ${z}, ptr ${p}`); + } else { + B.line(`store ${fieldTy} ${v}, ptr ${p}`); + } + }); + B.terminate(`ret ptr %r0`); + break; + } + case "union": { + const def = host.unionsById.get(t.unionId)!; + def.arms.forEach((arm, i) => { + const lNext = B.newLabel("dmr.next"); + if (arm.kind === "nullT" || arm.kind === "undefinedT") { + const hit = B.tmp(); + B.line( + `${hit} = icmp eq i32 ${kind}, ${arm.kind === "nullT" ? MESSAGE_KIND.NULL : MESSAGE_KIND.UNDEFINED}`, + ); + const lHit = B.newLabel("dmr.unit"); + B.condBr(hit, lHit, lNext); + B.startBlock(lHit); + B.terminate(`ret ptr ${host.unitInstanceRef(t.unionId, i)}`); + B.startBlock(lNext); + return; + } + if (arm.kind !== "record") { + const want = + arm.kind === "f64" + ? MESSAGE_KIND.NUMBER + : arm.kind === "bool" + ? MESSAGE_KIND.BOOL + : MESSAGE_KIND.STRING; + const hit = B.tmp(); + B.line(`${hit} = icmp eq i32 ${kind}, ${want}`); + const lHit = B.newLabel("dmr.arm"); + B.condBr(hit, lHit, lNext); + B.startBlock(lHit); + } + // A record arm that does not match leaves *fail clear for the + // next arm, like the checked conversion's next-arm match. + const v = B.tmp(); + B.line( + `${v} = call ${this.valTy(arm)} @${this.messageReaderHelper(arm)}(ptr %m, ${S} %n, ptr %fail)`, + ); + if (arm.kind === "record") { + const failed = B.tmp(); + B.line(`${failed} = load i1, ptr %fail`); + const lHit = B.newLabel("dmr.arm"); + const lMiss = B.newLabel("dmr.miss"); + B.condBr(failed, lMiss, lHit); + B.startBlock(lMiss); + B.line(`store i1 false, ptr %fail`); + B.br(lNext); + B.startBlock(lHit); + } + const u = B.tmp(); + if (arm.kind === "f64") { + host.declare(`declare ptr @scr_union_new_f64(i32, double)`); + B.line(`${u} = call ptr @scr_union_new_f64(i32 ${i}, double ${v})`); + } else if (arm.kind === "bool") { + host.declare(`declare ptr @scr_union_new_bool(i32, i1 zeroext)`); + B.line(`${u} = call ptr @scr_union_new_bool(i32 ${i}, i1 ${v})`); + } else { + const rc = vAdapters(host, arm); + host.declare(`declare ptr @scr_union_new_ref(i32, ptr, ptr, ptr, ptr)`); + B.line( + `${u} = call ptr @scr_union_new_ref(i32 ${i}, ptr ${v}, ptr ${rc.retain}, ptr ${rc.release}, ptr ${traceArg(host, arm)})`, + ); + } + B.terminate(`ret ptr ${u}`); + B.startBlock(lNext); + }); + B.br(lFail); + break; + } + default: + throw new InternalCompilerError(`llvm emitter bug: message reader of ${key}`); + } + B.startBlock(lFail); + B.line(`store i1 true, ptr %fail`); + B.terminate(`ret ${retTy} ${dummy}`); + this.defs.push( + `define internal ${retTy === "i1" ? "zeroext i1" : retTy} @${name}(ptr %m, ${S} %n, ptr %fail) ${FN_ATTRS} { ; message reader for ${llvmCommentText(key)}`, + B.render(), + `}`, + ``, + ); + this.host.journalBuilt?.(); return name; } @@ -4618,6 +5035,7 @@ export class LlDyn { if (existing) return existing; const name = `sc_dfa_${this.dynFuncAdapters.size}`; this.dynFuncAdapters.set(key, name); + this.host.journalAllocated?.(name, "dyn.dynFuncAdapterHelper", [t]); const host = this.host; const B = new BlockBuilder(); host.declare(`declare ptr @scr_box_get_ref(ptr)`); @@ -4720,6 +5138,7 @@ export class LlDyn { `}`, ``, ); + this.host.journalBuilt?.(); return name; } } diff --git a/packages/compiler/src/backend/llvm/emit-function.ts b/packages/compiler/src/backend/llvm/emit-function.ts index 5053c1b54..16e654393 100644 --- a/packages/compiler/src/backend/llvm/emit-function.ts +++ b/packages/compiler/src/backend/llvm/emit-function.ts @@ -16,9 +16,7 @@ import { withInitializerBindings, withInitializerLocals, } from "../../ir/initializer-bindings.js"; -import { findUnaliasedLocalArrays } from "../../ir/array-length-stability.js"; import { constructorClass } from "../../ir/final-fields.js"; -import { findInitializedByteLoopBindings } from "./byte-windows.js"; import { findLoopArrayBorrows } from "./loop-array-borrows.js"; import { findCallArrayReads, findLocalArrayReads } from "./local-array-reads.js"; import { findScalarStringSlices, findScratchStringSlices } from "./string-slices.js"; @@ -55,6 +53,9 @@ import { INT32_ABI_SUFFIX, SCALAR_UNION_RESULT } from "./int32-abi.js"; import { f64Lit } from "./common.js"; import { RESULT_ENTRY_PREFIX } from "./record-results.js"; import { emitIntegerClone, emitIntegerDispatcher } from "./integer-clones.js"; +import { beginFunctionLoops, LOOPS } from "./loop-state.js"; +import { runningExtremumUpdates } from "./running-extrema.js"; +import { findIntegerOrNaNLocals } from "./wrapping-sums.js"; export function emitFunction(emitter: LlEmitter, fn: IrFunction): string { const B = new BlockBuilder(); @@ -81,8 +82,11 @@ export function emitFunction(emitter: LlEmitter, fn: IrFunction): string { emitter.currentLocals.set(id, plain); emitter.lazyCaptureBoxes.set(id, ""); } + emitter.runningExtrema = emitter.debug === null ? runningExtremumUpdates(fn) : new Set(); emitter.currentConstantCallbacks = emitter.debug === null ? (emitter.constantCallbacks.get(fn.name) ?? new Map()) : new Map(); + emitter.knownCallbacks.clear(); + emitter.callbackVersionsEnabled = emitter.debug === null && !fn.async && !fn.generator; // Preserve concrete source bindings for debugger inspection. Suspended // functions keep the established array lifetime across continuations. emitter.streamingSplitsEnabled = emitter.debug === null && !fn.async && !fn.generator; @@ -97,7 +101,6 @@ export function emitFunction(emitter: LlEmitter, fn: IrFunction): string { const initializerBindings = emitter.initializerBindings.get(fn.name) ?? []; const numericFn = withInitializerBindings(fn, initializerBindings); emitter.numericLocals = new Map(numericFn.locals.map((l) => [l.id, l])); - emitter.unaliasedArrays = findUnaliasedLocalArrays(fn); emitter.borrowedParameters.clear(); emitter.referenceWrites?.enter(fn); emitter.reboundOwnerSlots.clear(); @@ -128,8 +131,10 @@ export function emitFunction(emitter: LlEmitter, fn: IrFunction): string { emitter.stableCaptureIds = fn.captures !== undefined ? emitter.lazyCaptures.stableCaptures(fn.name) : new Set(); emitter.integerLoopBindings.clear(); - emitter.countedLoopsEnabled = emitter.debug === null && !fn.async && !fn.generator; - emitter.speculativeLoopsEnabled = emitter.countedLoopsEnabled; + emitter.integerTemps.clear(); + emitter.integerTempsEnabled = emitter.debug === null && !fn.async && !fn.generator; + beginFunctionLoops(emitter, fn, numericFn); + emitter.speculativeLoopsEnabled = LOOPS.of(emitter).countedLoopsEnabled; emitter.speculativeFunction = fn.name; emitter.speculation = null; emitter.speculationResume = null; @@ -138,20 +143,6 @@ export function emitFunction(emitter: LlEmitter, fn: IrFunction): string { !fn.generator && constructorClass(fn.name) === null && emitter.finalFields.size > 0; - emitter.byteWindowsEnabled = emitter.countedLoopsEnabled; - emitter.bytesLoopVersionsEnabled = emitter.countedLoopsEnabled; - emitter.bytesLoopEntries = null; - emitter.bytesLoopFunction = fn; - emitter.denseLoopsEnabled = emitter.countedLoopsEnabled; - emitter.denseLoop = null; - emitter.denseLoopEntries = - emitter.denseLoopsEnabled && numericFn.locals.some((l) => l.type.kind === "array") - ? findInitializedByteLoopBindings(fn) - : new Map(); - emitter.byteWindowEntries = - emitter.byteWindowsEnabled && numericFn.locals.some((l) => l.type.kind === "bytes") - ? findInitializedByteLoopBindings(fn) - : new Map(); emitter.integerViews.clear(); emitter.fieldPointerTags.clear(); emitter.compressedFieldPtrs.clear(); @@ -227,6 +218,7 @@ export function emitFunction(emitter: LlEmitter, fn: IrFunction): string { emitter.integerRanges = rangeFacts.ranges; emitter.integerLoopRanges = rangeFacts.loopRanges; emitter.int32Elements = slotFacts.elements ?? null; + emitter.integerOrNaNLocals = findIntegerOrNaNLocals(emitter, numericFn); emitter.bytesBounds = findBytesBounds(numericFn, emitter.integerRanges); emitter.bytesOwned = new Set(); // Debug builds keep every number local a double for the debugger's @@ -409,7 +401,7 @@ export function emitFunction(emitter: LlEmitter, fn: IrFunction): string { if (local.boxed || emitter.captureIds.has(local.id)) slots.add(`%${mangleLocal(local.id)}`); B.volatileSlots = slots; // Without optimization a versioned copy only adds code. - emitter.bytesLoopVersionsEnabled = false; + LOOPS.of(emitter).bytesLoopVersionsEnabled = false; } // Captured bindings come in through the environment — borrowed for the // whole call (the closure owns them): bound here, never released here. diff --git a/packages/compiler/src/backend/llvm/emit-journal.ts b/packages/compiler/src/backend/llvm/emit-journal.ts new file mode 100644 index 000000000..ad89d2671 --- /dev/null +++ b/packages/compiler/src/backend/llvm/emit-journal.ts @@ -0,0 +1,237 @@ +/* Chunked function emission (emit-module.ts). An emitter that emits one + * contiguous range of a module's functions records here the helpers and + * sites it numbers from a counter (`sc_td_${size}` and the like). The + * emitter that merges the ranges replays each range's records in order: + * replay calls the same entry point with the same arguments, so every + * helper gets the number and the definition the serial emission gives it, + * and the range's text is renamed to those numbers. */ +import type { LlEmitter } from "./emitter.js"; + +/** One event of a range's emission, in order. */ +export type JournalEntry = + /** A helper or site the range's emitter numbered: the name it gave it + * (a counter prefix and a number), and the replay entry point + * (registerReplay) with its arguments, which are plain IR values. */ + | { + readonly kind: "op"; + readonly name: string; + readonly op: string; + readonly args: readonly unknown[]; + } + /** The first request of a key of a module-level table made outside any + * replayable definition, with the value the range's emitter stored. */ + | { + readonly kind: "entry"; + readonly table: string; + readonly key: string; + readonly value: unknown; + }; + +export class EmitJournal { + readonly entries: JournalEntry[] = []; + /** The replayable definitions being built, innermost last. */ + private readonly open: string[] = []; + + /** The definitions still open (empty between functions). */ + get unclosed(): readonly string[] { + return this.open; + } + /** Keys already recorded per table. */ + private readonly recorded = new Map>(); + + /** A keyed helper, recorded when its number is taken, before anything its + * definition creates in turn: that keeps the serial numbering order. + * Replaying a helper that exists answers its name, so helpers created + * inside another helper's definition are recorded too. Opens the + * definition, which the creating entry point closes with `built`. */ + allocated(name: string, op: string, args: readonly unknown[]): void { + this.entries.push({ kind: "op", name, op, args }); + this.open.push(op); + } + + /** Opens a definition whose helper is not replayed itself (its + * entry point records the request with `used`). */ + opened(op: string): void { + this.open.push(op); + } + + /** A request, made outside any definition, of the helper `name` that an + * entry point answered; recorded once per name. Replay makes the same + * request. */ + used(name: string, op: string, args: readonly unknown[]): void { + if (this.open.length !== 0) return; + if (this.usedNames.has(name)) return; + this.usedNames.add(name); + this.entries.push({ kind: "op", name, op, args }); + } + private readonly usedNames = new Set(); + + /** Closes the definition `allocated` or `opened` opened. */ + built(): void { + if (this.open.pop() === undefined) this.overclosed = true; + } + + /** A `built` closed a definition no `allocated` opened. */ + overclosed = false; + + /** An unkeyed site (one per use). Sites taken while a definition is built + * are taken again when the merging emitter replays that definition. */ + site(name: string, op: string, args: readonly unknown[] = []): void { + if (this.open.length === 0) this.entries.push({ kind: "op", name, op, args }); + } + + /** A request of `key` in a module-level table. Only the first request + * made outside any definition is recorded: requests made while a + * definition is built happen again when it is replayed. */ + entry(table: string, key: string, value: unknown): void { + if (this.open.length !== 0) return; + let keys = this.recorded.get(table); + if (keys === undefined) this.recorded.set(table, (keys = new Set())); + if (keys.has(key)) return; + keys.add(key); + this.entries.push({ kind: "entry", table, key, value }); + } +} + +/** A range emitter's result (LlEmitter.chunkResult): plain data, so a + * worker process can write it. */ +export interface ChunkResult { + readonly entries: readonly JournalEntry[]; + readonly flags: { + readonly usesCoroutines: boolean; + readonly usesTimers: boolean; + readonly usesGenSlots: boolean; + readonly needsUnionNone: boolean; + readonly needsNullableAbsent: boolean; + readonly needsOom: boolean; + readonly needsBadTag: boolean; + readonly needsBadKey: boolean; + readonly needsRetainBox: boolean; + }; + readonly publishedNamesSym: string | null; + readonly rcHelpers: readonly string[]; + readonly immortalValues: readonly string[]; + readonly fnValues: readonly string[]; + readonly arraySearchKinds: readonly string[]; + readonly recordCloneShapes: readonly string[]; + readonly awaitCallees: readonly string[]; + readonly adoptCallees: readonly string[]; + readonly directAwaitCallees: readonly string[]; + readonly inlineAwaitCallees: readonly string[]; +} + +type Replay = (emitter: LlEmitter, args: readonly unknown[]) => string; +const replays = new Map(); + +/** Registers the entry point that creates (or finds) a numbered helper or + * site from its recorded arguments and answers its name. */ +export function registerReplay(op: string, replay: Replay): void { + replays.set(op, replay); +} + +/** Replays a range's entries on the merging emitter, in record order, and + * records the renames from the range's names to its own in `names`. */ +export function replayJournal( + emitter: LlEmitter, + entries: readonly JournalEntry[], + names: Map, + tags: Map, +): void { + for (const entry of entries) { + if (entry.kind === "entry") { + emitter.applyJournalEntry(entry.table, entry.key, entry.value, names, tags); + continue; + } + const replay = replays.get(entry.op); + if (replay === undefined) + throw new Error(`llvm emitter bug: no replay for journal entry ${entry.op}`); + const own = stripSigil(replay(emitter, entry.args)); + const local = stripSigil(entry.name); + if (own !== local) names.set(local, own); + } +} + +/** The rename of a range's text: numbered names (`names`, without the + * sigil) and field alias tags (`tags`). One scan for each kind of name: + * a numbered name starts `sc_` after a character that cannot be part of a + * name, and ends at the last digit after its counter prefix. */ +export function renameChunk( + names: ReadonlyMap, + tags: ReadonlyMap, +): (text: string) => string { + const prefixes = new Set(); + for (const name of names.keys()) prefixes.add(name.replace(/\d+$/, "")); + if (prefixes.size === 0 && tags.size === 0) return (text) => text; + return (text) => { + let out = prefixes.size === 0 ? text : renameNames(text, names, prefixes); + if (tags.size > 0) out = renameTags(out, tags); + return out; + }; +} + +function renameNames( + text: string, + names: ReadonlyMap, + prefixes: ReadonlySet, +): string { + const parts: string[] = []; + let copied = 0; + for (let at = text.indexOf("sc_"); at >= 0; at = text.indexOf("sc_", at + 3)) { + if (at > 0 && isNameChar(text.charCodeAt(at - 1))) continue; + // The counter prefix ends where the digits start; the number ends at + // the last digit. + let end = at + 3; + while (end < text.length && isNameChar(text.charCodeAt(end)) && !isDigit(text.charCodeAt(end))) + end++; + if (end === text.length || !isDigit(text.charCodeAt(end))) continue; + if (!prefixes.has(text.slice(at, end))) continue; + let last = end; + while (last < text.length && isDigit(text.charCodeAt(last))) last++; + const own = names.get(text.slice(at, last)); + if (own === undefined) continue; + parts.push(text.slice(copied, at), own); + copied = last; + } + if (copied === 0) return text; + parts.push(text.slice(copied)); + return parts.join(""); +} + +function renameTags(text: string, tags: ReadonlyMap): string { + const marker = "!tbaa !"; + const parts: string[] = []; + let copied = 0; + for (let at = text.indexOf(marker); at >= 0; at = text.indexOf(marker, at + marker.length)) { + const start = at + marker.length; + let end = start; + while (end < text.length && isDigit(text.charCodeAt(end))) end++; + const own = tags.get(Number(text.slice(start, end))); + if (own === undefined) continue; + parts.push(text.slice(copied, start), String(own)); + copied = end; + } + if (copied === 0) return text; + parts.push(text.slice(copied)); + return parts.join(""); +} + +/** `[-$._A-Za-z0-9]`: a character of an LLVM identifier. */ +function isNameChar(code: number): boolean { + return ( + (code >= 48 && code <= 57) || + (code >= 65 && code <= 90) || + (code >= 97 && code <= 122) || + code === 95 || + code === 36 || + code === 45 || + code === 46 + ); +} + +function isDigit(code: number): boolean { + return code >= 48 && code <= 57; +} + +function stripSigil(name: string): string { + return name.startsWith("@") ? name.slice(1) : name; +} diff --git a/packages/compiler/src/backend/llvm/emit-module.ts b/packages/compiler/src/backend/llvm/emit-module.ts index 3d9d41072..b6e489c19 100644 --- a/packages/compiler/src/backend/llvm/emit-module.ts +++ b/packages/compiler/src/backend/llvm/emit-module.ts @@ -2,6 +2,10 @@ import { relieveHeapPressure } from "../../heap-pressure.js"; import { emitWasmModules } from "./wasm-modules.js"; import { type LlEmitter, ffiCallbackDummyLl, llStrBytes } from "./emitter.js"; +import { type ChunkResult, EmitJournal } from "./emit-journal.js"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { JS_IC_WORDS } from "./js-ic.js"; import { mangleAsyncSpawn, @@ -24,7 +28,7 @@ import { } from "../../ir/ir.js"; import { FN_ATTRS, - limitInlineDynReleases, + limitInlineReleases, releaseSym, typedRefConstructor, vAdapters, @@ -35,9 +39,11 @@ import { emitClassMembershipHelper } from "./classes.js"; import { type RegexMatcherCode, compileRegexMatcher } from "./regex-matchers.js"; import { MAP_ITER_DECL, + MAP_SIZE_DECL, MAP_ITER_NUM_DECL, SCR_MAP_NUM_DEAD, NUMBER_MAP_ENTRY_DECL, + STRING_MAP_ENTRY_C_DECL, STRING_MAP_ENTRY_DECL, } from "./map-number-lookup.js"; import { RUNTIME_ABI_MARKER } from "../runtime-abi.js"; @@ -59,16 +65,150 @@ import { STRING_READ_HELPERS, stringScanDecl } from "./string-reads.js"; import { emitLibraryIdentityLines } from "../library-identity-markers.js"; import { InternalCompilerError } from "../../errors.js"; +/** The function bodies emitted in `chunks` contiguous ranges, each by its + * own emitter (LlEmitter.chunkEmitter), then merged in function order: the + * text one emitter gives. */ +function emitFunctionsInChunks(emitter: LlEmitter, chunks: number): string[] { + const functions = emitter.mod.functions; + const size = Math.ceil(functions.length / chunks); + const ranges: { chunk: LlEmitter; texts: string[] }[] = []; + for (let start = 0; start < functions.length; start += size) { + const chunk = emitter.chunkEmitter(); + const texts = functions.slice(start, start + size).map((fn) => { + const text = chunk.emitFunction(fn); + if (chunk.journal!.overclosed) + throw new Error(`llvm emitter bug: journal definition closed twice in ${fn.name}`); + if (chunk.journal!.unclosed.length > 0) + throw new Error( + `llvm emitter bug: unclosed journal definitions after ${fn.name}: ${chunk.journal!.unclosed.join(", ")}`, + ); + return text; + }); + ranges.push({ chunk, texts }); + } + const fnDefs: string[] = []; + for (const { chunk, texts } of ranges) { + // The plain-data result a worker process would write, round-tripped. + const result = JSON.parse(JSON.stringify(chunk.chunkResult())) as ChunkResult; + const rename = emitter.mergeChunk(result); + for (const text of texts) { + const def = rename(text); + emitter.fnDefText.set(functions[fnDefs.length]!.name, def); + fnDefs.push(def); + } + } + return fnDefs; +} + +/** Modules with fewer functions emit in one process: forking and merging + * would cost more than the workers save (SCRIPTC_EMIT_WORKER_FUNCTIONS + * lowers it, for tests). */ +function workerMinFunctions(): number { + const value = Number(process.env["SCRIPTC_EMIT_WORKER_FUNCTIONS"] ?? "2000"); + return Number.isFinite(value) && value > 0 ? value : 2000; +} + +/** The function bodies emitted on forked worker processes, `workers` at a + * time: the function list splits into contiguous ranges, each emitted in + * its own process, which inherits this emitter as it is at the fork and + * records a journal (emit-journal.ts). Ranges merge in function order, so + * the text is the serial text. A range whose worker fails is emitted here + * when its turn comes. Null without fork primitives (Node, Windows, inside + * a worker) or when the module is small. */ +function emitFunctionsOnWorkers(emitter: LlEmitter, workers: number): string[] | null { + const fork = emitter.targetOptions.forkPrimitives; + const functions = emitter.mod.functions; + if (fork === undefined || workers < 2) return null; + if (functions.length < workerMinFunctions()) return null; + // More ranges than workers: a range's merge overlaps the later ranges' + // emission, and a slow range holds back less. + const count = Math.min(functions.length, workers * 3); + const size = Math.ceil(functions.length / count); + const dir = mkdtempSync(join(tmpdir(), "scriptc-emit-")); + const pids: number[] = []; + const start = (range: number): void => { + const pid = fork.fork(); + if (pid === 0) { + let code = 1; + try { + emitter.journal = new EmitJournal(); + const texts: string[] = []; + for (const fn of functions.slice(range * size, (range + 1) * size)) { + texts.push(emitter.emitFunction(fn)); + relieveHeapPressure(); + } + writeFileSync(join(dir, `${range}.json`), JSON.stringify(emitter.chunkResult())); + // Function text never holds NUL, so it separates the functions. + writeFileSync(join(dir, `${range}.ll`), texts.join("\0")); + code = 0; + } catch { + // The parent emits the range itself. + } + fork.exit(code); + } + pids.push(pid); + }; + const fnDefs: string[] = []; + try { + for (let range = 0; range < Math.min(workers, count); range++) start(range); + for (let range = 0; range < count; range++) { + const pid = pids[range]!; + const status = pid > 0 ? fork.wait(pid) : -1; + // The next worker starts from this emitter as merged so far, which + // the journal allows: it records requests, not table contents. + const merged = status === 0 ? readRange(dir, range) : null; + const slice = functions.slice(range * size, (range + 1) * size); + if (merged !== null && merged.texts.length === slice.length) { + const rename = emitter.mergeChunk(merged.result); + slice.forEach((fn, index) => { + const def = rename(merged.texts[index]!); + emitter.fnDefText.set(fn.name, def); + fnDefs.push(def); + }); + } else + for (const fn of slice) { + const def = emitter.emitFunction(fn); + emitter.fnDefText.set(fn.name, def); + fnDefs.push(def); + relieveHeapPressure(); + } + if (pids.length < count) start(pids.length); + } + } finally { + rmSync(dir, { recursive: true, force: true }); + } + return fnDefs; +} + +/** A worker's range result, or null when its files are missing. */ +function readRange(dir: string, range: number): { result: ChunkResult; texts: string[] } | null { + try { + const result = JSON.parse(readFileSync(join(dir, `${range}.json`), "utf8")) as ChunkResult; + const texts = readFileSync(join(dir, `${range}.ll`), "utf8").split("\0"); + return { result, texts }; + } catch { + return null; + } +} + export function emitModuleParts(emitter: LlEmitter): string[] { // Function bodies first (the literal/unit/fn-value tables fill as they // emit), then the file assembles around them — the runtime ABI’s order. - const fnDefs: string[] = []; - for (const fn of emitter.mod.functions) { - const def = emitter.emitFunction(fn); - fnDefs.push(def); - emitter.fnDefText.set(fn.name, def); - relieveHeapPressure(); - } + // Debug metadata is numbered per emitter and not journaled, so a debug + // build emits every body here. + const ranges = emitter.debug === null; + const chunks = emitter.targetOptions.functionChunks ?? 1; + const fnDefs = + (ranges && chunks > 1 ? emitFunctionsInChunks(emitter, chunks) : null) ?? + (ranges ? emitFunctionsOnWorkers(emitter, emitter.targetOptions.functionWorkers ?? 1) : null) ?? + []; + if (fnDefs.length === 0) + for (const fn of emitter.mod.functions) { + const def = emitter.emitFunction(fn); + fnDefs.push(def); + emitter.fnDefText.set(fn.name, def); + relieveHeapPressure(); + } emitter.selectStacklessAsync(fnDefs); const errorViews: string[] = []; for (const property of ["name", "message"]) @@ -456,15 +596,18 @@ export function emitModuleParts(emitter: LlEmitter): string[] { // RC fast paths test the traced byte (shapes.ts). ...(emitter.rcHelpers === null ? [] : [`%ScrMapRc = type { ${emitter.sizeType}, i8, i8, i8 }`]), // The complete ScrMap and its entries, read by the inline number-key - // lookup (sc_map_entry_f64) and the inline iteration steps - // (sc_map_iter_entry, sc_map_iter_entry_num): field 8 is the i32 entry + // lookup (sc_map_entry_f64), the inline iteration steps + // (sc_map_iter_entry, sc_map_iter_entry_num) and Map.size + // (sc_map_size): field 8 is the i32 entry count, field 9 the i32 live // count, field 10 the i64 absent-key filter, entries is field 11, // nbuckets and buckets fields 13 and 14, the direct index and its i32 // length fields 15 and 16. ...(emitter.decls.has(NUMBER_MAP_ENTRY_DECL) || emitter.decls.has(STRING_MAP_ENTRY_DECL) || + emitter.decls.has(STRING_MAP_ENTRY_C_DECL) || emitter.decls.has(MAP_ITER_DECL) || - emitter.decls.has(MAP_ITER_NUM_DECL) + emitter.decls.has(MAP_ITER_NUM_DECL) || + emitter.decls.has(MAP_SIZE_DECL) ? [ `%ScrMapIx = type { ${emitter.sizeType}, i8, i8, i8, i8, i32, ptr, ptr, i32, i32, i64, ptr, i32, i32, ptr, ptr, i32, i32 }`, ] @@ -479,6 +622,11 @@ export function emitModuleParts(emitter: LlEmitter): string[] { emitter.decls.has(MAP_ITER_NUM_DECL) ? [`%ScrMapEntry = type { i64, i64, i64 }`, `%ScrMapNumEntry = type { i64, i64 }`] : []), + // A compact-value map's { key, hash, val } entry (scr_map.h ScrMapCEntry): + // a 32-bit hash and the value as an address over 8. + ...(emitter.decls.has(STRING_MAP_ENTRY_C_DECL) + ? [`%ScrMapCEntry = type { i64, i32, i32 }`] + : []), // The runtime error prefix { rc, vt, name, message, code, cause } and the // class-object shape { rc, pre, post, ctor, name } — field reads on // builtin errors and classval loads GEP through these. @@ -545,7 +693,7 @@ export function emitModuleParts(emitter: LlEmitter): string[] { ``, `@scr_error_vts = external ${tl}global [${RUNTIME_ERROR_CLASSES.size} x %ScrVt]`, `declare void @scr_init()`, - ...(emitter.usesCompactRefs ? [`declare void @scr_plr_init()`] : []), + ...(emitter.compactRegion ? [`declare void @scr_plr_init()`] : []), `declare void @scr_lib_init(i32, ptr)`, ...(emitter.mod.workers ? [`declare void @scr_runtime_workers_v8()`] : []), ...(emitter.stackChecks?.size ? [`declare void @scr_stack_guard_init()`] : []), @@ -699,21 +847,19 @@ export function emitModuleParts(emitter: LlEmitter): string[] { for (const code of regexMatchers.values()) out.push(...code.lines, ``); for (const [, inst] of emitter.templateStringsInstances) { // One immortal ScrArr per tagged-template site: a data global of - // interned cooked-string literals followed by their states (the - // runtime finds them before data + cap * 9), and the ScrArr header over - // it (rc == SIZE_MAX, len == cap == filled, SCR_ELEM_STR = 2, no REF - // entry points). Every dense slot is present; reads retain immortal - // strings — a no-op. Slots are 8 bytes on every target: on 32-bit - // targets each holds the pointer in its low half and zero in its high - // half, so the states start where the runtime looks for them. + // interned cooked-string literals, and the ScrArr header over it + // (rc == SIZE_MAX, len == cap == filled, SCR_ELEM_STR = 2, no REF entry + // points, no state bytes: every dense slot is present). Reads retain + // immortal strings — a no-op. Slots are 8 bytes on every target: on + // 32-bit targets each holds the pointer in its low half and zero in its + // high half. const n = inst.slots.length; - const present = n === 0 ? "zeroinitializer" : `[ ${inst.slots.map(() => "i8 1").join(", ")} ]`; const wide = emitter.sizeType === "i64"; const slot = wide ? "ptr" : "<{ ptr, i32 }>"; const slotValue = (s: string): string => wide ? `ptr ${s}` : `<{ ptr, i32 }> <{ ptr ${s}, i32 0 }>`; out.push( - `@${inst.sym}_data = internal constant <{ [${n} x ${slot}], [${n} x i8] }> <{ [${n} x ${slot}] [ ${inst.slots.map(slotValue).join(", ")} ], [${n} x i8] ${present} }>, align 8`, + `@${inst.sym}_data = internal constant [${n} x ${slot}] [ ${inst.slots.map(slotValue).join(", ")} ], align 8`, `@${inst.sym} = internal global %ScrArr { ${emitter.sizeType} -1, i32 ${n}, i32 ${n}, i8 2, i8 0, i16 0, i32 ${n}, ptr @${inst.sym}_data }`, ); } @@ -840,7 +986,7 @@ export function emitModuleParts(emitter: LlEmitter): string[] { ` call void @scr_init()`, // Compressed fields hold addresses in the program-lifetime region, which // is reserved below 32 GiB before compiled code runs. - ...(emitter.usesCompactRefs ? [` call void @scr_plr_init()`] : []), + ...(emitter.compactRegion ? [` call void @scr_plr_init()`] : []), // Each context (the main thread, every worker) installs its stack // guard before running compiled code that checks it. ...(emitter.stackChecks?.size ? [` call void @scr_stack_guard_init()`] : []), @@ -1293,6 +1439,18 @@ export function helperDefs(emitter: LlEmitter): string[] { ``, ); } + // Map.size and Set.size read the live entry count (scr_map_size). + if (emitter.decls.has(MAP_SIZE_DECL)) + defs.push( + `define internal double @sc_map_size(ptr %m) ${FN_ATTRS} {`, + `entry:`, + ` %np = getelementptr inbounds %ScrMapIx, ptr %m, i32 0, i32 9`, + ` %n = load i32, ptr %np`, + ` %nf = uitofp i32 %n to double`, + ` ret double %nf`, + `}`, + ``, + ); // String-key Map/Set lookups test the map's absent-key filter inline // (scr_map.c scr_map_filter_bits): a key whose two filter bits are not // both set is absent, so most misses on small and medium maps return @@ -1301,36 +1459,69 @@ export function helperDefs(emitter: LlEmitter): string[] { // and the filter reads its bits 44..55, which are the capacity word's // own. A key without a cached hash, and every possible hit, take the // runtime lookup. - if (emitter.decls.has(STRING_MAP_ENTRY_DECL)) { + // A compact-value map's lookup (sc_map_entry_str_c) tests the same filter + // and calls scr_map_entry_str_c; its iteration step (sc_map_iter_entry_c) + // reads 16-byte entries and their 32-bit hash. + const stringMapEntry = (helper: string, runtime: string): string[] => [ + `define internal ptr @${helper}(ptr %m, ptr %k) ${FN_ATTRS} {`, + `entry:`, + ...(emitter.sizeType === "i64" + ? [ + ` %fp = getelementptr inbounds %ScrMapIx, ptr %m, i32 0, i32 10`, + ` %filter = load i64, ptr %fp`, + ` %capp = getelementptr inbounds %ScrStr, ptr %k, i32 0, i32 2`, + ` %cap = load i64, ptr %capp`, + ` %cached = icmp uge i64 %cap, 4294967296`, + ` br i1 %cached, label %test, label %slow`, + `test:`, + ` %s1 = lshr i64 %cap, 44`, + ` %i1 = and i64 %s1, 63`, + ` %b1 = shl i64 1, %i1`, + ` %s2 = lshr i64 %cap, 50`, + ` %i2 = and i64 %s2, 63`, + ` %b2 = shl i64 1, %i2`, + ` %bits = or i64 %b1, %b2`, + ` %have = and i64 %filter, %bits`, + ` %maybe = icmp eq i64 %have, %bits`, + ` br i1 %maybe, label %slow, label %absent`, + `absent:`, + ` ret ptr null`, + ] + : [` br label %slow`]), + `slow:`, + ` %r = call ptr @${runtime}(ptr %m, ptr %k)`, + ` ret ptr %r`, + `}`, + ``, + ]; + if (emitter.decls.has(STRING_MAP_ENTRY_DECL)) + defs.push(...stringMapEntry("sc_map_entry_str", "scr_map_entry_str")); + if (emitter.decls.has(STRING_MAP_ENTRY_C_DECL)) { + const sz = emitter.sizeType; defs.push( - `define internal ptr @sc_map_entry_str(ptr %m, ptr %k) ${FN_ATTRS} {`, + ...stringMapEntry("sc_map_entry_str_c", "scr_map_entry_str_c"), + `define internal ptr @sc_map_iter_entry_c(ptr %m, double %i) ${FN_ATTRS} {`, `entry:`, - ...(emitter.sizeType === "i64" - ? [ - ` %fp = getelementptr inbounds %ScrMapIx, ptr %m, i32 0, i32 10`, - ` %filter = load i64, ptr %fp`, - ` %capp = getelementptr inbounds %ScrStr, ptr %k, i32 0, i32 2`, - ` %cap = load i64, ptr %capp`, - ` %cached = icmp uge i64 %cap, 4294967296`, - ` br i1 %cached, label %test, label %slow`, - `test:`, - ` %s1 = lshr i64 %cap, 44`, - ` %i1 = and i64 %s1, 63`, - ` %b1 = shl i64 1, %i1`, - ` %s2 = lshr i64 %cap, 50`, - ` %i2 = and i64 %s2, 63`, - ` %b2 = shl i64 1, %i2`, - ` %bits = or i64 %b1, %b2`, - ` %have = and i64 %filter, %bits`, - ` %maybe = icmp eq i64 %have, %bits`, - ` br i1 %maybe, label %slow, label %absent`, - `absent:`, - ` ret ptr null`, - ] - : [` br label %slow`]), - `slow:`, - ` %r = call ptr @scr_map_entry_str(ptr %m, ptr %k)`, - ` ret ptr %r`, + ` %np = getelementptr inbounds %ScrMapIx, ptr %m, i32 0, i32 8`, + ` %n = load i32, ptr %np`, + ` %nf = uitofp i32 %n to double`, + ` %lo = fcmp oge double %i, 0.0`, + ` %hi = fcmp olt double %i, %nf`, + ` %in = and i1 %lo, %hi`, + ` br i1 %in, label %load, label %none`, + `load:`, + ` %ix = fptoui double %i to ${sz}`, + ` %ep = getelementptr inbounds %ScrMapIx, ptr %m, i32 0, i32 11`, + ` %entries = load ptr, ptr %ep`, + ` %e = getelementptr inbounds %ScrMapCEntry, ptr %entries, ${sz} %ix`, + ` %hp = getelementptr inbounds %ScrMapCEntry, ptr %e, i32 0, i32 1`, + ` %h = load i32, ptr %hp`, + ` %live = icmp ne i32 %h, 0`, + ` br i1 %live, label %yes, label %none`, + `yes:`, + ` ret ptr %e`, + `none:`, + ` ret ptr null`, `}`, ``, ); @@ -2278,7 +2469,7 @@ export function emitFfiCallbackDefs(emitter: LlEmitter): { globals: string[]; de export function emitParts(emitter: LlEmitter): string[] { const parts = [ - ...limitInlineDynReleases(emitter.emitModuleParts()), + ...limitInlineReleases(emitter.emitModuleParts(), emitter.shapeHost.rcMode), ...emitter.disposeObserverGates(), ]; if (!emitter.executableTls) return parts; diff --git a/packages/compiler/src/backend/llvm/emit-statements.ts b/packages/compiler/src/backend/llvm/emit-statements.ts index e15de353a..b530f794d 100644 --- a/packages/compiler/src/backend/llvm/emit-statements.ts +++ b/packages/compiler/src/backend/llvm/emit-statements.ts @@ -32,12 +32,12 @@ import { allocateLocalUnion, storeLocalUnion } from "./local-union-storage.js"; import { boxAccess, boxNewCall, elemAccess } from "./shapes.js"; import { dynHoleRead } from "./loop-array-borrows.js"; import { endsWithJump, matchStringSelfConcat } from "../../ir/analysis.js"; -import { emitDiscardedSplice } from "./expr-containers.js"; +import { charAtUnitRead, emitDiscardedSplice } from "./expr-containers.js"; import { InternalCompilerError } from "../../errors.js"; import { emitDenseArrayGet, emitDenseArrayPop, emitDenseArraySet } from "./dense-array-access.js"; import { emitBorrowedInput } from "./borrowed-inputs.js"; import { f64Lit, llvmCommentText, loadArrCount, sizeToDouble } from "./common.js"; -import { RESULT_DST_ID, RESULT_ENTRY_PREFIX } from "./record-results.js"; +import { resultSlotStore } from "../result-slots.js"; import { matchIntegerArrayForLoop, matchIntegerBytesForLoop, @@ -51,10 +51,12 @@ import { emitCountedLoopSafety, emitPairedLoopSafety, } from "./counted-loops.js"; -import { emitBytesLoopVersionGuard } from "./bytes-loop-versions.js"; +import { emitBytesLoopVersionGuard, type BytesLoopVersion } from "./bytes-loop-versions.js"; import { mangleLocal } from "../mangle.js"; import { LlvmUnsupportedError } from "./unsupported.js"; import type { LlValue } from "./expr-context.js"; +import { everyExprChild, everyStmtChild } from "../../ir/traverse.js"; +import { widenInteger } from "./integer-values.js"; import { SCALAR_UNION_RESULT } from "./int32-abi.js"; import { emitLiteralSwitch } from "./switch-dispatch.js"; import { @@ -74,6 +76,10 @@ import { stringParts, } from "./string-construction.js"; import { emitStringInputs } from "./string-lifetimes.js"; +import { LOOPS } from "./loop-state.js"; + +/** A callback loop version copies the loop; keep the copies small. */ +const MAX_CALLBACK_VERSION_COST = 400; export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { const B = emitter.B; @@ -272,6 +278,7 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { else emitter.toFrame(v); B.line(`store ${emitter.llType(b.type)} ${v.name}, ptr ${b.slot}`); emitter.storeIntegerView(s.localId, v, s.init); + storeIntegerTemp(emitter, s.localId, b, v); if (isRefCounted(b.type)) { emitter.scopes[emitter.scopes.length - 1]!.push({ slot: b.slot, type: b.type }); emitter.noteLastUseMove(s, b); @@ -433,6 +440,11 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { const length = emitter.emitExpr(s.length); if (s.arr.type.kind !== "array") throw new InternalCompilerError("llvm emitter bug: arraySetLength on non-array"); + if (s.reserve === true) { + emitter.declare(`declare void @scr_arr_reserve_len(ptr, double)`); + B.line(`call void @scr_arr_reserve_len(ptr ${arr.name}, double ${length.name})`); + break; + } emitter.emitPublishedArrayGuard(arr.name, s.arr.type, s.pop === true ? 2 : 3); emitter.declare(`declare void @scr_arr_set_len(ptr, double)`); // Assigning the current length (a reused work array reset to where @@ -467,7 +479,7 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { B.startBlock(pop); const elem = s.arr.type.elem; const acc = elemAccess(elem); - const raw = emitDenseArrayPop(emitter, arr.name, acc, call, call); + const raw = emitDenseArrayPop(emitter, arr.name, acc, elem, call, call); if (acc === "ref" && isRefCounted(elem)) { const old = B.tmp(); B.line(`${old} = inttoptr i64 ${raw} to ptr`); @@ -567,13 +579,7 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { ? emitter.classFieldPtr(obj.name, s.className, s.field, "compressed") : emitter.recordFieldPtr(obj.name, s.shapeId, s.field); // A result-slot entry fills zeroed caller storage, each field once. - if ( - s.kind === "recordSet" && - s.obj.kind === "varRef" && - s.obj.localId === RESULT_DST_ID && - emitter.currentFunctionName.startsWith(RESULT_ENTRY_PREFIX) - ) - emitter.initField(ptr, type, inline, v); + if (resultSlotStore(emitter.currentFunctionName, s)) emitter.initField(ptr, type, inline, v); else emitter.replaceField(ptr, type, inline, v); if ( s.kind === "fieldSet" && @@ -780,7 +786,12 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { const trueLabel = B.newLabel("if.t"); const joinLabel = B.newLabel("if.j"); const falseLabel = s.else_ ? B.newLabel("if.f") : joinLabel; - B.condBr(cond, trueLabel, falseLabel); + // A running maximum or minimum is rarely updated; the weights keep + // the branch, where a select would make each element wait on the last. + const weights = emitter.runningExtrema.has(s) + ? `, !prof !{!"branch_weights", i32 1, i32 1000}` + : ""; + B.condBr(cond, trueLabel, falseLabel, weights); B.startBlock(trueLabel); emitter.emitBlock(s.then); B.br(joinLabel); @@ -793,6 +804,21 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { break; } case "while": { + const callbacks = callbackVersionBindings(emitter, s); + if (callbacks) { + emitCallbackVersionedLoop(emitter, s, callbacks); + break; + } + const version = + LOOPS.of(emitter).bytesLoopVersionsEnabled && + LOOPS.of(emitter).bytesLoopVersioning.size < MAX_BYTES_LOOP_VERSION_DEPTH && + !LOOPS.of(emitter).bytesLoopVersioning.has(s) + ? emitter.matchBytesLoopVersion(s, null) + : null; + if (version) { + emitVersionedLoop(emitter, s, version); + break; + } const workerBudget = emitter.workerLoopBudget(s); const le = B.newLabel("loop.e"); emitter.emitLoopCopies(s, true, le, (exit) => { @@ -801,6 +827,7 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { const lp = workerBudget !== null ? B.newLabel("loop.p") : lc; B.br(lc); B.startBlock(lc); + enterLoopHeader(emitter, lc); B.condBr(emitter.emitCondition(s.cond), lb, exit); B.startBlock(lb); emitter.jumpTargets.push({ @@ -825,6 +852,11 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { break; } case "doWhile": { + const callbacks = callbackVersionBindings(emitter, s); + if (callbacks) { + emitCallbackVersionedLoop(emitter, s, callbacks); + break; + } const workerBudget = emitter.workerLoopBudget(s); // Body first (runs at least once); continue jumps to the CONDITION. const le = B.newLabel("loop.e"); @@ -833,6 +865,7 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { const lc = B.newLabel("loop.c"); B.br(lb); B.startBlock(lb); + enterLoopHeader(emitter, lb); emitter.jumpTargets.push({ kind: "loop", brkLabel: exit, @@ -853,6 +886,11 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { break; } case "for": { + const callbacks = callbackVersionBindings(emitter, s); + if (callbacks) { + emitCallbackVersionedLoop(emitter, s, callbacks); + break; + } // The init's scope wraps the whole loop (break/continue must NOT // release it — scopeDepth captured after the push, C parity). const integerArrayLoop = @@ -863,32 +901,33 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { integerArrayLoop ?? (emitter.debug === null ? matchIntegerBytesForLoop(s, emitter.numericLocals) : null); const countedLoop = - !integerLoop && emitter.countedLoopsEnabled + !integerLoop && LOOPS.of(emitter).countedLoopsEnabled ? matchIntegerCountedForLoop( s, emitter.numericLocals, emitter.integerRanges, - emitter.unaliasedArrays, + LOOPS.of(emitter).unaliasedArrays, ) : null; // Two counters closing in on each other (`lo++, hi--`) take the same // integer storage as a counted loop's one. const pairedLoop = - !integerLoop && !countedLoop && emitter.countedLoopsEnabled + !integerLoop && !countedLoop && LOOPS.of(emitter).countedLoopsEnabled ? matchIntegerPairedForLoop(s, emitter.numericLocals, emitter.integerRanges) : null; + // Byte windows and dense loops reason about one counter. const window = - countedLoop && emitter.byteWindowsEnabled + countedLoop && countedLoop.followers.length === 0 && LOOPS.of(emitter).byteWindowsEnabled ? matchByteWindow( s, countedLoop, emitter.numericLocals, emitter.captureIds, emitter.integerRanges, - emitter.byteWindowEntries.get(s) ?? new Set(), + LOOPS.of(emitter).byteWindowEntries.get(s) ?? new Set(), ) : null; - const denseShape = !emitter.denseLoopsEnabled + const denseShape = !LOOPS.of(emitter).denseLoopsEnabled ? null : integerArrayLoop ? { @@ -896,7 +935,7 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { length: integerArrayLoop.limitReceiver as IrExpr & { kind: "varRef" }, range: { min: 0, max: 4294967294 }, } - : countedLoop && !countedLoop.guarded + : countedLoop && !countedLoop.guarded && countedLoop.followers.length === 0 ? countedDenseShape(s, countedLoop) : null; const dense = @@ -905,8 +944,8 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { s, denseShape, emitter.numericLocals, - emitter.unaliasedArrays, - emitter.denseLoopEntries.get(s) ?? new Set(), + LOOPS.of(emitter).unaliasedArrays, + LOOPS.of(emitter).denseLoopEntries.get(s) ?? new Set(), ) : null; if (dense) { @@ -915,18 +954,18 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { slow = B.newLabel("dense.loop.slow"), done = B.newLabel("dense.loop.done"); B.condBr(valid, fast, slow); - emitter.denseLoopsEnabled = false; + LOOPS.of(emitter).denseLoopsEnabled = false; try { B.startBlock(slow); emitter.emitStmt(s); B.br(done); B.startBlock(fast); - emitter.denseLoop = dense; + LOOPS.of(emitter).denseLoop = dense; emitter.emitStmt(s); B.br(done); } finally { - emitter.denseLoop = null; - emitter.denseLoopsEnabled = true; + LOOPS.of(emitter).denseLoop = null; + LOOPS.of(emitter).denseLoopsEnabled = true; } B.startBlock(done); break; @@ -939,7 +978,7 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { B.condBr(valid, fast, slow); const originalRanges = emitter.integerRanges, originalBounds = emitter.bytesBounds; - emitter.byteWindowsEnabled = false; + LOOPS.of(emitter).byteWindowsEnabled = false; try { B.startBlock(slow); emitter.emitStmt(s); @@ -952,64 +991,39 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { } finally { emitter.integerRanges = originalRanges; emitter.bytesBounds = originalBounds; - emitter.byteWindowsEnabled = true; + LOOPS.of(emitter).byteWindowsEnabled = true; } B.startBlock(done); break; } const versionable = - emitter.bytesLoopVersionsEnabled && - emitter.bytesLoopVersioning.size < MAX_BYTES_LOOP_VERSION_DEPTH && - !emitter.bytesLoopVersioning.has(s); + LOOPS.of(emitter).bytesLoopVersionsEnabled && + LOOPS.of(emitter).bytesLoopVersioning.size < MAX_BYTES_LOOP_VERSION_DEPTH && + !LOOPS.of(emitter).bytesLoopVersioning.has(s); // A loop to a typed array's or an array's length keeps its integer // induction. Its counted form only gives the version guard the // counter's iteration space, so the guard also covers accesses of // other typed arrays at the counter, such as `x[i]` and `y[i]` in // `for (let i = 0; i < out.length; i++) out[i] = x[i] * y[i]`. const versionCounted = - versionable && !countedLoop && integerLoop && emitter.countedLoopsEnabled + versionable && !countedLoop && integerLoop && LOOPS.of(emitter).countedLoopsEnabled ? matchIntegerCountedForLoop( s, emitter.numericLocals, emitter.integerRanges, - emitter.unaliasedArrays, + LOOPS.of(emitter).unaliasedArrays, ) : countedLoop; const version = versionable ? emitter.matchBytesLoopVersion(s, versionCounted) : null; if (version) { - const fast = B.newLabel("bytes.version.fast"), - slow = B.newLabel("bytes.version.slow"), - done = B.newLabel("bytes.version.done"); - emitBytesLoopVersionGuard(emitter, version, fast, slow); - const originalBounds = emitter.bytesBounds, - originalOwned = emitter.bytesOwned, - originalRanges = emitter.integerRanges; - emitter.bytesLoopVersioning.add(s); - try { - B.startBlock(slow); - emitter.emitStmt(s); - B.br(done); - B.startBlock(fast); - emitter.bytesBounds = new Set([...originalBounds, ...version.bounds]); - if (version.owned.size > 0) - emitter.bytesOwned = new Set([...originalOwned, ...version.owned]); - if (version.ranges.size > 0) - emitter.integerRanges = new Map([...originalRanges, ...version.ranges]); - if (version.counted?.guarded) emitter.provenCountedGuards.add(s); - emitter.emitStmt(s); - B.br(done); - } finally { - emitter.bytesBounds = originalBounds; - emitter.bytesOwned = originalOwned; - emitter.integerRanges = originalRanges; - emitter.provenCountedGuards.delete(s); - emitter.bytesLoopVersioning.delete(s); - } - B.startBlock(done); + emitVersionedLoop(emitter, s, version); break; } let countedJoin: string | null = null; - if ((countedLoop?.guarded && !emitter.provenCountedGuards.has(s)) || pairedLoop?.guarded) { + if ( + (countedLoop?.guarded && !LOOPS.of(emitter).provenCountedGuards.has(s)) || + pairedLoop?.guarded + ) { const safe = countedLoop ? emitCountedLoopSafety(emitter, countedLoop) : emitPairedLoopSafety(emitter, pairedLoop!); @@ -1018,9 +1032,9 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { countedJoin = B.newLabel("counted.done"); B.condBr(safe, fast, slow); B.startBlock(slow); - emitter.countedLoopsEnabled = false; + LOOPS.of(emitter).countedLoopsEnabled = false; emitter.emitStmt(s); - emitter.countedLoopsEnabled = true; + LOOPS.of(emitter).countedLoopsEnabled = true; B.br(countedJoin); B.startBlock(fast); } @@ -1028,6 +1042,7 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { let integerSlot: string | null = null; let countedLimit: string | null = null; const pairedSlots: string[] = []; + const followerSlots: string[] = []; if (integerLoop) { integerSlot = B.slot(); B.entryAllocas.push( @@ -1049,8 +1064,8 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { slot: integerSlot, type: emitter.sizeType, range: - emitter.denseLoop?.counter === integerLoop.localId - ? emitter.denseLoop.range + LOOPS.of(emitter).denseLoop?.counter === integerLoop.localId + ? LOOPS.of(emitter).denseLoop!.range : { min: 0, max: integerArrayLoop ? 4294967294 : Number.MAX_SAFE_INTEGER - 1 }, }); } else if (countedLoop) { @@ -1067,10 +1082,27 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { type: "i64", signed: true, range: - emitter.denseLoop?.counter === countedLoop.localId - ? emitter.denseLoop.range + LOOPS.of(emitter).denseLoop?.counter === countedLoop.localId + ? LOOPS.of(emitter).denseLoop!.range : countedLoop.range, }); + for (const follower of countedLoop.followers) { + const slot = B.slot(); + B.entryAllocas.push( + `${slot} = alloca i64 ; integer induction ${emitter.currentLocals.get(follower.localId)!.name}`, + ); + const value = emitter.emitExpr(follower.start); + const followerStart = B.tmp(); + B.line(`${followerStart} = fptosi double ${value.name} to i64`); + B.line(`store i64 ${followerStart}, ptr ${slot}`); + followerSlots.push(slot); + emitter.integerLoopBindings.set(follower.localId, { + slot, + type: "i64", + signed: true, + range: follower.range, + }); + } countedLimit = emitCountedLoopLimit(emitter, countedLoop); } else if (pairedLoop) { for (const counter of [pairedLoop.low, pairedLoop.high]) { @@ -1133,6 +1165,7 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { s.update || capturedLets.length > 0 || workerBudget !== null ? B.newLabel("loop.u") : lc; B.br(lc); B.startBlock(lc); + enterLoopHeader(emitter, lc); if (integerLoop && integerSlot) { const receiver = emitter.emitStableReceiver(integerLoop.limitReceiver, []); const lenPtr = B.tmp(); @@ -1210,6 +1243,13 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { B.line(`${old} = load i64, ptr ${integerSlot}`); B.line(`${next} = add nsw i64 ${old}, ${countedLoop.step}`); B.line(`store i64 ${next}, ptr ${integerSlot}`); + countedLoop.followers.forEach((follower, i) => { + const was = B.tmp(); + const now = B.tmp(); + B.line(`${was} = load i64, ptr ${followerSlots[i]}`); + B.line(`${now} = add nsw i64 ${was}, ${follower.step}`); + B.line(`store i64 ${now}, ptr ${followerSlots[i]}`); + }); } else if (pairedLoop) { [pairedLoop.low, pairedLoop.high].forEach((counter, i) => { const old = B.tmp(); @@ -1225,7 +1265,11 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { B.startBlock(le); emitter.releaseScope(emitter.scopes.pop()!); if (integerLoop) emitter.integerLoopBindings.delete(integerLoop.localId); - if (countedLoop) emitter.integerLoopBindings.delete(countedLoop.localId); + if (countedLoop) { + emitter.integerLoopBindings.delete(countedLoop.localId); + for (const follower of countedLoop.followers) + emitter.integerLoopBindings.delete(follower.localId); + } if (pairedLoop) { emitter.integerLoopBindings.delete(pairedLoop.low.localId); emitter.integerLoopBindings.delete(pairedLoop.high.localId); @@ -1596,6 +1640,48 @@ export function emitStmtBody(emitter: LlEmitter, s: IrStmt): void { * Abrupt completions inside tryBody/catchBody ride the finallyStack: * returns inline copies at the return site, while break/continue use the * shared region walk before branching to their resolved target. */ +/** A constant number local whose initializer has an exact integer form + * (such as `const j = i * 4` in a typed-array loop version) keeps that + * integer in an i64 slot beside the double, so reads such as `px[j + 1]` + * index with integer arithmetic instead of converting the double back. + * Every other declaration of the local drops the integer: the same + * declaration is emitted once per loop copy, and a copy must not read the + * integer another copy stored. */ +function storeIntegerTemp( + emitter: LlEmitter, + localId: string, + b: ReturnType, + v: LlValue, +): void { + const local = b.local; + if ( + !emitter.integerTempsEnabled || + b.kind !== "local" || + !local || + local.type.kind !== "f64" || + local.mutable || + local.tdz === true || + emitter.captureIds.has(localId) || + !v.integer + ) { + emitter.integerTemps.delete(localId); + return; + } + const B = emitter.B; + let slot = emitter.integerTemps.get(localId)?.slot; + if (slot === undefined) { + slot = B.slot(); + B.entryAllocas.push(`${slot} = alloca i64 ; integer ${local.name}`); + } + B.line(`store i64 ${widenInteger(emitter, v.integer)}, ptr ${slot}`); + emitter.integerTemps.set(localId, { + slot, + type: "i64", + signed: true, + range: v.integer.range, + }); +} + export function emitTryCatch(emitter: LlEmitter, s: IrStmt & { kind: "tryCatch" }): void { const B = emitter.B; const hasCatch = s.catchBody !== null; @@ -1841,10 +1927,148 @@ export function emitSwitch(emitter: LlEmitter, s: IrStmt & { kind: "switch" }): B.startBlock(end); } +/** The loop copies a callback loop version needs: the bindings the loop + * calls that the constant-callback census resolves to one function, each + * with that function's direct entry. Only small loops of optimized + * synchronous functions, and only bindings declared before the loop, + * qualify: the guard reads each binding before the loop runs. Versions do + * not nest: a loop inside either copy of a version (including the + * versioned loop itself, emitted again for each copy) keeps its calls as + * they are, so a loop nest is emitted at most twice. */ +function callbackVersionBindings( + emitter: LlEmitter, + s: IrStmt & { kind: "for" | "while" | "doWhile" }, +): { ref: IrExpr & { kind: "varRef" }; direct: string }[] | null { + if ( + !emitter.callbackVersionsEnabled || + emitter.currentConstantCallbacks.size === 0 || + emitter.callbackVersioning.size > 0 + ) + return null; + const found = new Map(); + // Bindings the loop declares or writes (a callback declared in its body). + const bound = new Set(); + let cost = 0; + const expr = (e: IrExpr): boolean => { + if (++cost > MAX_CALLBACK_VERSION_COST) return false; + if (e.kind === "assignExpr") bound.add(e.localId); + if (e.kind === "callValue" && e.callee.kind === "varRef" && !found.has(e.callee.localId)) { + const local = emitter.currentLocals.get(e.callee.localId); + const target = + local && local.tdz !== true ? emitter.knownCallbackTarget(e.callee) : undefined; + if (target) found.set(e.callee.localId, { ref: e.callee, direct: target.direct }); + } + return everyExprChild(e, expr, stmt); + }; + const stmt = (x: IrStmt): boolean => { + if (++cost > MAX_CALLBACK_VERSION_COST) return false; + if (x.kind === "varDecl" || x.kind === "assign" || x.kind === "forOf") bound.add(x.localId); + else if (x.kind === "tryCatch" && x.catchLocalId !== null) bound.add(x.catchLocalId); + return everyStmtChild(x, expr, stmt); + }; + if (!stmt(s)) return null; + const bindings = [...found.values()].filter(({ ref }) => !bound.has(ref.localId)); + return bindings.length > 0 ? bindings : null; +} + +/** A callback loop version. The guard tests, once before the loop, that + * each binding's closure holds its known function: a closure's code + * pointer is written only when the closure is built, and the census + * resolves only bindings the function never rebinds. The copy where the + * guard holds calls those functions directly, with no indirect fallback + * that could rewrite the closure or what it captures, so LLVM can keep a + * captured scalar the callback updates in a register. The other copy is the + * ordinary loop. */ +function emitCallbackVersionedLoop( + emitter: LlEmitter, + s: IrStmt & { kind: "for" | "while" | "doWhile" }, + bindings: { ref: IrExpr & { kind: "varRef" }; direct: string }[], +): void { + const B = emitter.B; + let ok = "true"; + for (const { ref, direct } of bindings) { + // A borrowed read: the guard only compares the code pointer. + const closure = emitter.emitReadReceiver(ref).name; + const fnp = B.tmp(), + fn = B.tmp(), + same = B.tmp(); + B.line(`${fnp} = getelementptr inbounds %ScrClosure, ptr ${closure}, i64 0, i32 1`); + B.line(`${fn} = load ptr, ptr ${fnp}`); + B.line(`${same} = icmp eq ptr ${fn}, ${direct}`); + if (ok === "true") ok = same; + else { + const both = B.tmp(); + B.line(`${both} = and i1 ${ok}, ${same}`); + ok = both; + } + } + const fast = B.newLabel("callback.version.fast"), + slow = B.newLabel("callback.version.slow"), + done = B.newLabel("callback.version.done"); + B.condBr(ok, fast, slow); + emitter.callbackVersioning.add(s); + try { + B.startBlock(slow); + emitter.emitStmt(s); + B.br(done); + B.startBlock(fast); + for (const { ref } of bindings) emitter.knownCallbacks.add(ref.localId); + emitter.emitStmt(s); + B.br(done); + } finally { + for (const { ref } of bindings) emitter.knownCallbacks.delete(ref.localId); + emitter.callbackVersioning.delete(s); + } + B.startBlock(done); +} + +/** Entries in a row whose fast copy bailed before a speculative loop site + * stops trying it. */ +const SPECULATION_BAILS = 8; + /** Emit a loop's condition, body and update through `emitCopy`, twice * when speculative-integers.ts plans a fast integer copy. Both copies * share the loop's setup and exit; the ordinary copy comes first so the * fast copy is only emitted when every resume point exists. */ +/** A typed-array loop version: the guard, then the checked copy, which + * runs whenever the guard fails, and the copy whose accesses the guard + * proves in bounds (or thread-owned). */ +function emitVersionedLoop( + emitter: LlEmitter, + s: IrStmt & { kind: "for" | "while" }, + version: BytesLoopVersion, +): void { + const B = emitter.B; + const fast = B.newLabel("bytes.version.fast"), + slow = B.newLabel("bytes.version.slow"), + done = B.newLabel("bytes.version.done"); + emitBytesLoopVersionGuard(emitter, version, fast, slow); + const originalBounds = emitter.bytesBounds, + originalOwned = emitter.bytesOwned, + originalRanges = emitter.integerRanges; + LOOPS.of(emitter).bytesLoopVersioning.add(s); + try { + B.startBlock(slow); + emitter.emitStmt(s); + B.br(done); + B.startBlock(fast); + emitter.bytesBounds = new Set([...originalBounds, ...version.bounds]); + if (version.owned.size > 0) emitter.bytesOwned = new Set([...originalOwned, ...version.owned]); + if (version.ranges.size > 0) + emitter.integerRanges = new Map([...originalRanges, ...version.ranges]); + if (version.counted?.guarded) LOOPS.of(emitter).provenCountedGuards.add(s); + emitter.emitStmt(s); + B.br(done); + } finally { + emitter.bytesBounds = originalBounds; + emitter.bytesOwned = originalOwned; + emitter.integerRanges = originalRanges; + LOOPS.of(emitter).provenCountedGuards.delete(s); + LOOPS.of(emitter).bytesLoopVersioning.delete(s); + } + B.startBlock(done); +} + export function emitLoopCopies( emitter: LlEmitter, loop: Extract, @@ -1895,23 +2119,65 @@ export function emitLoopCopies( ok = both; } } + // Each entry whose fast copy bails counts at the loop site, and a fast + // copy that completes a speculated write and leaves the loop clears the + // count. After SPECULATION_BAILS bailing entries in a row, the site runs + // the ordinary copy only. The count is a hint: both copies give the same + // results, and a race between workers loses at most an update. + const bails = emitter.speculativeLoopSite(); + const count = B.tmp(), + trying = B.tmp(); + B.line(`${count} = load atomic i8, ptr ${bails} unordered, align 1`); + B.line(`${trying} = icmp ult i8 ${count}, ${SPECULATION_BAILS}`); + if (ok === "true") ok = trying; + else { + const both = B.tmp(); + B.line(`${both} = and i1 ${ok}, ${trying}`); + ok = both; + } const fast = B.newLabel("spec.fast"), slow = B.newLabel("spec.slow"); B.condBr(ok, fast, slow); const resume = new Map(); for (const s of plan.writes) resume.set(s, { label: B.newLabel("spec.resume"), placed: false }); + // A failed check finishes its iteration in a third copy, entered only + // there: it re-executes the statement and the rest of the body and the + // update, then enters the ordinary copy through its header. Jumping + // into the middle of the ordinary copy instead would give that loop a + // second entry, and LLVM does not optimize an irreducible loop. + const points = [...resume.values()]; + let header: string | null = null; B.startBlock(slow); + emitter.speculationHeader = (label) => { + header = label; + }; + try { + emitCopy(exit); + } finally { + emitter.speculationHeader = null; + } + if (header === null) + throw new InternalCompilerError("llvm emitter bug: speculative loop copy without a header"); + B.startBlock(B.newLabel("spec.tail")); emitter.speculationResume = resume; + emitter.speculationHeader = () => { + B.br(header!); + B.startBlock(B.newLabel("spec.unused")); + }; try { emitCopy(exit); } finally { emitter.speculationResume = null; + emitter.speculationHeader = null; } B.startBlock(fast); - if (![...resume.values()].every((r) => r.placed)) { + if (!points.every((r) => r.placed)) { B.br(slow); return; } + const ran = B.slot(); + B.entryAllocas.push(`${ran} = alloca i1 ; speculated write completed`); + B.line(`store i1 false, ptr ${ran}`); for (const id of plan.locals.keys()) { const shadow = B.slot(); B.entryAllocas.push( @@ -1948,22 +2214,43 @@ export function emitLoopCopies( writes: plan.writes, resume: new Map([...resume].map(([s, r]) => [s, r.label])), deferred, + bails, + ran, }; try { - if (deferred.size === 0) emitCopy(exit); - else { - const leave = B.newLabel("spec.leave"); - emitCopy(leave); - B.startBlock(leave); - emitter.writeBackDeferred(deferred); - B.br(exit); - } + const leave = B.newLabel("spec.leave"); + emitCopy(leave); + B.startBlock(leave); + emitter.writeBackDeferred(deferred); + // An entry that never ran a speculated write (a loop of no iterations) + // says nothing about the site. + const wrote = B.tmp(), + left = B.tmp(), + counted = B.tmp(), + both = B.tmp(), + clear = B.newLabel("spec.clear"); + B.line(`${wrote} = load i1, ptr ${ran}`); + B.line(`${left} = load atomic i8, ptr ${bails} unordered, align 1`); + B.line(`${counted} = icmp ne i8 ${left}, 0`); + B.line(`${both} = and i1 ${wrote}, ${counted}`); + B.condBr(both, clear, exit); + B.startBlock(clear); + B.line(`store atomic i8 0, ptr ${bails} unordered, align 1`); + B.br(exit); } finally { emitter.speculation = null; for (const id of plan.locals.keys()) emitter.integerLoopBindings.delete(id); } } +/** At the top of a loop copy's header: lets a speculative loop find its + * ordinary copy's header, and keeps its third copy out of the loop. */ +function enterLoopHeader(emitter: LlEmitter, header: string): void { + const dispatch = emitter.speculationHeader; + emitter.speculationHeader = null; + dispatch?.(header); +} + /** A proven integer loop (speculative-integers.ts) for this loop, or null. * A shadowed local's double is stale until the loop is left, which only * the loop's exit, a return and an exception do: the loop is planned only @@ -2090,7 +2377,8 @@ export function emitSpeculativeWrite( if (emitter.frames.pop()!.length > 0) throw new InternalCompilerError("llvm emitter bug: speculative write owns a temporary"); B.line(`store i64 ${result}, ptr ${binding.slot}`); - const deferred = emitter.speculation!.deferred; + const { deferred, bails: site, ran } = emitter.speculation!; + if (ran !== undefined) B.line(`store i1 true, ptr ${ran}`); if (!deferred.has(target.localId)) { const number = B.tmp(); B.line(`${number} = sitofp i64 ${result} to double`); @@ -2101,6 +2389,14 @@ export function emitSpeculativeWrite( B.br(done); B.startBlock(failed); emitter.writeBackDeferred(deferred); + if (site !== undefined) { + const count = B.tmp(), + next = B.tmp(); + emitter.declare("declare i8 @llvm.uadd.sat.i8(i8, i8)"); + B.line(`${count} = load atomic i8, ptr ${site} unordered, align 1`); + B.line(`${next} = call i8 @llvm.uadd.sat.i8(i8 ${count}, i8 1)`); + B.line(`store atomic i8 ${next}, ptr ${site} unordered, align 1`); + } B.br(resume!); B.startBlock(done); } @@ -2235,7 +2531,7 @@ function charAtUnitSwitch(s: IrStmt & { kind: "switch" }): (IrStmt & { kind: "sw return null; return { ...s, - disc: { ...disc, method: "charCodeAt", type: F64 }, + disc: charAtUnitRead(disc), cases: s.cases.map((c) => c.test?.kind === "strLit" ? { diff --git a/packages/compiler/src/backend/llvm/emitter-state.ts b/packages/compiler/src/backend/llvm/emitter-state.ts new file mode 100644 index 000000000..62dc47b4e --- /dev/null +++ b/packages/compiler/src/backend/llvm/emitter-state.ts @@ -0,0 +1,24 @@ +/* Per-feature emitter state. A feature defines its state in its own file + * with defineModuleState and reads it through the returned key, so adding + * or extending a feature does not edit LlEmitter's field list or + * constructor. */ +import type { LlEmitter } from "./emitter.js"; + +/** A feature's state on an emitter, read with `key.of(emitter)`. */ +export interface EmitterStateKey { + of(emitter: LlEmitter): T; +} + +let moduleSlots = 0; + +/** State that lives for the whole module, created on first read. */ +export function defineModuleState(create: (emitter: LlEmitter) => T): EmitterStateKey { + const slot = moduleSlots++; + return { + of(emitter) { + const states = emitter.moduleStates; + if (slot >= states.length || states[slot] === undefined) states[slot] = create(emitter); + return states[slot] as T; + }, + }; +} diff --git a/packages/compiler/src/backend/llvm/emitter.test.ts b/packages/compiler/src/backend/llvm/emitter.test.ts index f413d6153..d1fd62a83 100644 --- a/packages/compiler/src/backend/llvm/emitter.test.ts +++ b/packages/compiler/src/backend/llvm/emitter.test.ts @@ -13,6 +13,7 @@ import { type IrType, } from "../../ir/ir.js"; import { emitLlvmModule, emitLlvmModuleSource, LlEmitter } from "./emitter.js"; +import { INLINE_STR_RELEASES_PER_FUNCTION } from "./shapes.js"; /** A pending-exception check: the inline active-cell test or a runtime call. */ const PENDING_CHECK = /@scr_exc_(?:active|pending)\b/; @@ -201,17 +202,24 @@ test("detached exit defines the runtime opt-in symbol only when requested", () = expect(detached.replace("@scr_detached_exit = constant i8 1\n", "")).toBe(plain); }); -test("inline RC inlines every fast path at speed and keeps string and box releases as calls in release", () => { +test("inline RC inlines every fast path at speed and keeps box releases as calls in release", () => { for (const boxed of [false, true]) { const module = moduleFor(Array.from({ length: 4 }, call), { boxed }); const release = emitLlvmModule(module); expect(release).not.toContain("@sc_rc_"); expect(release).not.toContain("%ScrMapRc"); - // The release subset inlines string retains and dyn retains and releases - // only; these string and box releases stay runtime calls. + // The release subset inlines string and dyn retains and releases and Map + // retains only: box releases stay runtime calls, and so do the string + // releases of a function with more than INLINE_STR_RELEASES_PER_FUNCTION. const subset = emitLlvmModule(module, { inlineRc: "release" }); - expect(subset).not.toContain("@sc_rc_release_str"); - expect(subset).not.toContain("@sc_rc_release_box"); + expect(subset).not.toContain("call void @sc_rc_release_box("); + const sites = (ir: string, fn: string): number => ir.split(`call void @${fn}(ptr`).length - 1; + if (!boxed) { + expect(sites(subset, "sc_rc_release_str")).toBe(0); + // Every site calls the runtime, and so does the unused helper's slow path. + expect(sites(subset, "scr_str_release")).toBe(sites(release, "scr_str_release") + 1); + expect(sites(release, "scr_str_release")).toBeGreaterThan(INLINE_STR_RELEASES_PER_FUNCTION); + } const speed = emitLlvmModule(module, { inlineRc: "speed" }); const helper = boxed ? "sc_rc_release_box" : "sc_rc_release_str"; const runtime = boxed ? "scr_box_release" : "scr_str_release"; diff --git a/packages/compiler/src/backend/llvm/emitter.ts b/packages/compiler/src/backend/llvm/emitter.ts index c254d0907..9c42920b9 100644 --- a/packages/compiler/src/backend/llvm/emitter.ts +++ b/packages/compiler/src/backend/llvm/emitter.ts @@ -57,7 +57,6 @@ import { } from "../../ir/ir.js"; import { moduleRuntimeFeatures, type RuntimeFeatures } from "../../ir/runtime-features.js"; import { captureFreeFunctions, observesStacks } from "../stack-observations.js"; -import { type DenseArrayLoop } from "./dense-array-loops.js"; import { findInitializedByteLoopBindings } from "./byte-windows.js"; import { matchBytesLoopVersion } from "./bytes-loop-versions.js"; import { globalSlotAlias } from "./bytes-alias.js"; @@ -71,7 +70,15 @@ import { import { scalarizeNumericRecords } from "../../ir/scalar-records.js"; import { addRecordResultEntries } from "./record-results.js"; import { specializeCallbackCalls } from "../../ir/callback-specialization.js"; +import { + type ChunkResult, + EmitJournal, + registerReplay, + renameChunk, + replayJournal, +} from "./emit-journal.js"; import { specializeNumericCalls } from "../../ir/numeric-call-specialization.js"; +import { versionLoopBoundParameters } from "../../ir/parameter-versions.js"; import { everyExpr, everyExprChild, everyStmtChild, everyStmtList } from "../../ir/traverse.js"; import { INT32_RANGE, type IntegerRange, type IntegerRanges } from "../../ir/integer-ranges.js"; import { unshareNodes } from "../../ir/unshare.js"; @@ -83,6 +90,7 @@ import { foldConstantGlobals } from "../../ir/constant-globals.js"; import { dropUnwrittenPropertyBags } from "../../ir/property-bags.js"; import { freezeInitOnlyGlobals } from "../../ir/init-only-globals.js"; import { hoistFinalFieldReads } from "../../ir/field-values.js"; +import { holdCharLocalsAsUnits } from "../../ir/char-unit-locals.js"; import { findInt32Abis, INT32_ABI_SUFFIX, @@ -175,8 +183,10 @@ import { emitDynamicExpr } from "./expr-dynamic.js"; import { emitIntrinsicExpr, emitSerializationExpr, emitAsyncExpr } from "./expr-async.js"; import { PublishWalkers } from "./publish.js"; import { computeImmutableFields, stableGlobals, type ImmutableFields } from "../immutability.js"; +import { computeCycleMutability, hierarchyUnitOfClass } from "../cycle-mutability.js"; import { computePublishedTypes, type PublishedTypes } from "../publication.js"; import { emitExpr } from "./expr-dispatch.js"; +import { LOOPS } from "./loop-state.js"; import { dynKind, @@ -392,9 +402,32 @@ export interface LlScopeEntry { lazy?: boolean; } +/** Process primitives for forked emission workers. */ +export interface ForkPrimitives { + /** 0 in the worker, the worker's pid in the parent, -1 on failure. */ + fork(): number; + /** Ends the worker without running exit handlers. */ + exit(code: number): void; + /** The worker's exit status, 128 plus a signal number, or -1. */ + wait(pid: number): number; +} + export interface LlvmTargetOptions { /** C ABI target; omitted direct emission uses the host ABI. */ targetTriple?: string; + /** Emit the function bodies in this many contiguous ranges, each by its + * own emitter, and merge them in function order (emit-journal.ts). The + * output is the same as one emitter's. Debug builds (`debugSources`) + * emit in one emitter. */ + functionChunks?: number; + /** Emit the function bodies of a large module on this many forked worker + * processes at a time (emit-module.ts), forked with `forkPrimitives`. The + * output is the same as one emitter's. Debug builds (`debugSources`) + * emit in one emitter. */ + functionWorkers?: number; + /** The host's process primitives, where it can fork (the native + * compiler's). */ + forkPrimitives?: ForkPrimitives | undefined; /** Exact frontend sources for dev-build locations and variable metadata. */ debugSources?: ReadonlyMap; /** Pointer width of the target C ABI. Native targets are 64-bit today. */ @@ -442,6 +475,14 @@ export function lowRegionTarget(platform: string, sanitize: boolean): boolean { return platform === "linux" && !sanitize; } +/** Function versions on loop-bounding number parameters + * (ir/parameter-versions.ts). Library builds have no int32 entries, and a + * module that observes call stacks could see the version's frame. */ +function versionParameters(mod: IrModule): IrModule { + if (mod.lib !== undefined || observesStacks(mod)) return mod; + return versionLoopBoundParameters(mod, mangleFunction); +} + export function emitLlvmModule(input: IrModule, options: LlvmTargetOptions = {}): string { // Facts are keyed by node identity: emit the same module whether it was // lowered in memory or read back from its serialized form. @@ -449,20 +490,26 @@ export function emitLlvmModule(input: IrModule, options: LlvmTargetOptions = {}) // Keep source storage intact for debugger inspection in dev builds. return new LlEmitter( options.debugSources === undefined - ? addRecordResultEntries( - scalarizeNumericRecords( - specializeCallbackCalls( - specializeNumericCalls( - foldConstantGlobals( - copyStableCaptures( - resolveSelfCaptures( - hoistFinalFieldReads(freezeInitOnlyGlobals(dropUnwrittenPropertyBags(mod))), + ? versionParameters( + addRecordResultEntries( + scalarizeNumericRecords( + specializeCallbackCalls( + specializeNumericCalls( + foldConstantGlobals( + copyStableCaptures( + resolveSelfCaptures( + hoistFinalFieldReads( + freezeInitOnlyGlobals( + holdCharLocalsAsUnits(dropUnwrittenPropertyBags(mod)), + ), + ), + ), ), ), + mangleFunction, ), mangleFunction, ), - mangleFunction, ), ), ) @@ -481,20 +528,26 @@ export function emitLlvmModuleSource( const mod = unshareNodes(input); const parts = new LlEmitter( options.debugSources === undefined - ? addRecordResultEntries( - scalarizeNumericRecords( - specializeCallbackCalls( - specializeNumericCalls( - foldConstantGlobals( - copyStableCaptures( - resolveSelfCaptures( - hoistFinalFieldReads(freezeInitOnlyGlobals(dropUnwrittenPropertyBags(mod))), + ? versionParameters( + addRecordResultEntries( + scalarizeNumericRecords( + specializeCallbackCalls( + specializeNumericCalls( + foldConstantGlobals( + copyStableCaptures( + resolveSelfCaptures( + hoistFinalFieldReads( + freezeInitOnlyGlobals( + holdCharLocalsAsUnits(dropUnwrittenPropertyBags(mod)), + ), + ), + ), ), ), + mangleFunction, ), mangleFunction, ), - mangleFunction, ), ), ) @@ -616,6 +669,8 @@ function countLocalMentions(body: readonly IrStmt[], id: string): number { } export class LlEmitter { + /** Per-feature state (emitter-state.ts), indexed by each key's slot. */ + readonly moduleStates: unknown[] = []; localArrayReads = new Map(); loopArrayBorrows: ReadonlySet = new Set(); scalarStringSlices = new Map(); @@ -641,9 +696,11 @@ export class LlEmitter { * 32-bit references to compact class instances (LlClassMeta.compressed): * loadField/loadRef decode them and storeField/storeRef encode them. */ readonly compressedFieldPtrs = new Set(); - /** Whether a class has compressed fields: main reserves the region before - * compiled code runs (scr_plr_init). */ - usesCompactRefs = false; + /** Compact class instances live in the program-lifetime region below + * 32 GiB (LlvmTargetOptions.lowRegion, and the program has compact + * classes): main reserves it before compiled code runs (scr_plr_init), and + * fields and arrays of compactRefType hold 32-bit references. */ + compactRegion = false; /** Native class fields with different property names cannot occupy the * same slot of one object. Inherited views of the same property share a @@ -660,6 +717,7 @@ export class LlEmitter { tag = 2 + this.fieldAliasTags.size * 2; this.fieldAliasTags.set(field, tag); } + this.journal?.entry("tag", field, tag); this.fieldPointerTags.set(ptr, tag); } @@ -672,6 +730,7 @@ export class LlEmitter { tag = 2 + this.fieldAliasTags.size * 2; this.fieldAliasTags.set(category, tag); } + this.journal?.entry("tag", category, tag); return `, !tbaa !${tag}`; } @@ -679,7 +738,7 @@ export class LlEmitter { * prefix: the counter of a dense array loop's fast copy indexing one of * the arrays its entry test covered. */ provenDenseIndex(arr: IrExpr, index: IrExpr): boolean { - const loop = this.denseLoop; + const loop = LOOPS.of(this).denseLoop; return ( loop !== null && arr.kind === "varRef" && @@ -831,6 +890,15 @@ export class LlEmitter { readonly callLifetimes: CallLifetimes; readonly constantCallbacks: Map>; currentConstantCallbacks: ReadonlyMap = new Map(); + /** The current function's running maximum and minimum updates, whose + * branches are weighted as rarely taken (running-extrema.ts). */ + runningExtrema: ReadonlySet = new Set(); + /** Callback bindings whose closures an enclosing callback loop version + * proved to hold their known function: calls take the direct entry with + * no fallback (emitCallbackVersionedLoop). */ + knownCallbacks = new Set(); + readonly callbackVersioning = new Set(); + callbackVersionsEnabled = false; readonly stackCallbacks: StackCallbacks; readonly receiverReaders: AmbientReceiverReaders; readonly stackCaptures: StackCaptures; @@ -966,6 +1034,11 @@ export class LlEmitter { get usesDynBuiltinStream(): boolean { return this.runtimeFeatures.dynBuiltinStream; } + /** A checked-dynamic for-await may hold a native stream: the program + * links the stream unit (and the dyn-async one the loop needs). */ + get dynForAwaitStreams(): boolean { + return this.runtimeFeatures.stream && this.runtimeFeatures.dynAsync; + } /** Runtime-arm dispatchers for live union values. */ readonly liveDynUnionRefAdapters = new Map(); readonly dynPromiseAdapters = new Map(); @@ -1067,21 +1140,23 @@ export class LlEmitter { * immortal from construction (classes.ts programLifetimeClass). */ readonly programLifetime: ReadonlySet; numericLocals = new Map(); - /** Local arrays of the current function that no other binding can hold - * (ir/array-length-stability.ts). */ - unaliasedArrays: ReadonlySet = new Set(); - /** Dense array loops (dense-array-loops.ts) run in this function. */ - denseLoopsEnabled = false; - denseLoopEntries: ReturnType = new Map(); - /** The fast copy of a dense array loop being emitted. */ - denseLoop: DenseArrayLoop | null = null; captureIds = new Set(); /** Active induction bindings retain their width independently of size_t. */ integerLoopBindings = new Map< string, { slot: string; type: "i32" | "i64"; signed?: boolean; range?: { min: number; max: number } } >(); - countedLoopsEnabled = false; + /** Constant number locals whose latest emitted declaration stored an + * exact integer beside the double, such as `const j = i * 4` in a + * typed-array loop version: an i64 slot and the integer's range. */ + integerTemps = new Map< + string, + { slot: string; type: "i64"; signed: true; range: IntegerRange } + >(); + /** Integer temps are kept only in optimized synchronous functions: an + * async or generator body resumes with its locals in its frame, which + * an entry alloca is not part of. */ + integerTempsEnabled = false; /** Speculative integer loops (speculative-integers.ts) run in this function. */ speculativeLoopsEnabled = false; /** The fast copy of a speculative integer loop being emitted: its @@ -1091,9 +1166,20 @@ export class LlEmitter { resume: Map; /** Globals whose double is written back only when the copy is left. */ deferred: Set; + /** The loop site's count of bailing entries in a row (a global), and + * whether this entry completed a speculated write (a slot). A proven + * integer loop has neither. */ + bails?: string; + ran?: string; } | null = null; + /** Speculative loop sites numbered so far in the module. */ + speculativeLoopSites = 0; /** The ordinary copy being emitted: resume labels still to place. */ speculationResume: Map | null = null; + /** Run once at the top of the next loop copy's header + * (`enterLoopHeader`): records the ordinary copy's header, or sends the + * third copy's header there. */ + speculationHeader: ((header: string) => void) | null = null; /** The function being emitted, for speculative globals. */ speculativeFunction = ""; /** Every function that writes each number global (computed on demand). */ @@ -1111,19 +1197,9 @@ export class LlEmitter { int32Elements: ((arr: IrExpr) => boolean) | null = null; /** Sums whose result only feeds 32-bit conversions (wrapping-sums.ts). */ wrappingSums = new Set(); - byteWindowsEnabled = true; - byteWindowEntries: ReturnType = new Map(); - /** Typed-array loop versioning (bytes-loop-versions.ts) for the current - * function: off in debug and suspending functions and inside a copy. */ - bytesLoopVersionsEnabled = false; - /** Loops being versioned around the statement being emitted: a loop is - * never versioned inside its own copies, and versions nest boundedly. */ - readonly bytesLoopVersioning = new Set(); - bytesLoopEntries: ReturnType | null = null; - bytesLoopFunction: IrFunction | null = null; - /** Counted loops whose integer-form safety test an enclosing version - * guard already passed. */ - readonly provenCountedGuards = new Set(); + /** Number locals of the current function that hold exact integers or NaN + * (findIntegerOrNaNLocals in wrapping-sums.ts). */ + integerOrNaNLocals: ReadonlyMap = new Map(); bytesBounds: ReadonlySet = new Set(); /** Worker programs: typed-array accesses whose views an enclosing version * guard proved thread-owned. */ @@ -1195,13 +1271,29 @@ export class LlEmitter { readonly chainSlots = new Map(); logArgSlots = 0; readonly stackTraces: boolean; + /** The options this emitter was built with (chunk emitters reuse them). */ + readonly targetOptions: LlvmTargetOptions; + /** Records the module-level effects of emitting a range of functions, + * which the emitter that merges the range replays (emit-journal.ts). Null + * when this emitter emits the whole module itself. */ + journal: EmitJournal | null; + /** The emitter's hosts forward to `journal` (journal set, or workers). */ + private readonly journaled: boolean; /** Stack-trace mode: functions no capture can include (no frame push). */ readonly unframedFunctions: ReadonlySet; constructor( readonly mod: IrModule, options: LlvmTargetOptions, + journal: EmitJournal | null = null, ) { + this.targetOptions = options; + this.journal = journal; + this.journaled = + journal !== null || + ((options.functionWorkers ?? 1) > 1 && + options.forkPrimitives !== undefined && + options.debugSources === undefined); this.stackTraces = observesStacks(mod); this.nullableUnions = new NullableUnions(mod, options.debugSources === undefined); this.mockTimers = this.runtimeFeatures.mockTimers; @@ -1284,8 +1376,10 @@ export class LlEmitter { // and per async fiber; WASI, Windows and library builds have none. const triple = (options.targetTriple ?? "").toLowerCase(); const windows = triple === "" ? process.platform === "win32" : triple.includes("windows"); + this.publishedTypes = computePublishedTypes(mod); const mt = computeMayThrow(mod, { stackChecks: !this.wasi && mod.lib === undefined && !windows, + published: this.publishedTypes, }); this.mayThrow = mt.fns; this.workerEntryPolls = mt.workerEntryPolls ?? null; @@ -1294,11 +1388,12 @@ export class LlEmitter { // runtime moves deep prefix nests to a fresh stack using the guard, // which Windows lacks. this.stacklessAsyncAllowed = this.stacklessGenerators && mod.lib === undefined && !windows; - this.publishedTypes = computePublishedTypes(mod); this.unframedFunctions = this.stackTraces ? captureFreeFunctions(mod, this.stackChecks, this.publishedTypes) : new Set(); - this.immutableFields = computeImmutableFields(mod, dynamicStores); + // One field-mutability answer serves immutable fields and traced shapes. + const cycleMutability = computeCycleMutability(mod, hierarchyUnitOfClass(mod), dynamicStores); + this.immutableFields = computeImmutableFields(mod, dynamicStores, cycleMutability); this.constructorFunctions = new Set((mod.classes ?? []).map((c) => `%${c.name}.constructor`)); this.indirectMayThrow = mt.indirect || mod.workers === true; for (const cls of mod.classes ?? []) { @@ -1423,7 +1518,7 @@ export class LlEmitter { this.receiverReaders = new AmbientReceiverReaders(this.fnByName); this.stackCaptures = new StackCaptures(this.fnByName, this.callLifetimes, this.stackCallbacks); this.lazyCaptures = new LazyCaptures(this.fnByName); - const traced = computeTraced(mod, dynamicStores); + const traced = computeTraced(mod, dynamicStores, cycleMutability); this.tracedShapes = traced.shapes; this.tracedUnions = traced.unions; // A shape union's value is whichever record it holds, and the collector @@ -1448,6 +1543,22 @@ export class LlEmitter { } } this.shapeHost = { + // Journal hooks only on emitters that can emit ranges (chunk + // emitters, and emitters whose workers take a journal after the + // fork), so the host's optional calls cost nothing otherwise. + journalAllocated: !this.journaled + ? undefined + : (name, op, args) => this.journal?.allocated(name, op, args), + journalBuilt: !this.journaled ? undefined : () => this.journal?.built(), + journalOpened: !this.journaled ? undefined : (op) => this.journal?.opened(op), + journalUsed: !this.journaled + ? undefined + : (name, op, args) => this.journal?.used(name, op, args), + journalEntry: !this.journaled + ? undefined + : (table, key, value) => this.journal?.entry(table, key, value), + compactArrayElem: (elem) => this.compactArrayElem(elem), + compactRegion: () => this.compactRegion, sizeType: this.sizeType, cycleBufOffset: this.cycleBufOffset, tracedShapes: this.tracedShapes, @@ -1489,6 +1600,11 @@ export class LlEmitter { dynPromiseAdapter: (type) => this.dynPromiseAdapter(type), isErrorClass: (name) => this.classMeta.get(name)?.root.def.name === "%Error", classRootOf: (name) => this.classMeta.get(name)?.root.def.name, + releasesNothing: (t) => { + if (t.kind !== "object" || (this.shapeHost.regions ?? null) !== null) return false; + const meta = this.classMeta.get(t.className); + return meta !== undefined && programLifetimeClass(this.shapeHost, meta); + }, classSubtypes: (name) => { const target = this.classMetaOf(name); const intervals = classMembershipIntervals(this.classMeta, target.def.name); @@ -1577,22 +1693,19 @@ export class LlEmitter { ? (cls, i, isCompact) => { const f = cls.fields[i]!; if (this.inlineUnions.classField(cls.name, f.name)) return false; - const t = f.type; - if (t.kind === "object") return isCompact(t.className); - if (t.kind !== "union") return false; - const single = this.nullableUnions.single(t.unionId); - if (single !== null) - return ( - single.nullTag < 0 && - single.arm.kind === "object" && - isCompact(single.arm.className) - ); - const nullable = this.nullableFields.get(cls.name, f.name); + if (this.compactRefType(f.type, isCompact)) return true; + const nullable = + f.type.kind === "union" && this.nullableUnions.single(f.type.unionId) === null + ? this.nullableFields.get(cls.name, f.name) + : null; return nullable !== null && isCompact(nullable.arm.className); } : undefined, ); - this.usesCompactRefs = [...this.classMeta.values()].some((m) => m.compressed.some(Boolean)); + this.compactRegion = + mod.lib === undefined && + options.lowRegion === true && + [...this.classMeta.values()].some((m) => m.compact); for (const [name, rec] of RUNTIME_ERROR_CLASSES) { const meta = this.classMeta.get(name); if (!meta) break; // hand-written IR without the builtin defs: no stamps @@ -1885,14 +1998,14 @@ export class LlEmitter { /** Whether a fiberless body running on its caller's stack needs the * frame scr_async_inline_enter/exit keep: it isolates the Error.stack - * frame chain, which only stack-observing programs push, and the - * AsyncLocalStorage context, which only programs that enter stores - * change (RuntimeFeatures asyncContext), as a fresh fiber would. Other - * programs run the body with a plain call. The frame also counts the - * bodies running on a fiber's stack for the runtime's trap on a fiberless - * body that suspends. */ + * frame chain, which only stack-observing programs push, as a fresh fiber + * would. Other programs run the body with a plain call. The body runs in + * its caller's AsyncLocalStorage context either way, as Node runs an async + * body up to its first await. The frame also counts the bodies running on + * a fiber's stack for the runtime's trap on a fiberless body that + * suspends. */ get fiberlessFrames(): boolean { - return this.stackTraces || this.schedulesInContext; + return this.stackTraces; } /** The spawn wrapper of a fiberless async function: runs the body on the @@ -2204,7 +2317,7 @@ export class LlEmitter { B.condBr(thrown, rejected, clean); B.startBlock(clean); if (acc === "ref") this.toHeap(value); - this.arrPush(values, acc, value.name); + this.arrPush(values, acc, value.name, elem); B.br(next); B.startBlock(rejected); const promise = B.tmp(); @@ -2320,6 +2433,7 @@ export class LlEmitter { }; this.literals.set(text, lit); } + this.journal?.entry("literal", text, lit); const name = `@${lit.sym}`; this.immortalValues.add(name); return name; @@ -2330,6 +2444,7 @@ export class LlEmitter { literalEquals(text: string): string { const literal = this.internLiteral(text); const name = `@sc_streq_${literal.slice("@sc_lit_".length)}`; + this.journal?.entry("literalEquality", text, name); if (!this.literalEqualities.has(text)) { this.literalEqualities.set(text, name); if (Buffer.byteLength(text, "utf8") > INLINE_LITERAL_BYTES) { @@ -2356,6 +2471,7 @@ export class LlEmitter { lit = { sym: this.contentSymbol("sc_bigint_", key), value }; this.bigintLiterals.set(key, lit); } + this.journal?.entry("bigint", key, { sym: lit.sym, value: lit.value.toString() }); const name = `@${lit.sym}`; this.immortalValues.add(name); return name; @@ -2369,6 +2485,7 @@ export class LlEmitter { c = { sym: this.contentSymbol("sc_cs_", text), len: Buffer.byteLength(text, "utf8") }; this.cstrs.set(text, c); } + this.journal?.entry("cstr", text, c); return `@${c.sym}`; } @@ -2385,6 +2502,7 @@ export class LlEmitter { sym = this.contentSymbol("sc_map_ops_", body); this.mapOpsConsts.set(body, sym); } + this.journal?.entry("mapOps", body, sym); return `@${sym}`; } @@ -2411,6 +2529,7 @@ export class LlEmitter { sym = `sc_unit_${this.unitInstances.size}`; this.unitInstances.set(key, sym); } + this.journal?.entry("unit", key, sym); const name = `@${sym}`; this.immortalValues.add(name); return name; @@ -2424,6 +2543,7 @@ export class LlEmitter { sym = `sc_retype_guard_${this.retypeGuards.size}`; this.retypeGuards.set(unionId, sym); } + this.journal?.entry("retype", unionId, sym); return `@${sym}`; } @@ -2445,6 +2565,7 @@ export class LlEmitter { sym = `sc_absent_${this.absentInstances.size}`; this.absentInstances.set(unionId, sym); } + this.journal?.entry("absent", unionId, sym); const name = `@${sym}`; this.immortalValues.add(name); return name; @@ -2492,6 +2613,7 @@ export class LlEmitter { } declare(decl: string): void { + this.journal?.entry("decl", decl, null); this.decls.add(decl); } @@ -3557,6 +3679,30 @@ export class LlEmitter { return { ptr: p, type, inline: this.inlineUnions.classField(className, field), compressed }; } + /** Whether values of `t` are NULL or a compact class instance: `C`, + * `C | undefined` or `C | null` for a compact class `C`. `C | null | + * undefined` is not: its null is a sentinel outside the region. */ + compactRefType( + t: IrType, + isCompact: (className: string) => boolean = (name) => + this.classMeta.get(name)?.compact === true, + ): boolean { + if (t.kind === "object") return isCompact(t.className); + if (t.kind !== "union") return false; + const single = this.nullableUnions.single(t.unionId); + return ( + single !== null && + single.nullTag < 0 && + single.arm.kind === "object" && + isCompact(single.arm.className) + ); + } + + /** Whether arrays of `elem` hold 32-bit references (SCR_ELEM_CREF). */ + compactArrayElem(elem: IrType): boolean { + return this.compactRegion && this.compactRefType(elem); + } + /** Loads the reference a field pointer addresses: a pointer, or the * decoded 32-bit reference of a compressed field (compressedFieldPtrs). * `tagged`: the load carries the field's alias tags. */ @@ -3612,6 +3758,7 @@ export class LlEmitter { const meta = this.classMetaOf(className); this.classObjs.set(className, { nameSym: this.internLiteral(classJsName(meta.def)) }); } + this.journal?.entry("classObj", className, this.classObjs.get(className)); return mangleClassObj(className); } @@ -3821,13 +3968,13 @@ export class LlEmitter { /** A binding's storage: a module global, a plain local slot, or a boxed * local (the slot holds the capture BOX; access goes through it). */ matchBytesLoopVersion( - s: IrStmt & { kind: "for" }, + s: IrStmt & { kind: "for" | "while" }, counted: IntegerCountedForLoop | null, ): ReturnType { - const fn = this.bytesLoopFunction; + const fn = LOOPS.of(this).bytesLoopFunction; if (!fn) return null; - this.bytesLoopEntries ??= findInitializedByteLoopBindings(fn); - const initialized = this.bytesLoopEntries.get(s); + LOOPS.of(this).bytesLoopEntries ??= findInitializedByteLoopBindings(fn); + const initialized = LOOPS.of(this).bytesLoopEntries!.get(s); if (!initialized) return null; const invariantGlobals = new Set(this.stableGlobals); for (const global of this.initializerBindings.get(fn.name) ?? []) @@ -3841,6 +3988,7 @@ export class LlEmitter { proven: this.bytesBounds, workers: this.mod.workers === true, owned: this.bytesOwned, + scalarStrings: new Set(this.stringSlices.keys()), }); } @@ -3890,6 +4038,25 @@ export class LlEmitter { return b; } + /** The function a call through `callee` is known to reach (a literal + * closure, or a binding the constant-callback census resolves) and the + * entry it calls directly. Async and generator functions stay indirect. */ + knownCallbackTarget(callee: IrExpr): { known: IrFunction; direct: string } | undefined { + const knownName = + callee.kind === "closure" + ? callee.fnName + : callee.kind === "varRef" + ? this.currentConstantCallbacks.get(callee.localId) + : undefined; + const known = knownName ? this.fnByName.get(knownName) : undefined; + if (!known || known.async || known.generator) return undefined; + if (known.captures === undefined) { + this.fnValues.add(known.name); + return { known, direct: `@${mangleWrapper(known.name)}` }; + } + return { known, direct: `@${this.callTarget(known.name)}` }; + } + /** The payload slot of a capture box (ScrBox.slot, field 5). */ boxSlot(box: string): string { const slot = this.B.tmp(); @@ -3903,12 +4070,18 @@ export class LlEmitter { const r = B.tmp(); // Scalar payloads are read in place (scr_box_get_f64/bool are a // memcpy and a nonzero test of the same slot), so LLVM can keep a - // captured number in a register across a loop of calls. + // captured number in a register across a loop of calls. They have an + // alias category of their own: every other access to a box's payload + // is untagged or a runtime call. if (acc === "f64") { - B.line(`${r} = load double, ptr ${this.boxSlot(box)}`); + B.line( + `${r} = load double, ptr ${this.boxSlot(box)}${this.memoryAliasAttachment("box:scalar")}`, + ); } else if (acc === "bool") { const raw = B.tmp(); - B.line(`${raw} = load i64, ptr ${this.boxSlot(box)}`); + B.line( + `${raw} = load i64, ptr ${this.boxSlot(box)}${this.memoryAliasAttachment("box:scalar")}`, + ); B.line(`${r} = icmp ne i64 ${raw}, 0`); } else { this.declare(`declare ptr @scr_box_get_ref(ptr)`); @@ -3922,11 +4095,15 @@ export class LlEmitter { const B = this.B; const acc = boxAccess(t); if (acc === "f64") { - B.line(`store double ${value}, ptr ${this.boxSlot(box)}`); + B.line( + `store double ${value}, ptr ${this.boxSlot(box)}${this.memoryAliasAttachment("box:scalar")}`, + ); } else if (acc === "bool") { const raw = B.tmp(); B.line(`${raw} = zext i1 ${value} to i64`); - B.line(`store i64 ${raw}, ptr ${this.boxSlot(box)}`); + B.line( + `store i64 ${raw}, ptr ${this.boxSlot(box)}${this.memoryAliasAttachment("box:scalar")}`, + ); } else { this.declare(`declare void @scr_box_set_ref(ptr, ptr)`); B.line(`call void @scr_box_set_ref(ptr ${box}, ptr ${value})`); @@ -3975,7 +4152,7 @@ export class LlEmitter { const acc = boxAccess(t); const cell = B.tmp(); B.line(`${cell} = ${arrNewCall(this.shapeHost, t, "1")} ; TDZ cell`); - this.arrPush(cell, acc === "bool" ? "bool" : "f64", value); + this.arrPush(cell, acc === "bool" ? "bool" : "f64", value, null); this.declare(`declare void @scr_box_set_ref(ptr, ptr)`); B.line(`call void @scr_box_set_ref(ptr ${box}, ptr ${cell})`); } @@ -4290,6 +4467,189 @@ export class LlEmitter { return emitFunction(this, fn); } + /** What this range emitter (chunkEmitter) hands the merging emitter, as + * plain data a worker process can write: its journal and the sets and + * flags its functions set. */ + chunkResult(): ChunkResult { + return { + entries: this.journal!.entries, + flags: { + usesCoroutines: this.usesCoroutines, + usesTimers: this.usesTimers, + usesGenSlots: this.usesGenSlots, + needsUnionNone: this.needsUnionNone, + needsNullableAbsent: this.needsNullableAbsent, + needsOom: this.needsOom, + needsBadTag: this.needsBadTag, + needsBadKey: this.needsBadKey, + needsRetainBox: this.needsRetainBox, + }, + publishedNamesSym: this.publishedNamesSym, + rcHelpers: this.rcHelpers === null ? [] : [...this.rcHelpers], + immortalValues: [...this.immortalValues], + fnValues: [...this.fnValues], + arraySearchKinds: [...this.arraySearchKinds], + recordCloneShapes: [...this.recordCloneShapes], + awaitCallees: [...this.awaitCallees], + adoptCallees: [...this.adoptCallees], + directAwaitCallees: [...this.directAwaitCallees], + inlineAwaitCallees: [...this.inlineAwaitCallees], + }; + } + + /** Merges a range emitter's result (chunkResult) into this emitter, in + * the range's order, and answers the rename of the range's text to this + * emitter's numbered helpers. Ranges merge in function order. */ + mergeChunk(chunk: ChunkResult): (text: string) => string { + const names = new Map(); + const tags = new Map(); + // The range's helpers and table entries first, in its order; then the + // sets and flags, which replayed definitions must find as serial + // emission left them (a helper set guards the declarations its first + // request adds). + replayJournal(this, chunk.entries, names, tags); + const flags = chunk.flags; + this.usesCoroutines ||= flags.usesCoroutines; + this.usesTimers ||= flags.usesTimers; + this.usesGenSlots ||= flags.usesGenSlots; + this.needsUnionNone ||= flags.needsUnionNone; + this.needsNullableAbsent ||= flags.needsNullableAbsent; + this.needsOom ||= flags.needsOom; + this.needsBadTag ||= flags.needsBadTag; + this.needsBadKey ||= flags.needsBadKey; + this.needsRetainBox ||= flags.needsRetainBox; + this.publishedNamesSym ??= chunk.publishedNamesSym; + if (this.rcHelpers !== null) for (const key of chunk.rcHelpers) this.rcHelpers.add(key); + for (const name of chunk.immortalValues) this.immortalValues.add(name); + for (const name of chunk.fnValues) this.fnValues.add(name); + for (const kind of chunk.arraySearchKinds) this.arraySearchKinds.add(kind as ArraySearchKind); + for (const shapeId of chunk.recordCloneShapes) this.recordCloneShapes.add(shapeId); + for (const name of chunk.awaitCallees) this.awaitCallees.add(name); + for (const name of chunk.adoptCallees) this.adoptCallees.add(name); + for (const name of chunk.directAwaitCallees) this.directAwaitCallees.add(name); + for (const name of chunk.inlineAwaitCallees) this.inlineAwaitCallees.add(name); + return renameChunk(names, tags); + } + + /** Adds a content-named constant a chunk interned. Its symbol is this + * emitter's own: a digest collision retries in first-use order, which a + * chunk alone does not know. */ + private addContentEntry( + into: Map, + key: string, + entry: V, + prefix: string, + names: Map, + ): void { + let own = into.get(key); + if (own === undefined) { + own = { ...entry, sym: this.contentSymbol(prefix, key) }; + into.set(key, own); + } + if (own.sym !== entry.sym) names.set(entry.sym, own.sym); + } + + /** Applies a chunk's table entry (EmitJournal.entry) at its place in the + * chunk's order: a key this emitter lacks is added, numbered after its + * own entries where the table numbers them, and the chunk's name for it + * is renamed to this emitter's. */ + applyJournalEntry( + table: string, + key: string, + value: unknown, + names: Map, + tags: Map, + ): void { + switch (table) { + case "decl": + this.decls.add(key); + return; + case "literal": + this.addContentEntry( + this.literals, + key, + value as { sym: string; len: number }, + "sc_lit_", + names, + ); + return; + case "literalEquality": + addEntry(this.literalEqualities, key, value as string); + return; + case "bigint": + { + const entry = value as { sym: string; value: string }; + this.addContentEntry( + this.bigintLiterals, + key, + { sym: entry.sym, value: BigInt(entry.value) }, + "sc_bigint_", + names, + ); + } + return; + case "cstr": + this.addContentEntry( + this.cstrs, + key, + value as { sym: string; len: number }, + "sc_cs_", + names, + ); + return; + case "mapOps": { + let own = this.mapOpsConsts.get(key); + if (own === undefined) { + own = this.contentSymbol("sc_map_ops_", key); + this.mapOpsConsts.set(key, own); + } + if (own !== value) names.set(value as string, own); + return; + } + case "classObj": + addEntry(this.classObjs, key, value as { nameSym: string }); + return; + case "retainWrapper": + addEntry(this.nullableUnions.retainWrappers, key, value as string); + return; + case "unit": + return addNumbered(this.unitInstances, key, value as string, "sc_unit_", names); + case "absent": + return addNumbered(this.absentInstances, key, value as string, "sc_absent_", names); + case "retype": + return addNumbered(this.retypeGuards, key, value as string, "sc_retype_guard_", names); + case "slots": + return addNumbered(this.threadSlotsBlocks, key, value as string, "@sc_slots_", names); + case "regex": + return addNumberedSymbol(this.regexInstances, key, value as never, "sc_re_", names); + case "templateStrings": + return addNumberedSymbol( + this.templateStringsInstances, + key, + value as never, + "sc_tsa_", + names, + ); + case "tag": { + let own = this.fieldAliasTags.get(key); + if (own === undefined) { + own = 2 + this.fieldAliasTags.size * 2; + this.fieldAliasTags.set(key, own); + } + if (own !== value) tags.set(value as number, own); + return; + } + default: + throw new InternalCompilerError(`llvm emitter bug: no journal table ${table}`); + } + } + + /** An emitter for a range of this module's functions: the same facts, + * empty module-level tables, and a journal of what the range adds. */ + chunkEmitter(): LlEmitter { + return new LlEmitter(this.mod, { ...this.targetOptions, functionChunks: 1 }, new EmitJournal()); + } + /** The double-ABI entry of a function with an i32 entry: every caller * that is not a direct call (closures, dispatch, adapters, the runtime) * enters here. A pending exception passes through to its caller. */ @@ -5372,6 +5732,7 @@ export class LlEmitter { sym = `@sc_slots_${this.threadSlotsBlocks.size}`; this.threadSlotsBlocks.set(name, sym); } + this.journal?.entry("slots", name, sym); return sym; } @@ -5521,6 +5882,20 @@ export class LlEmitter { if (this.publishWalkersCache !== null) return this.publishWalkersCache; const byPre = [...this.classMeta.values()].sort((a, b) => a.pre - b.pre); this.publishWalkersCache = new PublishWalkers({ + // Journal hooks only on emitters that can emit ranges (chunk + // emitters, and emitters whose workers take a journal after the + // fork), so the host's optional calls cost nothing otherwise. + journalAllocated: !this.journaled + ? undefined + : (name, op, args) => this.journal?.allocated(name, op, args), + journalBuilt: !this.journaled ? undefined : () => this.journal?.built(), + journalOpened: !this.journaled ? undefined : (op) => this.journal?.opened(op), + journalUsed: !this.journaled + ? undefined + : (name, op, args) => this.journal?.used(name, op, args), + journalEntry: !this.journaled + ? undefined + : (table, key, value) => this.journal?.entry(table, key, value), declare: (decl) => this.declare(decl), cstr: (text) => this.cstr(text), sizeType: this.sizeType, @@ -6007,12 +6382,27 @@ export class LlEmitter { } jsIcSite(): string { - return `@sc_js_ic_${this.jsIcSiteCount++}`; + const name = `@sc_js_ic_${this.jsIcSiteCount++}`; + this.journal?.site(name, "jsIcSite"); + return name; } /** A fresh read-site cache for one constant-key dyn read. */ dynReadIcSite(): string { - return `@sc_dyn_read_ic_${this.dynReadIcSites++}`; + const name = `@sc_dyn_read_ic_${this.dynReadIcSites++}`; + this.journal?.site(name, "dynReadIcSite"); + return name; + } + + /** A fresh speculative loop site: the global that counts its bailing + * entries in a row. */ + speculativeLoopSite(): string { + const name = `@sc_spec_bails_${this.speculativeLoopSites++}`; + this.journal?.site(name, "speculativeLoopSite"); + this.journal?.opened("speculativeLoopSite"); + this.declare(`${name} = internal global i8 0`); + this.journal?.built(); + return name; } dynKind(d: string): string { @@ -6089,7 +6479,10 @@ export class LlEmitter { return streamDataAdapter(this, cbT); } - streamDoneFnFor(kind: "w" | "f" | "d" | "t" | "l", doneT: IrType & { kind: "func" }): string { + streamDoneFnFor( + kind: "w" | "f" | "d" | "t" | "l" | "c", + doneT: IrType & { kind: "func" }, + ): string { return streamDoneFnFor(this, kind, doneT); } @@ -6113,7 +6506,7 @@ export class LlEmitter { return zlibBytesThunkFor(this, cbT); } - streamCbThunkFor(kind: "r" | "w" | "f" | "d" | "t" | "l" | "e", cbT: IrType): string { + streamCbThunkFor(kind: "r" | "w" | "f" | "d" | "t" | "l" | "e" | "c" | "v", cbT: IrType): string { return streamCbThunkFor(this, kind, cbT); } @@ -6125,8 +6518,8 @@ export class LlEmitter { return tagInSet(this, uName, unionId, tags); } - arrPush(arr: string, acc: "f64" | "bool" | "ref", value: string): string { - return arrPush(this, arr, acc, value); + arrPush(arr: string, acc: "f64" | "bool" | "ref", value: string, element: IrType | null): string { + return arrPush(this, arr, acc, value, element); } emitArrayCopyLoop(dst: string, src: string, acc: "f64" | "bool" | "ref"): void { @@ -6414,3 +6807,76 @@ export function adoptingAwaitOf(value: IrExpr | null): ExprOf<"awaitExpr"> | nul }); return found; } + +/** Adds `key` to `into` when it lacks it. */ +function addEntry(into: Map, key: string, value: V): void { + if (!into.has(key)) into.set(key, value); +} + +/** Adds `key` to a numbered table when it lacks it, numbering it after the + * table's own entries (`prefix` and its index), and records the rename of + * the chunk's `name` for it. */ +function addNumbered( + into: Map, + key: string, + name: string, + prefix: string, + names: Map, +): void { + let own = into.get(key); + if (own === undefined) { + own = `${prefix}${into.size}`; + into.set(key, own); + } + if (own !== name) names.set(name.replace(/^@/, ""), own.replace(/^@/, "")); +} + +/** addNumbered for entries that keep their numbered name in `sym`. */ +function addNumberedSymbol( + into: Map, + key: string, + entry: V, + prefix: string, + names: Map, +): void { + let own = into.get(key); + if (own === undefined) { + own = { ...entry, sym: `${prefix}${into.size}` }; + into.set(key, own); + } + if (own.sym !== entry.sym) names.set(entry.sym, own.sym); +} + +registerReplay("jsIcSite", (emitter) => emitter.jsIcSite()); +registerReplay("dynReadIcSite", (emitter) => emitter.dynReadIcSite()); +registerReplay("speculativeLoopSite", (emitter) => emitter.speculativeLoopSite()); +for (const op of [ + "dyn.collectionDynOps", + "dyn.dynMatchHelper", + "dyn.jsonSchema", + "dyn.recordNameTable", + "dyn.jsonParseHelper", + "dyn.dynCheckHelper", + "dyn.toDynHelper", + "dyn.promiseDynAdapterHelper", + "dyn.dynFuncThunkHelper", + "dyn.dynFuncBoxHelper", + "dyn.dynFuncAdapterHelper", + "dyn.dynToStrHelper", + "dyn.dynIterNHelper", + "dyn.dynDestrCheckHelper", + "dyn.dynKeyGetHelper", + "dyn.dynComputedKeyGetHelper", + "dyn.caughtToDynHelper", + "dyn.messageListenerHelper", + "dyn.messageReaderHelper", +]) + registerReplay(op, (emitter, args) => emitter.dyn.replayHelper(op, args)); +for (const op of [ + "walkers.jsonWriteHelper", + "walkers.recordFieldWriter", + "walkers.unionJoinHelper", +]) + registerReplay(op, (emitter, args) => emitter.walkers.replayHelper(op, args)); +for (const op of ["publish.walker", "publish.refusal"]) + registerReplay(op, (emitter, args) => emitter.publishWalkers.replayHelper(op, args)); diff --git a/packages/compiler/src/backend/llvm/expr-bytes.ts b/packages/compiler/src/backend/llvm/expr-bytes.ts index 062bfdfbe..c16ae856a 100644 --- a/packages/compiler/src/backend/llvm/expr-bytes.ts +++ b/packages/compiler/src/backend/llvm/expr-bytes.ts @@ -7,7 +7,7 @@ import { F64_INF, exactIndexLines, f64Lit, sizeToDouble } from "./common.js"; import { exactInteger, widenInteger } from "./integer-values.js"; import { byteNumberAccess } from "../../ir/byte-numbers.js"; import { emitByteNumber } from "./byte-numbers.js"; -import { integerOrNaNRange } from "./wrapping-sums.js"; +import { integerOrNaNIndex, integerOrNaNRange } from "./wrapping-sums.js"; import { bytesElementAlias, bytesHeaderAlias } from "./bytes-alias.js"; const BYTES_NUM_KIND: Record = { @@ -119,12 +119,28 @@ export function emitBytesIndex( B.line(`${narrow} = trunc i64 ${wideIndex} to ${host.sizeType}`); return narrow; } - const exact = exactIndexLines(index, len, host.sizeType, () => B.tmp()); - for (const line of exact.lines) B.line(line); + let ok: string; + let wide: string; + const nanIndex = integerOrNaNIndex(host, value, expr); + if (nanIndex) { + // An exact integer or NaN: in range when ordered and below the length. + const wideLength = host.sizeType === "i64" ? len : B.tmp(); + if (host.sizeType !== "i64") B.line(`${wideLength} = zext ${host.sizeType} ${len} to i64`); + const below = B.tmp(); + ok = B.tmp(); + B.line(`${below} = icmp ult i64 ${nanIndex.wide}, ${wideLength}`); + B.line(`${ok} = and i1 ${nanIndex.ordered}, ${below}`); + wide = nanIndex.wide; + } else { + const exact = exactIndexLines(index, len, host.sizeType, () => B.tmp()); + for (const line of exact.lines) B.line(line); + ok = exact.ok; + wide = exact.wide; + } const invalid = B.newLabel("bytes.index.invalid"); const valid = B.newLabel("bytes.index.valid"); - B.condBr(exact.ok, valid, invalid); - let idx = exact.wide; + B.condBr(ok, valid, invalid); + let idx = wide; B.startBlock(invalid); if (skipInvalid) B.br(skipInvalid); @@ -138,7 +154,7 @@ export function emitBytesIndex( B.startBlock(valid); if (host.sizeType !== "i64") { idx = B.tmp(); - B.line(`${idx} = trunc i64 ${exact.wide} to ${host.sizeType}`); + B.line(`${idx} = trunc i64 ${wide} to ${host.sizeType}`); } return idx; } @@ -455,11 +471,13 @@ export function emitToUint32( B.line(`${out} = select i1 ${ordered}, i32 ${low}, i32 0`); return out; } + // Below 2^63 in magnitude, the i64 conversion truncates exactly (every + // double above 2^53 is an integer), and its low 32 bits are ToUint32. const aboveMin = B.tmp(); const belowMax = B.tmp(); const fast = B.tmp(); - B.line(`${aboveMin} = fcmp oge double ${value}, ${f64Lit(-9007199254740992)}`); - B.line(`${belowMax} = fcmp ole double ${value}, ${f64Lit(9007199254740992)}`); + B.line(`${aboveMin} = fcmp oge double ${value}, ${f64Lit(-9223372036854775808)}`); + B.line(`${belowMax} = fcmp olt double ${value}, ${f64Lit(9223372036854775808)}`); B.line(`${fast} = and i1 ${aboveMin}, ${belowMax}`); const fastLabel = B.newLabel("uint32.coerce.fast"); @@ -475,8 +493,8 @@ export function emitToUint32( B.br(done); B.startBlock(slowLabel); - // Only NaN, the infinities and magnitudes above 2^53 reach this block. - // Such a finite double is the integer mantissa * 2^shift with shift >= 1, + // Only NaN, the infinities and magnitudes from 2^63 reach this block. + // Such a finite double is the integer mantissa * 2^shift with shift >= 11, // so its low 32 bits are the shifted mantissa's (none once shift >= 64), // negated for a negative value. NaN and the infinities have the maximum // exponent, a shift of 972, and convert to 0 like ToUint32. Integer diff --git a/packages/compiler/src/backend/llvm/expr-callbacks.ts b/packages/compiler/src/backend/llvm/expr-callbacks.ts index b91cdc543..398aebb21 100644 --- a/packages/compiler/src/backend/llvm/expr-callbacks.ts +++ b/packages/compiler/src/backend/llvm/expr-callbacks.ts @@ -14,6 +14,7 @@ import { LlvmUnsupportedError } from "./unsupported.js"; import type { LlvmEmitterContext } from "./expr-context.js"; import { unionPeekLines, unionTagLines } from "./union-repr.js"; import { inlineUnionCopyLines } from "./inline-unions.js"; +import { registerReplay } from "./emit-journal.js"; /** Text-template union construction around an owned (+1) reference payload: * a fresh box, or the payload itself for a nullable union. */ @@ -55,6 +56,7 @@ export function raceAdapterFor(host: LlvmEmitterContext, from: IrType, to: IrTyp if (sym) return sym; sym = `sc_race_${host.resolveThunks.size}`; host.resolveThunks.set(key, sym); + host.journal?.allocated(sym, "raceAdapterFor", [from, to]); const toArms = to.kind === "union" ? (host.unionsById.get(to.unionId)?.arms ?? []) : []; if (from.kind === "void" && !toArms.some((a) => a.kind === "undefinedT")) { // A Promise entry (the frontend admits void entries without an @@ -70,6 +72,7 @@ export function raceAdapterFor(host: LlvmEmitterContext, from: IrType, to: IrTyp `}`, ``, ); + host.journal?.built(); return sym; } if (to.kind !== "union") @@ -98,6 +101,7 @@ export function raceAdapterFor(host: LlvmEmitterContext, from: IrType, to: IrTyp const tag = tagOf(UNDEFINED_T); d.push(` ${fulfill(host.unitInstanceRef(to.unionId, tag))}`, ` ret void`, `}`, ``); host.resolveThunkDefs.push(...d); + host.journal?.built(); return sym; } if (from.kind !== "union") { @@ -138,6 +142,7 @@ export function raceAdapterFor(host: LlvmEmitterContext, from: IrType, to: IrTyp } d.push(` ${fulfill("%u")}`, ` ret void`, `}`, ``); host.resolveThunkDefs.push(...d); + host.journal?.built(); return sym; } // Sub-union re-tag: switch over the entry's arms, rebuild under the @@ -200,6 +205,7 @@ export function raceAdapterFor(host: LlvmEmitterContext, from: IrType, to: IrTyp ``, ); host.resolveThunkDefs.push(...d); + host.journal?.built(); return sym; } @@ -213,6 +219,7 @@ export function genResultThunkFor( if (sym) return sym; sym = mangleGenResThunk(host.resolveThunks.size); host.resolveThunks.set(key, sym); + host.journal?.allocated(sym, "genResultThunkFor", [genT, recT]); const shape = host.recordsById.get(recT.shapeId); const base = host.nullableUnions.fieldBase(recT.shapeId); const valueT = shape?.fields.find((f) => f.name === "value")?.type; @@ -299,6 +306,7 @@ export function genResultThunkFor( ``, ]; host.resolveThunkDefs.push(...d); + host.journal?.built(); return sym; } if (valueT.kind !== "union") throw new LlvmUnsupportedError(`genResume:${valueT.kind}`); @@ -456,6 +464,7 @@ export function genResultThunkFor( ``, ); host.resolveThunkDefs.push(...d); + host.journal?.built(); return sym; } @@ -467,6 +476,7 @@ export function childExitThunkFor(host: LlvmEmitterContext, param: IrType): stri if (sym) return sym; sym = `sc_cx_${host.resolveThunks.size}`; host.resolveThunks.set(key, sym); + host.journal?.allocated(sym, "childExitThunkFor", [param]); const def = host.unionsById.get(param.unionId); const f64Tag = def ? def.arms.findIndex((a) => a.kind === "f64") : -1; const nullTag = def ? def.arms.findIndex((a) => a.kind === "nullT") : -1; @@ -494,6 +504,7 @@ export function childExitThunkFor(host: LlvmEmitterContext, param: IrType): stri `}`, ``, ); + host.journal?.built(); return sym; } @@ -510,6 +521,7 @@ export function childExitSignalThunkFor( if (sym) return sym; sym = `sc_cx_${host.resolveThunks.size}`; host.resolveThunks.set(key, sym); + host.journal?.allocated(sym, "childExitSignalThunkFor", [codeParam, sigParam]); const codeDef = host.unionsById.get(codeParam.unionId); const f64Tag = codeDef ? codeDef.arms.findIndex((a) => a.kind === "f64") : -1; const codeNullTag = codeDef ? codeDef.arms.findIndex((a) => a.kind === "nullT") : -1; @@ -560,6 +572,7 @@ export function childExitSignalThunkFor( `}`, ``, ); + host.journal?.built(); return sym; } @@ -569,6 +582,7 @@ export function execFileThunkFor(host: LlvmEmitterContext, cbT: IrType & { kind: if (sym) return sym; sym = `sc_exec_${host.resolveThunks.size}`; host.resolveThunks.set(key, sym); + host.journal?.allocated(sym, "execFileThunkFor", [cbT]); const errorParam = cbT.params[0]; let errorTag = -1; let nullTag = -1; @@ -627,6 +641,7 @@ export function execFileThunkFor(host: LlvmEmitterContext, cbT: IrType & { kind: ``, ); host.resolveThunkDefs.push(...d); + host.journal?.built(); return sym; } @@ -639,6 +654,7 @@ export function ipcMessageThunkFor( if (sym) return sym; sym = `sc_ipc_msg_${host.resolveThunks.size}`; host.resolveThunks.set(key, sym); + host.journal?.allocated(sym, "ipcMessageThunkFor", [cbT]); const param = cbT.params[0]; const d: string[] = [ `define internal void @${sym}(ptr %cb, ptr %message) ${FN_ATTRS} { ; IPC message ${typeKey(cbT)}`, @@ -679,6 +695,7 @@ export function ipcMessageThunkFor( } d.push(` ret void`, `}`, ``); host.resolveThunkDefs.push(...d); + host.journal?.built(); return sym; } @@ -688,6 +705,7 @@ export function ipcSendThunkFor(host: LlvmEmitterContext, cbT: IrType & { kind: if (sym) return sym; sym = `sc_ipc_send_${host.resolveThunks.size}`; host.resolveThunks.set(key, sym); + host.journal?.allocated(sym, "ipcSendThunkFor", [cbT]); const param = cbT.params[0]; const d: string[] = [ `define internal void @${sym}(ptr %cb, ptr %error) ${FN_ATTRS} { ; IPC send callback ${typeKey(cbT)}`, @@ -736,6 +754,7 @@ export function ipcSendThunkFor(host: LlvmEmitterContext, cbT: IrType & { kind: } d.push(` ret void`, `}`, ``); host.resolveThunkDefs.push(...d); + host.journal?.built(); return sym; } @@ -747,6 +766,7 @@ export function childDataThunkFor(host: LlvmEmitterContext, param: IrType): stri if (sym) return sym; sym = `sc_cd_${host.resolveThunks.size}`; host.resolveThunks.set(key, sym); + host.journal?.allocated(sym, "childDataThunkFor", [param]); const def = host.unionsById.get(param.unionId); const bytesTag = def ? def.arms.findIndex((a) => a.kind === "bytes" && a.elem === "u8") : -1; if (bytesTag < 0) @@ -768,6 +788,7 @@ export function childDataThunkFor(host: LlvmEmitterContext, param: IrType): stri `}`, ``, ); + host.journal?.built(); return sym; } @@ -780,6 +801,7 @@ export function childDataDynThunkFor(host: LlvmEmitterContext, chunk: "bytes" | if (sym) return sym; sym = `sc_cdd_${host.resolveThunks.size}`; host.resolveThunks.set(key, sym); + host.journal?.allocated(sym, "childDataDynThunkFor", [chunk]); const box = chunk === "bytes" ? "scr_dyn_new_buffer" : "scr_dyn_new_str"; host.declare(`declare ptr @${box}(ptr)`); host.resolveThunkDefs.push( @@ -793,6 +815,7 @@ export function childDataDynThunkFor(host: LlvmEmitterContext, chunk: "bytes" | `}`, ``, ); + host.journal?.built(); return sym; } @@ -813,6 +836,7 @@ export function emitterFixedAdapter( if (sym) return { fn: sym, shim }; sym = `sc_ee_ad_${host.resolveThunks.size}`; host.resolveThunks.set(key, sym); + host.journal?.allocated(sym, "emitterFixedAdapter", [cbT]); host.declare(`declare ptr @scr_box_get_ref(ptr)`); host.declare(`declare void @scr_closure_release(ptr)`); const params = cursor ? "ptr %args" : cbT.params.map((_, i) => `ptr %a${i}`).join(", "); @@ -857,6 +881,7 @@ export function emitterFixedAdapter( } d.push(` call void @scr_closure_release(ptr %orig)`, ` ret void`, `}`, ``); host.resolveThunkDefs.push(...d); + host.journal?.built(); return { fn: sym, shim }; } @@ -882,6 +907,7 @@ export function emitterOnceAdapter( if (sym) return { fn: sym, shim }; sym = `sc_ee_once_${host.resolveThunks.size}`; host.resolveThunks.set(key, sym); + host.journal?.allocated(sym, "emitterOnceAdapter", [boxerT, fire]); host.declare(`declare ptr @scr_box_get_ref(ptr)`); host.declare(`declare void @scr_closure_release(ptr)`); host.declare(`declare void @${fire}(ptr, ptr)`); @@ -921,6 +947,7 @@ export function emitterOnceAdapter( ``, ); host.resolveThunkDefs.push(...d); + host.journal?.built(); return { fn: sym, shim }; } @@ -990,6 +1017,7 @@ export function closeBindThunkFor( if (sym) return sym; sym = `sc_ncb_${host.resolveThunks.size}`; host.resolveThunks.set(key, sym); + host.journal?.allocated(sym, "closeBindThunkFor", [cbUnion, retServer]); const def = host.unionsById.get(cbUnion.unionId); const funcTag = def ? def.arms.findIndex((a) => a.kind === "func") : -1; const funcArm = funcTag >= 0 ? (def!.arms[funcTag] as IrType & { kind: "func" }) : null; @@ -1079,6 +1107,7 @@ export function closeBindThunkFor( } d.push(`}`, ``); host.resolveThunkDefs.push(...d); + host.journal?.built(); return sym; } @@ -1094,6 +1123,7 @@ export function closeOverrideWrapFor( if (sym) return sym; sym = `sc_ncw_${host.resolveThunks.size}`; host.resolveThunks.set(key, sym); + host.journal?.allocated(sym, "closeOverrideWrapFor", [cbUnion, retServer]); const def = host.unionsById.get(cbUnion.unionId); const undefTag = def ? def.arms.findIndex((a) => a.kind === "undefinedT") : -1; if (undefTag < 0) @@ -1122,6 +1152,7 @@ export function closeOverrideWrapFor( `}`, ``, ); + host.journal?.built(); return sym; } @@ -1140,6 +1171,7 @@ export function settledStoreFor( if (sym) return sym; sym = `sc_settled_${host.resolveThunks.size}`; host.resolveThunks.set(key, sym); + host.journal?.allocated(sym, "settledStoreFor", [from, to]); const def = host.unionsById.get(to.unionId); if (!def) throw new InternalCompilerError("llvm emitter bug: settled store to an unknown union"); const armOf = (field: string): { tag: number; arm: IrType & { kind: "record" } } => { @@ -1230,5 +1262,52 @@ export function settledStoreFor( `}`, ``, ); + host.journal?.built(); return sym; } + +registerReplay("raceAdapterFor", (host, args) => + raceAdapterFor(host, args[0] as IrType, args[1] as IrType), +); +registerReplay("genResultThunkFor", (host, args) => + genResultThunkFor( + host, + args[0] as IrType & { kind: "generator" }, + args[1] as IrType & { kind: "record" }, + ), +); +registerReplay("childExitThunkFor", (host, args) => childExitThunkFor(host, args[0] as IrType)); +registerReplay("childExitSignalThunkFor", (host, args) => + childExitSignalThunkFor(host, args[0] as IrType, args[1] as IrType), +); +registerReplay("execFileThunkFor", (host, args) => + execFileThunkFor(host, args[0] as IrType & { kind: "func" }), +); +registerReplay("ipcMessageThunkFor", (host, args) => + ipcMessageThunkFor(host, args[0] as IrType & { kind: "func" }), +); +registerReplay("ipcSendThunkFor", (host, args) => + ipcSendThunkFor(host, args[0] as IrType & { kind: "func" }), +); +registerReplay("childDataThunkFor", (host, args) => childDataThunkFor(host, args[0] as IrType)); +registerReplay("childDataDynThunkFor", (host, args) => + childDataDynThunkFor(host, args[0] as "bytes" | "str"), +); +registerReplay("closeBindThunkFor", (host, args) => + closeBindThunkFor(host, args[0] as IrType, args[1] as boolean), +); +registerReplay("closeOverrideWrapFor", (host, args) => + closeOverrideWrapFor(host, args[0] as IrType, args[1] as boolean), +); +registerReplay("settledStoreFor", (host, args) => + settledStoreFor(host, args[0] as IrType, args[1] as IrType & { kind: "union" }), +); +registerReplay( + "emitterFixedAdapter", + (host, args) => emitterFixedAdapter(host, args[0] as IrType & { kind: "func" }).fn, +); +registerReplay( + "emitterOnceAdapter", + (host, args) => + emitterOnceAdapter(host, args[0] as IrType & { kind: "func" }, args[1] as string).fn, +); diff --git a/packages/compiler/src/backend/llvm/expr-calls.ts b/packages/compiler/src/backend/llvm/expr-calls.ts index f0aa3b276..a4e7cde2c 100644 --- a/packages/compiler/src/backend/llvm/expr-calls.ts +++ b/packages/compiler/src/backend/llvm/expr-calls.ts @@ -11,6 +11,7 @@ import { type IrExpr, type IrFunction, classValueConstructor, + type IrType, } from "../../ir/ir.js"; import { liveRefView } from "./expr-stream-bridges.js"; import { typedRefConstructor, vAdapters } from "./shapes.js"; @@ -29,7 +30,6 @@ import { mangleClassStruct, mangleFnClosure, mangleFunction, - mangleWrapper, mangleVtStruct, mangleAsyncDirectSpawn, } from "../mangle.js"; @@ -56,6 +56,7 @@ import { import type { Writes } from "./reference-writes.js"; import { emitJsIcCall, jsIcSiteOf } from "./js-ic.js"; import { emitClassMembership, emitDowncastGuard } from "./narrow-guards.js"; +import { registerReplay } from "./emit-journal.js"; export function emitCallExpr( host: LlvmEmitterContext, @@ -816,22 +817,7 @@ export function emitCallExpr( const pushReceiver = (): void => { if (lazyReceiver) { const t = lazyReceiver.type; - const key = typeKey(t); - let recipe = host.typedRefRecipes.get(key); - if (recipe === undefined) { - const adapter = host.liveDynRefAdapter(t); - const rc = vAdapters(host.shapeHost, t); - const ctor = typedRefConstructor(host.shapeHost, t); - const kind = ctor.endsWith("_traced") ? 2 : ctor.endsWith("_observed") ? 1 : 0; - // The box binds the same live view eager boxing attaches, so - // `in`, for-in and Object.keys see the class members. - const view = liveRefView(adapter); - recipe = `@sc_trr_${host.typedRefRecipes.size}`; - host.typedRefRecipes.set(key, recipe); - host.resolveThunkDefs.push( - `${recipe} = internal constant { ptr, ptr, ptr, ${host.sizeType}, ptr, ptr, i32, i32, ptr } { ptr ${rc.retain}, ptr ${rc.release}, ptr ${host.cstr(key)}, ${host.sizeType} ${Buffer.byteLength(key, "utf8")}, ptr @${adapter.snapshot}, ptr ${adapter.commit}, i32 ${kind}, i32 ${view?.code ?? 0}, ptr ${view?.ops ?? "null"} }`, - ); - } + const recipe = typedRefRecipe(host, t); host.declare("declare void @scr_dyn_this_push_typed(ptr, ptr)"); B.line(`call void @scr_dyn_this_push_typed(ptr ${lazyReceiver.name}, ptr ${recipe})`); return; @@ -839,21 +825,9 @@ export function emitCallExpr( host.declare("declare void @scr_dyn_this_push_dyn(ptr)"); B.line(`call void @scr_dyn_this_push_dyn(ptr ${receiver?.name ?? "null"})`); }; - const knownName = - e.callee.kind === "closure" - ? e.callee.fnName - : e.callee.kind === "varRef" - ? host.currentConstantCallbacks.get(e.callee.localId) - : undefined; - const candidate = knownName ? host.fnByName.get(knownName) : undefined; - const known = candidate && !candidate.async && !candidate.generator ? candidate : undefined; - let direct: string | undefined; - if (known) { - if (known.captures === undefined) { - host.fnValues.add(known.name); - direct = `@${mangleWrapper(known.name)}`; - } else direct = `@${host.callTarget(known.name)}`; - } + const target = host.knownCallbackTarget(e.callee); + const known = target?.known; + const direct = target?.direct; // A known closure body that borrows reference parameters is entered // directly with lent arguments, as a direct call to a borrowing body // is: an argument is read without a reference when neither a later @@ -939,7 +913,13 @@ export function emitCallExpr( let pending = host.indirectMayThrow; let pendingGuard: string | undefined; let t: string; - if (direct && e.callee.kind === "closure") { + // A literal closure, or a binding an enclosing callback loop version + // proved to hold its known function, enters it directly. + if ( + direct && + (e.callee.kind === "closure" || + (e.callee.kind === "varRef" && host.knownCallbacks.has(e.callee.localId))) + ) { t = invoke(lending ?? direct, !host.receiverReaders.ignores(known!)); if (quiet) pending = false; } else { @@ -1500,3 +1480,28 @@ function emitNumericIndexRead( B.line(`${result} = phi ptr [ ${fast}, %${fastLabel} ], [ ${read.name}, %${slowLabel} ]`); return host.own({ name: result, type: e.type }); } + +/** The recipe a lazily boxed receiver of type `t` is built from: its RC + * adapters, type key and live view, one per type. */ +function typedRefRecipe(host: LlvmEmitterContext, t: IrType): string { + const key = typeKey(t); + let recipe = host.typedRefRecipes.get(key); + if (recipe !== undefined) return recipe; + const adapter = host.liveDynRefAdapter(t); + const rc = vAdapters(host.shapeHost, t); + const ctor = typedRefConstructor(host.shapeHost, t); + const kind = ctor.endsWith("_traced") ? 2 : ctor.endsWith("_observed") ? 1 : 0; + // The box binds the same live view eager boxing attaches, so `in`, + // for-in and Object.keys see the class members. + const view = liveRefView(adapter); + recipe = `@sc_trr_${host.typedRefRecipes.size}`; + host.typedRefRecipes.set(key, recipe); + host.journal?.allocated(recipe, "typedRefRecipe", [t]); + host.resolveThunkDefs.push( + `${recipe} = internal constant { ptr, ptr, ptr, ${host.sizeType}, ptr, ptr, i32, i32, ptr } { ptr ${rc.retain}, ptr ${rc.release}, ptr ${host.cstr(key)}, ${host.sizeType} ${Buffer.byteLength(key, "utf8")}, ptr @${adapter.snapshot}, ptr ${adapter.commit}, i32 ${kind}, i32 ${view?.code ?? 0}, ptr ${view?.ops ?? "null"} }`, + ); + host.journal?.built(); + return recipe; +} + +registerReplay("typedRefRecipe", (host, args) => typedRefRecipe(host, args[0] as IrType)); diff --git a/packages/compiler/src/backend/llvm/expr-containers.ts b/packages/compiler/src/backend/llvm/expr-containers.ts index 8970aa3be..2f4cd98e9 100644 --- a/packages/compiler/src/backend/llvm/expr-containers.ts +++ b/packages/compiler/src/backend/llvm/expr-containers.ts @@ -2,7 +2,7 @@ import { arraySearchHelperName, arraySearchKind } from "./array-search.js"; import { InternalCompilerError } from "../../errors.js"; import { isStableReceiverOperand, undefinedArmTag } from "../../ir/analysis.js"; -import { type IrExpr, type IrType, isRefCounted, typeEquals, typeKey } from "../../ir/ir.js"; +import { F64, type IrExpr, type IrType, isRefCounted, typeEquals, typeKey } from "../../ir/ir.js"; import { mangleResolveThunk } from "../mangle.js"; import { arrOps, @@ -31,8 +31,10 @@ import { emitMapIterCount, emitMapIterEntry, emitMapIterSlot, + compactMapValues, mapEntryLayout, emitMapIterStart, + emitMapSize, emitNumberMapGetRef, emitNumberMapGetScalar, emitNumberMapHas, @@ -49,6 +51,8 @@ import { STRING_CHAR_AT_INT_MARKER, STRING_CHAR_CODE_AT_DECL, STRING_CHAR_CODE_AT_INT_MARKER, + emitAsciiChar, + emitAsciiCharCode, STRING_UTF16_LEN_DECL, } from "./string-reads.js"; import { exactInteger, widenInteger } from "./integer-values.js"; @@ -58,6 +62,7 @@ import { emitDenseArrayPush, } from "./dense-array-access.js"; import { emitUnionWiden } from "./expr-records.js"; +import { registerReplay } from "./emit-journal.js"; export function resolveThunkFor(host: LlvmEmitterContext, inner: IrType): string { const key = typeKey(inner); @@ -65,6 +70,7 @@ export function resolveThunkFor(host: LlvmEmitterContext, inner: IrType): string if (!sym) { sym = mangleResolveThunk(host.resolveThunks.size); host.resolveThunks.set(key, sym); + host.journal?.allocated(sym, "resolveThunkFor", [inner]); const v = vAdapters(host.shapeHost, inner); host.declare(`declare void @scr_resolve_ref_impl(ptr, ptr, ptr, ptr, ptr)`); host.resolveThunkDefs.push( @@ -75,6 +81,7 @@ export function resolveThunkFor(host: LlvmEmitterContext, inner: IrType): string `}`, ``, ); + host.journal?.built(); } return sym; } @@ -102,13 +109,17 @@ export function tagInSet( return acc; } +/** `element`: the array's element type, or null for arrays whose + * elements are not compact class references (dense-array-access.ts + * slotKind). */ export function arrPush( host: LlvmEmitterContext, arr: string, acc: "f64" | "bool" | "ref", value: string, + element: IrType | null, ): string { - return emitDenseArrayPush(host, arr, acc, value); + return emitDenseArrayPush(host, arr, acc, element, value); } /** Move evaluated values through one bounded slot buffer per call site. */ @@ -116,6 +127,7 @@ export function emitArrayValues( host: LlvmEmitterContext, arr: string, acc: "f64" | "bool" | "ref", + element: IrType, values: LlValue[], prepend = false, sharedBuffer?: string, @@ -129,7 +141,7 @@ export function emitArrayValues( return result; } if (values.length === 1) { - if (!prepend) return arrPush(host, arr, acc, values[0]!.name); + if (!prepend) return arrPush(host, arr, acc, values[0]!.name, element); const ty = acc === "f64" ? "double" : acc === "bool" ? "i1" : "ptr"; host.declare( `declare double @scr_arr_unshift_${acc}(ptr, ${ty}${acc === "bool" ? " zeroext" : ""})`, @@ -274,6 +286,36 @@ export function emitArrayCopyLoop( host.B.line(`call double @scr_arr_push_spread(ptr ${dst}, ptr ${src})`); } +/** The `charCodeAt` reads that stand for `charAt` reads the emitter + * rewrote, such as one-unit tests and switches: a loop version's proof + * for the charAt covers its read. */ +const unitReadOrigins = new WeakMap(); + +/** `s.charCodeAt(i)` in place of `s.charAt(i)`, the same index read as a + * code unit. */ +export function charAtUnitRead( + charAt: IrExpr & { kind: "strIntrinsic" }, +): IrExpr & { kind: "strIntrinsic" } { + const read: IrExpr & { kind: "strIntrinsic" } = { + kind: "strIntrinsic", + method: "charCodeAt", + receiver: charAt.receiver, + args: charAt.args, + type: F64, + loc: charAt.loc, + }; + unitReadOrigins.set(read, charAt); + return read; +} + +/** An enclosing loop version proved the string of `e` ASCII and its index + * below the length (bytes-loop-versions.ts). */ +function provenStringRead(host: LlvmEmitterContext, e: IrExpr): boolean { + if (host.bytesBounds.has(e)) return true; + const origin = unitReadOrigins.get(e); + return origin !== undefined && host.bytesBounds.has(origin); +} + export function emitStrIntrinsic( host: LlvmEmitterContext, e: IrExpr & { kind: "strIntrinsic" }, @@ -319,8 +361,10 @@ export function emitStrIntrinsic( const t = B.tmp(); const index = e.args[0] ? exactInteger(host, args[0]!, e.args[0]) : null; if (index) { - host.declare(STRING_CHAR_CODE_AT_INT_MARKER); const wide = widenInteger(host, index); + if (provenStringRead(host, e)) + return { name: emitAsciiCharCode(host, r.name, wide), type: e.type }; + host.declare(STRING_CHAR_CODE_AT_INT_MARKER); B.line(`${t} = call double @sc_str_char_code_at_int(ptr ${r.name}, i64 ${wide})`); return { name: t, type: e.type }; } @@ -333,8 +377,11 @@ export function emitStrIntrinsic( const t = B.tmp(); const index = e.args[0] ? exactInteger(host, args[0]!, e.args[0]) : null; if (index) { - host.declare(STRING_CHAR_AT_INT_MARKER); const wide = widenInteger(host, index); + // The table entry is immortal: nothing owns it. + if (provenStringRead(host, e)) + return host.markImmortal({ name: emitAsciiChar(host, r.name, wide), type: e.type }); + host.declare(STRING_CHAR_AT_INT_MARKER); B.line(`${t} = call ptr @sc_str_char_at_int(ptr ${r.name}, i64 ${wide})`); } else { const at = args[0]?.name ?? f64Lit(0); @@ -628,7 +675,7 @@ export function emitArrIntrinsic( // no-op zero-argument call. const vs = e.args.map((a) => host.emitExpr(a)); host.emitPublishedArrayGuard(r.name, e.receiver.type, 1, f64Lit(0), f64Lit(vs.length)); - return { name: emitArrayValues(host, r.name, acc, vs), type: e.type }; + return { name: emitArrayValues(host, r.name, acc, elem, vs), type: e.type }; } case "pushSpread": { // `a.push(...src)`: append src's elements in order (borrowed src, @@ -660,7 +707,7 @@ export function emitArrIntrinsic( // from right to left so the final front order is source order. const vs = e.args.map((a) => host.emitExpr(a)); host.emitPublishedArrayGuard(r.name, e.receiver.type, 4, f64Lit(0), f64Lit(vs.length)); - return { name: emitArrayValues(host, r.name, acc, vs, true), type: e.type }; + return { name: emitArrayValues(host, r.name, acc, elem, vs, true), type: e.type }; } case "unshiftSpread": { // The runtime snapshots the borrowed source and handles self-spread. @@ -702,7 +749,7 @@ export function emitArrIntrinsic( let slowLabel = ""; if (method === "pop") { slowLabel = B.newLabel("remove.slow"); - denseRaw = emitDenseArrayPop(host, r.name, acc, la, slowLabel); + denseRaw = emitDenseArrayPop(host, r.name, acc, elem, la, slowLabel); denseLabel = B.currentLabel(); B.br(lp); B.startBlock(slowLabel); @@ -771,7 +818,7 @@ export function emitArrIntrinsic( // by content, everything else by pointer). Strict equality. Arrays of // objects and strings scan inline (array-search.ts). const v = host.emitExpr(e.args[0]!); - const search = acc === "ref" ? arraySearchKind(elem) : null; + const search = acc === "ref" ? arraySearchKind(elem, host.compactArrayElem(elem)) : null; if (search !== null) { host.arraySearchKinds.add(search); const t = B.tmp(); @@ -789,7 +836,7 @@ export function emitArrIntrinsic( // Borrowed needle, SameValueZero (NaN matches NaN). For the inline // searches SameValueZero is strict equality. const v = host.emitExpr(e.args[0]!); - const search = acc === "ref" ? arraySearchKind(elem) : null; + const search = acc === "ref" ? arraySearchKind(elem, host.compactArrayElem(elem)) : null; if (search !== null) { host.arraySearchKinds.add(search); const at = B.tmp(), @@ -1060,8 +1107,10 @@ function newCollection(host: LlvmEmitterContext, key: IrType, value: IrType): st const kind = mapKeyKindNum(key, arms); const m = B.tmp(); host.declare(`declare ptr @scr_map_new(i32, i32, ptr)`); + // SCR_MAP_VAL_CREF (3): string keys and compact values (compactMapValues). + const valKind = compactMapValues(host, key, value) ? 3 : mapValKindNum(value); B.line( - `${m} = call ptr @scr_map_new(i32 ${kind}, i32 ${mapValKindNum(value)}, ptr ${collectionOps(host, key, value)})`, + `${m} = call ptr @scr_map_new(i32 ${kind}, i32 ${valKind}, ptr ${collectionOps(host, key, value)})`, ); return m; } @@ -1124,6 +1173,9 @@ export function emitMapLikeIntrinsic( const key = receiverType.kind === "map" ? receiverType.key : receiverType.elem; const kAcc = mapKeyAccess(key); const kTy = mapKeyParamType(kAcc); + // The map keeps compact values in 16-byte entries (SCR_MAP_VAL_CREF). + const compact = receiverType.kind === "map" && compactMapValues(host, key, receiverType.value); + const layout = mapEntryLayout(key, compact); const method = e.method; // A published Map or Set rejects mutation (the guard precedes the // operands, which each method evaluates itself). @@ -1287,7 +1339,7 @@ export function emitMapLikeIntrinsic( if (numberKey !== null) { raw = emitNumberMapGetRef(host, r.name, numberKey, value); } else if (stringKey !== null) { - raw = emitStringMapGetRef(host, r.name, stringKey, value); + raw = emitStringMapGetRef(host, r.name, stringKey, value, compact); } else { host.declare(`declare ptr @scr_map_get_${kAcc}_ref(ptr, ${kTy})`); raw = B.tmp(); @@ -1365,7 +1417,7 @@ export function emitMapLikeIntrinsic( return host.wrapNullable(raw, raw, value, valueTag, e.type, undefTag); } if (stringKey !== null && isRefCounted(value)) { - const raw = emitStringMapGetRef(host, r.name, stringKey, value); + const raw = emitStringMapGetRef(host, r.name, stringKey, value, compact); return host.wrapNullable(raw, raw, value, valueTag, e.type, undefTag); } host.declare(`declare ptr @scr_map_get_${kAcc}_ref(ptr, ${kTy})`); @@ -1413,7 +1465,8 @@ export function emitMapLikeIntrinsic( case "has": { const k = borrowInputs ? host.emitReadReceiver(e.args[0]!) : host.emitExpr(e.args[0]!); if (kAcc === "f64") return { name: emitNumberMapHas(host, r.name, k.name), type: e.type }; - if (kAcc === "str") return { name: emitStringMapHas(host, r.name, k.name), type: e.type }; + if (kAcc === "str") + return { name: emitStringMapHas(host, r.name, k.name, compact), type: e.type }; host.declare(`declare zeroext i1 @scr_map_has_${kAcc}(ptr, ${kTy})`); const t = B.tmp(); B.line(`${t} = call zeroext i1 @scr_map_has_${kAcc}(ptr ${r.name}, ${kTy} ${k.name})`); @@ -1426,12 +1479,8 @@ export function emitMapLikeIntrinsic( B.line(`${t} = call zeroext i1 @scr_map_delete_${kAcc}(ptr ${r.name}, ${kTy} ${k.name})`); return { name: t, type: e.type }; } - case "size": { - host.declare(`declare double @scr_map_size(ptr)`); - const t = B.tmp(); - B.line(`${t} = call double @scr_map_size(ptr ${r.name})`); - return { name: t, type: e.type }; - } + case "size": + return { name: emitMapSize(host, r.name), type: e.type }; case "clear": host.declare(`declare void @scr_map_clear(ptr)`); B.line(`call void @scr_map_clear(ptr ${r.name})`); @@ -1442,7 +1491,7 @@ export function emitMapLikeIntrinsic( return { name: emitMapIterStart(host, r.name), type: e.type }; case "iterLive": { const i = host.emitExpr(e.args[0]!); - const entry = emitMapIterEntry(host, r.name, i.name, mapEntryLayout(key)); + const entry = emitMapIterEntry(host, r.name, i.name, layout); const t = B.tmp(); B.line(`${t} = icmp ne ptr ${entry}, null`); return { name: t, type: e.type }; @@ -1461,7 +1510,7 @@ export function emitMapLikeIntrinsic( kAcc === "str" ? "ref" : kAcc, key, { decl: `declare ${retTy} @${symbol}(ptr, double)`, symbol }, - mapEntryLayout(key), + layout, ); return host.own({ name: t, type: e.type }); } @@ -1488,7 +1537,7 @@ export function emitMapLikeIntrinsic( decl: `declare ${vAcc === "bool" ? "zeroext i1" : retTy} @${symbol}(ptr, double)`, symbol, }, - mapEntryLayout(key), + layout, ); return host.own({ name: t, type: e.type }); } @@ -1539,3 +1588,5 @@ export function emitSetNew(host: LlvmEmitterContext, e: IrExpr & { kind: "setNew } return out; } + +registerReplay("resolveThunkFor", (host, args) => resolveThunkFor(host, args[0] as IrType)); diff --git a/packages/compiler/src/backend/llvm/expr-dynamic.ts b/packages/compiler/src/backend/llvm/expr-dynamic.ts index 563a900f8..9af677586 100644 --- a/packages/compiler/src/backend/llvm/expr-dynamic.ts +++ b/packages/compiler/src/backend/llvm/expr-dynamic.ts @@ -16,6 +16,7 @@ import { streamTypedRefEligible } from "../../ir/analysis.js"; import { DYN, type IrExpr, + type IrType, isDynTypedRefType, isRefCounted, isUnitType, @@ -221,6 +222,19 @@ export function emitDynamicExpr( host.own({ name: prepared, type: { kind: "dyn" } }); host.emitPendingCheck(); const args = e.args.map((a) => emitBorrowedInput(host, a)); + // A closure registered as a 'message' listener gets a typed message + // entry: ports deliver messages of its parameter's layout without + // decoding them to checked-dynamic values first. + const listener = messageListenerArg(e); + if (listener !== null) { + const entry = host.dyn.messageListenerHelper(listener); + if (entry !== null) { + host.declare(`declare void @scr_dyn_func_set_message(ptr, ptr, ptr)`); + B.line( + `call void @scr_dyn_func_set_message(ptr ${args[1]!.name}, ptr @${host.dyn.dynFuncThunkHelper(listener)}, ptr @${entry})`, + ); + } + } let argsPtr = "null"; if (args.length > 0) { const arr = B.slot(); @@ -1282,9 +1296,7 @@ function emitUnionEqWrappedScalar( B.startBlock(same); const eq = B.tmp(); if (arm.kind === "f64") { - host.declare(`declare double @scr_union_get_f64(ptr)`); - const v = B.tmp(); - B.line(`${v} = call double @scr_union_get_f64(ptr ${union.name})`); + const v = host.unionGetF64(union.name); if (e.sameValue) { host.declare(`declare zeroext i1 @scr_num_same_value(double, double)`); B.line(`${eq} = call zeroext i1 @scr_num_same_value(double ${v}, double ${plain.name})`); @@ -1292,9 +1304,7 @@ function emitUnionEqWrappedScalar( B.line(`${eq} = fcmp oeq double ${v}, ${plain.name}`); } } else { - host.declare(`declare zeroext i1 @scr_union_get_bool(ptr)`); - const v = B.tmp(); - B.line(`${v} = call zeroext i1 @scr_union_get_bool(ptr ${union.name})`); + const v = host.unionGetBool(union.name); B.line(`${eq} = icmp eq i1 ${v}, ${plain.name}`); } B.line(`store i1 ${eq}, ptr ${slot}`); @@ -1323,3 +1333,24 @@ export const INHERITED_OBJECT_MEMBERS: ReadonlySet = new Set([ "hasOwnProperty", "propertyIsEnumerable", ]); + +/** EventEmitter methods that register their second argument as a listener. */ +const LISTENER_METHODS: ReadonlySet = new Set([ + "on", + "once", + "addListener", + "prependListener", + "prependOnceListener", +]); + +/** The closure type of `recv.on("message", listener)` and the other + * listener registrations with a typed closure for the 'message' event, or + * null. */ +function messageListenerArg(e: ExprOf<"dynInvoke">): (IrType & { kind: "func" }) | null { + if (!LISTENER_METHODS.has(e.method) || e.args.length !== 2) return null; + const [event, listener] = e.args; + if (event?.kind !== "dynFrom" || event.value.kind !== "strLit" || event.value.value !== "message") + return null; + if (listener?.kind !== "dynFrom" || listener.value.type.kind !== "func") return null; + return listener.value.type; +} diff --git a/packages/compiler/src/backend/llvm/expr-primitives.test.ts b/packages/compiler/src/backend/llvm/expr-primitives.test.ts index 41ecd189e..f343c956e 100644 --- a/packages/compiler/src/backend/llvm/expr-primitives.test.ts +++ b/packages/compiler/src/backend/llvm/expr-primitives.test.ts @@ -200,6 +200,10 @@ test("identity bitwise forms over a proven int32 return the operand's number", ( } // Unproven operands keep the full ToInt32; other operators still compute. expect(body("unknown_or")).toContain("uint32.coerce.slow"); + // The i64 conversion covers every magnitude below 2^63; only NaN, the + // infinities and larger magnitudes take the slow block. + expect(body("unknown_or")).toMatch(/ = fcmp oge double %\S+, 0xC3E0000000000000$/m); + expect(body("unknown_or")).toMatch(/ = fcmp olt double %\S+, 0x43E0000000000000$/m); expect(body("length_and")).toMatch(/ = and i32 .*, 255$/m); }); @@ -308,7 +312,7 @@ test("sums that only feed a bitwise conversion of int32 operands add in 32 bits" }); test.each([32, 64] as const)( - "tagged-template string arrays keep 8-byte slots before their states on %i-bit targets", + "tagged-template string arrays keep 8-byte slots without states on %i-bit targets", (bits) => { const strings: IrExpr = { kind: "templateStrings", @@ -321,14 +325,17 @@ test.each([32, 64] as const)( mod.functions[0]!.body = [{ kind: "exprStmt", expr: strings, loc }]; const llvm = emitLlvmModule(mod, { pointerBits: bits }); const data = /^@sc_tsa_0_data = internal constant .*$/m.exec(llvm)![0]; - // The runtime reads each slot as 8 bytes and finds the states after - // cap * 8 bytes of slots (scr_arr_states_end). - if (bits === 64) expect(data).toContain("<{ [3 x ptr], [3 x i8] }>"); + // The runtime reads each slot as 8 bytes; an array without states + // (`spare` 0 in its header) has no state bytes after them. + if (bits === 64) expect(data).toMatch(/^\S+ = internal constant \[3 x ptr\] /); else { - expect(data).toContain("<{ [3 x <{ ptr, i32 }>], [3 x i8] }>"); + expect(data).toMatch(/^\S+ = internal constant \[3 x <\{ ptr, i32 \}>\] /); expect(data.match(/<\{ ptr @\S+, i32 0 \}>/g)).toHaveLength(3); } - expect(data).toContain("[3 x i8] [ i8 1, i8 1, i8 1 ]"); + expect(data).not.toContain("x i8]"); + expect(llvm).toMatch( + /^@sc_tsa_0 = internal global %ScrArr \{ i\d+ -1, i32 3, i32 3, i8 2, i8 0, i16 0, i32 3, /m, + ); }, ); diff --git a/packages/compiler/src/backend/llvm/expr-primitives.ts b/packages/compiler/src/backend/llvm/expr-primitives.ts index 12e488b6d..72392956a 100644 --- a/packages/compiler/src/backend/llvm/expr-primitives.ts +++ b/packages/compiler/src/backend/llvm/expr-primitives.ts @@ -1,7 +1,7 @@ /* Focused LLVM expression emission extracted from emitter.ts. */ import { InternalCompilerError } from "../../errors.js"; import { matchStringSelfConcat, undefinedArmTag } from "../../ir/analysis.js"; -import { F64, isRefCounted, type IrExpr, type IrType } from "../../ir/ir.js"; +import { isRefCounted, type IrExpr, type IrStrCmpOp, type IrType } from "../../ir/ir.js"; import { mangleRecordClone, mangleRecordNew } from "../mangle.js"; import { arrNewCall, elemAccess } from "./shapes.js"; import { LlvmUnsupportedError } from "./unsupported.js"; @@ -25,14 +25,14 @@ import { withinInt32, withinUint32, } from "../../ir/integer-ranges.js"; -import { emitArrayValues } from "./expr-containers.js"; +import { charAtUnitRead, emitArrayValues } from "./expr-containers.js"; import { constantDivisor, emitCheckedRemainder, emitPowerOfTwoRemainder, emitSignedIntegerRemainder, } from "./integer-remainder.js"; -import { emitDenseArrayGet, emitDenseArrayState, slotWidth } from "./dense-array-access.js"; +import { denseSlotWidth, emitDenseArrayGet, emitDenseArrayState } from "./dense-array-access.js"; import { emitWrappingSum, markWrappingOperands } from "./wrapping-sums.js"; export function emitLiteralExpr( @@ -59,7 +59,8 @@ export function emitLiteralExpr( throw new InternalCompilerError(`llvm emitter bug: bare unitLit '${e.unit}'`); case "varRef": { host.materializeSplitLocal(e.localId); - const integerSlot = host.integerLoopBindings.get(e.localId); + const integerSlot = + host.integerLoopBindings.get(e.localId) ?? host.integerTemps.get(e.localId); if (integerSlot !== undefined) { const integer = B.tmp(); const number = B.tmp(); @@ -562,14 +563,16 @@ export function regexLiteralTemplate( }; host.regexInstances.set(key, re); } + host.journal?.entry("regex", key, re); return `@${re.sym}`; } -/** A string equality between `s.charAt(i)` and a literal of exactly one - * UTF-16 code unit: the charAt call and the unit. */ +/** A string equality or comparison between `s.charAt(i)` and a literal of + * exactly one UTF-16 code unit: the charAt call, the unit, and whether the + * charAt is the left operand. */ function charAtUnitTest( - e: ExprOf<"strEq">, -): { charAt: ExprOf<"strIntrinsic">; code: number } | null { + e: ExprOf<"strEq" | "strCmp">, +): { charAt: ExprOf<"strIntrinsic">; code: number; left: boolean } | null { let text: string; let other: IrExpr; if (e.right.kind === "strLit") { @@ -584,7 +587,17 @@ function charAtUnitTest( if (text.length !== 1) return null; if (other.kind !== "strIntrinsic" || other.method !== "charAt" || other.args.length !== 1) return null; - return { charAt: other, code: text.charCodeAt(0) }; + return { charAt: other, code: text.charCodeAt(0), left: other === e.left }; +} + +/** The fcmp predicate of `s.charAt(i) op "c"` on the code unit (or of + * `"c" op s.charAt(i)` when `charAtLeft` is false). A one-unit string + * compares as its unit; an index out of range reads "", which is below + * every one-unit literal, and its unit read is NaN, which the unordered + * predicates count as below. */ +function charAtUnitPredicate(op: IrStrCmpOp, charAtLeft: boolean): string { + const flipped = charAtLeft ? op : ({ "<": ">", "<=": ">=", ">": "<", ">=": "<=" } as const)[op]; + return { "<": "ult", "<=": "ule", ">": "ogt", ">=": "oge" }[flipped]; } export function emitStringExpr( @@ -635,14 +648,7 @@ export function emitStringExpr( // equals no unit, as "" equals no one-unit literal. const unit = charAtUnitTest(e); if (unit !== null) { - const code = host.emitExpr({ - kind: "strIntrinsic", - method: "charCodeAt", - receiver: unit.charAt.receiver, - args: unit.charAt.args, - type: F64, - loc: unit.charAt.loc, - }); + const code = host.emitExpr(charAtUnitRead(unit.charAt)); const t = B.tmp(); B.line( `${t} = fcmp ${e.negated ? "une" : "oeq"} double ${code.name}, ${f64Lit(unit.code)}`, @@ -672,6 +678,17 @@ export function emitStringExpr( return { name: t, type: e.type }; } case "strCmp": { + // `s.charAt(i) < "c"` (and `s[i]`) for a one-unit literal compares + // the code unit, as the equality above does. + const unit = charAtUnitTest(e); + if (unit !== null) { + const code = host.emitExpr(charAtUnitRead(unit.charAt)); + const t = B.tmp(); + B.line( + `${t} = fcmp ${charAtUnitPredicate(e.op, unit.left)} double ${code.name}, ${f64Lit(unit.code)}`, + ); + return { name: t, type: e.type }; + } const [l, r] = emitStringInputs(host, [e.left, e.right]); const fn = "scr_str_cmp_u16"; host.declare(`declare i32 @${fn}(ptr, ptr)`); @@ -822,6 +839,7 @@ export function emitStringExpr( }; host.templateStringsInstances.set(e.key, inst); } + host.journal?.entry("templateStrings", e.key, inst); return host.own({ name: host.retainFrame(`@${inst.sym}`, e.type), type: e.type }); } case "regexIntrinsic": @@ -878,7 +896,7 @@ export function emitContainerExpr( buffer = B.tmp(); B.entryAllocas.push(`${buffer} = alloca [${Math.min(e.elems.length, 64)} x i64]`); } - if (pending.length > 0) emitArrayValues(host, arr, acc, pending, false, buffer); + if (pending.length > 0) emitArrayValues(host, arr, acc, elem, pending, false, buffer); pending = []; }; e.elems.forEach((el, i) => { @@ -923,7 +941,7 @@ export function emitContainerExpr( } const bound = B.tmp(); B.line(`${bound} = fsub double ${n.name}, ${f64Lit(1)}`); - B.countedLoop(bound, () => host.arrPush(arr, acc, fill), "ole"); + B.countedLoop(bound, () => host.arrPush(arr, acc, fill, elem), "ole"); return out; } case "arrayGet": { @@ -961,7 +979,7 @@ export function emitContainerExpr( idx, e.index, "has", - slotWidth(elemAccess(e.arr.type.elem)), + denseSlotWidth(host, e.arr.type.elem), ); return { name: t, type: e.type }; } @@ -976,7 +994,7 @@ export function emitContainerExpr( idx, e.index, "state", - slotWidth(elemAccess(e.arr.type.elem)), + denseSlotWidth(host, e.arr.type.elem), ); return { name: t, type: e.type }; } diff --git a/packages/compiler/src/backend/llvm/expr-stream-bridges.ts b/packages/compiler/src/backend/llvm/expr-stream-bridges.ts index a0a0cf24a..7cb0fa772 100644 --- a/packages/compiler/src/backend/llvm/expr-stream-bridges.ts +++ b/packages/compiler/src/backend/llvm/expr-stream-bridges.ts @@ -44,6 +44,7 @@ import type { NullableRefField } from "./nullable-fields.js"; import { emitUnionPeek, emitUnionTag } from "./union-repr.js"; import { inlineUnionCopyLines } from "./inline-unions.js"; import { recordMayKeepSource } from "./record-sources.js"; +import { registerReplay } from "./emit-journal.js"; /** An owned (+1) union value for a nullable-pointer class field slot `p` * (the unit arm's immortal instance, or a fresh box around a retained @@ -91,6 +92,7 @@ export function dynPromiseAdapter(host: LlvmEmitterContext, inner: IrType): stri if (existing) return existing; const sym = `sc_dpa_${host.dynPromiseAdapters.size}`; host.dynPromiseAdapters.set(key, sym); + host.journal?.allocated(sym, "dynPromiseAdapter", [inner]); host.declare(`declare ptr @scr_promise_payload_ref(ptr)`); host.declare(`declare void @scr_dyn_release_v(ptr)`); host.declare(`declare void @scr_promise_reject_pending(ptr)`); @@ -146,6 +148,7 @@ export function dynPromiseAdapter(host: LlvmEmitterContext, inner: IrType): stri `}`, ``, ); + host.journal?.built(); return sym; } @@ -602,6 +605,7 @@ export function liveDynUnionRefAdapter( const sym = `sc_ldu_${host.liveDynUnionRefAdapters.size}`; host.liveDynUnionRefAdapters.set(key, sym); + host.journal?.allocated(sym, "liveDynUnionRefAdapter", [t]); const adapters = new Map(); for (const { arm, tag } of mutableArms) { @@ -684,6 +688,7 @@ export function liveDynUnionRefAdapter( `}`, ``, ); + host.journal?.built(); return sym; } @@ -732,6 +737,11 @@ export function streamTypedRefMaterializeAdapter( const snapshot = `sc_ldr_${host.liveDynRefAdapters.size}_materialize`; const adapter: LlStreamTypedRefAdapter = { snapshot, commit: "null" }; host.liveDynRefAdapters.set(key, adapter); + host.journal?.allocated( + snapshot.replace(/_materialize$/, ""), + "streamTypedRefMaterializeAdapter", + [t], + ); if (isDynTypedRefType(t)) { const fields = host.classMeta.get(t.className)?.def.fields; if ( @@ -744,6 +754,7 @@ export function streamTypedRefMaterializeAdapter( ) { host.declare(`declare ptr @scr_dyn_class_view_unavailable(ptr)`); adapter.snapshot = "scr_dyn_class_view_unavailable"; + host.journal?.built(); return adapter; } } @@ -1185,6 +1196,7 @@ export function streamTypedRefMaterializeAdapter( `}`, ``, ); + host.journal?.built(); return adapter; } @@ -1469,6 +1481,7 @@ export function streamFromArrayAdapter( if (existing) return existing; const sym = `sc_sfa_${host.streamFromArrayAdapters.size}`; host.streamFromArrayAdapters.set(key, sym); + host.journal?.allocated(sym, "streamFromArrayAdapter", [t]); const B = new BlockBuilder(); const unionDef = elem.kind === "union" ? host.unionsById.get(elem.unionId) : undefined; if (elem.kind === "union" && !unionDef) { @@ -1585,5 +1598,17 @@ export function streamFromArrayAdapter( `}`, ``, ); + host.journal?.built(); return sym; } + +registerReplay("dynPromiseAdapter", (host, args) => dynPromiseAdapter(host, args[0] as IrType)); +registerReplay("liveDynUnionRefAdapter", (host, args) => + liveDynUnionRefAdapter(host, args[0] as IrType & { kind: "union" }), +); +registerReplay("streamTypedRefMaterializeAdapter", (host, args) => + streamTypedRefMaterializeAdapter(host, args[0] as IrType).snapshot.replace(/_materialize$/, ""), +); +registerReplay("streamFromArrayAdapter", (host, args) => + streamFromArrayAdapter(host, args[0] as IrType & { kind: "array" }), +); diff --git a/packages/compiler/src/backend/llvm/expr-stream-callbacks.ts b/packages/compiler/src/backend/llvm/expr-stream-callbacks.ts index 9be757a20..14a2e3432 100644 --- a/packages/compiler/src/backend/llvm/expr-stream-callbacks.ts +++ b/packages/compiler/src/backend/llvm/expr-stream-callbacks.ts @@ -4,6 +4,7 @@ import { type IrType, isRefCounted, typeKey } from "../../ir/ir.js"; import { FN_ATTRS, releaseSym, retainSym, traceArg } from "./shapes.js"; import type { LlvmEmitterContext } from "./expr-context.js"; import { unionPeekLines, unionTagLines } from "./union-repr.js"; +import { registerReplay } from "./emit-journal.js"; export function streamDataAdapter( host: LlvmEmitterContext, @@ -14,24 +15,57 @@ export function streamDataAdapter( if (sym) return sym; sym = `sc_ee_dad_${host.resolveThunks.size}`; host.resolveThunks.set(key, sym); + host.journal?.allocated(sym, "streamDataAdapter", [cbT]); const p = cbT.params[0]; - if ( - cbT.params.length > 1 || - (p && p.kind !== "bytes" && p.kind !== "string" && p.kind !== "dyn" && p.kind !== "union") - ) { + if (cbT.params.length > 1) { throw new InternalCompilerError( "llvm emitter bug: stream data listener param shape (frontend must fence)", ); } + // A `Buffer | string` union wraps the filled slot; any other union (or + // other type) converts from the chunk's checked-dynamic value. + const bytesOrString = + p?.kind === "union" && + (() => { + const def = host.unionsById.get(p.unionId); + return ( + def !== undefined && + !host.nullableUnions.has(p.unionId) && + def.arms.length === 2 && + def.arms.some((a) => a.kind === "bytes" && a.elem === "u8") && + def.arms.some((a) => a.kind === "string") + ); + })(); host.declare(`declare ptr @scr_box_get_ref(ptr)`); host.declare(`declare void @scr_closure_release(ptr)`); + // The emit ABI's three slots (scr_stream_emit_data): the bytes chunk, + // the string chunk, and an object-mode entry's value. const d: string[] = [ - `define internal void @${sym}(ptr %cb, ptr %a0, ptr %a1) ${FN_ATTRS} { ; stream 'data' adapter ${typeKey(cbT)}`, + `define internal void @${sym}(ptr %cb, ptr %a0, ptr %a1, ptr %a2) ${FN_ATTRS} { ; stream 'data' adapter ${typeKey(cbT)}`, `entry:`, ` %capsp = getelementptr inbounds %ScrClosure, ptr %cb, i64 1`, ` %bx = load ptr, ptr %capsp`, ` %orig = call ptr @scr_box_get_ref(ptr %bx) ; the listener, +1`, ]; + const finishTyped = (arg: string, argTy: string): void => { + d.push( + ` %fnp = getelementptr inbounds %ScrClosure, ptr %orig, i64 0, i32 1`, + ` %fn = load ptr, ptr %fnp`, + ); + const retTy = host.llType(cbT.ret); + const argList = `ptr %orig, ${argTy} ${arg}`; + if (retTy === "void") { + d.push(` call void %fn(${argList})`); + } else { + d.push(` %ret = call ${retTy} %fn(${argList})`); + if (isRefCounted(cbT.ret)) { + d.push( + ` call void ${releaseSym(host.shapeHost, cbT.ret)}(ptr %ret) ; discarded listener result`, + ); + } + } + d.push(` call void @scr_closure_release(ptr %orig)`, ` ret void`); + }; const finish = (arg: string | null): void => { d.push( ` %fnp = getelementptr inbounds %ScrClosure, ptr %orig, i64 0, i32 1`, @@ -57,8 +91,8 @@ export function streamDataAdapter( } else if (p.kind === "bytes" || p.kind === "string") { const msg = p.kind === "bytes" - ? "a 'data' listener declaring a Buffer chunk received a string (the stream has an encoding set)" - : "a 'data' listener declaring a string chunk received a Buffer (call setEncoding, or declare the chunk as a Buffer)"; + ? "a 'data' listener declaring a Buffer chunk received a string or an object-mode value (the stream has an encoding set, or is in object mode)" + : "a 'data' listener declaring a string chunk received a Buffer or an object-mode value (call setEncoding, or declare the chunk's type)"; const slot = p.kind === "bytes" ? "%a0" : "%a1"; host.declare(`declare void @scr_throw_error_msg(i32, ptr, ${host.sizeType})`); d.push( @@ -73,7 +107,7 @@ export function streamDataAdapter( ); finish("%r0"); d.push(`}`, ``); - } else if (p.kind === "union") { + } else if (p.kind === "union" && bytesOrString) { // A `Buffer | string` chunk: wrap whichever slot the stream filled at // its arm of the (boxed) union. const def = host.unionsById.get(p.unionId); @@ -94,6 +128,9 @@ export function streamDataAdapter( host.declare(`declare void @scr_bytes_release_v(ptr)`); host.declare(`declare ptr @scr_str_retain_v(ptr)`); host.declare(`declare void @scr_str_release_v(ptr)`); + host.declare(`declare void @scr_throw_error_msg(i32, ptr, ${host.sizeType})`); + const unionMsg = + "a 'data' listener declaring a Buffer | string chunk received an object-mode value that is neither (declare the chunk's type)"; d.push( ` %uslot = alloca ptr`, ` %isb = icmp ne ptr %a0, null`, @@ -104,6 +141,15 @@ export function streamDataAdapter( ` store ptr %ub, ptr %uslot`, ` br label %go`, `str:`, + // an object-mode value that is neither: the catchable error the + // one-type adapters throw + ` %nos = icmp eq ptr %a1, null`, + ` br i1 %nos, label %bad, label %strok`, + `bad:`, + ` call void @scr_throw_error_msg(i32 1, ptr ${host.cstr(unionMsg)}, ${host.sizeType} ${Buffer.byteLength(unionMsg, "utf8")})`, + ` call void @scr_closure_release(ptr %orig)`, + ` ret void`, + `strok:`, ` %rs = call ptr @scr_str_retain_v(ptr %a1)`, ` %us = call ptr @scr_union_new_ref(i32 ${strTag}, ptr %rs, ptr @scr_str_retain_v, ptr @scr_str_release_v, ptr null)`, ` store ptr %us, ptr %uslot`, @@ -114,11 +160,20 @@ export function streamDataAdapter( finish("%uv"); d.push(`}`, ``); } else { - // dyn: box by runtime tag — the JS lane's adapter parameter. + // dyn: the object-mode value, else box by runtime tag — the JS lane's + // adapter parameter. Any other type converts from that value. host.declare(`declare ptr @scr_dyn_new_buffer(ptr)`); host.declare(`declare ptr @scr_dyn_new_str(ptr)`); + host.declare(`declare ptr @scr_dyn_retain_v(ptr)`); d.push( ` %dslot = alloca ptr`, + ` %isv = icmp ne ptr %a2, null`, + ` br i1 %isv, label %val, label %chunk`, + `val:`, + ` %dvv = call ptr @scr_dyn_retain_v(ptr %a2)`, + ` store ptr %dvv, ptr %dslot`, + ` br label %go`, + `chunk:`, ` %isb = icmp ne ptr %a0, null`, ` br i1 %isb, label %buf, label %str`, `buf:`, @@ -132,16 +187,35 @@ export function streamDataAdapter( `go:`, ` %dv = load ptr, ptr %dslot`, ); - finish("%dv"); + if (p.kind === "dyn") { + finish("%dv"); + } else { + const helper = host.dyn.dynCheckHelper(p, false); + const ty = host.llType(p); + host.declare(`declare void @scr_dyn_release(ptr)`); + host.declare(`declare zeroext i1 @scr_exc_pending()`); + d.push( + ` %tv = call ${ty === "i1" ? "zeroext i1" : ty} @${helper}(ptr %dv, ptr null)`, + ` call void @scr_dyn_release(ptr %dv)`, + ` %pend = call zeroext i1 @scr_exc_pending()`, + ` br i1 %pend, label %fail, label %conv`, + `fail:`, + ` call void @scr_closure_release(ptr %orig)`, + ` ret void`, + `conv:`, + ); + finishTyped("%tv", ty); + } d.push(`}`, ``); } host.resolveThunkDefs.push(...d); + host.journal?.built(); return sym; } export function streamDoneFnFor( host: LlvmEmitterContext, - kind: "w" | "f" | "d" | "t" | "l", + kind: "w" | "f" | "d" | "t" | "l" | "c", doneT: IrType & { kind: "func" }, ): string { const key = `sd:${kind}:${typeKey(doneT)}`; @@ -149,6 +223,7 @@ export function streamDoneFnFor( if (sym) return sym; sym = `sc_sd_${host.resolveThunks.size}`; host.resolveThunks.set(key, sym); + host.journal?.allocated(sym, "streamDoneFnFor", [kind, doneT]); const errT = doneT.params[0]; let errTag = -1; if (errT !== undefined) { @@ -164,25 +239,46 @@ export function streamDoneFnFor( const dataT = kind === "t" || kind === "l" ? doneT.params[1] : undefined; let bytesTag = -1; let strTag = -1; + // data of any type other than a union of Buffer, string, undefined and + // null (an object-mode Transform's value) completes through the + // value entry points with the data boxed. + let valueData = false; if (dataT !== undefined) { - if (dataT.kind !== "union") - throw new InternalCompilerError("llvm emitter bug: stream done data param not a union"); - const def = host.unionsById.get(dataT.unionId); - bytesTag = def ? def.arms.findIndex((a) => a.kind === "bytes") : -1; - strTag = def ? def.arms.findIndex((a) => a.kind === "string") : -1; + const def = dataT.kind === "union" ? host.unionsById.get(dataT.unionId) : undefined; + valueData = + def === undefined || + !def.arms.every( + (a) => + (a.kind === "bytes" && a.elem === "u8") || + a.kind === "string" || + a.kind === "undefinedT" || + a.kind === "nullT", + ); + if (!valueData) { + bytesTag = def!.arms.findIndex((a) => a.kind === "bytes"); + strTag = def!.arms.findIndex((a) => a.kind === "string"); + } } const entry = - kind === "w" - ? "scr_stream_write_done" - : kind === "f" - ? "scr_stream_final_done" - : kind === "d" - ? "scr_stream_destroy_done" - : kind === "t" - ? "scr_stream_transform_done" - : "scr_stream_flush_done"; - const twoSlot = kind === "t" || kind === "l"; - host.declare(`declare void @${entry}(ptr, ptr${twoSlot ? ", ptr, ptr" : ""})`); + kind === "c" + ? "scr_stream_construct_done" + : kind === "w" + ? "scr_stream_write_done" + : kind === "f" + ? "scr_stream_final_done" + : kind === "d" + ? "scr_stream_destroy_done" + : kind === "t" + ? valueData + ? "scr_stream_transform_done_value" + : "scr_stream_transform_done" + : valueData + ? "scr_stream_flush_done_value" + : "scr_stream_flush_done"; + const twoSlot = (kind === "t" || kind === "l") && !valueData; + host.declare( + `declare void @${entry}(ptr, ptr${twoSlot ? ", ptr, ptr" : valueData ? ", ptr" : ""})`, + ); host.declare(`declare ptr @scr_box_get_ref(ptr)`); host.declare(`declare void @scr_stream_release_v(ptr)`); host.declare(`declare ptr @scr_error_retain_v(ptr)`); @@ -190,7 +286,7 @@ export function streamDoneFnFor( const params = [ "ptr %self", ...(errT !== undefined ? ["ptr %e"] : []), - ...(dataT !== undefined ? ["ptr %d"] : []), + ...(dataT !== undefined ? [`${host.llType(dataT)} %d`] : []), ]; const d: string[] = [ `define internal void @${sym}(${params.join(", ")}) ${FN_ATTRS} { ; stream '${kind}' done ${typeKey(doneT)}`, @@ -234,7 +330,15 @@ export function streamDoneFnFor( unwrap("%d", strTag, "@scr_str_retain_v", "%sslot"); } d.push(` %ev = load ptr, ptr %eslot`); - if (twoSlot) { + if (valueData) { + const conv = host.dyn.toDynHelper(dataT!); + host.declare(`declare void @scr_dyn_release(ptr)`); + d.push( + ` %dv = call ptr @${conv}(${host.llType(dataT!)} %d)`, + ` call void @${entry}(ptr %s, ptr %ev, ptr %dv) ; moves err; borrows s and the value`, + ` call void @scr_dyn_release(ptr %dv)`, + ); + } else if (twoSlot) { d.push( ` %bv = load ptr, ptr %bslot`, ` %sv = load ptr, ptr %sslot`, @@ -245,9 +349,11 @@ export function streamDoneFnFor( } d.push(` call void @scr_stream_release_v(ptr %s)`); if (errT !== undefined) d.push(` call void ${releaseSym(host.shapeHost, errT)}(ptr %e)`); - if (dataT !== undefined) d.push(` call void ${releaseSym(host.shapeHost, dataT)}(ptr %d)`); + if (dataT !== undefined && isRefCounted(dataT)) + d.push(` call void ${releaseSym(host.shapeHost, dataT)}(ptr %d)`); d.push(` ret void`, `}`, ``); host.resolveThunkDefs.push(...d); + host.journal?.built(); return sym; } @@ -261,6 +367,7 @@ export function fsRenameThunkFor(host: LlvmEmitterContext, cbT: IrType & { kind: if (sym) return sym; sym = `sc_fsren_${host.resolveThunks.size}`; host.resolveThunks.set(key, sym); + host.journal?.allocated(sym, "fsRenameThunkFor", [cbT]); const param = cbT.params[0]!; const d: string[] = [ `define internal void @${sym}(ptr %cb, ptr %err) ${FN_ATTRS} { ; fs.rename callback ${typeKey(cbT)}`, @@ -316,6 +423,7 @@ export function fsRenameThunkFor(host: LlvmEmitterContext, cbT: IrType & { kind: ``, ); host.resolveThunkDefs.push(...d); + host.journal?.built(); return sym; } @@ -348,6 +456,7 @@ export function cryptoIntThunkFor( if (sym) return sym; sym = `sc_cryptoint_${host.resolveThunks.size}`; host.resolveThunks.set(key, sym); + host.journal?.allocated(sym, "cryptoIntThunkFor", [cbT]); const d: string[] = [ `define internal void @${sym}(ptr %cb, double %value) ${FN_ATTRS} { ; randomInt callback ${typeKey(cbT)}`, `entry:`, @@ -390,6 +499,7 @@ export function cryptoIntThunkFor( ``, ); host.resolveThunkDefs.push(...d); + host.journal?.built(); return sym; } @@ -408,6 +518,7 @@ export function zlibBytesThunkFor( if (sym) return sym; sym = `sc_${family}bytes_${host.resolveThunks.size}`; host.resolveThunks.set(key, sym); + host.journal?.allocated(sym, "zlibBytesThunkFor", [cbT, arrayBuffer, family, valueMode]); const d: string[] = [ `define internal void @${sym}(ptr %cb, ptr %err, ptr %value) ${FN_ATTRS} { ; zlib bytes callback ${typeKey(cbT)}`, `entry:`, @@ -519,12 +630,13 @@ export function zlibBytesThunkFor( ``, ); host.resolveThunkDefs.push(...d); + host.journal?.built(); return sym; } export function streamCbThunkFor( host: LlvmEmitterContext, - kind: "r" | "w" | "f" | "d" | "t" | "l" | "e", + kind: "r" | "w" | "f" | "d" | "t" | "l" | "e" | "c" | "v", cbT: IrType, ): string { if (cbT.kind !== "func") @@ -534,14 +646,17 @@ export function streamCbThunkFor( if (sym) return sym; sym = `sc_scb_${host.resolveThunks.size}`; host.resolveThunks.set(key, sym); + host.journal?.allocated(sym, "streamCbThunkFor", [kind, cbT]); const runtimeParams = kind === "r" ? ["ptr %s", "double %size"] : kind === "w" || kind === "t" ? ["ptr %s", "ptr %chunk"] - : kind === "d" || kind === "e" - ? ["ptr %s", "ptr %err"] - : ["ptr %s"]; + : kind === "v" + ? ["ptr %s", "ptr %chunks"] + : kind === "d" || kind === "e" + ? ["ptr %s", "ptr %err"] + : ["ptr %s"]; const declared = cbT.params; const hasThis = declared[0] !== undefined && declared[0].kind === "object"; if (declared.length === 0) { @@ -550,7 +665,9 @@ export function streamCbThunkFor( ); } const off = hasThis ? 1 : 0; - const full = (kind === "r" ? 1 : kind === "w" || kind === "t" ? 3 : kind === "d" ? 2 : 1) + off; + const full = + (kind === "r" ? 1 : kind === "w" || kind === "t" ? 3 : kind === "d" || kind === "v" ? 2 : 1) + + off; if (declared.length > full) { throw new InternalCompilerError( `llvm emitter bug: stream '${kind}' callback declares ${declared.length} params (frontend must fence)`, @@ -598,6 +715,31 @@ export function streamCbThunkFor( } continue; } + if (kind === "v" && pos === 0) { + // writev's chunks: the batch array (borrowed from the runtime), as + // a dyn value or converted to the declared type + if (p.kind === "dyn") { + host.declare(`declare ptr @scr_dyn_retain_v(ptr)`); + d.push(` %vc${i} = call ptr @scr_dyn_retain_v(ptr %chunks)`); + passed.push(`ptr %vc${i}`); + } else { + const helper = host.dyn.dynCheckHelper(p, false); + const ty = host.llType(p); + host.declare(`declare zeroext i1 @scr_exc_pending()`); + if (hasThis) host.declare(`declare void @scr_stream_release_v(ptr)`); + d.push( + ` %vt${i} = call ${ty === "i1" ? "zeroext i1" : ty} @${helper}(ptr %chunks, ptr null)`, + ` %vtbad${i} = call zeroext i1 @scr_exc_pending()`, + ` br i1 %vtbad${i}, label %vtfail${i}, label %vtok${i}`, + `vtfail${i}:`, + ...(hasThis ? [` call void @scr_stream_release_v(ptr %sr)`] : []), + ` ret void`, + `vtok${i}:`, + ); + passed.push(`${ty} %vt${i}`); + } + continue; + } const isChunkPos = (kind === "w" || kind === "t") && pos === 0; const isEncPos = (kind === "w" || kind === "t") && pos === 1; const isErrPos = (kind === "d" || kind === "e") && pos === 0; @@ -606,23 +748,19 @@ export function streamCbThunkFor( ? false : kind === "w" || kind === "t" ? pos === 2 - : kind === "f" || kind === "l" + : kind === "f" || kind === "l" || kind === "c" ? pos === 0 : pos === 1; if (p.kind === "dyn") { if (isChunkPos) { - host.declare(`declare ptr @scr_dyn_new_buffer(ptr)`); - d.push(` %dc${i} = call ptr @scr_dyn_new_buffer(ptr %chunk)`); + // the chunk's value: a Buffer, or an object-mode side's value + host.declare(`declare ptr @scr_stream_chunk_value(ptr, ptr)`); + d.push(` %dc${i} = call ptr @scr_stream_chunk_value(ptr %s, ptr %chunk)`); passed.push(`ptr %dc${i}`); } else if (isEncPos) { - host.declare(`declare ptr @scr_str_new(ptr, ${host.sizeType})`); - host.declare(`declare ptr @scr_dyn_new_str(ptr)`); - host.declare(`declare void @scr_str_release(ptr)`); - d.push( - ` %es${i} = call ptr @scr_str_new(ptr ${host.cstr("buffer")}, ${host.sizeType} 6)`, - ` %ed${i} = call ptr @scr_dyn_new_str(ptr %es${i})`, - ` call void @scr_str_release(ptr %es${i})`, - ); + // 'buffer', or the encoding argument an object-mode write passed + host.declare(`declare ptr @scr_stream_chunk_encoding_value(ptr)`); + d.push(` %ed${i} = call ptr @scr_stream_chunk_encoding_value(ptr %s)`); passed.push(`ptr %ed${i}`); } else if (isErrPos) { // finished/pipeline succeed with UNDEFINED (Node calls the eos @@ -656,7 +794,7 @@ export function streamCbThunkFor( d.push(` br label %ego${i}`, `ego${i}:`, ` %edv${i} = load ptr, ptr %edslot${i}`); passed.push(`ptr %edv${i}`); } else if (isDonePos) { - const glue = `scr_stream_done_dyn_${kind}`; + const glue = `scr_stream_done_dyn_${kind === "v" ? "w" : kind}`; host.declare(`declare ptr @${glue}(ptr, ptr, ${host.sizeType})`); host.declare(`declare ptr @scr_dyn_new_func(ptr, ptr, i32, ptr, ptr)`); const clo = doneClosure(`@${glue}`, `dd${i}`); @@ -673,15 +811,71 @@ export function streamCbThunkFor( } continue; } - if (isChunkPos) { - host.declare(`declare ptr @scr_bytes_retain_v(ptr)`); - d.push(` %rc${i} = call ptr @scr_bytes_retain_v(ptr %chunk)`); + if (isChunkPos && p.kind === "bytes") { + // A Buffer, which an object-mode side's value must be (else a + // TypeError, thrown out of the write). + host.declare(`declare ptr @scr_stream_chunk_bytes(ptr, ptr)`); + d.push( + ` %rc${i} = call ptr @scr_stream_chunk_bytes(ptr %s, ptr %chunk)`, + ` %rcbad${i} = icmp eq ptr %rc${i}, null`, + ` br i1 %rcbad${i}, label %rcfail${i}, label %rcok${i}`, + `rcfail${i}:`, + ...(hasThis ? [` call void @scr_stream_release_v(ptr %sr)`] : []), + ` ret void`, + `rcok${i}:`, + ); + if (hasThis) host.declare(`declare void @scr_stream_release_v(ptr)`); passed.push(`ptr %rc${i}`); - } else if (isEncPos) { - // Node's encoding for decoded (Buffer) chunks is 'buffer'. - host.declare(`declare ptr @scr_str_new(ptr, ${host.sizeType})`); - d.push(` %en${i} = call ptr @scr_str_new(ptr ${host.cstr("buffer")}, ${host.sizeType} 6)`); + } else if (isChunkPos) { + // Any other declared type converts from the chunk's value (an + // object-mode side's value, or the Buffer), or throws out of the + // write. + const helper = host.dyn.dynCheckHelper(p, false); + const ty = host.llType(p); + host.declare(`declare ptr @scr_stream_chunk_value(ptr, ptr)`); + host.declare(`declare void @scr_dyn_release(ptr)`); + host.declare(`declare zeroext i1 @scr_exc_pending()`); + if (hasThis) host.declare(`declare void @scr_stream_release_v(ptr)`); + d.push( + ` %cv${i} = call ptr @scr_stream_chunk_value(ptr %s, ptr %chunk)`, + ` %ct${i} = call ${ty === "i1" ? "zeroext i1" : ty} @${helper}(ptr %cv${i}, ptr null)`, + ` call void @scr_dyn_release(ptr %cv${i})`, + ` %ctbad${i} = call zeroext i1 @scr_exc_pending()`, + ` br i1 %ctbad${i}, label %ctfail${i}, label %ctok${i}`, + `ctfail${i}:`, + ...(hasThis ? [` call void @scr_stream_release_v(ptr %sr)`] : []), + ` ret void`, + `ctok${i}:`, + ); + passed.push(`${ty} %ct${i}`); + } else if (isEncPos && p.kind === "string") { + // Node's encoding for decoded (Buffer) chunks is 'buffer'; an + // object-mode side passes the write's encoding argument ("" for + // undefined and null). + host.declare(`declare ptr @scr_stream_chunk_encoding(ptr)`); + d.push(` %en${i} = call ptr @scr_stream_chunk_encoding(ptr %s)`); passed.push(`ptr %en${i}`); + } else if (isEncPos) { + // Another declared type (string | null | undefined) converts from + // the encoding argument's value. + const helper = host.dyn.dynCheckHelper(p, false); + const ty = host.llType(p); + host.declare(`declare ptr @scr_stream_chunk_encoding_value(ptr)`); + host.declare(`declare void @scr_dyn_release(ptr)`); + host.declare(`declare zeroext i1 @scr_exc_pending()`); + if (hasThis) host.declare(`declare void @scr_stream_release_v(ptr)`); + d.push( + ` %ev${i} = call ptr @scr_stream_chunk_encoding_value(ptr %s)`, + ` %et${i} = call ${ty === "i1" ? "zeroext i1" : ty} @${helper}(ptr %ev${i}, ptr null)`, + ` call void @scr_dyn_release(ptr %ev${i})`, + ` %etbad${i} = call zeroext i1 @scr_exc_pending()`, + ` br i1 %etbad${i}, label %etfail${i}, label %etok${i}`, + `etfail${i}:`, + ...(hasThis ? [` call void @scr_stream_release_v(ptr %sr)`] : []), + ` ret void`, + `etok${i}:`, + ); + passed.push(`${ty} %et${i}`); } else if (isErrPos) { // destroy's error argument: `Error | null` — wrap type-directedly. // The finished/pipeline callback ("e") may declare `Error | null | @@ -721,7 +915,8 @@ export function streamCbThunkFor( ); passed.push(`ptr %euv${i}`); } else if (isDonePos) { - const doneKind = kind as "w" | "f" | "d" | "t" | "l"; // "e" has no done position + // "e" has no done position; writev completes as a write + const doneKind = (kind === "v" ? "w" : kind) as "w" | "f" | "d" | "t" | "l" | "c"; if (p.kind !== "func") throw new InternalCompilerError("llvm emitter bug: stream done callback not a func"); const doneFn = host.streamDoneFnFor(doneKind, p); @@ -750,5 +945,35 @@ export function streamCbThunkFor( } d.push(` ret void`, `}`, ``); host.resolveThunkDefs.push(...d); + host.journal?.built(); return sym; } + +registerReplay("streamDataAdapter", (host, args) => + streamDataAdapter(host, args[0] as IrType & { kind: "func" }), +); +registerReplay("streamDoneFnFor", (host, args) => + streamDoneFnFor( + host, + args[0] as "w" | "f" | "d" | "t" | "l", + args[1] as IrType & { kind: "func" }, + ), +); +registerReplay("fsRenameThunkFor", (host, args) => + fsRenameThunkFor(host, args[0] as IrType & { kind: "func" }), +); +registerReplay("cryptoIntThunkFor", (host, args) => + cryptoIntThunkFor(host, args[0] as IrType & { kind: "func" }), +); +registerReplay("zlibBytesThunkFor", (host, args) => + zlibBytesThunkFor( + host, + args[0] as IrType & { kind: "func" }, + args[1] as boolean, + args[2] as string, + args[3] as BytesThunkValue, + ), +); +registerReplay("streamCbThunkFor", (host, args) => + streamCbThunkFor(host, args[0] as "r" | "w" | "f" | "d" | "t" | "l" | "e", args[1] as IrType), +); diff --git a/packages/compiler/src/backend/llvm/integer-or-nan-indexes.test.ts b/packages/compiler/src/backend/llvm/integer-or-nan-indexes.test.ts new file mode 100644 index 000000000..93a0a73ed --- /dev/null +++ b/packages/compiler/src/backend/llvm/integer-or-nan-indexes.test.ts @@ -0,0 +1,130 @@ +import { expect, test } from "vitest"; +import { F64, arrayOf, bytesOf, type IrExpr, type IrModule, type IrStmt } from "../../ir/ir.js"; +import { emitLlvmModule } from "./emitter.js"; + +const loc = { file: "integer-or-nan-indexes.ts", start: 0, end: 0 }; +const nums = arrayOf(F64); +const u8 = bytesOf("u8"); +const ref = (localId: string, type: IrExpr["type"]): IrExpr => ({ + kind: "varRef", + localId, + type, + loc, +}); +const num = (value: number): IrExpr => ({ kind: "numLit", value, type: F64, loc }); +/** `t[i]!`: the element, or NaN for an index that misses. */ +const byteRead = (index: IrExpr): IrExpr => ({ + kind: "bytesIntrinsic", + method: "get", + receiver: ref("t", u8), + args: [index], + type: F64, + loc, + invalidNaN: true, +}); + +function module(body: IrStmt[]): IrModule { + return { + irVersion: 17, + sourceFile: loc.file, + entry: "__main", + unions: [], + functions: [ + { name: "__main", params: [], returnType: F64, locals: [], body: [], loc }, + { + name: "read", + params: [ + { name: "a", localId: "a", type: nums }, + { name: "t", localId: "t", type: u8 }, + { name: "i", localId: "i", type: F64 }, + ], + returnType: F64, + locals: [ + { id: "a", name: "a", type: nums, mutable: false }, + { id: "t", name: "t", type: u8, mutable: false }, + { id: "i", name: "i", type: F64, mutable: false }, + { id: "c", name: "c", type: F64, mutable: true }, + ], + body, + loc, + }, + ], + }; +} + +function body(llvm: string): string { + return /^define internal [^\n]*@sc_bf_read(?:\.i32)?\([^]*?^}/m.exec(llvm)![0]; +} + +const count = (text: string, pattern: RegExp): number => text.match(pattern)?.length ?? 0; + +test("an index bound to a byte read that may miss checks only that it is ordered", () => { + const llvm = emitLlvmModule( + module([ + { kind: "varDecl", localId: "c", init: byteRead(ref("i", F64)), loc }, + { + kind: "return", + value: { + kind: "bin", + op: "+", + left: { kind: "arrayGet", arr: ref("a", nums), index: ref("c", F64), type: F64, loc }, + right: { + kind: "bytesIntrinsic", + method: "get", + receiver: ref("t", u8), + args: [{ kind: "bin", op: "+", left: ref("c", F64), right: num(1), type: F64, loc }], + type: F64, + loc, + invalidNaN: true, + }, + type: F64, + loc, + }, + loc, + }, + ]), + ); + const fn = body(llvm); + // Only the parameter index `i` round-trips through a double. + expect(count(fn, /fcmp oeq double/g)).toBe(1); + expect(count(fn, /fcmp ord double/g)).toBe(2); +}); + +test("a local also written an ordinary number keeps the exact index check", () => { + const llvm = emitLlvmModule( + module([ + { kind: "varDecl", localId: "c", init: byteRead(ref("i", F64)), loc }, + { kind: "assign", localId: "c", value: ref("i", F64), loc }, + { + kind: "return", + value: { kind: "arrayGet", arr: ref("a", nums), index: ref("c", F64), type: F64, loc }, + loc, + }, + ]), + ); + const fn = body(llvm); + expect(count(fn, /fcmp oeq double/g)).toBe(2); + expect(fn).not.toContain("fcmp ord double"); +}); + +test("a local whose writes grow from its own value keeps the exact index check", () => { + const llvm = emitLlvmModule( + module([ + { kind: "varDecl", localId: "c", init: byteRead(ref("i", F64)), loc }, + { + kind: "assign", + localId: "c", + value: { kind: "bin", op: "+", left: ref("c", F64), right: num(1), type: F64, loc }, + loc, + }, + { + kind: "return", + value: { kind: "arrayGet", arr: ref("a", nums), index: ref("c", F64), type: F64, loc }, + loc, + }, + ]), + ); + const fn = body(llvm); + expect(count(fn, /fcmp oeq double/g)).toBe(2); + expect(fn).not.toContain("fcmp ord double"); +}); diff --git a/packages/compiler/src/backend/llvm/lib-connect.ts b/packages/compiler/src/backend/llvm/lib-connect.ts index ce9c40e21..4d151fc7e 100644 --- a/packages/compiler/src/backend/llvm/lib-connect.ts +++ b/packages/compiler/src/backend/llvm/lib-connect.ts @@ -3,6 +3,7 @@ import { typeKey } from "../../ir/ir.js"; import type { LibCallExpr, LlValue, LlvmEmitterContext } from "./expr-context.js"; import { abiValue, callbackType, finishRuntimeCall, ptr } from "./lib-abi.js"; import { FN_ATTRS } from "./shapes.js"; +import { registerReplay } from "./emit-journal.js"; /** CONNECT transfers owned request/socket/response values to the listener. */ function connectAdapter(host: LlvmEmitterContext, cb: LlValue, h2: boolean): string { @@ -18,6 +19,7 @@ function connectAdapter(host: LlvmEmitterContext, cb: LlValue, h2: boolean): str if (previous !== undefined) return previous; const symbol = `sc_connect_${host.resolveThunks.size}`; host.resolveThunks.set(key, symbol); + host.journal?.allocated(symbol, "connectAdapter", [cb, h2]); const retain = h2 ? "scr_http_res_retain_v" : "scr_net_sock_retain_v"; const release = h2 ? "scr_http_res_release_v" : "scr_net_sock_release_v"; host.declare(`declare ptr @${retain}(ptr)`); @@ -37,6 +39,7 @@ function connectAdapter(host: LlvmEmitterContext, cb: LlValue, h2: boolean): str "}", "", ); + host.journal?.built(); return symbol; } @@ -70,3 +73,7 @@ export function emitConnectListener(host: LlvmEmitterContext, e: LibCallExpr): L a[2]!, ]); } + +registerReplay("connectAdapter", (host, args) => + connectAdapter(host, args[0] as LlValue, args[1] as boolean), +); diff --git a/packages/compiler/src/backend/llvm/lib-datagram.ts b/packages/compiler/src/backend/llvm/lib-datagram.ts index 184fdb99e..07de4e54e 100644 --- a/packages/compiler/src/backend/llvm/lib-datagram.ts +++ b/packages/compiler/src/backend/llvm/lib-datagram.ts @@ -11,6 +11,7 @@ import { ptr, } from "./lib-abi.js"; import { FN_ATTRS } from "./shapes.js"; +import { registerReplay } from "./emit-journal.js"; function messageAdapter(host: LlvmEmitterContext, type: IrType): string { if (type.kind !== "record") @@ -20,6 +21,7 @@ function messageAdapter(host: LlvmEmitterContext, type: IrType): string { if (previous !== undefined) return previous; const symbol = `sc_dgram_message_${host.resolveThunks.size}`; host.resolveThunks.set(key, symbol); + host.journal?.allocated(symbol, "messageAdapter", [type]); const shape = host.recordsById.get(type.shapeId); if (shape === undefined) throw new InternalCompilerError("missing datagram remote info shape"); const lines: string[] = []; @@ -48,6 +50,7 @@ function messageAdapter(host: LlvmEmitterContext, type: IrType): string { "}", "", ); + host.journal?.built(); return symbol; } @@ -67,6 +70,7 @@ function lookupAdapter(host: LlvmEmitterContext, cb: LlValue): string { if (previous !== undefined) return previous; const symbol = `sc_dns_lookup_${host.resolveThunks.size}`; host.resolveThunks.set(key, symbol); + host.journal?.allocated(symbol, "lookupAdapter", [cb]); host.declare("declare ptr @scr_error_new(i32, ptr)"); host.declare("declare ptr @scr_error_retain_v(ptr)"); host.declare("declare void @scr_error_release_v(ptr)"); @@ -93,6 +97,7 @@ function lookupAdapter(host: LlvmEmitterContext, cb: LlValue): string { "}", "", ); + host.journal?.built(); return symbol; } @@ -105,6 +110,10 @@ export function emitDatagramLibCall(host: LlvmEmitterContext, e: LibCallExpr): L "dgram.sendStr": "scr_dgram_send_str", "dgram.sendBytes": "scr_dgram_send_bytes", "dgram.sendChk": "scr_dgram_send_chk", + "dgram.unixSocket": "scr_dgram_unix_socket", + "dgram.unixConnect": "scr_dgram_unix_connect", + "dgram.unixSend": "scr_dgram_unix_send", + "dgram.unixClose": "scr_dgram_unix_close", "dgram.ref": "scr_dgram_ref", "dgram.unref": "scr_dgram_unref", "dgram.setBroadcast": "scr_dgram_set_broadcast", @@ -250,3 +259,6 @@ export function emitDatagramLibCall(host: LlvmEmitterContext, e: LibCallExpr): L throw new InternalCompilerError(`unhandled datagram call ${e.fn}`); } } + +registerReplay("messageAdapter", (host, args) => messageAdapter(host, args[0] as IrType)); +registerReplay("lookupAdapter", (host, args) => lookupAdapter(host, args[0] as LlValue)); diff --git a/packages/compiler/src/backend/llvm/lib-dispatch.ts b/packages/compiler/src/backend/llvm/lib-dispatch.ts index 24f2bf019..cebe661d4 100644 --- a/packages/compiler/src/backend/llvm/lib-dispatch.ts +++ b/packages/compiler/src/backend/llvm/lib-dispatch.ts @@ -553,7 +553,11 @@ export function emitGenericLibCall(host: LlvmEmitterContext, e: LibCallExpr): Ll // which also takes those streams. e.fn === "stream.unboxDyn" && host.usesDynBuiltinStream ? "scr_dyn_builtin_stream_unbox" - : LIB_FN_SYMS[e.fn]); + : // for await over a checked-dynamic value iterates a native + // stream behind it (scr_dyn_for_await_stream.c) + e.fn === "dyn.asyncIteratorOpen" && host.dynForAwaitStreams + ? "scr_stream_dyn_async_iterator_open" + : LIB_FN_SYMS[e.fn]); if (sym === undefined) throw new LlvmUnsupportedError(`libCall:${e.fn}`, e.loc); const args = READ_ONLY_STRING_LIB_FNS.has(e.fn) ? emitBorrowedInputs(host, e.args) @@ -734,7 +738,7 @@ export function emitLibCall(host: LlvmEmitterContext, e: LibCallExpr): LlValue { if (e.fn === "process.nextTick") return host.emitAsyncContextLibCall(e); if ( e.fn === "sp.pipeline" || - e.fn === "sp.pipelineStages" || + e.fn.startsWith("sp.pipelineStages") || e.fn.startsWith("sp.pipelineOpts") || e.fn.startsWith("sp.finishedOpts") ) @@ -858,6 +862,7 @@ export function emitLibCall(host: LlvmEmitterContext, e: LibCallExpr): LlValue { return host.emitGenericLibCall(e); case "weakMap": case "weakSet": + case "finalizationRegistry": case "ffi": case "sharedArrayBuffer": case "arrayBuffer": diff --git a/packages/compiler/src/backend/llvm/lib-filesystem.ts b/packages/compiler/src/backend/llvm/lib-filesystem.ts index 6d5fe652d..7d9be632d 100644 --- a/packages/compiler/src/backend/llvm/lib-filesystem.ts +++ b/packages/compiler/src/backend/llvm/lib-filesystem.ts @@ -163,7 +163,7 @@ function emitObjEntryPairs(host: LlvmEmitterContext, e: LibCallExpr): LlValue { B.line(`${row} = call ptr @${mangleRecordNew(rowT.shapeId)}()`); host.storeField(host.recordFieldPtr(row, rowT.shapeId, "0").ptr, STRING, key, false); host.storeField(host.recordFieldPtr(row, rowT.shapeId, "1").ptr, DYN, item, false); - host.arrPush(arr, "ref", row); // push takes ownership of the row + host.arrPush(arr, "ref", row, null); // push takes ownership of the row const next = B.tmp(); B.line(`${next} = add ${size} ${i}, 1`); B.line(`store ${size} ${next}, ptr ${iSlot}`); @@ -536,7 +536,7 @@ export function emitFilesystemLibCall(host: LlvmEmitterContext, e: LibCallExpr): const parent = B.tmp(); B.line(`${parent} = call ptr @scr_fs_glob_parent(ptr ${snap}, ${host.sizeType} ${i}) ; +1`); B.line(`store ptr ${parent}, ptr ${host.recordFieldPtr(row, recT.shapeId, "parentPath").ptr}`); - host.arrPush(arr, "ref", row); // push takes ownership of the row + host.arrPush(arr, "ref", row, null); // push takes ownership of the row const i2 = B.tmp(); B.line(`${i2} = add ${host.sizeType} ${i}, 1`); B.line(`store ${host.sizeType} ${i2}, ptr ${iSlot}`); @@ -620,7 +620,7 @@ export function emitFilesystemLibCall(host: LlvmEmitterContext, e: LibCallExpr): B.line( `store ptr ${host.retainHeap(path.name, STRING)}, ptr ${host.recordFieldPtr(row, recT.shapeId, "parentPath").ptr}`, ); - host.arrPush(arr, "ref", row); // push takes ownership of the row + host.arrPush(arr, "ref", row, null); // push takes ownership of the row const i2 = B.tmp(); B.line(`${i2} = add ${host.sizeType} ${i}, 1`); B.line(`store ${host.sizeType} ${i2}, ptr ${iSlot}`); @@ -955,7 +955,7 @@ export function emitPathUrlLibCall(host: LlvmEmitterContext, e: LibCallExpr): Ll B.startBlock(lj); const rows = B.tmp(); B.line(`${rows} = load ptr, ptr ${rowsSlot}`); - host.arrPush(rows, "ref", row); // push takes ownership of the row + host.arrPush(rows, "ref", row, null); // push takes ownership of the row B.line(`call void @scr_arr_release(ptr ${rows})`); B.line(`call void @scr_str_release(ptr ${nm})`); const i2 = B.tmp(); diff --git a/packages/compiler/src/backend/llvm/lib-http2.ts b/packages/compiler/src/backend/llvm/lib-http2.ts index 791987f86..321f1d005 100644 --- a/packages/compiler/src/backend/llvm/lib-http2.ts +++ b/packages/compiler/src/backend/llvm/lib-http2.ts @@ -13,6 +13,7 @@ import { requestHandler, } from "./lib-abi.js"; import { FN_ATTRS } from "./shapes.js"; +import { registerReplay } from "./emit-journal.js"; /** The runtime owns the answer closure; its arguments arrive owned from the caller. */ function sniAnswer(host: LlvmEmitterContext, type: IrType): string { @@ -22,6 +23,7 @@ function sniAnswer(host: LlvmEmitterContext, type: IrType): string { if (previous !== undefined) return previous; const symbol = `sc_sni_answer_${host.resolveThunks.size}`; host.resolveThunks.set(key, symbol); + host.journal?.allocated(symbol, "sniAnswer", [type]); const params = ["ptr %self"], body: string[] = []; let hasError = "false", @@ -82,6 +84,7 @@ function sniAnswer(host: LlvmEmitterContext, type: IrType): string { "}", "", ); + host.journal?.built(); return symbol; } @@ -318,3 +321,5 @@ export function emitHttp2LibCall(host: LlvmEmitterContext, e: LibCallExpr): LlVa const handler = thunk === null ? [a[1]!] : callbackAdapter(host, cb, thunk, params); return finishRuntimeCall(host, e, runtime, [a[0]!, ...handler, ...a.slice(2)]); } + +registerReplay("sniAnswer", (host, args) => sniAnswer(host, args[0] as IrType)); diff --git a/packages/compiler/src/backend/llvm/lib-lookup.ts b/packages/compiler/src/backend/llvm/lib-lookup.ts index c6bc4d97b..56e94461f 100644 --- a/packages/compiler/src/backend/llvm/lib-lookup.ts +++ b/packages/compiler/src/backend/llvm/lib-lookup.ts @@ -1,9 +1,10 @@ import { InternalCompilerError } from "../../errors.js"; -import { typeKey } from "../../ir/ir.js"; +import { type IrType, typeKey } from "../../ir/ir.js"; import { mangleRecordRelease, mangleRecordStruct } from "../mangle.js"; import type { LibCallExpr, LlValue, LlvmEmitterContext } from "./expr-context.js"; import { abiValue, callbackType, finishRuntimeCall, ptr } from "./lib-abi.js"; import { FN_ATTRS } from "./shapes.js"; +import { registerReplay } from "./emit-journal.js"; export function emitLookupConnect(host: LlvmEmitterContext, e: LibCallExpr): LlValue { const args = e.args.map((arg) => host.emitExpr(arg)), @@ -12,6 +13,18 @@ export function emitLookupConnect(host: LlvmEmitterContext, e: LibCallExpr): LlV answer = lookup.params[2]; if (answer?.kind !== "func" || answer.params.length !== 2) throw new InternalCompilerError("lookup answer must have two parameters"); + const symbol = lookupAnswer(host, answer); + host.usesTimers = true; + host.toHeap(cb); + return finishRuntimeCall(host, e, "scr_net_connect_lookup", [ + ...args.map((arg) => abiValue(host, arg)), + ptr("@" + symbol), + ]); +} + +/** The thunk that hands a lookup's answer (error, addresses) to the + * runtime, one per answer signature. */ +function lookupAnswer(host: LlvmEmitterContext, answer: IrType & { kind: "func" }): string { const error = answer.params[0]!, addresses = answer.params[1]!; if (error.kind !== "union" || addresses.kind !== "array" || addresses.elem.kind !== "record") @@ -26,6 +39,7 @@ export function emitLookupConnect(host: LlvmEmitterContext, e: LibCallExpr): LlV if (symbol === undefined) { symbol = `sc_lookup_answer_${host.resolveThunks.size}`; host.resolveThunks.set(key, symbol); + host.journal?.allocated(symbol, "lookupAnswer", [answer]); for (const declaration of [ "declare ptr @scr_str_retain_v(ptr)", "declare void @scr_str_release(ptr)", @@ -84,11 +98,11 @@ export function emitLookupConnect(host: LlvmEmitterContext, e: LibCallExpr): LlV "}", "", ); + host.journal?.built(); } - host.usesTimers = true; - host.toHeap(cb); - return finishRuntimeCall(host, e, "scr_net_connect_lookup", [ - ...args.map((arg) => abiValue(host, arg)), - ptr("@" + symbol), - ]); + return symbol; } + +registerReplay("lookupAnswer", (host, args) => + lookupAnswer(host, args[0] as IrType & { kind: "func" }), +); diff --git a/packages/compiler/src/backend/llvm/lib-process.ts b/packages/compiler/src/backend/llvm/lib-process.ts index 699e52575..3e8a9bff5 100644 --- a/packages/compiler/src/backend/llvm/lib-process.ts +++ b/packages/compiler/src/backend/llvm/lib-process.ts @@ -924,32 +924,41 @@ export function emitErrorsEventsLibCall(host: LlvmEmitterContext, e: LibCallExpr } if (e.fn === "emitter.emitData") { // A user emit('data', chunk) on a stream-rooted receiver: fill the - // matching payload slot of the two-slot 'data' ABI, NULL the other. + // matching payload slot of the three-slot 'data' ABI (bytes, string, + // object-mode value), NULL the others; a checked-dynamic chunk fills + // them by tag (scr_stream_emit_value). const args = e.args.map((a) => host.emitExpr(a)); const chunkT = e.args[2]!.type; - const both = - chunkT.kind === "string" - ? [`ptr null`, `ptr ${args[2]!.name}`] - : [`ptr ${args[2]!.name}`, `ptr null`]; - host.declare(`declare zeroext i1 @scr_emitter_emit(ptr, ptr, ...)`); const t = B.tmp(); - B.line( - `${t} = call zeroext i1 (ptr, ptr, ...) @scr_emitter_emit(ptr ${args[0]!.name}, ptr ${args[1]!.name}, ${both.join(", ")})`, - ); + if (chunkT.kind === "dyn") { + host.declare(`declare zeroext i1 @scr_stream_emit_value(ptr, ptr, ptr)`); + B.line( + `${t} = call zeroext i1 @scr_stream_emit_value(ptr ${args[0]!.name}, ptr ${args[1]!.name}, ptr ${args[2]!.name})`, + ); + } else { + const slots = + chunkT.kind === "string" + ? [`ptr null`, `ptr ${args[2]!.name}`, `ptr null`] + : [`ptr ${args[2]!.name}`, `ptr null`, `ptr null`]; + host.declare(`declare zeroext i1 @scr_emitter_emit(ptr, ptr, ...)`); + B.line( + `${t} = call zeroext i1 (ptr, ptr, ...) @scr_emitter_emit(ptr ${args[0]!.name}, ptr ${args[1]!.name}, ${slots.join(", ")})`, + ); + } host.emitPendingCheck(); return e.type.kind === "void" ? { name: "", type: e.type } : { name: t, type: e.type }; } if (e.fn === "emitter.onData" || e.fn === "emitter.onDataDyn") { // The stream-'data' registration: same runtime entries as - // emitter.on/onDyn, but the DATA adapter (the two-slot payload ABI - // — scr_stream_emit_data) behind the arity-2 fixed shim. + // emitter.on/onDyn, but the DATA adapter (the three-slot payload ABI + // — scr_stream_emit_data) behind the arity-3 fixed shim. const isDyn = e.fn === "emitter.onDataDyn"; const cbT = e.args[isDyn ? 3 : 2]!.type; if (cbT.kind !== "func") throw new InternalCompilerError(`llvm emitter bug: ${e.fn} listener not a func`); const args = e.args.map((a) => host.emitExpr(a)); const adapterFn = host.streamDataAdapter(cbT); - host.declare(`declare void @scr_ee_inv_fixed2(ptr, ptr)`); + host.declare(`declare void @scr_ee_inv_fixed3(ptr, ptr)`); const t = B.tmp(); if (isDyn) { host.toHeap(args[3]!); @@ -959,7 +968,7 @@ export function emitErrorsEventsLibCall(host: LlvmEmitterContext, e: LibCallExpr ); B.line( `${t} = call ptr @scr_emitter_on_dyn(ptr ${args[0]!.name}, ptr ${args[1]!.name}, ` + - `ptr ${args[2]!.name}, ptr ${wrapped}, ptr @scr_ee_inv_fixed2, i1 ${args[4]!.name}, i1 ${args[5]!.name})`, + `ptr ${args[2]!.name}, ptr ${wrapped}, ptr @scr_ee_inv_fixed3, i1 ${args[4]!.name}, i1 ${args[5]!.name})`, ); } else { host.declare(`declare ptr @scr_closure_retain_v(ptr)`); @@ -972,7 +981,7 @@ export function emitErrorsEventsLibCall(host: LlvmEmitterContext, e: LibCallExpr ); B.line( `${t} = call ptr @scr_emitter_on_via(ptr ${args[0]!.name}, ptr ${args[1]!.name}, ` + - `ptr ${args[2]!.name}, ptr ${wrapped}, ptr @scr_ee_inv_fixed2, i1 ${args[3]!.name}, i1 ${args[4]!.name})`, + `ptr ${args[2]!.name}, ptr ${wrapped}, ptr @scr_ee_inv_fixed3, i1 ${args[3]!.name}, i1 ${args[4]!.name})`, ); } const out = host.own({ name: t, type: e.type }); diff --git a/packages/compiler/src/backend/llvm/lib-shared.ts b/packages/compiler/src/backend/llvm/lib-shared.ts index 80e0b0044..58fac56bc 100644 --- a/packages/compiler/src/backend/llvm/lib-shared.ts +++ b/packages/compiler/src/backend/llvm/lib-shared.ts @@ -44,10 +44,12 @@ export const LIB_FN_SYMS: Record = { "weakSet.is": "scr_weak_set_is", "weakMap.new": "scr_weak_map_new", "weakSet.new": "scr_weak_set_new", + "finalizationRegistry.new": "scr_finalization_registry_new", + "finalizationRegistry.is": "scr_finalization_registry_is", "dyn.fromEntries": "scr_dyn_from_entries", "bytes.constructor": "scr_bytes_constructor", "bytes.construct": "scr_bytes_construct", - "bytes.instanceOf": "scr_bytes_instanceof", + "bytes.instanceOf": "scr_bytes_instanceof_at", "arrayBuffer.constructor": "scr_array_buffer_constructor", "sharedArrayBuffer.new": "scr_shared_array_buffer_new", "sharedArrayBuffer.is": "scr_shared_array_buffer_is", @@ -448,6 +450,7 @@ export const LIB_FN_SYMS: Record = { "buffer.poolFromArray": "scr_buffer_from_arr", "buffer.poolFromDyn": "scr_buffer_from_dyn_pooled", "buffer.poolFromDynRef": "scr_buffer_from_dyn_ref_pooled", + "buffer.poolFromDynOffset": "scr_buffer_from_dyn_offset_pooled", "buffer.poolSize": "scr_buffer_pool_size", "buffer.setPoolSize": "scr_buffer_set_pool_size", "buffer.byteLenDyn": "scr_buffer_byte_length_dyn", @@ -577,6 +580,12 @@ export const LIB_FN_SYMS: Record = { "crypto.cipherNew": "scr_crypto_cipher_new", "crypto.ecdhNew": "scr_crypto_ecdh_new", "crypto.ecdhConvertKey": "scr_crypto_ecdh_convert_key", + "crypto.dhNew": "scr_crypto_dh_new", + "crypto.checkPrimeSync": "scr_crypto_check_prime_sync", + "crypto.checkPrimeCb": "scr_crypto_check_prime_async", + "crypto.generatePrimeSync": "scr_crypto_generate_prime_sync", + "crypto.generatePrimeCb": "scr_crypto_generate_prime_async", + "crypto.dhGroupNew": "scr_crypto_dh_group_new", "crypto.hmacNewStr": "scr_crypto_hmac_new_str", "crypto.hmacNewBytes": "scr_crypto_hmac_new_bytes", "crypto.hashUpdateStr": "scr_crypto_hash_update_str", @@ -614,11 +623,20 @@ export const LIB_FN_SYMS: Record = { "crypto.generateKeySync": "scr_crypto_generate_key_sync", "crypto.keyObjectInput": "scr_crypto_key_object_input", "crypto.isKeyObject": "scr_crypto_is_key_object", + "webcrypto.generateKey": "scr_webcrypto_generate_key", "webcrypto.importKey": "scr_webcrypto_import_key", + "webcrypto.exportKey": "scr_webcrypto_export_key", + "webcrypto.encrypt": "scr_webcrypto_encrypt", + "webcrypto.decrypt": "scr_webcrypto_decrypt", + "webcrypto.wrapKey": "scr_webcrypto_wrap_key", + "webcrypto.unwrapKey": "scr_webcrypto_unwrap_key", + "webcrypto.deriveBits": "scr_webcrypto_derive_bits", + "webcrypto.deriveKey": "scr_webcrypto_derive_key", "webcrypto.sign": "scr_webcrypto_sign", "webcrypto.verify": "scr_webcrypto_verify", "webcrypto.digest": "scr_webcrypto_digest", "webcrypto.isCryptoKey": "scr_webcrypto_is_crypto_key", + "webcrypto.object": "scr_webcrypto_object", "crypto.randomUUIDv7": "scr_crypto_random_uuid_v7", "crypto.pbkdf2": "scr_crypto_pbkdf2", "crypto.hkdf": "scr_crypto_hkdf", @@ -742,6 +760,7 @@ export const LIB_FN_SYMS: Record = { "cp.spawnSync": "scr_spawn_sync", "cp.spawnSyncOpts": "scr_spawn_sync_opts", "cp.spawnSyncStdioStr": "scr_spawn_sync_stdio_str", + "cp.spawnSyncEnv": "scr_spawn_sync_env", "cp.execSync": "scr_exec_sync", "cp.execCapture": "scr_exec_capture", "spawnRes.stdout": "scr_spawn_res_stdout", @@ -754,6 +773,7 @@ export const LIB_FN_SYMS: Record = { "procStream.write": "scr_proc_stream_write", "stream.stdioWritable": "scr_stream_stdio_writable", "stream.unboxDyn": "scr_stream_unbox_dyn", + "stream.handleStream": "scr_stream_handle", "stream.pipeDyn": "scr_stream_pipe_dyn", "stream.unpipeDyn": "scr_stream_unpipe_dyn", "process.kill": "scr_process_kill_named", @@ -997,12 +1017,15 @@ export const LIB_FN_SYMS: Record = { "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.nativeDateIs": "scr_dyn_date_instance_is", + "dyn.nativeDateHandleIs": "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.argumentsTime": "scr_dyn_date_arguments_time", + "date.classOperation": "scr_date_class_operation_install", "date.checkedValue": "scr_dyn_native_date_value", "dyn.nativeRegexIs": "scr_dyn_native_regex_is", "dyn.toString": "scr_dyn_to_string_argument", @@ -1027,6 +1050,14 @@ export const LIB_FN_SYMS: Record = { "crypto.x509ValidFromStr": "scr_crypto_x509_valid_from_str", "crypto.x509ValidTo": "scr_crypto_x509_valid_to", "crypto.x509ValidToStr": "scr_crypto_x509_valid_to_str", + "crypto.createPrivateKey": "scr_crypto_create_private_key", + "crypto.createPublicKey": "scr_crypto_create_public_key", + "crypto.generateKeyPairSync": "scr_crypto_generate_key_pair_sync", + "crypto.generateKeyPairCb": "scr_crypto_generate_key_pair_async", + "crypto.signOneshot": "scr_crypto_sign_oneshot", + "crypto.verifyOneshot": "scr_crypto_verify_oneshot", + "crypto.createSign": "scr_crypto_create_sign", + "crypto.createVerify": "scr_crypto_create_verify", "fs.writeFileModeSync": "scr_fs_write_file_mode", "fs.chownSync": "scr_fs_chown", "fs.lchownSync": "scr_fs_lchown", @@ -1037,6 +1068,9 @@ export const LIB_FN_SYMS: Record = { "atomics.op": "scr_atomics_op", "atomics.notify": "scr_atomics_notify", "atomics.wait": "scr_atomics_wait", + "atomics.opDyn": "scr_atomics_op_dyn", + "atomics.waitDyn": "scr_atomics_wait_dyn", + "atomics.notifyDyn": "scr_atomics_notify_dyn", "worker.new": "scr_worker_new", "worker.isMainThread": "scr_context_is_main", "worker.threadId": "scr_context_thread_number", @@ -1094,14 +1128,30 @@ export const LIB_FN_SYMS: Record = { // chaining forms answer the receiver +1. The throwing members // (listeners and option callbacks run synchronously inside) ride the // generic pending check; loop liveness rides USES_TIMERS_LIB_FNS. - "readable.push": "scr_stream_push", + "readable.push": "scr_stream_push_view", "readable.pushStr": "scr_stream_push_str", "readable.pushStrEnc": "scr_stream_push_str_enc", "readable.pushEncoding": "scr_stream_set_push_encoding", + "stream.objectMode": "scr_stream_object_mode", + "stream.decodeStrings": "scr_stream_decode_strings", + "stream.duplexFromGen": "scr_stream_duplex_from_gen", + "stream.duplexFromDyn": "scr_stream_duplex_from_dyn", + "stream.duplexifyReadable": "scr_stream_duplexify_readable", + "stream.duplexifyWritable": "scr_stream_duplexify_writable", + "stream.duplexifyPair": "scr_stream_duplexify_pair", + "stream.duplexFromPromise": "scr_stream_duplex_from_promise", + "stream.duplexFromAsyncFn": "scr_stream_duplex_from_async_fn", + "stream.duplexFromGenSignal": "scr_stream_duplex_from_gen_signal", + "stream.duplexFromAsyncFnSignal": "scr_stream_duplex_from_async_fn_signal", + "fetch.readableFromWeb": "scr_stream_readable_from_web", + "writable.writeEncoding": "scr_stream_write_encoding", + "writable.setDefaultEncoding": "scr_stream_set_default_encoding", + "stream.chunkDone": "scr_stream_chunk_done", "readable.pushNull": "scr_stream_push_null", "readable.pushDyn": "scr_stream_push_dyn", "readable.unshift": "scr_stream_unshift", "readable.unshiftStr": "scr_stream_unshift_str", + "readable.unshiftDyn": "scr_stream_unshift_dyn", "readable.pause": "scr_stream_pause", "readable.resume": "scr_stream_resume", "readable.isPaused": "scr_stream_is_paused", @@ -1159,6 +1209,8 @@ export const LIB_FN_SYMS: Record = { "readable.opMap": "scr_stream_op_map", "readable.opFilter": "scr_stream_op_filter", "readable.opFlatMap": "scr_stream_op_flat_map", + "readable.opFlatMapAsyncGen": "scr_stream_op_flat_map_async_gen", + "readable.opFlatMapSyncGen": "scr_stream_op_flat_map_sync_gen", "readable.opDrop": "scr_stream_op_drop", "readable.opTake": "scr_stream_op_take", "readable.opToArray": "scr_stream_op_to_array", @@ -1167,6 +1219,11 @@ export const LIB_FN_SYMS: Record = { "readable.opEvery": "scr_stream_op_every", "readable.opFind": "scr_stream_op_find", "readable.opReduce": "scr_stream_op_reduce", + "readable.opSignalList": "scr_stream_op_signal_list", + "readable.opReduceSignal": "scr_stream_op_reduce_signal", + "readable.opSignalOf": "scr_stream_op_signal_of", + "readable.opOnceOptions": "scr_stream_op_once_options", + "readable.opSignalOpts": "scr_stream_op_signal_opts", "readable.pipe": "scr_stream_pipe", "readable.pipeGeneral": "scr_stream_pipe_general", "writable.cork": "scr_stream_cork", @@ -1478,6 +1535,10 @@ export const LIB_FN_SYMS: Record = { "dyn.arrayPrototype": "scr_dyn_array_prototype", "dyn.arrayConstructor": "scr_dyn_array_constructor", "dyn.objectPrototype": "scr_dyn_object_prototype", + "dyn.errorPrototype": "scr_dyn_error_prototype", + "dyn.inheritsErrorPrototype": "scr_dyn_inherits_error_prototype", + "dyn.errorCaptureStackTrace": "scr_dyn_error_capture_stack_trace", + "dyn.errorCaptureStackTraceFunction": "scr_dyn_error_capture_stack_trace_function", "dyn.functionApply": "scr_dyn_function_apply", "dyn.builtinMethod": "scr_dyn_builtin_method", "dyn.classPrototype": "scr_dyn_class_prototype", @@ -1566,6 +1627,9 @@ export function mockTimerSym( } export const USES_TIMERS_LIB_FNS = new Set([ + "crypto.generateKeyPairCb", + "crypto.checkPrimeCb", + "crypto.generatePrimeCb", "process.emitWarning", // Constructor-function streams defer their events on the stream ticks. "dyn.builtinStreamClass", @@ -1574,6 +1638,13 @@ export const USES_TIMERS_LIB_FNS = new Set([ // ecdh.setPublicKey reports DEP0031 on the next tick. "crypto.ecdhNew", // WebCrypto results settle through the deferred crypto queue. + "webcrypto.generateKey", + "webcrypto.encrypt", + "webcrypto.decrypt", + "webcrypto.wrapKey", + "webcrypto.unwrapKey", + "webcrypto.deriveBits", + "webcrypto.deriveKey", "webcrypto.sign", "webcrypto.verify", "webcrypto.digest", @@ -1644,6 +1715,7 @@ export const USES_TIMERS_LIB_FNS = new Set([ "readable.pushDyn", "readable.unshift", "readable.unshiftStr", + "readable.unshiftDyn", "readable.read", "readable.readDyn", "readable.setEncoding", @@ -1658,6 +1730,8 @@ export const USES_TIMERS_LIB_FNS = new Set([ "readable.opMap", "readable.opFilter", "readable.opFlatMap", + "readable.opFlatMapAsyncGen", + "readable.opFlatMapSyncGen", "readable.opDrop", "readable.opTake", "readable.opToArray", @@ -1666,6 +1740,7 @@ export const USES_TIMERS_LIB_FNS = new Set([ "readable.opEvery", "readable.opFind", "readable.opReduce", + "readable.opReduceSignal", "readable.resume", "readable.pipe", "readable.pipeGeneral", @@ -1675,6 +1750,7 @@ export const USES_TIMERS_LIB_FNS = new Set([ "console.write", "writable.writeU", "writable.writeDyn", + "writable.writeEnc", "writable.end", "writable.uncork", "stream.destroy", @@ -1686,6 +1762,19 @@ export const USES_TIMERS_LIB_FNS = new Set([ "stream.setDestroy", "stream.setTransform", "stream.setFlush", + "stream.setConstruct", + "stream.duplexFromGen", + "stream.duplexFromDyn", + "stream.duplexifyReadable", + "stream.duplexifyWritable", + "stream.duplexifyPair", + "stream.duplexFromPromise", + "stream.duplexFromAsyncFn", + "stream.duplexFromGenSignal", + "stream.duplexFromAsyncFnSignal", + "fetch.readableFromWeb", + "stream.setWritev", + "stream.setWritevDefault", "process.activeResources", "stream.finished", "stream.finishedDyn", @@ -1695,8 +1784,10 @@ export const USES_TIMERS_LIB_FNS = new Set([ "sp.finished", "sp.pipeline", "sp.pipelineStages", + "sp.pipelineStagesOpts", "stream.pipelineStages", "stream.pipelineStagesDyn", + "stream.composeStages", "sp.pipelineOpts", "sp.pipelineOptsSignal", "sp.finishedOpts", diff --git a/packages/compiler/src/backend/llvm/lib-stream.ts b/packages/compiler/src/backend/llvm/lib-stream.ts index d3b4b1f5b..5fd4af1a9 100644 --- a/packages/compiler/src/backend/llvm/lib-stream.ts +++ b/packages/compiler/src/backend/llvm/lib-stream.ts @@ -2,6 +2,7 @@ import { InternalCompilerError } from "../../errors.js"; import type { LlvmEmitterContext, LibCallExpr, LlValue } from "./expr-context.js"; import { f64Lit } from "./common.js"; +import { pipelinePumpedRuns } from "../../ir/builtin-signatures.js"; const STREAM_CANONICAL_CBS: Record = { readable: ["r", "d"], @@ -186,18 +187,24 @@ export function emitStreamLibCall(host: LlvmEmitterContext, e: LibCallExpr): LlV e.fn === "stream.setFinal" || e.fn === "stream.setDestroy" || e.fn === "stream.setTransform" || - e.fn === "stream.setFlush" + e.fn === "stream.setFlush" || + e.fn === "stream.setConstruct" || + e.fn === "stream.setWritev" || + e.fn === "stream.setWritevDefault" ) { // The underscore-method assignment surface: the runtime slot swaps // its closure (+1 moves in) and invoke thunk — the next // _read/_write/... dispatch uses it, Node's timing. - const kindOf: Record = { + const kindOf: Record = { "stream.setRead": "r", "stream.setWrite": "w", "stream.setFinal": "f", "stream.setDestroy": "d", "stream.setTransform": "t", "stream.setFlush": "l", + "stream.setConstruct": "c", + "stream.setWritev": "v", + "stream.setWritevDefault": "v", }; const symOf: Record = { "stream.setRead": "scr_stream_set_read", @@ -206,6 +213,9 @@ export function emitStreamLibCall(host: LlvmEmitterContext, e: LibCallExpr): LlV "stream.setDestroy": "scr_stream_set_destroy", "stream.setTransform": "scr_stream_set_transform", "stream.setFlush": "scr_stream_set_flush", + "stream.setConstruct": "scr_stream_set_construct", + "stream.setWritev": "scr_stream_set_writev", + "stream.setWritevDefault": "scr_stream_set_writev_default", }; const recv = host.emitExpr(e.args[0]!); const cb = host.emitExpr(e.args[1]!); @@ -418,10 +428,34 @@ export function emitStreamLibCall(host: LlvmEmitterContext, e: LibCallExpr): LlV host.emitPendingCheck(); return e.type.kind === "void" ? { name: "", type: e.type } : { name: t, type: e.type }; } + if (e.fn === "writable.writeEnc") { + // (recv, flags, chunk[, encoding][, cb]) — flags: 1 encoding, 2 + // callback (MOVES). Without an encoding the argument is undefined, or + // null when the callback took its place. + const flagsArg = e.args[1]!; + if (flagsArg.kind !== "numLit") + throw new InternalCompilerError("llvm emitter bug: writable.writeEnc flags not a literal"); + const flags = flagsArg.value; + const args = e.args.map((a) => host.emitExpr(a)); + let at = 3; + const enc = flags & 1 ? args[at++]!.name : writeEncNull(host, flags & 2 ? "null" : "undef"); + let cb = "null"; + if (flags & 2) { + host.toHeap(args[at]!); + cb = args[at]!.name; + } + host.declare(`declare zeroext i1 @scr_stream_write_enc(ptr, ptr, ptr, ptr)`); + const t = B.tmp(); + B.line( + `${t} = call zeroext i1 @scr_stream_write_enc(ptr ${args[0]!.name}, ptr ${args[2]!.name}, ptr ${enc}, ptr ${cb})`, + ); + host.emitPendingCheck(); + return e.type.kind === "void" ? { name: "", type: e.type } : { name: t, type: e.type }; + } if (e.fn === "writable.end") { - // (recv, flags[, chunk][, cb]) — flags: 1 bytes chunk, 2 string - // chunk, 8 dyn chunk (write first, Node's end(chunk) decomposition), - // 4 callback. + // (recv, flags[, chunk][, encoding][, cb]) — flags: 1 bytes chunk, 2 + // string chunk, 8 dyn chunk (write first, Node's end(chunk) + // decomposition), 16 an encoding after the dyn chunk, 4 callback. const flagsArg = e.args[1]!; if (flagsArg.kind !== "numLit") throw new InternalCompilerError("llvm emitter bug: writable.end flags not a literal"); @@ -431,19 +465,27 @@ export function emitStreamLibCall(host: LlvmEmitterContext, e: LibCallExpr): LlV let chunkB = "null"; let chunkS = "null"; let chunkD: string | null = null; + let encD = "null"; if (flags & 1) chunkB = args[at++]!.name; else if (flags & 2) chunkS = args[at++]!.name; else if (flags & 8) chunkD = args[at++]!.name; + if (flags & 16) encD = args[at++]!.name; + else if (chunkD !== null && flags & 4) encD = writeEncNull(host, "null"); let cbName = "null"; if (flags & 4) { host.toHeap(args[at]!); cbName = args[at]!.name; } if (chunkD !== null) { - host.declare(`declare zeroext i1 @scr_stream_write_dyn(ptr, ptr, ptr)`); + // end(chunk, cb) writes with a null encoding argument (Node's end + // shifts the callback out of it) + host.declare(`declare zeroext i1 @scr_stream_write_enc(ptr, ptr, ptr, ptr)`); B.line( - `${B.tmp()} = call zeroext i1 @scr_stream_write_dyn(ptr ${args[0]!.name}, ptr ${chunkD}, ptr null)`, + `${B.tmp()} = call zeroext i1 @scr_stream_write_enc(ptr ${args[0]!.name}, ptr ${chunkD}, ptr ${encD}, ptr null)`, ); + // a write that throws (an unknown encoding) leaves the stream as it + // was: Node's end() throws before it ends the stream + host.emitPendingCheck(); } host.declare(`declare ptr @scr_stream_end(ptr, ptr, ptr, ptr)`); const t = B.tmp(); @@ -659,17 +701,20 @@ export function emitStreamLibCall(host: LlvmEmitterContext, e: LibCallExpr): LlV } if ( e.fn === "sp.pipelineStages" || + e.fn === "sp.pipelineStagesOpts" || e.fn === "stream.pipelineStages" || - e.fn === "stream.pipelineStagesDyn" + e.fn === "stream.pipelineStagesDyn" || + e.fn === "stream.composeStages" ) { - // (n, at, k, flags, mask, s1..sn, stage1..stagek, (next, read, - // return)?, box?, (signal, abort)?[, cb]): the streams and the stage - // closures ride stack arrays; absent groups pass null. - const [nArg, atArg, kArg, flagsArg, maskArg] = e.args; + // (n, k, positions, flags, mask, s1..sn, stage1..stagek, helpers..., + // box?, (signal, abort)?[, cb | end, signal?]): the streams, the + // stage closures and the helpers ride stack arrays; absent groups + // pass null. + const [nArg, kArg, positionsArg, flagsArg, maskArg] = e.args; if ( nArg?.kind !== "numLit" || - atArg?.kind !== "numLit" || kArg?.kind !== "numLit" || + positionsArg?.kind !== "numLit" || flagsArg?.kind !== "numLit" || maskArg?.kind !== "numLit" ) @@ -677,6 +722,7 @@ export function emitStreamLibCall(host: LlvmEmitterContext, e: LibCallExpr): LlV const n = nArg.value; const k = kArg.value; const flags = flagsArg.value; + const helperCount = 3 * pipelinePumpedRuns(n + k, positionsArg.value, flags); const args = e.args.map((a) => host.emitExpr(a)); const packed = (from: number, count: number): string => { if (count === 0) return "null"; @@ -691,24 +737,36 @@ export function emitStreamLibCall(host: LlvmEmitterContext, e: LibCallExpr): LlV }; const streams = packed(5, n); const stages = packed(5 + n, k); - let at = 5 + n + k; + const helpers = packed(5 + n + k, helperCount); + let at = 5 + n + k + helperCount; const take = (present: boolean): string => (present ? args[at++]!.name : "null"); - const hasHelpers = (flags & 8) !== 0; - const next = take(hasHelpers); - const read = take(hasHelpers); - const ret = take(hasHelpers); - const box = take((flags & 16) !== 0); + const box = take(((flags >> 1) & 3) === 2); const signal = take((flags & 32) !== 0); const abort = take((flags & 32) !== 0); const head = - `double ${f64Lit(n)}, ptr ${streams}, double ${f64Lit(atArg.value)}, double ${f64Lit(k)}, ` + - `ptr ${stages}, double ${f64Lit(flags)}, double ${f64Lit(maskArg.value)}, ` + - `ptr ${next}, ptr ${read}, ptr ${ret}, ptr ${box}, ptr ${signal}, ptr ${abort}`; - const params = "double, ptr, double, double, ptr, double, double, ptr, ptr, ptr, ptr, ptr, ptr"; + `double ${f64Lit(n)}, ptr ${streams}, double ${f64Lit(k)}, ptr ${stages}, ` + + `double ${f64Lit(positionsArg.value)}, double ${f64Lit(flags)}, double ${f64Lit(maskArg.value)}, ` + + `ptr ${helpers}, ptr ${box}, ptr ${signal}, ptr ${abort}`; + const params = "double, ptr, double, ptr, double, double, double, ptr, ptr, ptr, ptr"; const t = B.tmp(); if (e.fn === "sp.pipelineStages") { host.declare(`declare ptr @scr_sp_pipeline_stages(${params})`); B.line(`${t} = call ptr @scr_sp_pipeline_stages(${head})`); + } else if (e.fn === "sp.pipelineStagesOpts") { + const end = args[at++]!.name; + const outer = take((flags & 64) !== 0); + let add = "null"; + if (outer !== "null") { + host.declare(`declare ptr @scr_events_add_abort_listener(ptr, ptr)`); + add = "@scr_events_add_abort_listener"; + } + host.declare(`declare ptr @scr_sp_pipeline_stages_opts(${params}, i1, ptr, ptr)`); + B.line( + `${t} = call ptr @scr_sp_pipeline_stages_opts(${head}, i1 ${end}, ptr ${outer}, ptr ${add})`, + ); + } else if (e.fn === "stream.composeStages") { + host.declare(`declare ptr @scr_stream_compose_stages(${params})`); + B.line(`${t} = call ptr @scr_stream_compose_stages(${head})`); } else if (e.fn === "stream.pipelineStagesDyn") { host.declare(`declare ptr @scr_stream_pipeline_stages_dyn(${params}, ptr)`); B.line( @@ -772,3 +830,13 @@ export function emitStreamLibCall(host: LlvmEmitterContext, e: LibCallExpr): LlV // adapters; the handful of union-wrapped reads use the envGet shapes. return host.emitGenericLibCall(e); } + +/** The encoding argument a write passes when the call has none: undefined + * (a null pointer), or the null value when a callback took its place. */ +function writeEncNull(host: LlvmEmitterContext, which: "null" | "undef"): string { + if (which === "undef") return "null"; + host.declare(`declare ptr @scr_dyn_new_null()`); + const t = host.B.tmp(); + host.B.line(`${t} = call ptr @scr_dyn_new_null()`); + return t; +} diff --git a/packages/compiler/src/backend/llvm/lib-tls.ts b/packages/compiler/src/backend/llvm/lib-tls.ts index c5c77d3a6..1d1cf659c 100644 --- a/packages/compiler/src/backend/llvm/lib-tls.ts +++ b/packages/compiler/src/backend/llvm/lib-tls.ts @@ -121,6 +121,13 @@ export function emitTlsLibCall(host: LlvmEmitterContext, e: LibCallExpr): LlValu case "tls.sockOnSecureConnect": host.toHeap(args[1]!); return finishRuntimeCall(host, e, "scr_tls_sock_on_secure_connect", a); + case "tls.sockOnSecure": + host.toHeap(args[1]!); + return finishRuntimeCall(host, e, "scr_tls_sock_on_secure", a); + case "tls.wrapSocket": + return finishRuntimeCall(host, e, "scr_tls_wrap_socket", [a[0]!, a[1]!, ptr()]); + case "tls.wrapSocketCtx": + return finishRuntimeCall(host, e, "scr_tls_wrap_socket", a); case "tls.sockOnSession": { const cb = args[1]!, type = callbackType(cb); diff --git a/packages/compiler/src/backend/llvm/local-array-reads.test.ts b/packages/compiler/src/backend/llvm/local-array-reads.test.ts index 96221942f..7af495d42 100644 --- a/packages/compiler/src/backend/llvm/local-array-reads.test.ts +++ b/packages/compiler/src/backend/llvm/local-array-reads.test.ts @@ -925,3 +925,32 @@ test.each([ if (consumer !== "local") expect(ir).toContain("local.array.dense"); } }); + +test("a dense read tests the hole-free prefix before the capacity", () => { + const module = immediateFixture(); + for (const bits of [32, 64] as const) { + const ir = workBody(module, bits); + // Field 6 is `filled` and field 2 `cap`: the first branch takes the value + // path below the prefix, and only the range block reads the capacity. + const firstFilled = ir.search(/getelementptr inbounds %ScrArr, ptr %[^,]+, i32 0, i32 6\b/); + const firstCap = ir.search(/getelementptr inbounds %ScrArr, ptr %[^,]+, i32 0, i32 2\b/); + expect(firstFilled).toBeGreaterThan(0); + expect(firstCap).toBeGreaterThan(firstFilled); + expect(ir.slice(firstFilled, firstCap)).toMatch(/br i1 [^,]+, label %local\.array\.value/); + expect(ir.lastIndexOf("local.array.range", firstCap)).toBeGreaterThan(firstFilled); + } +}); + +test("an optional read at a proven integer index skips the double round trip", () => { + const module = fixture(); + const call = module.functions[2]!.body[0]!; + if (call.kind !== "varDecl" || call.init?.kind !== "call") throw new Error("missing call"); + call.init.args[1] = { kind: "bin", op: "|", left: ref("i", F64), right: num(0), type: F64, loc }; + expect(candidates(module).get("value")?.borrow).toBe(true); + expect(validateModule(module)).toEqual([]); + // The int32 index is the dense offset on 64-bit targets; a 32-bit target + // converts the double, as a borrowed read does. + expect(workBody(module, 64)).not.toContain("local.array.exact"); + expect(workBody(module, 64)).toContain("local.array.value"); + expect(workBody(module, 32)).toContain("local.array.exact"); +}); diff --git a/packages/compiler/src/backend/llvm/local-array-reads.ts b/packages/compiler/src/backend/llvm/local-array-reads.ts index b9fd0f54b..8df187736 100644 --- a/packages/compiler/src/backend/llvm/local-array-reads.ts +++ b/packages/compiler/src/backend/llvm/local-array-reads.ts @@ -12,9 +12,16 @@ import { everyStmtList } from "../../ir/traverse.js"; import { analyzeCallLifetimes, type CallLifetimes } from "./call-lifetimes.js"; import type { LlValue, LlvmEmitterContext } from "./expr-context.js"; import { ReferenceEffects } from "./reference-effects.js"; -import { SCR_ARR_FIELD, exactIndexLines, loadArrCount, scrArrStateAt } from "./common.js"; +import { SCR_ARR_FIELD, loadArrCount, scrArrStateAt } from "./common.js"; import { exactInteger, widenInteger } from "./integer-values.js"; import { READ_FALLBACK } from "./dense-array-access.js"; +import { compactRefLoadLines } from "./classes.js"; + +/** The dense slot load of a reference read from an array of type + * `arrayType`: a pointer, or a compact class reference (SCR_ELEM_CREF). */ +function referenceLoad(host: LlvmEmitterContext, arrayType: IrType): "ptr" | "cref" { + return arrayType.kind === "array" && host.compactArrayElem(arrayType.elem) ? "cref" : "ptr"; +} export interface LocalArrayRead { type: IrType; @@ -469,81 +476,84 @@ function emitDenseReferenceArrayRead( no: string, slow: string, join: string, - loadType: "ptr" | "i64" | "i8" = "ptr", + loadType: "ptr" | "cref" | "i64" | "i8" = "ptr", ): void { const B = host.B; - const range = B.newLabel("local.array.range"), - dense = B.newLabel("local.array.dense"); - // The dense path uses the existing ScrArr ABI. Sparse indices and - // noncanonical numeric properties retain the runtime lookup semantics. - const capPtr = B.tmp(), - cap = B.tmp(); - B.line( - `${capPtr} = getelementptr inbounds %ScrArr, ptr ${array.name}, i32 0, i32 ${SCR_ARR_FIELD.cap}`, - ); - host.markMemoryPointer(capPtr, "array:header"); - loadArrCount(host, cap, capPtr, host.fieldAliasAttachment(capPtr)); - let offset: string, inRange: string; + const header = (field: number): string => { + const ptr = B.tmp(); + B.line(`${ptr} = getelementptr inbounds %ScrArr, ptr ${array.name}, i32 0, i32 ${field}`); + host.markMemoryPointer(ptr, "array:header"); + return ptr; + }; + const valueLabel = B.newLabel("local.array.value"); + // `key` is the index compared with the array's counts and `offset` the + // index that addresses its slots. A double index that is not an exact + // integer, like a sparse or noncanonical one, keeps the runtime lookup + // semantics; an exact one compares as i64, which a 32-bit target does + // before truncating it. + let key: string, keyType: string, offset: string; if (integerIndex) { - offset = integerIndex; - inRange = B.tmp(); - B.line(`${inRange} = icmp ult ${host.sizeType} ${integerIndex}, ${cap}`); + key = offset = integerIndex; + keyType = host.sizeType; } else { - // Capacity bounds the dense slots; the length check below still decides presence. - const exact = exactIndexLines(index.name, cap, host.sizeType, () => B.tmp()); - for (const line of exact.lines) B.line(line); - inRange = exact.ok; - offset = exact.wide; + const raw = B.tmp(), + back = B.tmp(), + integral = B.tmp(), + exact = B.newLabel("local.array.exact"); + key = B.tmp(); + keyType = "i64"; + B.line(`${raw} = fptosi double ${index.name} to i64`); + B.line(`${key} = freeze i64 ${raw}`); + B.line(`${back} = sitofp i64 ${key} to double`); + B.line(`${integral} = fcmp oeq double ${back}, ${index.name}`); + B.condBr(integral, exact, slow); + B.startBlock(exact); + offset = key; if (host.sizeType !== "i64") { offset = B.tmp(); - B.line(`${offset} = trunc i64 ${exact.wide} to ${host.sizeType}`); + B.line(`${offset} = trunc i64 ${key} to ${host.sizeType}`); } } - B.condBr(inRange, range, slow); - B.startBlock(range); - B.br(dense); - B.startBlock(dense); - // The state and value paths below both index from `data`: one load here - // serves both. - const dataPtr = B.tmp(), + const widen = (count: string, type: string): string => { + if (type === keyType) return count; + const wide = B.tmp(); + B.line(`${wide} = zext ${type} ${count} to ${keyType}`); + return wide; + }; + // The state and value paths both index from `data`: one load serves both. + const dataPtr = header(SCR_ARR_FIELD.data), data = B.tmp(); - B.line( - `${dataPtr} = getelementptr inbounds %ScrArr, ptr ${array.name}, i32 0, i32 ${SCR_ARR_FIELD.data}`, - ); - host.markMemoryPointer(dataPtr, "array:header"); B.line(`${data} = load ptr, ptr ${dataPtr}${host.fieldAliasAttachment(dataPtr)}`); - // Below the hole-free prefix bound every state is a present value. - const filledPtr = B.tmp(), + // Below the hole-free prefix every state is a present value, and the + // prefix is at most the length and the capacity, so an index below it needs + // no other test before the value load. + const filledPtr = header(SCR_ARR_FIELD.filled), filled = B.tmp(), - belowFilled = B.tmp(), - lenLabel = B.newLabel("local.array.len"); - B.line( - `${filledPtr} = getelementptr inbounds %ScrArr, ptr ${array.name}, i32 0, i32 ${SCR_ARR_FIELD.filled}`, - ); - host.markMemoryPointer(filledPtr, "array:header"); + prefix = B.tmp(); B.line(`${filled} = load i32, ptr ${filledPtr}${host.fieldAliasAttachment(filledPtr)}`); - let filledSized = filled; - if (host.sizeType !== "i32") { - filledSized = B.tmp(); - B.line(`${filledSized} = zext i32 ${filled} to ${host.sizeType}`); - } - B.line(`${belowFilled} = icmp ult ${host.sizeType} ${offset}, ${filledSized}`); - const valueLabel = B.newLabel("local.array.value"); + B.line(`${prefix} = icmp ult ${keyType} ${key}, ${widen(filled, "i32")}`); if (induction) { // The state of slot i is at data + cap * (width + 1) - 1 - i, and an // inline state check makes LLVM keep -1 - i as a second induction // variable in the loop; above the prefix the runtime reads the slot. - B.condBr(belowFilled, valueLabel, slow); + B.condBr(prefix, valueLabel, slow); } else { - B.condBr(belowFilled, valueLabel, lenLabel); - B.startBlock(lenLabel); - const lenPtr = B.tmp(), + const range = B.newLabel("local.array.range"), + dense = B.newLabel("local.array.dense"); + B.condBr(prefix, valueLabel, range); + B.startBlock(range); + const capPtr = header(SCR_ARR_FIELD.cap), + cap = B.tmp(), + inRange = B.tmp(); + loadArrCount(host, cap, capPtr, host.fieldAliasAttachment(capPtr)); + B.line(`${inRange} = icmp ult ${keyType} ${key}, ${widen(cap, host.sizeType)}`); + B.condBr(inRange, dense, slow); + // Within the capacity and above the prefix, a slot below the length is + // present when its state is. + B.startBlock(dense); + const lenPtr = header(SCR_ARR_FIELD.len), len = B.tmp(), belowLen = B.tmp(); - B.line( - `${lenPtr} = getelementptr inbounds %ScrArr, ptr ${array.name}, i32 0, i32 ${SCR_ARR_FIELD.len}`, - ); - host.markMemoryPointer(lenPtr, "array:header"); loadArrCount(host, len, lenPtr, host.fieldAliasAttachment(lenPtr)); B.line(`${belowLen} = icmp ult ${host.sizeType} ${offset}, ${len}`); const stateLabel = B.newLabel("local.array.state"); @@ -552,7 +562,14 @@ function emitDenseReferenceArrayRead( const statePtr = B.tmp(), denseState = B.tmp(), densePresent = B.tmp(); - scrArrStateAt(host, statePtr, data, cap, loadType === "i8" ? 1 : 8, offset); + scrArrStateAt( + host, + statePtr, + data, + cap, + loadType === "i8" ? 1 : loadType === "cref" ? 4 : 8, + offset, + ); host.markMemoryPointer(statePtr, "array:present"); B.line(`${denseState} = load i8, ptr ${statePtr}${host.fieldAliasAttachment(statePtr)}`); B.line(`${densePresent} = icmp eq i8 ${denseState}, 1`); @@ -561,13 +578,20 @@ function emitDenseReferenceArrayRead( B.startBlock(valueLabel); const valuePtr = B.tmp(), raw = B.tmp(); - // Boolean arrays store one byte per element; every other kind an 8-byte slot. - const slotType = loadType === "i8" ? "i8" : "i64"; + // Boolean arrays store one byte per element, compact references four, + // every other kind an 8-byte slot. + const slotType = loadType === "i8" ? "i8" : loadType === "cref" ? "i32" : "i64"; B.line( `${valuePtr} = getelementptr inbounds ${slotType}, ptr ${data}, ${host.sizeType} ${offset}`, ); host.markMemoryPointer(valuePtr, "array:elements"); - B.line(`${raw} = load ${loadType}, ptr ${valuePtr}${host.fieldAliasAttachment(valuePtr)}`); + if (loadType === "cref") { + const ref = B.tmp(); + B.line(`${ref} = load i32, ptr ${valuePtr}${host.fieldAliasAttachment(valuePtr)}`); + for (const line of compactRefLoadLines(ref, raw, `${raw}.r`)) B.line(line.trimStart()); + } else { + B.line(`${raw} = load ${loadType}, ptr ${valuePtr}${host.fieldAliasAttachment(valuePtr)}`); + } present(raw); B.br(join); } @@ -583,6 +607,36 @@ export function emitBorrowedArrayRead( const B = host.B; const array = host.emitStableReceiver(read.arr, [read.index]); const loopIndex = host.emitIntegerLoopIndex(read.index); + if (loopIndex !== null && host.provenDenseIndex(read.arr, read.index)) { + // In a dense array loop's fast copy, the entry test proved the counter + // below the array's hole-free prefix: the slot holds a present value. + const dataPtr = B.tmp(), + data = B.tmp(), + valuePtr = B.tmp(), + value = B.tmp(); + B.line( + `${dataPtr} = getelementptr inbounds %ScrArr, ptr ${array.name}, i32 0, i32 ${SCR_ARR_FIELD.data}`, + ); + host.markMemoryPointer(dataPtr, "array:header"); + B.line(`${data} = load ptr, ptr ${dataPtr}${host.fieldAliasAttachment(dataPtr)}`); + if (referenceLoad(host, read.arr.type) === "cref") { + // Compact references: 4-byte slots holding the address over 8. + const ref = B.tmp(); + B.line( + `${valuePtr} = getelementptr inbounds i32, ptr ${data}, ${host.sizeType} ${loopIndex}`, + ); + host.markMemoryPointer(valuePtr, "array:elements"); + B.line(`${ref} = load i32, ptr ${valuePtr}${host.fieldAliasAttachment(valuePtr)}`); + for (const line of compactRefLoadLines(ref, value, `${value}.r`)) B.line(line.trimStart()); + B.line(`store ptr ${value}, ptr ${slot}`); + return; + } + B.line(`${valuePtr} = getelementptr inbounds i64, ptr ${data}, ${host.sizeType} ${loopIndex}`); + host.markMemoryPointer(valuePtr, "array:elements"); + B.line(`${value} = load ptr, ptr ${valuePtr}${host.fieldAliasAttachment(valuePtr)}`); + B.line(`store ptr ${value}, ptr ${slot}`); + return; + } const index = host.emitExpr(read.index); // A proven integer index (an int32 local, say) needs no double // round-trip; a negative one compares above the capacity as unsigned. @@ -601,6 +655,7 @@ export function emitBorrowedArrayRead( slow, slow, join, + referenceLoad(host, read.arr.type), ); B.startBlock(slow); host.declare("declare ptr @scr_arr_borrow_ref(ptr, double)"); @@ -623,8 +678,15 @@ export function emitLocalArrayRead( ): { slot: string; type: IrType } | null { const B = host.B; const array = host.emitStableReceiver(read.array, [read.index]); - const integerIndex = inline ? host.emitIntegerLoopIndex(read.index) : null; + const loopIndex = inline ? host.emitIntegerLoopIndex(read.index) : null; const index = host.emitExpr(read.index); + // A proven integer index (a counter with a known range, say) needs no + // double round trip, as in a borrowed read. + const exact = + inline && loopIndex === null && host.sizeType === "i64" + ? exactInteger(host, index, read.index) + : null; + const integerIndex = loopIndex ?? (exact ? widenInteger(host, exact) : null); const nullable = read.type.kind === "union" ? host.nullableUnions.get(read.type.unionId) : null; if (nullable) { // A nullable union is the element pointer itself: borrowed from an @@ -644,12 +706,12 @@ export function emitLocalArrayRead( array, index, integerIndex, - integerIndex !== null, + loopIndex !== null, store, no, slow, join, - "ptr", + referenceLoad(host, read.array.type), ); else B.br(slow); B.startBlock(slow); @@ -705,12 +767,12 @@ export function emitLocalArrayRead( array, index, integerIndex, - integerIndex !== null, + loopIndex !== null, storeValue, no, slow, join, - !scalar ? "ptr" : read.element.kind === "bool" ? "i8" : "i64", + !scalar ? referenceLoad(host, read.array.type) : read.element.kind === "bool" ? "i8" : "i64", ); else B.br(slow); B.startBlock(slow); diff --git a/packages/compiler/src/backend/llvm/loop-state.ts b/packages/compiler/src/backend/llvm/loop-state.ts new file mode 100644 index 000000000..ce9189a45 --- /dev/null +++ b/packages/compiler/src/backend/llvm/loop-state.ts @@ -0,0 +1,76 @@ +/* The loop optimizations' per-function state: counted loops, dense array + * loops, byte windows and typed-array loop versioning, and the unaliased + * local arrays they rely on. */ +import { findUnaliasedLocalArrays } from "../../ir/array-length-stability.js"; +import type { IrFunction, IrStmt } from "../../ir/ir.js"; +import { findInitializedByteLoopBindings } from "./byte-windows.js"; +import type { DenseArrayLoop } from "./dense-array-loops.js"; +import type { LlEmitter } from "./emitter.js"; +import { defineModuleState } from "./emitter-state.js"; + +/** Sets the loop state for `fn` at the start of its emission; `numericFn` + * is `fn` with its initializer bindings (emitFunction). */ +export function beginFunctionLoops( + emitter: LlEmitter, + fn: IrFunction, + numericFn: IrFunction, +): void { + const loops = LOOPS.of(emitter); + loops.unaliasedArrays = findUnaliasedLocalArrays(fn); + loops.countedLoopsEnabled = emitter.debug === null && !fn.async && !fn.generator; + loops.byteWindowsEnabled = loops.countedLoopsEnabled; + loops.bytesLoopVersionsEnabled = loops.countedLoopsEnabled; + loops.bytesLoopEntries = null; + loops.bytesLoopFunction = fn; + loops.denseLoopsEnabled = loops.countedLoopsEnabled; + loops.denseLoop = null; + loops.denseLoopEntries = + loops.denseLoopsEnabled && numericFn.locals.some((l) => l.type.kind === "array") + ? findInitializedByteLoopBindings(fn) + : new Map(); + loops.byteWindowEntries = + loops.byteWindowsEnabled && numericFn.locals.some((l) => l.type.kind === "bytes") + ? findInitializedByteLoopBindings(fn) + : new Map(); +} + +/** The state LOOPS holds on each emitter. */ +export interface LoopState { + /** Local arrays of the current function that no other binding can hold + * (ir/array-length-stability.ts). */ + unaliasedArrays: ReadonlySet; + /** Dense array loops (dense-array-loops.ts) run in this function. */ + denseLoopsEnabled: boolean; + denseLoopEntries: ReturnType; + /** The fast copy of a dense array loop being emitted. */ + denseLoop: DenseArrayLoop | null; + countedLoopsEnabled: boolean; + byteWindowsEnabled: boolean; + byteWindowEntries: ReturnType; + /** Typed-array loop versioning (bytes-loop-versions.ts) for the current + * function: off in debug and suspending functions and inside a copy. */ + bytesLoopVersionsEnabled: boolean; + /** Loops being versioned around the statement being emitted: a loop is + * never versioned inside its own copies, and versions nest boundedly. */ + readonly bytesLoopVersioning: Set; + bytesLoopEntries: ReturnType | null; + bytesLoopFunction: IrFunction | null; + /** Counted loops whose integer-form safety test an enclosing version + * guard already passed. */ + readonly provenCountedGuards: Set; +} + +export const LOOPS = defineModuleState(() => ({ + unaliasedArrays: new Set(), + denseLoopsEnabled: false, + denseLoopEntries: new Map(), + denseLoop: null, + countedLoopsEnabled: false, + byteWindowsEnabled: true, + byteWindowEntries: new Map(), + bytesLoopVersionsEnabled: false, + bytesLoopVersioning: new Set(), + bytesLoopEntries: null, + bytesLoopFunction: null, + provenCountedGuards: new Set(), +})); diff --git a/packages/compiler/src/backend/llvm/map-number-lookup.test.ts b/packages/compiler/src/backend/llvm/map-number-lookup.test.ts index 5dc3589e4..989b8b3b0 100644 --- a/packages/compiler/src/backend/llvm/map-number-lookup.test.ts +++ b/packages/compiler/src/backend/llvm/map-number-lookup.test.ts @@ -181,3 +181,63 @@ test("hashed number-key lookups probe inline and call the runtime only for wide ); } }); + +/** work(map): map.size, and keep(map): map returned as an owned value. */ +function sizeFixture(): IrModule { + const map: IrType = { kind: "map", key: F64, value: F64 }; + const params = [{ localId: "map", name: "map", type: map }]; + const locals = params.map((p) => ({ id: p.localId, name: p.name, type: p.type, mutable: true })); + const size: IrExpr = { + kind: "mapIntrinsic", + method: "size", + receiver: ref("map", map), + args: [], + type: F64, + loc, + }; + return { + irVersion: 17, + sourceFile: loc.file, + entry: "main", + records: [], + unions: [], + functions: [ + { name: "main", params: [], locals: [], returnType: VOID, body: [], loc }, + { + name: "work", + params, + returnType: F64, + loc, + locals, + body: [{ kind: "return", value: size, loc }], + }, + { + name: "keep", + params, + returnType: map, + loc, + locals, + body: [{ kind: "return", value: ref("map", map), loc }], + }, + ], + }; +} + +test("Map.size and Map retains need no runtime call in release builds", () => { + const mod = sizeFixture(); + expect(validateModule(mod)).toEqual([]); + for (const bits of [32, 64] as const) { + const module = emitLlvmModule(mod, { pointerBits: bits, inlineRc: "release" }); + const fn = (name: string) => + new RegExp(`^define internal [^\\n]*@sc_(?:b)?f_${name}(?:\\.i32)?\\([^]*?^}`, "m").exec( + module, + )![0]; + // Field 9 is the live entry count (scr_map.h). + expect(module).toMatch(/^define internal double @sc_map_size\(ptr %m\)/m); + expect(module).toContain(`getelementptr inbounds %ScrMapIx, ptr %m, i32 0, i32 9`); + expect(fn("work")).toContain("call double @sc_map_size("); + expect(module).not.toContain("call double @scr_map_size("); + expect(fn("keep")).toContain("@sc_rc_retain_map("); + expect(module).not.toContain("call ptr @scr_map_retain_v("); + } +}); diff --git a/packages/compiler/src/backend/llvm/map-number-lookup.ts b/packages/compiler/src/backend/llvm/map-number-lookup.ts index 1244bd9c3..6d219b50a 100644 --- a/packages/compiler/src/backend/llvm/map-number-lookup.ts +++ b/packages/compiler/src/backend/llvm/map-number-lookup.ts @@ -15,6 +15,12 @@ * retain inline rather than through the runtime's indirect adapter call, * and scalar reads and has() share the one lookup. * + * A string-key map whose values are compact class instances + * (SCR_MAP_VAL_CREF, LlEmitter.compactArrayElem of the value type) keeps + * 16-byte { key, hash, val } entries with the value as an address over 8: + * its reads go through sc_map_entry_str_c and sc_map_iter_entry_c, and + * decode the 4-byte value. + * * The iteration steps behind for-of, forEach and the other entry walks read * the entries array through the internal sc_map_iter_entry and * sc_map_iter_count helpers: a live entry's key or value loads in place, @@ -24,6 +30,7 @@ */ import type { IrType } from "../../ir/ir.js"; import type { LlvmEmitterContext } from "./expr-context.js"; +import { mapKeyAccess } from "./shapes.js"; export const NUMBER_MAP_ENTRY_DECL = "declare ptr @scr_map_entry_f64(ptr, double)"; @@ -47,18 +54,59 @@ export function emitNumberMapSlot(host: LlvmEmitterContext, entry: string, type: } export const STRING_MAP_ENTRY_DECL = "declare ptr @scr_map_entry_str(ptr, ptr)"; +/** Declared by reads of a compact-value map; its presence makes the emitter + * define sc_map_entry_str_c and sc_map_iter_entry_c (emit-module.ts). */ +export const STRING_MAP_ENTRY_C_DECL = "declare ptr @scr_map_entry_str_c(ptr, ptr)"; -/** The entry for a string `key`, or null when absent. Valid until the next mutation. */ -export function emitStringMapEntry(host: LlvmEmitterContext, map: string, key: string): string { - host.declare(STRING_MAP_ENTRY_DECL); +/** Whether a Map with key type `key` and value type `value` keeps compact + * values (SCR_MAP_VAL_CREF): string keys and a value type whose instances + * are compact (LlEmitter.compactArrayElem). */ +export function compactMapValues(host: LlvmEmitterContext, key: IrType, value: IrType): boolean { + // SCR_MAP_KEY_STR (shapes.ts mapKeyKindNum 1): string access, not a union. + return key.kind !== "union" && mapKeyAccess(key) === "str" && host.compactArrayElem(value); +} + +/** The entry for a string `key`, or null when absent. Valid until the next + * mutation. `compact`: the map keeps compact values (a %ScrMapCEntry). */ +export function emitStringMapEntry( + host: LlvmEmitterContext, + map: string, + key: string, + compact = false, +): string { + host.declare(compact ? STRING_MAP_ENTRY_C_DECL : STRING_MAP_ENTRY_DECL); const entry = host.B.tmp(); - host.B.line(`${entry} = call ptr @sc_map_entry_str(ptr ${map}, ptr ${key})`); + host.B.line( + `${entry} = call ptr @${compact ? "sc_map_entry_str_c" : "sc_map_entry_str"}(ptr ${map}, ptr ${key})`, + ); return entry; } +/** A found compact-value entry's value as a pointer: its 4-byte form, an + * address over 8 (scr_map.h ScrMapCEntry). */ +export function emitCompactMapSlot(host: LlvmEmitterContext, entry: string): string { + const B = host.B; + const slot = B.tmp(), + ref = B.tmp(), + wide = B.tmp(), + addr = B.tmp(), + value = B.tmp(); + B.line(`${slot} = getelementptr inbounds %ScrMapCEntry, ptr ${entry}, i32 0, i32 2`); + B.line(`${ref} = load i32, ptr ${slot}`); + B.line(`${wide} = zext i32 ${ref} to i64`); + B.line(`${addr} = shl nuw nsw i64 ${wide}, 3`); + B.line(`${value} = inttoptr i64 ${addr} to ptr`); + return value; +} + /** Map.has / Set.has under a string key. */ -export function emitStringMapHas(host: LlvmEmitterContext, map: string, key: string): string { - const entry = emitStringMapEntry(host, map, key); +export function emitStringMapHas( + host: LlvmEmitterContext, + map: string, + key: string, + compact = false, +): string { + const entry = emitStringMapEntry(host, map, key, compact); const found = host.B.tmp(); host.B.line(`${found} = icmp ne ptr ${entry}, null`); return found; @@ -92,12 +140,18 @@ export function emitStringMapGetRef( map: string, key: string, value: IrType, + compact = false, ): string { - return emitMapEntryGetRef(host, emitStringMapEntry(host, map, key), value); + return emitMapEntryGetRef(host, emitStringMapEntry(host, map, key, compact), value, compact); } /** The +1 value of a found entry, or null for a missing (null) entry. */ -function emitMapEntryGetRef(host: LlvmEmitterContext, entry: string, value: IrType): string { +function emitMapEntryGetRef( + host: LlvmEmitterContext, + entry: string, + value: IrType, + compact = false, +): string { const B = host.B; const found = B.tmp(); B.line(`${found} = icmp ne ptr ${entry}, null`); @@ -106,7 +160,10 @@ function emitMapEntryGetRef(host: LlvmEmitterContext, entry: string, value: IrTy join = B.newLabel("mapn.join"); B.condBr(found, hit, miss); B.startBlock(hit); - const retained = host.retainFrame(emitNumberMapSlot(host, entry, "ptr"), value); + const retained = host.retainFrame( + compact ? emitCompactMapSlot(host, entry) : emitNumberMapSlot(host, entry, "ptr"), + value, + ); B.br(join); B.startBlock(miss); B.br(join); @@ -199,20 +256,25 @@ export const SCR_MAP_NUM_DEAD = "9218868437227405313"; /** The entry layout a Map or Set of key type `key` stores: * - "num": number keys, whose entries are { key, val } (scr_map.h ScrMapNumEntry); + * - "centry": string keys with compact values (compactMapValues), whose + * entries are { key, hash, val } (ScrMapCEntry); * - "entry": every other typed key, whose entries are { key, val, hash }; * - "either": checked (`unknown`) keys. A `Map` or * `Set` cast from a checked value keeps the collection's own - * storage (scr_dyn_native_collection_check), which can have number keys. */ -export type MapEntryLayout = "num" | "entry" | "either"; + * storage (scr_dyn_native_collection_check), which can have number keys + * or compact values. */ +export type MapEntryLayout = "num" | "centry" | "entry" | "either"; -export function mapEntryLayout(key: IrType): MapEntryLayout { +export function mapEntryLayout(key: IrType, compact = false): MapEntryLayout { + if (compact) return "centry"; return key.kind === "f64" ? "num" : key.kind === "dyn" ? "either" : "entry"; } /** The entry at an iteration index, or null for a tombstone or an index at * or past the entry count (the scr_map_iter_live test). With the "either" * layout, the map's key kind (%ScrMapIx field 1, SCR_MAP_KEY_F64 = 0) picks - * the step at run time. */ + * the step at run time; in a program with compact class instances, so does + * its value kind (field 2, SCR_MAP_VAL_CREF = 3). */ export function emitMapIterEntry( host: LlvmEmitterContext, map: string, @@ -220,14 +282,20 @@ export function emitMapIterEntry( layout: MapEntryLayout, ): string { const B = host.B; - const step = (num: boolean): string => { - host.declare(num ? MAP_ITER_NUM_DECL : MAP_ITER_DECL); + const step = (kind: "num" | "centry" | "entry"): string => { + host.declare(kind === "num" ? MAP_ITER_NUM_DECL : MAP_ITER_DECL); + if (kind === "centry") host.declare(STRING_MAP_ENTRY_C_DECL); const entry = B.tmp(); - const helper = num ? "sc_map_iter_entry_num" : "sc_map_iter_entry"; + const helper = + kind === "num" + ? "sc_map_iter_entry_num" + : kind === "centry" + ? "sc_map_iter_entry_c" + : "sc_map_iter_entry"; B.line(`${entry} = call ptr @${helper}(ptr ${map}, double ${index})`); return entry; }; - if (layout !== "either") return step(layout === "num"); + if (layout !== "either") return step(layout); host.declare(MAP_ITER_DECL); const kindPtr = B.tmp(), kind = B.tmp(), @@ -240,16 +308,31 @@ export function emitMapIterEntry( join = B.newLabel("mapit.layout"); B.condBr(isNum, numLabel, entryLabel); B.startBlock(numLabel); - const numEntry = step(true); + const numEntry = step("num"); const numEnd = B.currentLabel(); B.br(join); B.startBlock(entryLabel); - const otherEntry = step(false); - const entryEnd = B.currentLabel(); + const arms: { value: string; label: string }[] = [{ value: numEntry, label: numEnd }]; + if (host.shapeHost.compactRegion?.() === true) { + const valPtr = B.tmp(), + valKind = B.tmp(), + isCompact = B.tmp(); + B.line(`${valPtr} = getelementptr inbounds %ScrMapIx, ptr ${map}, i32 0, i32 2`); + B.line(`${valKind} = load i8, ptr ${valPtr}`); + B.line(`${isCompact} = icmp eq i8 ${valKind}, 3`); + const compactLabel = B.newLabel("mapit.centry"), + wideLabel = B.newLabel("mapit.wide"); + B.condBr(isCompact, compactLabel, wideLabel); + B.startBlock(compactLabel); + arms.push({ value: step("centry"), label: B.currentLabel() }); + B.br(join); + B.startBlock(wideLabel); + } + arms.push({ value: step("entry"), label: B.currentLabel() }); B.br(join); B.startBlock(join); const entry = B.tmp(); - B.line(`${entry} = phi ptr [ ${numEntry}, %${numEnd} ], [ ${otherEntry}, %${entryEnd} ]`); + B.line(`${entry} = phi ptr ${arms.map((a) => `[ ${a.value}, %${a.label} ]`).join(", ")}`); return entry; } @@ -270,6 +353,16 @@ export function emitMapIterCount(host: LlvmEmitterContext, map: string): string return count; } +export const MAP_SIZE_DECL = "declare double @scr_map_size(ptr)"; + +/** Map.size / Set.size: the live entry count, read inline (sc_map_size). */ +export function emitMapSize(host: LlvmEmitterContext, map: string): string { + host.declare(MAP_SIZE_DECL); + const size = host.B.tmp(); + host.B.line(`${size} = call double @sc_map_size(ptr ${map})`); + return size; +} + /** The key (field 0) or value (field 1) of the live entry at an iteration * index, read inline: a number as double, a boolean as i1, and a string or * reference retained with `type`'s retain (+1), the adapter the collection @@ -294,18 +387,24 @@ export function emitMapIterSlot( join = B.newLabel("mapit.join"); B.condBr(found, hit, miss); B.startBlock(hit); - const slot = B.tmp(); - B.line(`${slot} = getelementptr inbounds %ScrMapEntry, ptr ${entry}, i32 0, i32 ${field}`); const llTy = access === "f64" ? "double" : access === "bool" ? "i1" : "ptr"; - let loaded = B.tmp(); - if (access === "bool") { - const bits = loaded; - B.line(`${bits} = load i64, ptr ${slot}`); - loaded = B.tmp(); - B.line(`${loaded} = icmp ne i64 ${bits}, 0`); + let loaded: string; + if (layout === "centry" && field === 1) { + // A compact value; its type's retain emits no counting. + loaded = host.retainFrame(emitCompactMapSlot(host, entry), type); } else { - B.line(`${loaded} = load ${llTy}, ptr ${slot}`); - if (access === "ref") loaded = host.retainFrame(loaded, type); + const slot = B.tmp(); + B.line(`${slot} = getelementptr inbounds %ScrMapEntry, ptr ${entry}, i32 0, i32 ${field}`); + loaded = B.tmp(); + if (access === "bool") { + const bits = loaded; + B.line(`${bits} = load i64, ptr ${slot}`); + loaded = B.tmp(); + B.line(`${loaded} = icmp ne i64 ${bits}, 0`); + } else { + B.line(`${loaded} = load ${llTy}, ptr ${slot}`); + if (access === "ref") loaded = host.retainFrame(loaded, type); + } } const hitEnd = B.currentLabel(); B.br(join); diff --git a/packages/compiler/src/backend/llvm/map-read-lifetimes.ts b/packages/compiler/src/backend/llvm/map-read-lifetimes.ts index 005f88f13..6b58d314a 100644 --- a/packages/compiler/src/backend/llvm/map-read-lifetimes.ts +++ b/packages/compiler/src/backend/llvm/map-read-lifetimes.ts @@ -15,6 +15,7 @@ import { emitNumberMapGetScalar, emitStringMapGetScalar, emitStringMapGetRef, + compactMapValues, } from "./map-number-lookup.js"; import { mapKeyAccess, mapKeyParamType } from "./shapes.js"; import { rememberMapEntry } from "./map-entry-fusion.js"; @@ -323,7 +324,10 @@ export function emitStackMapRead(host: LlvmEmitterContext, read: LocalMapRead): } else if (isRefCounted(read.value)) { const stringKey = entryStringKey(key); let raw: string; - if (stringKey !== null) raw = emitStringMapGetRef(host, receiver.name, stringKey, read.value); + const mapType = read.receiver.type; + const compact = mapType.kind === "map" && compactMapValues(host, mapType.key, mapType.value); + if (stringKey !== null) + raw = emitStringMapGetRef(host, receiver.name, stringKey, read.value, compact); else { raw = B.tmp(); host.declare(`declare ptr @scr_map_get_${access}_ref(ptr, ${keyType})`); diff --git a/packages/compiler/src/backend/llvm/nullable-unions.ts b/packages/compiler/src/backend/llvm/nullable-unions.ts index 8729e9649..2c355f551 100644 --- a/packages/compiler/src/backend/llvm/nullable-unions.ts +++ b/packages/compiler/src/backend/llvm/nullable-unions.ts @@ -279,6 +279,8 @@ function shapeUnion( * tag and payload inside the C map. */ function boxedUnionIds(mod: IrModule): Set { const boxed = new Set(); + // Only the module's union definitions consult the result. + if (!mod.unions?.length) return boxed; const mark = (t: IrType): void => { if (t.kind === "union") boxed.add(t.unionId); }; diff --git a/packages/compiler/src/backend/llvm/publish.ts b/packages/compiler/src/backend/llvm/publish.ts index 2f45c3cd2..60270adda 100644 --- a/packages/compiler/src/backend/llvm/publish.ts +++ b/packages/compiler/src/backend/llvm/publish.ts @@ -31,6 +31,13 @@ import type { InlineUnionFields } from "./inline-unions.js"; import { LlvmUnsupportedError } from "./unsupported.js"; export interface PublishHost { + /** Chunk emitters only (emit-journal.ts): EmitJournal's allocated, built, + * opened, used and entry. */ + journalAllocated?: ((name: string, op: string, args: readonly unknown[]) => void) | undefined; + journalBuilt?: (() => void) | undefined; + journalOpened?: ((op: string) => void) | undefined; + journalUsed?: ((name: string, op: string, args: readonly unknown[]) => void) | undefined; + journalEntry?: ((table: string, key: string, value: unknown) => void) | undefined; declare(decl: string): void; /** An interned NUL-terminated constant. */ cstr(text: string): string; @@ -103,6 +110,14 @@ export class PublishWalkers { constructor(private readonly host: PublishHost) {} + /** Journal replay (emit-journal.ts): builds or finds the walker a chunk + * emitter recorded, and answers its name. */ + replayHelper(op: string, args: readonly unknown[]): string { + if (op === "publish.walker") + return this.walker(args[0] as IrType, args[1] as string, args[2] as SrcLoc)!; + return this.refusal(args[0] as string, args[1] as string); + } + /** The definitions emitted so far (module-level LLVM text). */ defs(): string[] { return this.defsOut; @@ -119,6 +134,7 @@ export class PublishWalkers { } const fn = this.walker(t, "the published value", loc); if (fn === null) return []; + this.host.journalUsed?.(fn, "publish.walker", [t, "the published value", loc]); this.host.declare(`declare void @scr_publish(ptr, ptr)`); return [` call void @scr_publish(ptr ${v}, ptr ${fn})`]; } @@ -156,8 +172,10 @@ export class PublishWalkers { if (known !== undefined) return known; const sym = `@sc_pub_${this.counter++}`; this.walkers.set(key, sym); + this.host.journalOpened?.("publish.walker"); const body = this.body(t, sym, path, loc); this.defsOut.push(...body, ``); + this.host.journalBuilt?.(); return sym; } @@ -172,6 +190,7 @@ export class PublishWalkers { if (known !== undefined) return known; const sym = `@sc_pub_${this.counter++}`; this.refusals.set(key, sym); + this.host.journalOpened?.("publish.refusal"); this.host.declare(`declare void @scr_pub_refuse_at(ptr, ptr, ptr)`); this.defsOut.push( `define internal void ${sym}(ptr %o, ptr %ctx) ${FN_ATTRS} { ; refuse ${llvmComment(detail)}`, @@ -181,6 +200,7 @@ export class PublishWalkers { `}`, ``, ); + this.host.journalBuilt?.(); return sym; } diff --git a/packages/compiler/src/backend/llvm/record-results.ts b/packages/compiler/src/backend/llvm/record-results.ts index 47a7983d2..db25016cd 100644 --- a/packages/compiler/src/backend/llvm/record-results.ts +++ b/packages/compiler/src/backend/llvm/record-results.ts @@ -12,20 +12,9 @@ import { import { dynamicFieldStores } from "../../ir/int32-slots.js"; import { everyExpr, everyStmtList, transformStmtList } from "../../ir/traverse.js"; import { InlineUnionFields } from "./inline-unions.js"; +import { RESULT_DST_ID, resultEntryName } from "../result-slots.js"; -/** Prefix of a function's result-slot entry: `%into.(...params, dst)` - * writes the function's fresh result object into `dst` and returns nothing. */ -export const RESULT_ENTRY_PREFIX = "%into."; - -export function resultEntryName(name: string): string { - return `${RESULT_ENTRY_PREFIX}${name}`; -} - -/** The local id of a result-slot entry's destination parameter. The - * caller passes zeroed frame storage, and on every path the entry stores - * each of its fields at most once, so a store into it is an - * initialization: there is no old value to release. */ -export const RESULT_DST_ID = "%into.dst"; +export { RESULT_DST_ID, RESULT_ENTRY_PREFIX, resultEntryName } from "../result-slots.js"; function distinctNames(names: readonly string[]): boolean { return new Set(names).size === names.length; diff --git a/packages/compiler/src/backend/llvm/reference-writes.ts b/packages/compiler/src/backend/llvm/reference-writes.ts index d040e8c93..df2ec5032 100644 --- a/packages/compiler/src/backend/llvm/reference-writes.ts +++ b/packages/compiler/src/backend/llvm/reference-writes.ts @@ -119,6 +119,7 @@ const INERT_LIB_CALLS = new Set([ "worker.parentPort", "worker.root", "cp.spawnSyncOpts", + "cp.spawnSyncEnv", ]); /** jsval conversions (ir/jsval.ts): no user code, no stores. */ diff --git a/packages/compiler/src/backend/llvm/regex-matchers.test.ts b/packages/compiler/src/backend/llvm/regex-matchers.test.ts index 1acd9c465..d009de7c9 100644 --- a/packages/compiler/src/backend/llvm/regex-matchers.test.ts +++ b/packages/compiler/src/backend/llvm/regex-matchers.test.ts @@ -110,6 +110,25 @@ describe("regex literal matcher code", () => { expect(body("a\\d{1,3}")).not.toContain("<16 x i8>"); }); + test("fixed leading characters filter 16 start positions at once", () => { + // Both alternatives' first characters are tested at every offset and + // combined, and the reads reach seven characters past the block. + const text = body("agggtaaa|tttaccct", "gi"); + expect(text.match(/load <16 x i8>/g)!.length).toBeGreaterThanOrEqual(16); + expect(text).toMatch(/and i16 /); + expect(text).toMatch(/or i16 /); + expect(text).toMatch(/add i32 %t\d+, 7\n/); + // A class sequence with a fixed count extends the filter. + expect(body("[cg]x{3}y")).toMatch(/and i16 /); + // An optional first character, a single first character and a + // variable-length start keep the first-character search. + expect(body("[ab]?cd")).not.toMatch(/and i16 /); + expect(body("[ab]*cd")).not.toMatch(/and i16 /); + expect(body("xy|zw")).toMatch(/and i16 /); + expect(body("[ab]|cd")).not.toMatch(/and i16 /); + expect(body("agggtaaa|tttaccct", "gi", false)).not.toContain("<16 x i8>"); + }); + test("loops no continuation can share push no backtrack entries", () => { // \d+ then a dot; [^\]]+ then ]; the run at the end of the pattern. expect(body("\\d+\\.\\d+")).not.toContain("@scr_regex_stack_grow"); diff --git a/packages/compiler/src/backend/llvm/regex-matchers.ts b/packages/compiler/src/backend/llvm/regex-matchers.ts index 001f081e5..d83d6bae5 100644 --- a/packages/compiler/src/backend/llvm/regex-matchers.ts +++ b/packages/compiler/src/backend/llvm/regex-matchers.ts @@ -589,6 +589,90 @@ function firstOf(node: RxNode): FirstInfo { } } +/** Positions the start filter tests and alternatives it keeps. */ +const PREFIX_LENGTH = 8; +const PREFIX_ALTERNATIVES = 8; + +/** The character sets a match's first characters must belong to: every + * match of the node begins with the characters of some entry of `alts`, + * one set per character. `complete` means every match is exactly as long as + * its entry (so a following node continues the sequences). Null when the + * node gives no usable condition (an alternative that can start with + * anything, or too many alternatives). Assertions add no characters: the + * result stays a necessary condition. */ +interface Prefix { + alts: CharSet[][]; + complete: boolean; +} + +/** Each head followed by each tail, cut to PREFIX_LENGTH sets; null past + * PREFIX_ALTERNATIVES entries. */ +function crossPrefixes(heads: CharSet[][], tails: CharSet[][]): CharSet[][] | null { + if (heads.length * tails.length > PREFIX_ALTERNATIVES) return null; + const out: CharSet[][] = []; + for (const head of heads) + for (const tail of tails) out.push([...head, ...tail].slice(0, PREFIX_LENGTH)); + return out; +} + +/** Whether no entry was cut at PREFIX_LENGTH. */ +function uncut(alts: CharSet[][]): boolean { + return alts.every((alt) => alt.length < PREFIX_LENGTH); +} + +function prefixOf(node: RxNode): Prefix | null { + switch (node.kind) { + case "set": + return { alts: [[node.set]], complete: true }; + case "assert": + return { alts: [[]], complete: true }; + case "cap": + return prefixOf(node.body); + case "alt": { + const alts: CharSet[][] = []; + let complete = true; + for (const alt of node.alts) { + const p = prefixOf(alt); + if (p === null) return null; + alts.push(...p.alts); + complete &&= p.complete; + } + return alts.length <= PREFIX_ALTERNATIVES ? { alts, complete } : null; + } + case "seq": { + let alts: CharSet[][] = [[]]; + for (const item of node.items) { + const p = prefixOf(item); + if (p === null) return { alts, complete: false }; + const joined = crossPrefixes(alts, p.alts); + if (joined === null) return { alts, complete: false }; + alts = joined; + if (!p.complete || !uncut(alts)) return { alts, complete: false }; + } + return { alts, complete: true }; + } + case "rep": { + if (node.max === 0) return { alts: [[]], complete: true }; + if (node.min === 0) return { alts: [[]], complete: false }; + const body = prefixOf(node.body); + if (body === null) return null; + // The first `min` iterations are required; they extend the sequences + // while the body has a fixed length. + let alts = body.alts; + let covered = 1; + while (covered < node.min && body.complete && uncut(alts)) { + const joined = crossPrefixes(alts, body.alts); + if (joined === null) break; + alts = joined; + covered++; + } + const complete = + body.complete && covered === node.min && node.min === node.max && uncut(alts); + return { alts, complete }; + } + } +} + /** Whether a node can match without consuming (assertions included). */ function canMatchEmpty(node: RxNode): boolean { switch (node.kind) { @@ -721,16 +805,74 @@ class RxGen { return wide; } + /** The vector plans of a start filter (prefixOf): per alternative, the + * plans of its first sets up to the first set without one. Null unless + * every alternative keeps at least two positions, where the filter is + * more selective than the first character alone. */ + prefixPlans(prefix: Prefix | null): { ranges: number[][]; negate: boolean }[][] | null { + if (prefix === null || !this.vector) return null; + const plans: { ranges: number[][]; negate: boolean }[][] = []; + for (const alt of prefix.alts) { + const row: { ranges: number[][]; negate: boolean }[] = []; + for (const set of alt) { + const plan = this.vectorPlan(set); + if (plan === null) break; + row.push(plan); + } + if (row.length < 2) return null; + plans.push(row); + } + return plans.length === 0 ? null : plans; + } + + /** Start positions s[index..index+16) where some alternative of the + * filter matches its first sets: an i16 mask. */ + testPrefix(plans: { ranges: number[][]; negate: boolean }[][], index: string): string { + let any = ""; + for (const row of plans) { + let all = ""; + for (let k = 0; k < row.length; k++) { + let at = index; + if (k > 0) { + at = this.tmp(); + this.line(`${at} = add i32 ${index}, ${k}`); + } + const bits = this.testVector(row[k]!, at); + if (all === "") all = bits; + else { + const both = this.tmp(); + this.line(`${both} = and i16 ${all}, ${bits}`); + all = both; + } + } + if (any === "") any = all; + else { + const either = this.tmp(); + this.line(`${either} = or i16 ${any}, ${all}`); + any = either; + } + } + return any; + } + /** The first-character search: from %at, store the next position whose - * character is in `set` and branch to %attempt, or branch to %nomatch. */ - emitSeek(set: CharSet): void { + * character is in `set` and branch to %attempt, or branch to %nomatch. + * With a start filter (`prefix`), the vector loop tests the filter's + * first sets of each alternative at 16 start positions at once and stops + * only where one of them matches all of its sets; a match can start + * nowhere else, so the attempts that remain are the ones that can + * succeed, in the same order. */ + emitSeek(set: CharSet, prefix: Prefix | null = null): void { this.block("seek"); const a = this.tmp(); this.line(`${a} = load i32, ptr %at`); + const filter = this.prefixPlans(prefix); const plan = this.vectorPlan(set); + // The filter reads s[i + reach + 15] at its farthest. + const reach = filter === null ? 0 : Math.max(...filter.map((row) => row.length)) - 1; let from = "seek", start = a; - if (plan !== null) { + if (plan !== null || filter !== null) { const head = this.label("vsh"), load = this.label("vsl"), next = this.label("vsn"), @@ -740,17 +882,21 @@ class RxGen { this.block(head); const i = this.tmp(), i16 = this.tmp(), + rest = this.tmp(), fits = this.tmp(); this.line(`${i} = phi i32 [ ${a}, %seek ], [ ${i16}, %${next} ]`); - this.line(`${i16} = add i32 ${i}, 16`); - this.line(`${fits} = icmp sle i32 ${i16}, %len`); + // The characters left (0 <= i <= len, so this cannot wrap; i + 16 + // can for subjects near 2^31 characters). + this.line(`${rest} = sub i32 %len, ${i}`); + this.line(`${fits} = icmp sge i32 ${rest}, ${16 + reach}`); this.line(`br i1 ${fits}, label %${load}, label %${tail}`); this.block(load); - const mask = this.testVector(plan, i), + const mask = filter !== null ? this.testPrefix(filter, i) : this.testVector(plan!, i), any = this.tmp(); this.line(`${any} = icmp ne i16 ${mask}, 0`); this.line(`br i1 ${any}, label %${hit}, label %${next}`); this.block(next); + this.line(`${i16} = add i32 ${i}, 16`); this.line(`br label %${head}`); this.block(hit); const k = this.lowestBit(mask), @@ -1001,10 +1147,10 @@ class RxGen { check = this.label("chk"); this.block(entry); const p = this.loadPos(), - end = this.tmp(), + rest = this.tmp(), inb = this.tmp(); - this.line(`${end} = add i32 ${p}, ${sets.length}`); - this.line(`${inb} = icmp sle i32 ${end}, %len`); + this.line(`${rest} = sub i32 %len, ${p}`); + this.line(`${inb} = icmp sge i32 ${rest}, ${sets.length}`); this.line(`br i1 ${inb}, label %${check}, label %fail`); this.block(check); let acc = ""; @@ -1023,6 +1169,8 @@ class RxGen { acc = both; } } + const end = this.tmp(); + this.line(`${end} = add i32 ${p}, ${sets.length}`); // Storing before the branch is safe: every resume sets the position. this.storePos(end); this.line(`br i1 ${acc}, label %${succ}, label %fail`); @@ -1229,10 +1377,11 @@ class RxGen { this.block(vhead); const kv = this.tmp(), kv16 = this.tmp(), + left = this.tmp(), fits = this.tmp(); this.line(`${kv} = phi i32 [ 0, %${entry} ], [ ${kv16}, %${vnext} ]`); - this.line(`${kv16} = add i32 ${kv}, 16`); - this.line(`${fits} = icmp sle i32 ${kv16}, ${lim}`); + this.line(`${left} = sub i32 ${lim}, ${kv}`); + this.line(`${fits} = icmp sge i32 ${left}, 16`); this.line(`br i1 ${fits}, label %${vload}, label %${tail}`); this.block(vload); const vat = this.tmp(); @@ -1242,6 +1391,7 @@ class RxGen { this.line(`${all} = icmp eq i16 ${mask}, -1`); this.line(`br i1 ${all}, label %${vnext}, label %${vexit}`); this.block(vnext); + this.line(`${kv16} = add i32 ${kv}, 16`); this.line(`br label %${vhead}`); this.block(vexit); const missing = this.tmp(); @@ -1769,7 +1919,10 @@ export function compileRegexMatcher( fn.push(` store i32 %off.n, ptr %at`); fn.push(` br label %attempt`); } else { - gen.emitSeek(first.set); + // A start filter over the first few characters (a single first byte + // keeps memchr). + const prefix = prefixOf(root); + gen.emitSeek(first.set, gen.prefixPlans(prefix) === null ? null : prefix); } } diff --git a/packages/compiler/src/backend/llvm/running-extrema.test.ts b/packages/compiler/src/backend/llvm/running-extrema.test.ts new file mode 100644 index 000000000..4ce307c5c --- /dev/null +++ b/packages/compiler/src/backend/llvm/running-extrema.test.ts @@ -0,0 +1,97 @@ +import { expect, test } from "vitest"; +import { BOOL, F64, type IrExpr, type IrFunction, type IrStmt } from "../../ir/ir.js"; +import { runningExtremumUpdates } from "./running-extrema.js"; + +const loc = { file: "extrema.ts", start: 0, end: 0 }; +const ref = (localId: string): IrExpr => ({ kind: "varRef", localId, type: F64, loc }); +const num = (value: number): IrExpr => ({ kind: "numLit", value, type: F64, loc }); +const assign = (localId: string, value: IrExpr): IrStmt => ({ + kind: "assign", + localId, + value, + loc, +}); +const decl = (localId: string): IrStmt => ({ kind: "varDecl", localId, init: num(0), loc }); +const compare = (op: "<" | ">", left: IrExpr, right: IrExpr): IrExpr => ({ + kind: "bin", + op, + left, + right, + type: BOOL, + loc, +}); +/** `if (v > max) max = v;` */ +const update = (): IrStmt & { kind: "if" } => ({ + kind: "if", + cond: compare(">", ref("v"), ref("max")), + then: [assign("max", ref("v"))], + else_: null, + loc, +}); +const loop = (body: IrStmt[]): IrStmt => ({ + kind: "while", + cond: compare(">", ref("n"), num(0)), + body, + loc, +}); +const fn = (body: IrStmt[], captures: string[] = []): IrFunction => ({ + name: "scan", + params: [], + locals: ["v", "max", "n"].map((id) => ({ id, name: id, type: F64, mutable: true })), + captures: captures.map((localId) => ({ localId, name: localId, type: F64 })), + returnType: F64, + body, + loc, +}); + +test("a loop's update of an accumulator declared outside it qualifies", () => { + const s = update(); + expect(runningExtremumUpdates(fn([decl("max"), loop([decl("v"), s])])).has(s)).toBe(true); +}); + +test("the local may be on either side of the comparison", () => { + const s = update(); + s.cond = compare("<", ref("max"), ref("v")); + expect(runningExtremumUpdates(fn([decl("max"), loop([s])])).has(s)).toBe(true); +}); + +test("a local declared in the loop is not an accumulator", () => { + const s = update(); + expect(runningExtremumUpdates(fn([loop([decl("max"), s])])).size).toBe(0); +}); + +test("another write in the loop disqualifies the update", () => { + const s = update(); + const body = [decl("max"), loop([assign("max", num(1)), s])]; + expect(runningExtremumUpdates(fn(body)).size).toBe(0); +}); + +test("the assigned value must be the compared expression", () => { + const s = update(); + s.then = [assign("max", num(5))]; + expect(runningExtremumUpdates(fn([decl("max"), loop([s])])).size).toBe(0); +}); + +test("outside a loop only a captured binding qualifies", () => { + const captured = update(); + expect(runningExtremumUpdates(fn([captured], ["max"])).has(captured)).toBe(true); + expect(runningExtremumUpdates(fn([update()])).size).toBe(0); +}); + +test("an else branch disqualifies the update", () => { + const s = update(); + s.else_ = [assign("v", num(0))]; + expect(runningExtremumUpdates(fn([decl("max"), loop([s])])).size).toBe(0); +}); + +test("an update nested in another branch does not qualify", () => { + const s = update(); + const guard: IrStmt = { + kind: "if", + cond: compare(">", ref("v"), num(0)), + then: [s], + else_: null, + loc, + }; + expect(runningExtremumUpdates(fn([decl("max"), loop([guard])])).size).toBe(0); +}); diff --git a/packages/compiler/src/backend/llvm/running-extrema.ts b/packages/compiler/src/backend/llvm/running-extrema.ts new file mode 100644 index 000000000..1ddea603d --- /dev/null +++ b/packages/compiler/src/backend/llvm/running-extrema.ts @@ -0,0 +1,110 @@ +// Running maximum and minimum updates, `if (v > max) { max = v; ... }`. +// With the accumulator in a register LLVM turns such an update into a +// select (`maxsd`, or a compare and mask), so every element waits on the +// previous one's. The update gets rarer as a scan goes on, so a branch +// predicts well; emitStmtBody gives these `if`s branch weights that say the +// update is rarely taken, and LLVM keeps the branch. A clamp of a value read +// in the same iteration is not an accumulator and keeps its select: its +// branch would go whichever way the data goes. An update nested in another +// branch keeps its select too: kept, its branch can stop LLVM from turning +// the enclosing branch into selects, and that branch may follow the data. + +import type { IrExpr, IrFunction, IrStmt } from "../../ir/ir.js"; +import { everyExprChild, everyStmtChild } from "../../ir/traverse.js"; + +type Loop = IrStmt & { kind: "for" | "while" | "doWhile" | "forOf" }; + +const RELATIONAL = new Set(["<", "<=", ">", ">="]); + +/** The `if` statements of `fn` that update a running maximum or minimum: + * no `else`, a numeric `<`, `<=`, `>` or + * `>=` between a local and another expression, and a then-block that + * assigns that expression to the local. The local must carry across + * iterations: inside a loop the `if` is a statement of the innermost loop's + * body, the local is declared outside that loop, and the loop writes it only + * in this `if`; outside any loop the `if` is a statement of the function + * body and the local is a binding the function captures and writes only in + * this `if` (a callback that a loop elsewhere calls). */ +export function runningExtremumUpdates(fn: IrFunction): Set { + const found = new Set(); + const captured = new Set((fn.captures ?? []).map((c) => c.localId)); + const loops: Loop[] = []; + const candidates: { s: IrStmt; local: string; loop: Loop | undefined }[] = []; + const expr = (e: IrExpr): boolean => everyExprChild(e, expr, stmt); + const stmt = (s: IrStmt): boolean => { + if (s.kind === "if") { + const local = updatedExtremum(s); + if (local !== undefined) candidates.push({ s, local, loop: loops[loops.length - 1] }); + } + const loop = + s.kind === "for" || s.kind === "while" || s.kind === "doWhile" || s.kind === "forOf"; + if (loop) loops.push(s); + everyStmtChild(s, expr, stmt); + if (loop) loops.pop(); + return true; + }; + for (const s of fn.body) stmt(s); + for (const { s, local, loop } of candidates) { + const scope = loop ?? (captured.has(local) ? fn.body : undefined); + const body = loop ? loop.body : fn.body; + if (scope !== undefined && body.includes(s) && writes(scope, local) === 1) found.add(s); + } + return found; +} + +/** The local an `if` updates to a new maximum or minimum, if it is one. */ +function updatedExtremum(s: IrStmt & { kind: "if" }): string | undefined { + if (s.else_ !== null && s.else_.length > 0) return undefined; + const c = s.cond; + if (c.kind !== "bin" || !RELATIONAL.has(c.op)) return undefined; + if (c.left.type.kind !== "f64" || c.right.type.kind !== "f64") return undefined; + for (const [local, other] of [ + [c.left, c.right], + [c.right, c.left], + ]) { + if (local!.kind !== "varRef") continue; + const id = local!.localId; + const assigns = s.then.some( + (x) => x.kind === "assign" && x.localId === id && sameExpr(x.value, other!), + ); + if (assigns) return id; + } + return undefined; +} + +/** Declarations and writes of `local` under `scope`. A declaration counts + * as a write too, so a local declared inside a loop does not qualify. */ +function writes(scope: IrStmt | IrStmt[], local: string): number { + let n = 0; + const expr = (e: IrExpr): boolean => { + if ((e.kind === "assignExpr" || e.kind === "incDec") && e.localId === local) n++; + return everyExprChild(e, expr, stmt); + }; + const stmt = (s: IrStmt): boolean => { + if ((s.kind === "assign" || s.kind === "varDecl" || s.kind === "forOf") && s.localId === local) + n++; + else if (s.kind === "tryCatch" && s.catchLocalId === local) n++; + return everyStmtChild(s, expr, stmt); + }; + if (Array.isArray(scope)) for (const s of scope) stmt(s); + else stmt(scope); + return n; +} + +/** Structural equality of two small expressions (`v`, `a[i]`), ignoring + * source locations and types; larger expressions do not compare equal. */ +function sameExpr(a: IrExpr, b: IrExpr): boolean { + let budget = 64; + const same = (x: unknown, y: unknown): boolean => { + if (--budget < 0) return false; + if (typeof x !== "object" || x === null || typeof y !== "object" || y === null) return x === y; + if (Array.isArray(x) !== Array.isArray(y)) return false; + const keys = Object.keys(x).filter((k) => k !== "loc" && k !== "type"); + if (keys.length !== Object.keys(y).filter((k) => k !== "loc" && k !== "type").length) + return false; + return keys.every((k) => + same((x as Record)[k], (y as Record)[k]), + ); + }; + return same(a, b); +} diff --git a/packages/compiler/src/backend/llvm/shapes.test.ts b/packages/compiler/src/backend/llvm/shapes.test.ts index 347099c16..f7327a688 100644 --- a/packages/compiler/src/backend/llvm/shapes.test.ts +++ b/packages/compiler/src/backend/llvm/shapes.test.ts @@ -6,8 +6,9 @@ import { emitRecordShapes, inlineRcDecls, INLINE_DYN_RELEASES_PER_FUNCTION, + INLINE_STR_RELEASES_PER_FUNCTION, inlineRcOption, - limitInlineDynReleases, + limitInlineReleases, releaseSym, retainSym, type ShapeHost, @@ -132,10 +133,10 @@ describe("LLVM runtime RC symbols", () => { ]); }); - test("release builds inline only string retains and dyn retains and releases", () => { + test("release builds inline only string and dyn retains and releases and Map retains", () => { const { host } = declarationHost(64, "release"); expect(retainSym(host, { kind: "string" })).toBe("@sc_rc_retain_str"); - expect(releaseSym(host, { kind: "string" })).toBe("@scr_str_release"); + expect(releaseSym(host, { kind: "string" })).toBe("@sc_rc_release_str"); expect(retainSym(host, { kind: "dyn" })).toBe("@sc_rc_retain_dyn"); expect(releaseSym(host, { kind: "dyn" })).toBe("@sc_rc_release_dyn"); expect(releaseSym(host, { kind: "union", unionId: "u0" } as never)).toBe("@scr_union_release"); @@ -251,12 +252,12 @@ describe("LLVM runtime RC symbols", () => { }); }); -describe("inline dyn release budget", () => { - const body = (name: string, sites: number): string => +describe("inline release budgets", () => { + const body = (name: string, sites: number, family = "dyn"): string => [ `define internal void @${name}(ptr %v) #0 {`, "entry:", - ...Array.from({ length: sites }, () => " call void @sc_rc_release_dyn(ptr %v)"), + ...Array.from({ length: sites }, () => ` call void @sc_rc_release_${family}(ptr %v)`), " ret void", "}", "", @@ -266,7 +267,9 @@ describe("inline dyn release budget", () => { const small = body("small", INLINE_DYN_RELEASES_PER_FUNCTION); const large = body("large", INLINE_DYN_RELEASES_PER_FUNCTION + 1); // main's lines are separate parts. - const limited = limitInlineDynReleases([`; header\n${small}`, ...large.split("\n")]).join("\n"); + const limited = limitInlineReleases([`; header\n${small}`, ...large.split("\n")], "speed").join( + "\n", + ); expect(limited.startsWith("; header\n")).toBe(true); expect(limited).toContain(small); const out = limited.slice(limited.indexOf("@large(")); @@ -275,6 +278,20 @@ describe("inline dyn release budget", () => { INLINE_DYN_RELEASES_PER_FUNCTION + 1, ); }); + + test("a function over the string budget calls the runtime string release at every site", () => { + const small = body("small", INLINE_STR_RELEASES_PER_FUNCTION, "str"); + const large = body("large", INLINE_STR_RELEASES_PER_FUNCTION + 1, "str"); + const limited = limitInlineReleases([small, large], "release").join("\n"); + expect(limited).toContain(small); + // Speed emission keeps every inline string release. + expect(limitInlineReleases([small, large], "speed").join("\n")).toBe([small, large].join("\n")); + const out = limited.slice(limited.indexOf("@large(")); + expect(out).not.toContain("@sc_rc_release_str("); + expect(out.split("call void @scr_str_release(ptr %v)").length - 1).toBe( + INLINE_STR_RELEASES_PER_FUNCTION + 1, + ); + }); }); describe("emitted object releases", () => { diff --git a/packages/compiler/src/backend/llvm/shapes.ts b/packages/compiler/src/backend/llvm/shapes.ts index 6de92f667..d13f80a78 100644 --- a/packages/compiler/src/backend/llvm/shapes.ts +++ b/packages/compiler/src/backend/llvm/shapes.ts @@ -68,9 +68,26 @@ const CYC_MAX_TYPES = 32768; /** What the tables need from the emitter: the extern-declaration ledger * and the module-wide cycle/shape indexes. */ export interface ShapeHost { + /** Chunk emitters only (emit-journal.ts): EmitJournal's allocated, built, + * opened, used and entry. */ + journalAllocated?: ((name: string, op: string, args: readonly unknown[]) => void) | undefined; + journalBuilt?: (() => void) | undefined; + journalOpened?: ((op: string) => void) | undefined; + journalUsed?: ((name: string, op: string, args: readonly unknown[]) => void) | undefined; + journalEntry?: ((table: string, key: string, value: unknown) => void) | undefined; /** The hierarchy root of a class (a program class or a runtime base), * or undefined for classes outside the class graph. */ classRootOf?(className: string): string | undefined; + /** Whether releasing a value of this type does nothing: instances of a + * program-lifetime class without lifetime regions (classes.ts + * programLifetimeClass). */ + releasesNothing?(t: IrType): boolean; + /** Whether arrays of `elem` hold 32-bit references to compact class + * instances (SCR_ELEM_CREF; LlEmitter.compactArrayElem). */ + compactArrayElem?(elem: IrType): boolean; + /** Whether compact class instances live in the program-lifetime region + * (LlEmitter.compactRegion). */ + compactRegion?(): boolean; /** Byte offset from an object pointer back to ScrCycHdr.buf. */ readonly cycleBufOffset: number; declare(decl: string): void; @@ -386,6 +403,7 @@ function nullableRetainSym(host: ShapeHost, arm: IrType): string { const sym = `@sc_nretain_${arm.kind}`; if (!host.nullableUnions.retainWrappers.has(sym)) host.nullableUnions.retainWrappers.set(sym, retainSym(host, arm)); + host.journalEntry?.("retainWrapper", sym, host.nullableUnions.retainWrappers.get(sym)); return sym; } @@ -564,14 +582,18 @@ export function inlineRcFamily(host: ShapeHost, stem: string, op: RcOp): InlineR } /** Which RC fast paths an emission inlines. `speed` mirrors every family - * with a fast path. `release` mirrors only the string retain and the dyn - * retain and release: the operations that dominate dynamic-value and string - * code, at almost no size cost. String releases stay calls in `release` - * because string-heavy programs have many release sites. */ + * with a fast path. `release` mirrors only the string retain and release, + * the Map retain and the dyn retain and release: the operations that + * dominate dynamic-value, string and Map code (a Map read from an array or + * another Map). String-heavy programs have many string release sites, so a + * function with more than INLINE_STR_RELEASES_PER_FUNCTION of them calls the + * runtime release at each (limitInlineReleases). */ export type InlineRcMode = "release" | "speed"; const RELEASE_RC_OPS = new Set([ "str:retain", + "str:release", + "map:retain", "dyn:retain", "dyn:release", "js:retain", @@ -654,12 +676,34 @@ function inlineRcName(family: string, op: RcOp): string { * the inline helper mirrors, at every site. */ export const INLINE_DYN_RELEASES_PER_FUNCTION = 256; -/** Apply {@link INLINE_DYN_RELEASES_PER_FUNCTION} to each function of an - * emitted module, given as parts joined by newlines. A function can span - * parts (main's lines) and a part can hold several functions. */ -export function limitInlineDynReleases(parts: readonly string[]): string[] { - const call = `call void @${inlineRcName("dyn", "release")}(`; - const runtime = `call void @${INLINE_RC_FAMILIES["dyn"]!.release}(`; +/** Inlined string releases one function body keeps in `release` emission, + * which inlines string releases (RELEASE_RC_OPS); the bodies with the most of them, such as + * builders of string-heavy records and module initializers, would grow the + * most for the least gain, so a body with more calls scr_str_release at + * every site. */ +export const INLINE_STR_RELEASES_PER_FUNCTION = 8; + +/** Apply {@link INLINE_DYN_RELEASES_PER_FUNCTION}, and in `release` emission + * {@link INLINE_STR_RELEASES_PER_FUNCTION}, to each function of an emitted + * module, given as parts joined by newlines. A function can span parts + * (main's lines) and a part can hold several functions. */ +export function limitInlineReleases( + parts: readonly string[], + mode: InlineRcMode | undefined, +): string[] { + const dyn = limitInlineReleaseFamily(parts, "dyn", INLINE_DYN_RELEASES_PER_FUNCTION); + return mode === "release" + ? limitInlineReleaseFamily(dyn, "str", INLINE_STR_RELEASES_PER_FUNCTION) + : dyn; +} + +function limitInlineReleaseFamily( + parts: readonly string[], + family: "dyn" | "str", + max: number, +): string[] { + const call = `call void @${inlineRcName(family, "release")}(`; + const runtime = `call void @${INLINE_RC_FAMILIES[family]!.release}(`; // The function each release site belongs to: the last `define` line // before it, counted over the joined text. const sites = ( @@ -685,9 +729,7 @@ export function limitInlineDynReleases(parts: readonly string[]): string[] { const counts = new Map(); let fn = 0; for (const part of parts) fn = sites(part, (_, f) => counts.set(f, (counts.get(f) ?? 0) + 1), fn); - const over = new Set( - [...counts].filter(([, n]) => n > INLINE_DYN_RELEASES_PER_FUNCTION).map(([f]) => f), - ); + const over = new Set([...counts].filter(([, n]) => n > max).map(([f]) => f)); if (over.size === 0) return [...parts]; fn = 0; return parts.map((part) => { @@ -1076,18 +1118,41 @@ export function arrNewCall( /** The %ScrArrOps descriptor (retain, release, trace, registry id) of a REF * element type, defined once per module and shared by all its arrays. It is - * writable: the runtime stores its registry id on the first array. */ + * writable: the runtime stores its registry id on the first array. Its tail + * padding is the runtime's flags word (0); arrays of compact class + * references (ShapeHost.compactArrayElem) spell the word out as + * SCR_ARR_OPS_COMPACT, and on 64-bit targets arrays whose element release + * does nothing (ShapeHost.releasesNothing) as SCR_ARR_OPS_RELEASE_NOTHING, + * so that destroying them only frees their storage. */ export function arrOps(host: ShapeHost, elem: IrType): string { const v = vAdapters(host, elem); const trace = traceArg(host, elem); const part = (sym: string): string => sym.replace(/^@/, "").replace(/[^A-Za-z0-9_.]/g, "_"); const name = `@sc_arrops.${part(v.retain)}.${part(v.release)}.${part(trace)}`; + if (host.compactArrayElem?.(elem) === true) { + host.declare( + `${name}.c = internal global { ptr, ptr, ptr, i32, i32 } { ptr ${v.retain}, ptr ${v.release}, ptr ${trace}, i32 0, i32 ${SCR_ARR_OPS_COMPACT} }`, + ); + return `${name}.c`; + } + const nullable = host.nullableUnions.of(elem); + const payload = nullable?.repr === "single" ? nullable.arm : elem; + if (host.sizeType === "i64" && host.releasesNothing?.(payload) === true) { + host.declare( + `${name}.n = internal global { ptr, ptr, ptr, i32, i32 } { ptr ${v.retain}, ptr ${v.release}, ptr ${trace}, i32 0, i32 ${SCR_ARR_OPS_RELEASE_NOTHING} }`, + ); + return `${name}.n`; + } host.declare( `${name} = internal global %ScrArrOps { ptr ${v.retain}, ptr ${v.release}, ptr ${trace}, i32 0 }`, ); return name; } +/** scr_array.h SCR_ARR_OPS_COMPACT and SCR_ARR_OPS_RELEASE_NOTHING. */ +const SCR_ARR_OPS_COMPACT = 1; +const SCR_ARR_OPS_RELEASE_NOTHING = 2; + /* ── capture boxes ────────────────────────────────────────────────────── */ /** Box construction call text (boxNewC's dispatch): plain-kind boxes for diff --git a/packages/compiler/src/backend/llvm/string-reads.ts b/packages/compiler/src/backend/llvm/string-reads.ts index 03a9fa282..441c925f3 100644 --- a/packages/compiler/src/backend/llvm/string-reads.ts +++ b/packages/compiler/src/backend/llvm/string-reads.ts @@ -17,6 +17,7 @@ * is thread-local. */ +import type { LlvmEmitterContext } from "./expr-context.js"; import { exactIndexLines, sizeToDouble } from "./common.js"; import { wtf8Bytes } from "../literals.js"; import { literalCapWord, literalCapWord32 } from "./string-key-hash.js"; @@ -37,6 +38,66 @@ export const STRING_CHAR_AT_DECL = "declare ptr @scr_str_char_at(ptr, double)"; /** Requests the integer-index charAt helper, as the marker above does. */ export const STRING_CHAR_AT_INT_MARKER = "; uses @sc_str_char_at_int"; +/** The proven-ASCII flag of string `s`, as an i1. */ +export function emitStringAsciiFlag(host: LlvmEmitterContext, s: string): string { + const B = host.B; + const wordPointer = B.tmp(), + word = B.tmp(), + ascii = B.tmp(); + B.line(`${wordPointer} = getelementptr inbounds %ScrStr, ptr ${s}, i32 0, i32 2`); + B.line(`${word} = load i32, ptr ${wordPointer}`); + B.line(`${ascii} = icmp slt i32 ${word}, 0`); + return ascii; +} + +/** The byte length of string `s`, as the target's size type. */ +export function emitStringByteLength(host: LlvmEmitterContext, s: string): string { + const B = host.B; + const lengthPointer = B.tmp(), + length = B.tmp(); + B.line(`${lengthPointer} = getelementptr inbounds %ScrStr, ptr ${s}, i32 0, i32 1`); + B.line(`${length} = load ${host.sizeType}, ptr ${lengthPointer}`); + return length; +} + +/** Unit `index` (an i64) of a proven-ASCII string `s` whose length covers + * it: one byte load, as a double. */ +export function emitAsciiCharCode(host: LlvmEmitterContext, s: string, index: string): string { + const B = host.B; + const data = B.tmp(), + pointer = B.tmp(), + byte = B.tmp(), + code = B.tmp(); + B.line(`${data} = getelementptr inbounds %ScrStr, ptr ${s}, i32 1`); + B.line(`${pointer} = getelementptr inbounds i8, ptr ${data}, i64 ${index}`); + B.line(`${byte} = load i8, ptr ${pointer}`); + B.line(`${code} = uitofp i8 ${byte} to double`); + return code; +} + +/** The one-character string of unit `index` (an i64) of a proven-ASCII + * string `s` whose length covers it: the immortal `@sc_ascii_chars` entry + * for its byte, as the inline charAt helpers answer. */ +export function emitAsciiChar(host: LlvmEmitterContext, s: string, index: string): string { + // The table is defined with sc_str_char_at. + host.declare(STRING_CHAR_AT_DECL); + const B = host.B; + const sz = host.sizeType; + const data = B.tmp(), + pointer = B.tmp(), + byte = B.tmp(), + code = B.tmp(), + entry = B.tmp(); + B.line(`${data} = getelementptr inbounds %ScrStr, ptr ${s}, i32 1`); + B.line(`${pointer} = getelementptr inbounds i8, ptr ${data}, i64 ${index}`); + B.line(`${byte} = load i8, ptr ${pointer}`); + B.line(`${code} = zext i8 ${byte} to i64`); + B.line( + `${entry} = getelementptr inbounds [128 x { ${sz}, ${sz}, ${sz}, [2 x i8] }], ptr @sc_ascii_chars, i64 0, i64 ${code}`, + ); + return entry; +} + /** Load the proven-ASCII flag of `%s` into `%ascii`. */ function asciiTest(): string[] { return [ diff --git a/packages/compiler/src/backend/llvm/walkers.ts b/packages/compiler/src/backend/llvm/walkers.ts index 46dbc86e1..044cb79ae 100644 --- a/packages/compiler/src/backend/llvm/walkers.ts +++ b/packages/compiler/src/backend/llvm/walkers.ts @@ -62,6 +62,21 @@ export class LlWalkers { constructor(private readonly host: WalkerHost) {} + /** Journal replay (emit-journal.ts): builds or finds the helper a chunk + * emitter recorded, and answers its name. */ + replayHelper(op: string, args: readonly unknown[]): string { + switch (op) { + case "walkers.jsonWriteHelper": + return this.jsonWriteHelper(args[0] as IrType); + case "walkers.recordFieldWriter": + return this.recordFieldWriter(args[0] as string); + case "walkers.unionJoinHelper": + return this.unionJoinHelper(args[0] as string); + default: + throw new InternalCompilerError(`llvm emitter bug: no walker replay ${op}`); + } + } + private get S(): "i32" | "i64" { return this.host.sizeType; } @@ -191,6 +206,7 @@ export class LlWalkers { if (existing) return existing; const name = `sc_jw_${this.jsonWriters.size}`; this.jsonWriters.set(key, name); + this.host.journalAllocated?.(name, "walkers.jsonWriteHelper", [t]); const B = new BlockBuilder(); switch (t.kind) { case "f64": @@ -244,6 +260,7 @@ export class LlWalkers { `}`, ``, ); + this.host.journalBuilt?.(); return name; } @@ -457,6 +474,7 @@ export class LlWalkers { throw new InternalCompilerError(`llvm emitter bug: field writer of unknown shape ${shapeId}`); const name = `sc_jwf_${this.recordFieldWriters.size}`; this.recordFieldWriters.set(shapeId, name); + this.host.journalAllocated?.(name, "walkers.recordFieldWriter", [shapeId]); const fieldBase = this.host.nullableUnions.fieldBase(shapeId); const fieldIndex = new Map(shape.fields.map((f, i) => [f.name, i + fieldBase])); const byName = new Map(shape.fields.map((f) => [f.name, f])); @@ -508,6 +526,7 @@ export class LlWalkers { `}`, ``, ); + this.host.journalBuilt?.(); return name; } @@ -852,6 +871,7 @@ export class LlWalkers { if (!def) throw new InternalCompilerError(`llvm emitter bug: join of unknown union ${unionId}`); const name = `sc_uj_${this.unionJoinFns.size}`; this.unionJoinFns.set(unionId, name); + this.host.journalAllocated?.(name, "walkers.unionJoinHelper", [unionId]); const host = this.host; host.declare(`declare void @scr_jb_init(ptr)`); @@ -946,6 +966,7 @@ export class LlWalkers { `}`, ``, ); + this.host.journalBuilt?.(); return name; } } diff --git a/packages/compiler/src/backend/llvm/wrapping-sums.ts b/packages/compiler/src/backend/llvm/wrapping-sums.ts index b00b61cbb..c736fcf72 100644 --- a/packages/compiler/src/backend/llvm/wrapping-sums.ts +++ b/packages/compiler/src/backend/llvm/wrapping-sums.ts @@ -1,4 +1,5 @@ -import type { IrExpr } from "../../ir/ir.js"; +import type { IrExpr, IrFunction, IrStmt } from "../../ir/ir.js"; +import { everyExprChild, everyStmtChild } from "../../ir/traverse.js"; import { integerArithmeticRange, type IntegerRange } from "../../ir/integer-ranges.js"; import type { LlValue, LlvmEmitterContext } from "./expr-context.js"; import type { LlInteger } from "./integer-values.js"; @@ -47,6 +48,7 @@ export function integerOrNaNRange(host: LlvmEmitterContext, e: IrExpr): IntegerR return ELEMENT_RANGES.i32!; // A UTF-16 code unit, or NaN past either end. if (e.kind === "strIntrinsic" && e.method === "charCodeAt") return { min: 0, max: 65535 }; + if (e.kind === "varRef") return host.integerOrNaNLocals.get(e.localId) ?? null; if (e.kind === "bin" && (e.op === "+" || e.op === "-")) { const left = integerOrNaNRange(host, e.left); const right = left && integerOrNaNRange(host, e.right); @@ -55,6 +57,34 @@ export function integerOrNaNRange(host: LlvmEmitterContext, e: IrExpr): IntegerR return null; } +/** An index that is an exact integer or NaN (`integerOrNaNRange`): the integer as an i64, and an + * i1 that is false when the index is NaN. An index check then needs no round trip through a double: + * the integer is the value's ToUint32 view where the range proves it holds the whole value, or one + * conversion, which is exact for a safe integer and frozen, since the conversion of NaN is poison. + * Null for any other index. */ +export function integerOrNaNIndex( + host: LlvmEmitterContext, + value: LlValue, + expr: IrExpr | undefined, +): { wide: string; ordered: string } | null { + const range = expr ? integerOrNaNRange(host, expr) : null; + if (!range) return null; + const B = host.B; + const ordered = B.tmp(); + const wide = B.tmp(); + B.line(`${ordered} = fcmp ord double ${value.name}, 0.0`); + if (value.uint32 !== undefined && range.min >= 0 && range.max <= 4294967295) { + B.line(`${wide} = zext i32 ${value.uint32} to i64`); + } else if (value.uint32 !== undefined && range.min >= -2147483648 && range.max <= 2147483647) { + B.line(`${wide} = sext i32 ${value.uint32} to i64`); + } else { + const raw = B.tmp(); + B.line(`${raw} = fptosi double ${value.name} to i64`); + B.line(`${wide} = freeze i64 ${raw}`); + } + return { wide, ordered }; +} + const ELEMENT_RANGES: Partial> = { u8: { min: 0, max: 255 }, u8c: { min: 0, max: 255 }, @@ -131,3 +161,85 @@ export function emitWrappingSum( B.line(`${out} = select i1 ${valid}, i32 ${sum}, i32 0`); return out; } + +/** The number locals of `fn` that only hold exact integers (never -0) or NaN, with the range of + * those integers: locals declared once with an initializer, neither parameters nor captured or + * boxed, whose initializer and every later write `integerOrNaNRange` covers. A local joins once + * the values it is written depend only on locals that have joined, so `x = x + 1` keeps `x` out: + * its values have no bound. Uses the function's `integerRanges` and `int32Elements`. */ +export function findIntegerOrNaNLocals( + host: LlvmEmitterContext, + fn: IrFunction, +): ReadonlyMap { + const found = new Map(); + if (fn.async || fn.generator) return found; + const excluded = new Set(); + for (const param of fn.params) excluded.add(param.localId); + for (const capture of fn.captures ?? []) excluded.add(capture.localId); + for (const capture of fn.classCaptures ?? []) excluded.add(capture.localId); + const candidates = new Set(); + for (const local of fn.locals) + if (local.type.kind === "f64" && !local.boxed && !local.tdz && !excluded.has(local.id)) + candidates.add(local.id); + if (candidates.size === 0) return found; + const declared = new Set(); + const writes = new Map(); + const drop = (id: string): void => { + candidates.delete(id); + writes.delete(id); + }; + const write = (id: string, value: IrExpr): void => { + if (!candidates.has(id)) return; + const list = writes.get(id); + if (list) list.push(value); + else writes.set(id, [value]); + }; + function walkExpr(e: IrExpr): boolean { + if (e.kind === "assignExpr") write(e.localId, e.value); + else if (e.kind === "incDec") drop(e.localId); + return everyExprChild(e, walkExpr, walkStmt); + } + function walkStmt(s: IrStmt): boolean { + if (s.kind === "assign") write(s.localId, s.value); + else if (s.kind === "varDecl") { + if (s.init === null || declared.has(s.localId)) drop(s.localId); + else { + declared.add(s.localId); + write(s.localId, s.init); + } + } else if (s.kind === "forOf") drop(s.localId); + else if (s.kind === "tryCatch" && s.catchLocalId) drop(s.catchLocalId); + return everyStmtChild(s, walkExpr, walkStmt); + } + for (const s of fn.body) walkStmt(s); + // `integerOrNaNRange` reads the joined locals while the next ones are tested. + const previous = host.integerOrNaNLocals; + host.integerOrNaNLocals = found; + try { + let joined = true; + while (joined) { + joined = false; + for (const [id, values] of writes) { + if (found.has(id) || !declared.has(id)) continue; + let range: IntegerRange | null = null; + for (const value of values) { + const next = integerOrNaNRange(host, value); + if (next === null) { + range = null; + break; + } + range = + range === null + ? next + : { min: Math.min(range.min, next.min), max: Math.max(range.max, next.max) }; + } + if (range === null) continue; + found.set(id, range); + joined = true; + } + } + } finally { + host.integerOrNaNLocals = previous; + } + return found; +} diff --git a/packages/compiler/src/backend/may-throw.ts b/packages/compiler/src/backend/may-throw.ts index b72dc545d..a04cce856 100644 --- a/packages/compiler/src/backend/may-throw.ts +++ b/packages/compiler/src/backend/may-throw.ts @@ -35,7 +35,12 @@ export type MayThrowReason = * and a generator's `.return()` unwind through `catch`. */ export function computeMayThrow( mod: IrModule, - options: { stackChecks?: boolean; explain?: boolean } = {}, + options: { + stackChecks?: boolean; + explain?: boolean; + /** computePublishedTypes(mod), when the caller already has it. */ + published?: ReturnType; + } = {}, ): { fns: Set; /** With `explain`: the reason each may-throw function was marked. */ @@ -50,7 +55,8 @@ export function computeMayThrow( const terminations = mod.workers === true ? workerTerminationPolls(mod) : null; const stackChecks = options.stackChecks === true ? stackCheckedFunctions(mod) : null; // Stores that can reach a published object throw the frozen TypeError. - const published = computePublishedTypes(mod); + const published = + options.published !== undefined ? options.published : computePublishedTypes(mod); interface Facts { throws: boolean; callees: string[]; diff --git a/packages/compiler/src/backend/native-link-info-core.ts b/packages/compiler/src/backend/native-link-info-core.ts index a476e1f7f..5782f091d 100644 --- a/packages/compiler/src/backend/native-link-info-core.ts +++ b/packages/compiler/src/backend/native-link-info-core.ts @@ -84,12 +84,22 @@ export interface NativeLinkFeatures { foreignFfi: boolean; nodeTest: boolean; tls: boolean; - /** crypto.createCipheriv/createDecipheriv: scr_cipher.c plus the mbedTLS - * archive. */ + /** crypto.createCipheriv/createDecipheriv and WebCrypto's encrypt and + * decrypt: scr_cipher.c plus the mbedTLS archive (and, with webcrypto, + * scr_webcrypto_aes.c). */ cipher: boolean; /** crypto.createECDH and ECDH.convertKey: scr_ecdh.c plus the mbedTLS * archive. */ ecdh: boolean; + /** crypto.createDiffieHellman, getDiffieHellman and + * createDiffieHellmanGroup: scr_dh.c plus the mbedTLS archive. */ + dh: boolean; + /** Asymmetric KeyObjects, crypto.sign/verify and Sign/Verify: scr_pki.c + * plus the mbedTLS archive. */ + pki: boolean; + /** Ed25519 keys and signatures with pki: scr_ed25519.c (the vendored + * libsodium Ed25519). */ + ed25519: boolean; /** perf_hooks event-loop metrics: scr_perf_loop.c. */ perfLoop: boolean; tlsCa: boolean; diff --git a/packages/compiler/src/backend/native/contracts.ts b/packages/compiler/src/backend/native/contracts.ts index 06a41c9b2..f683ede3e 100644 --- a/packages/compiler/src/backend/native/contracts.ts +++ b/packages/compiler/src/backend/native/contracts.ts @@ -6,6 +6,10 @@ export interface CcOptions { * LLVM backend's .ll — clang compiles IR text natively on the same * command line, so both ride this one seat. */ cPath: string; + /** Where the program TU's bytes are read from, when that is not `cPath`: an invocation-private + * copy that a concurrent build of another program cannot replace. `cPath` stays the spelling + * clang sees (`__FILE__`, debug file names) and the one cache keys name. */ + cSourcePath?: string; /** Path of the native executable to produce. */ outPath: string; /** Additional identity for a translation unit whose complete non-system @@ -243,12 +247,23 @@ export interface CcOptions { * The unit also compiles whenever `tls` does — scr_tls.c consults its * default-set override and shared Windows-certificate enumerator. */ tlsCa?: boolean; - /** crypto.createCipheriv/createDecipheriv: compiles scr_cipher.c and links - * the mbedTLS archive (shared with tls). */ + /** crypto.createCipheriv/createDecipheriv and WebCrypto's encrypt and + * decrypt: compiles scr_cipher.c (and, with webcrypto, + * scr_webcrypto_aes.c) and links the mbedTLS archive (shared with tls). */ cipher?: boolean; /** crypto.createECDH and ECDH.convertKey: compiles scr_ecdh.c and links * the mbedTLS archive (shared with tls). */ ecdh?: boolean; + /** crypto.createDiffieHellman, getDiffieHellman and + * createDiffieHellmanGroup: compiles scr_dh.c and links the mbedTLS + * archive (shared with tls). */ + dh?: boolean; + /** Asymmetric KeyObjects and signatures: compiles scr_pki.c and links + * the mbedTLS archive. */ + pki?: boolean; + /** Ed25519 with pki: compiles scr_ed25519.c (the vendored libsodium + * Ed25519). */ + ed25519?: boolean; /** crypto.subtle importKey/sign/verify/digest: compiles scr_webcrypto.c. */ webcrypto?: boolean; /** perf_hooks event-loop metrics: compiles scr_perf_loop.c. */ diff --git a/packages/compiler/src/backend/native/executable.ts b/packages/compiler/src/backend/native/executable.ts index a551ad600..1b90bb1f1 100644 --- a/packages/compiler/src/backend/native/executable.ts +++ b/packages/compiler/src/backend/native/executable.ts @@ -114,6 +114,8 @@ interface RuntimeUnitContext { tlsCa: boolean; cipher: boolean; ecdh: boolean; + dh: boolean; + pki: boolean; lreObjects: readonly string[]; zlibObjects: readonly string[]; tlsArchive: string | null; @@ -279,6 +281,11 @@ const RUNTIME_UNITS: readonly RuntimeUnit[] = [ unit((u) => u.opts.handleProps === true, "scr_dyn_handle_props.c"), // for await over checked-dynamic values. unit((u) => u.opts.dynForAwait === true, "scr_dyn_for_await.c"), + // for await over checked-dynamic values that may hold native streams. + unit( + (u) => u.opts.dynForAwait === true && u.opts.stream && u.opts.dynAsync, + "scr_dyn_for_await_stream.c", + ), // FileHandle streams reference both the stream unit and FileHandle. unit((u) => u.opts.stream && u.opts.fileHandle, "scr_fs_stream_fh.c"), // The readiness-poller backends (scr_platform.h): kqueue on macOS/BSD, @@ -297,6 +304,10 @@ const RUNTIME_UNITS: readonly RuntimeUnit[] = [ unit((u) => u.opts.foreignFfi, "scr_ffi_queue.c"), unit((u) => u.opts.nodeTest, "scr_test.c"), unit((u) => u.opts.webcrypto, "scr_webcrypto.c"), + unit((u) => u.opts.webcrypto === true && u.opts.pki === true, "scr_webcrypto_pki.c"), + unit((u) => u.opts.pki === true && u.opts.ed25519 === true, "scr_ed25519.c"), + // The crypto global's object extends scr_async_dyn.c's. + unit((u) => u.opts.webcrypto && u.opts.dynAsync, "scr_webcrypto_object.c"), // The CA-store unit rides its own gate OR the tls one: scr_tls.c // references its default-set override unconditionally. unit((u) => u.tlsCa, "scr_tls_ca.c"), @@ -308,6 +319,9 @@ const RUNTIME_UNITS: readonly RuntimeUnit[] = [ ...(u.tls ? [u.rt(join(u.rtDir, "scr_tls.c"))] : []), ...(u.cipher ? [u.rt(join(u.rtDir, "scr_cipher.c"))] : []), ...(u.ecdh ? [u.rt(join(u.rtDir, "scr_ecdh.c"))] : []), + ...(u.dh ? [u.rt(join(u.rtDir, "scr_dh.c"))] : []), + ...(u.pki ? [u.rt(join(u.rtDir, "scr_pki.c"))] : []), + ...(u.cipher && u.opts.webcrypto ? [u.rt(join(u.rtDir, "scr_webcrypto_aes.c"))] : []), u.tlsArchive, // mbedTLS's win32 entropy poll is BCryptGenRandom (bcrypt.h). // The unconditional win32 libs above do not carry it. @@ -323,6 +337,8 @@ const RUNTIME_UNITS: readonly RuntimeUnit[] = [ unitArgs((u) => (u.tlsCa && targetPlatform(u.driver) === "win32" ? ["-lcrypt32"] : [])), // Fetch uses the native network, TLS, and HTTP runtime. unit((u) => u.nativeFetch, "scr_fetch.c"), + // Readable.fromWeb reads a web ReadableStream through its reader. + unit((u) => u.nativeFetch && u.opts.stream, "scr_stream_from_web.c"), ]; /** The arguments of the optional runtime inputs, in link order. */ @@ -372,10 +388,13 @@ export async function compileCInternal( const http = (opts.http ?? false) || nativeFetch; const tls = (opts.tls ?? false) || nativeFetch; const tlsCa = (opts.tlsCa ?? false) || tls; - // Symmetric ciphers and ECDH link the same mbedTLS archive as TLS. + // Symmetric ciphers, ECDH and DiffieHellman link the same mbedTLS + // archive as TLS. const cipher = opts.cipher ?? false; const ecdh = opts.ecdh ?? false; - const mbedtls = tls || cipher || ecdh; + const dh = opts.dh ?? false; + const pki = opts.pki ?? false; + const mbedtls = tls || cipher || ecdh || dh || pki; const driver = resolveCc(); const darwinDebugSymbols = needsDarwinDebugSymbols( targetPlatform(driver), @@ -481,7 +500,7 @@ export async function compileCInternal( const [compiler, runtimeHash, programBytes] = await Promise.all([ resolvedTool(driver.argv[0] ?? "clang"), runtimeFingerprint(rtDir), - readFile(opts.cPath), + readFile(opts.cSourcePath ?? opts.cPath), ]); if (compiler !== null) { const effectiveCompiler = @@ -733,6 +752,8 @@ export async function compileCInternal( tlsCa, cipher, ecdh, + dh, + pki, lreObjects, zlibObjects, tlsArchive, @@ -861,7 +882,12 @@ export async function compileCInternal( ); try { await materializeVendorPrerequisites(undefined, privateVendorRoot); - await buildExecutable((p) => p); + await buildExecutable( + (p) => p, + opts.cSourcePath === undefined + ? {} + : { programPath: opts.cSourcePath, compilerVisibleSource: opts.cPath }, + ); } finally { await rm(privateVendorRoot, { recursive: true, force: true }).catch(() => undefined); } @@ -896,7 +922,9 @@ export async function compileCInternal( localArtifact === null ? runtimeFingerprint(rtDir) : Promise.resolve(localArtifact.runtimeHash), - localArtifact === null ? readFile(opts.cPath) : Promise.resolve(localArtifact.programBytes), + localArtifact === null + ? readFile(opts.cSourcePath ?? opts.cPath) + : Promise.resolve(localArtifact.programBytes), ]); compileMetadataStamp = compileMetadataKey === null @@ -965,7 +993,7 @@ export async function compileCInternal( Promise.all([ ccVersion(driver.argv, toolchainEnv, true), runtimeFingerprint(rtDir), - readFile(opts.cPath), + readFile(opts.cSourcePath ?? opts.cPath), ])); } catch (error) { // A version/fingerprint probe is an optimization boundary. If the compiler diff --git a/packages/compiler/src/backend/result-slots.ts b/packages/compiler/src/backend/result-slots.ts new file mode 100644 index 000000000..608877f06 --- /dev/null +++ b/packages/compiler/src/backend/result-slots.ts @@ -0,0 +1,29 @@ +import type { IrStmt } from "../ir/ir.js"; + +/** Prefix of a function's result-slot entry: `%into.(...params, dst)` + * writes the function's fresh result object into `dst` and returns nothing + * (llvm/record-results.ts). */ +export const RESULT_ENTRY_PREFIX = "%into."; + +export function resultEntryName(name: string): string { + return `${RESULT_ENTRY_PREFIX}${name}`; +} + +/** The local id of a result-slot entry's destination parameter. The + * caller passes zeroed frame storage, and on every path the entry stores + * each of its fields at most once, so a store into it is an + * initialization: there is no old value to release. */ +export const RESULT_DST_ID = "%into.dst"; + +/** Whether `s`, a statement of the function `fnName`, is a result-slot + * entry's store into its destination. The destination is frame storage of + * a caller that only projects the value (llvm/stack-objects.ts), so the + * store initializes a field of an object no other object can point to. */ +export function resultSlotStore(fnName: string, s: IrStmt): boolean { + return ( + s.kind === "recordSet" && + s.obj.kind === "varRef" && + s.obj.localId === RESULT_DST_ID && + fnName.startsWith(RESULT_ENTRY_PREFIX) + ); +} diff --git a/packages/compiler/src/backend/runtime-abi.ts b/packages/compiler/src/backend/runtime-abi.ts index 5eb24482b..7d3dcbc02 100644 --- a/packages/compiler/src/backend/runtime-abi.ts +++ b/packages/compiler/src/backend/runtime-abi.ts @@ -2,8 +2,8 @@ * of the link contract: a program object keeps this symbol undefined and the * matching runtime defines it, so incompatible manual links fail before the * program can start. */ -export const RUNTIME_ABI_VERSION = 24 as const; -export const RUNTIME_ABI_MARKER = "scr_runtime_abi_v24" as const; +export const RUNTIME_ABI_VERSION = 33 as const; +export const RUNTIME_ABI_MARKER = "scr_runtime_abi_v33" as const; /** Object consumption is useful today, but the complete scr_* surface may * still change before 1.0. The versioned marker prevents accidental mixing; diff --git a/packages/compiler/src/backend/runtime-pack-targets.test.ts b/packages/compiler/src/backend/runtime-pack-targets.test.ts index fc7ed9efa..532051b88 100644 --- a/packages/compiler/src/backend/runtime-pack-targets.test.ts +++ b/packages/compiler/src/backend/runtime-pack-targets.test.ts @@ -52,7 +52,7 @@ async function fixture(target: NativeTargetSpec, workers = false) { object_format: target.objectFormat, minimum_os: target.minimumOs, }, - runtime_abi: { version: 24, marker: "scr_runtime_abi_v24" }, + runtime_abi: { version: 33, marker: "scr_runtime_abi_v33" }, compiler: { command: "fixture", identity: "fixture", target: target.llvmTriple }, macros: { executable: [], excluded: ["SCR_LIB"], sanitizer: "external-toolchain-required" }, flavors: { @@ -125,6 +125,9 @@ const features = { tlsCa: false, cipher: false, ecdh: false, + dh: false, + pki: false, + ed25519: false, webcrypto: false, perfLoop: false, }; diff --git a/packages/compiler/src/backend/runtime-pack.test.ts b/packages/compiler/src/backend/runtime-pack.test.ts index 5ffb4797d..18b04b9a6 100644 --- a/packages/compiler/src/backend/runtime-pack.test.ts +++ b/packages/compiler/src/backend/runtime-pack.test.ts @@ -61,6 +61,9 @@ const BASE: NativeLinkFeatures = { tlsCa: false, cipher: false, ecdh: false, + dh: false, + pki: false, + ed25519: false, webcrypto: false, perfLoop: false, }; @@ -124,7 +127,7 @@ async function fixture(target: NativeTargetSpec = MACOS_ARM64_TARGET) { object_format: target.objectFormat, minimum_os: target.minimumOs, }, - runtime_abi: { version: 24, marker: "scr_runtime_abi_v24" }, + runtime_abi: { version: 33, marker: "scr_runtime_abi_v33" }, compiler: { command: "clang", identity: "fixture clang", diff --git a/packages/compiler/src/backend/stack-observations.ts b/packages/compiler/src/backend/stack-observations.ts index fa67c071f..c448897f1 100644 --- a/packages/compiler/src/backend/stack-observations.ts +++ b/packages/compiler/src/backend/stack-observations.ts @@ -29,35 +29,50 @@ const NON_STACK_KEY_TYPES: ReadonlySet = new Set(["f64", "bigint * containers or calls; a key the program assembles from other strings or * from data it reads keeps the static answer. */ class StackKeys { - private readonly spelled: boolean; - private readonly calls = new Map(); - private readonly named: Set; + private spelled: boolean | undefined; + private census: + | { calls: Map; named: Set } + | undefined; private readonly inits = new Map>(); /** Settled answers by function and local: true where a search reached a * key that can be "stack", false where a search that found none passed. */ private readonly answers = new Map(); - constructor(mod: IrModule) { - this.spelled = spellsStack(mod); - this.named = new Set(moduleFunctionReferences(mod)); + // The module walks run on the first question that needs them: a program + // without a dynamic key read asks none. + constructor(private readonly mod: IrModule) {} + + private spellsStack(): boolean { + return (this.spelled ??= spellsStack(this.mod)); + } + + private callCensus(): { + calls: Map; + named: Set; + } { + if (this.census !== undefined) return this.census; + const mod = this.mod; + const calls = new Map(); + const named = new Set(moduleFunctionReferences(mod)); // Class methods, accessors and constructors are called through dispatch. const classNames = new Set((mod.classes ?? []).map((cls) => cls.name)); for (const fn of mod.functions) { - if (isClassMember(fn.name, classNames)) this.named.add(fn.name); + if (isClassMember(fn.name, classNames)) named.add(fn.name); everyStmtList(fn.body, { stmt: () => true, expr: (expr) => { if (expr.kind === "call") { - const sites = this.calls.get(expr.callee) ?? []; + const sites = calls.get(expr.callee) ?? []; sites.push({ caller: fn, args: expr.args }); - this.calls.set(expr.callee, sites); + calls.set(expr.callee, sites); } const referenced = exprFunctionReference(expr); - if (referenced !== undefined) this.named.add(referenced); + if (referenced !== undefined) named.add(referenced); return true; }, }); } + return (this.census = { calls, named }); } mayBeStack(fn: IrFunction, key: IrExpr): boolean { @@ -71,7 +86,7 @@ class StackKeys { private keyMayBeStack(fn: IrFunction, key: IrExpr, visited: Set): boolean { if (key.kind === "strLit") return key.value === "stack"; - if (!this.spelled) return false; + if (!this.spellsStack()) return false; if (NON_STACK_KEY_TYPES.has(key.type.kind)) return false; if (key.kind === "toString" && NON_STACK_KEY_TYPES.has(key.operand.type.kind)) return false; if (key.kind === "dynFrom" && NON_STACK_KEY_TYPES.has(key.value.type.kind)) return false; @@ -93,8 +108,9 @@ class StackKeys { if (local === undefined || local.mutable) return true; const index = fn.params.findIndex((param) => param.localId === localId); if (index !== -1) { - const sites = this.calls.get(fn.name); - if (this.named.has(fn.name) || sites === undefined) return true; + const { calls, named } = this.callCensus(); + const sites = calls.get(fn.name); + if (named.has(fn.name) || sites === undefined) return true; return sites.some( (site) => site.args.length !== fn.params.length || diff --git a/packages/compiler/src/backend/target-diagnostics.ts b/packages/compiler/src/backend/target-diagnostics.ts index b7049f6fe..236ce12cf 100644 --- a/packages/compiler/src/backend/target-diagnostics.ts +++ b/packages/compiler/src/backend/target-diagnostics.ts @@ -2,7 +2,12 @@ import { everyModuleNode, everyStmtList, transformStmtList } from "../ir/travers import type { LlvmUnsupportedError } from "./llvm/emitter.js"; import type { ScrDiagnostic } from "../diagnostics/diagnostic.js"; import { type IrModule, type SrcLoc } from "../ir/ir.js"; -import { moduleUsesFetch } from "../ir/runtime-features.js"; +import { + DH_LIB_FNS, + PKI_LIB_FNS, + moduleUsesFetch, + moduleUsesWebCryptoAsymmetric, +} from "../ir/runtime-features.js"; /** Reflection tables expose methods that the program never calls. On WASI, * keep their host-only implementations as explicit runtime refusals. Typed @@ -208,6 +213,19 @@ export function moduleWasiUnavailableSurface( }; return false; } + if ( + node.fn === "webcrypto.encrypt" || + node.fn === "webcrypto.decrypt" || + node.fn === "webcrypto.wrapKey" || + node.fn === "webcrypto.unwrapKey" + ) { + found = { + surface: + "WebCrypto encrypt, decrypt, wrapKey and unwrapKey (the wasm32-wasi runtime does not include the mbedTLS library)", + loc, + }; + return false; + } if (node.fn === "crypto.ecdhNew" || node.fn === "crypto.ecdhConvertKey") { found = { surface: "ECDH (the wasm32-wasi runtime does not include the mbedTLS library)", @@ -215,6 +233,24 @@ export function moduleWasiUnavailableSurface( }; return false; } + if (DH_LIB_FNS.has(node.fn)) { + found = { + surface: + node.fn === "crypto.dhNew" || node.fn === "crypto.dhGroupNew" + ? "DiffieHellman (the wasm32-wasi runtime does not include the mbedTLS library)" + : "checkPrime and generatePrime (the wasm32-wasi runtime does not include the mbedTLS library)", + loc, + }; + return false; + } + if (PKI_LIB_FNS.has(node.fn)) { + found = { + surface: + "asymmetric keys and signatures (the wasm32-wasi runtime does not include the mbedTLS library)", + loc, + }; + return false; + } if (node.fn === "os.networkInterfaces") { found = { surface: "network-interface enumeration (WASI Preview 1 has no interface API)", @@ -241,5 +277,12 @@ export function moduleWasiUnavailableSurface( if (moduleUsesFetch(mod)) { return { surface: "network-backed fetch (WASI Preview 1 has no socket API)", loc: entryLoc }; } + if (moduleUsesWebCryptoAsymmetric(mod)) { + return { + surface: + "WebCrypto ECDSA and RSA (the wasm32-wasi runtime does not include the mbedTLS library)", + loc: entryLoc, + }; + } return null; } diff --git a/packages/compiler/src/backend/warm-cache.ts b/packages/compiler/src/backend/warm-cache.ts index 2d8ae6641..b48cf6739 100644 --- a/packages/compiler/src/backend/warm-cache.ts +++ b/packages/compiler/src/backend/warm-cache.ts @@ -67,6 +67,9 @@ export async function warmNativeCaches( tls: false, cipher: false, ecdh: false, + dh: false, + pki: false, + ed25519: false, webcrypto: false, perfLoop: false, tlsCa: false, diff --git a/packages/compiler/src/contracts/check.ts b/packages/compiler/src/contracts/check.ts index 5934624bf..fe5dc171e 100644 --- a/packages/compiler/src/contracts/check.ts +++ b/packages/compiler/src/contracts/check.ts @@ -174,7 +174,8 @@ class ContractChecker { return `${owner}.${method[2]}`; } if (fn?.sourceName !== undefined && fn.sourceName !== "") return fn.sourceName; - if (fn !== undefined && /^%fn\d+$/.test(fnName)) return `the function at ${this.where(fn.loc)}`; + if (fn !== undefined && /^%fn\.[0-9a-f]{12}$/.test(fnName)) + return `the function at ${this.where(fn.loc)}`; return fnName.replace(/^%/, ""); } @@ -284,9 +285,10 @@ class ContractChecker { * the lifetimes of the objects they receive). Publication to other * threads needs no check: an instance carries a reference count of its * own until publication marks it like any other object it reaches - * (classes.ts programLifetimeRc). Static code has no WeakRef or - * FinalizationRegistry; weak collections stay correct because an entry - * keyed by an object that is never freed is never observable as removed. */ + * (classes.ts programLifetimeRc). Static code has no WeakRef, and a + * FinalizationRegistry never runs its cleanup callbacks; weak collections + * stay correct because an entry keyed by an object that is never freed is + * never observable as removed. */ private checkProgramLifetime(): void { if (this.notes.classes.size === 0) return; const roots: string[] = []; diff --git a/packages/compiler/src/coverage/report.ts b/packages/compiler/src/coverage/report.ts index 37f77f4c6..79017c97a 100644 --- a/packages/compiler/src/coverage/report.ts +++ b/packages/compiler/src/coverage/report.ts @@ -318,12 +318,23 @@ export function renderCoverage(input: CoverageInput, opts: CoverageRenderOptions // statements the module carries): they compile, but executing one // throws its SC-coded error — the report lists them so a "compiling" // JS program never hides its dynamic gaps. + // Fences in a module's top-level code run when the module initializes: + // they are listed first, as sites that run at startup. const fences = input.runtimeFences ?? []; - if (fences.length > 0) { + const startup = fences.filter((d) => d.startup === true); + const later = fences.filter((d) => d.startup !== true); + if (startup.length > 0) { out.push( - ` ${c(YELLOW, "deferred to runtime")} ${fences.length} site${fences.length === 1 ? "" : "s"} ${c(DIM, "(JS statements that throw their fence if executed)")}`, + ` ${c(YELLOW, "runs at startup")} ${startup.length} site${startup.length === 1 ? "" : "s"} ${c(DIM, "(JS statements in module top-level code, which runs when the module loads)")}`, ); - renderRows(groupBlockers(fences, "deferred"), YELLOW); + renderRows(groupBlockers(startup, "deferred"), YELLOW); + out.push(""); + } + if (later.length > 0) { + out.push( + ` ${c(YELLOW, "deferred to runtime")} ${later.length} site${later.length === 1 ? "" : "s"} ${c(DIM, "(JS statements that throw their fence if executed)")}`, + ); + renderRows(groupBlockers(later, "deferred"), YELLOW); out.push(""); } diff --git a/packages/compiler/src/diagnostics/diagnostic.ts b/packages/compiler/src/diagnostics/diagnostic.ts index 17cb2efc0..625ee93af 100644 --- a/packages/compiler/src/diagnostics/diagnostic.ts +++ b/packages/compiler/src/diagnostics/diagnostic.ts @@ -92,6 +92,10 @@ export interface ScrDiagnostic { * the error may not reproduce under the project's tsc. Machine-readable * output reports these under the "environment" category. */ typeWorld?: boolean; + /** A runtime fence in a module's top-level code, outside every function + * and class member body: it throws when the module initializes, which is + * program startup for a module the entry imports. */ + startup?: true; } /** SC3002–SC3004 — native-helper target, installation, and execution diff --git a/packages/compiler/src/diagnostics/envelope.ts b/packages/compiler/src/diagnostics/envelope.ts index 59c285ead..b4de8db77 100644 --- a/packages/compiler/src/diagnostics/envelope.ts +++ b/packages/compiler/src/diagnostics/envelope.ts @@ -67,6 +67,9 @@ export interface LocatedDiagnostic extends SourcePosition { hint: string; /** The id of the root-cause group this site belongs to. */ group: string; + /** Deferred scope only: the statement is module top-level code, so it + * runs when its module loads. */ + startup?: true; } export interface DiagnosticGroup { @@ -290,6 +293,7 @@ export function locateDiagnostic( message: diag.message, hint: hintOf(diag), group: groupId(diag, scope), + ...(scope === "deferred" && diag.startup === true ? { startup: true as const } : {}), }; } diff --git a/packages/compiler/src/executable/executable-cache.test.ts b/packages/compiler/src/executable/executable-cache.test.ts index 94b136c90..5cf8c6588 100644 --- a/packages/compiler/src/executable/executable-cache.test.ts +++ b/packages/compiler/src/executable/executable-cache.test.ts @@ -65,6 +65,9 @@ const native: EarlyExecutableNativeFeatures = { tlsCa: false, cipher: false, ecdh: false, + dh: false, + pki: false, + ed25519: false, webcrypto: false, perfLoop: false, }; @@ -133,8 +136,15 @@ test("early executable cache restores the emitted TU, IR, and native feature gat const hit = await readEarlyExecutableCache(f.root, f.options); expect(hit?.native).toEqual(native); expect(hit?.executableRestored).toBe(false); - expect(await readFile(f.llvmPath, "utf8")).toBe("; generated llvm\n"); - expect(await readFile(f.irPath, "utf8")).toContain("irVersion"); + // The build compiles private copies beside the shared names and installs + // them there when it is done. + expect(hit?.llvmPath).toBe(f.llvmPath); + expect(hit?.irPath).toBe(f.irPath); + expect(hit?.llvmSourcePath).toMatch(/[/\\]\.scriptc-llvm-[^/\\]*\.ll$/); + expect(hit?.irSourcePath).toMatch(/[/\\]\.scriptc-ir-/); + expect(await readFile(hit!.llvmSourcePath!, "utf8")).toBe("; generated llvm\n"); + expect(await readFile(hit!.irSourcePath!, "utf8")).toContain("irVersion"); + await expect(stat(f.llvmPath)).rejects.toThrow(); expect(await readFile(alternateC, "utf8")).toBe("/* user-owned native source */\n"); }); diff --git a/packages/compiler/src/executable/executable-cache.ts b/packages/compiler/src/executable/executable-cache.ts index 2312f5e85..5c3904a91 100644 --- a/packages/compiler/src/executable/executable-cache.ts +++ b/packages/compiler/src/executable/executable-cache.ts @@ -18,6 +18,7 @@ import { compilerReleaseVersion } from "../library/sidecar.js"; import { nativeArtifactDependenciesStillMatch } from "../backend/native/artifact-stamps.js"; import { type NativeArtifactDependency } from "../backend/native/contracts.js"; import { optimizationKeyParts } from "../backend/optimization.js"; +import { privateSiblingPath } from "../backend/build-cache.js"; import type { CompilerImplementationDependency } from "../library/compiler-self-identity.js"; import { installDarwinDebugSymbols, @@ -96,6 +97,9 @@ export interface EarlyExecutableNativeFeatures { tls: boolean; cipher: boolean; ecdh: boolean; + dh: boolean; + pki: boolean; + ed25519: boolean; perfLoop: boolean; tlsCa: boolean; webcrypto: boolean; @@ -179,6 +183,15 @@ interface EarlyExecutableImplementationProof { export interface EarlyExecutableCacheHit { llvmPath: string; irPath?: string; + /** When the executable was not restored: private copies of the cached LLVM text and IR beside + * llvmPath and irPath, which the build compiles from and installs at those names when it is done + * (index.ts BuildSources). A restored executable needs no compile, and its files are installed at + * llvmPath and irPath. */ + llvmSourcePath?: string; + irSourcePath?: string; + /** llvmPath (irPath) already holds the cached bytes: the build leaves it as it is. */ + llvmPathCurrent?: true; + irPathCurrent?: true; /** True when the final executable was restored after native dependencies * validated. False restores only frontend artifacts and must call compileC. */ executableRestored: boolean; @@ -228,6 +241,9 @@ const BOOLEAN_NATIVE_KEYS = [ "tlsCa", "cipher", "ecdh", + "dh", + "pki", + "ed25519", "webcrypto", "perfLoop", ] as const satisfies readonly (keyof EarlyExecutableNativeFeatures)[]; @@ -575,15 +591,6 @@ async function readExecutableCache( (await nativeArtifactDependenciesStillMatch(stamp.nativeDependencies)); if (validateRoute !== undefined && !executableRestored) return null; const paths = outputPaths(options, stamp.native.backend); - if (!(await fileMatches(paths.llvmPath, stamp.files.translationUnit.digest))) { - await installBytes(translationUnit, paths.llvmPath); - } - if ( - ir !== null && - stamp.files.ir !== null && - !(await fileMatches(paths.irPath, stamp.files.ir.digest)) - ) - await installBytes(ir, paths.irPath); if (executableRestored) { try { if (debugSymbols !== null) await installDarwinDebugSymbols(debugSymbols, options.outPath); @@ -598,6 +605,32 @@ async function readExecutableCache( executableRestored = false; } } + // A build that compiles from the cached translation unit compiles its own copy: a concurrent + // build of another program with the same entry name may replace the shared names meanwhile. + let llvmSourcePath: string | undefined; + let irSourcePath: string | undefined; + let llvmPathCurrent = false; + let irPathCurrent = false; + if (executableRestored) { + if (!(await fileMatches(paths.llvmPath, stamp.files.translationUnit.digest))) + await installBytes(translationUnit, paths.llvmPath); + if ( + ir !== null && + stamp.files.ir !== null && + !(await fileMatches(paths.irPath, stamp.files.ir.digest)) + ) + await installBytes(ir, paths.irPath); + } else { + // The extension keeps clang reading the copy as LLVM IR rather than as a linker input. + llvmSourcePath = `${privateSiblingPath(paths.llvmPath, "llvm")}.ll`; + await installBytes(translationUnit, llvmSourcePath); + llvmPathCurrent = await fileMatches(paths.llvmPath, stamp.files.translationUnit.digest); + if (ir !== null && stamp.files.ir !== null) { + irSourcePath = privateSiblingPath(paths.irPath, "ir"); + await installBytes(ir, irSourcePath); + irPathCurrent = await fileMatches(paths.irPath, stamp.files.ir.digest); + } + } const now = new Date(); await Promise.all( [ @@ -619,6 +652,10 @@ async function readExecutableCache( ? { performance: stamp.performance } : {}), ...(ir === null ? {} : { irPath: paths.irPath }), + ...(llvmSourcePath === undefined ? {} : { llvmSourcePath }), + ...(irSourcePath === undefined ? {} : { irSourcePath }), + ...(llvmPathCurrent ? { llvmPathCurrent: true as const } : {}), + ...(irPathCurrent ? { irPathCurrent: true as const } : {}), }; } catch { return null; diff --git a/packages/compiler/src/frontend/jsx-entities.ts b/packages/compiler/src/frontend/jsx-entities.ts new file mode 100644 index 000000000..b9b0070de --- /dev/null +++ b/packages/compiler/src/frontend/jsx-entities.ts @@ -0,0 +1,258 @@ +/** The HTML entity names JSX text and attribute strings decode (HTML 4's + * 253 named character references, the set TypeScript's JSX emit decodes), + * by name. */ +export const JSX_ENTITIES: ReadonlyMap = new Map([ + ["quot", 34], + ["amp", 38], + ["apos", 39], + ["lt", 60], + ["gt", 62], + ["nbsp", 160], + ["iexcl", 161], + ["cent", 162], + ["pound", 163], + ["curren", 164], + ["yen", 165], + ["brvbar", 166], + ["sect", 167], + ["uml", 168], + ["copy", 169], + ["ordf", 170], + ["laquo", 171], + ["not", 172], + ["shy", 173], + ["reg", 174], + ["macr", 175], + ["deg", 176], + ["plusmn", 177], + ["sup2", 178], + ["sup3", 179], + ["acute", 180], + ["micro", 181], + ["para", 182], + ["middot", 183], + ["cedil", 184], + ["sup1", 185], + ["ordm", 186], + ["raquo", 187], + ["frac14", 188], + ["frac12", 189], + ["frac34", 190], + ["iquest", 191], + ["Agrave", 192], + ["Aacute", 193], + ["Acirc", 194], + ["Atilde", 195], + ["Auml", 196], + ["Aring", 197], + ["AElig", 198], + ["Ccedil", 199], + ["Egrave", 200], + ["Eacute", 201], + ["Ecirc", 202], + ["Euml", 203], + ["Igrave", 204], + ["Iacute", 205], + ["Icirc", 206], + ["Iuml", 207], + ["ETH", 208], + ["Ntilde", 209], + ["Ograve", 210], + ["Oacute", 211], + ["Ocirc", 212], + ["Otilde", 213], + ["Ouml", 214], + ["times", 215], + ["Oslash", 216], + ["Ugrave", 217], + ["Uacute", 218], + ["Ucirc", 219], + ["Uuml", 220], + ["Yacute", 221], + ["THORN", 222], + ["szlig", 223], + ["agrave", 224], + ["aacute", 225], + ["acirc", 226], + ["atilde", 227], + ["auml", 228], + ["aring", 229], + ["aelig", 230], + ["ccedil", 231], + ["egrave", 232], + ["eacute", 233], + ["ecirc", 234], + ["euml", 235], + ["igrave", 236], + ["iacute", 237], + ["icirc", 238], + ["iuml", 239], + ["eth", 240], + ["ntilde", 241], + ["ograve", 242], + ["oacute", 243], + ["ocirc", 244], + ["otilde", 245], + ["ouml", 246], + ["divide", 247], + ["oslash", 248], + ["ugrave", 249], + ["uacute", 250], + ["ucirc", 251], + ["uuml", 252], + ["yacute", 253], + ["thorn", 254], + ["yuml", 255], + ["OElig", 338], + ["oelig", 339], + ["Scaron", 352], + ["scaron", 353], + ["Yuml", 376], + ["fnof", 402], + ["circ", 710], + ["tilde", 732], + ["Alpha", 913], + ["Beta", 914], + ["Gamma", 915], + ["Delta", 916], + ["Epsilon", 917], + ["Zeta", 918], + ["Eta", 919], + ["Theta", 920], + ["Iota", 921], + ["Kappa", 922], + ["Lambda", 923], + ["Mu", 924], + ["Nu", 925], + ["Xi", 926], + ["Omicron", 927], + ["Pi", 928], + ["Rho", 929], + ["Sigma", 931], + ["Tau", 932], + ["Upsilon", 933], + ["Phi", 934], + ["Chi", 935], + ["Psi", 936], + ["Omega", 937], + ["alpha", 945], + ["beta", 946], + ["gamma", 947], + ["delta", 948], + ["epsilon", 949], + ["zeta", 950], + ["eta", 951], + ["theta", 952], + ["iota", 953], + ["kappa", 954], + ["lambda", 955], + ["mu", 956], + ["nu", 957], + ["xi", 958], + ["omicron", 959], + ["pi", 960], + ["rho", 961], + ["sigmaf", 962], + ["sigma", 963], + ["tau", 964], + ["upsilon", 965], + ["phi", 966], + ["chi", 967], + ["psi", 968], + ["omega", 969], + ["thetasym", 977], + ["upsih", 978], + ["piv", 982], + ["ensp", 8194], + ["emsp", 8195], + ["thinsp", 8201], + ["zwnj", 8204], + ["zwj", 8205], + ["lrm", 8206], + ["rlm", 8207], + ["ndash", 8211], + ["mdash", 8212], + ["lsquo", 8216], + ["rsquo", 8217], + ["sbquo", 8218], + ["ldquo", 8220], + ["rdquo", 8221], + ["bdquo", 8222], + ["dagger", 8224], + ["Dagger", 8225], + ["bull", 8226], + ["hellip", 8230], + ["permil", 8240], + ["prime", 8242], + ["Prime", 8243], + ["lsaquo", 8249], + ["rsaquo", 8250], + ["oline", 8254], + ["frasl", 8260], + ["euro", 8364], + ["image", 8465], + ["weierp", 8472], + ["real", 8476], + ["trade", 8482], + ["alefsym", 8501], + ["larr", 8592], + ["uarr", 8593], + ["rarr", 8594], + ["darr", 8595], + ["harr", 8596], + ["crarr", 8629], + ["lArr", 8656], + ["uArr", 8657], + ["rArr", 8658], + ["dArr", 8659], + ["hArr", 8660], + ["forall", 8704], + ["part", 8706], + ["exist", 8707], + ["empty", 8709], + ["nabla", 8711], + ["isin", 8712], + ["notin", 8713], + ["ni", 8715], + ["prod", 8719], + ["sum", 8721], + ["minus", 8722], + ["lowast", 8727], + ["radic", 8730], + ["prop", 8733], + ["infin", 8734], + ["ang", 8736], + ["and", 8743], + ["or", 8744], + ["cap", 8745], + ["cup", 8746], + ["int", 8747], + ["there4", 8756], + ["sim", 8764], + ["cong", 8773], + ["asymp", 8776], + ["ne", 8800], + ["equiv", 8801], + ["le", 8804], + ["ge", 8805], + ["sub", 8834], + ["sup", 8835], + ["nsub", 8836], + ["sube", 8838], + ["supe", 8839], + ["oplus", 8853], + ["otimes", 8855], + ["perp", 8869], + ["sdot", 8901], + ["lceil", 8968], + ["rceil", 8969], + ["lfloor", 8970], + ["rfloor", 8971], + ["lang", 9001], + ["rang", 9002], + ["loz", 9674], + ["spades", 9824], + ["clubs", 9827], + ["hearts", 9829], + ["diams", 9830], +]); diff --git a/packages/compiler/src/frontend/jsx-source.test.ts b/packages/compiler/src/frontend/jsx-source.test.ts new file mode 100644 index 000000000..564a61d98 --- /dev/null +++ b/packages/compiler/src/frontend/jsx-source.test.ts @@ -0,0 +1,244 @@ +import ts5 from "typescript5"; +import { afterAll, describe, expect, it } from "vitest"; +import { jsxEmitPlan, decodeEntities, jsxPragmas, jsxTextValue, lowerJsx } from "./jsx-source.js"; +import { closeSourceParser, parseSourceFile } from "./ts7/source-parser-node.js"; + +afterAll(() => closeSourceParser()); + +/** Evaluates a program whose last statement is `result = ...`, with `h` and + * `Fragment` recording the calls the JSX makes. */ +function evaluate(code: string): unknown { + const run = new Function( + "h", + "Fragment", + "React", + `"use strict"; let result; ${code}; return result;`, + ) as (...args: unknown[]) => unknown; + const h = (tag: unknown, props: unknown, ...children: unknown[]): unknown => ({ + tag: typeof tag === "function" ? `fn:${tag.name}` : tag === Fragment ? "#fragment" : tag, + props, + children, + }); + const Fragment = { fragment: true }; + return run(h, Fragment, { createElement: h, Fragment }); +} + +/** TypeScript's own classic-runtime emit of the snippet. */ +function typescriptEmit(source: string, factory?: string): string { + return ts5.transpileModule(source, { + fileName: "case.tsx", + compilerOptions: { + target: ts5.ScriptTarget.ES2022, + module: ts5.ModuleKind.ESNext, + jsx: ts5.JsxEmit.React, + ...(factory === undefined ? {} : { jsxFactory: factory, jsxFragmentFactory: "Fragment" }), + }, + }).outputText; +} + +function rewrite(source: string, factory?: string): string { + const sf = parseSourceFile("/case.tsx", source, "tsx"); + const plan = jsxEmitPlan( + { + jsx: "react", + ...(factory === undefined ? {} : { jsxFactory: factory, jsxFragmentFactory: "Fragment" }), + }, + jsxPragmas(source), + ); + return lowerJsx(sf, plan).text; +} + +const cases: Record = { + "attributes and text": `const name = "w"; const p = { id: 1 }; +result =

Hello {name} & A © + second line + {/* comment */} + {name}{" "}bold +
;`, + fragments: `function Foo() {} Foo.Bar = function Bar() {}; +result = <>;`, + namespaced: `result = ;`, + "keys and nested maps": `const p = { id: 1 }; +result =
{[1, 2].map((n) => {n})}
;`, + "white space only": `result = [
,
+
,
a {"b"} c
];`, + "spreads": `const p = { id: 1 }; const kids = [1, 2]; +result = [
,
,
{...kids}
,
,
];`, + "attribute strings": `result =
;`, + "attribute values": `result =
c={{1}} d={[

]} />;`, + "member and this tags": `class X { Tag = function Tag() {}; render() { return ; } } +result = new X().render();`, + "dashed and capitalized names": `function Comp() {} +result = [, ];`, + "nested JSX in expressions": `const items = ["a", "b"]; +result =

    + {items.length > 1 ?
  • {items[0]}
  • : null} + {items.map((item) => +
  • + {item} +
  • )} +
;`, +}; + +describe("lowerJsx", () => { + for (const [name, source] of Object.entries(cases)) { + it(`matches TypeScript's emit: ${name}`, () => { + const lowered = rewrite(source); + expect(evaluate(lowered)).toEqual(evaluate(typescriptEmit(source))); + expect(lowered.split("\n").length).toBe(source.split("\n").length); + }); + } + + it("uses jsxFactory and the pragmas", () => { + const source = `result = <>;`; + expect(evaluate(rewrite(source, "h"))).toEqual(evaluate(typescriptEmit(source, "h"))); + const pragma = `/** @jsx h */\n/** @jsxFrag Fragment */\nresult = <>;`; + expect(rewrite(pragma)).toContain(`h(Fragment, null`); + expect(evaluate(rewrite(pragma))).toEqual(evaluate(typescriptEmit(pragma))); + }); + + it("keeps every byte outside JSX", () => { + const source = `const a = 1; // \nconst b = "
";\nresult = [a, b, ];\n`; + const lowered = rewrite(source); + expect( + lowered.startsWith(`const a = 1; // \nconst b = "
";\nresult = [a, b, `), + ).toBe(true); + }); + + it("maps rewritten positions back to the source", () => { + const source = `const x = 1;\nresult =
{x}
;\nconst y = 2;\n`; + const sf = parseSourceFile("/case.tsx", source, "tsx"); + const lowered = lowerJsx(sf, { runtime: "classic", factory: "h", fragment: "Fragment" }); + const after = lowered.text.indexOf("const y"); + expect(lowered.originalPosition(after)).toBe(source.indexOf("const y")); + const copied = lowered.text.indexOf("{ a: x }") + "{ a: ".length; + expect(lowered.originalPosition(copied)).toBe(source.indexOf("{x}>") + 1); + expect(lowered.originalPosition(lowered.text.indexOf("h("))).toBe(source.indexOf(" + list + .split(",") + .map((item) => { + const [name, local] = item.trim().split(/\s+as\s+/); + return `const ${local} = runtime.${name};`; + }) + .join(" "), + ) + .replace(/(^|\s)export /gm, "$1"); + const record = + (kind: string) => + (...args: unknown[]): unknown => ({ kind, args: args.map(named) }); + const runtime = { + jsx: record("jsx"), + jsxs: record("jsxs"), + jsxDEV: record("jsxDEV"), + createElement: record("createElement"), + Fragment: "#fragment", + }; + const run = new Function("runtime", `"use strict"; let result; ${body}; return result;`) as ( + runtime: unknown, + ) => unknown; + return run(runtime); +} + +/** Functions compare by name: each evaluation declares its own. */ +function named(value: unknown): unknown { + if (typeof value === "function") return `fn:${value.name}`; + if (Array.isArray(value)) return value.map(named); + if (value !== null && typeof value === "object") + return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, named(item)])); + return value; +} + +function typescriptAutomatic(source: string, development: boolean): string { + return ts5.transpileModule(source, { + fileName: "/case.tsx", + compilerOptions: { + target: ts5.ScriptTarget.ES2022, + module: ts5.ModuleKind.ESNext, + jsx: development ? ts5.JsxEmit.ReactJSXDev : ts5.JsxEmit.ReactJSX, + }, + }).outputText; +} + +function rewriteAutomatic(source: string, development: boolean): string { + const sf = parseSourceFile("/case.tsx", source, "tsx"); + const plan = jsxEmitPlan({ jsx: development ? "react-jsxdev" : "react-jsx" }, jsxPragmas(source)); + return lowerJsx(sf, plan).text; +} + +const automaticCases: Record = { + ...cases, + "keys": `const p = { id: 1 }; +result = [
  • x
  • ,
  • ,
  • ,
  • ,
  • ];`, + "children shapes": `const kids = [1, 2]; +result = [

    ,

    {}

    ,

    +

    ,

    one

    ,

    {1}{2}

    ,

    {...kids}

    ,

    , <>, <>];`, + "names in use": `const _jsx = "taken"; const _jsxs = 1; +result = [

    {_jsx}

    ,

    {_jsxs}{_jsx}

    ];`, +}; + +describe("lowerJsx with the automatic runtime", () => { + for (const [name, source] of Object.entries(automaticCases)) { + for (const development of [false, true]) { + it(`matches TypeScript's ${development ? "react-jsxdev" : "react-jsx"} emit: ${name}`, () => { + const lowered = rewriteAutomatic(`export {};\n${source}`, development); + const expected = typescriptAutomatic(`export {};\n${source}`, development); + expect(evaluateAutomatic(lowered)).toEqual(evaluateAutomatic(expected)); + expect(lowered.split("\n").length).toBe(source.split("\n").length + 1); + }); + } + } + + it("imports the runtime functions on the first statement's line", () => { + const lowered = rewriteAutomatic( + `"use strict";\nexport const a = <>;\n`, + false, + ); + expect(lowered).toBe( + `"use strict";import { jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime"; \nexport const a = _jsx(_Fragment, { children: _jsx("b", {}, "k") });\n`, + ); + }); + + it("reads @jsxImportSource and @jsxRuntime", () => { + const pragma = `/** @jsxImportSource preact */\nexport const a = ;\n`; + expect(rewriteAutomatic(pragma, false)).toContain(`from "preact/jsx-runtime"`); + const classic = `/** @jsxRuntime classic */\n/** @jsx h */\nexport const a = ;\n`; + expect(rewriteAutomatic(classic, false)).toContain(`h("b", null)`); + }); +}); + +describe("JSX text", () => { + it("trims lines as TypeScript does", () => { + expect(jsxTextValue(" a \n b \n ")).toBe(" a b"); + expect(jsxTextValue("\n \n")).toBeUndefined(); + expect(jsxTextValue(" ")).toBe(" "); + }); + + it("decodes entities", () => { + expect(decodeEntities("<>& AB&bogus;�")).toBe( + "<>& AB&bogus;�", + ); + }); +}); + +describe("jsxPragmas", () => { + it("reads leading multi-line comments, first @jsx and last @jsxImportSource", () => { + expect( + jsxPragmas( + "#!/usr/bin/env node\n/** @jsx h\n * @jsx g */\n// @jsxFrag F\n/* @jsxImportSource a */ /* @jsxImportSource b */\nconst x = 1; /** @jsx late */", + ), + ).toEqual({ jsx: "h", jsxImportSource: "b" }); + }); +}); diff --git a/packages/compiler/src/frontend/jsx-source.ts b/packages/compiler/src/frontend/jsx-source.ts new file mode 100644 index 000000000..915a5d16f --- /dev/null +++ b/packages/compiler/src/frontend/jsx-source.ts @@ -0,0 +1,856 @@ +/* JSX lowering at the source level, before IR lowering. + * + * A program that contains JSX is checked as written: the checker types JSX + * with the project's jsx settings and reports the errors tsc reports. Each + * file that contains JSX is then rewritten with every JSX expression + * replaced by the calls TypeScript emits for it, and the rewritten program is + * what the lowering compiles, through the same import, call and object + * literal lowering as ordinary code. + * + * The rewrite copies every byte outside JSX expressions, and copies the + * expressions inside them (attribute values, children, spreads) with their + * own JSX rewritten. It keeps every line break of a JSX expression, between + * the arguments it emits, so a position keeps its line in the rewritten + * text. */ + +import * as ts from "./ts7/adapter.js"; +import { jsxOptionName } from "./ts7/enums.js"; +import { JSX_ENTITIES } from "./jsx-entities.js"; + +/** The project's jsx compiler options, as the tsconfig spells them. */ +export interface JsxOptions { + jsx?: string | number | undefined; + jsxFactory?: string | undefined; + jsxFragmentFactory?: string | undefined; + jsxImportSource?: string | undefined; + reactNamespace?: string | undefined; +} + +/** The tsconfig name of a `jsx` option value (TS7 options carry JsxEmit + * numbers, parsed tsconfigs may carry the name). */ +export function jsxEmitName(value: string | number | undefined): string | undefined { + if (typeof value === "number") return jsxOptionName(value); + return value?.toLowerCase(); +} + +/** The `@jsx`, `@jsxFrag`, `@jsxImportSource` and `@jsxRuntime` pragmas of + * a file's leading comments, as TypeScript reads them: multi-line comments + * only, the first `@jsx` and `@jsxFrag` and the last `@jsxImportSource` and + * `@jsxRuntime`. */ +export interface JsxPragmas { + jsx?: string; + jsxFrag?: string; + jsxImportSource?: string; + jsxRuntime?: string; +} + +export function jsxPragmas(text: string): JsxPragmas { + const pragmas: JsxPragmas = {}; + for (const comment of leadingMultiLineComments(text)) { + const pattern = /@(\S+)(\s+(?:\S.*)?)?$/gm; + for (let match = pattern.exec(comment); match !== null; match = pattern.exec(comment)) { + const argument = match[2]?.trim().split(/\s+/)[0]; + if (!argument) continue; + switch (match[1]!.toLowerCase()) { + case "jsx": + pragmas.jsx ??= argument; + break; + case "jsxfrag": + pragmas.jsxFrag ??= argument; + break; + case "jsximportsource": + pragmas.jsxImportSource = argument; + break; + case "jsxruntime": + pragmas.jsxRuntime = argument; + break; + } + } + } + return pragmas; +} + +/** The `/* ... *\/` comments before a file's first token (after a shebang). */ +function leadingMultiLineComments(text: string): string[] { + const comments: string[] = []; + let i = text.startsWith("#!") ? text.indexOf("\n") : 0; + if (i < 0) return comments; + while (i < text.length) { + const ch = text.charCodeAt(i); + if (isLineBreak(ch) || isWhiteSpaceSingleLine(ch)) { + i++; + } else if (text.startsWith("//", i)) { + while (i < text.length && !isLineBreak(text.charCodeAt(i))) i++; + } else if (text.startsWith("/*", i)) { + const end = text.indexOf("*/", i + 2); + const close = end < 0 ? text.length : end + 2; + comments.push(text.slice(i, close)); + i = close; + } else { + break; + } + } + return comments; +} + +function isLineBreak(ch: number): boolean { + return ch === 10 || ch === 13 || ch === 0x2028 || ch === 0x2029; +} + +function isWhiteSpaceSingleLine(ch: number): boolean { + return ( + ch === 32 || + ch === 9 || + ch === 11 || + ch === 12 || + ch === 160 || + ch === 133 || + ch === 5760 || + (ch >= 8192 && ch <= 8203) || + ch === 8239 || + ch === 8287 || + ch === 12288 || + ch === 65279 + ); +} + +/** How a file's JSX is emitted, after its pragmas. */ +export type JsxEmitPlan = + | { + runtime: "classic"; + /** The factory call (`h`, `React.createElement`). */ + factory: string; + /** The fragment tag (`Fragment`, `React.Fragment`). */ + fragment: string; + } + | { + runtime: "automatic"; + /** The module `jsx-runtime` (or `jsx-dev-runtime`) is under, and that + * a `createElement` fallback imports from (`react`). */ + importSource: string; + /** jsx: react-jsxdev: `jsxDEV` calls with source locations. */ + development: boolean; + }; + +/** The plan of a file: the automatic runtime with jsx: react-jsx or + * react-jsxdev, an import source or an `@jsxRuntime automatic` pragma (an + * `@jsxRuntime classic` pragma overrides all of them), the classic runtime + * otherwise. */ +export function jsxEmitPlan(options: JsxOptions, pragmas: JsxPragmas): JsxEmitPlan { + const mode = jsxEmitName(options.jsx); + const automatic = + pragmas.jsxRuntime !== "classic" && + (mode === "react-jsx" || + mode === "react-jsxdev" || + options.jsxImportSource !== undefined || + pragmas.jsxImportSource !== undefined || + pragmas.jsxRuntime === "automatic"); + if (automatic) { + return { + runtime: "automatic", + importSource: pragmas.jsxImportSource ?? options.jsxImportSource ?? "react", + development: mode === "react-jsxdev", + }; + } + const namespace = options.reactNamespace ?? "React"; + return { + runtime: "classic", + factory: pragmas.jsx ?? options.jsxFactory ?? `${namespace}.createElement`, + fragment: pragmas.jsxFrag ?? options.jsxFragmentFactory ?? `${namespace}.Fragment`, + }; +} + +/** True when the file contains a JSX expression. */ +export function containsJsx(sf: ts.SourceFile): boolean { + let found = false; + const visit = (node: ts.Node): void => { + if (found) return; + if (isJsxExpressionRoot(node)) { + found = true; + return; + } + ts.forEachChild(node, visit); + }; + visit(sf); + return found; +} + +/** The first JSX expression of the file (for diagnostics), or null. */ +export function firstJsx(sf: ts.SourceFile): ts.Node | null { + let found: ts.Node | null = null; + const visit = (node: ts.Node): void => { + if (found !== null) return; + if (isJsxExpressionRoot(node)) { + found = node; + return; + } + ts.forEachChild(node, visit); + }; + visit(sf); + return found; +} + +type JsxRoot = ts.JsxElement | ts.JsxSelfClosingElement | ts.JsxFragment; + +function isJsxExpressionRoot(node: ts.Node): node is JsxRoot { + return ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node) || ts.isJsxFragment(node); +} + +/** A file's text with its JSX lowered, and the way back from a position of + * that text to the source position it stands for. */ +export interface LoweredJsx { + text: string; + /** A rewritten-text offset as an offset of the original text: copied text + * keeps its offset; emitted call text maps to the JSX it stands for. */ + originalPosition(pos: number): number; + /** An original-text offset in the rewritten text: copied text keeps its + * offset; a position inside replaced JSX maps to the call text emitted + * for the JSX at or before it (its end, for the `end` of a span). */ + rewrittenPosition(pos: number, end: boolean): number; +} + +/** The file's text with its JSX replaced by the calls TypeScript emits for + * the plan, and for the automatic runtime the imports of the runtime + * functions those calls use. */ +export function lowerJsx(sf: ts.SourceFile, plan: JsxEmitPlan): LoweredJsx { + return new JsxRewriter(sf, plan).file(); +} + +/** A run of rewritten text: `copied` text starts at `original`; emitted + * text stands for the source position `original`. */ +interface Segment { + rewritten: number; + original: number; + /** The copied length, 0 for emitted text. */ + copied: number; +} + +class JsxRewriter { + private readonly text: string; + /** Output pieces; `cursor` is the source position whose line breaks the + * output has reached. */ + private readonly pieces: string[] = []; + private readonly segments: Segment[] = []; + private length = 0; + private cursor = 0; + + constructor( + private readonly sf: ts.SourceFile, + private readonly plan: JsxEmitPlan, + ) { + this.text = sf.text; + } + + file(): LoweredJsx { + const insertAt = this.plan.runtime === "automatic" ? this.prologueEnd() : -1; + this.copy(0, this.text.length); + if (insertAt >= 0) this.insertImports(insertAt); + const segments = this.segments; + const total = this.length; + return { + text: this.pieces.join(""), + originalPosition: (pos: number): number => { + let low = 0; + let high = segments.length - 1; + while (low < high) { + const mid = (low + high + 1) >> 1; + if (segments[mid]!.rewritten <= pos) low = mid; + else high = mid - 1; + } + const segment = segments[low]; + if (segment === undefined) return pos; + return segment.copied > 0 + ? segment.original + Math.min(pos - segment.rewritten, segment.copied) + : segment.original; + }, + rewrittenPosition: (pos: number, end: boolean): number => { + // Segments are in source order: the last one starting at or before + // `pos` holds it, or is the emitted text for the JSX holding it. + let low = 0; + let high = segments.length - 1; + while (low < high) { + const mid = (low + high + 1) >> 1; + if (segments[mid]!.original <= pos) low = mid; + else high = mid - 1; + } + const segment = segments[low]; + if (segment === undefined) return pos; + if (segment.copied > 0) + return segment.rewritten + Math.min(pos - segment.original, segment.copied); + return end ? (segments[low + 1]?.rewritten ?? total) : segment.rewritten; + }, + }; + } + + /** Local names of the automatic runtime's functions, by module and + * export, in the order of first use (TypeScript's implicit imports). */ + private readonly imports = new Map>(); + private names: Set | null = null; + private fileNameLocal: string | null = null; + + /** The local name bound to `name` of `module`: `_name`, or `_name_1`, + * `_name_2`, ... past an identifier the file already uses. */ + private importName(name: string, module: string): string { + let names = this.imports.get(module); + if (names === undefined) { + names = new Map(); + this.imports.set(module, names); + } + let local = names.get(name); + if (local === undefined) { + local = this.uniqueName(`_${name}`); + names.set(name, local); + } + return local; + } + + private uniqueName(base: string): string { + if (this.names === null) { + const names = new Set(); + const visit = (node: ts.Node): void => { + if (ts.isIdentifier(node)) names.add(node.text); + ts.forEachChild(node, visit); + }; + visit(this.sf); + this.names = names; + } + let name = base; + for (let i = 1; this.names.has(name); i++) name = `${base}_${i}`; + this.names.add(name); + return name; + } + + /** Where the runtime imports go: after the leading "use strict"-style + * directives, else before the first statement, so the inserted text + * shares that statement's line. */ + private prologueEnd(): number { + const statements = this.sf.statements.nodes; + let end = -1; + for (const statement of statements) { + if (!ts.isExpressionStatement(statement) || !ts.isStringLiteral(statement.expression)) break; + end = statement.end; + } + if (end >= 0) return end; + const first = statements[0]; + return first === undefined ? this.text.length : first.getStart(this.sf); + } + + /** Inserts the imports (or, in a CommonJS file, the requires) of the + * runtime functions the file's JSX used, and react-jsxdev's file name + * constant, at `at`: imports in the reverse order of their modules' first + * use, as TypeScript inserts each after the prologue. */ + private insertImports(at: number): void { + if (this.imports.size === 0 && this.fileNameLocal === null) return; + const esm = ts.isExternalModule(this.sf); + const parts: string[] = []; + for (const [module, names] of [...this.imports].reverse()) { + const specifier = JSON.stringify(module); + if (esm) { + const list = [...names].map(([name, local]) => `${name} as ${local}`).join(", "); + parts.push(`import { ${list} } from ${specifier};`); + } else if (/\.[cm]?jsx?$/.test(this.sf.fileName)) { + const list = [...names].map(([name, local]) => `${name}: ${local}`).join(", "); + parts.push(`const { ${list} } = require(${specifier});`); + } + } + if (this.fileNameLocal !== null) + parts.push(`const ${this.fileNameLocal} = ${JSON.stringify(this.sf.fileName)};`); + if (parts.length === 0) return; + const text = `${parts.join(" ")} `; + let index = 0; + let rewritten = 0; + for (; index < this.segments.length; index++) { + const segment = this.segments[index]!; + if (segment.copied > 0 && segment.original <= at && at <= segment.original + segment.copied) { + rewritten = segment.rewritten + (at - segment.original); + break; + } + } + // Split the copied segment holding `at` and shift what follows. + const holder = this.segments[index]; + const joined = this.pieces.join(""); + this.pieces.length = 0; + this.pieces.push(joined.slice(0, rewritten), text, joined.slice(rewritten)); + const following: Segment[] = [{ rewritten, original: at, copied: 0 }]; + if (holder !== undefined && holder.copied > 0) { + const head = at - holder.original; + const tail = holder.copied - head; + holder.copied = head; + if (tail > 0) + following.push({ rewritten: rewritten + text.length, original: at, copied: tail }); + } + for (let i = index + 1; i < this.segments.length; i++) + this.segments[i]!.rewritten += text.length; + this.segments.splice(index + 1, 0, ...following); + if (holder !== undefined && holder.copied === 0) this.segments.splice(index, 1); + this.length += text.length; + } + + /** Emits source text [start, end) unchanged. */ + private copied(start: number, end: number): void { + if (end <= start) return; + this.segments.push({ rewritten: this.length, original: start, copied: end - start }); + this.pieces.push(this.text.slice(start, end)); + this.length += end - start; + } + + /** Emits call text standing for the source position the cursor reached. */ + private emit(...texts: string[]): void { + for (const text of texts) { + if (text.length === 0) continue; + const last = this.segments[this.segments.length - 1]; + if (last === undefined || last.copied > 0 || last.original !== this.cursor) + this.segments.push({ rewritten: this.length, original: this.cursor, copied: 0 }); + this.pieces.push(text); + this.length += text.length; + } + } + + /** Copies the source range [start, end), with its JSX expressions + * replaced. */ + private copy(start: number, end: number): void { + let at = start; + const visit = (node: ts.Node): void => { + if (node.end <= at || (node !== this.sf && node.getStart(this.sf) >= end)) return; + if (isJsxExpressionRoot(node)) { + const nodeStart = node.getStart(this.sf); + this.copied(at, nodeStart); + if (nodeStart > this.cursor) this.cursor = nodeStart; + this.element(node); + this.sync(node.end); + at = node.end; + return; + } + ts.forEachChild(node, visit); + }; + // The cursor never moves back: a range copied after source that follows + // it (jsx()'s key argument, after the children) emits no line break + // twice. + if (start > this.cursor) this.cursor = start; + visit(this.enclosing(start, end)); + this.copied(at, end); + if (end > this.cursor) this.cursor = end; + } + + /** The smallest node around [start, end) whose children cover it. */ + private enclosing(start: number, end: number): ts.Node { + let node: ts.Node = this.sf; + for (;;) { + let next: ts.Node | undefined; + ts.forEachChild(node, (child) => { + if (next === undefined && child.pos <= start && child.end >= end) next = child; + }); + if (next === undefined || next === node) return node; + node = next; + } + } + + /** Emits the line breaks of the source between the cursor and `pos`. */ + private sync(pos: number): void { + for (let i = this.cursor; i < pos; i++) { + const ch = this.text.charCodeAt(i); + if (ch === 13 && this.text.charCodeAt(i + 1) === 10) { + this.cursor = i; + this.emit("\r\n"); + i++; + } else if (isLineBreak(ch)) { + this.cursor = i; + this.emit(this.text[i]!); + } + } + if (pos > this.cursor) this.cursor = pos; + } + + /** Copies an expression in a JSX expression's place. */ + private expression(node: ts.Node): void { + const start = node.getStart(this.sf); + this.sync(start); + this.copy(start, node.end); + } + + private element(node: JsxRoot): void { + const plan = this.plan; + if (plan.runtime === "classic") { + this.createElement(node, plan.factory, plan.fragment); + return; + } + const opening = ts.isJsxFragment(node) + ? null + : ts.isJsxElement(node) + ? node.openingElement + : node; + if (opening !== null && hasKeyAfterPropsSpread(opening.attributes)) { + // A key after a spread of props is not jsx()'s key argument: the + // element is the import source's createElement call. + this.createElement(node, this.importName("createElement", plan.importSource), ""); + return; + } + this.automaticElement(node, opening, plan.importSource, plan.development); + } + + /** The classic-runtime call: `factory(tag, props or null, ...children)`. */ + private createElement(node: JsxRoot, factory: string, fragment: string): void { + const children = ts.isJsxSelfClosingElement(node) ? [] : node.children.nodes; + if (ts.isJsxFragment(node)) { + this.emit(`${factory}(${fragment}, null`); + } else { + const opening = ts.isJsxElement(node) ? node.openingElement : node; + this.emit(`${factory}(`); + this.tagName(opening.tagName); + this.emit(", "); + this.attributes(opening.attributes.properties.nodes, null); + } + for (const child of children) { + if (ts.isJsxText(child)) { + const value = jsxTextValue(child.text); + if (value === undefined) continue; + this.emit(", "); + this.sync(child.getStart(this.sf)); + this.emit(JSON.stringify(value)); + } else if (ts.isJsxExpression(child)) { + if (child.expression === undefined) continue; + this.emit(", "); + if (child.dotDotDotToken !== undefined) this.emit("..."); + this.expression(child.expression); + } else if (isJsxExpressionRoot(child)) { + this.emit(", "); + this.sync(child.getStart(this.sf)); + this.element(child); + } + this.sync(child.end); + } + this.sync(node.end); + this.emit(")"); + } + + /** The automatic-runtime call: `jsx(tag, props[, key])` with the + * children in props, `jsxs` for more than one child or a spread child, and + * react-jsxdev's `jsxDEV(tag, props, key, isStatic, source, self)`. */ + private automaticElement( + node: JsxRoot, + opening: ts.JsxOpeningElement | ts.JsxSelfClosingElement | null, + importSource: string, + development: boolean, + ): void { + const children: readonly ts.JsxChild[] = ts.isJsxSelfClosingElement(node) + ? [] + : node.children.nodes; + const semantic = children.filter(isSemanticJsxChild); + const first = semantic[0]; + const isStatic = + semantic.length > 1 || + (first !== undefined && ts.isJsxExpression(first) && first.dotDotDotToken !== undefined); + const module = `${importSource}/${development ? "jsx-dev-runtime" : "jsx-runtime"}`; + this.emit(`${this.importName(development ? "jsxDEV" : isStatic ? "jsxs" : "jsx", module)}(`); + // TypeScript's children prop: the one semantic child itself, else an + // array of every child that emits a value. + const single = semantic.length === 1 && !isStatic ? first! : null; + const listed = single === null ? children.filter((child) => jsxChildEmits(child)) : []; + const childrenProp = + children.length > 0 && (single !== null ? jsxChildEmits(single) : listed.length > 0) + ? (): void => { + this.emit("children: "); + if (single !== null) { + this.child(single); + } else { + this.emit("["); + listed.forEach((child, index) => { + if (index > 0) this.emit(", "); + this.child(child); + this.sync(child.end); + }); + this.emit("]"); + } + } + : null; + let key: ts.JsxAttribute | undefined; + if (opening === null) { + this.emit(this.importName("Fragment", module), ", "); + if (childrenProp === null) this.emit("{}"); + else this.attributes([], childrenProp); + } else { + this.tagName(opening.tagName); + this.emit(", "); + const properties = opening.attributes.properties.nodes; + key = properties.find( + (property): property is ts.JsxAttribute => + ts.isJsxAttribute(property) && + ts.isIdentifier(property.name) && + property.name.text === "key", + ); + const attributes = properties.filter((property) => property !== key); + if (attributes.length === 0 && childrenProp === null) this.emit("{}"); + else this.attributes(attributes, childrenProp); + } + if (key !== undefined) { + this.emit(", "); + this.attributeValue(key.initializer); + } + if (development) { + if (key === undefined) this.emit(", void 0"); + const { line, column } = lineAndColumn(this.text, node.pos); + this.fileNameLocal ??= this.uniqueName("_jsxFileName"); + this.emit( + `, ${isStatic}, { fileName: ${this.fileNameLocal}, lineNumber: ${line}, columnNumber: ${column} }, `, + jsxSelf(node), + ); + } + this.sync(node.end); + this.emit(")"); + } + + /** A child's value in the children prop (it emits one: jsxChildEmits). */ + private child(child: ts.JsxChild): void { + if (ts.isJsxText(child)) { + this.sync(child.getStart(this.sf)); + this.emit(JSON.stringify(jsxTextValue(child.text)!)); + } else if (ts.isJsxExpression(child)) { + if (child.dotDotDotToken !== undefined) this.emit("..."); + this.expression(child.expression!); + } else { + this.sync(child.getStart(this.sf)); + this.element(child as JsxRoot); + } + } + + private tagName(tag: ts.JsxTagNameExpression): void { + this.sync(tag.getStart(this.sf)); + if (ts.isIdentifier(tag) && isIntrinsicJsxName(tag.text)) { + this.emit(JSON.stringify(tag.text)); + } else if (ts.isJsxNamespacedName(tag)) { + this.emit(JSON.stringify(`${tag.namespace.text}:${tag.name.text}`)); + } else { + this.emit(this.text.slice(tag.getStart(this.sf), tag.end)); + } + this.cursor = tag.end; + } + + /** The props object of `properties`, then `children` (the automatic + * runtime's children prop), or `null` for no properties and no children + * prop. */ + private attributes( + properties: readonly ts.JsxAttributeLike[], + children: (() => void) | null, + ): void { + if (properties.length === 0 && children === null) { + this.emit("null"); + return; + } + if (properties.length === 0) { + this.emit("{ "); + children!(); + this.emit(" }"); + return; + } + this.emit("{ "); + let first = true; + const separate = (): void => { + if (!first) this.emit(", "); + first = false; + }; + for (const attribute of properties) { + if (ts.isJsxSpreadAttribute(attribute)) { + const value = attribute.expression; + if (ts.isObjectLiteralExpression(value) && !hasProtoProperty(value)) { + // TypeScript inlines the properties of a spread object literal. + for (const property of value.properties.nodes) { + separate(); + this.expression(property); + } + } else { + separate(); + this.emit("..."); + this.expression(value); + } + } else { + separate(); + this.sync(attribute.getStart(this.sf)); + this.emit(attributeName(attribute.name), ": "); + this.attributeValue(attribute.initializer); + } + this.sync(attribute.end); + } + if (children !== null) { + this.emit(", "); + children(); + } + this.emit(" }"); + } + + private attributeValue(value: ts.JsxAttributeValue | undefined): void { + if (value === undefined) { + this.emit("true"); + } else if (ts.isStringLiteral(value)) { + this.sync(value.getStart(this.sf)); + this.emit(JSON.stringify(decodeEntities(value.text))); + } else if (ts.isJsxExpression(value)) { + if (value.expression === undefined) this.emit("true"); + else this.expression(value.expression); + } else { + this.sync(value.getStart(this.sf)); + this.element(value as JsxRoot); + } + } +} + +/** A child TypeScript counts: an expression container with an expression, + * text that is not only white space spanning lines, or an element. */ +function isSemanticJsxChild(child: ts.JsxChild): boolean { + if (ts.isJsxExpression(child)) return child.expression !== undefined; + if (ts.isJsxText(child)) return !child.containsOnlyTriviaWhiteSpaces; + return true; +} + +/** True when the child emits a value (text that trims to nothing and empty + * expression containers emit none). */ +function jsxChildEmits(child: ts.JsxChild): boolean { + if (ts.isJsxText(child)) return jsxTextValue(child.text) !== undefined; + if (ts.isJsxExpression(child)) return child.expression !== undefined; + return true; +} + +/** A `key` attribute after a spread that is not an object literal free of + * spreads: TypeScript emits createElement for such an element. */ +function hasKeyAfterPropsSpread(attributes: ts.JsxAttributes): boolean { + let spread = false; + for (const property of attributes.properties.nodes) { + if ( + ts.isJsxSpreadAttribute(property) && + (!ts.isObjectLiteralExpression(property.expression) || + property.expression.properties.nodes.some((p: ts.ObjectLiteralElementLike) => + ts.isSpreadAssignment(p), + )) + ) { + spread = true; + } else if ( + spread && + ts.isJsxAttribute(property) && + ts.isIdentifier(property.name) && + property.name.text === "key" + ) { + return true; + } + } + return false; +} + +/** The 1-based line and column of `pos`, counting the line breaks + * TypeScript counts (\r\n, \n, \r, U+2028, U+2029) and UTF-16 units. */ +function lineAndColumn(text: string, pos: number): { line: number; column: number } { + let line = 1; + let start = 0; + for (let i = 0; i < pos; i++) { + const ch = text.charCodeAt(i); + if (ch === 13 && text.charCodeAt(i + 1) === 10) continue; + if (isLineBreak(ch)) { + line++; + start = i + 1; + } + } + return { line, column: pos - start + 1 }; +} + +/** react-jsxdev's `self` argument. TypeScript passes `this`; where `this` + * has no declared type (the top level of an ES module and a function that is + * not a method and declares no `this` parameter) the argument is the + * `undefined` such code observes when called without a receiver, since an + * untyped `this` does not type-check under noImplicitThis. */ +function jsxSelf(node: ts.Node): string { + for (let at = node.parent; at !== undefined; at = at.parent) { + if (ts.isArrowFunction(at)) continue; + if ( + ts.isMethodDeclaration(at) || + ts.isConstructorDeclaration(at) || + ts.isGetAccessorDeclaration(at) || + ts.isSetAccessorDeclaration(at) || + ts.isPropertyDeclaration(at) || + ts.isClassStaticBlockDeclaration(at) + ) + return "this"; + if (ts.isFunctionDeclaration(at) || ts.isFunctionExpression(at)) { + const declaresThis = at.parameters.nodes.some( + (parameter: ts.ParameterDeclaration) => + ts.isIdentifier(parameter.name) && parameter.name.text === "this", + ); + const objectMethod = + ts.isFunctionExpression(at) && + at.parent !== undefined && + ts.isPropertyAssignment(at.parent); + return declaresThis || objectMethod ? "this" : "undefined"; + } + if (ts.isSourceFile(at)) return ts.isExternalModule(at) ? "undefined" : "this"; + } + return "undefined"; +} + +/** TypeScript's intrinsic-element test: a lowercase first letter or a dash. */ +function isIntrinsicJsxName(name: string): boolean { + const ch = name.charCodeAt(0); + return (ch >= 97 && ch <= 122) || name.includes("-"); +} + +function attributeName(name: ts.JsxAttributeName): string { + if (ts.isJsxNamespacedName(name)) + return JSON.stringify(`${name.namespace.text}:${name.name.text}`); + return /^[A-Z_]\w*$/i.test(name.text) ? name.text : JSON.stringify(name.text); +} + +function hasProtoProperty(object: ts.ObjectLiteralExpression): boolean { + return object.properties.nodes.some( + (property: ts.ObjectLiteralElementLike) => + ts.isPropertyAssignment(property) && + ((ts.isIdentifier(property.name) && property.name.text === "__proto__") || + (ts.isStringLiteral(property.name) && property.name.text === "__proto__")), + ); +} + +/** A JSX text child's string value: each line trimmed (the first line keeps + * its leading and the last line its trailing white space), lines without + * text dropped, the rest joined with one space and entities decoded. + * Undefined when nothing remains. */ +export function jsxTextValue(text: string): string | undefined { + let value: string | undefined; + let firstNonWhitespace = 0; + let lastNonWhitespace = -1; + const add = (line: string): void => { + const decoded = decodeEntities(line); + value = value === undefined ? decoded : `${value} ${decoded}`; + }; + for (let i = 0; i < text.length; i++) { + const ch = text.charCodeAt(i); + if (isLineBreak(ch)) { + if (firstNonWhitespace !== -1 && lastNonWhitespace !== -1) + add(text.slice(firstNonWhitespace, lastNonWhitespace + 1)); + firstNonWhitespace = -1; + } else if (!isWhiteSpaceSingleLine(ch)) { + lastNonWhitespace = i; + if (firstNonWhitespace === -1) firstNonWhitespace = i; + } + } + if (firstNonWhitespace !== -1) add(text.slice(firstNonWhitespace)); + return value; +} + +/** Decodes `&name;`, `&#ddd;` and `&#xhh;` references. Unknown names and + * numbers past U+10FFFF stay as written. */ +export function decodeEntities(text: string): string { + return text.replace( + /&((#((\d+)|x([\da-fA-F]+)))|(\w+));/g, + ( + match: string, + _all: string | undefined, + _number: string | undefined, + _digits: string | undefined, + decimal: string | undefined, + hex: string | undefined, + word: string | undefined, + ) => { + const code = decimal + ? parseInt(decimal, 10) + : hex + ? parseInt(hex, 16) + : JSX_ENTITIES.get(word!); + return code === undefined || code > 0x10ffff ? match : String.fromCodePoint(code); + }, + ); +} diff --git a/packages/compiler/src/frontend/literal-values.test.ts b/packages/compiler/src/frontend/literal-values.test.ts index 2a85f82bf..1d792b1d4 100644 --- a/packages/compiler/src/frontend/literal-values.test.ts +++ b/packages/compiler/src/frontend/literal-values.test.ts @@ -8,16 +8,15 @@ import { function harness() { const members = new Map(); - const snapshot = new SemanticSnapshot(1, { - text(method, payload) { - const query = JSON.parse(payload) as { objectId: number }; - if (method !== "getTypesOfType" || !members.has(query.objectId)) - throw new Error(`unexpected request: ${method}`); - return JSON.stringify(members.get(query.objectId)); - }, - binary(method) { + const reply = (method: string, payload: string) => { + const query = JSON.parse(payload) as { objectId: number }; + if (method !== "getTypesOfType" || !members.has(query.objectId)) throw new Error(`unexpected request: ${method}`); - }, + return JSON.stringify(members.get(query.objectId)); + }; + const snapshot = new SemanticSnapshot(1, { + text: reply, + binary: (method, payload) => new TextEncoder().encode(reply(method, payload)), }); const project = snapshot.addProject("literal-values", () => undefined); let id = 0; diff --git a/packages/compiler/src/frontend/lowering/array-indexed-mutation.ts b/packages/compiler/src/frontend/lowering/array-indexed-mutation.ts index 6d539212e..0ded460da 100644 --- a/packages/compiler/src/frontend/lowering/array-indexed-mutation.ts +++ b/packages/compiler/src/frontend/lowering/array-indexed-mutation.ts @@ -9,6 +9,7 @@ import { type SrcLoc, typeEquals, } from "../../ir/ir.js"; +import { keyedHelperName } from "./stable-names.js"; import { numLit, varRef } from "../../ir/build.js"; import { typeKey } from "../type-mapper.js"; import type { Lowerer } from "./lowerer.js"; @@ -125,7 +126,7 @@ export function lowerArrayFill( writeNull; let name = lowerer.arrHofHelpers.get(key); if (!name) { - name = "%arr.fill." + lowerer.arrHofHelpers.size; + name = keyedHelperName(lowerer, "%arr.fill", key); lowerer.arrHofHelpers.set(key, name); const a = varRef("a.0", arrType, loc); const n = varRef("n.0", F64, loc); diff --git a/packages/compiler/src/frontend/lowering/array-values.ts b/packages/compiler/src/frontend/lowering/array-values.ts index 0ca8503df..314cdfd24 100644 --- a/packages/compiler/src/frontend/lowering/array-values.ts +++ b/packages/compiler/src/frontend/lowering/array-values.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "./stable-names.js"; import { InternalCompilerError } from "../../errors.js"; import { dynUndefinedExpr, helperLoc, varRef } from "../../ir/build.js"; import { @@ -252,7 +253,7 @@ export function lowerSafeIndexRead( let name = lowerer.arrHofHelpers.get(key); if (!name) { const at = helperLoc(loc); - name = `%arr.idxOr.${lowerer.arrHofHelpers.size}`; + name = keyedHelperName(lowerer, "%arr.idxOr", key); lowerer.arrHofHelpers.set(key, name); const arrT = arr.type; lowerer.liftedFns.push({ @@ -298,7 +299,7 @@ export function lowerSafeBytesRead( let name = lowerer.arrHofHelpers.get(key); if (!name) { const at = helperLoc(loc); - name = `%bytes.idxOr.${lowerer.arrHofHelpers.size}`; + name = keyedHelperName(lowerer, "%bytes.idxOr", key); lowerer.arrHofHelpers.set(key, name); const b = varRef("b.0", bytesT, at); const i = varRef("i.0", F64, at); diff --git a/packages/compiler/src/frontend/lowering/binding-analysis.ts b/packages/compiler/src/frontend/lowering/binding-analysis.ts index 83b9aa6f9..1987c86ba 100644 --- a/packages/compiler/src/frontend/lowering/binding-analysis.ts +++ b/packages/compiler/src/frontend/lowering/binding-analysis.ts @@ -10,7 +10,13 @@ import { isGenericCallableMemberType } from "../type-mapper.js"; * Sound file-locally for module-scope bindings because ESM import * bindings are read-only — no other file can write one. Cached per * symbol (the scan walks the whole file once). */ -export function bindingNeverReassigned(lowerer: Lowerer, sym: ts.Symbol, decl: ts.Node): boolean { +export function bindingNeverReassigned( + lowerer: Lowerer, + sym: ts.Symbol, + decl: ts.Node, + resolve: (ident: ts.Identifier) => ts.Symbol | null | undefined = (ident) => + lowerer.resolveValueSymbol(ident), +): boolean { const cached = lowerer.neverReassignedCache.get(sym); if (cached !== undefined) return cached; let written = false; @@ -18,7 +24,7 @@ export function bindingNeverReassigned(lowerer: Lowerer, sym: ts.Symbol, decl: t // identifiers pay a symbol resolution. const symText = ts.symbolName(sym); const namesSym = (e: ts.Node): boolean => - ts.isIdentifier(e) && e.text === symText && lowerer.resolveValueSymbol(e) === sym; + ts.isIdentifier(e) && e.text === symText && resolve(e) === sym; const scanTarget = (t: ts.Expression): void => { let e: ts.Expression = t; while (ts.isParenthesizedExpression(e)) e = e.expression; diff --git a/packages/compiler/src/frontend/lowering/builtins/arguments.ts b/packages/compiler/src/frontend/lowering/builtins/arguments.ts index 7f862f603..d2fc430dd 100644 --- a/packages/compiler/src/frontend/lowering/builtins/arguments.ts +++ b/packages/compiler/src/frontend/lowering/builtins/arguments.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "../stable-names.js"; import { BYTES_U8, BOOL, @@ -72,7 +73,7 @@ export function lowerOptionalNumberPredicate( const key = `number.optionalPredicate:${fn}:${typeKey(widened)}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = `%number.optionalPredicate.${lowerer.valueHelpers.size}`; + helper = keyedHelperName(lowerer, "%number.optionalPredicate", key); lowerer.valueHelpers.set(key, helper); const input = varRef("value.0", widened, loc); lowerer.liftedFns.push({ diff --git a/packages/compiler/src/frontend/lowering/builtins/atomics.ts b/packages/compiler/src/frontend/lowering/builtins/atomics.ts index 41e35a511..5c72ed08c 100644 --- a/packages/compiler/src/frontend/lowering/builtins/atomics.ts +++ b/packages/compiler/src/frontend/lowering/builtins/atomics.ts @@ -60,10 +60,14 @@ export function lowerAtomicsCall( // has a concrete typed-array binding. Validate the actual lowered storage. const array = lowerer.lowerExpr(source); const type = array.type; + // An untyped array (a JavaScript `workerData` or field): the runtime + // checks its kind and throws Node's TypeError for any other value. + const dynamic = type?.kind === "dyn"; if ( - type?.kind !== "bytes" || - !["i8", "u8", "i16", "u16", "i32", "u32"].includes(type.elem) || - ((member === "wait" || member === "notify") && type.elem !== "i32") + !dynamic && + (type?.kind !== "bytes" || + !["i8", "u8", "i16", "u16", "i32", "u32"].includes(type.elem) || + ((member === "wait" || member === "notify") && type.elem !== "i32")) ) { lowerer.noLowering( `Atomics.${member} over this array`, @@ -82,7 +86,7 @@ export function lowerAtomicsCall( if (member === "wait") return { kind: "libCall", - fn: "atomics.wait", + fn: dynamic ? "atomics.waitDyn" : "atomics.wait", args: [array, index, arg(2, 0), arg(3, Infinity)], type: STRING, loc, @@ -90,14 +94,14 @@ export function lowerAtomicsCall( if (member === "notify") return { kind: "libCall", - fn: "atomics.notify", + fn: dynamic ? "atomics.notifyDyn" : "atomics.notify", args: [array, index, arg(2, Infinity)], type: F64, loc, }; return { kind: "libCall", - fn: "atomics.op", + fn: dynamic ? "atomics.opDyn" : "atomics.op", args: [array, index, arg(2, 0), arg(3, 0), number(operation)], type: F64, loc, diff --git a/packages/compiler/src/frontend/lowering/builtins/child-process-async.ts b/packages/compiler/src/frontend/lowering/builtins/child-process-async.ts index 5590fbe9f..d0991dce5 100644 --- a/packages/compiler/src/frontend/lowering/builtins/child-process-async.ts +++ b/packages/compiler/src/frontend/lowering/builtins/child-process-async.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "../stable-names.js"; import { recordToEnvPairs } from "./environment.js"; import { lowerChildArgsArg } from "./child-process.js"; import { boolLit, numLit, varRef } from "../../../ir/build.js"; @@ -218,7 +219,7 @@ function execFileAsyncHelper( const key = shell ? "execAsync" : "execFileAsync"; const existing = lowerer.valueHelpers.get(key); if (existing) return { name: existing, shapeId, envShapeId }; - const name = `%${key}.${lowerer.valueHelpers.size}`; + const name = keyedHelperName(lowerer, `%${key}`, key); lowerer.valueHelpers.set(key, name); const recT: IrType = { kind: "record", shapeId }; const envRecT: IrType = { kind: "record", shapeId: envShapeId }; diff --git a/packages/compiler/src/frontend/lowering/builtins/child-process-methods.ts b/packages/compiler/src/frontend/lowering/builtins/child-process-methods.ts index af7270ea9..2e0f305a0 100644 --- a/packages/compiler/src/frontend/lowering/builtins/child-process-methods.ts +++ b/packages/compiler/src/frontend/lowering/builtins/child-process-methods.ts @@ -1,4 +1,4 @@ -import { boolLit, strLit } from "../../../ir/build.js"; +import { boolLit, strLit, varRef } from "../../../ir/build.js"; import * as ts from "../../ts7/adapter.js"; import { requestGeneralStreamSurface } from "../general-streams.js"; import { type Lowerer } from "../lowerer.js"; @@ -93,32 +93,47 @@ export function lowerChildMethodCall( '"exit", "close", "error", "message", and "disconnect" are the supported child events (as literals)', ); } - if (!ts.isExpressionStatement(call.parent)) { - lowerer.unsupported( - "SC1090", - call, - `chaining child.${name}(...) (the result is void here — register each listener as its own statement)`, - ); - } - const receiver = lowerer.lowerExpr(access.expression); + // `child.on(...)` returns the child: a chained call or a stored result + // reads the receiver, which evaluates once, before the listener. + let receiver = lowerer.lowerExpr(access.expression); + const chained = ts.isExpressionStatement(call.parent) + ? null + : { + local: lowerer.declareHiddenLocal("%childListenerTarget", receiver.type), + init: receiver, + }; + if (chained) receiver = varRef(chained.local.id, chained.local.type, loc); + const registered = (registration: IrExpr): IrExpr => + chained === null + ? registration + : { + kind: "seqExpr", + stmts: [ + { kind: "varDecl", localId: chained.local.id, init: chained.init, loc }, + { kind: "exprStmt", expr: registration, loc }, + ], + result: varRef(chained.local.id, chained.local.type, loc), + type: chained.local.type, + loc, + }; const once: IrExpr = { kind: "boolLit", value: name === "once", type: BOOL, loc }; if (event === "message") { - return { + return registered({ kind: "libCall", fn: "child.onMessage", args: [receiver, ipcMessageListener(lowerer, call.arguments.nodes[1]!), once], type: VOID, loc, - }; + }); } if (event === "disconnect") { - return { + return registered({ kind: "libCall", fn: "child.onDisconnect", args: [receiver, ipcDisconnectListener(lowerer, call.arguments.nodes[1]!), once], type: VOID, loc, - }; + }); } const listenerNode = stripTypeCasts(call.arguments.nodes[1]!); if ( @@ -163,7 +178,7 @@ export function lowerChildMethodCall( call.arguments.nodes[1]!, ); } - return { + return registered({ kind: "libCall", fn: "child.onDyn", args: [ @@ -173,7 +188,7 @@ export function lowerChildMethodCall( ], type: VOID, loc, - }; + }); } if (event === "spawn") { if (cb.type.kind !== "func" || cb.type.params.length !== 0 || cb.type.ret.kind !== "void") { @@ -182,7 +197,13 @@ export function lowerChildMethodCall( call.arguments.nodes[1]!, ); } - return { kind: "libCall", fn: "child.onSpawn", args: [receiver, cb], type: VOID, loc }; + return registered({ + kind: "libCall", + fn: "child.onSpawn", + args: [receiver, cb], + type: VOID, + loc, + }); } if (cb.type.kind !== "func" || cb.type.params.length > (event === "error" ? 1 : 2)) { lowerer.unsupported( @@ -243,13 +264,13 @@ export function lowerChildMethodCall( `${event} listeners whose signal parameter is not 'Signals | null' (got '${lowerer.fmt(sigParam!)}')`, ); } - return { + return registered({ kind: "libCall", fn: event === "close" ? "child.onClose" : "child.onExit", args: [receiver, cb], type: VOID, loc, - }; + }); } if (param !== undefined && !(param.kind === "object" && param.className === "%Error")) { lowerer.unsupported( @@ -258,7 +279,13 @@ export function lowerChildMethodCall( `error listeners whose parameter is not 'Error' (got '${lowerer.fmt(param)}')`, ); } - return { kind: "libCall", fn: "child.onError", args: [receiver, cb], type: VOID, loc }; + return registered({ + kind: "libCall", + fn: "child.onError", + args: [receiver, cb], + type: VOID, + loc, + }); } // child.kill(signal?) — Node's semantics exactly: the name resolves // through Node's signal table (unknown names throw the ERR_UNKNOWN_SIGNAL diff --git a/packages/compiler/src/frontend/lowering/builtins/child-process-sync.ts b/packages/compiler/src/frontend/lowering/builtins/child-process-sync.ts index 24adcc1ba..b9858e768 100644 --- a/packages/compiler/src/frontend/lowering/builtins/child-process-sync.ts +++ b/packages/compiler/src/frontend/lowering/builtins/child-process-sync.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "../stable-names.js"; import { recordToEnvPairs } from "./environment.js"; import { lowerChildArgsArg } from "./child-process.js"; import { boolLit, numLit, strLit, varRef } from "../../../ir/build.js"; @@ -541,7 +542,7 @@ function execStdioModeHelper( const key = `cp.stdiomode:${shapeId}:${fd}`; const existing = lowerer.arrHofHelpers.get(key); if (existing) return existing; - const name = `%cp.stdioMode.${fd}.${lowerer.arrHofHelpers.size}`; + const name = keyedHelperName(lowerer, `%cp.stdioMode.${fd}`, key); lowerer.arrHofHelpers.set(key, name); const optsT: IrType = { kind: "record", shapeId }; diff --git a/packages/compiler/src/frontend/lowering/builtins/child-process.ts b/packages/compiler/src/frontend/lowering/builtins/child-process.ts index ea2dd379d..9096316a3 100644 --- a/packages/compiler/src/frontend/lowering/builtins/child-process.ts +++ b/packages/compiler/src/frontend/lowering/builtins/child-process.ts @@ -115,6 +115,8 @@ export function lowerSpawnSyncCall(lowerer: Lowerer, expr: ts.CallExpression, lo // "pipe"`) — accepted when its TYPE proves every arm is a supported // literal; the runtime maps the value to the modes at the call. let stdioStr: IrExpr | null = null; + // The `env` option's [k,v,...] pairs, which replace the child's environment. + let envPairs: IrExpr | null = null; let plain = true; // no behavior-changing option: the historical libCall if (optsNode) { @@ -227,11 +229,16 @@ export function lowerSpawnSyncCall(lowerer: Lowerer, expr: ts.CallExpression, lo case "windowsHide": lowerer.lowerExpr(m.value); // Node no-op on POSIX break; + case "env": + // A REPLACEMENT environment, as for spawn and execFileSync. + envPairs = recordToEnvPairs(lowerer, m.value); + plain = false; + break; default: lowerer.noLowering( `spawnSync option '${m.name}'`, p, - "encoding, timeout, killSignal, stdio, and windowsHide are the supported options", + "encoding, timeout, killSignal, stdio, env, and windowsHide are the supported options", ); } } @@ -239,6 +246,13 @@ export function lowerSpawnSyncCall(lowerer: Lowerer, expr: ts.CallExpression, lo if (plain) { return { kind: "libCall", fn: "cp.spawnSync", args: [cmd, argv], type: SPAWNRES_T, loc }; } + if (stdioStr !== null && envPairs !== null) { + lowerer.noLowering( + "spawnSync with a runtime stdio value and env", + optsNode!, + 'pass stdio as a "pipe"/"ignore"/"inherit" literal when env is set', + ); + } if (stdioStr !== null) { return { kind: "libCall", @@ -250,7 +264,7 @@ export function lowerSpawnSyncCall(lowerer: Lowerer, expr: ts.CallExpression, lo } return { kind: "libCall", - fn: "cp.spawnSyncOpts", + fn: envPairs !== null ? "cp.spawnSyncEnv" : "cp.spawnSyncOpts", args: [ cmd, argv, @@ -259,6 +273,7 @@ export function lowerSpawnSyncCall(lowerer: Lowerer, expr: ts.CallExpression, lo numLit(inMode, loc), numLit(outMode, loc), numLit(errMode, loc), + ...(envPairs !== null ? [envPairs] : []), ], type: SPAWNRES_T, loc, diff --git a/packages/compiler/src/frontend/lowering/builtins/crypto.ts b/packages/compiler/src/frontend/lowering/builtins/crypto.ts index f4270dbe8..47e66f9b2 100644 --- a/packages/compiler/src/frontend/lowering/builtins/crypto.ts +++ b/packages/compiler/src/frontend/lowering/builtins/crypto.ts @@ -1,12 +1,14 @@ import { lowerBuiltinByteInput, errorFirstBytesCallback, errorFirstCallback } from "./arguments.js"; import { isKeyObjectValue } from "./key-object.js"; import { lowerCreateEcdh } from "./ecdh.js"; +import { lowerCreateDiffieHellman, lowerGetDiffieHellman } from "./dh.js"; import { boolLit, dynUndefinedExpr, nodeThrowExpr, varRef } from "../../../ir/build.js"; import * as ts from "../../ts7/adapter.js"; import { type Lowerer, own } from "../lowerer.js"; import { locOf } from "../../program.js"; import { CIPHER_TYPE_NAMES } from "../../type-mapper.js"; import { CRYPTO_CIPHERS, CRYPTO_CURVES, CRYPTO_HASHES } from "../crypto-tables.js"; +import { stdlibGlobalNameOf } from "../surfaces.js"; import { BOOL, BYTES_U8, @@ -410,6 +412,9 @@ export function lowerCryptoModuleCall( }; } if (bi.member === "createECDH") return lowerCreateEcdh(lowerer, expr); + if (bi.member === "createDiffieHellman") return lowerCreateDiffieHellman(lowerer, expr); + if (bi.member === "getDiffieHellman" || bi.member === "createDiffieHellmanGroup") + return lowerGetDiffieHellman(lowerer, expr); if (bi.member === "createHmac") { if (args.length < 1 || args.length > 3 || args.some(ts.isSpreadElement)) { lowerer.noLowering( @@ -695,6 +700,10 @@ export function lowerCryptoModuleCall( loc, }; } + const pki = lowerPkiCall(lowerer, expr, bi.member, args, loc); + if (pki) return pki; + const prime = lowerPrimeCall(lowerer, expr, bi.member, args, loc); + if (prime) return prime; if (bi.member === "createSecretKey") { if (args.length < 1 || args.length > 2 || args.some(ts.isSpreadElement)) lowerer.noLowering( @@ -860,11 +869,29 @@ const IMPLEMENTED_CIPHERS = new Set([ "id-aes192-gcm", "id-aes256-gcm", "chacha20-poly1305", + ...["128", "192", "256"].flatMap((bits) => + ["ecb", "cfb", "cfb8", "cfb1", "ofb"].map((mode) => `aes-${bits}-${mode}`), + ), + "des-ede3-cbc", + "des3", + "des-ede3", + "des-ede3-ecb", + "des-ede3-cfb", + "des-ede3-cfb8", + "des-ede3-cfb1", + "des-ede3-ofb", + "des-ede-cbc", + "des-ede", + "des-ede-ecb", + "des-ede-cfb", + "des-ede-ofb", + "chacha20", ]); const SUPPORTED_CIPHERS_HINT = - "the supported ciphers are aes-128-cbc, aes-192-cbc, aes-256-cbc, aes-128-ctr, aes-192-ctr, " + - "aes-256-ctr, aes-128-gcm, aes-192-gcm, aes-256-gcm, and chacha20-poly1305"; + "the supported ciphers are aes-128, aes-192 and aes-256 in cbc, ctr, gcm, ecb, cfb, cfb8, cfb1 " + + "and ofb modes, des-ede3 in cbc, ecb, cfb, cfb8, cfb1 and ofb modes, des-ede in cbc, ecb, cfb " + + "and ofb modes, chacha20, and chacha20-poly1305"; /** A literal cipher name that Node knows but the runtime does not * implement is refused at compile time. Unknown literal names keep Node's @@ -907,7 +934,8 @@ export function v8CalleeText(node: ts.Expression): string { /** Calls on native Cipheriv/Decipheriv handles dispatch through the * handle's methods with checked-dynamic arguments. The stream.Transform - * members the classes inherit are refused. */ + * members the classes inherit lower over the cipher's Transform + * (lowerHashStreamCall, which runs first); other members are refused. */ export function lowerCipherMethodCall( lowerer: Lowerer, call: ts.CallExpression, @@ -920,7 +948,7 @@ export function lowerCipherMethodCall( lowerer.noLowering( `Cipheriv/Decipheriv.${name}`, call, - "update(), final(), setAAD(), setAutoPadding(), getAuthTag(), and setAuthTag() are supported; cipher streams are not", + "update(), final(), setAAD(), setAutoPadding(), getAuthTag(), setAuthTag(), and the stream members are supported", ); } if (call.arguments.nodes.some(ts.isSpreadElement)) @@ -1316,8 +1344,10 @@ export function lowerCryptoGetRandomValues( } /** Whether `receiver` names a WebCrypto Crypto object: the `crypto` - * global (also through globalThis) or node:crypto's `webcrypto`. */ + * global (also through globalThis or an alias of it) or node:crypto's + * `webcrypto`. */ export function isWebCryptoReceiver(lowerer: Lowerer, receiver: ts.Expression): boolean { + if (stdlibGlobalNameOf(lowerer, receiver) === "crypto") return true; if (ts.isIdentifier(receiver)) { if (receiver.text === "crypto" && lowerer.isStdlibGlobal(receiver, "crypto")) return true; const imported = lowerer.builtinImportOf(receiver); @@ -1335,3 +1365,108 @@ export function isWebCryptoReceiver(lowerer: Lowerer, receiver: ts.Expression): } return false; } + +/** Node calls checkPrime's and generatePrime's callbacks with undefined as + * the error, where @types/node declares Error | null: whether this + * callback's error parameter can hold undefined. One that cannot receives + * null instead. */ +function takesUndefinedError(lowerer: Lowerer, callback: ts.Expression): boolean { + const type = lowerer.irTypeOf(callback); + if (type.kind !== "func") return true; + const error = type.params[0]; + if (error === undefined || error.kind === "dyn" || error.kind === "undefinedT") return true; + if (error.kind !== "union") return false; + return !!lowerer.unions.get(error.unionId)?.arms.some((arm) => arm.kind === "undefinedT"); +} + +/** checkPrime, checkPrimeSync, generatePrime and generatePrimeSync + * (scr_dh.c): checked-dynamic arguments, which the runtime checks as Node + * does (a function in the options position is the callback), and the + * sync forms' boolean, ArrayBuffer or bigint converted to the call site's + * type. Null for other members. */ +function lowerPrimeCall( + lowerer: Lowerer, + expr: ts.CallExpression, + member: string, + args: readonly ts.Expression[], + loc: SrcLoc, +): IrExpr | null { + const forms: Readonly> = { + checkPrimeSync: ["crypto.checkPrimeSync", 1, 2, "checkPrimeSync(candidate[, options])"], + checkPrime: ["crypto.checkPrimeCb", 1, 3, "checkPrime(candidate[, options], callback)"], + generatePrimeSync: ["crypto.generatePrimeSync", 1, 2, "generatePrimeSync(size[, options])"], + generatePrime: ["crypto.generatePrimeCb", 1, 3, "generatePrime(size[, options], callback)"], + }; + const form = forms[member]; + if (!form) return null; + const [fn, min, max, supported] = form; + if (args.length < min || args.length > max || args.some(ts.isSpreadElement)) + lowerer.noLowering( + `crypto.${member} with ${args.length} arguments`, + expr, + `${supported} is supported`, + ); + const values = Array.from({ length: max }, (_, i) => dynArg(lowerer, args[i], loc)); + if (fn === "crypto.checkPrimeCb" || fn === "crypto.generatePrimeCb") { + const callback = args[args.length - 1]; + const nullError = callback !== undefined && !takesUndefinedError(lowerer, callback); + values.push({ kind: "boolLit", value: nullError, type: BOOL, loc }); + return { kind: "libCall", fn, args: values, type: VOID, loc }; + } + const call: IrExpr = { kind: "libCall", fn, args: values, type: DYN, loc }; + const result = lowerer.mapTypeOf(lowerer.typeOf(expr)); + if (result === null || result.kind === "dyn") return call; + return lowerer.coerceInto(expr, call, result); +} + +/** The asymmetric-key and signature members (scr_pki.c): checked-dynamic + * arguments, and the result converted to the call site's type + * (KeyObject, Sign and Verify are checked-dynamic handles; key pairs, + * signatures and verdicts convert to their records, Buffers and + * booleans). Null for other members. */ +function lowerPkiCall( + lowerer: Lowerer, + expr: ts.CallExpression, + member: string, + args: readonly ts.Expression[], + loc: SrcLoc, +): IrExpr | null { + const forms: Readonly> = { + createPrivateKey: ["crypto.createPrivateKey", 1, 1, "createPrivateKey(key)"], + createPublicKey: ["crypto.createPublicKey", 1, 1, "createPublicKey(key)"], + generateKeyPairSync: ["crypto.generateKeyPairSync", 1, 2, "generateKeyPairSync(type, options)"], + generateKeyPair: [ + "crypto.generateKeyPairCb", + 2, + 3, + "generateKeyPair(type, [options,] callback)", + ], + sign: ["crypto.signOneshot", 3, 3, "sign(algorithm, data, key)"], + verify: ["crypto.verifyOneshot", 4, 4, "verify(algorithm, data, key, signature)"], + createSign: ["crypto.createSign", 1, 1, "createSign(algorithm)"], + createVerify: ["crypto.createVerify", 1, 1, "createVerify(algorithm)"], + }; + const form = forms[member]; + if (!form) return null; + const [fn, min, max, supported] = form; + if (args.length < min || args.length > max) + lowerer.noLowering( + `crypto.${member} with ${args.length} arguments`, + expr, + `${supported} is supported`, + ); + // generateKeyPair(type, callback): Node reads a function in the options + // position as the callback. + const shifted = fn === "crypto.generateKeyPairCb" && args.length === 2; + const values: IrExpr[] = []; + for (let i = 0; i < max; i++) { + const node = shifted ? (i === 1 ? undefined : i === 2 ? args[1] : args[i]) : args[i]; + values.push(dynArg(lowerer, node, loc)); + } + if (fn === "crypto.generateKeyPairCb") + return { kind: "libCall", fn, args: values, type: VOID, loc }; + const call: IrExpr = { kind: "libCall", fn, args: values, type: DYN, loc }; + const result = lowerer.mapTypeOf(lowerer.typeOf(expr)); + if (result === null || result.kind === "dyn") return call; + return lowerer.coerceInto(expr, call, result); +} diff --git a/packages/compiler/src/frontend/lowering/builtins/date-classes.ts b/packages/compiler/src/frontend/lowering/builtins/date-classes.ts new file mode 100644 index 000000000..a2b0fc20a --- /dev/null +++ b/packages/compiler/src/frontend/lowering/builtins/date-classes.ts @@ -0,0 +1,552 @@ +import * as ts from "../../ts7/adapter.js"; +import { type Lowerer } from "../lowerer.js"; +import { locOf } from "../../program.js"; +import { type ClassInfo } from "../lower-classes.js"; +import { DATE_METHOD_HINT, dateJsonType, dateValueMethod } from "./dates.js"; +import { dynUndefinedExpr, varRef } from "../../../ir/build.js"; +import { + BOOL, + DATE_T, + DYN, + F64, + NULL_T, + STRING, + VOID, + typeKey, + type IrExpr, + type IrStmt, + type IrType, + type SrcLoc, +} from "../../../ir/ir.js"; + +/** The hidden field holding the time value of a class declared `extends + * Date`, the first field of its layout. */ +export const DATE_TIME_FIELD = "%time"; + +/** The class declared `extends Date` at the root of `info`'s base chain, or + * null. */ +export function dateRootOf(info: ClassInfo | null | undefined): ClassInfo | null { + for (let c = info ?? null; c; c = c.base) if (c.extendsDate) return c; + return null; +} + +/** Whether the program declares a class that extends Date. */ +export function programDeclaresDateClass(lowerer: Lowerer): boolean { + for (const info of lowerer.classes.values()) if (info.extendsDate) return true; + return false; +} + +/** The Date.prototype methods a class declared `extends Date` inherits. + * Those without a lowering refuse at the call. */ +const DATE_PROTOTYPE_METHODS: ReadonlySet = new Set([ + "getTime", + "valueOf", + "toISOString", + "toUTCString", + "toJSON", + "toString", + "toDateString", + "toTimeString", + "toGMTString", + "toLocaleString", + "toLocaleDateString", + "toLocaleTimeString", + "getFullYear", + "getUTCFullYear", + "getYear", + "getMonth", + "getUTCMonth", + "getDate", + "getUTCDate", + "getDay", + "getUTCDay", + "getHours", + "getUTCHours", + "getMinutes", + "getUTCMinutes", + "getSeconds", + "getUTCSeconds", + "getMilliseconds", + "getUTCMilliseconds", + "getTimezoneOffset", + "setTime", + "setFullYear", + "setUTCFullYear", + "setYear", + "setMonth", + "setUTCMonth", + "setDate", + "setUTCDate", + "setHours", + "setUTCHours", + "setMinutes", + "setUTCMinutes", + "setSeconds", + "setUTCSeconds", + "setMilliseconds", + "setUTCMilliseconds", +]); + +export const DATE_PROTOTYPE_METHOD_NAMES: readonly string[] = [...DATE_PROTOTYPE_METHODS]; + +export function isDatePrototypeMethod(name: string): boolean { + return DATE_PROTOTYPE_METHODS.has(name); +} + +/** Whether `name` is a Date method an instance of `info` inherits from + * Date.prototype: its class chain is rooted at a class declared `extends + * Date` and declares no member of that name. The runtime's view of the + * instance answers it (scr_dyn_date_class_method). */ +export function dateInheritedMember(lowerer: Lowerer, info: ClassInfo, name: string): boolean { + return ( + dateRootOf(info) !== null && + DATE_PROTOTYPE_METHODS.has(name) && + !lowerer.findMethodOn(info, name) && + !info.fields.has(name) + ); +} + +/** super(...args) in a class declared `extends Date`: the time value the + * Date constructor computes from the argument vector `args` (one dyn + * array), stored in the hidden field. */ +export function dateSuperCall(thisRef: IrExpr, info: ClassInfo, args: IrExpr, loc: SrcLoc): IrStmt { + return { + kind: "fieldSet", + obj: thisRef, + className: info.def.name, + field: DATE_TIME_FIELD, + value: { kind: "libCall", fn: "date.argumentsTime", args: [args], type: DATE_T, loc }, + loc, + }; +} + +/** The time value of `receiver`, an instance of a class rooted at `root`. */ +function timeOf(lowerer: Lowerer, receiver: IrExpr, root: ClassInfo, loc: SrcLoc): IrExpr { + return { + kind: "fieldGet", + obj: lowerer.upcastTo(receiver, root.def.name), + className: root.def.name, + field: DATE_TIME_FIELD, + type: DATE_T, + loc, + }; +} + +/** `receiver.name()` with no arguments where the static class `info` does + * not declare `name`: the subclasses of `info` that declare it run theirs, + * any other instance the Date method. `receiver` is a variable read. */ +function instanceMethodCall( + lowerer: Lowerer, + blame: ts.Node, + info: ClassInfo, + receiver: IrExpr, + name: string, + inherited: IrExpr, + loc: SrcLoc, +): IrExpr { + const found = lowerer.findMethodOn(info, name); + if (found) { + if (found.sig.params.length > 0) + lowerer.unsupported( + "SC1090", + blame, + `a '${name}' declaration with parameters in a class that extends Date, called by an inherited Date method`, + ); + const args: IrExpr[] = []; + if (lowerer.overrideBelow(info, name)) { + lowerer.noteVirtualEdge(info, name); + return { + kind: "virtualCall", + className: info.def.name, + method: name, + args: [lowerer.upcastTo(receiver, info.def.name), ...args], + type: found.sig.ret, + loc, + }; + } + lowerer.noteEdge(`%${found.declarer.def.name}.${name}`); + return { + kind: "call", + callee: `%${found.declarer.def.name}.${name}`, + args: [lowerer.upcastTo(receiver, found.declarer.def.name), ...args], + type: found.sig.ret, + loc, + }; + } + let result = inherited; + // Deeper declarations are tested first. + const declaring: ClassInfo[] = []; + const visit = (c: ClassInfo): void => { + for (const sub of c.subclasses) { + if (sub.methods.has(name)) declaring.push(sub); + else visit(sub); + } + }; + visit(info); + for (const sub of declaring) { + const call = instanceMethodCall( + lowerer, + blame, + sub, + { kind: "downcast", value: receiver, type: { kind: "object", className: sub.def.name }, loc }, + name, + inherited, + loc, + ); + const type = result.type; + result = { + kind: "ternary", + cond: { kind: "instanceOf", value: receiver, className: sub.def.name, type: BOOL, loc }, + then: lowerer.coerceToExpected(call, type), + else_: result, + type, + loc, + }; + } + return result; +} + +/** ToNumber of `value`, the lowered value of `node`. */ +function numberValue(lowerer: Lowerer, node: ts.Expression, value: IrExpr, loc: SrcLoc): IrExpr { + if (value.type.kind === "f64") return value; + if (value.type.kind === "dyn") + return { kind: "libCall", fn: "dyn.toNumberCoerce", args: [value], type: F64, loc }; + if (lowerer.dynConvertible(value.type)) + return { + kind: "libCall", + fn: "dyn.toNumberCoerce", + args: [{ kind: "dynFrom", value, type: DYN, loc }], + type: F64, + loc, + }; + return lowerer.coerceInto(node, value, F64); +} + +/** A Date.prototype method a class rooted at `root` does not declare, + * called on `receiver` (an instance of `info`, evaluated here once). The + * method reads or sets the hidden time value; toJSON calls the instance's + * toISOString, as Date.prototype.toJSON does. */ +export function lowerInheritedDateMethodCall( + lowerer: Lowerer, + call: ts.CallExpression, + name: string, + info: ClassInfo, + receiver: IrExpr, +): IrExpr { + const root = dateRootOf(info)!; + const loc = locOf(call); + const local = lowerer.declareHiddenLocal("%dateReceiver", receiver.type); + const value = varRef(local.id, receiver.type, loc); + const stmts: IrStmt[] = [{ kind: "varDecl", localId: local.id, init: receiver, loc }]; + const args = call.arguments.nodes; + if (args.some(ts.isSpreadElement)) + lowerer.unsupported("SC1090", call, `spread arguments to 'Date.prototype.${name}'`); + const done = (result: IrExpr): IrExpr => ({ + kind: "seqExpr", + stmts, + result, + type: result.type, + loc, + }); + if (name === "setTime") { + // Every argument is evaluated before setTime converts the first one. + let ms: IrExpr = { kind: "numLit", value: Number.NaN, type: F64, loc }; + if (args[0]) { + const first = lowerer.lowerExpr(args[0]); + const saved = lowerer.declareHiddenLocal("%dateArgument", first.type); + stmts.push({ kind: "varDecl", localId: saved.id, init: first, loc: locOf(args[0]) }); + ms = numberValue(lowerer, args[0], varRef(saved.id, first.type, loc), loc); + } + for (const arg of args.slice(1)) + stmts.push({ kind: "exprStmt", expr: lowerer.lowerExpr(arg), loc: locOf(arg) }); + const time = lowerer.declareHiddenLocal("%dateTime", DATE_T); + stmts.push( + { + kind: "varDecl", + localId: time.id, + init: { kind: "libCall", fn: "date.newMs", args: [ms], type: DATE_T, loc }, + loc, + }, + { + kind: "fieldSet", + obj: lowerer.upcastTo(value, root.def.name), + className: root.def.name, + field: DATE_TIME_FIELD, + value: varRef(time.id, DATE_T, loc), + loc, + }, + ); + return done({ + kind: "libCall", + fn: "date.getTime", + args: [varRef(time.id, DATE_T, loc)], + type: F64, + loc, + }); + } + for (const arg of args) { + if (name !== "toJSON") + lowerer.noLowering(`Date.prototype.${name} with arguments`, call, DATE_METHOD_HINT); + stmts.push({ kind: "exprStmt", expr: lowerer.lowerExpr(arg), loc: locOf(arg) }); + } + if (name === "toJSON") return done(dateClassToJson(lowerer, call, info, value, loc)); + const result = dateValueMethod(name, timeOf(lowerer, value, root, loc), loc); + if (!result) lowerer.noLowering(`Date.prototype.${name}`, call, DATE_METHOD_HINT); + return done(result); +} + +/** Date.prototype.toJSON on `value` (a variable read of an instance of + * `info`): null for an invalid time, else the instance's toISOString(). */ +function dateClassToJson( + lowerer: Lowerer, + blame: ts.Node, + info: ClassInfo, + value: IrExpr, + loc: SrcLoc, +): IrExpr { + const root = dateRootOf(info)!; + const time: IrExpr = { + kind: "libCall", + fn: "date.getTime", + args: [timeOf(lowerer, value, root, loc)], + type: F64, + loc, + }; + const type = dateJsonType(lowerer); + const iso = instanceMethodCall( + lowerer, + blame, + info, + value, + "toISOString", + { + kind: "libCall", + fn: "date.toISOStringValue", + args: [timeOf(lowerer, value, root, loc)], + type: STRING, + loc, + }, + loc, + ); + return { + kind: "ternary", + // An invalid date's time value is NaN, the one value unequal to itself. + cond: { kind: "bin", op: "!==", left: time, right: time, type: BOOL, loc }, + then: lowerer.coerceToExpected({ kind: "unitLit", unit: "null", type: NULL_T, loc }, type), + else_: lowerer.coerceToExpected(iso, type), + type, + loc, + }; +} + +/** `super.name(...)` in a class whose base chain declares no `name`, when + * the chain is rooted at a class declared `extends Date`. */ +export function lowerDateSuperMethodCall( + lowerer: Lowerer, + call: ts.CallExpression, + name: string, + cls: ClassInfo, + thisRef: IrExpr, +): IrExpr | null { + if (!dateRootOf(cls) || !isDatePrototypeMethod(name)) return null; + // Date.prototype.toJSON reads this.toISOString, which this class or a + // subclass may declare. + return lowerInheritedDateMethodCall(lowerer, call, name, cls, thisRef); +} + +const DATE_CLASS_TIME = "%date.classTime"; +const DATE_CLASS_METHOD = "%date.classMethod"; + +/** The classes of a program rooted at a class declared `extends Date`. */ +function dateClasses(lowerer: Lowerer): ClassInfo[] { + return [...lowerer.classes.values()].filter( + (info) => !info.def.runtime && !info.generic && dateRootOf(info) !== null, + ); +} + +const PARAMS = ["op", "value", "argument"]; + +/** A lifted `(op, value, argument)` function over checked-dynamic values. */ +function liftOperation(lowerer: Lowerer, name: string, body: IrStmt[], loc: SrcLoc): void { + lowerer.liftedFns.push({ + name, + params: PARAMS.map((p) => ({ localId: p, name: p, type: DYN })), + returnType: DYN, + locals: PARAMS.map((p) => ({ id: p, name: p, type: DYN, mutable: false })), + body, + loc, + }); +} + +function opIs(code: number, loc: SrcLoc): IrExpr { + return { + kind: "bin", + op: "===", + left: { kind: "dynCheck", value: varRef("op", DYN, loc), type: F64, loc }, + right: { kind: "numLit", value: code, type: F64, loc }, + type: BOOL, + loc, + }; +} + +/** Lifts `%date.classMethod(op, value, argument)` when the program declares + * a class that extends Date: ops 2 to 5 call `value`'s toISOString, + * toJSON(argument), toString and valueOf as checked-dynamic method calls, + * which the class dispatch resolves to each class's declarations and the + * runtime to the inherited Date methods. Called before the class dispatch + * runs over the lowered functions. */ +export function noteDateClassMethods(lowerer: Lowerer): void { + if (lowerer.liftedFnNamed(DATE_CLASS_METHOD)) return; + const classes = dateClasses(lowerer); + if (classes.length === 0) return; + const loc = classes[0]!.def.loc; + const value = varRef("value", DYN, loc); + const body: IrStmt[] = ["toISOString", "toJSON", "toString", "valueOf"].map( + (method, index): IrStmt => ({ + kind: "if", + cond: opIs(index + 2, loc), + then: [ + { + kind: "return", + value: { + kind: "dynInvoke", + recv: value, + method, + calleeName: method, + args: method === "toJSON" ? [varRef("argument", DYN, loc)] : [], + type: DYN, + loc, + }, + loc, + }, + ], + else_: null, + loc, + }), + ); + body.push({ kind: "return", value: dynUndefinedExpr(loc), loc }); + liftOperation(lowerer, DATE_CLASS_METHOD, body, loc); +} + +/** %main's installation of the functions the runtime calls for a + * checked-dynamic value that holds an instance of a class declared `extends + * Date` (scr_date_class_operation_install). `%date.classTime(op, value, + * argument)` answers the time value for op 0 (undefined for any other + * value), sets it from the number `argument` for op 1 and answers the + * class's name for op 6; `%date.classMethod` (noteDateClassMethods) calls + * its methods. */ +export function dateClassOperationPrelude(lowerer: Lowerer, loc: SrcLoc): IrStmt[] { + const classes = dateClasses(lowerer); + if (classes.length === 0) return []; + noteDateClassMethods(lowerer); + const value = varRef("value", DYN, loc); + const argument = varRef("argument", DYN, loc); + const body: IrStmt[] = []; + for (const info of classes) { + const root = dateRootOf(info)!; + const type: IrType = { kind: "object", className: info.def.name }; + const instance: IrExpr = { kind: "dynCheck", value, type, loc }; + body.push({ + kind: "if", + cond: { + kind: "libCall", + fn: "dyn.typedRefIs", + args: [value, { kind: "strLit", value: typeKey(type), type: STRING, loc }], + type: BOOL, + loc, + }, + then: [ + { + kind: "if", + cond: opIs(6, loc), + then: [ + { + kind: "return", + value: { + kind: "dynFrom", + value: { + kind: "strLit", + value: info.def.jsName ?? info.def.name, + type: STRING, + loc, + }, + type: DYN, + loc, + }, + loc, + }, + ], + else_: null, + loc, + }, + { + kind: "if", + cond: opIs(1, loc), + then: [ + { + kind: "fieldSet", + obj: lowerer.upcastTo(instance, root.def.name), + className: root.def.name, + field: DATE_TIME_FIELD, + value: { + kind: "libCall", + fn: "date.newMs", + args: [{ kind: "dynCheck", value: argument, type: F64, loc }], + type: DATE_T, + loc, + }, + loc, + }, + ], + else_: null, + loc, + }, + { + kind: "return", + value: { + kind: "dynFrom", + value: { + kind: "libCall", + fn: "date.getTime", + args: [timeOf(lowerer, instance, root, loc)], + type: F64, + loc, + }, + type: DYN, + loc, + }, + loc, + }, + ], + else_: null, + loc, + }); + } + body.push({ kind: "return", value: dynUndefinedExpr(loc), loc }); + liftOperation(lowerer, DATE_CLASS_TIME, body, loc); + const closure = (fnName: string): IrExpr => ({ + kind: "dynFrom", + value: { + kind: "closure", + fnName, + captures: [], + type: { kind: "func", params: [DYN, DYN, DYN], ret: DYN }, + loc, + }, + type: DYN, + loc, + }); + return [ + { + kind: "exprStmt", + expr: { + kind: "libCall", + fn: "date.classOperation", + args: [closure(DATE_CLASS_TIME), closure(DATE_CLASS_METHOD)], + type: VOID, + loc, + }, + loc, + }, + ]; +} diff --git a/packages/compiler/src/frontend/lowering/builtins/dates.ts b/packages/compiler/src/frontend/lowering/builtins/dates.ts index 31be995e7..a598f4ee6 100644 --- a/packages/compiler/src/frontend/lowering/builtins/dates.ts +++ b/packages/compiler/src/frontend/lowering/builtins/dates.ts @@ -1,6 +1,8 @@ import * as ts from "../../ts7/adapter.js"; import { type Lowerer, own } from "../lowerer.js"; import { locOf } from "../../program.js"; +import { tryLowerExpression } from "../expressions/try-lower-expression.js"; +import { programDeclaresDateClass } from "./date-classes.js"; import { BOOL, F64, @@ -9,6 +11,7 @@ import { type IrStmt, type IrType, NULL_T, + type SrcLoc, STRING, typeKey, } from "../../../ir/ir.js"; @@ -39,7 +42,7 @@ const DATE_TEXT_FNS: ReadonlyMap = new Map([ ["toTimeString", "date.toTimeString"], ]); -const DATE_METHOD_HINT = +export const DATE_METHOD_HINT = "getTime(), valueOf(), toISOString(), toUTCString(), toJSON(), toString(), toDateString(), toTimeString(), the local/UTC calendar getters, and getTimezoneOffset() are supported; Date setters and locale formatters have no lowering"; /** The Date slice: statics plus read-only Date values backed by one @@ -52,7 +55,52 @@ export function lowerDateCall( ): IrExpr | null { if (call.questionDotToken || access.questionDotToken) return null; const loc = locOf(call); - if (lowerer.stdlibGlobalMember(access, "Date") === "now") { + const member = lowerer.stdlibGlobalMember(access, "Date"); + if (member === "now" || member === "parse" || member === "UTC") + return lowerDateStaticCall(lowerer, call, member); + if (lowerer.mapTypeOf(lowerer.typeOf(access.expression))?.kind !== "date") return null; + if (!lowerer.isStdlibMember(access)) return null; + const name = access.name.text; + // A Date a JavaScript file constructs is a mutable object; setTime on + // it takes the dynamic method call. So does every Date method on a + // checked-dynamic receiver when the program declares a class that extends + // Date: the value can be an instance, whose class may declare the method. + if ( + (name === "setTime" || programDeclaresDateClass(lowerer)) && + tryLowerExpression(lowerer, access.expression)?.type.kind === "dyn" + ) + return null; + if (name === "toJSON") return lowerDateToJson(lowerer, call, access); + if (call.arguments.nodes.length !== 0) { + lowerer.noLowering(`Date.prototype.${name} with arguments`, call, DATE_METHOD_HINT); + } + const raw = lowerer.lowerExpr(access.expression); + const receiver: IrExpr = + raw.type.kind === "dyn" + ? { kind: "libCall", fn: "date.checkedValue", args: [raw], type: { kind: "date" }, loc } + : raw; + if (receiver.type.kind !== "date") + lowerer.badType(access.expression, lowerer.typeOf(access.expression)); + const result = dateValueMethod(name, receiver, loc); + if (result) return result; + lowerer.noLowering( + `Date.prototype.${name}`, + call, + DATE_METHOD_HINT, + lowerer.checker.getSymbolAtLocation(access.name), + ); +} + +/** Date.now(), Date.parse(text) and Date.UTC(...), also called through a + * class declared `extends Date`, which inherits them. Null for other + * names. */ +export function lowerDateStaticCall( + lowerer: Lowerer, + call: ts.CallExpression, + name: string, +): IrExpr | null { + const loc = locOf(call); + if (name === "now") { if (call.arguments.nodes.length !== 0) { lowerer.noLowering(`Date.now with ${call.arguments.nodes.length} arguments`, call); } @@ -60,7 +108,7 @@ export function lowerDateCall( } // 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 (name === "parse") { if (call.arguments.nodes.length !== 1 || ts.isSpreadElement(call.arguments.nodes[0]!)) { lowerer.noLowering(`Date.parse with ${call.arguments.nodes.length} arguments`, call); } @@ -72,7 +120,7 @@ export function lowerDateCall( // TimeClip. Omitted trailing arguments complete with the spec's // defaults (month 0, date 1, time parts 0); tsc pins every present // argument to number, so the seven-f64 ABI is exact. - if (lowerer.stdlibGlobalMember(access, "Date") === "UTC") { + if (name === "UTC") { if ( call.arguments.nodes.length < 1 || call.arguments.nodes.length > 7 || @@ -92,49 +140,38 @@ export function lowerDateCall( } return { kind: "libCall", fn: "date.utc", args, type: F64, loc }; } - if (lowerer.mapTypeOf(lowerer.typeOf(access.expression))?.kind !== "date") return null; - if (!lowerer.isStdlibMember(access)) return null; - const name = access.name.text; - if (name === "toJSON") return lowerDateToJson(lowerer, call, access); - if (call.arguments.nodes.length !== 0) { - lowerer.noLowering(`Date.prototype.${name} with arguments`, call, DATE_METHOD_HINT); - } - const raw = lowerer.lowerExpr(access.expression); - const receiver: IrExpr = - raw.type.kind === "dyn" - ? { kind: "libCall", fn: "date.checkedValue", args: [raw], type: { kind: "date" }, loc } - : raw; - if (receiver.type.kind !== "date") - lowerer.badType(access.expression, lowerer.typeOf(access.expression)); + return null; +} + +/** The Date methods without arguments that have a lowering, applied to the + * time value `value` (a `date`): getTime, valueOf, toISOString, + * toUTCString, the calendar getters and the text forms. Null for other + * names. */ +export function dateValueMethod(name: string, value: IrExpr, loc: SrcLoc): IrExpr | null { if (name === "getTime" || name === "valueOf") { return { kind: "libCall", fn: name === "getTime" ? "date.getTime" : "date.valueOf", - args: [receiver], + args: [value], type: F64, loc, }; } if (name === "toISOString") { - return { kind: "libCall", fn: "date.toISOStringValue", args: [receiver], type: STRING, loc }; + return { kind: "libCall", fn: "date.toISOStringValue", args: [value], type: STRING, loc }; } if (name === "toUTCString") { - return { kind: "libCall", fn: "date.toUTCString", args: [receiver], type: STRING, loc }; + return { kind: "libCall", fn: "date.toUTCString", args: [value], type: STRING, loc }; } const fn = own(DATE_GETTER_FNS, name); if (fn !== undefined) { - return { kind: "libCall", fn, args: [receiver], type: F64, loc }; + return { kind: "libCall", fn, args: [value], type: F64, loc }; } const textFn = DATE_TEXT_FNS.get(name); if (textFn !== undefined) { - return { kind: "libCall", fn: textFn, args: [receiver], type: STRING, loc }; + return { kind: "libCall", fn: textFn, args: [value], type: STRING, loc }; } - lowerer.noLowering( - `Date.prototype.${name}`, - call, - DATE_METHOD_HINT, - lowerer.checker.getSymbolAtLocation(access.name), - ); + return null; } /** `d.toJSON(key?)`: Node answers null for an invalid date and the diff --git a/packages/compiler/src/frontend/lowering/builtins/dh.ts b/packages/compiler/src/frontend/lowering/builtins/dh.ts new file mode 100644 index 000000000..eea5a4813 --- /dev/null +++ b/packages/compiler/src/frontend/lowering/builtins/dh.ts @@ -0,0 +1,166 @@ +import * as ts from "../../ts7/adapter.js"; +import { nodeThrowExpr } from "../../../ir/build.js"; +import { type Lowerer } from "../lowerer.js"; +import { locOf } from "../../program.js"; +import { DYN, type IrExpr, type IrStmt } from "../../../ir/ir.js"; +import { v8CalleeText } from "./crypto.js"; +import { dynArguments, refuseUnmatchedOverload } from "./ecdh.js"; + +/* node:crypto's DiffieHellman and DiffieHellmanGroup are native + * checked-dynamic handles (scr_dh.c): both types map to dyn, their methods + * dispatch through the handle, and these helpers lower + * createDiffieHellman, getDiffieHellman, createDiffieHellmanGroup and the + * method calls. The runtime applies Node's argument checks, so the + * constructors take any arguments; method calls are refused when their + * argument types leave the Buffer or string result undetermined. */ + +/** Whether a checker type is node:crypto's DiffieHellman class or its + * DiffieHellmanGroup alias, or a union of them. */ +export function isDiffieHellmanType(lowerer: Lowerer, type: ts.Type): boolean { + if (type.isUnionType()) + return ts.constituentTypes(type).every((part) => isDiffieHellmanType(lowerer, part)); + const symbol = type.getAliasSymbol() ?? type.getSymbol(); + if (!symbol || !lowerer.isStdlibSymbol(symbol)) return false; + const name = ts.symbolName(symbol); + return name === "DiffieHellman" || name === "DiffieHellmanGroup"; +} + +function isDiffieHellmanGroupType(type: ts.Type): boolean { + if (type.isUnionType()) return ts.constituentTypes(type).some(isDiffieHellmanGroupType); + const symbol = type.getAliasSymbol(); + return !!symbol && ts.symbolName(symbol) === "DiffieHellmanGroup"; +} + +function newHandle( + lowerer: Lowerer, + call: ts.CallExpression, + fn: "crypto.dhNew" | "crypto.dhGroupNew", +): IrExpr { + const loc = locOf(call); + const stmts: IrStmt[] = []; + const values = dynArguments(lowerer, call, fn === "crypto.dhNew" ? 4 : 1, stmts, "%dhInput"); + return { + kind: "seqExpr", + stmts, + result: { kind: "libCall", fn, args: values, type: DYN, loc }, + type: DYN, + loc, + }; +} + +/** crypto.createDiffieHellman(sizeOrKey, keyEncoding, generator, + * generatorEncoding): a native DiffieHellman handle. */ +export function lowerCreateDiffieHellman(lowerer: Lowerer, call: ts.CallExpression): IrExpr { + return newHandle(lowerer, call, "crypto.dhNew"); +} + +/** crypto.getDiffieHellman(groupName) and createDiffieHellmanGroup(name): + * a native DiffieHellmanGroup handle. */ +export function lowerGetDiffieHellman(lowerer: Lowerer, call: ts.CallExpression): IrExpr { + return newHandle(lowerer, call, "crypto.dhGroupNew"); +} + +const DH_METHODS = new Set([ + "generateKeys", + "computeSecret", + "getPrime", + "getGenerator", + "getPublicKey", + "getPrivateKey", + "setPublicKey", + "setPrivateKey", +]); + +/** Object.prototype methods, which a DiffieHellman inherits. */ +const OBJECT_METHODS = new Set([ + "constructor", + "hasOwnProperty", + "isPrototypeOf", + "propertyIsEnumerable", + "toLocaleString", + "toString", + "valueOf", +]); + +/** The argument that selects each method's Buffer or string result: the + * output encoding. */ +const OUTPUT_ENCODING_ARG: Record = { + generateKeys: 0, + computeSecret: 2, + getPrime: 0, + getGenerator: 0, + getPublicKey: 0, + getPrivateKey: 0, +}; + +/** An output encoding typed any: the checker's chosen overload then types + * the result as a Buffer or a string that Node may not answer, so the call + * is refused rather than checked against that type at run time. */ +function refuseAnyOutputEncoding(lowerer: Lowerer, call: ts.CallExpression, name: string): void { + const index = OUTPUT_ENCODING_ARG[name]; + const arg = index === undefined ? undefined : call.arguments.nodes[index]; + if (!arg || (lowerer.typeOf(arg).flags & ts.TypeFlags.Any) === 0) return; + lowerer.noLowering( + `DiffieHellman.${name} with an output encoding typed any`, + arg, + "type the encoding as a BinaryToTextEncoding such as 'hex', or as null or undefined for a Buffer", + ); +} + +/** Calls on native DiffieHellman and DiffieHellmanGroup handles. Methods + * dispatch through the handle with checked-dynamic arguments. */ +export function lowerDiffieHellmanCall(lowerer: Lowerer, call: ts.CallExpression): IrExpr | null { + if (call.questionDotToken || !ts.isPropertyAccessExpression(call.expression)) return null; + const access = call.expression; + if (access.questionDotToken) return null; + const receiver = lowerer.typeOf(access.expression); + if (!isDiffieHellmanType(lowerer, receiver)) return null; + const name = access.name.text; + const loc = locOf(call); + const setter = name === "setPublicKey" || name === "setPrivateKey"; + if (!DH_METHODS.has(name) || (setter && isDiffieHellmanGroupType(receiver))) { + if (OBJECT_METHODS.has(name)) + lowerer.noLowering( + `DiffieHellman.${name}`, + call, + "generateKeys(), computeSecret(), getPrime(), getGenerator(), getPublicKey(), getPrivateKey(), " + + "setPublicKey(), setPrivateKey() and verifyError are supported", + ); + // Node reads the member as undefined (a DiffieHellmanGroup has no key + // setters) and throws a TypeError once the receiver and arguments are + // evaluated. + const evaluated = [access.expression, ...call.arguments.nodes].map((node): IrStmt => ({ + kind: "exprStmt", + expr: lowerer.lowerExpr(node), + loc, + })); + return { + kind: "seqExpr", + stmts: evaluated, + result: nodeThrowExpr(1, "", `${v8CalleeText(access)} is not a function`, DYN, loc), + type: DYN, + loc, + }; + } + if (call.arguments.nodes.some(ts.isSpreadElement)) + lowerer.noLowering(`DiffieHellman.${name} with spread arguments`, call); + refuseAnyOutputEncoding(lowerer, call, name); + refuseUnmatchedOverload(lowerer, call, `DiffieHellman.${name}`); + const invoke: IrExpr = { + kind: "dynInvoke", + recv: lowerer.lowerExprExpecting(access.expression, DYN), + method: name, + calleeName: v8CalleeText(access), + args: call.arguments.nodes.map((arg) => lowerer.lowerExprExpecting(arg, DYN)), + type: DYN, + loc, + }; + // setPublicKey and setPrivateKey answer the receiver where @types/node + // declares void. Other results take the static representation of the + // declared overload the arguments match. + if (setter) return invoke; + const result = lowerer.irTypeOf(call); + return result.kind === "bytes" || result.kind === "string" + ? lowerer.coerceInto(call, invoke, result) + : invoke; +} diff --git a/packages/compiler/src/frontend/lowering/builtins/disposable-stack.ts b/packages/compiler/src/frontend/lowering/builtins/disposable-stack.ts index 1b9a9c03a..375c3f1e7 100644 --- a/packages/compiler/src/frontend/lowering/builtins/disposable-stack.ts +++ b/packages/compiler/src/frontend/lowering/builtins/disposable-stack.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "../stable-names.js"; import * as ts from "../../ts7/adapter.js"; import { type Lowerer } from "../lowerer.js"; import { locOf } from "../../program.js"; @@ -84,7 +85,7 @@ export function lowerDisposableStackUseCall( const key = `disposableStack.use:${className}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = `%disposableStack.use.${lowerer.valueHelpers.size}`; + helper = keyedHelperName(lowerer, "%disposableStack.use", key); lowerer.valueHelpers.set(key, helper); const context = newFnCtx(false, null, null, VOID); lowerer.fnStack.push(context); diff --git a/packages/compiler/src/frontend/lowering/builtins/ecdh.ts b/packages/compiler/src/frontend/lowering/builtins/ecdh.ts index e08be56f4..6e937284c 100644 --- a/packages/compiler/src/frontend/lowering/builtins/ecdh.ts +++ b/packages/compiler/src/frontend/lowering/builtins/ecdh.ts @@ -28,15 +28,16 @@ export function isEcdhType(lowerer: Lowerer, type: ts.Type): boolean { return !!symbol && ts.symbolName(symbol) === "ECDH" && lowerer.isStdlibSymbol(symbol); } -/** The call's arguments as checked-dynamic values in hidden locals, the - * first `count` of them padded with undefined, so every argument is - * evaluated left to right before the runtime checks them. Surplus - * arguments are evaluated and dropped. */ -function dynArguments( +/** The call's arguments as checked-dynamic values in hidden locals named + * `local`, the first `count` of them padded with undefined, so every + * argument is evaluated left to right before the runtime checks them. + * Surplus arguments are evaluated and dropped. */ +export function dynArguments( lowerer: Lowerer, call: ts.CallExpression, count: number, stmts: IrStmt[], + local = "%ecdhInput", ): IrExpr[] { const args = call.arguments.nodes; const loc = locOf(call); @@ -45,7 +46,7 @@ function dynArguments( const input: IrExpr = args[i] ? lowerer.lowerExprExpecting(args[i]!, DYN) : dynUndefinedExpr(loc); - const saved = lowerer.declareHiddenLocal("%ecdhInput", DYN); + const saved = lowerer.declareHiddenLocal(local, DYN); stmts.push({ kind: "varDecl", localId: saved.id, init: input, loc }); values.push(varRef(saved.id, DYN, loc)); } @@ -137,7 +138,11 @@ function refuseViewKeyWithEncoding(lowerer: Lowerer, call: ts.CallExpression, na * not follow (getPublicKey("HEX") answers a string where the encoding-less * overload declares a Buffer), so the call is refused rather than checked * against that type at run time. Arguments typed any are accepted. */ -function refuseUnmatchedOverload(lowerer: Lowerer, call: ts.CallExpression, what: string): void { +export function refuseUnmatchedOverload( + lowerer: Lowerer, + call: ts.CallExpression, + what: string, +): void { const signature = lowerer.checker.getResolvedSignature(call); if (signature === undefined) return; const params = signature.getParameters(); diff --git a/packages/compiler/src/frontend/lowering/builtins/errors.ts b/packages/compiler/src/frontend/lowering/builtins/errors.ts index d95442829..1371769d6 100644 --- a/packages/compiler/src/frontend/lowering/builtins/errors.ts +++ b/packages/compiler/src/frontend/lowering/builtins/errors.ts @@ -1,6 +1,8 @@ import * as ts from "../../ts7/adapter.js"; import { type Lowerer } from "../lowerer.js"; import { locOf } from "../../program.js"; +import { tryLowerExpression } from "../expressions/try-lower-expression.js"; +import { dynUndefinedExpr } from "../../../ir/build.js"; import { BOOL, CAUGHT, @@ -8,6 +10,7 @@ import { DYN_CLASS_PROPERTIES, F64, type IrExpr, + type IrStmt, type IrType, STRING, } from "../../../ir/ir.js"; @@ -267,6 +270,114 @@ function isErrorClassType(lowerer: Lowerer, type: IrType): boolean { ); } +/** Error classes that construct when called without `new`. */ +const CALLABLE_ERROR_CLASSES: ReadonlySet = new Set([ + "%Error", + "%TypeError", + "%RangeError", + "%SyntaxError", + "%ReferenceError", + "%EvalError", + "%URIError", +]); + +/** `Error(message?, options?)` and `Error.call(thisArg, message?, options?)` + * (an ES5 constructor function's `Error.call(this)`), and the same for the + * other standard error classes: called as a function, the constructor + * returns a new error and ignores the receiver. `thisArg` is evaluated + * first. Null for other callees. */ +export function lowerErrorFunctionCall(lowerer: Lowerer, call: ts.CallExpression): IrExpr | null { + if (call.questionDotToken) return null; + let callee = call.expression; + let args = call.arguments.nodes; + let thisArg: ts.Expression | undefined; + const viaCall = + ts.isPropertyAccessExpression(callee) && + !callee.questionDotToken && + callee.name.text === "call" && + ts.isIdentifier(callee.expression); + if (viaCall) { + callee = (callee as ts.PropertyAccessExpression).expression; + thisArg = args[0]; + args = args.slice(1); + } + if (!ts.isIdentifier(callee) || args.some(ts.isSpreadElement)) return null; + if (thisArg && ts.isSpreadElement(thisArg)) return null; + const info = lowerer.builtinErrorInfoOf(lowerer.checker.getSymbolAtLocation(callee)); + if (!info || !CALLABLE_ERROR_CLASSES.has(info.def.name)) return null; + const loc = locOf(call); + const stmts: IrStmt[] = []; + if (thisArg) { + const receiver = lowerer.lowerExpr(thisArg); + if (receiver.kind !== "varRef" && receiver.kind !== "unitLit") + stmts.push({ kind: "exprStmt", expr: receiver, loc: receiver.loc }); + } + const error: IrExpr = { + kind: "libCall", + fn: "error.newOptions", + args: lowerer.errorConstructorArgs(args, loc, call), + type: { kind: "object", className: info.def.name }, + loc, + }; + return stmts.length > 0 + ? { kind: "seqExpr", stmts, result: error, type: error.type, loc } + : error; +} + +/** `Error.captureStackTrace(target[, constructorOpt])` (also called as + * `Error.captureStackTrace?.(...)`, which always calls it). On a + * checked-dynamic target (`this` in a JavaScript constructor function) the + * runtime defines target's `stack`. An instance of a class that extends + * Error derives its stack from its name and message when the stack is + * read, so the call only evaluates its arguments. Both arguments are + * evaluated; the second only selects frames in Node. Null for other + * targets and callees. */ +export function lowerErrorCaptureStackTraceCall( + lowerer: Lowerer, + call: ts.CallExpression, + access: ts.PropertyAccessExpression, +): IrExpr | null { + if (access.questionDotToken) return null; + if (lowerer.stdlibGlobalMember(access, "Error") !== "captureStackTrace") return null; + const args = call.arguments.nodes; + if (args.length < 1 || args.length > 2 || args.some(ts.isSpreadElement)) return null; + const probed = tryLowerExpression(lowerer, args[0]!); + const loc = locOf(call); + if ( + probed?.type.kind === "object" && + (probed.type.className === "%Error" || lowerer.isSubclassOf(probed.type.className, "%Error")) + ) { + const stmts: IrStmt[] = []; + for (const arg of args) { + const value = lowerer.lowerExpr(arg); + if (value.kind !== "varRef") stmts.push({ kind: "exprStmt", expr: value, loc: value.loc }); + } + const result = dynUndefinedExpr(loc); + return stmts.length > 0 ? { kind: "seqExpr", stmts, result, type: DYN, loc } : result; + } + if (probed?.type.kind !== "dyn") return null; + const target = lowerer.lowerExpr(args[0]!); + const result: IrExpr = { + kind: "libCall", + fn: "dyn.errorCaptureStackTrace", + args: [target], + type: DYN, + loc, + }; + if (args.length === 1) return result; + const local = lowerer.declareHiddenLocal("%captureTarget", DYN); + return { + kind: "seqExpr", + stmts: [ + { kind: "varDecl", localId: local.id, init: target, loc }, + { kind: "exprStmt", expr: lowerer.lowerExprExpecting(args[1]!, DYN), loc }, + ], + result: { ...result, args: [{ kind: "varRef", localId: local.id, type: DYN, loc }] }, + type: DYN, + loc, + }; +} + /** `Error.isError(value)`. A catch binding tests its payload against the * Error class, an `unknown` value tests the checked-dynamic tree's error * encoding, and a union tests its runtime tag against the arms whose class diff --git a/packages/compiler/src/frontend/lowering/builtins/filesystem.ts b/packages/compiler/src/frontend/lowering/builtins/filesystem.ts index 0e1c062c5..6b988c491 100644 --- a/packages/compiler/src/frontend/lowering/builtins/filesystem.ts +++ b/packages/compiler/src/frontend/lowering/builtins/filesystem.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "../stable-names.js"; import { dynUndefinedExpr, boolLit, numLit, varRef } from "../../../ir/build.js"; import * as ts from "../../ts7/adapter.js"; import { type Lowerer, ladderFenceExpr } from "../lowerer.js"; @@ -442,7 +443,7 @@ export function lowerStringOrBytesWrite( const key = `fs.${append ? "append" : "write"}:${dataType.unionId}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = `%fs.writeData.${lowerer.valueHelpers.size}`; + helper = keyedHelperName(lowerer, "%fs.writeData", key); lowerer.valueHelpers.set(key, helper); const body: IrStmt[] = []; for (let tag = 0; tag < arms.length; tag++) { diff --git a/packages/compiler/src/frontend/lowering/builtins/hash-stream.ts b/packages/compiler/src/frontend/lowering/builtins/hash-stream.ts index 382d15eaf..88f6c2d95 100644 --- a/packages/compiler/src/frontend/lowering/builtins/hash-stream.ts +++ b/packages/compiler/src/frontend/lowering/builtins/hash-stream.ts @@ -1,17 +1,27 @@ import * as ts from "../../ts7/adapter.js"; import { type Lowerer } from "../lowerer.js"; import { locOf } from "../../program.js"; +import type { SrcLoc } from "../../../ir/ir.js"; import { varRef } from "../../../ir/build.js"; -import { type IrExpr, type IrType } from "../../../ir/ir.js"; +import { type IrExpr, type IrStmt, type IrType } from "../../../ir/ir.js"; +import { withStreamReceiver } from "../dyn-streams.js"; import { EMITTER_API_MEMBERS } from "../lower-classes.js"; import { lowerEmitterMethodCall } from "../lower-event-emitter.js"; -import { STREAM_API_MEMBERS, STREAM_OPERATORS, lowerStreamMethodCall } from "../lower-stream.js"; +import { + STREAM_API_MEMBERS, + STREAM_OPERATORS, + lowerStreamMethodCall, + lowerStreamProperty, +} from "../lower-stream.js"; +import { isCipherType } from "./crypto.js"; -/* node:crypto's Hash and Hmac are Transforms: a value written, read, - * listened to, or piped as a stream reads and writes through its own - * native Transform (scr_stream.c), created on first use. update() and - * digest() keep the value's static lowering; the stream members lower - * through the stream and emitter spokes over that Transform. */ +/* node:crypto's Hash, Hmac, Cipheriv and Decipheriv are Transforms: a + * value written, read, listened to, or piped as a stream reads and writes + * through its own native Transform, which scr_stream.c creates on first + * use. update(), digest() and final() keep the value's own lowering; the + * stream members lower through the stream and emitter spokes over that + * Transform. A Hash or Hmac is known by its IR type; a cipher is a + * checked-dynamic handle and is known by its checker type. */ const TRANSFORM_CLASS = "%Transform"; const TRANSFORM: IrType = { kind: "object", className: TRANSFORM_CLASS }; @@ -20,6 +30,12 @@ export function isHashValueType(type: IrType | null | undefined): boolean { return type?.kind === "cryptoHash" || type?.kind === "cryptoHmac"; } +/** Whether `node` evaluates to a Hash, Hmac, Cipheriv or Decipheriv. */ +export function isValueStream(lowerer: Lowerer, node: ts.Expression): boolean { + const type = lowerer.typeOf(node); + return isHashValueType(lowerer.mapTypeOf(type)) || isCipherType(lowerer, type); +} + /** The Transform of a lowered Hash or Hmac value (+1). A pipe * destination or pipeline stage (`piped`) also keeps the value alive * until its stream flushes or is destroyed. */ @@ -33,9 +49,27 @@ export function hashStreamOf(value: IrExpr, piped = false): IrExpr { }; } -/** A stream member called on a Hash or Hmac (`hash.write(chunk)`, - * `hash.on("data", cb)`, `hash.setEncoding("hex")`). Members that answer - * the stream (`this`) answer the Hash itself. */ +/** The Transform of a lowered Hash, Hmac, Cipheriv or Decipheriv value + * (+1), with hashStreamOf's `piped` (a cipher's stream always holds its + * cipher). */ +export function valueStreamOf(value: IrExpr, piped = false): IrExpr { + if (isHashValueType(value.type)) return hashStreamOf(value, piped); + // A value already lowered as its stream (addAbortSignal answers the + // Transform it was given, which its generic signature types as the + // cipher). + if (value.type.kind === "object") return value; + return { + kind: "libCall", + fn: "stream.handleStream", + args: [value], + type: TRANSFORM, + loc: value.loc, + }; +} + +/** A stream member called on a Hash, Hmac, Cipheriv or Decipheriv + * (`hash.write(chunk)`, `cipher.on("data", cb)`, `hash.setEncoding("hex")`). + * Members that answer the stream (`this`) answer the value itself. */ export function lowerHashStreamCall( lowerer: Lowerer, call: ts.CallExpression, @@ -45,39 +79,96 @@ export function lowerHashStreamCall( const name = access.name.text; const streamMember = STREAM_API_MEMBERS.has(name) || STREAM_OPERATORS.has(name); if (!streamMember && !EMITTER_API_MEMBERS.has(name)) return null; - if (!isHashValueType(lowerer.mapTypeOf(lowerer.typeOf(access.expression)))) return null; + if (!isValueStream(lowerer, access.expression)) return null; const info = lowerer.classes.get(TRANSFORM_CLASS); if (!info) return null; - const loc = locOf(call); - const hash = lowerer.lowerExpr(access.expression); - const local = lowerer.declareHiddenLocal("%hash", hash.type); - // The spokes lower the receiver to the value's Transform. - lowerer.hashStreamReceivers.set(access.expression, { localId: local.id, type: hash.type }); + // pipe(dest) answers its destination, which may be a Transform too; + // the other members typed as the Transform answer `this` + const answersThis = name !== "pipe"; + return withValueStreamReceiver(lowerer, access.expression, locOf(call), answersThis, () => + streamMember + ? lowerStreamMethodCall(lowerer, call, access, info) + : lowerEmitterMethodCall(lowerer, call, access, info), + ); +} + +/** A stream property read on a Hash, Hmac, Cipheriv or Decipheriv + * (`cipher.destroyed`, `hash.readableEnded`). */ +export function lowerValueStreamProperty( + lowerer: Lowerer, + expr: ts.PropertyAccessExpression, +): IrExpr | null { + if (expr.questionDotToken || !isValueStream(lowerer, expr.expression)) return null; + const info = lowerer.classes.get(TRANSFORM_CLASS); + if (!info) return null; + return withValueStreamReceiver(lowerer, expr.expression, locOf(expr), true, () => + lowerStreamProperty(lowerer, expr, info), + ); +} + +/** Evaluates the value `receiver` names once into a hidden local and runs + * `lower` with the receiver lowering to that value's Transform. When + * `answersThis`, a result typed as the Transform (the member answered + * `this`) answers the value itself. */ +function withValueStreamReceiver( + lowerer: Lowerer, + receiver: ts.Expression, + loc: SrcLoc, + answersThis: boolean, + lower: () => IrExpr | null, +): IrExpr | null { + const value = lowerer.lowerExpr(receiver); + const local = lowerer.declareHiddenLocal("%streamValue", value.type); + lowerer.valueStreamReceivers.set(receiver, { localId: local.id, type: value.type }); let lowered: IrExpr | null; try { - lowered = streamMember - ? lowerStreamMethodCall(lowerer, call, access, info) - : lowerEmitterMethodCall(lowerer, call, access, info); + lowered = lower(); } finally { - lowerer.hashStreamReceivers.delete(access.expression); + lowerer.valueStreamReceivers.delete(receiver); } if (!lowered) return null; const answersStream = - lowered.type.kind === "object" && lowered.type.className === TRANSFORM_CLASS; + answersThis && lowered.type.kind === "object" && lowered.type.className === TRANSFORM_CLASS; const result: IrExpr = answersStream ? { kind: "seqExpr", stmts: [{ kind: "exprStmt", expr: lowered, loc }], - result: varRef(local.id, hash.type, loc), - type: hash.type, + result: varRef(local.id, value.type, loc), + type: value.type, loc, } : lowered; return { kind: "seqExpr", - stmts: [{ kind: "varDecl", localId: local.id, init: hash, loc }], + stmts: [{ kind: "varDecl", localId: local.id, init: value, loc }], result, type: result.type, loc, }; } + +/** `for await (const chunk of value)` over a Hash, Hmac, Cipheriv or + * Decipheriv: the loop iterates the value's Transform. */ +export function lowerForAwaitValueStream( + lowerer: Lowerer, + stmt: ts.ForOfStatement, + lowerLoop: () => IrStmt | null, +): IrStmt | null { + if (!isValueStream(lowerer, stmt.expression)) return null; + const loc = locOf(stmt.expression); + const local = lowerer.declareHiddenLocal("%streamIterated", TRANSFORM); + const init = valueStreamOf(lowerer.lowerExpr(stmt.expression)); + const loop = withStreamReceiver( + lowerer, + stmt.expression, + varRef(local.id, TRANSFORM, loc), + TRANSFORM, + lowerLoop, + ); + if (loop === null) return null; + return { + kind: "block", + body: [{ kind: "varDecl", localId: local.id, init, loc }, loop], + loc: locOf(stmt), + }; +} diff --git a/packages/compiler/src/frontend/lowering/builtins/json.ts b/packages/compiler/src/frontend/lowering/builtins/json.ts index 7eb8aa9b2..64f829865 100644 --- a/packages/compiler/src/frontend/lowering/builtins/json.ts +++ b/packages/compiler/src/frontend/lowering/builtins/json.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "../stable-names.js"; import { isDateJsonSource } from "./dates.js"; import { dynUndefinedExpr, varRef } from "../../../ir/build.js"; import { InternalCompilerError } from "../../../errors.js"; @@ -253,7 +254,7 @@ function lowerOptionalStringifyRoot( const key = `json.optionalString:${value.type.unionId}:${JSON.stringify(indent)}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = `%json.optionalString.${lowerer.valueHelpers.size}`; + helper = keyedHelperName(lowerer, "%json.optionalString", key); lowerer.valueHelpers.set(key, helper); const input = varRef("value.0", value.type, loc); const serialized: IrExpr = { diff --git a/packages/compiler/src/frontend/lowering/builtins/key-object.ts b/packages/compiler/src/frontend/lowering/builtins/key-object.ts index 7e680fa20..ecb4f275a 100644 --- a/packages/compiler/src/frontend/lowering/builtins/key-object.ts +++ b/packages/compiler/src/frontend/lowering/builtins/key-object.ts @@ -4,10 +4,11 @@ import { locOf } from "../../program.js"; import { BOOL, DYN, type IrExpr } from "../../../ir/ir.js"; import { builtinImportOf } from "./module-bindings.js"; -/* node:crypto's secret KeyObject is a native checked-dynamic handle - * (scr_lib.c): the KeyObject type maps to dyn, its getters and methods - * dispatch through the handle, and these helpers lower the class's uses - * that a dyn value cannot answer by itself. */ +/* node:crypto's KeyObject is a native checked-dynamic handle (secret keys + * in scr_lib.c, private and public keys in scr_pki.c), as are Sign and + * Verify: the types map to dyn, their getters and methods dispatch through + * the handle, and these helpers lower the uses that a dyn value cannot + * answer by itself. */ /** Whether `node` names node:crypto's KeyObject class. */ export function isKeyObjectClass(lowerer: Lowerer, node: ts.Expression): boolean { @@ -37,15 +38,31 @@ export function lowerKeyObjectInstanceof( } const KEY_OBJECT_METHODS = new Set(["export", "equals", "toCryptoKey"]); +const SIGNER_METHODS = new Set(["update", "sign", "verify"]); -/** `key.export(...)`, `key.equals(...)` and `key.toCryptoKey(...)`: the +/** Whether a value's checker type is node:crypto's Sign or Verify. */ +function isSignerValue(lowerer: Lowerer, node: ts.Expression): boolean { + const type = lowerer.typeOf(node); + const sym = type.getAliasSymbol() ?? type.getSymbol(); + return ( + !!sym && + (ts.symbolName(sym) === "Sign" || ts.symbolName(sym) === "Verify") && + lowerer.isStdlibSymbol(sym) + ); +} + +/** `key.export(...)`, `key.equals(...)` and `key.toCryptoKey(...)`, and + * the update/sign/verify methods of Sign and Verify (scr_pki.c): the * handle answers them as methods, so they dispatch through dynInvoke * rather than as a member read and a call. */ export function lowerKeyObjectCall(lowerer: Lowerer, call: ts.CallExpression): IrExpr | null { if (call.questionDotToken || !ts.isPropertyAccessExpression(call.expression)) return null; const access = call.expression; - if (access.questionDotToken || !KEY_OBJECT_METHODS.has(access.name.text)) return null; - if (!isKeyObjectValue(lowerer, access.expression)) return null; + if (access.questionDotToken) return null; + const method = access.name.text; + const keyMethod = KEY_OBJECT_METHODS.has(method) && isKeyObjectValue(lowerer, access.expression); + if (!keyMethod && !(SIGNER_METHODS.has(method) && isSignerValue(lowerer, access.expression))) + return null; if (call.arguments.nodes.some(ts.isSpreadElement)) return null; return { kind: "dynInvoke", diff --git a/packages/compiler/src/frontend/lowering/builtins/numbers.ts b/packages/compiler/src/frontend/lowering/builtins/numbers.ts index 18ca0f1f3..9764216b7 100644 --- a/packages/compiler/src/frontend/lowering/builtins/numbers.ts +++ b/packages/compiler/src/frontend/lowering/builtins/numbers.ts @@ -1,7 +1,7 @@ import * as ts from "../../ts7/adapter.js"; import { type Lowerer, own } from "../lowerer.js"; import { lowerCheckedPredicateValue } from "../lower-builtin-values.js"; -import { locOf } from "../../program.js"; +import { isJsSourceFile, locOf } from "../../program.js"; import { BOOL, F64, STRING, type IrExpr, type IrLibFn } from "../../../ir/ir.js"; import { lowerBuiltinValuePreservingUndefined, lowerOptionalNumberPredicate } from "./arguments.js"; import { tryLowerExpression } from "../expressions/try-lower-expression.js"; @@ -72,17 +72,14 @@ export function lowerNumberStaticCall( return { kind: "libCall", fn, args: [arg], type: BOOL, loc }; } if (member === "parseFloat" || member === "parseInt") { - const want = member === "parseFloat" ? 1 : 2; - if (call.arguments.nodes.length !== want) { - lowerer.noLowering( - `Number.${member} with ${call.arguments.nodes.length} argument${call.arguments.nodes.length === 1 ? "" : "s"}`, - call, - member === "parseInt" ? "pass an explicit radix: Number.parseInt(s, 10)" : undefined, - ); + const count = call.arguments.nodes.length; + if (count < 1 || count > (member === "parseFloat" ? 1 : 2)) { + lowerer.noLowering(`Number.${member} with ${count} argument${count === 1 ? "" : "s"}`, call); } // Number.parseFloat/Number.parseInt ARE the global parsers: over a // string argument they lower to the same static parse (parseInt with - // its explicit radix); only the coercing argument shapes are refused. + // its radix, or radix 0 when it is missing); only the coercing argument + // shapes are refused. const probed = tryLowerExpression(lowerer, call.arguments.nodes[0]!); if (probed !== null && isStringLike(lowerer, probed.type)) { const parsed = lowerStaticNumberGlobal(lowerer, member, call, call.arguments.nodes, loc); @@ -101,9 +98,19 @@ export function lowerNumberStaticCall( }; if (member === "parseFloat") return { kind: "libCall", fn: "num.parseFloat", args: [text], type: F64, loc }; - const radix = lowerer.lowerExprExpecting(call.arguments.nodes[1]!, F64); + const radixNode = call.arguments.nodes[1]; + const radix: IrExpr = radixNode + ? lowerer.lowerExprExpecting(radixNode, F64) + : { kind: "numLit", value: 0, type: F64, loc }; return { kind: "libCall", fn: "num.parseInt", args: [text, radix], type: F64, loc }; } + // JavaScript whose argument does not lower on its own (zod's + // `Number.parseInt(val.toFixed(n).replace(".", ""))` over an untyped + // parameter): the global parser's own JavaScript forms. + if (probed === null && member === "parseInt" && isJsSourceFile(ts.getSourceFileOfNode(call))) { + const parsed = lowerStaticNumberGlobal(lowerer, member, call, call.arguments.nodes, loc); + if (parsed !== null) return parsed; + } const argText = probed !== null ? lowerer.fmt(probed.type) diff --git a/packages/compiler/src/frontend/lowering/builtins/operating-system.ts b/packages/compiler/src/frontend/lowering/builtins/operating-system.ts index c10465039..ee189a1f3 100644 --- a/packages/compiler/src/frontend/lowering/builtins/operating-system.ts +++ b/packages/compiler/src/frontend/lowering/builtins/operating-system.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "../stable-names.js"; import { numLit, strLit, varRef } from "../../../ir/build.js"; import * as ts from "../../ts7/adapter.js"; import { type Lowerer } from "../lowerer.js"; @@ -219,7 +220,7 @@ export function lowerOsCpusCall(lowerer: Lowerer, call: ts.CallExpression, loc: const key = `os.cpus:${typeKey(result)}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = `%os.cpus.${lowerer.valueHelpers.size}`; + helper = keyedHelperName(lowerer, "%os.cpus", key); lowerer.valueHelpers.set(key, helper); const index = varRef("i.0", F64, loc); const field = (k: number): IrExpr => ({ @@ -346,7 +347,7 @@ export function lowerPathParseCall( const key = `${fn}:${typeKey(result)}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = `%path.parse.${lowerer.valueHelpers.size}`; + helper = keyedHelperName(lowerer, "%path.parse", key); lowerer.valueHelpers.set(key, helper); const parts = varRef("parts.0", arrayOf(STRING), loc); lowerer.liftedFns.push({ @@ -448,7 +449,7 @@ export function lowerPathFormatCall( const key = `${fn}:${typeKey(recordT)}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = `%path.format.${lowerer.valueHelpers.size}`; + helper = keyedHelperName(lowerer, "%path.format", key); lowerer.valueHelpers.set(key, helper); const object = varRef("object.0", recordT, loc); const read = (name: string): IrExpr => { diff --git a/packages/compiler/src/frontend/lowering/builtins/performance.ts b/packages/compiler/src/frontend/lowering/builtins/performance.ts index 72304e6a9..bae525c17 100644 --- a/packages/compiler/src/frontend/lowering/builtins/performance.ts +++ b/packages/compiler/src/frontend/lowering/builtins/performance.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "../stable-names.js"; import * as ts from "../../ts7/adapter.js"; import { type Lowerer } from "../lowerer.js"; import { locOf } from "../../program.js"; @@ -330,7 +331,7 @@ function lowerPerfTimelineCall( const key = `perf.${many ? "entries" : timeline.fn}:${typeKey(result)}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = `%perf.${many ? "entries" : member}.${lowerer.valueHelpers.size}`; + helper = keyedHelperName(lowerer, `%perf.${many ? "entries" : member}`, key); lowerer.valueHelpers.set(key, helper); const argsRef = varRef("a.0", DYN, loc); const whichRef = varRef("w.0", F64, loc); @@ -461,7 +462,7 @@ export function perfEntryTag( const key = `perf.tag:${entryT.shapeId}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = `%perf.tag.${lowerer.valueHelpers.size}`; + helper = keyedHelperName(lowerer, "%perf.tag", key); lowerer.valueHelpers.set(key, helper); const e = varRef("e.0", entryT, loc); lowerer.liftedFns.push({ diff --git a/packages/compiler/src/frontend/lowering/builtins/process.ts b/packages/compiler/src/frontend/lowering/builtins/process.ts index 25653f541..842f42b57 100644 --- a/packages/compiler/src/frontend/lowering/builtins/process.ts +++ b/packages/compiler/src/frontend/lowering/builtins/process.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "../stable-names.js"; import { stdinKeypressListener } from "./readline.js"; import { envSnapshotHelper, lowerProcessLoadEnvFile } from "./environment.js"; import { dynUndefinedExpr, boolLit, numLit, strLit, varRef } from "../../../ir/build.js"; @@ -1561,7 +1562,7 @@ export function lowerProcessMethodCall( const key = `${prefix}usage.diff:${prevT.shapeId}:${t.shapeId}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = `%${prefix}usage.diff.${lowerer.valueHelpers.size}`; + helper = keyedHelperName(lowerer, `%${prefix}usage.diff`, key); lowerer.valueHelpers.set(key, helper); const pRef: IrExpr = { kind: "varRef", localId: "p.0", type: prevT, loc }; const fieldOf = (name: string): IrExpr => ({ @@ -1636,7 +1637,7 @@ export function lowerProcessMethodCall( const key = `process.memoryUsage:${t.shapeId}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = `%process.memoryUsage.${lowerer.valueHelpers.size}`; + helper = keyedHelperName(lowerer, "%process.memoryUsage", key); lowerer.valueHelpers.set(key, helper); lowerer.liftedFns.push({ name: helper, diff --git a/packages/compiler/src/frontend/lowering/builtins/promises.ts b/packages/compiler/src/frontend/lowering/builtins/promises.ts index 668ef01f8..129ac73a3 100644 --- a/packages/compiler/src/frontend/lowering/builtins/promises.ts +++ b/packages/compiler/src/frontend/lowering/builtins/promises.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "../stable-names.js"; import { checkedPromiseAll, thenReader } from "../checked-promise-all.js"; import { InternalCompilerError } from "../../../errors.js"; import * as ts from "../../ts7/adapter.js"; @@ -8,6 +9,7 @@ import { isJsSourceFile, locOf } from "../../program.js"; import { BOOL, DYN, + F64, type IrExpr, type IrFunction, type IrStmt, @@ -55,7 +57,7 @@ function lowerTuplePromiseAll( 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}`; + name = keyedHelperName(lowerer, "%promise.allTuple", `promise.allTuple:${key}`); lowerer.arrHofHelpers.set(`promise.allTuple:${key}`, name); const ctx = newFnCtx(false, null, null, resultT.inner); ctx.isAsync = true; @@ -375,8 +377,14 @@ export function lowerPromiseStaticCall( ); } const entries = lowerer.lowerExpr(argNode); - if (isJsSourceFile(ts.getSourceFileOfNode(call)) && entries.type.kind === "dyn") - return checkedPromiseAll(lowerer, entries, loc); + if (entries.type.kind === "dyn") return checkedPromiseAll(lowerer, entries, loc); + // An 'any'-typed argument that holds a typed value (`const xs: any = + // []`): the combinator reads it as the runtime value it is. + if ( + (lowerer.typeOf(argNode).flags & ts.TypeFlags.Any) !== 0 && + lowerer.dynConvertible(entries.type) + ) + return checkedPromiseAll(lowerer, lowerer.coerceToExpected(entries, DYN), loc); // loadPlugin(p)))` — the loadPlugins shape, where the checker // spells `any[]`): the ENGINE's own Promise.all runs over the @@ -557,7 +565,7 @@ export function lowerPromiseStaticCall( const key = `promise.try:${typeKey(f.type)}:${args.map((a) => typeKey(a.type)).join(",")}`; let helper = lowerer.arrHofHelpers.get(key); if (!helper) { - helper = `%promise.try.${lowerer.arrHofHelpers.size}`; + helper = keyedHelperName(lowerer, "%promise.try", key); lowerer.arrHofHelpers.set(key, helper); const fRef: IrExpr = { kind: "varRef", localId: "f.0", type: f.type, loc }; const argLocals = args.map((a, i) => ({ id: `a${i}.0`, name: `a${i}`, type: a.type })); @@ -844,3 +852,89 @@ function lowerTypedSettledCombinator( } return { kind: "intrinsic", name: "promise.allSettled", args: [entries], type: resultT, loc }; } + +/** `const pair = await Promise.all([p, q])` where every entry is the same + * Promise and the binding's type is the checker's tuple `[T, T]`: the + * uniform entries settle through one runtime combinator into a T[] (the + * same combinator and turn as the array form), and the binding receives + * the tuple of its elements. Null for every other await. */ +export function lowerAwaitedUniformPromiseAll( + lowerer: Lowerer, + expr: ts.AwaitExpression, +): IrExpr | null { + let operand: ts.Expression = expr.expression; + while (ts.isParenthesizedExpression(operand)) operand = operand.expression; + if ( + !ts.isCallExpression(operand) || + operand.questionDotToken || + !ts.isPropertyAccessExpression(operand.expression) || + operand.arguments.nodes.length !== 1 || + isJsSourceFile(ts.getSourceFileOfNode(expr)) + ) + return null; + const argNode = operand.arguments.nodes[0]!; + if ( + !ts.isArrayLiteralExpression(argNode) || + argNode.elements.nodes.length === 0 || + argNode.elements.nodes.some(ts.isSpreadElement) + ) + return null; + let user: ts.Node = expr; + while (ts.isParenthesizedExpression(user.parent)) user = user.parent; + const decl = user.parent; + if (!ts.isVariableDeclaration(decl) || decl.initializer !== user || !ts.isIdentifier(decl.name)) + return null; + if (lowerer.stdlibGlobalMember(operand.expression, "Promise") !== "all") return null; + const tuple = lowerer.mapTypeOf(lowerer.typeOf(decl.name)); + if (tuple?.kind !== "record") return null; + const shape = lowerer.shapes.get(tuple.shapeId); + if (!shape?.tuple || shape.fields.length !== argNode.elements.nodes.length) return null; + const elems = argNode.elements.nodes.map((el) => lowerer.lowerExpr(el)); + const first = elems[0]!.type; + if ( + first.kind !== "promise" || + first.inner.kind === "void" || + !elems.every((e) => typeEquals(e.type, first)) || + !shape.fields.every((f) => typeEquals(f.type, first.inner)) + ) + return null; + const loc = locOf(expr); + const values = arrayOf(first.inner); + const local = lowerer.declareHiddenLocal("%allValues", values); + const all: IrExpr = { + kind: "intrinsic", + name: "promise.all", + args: [{ kind: "arrayLit", elems, type: arrayOf(first), loc }], + type: { kind: "promise", inner: values }, + loc, + }; + return { + kind: "seqExpr", + stmts: [ + { + kind: "varDecl", + localId: local.id, + init: { kind: "awaitExpr", value: all, type: values, loc }, + loc, + }, + ], + // Shape fields are sorted by name; a tuple field's name is its position. + result: { + kind: "recordLit", + fields: shape.fields.map((f) => ({ + name: f.name, + value: { + kind: "arrayGet", + arr: varRef(local.id, values, loc), + index: { kind: "numLit", value: Number(f.name), type: F64, loc }, + type: f.type, + loc, + }, + })), + type: tuple, + loc, + }, + type: tuple, + loc, + }; +} diff --git a/packages/compiler/src/frontend/lowering/builtins/promisify-callback.ts b/packages/compiler/src/frontend/lowering/builtins/promisify-callback.ts index 822a4fecc..b4dbbf513 100644 --- a/packages/compiler/src/frontend/lowering/builtins/promisify-callback.ts +++ b/packages/compiler/src/frontend/lowering/builtins/promisify-callback.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "../stable-names.js"; import * as ts from "../../ts7/adapter.js"; import { type Lowerer } from "../lowerer.js"; import { varRef } from "../../../ir/build.js"; @@ -170,7 +171,7 @@ function promisifyMaker(lowerer: Lowerer, shape: CallbackShape, loc: SrcLoc): st 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}`; + const base = keyedHelperName(lowerer, "%promisify", key); lowerer.arrHofHelpers.set(key, base); const { fnT, resultT, args, callbackT, callbackParamT, inner, error } = shape; const promiseT = resultT.ret; diff --git a/packages/compiler/src/frontend/lowering/builtins/readline.ts b/packages/compiler/src/frontend/lowering/builtins/readline.ts index ede65d788..846b9a926 100644 --- a/packages/compiler/src/frontend/lowering/builtins/readline.ts +++ b/packages/compiler/src/frontend/lowering/builtins/readline.ts @@ -353,7 +353,8 @@ function lowerPromptArg(lowerer: Lowerer, node: ts.Expression): { value: IrExpr; * - on/once/addListener for 'line' ((input: string) or no parameters), * 'error' ((err: Error) or no parameters), 'history' ((history: * string[]) or no parameters), and 'close'/'pause'/'resume'/'SIGINT'/ - * 'SIGTSTP'/'SIGCONT' (no parameters), as statements. + * 'SIGTSTP'/'SIGCONT' (no parameters); as an expression the call yields + * the interface, so registrations chain. * Everything else the lib declares fences member-qualified. Null for * non-Interface receivers. */ export function lowerReadlineMethodCall( @@ -505,14 +506,19 @@ export function lowerReadlineMethodCall( `${RL_EVENT_LIST} are the supported readline events`, ); } - if (!ts.isExpressionStatement(call.parent)) { - lowerer.unsupported( - "SC1090", - call, - "chaining readline listener registration (register each listener as its own statement)", - ); - } - const recv = receiver(); + // As an expression (`rl.on("line", f).on("close", g)`), the call + // registers the listener and yields the interface, as Node's on() does. + const recvLocal = ts.isExpressionStatement(call.parent) + ? undefined + : lowerer.declareHiddenLocal("%readlineListener", F64); + const saved: IrStmt[] = + recvLocal === undefined + ? [] + : [{ kind: "varDecl", localId: recvLocal.id, init: receiver(), loc }]; + const recv: IrExpr = + recvLocal === undefined + ? receiver() + : { kind: "varRef", localId: recvLocal.id, type: F64, loc }; const cb = lowerer.lowerExpr(args[1]!); const want = event === "line" @@ -547,13 +553,21 @@ export function lowerReadlineMethodCall( : `'${event}' listeners with parameters or a return value (use ())`, ); } - return { + const register: IrExpr = { kind: "libCall", fn: "rl.on", args: [recv, numLit(ev, loc), cb, boolLit(name === "once", loc)], type: VOID, loc, }; + if (recvLocal === undefined) return register; + return { + kind: "seqExpr", + stmts: [...saved, { kind: "exprStmt", expr: register, loc }], + result: { kind: "varRef", localId: recvLocal.id, type: F64, loc }, + type: F64, + loc, + }; } lowerer.noLowering( `readline.Interface.${name}`, diff --git a/packages/compiler/src/frontend/lowering/builtins/text-codecs.ts b/packages/compiler/src/frontend/lowering/builtins/text-codecs.ts index 7229d5b84..8d47c8e3a 100644 --- a/packages/compiler/src/frontend/lowering/builtins/text-codecs.ts +++ b/packages/compiler/src/frontend/lowering/builtins/text-codecs.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "../stable-names.js"; import { isBuiltinClassInstance } from "./receiver-types.js"; import { strLit, varRef, dynUndefinedExpr } from "../../../ir/build.js"; import { staticTextDecoderEncoding } from "../text-decoder-encoding.js"; @@ -129,7 +130,7 @@ function stringDecoderHelper( const key = `strdec.${op}`; const existing = lowerer.valueHelpers.get(key); if (existing) return existing; - const name = `%strdec.${op}.${lowerer.valueHelpers.size}`; + const name = keyedHelperName(lowerer, `%strdec.${op}`, key); lowerer.valueHelpers.set(key, name); const recT: IrType = { kind: "record", shapeId }; diff --git a/packages/compiler/src/frontend/lowering/builtins/timers.ts b/packages/compiler/src/frontend/lowering/builtins/timers.ts index 2d531663f..d7cbd63b5 100644 --- a/packages/compiler/src/frontend/lowering/builtins/timers.ts +++ b/packages/compiler/src/frontend/lowering/builtins/timers.ts @@ -85,7 +85,7 @@ export function lowerTimersPromisesSetInterval( const genT = timersPromisesIntervalType(lowerer, expr); if (genT === null) lowerer.badType(expr, lowerer.typeOf(expr)); const yielded = lowerer.coerceInto(valueNode, value, genT.yieldT); - const fnName = `%fn${lowerer.lambdaCounter++}_tpInterval`; + const fnName = lowerer.closureName(loc, "_tpInterval"); const msParam: IrLocal = { id: "%tp.ms", name: "delay", type: F64, mutable: false }; const valueParam: IrLocal = { id: "%tp.value", name: "value", type: genT.yieldT, mutable: false }; const promiseVoid: IrType = { kind: "promise", inner: VOID }; diff --git a/packages/compiler/src/frontend/lowering/builtins/url.ts b/packages/compiler/src/frontend/lowering/builtins/url.ts index dca8a7cc0..8619b4997 100644 --- a/packages/compiler/src/frontend/lowering/builtins/url.ts +++ b/packages/compiler/src/frontend/lowering/builtins/url.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "../stable-names.js"; import { nodeThrowExpr, countedFor, strLit, varRef, dynUndefinedExpr } from "../../../ir/build.js"; import * as ts from "../../ts7/adapter.js"; import { type Lowerer, own } from "../lowerer.js"; @@ -194,7 +195,30 @@ export function lowerSearchParamsNew( ); } const arg = args[0]; - if (arg === undefined || (ts.isIdentifier(arg) && arg.text === "undefined")) { + if (arg === undefined) { + return { kind: "libCall", fn: "sp.new", args: [], type: SEARCH_PARAMS_T, loc }; + } + return lowerSearchParamsInit(lowerer, arg, loc); +} + +/** The URLSearchParams built from one init expression. A conditional + * init (`new URLSearchParams(c ? { a: "1" } : {})`) evaluates its + * condition first and builds from the arm it selects, so each arm may be + * any supported init shape. */ +function lowerSearchParamsInit(lowerer: Lowerer, arg: ts.Expression, loc: SrcLoc): IrExpr { + let inner = arg; + while (ts.isParenthesizedExpression(inner)) inner = inner.expression; + if (ts.isConditionalExpression(inner)) { + return { + kind: "ternary", + cond: lowerer.lowerCondition(inner.condition), + then: lowerSearchParamsInit(lowerer, inner.whenTrue, loc), + else_: lowerSearchParamsInit(lowerer, inner.whenFalse, loc), + type: SEARCH_PARAMS_T, + loc, + }; + } + if (ts.isIdentifier(arg) && arg.text === "undefined") { return { kind: "libCall", fn: "sp.new", args: [], type: SEARCH_PARAMS_T, loc }; } // The object-literal init: `{ a: "1", b: "2" }` appends pairs in @@ -292,7 +316,7 @@ function searchParamsFromTuples( const key = `sp.fromTuples:${row.shapeId}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = `%sp.fromTuples.${lowerer.valueHelpers.size}`; + helper = keyedHelperName(lowerer, "%sp.fromTuples", key); lowerer.valueHelpers.set(key, helper); const pairsT = init.type; const sp = (): IrExpr => varRef("sp.0", SEARCH_PARAMS_T, loc); @@ -372,7 +396,7 @@ function lowerOptionalStringSearchParams( const key = `sp.optionalString:${init.type.unionId}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = `%sp.optionalString.${lowerer.valueHelpers.size}`; + helper = keyedHelperName(lowerer, "%sp.optionalString", key); lowerer.valueHelpers.set(key, helper); const value = varRef("init.0", init.type, loc); lowerer.liftedFns.push({ @@ -678,7 +702,7 @@ function lowerSpForEachCall( const key = `${arity}:${typeKey(fnRet)}`; let helper = lowerer.spHofHelpers.get(key); if (!helper) { - helper = `%sp.forEach.${lowerer.spHofHelpers.size}`; + helper = keyedHelperName(lowerer, "%sp.forEach", key); lowerer.spHofHelpers.set(key, helper); lowerer.liftedFns.push(buildSpForEachFn(helper, arity, fnRet, loc)); } diff --git a/packages/compiler/src/frontend/lowering/builtins/v8.ts b/packages/compiler/src/frontend/lowering/builtins/v8.ts index 3582ce8ae..989a61a3f 100644 --- a/packages/compiler/src/frontend/lowering/builtins/v8.ts +++ b/packages/compiler/src/frontend/lowering/builtins/v8.ts @@ -5,6 +5,7 @@ * spirit of process.memoryUsage(): approximate values, not V8 heap * figures (a compiled binary embeds no V8 engine). Every other member * fences at its use with the by-design reason (builtinFenceHintOf). */ +import { keyedHelperName } from "../stable-names.js"; import { numLit } from "../../../ir/build.js"; import * as ts from "../../ts7/adapter.js"; import { type Lowerer } from "../lowerer.js"; @@ -55,7 +56,7 @@ export function lowerV8HeapStatisticsCall( const key = `v8.getHeapStatistics:${t.shapeId}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = `%v8.getHeapStatistics.${lowerer.valueHelpers.size}`; + helper = keyedHelperName(lowerer, "%v8.getHeapStatistics", key); lowerer.valueHelpers.set(key, helper); const sample = (index: number): IrExpr => ({ kind: "libCall", diff --git a/packages/compiler/src/frontend/lowering/builtins/webassembly.ts b/packages/compiler/src/frontend/lowering/builtins/webassembly.ts index 56347e437..8e5c3a048 100644 --- a/packages/compiler/src/frontend/lowering/builtins/webassembly.ts +++ b/packages/compiler/src/frontend/lowering/builtins/webassembly.ts @@ -96,9 +96,15 @@ function webAssemblySurface(lowerer: Lowerer, expr: ts.Expression): string | nul isGlobalThis(lowerer, expr.expression) ) { const target = lowerer.checker.getTypeAtLocation(expr.type); - return lowerer.checker.getPropertyOfType(target, "WebAssembly") !== undefined - ? "globalThis.WebAssembly" - : null; + const member = lowerer.checker.getPropertyOfType(target, "WebAssembly"); + // A target built from `typeof globalThis` (`typeof globalThis & { key?: T }`) + // inherits the global's own WebAssembly declaration: that cast names the + // whole global object, whose other properties stay readable and writable. + const globalMember = lowerer.checker.getPropertyOfType( + lowerer.typeOf(bare(expr.expression)), + "WebAssembly", + ); + return member !== undefined && member !== globalMember ? "globalThis.WebAssembly" : null; } const node = bare(expr); if (ts.isIdentifier(node)) { diff --git a/packages/compiler/src/frontend/lowering/builtins/webcrypto.ts b/packages/compiler/src/frontend/lowering/builtins/webcrypto.ts index 93cba84c5..8487e5cb7 100644 --- a/packages/compiler/src/frontend/lowering/builtins/webcrypto.ts +++ b/packages/compiler/src/frontend/lowering/builtins/webcrypto.ts @@ -5,34 +5,60 @@ import { BOOL, DYN, type IrExpr, type IrLibFn } from "../../../ir/ir.js"; import { lowerDynObjectLiteral } from "../expressions/object-literals.js"; import { stdlibGlobalNameOf } from "../surfaces.js"; import { WEBCRYPTO_DYN_TYPES } from "../../type-mapper.js"; +import { isWebCryptoReceiver } from "./crypto.js"; -/* WebCrypto's HMAC slice (scr_webcrypto.c): `crypto.subtle.importKey`, - * `sign`, `verify` and `digest` called on the crypto global (also through - * globalThis) lower to runtime entry points that take the argument vector - * as one dyn array and answer a promise, so Web IDL conversion, algorithm - * normalization and every error stay Node-shaped at run time. CryptoKey +/* WebCrypto (scr_webcrypto.c, with encrypt and decrypt in + * scr_webcrypto_aes.c and the ECDSA, Ed25519, RSASSA-PKCS1-v1_5 and RSA-PSS + * algorithms in scr_webcrypto_pki.c): `crypto.subtle`'s `importKey`, + * `generateKey`, `exportKey`, `encrypt`, `decrypt`, `wrapKey`, + * `unwrapKey`, `deriveBits`, `deriveKey`, `sign`, `verify` and `digest` + * called on the crypto global (also through + * globalThis, node:crypto's webcrypto and node:crypto's subtle) lower to + * runtime entry points that take the argument vector as one dyn array and + * answer a promise, so Web IDL conversion, algorithm normalization and + * every error stay Node-shaped at run time. CryptoKey * values are native handles; their type maps to dyn and their members * are handle reads. Other SubtleCrypto methods are refused by name. */ const SUBTLE_LOWERED: ReadonlyMap = new Map([ + ["generateKey", "webcrypto.generateKey"], ["importKey", "webcrypto.importKey"], + ["exportKey", "webcrypto.exportKey"], + ["encrypt", "webcrypto.encrypt"], + ["decrypt", "webcrypto.decrypt"], + ["wrapKey", "webcrypto.wrapKey"], + ["unwrapKey", "webcrypto.unwrapKey"], + ["deriveBits", "webcrypto.deriveBits"], + ["deriveKey", "webcrypto.deriveKey"], ["sign", "webcrypto.sign"], ["verify", "webcrypto.verify"], ["digest", "webcrypto.digest"], ]); const SUBTLE_HINT = - "the native WebCrypto surface is crypto.subtle.importKey('raw', ...) for HMAC keys, sign and verify with HMAC, and digest with SHA-1, SHA-256, SHA-384 or SHA-512, each called directly on crypto.subtle"; + "the native WebCrypto surface is crypto.subtle's importKey, generateKey and exportKey for HMAC and AES keys (importKey also for PBKDF2 and HKDF keys), encrypt and decrypt with AES-GCM, AES-CBC or AES-CTR, wrapKey and unwrapKey of secret keys with AES-KW or those ciphers, deriveBits and deriveKey with PBKDF2 or HKDF, sign and verify with HMAC, generateKey, importKey, exportKey, sign and verify for ECDSA, Ed25519, RSASSA-PKCS1-v1_5 and RSA-PSS, and digest with SHA-1, SHA-256, SHA-384 or SHA-512, each called directly on crypto.subtle"; -/** Whether `node` is `crypto.subtle` on the WebCrypto global. */ +/** Whether `node` is a SubtleCrypto object: `subtle` on a WebCrypto + * Crypto object (the global, globalThis.crypto or node:crypto's + * `webcrypto`) or node:crypto's own `subtle` export, named or through + * the namespace. */ function isSubtleReceiver(lowerer: Lowerer, node: ts.Expression): boolean { while (ts.isParenthesizedExpression(node)) node = node.expression; - return ( - ts.isPropertyAccessExpression(node) && - !node.questionDotToken && - node.name.text === "subtle" && - stdlibGlobalNameOf(lowerer, node.expression) === "crypto" - ); + if (ts.isIdentifier(node)) { + const imported = lowerer.builtinImportOf(node); + return imported?.module === "crypto" && imported.member === "subtle"; + } + if ( + !ts.isPropertyAccessExpression(node) || + node.questionDotToken || + node.name.text !== "subtle" + ) { + return false; + } + if (stdlibGlobalNameOf(lowerer, node.expression) === "crypto") return true; + if (isWebCryptoReceiver(lowerer, node.expression)) return true; + const member = lowerer.builtinMemberOf(node); + return member?.module === "crypto" && member.member === "subtle"; } /** `crypto.subtle.(...args)`: the lowered methods become their @@ -51,17 +77,6 @@ export function lowerWebCryptoCall(lowerer: Lowerer, call: ts.CallExpression): I if (call.arguments.nodes.some(ts.isSpreadElement)) { lowerer.noLowering(`crypto.subtle.${member} with spread arguments`, call, SUBTLE_HINT); } - // JsonWebKey imports are not implemented: a literal 'jwk' format is - // refused here (the runtime refuses a computed one). - const format = call.arguments.nodes[0]; - if ( - member === "importKey" && - format !== undefined && - ts.isStringLiteralLike(format) && - format.text === "jwk" - ) { - lowerer.noLowering("crypto.subtle.importKey with the 'jwk' key format", format, SUBTLE_HINT); - } const loc = locOf(call); const args = call.arguments.nodes.map((arg) => ts.isObjectLiteralExpression(arg) diff --git a/packages/compiler/src/frontend/lowering/call-arguments.ts b/packages/compiler/src/frontend/lowering/call-arguments.ts index 49f7c8ec0..060ffe9d2 100644 --- a/packages/compiler/src/frontend/lowering/call-arguments.ts +++ b/packages/compiler/src/frontend/lowering/call-arguments.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "./stable-names.js"; import { forwardedTupleType, pureForwardedValues, stripTypeWrappers } from "./typed-arguments.js"; import { dynUndefinedExpr } from "../../ir/build.js"; import { InternalCompilerError } from "../../errors.js"; @@ -753,7 +754,7 @@ function holeReadingLift(lowerer: Lowerer, from: IrType, to: IrType, loc: SrcLoc const key = `arr.holes:${typeKey(elem)}`; const existing = lowerer.valueHelpers.get(key); if (existing) return existing; - const name = `%arr.holes.${lowerer.valueHelpers.size}`; + const name = keyedHelperName(lowerer, "%arr.holes", key); lowerer.valueHelpers.set(key, name); lowerer.liftedFns.push( buildArrayConversion( diff --git a/packages/compiler/src/frontend/lowering/call-signatures.ts b/packages/compiler/src/frontend/lowering/call-signatures.ts index 34343ad27..dacb4d324 100644 --- a/packages/compiler/src/frontend/lowering/call-signatures.ts +++ b/packages/compiler/src/frontend/lowering/call-signatures.ts @@ -849,7 +849,10 @@ export function collectSignatureInner(lowerer: Lowerer, decl: ts.FunctionDeclara lowerer.genericFnsBySymbol.set(symbol, { decl, baseName: nameText, - qualifiedName: lowerer.qualify(ts.getSourceFileOfNode(decl), nsPathPrefix(decl) + nameText), + qualifiedName: lowerer.qualify( + ts.getSourceFileOfNode(decl), + nsPathPrefix(lowerer, decl) + nameText, + ), typeParams: [], instances: new Map(), implicitParams: implicit, @@ -897,7 +900,7 @@ export function collectSignatureInner(lowerer: Lowerer, decl: ts.FunctionDeclara // "%default" spelling ('%' cannot appear in a user identifier). name: lowerer.qualify( ts.getSourceFileOfNode(decl), - nsPathPrefix(decl) + (decl.name?.text ?? "%default"), + nsPathPrefix(lowerer, decl) + (decl.name?.text ?? "%default"), ), params, returnType, diff --git a/packages/compiler/src/frontend/lowering/caught-value-dispatch.ts b/packages/compiler/src/frontend/lowering/caught-value-dispatch.ts index 606d10d56..07d68baec 100644 --- a/packages/compiler/src/frontend/lowering/caught-value-dispatch.ts +++ b/packages/compiler/src/frontend/lowering/caught-value-dispatch.ts @@ -11,6 +11,7 @@ import { } from "../../ir/ir.js"; import { everyStmtList, transformStmtList } from "../../ir/traverse.js"; import { classInstanceOf } from "./class-dynamic-dispatch.js"; +import type { DispatchSites } from "./dispatch-sites.js"; import type { ClassInfo } from "./lower-classes.js"; import type { Lowerer } from "./lowerer.js"; @@ -26,25 +27,16 @@ export class CaughtValueDispatch { private readonly payloadHelpers = new Map(); private readonly payloadHelperFns = new Set(); - process(lowerer: Lowerer, functions: readonly IrFunction[]): boolean { + process(lowerer: Lowerer, functions: readonly IrFunction[], sites: DispatchSites): boolean { const consumers: IrFunction[] = []; for (const fn of functions) { if (fn === this.helper) continue; - let consumes = false; - everyStmtList(fn.body, { - stmt: (stmt) => { - if (stmt.kind === "throw" && stmt.value.type.kind === "object") { - const info = lowerer.classes.get(stmt.value.type.className); - if (info) this.thrownClasses.add(info.def.name); - } - return true; - }, - expr: (expr) => { - if (expr.kind === "caughtToDyn") consumes = true; - return true; - }, - }); - if (consumes) consumers.push(fn); + const found = sites.of(fn); + for (const className of found.thrown) { + const info = lowerer.classes.get(className); + if (info) this.thrownClasses.add(info.def.name); + } + if (found.caughtValues) consumers.push(fn); } if (!this.helper && consumers.length === 0) return false; let changed = false; diff --git a/packages/compiler/src/frontend/lowering/class-assertions.ts b/packages/compiler/src/frontend/lowering/class-assertions.ts index 900c32426..52654fab8 100644 --- a/packages/compiler/src/frontend/lowering/class-assertions.ts +++ b/packages/compiler/src/frontend/lowering/class-assertions.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "./stable-names.js"; import { nodeThrowExpr, varRef } from "../../ir/build.js"; import { BOOL, @@ -122,7 +123,7 @@ export function checkedClassAssertion( const key = `classassert:${typeKey(source.type)}:${typeKey(target)}`; let name = lowerer.coercions.retags.get(key); if (!name) { - name = `%class.assert.${lowerer.coercions.retags.size}`; + name = keyedHelperName(lowerer, "%class.assert", key); lowerer.coercions.retags.set(key, name); const input = varRef("value.0", source.type, loc); const body: IrStmt[] = []; @@ -228,7 +229,7 @@ export function checkedClassUnionAssertion( const key = `classunionassert:${typeKey(value.type)}:${typeKey(target)}`; let name = lowerer.coercions.retags.get(key); if (!name) { - name = `%class.assert.${lowerer.coercions.retags.size}`; + name = keyedHelperName(lowerer, "%class.assert", key); lowerer.coercions.retags.set(key, name); const input = varRef("value.0", value.type, loc); const locals = [{ id: "value.0", name: "value", type: value.type, mutable: false }]; diff --git a/packages/compiler/src/frontend/lowering/class-construction.ts b/packages/compiler/src/frontend/lowering/class-construction.ts index 30f504b4a..7ee53d04e 100644 --- a/packages/compiler/src/frontend/lowering/class-construction.ts +++ b/packages/compiler/src/frontend/lowering/class-construction.ts @@ -13,7 +13,8 @@ import { type IrType, type SrcLoc, } from "../../ir/ir.js"; -import { everyStmtList, transformExpr, transformStmtList } from "../../ir/traverse.js"; +import { transformExpr, transformStmtList } from "../../ir/traverse.js"; +import type { DispatchSites } from "./dispatch-sites.js"; import type { Lowerer } from "./lowerer.js"; import type { ParamShape } from "./call-signatures.js"; import { classPrototypeData } from "./class-prototypes.js"; @@ -24,16 +25,21 @@ const PREFIX = "%class.construct:"; const PACKED = `${PREFIX}packed`; const INSTANCEOF = "%class.instanceof:dynamic"; +/** `value instanceof callee` for an untyped constructor value, through one + * shared helper. `refusal` is the site's message for a runtime + * constructor with no instance test. */ export function checkedClassInstanceOf( lowerer: Lowerer, value: IrExpr, callee: IrExpr, + refusal: string, loc: SrcLoc, ): IrExpr { if (!lowerer.liftedFns.some((fn) => fn.name === INSTANCEOF)) { const params = [ { localId: "value", name: "value", type: DYN }, { localId: "callee", name: "callee", type: DYN }, + { localId: "refusal", name: "refusal", type: STRING }, ]; lowerer.liftedFns.push({ name: INSTANCEOF, @@ -46,7 +52,11 @@ export function checkedClassInstanceOf( value: { kind: "libCall", fn: "bytes.instanceOf", - args: [varRef("value", DYN, loc), varRef("callee", DYN, loc)], + args: [ + varRef("value", DYN, loc), + varRef("callee", DYN, loc), + varRef("refusal", STRING, loc), + ], type: BOOL, loc, }, @@ -56,7 +66,13 @@ export function checkedClassInstanceOf( loc, }); } - return { kind: "call", callee: INSTANCEOF, args: [value, callee], type: BOOL, loc }; + return { + kind: "call", + callee: INSTANCEOF, + args: [value, callee, { kind: "strLit", value: refusal, type: STRING, loc }], + type: BOOL, + loc, + }; } /** Checked construction dispatches to emitted native constructor thunks. */ @@ -254,22 +270,17 @@ export class ClassConstructionDispatch { private prototypeHelper: IrFunction | null = null; private readonly prototypes = new Set(); - process(lowerer: Lowerer, functions: readonly IrFunction[]): boolean { + process(lowerer: Lowerer, functions: readonly IrFunction[], sites: DispatchSites): boolean { const discover = (type: IrType): void => { if (type.kind === "classval") this.constructors.add(type.className); else if (type.kind === "union") lowerer.unions.get(type.unionId)?.arms.forEach(discover); }; const prototypeReads = new Set(); - for (const fn of functions) - everyStmtList(fn.body, { - stmt: () => true, - expr: (expr) => { - if (expr.kind === "dynFrom") discover(expr.value.type); - if (expr.kind === "libCall" && expr.fn === "dyn.classBasePrototype") - prototypeReads.add(fn); - return true; - }, - }); + for (const fn of functions) { + const found = sites.of(fn); + found.values.forEach(discover); + if (found.basePrototypes) prototypeReads.add(fn); + } let changed = false; for (const fn of functions) { if (fn === this.prototypeHelper || !prototypeReads.has(fn)) continue; diff --git a/packages/compiler/src/frontend/lowering/class-dynamic-dispatch.ts b/packages/compiler/src/frontend/lowering/class-dynamic-dispatch.ts index c90e1135b..8a4a1e417 100644 --- a/packages/compiler/src/frontend/lowering/class-dynamic-dispatch.ts +++ b/packages/compiler/src/frontend/lowering/class-dynamic-dispatch.ts @@ -1,9 +1,19 @@ import { primitiveConstructorOr } from "./lower-exprs.js"; +import { InternalCompilerError } from "../../errors.js"; import { dynUndefinedExpr, helperLoc, nodeThrowExpr, varRef } from "../../ir/build.js"; import { constructedValue } from "./constructor-returns.js"; import { eventTargetApiMembers, eventTargetInheritedMember } from "./lower-event-target.js"; +import { + DATE_PROTOTYPE_METHOD_NAMES, + DATE_TIME_FIELD, + dateInheritedMember, + dateRootOf, + programDeclaresDateClass, +} from "./builtins/date-classes.js"; +import { dateValueMethod } from "./builtins/dates.js"; import { BOOL, + DATE_T, DYN, F64, DYN_CLASS_PROPERTIES as PROPERTY_BAG, @@ -68,13 +78,14 @@ import { isClassCallback } from "./class-callbacks.js"; import { CaughtValueDispatch } from "./caught-value-dispatch.js"; import { refreshDescriptorGuards } from "./class-descriptors.js"; import { ClassConstructionDispatch } from "./class-construction.js"; +import { DispatchSites } from "./dispatch-sites.js"; import { emitterRooted, lowerDynamicEmitterEmit, lowerDynamicEmitterOn, } from "./lower-event-emitter.js"; import { protocolArm, protocolFieldArm } from "./class-protocol-dispatch.js"; -import { STREAM_OPERATORS } from "./lower-stream.js"; +import { STREAM_OPERATORS, operatorSignalOptions, reduceSignalSetup } from "./lower-stream.js"; import { deletedPropertyNames, fixedFieldFamily } from "./js-class-fields.js"; const STREAM_METHODS = new Set([ @@ -217,7 +228,7 @@ const KEY_CALLS = new Map([ ["dyn.keySetComputed", "value"], ]); -function toPrimitiveHint(expr: IrExpr): ToPrimitiveHint | null { +export function toPrimitiveHint(expr: IrExpr): ToPrimitiveHint | null { if (expr.kind === "toString") return expr.operand.type.kind === "dyn" ? "string" : null; if (expr.kind === "dynKeyGet") return expr.key.type.kind === "dyn" ? "string" : null; if (expr.kind !== "libCall") return null; @@ -296,6 +307,32 @@ export function classInstanceOf( ); const body: IrStmt[] = prototype ? [ + // In a program that declares a class extending Date, a Date can + // meet a class test (`date instanceof Moment`): its prototype + // chain holds no class prototype. + ...(programDeclaresDateClass(lowerer) + ? [ + { + kind: "if" as const, + cond: { + kind: "libCall" as const, + fn: "dyn.nativeDateHandleIs" as const, + args: [varRef("value", DYN, loc)], + type: BOOL, + loc, + }, + then: [ + { + kind: "return" as const, + value: { kind: "boolLit" as const, value: false, type: BOOL, loc }, + loc, + }, + ], + else_: null, + loc, + }, + ] + : []), { kind: "varDecl", localId: "candidate", init: varRef("value", DYN, loc), loc }, { kind: "while", @@ -432,6 +469,79 @@ function sortAdded(lowerer: Lowerer, set: Set, from: number): void { for (const name of added) set.add(name); } +/** The receivers of one property-receiver list (propertyReceivers) by the + * names that can make them answer a member, as positions in the list. A + * receiver whose root answers names of its own (an emitter, a stream, an + * EventTarget or a Date) is in `rooted` instead. */ +interface ReceiverIndex { + plans: readonly PropertyReceiver[]; + /** By a method or generic method its base chain declares. */ + methods: Map; + /** By a method, generic method or accessor its base chain declares (an + * accessor under its key and under its property name), or a field it has. */ + members: Map; + rooted: number[]; +} + +function receiverIndex(lowerer: Lowerer, plans: readonly PropertyReceiver[]): ReceiverIndex { + const methods = new Map(); + const members = new Map(); + const rooted: number[] = []; + const add = (table: Map, name: string, position: number): void => { + const positions = table.get(name); + if (positions === undefined) table.set(name, [position]); + else if (positions[positions.length - 1] !== position) positions.push(position); + }; + plans.forEach(({ info }, position) => { + if ( + emitterRooted(lowerer, info) || + info.builtinStream !== undefined || + eventTargetApiMembers(info) !== null || + dateRootOf(info) !== null + ) { + rooted.push(position); + return; + } + for (let c: ClassInfo | null = info; c; c = c.base) { + for (const name of c.methods.keys()) { + add(methods, name, position); + // A `get:`/`set:` key is an accessor of the property after the + // prefix, or a method whose quoted name has that prefix; the test + // looks up both. + add(members, name, position); + if (name.startsWith("get:") || name.startsWith("set:")) + add(members, name.slice(4), position); + } + if (c.genericMethods) + for (const name of c.genericMethods.keys()) { + add(methods, name, position); + add(members, name, position); + } + } + for (const name of info.fields.keys()) add(members, name, position); + }); + for (const table of [methods, members]) + for (const positions of table.values()) positions.sort((a, b) => a - b); + return { plans, methods, members, rooted }; +} + +/** The ascending union of two ascending position lists. */ +function mergePositions(left: readonly number[], right: readonly number[]): number[] { + const out: number[] = []; + let i = 0; + let j = 0; + while (i < left.length || j < right.length) { + const next = + j >= right.length || (i < left.length && left[i]! <= right[j]!) ? left[i++]! : right[j++]!; + if (out[out.length - 1] !== next) out.push(next); + } + return out; +} + +/** SCRIPTC_CHECK_DISPATCH_CANDIDATES=1 checks every indexed receiver selection + * against a test of every receiver. */ +const CHECK_CANDIDATES = process.env["SCRIPTC_CHECK_DISPATCH_CANDIDATES"] === "1"; + export function classPropertiesHelper(lowerer: Lowerer, loc: SrcLoc, readOnly = false): IrFunction { const name = readOnly ? READ_PROPERTIES : "%dyn.class.properties"; lowerer.shareHelper(name); @@ -745,6 +855,8 @@ export class ClassDynamicDispatch { private readonly generatorDispatch = new GeneratorDynamicDispatch(); private readonly caughtDispatch = new CaughtValueDispatch(); private readonly constructionDispatch = new ClassConstructionDispatch(); + /** What each function's body holds for this pass and its sub-passes. */ + readonly sites = new DispatchSites(); /** Property names a delete can remove (null: any name), for the field * creation tracking decision. */ private deletedNames: Set | null | undefined; @@ -827,12 +939,13 @@ export class ClassDynamicDispatch { ) fn.body.shift(); } - let changed = this.caughtDispatch.process(lowerer, functions); + let changed = this.caughtDispatch.process(lowerer, functions, this.sites); changed = refreshErrorMethodDispatch(lowerer, functions) || changed; changed = refreshClassMethodValueSelections(lowerer) || changed; changed = refreshErrorPropertyDispatch(lowerer, functions) || changed; - changed = this.generatorDispatch.process(lowerer, functions, this.generated) || changed; - changed = this.constructionDispatch.process(lowerer, functions) || changed; + changed = + this.generatorDispatch.process(lowerer, functions, this.generated, this.sites) || changed; + changed = this.constructionDispatch.process(lowerer, functions, this.sites) || changed; const seenTypes = new Set(); const rewrite = new Set(); const toPrimitiveSites = new Set(); @@ -856,100 +969,18 @@ export class ClassDynamicDispatch { }; const boxedBefore = this.boxed.size; const boxedConstructorsBefore = this.boxedConstructors.size; - for (const fn of functions) - everyStmtList(fn.body, { - stmt: (statement) => { - // Field-creation instrumentation can box a base-constructor receiver - // even when only its derived instances otherwise cross the boundary. - if ( - statement.kind === "fieldSet" && - lowerer.classes.get(statement.className)?.def.tracksOwnFields && - isClassOwnEnumerableFieldName(statement.field) - ) - discover(statement.obj.type); - return true; - }, - expr: (expr) => { - if ( - expr.kind === "jsonStringify" || - (expr.kind === "libCall" && - (expr.fn === "json.stringifyValue" || expr.fn === "json.stringifyReplacer")) - ) { - this.serializesClasses = true; - } - if ( - toPrimitiveHint(expr) !== null || - (expr.kind === "libCall" && (expr.fn === "dyn.valueOf" || expr.fn === "dyn.toString")) - ) - toPrimitiveSites.add(fn); - switch (expr.kind) { - case "dynFrom": - discover(expr.value.type); - break; - case "fieldIncDec": - if ( - lowerer.classes.get(expr.className)?.def.tracksOwnFields && - isClassOwnEnumerableFieldName(expr.field) - ) - discover(expr.obj.type); - break; - case "call": - if ( - (expr.callee === "%dyn.class.properties" || - expr.callee === "%dyn.class.readProperties") && - expr.args[0]?.kind === "dynFrom" && - isDynTypedRefType(expr.args[0].value.type) - ) - rewrite.add(fn); - break; - case "dynHasKey": - hasKeySites.add(fn); - break; - case "caughtTest": - if (expr.test === "instanceof") caughtSites.add(fn); - break; - case "caughtNarrow": - case "caughtCheck": - if (expr.type.kind === "object") caughtSites.add(fn); - break; - case "dynKeyGet": - case "dynInvoke": - rewrite.add(fn); - break; - case "dynCheck": - if (isDynTypedRefType(expr.type)) rewrite.add(fn); - // A dynamic function checked into a native function type - // receives its arguments as dynamic values: class instances - // passed to it cross the boundary when it is called (a JS - // `list.map((rec) => rec.match(x))` callback with an untyped - // parameter). - if (expr.type.kind === "func") expr.type.params.forEach(discover); - break; - case "libCall": - if ( - expr.fn === "bytes.construct" || - expr.fn === "dyn.keySet" || - expr.fn === "dyn.keySetComputed" || - expr.fn === "dyn.iterator" || - expr.fn === "dyn.arrayFromIterator" || - expr.fn === "dyn.toString" || - expr.fn === "dyn.stringConstructor" || - expr.fn === "dyn.forInKeys" || - expr.fn === "dyn.forInKeyStrings" || - expr.fn === "dyn.hasKeyComputed" || - expr.fn === "dyn.hasOwnComputed" || - expr.fn === "dyn.propertyIsEnumerableComputed" || - expr.fn === "dyn.defineProperty" || - expr.fn === "dyn.getPrototype" || - expr.fn === "dyn.reflectGet" || - expr.fn === "dyn.reflectSet" - ) - rewrite.add(fn); - break; - } - return true; - }, - }); + for (const fn of functions) { + const found = this.sites.of(fn); + // A class starts tracking its own fields during this pass. + for (const { type, fieldClass } of found.boxing) + if (fieldClass === undefined || lowerer.classes.get(fieldClass)?.def.tracksOwnFields) + discover(type); + if (found.serializes) this.serializesClasses = true; + if (found.conversions) toPrimitiveSites.add(fn); + if (found.dispatches) rewrite.add(fn); + if (found.keyTests) hasKeySites.add(fn); + if (found.caughtClassTests) caughtSites.add(fn); + } // The classes this pass found join the tables in a fixed order, not in // the order the scan met them. sortAdded(lowerer, this.boxed, boxedBefore); @@ -1307,10 +1338,30 @@ export class ClassDynamicDispatch { } refreshDescriptorGuards(lowerer); const byMethod = new Map(); + // A query asks every receiver about one name, and the program's dispatch + // sites ask about thousands: index the receivers by name once per list. + let index: ReceiverIndex | null = null; + const indexOf = (plans: readonly PropertyReceiver[]): ReceiverIndex => + index?.plans === plans ? index : (index = receiverIndex(lowerer, plans)); + /** The receivers of `plans` that can answer `name`, in list order: those + * `table` lists under it and the rooted ones. Emit-override + * specializations (`emit:`) join a class's methods while bodies + * lower, so they keep every receiver. */ + const receiversFor = ( + plans: readonly PropertyReceiver[], + name: string, + table: "methods" | "members", + ): readonly PropertyReceiver[] => { + if (name.startsWith("emit:")) return plans; + const found = indexOf(plans); + const positions = (table === "methods" ? found.methods : found.members).get(name); + return mergePositions(positions ?? [], found.rooted).map((position) => plans[position]!); + }; const candidates = (method: string): ClassInfo[] => { const found = byMethod.get(method); if (found) return found; - const matching = this.propertyReceivers(lowerer, true).flatMap(({ info }) => { + const plans = this.propertyReceivers(lowerer, true); + const test = ({ info }: PropertyReceiver): ClassInfo[] => { if (!info || info.fields.has(method) || info.builtinError) return []; if (emitterRooted(lowerer, info) && EMITTER_METHODS.has(method)) return [info]; if ( @@ -1329,7 +1380,13 @@ export class ClassDynamicDispatch { return findMethodOn(lowerer, info, method) || findGenericMethodOn(lowerer, info, method) ? [info] : []; - }); + }; + const matching = receiversFor(plans, method, "methods").flatMap(test); + if (CHECK_CANDIDATES) { + const every = plans.flatMap(test); + if (every.length !== matching.length || every.some((info, i) => info !== matching[i])) + throw new InternalCompilerError(`indexed candidates for ${method} differ`); + } byMethod.set(method, matching); return matching; }; @@ -2863,23 +2920,40 @@ export class ClassDynamicDispatch { }); changed = true; } - for (const plan of this.propertyReceivers(lowerer, true)) { + // Only the receivers that declare or hold the name, and the rooted + // ones, can pass the test, except for names it decides on every + // receiver. Fields added while bodies lower (the property bag and the + // attribute words) have compiler names, which take every receiver. + const plans = this.propertyReceivers(lowerer, true); + const anyReceiver = + !isClassOwnEnumerableFieldName(dispatch.name) || + dispatch.name === "constructor" || + dispatch.name === "stack"; + const skips = (plan: PropertyReceiver): boolean => + !isClassOwnEnumerableFieldName(dispatch.name) || + (!(plan.info.builtinStream !== undefined && streamProperty(dispatch.name)) && + !eventTargetInheritedMember(plan.info, dispatch.name) && + !dateInheritedMember(lowerer, plan.info, dispatch.name) && + !findMethodOn(lowerer, plan.info, dispatch.name) && + !findGenericMethodOn(lowerer, plan.info, dispatch.name) && + dispatch.name !== "constructor" && + !plan.info.fields.has(dispatch.name) && + !(dispatch.name === "stack" && lowerer.isSubclassOf(plan.info.def.name, "%Error")) && + !findMethodOn(lowerer, plan.info, `get:${dispatch.name}`) && + !findMethodOn(lowerer, plan.info, `set:${dispatch.name}`)); + const selected = anyReceiver ? plans : receiversFor(plans, dispatch.name, "members"); + if ( + CHECK_CANDIDATES && + plans.some( + (plan) => !dispatch.classes.has(plan.key) && !skips(plan) && !selected.includes(plan), + ) + ) + throw new InternalCompilerError(`indexed receivers for ${dispatch.name} differ`); + for (const plan of selected) { const { info } = plan; // Classes answered in an earlier pass skip the member lookups. if (dispatch.classes.has(plan.key)) continue; - if ( - !isClassOwnEnumerableFieldName(dispatch.name) || - (!(info.builtinStream !== undefined && streamProperty(dispatch.name)) && - !eventTargetInheritedMember(info, dispatch.name) && - !findMethodOn(lowerer, info, dispatch.name) && - !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}`)) - ) - continue; + if (skips(plan)) continue; dispatch.classes.add(plan.key); const loc = dispatch.fn.loc; const { receiver, condition } = this.propertyReceiver(plan, loc); @@ -2987,7 +3061,8 @@ export class ClassDynamicDispatch { ]; if ( ((info.builtinStream !== undefined && streamProperty(name)) || - eventTargetInheritedMember(info, name)) && + eventTargetInheritedMember(info, name) || + dateInheritedMember(lowerer, info, name)) && dispatch.probe ) return [ @@ -3200,6 +3275,9 @@ export class ClassDynamicDispatch { for (const name of [...STREAM_BOOL_PROPERTIES, ...STREAM_NUM_PROPERTIES]) names.add(name); const inherited = eventTargetApiMembers(info); if (inherited) for (const name of inherited) names.add(name); + if (dateRootOf(info)) + for (const name of DATE_PROTOTYPE_METHOD_NAMES) + if (dateInheritedMember(lowerer, info, name)) names.add(name); for (let owner: ClassInfo | null = info; owner; owner = owner.base) { const methodNames = [...owner.methods.keys()]; @@ -3863,6 +3941,70 @@ export class ClassDynamicDispatch { ]; return { kind: "if", cond: condition, then: body, else_: null, loc }; } + // Date.prototype[Symbol.toPrimitive] takes "default" as "string", and a + // class declared `extends Date` inherits Date's toString and valueOf, + // which answer primitives from the time value. + const dateRoot = dateRootOf(info); + if (dateRoot) { + const dateOrder: ("valueOf" | "toString")[] = + hint === "number" ? ["valueOf", "toString"] : ["toString", "valueOf"]; + const { receiver } = this.propertyReceiver(plan, loc); + const body: IrStmt[] = []; + for (const method of dateOrder) { + if (!conversionMethod(lowerer, info, method)) { + const time: IrExpr = { + kind: "fieldGet", + obj: upcastTo(lowerer, receiver, dateRoot.def.name), + className: dateRoot.def.name, + field: DATE_TIME_FIELD, + type: DATE_T, + loc, + }; + body.push({ + kind: "return", + value: lowerer.coerceToExpected(dateValueMethod(method, time, loc)!, DYN), + loc, + }); + break; + } + const result = `%toPrimitive.${method}.${helper.locals.length}`; + helper.locals.push({ id: result, name: method, type: DYN, mutable: false }); + body.push( + { + kind: "varDecl", + localId: result, + init: { + kind: "call", + callee: this.toPrimitiveCall(lowerer, plan, method, 0, loc), + args: [varRef("p.0", DYN, loc)], + type: DYN, + loc, + }, + loc, + }, + { + kind: "if", + cond: isPrimitive(varRef(result, DYN, loc), loc), + then: [{ kind: "return", value: varRef(result, DYN, loc), loc }], + else_: null, + loc, + }, + ); + } + if (body.at(-1)?.kind !== "return") + body.push({ + kind: "return", + value: nodeThrowExpr(1, "", "Cannot convert object to primitive value", DYN, loc), + loc, + }); + return { + kind: "if", + cond: this.propertyReceiver(plan, loc).condition, + then: body, + else_: null, + loc, + }; + } const order: ("valueOf" | "toString")[] = hint === "string" ? ["toString", "valueOf"] : ["valueOf", "toString"]; if (!order.some((method) => conversionMethod(lowerer, info, method))) return null; @@ -4731,9 +4873,11 @@ export class ClassDynamicDispatch { ): IrStmt[] { const { name, write } = dispatch; const loc = dispatch.fn.loc; - // The inherited EventTarget/Event members of a subclass instance: the - // runtime's capsule view answers the accessors and method values. - if (eventTargetInheritedMember(info, name)) { + // The inherited EventTarget/Event members of a subclass instance, and + // the inherited Date methods of an instance of a class declared + // `extends Date`: the runtime's capsule view answers the accessors and + // method values. + if (eventTargetInheritedMember(info, name) || dateInheritedMember(lowerer, info, name)) { const key: IrExpr = { kind: "strLit", value: name, type: STRING, loc }; if (!write) return [ @@ -5496,13 +5640,16 @@ export class ClassDynamicDispatch { const readableT: IrType = { kind: "object", className: "%Readable" }; const op = (fn: string, args: IrExpr[], type: IrType): IrStmt[] => ret({ kind: "libCall", fn: fn as IrLibFn, args: [receiver, ...args], type, loc }); + // Node passes every callback its { signal }; the callback's + // declared parameters are not known here. + const sig = (): IrExpr => operatorSignalOptions(lowerer, arg(1), loc); switch (method) { case "map": - return op("readable.opMap", [arg(0), arg(1)], readableT); + return op("readable.opMap", [arg(0), arg(1), sig()], readableT); case "filter": - return op("readable.opFilter", [arg(0), arg(1)], readableT); + return op("readable.opFilter", [arg(0), arg(1), sig()], readableT); case "flatMap": - return op("readable.opFlatMap", [arg(0), arg(1)], readableT); + return op("readable.opFlatMap", [arg(0), arg(1), sig()], readableT); case "drop": return op("readable.opDrop", [arg(0), arg(1)], readableT); case "take": @@ -5510,25 +5657,49 @@ export class ClassDynamicDispatch { case "toArray": return op("readable.opToArray", [arg(0)], { kind: "promise", inner: DYN }); case "forEach": - return op("readable.opForEach", [arg(0), arg(1)], { kind: "promise", inner: VOID }); + return op("readable.opForEach", [arg(0), arg(1), sig()], { + kind: "promise", + inner: VOID, + }); case "some": - return op("readable.opSome", [arg(0), arg(1)], { kind: "promise", inner: BOOL }); + return op("readable.opSome", [arg(0), arg(1), sig()], { kind: "promise", inner: BOOL }); case "every": - return op("readable.opEvery", [arg(0), arg(1)], { kind: "promise", inner: BOOL }); + return op("readable.opEvery", [arg(0), arg(1), sig()], { + kind: "promise", + inner: BOOL, + }); case "find": - return op("readable.opFind", [arg(0), arg(1)], { kind: "promise", inner: DYN }); - case "reduce": - return op( - "readable.opReduce", - [ - arg(0), - arg(1), - { kind: "boolLit", value: dispatch.source.args.length >= 2, type: BOOL, loc }, - arg(2), - { kind: "numLit", value: 0, type: F64, loc }, - ], - { kind: "promise", inner: DYN }, - ); + return op("readable.opFind", [arg(0), arg(1), sig()], { kind: "promise", inner: DYN }); + case "reduce": { + // the dispatch function's locals: there is no function + // context while dispatch bodies are built + const setup = reduceSignalSetup(lowerer, arg(2), loc, (name, type) => { + const local = { + id: `${name}.${dispatch.fn.locals.length}`, + name, + type, + mutable: false, + }; + dispatch.fn.locals.push(local); + return local; + }); + return [ + ...setup.stmts, + ...op( + "readable.opReduceSignal", + [ + arg(0), + arg(1), + { kind: "boolLit", value: dispatch.source.args.length >= 2, type: BOOL, loc }, + arg(2), + { kind: "numLit", value: 0, type: F64, loc }, + setup.abort, + setup.cbOpts, + ], + { kind: "promise", inner: DYN }, + ), + ]; + } } } if (method === "destroy" && (!incoming.length || incoming[0]?.kind === "unitLit")) diff --git a/packages/compiler/src/frontend/lowering/class-iterables.ts b/packages/compiler/src/frontend/lowering/class-iterables.ts index 8c58fc0bd..0f4d6c254 100644 --- a/packages/compiler/src/frontend/lowering/class-iterables.ts +++ b/packages/compiler/src/frontend/lowering/class-iterables.ts @@ -1,13 +1,18 @@ import type { IrExpr, IrType } from "../../ir/ir.js"; import type { Lowerer } from "./lowerer.js"; import { accessorCall } from "./lower-classes.js"; +import { iterableGenerator, iterableUnionOf } from "./iterable-values.js"; /** The generator a class instance's `[Symbol.iterator]` returns, when that - * method is a generator method taking no arguments: `obj[Symbol.iterator]()`, + * method is a generator method taking no arguments (or the iterator an + * Iterable value opens over its current arm): `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 { + // An Iterable value opens an iterator over its current arm. + const iterable = iterableUnionOf(lowerer, value.type); + if (iterable) return iterableGenerator(lowerer, value, iterable); 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; @@ -17,6 +22,7 @@ export function classGeneratorIterable(lowerer: Lowerer, value: IrExpr): IrExpr /** 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 (iterableUnionOf(lowerer, type)) return true; 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; diff --git a/packages/compiler/src/frontend/lowering/class-method-mutations.ts b/packages/compiler/src/frontend/lowering/class-method-mutations.ts index cc8700469..abbaf3a75 100644 --- a/packages/compiler/src/frontend/lowering/class-method-mutations.ts +++ b/packages/compiler/src/frontend/lowering/class-method-mutations.ts @@ -1,3 +1,4 @@ +import { isErrorPrototypeValue } from "./class-prototypes.js"; import * as ts from "../ts7/adapter.js"; import { literalValues } from "../literal-values.js"; import { isJsSourceFile } from "../program.js"; @@ -377,6 +378,8 @@ export function collectClassMethodMutations( node.initializer.kind !== ts.SyntaxKind.MissingDeclaration ) markTarget(node.initializer, node); + if (ts.isPropertyAccessExpression(node) && isErrorPrototypeValue(lowerer, node)) + lowerer.errorPrototypeValues = true; if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) { const base = unwrap(node.expression); const prototype = diff --git a/packages/compiler/src/frontend/lowering/class-protocols.ts b/packages/compiler/src/frontend/lowering/class-protocols.ts index 81aa90a1f..76091b13e 100644 --- a/packages/compiler/src/frontend/lowering/class-protocols.ts +++ b/packages/compiler/src/frontend/lowering/class-protocols.ts @@ -101,6 +101,8 @@ export class ClassProtocols { const sites: { source: ts.Expression; target: () => ts.Type | undefined; + /** The node whose contextual type `target` answers. */ + contextual?: ts.Expression; assertion?: true; }[] = []; /** Expressions whose values are observed as whole objects. */ @@ -122,7 +124,8 @@ export class ClassProtocols { const callbackParams: { fn: ts.SignatureDeclaration; index: number; name: ts.Node }[] = []; const contextual = (expr: ts.Expression) => () => this.checker.getContextualType(expr); const flow = (expr: ts.Expression | undefined): void => { - if (expr !== undefined) sites.push({ source: expr, target: contextual(expr) }); + if (expr !== undefined) + sites.push({ source: expr, target: contextual(expr), contextual: expr }); }; const write = (target: ts.Expression): void => { while (ts.isParenthesizedExpression(target) || ts.isNonNullExpression(target)) @@ -329,7 +332,11 @@ export class ClassProtocols { facts.loose.push({ node: looseArguments[i]!, call: looseCalls[i]!, symbols }); } this.facts = facts; - const pending: { sourceType: ts.Type; target: () => ts.Type | undefined }[] = []; + const pending: { + sourceType: ts.Type; + target: () => ts.Type | undefined; + contextual?: ts.Expression; + }[] = []; /** Views a value of unknown origin is asserted to and that expose a * method of a class the view accepts (see methodViewSources). */ const methodViews = new Set(); @@ -352,7 +359,11 @@ export class ClassProtocols { } continue; } - pending.push({ sourceType, target: site.target }); + pending.push( + site.contextual === undefined + ? { sourceType, target: site.target } + : { sourceType, target: site.target, contextual: site.contextual }, + ); } for (const { fn, index, name } of callbackParams) { attempt(() => { @@ -377,6 +388,19 @@ export class ClassProtocols { // flows and origins are complete. const before = new Set(marked); const targets = new Map(); + // The fixpoint asks the target of each site whose source carries + // identity: one batch asks those of the sites that carry it now, and a + // site that starts to as marks grow asks its own. + attempt(() => + this.checker.prefetchContextualTypes( + pending.flatMap((entry) => + entry.contextual !== undefined && + attempt(() => this.carriesIdentity(entry.sourceType, marked)) === true + ? [entry.contextual] + : [], + ), + ), + ); let changed = true; while (changed) { changed = false; diff --git a/packages/compiler/src/frontend/lowering/class-prototypes.ts b/packages/compiler/src/frontend/lowering/class-prototypes.ts index 4cbd8e5cf..2a05cf977 100644 --- a/packages/compiler/src/frontend/lowering/class-prototypes.ts +++ b/packages/compiler/src/frontend/lowering/class-prototypes.ts @@ -457,6 +457,28 @@ export function isCompiledPrototypeMember( ); } +/** `Error.prototype` read as the checked-dynamic object, as a value or for + * a member other than `toString` and `constructor`, which keep the Error + * class's prototype data (`this.toString !== Error.prototype.toString` + * compares class method values). */ +export function isErrorPrototypeValue( + lowerer: Lowerer, + expr: ts.PropertyAccessExpression, +): boolean { + let node: ts.Node = expr; + while (ts.isParenthesizedExpression(node.parent)) node = node.parent; + const parent = node.parent; + return ( + expr.name.text === "prototype" && + lowerer.isStdlibGlobal(expr.expression, "Error") && + !( + ts.isPropertyAccessExpression(parent) && + parent.expression === node && + (parent.name.text === "toString" || parent.name.text === "constructor") + ) + ); +} + /** Named data and method slots have native descriptors. Bare reflection and * accessor replacement still require a complete view of the prototype. */ export function lowerClassPrototypeData( @@ -469,6 +491,11 @@ export function lowerClassPrototypeData( exactClassOfReceiver(lowerer, expr.expression) ?? (stored?.kind === "classval" ? lowerer.classes.get(stored.className) : undefined); if (!info) return null; + // Error.prototype as a value: the checked-dynamic object an ES5 + // constructor function inherits from (`F.prototype = + // Object.create(Error.prototype)`). + if (isErrorPrototypeValue(lowerer, expr)) + return { kind: "libCall", fn: "dyn.errorPrototype", args: [], type: DYN, loc: locOf(expr) }; // EventEmitter.prototype and the stream prototypes: the untyped // constructor's prototype object (builtin-class-dyn.ts). const builtinKind = builtinClassKind(info.def.name); diff --git a/packages/compiler/src/frontend/lowering/class-runtime-statics.ts b/packages/compiler/src/frontend/lowering/class-runtime-statics.ts index 310c8f389..707c916ec 100644 --- a/packages/compiler/src/frontend/lowering/class-runtime-statics.ts +++ b/packages/compiler/src/frontend/lowering/class-runtime-statics.ts @@ -1,6 +1,6 @@ import { dynUndefinedExpr, varRef } from "../../ir/build.js"; import * as ts from "../ts7/adapter.js"; -import { BOOL, DYN, STRING, type IrExpr, type IrStmt } from "../../ir/ir.js"; +import { BOOL, DYN, STRING, type IrExpr, type IrLocal, type IrStmt } from "../../ir/ir.js"; import { locOf } from "../program.js"; import type { Lowerer } from "./lowerer.js"; import { classValueRef, type ClassInfo } from "./lower-classes.js"; @@ -15,9 +15,29 @@ export function hasRuntimeStatics(info: ClassInfo): boolean { /** Constructor descriptors preserve inherited getter receivers and static * initialization order. Factory evaluations additionally own independent - * fields and closures when the same factory is called repeatedly. */ -export function initializeRuntimeStatics(lowerer: Lowerer, info: ClassInfo, value: IrExpr): IrExpr { - if (!info.runtimeStatics && !info.runtimePrototypeMembers) return value; + * fields and closures when the same factory is called repeatedly. + * + * `binding` is the local that holds the class under its own name (a + * function-local class declaration's binding, or the inner name of a + * function-local class expression whose body names itself), declared + * without a value. It is assigned before any static member is defined, so + * static initializers and methods read the class through it. */ +export function initializeRuntimeStatics( + lowerer: Lowerer, + info: ClassInfo, + value: IrExpr, + binding?: IrLocal, +): IrExpr { + if (!info.runtimeStatics && !info.runtimePrototypeMembers) { + if (!binding) return value; + return { + kind: "seqExpr", + stmts: [{ kind: "assign", localId: binding.id, value, loc: value.loc }], + result: varRef(binding.id, binding.type, value.loc), + type: binding.type, + loc: value.loc, + }; + } const loc = value.loc; const local = lowerer.declareHiddenLocal("%staticClass", value.type); const receiver = varRef(local.id, value.type, loc); @@ -28,6 +48,16 @@ export function initializeRuntimeStatics(lowerer: Lowerer, info: ClassInfo, valu : dynUndefinedExpr(loc); const statements: IrStmt[] = [ { kind: "varDecl", localId: local.id, init: value, loc }, + ...(binding + ? [ + { + kind: "assign" as const, + localId: binding.id, + value: lowerer.coerceToExpected(receiver, binding.type), + loc, + }, + ] + : []), { kind: "exprStmt", expr: { kind: "libCall", fn: "dyn.classInherit", args: [boxed, base], type: DYN, loc }, diff --git a/packages/compiler/src/frontend/lowering/class-to-primitive.ts b/packages/compiler/src/frontend/lowering/class-to-primitive.ts index f3a6b23fa..0b107ab4e 100644 --- a/packages/compiler/src/frontend/lowering/class-to-primitive.ts +++ b/packages/compiler/src/frontend/lowering/class-to-primitive.ts @@ -1,10 +1,21 @@ import { varRef } from "../../ir/build.js"; -import { BOOL, DYN, F64, STRING, type IrExpr, type IrStmt, type IrType } from "../../ir/ir.js"; +import { + BOOL, + DATE_T, + DYN, + F64, + STRING, + type IrExpr, + type IrStmt, + type IrType, +} from "../../ir/ir.js"; import * as ts from "../ts7/adapter.js"; import type { Lowerer } from "./lowerer.js"; import { accessorCall, findMethodOn, type ClassInfo } from "./lower-classes.js"; import { isClassCallback } from "./class-callbacks.js"; import { isSafeToRepeat } from "./expressions/evaluation-safety.js"; +import { DATE_TIME_FIELD, dateRootOf } from "./builtins/date-classes.js"; +import { dateValueMethod } from "./builtins/dates.js"; /** The ToPrimitive hint of a conversion: `String(x)` and template literals * take "string", `+` "default", `Number(x)` "number". */ @@ -13,9 +24,12 @@ export type StringConversionHint = "string" | "default"; type ConversionMethod = "sym:toPrimitive" | "valueOf" | "toString"; -/** How an instance of one class converts: through one of its methods, or - * through Object.prototype.toString ("[object Object]"). */ -type Plan = { method: ConversionMethod; ret: IrType } | { method: null }; +/** How an instance of one class converts: through one of its methods, + * through the Date.prototype method `date` of a class declared `extends + * Date`, or through Object.prototype.toString ("[object Object]"). */ +type Plan = + | { method: ConversionMethod; ret: IrType } + | { method: null; date?: "toString" | "valueOf" }; const PRIMITIVE_KINDS = new Set(["f64", "string", "bool", "bigint", "undefinedT", "nullT"]); @@ -138,6 +152,18 @@ function classConversion( } const convert = (cls: ClassInfo, object: IrExpr): IrExpr => { const plan = plans.get(cls)!; + if (plan.method === null && plan.date) { + const root = dateRootOf(cls)!; + const time: IrExpr = { + kind: "fieldGet", + obj: lowerer.upcastTo(object, root.def.name), + className: root.def.name, + field: DATE_TIME_FIELD, + type: DATE_T, + loc, + }; + return finish(dateValueMethod(plan.date, time, loc)!); + } if (plan.method === null) return finish({ kind: "strLit", value: "[object Object]", type: STRING, loc }); const args: IrExpr[] = @@ -202,7 +228,10 @@ function depth(info: ClassInfo): number { } function samePlan(a: Plan, b: Plan): boolean { - return a.method === b.method; + return ( + a.method === b.method && + (a.method !== null || b.method !== null || a.date === (b as { date?: string }).date) + ); } /** A conversion method the class declares or inherits (a field of that @@ -227,11 +256,17 @@ function planOf(lowerer: Lowerer, info: ClassInfo, hint: ConversionHint, node: t // OrdinaryToPrimitive: "string" tries toString first, which every object // has (Object.prototype.toString answers a string); "default" and // "number" try valueOf first, whose Object.prototype version answers the - // object itself. - const order: ConversionMethod[] = hint === "string" ? ["toString"] : ["valueOf", "toString"]; + // object itself. Date.prototype[Symbol.toPrimitive] takes "default" as + // "string", and Date.prototype answers both methods with primitives. + const date = dateRootOf(info) !== null; + const order: ConversionMethod[] = + hint === "string" || (date && hint === "default") ? ["toString"] : ["valueOf", "toString"]; for (const method of order) { const found = declared(lowerer, info, method); - if (!found) continue; + if (!found) { + if (date && method !== "sym:toPrimitive") return { method: null, date: method }; + continue; + } if (!primitive(lowerer, found.ret)) refuse(lowerer, node, info, `a '${method}' method that can return an object`); return { method, ret: found.ret }; diff --git a/packages/compiler/src/frontend/lowering/class-unions.ts b/packages/compiler/src/frontend/lowering/class-unions.ts index f52026ba4..0021b2cf8 100644 --- a/packages/compiler/src/frontend/lowering/class-unions.ts +++ b/packages/compiler/src/frontend/lowering/class-unions.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "./stable-names.js"; import * as ts from "../ts7/adapter.js"; import { BOOL, typeKey, type IrExpr, type IrStmt, type IrType } from "../../ir/ir.js"; import { nodeThrowExpr, varRef } from "../../ir/build.js"; @@ -132,7 +133,7 @@ export function narrowClassUnion( const key = `classUnion:${source.className}:${target.unionId}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = `%class.union.${lowerer.valueHelpers.size}`; + helper = keyedHelperName(lowerer, "%class.union", key); lowerer.valueHelpers.set(key, helper); const input = varRef("value.0", source, loc); // Rank by ancestry before sorting: returning zero for unrelated pairs diff --git a/packages/compiler/src/frontend/lowering/coercions/function-adapters.ts b/packages/compiler/src/frontend/lowering/coercions/function-adapters.ts index ffdac19f0..fe3c14605 100644 --- a/packages/compiler/src/frontend/lowering/coercions/function-adapters.ts +++ b/packages/compiler/src/frontend/lowering/coercions/function-adapters.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "../stable-names.js"; import { dynUndefinedExpr } from "../../../ir/build.js"; import { buildFunctionAdapter } from "./builders.js"; import { InternalCompilerError } from "../../../errors.js"; @@ -33,7 +34,7 @@ export function funcReturnWidthAdapter( const key = `fn:${typeKey(fromT.ret.elem)}:${typeKey(toT.ret.elem)}`; const existing = lowerer.valueHelpers.get(key); if (existing) return existing; - const name = `%fn.width.${lowerer.valueHelpers.size}`; + const name = keyedHelperName(lowerer, "%fn.width", key); lowerer.valueHelpers.set(key, name); lowerer.freshClosureAdapters.add(name); // The returned closure's body: call the captured original, width-map. @@ -163,7 +164,7 @@ function restPackingAdapter( 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}`; + const name = keyedHelperName(lowerer, "%fn.adapt", key); lowerer.coercions.retags.set(key, name); lowerer.freshClosureAdapters.add(name); const fixed = fromT.params.length - 1; @@ -220,7 +221,7 @@ function funcIntoDynRestAdapter( 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}`; + const name = keyedHelperName(lowerer, "%fn.adapt", key); lowerer.coercions.retags.set(key, name); lowerer.freshClosureAdapters.add(name); const params: IrParam[] = [{ localId: "rest.0", name: "args", type: DYN }]; @@ -376,7 +377,7 @@ export function funcCoerceAdapter( 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}`; + const name = keyedHelperName(lowerer, "%fn.adapt", key); lowerer.coercions.retags.set(key, name); lowerer.freshClosureAdapters.add(name); const params: IrParam[] = toT.params.map((t, i) => ({ @@ -604,7 +605,7 @@ export function spawnResFnAdapter( const key = `fnspawn:${typeKey(fromT)}:${typeKey(toT)}`; const existing = lowerer.valueHelpers.get(key); if (existing) return existing; - const name = `%fnval.spawnres.${lowerer.valueHelpers.size}`; + const name = keyedHelperName(lowerer, "%fnval.spawnres", key); lowerer.valueHelpers.set(key, name); lowerer.freshClosureAdapters.add(name); const params: IrParam[] = toT.params.map((p, i) => ({ diff --git a/packages/compiler/src/frontend/lowering/coercions/structural-plans.ts b/packages/compiler/src/frontend/lowering/coercions/structural-plans.ts index 53b0748b4..f42663a13 100644 --- a/packages/compiler/src/frontend/lowering/coercions/structural-plans.ts +++ b/packages/compiler/src/frontend/lowering/coercions/structural-plans.ts @@ -1,7 +1,7 @@ import { planRecordUnionLift, planRecordUnionWrap } from "../union-retag.js"; import type { WidthLift } from "../width-lift.js"; import type { IrType } from "../../../ir/ir.js"; -import { isUnitType, typeEquals, UNDEFINED_T } from "../../../ir/ir.js"; +import { canDynCheckTo, isUnitType, typeEquals, UNDEFINED_T } from "../../../ir/ir.js"; import { type ClassInfo, findMethodOn, findGenericMethodOn } from "../lower-classes.js"; import type { Lowerer } from "../lowerer.js"; @@ -21,6 +21,22 @@ export function widthLiftPlan(lowerer: Lowerer, src: IrType, dst: IrType): Width if (dst.kind === "dyn" && src.kind !== "dyn" && lowerer.dynConvertible(src)) { return { how: "dynIn" }; } + // An 'unknown' (dyn) SOURCE field into a typed slot — a field TypeScript + // types `any` (a JSON.parse read), which the checker lets into any + // declared field type: the checked extraction, the same dynCheck a + // typed binding initialized from that value applies. + if ( + src.kind === "dyn" && + dst.kind !== "dyn" && + dst.kind !== "union" && + canDynCheckTo( + dst, + (id) => lowerer.shapes.get(id), + (id) => lowerer.unions.get(id), + ) + ) { + return { how: "dynOut" }; + } if (dst.kind === "union") { if (src.kind === "union") { if (lowerer.unionRetagMappable(src.unionId, dst.unionId)) return { how: "retag" }; @@ -108,6 +124,10 @@ export function widthLiftPlan(lowerer: Lowerer, src: IrType, dst: IrType): Width return { how: "discriminantRoute" }; } } + if (selected.length === 2 && src.kind === "record") { + const route = presenceRoute(lowerer, src.shapeId, selected[0]!, selected[1]!); + if (route) return route; + } if (selected.length !== 1) return null; return { how: "liftWrap", tag: selected[0]!.tag, arm: selected[0]!.arm }; } @@ -202,6 +222,42 @@ export function widthLiftPlan(lowerer: Lowerer, src: IrType, dst: IrType): Width return null; } +/** Two record arms a source record fits, where one arm declares a field + * the other lacks and the source types that field `T | undefined` + * (`{ count, errors: errs.length ? errs : undefined }` into `{ count; + * errors: string[] } | { count }`): the field's value picks the arm at + * run time. Null for any other pair. */ +function presenceRoute( + lowerer: Lowerer, + sourceId: string, + a: { tag: number; arm: IrType }, + b: { tag: number; arm: IrType }, +): WidthLift | null { + const source = lowerer.shapes.get(sourceId); + if (!source || source.tuple || source.indexValue || a.arm.kind !== "record") return null; + if (b.arm.kind !== "record") return null; + const shapeA = lowerer.shapes.get(a.arm.shapeId); + const shapeB = lowerer.shapes.get(b.arm.shapeId); + if (!shapeA || !shapeB) return null; + const optional = (t: IrType): boolean => + t.kind === "union" && lowerer.armTag(t.unionId, UNDEFINED_T) >= 0; + for (const [present, absent, presentShape, absentShape] of [ + [a, b, shapeA, shapeB], + [b, a, shapeB, shapeA], + ] as const) { + const extra = presentShape.fields.filter( + (f) => !absentShape.fields.some((g) => g.name === f.name), + ); + if (extra.length !== 1 || optional(extra[0]!.type)) continue; + if (absentShape.fields.some((g) => !presentShape.fields.some((f) => f.name === g.name))) + continue; + const field = source.fields.find((f) => f.name === extra[0]!.name); + if (!field || !optional(field.type)) continue; + return { how: "presenceRoute", field: field.name, present, absent }; + } + return null; +} + /** True for the unit-only element types (`(null | undefined)[]`, the * `readonly []` mapping): a union whose every arm is a unit. */ export function unitOnlyElem(lowerer: Lowerer, t: IrType): boolean { diff --git a/packages/compiler/src/frontend/lowering/coercions/structural.ts b/packages/compiler/src/frontend/lowering/coercions/structural.ts index 496a29607..c3b4ad906 100644 --- a/packages/compiler/src/frontend/lowering/coercions/structural.ts +++ b/packages/compiler/src/frontend/lowering/coercions/structural.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "../stable-names.js"; import { constructedValue } from "../constructor-returns.js"; import { dynUndefinedExpr, varRef } from "../../../ir/build.js"; import type { FieldLift } from "./structural-plans.js"; @@ -5,7 +6,7 @@ import { buildArrayConversion } from "./builders.js"; import type { WidthLift } from "../width-lift.js"; import { InternalCompilerError } from "../../../errors.js"; import type { IrExpr, IrFunction, IrRecordShape, IrStmt, IrType, SrcLoc } from "../../../ir/ir.js"; -import { BOOL, DYN, F64, STRING } from "../../../ir/ir.js"; +import { BOOL, DYN, F64, STRING, UNDEFINED_T } from "../../../ir/ir.js"; import { typeKey } from "../../type-mapper.js"; import { findStaticOn, findGenericStaticOn } from "../lower-classes.js"; import { lowerRecordOvfCaptureHelper } from "../containers/indexed-objects.js"; @@ -154,6 +155,76 @@ export function applyWidthLift( loc, }; } + case "presenceRoute": { + if (dst.kind !== "union" || value.type.kind !== "record") + throw new InternalCompilerError("lowerer bug: presenceRoute lift shape"); + const sourceType = value.type; + const fieldType = lowerer.shapes + .get(sourceType.shapeId) + ?.fields.find((f) => f.name === lift.field)?.type; + if (fieldType?.kind !== "union") + throw new InternalCompilerError("lowerer bug: presenceRoute field shape"); + // One helper per pair: the conversion reads the source twice. + const key = `presence:${typeKey(sourceType)}:${dst.unionId}:${lift.field}`; + let helper = lowerer.valueHelpers.get(key); + if (!helper) { + helper = `%union.presence.${lowerer.valueHelpers.size}`; + lowerer.valueHelpers.set(key, helper); + const source = (): IrExpr => varRef("v.0", sourceType, loc); + const arm = (route: { tag: number; arm: IrType }): IrExpr => { + const inner = lowerer.widthLiftPlan(sourceType, route.arm); + if (!inner) + throw new InternalCompilerError( + "lowerer bug: planned presenceRoute arm stopped lifting", + ); + return { + kind: "unionWrap", + unionId: dst.unionId, + tag: route.tag, + value: lowerer.applyWidthLift(inner, source(), route.arm, loc), + type: dst, + loc, + }; + }; + lowerer.liftedFns.push({ + name: helper, + params: [{ localId: "v.0", name: "v", type: sourceType }], + returnType: dst, + locals: [{ id: "v.0", name: "v", type: sourceType, mutable: false }], + body: [ + { + kind: "return", + value: { + kind: "ternary", + cond: { + kind: "unionIsTag", + unionId: fieldType.unionId, + tag: lowerer.armTag(fieldType.unionId, UNDEFINED_T), + value: { + kind: "recordGet", + obj: source(), + shapeId: sourceType.shapeId, + field: lift.field, + type: fieldType, + loc, + }, + negated: false, + type: BOOL, + loc, + }, + then: arm(lift.absent), + else_: arm(lift.present), + type: dst, + loc, + }, + loc, + }, + ], + loc, + }); + } + return { kind: "call", callee: helper, args: [value], type: dst, loc }; + } case "width": { if (dst.kind !== "record" || value.type.kind !== "record") throw new InternalCompilerError("lowerer bug: width lift shape"); @@ -219,6 +290,8 @@ export function applyWidthLift( throw new InternalCompilerError("lowerer bug: dynIn lift against a non-dyn slot"); return { kind: "dynFrom", value, type: DYN, loc }; } + case "dynOut": + return { kind: "dynCheck", value, type: dst, loc }; case "upcast": { if (dst.kind !== "object" || value.type.kind !== "object") throw new InternalCompilerError("lowerer bug: upcast lift shape"); @@ -253,7 +326,7 @@ export function unionRecordWidthHelper( const key = `unionWidth:${fromId}:${target.shapeId}`; const existing = lowerer.valueHelpers.get(key); if (existing) return existing; - const name = `%union.record.${lowerer.valueHelpers.size}`; + const name = keyedHelperName(lowerer, "%union.record", key); lowerer.valueHelpers.set(key, name); const type: IrType = { kind: "union", unionId: fromId }; const value = varRef("value.0", type, loc); @@ -312,7 +385,7 @@ export function recordWidthHelper( const key = `rec:${fromId}:${toId}`; const existing = lowerer.valueHelpers.get(key); if (existing) return existing; - const name = `%rec.width.${lowerer.valueHelpers.size}`; + const name = keyedHelperName(lowerer, "%rec.width", key); // Interned BEFORE the body builds: a recursive nested-width field // (self-referential shapes) resolves to this helper itself. lowerer.valueHelpers.set(key, name); @@ -341,7 +414,7 @@ export function tupleArrayWidthHelper( const key = `tuparr:${fromId}:${typeKey(toT.elem)}`; const existing = lowerer.valueHelpers.get(key); if (existing) return existing; - const name = `%tup.arr.${lowerer.valueHelpers.size}`; + const name = keyedHelperName(lowerer, "%tup.arr", key); lowerer.valueHelpers.set(key, name); const fromT: IrType = { kind: "record", shapeId: fromId }; const t: IrExpr = { kind: "varRef", localId: "t.0", type: fromT, loc }; @@ -388,7 +461,7 @@ export function emptyArrayLiftHelper( const key = `emptyarr:${typeKey(fromT.elem)}:${typeKey(toT.elem)}`; const existing = lowerer.valueHelpers.get(key); if (existing) return existing; - const name = `%arr.empty.${lowerer.valueHelpers.size}`; + const name = keyedHelperName(lowerer, "%arr.empty", key); lowerer.valueHelpers.set(key, name); const a: IrExpr = { kind: "varRef", localId: "a.0", type: fromT, loc }; lowerer.liftedFns.push({ @@ -452,7 +525,7 @@ export function arrayWidthHelper( const key = `arr:${typeKey(fromElem)}:${typeKey(toElem)}`; const existing = lowerer.valueHelpers.get(key); if (existing) return existing; - const name = `%arr.width.${lowerer.valueHelpers.size}`; + const name = keyedHelperName(lowerer, "%arr.width", key); lowerer.valueHelpers.set(key, name); const arrT: IrType = { kind: "array", elem: fromElem }; const outT: IrType = { kind: "array", elem: toElem }; @@ -492,7 +565,7 @@ export function objRecordWidthHelper( const key = `obj:${className}:${toId}`; const existing = lowerer.valueHelpers.get(key); if (existing) return existing; - const name = `%obj.width.${lowerer.valueHelpers.size}`; + const name = keyedHelperName(lowerer, "%obj.width", key); lowerer.valueHelpers.set(key, name); const fromT: IrType = { kind: "object", className }; lowerer.liftedFns.push(buildRecordProjection(lowerer, name, fromT, to, plan, loc)); @@ -517,7 +590,7 @@ export function recordClassWidthHelper( const key = `cls:${fromId}:${className}`; const existing = lowerer.valueHelpers.get(key); if (existing) return existing; - const name = `%cls.width.${lowerer.valueHelpers.size}`; + const name = keyedHelperName(lowerer, "%cls.width", key); lowerer.valueHelpers.set(key, name); lowerer.noteEdge(`%${className}.constructor`); const fromT: IrType = { kind: "record", shapeId: fromId }; diff --git a/packages/compiler/src/frontend/lowering/coercions/unions.ts b/packages/compiler/src/frontend/lowering/coercions/unions.ts index 06c0af9c6..434e687a5 100644 --- a/packages/compiler/src/frontend/lowering/coercions/unions.ts +++ b/packages/compiler/src/frontend/lowering/coercions/unions.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "../stable-names.js"; import { buildUnionNarrow, unionNarrowFailureMessage } from "../union-narrow.js"; import { isSafeToRepeat } from "../expressions/evaluation-safety.js"; import { nodeThrowExpr } from "../../../ir/build.js"; @@ -147,7 +148,7 @@ export function strandedUnitTrap( const key = `strandunit:${typeKey(expected)}:${expr.type.kind}`; let name = lowerer.coercions.retags.get(key); if (!name) { - name = `%unit.strand.${lowerer.coercions.retags.size}`; + name = keyedHelperName(lowerer, "%unit.strand", key); lowerer.coercions.retags.set(key, name); lowerer.liftedFns.push({ name, @@ -227,7 +228,7 @@ export function strandedCoercionTrap( const key = `strand:${expected.unionId}:${typeKey(src)}`; let name = lowerer.coercions.retags.get(key); if (!name) { - name = `%union.strand.${lowerer.coercions.retags.size}`; + name = keyedHelperName(lowerer, "%union.strand", key); lowerer.coercions.retags.set(key, name); const toT: IrType = { kind: "union", unionId: expected.unionId }; lowerer.liftedFns.push({ @@ -275,7 +276,7 @@ export function recordUnionWrapHelper( const key = `recordWrap:${source.shapeId}:${toId}`; const existing = lowerer.coercions.retags.get(key); if (existing) return existing; - const name = `%record.wrap.${lowerer.coercions.retags.size}`; + const name = keyedHelperName(lowerer, "%record.wrap", key); lowerer.coercions.retags.set(key, name); lowerer.liftedFns.push( buildRecordUnionWrap(name, source, to, plan, loc, (lift, value, dst) => @@ -307,7 +308,7 @@ export function recordUnionRouteHelper( (from, dst) => lowerer.widthLiftPlan(from, dst), ); if (!plan) return null; - const name = `%record.route.${lowerer.coercions.retags.size}`; + const name = keyedHelperName(lowerer, "%record.route", key); lowerer.coercions.retags.set(key, name); lowerer.liftedFns.push( buildRecordUnionWrap(name, source, to, plan, loc, (lift, value, dst) => @@ -352,7 +353,7 @@ export function unionRetagHelper( }); const key = `${fromId}:${toId}:${stranded.join(".")}`; const existing = lowerer.coercions.retags.get(key); - const name = existing ?? `%union.retag.${lowerer.coercions.retags.size}`; + const name = existing ?? keyedHelperName(lowerer, "%union.retag", key); if (!existing) { lowerer.coercions.retags.set(key, name); lowerer.liftedFns.push( @@ -410,7 +411,7 @@ export function narrowedArmHelper( lowerer.coercions.checkedNarrows.add(existing); return existing; } - const name = `%union.narrow.${lowerer.coercions.narrows.size}`; + const name = keyedHelperName(lowerer, "%union.narrow", key); lowerer.coercions.narrows.set(key, name); lowerer.coercions.checkedNarrows.add(name); const fn = buildUnionNarrow(name, from, target, loc, (type) => lowerer.fmt(type)); @@ -587,7 +588,7 @@ export function deferredReadHelper( const key = `deferred:${fromId}:${tag}`; const existing = lowerer.coercions.narrows.get(key); if (existing) return existing; - const name = `%deferred.read.${lowerer.coercions.narrows.size}`; + const name = keyedHelperName(lowerer, "%deferred.read", key); lowerer.coercions.narrows.set(key, name); const dflt: IrExpr = target.kind === "bool" diff --git a/packages/compiler/src/frontend/lowering/collection-ingestion.ts b/packages/compiler/src/frontend/lowering/collection-ingestion.ts index 5d14d5492..8fe2a6bbb 100644 --- a/packages/compiler/src/frontend/lowering/collection-ingestion.ts +++ b/packages/compiler/src/frontend/lowering/collection-ingestion.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "./stable-names.js"; import * as ts from "../ts7/adapter.js"; import { InternalCompilerError } from "../../errors.js"; import { typeKey } from "../type-mapper.js"; @@ -197,7 +198,7 @@ export function ingestCollection( const key = `ingest:${input.collection ? typeKey(input.collection) + ":" + input.selection : "cursor:" + typeKey(input.element)}:${typeKey(destination)}:${mapper ? typeKey(mapper.type) : "copy"}`; let name = lowerer.arrHofHelpers.get(key); if (!name) { - name = `%collection.ingest.${lowerer.arrHofHelpers.size}`; + name = keyedHelperName(lowerer, "%collection.ingest", key); lowerer.arrHofHelpers.set(key, name); const context = newFnCtx(false, null, null, destination); lowerer.fnStack.push(context); diff --git a/packages/compiler/src/frontend/lowering/containers/array-callbacks.ts b/packages/compiler/src/frontend/lowering/containers/array-callbacks.ts index eb99592bb..86f214bc1 100644 --- a/packages/compiler/src/frontend/lowering/containers/array-callbacks.ts +++ b/packages/compiler/src/frontend/lowering/containers/array-callbacks.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "../stable-names.js"; import { boolLit, countedFor, numLit, varRef } from "../../../ir/build.js"; import { transformStmtList } from "../../../ir/traverse.js"; import type { ScrDiagnostic } from "../../../diagnostics/diagnostic.js"; @@ -58,6 +59,7 @@ import { } from "./array-iteration.js"; import { dynamicReceiverThrows } from "./dynamic-receivers.js"; import { defaultAfterUndefined, lowerStaticallyUndefinedArgument } from "../optional-arguments.js"; +import { checkedFilterNarrowing } from "./filter-predicates.js"; /** `a.map(fn)` / `a.filter(fn)` / `a.forEach(fn)` desugar to a direct * call of a synthetic module function — one per method + element/result @@ -122,10 +124,11 @@ export function lowerArrayHofCall( } lowerer.badType(argNode, lowerer.typeOf(argNode)); } - const outElem = + const filtered = method === "filter" ? filterResultElem(lowerer, call, argNode, elem, valueT, booleanFilter) - : callbackArrayElement(lowerer, call, fnRet); + : null; + const outElem = filtered !== null ? filtered.elem : callbackArrayElement(lowerer, call, fnRet); // A filter that re-tags its elements keeps the single union-typed visit. const fast = present || booleanFilter || (method === "filter" && !typeEquals(outElem, elem)) @@ -144,19 +147,33 @@ export function lowerArrayHofCall( present, ); const resultType: IrType = method === "map" || method === "filter" ? arrayOf(outElem) : VOID; - return { + const result: IrExpr = { kind: "call", callee: helper, args: [receiver, fnArg, ...(fast ? [fast] : [])], type: resultType, loc, }; + const narrowing = filtered?.narrowing ?? null; + if (narrowing === null) return result; + return { + kind: "call", + callee: narrowing.helper, + args: [result], + type: arrayOf(narrowing.elem), + loc, + }; } -/** The checker-selected element of a filter result, with the same trust - * boundary as the historical narrowing filter: an inferred inline type - * predicate may prove one source arm; a written predicate annotation may - * not. Boolean is safe when every discarded arm is a nullish unit. */ +/** The element a filter keeps, and the checked conversion of the result + * to the checker's narrower element when the predicate does not prove it. + * An inferred inline type predicate proves one source arm, or a class + * view, so the loop keeps that type directly. A written predicate (`(p): p + * is Cat => ...`, a guard function passed as a value) is an assertion + * TypeScript does not check, and an inferred predicate that keeps several + * arms has no single arm to re-tag: the loop keeps the receiver's element + * and `narrowing` (checkedFilterNarrowing) converts each kept element. + * Boolean is safe when every discarded arm is a nullish unit. */ function filterResultElem( lowerer: Lowerer, call: ts.CallExpression, @@ -164,7 +181,37 @@ function filterResultElem( elem: IrType, valueT: IrType, booleanFilter: boolean, -): IrType { +): { elem: IrType; narrowing: { helper: string; elem: IrType } | null } { + const kept = filterKeptElem(lowerer, call, argNode, elem, valueT, booleanFilter); + if (typeof kept !== "string") return { elem: kept, narrowing: null }; + return { elem, narrowing: { helper: kept, elem: filterCheckerElem(lowerer, call, elem) } }; +} + +/** The checker's spelling of a filter result's element type. */ +function filterTypeText(lowerer: Lowerer, call: ts.CallExpression): string { + const result = lowerer.typeOf(call); + const element = lowerer.checker.isArrayType(result) + ? lowerer.checker.getTypeArguments(result as ts.TypeReference)[0] + : undefined; + return element === undefined ? "" : lowerer.checker.typeToString(element); +} + +/** The checker's element of a filter result, or the receiver's when the + * filter introduces no refinement. */ +function filterCheckerElem(lowerer: Lowerer, call: ts.CallExpression, elem: IrType): IrType { + const result = lowerer.mapTypeOf(lowerer.typeOf(call)); + return result?.kind === "array" ? result.elem : elem; +} + +/** filterResultElem's element, or the name of the checked narrowing helper. */ +function filterKeptElem( + lowerer: Lowerer, + call: ts.CallExpression, + argNode: ts.Expression, + elem: IrType, + valueT: IrType, + booleanFilter: boolean, +): IrType | string { const callT = lowerer.typeOf(call); const result = lowerer.mapTypeOf(callT); let outElem = result?.kind === "array" ? result.elem : elem; @@ -190,23 +237,31 @@ function filterResultElem( "keep the receiver's element type instead — annotate the callback's return ': boolean' " + "(the checker then skips the predicate) or annotate the result with the receiver's own " + "element type — and narrow the elements after"; - if (!booleanFilter) { + const written = + !booleanFilter && + ((!ts.isArrowFunction(argNode) && !ts.isFunctionExpression(argNode)) || + argNode.type !== undefined); + const narrowing = booleanFilter + ? null + : (): string | null => + checkedFilterNarrowing(lowerer, elem, outElem, filterTypeText(lowerer, call), locOf(call)); + if (written) { + const helper = narrowing!(); + if (helper !== null) return helper; if (!ts.isArrowFunction(argNode) && !ts.isFunctionExpression(argNode)) { lowerer.unsupported( "SC1090", argNode, - `narrowing '.filter' through a callback VALUE (only an inline callback whose predicate ` + - `the checker inferred can re-tag — ${annotateEscape})`, - ); - } - if (argNode.type) { - lowerer.unsupported( - "SC1090", - argNode, - `narrowing '.filter' with a hand-written type predicate (a written 'x is T' is an ` + - `unchecked assertion nothing validates at runtime — ${annotateEscape})`, + `narrowing '.filter' to '${lowerer.fmt(outElem)}' through a callback VALUE (no checked ` + + `conversion from '${lowerer.fmt(elem)}' — ${annotateEscape})`, ); } + lowerer.unsupported( + "SC1090", + argNode, + `narrowing '.filter' to '${lowerer.fmt(outElem)}' with a hand-written type predicate (no ` + + `checked conversion from '${lowerer.fmt(elem)}' — ${annotateEscape})`, + ); } const classRefinement = !booleanFilter && outElem.kind === "object" && canAssertClassValue(lowerer, valueT, outElem); @@ -214,6 +269,8 @@ function filterResultElem( !classRefinement && (valueT.kind !== "union" || lowerer.armTag(valueT.unionId, outElem) < 0) ) { + const helper = narrowing?.() ?? null; + if (helper !== null) return helper; const multiArm = outElem.kind === "union"; lowerer.unsupported( "SC1090", @@ -451,7 +508,7 @@ function withFastCallback(fn: IrFunction, fastT: CallbackType | null, elem: IrTy * constant-callback census then calls it directly and LLVM can inline the * callback into the loop (TurboFan's builtin+callback inlining). Callback * values keep the shared, type-interned helper. */ -function callbackSite(fnArg: IrExpr): string { +export function callbackSite(fnArg: IrExpr): string { return fnArg.kind === "closure" ? `@${fnArg.fnName}` : ""; } @@ -506,7 +563,7 @@ function arrayHofHelper( const key = `${method}:${typeKey(elem)}:${typeKey(fnRet)}:${arity}:${typeKey(outElem)}${site}${fastT ? ":split" : ""}${present ? ":present" : ""}`; const existing = lowerer.arrHofHelpers.get(key); if (existing) return existing; - const name = `%arr.${method}.${lowerer.arrHofHelpers.size}`; + const name = keyedHelperName(lowerer, `%arr.${method}`, key); lowerer.arrHofHelpers.set(key, name); lowerer.arrHofInfo.set(name, { method, elem, fnRet, arity, outElem, present, split: !!fastT }); const fn = buildArrayHofFn( @@ -619,7 +676,7 @@ function arrayUnionHofHelper( const key = `union:${method}:${receiverT.unionId}:${typeKey(callbackT)}:${typeKey(resultT)}`; const existing = lowerer.arrHofHelpers.get(key); if (existing) return existing; - const name = `%arr.union.${lowerer.arrHofHelpers.size}`; + const name = keyedHelperName(lowerer, "%arr.union", key); lowerer.arrHofHelpers.set(key, name); const receiver = varRef("a.0", receiverT, loc); const callback = varRef("f.0", callbackT, loc); @@ -777,6 +834,10 @@ function buildArrayHofFn( loc, }, readLen, + // map's result has the receiver's length, holes where the receiver + // has them. Storage for it is reserved first and the length is set + // after the loop, so a result without holes is filled by appends and + // gets no state bytes. ...(method === "map" ? [ { @@ -784,6 +845,7 @@ function buildArrayHofFn( arr: varRef("out.0", outT, loc), length: varRef("n.0", F64, loc), loc, + reserve: true, } satisfies IrStmt, ] : []), @@ -815,6 +877,16 @@ function buildArrayHofFn( loc, }, ]), + ...(method === "map" + ? [ + { + kind: "arraySetLength", + arr: varRef("out.0", outT, loc), + length: varRef("n.0", F64, loc), + loc, + } satisfies IrStmt, + ] + : []), { kind: "return", value: varRef("out.0", outT, loc), loc }, ]; } else if (method === "filter" && fastT) { @@ -1204,7 +1276,7 @@ function findHelper( const key = `${method}:${typeKey(elem)}:${typeKey(resultT)}:${typeKey(fnRet)}:${arity}${site}${present ? ":present" : ""}`; const existing = lowerer.arrHofHelpers.get(key); if (existing) return existing; - const name = `%arr.${method}.${lowerer.arrHofHelpers.size}`; + const name = keyedHelperName(lowerer, `%arr.${method}`, key); lowerer.arrHofHelpers.set(key, name); const arrT = arrayOf(elem); const valueT = callbackValueType(lowerer, elem, present); @@ -1304,7 +1376,7 @@ function findIndexHelper( const key = `${method}:${typeKey(elem)}:${typeKey(fnRet)}:${arity}${site}${fastT ? ":split" : ""}${present ? ":present" : ""}`; const existing = lowerer.arrHofHelpers.get(key); if (existing) return existing; - const name = `%arr.${method}.${lowerer.arrHofHelpers.size}`; + const name = keyedHelperName(lowerer, `%arr.${method}`, key); lowerer.arrHofHelpers.set(key, name); if (!last) lowerer.arrHofInfo.set(name, { @@ -1388,7 +1460,7 @@ function someEveryHelper( const key = `${method}:${typeKey(elem)}:${typeKey(fnRet)}:${arity}${site}${fastT ? ":split" : ""}${present ? ":present" : ""}`; const existing = lowerer.arrHofHelpers.get(key); if (existing) return existing; - const name = `%arr.${method}.${lowerer.arrHofHelpers.size}`; + const name = keyedHelperName(lowerer, `%arr.${method}`, key); lowerer.arrHofHelpers.set(key, name); lowerer.arrHofInfo.set(name, { method, @@ -1500,6 +1572,19 @@ export function lowerArrayFlatMapCall( } if (fnRet.kind === "union") { const def = lowerer.unions.get(fnRet.unionId); + const plan = def?.arms.some((a) => a.kind === "array") + ? flatMapUnionPlan(lowerer, call, argNode, fnRet) + : null; + if (plan) { + const helper = flatMapUnionHelper(lowerer, elem, fnRet, arity, plan, loc, present); + return { + kind: "call", + callee: helper, + args: [receiver, fnArg], + type: arrayOf(plan.outElem), + loc, + }; + } if (def?.arms.some((a) => a.kind === "array")) { lowerer.unsupported( "SC1090", @@ -1565,6 +1650,278 @@ export function lowerArrayFlatMapCall( }; } +/** How each arm of a flatMap callback's union result contributes to the + * output: an array arm appends its elements, an array arm the checker + * types `never[]` (an empty literal such as `s ? s : []`) appends nothing, + * and any other arm appends itself. */ +interface FlatMapUnionPlan { + outElem: IrType; + arms: ("spread" | "empty" | "value")[]; +} + +/** The plan for a callback returning `T | U[]`: every non-array arm must + * convert into the result's element type without a check, and every + * array arm's element type must be the result's. Null when an arm does + * not. */ +function flatMapUnionPlan( + lowerer: Lowerer, + call: ts.CallExpression, + argNode: ts.Expression, + fnRet: IrType & { kind: "union" }, +): FlatMapUnionPlan | null { + const out = lowerer.mapTypeOf(lowerer.typeOf(call)); + if (out?.kind !== "array") return null; + const outElem = out.elem; + const arms = lowerer.unions.get(fnRet.unionId)?.arms; + if (!arms) return null; + // The `never[]` constituents of the callback's checked result. + const emptyArms: IrType[] = []; + const signature = lowerer.checker.getCallSignatures(lowerer.typeOf(argNode))[0]; + if (signature) { + const ret = lowerer.checker.getReturnTypeOfSignature(signature); + for (const part of ret.isUnionType() ? ts.constituentTypes(ret) : [ret]) { + if (!lowerer.checker.isArrayType(part)) continue; + const [element] = lowerer.checker.getTypeArguments(part as ts.TypeReference); + if (element === undefined || (element.flags & ts.TypeFlags.Never) === 0) continue; + const mapped = lowerer.mapTypeOf(part); + if (mapped) emptyArms.push(mapped); + } + } + const converts = (t: IrType): boolean => { + if (typeEquals(t, outElem)) return true; + if (outElem.kind !== "union") return false; + return lowerer.armTag(outElem.unionId, t) >= 0; + }; + const plan: FlatMapUnionPlan["arms"] = []; + for (const arm of arms) { + if (arm.kind === "array" && emptyArms.some((e) => typeEquals(e, arm))) plan.push("empty"); + // An array arm copies its elements as they are stored, a present + // undefined included, so its element type is the result's. + else if (arm.kind === "array" && typeEquals(arm.elem, outElem)) plan.push("spread"); + else if (arm.kind !== "array" && converts(arm)) plan.push("value"); + else return null; + } + return { outElem, arms: plan }; +} + +/** The flatMap loop over a union-returning callback: each result tests + * its arm and appends its elements, nothing, or itself (Node's + * IsArray decision per value). */ +function flatMapUnionHelper( + lowerer: Lowerer, + elem: IrType, + fnRet: IrType & { kind: "union" }, + arity: number, + plan: FlatMapUnionPlan, + loc: SrcLoc, + present: boolean, +): string { + // The plan is part of the key: one union result type can carry an empty + // `never[]` arm in one callback and a populated array arm in another. + const key = `flatMapUnion:${typeKey(elem)}:${typeKey(fnRet)}:${typeKey(plan.outElem)}:${plan.arms.join(",")}:${arity}${present ? ":present" : ""}`; + const existing = lowerer.arrHofHelpers.get(key); + if (existing) return existing; + const name = `%arr.flatMap.${lowerer.arrHofHelpers.size}`; + lowerer.arrHofHelpers.set(key, name); + const arrT = arrayOf(elem); + const outT = arrayOf(plan.outElem); + const fnT = funcOf([callbackValueType(lowerer, elem, present), F64, arrT].slice(0, arity), fnRet); + const arms = lowerer.unions.get(fnRet.unionId)!.arms; + const outRef = (): IrExpr => varRef("out.0", outT, loc); + const resultRef = (): IrExpr => varRef("r.0", fnRet, loc); + const outLength = (): IrExpr => ({ + kind: "arrIntrinsic", + method: "length", + receiver: outRef(), + args: [], + type: F64, + loc, + }); + const locals: IrLocal[] = [ + ...arrayCallbackLocals(arrT, fnT), + { id: "out.0", name: "out", type: outT, mutable: false }, + { id: "r.0", name: "r", type: fnRet, mutable: false }, + ]; + const armBody = (tag: number): IrStmt[] => { + const arm = arms[tag]!; + const narrowed: IrExpr = { + kind: "unionNarrow", + unionId: fnRet.unionId, + tag, + value: resultRef(), + type: arm, + loc, + }; + if (plan.arms[tag] === "empty") return []; + if (plan.arms[tag] === "value") { + return [ + arrayValueStore( + lowerer, + outRef(), + outLength(), + lowerer.coerceToExpected( + // A unit arm's value is the unit itself, which has no + // narrowed representation. + isUnitType(arm) + ? { + kind: "unitLit", + unit: arm.kind === "nullT" ? "null" : "undefined", + type: arm, + loc, + } + : narrowed, + plan.outElem, + ), + plan.outElem, + loc, + ), + ]; + } + const innerT = arm as IrType & { kind: "array" }; + const listId = `list.${tag}`; + const lengthId = `m.${tag}`; + const indexId = `j.${tag}`; + const itemId = `inner.${tag}`; + locals.push( + { id: listId, name: "list", type: innerT, mutable: false }, + { id: lengthId, name: "m", type: F64, mutable: false }, + { id: indexId, name: "j", type: F64, mutable: true }, + { id: itemId, name: "inner", type: arrayValueType(lowerer, innerT.elem), mutable: false }, + ); + const list = (): IrExpr => varRef(listId, innerT, loc); + const index = (): IrExpr => varRef(indexId, F64, loc); + return [ + { kind: "varDecl", localId: listId, init: narrowed, loc }, + { + kind: "varDecl", + localId: lengthId, + init: { + kind: "arrIntrinsic", + method: "length", + receiver: list(), + args: [], + type: F64, + loc, + }, + loc, + }, + { + kind: "for", + init: { kind: "varDecl", localId: indexId, init: numLit(0, loc), loc }, + cond: { + kind: "bin", + op: "<", + left: index(), + right: varRef(lengthId, F64, loc), + type: BOOL, + loc, + }, + update: { + kind: "assign", + localId: indexId, + value: { kind: "bin", op: "+", left: index(), right: numLit(1, loc), type: F64, loc }, + loc, + }, + body: [ + { + kind: "if", + cond: arrayIndexPresent(list(), index(), loc), + then: [ + { + kind: "varDecl", + localId: itemId, + init: arrayValueRead(lowerer, list(), index(), innerT.elem, loc), + loc, + }, + arrayValueStore( + lowerer, + outRef(), + outLength(), + varRef(itemId, arrayValueType(lowerer, innerT.elem), loc), + plan.outElem, + loc, + ), + ], + else_: null, + loc, + }, + ], + loc, + }, + ]; + }; + let dispatch: IrStmt[] = armBody(arms.length - 1); + for (let tag = arms.length - 2; tag >= 0; tag--) { + dispatch = [ + { + kind: "if", + cond: { + kind: "unionIsTag", + unionId: fnRet.unionId, + tag, + value: resultRef(), + negated: false, + type: BOOL, + loc, + }, + then: armBody(tag), + else_: dispatch, + loc, + }, + ]; + } + const body: IrStmt[] = [ + { + kind: "varDecl", + localId: "out.0", + init: { kind: "arrayLit", elems: [], type: outT, loc }, + loc, + }, + arrayLengthDeclaration(arrT, loc), + countedFor(loc, varRef("n.0", F64, loc), () => [ + { + kind: "if", + cond: currentArrayIndexPresent(arrT, loc), + then: [ + { + kind: "varDecl", + localId: "r.0", + init: callArrayCallback( + arrT, + fnT, + fnRet, + arity, + callbackValueRead( + lowerer, + varRef("a.0", arrT, loc), + varRef("i.0", F64, loc), + elem, + present, + loc, + ), + loc, + ), + loc, + }, + ...dispatch, + ], + else_: null, + loc, + }, + ]), + { kind: "return", value: outRef(), loc }, + ]; + lowerer.liftedFns.push({ + name, + params: arrayCallbackParams(arrT, fnT), + returnType: outT, + locals, + body, + loc, + }); + return name; +} + /** The flatMap loop (array-returning callback), from existing IR nodes: * * out = []; n = a.length; @@ -1587,7 +1944,7 @@ function flatMapHelper( const key = `flatMap:${typeKey(elem)}:${typeKey(fnRet)}:${arity}${site}${fastT ? ":split" : ""}${present ? ":present" : ""}`; const existing = lowerer.arrHofHelpers.get(key); if (existing) return existing; - const name = `%arr.flatMap.${lowerer.arrHofHelpers.size}`; + const name = keyedHelperName(lowerer, "%arr.flatMap", key); lowerer.arrHofHelpers.set(key, name); lowerer.arrHofInfo.set(name, { method: "flatMapArray", @@ -1829,7 +2186,7 @@ function reduceHelper( const key = `${method}:${typeKey(elem)}:${typeKey(accT)}:${typeKey(fnRet)}:${arity}:${hasInit ? "init" : "seed"}${site}${fastT ? ":split" : ""}`; const existing = lowerer.arrHofHelpers.get(key); if (existing) return existing; - const name = `%arr.${method}.${lowerer.arrHofHelpers.size}`; + const name = keyedHelperName(lowerer, `%arr.${method}`, key); lowerer.arrHofHelpers.set(key, name); if (method === "reduce") lowerer.arrHofInfo.set(name, { @@ -2121,7 +2478,7 @@ export function lowerArraySortCall( const key = `${method}:${typeKey(elem)}:${arity}${native ? ":native" : ""}${keyed ? `:keyed${order}${reads ? `:field${reads.length}` : ""}` : ""}`; let helper = lowerer.arrHofHelpers.get(key); if (!helper) { - helper = `%arr.${method}.${lowerer.arrHofHelpers.size}`; + helper = keyedHelperName(lowerer, `%arr.${method}`, key); lowerer.arrHofHelpers.set(key, helper); const undefinedTag = elem.kind === "union" ? lowerer.armTag(elem.unionId, UNDEFINED_T) : -1; lowerer.liftedFns.push( @@ -2167,7 +2524,7 @@ function sortKeyReader( const cacheKey = `sortKey:${typeKey(elem)}:${sortKeysId(reads.map((read) => ({ order: 1, read })))}`; let reader = lowerer.arrHofHelpers.get(cacheKey); if (!reader) { - reader = `%arr.sortKey.${lowerer.arrHofHelpers.size}`; + reader = keyedHelperName(lowerer, "%arr.sortKey", cacheKey); lowerer.arrHofHelpers.set(cacheKey, reader); lowerer.liftedFns.push(buildSortKeyFn(reader, elem, reads, loc)); } @@ -2308,7 +2665,7 @@ function dynFlatMapHelper(lowerer: Lowerer, elemT: IrType, arity: number, loc: S const key = `dynflatmap:${typeKey(elemT)}:${arity}`; const existing = lowerer.arrHofHelpers.get(key); if (existing) return existing; - const name = `%dyn.flatmap.${lowerer.arrHofHelpers.size}`; + const name = keyedHelperName(lowerer, "%dyn.flatmap", key); lowerer.arrHofHelpers.set(key, name); lowerer.liftedFns.push(buildDynFlatMapFn(name, elemT, arity, loc)); return name; @@ -2481,7 +2838,7 @@ function dynFilterHelper(lowerer: Lowerer, elemT: IrType, arity: number, loc: Sr const key = `dynfilter:${typeKey(elemT)}:${arity}`; const existing = lowerer.arrHofHelpers.get(key); if (existing) return existing; - const name = `%dyn.filter.${lowerer.arrHofHelpers.size}`; + const name = keyedHelperName(lowerer, "%dyn.filter", key); lowerer.arrHofHelpers.set(key, name); lowerer.liftedFns.push(buildDynFilterFn(name, elemT, arity, loc)); return name; @@ -2649,6 +3006,7 @@ export function lowerTuplePredicateCall( // the value type an array find narrows from. let foundT: IrType = elem; let retag: string | null = null; + let narrowing: { helper: string; elem: IrType } | null = null; if (method === "filter") { // The element union is built in position order, so the checker's // result element can list the same arms in another order. @@ -2659,9 +3017,11 @@ export function lowerTuplePredicateCall( checkerResult?.kind === "array" && arms(checkerResult.elem).length === arms(elem).length && arms(checkerResult.elem).every((arm) => arms(elem).some((other) => typeEquals(arm, other))); - outElem = unchanged - ? elem - : filterResultElem(lowerer, call, argNode, elem, elem, booleanFilter); + if (!unchanged) { + const filtered = filterResultElem(lowerer, call, argNode, elem, elem, booleanFilter); + outElem = filtered.elem; + narrowing = filtered.narrowing; + } resultT = arrayOf(outElem); } else if (method === "find") { resultT = lowerer.irTypeOf(call); @@ -2676,7 +3036,7 @@ export function lowerTuplePredicateCall( const key = `tuple.${method}:${typeKey(receiver.type)}:${typeKey(fnArg.type)}:${typeKey(resultT)}:${arity}${callbackSite(fnArg)}`; let helper = lowerer.arrHofHelpers.get(key); if (!helper) { - helper = `%tuple.${method}.${lowerer.arrHofHelpers.size}`; + helper = keyedHelperName(lowerer, `%tuple.${method}`, key); lowerer.arrHofHelpers.set(key, helper); const v = varRef("v.0", elem, loc); const out = varRef("out.0", resultT, loc); @@ -2794,5 +3154,19 @@ export function lowerTuplePredicateCall( loc, }); } - return { kind: "call", callee: helper, args: [receiver, fnArg], type: resultT, loc }; + const result: IrExpr = { + kind: "call", + callee: helper, + args: [receiver, fnArg], + type: resultT, + loc, + }; + if (narrowing === null) return result; + return { + kind: "call", + callee: narrowing.helper, + args: [result], + type: arrayOf(narrowing.elem), + loc, + }; } diff --git a/packages/compiler/src/frontend/lowering/containers/array-concat.ts b/packages/compiler/src/frontend/lowering/containers/array-concat.ts index 4f6e4ca43..a7ce0a106 100644 --- a/packages/compiler/src/frontend/lowering/containers/array-concat.ts +++ b/packages/compiler/src/frontend/lowering/containers/array-concat.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "../stable-names.js"; import { identityPreservingWidening } from "../coercions/identity.js"; import { countedFor, numLit, varRef } from "../../../ir/build.js"; import { @@ -28,7 +29,7 @@ export function arrayConcatHelper( const key = `concat:${typeKey(elem)}:${shape.map((type) => (type ? `a:${typeKey(type)}` : "e")).join(";")}`; const existing = lowerer.arrHofHelpers.get(key); if (existing) return existing; - const name = `%arr.concat.${lowerer.arrHofHelpers.size}`; + const name = keyedHelperName(lowerer, "%arr.concat", key); const arrT = arrayOf(elem); const params = [ { localId: "a.0", name: "a", type: arrT }, @@ -96,11 +97,15 @@ export function arrayConcatHelper( return [ { kind: "varDecl", localId: "offset.0", init: length(out), loc }, { kind: "varDecl", localId: "count.0", init: length(source), loc }, + // Storage is reserved first and the length is set after the copy, so + // a source without holes is copied by appends and the result gets no + // state bytes. { kind: "arraySetLength", arr: out, length: { kind: "bin", op: "+", left: offset, right: count, type: F64, loc }, loc, + reserve: true, }, countedFor(loc, count, () => [ { @@ -133,6 +138,12 @@ export function arrayConcatHelper( loc, }, ]), + { + kind: "arraySetLength", + arr: out, + length: { kind: "bin", op: "+", left: offset, right: count, type: F64, loc }, + loc, + }, ]; }; const body: IrStmt[] = [ diff --git a/packages/compiler/src/frontend/lowering/containers/array-construction.ts b/packages/compiler/src/frontend/lowering/containers/array-construction.ts index 40e4d6436..1f10640c0 100644 --- a/packages/compiler/src/frontend/lowering/containers/array-construction.ts +++ b/packages/compiler/src/frontend/lowering/containers/array-construction.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "../stable-names.js"; import { generatorDrain } from "../iterator-adapters.js"; import { identityPreservingWidening } from "../coercions/identity.js"; import { liftedFreshSpread } from "../coercions/fresh-spread.js"; @@ -256,7 +257,7 @@ function appendWidenedArrayValues( const key = `insertValues:${typeKey(sourceType.elem)}:${typeKey(elem)}`; let name = lowerer.arrHofHelpers.get(key); if (!name) { - name = `%arr.insertValues.${lowerer.arrHofHelpers.size}`; + name = keyedHelperName(lowerer, "%arr.insertValues", key); lowerer.arrHofHelpers.set(key, name); const outType = arrayOf(elem); const valueType = arrayValueType(lowerer, source.type.elem); @@ -1035,7 +1036,7 @@ export function lowerArrayFromCall( const key = `fromArray:${typeKey(arrT.elem)}:${typeKey(outElem)}:${typeKey(fnRet)}:${arity}`; let helper = lowerer.arrHofHelpers.get(key); if (!helper) { - helper = `%arr.fromArray.${lowerer.arrHofHelpers.size}`; + helper = keyedHelperName(lowerer, "%arr.fromArray", key); lowerer.arrHofHelpers.set(key, helper); lowerer.liftedFns.push( buildArrayFromArrayFn(lowerer, helper, arrT.elem, outElem, fnRet, arity, loc), @@ -1122,7 +1123,7 @@ export function lowerArrayFromCall( const key = `fromLen:${typeKey(fnRet)}:${arity}`; let helper = lowerer.arrHofHelpers.get(key); if (!helper) { - helper = `%arr.fromLen.${lowerer.arrHofHelpers.size}`; + helper = keyedHelperName(lowerer, "%arr.fromLen", key); lowerer.arrHofHelpers.set(key, helper); lowerer.liftedFns.push(buildArrayFromLenFn(helper, fnRet, arity, loc)); } diff --git a/packages/compiler/src/frontend/lowering/containers/array-methods.ts b/packages/compiler/src/frontend/lowering/containers/array-methods.ts index e9a130a2d..44182fbda 100644 --- a/packages/compiler/src/frontend/lowering/containers/array-methods.ts +++ b/packages/compiler/src/frontend/lowering/containers/array-methods.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "../stable-names.js"; import { liftedFreshSpread } from "../coercions/fresh-spread.js"; import { lowerArrayIteratorValue } from "../iterator-adapters.js"; import { identityPreservingWidening } from "../coercions/identity.js"; @@ -1616,7 +1617,7 @@ function arraySearchHelper( const key = `${method}:${typeKey(elem)}:${typeKey(valueT)}:${typeKey(needleT)}:${directNeedle}:${typeKey(fromT)}`; const existing = lowerer.arrHofHelpers.get(key); if (existing) return existing; - const name = `%arr.${method}.${lowerer.arrHofHelpers.size}`; + const name = keyedHelperName(lowerer, `%arr.${method}`, key); lowerer.arrHofHelpers.set(key, name); const arrT = arrayOf(elem); const resultT = method === "includes" ? BOOL : F64; @@ -1972,7 +1973,7 @@ export function lowerTupleReadMethodCall( let helper = lowerer.arrHofHelpers.get(key); const resultType = method === "includes" ? BOOL : F64; if (!helper) { - helper = `%tuple.${method}.${lowerer.arrHofHelpers.size}`; + helper = keyedHelperName(lowerer, `%tuple.${method}`, key); lowerer.arrHofHelpers.set(key, helper); const params = [ { localId: "a.0", name: "a", type: receiver.type }, @@ -2034,7 +2035,7 @@ export function lowerTupleReadMethodCall( const key = `tuple.slice:${typeKey(receiver.type)}:${args.length}`; let helper = lowerer.arrHofHelpers.get(key); if (!helper) { - helper = `%tuple.slice.${lowerer.arrHofHelpers.size}`; + helper = keyedHelperName(lowerer, "%tuple.slice", key); lowerer.arrHofHelpers.set(key, helper); const params = [receiver, ...args].map((arg, i) => ({ localId: i === 0 ? "a.0" : `arg.${i}`, @@ -2125,7 +2126,7 @@ export function lowerTupleReadMethodCall( const key = `tuple.${method}:${typeKey(receiver.type)}:${typeKey(fnArg.type)}:${typeKey(outElem)}`; let helper = lowerer.arrHofHelpers.get(key); if (!helper) { - helper = `%tuple.${method}.${lowerer.arrHofHelpers.size}`; + helper = keyedHelperName(lowerer, `%tuple.${method}`, key); lowerer.arrHofHelpers.set(key, helper); const out = varRef("out.0", outType, loc); const result = varRef("r.0", ret, loc); @@ -2253,7 +2254,7 @@ function lowerArrayAtCall( const key = `at:${typeKey(elem)}:${typeKey(resultT)}:${typeKey(index.type)}`; let name = lowerer.arrHofHelpers.get(key); if (!name) { - name = `%arr.at.${lowerer.arrHofHelpers.size}`; + name = keyedHelperName(lowerer, "%arr.at", key); lowerer.arrHofHelpers.set(key, name); const arrT = arrayOf(elem); diff --git a/packages/compiler/src/frontend/lowering/containers/array-pipelines.ts b/packages/compiler/src/frontend/lowering/containers/array-pipelines.ts index cf45a7575..2f839a20b 100644 --- a/packages/compiler/src/frontend/lowering/containers/array-pipelines.ts +++ b/packages/compiler/src/frontend/lowering/containers/array-pipelines.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "../stable-names.js"; import { boolLit, countedFor, numLit, varRef } from "../../../ir/build.js"; import { BOOL, @@ -851,7 +852,7 @@ class PipelineFusion { if (!built) return null; let name = this.helpers.get(built.key); if (!name) { - name = `%arr.fused.${this.helpers.size}`; + name = keyedHelperName(this.lowerer, "%arr.fused", built.key); this.helpers.set(built.key, name); this.added.push({ ...built.fn, name }); } @@ -1262,17 +1263,28 @@ class FusedLoop { loc, }); if (holes) { + // The result keeps the source's holes: storage for its length is + // reserved first and the length is set after the loop, so a result + // without holes is filled by appends and gets no state bytes. + const length = (): IrExpr => ({ + kind: "ternary", + cond: { kind: "bin", op: "<", left: lo, right: hi, type: BOOL, loc }, + then: { kind: "bin", op: "-", left: hi, right: lo, type: F64, loc }, + else_: numLit(0, loc), + type: F64, + loc, + }); stateDecls.push({ kind: "arraySetLength", arr: varRef(out, resultT, loc), - length: { - kind: "ternary", - cond: { kind: "bin", op: "<", left: lo, right: hi, type: BOOL, loc }, - then: { kind: "bin", op: "-", left: hi, right: lo, type: F64, loc }, - else_: numLit(0, loc), - type: F64, - loc, - }, + length: length(), + loc, + reserve: true, + }); + epilogue.push({ + kind: "arraySetLength", + arr: varRef(out, resultT, loc), + length: length(), loc, }); } diff --git a/packages/compiler/src/frontend/lowering/containers/bytes.ts b/packages/compiler/src/frontend/lowering/containers/bytes.ts index bf9821d31..995cb177a 100644 --- a/packages/compiler/src/frontend/lowering/containers/bytes.ts +++ b/packages/compiler/src/frontend/lowering/containers/bytes.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "../stable-names.js"; import { boolLit, dynUndefinedExpr, numLit, varRef } from "../../../ir/build.js"; import { BUF_NUM_METHODS } from "./buffer-numeric-methods.js"; import * as ts from "../../ts7/adapter.js"; @@ -42,7 +43,7 @@ import { lowerArraySpreadItems, lowerCheckedArrayFrom } from "./array-constructi import { lowerToNumberArgument } from "../lower-exprs.js"; import { lowerBytesIteratorValue } from "../iterator-adapters.js"; import { lowerArrayCallback } from "./callback-arguments.js"; -import { findPredicateOk, predicateToBoolean } from "./array-callbacks.js"; +import { callbackSite, findPredicateOk, predicateToBoolean } from "./array-callbacks.js"; import { typeKey } from "../../type-mapper.js"; /** TypedArray.prototype.sort and toSorted. The receiver and comparator @@ -77,7 +78,7 @@ function lowerBytesSortCall( const cacheKey = `bytes.${method}:${bytesT.elem}:${key}`; let helper = lowerer.arrHofHelpers.get(cacheKey); if (!helper) { - helper = `%bytes.${method}.${lowerer.arrHofHelpers.size}`; + helper = keyedHelperName(lowerer, `%bytes.${method}`, cacheKey); lowerer.arrHofHelpers.set(cacheKey, helper); lowerer.liftedFns.push( buildBytesSortFn(helper, bytesT, arity, hasComparator, copyFirst, order, loc), @@ -250,13 +251,28 @@ function lowerBytesCallbackCall( : method === "findIndex" || method === "findLastIndex" ? F64 : lowerer.irTypeOf(call)); - const helper = bytesCallbackHelper(lowerer, method, bytesT, resultT, fnRet, arity, hasInit, loc); + const helper = bytesCallbackHelper( + lowerer, + method, + bytesT, + resultT, + fnRet, + arity, + hasInit, + loc, + callbackSite(fnArg), + ); const args: IrExpr[] = [receiver, fnArg]; if (hasInit) args.push(lowerer.lowerExprExpecting(call.arguments.nodes[1]!, resultT)); return { kind: "call", callee: helper, args, type: resultT, loc }; } -/** The interned helper of one typed-array callback method shape. */ +/** The interned helper of one typed-array callback method shape. A literal + * callback gets a helper of its own (`site`), which the backend then calls + * directly, as for the array methods. The visit is a loop on its own + * counter (`for (let i = 0; i < a.length; i++)`, or down from the last + * index), so the counter is an integer and the element reads need no + * index test. */ function bytesCallbackHelper( lowerer: Lowerer, method: BytesCallbackMethod, @@ -266,11 +282,12 @@ function bytesCallbackHelper( arity: number, hasInit: boolean, loc: SrcLoc, + site: string, ): string { - const key = `bytes.${method}:${bytesT.elem}:${typeKey(resultT)}:${typeKey(fnRet)}:${arity}:${hasInit ? "init" : ""}`; + const key = `bytes.${method}:${bytesT.elem}:${typeKey(resultT)}:${typeKey(fnRet)}:${arity}:${hasInit ? "init" : ""}${site}`; const existing = lowerer.arrHofHelpers.get(key); if (existing) return existing; - const name = `%bytes.${method}.${lowerer.arrHofHelpers.size}`; + const name = keyedHelperName(lowerer, `%bytes.${method}`, key); lowerer.arrHofHelpers.set(key, name); const reduce = method === "reduce" || method === "reduceRight"; const backward = method === "reduceRight" || method === "findLast" || method === "findLastIndex"; @@ -299,10 +316,20 @@ function bytesCallbackHelper( type: fnRet, loc, }); + // The forward bound is the receiver's length itself (fixed for a typed + // array, and equal to `n`), which the emitter's typed-array loops use. + const length = (): IrExpr => ({ + kind: "bytesIntrinsic", + method: "length", + receiver: a(), + args: [], + type: F64, + loc, + }); const inRange = (): IrExpr => backward ? { kind: "bin", op: ">=", left: i(), right: numLit(0, loc), type: BOOL, loc } - : { kind: "bin", op: "<", left: i(), right: n(), type: BOOL, loc }; + : { kind: "bin", op: "<", left: i(), right: length(), type: BOOL, loc }; const advance = (): IrStmt => ({ kind: "assign", localId: "i.0", @@ -343,6 +370,7 @@ function bytesCallbackHelper( ...(hasInit ? [{ localId: "z.0", name: "z", type: resultT }] : []), ]; const visit: IrStmt[] = [{ kind: "assign", localId: "v.0", value: at(i()), loc }]; + let seeded = false; const prologue: IrStmt[] = []; let epilogue: IrStmt[]; switch (method) { @@ -458,10 +486,12 @@ function bytesCallbackHelper( loc, }); } else { + // The seed is the first visited element; the loop starts past it. + seeded = true; prologue.push( { kind: "if", - cond: { kind: "unary", op: "!", operand: inRange(), type: BOOL, loc }, + cond: { kind: "bin", op: "===", left: n(), right: numLit(0, loc), type: BOOL, loc }, then: [ { kind: "throw", @@ -485,8 +515,16 @@ function bytesCallbackHelper( else_: null, loc, }, - { kind: "varDecl", localId: "acc.0", init: at(i()), loc }, - advance(), + { + kind: "varDecl", + localId: "acc.0", + init: at( + backward + ? { kind: "bin", op: "-", left: n(), right: numLit(1, loc), type: F64, loc } + : numLit(0, loc), + ), + loc, + }, ); } visit.push({ @@ -505,17 +543,30 @@ function bytesCallbackHelper( init: { kind: "bytesIntrinsic", method: "length", receiver: a(), args: [], type: F64, loc }, loc, }, - { - kind: "varDecl", - localId: "i.0", - init: backward - ? { kind: "bin", op: "-", left: n(), right: numLit(1, loc), type: F64, loc } - : numLit(0, loc), - loc, - }, { kind: "varDecl", localId: "v.0", init: numLit(0, loc), loc }, ...prologue, - { kind: "for", init: null, cond: inRange(), update: advance(), body: visit, loc }, + { + kind: "for", + init: { + kind: "varDecl", + localId: "i.0", + init: backward + ? { + kind: "bin", + op: "-", + left: n(), + right: numLit(seeded ? 2 : 1, loc), + type: F64, + loc, + } + : numLit(seeded ? 1 : 0, loc), + loc, + }, + cond: inRange(), + update: advance(), + body: visit, + loc, + }, ...epilogue, ]; lowerer.liftedFns.push({ name, params, returnType: resultT, locals, body, loc }); @@ -1077,11 +1128,20 @@ export function lowerBytesMethodCall( // Array-toString (comma join), a different operation: fenced. const declaredOnBuffer = (() => { const nameSym = lowerer.checker.getSymbolAtLocation(access.name); - return ( + if ( nameSym !== undefined && nameSym.declarations.some( (d) => ts.isInterfaceDeclaration(d.parent) && d.parent.name.text === "Buffer", ) + ) + return true; + // A receiver the lowering types as a Buffer where the checker says + // `any` (a JavaScript pipeline stage's chunk). + const receiverSym = lowerer.typeOf(access.expression).getSymbol(); + return ( + receiverSym !== undefined && + ts.symbolName(receiverSym) === "Buffer" && + receiverSym.declarations.some((d) => lowerer.isStdlibFile(ts.getSourceFileOfNode(d))) ); })(); if (receiverIr.elem !== "u8" || !declaredOnBuffer) { @@ -1354,7 +1414,8 @@ const BUF_ENCODINGS: Record = { * does not know — the ladder callers (stream options) turn unknown * literals into Node's runtime ERR_UNKNOWN_ENCODING throw. */ export function knownBufEncoding(name: string): string | undefined { - return own(BUF_ENCODINGS, name); + // Buffer.isEncoding: any letter case + return own(BUF_ENCODINGS, name) ?? own(BUF_ENCODINGS, name.toLowerCase()); } /** The literal encoding argument of a Buffer surface, normalized — or a @@ -1743,8 +1804,9 @@ function knownBufferProducer( /** Buffer.from over a checked-dynamic source and encoding, both already in * repeatable locals: Node's fromString takes utf8 for an absent, non-string - * or empty encoding and throws ERR_UNKNOWN_ENCODING for an unknown name; - * other sources ignore the encoding. */ + * or empty encoding and throws ERR_UNKNOWN_ENCODING for an unknown name; an + * ArrayBuffer takes the second argument as its byte offset; other sources + * ignore it. */ function dynBufferFromParts(source: IrExpr, encoding: IrExpr, loc: SrcLoc): IrExpr { const utf8: IrExpr = { kind: "strLit", value: "utf8", type: STRING, loc }; const isString = (x: IrExpr): IrExpr => ({ @@ -1786,10 +1848,12 @@ function dynBufferFromParts(source: IrExpr, encoding: IrExpr, loc: SrcLoc): IrEx type: BYTES_U8, loc, }, + // An ArrayBuffer takes the second argument as its byte offset + // (scr_buffer_from_dyn_offset_pooled); other values convert with utf8. else_: { kind: "libCall", - fn: "buffer.poolFromDynRef", - args: [source, utf8], + fn: "buffer.poolFromDynOffset", + args: [source, encoding], type: BYTES_U8, loc, }, diff --git a/packages/compiler/src/frontend/lowering/containers/callback-arguments.ts b/packages/compiler/src/frontend/lowering/containers/callback-arguments.ts index 18754f088..d95640978 100644 --- a/packages/compiler/src/frontend/lowering/containers/callback-arguments.ts +++ b/packages/compiler/src/frontend/lowering/containers/callback-arguments.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "../stable-names.js"; import * as ts from "../../ts7/adapter.js"; import type { Lowerer } from "../lowerer.js"; import { isJsSourceFile, locOf } from "../../program.js"; @@ -5,7 +6,9 @@ import { varRef } from "../../../ir/build.js"; import { typeKey } from "../../type-mapper.js"; import { BOOL, + DYN, F64, + STRING, type IrExpr, type IrType, type SrcLoc, @@ -50,6 +53,8 @@ export function lowerArrayCallback( bindUntyped = false, expectedReturn?: IrType, ): { fnArg: IrExpr & { type: IrType & { kind: "func" } }; arity: number } { + // `xs.map(((x) => x))`: a parenthesized callback is the function itself. + while (ts.isParenthesizedExpression(argNode)) argNode = argNode.expression; // 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 @@ -68,6 +73,20 @@ export function lowerArrayCallback( if (valueT.kind === "union") lowerer.requireTruthyUnion(valueT.unionId, argNode); return { fnArg: truthyFilterCallback(lowerer, valueT, locOf(argNode)), arity: 1 }; } + // The ambient `String` (`values.map(String)`): String(value) converts its + // first argument as a direct call does, whatever the element type; the + // constructor's own value form takes a string. + if ( + ts.isIdentifier(argNode) && + argNode.text === "String" && + !isJsSourceFile(ts.getSourceFileOfNode(argNode)) && + lowerer.isStdlibSymbol(lowerer.resolveValueSymbol(argNode) ?? undefined) + ) { + const valueT = lead[0]; + if (valueT === undefined || valueT.kind === "void") + lowerer.badType(argNode, lowerer.typeOf(argNode)); + return { fnArg: stringConversionCallback(lowerer, valueT, 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 @@ -273,6 +292,49 @@ function runtimeOptionalPairVariant(lowerer: Lowerer, expected: IrType, mapped: return lowerer.isRuntimeOptionalRecordVariant(strip(expected), strip(mapped)); } +/** `String` as a one-parameter callback over `valueT`: the conversion a + * direct `String(value)` call lowers to (the runtime's String() for unknown + * values and unions holding a symbol, ToString otherwise), interned per + * value type. */ +function stringConversionCallback( + lowerer: Lowerer, + valueT: IrType, + node: ts.Expression, +): IrExpr & { type: IrType & { kind: "func" } } { + const loc = locOf(node); + const fnT: IrType & { kind: "func" } = { kind: "func", params: [valueT], ret: STRING }; + const key = `mapString:${typeKey(valueT)}`; + let name = lowerer.arrHofHelpers.get(key); + if (!name) { + name = `%arr.mapString.${lowerer.arrHofHelpers.size}`; + lowerer.arrHofHelpers.set(key, name); + const value = varRef("v.0", valueT, loc); + const runtimeString = + valueT.kind === "dyn" || + (valueT.kind === "union" && + lowerer.unions.get(valueT.unionId)?.arms.some((arm) => arm.kind === "symbol") === true && + lowerer.dynConvertible(valueT)); + const converted: IrExpr = runtimeString + ? { + kind: "libCall", + fn: "dyn.stringConstructor", + args: [lowerer.coerceToExpected(value, DYN)], + type: STRING, + loc, + } + : lowerer.ensureString(value, node); + lowerer.liftedFns.push({ + name, + params: [{ localId: "v.0", name: "v", type: valueT }], + returnType: STRING, + locals: [{ id: "v.0", name: "v", type: valueT, mutable: false }], + body: [{ kind: "return", value: converted, loc }], + loc, + }); + } + return { kind: "closure", fnName: name, captures: [], type: fnT, loc }; +} + /** A native closure for the ambient Boolean callback. Reifying the * JavaScript constructor itself is unnecessary; Array#filter only observes * its one-argument ToBoolean result. */ @@ -285,7 +347,7 @@ export function truthyFilterCallback( const key = `filterBoolean:${typeKey(valueT)}`; let name = lowerer.arrHofHelpers.get(key); if (!name) { - name = `%arr.filterBoolean.${lowerer.arrHofHelpers.size}`; + name = keyedHelperName(lowerer, "%arr.filterBoolean", key); lowerer.arrHofHelpers.set(key, name); const value = varRef("v.0", valueT, loc); lowerer.liftedFns.push({ diff --git a/packages/compiler/src/frontend/lowering/containers/collection-grouping.ts b/packages/compiler/src/frontend/lowering/containers/collection-grouping.ts index 0bf126830..dae68d518 100644 --- a/packages/compiler/src/frontend/lowering/containers/collection-grouping.ts +++ b/packages/compiler/src/frontend/lowering/containers/collection-grouping.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "../stable-names.js"; import { countedFor, numLit, varRef } from "../../../ir/build.js"; import * as ts from "../../ts7/adapter.js"; import type { Lowerer } from "../lowerer.js"; @@ -104,7 +105,7 @@ export function lowerGroupByStaticCall( const key = `map.groupBy:${typeKey(items.type)}:${typeKey(f.type)}`; let helper = lowerer.mapHofHelpers.get(key); if (!helper) { - helper = `%map.groupBy.${lowerer.mapHofHelpers.size}`; + helper = keyedHelperName(lowerer, "%map.groupBy", key); lowerer.mapHofHelpers.set(key, helper); lowerer.liftedFns.push(buildGroupByFn(lowerer, helper, items.type, f.type, resultT, loc)); } @@ -141,7 +142,7 @@ export function lowerGroupByStaticCall( const key = `object.groupBy:${typeKey(items.type)}:${typeKey(f.type)}`; let helper = lowerer.mapHofHelpers.get(key); if (!helper) { - helper = `%object.groupBy.${lowerer.mapHofHelpers.size}`; + helper = keyedHelperName(lowerer, "%object.groupBy", key); lowerer.mapHofHelpers.set(key, helper); lowerer.liftedFns.push(buildGroupByFn(lowerer, helper, items.type, f.type, resultT, loc)); } diff --git a/packages/compiler/src/frontend/lowering/containers/collection-methods.ts b/packages/compiler/src/frontend/lowering/containers/collection-methods.ts index 370974c85..e043daf68 100644 --- a/packages/compiler/src/frontend/lowering/containers/collection-methods.ts +++ b/packages/compiler/src/frontend/lowering/containers/collection-methods.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "../stable-names.js"; import { nodeThrowExpr, boolLit, countedFor, numLit, strLit, varRef } from "../../../ir/build.js"; import { InternalCompilerError } from "../../../errors.js"; import * as ts from "../../ts7/adapter.js"; @@ -21,6 +22,7 @@ import { isPrimitiveCollectionKey, isUnitType, typeEquals, + UNDEFINED_T, } from "../../../ir/ir.js"; import { COLLECTION_ITERATOR_METHODS, @@ -43,7 +45,7 @@ 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"; +import { generatorDrain, lowerCollectionIteratorValue } 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 @@ -232,7 +234,7 @@ function lowerMapIterDrainCall( const key = `${method}:${typeKey(mapT.key)}:${typeKey(mapT.value)}`; let helper = lowerer.mapHofHelpers.get(key); if (!helper) { - helper = `%map.${method}.${lowerer.mapHofHelpers.size}`; + helper = keyedHelperName(lowerer, `%map.${method}`, key); lowerer.mapHofHelpers.set(key, helper); lowerer.liftedFns.push(buildMapIterDrainFn(helper, mapT, method, elemT, tupleT, loc)); } @@ -348,7 +350,7 @@ export function mapEntriesArray(lowerer: Lowerer, receiver: IrExpr): IrExpr { const key = `entries:${typeKey(mapT.key)}:${typeKey(mapT.value)}`; let helper = lowerer.mapHofHelpers.get(key); if (!helper) { - helper = `%map.entries.${lowerer.mapHofHelpers.size}`; + helper = keyedHelperName(lowerer, "%map.entries", key); lowerer.mapHofHelpers.set(key, helper); lowerer.liftedFns.push( buildMapIterDrainFn(helper, mapT, "entries", tupleT, tupleT, receiver.loc), @@ -519,7 +521,7 @@ export function lowerMapForEachCall( const key = `${typeKey(mapT.key)}:${typeKey(mapT.value)}:${arity}:${typeKey(fnRet)}`; let helper = lowerer.mapHofHelpers.get(key); if (!helper) { - helper = `%map.forEach.${lowerer.mapHofHelpers.size}`; + helper = keyedHelperName(lowerer, "%map.forEach", key); lowerer.mapHofHelpers.set(key, helper); lowerer.liftedFns.push(buildCollectionForEachFn(helper, mapT, arity, fnRet, loc)); } @@ -693,7 +695,7 @@ export function lowerSetForEachCall( const key = `${typeKey(setT.elem)}:${arity}:${typeKey(fnRet)}`; let helper = lowerer.setHofHelpers.get(key); if (!helper) { - helper = `%set.forEach.${lowerer.setHofHelpers.size}`; + helper = keyedHelperName(lowerer, "%set.forEach", key); lowerer.setHofHelpers.set(key, helper); lowerer.liftedFns.push(buildCollectionForEachFn(helper, setT, arity, fnRet, loc)); } @@ -745,7 +747,7 @@ function lowerSetCombineCall( const key = `${name}:${typeKey(setT.elem)}:${typeKey(otherT)}`; let helper = lowerer.setHofHelpers.get(key); if (!helper) { - helper = `%set.${name}.${lowerer.setHofHelpers.size}`; + helper = keyedHelperName(lowerer, `%set.${name}`, key); lowerer.setHofHelpers.set(key, helper); lowerer.liftedFns.push(buildSetCombineFn(helper, name, setT, otherT, loc)); } @@ -1344,6 +1346,17 @@ export function mapFromSeedValue( const drained = generatorDrain(lowerer, generator, entry, loc); return drained ? mapFromSeedValue(lowerer, drained, mapT) : null; } + // A Set of [key, value] pairs walks its values like a generator of them. + if (seed.type.kind === "set" && seed.type.elem.kind === "record") { + const walk = lowerCollectionIteratorValue( + lowerer, + seed, + "values", + { kind: "generator", yieldT: seed.type.elem, retT: VOID, nextT: UNDEFINED_T }, + loc, + ); + return walk ? mapFromSeedValue(lowerer, walk, 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 }; @@ -1357,7 +1370,7 @@ export function mapFromSeedValue( const key = `checked-seed:${typeKey(mapT)}`; let name = lowerer.mapHofHelpers.get(key); if (!name) { - name = `%map.checkedSeed.${lowerer.mapHofHelpers.size}`; + name = keyedHelperName(lowerer, "%map.checkedSeed", key); lowerer.mapHofHelpers.set(key, name); const source = varRef("source.0", DYN, loc); const entries = varRef("entries.0", DYN, loc); @@ -1457,7 +1470,7 @@ export function mapFromSeedValue( const key = `seed:${typeKey(mapT.key)}:${typeKey(mapT.value)}:${elem.shapeId}`; let helper = lowerer.mapHofHelpers.get(key); if (!helper) { - helper = `%map.seed.${lowerer.mapHofHelpers.size}`; + helper = keyedHelperName(lowerer, "%map.seed", key); lowerer.mapHofHelpers.set(key, helper); lowerer.liftedFns.push(buildMapSeedFn(mapT, helper, seed.type, elem, kT, vT, loc)); } diff --git a/packages/compiler/src/frontend/lowering/containers/filter-predicates.ts b/packages/compiler/src/frontend/lowering/containers/filter-predicates.ts new file mode 100644 index 000000000..3934edbf0 --- /dev/null +++ b/packages/compiler/src/frontend/lowering/containers/filter-predicates.ts @@ -0,0 +1,261 @@ +/* Checked narrowing for `.filter` with a written type predicate. + * + * A written predicate (`(p): p is Cat => ...`, or a guard function passed + * as a value) is an assertion TypeScript does not check, so the filter loop + * keeps the receiver's element type and the result converts to the + * predicate's type afterwards, element by element: + * + * - a union element to one of its arms, or to a union of some of its + * arms, by its tag; + * - a checked-dynamic element by dynCheck; + * - a class instance to a subclass by its class; + * - a tuple or record to one with the same fields, field by field. + * + * Each conversion throws the catchable TypeError of a checked extraction + * when a kept element is not of the predicate's type, which is when the + * predicate returned true for a value it does not describe. */ +import { varRef } from "../../../ir/build.js"; +import { + BOOL, + F64, + STRING, + isUnitType, + typeEquals, + type IrExpr, + type IrStmt, + type IrType, + type SrcLoc, +} from "../../../ir/ir.js"; +import { checkedClassAssertion } from "../class-assertions.js"; +import { buildArrayConversion } from "../coercions/builders.js"; +import type { Lowerer } from "../lowerer.js"; +import { keyedHelperName } from "../stable-names.js"; +import { typeKey } from "../../type-mapper.js"; + +/** The interned helper converting a `from[]` filter result to `to[]`, or + * null when an element of `from` has no checked conversion to `to`. + * `typeText` names the predicate's type in the TypeError. */ +export function checkedFilterNarrowing( + lowerer: Lowerer, + from: IrType, + to: IrType, + typeText: string, + loc: SrcLoc, +): string | null { + const element = elementHelper(lowerer, from, to, loc, typeText); + if (element === null) return null; + const key = `filter.narrow:${typeKey(from)}:${typeKey(to)}:${typeText}`; + const existing = lowerer.valueHelpers.get(key); + if (existing) return existing; + const name = keyedHelperName(lowerer, "%arr.narrow", key); + lowerer.valueHelpers.set(key, name); + const outT: IrType = { kind: "array", elem: to }; + lowerer.liftedFns.push( + buildArrayConversion( + name, + { kind: "array", elem: from }, + { kind: "arrayLit", elems: [], type: outT, loc }, + (value, _index, result) => ({ + kind: "arrIntrinsic", + method: "push", + receiver: result, + args: [{ kind: "call", callee: element, args: [value], type: to, loc }], + type: F64, + loc, + }), + loc, + ), + ); + return name; +} + +/** The interned helper converting one `from` value to `to`, or null. */ +function elementHelper( + lowerer: Lowerer, + from: IrType, + to: IrType, + loc: SrcLoc, + typeText = lowerer.fmt(to), +): string | null { + const key = `filter.narrow.value:${typeKey(from)}:${typeKey(to)}:${typeText}`; + const existing = lowerer.valueHelpers.get(key); + if (existing) return existing; + // A recursive type pair converts through the helper being built. + if (lowerer.coercions.planning.has(key)) return null; + lowerer.coercions.planning.add(key); + const input = varRef("v.0", from, loc); + let body: IrStmt[] | null; + try { + body = conversionBody(lowerer, input, from, to, typeText, loc); + } finally { + lowerer.coercions.planning.delete(key); + } + if (body === null) return null; + const name = keyedHelperName(lowerer, "%narrow.checked", key); + lowerer.valueHelpers.set(key, name); + lowerer.liftedFns.push({ + name, + params: [{ localId: "v.0", name: "v", type: from }], + returnType: to, + locals: [{ id: "v.0", name: "v", type: from, mutable: false }], + body, + loc, + }); + return name; +} + +/** A converted value: `value` itself when the types are equal, or a call of + * the conversion helper. */ +function converted( + lowerer: Lowerer, + value: IrExpr, + from: IrType, + to: IrType, + loc: SrcLoc, +): IrExpr | null { + if (typeEquals(from, to)) return value; + const helper = elementHelper(lowerer, from, to, loc); + return helper === null ? null : { kind: "call", callee: helper, args: [value], type: to, loc }; +} + +/** The TypeError a kept element of another type throws. */ +function typeError(message: string, loc: SrcLoc): IrStmt { + return { + kind: "throw", + value: { + kind: "libCall", + fn: "error.new", + args: [{ kind: "strLit", value: message, type: STRING, loc }], + type: { kind: "object", className: "%TypeError" }, + loc, + }, + loc, + }; +} + +function conversionBody( + lowerer: Lowerer, + input: IrExpr, + from: IrType, + to: IrType, + typeText: string, + loc: SrcLoc, +): IrStmt[] | null { + if (typeEquals(from, to)) return [{ kind: "return", value: input, loc }]; + if (from.kind === "dyn") + return [{ kind: "return", value: { kind: "dynCheck", value: input, type: to, loc }, loc }]; + if (from.kind === "object" && to.kind === "object") { + const asserted = checkedClassAssertion(lowerer, input, to, loc); + return asserted === null ? null : [{ kind: "return", value: asserted, loc }]; + } + if (from.kind === "union") + return unionConversion(lowerer, input, from.unionId, to, typeText, loc); + if (from.kind === "record" && to.kind === "record") { + const source = lowerer.shapes.get(from.shapeId); + const target = lowerer.shapes.get(to.shapeId); + if ( + !source || + !target || + source.tuple !== target.tuple || + source.indexValue || + target.indexValue + ) + return null; + if (source.fields.length !== target.fields.length) return null; + const fields: { name: string; value: IrExpr }[] = []; + for (const field of target.fields) { + const own = source.fields.find((f) => f.name === field.name); + if (!own) return null; + const read: IrExpr = { + kind: "recordGet", + obj: input, + shapeId: from.shapeId, + field: field.name, + type: own.type, + loc, + }; + const value = converted(lowerer, read, own.type, field.type, loc); + if (value === null) return null; + fields.push({ + name: field.name, + value: keepAbsence(lowerer, input, from.shapeId, field, value, loc), + }); + } + // The copy keeps the source's own keys in the source's order, as a width + // copy does (key-order-witness.ts). + const copy: IrExpr = { kind: "recordLit", fields, type: to, loc }; + return [{ kind: "return", value: lowerer.keyOrder.copy(copy, from.shapeId), loc }]; + } + return null; +} + +/** A converted field value that keeps the source field's absence: an + * optional field the source object lacks stays absent in the copy rather + * than becoming a property that holds undefined. */ +function keepAbsence( + lowerer: Lowerer, + input: IrExpr, + shapeId: string, + field: { name: string; type: IrType }, + value: IrExpr, + loc: SrcLoc, +): IrExpr { + if (field.type.kind !== "union") return value; + if (!lowerer.unions.get(field.type.unionId)?.arms.some((arm) => arm.kind === "undefinedT")) + return value; + return { + kind: "ternary", + cond: { kind: "recordHas", obj: input, shapeId, field: field.name, type: BOOL, loc }, + then: value, + else_: { kind: "fieldAbsent", unionId: field.type.unionId, type: field.type, loc }, + type: field.type, + loc, + }; +} + +/** A union value to one of its arms, or to a union of some of its arms: + * each arm the target holds returns, any other arm throws. */ +function unionConversion( + lowerer: Lowerer, + input: IrExpr, + unionId: string, + to: IrType, + typeText: string, + loc: SrcLoc, +): IrStmt[] | null { + const source = lowerer.unions.get(unionId); + if (!source) return null; + const targetArms = to.kind === "union" ? (lowerer.unions.get(to.unionId)?.arms ?? null) : [to]; + if (targetArms === null) return null; + const body: IrStmt[] = []; + let kept = 0; + for (let tag = 0; tag < source.arms.length; tag++) { + const arm = source.arms[tag]!; + const targetTag = targetArms.findIndex((t) => typeEquals(t, arm)); + if (targetTag < 0) continue; + kept++; + const payload: IrExpr = isUnitType(arm) + ? { kind: "unitLit", unit: arm.kind === "undefinedT" ? "undefined" : "null", type: arm, loc } + : { kind: "unionNarrow", unionId, tag, value: input, type: arm, loc }; + const value: IrExpr = + to.kind === "union" + ? { kind: "unionWrap", unionId: to.unionId, tag: targetTag, value: payload, type: to, loc } + : payload; + body.push({ + kind: "if", + cond: { kind: "unionIsTag", unionId, tag, negated: false, value: input, type: BOOL, loc }, + then: [{ kind: "return", value, loc }], + else_: null, + loc, + }); + } + // Every arm the target names must be one of the union's own arms. + if (kept === 0 || kept !== targetArms.length) return null; + body.push( + typeError( + `a kept element is not a '${typeText}' (a type predicate returned true for a value of another type)`, + loc, + ), + ); + return body; +} diff --git a/packages/compiler/src/frontend/lowering/containers/indexed-objects.ts b/packages/compiler/src/frontend/lowering/containers/indexed-objects.ts index efc173ffc..668603d47 100644 --- a/packages/compiler/src/frontend/lowering/containers/indexed-objects.ts +++ b/packages/compiler/src/frontend/lowering/containers/indexed-objects.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "../stable-names.js"; import { nullProtoRecordShape, recordNullProtoTest } from "../null-prototype.js"; import { countedFor, numLit, varRef } from "../../../ir/build.js"; import { objectEnumerationReceiver } from "../object-enumeration-receiver.js"; @@ -184,7 +185,7 @@ export function objectIterOverIndexShape( const key = `obj.${member}:ovf:${argIr.shapeId}:${typeKey(resultT)}`; let helper = lowerer.arrHofHelpers.get(key); if (!helper) { - helper = `%obj.${member}.${lowerer.arrHofHelpers.size}`; + helper = keyedHelperName(lowerer, `%obj.${member}`, key); const outRef = varRef("out.0", resultT, loc); const rRef = varRef("r.0", argIr, loc); @@ -608,7 +609,7 @@ function lowerTypedObjectFromEntriesCall( const key = `obj.fromEntries:${argIr.elem.shapeId}:${resultT.shapeId}`; let helper = lowerer.arrHofHelpers.get(key); if (!helper) { - helper = `%obj.fromEntries.${lowerer.arrHofHelpers.size}`; + helper = keyedHelperName(lowerer, "%obj.fromEntries", key); const tupleT = argIr.elem as IrType & { kind: "record" }; const tRef = varRef("t.0", tupleT, loc); @@ -712,7 +713,7 @@ function lowerFromEntriesStringRows( const key = `obj.fromEntries:strrows:${resultT.shapeId}`; let helper = lowerer.arrHofHelpers.get(key); if (!helper) { - helper = `%obj.fromEntries.${lowerer.arrHofHelpers.size}`; + helper = keyedHelperName(lowerer, "%obj.fromEntries", key); const tRef = varRef("t.0", rowT, loc); const rowLen: IrExpr = { @@ -931,7 +932,7 @@ export function lowerRecordOvfCaptureHelper( const key = `ovf:${fromId}:${toId}`; const existing = lowerer.valueHelpers.get(key); if (existing) return existing; - const name = `%rec.capture.${lowerer.valueHelpers.size}`; + const name = keyedHelperName(lowerer, "%rec.capture", key); lowerer.valueHelpers.set(key, name); const fromT: IrType = { kind: "record", shapeId: fromId }; const toT: IrType = { kind: "record", shapeId: toId }; @@ -1204,7 +1205,7 @@ export function lowerObjectAssignIndexShape( const key = `assign:${targetIr.shapeId}:${plan.fromId}`; const existing = lowerer.valueHelpers.get(key); if (existing) return existing; - const name = `%obj.assign.${lowerer.valueHelpers.size}`; + const name = keyedHelperName(lowerer, "%obj.assign", key); lowerer.valueHelpers.set(key, name); const toT: IrType = { kind: "record", shapeId: targetIr.shapeId }; const fromT: IrType = { kind: "record", shapeId: plan.fromId }; @@ -1387,6 +1388,15 @@ export type IndexMergeContributor = * JS own-key order. Explicit values arrive pre-coerced to the target's * value slot. Null when a spread source is outside that matrix (the * caller keeps its fence). */ +/** A value of an index slot's type that holds a key's place until a later + * write replaces it, or null for slot types without a literal. */ +function indexSlotPlaceholder(slot: IrType, loc: SrcLoc): IrExpr | null { + if (slot.kind === "string") return { kind: "strLit", value: "", type: STRING, loc }; + if (slot.kind === "f64") return { kind: "numLit", value: 0, type: slot, loc }; + if (slot.kind === "bool") return { kind: "boolLit", value: false, type: slot, loc }; + return null; +} + export function lowerIndexMergeHelper( lowerer: Lowerer, toId: string, @@ -1409,9 +1419,9 @@ export function lowerIndexMergeHelper( shapeId: string; wrapTag: number; retag: string | null; - fields: Map | null; + fields: Map | null; }[] = []; - for (const c of contributors) { + for (const [ci, c] of contributors.entries()) { // A conditional spread needs the undefined arm as its "absent" // value — a target slot without one can't carry the empty arm. if ( @@ -1425,15 +1435,26 @@ export function lowerIndexMergeHelper( if (!from || from.tuple) return null; if (!from.indexValue) { if (from.fields.some((f) => f.name.startsWith("%"))) return null; - const fields = new Map(); + const fields = new Map(); for (const ff of from.fields) { const lift = typeEquals(ff.type, tIv) ? ({ how: "copy" } as WidthLift) : tIv.kind === "dyn" && (ff.type.kind === "dyn" || lowerer.dynConvertible(ff.type)) ? "dyn" : lowerer.widthLiftPlan(ff.type, tIv); - if (lift === null) return null; - fields.set(ff.name, lift); + if (lift !== null) { + fields.set(ff.name, lift); + continue; + } + // A field a later plain property overrides (`{ ...tags, status: + // String(tags.status) }`): its value never survives, but its key + // keeps the spread's position, so a placeholder of the slot's + // type holds the place until the override writes. + const overridden = contributors + .slice(ci + 1) + .some((later) => later.kind === "field" && later.name === ff.name); + if (!overridden || indexSlotPlaceholder(tIv, loc) === null) return null; + fields.set(ff.name, "placeholder"); } srcPlans.push({ shapeId: c.shapeId, wrapTag: -1, retag: null, fields }); continue; @@ -1474,7 +1495,7 @@ export function lowerIndexMergeHelper( .join(","); const existing = lowerer.valueHelpers.get(key); if (existing) return existing; - const name = `%rec.merge.${lowerer.valueHelpers.size}`; + const name = keyedHelperName(lowerer, "%rec.merge", key); lowerer.valueHelpers.set(key, name); const toT: IrType = { kind: "record", shapeId: toId }; const ksT = arrayOf(STRING); @@ -1568,6 +1589,11 @@ export function lowerIndexMergeHelper( // own planned lift (absent optionals skip — the unset convention); // no overflow exists to walk. if (plan.fields !== null) { + // Keys enter in the source's enumeration order, as its own keys do. + // That order settles only after lowering (key-order witnesses), so + // the writes go into one block that a finalizer orders. + lowerer.keyOrder.observed.add(from.id); + const fieldStmts = new Map(); for (const ff of from.fields) { const lift = plan.fields.get(ff.name)!; const raw: IrExpr = { @@ -1585,13 +1611,16 @@ export function lowerIndexMergeHelper( shapeId: toId, key: { kind: "strLit", value: ff.name, type: STRING, loc }, value: - lift === "dyn" - ? { kind: "dynFrom", value: raw, type: DYN, loc } - : lowerer.applyWidthLift(lift, raw, tIv, loc), + lift === "placeholder" + ? indexSlotPlaceholder(tIv, loc)! + : lift === "dyn" + ? { kind: "dynFrom", value: raw, type: DYN, loc } + : lowerer.applyWidthLift(lift, raw, tIv, loc), overflowOnly: true, loc, }; - body.push( + fieldStmts.set( + ff.name, utag >= 0 && ff.type.kind === "union" ? { kind: "if", @@ -1603,6 +1632,17 @@ export function lowerIndexMergeHelper( : write, ); } + // declaredOrder omits internal '%'-fields, which never copy. + const ordered = (shape: IrRecordShape): IrStmt[] => + (shape.declaredOrder ?? shape.fields.map((f) => f.name)).flatMap((field) => { + const stmt = fieldStmts.get(field); + return stmt ? [stmt] : []; + }); + const group: IrStmt & { kind: "block" } = { kind: "block", body: ordered(from), loc }; + lowerer.shapeOrderHelperFinalizers.push(() => { + group.body = ordered(lowerer.shapes.get(plan.shapeId) ?? from); + }); + body.push(group); return; } const fIv = from.indexValue!; @@ -1805,7 +1845,7 @@ export function lowerEnvToPairsHelper( const key = `env.pairs:${shapeId}`; const existing = lowerer.valueHelpers.get(key); if (existing) return existing; - const name = `%env.pairs.${lowerer.valueHelpers.size}`; + const name = keyedHelperName(lowerer, "%env.pairs", key); lowerer.valueHelpers.set(key, name); const recT: IrType = { kind: "record", shapeId }; const arrT = arrayOf(STRING); diff --git a/packages/compiler/src/frontend/lowering/containers/iterator-helpers.ts b/packages/compiler/src/frontend/lowering/containers/iterator-helpers.ts index c23e6931c..ba5d0684d 100644 --- a/packages/compiler/src/frontend/lowering/containers/iterator-helpers.ts +++ b/packages/compiler/src/frontend/lowering/containers/iterator-helpers.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "../stable-names.js"; import { boolLit, numLit, varRef } from "../../../ir/build.js"; import { InternalCompilerError } from "../../../errors.js"; import * as ts from "../../ts7/adapter.js"; @@ -966,7 +967,7 @@ function lowerFusedChain( const key = `iter:${srcKey}:${stageKeys.join(",")}:${terminal}:${termArgs.map((a) => typeKey(a.type)).join(",")}`; let helper = lowerer.arrHofHelpers.get(key); if (!helper) { - helper = `%iter.${terminal}.${lowerer.arrHofHelpers.size}`; + helper = keyedHelperName(lowerer, `%iter.${terminal}`, key); lowerer.arrHofHelpers.set(key, helper); lowerer.liftedFns.push( buildIterChainFn( @@ -1038,7 +1039,7 @@ function lowerHelperObject( const key = `iterHelper:${stage.kind}:${srcKey}:${typeKey(srcElem)}:${typeKey(arg.type)}:${typeKey(outT)}`; let name = lowerer.arrHofHelpers.get(key); if (!name) { - name = `%iter.${stage.kind}.${lowerer.arrHofHelpers.size}`; + name = keyedHelperName(lowerer, `%iter.${stage.kind}`, key); lowerer.arrHofHelpers.set(key, name); lowerer.liftedFns.push( buildHelperGenFn(lowerer, name, source, srcElem, stage, arg.type, outT, resultType, loc), @@ -1058,7 +1059,7 @@ function internBudgetChecker(lowerer: Lowerer, loc: SrcLoc, srcT: GenType | null const key = srcT === null ? "iter:budget" : `iter:budget:close:${typeKey(srcT)}`; let name = lowerer.arrHofHelpers.get(key); if (name !== undefined) return name; - name = srcT === null ? "%iter.budget" : `%iter.budget.close.${lowerer.arrHofHelpers.size}`; + name = srcT === null ? "%iter.budget" : keyedHelperName(lowerer, "%iter.budget.close", key); lowerer.arrHofHelpers.set(key, name); const v = (): IrExpr => ({ kind: "varRef", localId: "v.0", type: F64, loc }); @@ -1222,7 +1223,7 @@ class HostFrame implements ChainFrame { /** The locals and parameters of a lifted helper function under * construction. */ -class LiftedFrame implements ChainFrame { +export class LiftedFrame implements ChainFrame { readonly locals: IrLocal[] = []; readonly params: IrParam[] = []; private n = 0; @@ -1252,7 +1253,7 @@ class LiftedFrame implements ChainFrame { * step leave it unclosed, as in Node. The generator counts as unfinished * before the first step, so a `pre` that breaks at once (take(0)) closes * a source it never pulled. `genT` must be stepDrivable. */ -function driveGenerator( +export function driveGenerator( lowerer: Lowerer, frame: ChainFrame, genId: string, diff --git a/packages/compiler/src/frontend/lowering/containers/string-and-regexp.ts b/packages/compiler/src/frontend/lowering/containers/string-and-regexp.ts index 9567ee0f6..1947f0d75 100644 --- a/packages/compiler/src/frontend/lowering/containers/string-and-regexp.ts +++ b/packages/compiler/src/frontend/lowering/containers/string-and-regexp.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "../stable-names.js"; import { matchAllRowsReadByElements } from "./match-row-uses.js"; import { boolLit, @@ -159,7 +160,7 @@ export function lowerStringSplitCall( const key = `str.split:${receiver.type.kind === "union" ? typeKey(receiver.type) : receiver.type.kind}:${typeKey(separator.type)}:${typeKey(limit.type)}:${absent}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = `%str.split.${lowerer.valueHelpers.size}`; + helper = keyedHelperName(lowerer, "%str.split", key); const values = [receiver, separator, limit]; const params = values.map((value, index) => ({ localId: `arg.${index}`, @@ -395,7 +396,7 @@ function stringIndexHelperCall( const key = `str.index:${method}:${typeKey(receiver.type)}:${typeKey(index.type)}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = `%str.index.${lowerer.valueHelpers.size}`; + helper = keyedHelperName(lowerer, "%str.index", key); lowerer.valueHelpers.set(key, helper); const rawReceiver = varRef("arg.0", receiver.type, loc); const rawIndex = varRef("arg.1", index.type, loc); @@ -673,7 +674,7 @@ export function lowerStringPaddingCall( const key = `str.pad:${method}:${values.map((value) => typeKey(value.type)).join(":")}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = `%str.pad.${lowerer.valueHelpers.size}`; + helper = keyedHelperName(lowerer, "%str.pad", key); const params = values.map((value, index) => ({ localId: `arg.${index}`, name: `arg${index}`, @@ -919,12 +920,12 @@ export function lowerRegexMethodCall( })(); if ((receiverKind === "string" || nullableStringRecv) && name === "match") { const arg0 = call.arguments.nodes[0]; - if (!arg0 || lowerer.mapTypeOf(lowerer.typeOf(arg0))?.kind !== "regex") return null; // string-pattern match: the SC2020 fence + if (!arg0 || !isRegexPatternArgument(lowerer, arg0)) return null; // string-pattern match: the SC2020 fence if (call.arguments.nodes.length !== 1) return null; const receiver = nullableStringRecv ? lowerMethodReceiver(lowerer, access.expression, STRING, access.name.text) : lowerReceiver(); - const re = lowerer.lowerExprExpecting(arg0, { kind: "regex" }); + const re = lowerRegexPatternArgument(lowerer, arg0); // RegExpMatchArray | null maps to the string[] | null union by // itself; intern it directly when the checker's spelling doesn't — // or when it maps to something WIDER (an optional-chain call node @@ -982,10 +983,10 @@ export function lowerRegexMethodCall( // 0, exactly Node. Never throws. if (receiverKind === "string" && name === "search") { const arg0 = call.arguments.nodes[0]; - if (!arg0 || lowerer.mapTypeOf(lowerer.typeOf(arg0))?.kind !== "regex") return null; // string-pattern form: the SC2020 fence + if (!arg0 || !isRegexPatternArgument(lowerer, arg0)) return null; // string-pattern form: the SC2020 fence if (call.arguments.nodes.length !== 1) return null; const receiver = lowerReceiver(); - const re = lowerer.lowerExprExpecting(arg0, { kind: "regex" }); + const re = lowerRegexPatternArgument(lowerer, arg0); return { kind: "regexIntrinsic", method: "search", receiver, args: [re], type: F64, loc }; } if (receiverKind === "string" && (name === "replace" || name === "replaceAll")) { @@ -1309,7 +1310,7 @@ export function lowerStringMethodCall( const key = `str.positions:${entry.method}:${typeKey(needle.type)}:${typeKey(position.type)}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = `%str.positions.${lowerer.valueHelpers.size}`; + helper = keyedHelperName(lowerer, "%str.positions", key); const params = [receiver, needle, position].map((arg, index) => ({ localId: `arg.${index}`, name: `arg${index}`, @@ -1411,7 +1412,7 @@ export function lowerStringMethodCall( const key = `str.positions:${entry.method}:${args.map((arg) => typeKey(arg.type)).join(":")}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = `%str.positions.${lowerer.valueHelpers.size}`; + helper = keyedHelperName(lowerer, "%str.positions", key); const params = [receiver, ...args].map((arg, index) => ({ localId: `arg.${index}`, name: `arg${index}`, @@ -1920,3 +1921,31 @@ export function lowerDynPrimitiveMethodCall( ); return seq(stmts, result); } + +/** Whether the pattern of `match` or `search` is a RegExp, or a RegExp that + * may be undefined (`s.match(patterns[i])` under noUncheckedIndexedAccess). */ +function isRegexPatternArgument(lowerer: Lowerer, node: ts.Expression): boolean { + const t = lowerer.mapTypeOf(lowerer.typeOf(node)); + if (t?.kind === "regex") return true; + if (t?.kind !== "union") return false; + const arms = lowerer.unions.get(t.unionId)?.arms ?? []; + return ( + arms.length === 2 && + arms.some((arm) => arm.kind === "regex") && + arms.some((arm) => arm.kind === "undefinedT") + ); +} + +/** The pattern of `match` or `search` as a RegExp: an undefined pattern is + * `new RegExp(undefined)`, the empty pattern, as in Node. */ +function lowerRegexPatternArgument(lowerer: Lowerer, node: ts.Expression): IrExpr { + const regex: IrType = { kind: "regex" }; + const empty: IrExpr = { + kind: "regexLit", + pattern: "(?:)", + flags: "", + type: regex, + loc: locOf(node), + }; + return lowerOptionalArgument(lowerer, node, regex, empty); +} diff --git a/packages/compiler/src/frontend/lowering/containers/string-replacement.ts b/packages/compiler/src/frontend/lowering/containers/string-replacement.ts index 6856bc50b..780c77d0f 100644 --- a/packages/compiler/src/frontend/lowering/containers/string-replacement.ts +++ b/packages/compiler/src/frontend/lowering/containers/string-replacement.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "../stable-names.js"; import * as ts from "../../ts7/adapter.js"; import { BOOL, @@ -162,7 +163,7 @@ function lowerStringReplacementValues( const key = `str.${method}:${typeKey(replacement.type)}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = `%str.${method}.${lowerer.valueHelpers.size}`; + helper = keyedHelperName(lowerer, `%str.${method}`, key); lowerer.valueHelpers.set(key, helper); const subject = varRef("s.0", STRING, loc); const needle = varRef("search.0", STRING, loc); diff --git a/packages/compiler/src/frontend/lowering/cycle-initialization.ts b/packages/compiler/src/frontend/lowering/cycle-initialization.ts index 092588a6e..4b1e74fcf 100644 --- a/packages/compiler/src/frontend/lowering/cycle-initialization.ts +++ b/packages/compiler/src/frontend/lowering/cycle-initialization.ts @@ -463,16 +463,38 @@ export function checkCycleBindingAccesses(lowerer: Lowerer, mod: IrModule): void /** Writes to a binding declared without an initializer that run after its * declaration store into an initialized binding whose slot may still be * empty: the pointer guard must not refuse them. Writes that can run - * earlier carry the flag check rewriteFunction inserted. */ + * earlier carry the flag check rewriteFunction inserted. An assignment in + * expression position (`(f = v)`) becomes an initializing `assign` whose + * value a temp holds and yields. */ function markUninitializedWrites(lowerer: Lowerer, mod: IrModule): void { const ids = new Set(); for (const [id, flag] of lowerer.cycleInitFlags) if (flag.uninitialized) ids.add(id); if (ids.size === 0) return; const mark = (s: IrStmt): IrStmt => s.kind === "assign" && !s.initializes && ids.has(s.localId) ? { ...s, initializes: true } : s; - const rewriteExpr = (e: IrExpr): IrExpr => mapExprChildren(e, rewriteExpr, rewriteStmt); - const rewriteStmt = (s: IrStmt): IrStmt => mark(mapStmtChildren(s, rewriteExpr, rewriteStmt)); - for (const fn of mod.functions) fn.body = fn.body.map(rewriteStmt); + for (const fn of mod.functions) { + let temps = 0; + const markExpr = (e: IrExpr): IrExpr => { + if (e.kind !== "assignExpr" || !ids.has(e.localId)) return e; + const t = `%uninitWrite.${temps++}`; + fn.locals.push({ id: t, name: "%uninitWrite", type: e.value.type, mutable: false }); + const value: IrExpr = { kind: "varRef", localId: t, type: e.value.type, loc: e.loc }; + return { + kind: "seqExpr", + stmts: [ + { kind: "varDecl", localId: t, init: e.value, loc: e.loc }, + { kind: "assign", localId: e.localId, value, initializes: true, loc: e.loc }, + ], + result: value, + type: e.type, + loc: e.loc, + }; + }; + const rewriteExpr = (e: IrExpr): IrExpr => + markExpr(mapExprChildren(e, rewriteExpr, rewriteStmt)); + const rewriteStmt = (s: IrStmt): IrStmt => mark(mapStmtChildren(s, rewriteExpr, rewriteStmt)); + fn.body = fn.body.map(rewriteStmt); + } } function rewriteFunction( diff --git a/packages/compiler/src/frontend/lowering/deferred-module-initializers.test.ts b/packages/compiler/src/frontend/lowering/deferred-module-initializers.test.ts index 28f05bfce..4696659bc 100644 --- a/packages/compiler/src/frontend/lowering/deferred-module-initializers.test.ts +++ b/packages/compiler/src/frontend/lowering/deferred-module-initializers.test.ts @@ -159,6 +159,15 @@ test("fills every empty copy with the exact file and span while preserving popul for (const untouched of [otherFile, otherStart, otherEnd]) expect(untouched.body).toEqual([]); }); +test("reports the functions whose placeholders it fills", () => { + const { initializers, pending, lowerer } = fixture(); + const functions = [fn("init", [block(loc)]), fn("use", [read("registry")])]; + pending.set("registry", [{ loc, lower: () => [value(4)] }]); + const filled: IrFunction[] = []; + expect(initializers.process(lowerer, functions, (f) => filled.push(f))).toBe(true); + expect(filled).toEqual([functions[0]]); +}); + test("an update of the binding demands its initializer", () => { const { initializers, pending, lowerer } = fixture(); const updated = block(loc), diff --git a/packages/compiler/src/frontend/lowering/deferred-module-initializers.ts b/packages/compiler/src/frontend/lowering/deferred-module-initializers.ts index eb22b4085..a44df8f75 100644 --- a/packages/compiler/src/frontend/lowering/deferred-module-initializers.ts +++ b/packages/compiler/src/frontend/lowering/deferred-module-initializers.ts @@ -129,7 +129,14 @@ export class DeferredModuleInitializers { return block; } - process(lowerer: Lowerer, functions: readonly IrFunction[]): boolean { + /** Materializes the initializers that reached bodies observe. `filled` + * receives each function whose body changes inside an unchanged statement + * list. */ + process( + lowerer: Lowerer, + functions: readonly IrFunction[], + filled?: (fn: IrFunction) => void, + ): boolean { if (this.pending.size === 0) return false; // Scans keep only the reads of deferred bindings. for (const key of this.pending.keys()) { @@ -192,7 +199,10 @@ export class DeferredModuleInitializers { } if (holders.length === 0) continue; // These bodies changed inside unchanged statement lists. - for (const fn of holders) this.scans.delete(fn); + for (const fn of holders) { + this.scans.delete(fn); + filled?.(fn); + } // An inserted body can introduce a placeholder needed by another // action in this pass. Unattached bodies are not part of the live IR. for (const nested of scanStatements(body).placeholders) add(nested, holders); diff --git a/packages/compiler/src/frontend/lowering/dispatch-sites.test.ts b/packages/compiler/src/frontend/lowering/dispatch-sites.test.ts new file mode 100644 index 000000000..1d027ac34 --- /dev/null +++ b/packages/compiler/src/frontend/lowering/dispatch-sites.test.ts @@ -0,0 +1,60 @@ +import { expect, test, vi } from "vitest"; +import { DYN, F64, VOID, type IrFunction, type IrStmt, type SrcLoc } from "../../ir/ir.js"; +import * as traversal from "../../ir/traverse.js"; +import { DispatchSites } from "./dispatch-sites.js"; + +const loc: SrcLoc = { file: "sites.ts", start: 0, end: 1 }; +const keyRead = (key: string): IrStmt => ({ + kind: "exprStmt", + expr: { + kind: "dynKeyGet", + value: { kind: "varRef", localId: "value", type: DYN, loc }, + key: { kind: "strLit", value: key, type: DYN, loc }, + type: DYN, + loc, + }, + loc, +}); +const value = (n: number): IrStmt => ({ + kind: "exprStmt", + expr: { kind: "numLit", value: n, type: F64, loc }, + loc, +}); +const fn = (body: IrStmt[]): IrFunction => ({ + name: "f", + body, + params: [], + locals: [], + returnType: VOID, + loc, +}); + +test("reuses a function's sites while its statement list is unchanged", () => { + const sites = new DispatchSites(); + const f = fn([value(1)]); + const walk = vi.spyOn(traversal, "everyStmtList"); + try { + expect(sites.of(f).dispatches).toBe(false); + expect(sites.of(f).dispatches).toBe(false); + expect(walk).toHaveBeenCalledTimes(1); + // A statement added to the same list is found. + f.body.push(keyRead("next")); + expect(sites.of(f)).toMatchObject({ dispatches: true, generatorSteps: true }); + // So is a replaced list. + f.body = [value(2)]; + expect(sites.of(f)).toMatchObject({ dispatches: false, generatorSteps: false }); + expect(walk).toHaveBeenCalledTimes(3); + } finally { + walk.mockRestore(); + } +}); + +test("scans a body again once a change inside an unchanged list is reported", () => { + const sites = new DispatchSites(); + const placeholder: Extract = { kind: "block", body: [], loc }; + const f = fn([placeholder]); + expect(sites.of(f).dispatches).toBe(false); + placeholder.body.push(keyRead("map")); + sites.forget(f); + expect(sites.of(f)).toMatchObject({ dispatches: true, runtimeSteps: true }); +}); diff --git a/packages/compiler/src/frontend/lowering/dispatch-sites.ts b/packages/compiler/src/frontend/lowering/dispatch-sites.ts new file mode 100644 index 000000000..c8a8d6ba6 --- /dev/null +++ b/packages/compiler/src/frontend/lowering/dispatch-sites.ts @@ -0,0 +1,284 @@ +import { InternalCompilerError } from "../../errors.js"; +import { + isClassOwnEnumerableFieldName, + isDynTypedRefType, + typeKey, + type IrFunction, + type IrStmt, + type IrType, +} from "../../ir/ir.js"; +import { everyStmtList } from "../../ir/traverse.js"; +import { toPrimitiveHint } from "./class-dynamic-dispatch.js"; +import { GENERATOR_STEP_METHODS, HELPER_METHODS } from "./generator-dynamic-dispatch.js"; + +/** Runtime entry points that step a checked-dynamic iterable's iterator: + * destructuring rest, and the collection constructors' and + * Object.fromEntries' seeds. */ +const RUNTIME_STEP_LIB_FNS: ReadonlySet = new Set([ + "dyn.destructureRest", + "dyn.nativeSetNew", + "dyn.mapSeedEntries", + "dyn.fromEntries", + "weakMap.new", + "weakSet.new", +]); + +/** What one function's body holds for the class dispatch pass and its + * caught-value, generator and class construction sub-passes, collected in + * one walk. Lists keep the order the walk meets their entries. */ +export interface FunctionSites { + statements: IrStmt[]; + length: number; + first: IrStmt | undefined; + last: IrStmt | undefined; + /** The value types of `dynFrom` expressions, once per type key. */ + values: IrType[]; + /** The types the class dispatch scan boxes, once per type key and class: + * `dynFrom` values, the parameter types of dynamic functions checked into + * native function types, and the receivers of own enumerable field writes + * and updates. A receiver counts only while its class (`fieldClass`) + * tracks its own fields. */ + boxing: { type: IrType; fieldClass?: string }[]; + /** JSON serialization of dynamic values. */ + serializes: boolean; + /** ToPrimitive conversions, and `dyn.valueOf` and `dyn.toString` calls. */ + conversions: boolean; + /** Sites the class dispatch rewrite can change. */ + dispatches: boolean; + /** `dynHasKey` tests. */ + keyTests: boolean; + /** `instanceof` tests of caught values, and caught values narrowed or + * checked to class types. */ + caughtClassTests: boolean; + /** Calls and reads of generator steps, and reads of iterator helper + * methods. */ + generatorSteps: boolean; + /** Values the runtime steps: iterator helper calls and reads, `dynIterN`, + * and rest destructuring. */ + runtimeSteps: boolean; + /** `dyn.classBasePrototype` calls. */ + basePrototypes: boolean; + /** The classes of thrown class instances, once each. */ + thrown: string[]; + /** `caughtToDyn` conversions. */ + caughtValues: boolean; +} + +/** The `libCall`s the class dispatch rewrite can change. */ +const DISPATCH_LIB_CALLS = new Set([ + "bytes.construct", + "dyn.keySet", + "dyn.keySetComputed", + "dyn.iterator", + "dyn.arrayFromIterator", + "dyn.toString", + "dyn.stringConstructor", + "dyn.forInKeys", + "dyn.forInKeyStrings", + "dyn.hasKeyComputed", + "dyn.hasOwnComputed", + "dyn.propertyIsEnumerableComputed", + "dyn.defineProperty", + "dyn.getPrototype", + "dyn.reflectGet", + "dyn.reflectSet", +]); + +/** Prototype data helpers (classPrototypeData) gain method slots inside + * their initialization block, so their summaries are not reused. */ +const PROTOTYPE_DATA_PREFIX = "%prototype.data."; + +/** SCRIPTC_CHECK_DISPATCH_SCANS=1 checks each reused summary against a fresh walk. */ +const CHECK_SCANS = process.env["SCRIPTC_CHECK_DISPATCH_SCANS"] === "1"; + +/** The function summaries (FunctionSites) of one class dispatch pass, kept + * across its runs. */ +export class DispatchSites { + private readonly sites = new Map(); + + /** The sites of `fn`. A summary is reused while the function's statement + * list is the same array with the same length and the same first and last + * statements: the dispatch passes replace the lists they rewrite and add + * statements to the helpers they extend. Other changes inside an + * unchanged list are reported with `forget`, except in prototype data + * helpers, which are scanned on every use. */ + of(fn: IrFunction): FunctionSites { + const cached = this.sites.get(fn); + if ( + cached !== undefined && + !fn.name.startsWith(PROTOTYPE_DATA_PREFIX) && + cached.statements === fn.body && + cached.length === fn.body.length && + cached.first === fn.body[0] && + cached.last === fn.body[fn.body.length - 1] + ) { + if (CHECK_SCANS && !sameSites(cached, scanSites(fn.body))) + throw new InternalCompilerError( + `reused dispatch sites of ${fn.name} disagree with a fresh scan`, + ); + return cached; + } + const sites = scanSites(fn.body); + this.sites.set(fn, sites); + return sites; + } + + /** Drops the summary of a function whose body changed inside an unchanged + * statement list. */ + forget(fn: IrFunction): void { + this.sites.delete(fn); + } +} + +function scanSites(statements: IrStmt[]): FunctionSites { + const sites: FunctionSites = { + statements, + length: statements.length, + first: statements[0], + last: statements[statements.length - 1], + values: [], + boxing: [], + serializes: false, + conversions: false, + dispatches: false, + keyTests: false, + caughtClassTests: false, + generatorSteps: false, + runtimeSteps: false, + basePrototypes: false, + thrown: [], + caughtValues: false, + }; + const valueKeys = new Set(); + const boxingKeys = new Set(); + const thrown = new Set(); + const box = (type: IrType, fieldClass?: string): void => { + const key = `${fieldClass ?? ""}\0${typeKey(type)}`; + if (boxingKeys.has(key)) return; + boxingKeys.add(key); + sites.boxing.push(fieldClass === undefined ? { type } : { type, fieldClass }); + }; + everyStmtList(statements, { + stmt: (statement) => { + if (statement.kind === "throw" && statement.value.type.kind === "object") { + const className = statement.value.type.className; + if (!thrown.has(className)) { + thrown.add(className); + sites.thrown.push(className); + } + } + // Field-creation instrumentation can box a base-constructor receiver + // even when only its derived instances otherwise cross the boundary. + if (statement.kind === "fieldSet" && isClassOwnEnumerableFieldName(statement.field)) + box(statement.obj.type, statement.className); + return true; + }, + expr: (expr) => { + if ( + expr.kind === "jsonStringify" || + (expr.kind === "libCall" && + (expr.fn === "json.stringifyValue" || expr.fn === "json.stringifyReplacer")) + ) + sites.serializes = true; + if ( + toPrimitiveHint(expr) !== null || + (expr.kind === "libCall" && (expr.fn === "dyn.valueOf" || expr.fn === "dyn.toString")) + ) + sites.conversions = true; + if ( + (expr.kind === "dynInvoke" && GENERATOR_STEP_METHODS.has(expr.method)) || + (expr.kind === "dynKeyGet" && + expr.key.kind === "strLit" && + (GENERATOR_STEP_METHODS.has(expr.key.value) || HELPER_METHODS.has(expr.key.value))) + ) + sites.generatorSteps = true; + if ( + (expr.kind === "dynInvoke" && HELPER_METHODS.has(expr.method)) || + (expr.kind === "dynKeyGet" && + expr.key.kind === "strLit" && + HELPER_METHODS.has(expr.key.value)) || + expr.kind === "dynIterN" || + (expr.kind === "libCall" && RUNTIME_STEP_LIB_FNS.has(expr.fn)) + ) + sites.runtimeSteps = true; + switch (expr.kind) { + case "dynFrom": { + const key = typeKey(expr.value.type); + if (!valueKeys.has(key)) { + valueKeys.add(key); + sites.values.push(expr.value.type); + } + box(expr.value.type); + break; + } + case "fieldIncDec": + if (isClassOwnEnumerableFieldName(expr.field)) box(expr.obj.type, expr.className); + break; + case "call": + if ( + (expr.callee === "%dyn.class.properties" || + expr.callee === "%dyn.class.readProperties") && + expr.args[0]?.kind === "dynFrom" && + isDynTypedRefType(expr.args[0].value.type) + ) + sites.dispatches = true; + break; + case "dynHasKey": + sites.keyTests = true; + break; + case "caughtTest": + if (expr.test === "instanceof") sites.caughtClassTests = true; + break; + case "caughtNarrow": + case "caughtCheck": + if (expr.type.kind === "object") sites.caughtClassTests = true; + break; + case "caughtToDyn": + sites.caughtValues = true; + break; + case "dynKeyGet": + case "dynInvoke": + sites.dispatches = true; + break; + case "dynCheck": + if (isDynTypedRefType(expr.type)) sites.dispatches = true; + // A dynamic function checked into a native function type + // receives its arguments as dynamic values: class instances + // passed to it cross the boundary when it is called (a JS + // `list.map((rec) => rec.match(x))` callback with an untyped + // parameter). + if (expr.type.kind === "func") expr.type.params.forEach((type) => box(type)); + break; + case "libCall": + if (expr.fn === "dyn.classBasePrototype") sites.basePrototypes = true; + if (DISPATCH_LIB_CALLS.has(expr.fn)) sites.dispatches = true; + break; + } + return true; + }, + }); + return sites; +} + +function sameSites(left: FunctionSites, right: FunctionSites): boolean { + const sameList = (a: readonly T[], b: readonly T[], same: (x: T, y: T) => boolean): boolean => + a.length === b.length && a.every((item, index) => same(item, b[index]!)); + return ( + sameList(left.values, right.values, (a, b) => a === b) && + sameList( + left.boxing, + right.boxing, + (a, b) => a.type === b.type && a.fieldClass === b.fieldClass, + ) && + sameList(left.thrown, right.thrown, (a, b) => a === b) && + left.serializes === right.serializes && + left.conversions === right.conversions && + left.dispatches === right.dispatches && + left.keyTests === right.keyTests && + left.caughtClassTests === right.caughtClassTests && + left.generatorSteps === right.generatorSteps && + left.runtimeSteps === right.runtimeSteps && + left.basePrototypes === right.basePrototypes && + left.caughtValues === right.caughtValues + ); +} diff --git a/packages/compiler/src/frontend/lowering/dyn-streams.ts b/packages/compiler/src/frontend/lowering/dyn-streams.ts index 2ac09e8e5..2167eba23 100644 --- a/packages/compiler/src/frontend/lowering/dyn-streams.ts +++ b/packages/compiler/src/frontend/lowering/dyn-streams.ts @@ -76,7 +76,7 @@ function dynNativeStream( /** Runs `lower` with `node` lowering to `value` and its member calls taking * `type` as the receiver representation. */ -function withStreamReceiver( +export function withStreamReceiver( lowerer: Lowerer, node: ts.Expression, value: IrExpr, diff --git a/packages/compiler/src/frontend/lowering/dynamic-tier.ts b/packages/compiler/src/frontend/lowering/dynamic-tier.ts index 0293f9ab7..3e0cea20a 100644 --- a/packages/compiler/src/frontend/lowering/dynamic-tier.ts +++ b/packages/compiler/src/frontend/lowering/dynamic-tier.ts @@ -304,7 +304,18 @@ export function scanDynamicTier(lowerer: Lowerer, module: IrModule): DynamicTier }); } const rank = { loop: 0, "called-in-loop": 1, recursive: 2 } as const; - hot.sort((a, b) => rank[a.hot] - rank[b.hot] || b.loopOperations - a.loopOperations); + // Functions that rank alike list in source order: by the file's place in + // the module order, then by position. + const fileOrder = new Map(lowerer.moduleOrder.map((sf, index) => [sf.fileName, index])); + const fileRank = (file: string): number => fileOrder.get(file) ?? lowerer.moduleOrder.length; + hot.sort( + (a, b) => + rank[a.hot] - rank[b.hot] || + b.loopOperations - a.loopOperations || + fileRank(a.loc.file) - fileRank(b.loc.file) || + (a.loc.file < b.loc.file ? -1 : a.loc.file > b.loc.file ? 1 : 0) || + a.loc.start - b.loc.start, + ); return { hot, packages: [...packages] @@ -332,14 +343,15 @@ function boundName(lowerer: Lowerer, loc: SrcLoc): string | null { /** A function's name as the source spells it, without a module prefix * (`%%m144.Session.finish` → `Session.finish`, `m163.find` → `find`). A - * function expression (`%fn`) takes its own name, else the name it is - * bound to, else `anonymous function`. */ + * function expression (`%fn.`, with `_` when the expression is + * named) takes its own name, else the name it is bound to, else + * `anonymous function`. */ function displayName(lowerer: Lowerer, f: HotDynamicFunction): string { const plain = f.name .replace(/^%+/, "") .replace(/^m\d+\./, "") .replace(/^%+/, ""); - const lambda = /^fn\d+(?:_(.+))?$/.exec(plain); + const lambda = /^fn\.[0-9a-f]+(?:_(.+))?$/.exec(plain); if (lambda === null) return plain; return lambda[1] ?? boundName(lowerer, f.loc) ?? "anonymous function"; } diff --git a/packages/compiler/src/frontend/lowering/expressions/array-literals.ts b/packages/compiler/src/frontend/lowering/expressions/array-literals.ts index 00eae1041..6c7ce814e 100644 --- a/packages/compiler/src/frontend/lowering/expressions/array-literals.ts +++ b/packages/compiler/src/frontend/lowering/expressions/array-literals.ts @@ -58,6 +58,41 @@ export function jsHoldsDynObject(lowerer: Lowerer, expr: ts.Expression): boolean return false; } +/** The literal is the source of an array destructuring: an assignment's + * right side or a declaration's initializer under an array pattern. */ +function isPatternSource(expr: ts.ArrayLiteralExpression): boolean { + let node: ts.Node = expr; + while (ts.isParenthesizedExpression(node.parent)) node = node.parent; + const parent = node.parent; + if (ts.isBinaryExpression(parent)) + return ( + parent.right === node && + parent.operatorToken.kind === ts.SyntaxKind.EqualsToken && + ts.isArrayLiteralExpression(parent.left) + ); + return ( + ts.isVariableDeclaration(parent) && + parent.initializer === node && + ts.isArrayBindingPattern(parent.name) + ); +} + +/** An empty TypeScript literal whose own type is `never[]`: tsc's type for + * `[]` with no contextual array type (`return []` in an async function, + * whose contextual type is `string[] | PromiseLike`; `{ files: [] }`). + * It holds no element, as the empty tuple does, so it builds as the + * unit-only element array, and an array slot receives it through the + * checked empty-array lift. never's f64 element mapping would make it a + * `number[]`, which no `string[]` slot accepts. */ +function emptyNeverLiteral(lowerer: Lowerer, expr: ts.ArrayLiteralExpression): boolean { + if (expr.elements.nodes.length > 0 || isJsSourceFile(ts.getSourceFileOfNode(expr))) return false; + const own = lowerer.typeOf(expr); + return ( + lowerer.checker.isArrayType(own) && + (lowerer.checker.getTypeArguments(own as ts.TypeReference)[0]!.flags & ts.TypeFlags.Never) !== 0 + ); +} + /** `[a, b, c]`. The element type comes from the contextual type when tsc * has one (`const a: number[] = []`, arguments, nested literals) and from * the literal's own inferred type otherwise. A bare `[]` with no context @@ -80,6 +115,8 @@ export function lowerArrayLiteral( ? lowerer.typeOf(expr) : (ctxType ?? lowerer.typeOf(expr)); let mapped = expected ?? lowerer.mapTypeOf(tsType); + if (expected === undefined && ctxType === undefined && emptyNeverLiteral(lowerer, expr)) + mapped = arrayOf(unitOnlyUnion(lowerer.unions)); // Inferred JavaScript arrays can contain unrelated constructors with // structurally equal checker types. Their native class ABIs still differ. if ( @@ -107,6 +144,22 @@ export function lowerArrayLiteral( ) mapped = inferred; } + // A destructuring pattern's implied type ends in a rest element + // (`[h, ...t] = [1, 2, 3]` supplies `[number, ...number[]]`), which maps + // to an array. The literal keeps its own fixed tuple layout, read by + // position like any tuple source. + if ( + expected === undefined && + ctxType && + isPatternSource(expr) && + lowerer.checker.isTupleType(ctxType) && + ( + (ctxType as ts.TupleTypeReference).getTarget() as ts.TupleType | undefined + )?.elementFlags?.some((flag) => (flag & ts.ElementFlags.Rest) !== 0) + ) { + const own = lowerer.mapTypeOf(lowerer.typeOf(expr)); + if (own?.kind === "record" && lowerer.shapes.get(own.shapeId)?.tuple) mapped = own; + } // A JS literal whose OWN inferred type is never-tainted // (neverTaintedJsType — the evolving `const gb = []`, the mixed // command tuple `['pwd', []]`) carries no element information: route @@ -131,11 +184,14 @@ export function lowerArrayLiteral( // the literal's own inferred type is the real tuple. if (!mapped || mapped.kind === "union" || mapped.kind === "dyn") { const ctxUnion = mapped?.kind === "union" ? mapped : null; + const ctxUnmapped = mapped === null; mapped = lowerer.mapTypeOf(lowerer.typeOf(expr)); // The never-tainted own type carries no element information here // either (the JS story above) — only a contextual union's single // array arm below may still supply a static home. if (neverTaintedOwnJs) mapped = null; + if (ctxUnmapped && emptyNeverLiteral(lowerer, expr)) + mapped = arrayOf(unitOnlyUnion(lowerer.unions)); // An EMPTY literal in a union slot (`const t: string[] | undefined = // []`, the `[]` default argument against `string[] | undefined`) has // no useful own type — tsc infers `never[]`, whose f64-element @@ -184,6 +240,21 @@ export function lowerArrayLiteral( if (arms.length === 1) mapped = arms[0]!; } } + // A NON-EMPTY literal whose own type is an array, under a union with + // exactly one array arm and no tuple arm (`[1, { n: true }]` in a + // `Json[]` arm of a recursive `Json`): the checker types each element + // from the arm, so its object literals lower as the arm's elements, + // and the literal's own element type (`number | { n: boolean }`) + // cannot hold them. Build it as the arm; its value only flows into the + // union slot. + if (ctxUnion && expr.elements.nodes.length > 0 && mapped?.kind === "array") { + const def = lowerer.unions.get(ctxUnion.unionId); + const arrayArms = def?.arms.filter((a) => a.kind === "array") ?? []; + const tupleArms = + def?.arms.filter((a) => a.kind === "record" && !!lowerer.shapes.get(a.shapeId)?.tuple) ?? + []; + if (arrayArms.length === 1 && tupleArms.length === 0) mapped = arrayArms[0]!; + } } // A Date's toJSON() element keeps its null in a literal with no declared // destination: the lib types say string. diff --git a/packages/compiler/src/frontend/lowering/expressions/binary.ts b/packages/compiler/src/frontend/lowering/expressions/binary.ts index fafbbf695..9702a6dd9 100644 --- a/packages/compiler/src/frontend/lowering/expressions/binary.ts +++ b/packages/compiler/src/frontend/lowering/expressions/binary.ts @@ -1,4 +1,5 @@ /* Binary operators: arithmetic, comparisons and equality, logical and nullish pairs, and string conversion for concatenation. */ +import { keyedHelperName } from "../stable-names.js"; import * as ts from "../../ts7/adapter.js"; import { cleanFuncAdaptable } from "../coercions/function-adapters.js"; import { type Lowerer, jsFuncNameOf } from "../lowerer.js"; @@ -801,7 +802,7 @@ function nullProtoToString(lowerer: Lowerer, e: IrExpr, t: IrType & { kind: "rec const key = `nullProtoToString:${t.shapeId}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = `%rec.tostr.${lowerer.valueHelpers.size}`; + helper = keyedHelperName(lowerer, "%rec.tostr", key); lowerer.valueHelpers.set(key, helper); const r = varRef("r.0", t, loc); lowerer.liftedFns.push({ @@ -902,10 +903,15 @@ export function lowerCompoundValueToTarget( // operator on both values, then the checked conversion into the // target's declared type (a string result for a number target throws the // catchable TypeError, as the expanded assignment does). + // A union operand (`fraction += "0"` on a binding the program assigns + // both a number and a string) takes the same runtime operator. if ( - (target.type.kind === "dyn" || rhs.type.kind === "dyn") && - (isJsSourceFile(ts.getSourceFileOfNode(expr)) || - (lowerer.dynConvertible(read.type) && lowerer.dynConvertible(rhs.type))) + ((target.type.kind === "dyn" || rhs.type.kind === "dyn") && + (isJsSourceFile(ts.getSourceFileOfNode(expr)) || + (lowerer.dynConvertible(read.type) && lowerer.dynConvertible(rhs.type)))) || + ((target.type.kind === "union" || rhs.type.kind === "union") && + lowerer.dynConvertible(read.type) && + lowerer.dynConvertible(rhs.type)) ) { const left = lowerer.coerceInto(expr.left, read, DYN); const right = lowerer.coerceInto(expr.right, rhs, DYN); @@ -1276,6 +1282,48 @@ export function lowerBinary(lowerer: Lowerer, expr: ts.BinaryExpression): IrExpr loc, }; } + // `a[k] = b[k] = v` in a JavaScript file: a member write in value + // position lowers as its statement form and yields the value. The + // receiver, the key and the value are evaluated in that order into + // temporaries first. A receiver held in a temporary must be a + // checked-dynamic value, which the temporary shares; any other receiver + // must be a variable or `this`. + if ( + op === ts.SyntaxKind.EqualsToken && + isJsSourceFile(ts.getSourceFileOfNode(expr)) && + (ts.isPropertyAccessExpression(expr.left) || ts.isElementAccessExpression(expr.left)) && + !expr.left.questionDotToken + ) { + const target = expr.left; + const receiverNode = target.expression; + const bareReceiver = + ts.isIdentifier(receiverNode) || receiverNode.kind === ts.SyntaxKind.ThisKeyword; + if (bareReceiver || tryLowerExpression(lowerer, receiverNode)?.type.kind === "dyn") { + const stmts: IrStmt[] = []; + const overrides: { node: ts.Expression; value: IrExpr }[] = []; + const hold = (node: ts.Expression, name: string): IrExpr => { + const value = lowerer.lowerExpr(node); + const local = lowerer.declareHiddenLocal(name, value.type); + stmts.push({ kind: "varDecl", localId: local.id, init: value, loc: value.loc }); + const held = varRef(local.id, value.type, value.loc); + overrides.push({ node, value: held }); + return held; + }; + if (!bareReceiver) hold(receiverNode, "%assignReceiver"); + if ( + ts.isElementAccessExpression(target) && + !ts.isIdentifier(target.argumentExpression) && + !ts.isStringLiteral(target.argumentExpression) && + !ts.isNumericLiteral(target.argumentExpression) + ) + hold(target.argumentExpression, "%assignKey"); + const result = hold(expr.right, "%assignValue"); + stmts.push( + lowerer.withExpressionOverrides(overrides, () => lowerer.lowerExprStatement(expr)), + ); + return { kind: "seqExpr", stmts, result, type: result.type, loc }; + } + } lowerer.unsupported( "SC1090", expr, diff --git a/packages/compiler/src/frontend/lowering/expressions/element-access.ts b/packages/compiler/src/frontend/lowering/expressions/element-access.ts index 74f0be955..045bebdf4 100644 --- a/packages/compiler/src/frontend/lowering/expressions/element-access.ts +++ b/packages/compiler/src/frontend/lowering/expressions/element-access.ts @@ -616,9 +616,25 @@ export function lowerElementAccess(lowerer: Lowerer, expr: ts.ElementAccessExpre // An indexed string property is absent for non-integer and missing // indexes. charAt has different coercion and out-of-range semantics. const recv = lowerer.lowerExpr(expr.expression); + const rawIndex = lowerer.lowerExpr(expr.argumentExpression); + // A checked-dynamic index (an untyped JavaScript parameter, a parsed + // value) reads the property its key names, as JavaScript does: a code + // unit for an integer index, the length for "length", else undefined. + // The checker's string type does not describe those results, so the + // value stays checked-dynamic and consumers convert it. + if (rawIndex.type.kind === "dyn" && lowerer.dynConvertible(recv.type)) { + const key = lowerRecordPropertyKey(lowerer, rawIndex, expr.argumentExpression); + return { + kind: "dynKeyGet", + value: lowerer.coerceInto(expr.expression, recv, DYN), + key, + type: DYN, + loc: locOf(expr), + }; + } const index = lowerOptionalNumber( lowerer, - lowerer.lowerExpr(expr.argumentExpression), + rawIndex, locOf(expr.argumentExpression), expr.argumentExpression, ); @@ -1305,6 +1321,15 @@ export function lowerRecordKeyRead( shape.fields.every((f) => typeEquals(f.type, shape.fields[0]!.type)) ) { declared = shape.fields[0]!.type; + } else if (shape.fields.length > 0) { + // Fields of different types (`row[key]` with `key: keyof Row`): the + // checker types the read as the union of the field types the key can + // name. When every declared field surfaces in that union (an arm, or a + // union that widens into it), the per-field dispatch wraps each hit + // into its arm. + const read = lowerer.mapTypeOf(lowerer.typeOf(expr)); + if (read !== null && read.kind === "union" && recordKeyResultOk(lowerer, shape, read)) + declared = read; } // Fields of different types answer a checked-dynamic value where nothing // typed the read: in JavaScript, and where the checker types it 'any' diff --git a/packages/compiler/src/frontend/lowering/expressions/identifiers.ts b/packages/compiler/src/frontend/lowering/expressions/identifiers.ts index b5f99d682..ff7848930 100644 --- a/packages/compiler/src/frontend/lowering/expressions/identifiers.ts +++ b/packages/compiler/src/frontend/lowering/expressions/identifiers.ts @@ -11,6 +11,7 @@ import { DYN, F64, type IrExpr, + type IrLocal, type IrType, STRING, type SrcLoc, @@ -40,6 +41,7 @@ import { runtimeOptionalUseOf, } from "../lower-exprs.js"; import { runtimeOptionalReceiverRead } from "./narrowing.js"; +import { iterableUnionOf } from "../iterable-values.js"; import { builtinGlobalValueAt } from "./property-access.js"; import { varRef } from "../../../ir/build.js"; import { @@ -68,6 +70,7 @@ import { builtinModuleConstOf, builtinModuleFnOf, builtinModulesArrayLit, + identifierReadSymbol, stdlibGlobalNameOf, } from "../surfaces.js"; import { builtinConstantsObject } from "../lower-builtin-values.js"; @@ -226,7 +229,10 @@ export function lowerIdentifierExpr(lowerer: Lowerer, expr: ts.Identifier, loc: if (use?.kind === "element") { const key = runtimeOptionalElementKey(use.access.argumentExpression); if (key === null) { - return varRef(local.id, local.type, loc); + return ( + runtimeOptionalKeyedRecord(lowerer, expr, local, loc) ?? + varRef(local.id, local.type, loc) + ); } return runtimeOptionalReceiverRead(lowerer, expr, local, key, loc); } @@ -317,6 +323,16 @@ export function lowerIdentifierExpr(lowerer: Lowerer, expr: ts.Identifier, loc: // value arm before routing the member/element operation so dynamic // keys and builtin record walkers do not see a union receiver. const narrowed = lowerer.mapTypeOf(lowerer.typeOf(expr)); + // An optional Iterable proven present re-tags into the Iterable. + if ( + g.type.kind === "union" && + narrowed?.kind === "union" && + narrowed.unionId !== g.type.unionId && + iterableUnionOf(lowerer, narrowed) + ) { + const helper = lowerer.narrowedRetagHelper(expr, g.type.unionId, narrowed.unionId, loc); + if (helper) return { kind: "call", callee: helper, args: [ref], type: narrowed, loc }; + } const arithmeticUnion = g.type.kind === "union" && lowerer.unions.get(g.type.unionId)?.arms.length === 2 && @@ -549,6 +565,9 @@ export function lowerIdentifierExpr(lowerer: Lowerer, expr: ts.Identifier, loc: const callable = lowerer.lowerBuiltinCallableValue(bi, loc); if (callable) return callable; } + // node:crypto's webcrypto is the WebCrypto global's object. + if (bi.module === "crypto" && bi.member === "webcrypto") + return { kind: "libCall", fn: "webcrypto.object", args: [], type: DYN, loc }; // JavaScript sources: an otherwise unsupported builtin VALUE is // the same identity-token story as stdlib globals above (the // harness adds worker_threads.Worker to its identity Set). @@ -721,7 +740,7 @@ export function lowerIdentifierExpr(lowerer: Lowerer, expr: ts.Identifier, loc: return { kind: "closure", fnName: name, captures: [], type, loc }; } if (lowerer.isStdlibGlobal(expr, "crypto")) - return { kind: "libCall", fn: "crypto.native", args: [], type: DYN, loc }; + return { kind: "libCall", fn: "webcrypto.object", args: [], type: DYN, loc }; const nativeAlias = stdlibGlobalNameOf(lowerer, expr); if (nativeAlias === "Buffer" && expr.text !== "Buffer") { return { kind: "strLit", value: "[builtin Buffer]", type: STRING, loc }; @@ -746,7 +765,7 @@ export function lowerIdentifierExpr(lowerer: Lowerer, expr: ts.Identifier, loc: return lowerGlobalValue(lowerer, expr); } { - const sym = lowerer.checker.getSymbolAtLocation(expr); + const sym = identifierReadSymbol(lowerer, expr); // The temporal global is typed (TS 7's lib slice) but Node 24 does // not define it: the read throws Node's ReferenceError. if (isTemporalGlobalRoot(lowerer, expr, sym)) { @@ -782,8 +801,6 @@ export function lowerIdentifierExpr(lowerer: Lowerer, expr: ts.Identifier, loc: "ArrayBuffer constructor values have no native lowering; use new ArrayBuffer(length) for fixed-length shared storage", WeakRef: "deref()-after-collect exposes GC timing — genuinely dynamic; hold a strong reference instead", - FinalizationRegistry: - "finalization callbacks expose GC timing — genuinely dynamic; release resources explicitly instead", eval: "runtime code evaluation cannot be compiled ahead of time", }; lowerer.noLowering(expr.text, expr, globalHints[expr.text], sym ?? undefined); @@ -935,10 +952,43 @@ function moduleFileName(lowerer: Lowerer, sf: ts.SourceFile): string { : sf.fileName; } -/** Object.keys/Object.entries require an object receiver, but their first - * argument is not syntactically a member receiver. Recognize that one - * standard-library position so a runtime-optional loop element can be - * checked against the checker-narrowed record arm before builtin lowering. */ +/** A computed-key access (`value[key]` after `typeof value === "object"`) + * of a runtime-optional binding the checker narrowed to one record arm of a + * wider union. The binding re-tags to that record or undefined, so the keyed + * read or write evaluates its operands and then throws Node's TypeError for + * an undefined receiver. The other arms, which the checker excluded, fail + * the checked re-tag. Null when the binding stores only the record and + * undefined, or the narrowed record is not one of its arms. */ +function runtimeOptionalKeyedRecord( + lowerer: Lowerer, + expr: ts.Identifier, + local: IrLocal, + loc: SrcLoc, +): IrExpr | null { + if (local.type.kind !== "union") return null; + const narrowed = lowerer.mapTypeOf(lowerer.typeOf(expr)); + if (narrowed?.kind !== "record") return null; + const fromId = local.type.unionId; + const arms = lowerer.unions.get(fromId)?.arms; + const recordTag = lowerer.armTag(fromId, narrowed); + const undefTag = lowerer.armTag(fromId, UNDEFINED_T); + if (!arms || arms.length <= 2 || recordTag < 0 || undefTag < 0) return null; + const target = lowerer.withUndefinedArm(narrowed); + if (target.kind !== "union") return null; + const trappable = new Set(); + for (let tag = 0; tag < arms.length; tag++) { + if (tag !== recordTag && tag !== undefTag) trappable.add(tag); + } + const helper = lowerer.unionRetagHelper(fromId, target.unionId, loc, trappable); + if (!helper) return null; + return lowerer.checkedNarrowCall(helper, varRef(local.id, local.type, loc), target, loc); +} + +/** Object.keys, Object.values and Object.entries require an object + * receiver, but their first argument is not syntactically a member + * receiver. Recognize that one standard-library position so a + * runtime-optional loop element can be checked against the checker-narrowed + * record arm before builtin lowering. */ function runtimeOptionalObjectWalkerArg(lowerer: Lowerer, expr: ts.Expression): boolean { let arg = expr; while ( @@ -959,7 +1009,9 @@ function runtimeOptionalObjectWalkerArg(lowerer: Lowerer, expr: ts.Expression): return false; const access = call.expression; return ( - (access.name.text === "keys" || access.name.text === "entries") && + (access.name.text === "keys" || + access.name.text === "values" || + access.name.text === "entries") && lowerer.isStdlibMember(access) ); } diff --git a/packages/compiler/src/frontend/lowering/expressions/narrowing.ts b/packages/compiler/src/frontend/lowering/expressions/narrowing.ts index 2e3dd6140..acac99610 100644 --- a/packages/compiler/src/frontend/lowering/expressions/narrowing.ts +++ b/packages/compiler/src/frontend/lowering/expressions/narrowing.ts @@ -46,6 +46,7 @@ import { } from "../lower-exprs.js"; import { isConstAssertionTypeNode, unitOnlyUnion } from "../../type-mapper.js"; import { assertsGlobalObject, extractionCopiesReference } from "../assertion-identity.js"; +import { iterableSlotValue, iterableUnionOf } from "../iterable-values.js"; /** `c ? a : b`. An explicit destination constructs each branch at that * layout before joining it. Without one, retain the expression's inferred @@ -692,6 +693,18 @@ export function maybeNarrow(lowerer: Lowerer, expr: IrExpr, node: ts.Node): IrEx const hosted = hostedStorageView(lowerer, expr, narrowed, expr.loc); if (hosted) return hosted; } + // An optional Iterable narrowed to the iterable union (`xs !== undefined`): + // re-tag into it, so for-of, spread and the other consumers see the + // Iterable itself. + if ( + narrowed?.kind === "union" && + narrowed.unionId !== expr.type.unionId && + iterableUnionOf(lowerer, narrowed) + ) { + const helper = lowerer.narrowedRetagHelper(node, expr.type.unionId, narrowed.unionId, expr.loc); + if (helper) + return { kind: "call", callee: helper, args: [expr], type: narrowed, loc: expr.loc }; + } // A checker type narrowed to a UNIT arm (the `=== undefined` branch) // also stays union-typed: a unit arm has no payload to extract, and // nothing useful reads such a value anyway. (Standalone undefined maps @@ -985,11 +998,41 @@ export function runtimeOptionalReceiverRead( loc, }; } + // An array hole in a slot with more than two arms fails the member + // access with Node's TypeError before the checked extraction runs. + const holeGuarded = (extracted: IrExpr): IrExpr => { + if (local.type.kind !== "union") return extracted; + const holeTag = lowerer.armTag(local.type.unionId, UNDEFINED_T); + if (holeTag < 0) return extracted; + return { + kind: "ternary", + cond: { + kind: "unionIsTag", + unionId: local.type.unionId, + tag: holeTag, + negated: false, + value: varRef(local.id, local.type, loc), + type: BOOL, + loc, + }, + then: nodeThrowExpr( + 1, + "", + runtimeOptionalReceiverMessage(expr, property), + extracted.type, + loc, + ), + else_: extracted, + type: extracted.type, + loc, + }; + }; if (narrowed.kind === "object") { const view = checkedClassAssertion(lowerer, varRef(local.id, local.type, loc), narrowed, loc); // Preserve the member-specific missing-value error on the two-arm // path below; mixed storage also needs to validate its concrete class. - if (view && (lowerer.unions.get(local.type.unionId)?.arms.length ?? 0) > 2) return view; + if (view && (lowerer.unions.get(local.type.unionId)?.arms.length ?? 0) > 2) + return holeGuarded(view); } if (narrowed.kind === "record" && lowerer.armTag(local.type.unionId, narrowed) < 0) { const hosted = hostedStorageView(lowerer, varRef(local.id, local.type, loc), narrowed, loc); @@ -1014,7 +1057,9 @@ export function runtimeOptionalReceiverRead( "a direct read from a runtime-optional capture with multiple value arms", ); } - return lowerer.checkedNarrowCall(helper, varRef(local.id, local.type, loc), narrowed, loc); + return holeGuarded( + lowerer.checkedNarrowCall(helper, varRef(local.id, local.type, loc), narrowed, loc), + ); } // A predicate can strengthen a record's fields or narrow a base class // to a subclass without changing the slot's stored value arm. Extract @@ -1029,10 +1074,7 @@ export function runtimeOptionalReceiverRead( "a runtime-optional receiver without a representable value arm", ); } - const message = - property === null - ? `${expr.text} is not a function` - : `Cannot read properties of undefined (reading '${property}')`; + const message = runtimeOptionalReceiverMessage(expr, property); return lowerer.maybeNarrow( { kind: "ternary", @@ -1061,6 +1103,14 @@ export function runtimeOptionalReceiverRead( ); } +/** Node's TypeError message for a member read (`property`) or a call + * (`property` null) through an undefined runtime-optional receiver. */ +function runtimeOptionalReceiverMessage(expr: ts.Identifier, property: string | null): string { + return property === null + ? `${expr.text} is not a function` + : `Cannot read properties of undefined (reading '${property}')`; +} + export function runtimeOptionalTrueIds(lowerer: Lowerer, node: ts.Expression): IrLocal[] { return runtimeOptionalGuardIds(lowerer, node, true); } @@ -1487,6 +1537,10 @@ export function lowerAsExpression( // reach it (assertion-identity.ts). if (extractionCopiesReference(lowerer, target) && assertsGlobalObject(lowerer, expr)) return inner; + // `value as Iterable`: the value's own iterator, stepped lazily with + // each element checked against T (the generator arm's adapter). + const iterable = iterableSlotValue(lowerer, inner, target); + if (iterable) return iterable; if ( target.kind === "void" || !canDynCheckTo( diff --git a/packages/compiler/src/frontend/lowering/expressions/object-literals.ts b/packages/compiler/src/frontend/lowering/expressions/object-literals.ts index 565db0cd8..4d04be30a 100644 --- a/packages/compiler/src/frontend/lowering/expressions/object-literals.ts +++ b/packages/compiler/src/frontend/lowering/expressions/object-literals.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "../stable-names.js"; import { dateJsonType, isDateJsonSource } from "../builtins/dates.js"; import { dynUndefinedExpr, numLit, strLit, varRef } from "../../../ir/build.js"; import { pathModuleValue } from "../lower-builtin-values.js"; @@ -35,6 +36,7 @@ import { tryLowerExpression } from "./try-lower-expression.js"; import { fenceSymbolFieldCopy } from "../symbol-fields.js"; import { planUnionRetag } from "../union-retag.js"; import { jsHoldsDynObject, runtimeOptionalStorageOperand } from "../lower-exprs.js"; +import { builtinGlobalValue } from "./property-access.js"; /** `{ a: 1, b: "x" }` → recordLit. The record type comes from the * contextual type when tsc has one (annotated declarations, arguments, @@ -393,9 +395,11 @@ export function lowerDynObjectLiteral( const lowerValue = (): IrExpr => ts.isMethodDeclaration(prop) ? lowerer.lowerLambda(prop, true) - : !boxValue && ts.isObjectLiteralExpression(valueExpr) - ? lowerer.lowerExprExpecting(valueExpr, DYN) - : lowerer.lowerExpr(valueExpr as ts.Expression); + : ts.isShorthandPropertyAssignment(prop) && shorthandBuiltinValue(lowerer, prop) + ? shorthandBuiltinValue(lowerer, prop)! + : !boxValue && ts.isObjectLiteralExpression(valueExpr) + ? lowerer.lowerExprExpecting(valueExpr, DYN) + : lowerer.lowerExpr(valueExpr as ts.Expression); raw = fenceClosureProbe(lowerer, valueExpr, undefined, lowerValue) ?? lowerValue(); } catch (err) { // A PURE member read a JS file cannot lower (a namespace object @@ -406,7 +410,7 @@ export function lowerDynObjectLiteral( if (!(err instanceof PoisonError) || !pureMember) throw err; const fence = lowerer.deferToRuntimeFence(propDiagsBefore, prop, { kind: "closure", - name: () => `%fn${lowerer.lambdaCounter++}_dynfence`, + name: () => lowerer.closureName(loc, "_dynfence"), returnType: VOID, type: { kind: "func", params: [], ret: VOID }, }); @@ -461,7 +465,7 @@ export function lowerDynObjectLiteral( if (!(err instanceof PoisonError)) throw err; const fence = lowerer.deferToRuntimeFence(convDiagsBefore, prop, { kind: "closure", - name: () => `%fn${lowerer.lambdaCounter++}_dynfence`, + name: () => lowerer.closureName(loc, "_dynfence"), returnType: VOID, type: { kind: "func", params: [], ret: VOID }, }); @@ -795,8 +799,25 @@ export function lowerObjectLiteral( expr: ts.ObjectLiteralExpression, expected?: IrType & { kind: "record" }, ): IrExpr { + // A spread of an untyped (`any`) source into a typed slot: TypeScript + // types such a literal `any`, and the copy holds whatever own properties + // the source has at runtime. Build it as a checked-dynamic object, then + // check it into the expected record like any other `any` value assigned + // to that slot. + if ( + expected && + !isJsSourceFile(ts.getSourceFileOfNode(expr)) && + expr.properties.nodes.some( + (prop) => + ts.isSpreadAssignment(prop) && + (lowerer.typeOf(prop.expression).flags & ts.TypeFlags.Any) !== 0, + ) + ) { + return lowerer.coerceToExpected(lowerDynObjectLiteral(lowerer, expr), expected); + } // Unannotated JavaScript accumulator fields have no element contract. // Preserve their checked arrays instead of assigning never[] a numeric ABI. + // An empty object field is a map the program adds keys to. if ( !expected && isJsSourceFile(ts.getSourceFileOfNode(expr)) && @@ -805,6 +826,8 @@ export function lowerObjectLiteral( ts.isPropertyAssignment(prop) && ((ts.isArrayLiteralExpression(prop.initializer) && prop.initializer.elements.nodes.length === 0) || + (ts.isObjectLiteralExpression(prop.initializer) && + prop.initializer.properties.nodes.length === 0) || neverTaintedJsType(lowerer, prop.initializer, lowerer.typeOf(prop.initializer))), ) ) { @@ -926,11 +949,11 @@ export function lowerObjectLiteral( // spread's own position (any position: they introduce one fresh // name, collision-fenced below). Everything else stays fenced. const cs = conditionalSpreadOf(prop.expression) ?? andSpreadOf(lowerer, prop.expression); - if (cs === "unsupported" || (cs && cs.props.length !== 1)) { + if (cs === "unsupported" && conditionalRecordSpreadOf(lowerer, prop.expression) === null) { lowerer.unsupported( "SC1090", prop, - "conditional spreads beyond `...(c ? { field: v } : {})` (exactly one property against an empty arm — spell other shapes as optional fields)", + "conditional spreads beyond `...(c ? { field: v } : {})` and `...(c ? record : {})` (one arm must be empty — spell other shapes as optional fields)", ); } // Spread ORDER is fenced in the field-by-field desugar below, not @@ -1714,64 +1737,71 @@ export function lowerObjectLiteral( if (ts.isSpreadAssignment(prop)) { const cs = conditionalSpreadOf(prop.expression) ?? andSpreadOf(lowerer, prop.expression); if (cs && cs !== "unsupported") { - // `...(c ? { k: v } : {})` — ONE conditional field at the - // spread's own position: cond evaluates exactly once, `v` only - // when the non-empty arm is taken (ternary arms are lazy), and - // the empty arm holds the interned undefined arm — exactly the - // omitted-optional-field representation, which is also why the - // target field must be optional (tsc types the idiom that way). - const csProp = cs.props[0]!; // single-prop-checked in the fence pass - const name = csProp.name.text; - const fieldType = fieldTypes.get(name); - if (!fieldType) { - if (shape.indexValue) { + // `...(c ? { k: v } : {})` — one conditional field per carried + // property at the spread's own position: cond evaluates exactly + // once (into a hidden local when several fields test it), each + // `v` only when the non-empty arm is taken (ternary arms are + // lazy), in property order, and the empty arm holds the interned + // undefined arm — exactly the omitted-optional-field + // representation, which is also why the target fields must be + // optional (tsc types the idiom that way). + let cond: IrExpr | null = null; + for (const csProp of cs.props) { + const name = csProp.name.text; + const fieldType = fieldTypes.get(name); + if (!fieldType) { + if (shape.indexValue) { + lowerer.unsupported( + "SC1090", + prop, + "conditional spreads into index-signature keys (overflow entries model presence — write the key in an if statement instead)", + ); + } + shapeMismatch(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", prop, - "conditional spreads into index-signature keys (overflow entries model presence — write the key in an if statement instead)", + `conditional spreads onto the required field '${name}' (the empty arm leaves it undefined — declare the field optional)`, ); } - shapeMismatch(prop); + if (fields.some((f) => f.name === name)) { + lowerer.unsupported( + "SC1090", + prop, + `conditional spread of '${name}' over an earlier '${name}' (the desugar keeps one entry per name — restructure so each name has one contributor)`, + ); + } + if (cond === null) { + cond = lowerer.lowerCondition(cs.cond); + if (cs.props.length > 1) cond = capture(cond); + } + const valueNode = ts.isPropertyAssignment(csProp) ? csProp.initializer : csProp; + let v = ts.isPropertyAssignment(csProp) + ? lowerer.lowerExpr(csProp.initializer) + : lowerer.lowerShorthandValue(csProp); + v = lowerer.coerceInto(valueNode, v, fieldType); + if (!typeEquals(v.type, fieldType)) lowerer.badType(valueNode, lowerer.typeOf(valueNode)); + conditionalNames.add(name); + orderSegments.push({ kind: "key", name, definite: false }); + fields.push({ + name, + value: { + kind: "ternary", + cond, + then: cs.whenTrue ? v : absent, + else_: cs.whenTrue ? absent : v, + type: fieldType, + loc: 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", - prop, - `conditional spreads onto the required field '${name}' (the empty arm leaves it undefined — declare the field optional)`, - ); - } - if (fields.some((f) => f.name === name)) { - lowerer.unsupported( - "SC1090", - prop, - `conditional spread of '${name}' over an earlier '${name}' (the desugar keeps one entry per name — restructure so each name has one contributor)`, - ); - } - const cond = lowerer.lowerCondition(cs.cond); - const valueNode = ts.isPropertyAssignment(csProp) ? csProp.initializer : csProp; - let v = ts.isPropertyAssignment(csProp) - ? lowerer.lowerExpr(csProp.initializer) - : lowerer.lowerShorthandValue(csProp); - v = lowerer.coerceInto(valueNode, v, fieldType); - if (!typeEquals(v.type, fieldType)) lowerer.badType(valueNode, lowerer.typeOf(valueNode)); - conditionalNames.add(name); - orderSegments.push({ kind: "key", name, definite: false }); - fields.push({ - name, - value: { - kind: "ternary", - cond, - then: cs.whenTrue ? v : absent, - else_: cs.whenTrue ? absent : v, - type: fieldType, - loc: locOf(prop), - }, - }); continue; } // `{ ...base, ... }` — field-by-field copy of a known record @@ -1783,10 +1813,13 @@ export function lowerObjectLiteral( // overridden. Field snapshots above preserve the copy order. let srcNode: ts.Expression = prop.expression; while (ts.isParenthesizedExpression(srcNode)) srcNode = srcNode.expression; + const condRecord = conditionalRecordSpreadOf(lowerer, prop.expression); const srcLowered = capture( - prop === expr.properties.nodes[0] && leadingSpreadLowered !== null - ? leadingSpreadLowered - : lowerer.lowerExpr(srcNode), + condRecord !== null + ? lowerConditionalRecordSpread(lowerer, condRecord, locOf(prop)) + : prop === expr.properties.nodes[0] && leadingSpreadLowered !== null + ? leadingSpreadLowered + : lowerer.lowerExpr(srcNode), ); // Array callbacks can receive a record-or-undefined ABI even when // TypeScript describes a required record. Select the copy strategy @@ -2724,6 +2757,62 @@ function syntacticAndSpread( return { cond, props, whenTrue: true }; } +/** `...(c ? source : {})` (either arm order; the empty arm may also be + * `undefined` or `null`) where `source` maps to a record and is not the + * literal the field desugar handles (conditionalSpreadOf). The spread + * copies the source's fields when the source arm is taken and nothing + * otherwise, which is the copy of a `Record | undefined` spread source. */ +export function conditionalRecordSpreadOf( + lowerer: Lowerer, + expr: ts.Expression, +): { cond: ts.Expression; source: ts.Expression; whenTrue: boolean } | null { + let e: ts.Expression = expr; + while (ts.isParenthesizedExpression(e)) e = e.expression; + if (!ts.isConditionalExpression(e)) return null; + const unwrap = (a: ts.Expression): ts.Expression => { + let x = a; + while (ts.isParenthesizedExpression(x)) x = x.expression; + return x; + }; + const isEmpty = (x: ts.Expression): boolean => + (ts.isObjectLiteralExpression(x) && x.properties.nodes.length === 0) || + x.kind === ts.SyntaxKind.NullKeyword || + (ts.isIdentifier(x) && + x.text === "undefined" && + (lowerer.typeOf(x).flags & ts.TypeFlags.Undefined) !== 0); + const whenTrue = unwrap(e.whenTrue); + const whenFalse = unwrap(e.whenFalse); + const sourceIsTrue = isEmpty(whenFalse) && !isEmpty(whenTrue); + if (!sourceIsTrue && !(isEmpty(whenTrue) && !isEmpty(whenFalse))) return null; + const source = sourceIsTrue ? whenTrue : whenFalse; + if (lowerer.mapTypeOf(lowerer.typeOf(source))?.kind !== "record") return null; + return { cond: e.condition, source, whenTrue: sourceIsTrue }; +} + +/** The spread source of a conditionalRecordSpreadOf match: `c ? source : + * undefined` as a `Record | undefined` value (cond first, the source only + * when its arm is taken). */ +function lowerConditionalRecordSpread( + lowerer: Lowerer, + spread: { cond: ts.Expression; source: ts.Expression; whenTrue: boolean }, + loc: SrcLoc, +): IrExpr { + const cond = lowerer.lowerCondition(spread.cond); + const source = lowerer.lowerExpr(spread.source); + if (source.type.kind !== "record") lowerer.badType(spread.source, lowerer.typeOf(spread.source)); + const type = lowerer.withUndefinedArm(source.type); + const present = lowerer.coerceToExpected(source, type); + const absent = lowerer.wrappedUndefined(type, loc)!; + return { + kind: "ternary", + cond, + then: spread.whenTrue ? present : absent, + else_: spread.whenTrue ? absent : present, + type, + loc, + }; +} + /** A conditional spread's carrier property: `name: value` or shorthand, * with an identifier/string-literal name. */ export type CondSpreadProp = (ts.PropertyAssignment | ts.ShorthandPropertyAssignment) & { @@ -2956,7 +3045,7 @@ function lowerDeclaredSpreadMerge( const key = `declmerge-source:${type.shapeId}:${source.shapeId}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = `%rec.declmerge.${lowerer.valueHelpers.size}`; + helper = keyedHelperName(lowerer, "%rec.declmerge", key); const sourceType = source.value.type; const destination = varRef("out.0", type, loc); const receiver = varRef("source.0", sourceType, loc); @@ -3153,6 +3242,20 @@ function lowerDeclaredSpreadMerge( /** The value of a shorthand property (`{ x }`): the binding `x` refers to. * The property name's own symbol is the PROPERTY, so resolution goes * through getShorthandAssignmentValueSymbol. */ +/** `{ TypeError }`: a stdlib global in shorthand position reads as the value + * its name reads as elsewhere (the interned constructor or function value), + * or null when the global has no such value. The shorthand's name carries + * the property's symbol, so the identifier path cannot resolve it. */ +function shorthandBuiltinValue( + lowerer: Lowerer, + prop: ts.ShorthandPropertyAssignment, +): IrExpr | null { + const symbol = lowerer.checker.getShorthandAssignmentValueSymbol(prop); + if (!symbol || !lowerer.isStdlibSymbol(symbol)) return null; + const js = isJsSourceFile(ts.getSourceFileOfNode(prop)); + return builtinGlobalValue(ts.symbolName(symbol), locOf(prop.name), js); +} + export function lowerShorthandValue( lowerer: Lowerer, prop: ts.ShorthandPropertyAssignment, @@ -3169,6 +3272,8 @@ export function lowerShorthandValue( const callable = lowerer.lowerBuiltinCallableValue(builtin, loc); if (callable) return callable; } + const builtinValue = shorthandBuiltinValue(lowerer, prop); + if (builtinValue) return builtinValue; if (symbol) { if (lowerer.ctx.selfSymbol === symbol) { return { kind: "selfRef", type: lowerer.ctx.selfType!, loc }; @@ -3239,6 +3344,9 @@ export function lowerShorthandValue( } return lowerer.classValueRef(classInfo, propName); } + // A standard-library global (`{ Date }`): the value the long form + // `{ Date: Date }` reads. + if (lowerer.isStdlibSymbol(resolved)) return lowerer.lowerExpr(propName); } lowerer.rejectUnresolvedSymbol( symbol diff --git a/packages/compiler/src/frontend/lowering/expressions/optional-chains.ts b/packages/compiler/src/frontend/lowering/expressions/optional-chains.ts index fbcecdc32..4b8c5692a 100644 --- a/packages/compiler/src/frontend/lowering/expressions/optional-chains.ts +++ b/packages/compiler/src/frontend/lowering/expressions/optional-chains.ts @@ -240,7 +240,7 @@ export function lowerOptionalChain( const receiver = lowerer.runtimeOptionalSourceValue(recvNode, loweredReceiver) ?? loweredReceiver; if (receiver.type.kind === "dyn") { if (dotNode === expr && ts.isCallExpression(expr)) { - const id = `chain.${lowerer.chainCounter++}`; + const id = lowerer.closureName(loc, "", "chain"); const callee: IrExpr = { kind: "chainRecv", id, type: DYN, loc }; const stmts: IrStmt[] = []; let guarded = receiver; @@ -298,7 +298,7 @@ export function lowerOptionalChain( ); } if (dotNode === expr && ts.isElementAccessExpression(expr)) { - const id = `chain.${lowerer.chainCounter++}`; + const id = lowerer.closureName(loc, "", "chain"); const reference: IrExpr = { kind: "chainRecv", id, type: DYN, loc }; lowerer.chainRecvByNode.set(recvNode, reference); lowerer.chainHandled.add(dotNode); @@ -331,7 +331,7 @@ export function lowerOptionalChain( dotNode === expr.expression ) { const m = dotNode.name.text; - const id = `chain.${lowerer.chainCounter++}`; + const id = lowerer.closureName(loc, "", "chain"); const recvRef: IrExpr = { kind: "chainRecv", id, type: DYN, loc: locOf(recvNode) }; lowerer.chainRecvByNode.set(recvNode, recvRef); lowerer.chainHandled.add(dotNode); @@ -358,7 +358,7 @@ export function lowerOptionalChain( } return { kind: "optChain", id, receiver, body, type: DYN, loc }; } - const id = `chain.${lowerer.chainCounter++}`; + const id = lowerer.closureName(loc, "", "chain"); const reference: IrExpr = { kind: "chainRecv", id, type: DYN, loc }; lowerer.chainRecvByNode.set(recvNode, reference); lowerer.chainHandled.add(dotNode); @@ -420,7 +420,7 @@ export function lowerOptionalChain( rest.length === 1 ? rest[0]! : { kind: "union" as const, unionId: lowerer.unions.transform(def, rest) }; - const id = `chain.${lowerer.chainCounter++}`; + const id = lowerer.closureName(loc, "", "chain"); // A single present arm binds its payload. Multiple present arms bind // the original tagged value, then retag inside the guarded body. The // nullish arms never enter that body, and each record keeps its identity. diff --git a/packages/compiler/src/frontend/lowering/expressions/property-access.ts b/packages/compiler/src/frontend/lowering/expressions/property-access.ts index f0b980da0..2e6ab981a 100644 --- a/packages/compiler/src/frontend/lowering/expressions/property-access.ts +++ b/packages/compiler/src/frontend/lowering/expressions/property-access.ts @@ -1,11 +1,16 @@ /* Property reads (`a.b`): lowerExprInner's property-access branch, intrinsic and union properties, field reads and targets, and match-group reads. */ +import { keyedHelperName } from "../stable-names.js"; import { staticallySelected } from "../static-typeof.js"; import * as ts from "../../ts7/adapter.js"; import { lowerHistogramProperty } from "../builtins/performance.js"; import { staticFunctionNameRead } from "../static-function-names.js"; import { typedArgumentsArity } from "../typed-arguments.js"; import { isThisParameter } from "../call-signatures.js"; -import { localPrivateBrandClass } from "../private-brands.js"; +import { + checkedPrivateValue, + localPrivateBrandClass, + privateNameClass, +} from "../private-brands.js"; import { type Lowerer, PoisonError, jsFuncNameOf, neverTaintedJsType, own } from "../lowerer.js"; import { ARRAY_METHODS, @@ -90,7 +95,7 @@ import { runtimeConstructorReceiver, } from "../builtins/runtime-constructor.js"; import { findGenericMethodOn, lowerStaticFieldRead } from "../lower-classes.js"; -import { lowerClassPrototypeData } from "../class-prototypes.js"; +import { isErrorPrototypeValue, lowerClassPrototypeData } from "../class-prototypes.js"; import { lowerEnumAccess } from "../lower-enums.js"; import { hasOptionalChainGuard, @@ -131,6 +136,7 @@ import { lowerProtocolPropertyRead } from "../class-protocol-dispatch.js"; import { lowerReadlineProperty } from "../builtins/readline.js"; import { lowerEventStaticProperty } from "../builtins/numbers.js"; import { lowerStreamProperty, lowerStreamStateProperty, streamSidesOf } from "../lower-stream.js"; +import { lowerValueStreamProperty } from "../builtins/hash-stream.js"; import { lowerEventObjectProperty } from "../lower-event-target.js"; import { iteratorResultValueRead } from "../lower-generators.js"; import { lowerGlobalValue } from "../lower-global-value.js"; @@ -162,6 +168,7 @@ import { lowerUnionFieldRead } from "./union-fields.js"; import { errorPropertyRead } from "../error-methods.js"; import { isSafeToDiscard, isSafeToRepeat } from "./evaluation-safety.js"; import { isZlibStreamMember, lowerZlibStreamBytesWritten } from "../builtins/compression.js"; +import { isWebCryptoReceiver } from "../builtins/crypto.js"; import { isFsStreamMember, lowerFsStreamProperty } from "../builtins/fs-streams.js"; import { keyedFieldRead } from "./keyed-field-targets.js"; import { promisePrototypeValue } from "../thenables.js"; @@ -281,6 +288,24 @@ export function lowerPropertyAccessExpr( expr: ts.PropertyAccessExpression, loc: SrcLoc, ): IrExpr { + // `value.#x` on a checked-dynamic value, or on a checked extraction of + // one: the field of the brand-checked receiver (checkedPrivateValue). + if (ts.isPrivateIdentifier(expr.name)) { + const owner = privateNameClass(lowerer, expr.name); + const field = owner?.fields.get(expr.name.text); + const probed = field ? tryLowerExpression(lowerer, expr.expression) : null; + if (owner && field && probed && checkedDynamicValue(probed)) { + const value = checkedDynamicValue(lowerer.lowerExpr(expr.expression))!; + return { + kind: "fieldGet", + obj: checkedPrivateValue(lowerer, owner, expr, value, loc), + className: owner.def.name, + field: expr.name.text, + type: field, + loc, + }; + } + } if (!expr.questionDotToken) { const navigator = lowerNavigatorMember(lowerer, expr, NODE_COMPAT_VERSION); if (navigator) return navigator; @@ -641,14 +666,20 @@ export function lowerPropertyAccessExpr( ); if (fixedArity) { // A `this` parameter is type-only: callers never pass it. - return { - kind: "numLit", - value: (fn as ts.FunctionLikeDeclaration).parameters.nodes.filter( - (p) => !isThisParameter(p), - ).length, - type: F64, - loc, - }; + const declared = (fn as ts.FunctionLikeDeclaration).parameters.nodes.filter( + (p) => !isThisParameter(p), + ).length; + const count = Math.max(declared, contextualArgumentCount(lowerer, fn) ?? 0); + // Calls through the expression's own name pass the declared count, + // calls through the wider slot pass more: no constant answers both. + if (count > declared && referencesOwnName(lowerer, fn)) { + lowerer.unsupported( + "SC1090", + expr, + "'arguments.length' in a function expression that is called both through its own name and through a function type with more parameters (the count varies per call)", + ); + } + return { kind: "numLit", value: count, type: F64, loc }; } lowerer.unsupported( "SC1090", @@ -842,8 +873,16 @@ export function lowerPropertyAccessExpr( if (runtimeOptionalClassField(lowerer, handled, expr)) return handled; return iteratorResultValueRead(lowerer, handled, expr) ?? lowerer.maybeNarrow(handled, expr); } + // `globalThis.crypto` is the WebCrypto object the bare `crypto` answers. + if ( + !expr.questionDotToken && + stdlibGlobalNameOf(lowerer, expr.expression) === "globalThis" && + stdlibGlobalNameOf(lowerer, expr) === "crypto" + ) { + return { kind: "libCall", fn: "webcrypto.object", args: [], type: DYN, loc }; + } // `globalThis.` that no lowering above claimed - // (globalThis.crypto, globalThis.SubtleCrypto, globalThis.localStorage + // (globalThis.SubtleCrypto, globalThis.localStorage // — the harness's capability-conditional knownGlobals adds): the // PROPERTY spelling of the identifier chokepoint's JS rule — a stdlib // global taken as a VALUE in a JavaScript source is the same opaque @@ -1664,6 +1703,19 @@ export function lowerIntrinsicProperty( return { kind: "libCall", fn: "dyn.arrayPrototype", args: [], type: DYN, loc: locOf(expr) }; if (lowerer.stdlibGlobalMember(expr, "Object") === "prototype") return { kind: "libCall", fn: "dyn.objectPrototype", args: [], type: DYN, loc: locOf(expr) }; + // Error.prototype as a value (`F.prototype = Object.create(Error.prototype)`) + // and Error.captureStackTrace read as a function (`if + // (Error.captureStackTrace) ...`). + if (isErrorPrototypeValue(lowerer, expr)) + return { kind: "libCall", fn: "dyn.errorPrototype", args: [], type: DYN, loc: locOf(expr) }; + if (lowerer.stdlibGlobalMember(expr, "Error") === "captureStackTrace") + return { + kind: "libCall", + fn: "dyn.errorCaptureStackTraceFunction", + args: [], + type: DYN, + loc: locOf(expr), + }; // Function.prototype as a VALUE (a prototype-chain link: // `Object.setPrototypeOf(F.prototype, Function.prototype)`): one // anonymous function answering undefined, length 0 — a zero-capture @@ -2783,7 +2835,7 @@ export function lowerGroupsProjection( const key = `regexgroups:${shapeId}:${groups.map((g) => `${g.name}=${g.index}`).join(",")}:${recvKey}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = `%regex.groups.${lowerer.valueHelpers.size}`; + helper = keyedHelperName(lowerer, "%regex.groups", key); lowerer.valueHelpers.set(key, helper); const body: IrStmt[] = []; const locals: IrLocal[] = [{ id: "m.0", name: "m", type: recv.type, mutable: true }]; @@ -2959,6 +3011,9 @@ export function lowerFieldRead(lowerer: Lowerer, expr: ts.PropertyAccessExpressi if ( receiverIr?.kind !== "object" && propSym && + // The WebCrypto object's generic getRandomValues reads off its + // dynamic object. + !isWebCryptoReceiver(lowerer, expr.expression) && isGenericCallableMemberType(lowerer.checker.getTypeOfSymbol(propSym), lowerer.checker) && // CLASS members keep the class-path fences (a poisoned class's own // diagnostics, the bound-method fence above). @@ -3533,6 +3588,13 @@ export function classFieldTarget( * known class instance OR a record, and the member is a field or (class * receivers) a declared accessor property. Returns the pieces of a * fieldSet/recordSet/accessor-call (minus value/kind) or null. */ +/** The checked-dynamic value `expr` reads: itself, or the value a checked + * extraction validates. Null for other expressions. */ +function checkedDynamicValue(expr: IrExpr): IrExpr | null { + if (expr.type.kind === "dyn") return expr; + return expr.kind === "dynCheck" && expr.value.type.kind === "dyn" ? expr.value : null; +} + export function fieldTarget( lowerer: Lowerer, access: ts.PropertyAccessExpression, @@ -3569,6 +3631,30 @@ export function fieldTarget( return classFieldTarget(lowerer, access.expression, ownerType, access.name.text); } } + // `value.#x = v` on a checked-dynamic value: the field of the + // brand-checked receiver (checkedPrivateValue). + if (ts.isPrivateIdentifier(access.name)) { + const owner = privateNameClass(lowerer, access.name); + const probed = owner?.fields.has(access.name.text) + ? tryLowerExpression(lowerer, access.expression) + : null; + if (owner && probed && checkedDynamicValue(probed)) { + const receiver = checkedPrivateValue( + lowerer, + owner, + access, + checkedDynamicValue(lowerer.lowerExpr(access.expression))!, + locOf(access), + ); + return classFieldTarget( + lowerer, + access.expression, + { kind: "object", className: owner.def.name }, + access.name.text, + receiver, + ); + } + } const stored = ts.isIdentifier(access.expression) ? (lowerer.peekLocal(access.expression)?.type ?? lowerer.globalOf(access.expression)?.type) : undefined; @@ -3994,6 +4080,8 @@ function lowerStreamObjectProperty( expr: ts.PropertyAccessExpression, ): IrExpr | null { if (expr.questionDotToken && !lowerer.chainHandled.has(expr)) return null; + const valueStream = lowerValueStreamProperty(lowerer, expr); + if (valueStream) return valueStream; const recvT = lowerer.mapTypeOf(lowerer.typeOf(expr.expression)); if (recvT?.kind !== "object") return null; const info = lowerer.classes.get(recvT.className); @@ -4008,10 +4096,26 @@ function lowerStreamObjectProperty( return lowerStreamProperty(lowerer, expr, info); } +/** The error constructors among GLOBAL_CONSTRUCTOR_VALUES. Their statics + * (`Error.stackTraceLimit`, `Error.captureStackTrace`) keep their own + * lowerings, so fenceBuiltinConstructorStaticRead leaves them alone. */ +const ERROR_CONSTRUCTOR_VALUES: ReadonlySet = new Set([ + "Error", + "TypeError", + "RangeError", + "SyntaxError", + "ReferenceError", + "EvalError", + "URIError", + "AggregateError", +]); + /** 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. */ + * so `o.constructor === Object` and `err.constructor === TypeError` are + * exact identity tests, and `err.constructor.name` is the constructor's + * name. */ const GLOBAL_CONSTRUCTOR_VALUES: ReadonlySet = new Set([ "Object", "Function", @@ -4022,6 +4126,8 @@ const GLOBAL_CONSTRUCTOR_VALUES: ReadonlySet = new Set([ "Promise", "WeakMap", "WeakSet", + "FinalizationRegistry", + ...ERROR_CONSTRUCTOR_VALUES, ]); /** The builtin global functions JavaScript sources read as interned @@ -4072,8 +4178,18 @@ export function builtinGlobalValue(canonical: string, loc: SrcLoc, js = false): const BUILTIN_VALUE_MEMBERS: ReadonlySet = 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 = new Set(["is", "keys", "values", "entries"]); + * match Node's (identity, the empty enumerable own-key lists, and + * extensibility: freezing, sealing and preventExtensions are fenced, so the + * values stay extensible). */ +const BUILTIN_VALUE_REFLECTION: ReadonlySet = new Set([ + "is", + "keys", + "values", + "entries", + "isExtensible", + "isFrozen", + "isSealed", +]); /** 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 @@ -4164,6 +4280,7 @@ function fenceBuiltinConstructorStaticRead( symbol !== undefined && ts.symbolName(symbol).endsWith("Constructor") && GLOBAL_CONSTRUCTOR_VALUES.has(ts.symbolName(symbol).slice(0, -"Constructor".length)) && + !ERROR_CONSTRUCTOR_VALUES.has(ts.symbolName(symbol).slice(0, -"Constructor".length)) && lowerer.isStdlibSymbol(symbol) ) lowerer.stdlibMemberFence(access); @@ -4330,3 +4447,47 @@ function lowerPromiseConstructorRead( } return null; } + +/** Whether a named function expression refers to itself by name in its + * body (a recursive call, or the function escaping under its own name). */ +function referencesOwnName(lowerer: Lowerer, fn: ts.Node): boolean { + if (!ts.isFunctionExpression(fn) || fn.name === undefined || fn.body === undefined) return false; + const self = lowerer.checker.getSymbolAtLocation(fn.name); + if (self === undefined) return false; + const name = fn.name.text; + let found = false; + ts.walkPreorder(fn.body, (node) => { + if (found) return "stop"; + if ( + ts.isIdentifier(node) && + node.text === name && + lowerer.checker.getSymbolAtLocation(node) === self + ) + found = true; + return undefined; + }); + return found; +} + +/** The argument count every caller passes a function expression whose + * value flows into one fixed-arity function type, an array method's + * callback or an annotated slot: that type's parameter count. Null when + * there is no such type or its arity varies. */ +function contextualArgumentCount(lowerer: Lowerer, fn: ts.Node): number | null { + if (!ts.isFunctionExpression(fn)) return null; + const contextual = lowerer.checker.getContextualType(fn); + if (contextual === undefined) return null; + const signatures = lowerer.checker.getCallSignatures( + lowerer.checker.getNonNullableType(contextual), + ); + if (signatures.length !== 1) return null; + const declaration = signatures[0]!.declaration; + if (declaration === undefined) return null; + let count = 0; + for (const parameter of (declaration.parameters?.nodes ?? []) as ts.ParameterDeclaration[]) { + if (isThisParameter(parameter)) continue; + if (parameter.questionToken || parameter.initializer || parameter.dotDotDotToken) return null; + count++; + } + return count; +} diff --git a/packages/compiler/src/frontend/lowering/expressions/relational.ts b/packages/compiler/src/frontend/lowering/expressions/relational.ts index 088b45cff..0eb8ae653 100644 --- a/packages/compiler/src/frontend/lowering/expressions/relational.ts +++ b/packages/compiler/src/frontend/lowering/expressions/relational.ts @@ -1,4 +1,6 @@ /* instanceof and in, including private-name and runtime-key in. */ +import { dateRootOf } from "../builtins/date-classes.js"; +import { keyedHelperName } from "../stable-names.js"; import * as ts from "../../ts7/adapter.js"; import { builtinClassInstanceOfAny, builtinClassKind } from "../builtins/builtin-class-dyn.js"; import { @@ -47,6 +49,7 @@ import { InternalCompilerError } from "../../../errors.js"; import { tryLowerExpression } from "./try-lower-expression.js"; import { isJsSourceFile, locOf } from "../../program.js"; import { checkedClassInstanceOf } from "../class-construction.js"; +import { unsupportedDiag } from "../../../diagnostics/diagnostic.js"; import { globalSymbolKey } from "./global-symbols.js"; import { foldedStringKeyOf } from "./object-literals.js"; import { NARROW_FIRST, sideEffectFreeOptionValue } from "../surfaces.js"; @@ -145,6 +148,10 @@ export function lowerInstanceOf(lowerer: Lowerer, expr: ts.BinaryExpression, loc loc, }; } + if (lowerer.isStdlibGlobal(expr.right, "FinalizationRegistry")) { + const value = lowerer.coerceInto(expr.left, lowerer.lowerExpr(expr.left), DYN); + return { kind: "libCall", fn: "finalizationRegistry.is", args: [value], type: BOOL, loc }; + } const rhsBuiltin = ts.isIdentifier(expr.right) ? lowerer.builtinImportOf(expr.right) : ts.isPropertyAccessExpression(expr.right) @@ -265,7 +272,12 @@ export function lowerInstanceOf(lowerer: Lowerer, expr: ts.BinaryExpression, loc stmts: [{ kind: "exprStmt", expr: value, loc }], result: { kind: "boolLit", - value: value.type.kind === (date ? "date" : "url"), + value: + value.type.kind === (date ? "date" : "url") || + // An instance of a class declared `extends Date`. + (date && + value.type.kind === "object" && + dateRootOf(lowerer.classes.get(value.type.className)) !== null), type: BOOL, loc, }, @@ -483,7 +495,13 @@ export function lowerInstanceOf(lowerer: Lowerer, expr: ts.BinaryExpression, loc const constructor = tryLowerExpression(lowerer, expr.right); if (constructor?.type.kind === "dyn" && isJsSourceFile(ts.getSourceFileOfNode(expr))) { const value = lowerer.coerceInto(expr.left, lowerer.lowerExpr(expr.left), DYN); - return checkedClassInstanceOf(lowerer, value, constructor, loc); + return checkedClassInstanceOf( + lowerer, + value, + constructor, + dynInstanceOfRefusal(lowerer, expr), + loc, + ); } // `this instanceof Glob` in a JavaScript constructor function: the // function's prototype against the value's prototype chain. @@ -565,7 +583,33 @@ export function lowerInstanceOf(lowerer: Lowerer, expr: ts.BinaryExpression, loc loc, }; }; - const test = caughtInstanceOf(target); + let test = caughtInstanceOf(target); + // A thrown checked-dynamic object whose prototype chain reaches + // Error.prototype (an ES5 constructor function inheriting from it). + if (target.def.name === "%Error" && lowerer.errorPrototypeValues) { + const value = varRef(caughtLocal.id, CAUGHT, loc); + test = { + kind: "logical", + op: "||", + left: test, + right: { + kind: "logical", + op: "&&", + left: { kind: "caughtTest", value, test: "dynamic", type: BOOL, loc }, + right: { + kind: "libCall", + fn: "dyn.inheritsErrorPrototype", + args: [{ kind: "caughtToDyn", value, type: DYN, loc }], + type: BOOL, + loc, + }, + type: BOOL, + loc, + }, + type: BOOL, + loc, + }; + } return duplex ? { kind: "logical", op: "||", left: test, right: caughtInstanceOf(duplex), type: BOOL, loc } : test; @@ -590,9 +634,35 @@ export function lowerInstanceOf(lowerer: Lowerer, expr: ts.BinaryExpression, loc ) { return classInstanceOf(lowerer, left, target, loc); } - if (left.type.kind === "dyn" && target.def.name === "%Error") { + if (left.type.kind === "dyn" && target.def.name === "%Error" && !lowerer.errorPrototypeValues) { return { kind: "dynTest", test: "error", value: left, type: BOOL, loc }; } + // An object whose prototype chain reaches Error.prototype (an ES5 + // constructor function inheriting from it) is an instance as well. + if (left.type.kind === "dyn" && target.def.name === "%Error") { + const local = lowerer.declareHiddenLocal("%instanceofValue", DYN); + const value = varRef(local.id, DYN, loc); + return { + kind: "seqExpr", + stmts: [{ kind: "varDecl", localId: local.id, init: left, loc }], + result: { + kind: "logical", + op: "||", + left: { kind: "dynTest", test: "error", value, type: BOOL, loc }, + right: { + kind: "libCall", + fn: "dyn.inheritsErrorPrototype", + args: [value], + type: BOOL, + loc, + }, + type: BOOL, + loc, + }, + type: BOOL, + loc, + }; + } // `u instanceof TypeError` (and the other BUILTIN error classes) on a // dyn value: the from_error cache holds the checked-dynamic tree↔error identity edge, // so the runtime resolves the encoding back to its error and asks the @@ -647,7 +717,7 @@ export function lowerInstanceOf(lowerer: Lowerer, expr: ts.BinaryExpression, loc const key = `instanceof.union:${unionId}:${target.def.name}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = `%instanceof.union.${lowerer.valueHelpers.size}`; + helper = keyedHelperName(lowerer, "%instanceof.union", key); lowerer.valueHelpers.set(key, helper); const value: IrExpr = { kind: "varRef", localId: "value.0", type: left.type, loc }; const body: IrStmt[] = []; @@ -1434,6 +1504,32 @@ export function lowerInExpression( ); if (helper) recv = { kind: "call", callee: helper, args: [recv], type: siteType, loc }; } + // A builtin class held as a brand record (TextEncoder, TextDecoder: only + // `%`-prefixed internal fields): its members are the class's prototype + // members, which the standard library declares, so `"encodeInto" in + // encoder` answers from the checker's type, plus Object.prototype's keys. + // The receiver evaluates for its effects. + if (recv.type.kind === "record") { + const shape = lowerer.shapes.get(recv.type.shapeId); + if (shape && shape.fields.length > 0 && shape.fields.every((f) => f.name.startsWith("%"))) { + const declared = + lowerer.checker.getPropertyOfType(lowerer.typeOf(expr.right), key) !== undefined; + const answer: IrExpr = { + kind: "boolLit", + value: declared || OBJECT_PROTOTYPE_KEYS.has(key), + type: BOOL, + loc, + }; + if (recv.kind === "varRef") return answer; + return { + kind: "seqExpr", + stmts: [{ kind: "exprStmt", expr: recv, loc }], + result: answer, + type: BOOL, + loc, + }; + } + } // Error-rooted receivers (builtin or user subclass — the isErrnoException // predicate's `err instanceof Error && "code" in err` shape): `code` // answers from the runtime error's code slot (stamped by fs/system/ @@ -1847,7 +1943,7 @@ function lowerRuntimeKeyIn( const hkey = `haskey:${recvT.shapeId}`; let helper = lowerer.valueHelpers.get(hkey); if (!helper) { - helper = `%rec.haskey.${lowerer.valueHelpers.size}`; + helper = keyedHelperName(lowerer, "%rec.haskey", hkey); lowerer.valueHelpers.set(hkey, helper); const recT: IrType = { kind: "record", shapeId: recvT.shapeId }; @@ -1941,3 +2037,25 @@ function lowerRuntimeKeyIn( } return { kind: "call", callee: helper, args: [keyIr, recv], type: BOOL, loc }; } + +/** Standard-library constructors the untyped instanceof helper has no + * instance test for: an untyped `x instanceof Object` always refuses. */ +const DYN_INSTANCEOF_REFUSED: ReadonlySet = new Set(["Object", "Function"]); + +/** The SC1090 message `x instanceof C` throws, with the site's position, + * when `C` is a runtime constructor with no instance test. A right-hand + * side that names one of DYN_INSTANCEOF_REFUSED always reaches that + * refusal, so the site is listed with the runtime fences. */ +function dynInstanceOfRefusal(lowerer: Lowerer, expr: ts.BinaryExpression): string { + const diag = unsupportedDiag("SC1090", locOf(expr), "instanceof against this native constructor"); + const symbol = lowerer.checker.getSymbolAtLocation(expr.right); + if ( + symbol !== undefined && + lowerer.isStdlibSymbol(symbol) && + DYN_INSTANCEOF_REFUSED.has(ts.symbolName(symbol)) + ) + lowerer.runtimeFences.push(diag); + const sf = ts.getSourceFileOfNode(expr); + const line = ts.getLineAndCharacterOfPosition(sf, diag.loc.start).line + 1; + return `${diag.message} [${diag.code} at ${diag.loc.file}:${line}]`; +} diff --git a/packages/compiler/src/frontend/lowering/expressions/updates.ts b/packages/compiler/src/frontend/lowering/expressions/updates.ts index 13baca7d2..128093dad 100644 --- a/packages/compiler/src/frontend/lowering/expressions/updates.ts +++ b/packages/compiler/src/frontend/lowering/expressions/updates.ts @@ -23,6 +23,7 @@ import { type IrExpr, type IrStmt, type IrType, + isUnitType, STRING, type SrcLoc, UNDEFINED_T, @@ -100,6 +101,27 @@ function writeFree(expr: IrExpr): boolean { } } +/** A union unary `+`/`-` converts with the runtime's ToNumber: one with an + * arm other than numbers and units (`string | undefined`). Number and unit + * unions keep their native lowering. */ +function coercedUnion(lowerer: Lowerer, type: IrType): boolean { + if (type.kind !== "union" || !lowerer.dynConvertible(type)) return false; + const arms = lowerer.unions.get(type.unionId)?.arms ?? []; + return arms.some((arm) => arm.kind !== "f64" && !isUnitType(arm)); +} + +/** ToNumber of a boolean: 1 for true, 0 for false. */ +function booleanToNumber(value: IrExpr, loc: SrcLoc): IrExpr { + return { + kind: "ternary", + cond: value, + then: { kind: "numLit", value: 1, type: F64, loc }, + else_: { kind: "numLit", value: 0, type: F64, loc }, + type: F64, + loc, + }; +} + export function lowerPrefixUnary(lowerer: Lowerer, expr: ts.PrefixUnaryExpression): IrExpr { const loc = locOf(expr); switch (expr.operator) { @@ -111,9 +133,25 @@ export function lowerPrefixUnary(lowerer: Lowerer, expr: ts.PrefixUnaryExpressio } // Match the checked numeric boundary used by JS binary arithmetic. const operand = - raw.type.kind === "dyn" && isJsSourceFile(ts.getSourceFileOfNode(expr)) - ? { kind: "dynCheck" as const, value: raw, type: F64, loc } - : lowerOptionalNumber(lowerer, raw, loc, expr.operand); + raw.type.kind === "bool" + ? booleanToNumber(raw, loc) + : coercedUnion(lowerer, raw.type) + ? ({ + kind: "libCall", + fn: "dyn.toNumberCoerce", + args: [{ kind: "dynFrom", value: raw, type: DYN, loc }], + type: F64, + loc, + } satisfies IrExpr) + : raw.type.kind === "dyn" && isJsSourceFile(ts.getSourceFileOfNode(expr)) + ? ({ + kind: "libCall", + fn: "dyn.toNumberCoerce", + args: [raw], + type: F64, + loc, + } satisfies IrExpr) + : lowerOptionalNumber(lowerer, raw, loc, expr.operand); if (operand.type.kind !== "f64") operatorUnsupported(lowerer, expr, "-", [raw.type]); if (operand.kind === "numLit") return { ...operand, value: -operand.value, loc }; return { kind: "unary", op: "-", operand, type: F64, loc }; @@ -123,6 +161,12 @@ export function lowerPrefixUnary(lowerer: Lowerer, expr: ts.PrefixUnaryExpressio if (raw.type.kind === "dyn") { return { kind: "libCall", fn: "dyn.toNumberCoerce", args: [raw], type: F64, loc }; } + // A union of primitives (`+match[1]` over `string | undefined`): ToNumber + // over the boxed value, as for a checked-dynamic operand. + if (coercedUnion(lowerer, raw.type)) { + const boxed: IrExpr = { kind: "dynFrom", value: raw, type: DYN, loc }; + return { kind: "libCall", fn: "dyn.toNumberCoerce", args: [boxed], type: F64, loc }; + } // Unary + is ToNumber; on an already-number operand it's identity, // and a STRING operand runs the runtime's ECMA-exact StringToNumber // (num.fromString — Number(aString)'s lowering, scr_string.c). @@ -130,6 +174,7 @@ export function lowerPrefixUnary(lowerer: Lowerer, expr: ts.PrefixUnaryExpressio if (raw.type.kind === "string") { return { kind: "libCall", fn: "num.fromString", args: [raw], type: F64, loc }; } + if (raw.type.kind === "bool") return booleanToNumber(raw, loc); const classNumber = classToNumberConversion(lowerer, raw, expr.operand, "unary plus"); if (classNumber) return classNumber; const operand = lowerOptionalNumber(lowerer, raw, loc, expr.operand); @@ -321,9 +366,13 @@ export function lowerIncDec( !isJsSourceFile(ts.getSourceFileOfNode(expr)) && raw.type.kind === "dyn" && lowerer.mapTypeOf(lowerer.typeOf(access))?.kind === "f64"; + // A private name is the field of its class (fieldTarget). + const privateName = + ts.isPropertyAccessExpression(access) && ts.isPrivateIdentifier(access.name); if ( (isJsSourceFile(ts.getSourceFileOfNode(expr)) || checkedNumber) && - raw.type.kind === "dyn" + raw.type.kind === "dyn" && + !privateName ) { const receiver = save(raw, "%incrementReceiver"); const key = save( @@ -814,7 +863,8 @@ export function lowerFieldCompoundValue( probed?.type.kind === "classval" ? lowerer.classes.get(probed.type.className) : undefined; if (probed && staticClass && hasRuntimeStatics(staticClass)) probed = lowerer.coerceToExpected(probed, DYN); - if (probed?.type.kind === "dyn") { + // A private name is the field of its class (fieldTarget). + if (probed?.type.kind === "dyn" && !ts.isPrivateIdentifier(access.name)) { const receiver = save(probed, "%compoundReceiver"); const key: IrExpr = { kind: "strLit", diff --git a/packages/compiler/src/frontend/lowering/function-returns.ts b/packages/compiler/src/frontend/lowering/function-returns.ts index 9500d6d2d..5ede3efe3 100644 --- a/packages/compiler/src/frontend/lowering/function-returns.ts +++ b/packages/compiler/src/frontend/lowering/function-returns.ts @@ -1,3 +1,4 @@ +import { iterableGeneratorArm } from "./iterable-values.js"; import { mapAsyncGeneratorAnnotation } from "../type-mapper.js"; import { dynUndefinedExpr } from "../../ir/build.js"; import * as ts from "../ts7/adapter.js"; @@ -147,6 +148,9 @@ export function declaredReturnType( // (`.action(() => { throw ... })`). `never` VALUES stay unmapped. if (retTsType.flags & ts.TypeFlags.Never) return VOID; let mappedReturn = lowerer.mapTypeOf(retTsType); + // A generator declared to return Iterable returns a generator over T. + if (mappedReturn && decl.asteriskToken) + mappedReturn = iterableGeneratorArm(lowerer, mappedReturn); if ( mappedReturn === null && decl.asteriskToken && diff --git a/packages/compiler/src/frontend/lowering/generator-dynamic-dispatch.ts b/packages/compiler/src/frontend/lowering/generator-dynamic-dispatch.ts index 3f43e5e05..db542412f 100644 --- a/packages/compiler/src/frontend/lowering/generator-dynamic-dispatch.ts +++ b/packages/compiler/src/frontend/lowering/generator-dynamic-dispatch.ts @@ -13,16 +13,20 @@ import { type IrStmt, type IrType, } from "../../ir/ir.js"; -import { everyStmtList, transformStmtList } from "../../ir/traverse.js"; +import { transformStmtList } from "../../ir/traverse.js"; import { genResultRecord } from "../type-mapper.js"; +import type { DispatchSites } from "./dispatch-sites.js"; import type { Lowerer } from "./lowerer.js"; type GeneratorType = Extract; type Invoke = Extract; type KeyGet = Extract; +/** The generator methods a dynamic call or read steps. */ +export const GENERATOR_STEP_METHODS = new Set(["next", "return", "throw"]); + /** The iterator helper methods the runtime answers on checked iterators. */ -const HELPER_METHODS = new Set([ +export const HELPER_METHODS = new Set([ "map", "filter", "take", @@ -101,6 +105,7 @@ export class GeneratorDynamicDispatch { lowerer: Lowerer, functions: readonly IrFunction[], classHelpers: ReadonlySet, + sites: DispatchSites, ): boolean { const seen = new Set(); const rewrite = new Set(); @@ -117,34 +122,14 @@ export class GeneratorDynamicDispatch { lowerer.shapes.get(type.shapeId)?.fields.forEach((field) => discover(field.type)); else if (type.kind === "union") lowerer.unions.get(type.unionId)?.arms.forEach(discover); }; - for (const fn of functions) - everyStmtList(fn.body, { - stmt: () => true, - expr: (expr) => { - if (expr.kind === "dynFrom") discover(expr.value.type); - if (expr.kind === "dynInvoke" && ["next", "return", "throw"].includes(expr.method)) - rewrite.add(fn); - // The runtime steps the values iterator helpers and destructuring - // receive. - if ( - (expr.kind === "dynInvoke" && HELPER_METHODS.has(expr.method)) || - (expr.kind === "dynKeyGet" && - expr.key.kind === "strLit" && - HELPER_METHODS.has(expr.key.value)) || - expr.kind === "dynIterN" || - (expr.kind === "libCall" && expr.fn === "dyn.destructureRest") - ) - runtimeSteps = true; - if ( - expr.kind === "dynKeyGet" && - expr.key.kind === "strLit" && - (["next", "return", "throw"].includes(expr.key.value) || - HELPER_METHODS.has(expr.key.value)) - ) - rewrite.add(fn); - return true; - }, - }); + for (const fn of functions) { + const found = sites.of(fn); + found.values.forEach(discover); + // The runtime steps the values iterator helpers and destructuring + // receive. + if (found.runtimeSteps) runtimeSteps = true; + if (found.generatorSteps) rewrite.add(fn); + } let changed = false; for (const fn of functions) { // The generator helper's fallback may itself dispatch native classes. @@ -159,7 +144,7 @@ export class GeneratorDynamicDispatch { if ( expr.kind === "dynKeyGet" && expr.key.kind === "strLit" && - (["next", "return", "throw"].includes(expr.key.value) || + (GENERATOR_STEP_METHODS.has(expr.key.value) || (HELPER_METHODS.has(expr.key.value) && this.generators.size > 0)) ) { const method = expr.key.value; @@ -173,8 +158,7 @@ export class GeneratorDynamicDispatch { loc: expr.loc, }; } - if (expr.kind !== "dynInvoke" || !["next", "return", "throw"].includes(expr.method)) - return expr; + if (expr.kind !== "dynInvoke" || !GENERATOR_STEP_METHODS.has(expr.method)) return expr; const key = JSON.stringify([expr.method, expr.args.length, expr.calleeName]); let dispatch = this.dispatches.get(key); if (!dispatch) { diff --git a/packages/compiler/src/frontend/lowering/generic-functions.ts b/packages/compiler/src/frontend/lowering/generic-functions.ts index abcd5a584..e27ab7f5f 100644 --- a/packages/compiler/src/frontend/lowering/generic-functions.ts +++ b/packages/compiler/src/frontend/lowering/generic-functions.ts @@ -1,17 +1,24 @@ import { staticNameBindings } from "./static-function-names.js"; +import { positionTag } from "./structural-positions.js"; +import { keyedHelperName } from "./stable-names.js"; import * as ts from "../ts7/adapter.js"; import { bodyReadsArguments } from "../arguments-usage.js"; import type { Lowerer } from "./lowerer.js"; import { + BOOL, DYN, type IrExpr, type IrFunction, type IrParam, type IrStmt, type IrType, + type SrcLoc, + STRING, + VOID, isUnitType, typeEquals, } from "../../ir/ir.js"; +import { helperLoc, nodeThrowExpr } from "../../ir/build.js"; import { isJsSourceFile, locOf } from "../program.js"; import { typeKey } from "../type-mapper.js"; import { functionCanReturnUndefined } from "../function-completion.js"; @@ -22,7 +29,7 @@ import { nsPathPrefix } from "./lower-namespaces.js"; import { declSymbolOf } from "./lower-modules.js"; import { npmStaticPackageOfPath } from "../npm-static.js"; import { rejectStaticThis } from "./static-this.js"; -import { jsBindingHasOpenWrites } from "./lower-stmts.js"; +import { isVarDeclared, jsBindingHasOpenWrites } from "./lower-stmts.js"; import { type ParamShape, paramShapes, @@ -91,6 +98,17 @@ export interface GenericFnInfo { * declaration makes a new function object in JavaScript, while the * compiled instances are shared module functions, so only calls lower. */ functionScoped?: true; + /** The declaration of a generic arrow/function-expression binding. */ + bindingDecl?: ts.VariableDeclaration; + /** A module-scope binding that code can use before its declaration + * runs: the BOOL global its declaration sets, and whether it is a + * `let`/`const` (a temporal dead zone) or a `var` (undefined). */ + presence?: { flagId: string; lexical: boolean }; + /** genericValueForwarder's lifted functions, by instance name. */ + valueForwarders?: Map; + /** runsAfterDeclaration's answers for the function declarations whose + * calls it placed. */ + ordering?: Map; /** IMPLICIT-ANY monomorphization (npm-static JS): parallel to * decl.parameters — the param's own symbol when the slot is a BINDABLE * implicit-any parameter (untyped, identifier-named, never written in @@ -129,6 +147,10 @@ export interface GenericInstance { tsBindings?: Map; /** Rendered type arguments ("") for diagnostics. */ typeArgsText: string; + /** A factory returning one of its local classes through a declared + * constructor type: that type (by id) and the class value it maps to + * while the body lowers (Lowerer.instanceResultClass). */ + resultClass?: { declared: number; value: IrType }; /** Implicit instances only: param symbol → the call site's (widened) * checker type, consulted by the Lowerer's typeOf while this instance's * body lowers (the implicit twin of `bindings`). */ @@ -229,7 +251,10 @@ export function collectGenericSignature(lowerer: Lowerer, decl: ts.FunctionDecla lowerer.genericFnsBySymbol.set(symbol, { decl, baseName: nameText, - qualifiedName: lowerer.qualify(ts.getSourceFileOfNode(decl), nsPathPrefix(decl) + nameText), + qualifiedName: lowerer.qualify( + ts.getSourceFileOfNode(decl), + nsPathPrefix(lowerer, decl) + nameText, + ), typeParams, instances: new Map(), }); @@ -257,7 +282,14 @@ export function lowerGenericCall( ? implicitCallInstance(lowerer, expr, info) : genericCallInstance(lowerer, expr, info); const args = lowerer.completeArgs(expr.arguments.nodes, instance.params, loc, expr); - return { kind: "call", callee: instance.name, args, type: instance.returnType, loc }; + const call: IrExpr & { kind: "call" } = { + kind: "call", + callee: instance.name, + args, + type: instance.returnType, + loc, + }; + return guardEarlyBindingCall(lowerer, info, expr, call); } /** The instance a CALL of a generic function-like names: resolved @@ -468,7 +500,8 @@ function localClassResultInstance( params: ParamShape[], retTs: ts.Type, ): GenericInstance | null { - if (!localClassOfResult(lowerer, info, retTs)) return null; + const resultClass = localClassOfResult(lowerer, info, retTs); + if (!resultClass) return null; const tsBindings = new Map(); const bindings = lowerer.inferTypeParamBindings(expr, info, rsig, tsBindings); const bindingKey = info.typeParams @@ -483,12 +516,37 @@ function localClassResultInstance( tsBindings, }); if (inst.returnType !== pending) return inst; - const returnType = withInstanceScope(lowerer, info, inst, () => lowerer.mapTypeOf(retTs)); + // A result typed by a declared constructor type rather than the class + // (`Struct`) is the class value of the local class the body returns. + const declaredResult = info.decl.type + ? lowerer.checker.getTypeFromTypeNode(info.decl.type) + : undefined; + const viaConstructorType = retTs.getSymbol()?.valueDeclaration !== resultClass; + const returnType = withInstanceScope(lowerer, info, inst, () => { + if (!viaConstructorType) return lowerer.mapTypeOf(retTs); + // The local class's own constructor type: a class expression's type is + // its constructor type, named or not (`return class { ... } as Struct`). + const classSymbol = + !ts.isClassExpression(resultClass) && resultClass.name + ? lowerer.checker.getSymbolAtLocation(resultClass.name) + : undefined; + const classType = ts.isClassExpression(resultClass) + ? lowerer.checker.getTypeAtLocation(resultClass) + : classSymbol + ? lowerer.checker.getTypeOfSymbol(classSymbol) + : undefined; + return classType ? lowerer.mapTypeOf(classType) : null; + }); if (!returnType) { fenceGenericSignatureResult(lowerer, expr, retTs); lowerer.badType(expr, retTs); } inst.returnType = returnType; + if (viaConstructorType && returnType.kind === "classval") { + if (declaredResult) inst.resultClass = { declared: declaredResult.id, value: returnType }; + if (lowerer.typeParamBindings === null) lowerer.localClassValueTypes.set(retTs.id, returnType); + return inst; + } // Values of the class outside the factory (`const b = new B()`, `b.read()`) // carry the instantiated checker type; record which class it names. A // call inside another generic instance can have a type that depends on @@ -563,12 +621,102 @@ function localClassOfResult( type: ts.Type, ): ts.ClassLikeDeclaration | null { const symbol = type.getSymbol(); - if (!symbol || !(symbol.flags & ts.SymbolFlags.Class)) return null; - const decl = symbol.valueDeclaration; - if (!decl || !(ts.isClassExpression(decl) || ts.isClassDeclaration(decl))) return null; - for (let parent = decl.parent; parent && !ts.isSourceFile(parent); parent = parent.parent) - if (parent === info.decl) return decl; - return null; + const decl = symbol && symbol.flags & ts.SymbolFlags.Class ? symbol.valueDeclaration : undefined; + if (decl && (ts.isClassExpression(decl) || ts.isClassDeclaration(decl))) + return declaredInside(decl, info.decl) ? decl : null; + // A result typed by a constructor type (`Struct`, `new () => S`) whose + // every return gives back the one local class, through parentheses and + // assertions (`return Base as Struct`). + // A mixin (a class extending one of the function's parameters) keeps the + // mixin instantiation, which keys on the argument class. + if (lowerer.checker.getConstructSignatures(type).length === 0) return null; + const returned = returnedLocalClass(lowerer, info); + return returned && !extendsParameter(lowerer, returned, info) ? returned : null; +} + +function extendsParameter( + lowerer: Lowerer, + decl: ts.ClassLikeDeclaration, + info: GenericFnInfo, +): boolean { + const params = new Set(); + const fn = info.decl as { parameters?: { nodes: readonly ts.ParameterDeclaration[] } }; + for (const param of fn.parameters?.nodes ?? []) { + const symbol = ts.isIdentifier(param.name) + ? lowerer.checker.getSymbolAtLocation(param.name) + : undefined; + if (symbol !== undefined) params.add(symbol); + } + for (const clause of decl.heritageClauses?.nodes ?? []) + for (const base of clause.types.nodes) { + const symbol = ts.isIdentifier(base.expression) + ? lowerer.checker.getSymbolAtLocation(base.expression) + : undefined; + if (symbol !== undefined && params.has(symbol)) return true; + } + return false; +} + +function declaredInside(node: ts.Node, owner: ts.Node): boolean { + for (let parent = node.parent; parent && !ts.isSourceFile(parent); parent = parent.parent) + if (parent === owner) return true; + return false; +} + +/** The local class every return of `info`'s body gives back, or null when a + * return gives anything else (or nothing). Nested functions and classes keep + * their own returns. */ +function returnedLocalClass(lowerer: Lowerer, info: GenericFnInfo): ts.ClassLikeDeclaration | null { + const fn = info.decl as ts.Node & { body?: ts.Node }; + const body = fn.body; + if (!body) return null; + const classOf = (node: ts.Expression): ts.ClassLikeDeclaration | null => { + let expr = node; + while ( + ts.isParenthesizedExpression(expr) || + ts.isAsExpression(expr) || + ts.isSatisfiesExpression(expr) || + ts.isNonNullExpression(expr) + ) + expr = expr.expression; + if (ts.isClassExpression(expr)) return declaredInside(expr, info.decl) ? expr : null; + if (!ts.isIdentifier(expr)) return null; + const declaration = lowerer.checker.getSymbolAtLocation(expr)?.valueDeclaration; + if (!declaration || !declaredInside(declaration, info.decl)) return null; + if (ts.isClassDeclaration(declaration)) return declaration; + // A `const` bound to a class expression (`const C = class { ... }; return C`). + if ( + ts.isVariableDeclaration(declaration) && + ts.getCombinedNodeFlags(declaration) & ts.NodeFlags.Const && + declaration.initializer + ) { + let init: ts.Expression = declaration.initializer; + while (ts.isParenthesizedExpression(init)) init = init.expression; + if (ts.isClassExpression(init)) return init; + } + return null; + }; + if (!ts.isBlock(body)) return classOf(body as ts.Expression); + let found: ts.ClassLikeDeclaration | null = null; + let valid = true; + const visit = (node: ts.Node): void => { + if ( + !valid || + ts.isFunctionLike(node) || + ts.isClassDeclaration(node) || + ts.isClassExpression(node) + ) + return; + if (ts.isReturnStatement(node)) { + const returned = node.expression ? classOf(node.expression) : null; + if (!returned || (found !== null && found !== returned)) valid = false; + else found = returned; + return; + } + ts.forEachChild(node, visit); + }; + ts.forEachChild(body, visit); + return valid ? found : null; } /** Runs `fn` under an instance's type bindings and local-class names, as @@ -583,14 +731,17 @@ function withInstanceScope( const prevTsBindings = lowerer.typeParamTsBindings; const previousPath = lowerer.genericInstantiationPath; const prevContext = lowerer.instantiationContext; + const prevResultClass = lowerer.instanceResultClass; lowerer.typeParamBindings = inst.bindings; lowerer.typeParamTsBindings = inst.tsBindings ?? null; lowerer.genericInstantiationPath = inst.path; lowerer.instantiationContext = `instantiating '${info.baseName}' with ${inst.typeArgsText}`; + lowerer.instanceResultClass = inst.resultClass ?? null; lowerer.localClassInstantiations.push({ owner: info.decl, name: inst.name }); try { return fn(); } finally { + lowerer.instanceResultClass = prevResultClass; lowerer.localClassInstantiations.pop(); lowerer.typeParamBindings = prevBindings; lowerer.typeParamTsBindings = prevTsBindings; @@ -651,7 +802,7 @@ function internGenericInstance( const typeArgsText = `<${rendered.length > 80 ? rendered.slice(0, 77) + "..." : rendered}>`; inst = { path, - name: `${info.qualifiedName}%${info.instances.size}`, + name: keyedHelperName(lowerer, `${info.qualifiedName}%`, key, ""), ordinal: info.instances.size, params, returnType, @@ -1233,6 +1384,110 @@ export function lowerGenericFnValue( } } if (!target) fenceUnpinned(); + return guardEarlyBindingValue( + lowerer, + info, + ref, + pinnedGenericClosure(lowerer, ref, info, target, fenceUnpinned), + ); +} + +/** The value a generic binding declared inside a function stores when a + * nested function read it before the declaration lowered (`const read = + * () => id; const id: (x: number) => number = (x: T): T => x`): such + * a read resolves to an ordinary TDZ local, so the declaration assigns it + * the instance its concrete declared signature pins. Each evaluation of + * the declaration makes a new function object, as in JavaScript: the + * value is a closure over a forwarder to the instance, not the instance's + * interned closure. */ +export function genericBindingStoredValue( + lowerer: Lowerer, + decl: ts.VariableDeclaration, + info: GenericFnInfo, +): IrExpr { + const name = decl.name as ts.Identifier; + const fenceUnpinned = (): never => + lowerer.unsupported( + "SC1090", + name, + `generic function bindings read before their declaration without a concrete declared signature (annotate '${info.baseName}' with one, or declare it before its uses)`, + ); + const sigs = lowerer.checker.getCallSignatures(lowerer.typeOf(name)); + if (sigs.length !== 1) fenceUnpinned(); + const pinned = pinnedGenericClosure(lowerer, name, info, sigs[0]!, fenceUnpinned); + const async = ts.getModifiers(info.decl)?.some((m) => m.kind === ts.SyntaxKind.AsyncKeyword); + if (pinned.kind !== "closure" || pinned.type.kind !== "func" || pinned.type.rest || async) + return lowerer.unsupported( + "SC1090", + name, + `async or rest-parameter generic function bindings read before their declaration (each evaluation of '${info.baseName}' makes a new function object)`, + ); + return { + ...pinned, + fnName: genericValueForwarder(lowerer, info, pinned.fnName, pinned.type, pinned.loc), + }; +} + +/** A lifted function that calls the instance `instance` (of type `type`) + * with its own arguments. Lifted functions get a new closure object per + * evaluation; module functions, which instances are, get one interned + * closure. */ +function genericValueForwarder( + lowerer: Lowerer, + info: GenericFnInfo, + instance: string, + type: IrType & { kind: "func" }, + at: SrcLoc, +): string { + info.valueForwarders ??= new Map(); + const existing = info.valueForwarders.get(instance); + if (existing !== undefined) return existing; + const name = `${instance}%value`; + const loc = helperLoc(at); + const params: IrParam[] = type.params.map((paramType, i) => ({ + localId: `%arg${i}.0`, + name: `%arg${i}`, + type: paramType, + })); + const call: IrExpr = { + kind: "call", + callee: instance, + args: params.map((p): IrExpr => ({ kind: "varRef", localId: p.localId, type: p.type, loc })), + type: type.ret, + loc, + }; + lowerer.liftedFns.push({ + name, + params, + returnType: type.ret, + locals: params.map((p) => ({ id: p.localId, name: p.name, type: p.type, mutable: false })), + captures: [], + ...(ts.isFunctionExpression(info.decl) ? { ownsPrototype: true } : {}), + body: + type.ret.kind === "void" + ? [ + { kind: "exprStmt", expr: call, loc }, + { kind: "return", value: null, loc }, + ] + : [{ kind: "return", value: call, loc }], + loc, + }); + lowerer.noteEdge(name); + info.valueForwarders.set(instance, name); + return name; +} + +/** The closure of the instance of `info` that `target` pins, for a value + * read at `ref`. `fenceUnpinned` reports a signature that leaves a type + * parameter unbound. */ +function pinnedGenericClosure( + lowerer: Lowerer, + ref: ts.Expression, + info: GenericFnInfo, + target: ts.Signature, + fenceUnpinned: () => never, +): IrExpr { + const loc = locOf(ref); const bindings = new Map(); unifySignatureBindings(lowerer, info, target, bindings); const hofBinding = runtimeOptionalHofGenericBinding(lowerer, ref, info); @@ -2129,7 +2384,7 @@ function internImplicitInstance( const declared = dynamicBroadPromise ? null : implicitDeclaredReturn(lowerer, info); inst = { path, - name: `${info.qualifiedName}%${info.instances.size}`, + name: keyedHelperName(lowerer, `${info.qualifiedName}%`, key, ""), ordinal: info.instances.size, params: shapes, // The promise callers rely on before the body settles it: the @@ -2317,7 +2572,7 @@ export function implicitLocalFnInfoOf( baseName: name, qualifiedName: lowerer.qualify( ts.getSourceFileOfNode(decl), - nsPathPrefix(stmt ?? decl, decl) + `${name}%l${ts.tokenStartOfNode(decl)}`, + nsPathPrefix(lowerer, stmt ?? decl, decl) + `${name}%l${positionTag(lowerer, decl)}`, ), typeParams: [], instances: new Map(), @@ -2413,7 +2668,7 @@ export function objLitGenericFnInfoOf( baseName: name, qualifiedName: lowerer.qualify( ts.getSourceFileOfNode(fnNode), - `%ol${ts.tokenStartOfNode(fnNode)}.${name}`, + `%ol${positionTag(lowerer, fnNode)}.${name}`, ), typeParams, instances: new Map(), @@ -2559,15 +2814,24 @@ export function bindingGenericFnInfoOf( baseName: name, qualifiedName: lowerer.qualify( ts.getSourceFileOfNode(decl), - nsPathPrefix(stmt ?? decl, decl) + + nsPathPrefix(lowerer, stmt ?? decl, decl) + (topLevel ? name : `${name}%l${ts.tokenStartOfNode(decl)}`), ), typeParams, instances: new Map(), ...(functionScoped ? { functionScoped: true as const } : {}), + bindingDecl: decl, }; lowerer.bindingGenericFns.set(fnNode, info); lowerer.genericFnsBySymbol.set(sym, info); + // Module-scope uses resolve to the instances from the start, so those + // that can run first need the flag. Inside a function the declaration + // registers before any later use lowers, and earlier uses read a TDZ + // box (genericBindingStoredValue). + if (!functionScoped) { + const presence = bindingPresenceOf(lowerer, info, decl, sym); + if (presence !== undefined) info.presence = presence; + } if (ts.isFunctionExpression(fnNode) && fnNode.name !== undefined) { const inner = lowerer.checker.getSymbolAtLocation(fnNode.name); if (inner) lowerer.genericFnsBySymbol.set(inner, info); @@ -2575,6 +2839,261 @@ export function bindingGenericFnInfoOf( return info; } +/** Whether `use`, a reference to the binding `info` declares, can only + * run after the declaration has run: it follows the declaration in its + * statement list (closures count where they are created), sits inside the + * initializer itself, or is inside a function declaration whose every + * reference does. References from other modules run after this module's + * body, and export specifiers only export. A use the check cannot place + * answers false. */ +export function runsAfterDeclaration(lowerer: Lowerer, info: GenericFnInfo, use: ts.Node): boolean { + const decl = info.bindingDecl; + if (decl === undefined) return true; + info.ordering ??= new Map(); + return useRunsAfter(lowerer, decl, use, info.ordering, new Set()); +} + +function useRunsAfter( + lowerer: Lowerer, + decl: ts.VariableDeclaration, + use: ts.Node, + memo: Map, + inProgress: Set, +): boolean { + if (ts.getSourceFileOfNode(use) !== ts.getSourceFileOfNode(decl)) return true; + const init = decl.initializer; + if (init !== undefined && use.pos >= init.pos && use.end <= init.end) return true; + const stmt = decl.parent?.parent; + const list = stmt?.parent; + if (stmt === undefined || list === undefined) return false; + for (let n: ts.Node = use; n.parent !== undefined; n = n.parent) { + if (n.parent === list) return n === stmt ? use.pos >= decl.end : n.pos >= stmt.end; + if (ts.isFunctionDeclaration(n)) return functionRunsAfter(lowerer, decl, n, memo, inProgress); + } + return false; +} + +/** Whether every call of the function declaration `fn` runs after `decl` + * has run. A function in progress counts as running after: its calls of + * itself, directly or through other functions, add no earlier caller. + * Only answers that depend on no function in progress are memoized. */ +function functionRunsAfter( + lowerer: Lowerer, + decl: ts.VariableDeclaration, + fn: ts.FunctionDeclaration, + memo: Map, + inProgress: Set, +): boolean { + const known = memo.get(fn); + if (known !== undefined) return known; + if (inProgress.has(fn)) return true; + // `export default function () {}`: only importers call it, after this + // module's body has run. + if (fn.name === undefined) return true; + inProgress.add(fn); + let result = true; + try { + const symbol = lowerer.checker.getSymbolAtLocation(fn.name); + if (symbol === undefined) result = false; + else { + for (const ref of bindingReferences(lowerer, ts.getSourceFileOfNode(fn), symbol, fn.name)) { + if (ref.pos >= fn.pos && ref.end <= fn.end) continue; + if (!useRunsAfter(lowerer, decl, ref, memo, inProgress)) { + result = false; + break; + } + } + } + } finally { + inProgress.delete(fn); + } + if (inProgress.size === 0) memo.set(fn, result); + return result; +} + +/** The value references of `symbol` in `file` other than `name` (its + * declaration name): identifiers spelled like it that resolve to it, + * outside type positions and export specifiers. */ +function bindingReferences( + lowerer: Lowerer, + file: ts.SourceFile, + symbol: ts.Symbol, + name: ts.Identifier, +): ts.Identifier[] { + let byName = lowerer.bindingIdentifiers.get(file); + if (byName === undefined) { + byName = new Map(); + lowerer.bindingIdentifiers.set(file, byName); + } + let idents = byName.get(name.text); + if (idents === undefined) { + const found: ts.Identifier[] = []; + ts.walkPreorder(file, (node) => { + if (ts.isIdentifier(node) && node.text === name.text) found.push(node); + return undefined; + }); + lowerer.checker.prefetchSymbolNodesExact(found); + byName.set(name.text, found); + idents = found; + } + return idents.filter((ident) => { + if (ident === name) return false; + const parent = ident.parent; + if (parent === undefined || ts.isExportSpecifier(parent) || ts.isExportAssignment(parent)) + return false; + let resolved = lowerer.checker.getSymbolAtLocation(ident); + if (ts.isShorthandPropertyAssignment(parent) && parent.name === ident) + resolved = lowerer.checker.getShorthandAssignmentValueSymbol(parent) ?? resolved; + if (resolved !== symbol) return false; + for (let p: ts.Node | undefined = parent; p !== undefined; p = p.parent) { + if (ts.isTypeNode(p) && p.kind !== ts.SyntaxKind.ExpressionWithTypeArguments) return false; + if (ts.isStatement(p) || ts.isFunctionLike(p)) break; + } + return true; + }); +} + +/** The presence flag of a module-scope generic binding that code can use + * before its declaration runs (a hoisted function or an earlier closure + * called during module evaluation), or undefined when every use runs + * after it. The declaration statement sets the flag. */ +function bindingPresenceOf( + lowerer: Lowerer, + info: GenericFnInfo, + decl: ts.VariableDeclaration, + symbol: ts.Symbol, +): GenericFnInfo["presence"] { + const name = decl.name as ts.Identifier; + const early = bindingReferences(lowerer, ts.getSourceFileOfNode(decl), symbol, name).some( + (ref) => !runsAfterDeclaration(lowerer, info, ref), + ); + if (!early) return undefined; + const flagId = `%g.${info.qualifiedName}%initialized`; + lowerer.globalsList.push({ id: flagId, name: "%initialized", type: BOOL, mutable: true }); + return { flagId, lexical: !isVarDeclared(decl) }; +} + +/** The statement that records a generic binding's declaration as run, + * for a binding with a presence flag. */ +export function genericBindingPresenceStore( + info: GenericFnInfo, + decl: ts.VariableDeclaration, +): IrStmt | null { + if (info.presence === undefined) return null; + const loc = locOf(decl); + return { + kind: "assign", + localId: info.presence.flagId, + value: { kind: "boolLit", value: true, type: BOOL, loc }, + loc, + }; +} + +/** A call of a generic binding where the binding may not be initialized + * yet. A `let`/`const` binding in its temporal dead zone throws Node's + * ReferenceError before the arguments run; an unassigned `var` is + * undefined, so the arguments run and the call throws "is not a + * function". Calls that run after the declaration stay direct. */ +function guardEarlyBindingCall( + lowerer: Lowerer, + info: GenericFnInfo, + expr: ts.CallExpression, + call: IrExpr & { kind: "call" }, +): IrExpr { + if (info.bindingDecl === undefined || runsAfterDeclaration(lowerer, info, expr)) return call; + const loc = call.loc; + const presence = requirePresence(lowerer, info, expr.expression); + const flag: IrExpr = { kind: "varRef", localId: presence.flagId, type: BOOL, loc }; + if (presence.lexical) + return { + kind: "seqExpr", + stmts: [tdzCheck(flag, info.baseName, loc)], + result: call, + type: call.type, + loc, + }; + // Arguments first, in order, then the check: Node evaluates them + // before it finds the callee is not callable. + const stmts: IrStmt[] = []; + const args = call.args.map((arg): IrExpr => { + const id = `%earlyCallArg.${lowerer.ctx.locals.length}`; + lowerer.ctx.locals.push({ id, name: "%earlyCallArg", type: arg.type, mutable: false }); + stmts.push({ kind: "varDecl", localId: id, init: arg, loc }); + return { kind: "varRef", localId: id, type: arg.type, loc }; + }); + return { + kind: "seqExpr", + stmts, + result: { + kind: "ternary", + cond: flag, + then: { ...call, args }, + else_: nodeThrowExpr(1, "", `${info.baseName} is not a function`, call.type, loc), + type: call.type, + loc, + }, + type: call.type, + loc, + }; +} + +/** A generic binding read as a value where it may not be initialized + * yet: a `let`/`const` binding checks its temporal dead zone first. */ +function guardEarlyBindingValue( + lowerer: Lowerer, + info: GenericFnInfo, + ref: ts.Expression, + value: IrExpr, +): IrExpr { + if (info.bindingDecl === undefined || runsAfterDeclaration(lowerer, info, ref)) return value; + const presence = requirePresence(lowerer, info, ref); + if (!presence.lexical) + lowerer.unsupported( + "SC1090", + ref, + `generic 'var' bindings read as values before their declaration runs (Node reads undefined there; declare '${info.baseName}' with const)`, + ); + const loc = value.loc; + const flag: IrExpr = { kind: "varRef", localId: presence.flagId, type: BOOL, loc }; + return { + kind: "seqExpr", + stmts: [tdzCheck(flag, info.baseName, loc)], + result: value, + type: value.type, + loc, + }; +} + +/** The presence flag a use that can run before the declaration checks. + * Only module-scope bindings have one: a binding inside a function would + * need a per-call flag that its closures share. */ +function requirePresence( + lowerer: Lowerer, + info: GenericFnInfo, + blame: ts.Node, +): NonNullable { + if (info.presence !== undefined) return info.presence; + return lowerer.unsupported( + "SC1090", + blame, + `generic arrow/function-expression bindings declared inside functions that code can call before their declaration runs (the binding '${info.baseName}' is a 'var' in a branch or block, or is called from a place that can run first — declare it with const before its uses)`, + ); +} + +function tdzCheck(flag: IrExpr, name: string, loc: SrcLoc): IrStmt { + return { + kind: "exprStmt", + expr: { + kind: "intrinsic", + name: "module.tdzCheck", + args: [flag, { kind: "strLit", value: name, type: STRING, loc }], + type: VOID, + loc, + }, + loc, + }; +} + /** `const h = id` — a binding ALIASING a generic function (a top-level * declaration, a registered generic binding, or another alias — resolved * left to right in declaration order). The alias registers the SAME info diff --git a/packages/compiler/src/frontend/lowering/intern-tables.ts b/packages/compiler/src/frontend/lowering/intern-tables.ts index fc69237db..e3f2b0889 100644 --- a/packages/compiler/src/frontend/lowering/intern-tables.ts +++ b/packages/compiler/src/frontend/lowering/intern-tables.ts @@ -23,6 +23,7 @@ * The entry handles that itable.find and itable.insert answer stay inside * these lowerings: f64 locals that only reach toBool and itable.value. * Any other use of the class or its members as values is refused. */ +import { keyedHelperName } from "./stable-names.js"; import { dynUndefinedExpr } from "../../ir/build.js"; import { BOOL, F64, STRING, funcOf, typeKey } from "../../ir/ir.js"; import type { IrExpr, IrFunction, IrStmt, IrType, SrcLoc } from "../../ir/ir.js"; @@ -447,7 +448,11 @@ function helperName(lowerer: Lowerer, member: InternTableMember, signature: stri } function registerHelper(lowerer: Lowerer, member: InternTableMember, signature: string): string { - const name = `%${INTERN_TABLE_CLASS}.${member}.${lowerer.internTableHelpers.size}`; + const name = keyedHelperName( + lowerer, + `%${INTERN_TABLE_CLASS}.${member}`, + `${member}|${signature}`, + ); lowerer.internTableHelpers.set(`${member}|${signature}`, name); return name; } diff --git a/packages/compiler/src/frontend/lowering/iterable-values.ts b/packages/compiler/src/frontend/lowering/iterable-values.ts new file mode 100644 index 000000000..78de9720c --- /dev/null +++ b/packages/compiler/src/frontend/lowering/iterable-values.ts @@ -0,0 +1,342 @@ +/* `Iterable` values. The type maps to the iterable union + * (type-mapper.ts iterableUnionType): an array, Set, Map or string keeps + * its own arm, so the value stays the same multi-pass object (identity, + * inspection and typeof are the source's own), and every iterator — a + * generator, an array, Map or Set iterator, a checked-dynamic iterator — + * enters the generator arm, single-pass as in JavaScript. + * + * Consumers open an iterator over the current arm the way for-of's + * GetIterator does: an array, Set, Map or string arm starts a fresh live + * walk (the sources' own iterator helpers), the generator arm is itself. + * for-of gives the array arm its own array loop, so iterating an Iterable + * that holds an array runs at array-loop speed. */ +import * as ts from "../ts7/adapter.js"; +import { locOf } from "../program.js"; +import { varRef, numLit } from "../../ir/build.js"; +import { + BOOL, + F64, + iterableArmsElem, + typeEquals, + type IrExpr, + type IrStmt, + type IrType, +} from "../../ir/ir.js"; +import { typeKey } from "../type-mapper.js"; +import { keyedHelperName } from "./stable-names.js"; +import { PoisonError, type Lowerer } from "./lowerer.js"; +import { noLoweringDiag, unsupportedDiag } from "../../diagnostics/diagnostic.js"; +import { generatorLoopBinding, lowerForOfGenerator, type GenType } from "./lower-generators.js"; +import { + iteratorSlotAdapter, + lowerArrayIteratorValue, + lowerCollectionIteratorValue, + lowerStringIteratorValue, +} from "./iterator-adapters.js"; +import { arrayValueRead, arrayValueType } from "./array-values.js"; + +/** An iterable union and the tags of its arms. */ +export interface IterableUnion { + unionId: string; + type: IrType & { kind: "union" }; + elem: IrType; + arms: readonly IrType[]; + /** The generator arm: a sync generator over `elem`. */ + gen: GenType; +} + +/** The iterable union `t` names, or null. */ +export function iterableUnionOf(lowerer: Lowerer, t: IrType): IterableUnion | null { + const info = iterableSlotUnionOf(lowerer, t); + // An optional Iterable (`Iterable | undefined`) is consumed only once + // narrowed to the iterable union itself. + if (info === null || info.arms.some((arm) => arm.kind === "undefinedT" || arm.kind === "nullT")) + return null; + return info; +} + +/** The iterable union `t` names, also an optional or nullable one + * (`Iterable | undefined`, whose unit arms sit beside the iterable + * arms), or null. */ +function iterableSlotUnionOf(lowerer: Lowerer, t: IrType): IterableUnion | null { + if (t.kind !== "union") return null; + const arms = lowerer.unions.get(t.unionId)?.arms; + if (!arms) return null; + const elem = iterableArmsElem(arms); + if (elem === null) return null; + const gen = arms.find((arm) => arm.kind === "generator") as GenType; + return { unionId: t.unionId, type: t, elem, arms, gen }; +} + +/** The generator arm of an iterable union (what a generator function + * declared to return Iterable returns), or `t` itself. */ +export function iterableGeneratorArm(lowerer: Lowerer, t: IrType): IrType { + return iterableUnionOf(lowerer, t)?.gen ?? t; +} + +/** A value flowing into an iterable-typed slot, optional or nullable + * ones included: a source arm wraps as itself; a generator over other + * channel types or a checked-dynamic iterator (a Map or Set iterator) + * adapts into the generator arm. Null when neither applies, leaving the + * ordinary conversion fences to refuse other sources (class iterables, + * typed arrays, other element types). */ +export function iterableSlotValue(lowerer: Lowerer, expr: IrExpr, expected: IrType): IrExpr | null { + const info = iterableSlotUnionOf(lowerer, expected); + if (info === null || expr.type.kind === "union") return null; + const wrap = (value: IrExpr): IrExpr => ({ + kind: "unionWrap", + unionId: info.unionId, + tag: lowerer.armTag(info.unionId, value.type), + value, + type: info.type, + loc: expr.loc, + }); + if (lowerer.armTag(info.unionId, expr.type) >= 0) return wrap(expr); + if (expr.type.kind === "generator" || expr.type.kind === "dyn") { + const adapted = iteratorSlotAdapter(lowerer, expr, info.gen); + if (adapted && typeEquals(adapted.type, info.gen)) return wrap(adapted); + } + // Class instances (their own [Symbol.iterator]) and typed arrays have no + // arm: refuse them here, by name. + if (expr.type.kind === "object" || expr.type.kind === "bytes") { + lowerer.pushDiag( + unsupportedDiag( + "SC1090", + expr.loc, + `an Iterable<${lowerer.fmt(info.elem)}> holding a '${lowerer.fmt(expr.type)}' (an Iterable value holds an array, Set, Map, string, or iterator)`, + ), + ); + throw new PoisonError(); + } + return null; +} + +/** GetIterator on an iterable union value: an interned helper answering a + * generator over the current arm — a fresh live walk of an array, Set, Map + * or string, or the generator arm itself. */ +export function iterableGenerator(lowerer: Lowerer, value: IrExpr, info: IterableUnion): IrExpr { + const loc = value.loc; + const key = `iterableOf:${typeKey(info.type)}`; + let name = lowerer.valueHelpers.get(key); + if (!name) { + const u = varRef("u.0", info.type, loc); + const body: IrStmt[] = []; + let genTag = -1; + info.arms.forEach((arm, tag) => { + if (arm.kind === "generator") { + genTag = tag; + return; + } + const narrowed: IrExpr = { + kind: "unionNarrow", + unionId: info.unionId, + tag, + value: u, + type: arm, + loc, + }; + const walk = + arm.kind === "array" + ? lowerArrayIteratorValue(lowerer, narrowed, "values", info.gen, loc) + : arm.kind === "set" + ? lowerCollectionIteratorValue(lowerer, narrowed, "values", info.gen, loc) + : arm.kind === "map" + ? lowerCollectionIteratorValue(lowerer, narrowed, "entries", info.gen, loc) + : arm.kind === "string" + ? lowerStringIteratorValue(lowerer, narrowed, info.gen, loc) + : null; + if (walk === null || !typeEquals(walk.type, info.gen)) { + lowerer.pushDiag( + noLoweringDiag( + `iterating an Iterable<${lowerer.fmt(info.elem)}> that holds a ${arm.kind}`, + loc, + ), + ); + throw new PoisonError(); + } + body.push({ + kind: "if", + cond: { + kind: "unionIsTag", + unionId: info.unionId, + tag, + negated: false, + value: u, + type: BOOL, + loc, + }, + then: [{ kind: "return", value: walk, loc }], + else_: null, + loc, + }); + }); + body.push({ + kind: "return", + value: { + kind: "unionNarrow", + unionId: info.unionId, + tag: genTag, + value: u, + type: info.gen, + loc, + }, + loc, + }); + name = keyedHelperName(lowerer, "%iterable.of", key); + lowerer.valueHelpers.set(key, name); + lowerer.liftedFns.push({ + name, + params: [{ localId: "u.0", name: "u", type: info.type }], + returnType: info.gen, + locals: [{ id: "u.0", name: "u", type: info.type, mutable: false }], + body, + loc, + }); + } + return { kind: "call", callee: name, args: [value], type: info.gen, loc }; +} + +/** Whether a loop body declares a class (a class has one lowering per + * declaration, so its body cannot lower twice). */ +function declaresClass(body: ts.Statement): boolean { + let found = false; + ts.walkPreorder(body, (node) => { + if (ts.isClassDeclaration(node) || ts.isClassExpression(node)) { + found = true; + return "stop"; + } + return undefined; + }); + return found; +} + +/** `for (x of iterable)` over an iterable union: + * + * { const %src = ; + * if (%src is the array arm) { + * const %arr = ; + * for (let %cur = 0; %cur < %arr.length; %cur++) { const x = %arr[%cur]; } + * } else { + * for (const x of GetIterator(%src)) // the generator for-of + * } + * } + * + * The array arm walks exactly like an array for-of (live length, the + * backend's dense-array loop forms), so an Iterable holding an array + * iterates at array speed; every other arm drives its iterator with the + * generator for-of's IteratorClose rules. The body lowers once for each + * loop; a body that declares a class lowers only once, in the generator + * for-of over every arm. */ +export function lowerForOfIterable( + lowerer: Lowerer, + stmt: ts.ForOfStatement, + iterable: IrExpr, + info: IterableUnion, + labels?: string[], +): IrStmt { + const loc = locOf(stmt); + const generatorLoop = (source: IrExpr): IrStmt => + lowerForOfGenerator( + lowerer, + stmt, + iterableGenerator(lowerer, source, info) as IrExpr & { type: GenType }, + labels, + ); + const arrayTag = info.arms.findIndex((arm) => arm.kind === "array"); + // A union without an array arm (`Set | Generator`) has only the + // generator loop. + if (stmt.awaitModifier || declaresClass(stmt.statement) || arrayTag < 0) + return generatorLoop(iterable); + const arrT = info.arms[arrayTag]!; + lowerer.scopes.push(new Map()); + try { + const src = lowerer.declareHiddenLocal("%iterableSource", info.type); + const srcRef = (): IrExpr => varRef(src.id, info.type, loc); + const arr = lowerer.declareHiddenLocal("%arrayIterator", arrT); + const cursor = lowerer.declareHiddenLocal("%arrayCursor", F64); + cursor.mutable = true; + const arrRef = varRef(arr.id, arrT, loc); + const curRef = varRef(cursor.id, F64, loc); + // The element: a hole reads undefined, which an undefined-armed T + // holds; for other element types the read traps, as typed reads do. + const element: IrExpr = typeEquals(arrayValueType(lowerer, info.elem), info.elem) + ? arrayValueRead(lowerer, arrRef, curRef, info.elem, loc) + : { kind: "arrayGet", arr: arrRef, index: curRef, type: info.elem, loc }; + const arrayLoop = ((): IrStmt => { + lowerer.scopes.push(new Map()); + try { + const binding = generatorLoopBinding(lowerer, stmt, element, info.elem); + const body = lowerer.inCtl("loop", () => lowerer.lowerScopedBlock(stmt.statement), labels); + return { + kind: "for", + init: { kind: "varDecl", localId: cursor.id, init: numLit(0, loc), loc }, + cond: { + kind: "bin", + op: "<", + left: curRef, + right: { + kind: "arrIntrinsic", + method: "length", + receiver: arrRef, + args: [], + type: F64, + loc, + }, + type: BOOL, + loc, + }, + update: { + kind: "assign", + localId: cursor.id, + value: { kind: "bin", op: "+", left: curRef, right: numLit(1, loc), type: F64, loc }, + loc, + }, + body: [...binding, ...body], + ...(labels && { labels }), + loc, + }; + } finally { + lowerer.scopes.pop(); + } + })(); + return { + kind: "block", + body: [ + { kind: "varDecl", localId: src.id, init: iterable, loc }, + { + kind: "if", + cond: { + kind: "unionIsTag", + unionId: info.unionId, + tag: arrayTag, + negated: false, + value: srcRef(), + type: BOOL, + loc, + }, + then: [ + { + kind: "varDecl", + localId: arr.id, + init: { + kind: "unionNarrow", + unionId: info.unionId, + tag: arrayTag, + value: srcRef(), + type: arrT, + loc, + }, + loc, + }, + arrayLoop, + ], + else_: [generatorLoop(srcRef())], + loc, + }, + ], + loc, + }; + } finally { + lowerer.scopes.pop(); + } +} diff --git a/packages/compiler/src/frontend/lowering/iterator-adapters.ts b/packages/compiler/src/frontend/lowering/iterator-adapters.ts index 898c46f20..e50652182 100644 --- a/packages/compiler/src/frontend/lowering/iterator-adapters.ts +++ b/packages/compiler/src/frontend/lowering/iterator-adapters.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "./stable-names.js"; import { dynUndefinedExpr, varRef } from "../../ir/build.js"; import { BOOL, @@ -86,7 +87,7 @@ function dynIteratorAdapter( const key = `iterAdapt:${typeKey(expected)}`; let name = lowerer.valueHelpers.get(key); if (!name) { - name = `%iter.adapt.${lowerer.valueHelpers.size}`; + name = keyedHelperName(lowerer, "%iter.adapt", key); lowerer.valueHelpers.set(key, name); const locals: IrLocal[] = []; const local = (id: string, type: IrType, mutable = false): IrExpr => { @@ -313,7 +314,7 @@ export function lowerCollectionIteratorValue( loc, }; if (!typeEquals(yielded.type, type.yieldT)) return null; - name = `%coll.iter.${lowerer.valueHelpers.size}`; + name = keyedHelperName(lowerer, "%coll.iter", key); lowerer.valueHelpers.set(key, name); lowerer.liftedFns.push({ name, @@ -411,7 +412,7 @@ export function lowerBytesIteratorValue( const key = `bytesIter:${method}:${typeKey(bytesT)}:${typeKey(type)}`; let name = lowerer.valueHelpers.get(key); if (!name) { - name = `%bytes.iter.${lowerer.valueHelpers.size}`; + name = keyedHelperName(lowerer, "%bytes.iter", key); lowerer.valueHelpers.set(key, name); const list = varRef("list.0", bytesT, loc); const index = varRef("index.0", F64, loc); @@ -517,7 +518,7 @@ export function lowerStringIteratorValue( const key = `strIter:${typeKey(type)}`; let name = lowerer.valueHelpers.get(key); if (!name) { - name = `%str.iter.${lowerer.valueHelpers.size}`; + name = keyedHelperName(lowerer, "%str.iter", key); lowerer.valueHelpers.set(key, name); const text = varRef("text.0", STRING, loc); const index = varRef("index.0", F64, loc); @@ -677,7 +678,7 @@ function generatorRetypeAdapter( type: resumeType(expected.nextT), loc, }; - name = `%gen.retype.${lowerer.valueHelpers.size}`; + name = keyedHelperName(lowerer, "%gen.retype", key); lowerer.valueHelpers.set(key, name); lowerer.liftedFns.push({ name, @@ -794,7 +795,7 @@ export function generatorDrain( const outRef = varRef("out.0", arrT, loc); const value = lowerer.coerceToExpected(genValue(genRef, loc), elem); if (!typeEquals(value.type, elem)) return null; - name = `%gen.drain.${lowerer.valueHelpers.size}`; + name = keyedHelperName(lowerer, "%gen.drain", key); lowerer.valueHelpers.set(key, name); lowerer.liftedFns.push({ name, @@ -856,7 +857,7 @@ export function generatorDrain( if (!raw) return null; const value = lowerer.coerceToExpected(raw, elem); if (!typeEquals(value.type, elem)) return null; - name = `%gen.drain.${lowerer.valueHelpers.size}`; + name = keyedHelperName(lowerer, "%gen.drain", key); lowerer.valueHelpers.set(key, name); lowerer.liftedFns.push({ name, @@ -978,7 +979,7 @@ export function lowerArrayIteratorValue( }; } if (!yielded || !typeEquals(yielded.type, type.yieldT)) return null; - name = `%arr.iter.${lowerer.valueHelpers.size}`; + name = keyedHelperName(lowerer, "%arr.iter", key); lowerer.valueHelpers.set(key, name); lowerer.liftedFns.push({ name, diff --git a/packages/compiler/src/frontend/lowering/js-dynamic-objects.ts b/packages/compiler/src/frontend/lowering/js-dynamic-objects.ts index b9bbf6216..e27dd4183 100644 --- a/packages/compiler/src/frontend/lowering/js-dynamic-objects.ts +++ b/packages/compiler/src/frontend/lowering/js-dynamic-objects.ts @@ -21,6 +21,7 @@ * files only, and an empty answer leaves every mapping unchanged, so * TypeScript programs and JavaScript that never uses these patterns * compile exactly as before. */ +import { keyedHelperName } from "./stable-names.js"; import * as ts from "../ts7/adapter.js"; import { isJsSourceFile, locOf } from "../program.js"; import { BOOL, DYN, type IrExpr, type IrStmt } from "../../ir/ir.js"; @@ -215,10 +216,10 @@ export function lowerValueReturningConstructorNew( "spread arguments when constructing a class whose constructor returns a value", ); } - const key = `ctorValue:${ts.getSourceFileOfNode(decl).fileName}:${ts.tokenStartOfNode(decl)}`; + const key = `ctorValue:${lowerer.positions.of(decl)}`; let name = lowerer.valueHelpers.get(key); if (name === undefined) { - name = `%ctorValue.${lowerer.valueHelpers.size}`; + name = keyedHelperName(lowerer, "%ctorValue", key); lowerer.valueHelpers.set(key, name); const savedClass = lowerer.currentClass; lowerer.currentClass = null; diff --git a/packages/compiler/src/frontend/lowering/json-require.ts b/packages/compiler/src/frontend/lowering/json-require.ts index 927745253..d6c2da571 100644 --- a/packages/compiler/src/frontend/lowering/json-require.ts +++ b/packages/compiler/src/frontend/lowering/json-require.ts @@ -10,6 +10,7 @@ * JSON module is ordinary storage holding that object — destructuring * copies its properties at the require, exactly like Node. ES-module JSON * imports keep their own record (Node's ESM loader caches separately). */ +import { keyedHelperName } from "./stable-names.js"; import * as ts from "../ts7/adapter.js"; import type { Lowerer } from "./lowerer.js"; import { PoisonError } from "./lowerer.js"; @@ -84,7 +85,7 @@ export function collectJsonRequires(lowerer: Lowerer, parts: FileParts[]): void ); throw new PoisonError(); } - const id = `%g.jsonRequire.${lowerer.jsonRequireModules.size}`; + const id = keyedHelperName(lowerer, "%g.jsonRequire", jsonSf.fileName); const global: IrGlobal = { id, name: "%json", type: mapped, mutable: true }; const loadedId = `${id}%loaded`; lowerer.globalsList.push(global, { diff --git a/packages/compiler/src/frontend/lowering/key-order-witness.test.ts b/packages/compiler/src/frontend/lowering/key-order-witness.test.ts index de16e5d61..8632bad47 100644 --- a/packages/compiler/src/frontend/lowering/key-order-witness.test.ts +++ b/packages/compiler/src/frontend/lowering/key-order-witness.test.ts @@ -157,6 +157,36 @@ test("a synthesized construction pins today's table", () => { expect(f.order(ab)).toEqual(["a", "b"]); }); +test("a runtime builder typed by its use site pins today's table", () => { + const f = fixture(); + const ab = f.record( + [ + ["a", F64], + ["b", F64], + ], + ["a", "b"], + ); + // net.serverAddress's signature result is VOID: the call takes its record + // type from its use site, and the runtime builds the record in that order. + const built: IrExpr = { kind: "libCall", fn: "net.serverAddress", args: [], type: ab, loc }; + f.run([observe(f.literal(ab, ["b", "a"])), observe(built)]); + expect(f.order(ab)).toEqual(["a", "b"]); +}); + +test("an always-throwing call typed as the record leaves its literals' order", () => { + const f = fixture(); + const ab = f.record( + [ + ["a", F64], + ["b", F64], + ], + ["a", "b"], + ); + const thrown: IrExpr = { kind: "libCall", fn: "error.nodeThrow", args: [], type: ab, loc }; + f.run([observe(f.literal(ab, ["b", "a"])), observe(thrown)]); + expect(f.order(ab)).toEqual(["b", "a"]); +}); + test("a checked conversion alone pins today's table", () => { const f = fixture(); const ab = f.record( diff --git a/packages/compiler/src/frontend/lowering/key-order-witness.ts b/packages/compiler/src/frontend/lowering/key-order-witness.ts index 2fc9a6cbd..4adfb87ab 100644 --- a/packages/compiler/src/frontend/lowering/key-order-witness.ts +++ b/packages/compiler/src/frontend/lowering/key-order-witness.ts @@ -45,6 +45,7 @@ import type { IrExpr, IrFunction, IrRecordShape, IrStmt, IrType } from "../../ir import { shapeHasAccessorSlots, typeEquals, UNDEFINED_T } from "../../ir/ir.js"; import { everyExprChild, everyStmtChild, everyTypeChild } from "../../ir/traverse.js"; import type { Lowerer } from "./lowerer.js"; +import { ALWAYS_THROW_LIB_FNS } from "../../ir/builtin-effects.js"; /** One property of an object literal, in source order. */ export type KeyOrderSegment = @@ -312,7 +313,11 @@ export function applyKeyOrderWitnesses(lowerer: Lowerer, fns: readonly IrFunctio // Runtime surfaces (console, util.format, workers) that take a // record may walk its keys; runtime builders make new records. for (const arg of e.args) observedRoots.push(arg.type); - producedBy(e.type, true); + // An always-throwing call stands in for a value (`error.nodeThrow` + // in a narrowing ternary) and never produces one. Other calls + // whose signature result is VOID are typed by their use site and + // build the record at run time (`server.address()`). + if (!ALWAYS_THROW_LIB_FNS.has(e.fn)) producedBy(e.type, true); return; case "intrinsic": // Intrinsics hand back values built elsewhere, except allSettled's diff --git a/packages/compiler/src/frontend/lowering/lifetime-regions.ts b/packages/compiler/src/frontend/lowering/lifetime-regions.ts index b212ae473..b684c0395 100644 --- a/packages/compiler/src/frontend/lowering/lifetime-regions.ts +++ b/packages/compiler/src/frontend/lowering/lifetime-regions.ts @@ -14,6 +14,7 @@ * Any other use of the class or its methods as values is refused. The * module is marked lifetimeRegions, which moves every ProgramLifetime * class into counted regions. */ +import { keyedHelperName } from "./stable-names.js"; import { F64, VOID, funcOf, typeKey } from "../../ir/ir.js"; import type { IrExpr, IrFunction, IrStmt, IrType, SrcLoc } from "../../ir/ir.js"; import { experimentalImportOf, lifetimeRegionMemberOf } from "../experimental-import.js"; @@ -152,7 +153,7 @@ function runHelper(lowerer: Lowerer, fnType: IrType & { kind: "func" }, loc: Src const key = typeKey(fnType); const known = lowerer.regionRunHelpers.get(key); if (known !== undefined) return known; - const name = `%${LIFETIME_REGION_CLASS}.run.${lowerer.regionRunHelpers.size}`; + const name = keyedHelperName(lowerer, `%${LIFETIME_REGION_CLASS}.run`, key); lowerer.regionRunHelpers.set(key, name); const regionT = lifetimeRegionType(lowerer); const ret = fnType.ret; diff --git a/packages/compiler/src/frontend/lowering/lower-assert.ts b/packages/compiler/src/frontend/lowering/lower-assert.ts index 460f4d53a..bc51a9382 100644 --- a/packages/compiler/src/frontend/lowering/lower-assert.ts +++ b/packages/compiler/src/frontend/lowering/lower-assert.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "./stable-names.js"; import { InternalCompilerError } from "../../errors.js"; /* The node:assert lowering (a spoke module like lower-dgram.ts): the * callable module form (`assert(x)` through a default import or a CJS @@ -667,7 +668,7 @@ function partialEqHelper(lowerer: Lowerer, ta: IrType, tb: IrType, loc: SrcLoc): const key = `assert.pdeq:${typeKey(ta)}|${typeKey(tb)}`; const existing = lowerer.assertHelpers.get(key); if (existing) return existing; - const name = `%assert.pdeq.${lowerer.assertHelpers.size}`; + const name = keyedHelperName(lowerer, "%assert.pdeq", key); lowerer.assertHelpers.set(key, name); const a = (): IrExpr => varRef("a.0", ta, loc); const b = (): IrExpr => varRef("b.0", tb, loc); @@ -1280,7 +1281,7 @@ function deepCheckCall( const key = `assert.dcheck:${variant}:${negated}:${typeKey(a.type)}:${typeKey(b.type)}`; let name = lowerer.assertHelpers.get(key); if (!name) { - name = `%assert.dcheck.${lowerer.assertHelpers.size}`; + name = keyedHelperName(lowerer, "%assert.dcheck", key); lowerer.assertHelpers.set(key, name); const pa = varRef("a.0", a.type, loc); const pb = varRef("b.0", b.type, loc); @@ -1844,7 +1845,7 @@ function assertThrowsHelper( const key = `assert.${mode}:${recvIsPromise ? "p" : "f"}:${typeKey(recvType)}:${sig}`; const existing = lowerer.assertHelpers.get(key); if (existing) return existing; - const name = `%assert.${mode}.${lowerer.assertHelpers.size}`; + const name = keyedHelperName(lowerer, `%assert.${mode}`, key); lowerer.assertHelpers.set(key, name); const caughtRef = (): IrExpr => varRef("e.0", CAUGHT, loc); @@ -2293,7 +2294,7 @@ function ifErrorHelper(lowerer: Lowerer, t: IrType & { kind: "union" }, loc: Src const key = `assert.iferr:${typeKey(t)}`; const existing = lowerer.assertHelpers.get(key); if (existing) return existing; - const name = `%assert.iferr.${lowerer.assertHelpers.size}`; + const name = keyedHelperName(lowerer, "%assert.iferr", key); lowerer.assertHelpers.set(key, name); const def = lowerer.unions.get(t.unionId); if (!def) throw new InternalCompilerError(`assert.ifError over unknown union ${t.unionId}`); @@ -2464,7 +2465,7 @@ function deepEqHelper(lowerer: Lowerer, t: IrType, loc: SrcLoc, loose = false): const key = `assert.${prefix}:${typeKey(t)}`; const existing = lowerer.assertHelpers.get(key); if (existing) return existing; - const name = `%assert.${prefix}.${lowerer.assertHelpers.size}`; + const name = keyedHelperName(lowerer, `%assert.${prefix}`, key); lowerer.assertHelpers.set(key, name); const a = (): IrExpr => varRef("a.0", t, loc); diff --git a/packages/compiler/src/frontend/lowering/lower-async-iteration.ts b/packages/compiler/src/frontend/lowering/lower-async-iteration.ts index 0e48f2040..95916ee9a 100644 --- a/packages/compiler/src/frontend/lowering/lower-async-iteration.ts +++ b/packages/compiler/src/frontend/lowering/lower-async-iteration.ts @@ -359,13 +359,15 @@ function boolRef(localId: string, loc: ReturnType): IrExpr { /** The loop's stream: a JavaScript value typed as a stream can arrive as a * checked-dynamic value (returned through an untyped function), which - * checks back into the stream class. */ + * checks back into the stream class, or as a union with it (an element + * read), which narrows to it. */ function streamSource( lowerer: Lowerer, plan: NodeReadablePlan, loc: ReturnType, ): IrExpr { const v = lowerer.lowerExpr(plan.source); + if (v.type.kind === "union") return lowerer.coerceToExpected(v, plan.type); if (v.type.kind !== "dyn") return v; return { kind: "dynCheck", value: v, type: plan.type, loc }; } @@ -428,7 +430,9 @@ function lowerNodeReadable( }, { kind: "if", - cond: { kind: "dynTest", test: "undefined", value: chunkRef, type: BOOL, loc }, + // the end is the done marker: an object-mode stream can yield + // undefined + cond: { kind: "libCall", fn: "stream.chunkDone", args: [chunkRef], type: BOOL, loc }, then: [{ kind: "break", loc }], else_: null, loc, diff --git a/packages/compiler/src/frontend/lowering/lower-calls.ts b/packages/compiler/src/frontend/lowering/lower-calls.ts index c6e3d0c1e..fbaa6f4ed 100644 --- a/packages/compiler/src/frontend/lowering/lower-calls.ts +++ b/packages/compiler/src/frontend/lowering/lower-calls.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "./stable-names.js"; import { isForwardedTupleSpread, lowerForwardingApply } from "./typed-arguments.js"; import { guardNullProto, nullProtoRecordShape } from "./null-prototype.js"; import { lowerDynStreamMemberCall } from "./dyn-streams.js"; @@ -44,6 +45,7 @@ import { errorToStringCall } from "./error-methods.js"; import { lowerClassPrototypeAssign, lowerClassPrototypeDescriptors } from "./class-prototypes.js"; import { BYTES_ELEMENT_NAME, + BYTES_U8, BIGINT_T, BOOL, CAUGHT, @@ -52,6 +54,7 @@ import { F64, type IrExpr, type IrFunction, + type IrLibFn, type IrLocal, type IrParam, type IrStmt, @@ -75,6 +78,7 @@ import { } from "../../ir/ir.js"; import { lowerProtocolMethodCall } from "./class-protocol-dispatch.js"; import { isJsSourceFile, locOf, requireSpecOf } from "../program.js"; +import { isPackageShimFile, isShimIntrinsicName } from "../package-shims.js"; import { lowerJsonRequireCall } from "./json-require.js"; import { lowerAssertInstanceCall } from "./assert-instances.js"; import { @@ -141,7 +145,7 @@ import { lowerCryptoHashMethodCall, lowerPromisifiedCryptoCall, } from "./builtins/crypto.js"; -import { lowerErrorIsErrorCall } from "./builtins/errors.js"; +import { lowerErrorCaptureStackTraceCall, lowerErrorIsErrorCall } from "./builtins/errors.js"; import { lowerPromisifiedDnsCall } from "./lower-dgram.js"; import { lowerDisposableStackUseCall } from "./builtins/disposable-stack.js"; import { @@ -172,6 +176,7 @@ import { stringWrapperToString, symbolFieldInfo, templateRawTextOf, + primitiveCtorClosure, } from "./lower-exprs.js"; import { isSafeToDiscard } from "./expressions/evaluation-safety.js"; import { tryLowerExpression } from "./expressions/try-lower-expression.js"; @@ -199,6 +204,11 @@ import { import { classCallbackCall, isClassCallback } from "./class-callbacks.js"; import { emitterRooted, lowerEmitterMethodCall } from "./lower-event-emitter.js"; import { eventTargetApiMethod, lowerEventTargetMethodCall } from "./lower-event-target.js"; +import { + dateRootOf, + isDatePrototypeMethod, + lowerInheritedDateMethodCall, +} from "./builtins/date-classes.js"; import { lowerConsoleInstanceCall, lowerConsoleMethodCall, @@ -285,6 +295,12 @@ export function lowerCall(lowerer: Lowerer, expr: ts.CallExpression): IrExpr { const codeGeneration = codeGenerationCalleeOf(lowerer, expr.expression); if (codeGeneration !== null) return lowerCodeGenerationCall(lowerer, expr, codeGeneration); } + // A package shim's runtime intrinsic (a bodiless `declare function` + // named scriptcUnixDgram* in a shipped shim): a direct runtime call. + if (ts.isIdentifier(expr.expression) && isShimIntrinsicName(expr.expression.text)) { + const intrinsic = lowerShimIntrinsicCall(lowerer, expr, expr.expression, loc); + if (intrinsic) return intrinsic; + } // Inline require() of a program module (cjs-inline-require.ts): a // member call over its export table resolves like a binding's member // call after the module's %init at this position; the require itself @@ -1542,9 +1558,10 @@ export function lowerCall(lowerer: Lowerer, expr: ts.CallExpression): IrExpr { lowerer.fenceStaticReadableStreamMember(expr.expression, "call") ?? lowerDisposableStackUseCall(lowerer, expr, expr.expression) ?? lowerer.lowerStdlibMethodCall(expr, expr.expression) ?? - // crypto.getRandomValues on the WebCrypto global (untyped in - // fallback builds, so before the dyn receiver path) or webcrypto. - lowerWebCryptoGetRandomValues(lowerer, expr, expr.expression) ?? + // crypto.getRandomValues / randomUUID on the WebCrypto global + // (untyped in fallback builds, so before the dyn receiver path) or + // webcrypto. + lowerWebCryptoMethodCall(lowerer, expr, expr.expression) ?? // Dyn receivers (JSON.parse-derived `unknown`/`any` values) — lowerDynReceiverMethodCall(lowerer, expr, expr.expression) ?? @@ -1554,6 +1571,7 @@ export function lowerCall(lowerer: Lowerer, expr: ts.CallExpression): IrExpr { lowerer.lowerFilterNarrowCall(expr, expr.expression) ?? lowerArrayIsArrayCall(lowerer, expr, expr.expression) ?? lowerErrorIsErrorCall(lowerer, expr, expr.expression) ?? + lowerErrorCaptureStackTraceCall(lowerer, expr, expr.expression) ?? lowerBigIntMethodCall(lowerer, expr, expr.expression) ?? lowerSymbolStaticCall(lowerer, expr, expr.expression) ?? lowerSymbolMethodCall(lowerer, expr, expr.expression) ?? @@ -1610,7 +1628,16 @@ export function lowerCall(lowerer: Lowerer, expr: ts.CallExpression): IrExpr { } const accessorTarget = lowerer.fieldTarget(expr.expression); if (accessorTarget?.container === "accessor") { - const callee = lowerer.fieldGetExpr(accessorTarget, locOf(expr.expression), expr.expression); + let callee = lowerer.fieldGetExpr(accessorTarget, locOf(expr.expression), expr.expression); + // A getter returning a callable class instance (chalk's + // `chalk.red("x")`): call through its `%call` field. + if (callee.type.kind === "object") { + const direct = callableInstanceStringCall(lowerer, expr, callee, locOf(expr)); + if (direct) return direct; + callee = lowerer.hybridCallUnwrap(callee); + if (callee.type.kind === "func") + return lowerCallThroughValue(lowerer, expr, callee, locOf(expr)); + } if (callee.type.kind === "func") { const args = completeFuncValueArgs(lowerer, expr, callee.type, locOf(expr)); return { kind: "callValue", callee, args, type: callee.type.ret, loc: locOf(expr) }; @@ -1862,7 +1889,55 @@ export function lowerCall(lowerer: Lowerer, expr: ts.CallExpression): IrExpr { // a non-func IR type was already rejected while lowering the callee. // HYBRID (function-with-properties) values call through their %call slot. let callee = lowerer.lowerExpr(expr.expression); - if (callee.type.kind === "record") callee = lowerer.hybridCallUnwrap(callee); + { + const direct = callableInstanceStringCall(lowerer, expr, callee, loc); + if (direct) return direct; + } + if (callee.type.kind === "record" || callee.type.kind === "object") + callee = lowerer.hybridCallUnwrap(callee); + return lowerCallThroughValue(lowerer, expr, callee, loc); +} + +/** A callable class instance called with one string: its `%call1` method + * when the class has one (the chalk shim's typed fast path), skipping the + * variadic closure's checked-dynamic arguments. */ +function callableInstanceStringCall( + lowerer: Lowerer, + expr: ts.CallExpression, + callee: IrExpr, + loc: SrcLoc, +): IrExpr | null { + if (callee.type.kind !== "object" || expr.arguments.nodes.length !== 1) return null; + const arg = expr.arguments.nodes[0]!; + if (ts.isSpreadElement(arg)) return null; + const info = lowerer.classes.get(callee.type.className); + if (info === undefined || !info.fields.has("%call") || !lowerer.findMethodOn(info, "%call1")) + return null; + const value = lowerer.lowerExpr(arg); + if (value.type.kind === "string") + return lowerer.accessorCall(callee.type.className, "%call1", callee, [value], STRING, loc); + // Any other argument (a number behind a cast): the variadic closure, + // through the checked-dynamic call as lowerCallThroughValue would. + const closure = lowerer.hybridCallUnwrap(callee); + if (closure.type.kind !== "func") return null; + return { + kind: "dynCall", + callee: { kind: "dynFrom", value: closure, type: DYN, loc }, + calleeName: ts.isIdentifier(expr.expression) ? expr.expression.text : "value", + args: [lowerer.coerceToExpected(value, DYN)], + type: DYN, + loc, + }; +} + +/** A call through an evaluated callee value: checked-dynamic callees, + * function unions, typed-rest and runtime-arity closures. */ +function lowerCallThroughValue( + lowerer: Lowerer, + expr: ts.CallExpression, + callee: IrExpr, + loc: SrcLoc, +): IrExpr { // A CHECKED-DYNAMIC callee — `fn(a, b)` where fn is an implicit-any // JS binding (the mustCall body's `fn(...args)`), a dyn capture, or a // keyed read off a dyn value: the dynCall boundary. Arguments convert @@ -2094,7 +2169,7 @@ function lowerOptionalNumberDefault( const key = `number.optionalDefault:${widened.unionId}:${dflt}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = `%number.optionalDefault.${lowerer.valueHelpers.size}`; + helper = keyedHelperName(lowerer, "%number.optionalDefault", key); lowerer.valueHelpers.set(key, helper); const input = varRef("value.0", widened, loc); lowerer.liftedFns.push({ @@ -2203,7 +2278,7 @@ function primitiveConversionHandler( const key = `then.${name}:${typeKey(inner)}`; let fnName = lowerer.arrHofHelpers.get(key); if (fnName === undefined) { - fnName = `%then.${name}.${lowerer.arrHofHelpers.size}`; + fnName = keyedHelperName(lowerer, `%then.${name}`, key); lowerer.arrHofHelpers.set(key, fnName); const value = varRef("v.0", inner, loc); let body: IrExpr; @@ -2372,7 +2447,7 @@ function lowerBigIntConstructorValue(lowerer: Lowerer, arg: IrExpr, loc: SrcLoc) const key = `bigint.scalar:${unionId}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = `%bigint.scalar.${lowerer.valueHelpers.size}`; + helper = keyedHelperName(lowerer, "%bigint.scalar", key); lowerer.valueHelpers.set(key, helper); const value = varRef("value.0", arg.type, loc); const body: IrStmt[] = []; @@ -3234,7 +3309,7 @@ function lowerScalarUnionNumber( const key = `number.scalar:${arg.type.unionId}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = `%number.scalar.${lowerer.valueHelpers.size}`; + helper = keyedHelperName(lowerer, "%number.scalar", key); lowerer.valueHelpers.set(key, helper); const value = varRef("value.0", arg.type, loc); const nan: IrExpr = { @@ -3279,7 +3354,7 @@ function lowerOptionalStringNumber( const key = `${label}.optionalString:${arg.type.unionId}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = `%${label}.optionalString.${lowerer.valueHelpers.size}`; + helper = keyedHelperName(lowerer, `%${label}.optionalString`, key); lowerer.valueHelpers.set(key, helper); const value = varRef("value.0", arg.type, loc); lowerer.liftedFns.push({ @@ -3727,6 +3802,18 @@ function lowerDynReceiverMethodCall( // IS Node's semantics for every possible dyn value. Shared names would // need a receiver-kind dispatch — they keep the fence. if (DYN_STRING_ONLY_METHODS.has(access.name.text) && !ownCallable) { + // An object-typed receiver the member is missing from (a JavaScript + // module object whose members are assigned in a function body, + // `common.repeat(" ", n)`) holds a string or an object with that + // member: dispatch on the receiver's runtime kind. + if ( + !checkerUntyped && + (lowerer.typeOf(access).flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) !== 0 && + !call.questionDotToken && + !access.questionDotToken && + !call.arguments.nodes.some(ts.isSpreadElement) + ) + return lowerStringOrMemberCall(lowerer, call, access, recv); const checked = (): IrExpr => dynStringReceiver(lowerer, recv, access); return ( lowerRegexMethodCall(lowerer, call, access, checked) ?? @@ -3755,7 +3842,14 @@ function lowerDynReceiverMethodCall( } // The argument is a radix for bigint and an encoding for Buffer. // Preserve its runtime value so receiver dispatch can choose correctly. - if (access.name.text === "toString" && call.arguments.nodes.length <= 1) { + // An authored own `toString` member (zod's `errorUtil.toString`, which + // answers string | undefined) is an ordinary method call instead. + if ( + access.name.text === "toString" && + call.arguments.nodes.length <= 1 && + !ownCallable && + !(checkerUntyped && jsAssignsOwnToString(lowerer, access.expression)) + ) { const argument = call.arguments.nodes[0]; return { kind: "libCall", @@ -3865,12 +3959,22 @@ function lowerDynReceiverMethodCall( // The same holds when only the MEMBER is checker-untyped: TypeScript // importing chalk's JavaScript source types the default export as a // plain function, so `chalk.bold` reads as `any` on a typed receiver. + const ownToString = + access.name.text === "toString" && + checkerUntyped && + jsAssignsOwnToString(lowerer, access.expression); const stringOnlyName = (checkerUntyped || (lowerer.typeOf(access).flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) !== 0) && !ownCallable && DYN_STRING_PROTO_ONLY_NAMES.has(access.name.text); - if (DYN_PROTO_METHOD_NAMES.has(access.name.text) && !ownCallable && !stringOnlyName) return null; + if ( + DYN_PROTO_METHOD_NAMES.has(access.name.text) && + !ownCallable && + !ownToString && + !stringOnlyName + ) + return null; // Optional forms (`obj.cb?.()`, `obj?.cb()`) belong to the chain // machinery's short-circuit semantics — not modeled here yet. if (call.questionDotToken || access.questionDotToken) return null; @@ -3935,6 +4039,98 @@ function lowerDynReceiverMethodCall( }; } +/** `value.name(...args)` on a dyn receiver that may be a string or an + * object: a string runs the String.prototype lowering, any other value + * calls its member. The member is read before the arguments are + * evaluated, and the arguments are evaluated once for either branch. */ +function lowerStringOrMemberCall( + lowerer: Lowerer, + call: ts.CallExpression, + access: ts.PropertyAccessExpression, + recv: IrExpr, +): IrExpr { + const loc = locOf(call); + const receiverLocal = lowerer.declareHiddenLocal("%dynCallReceiver", DYN); + const receiver = varRef(receiverLocal.id, DYN, loc); + const isString: IrExpr = { kind: "dynTest", test: "string", value: receiver, type: BOOL, loc }; + const calleeLocal = lowerer.declareHiddenLocal("%dynCallCallee", DYN); + const callee = varRef(calleeLocal.id, DYN, loc); + const stmts: IrStmt[] = [ + { kind: "varDecl", localId: receiverLocal.id, init: recv, loc }, + { + kind: "varDecl", + localId: calleeLocal.id, + init: { + kind: "ternary", + cond: isString, + then: dynUndefinedExpr(loc), + else_: { + kind: "dynKeyGet", + key: { kind: "strLit", value: access.name.text, type: STRING, loc: locOf(access) }, + value: receiver, + type: DYN, + loc: locOf(access), + }, + type: DYN, + loc, + }, + loc, + }, + ]; + const args = call.arguments.nodes.map((node) => { + const value = lowerer.lowerExpr(node); + const local = lowerer.declareHiddenLocal("%dynCallArg", value.type); + stmts.push({ kind: "varDecl", localId: local.id, init: value, loc: value.loc }); + return { node, value: varRef(local.id, value.type, value.loc) }; + }); + // String.prototype methods ignore arguments past the ones they read. + const arity = DYN_STRING_ONLY_ARITY[access.name.text] ?? call.arguments.nodes.length; + const stringReceiver = (): IrExpr => ({ kind: "dynCheck", value: receiver, type: STRING, loc }); + const lowerString = (): IrExpr | null => + (call.arguments.nodes.length <= arity + ? lowerRegexMethodCall(lowerer, call, access, stringReceiver) + : null) ?? + lowerStringMethodCall( + lowerer, + call, + access, + stringReceiver, + call.arguments.nodes.slice(0, arity), + ); + const stringCall = lowerer.withExpressionOverrides(args, lowerString); + const memberCall: IrExpr = { + kind: "dynCall", + callee, + receiver, + calleeName: ts.getTextOfNode(access), + args: args.map((arg) => lowerer.coerceToExpected(arg.value, DYN)), + type: DYN, + loc, + }; + return { + kind: "seqExpr", + stmts, + result: { + kind: "ternary", + cond: isString, + then: stringCall + ? lowerer.coerceToExpected(stringCall, DYN) + : nodeThrowExpr( + 0, + "SC1090", + `method calls like '${ts.getTextOfNode(access)}' on a string are not supported yet [SC1090 at ${ts.getSourceFileOfNode(call).fileName}:${ts.getLineAndCharacterOfPosition(ts.getSourceFileOfNode(call), ts.tokenStartOfNode(call)).line + 1}]`, + DYN, + loc, + ), + else_: memberCall, + type: DYN, + loc, + }, + type: DYN, + loc, + }; +} + /** Prototype method names of the checked-dynamic tree-representable kinds (String, Array, * Object, Function, Number prototypes): a dyn receiver call on one of * these could be a REAL method on a real value, which a stored-member @@ -4205,6 +4401,9 @@ const DYN_DISPATCH_METHODS = new Set([ "additionalHeaders", "altsvc", "origin", + // FinalizationRegistry's methods (scr_finalization_registry_new). + "register", + "unregister", // Worker and MessagePort methods use the owning context's handle adapter. "postMessage", "terminate", @@ -4225,6 +4424,21 @@ export function lowerDynDispatchMethodCall( lowerer.chainBlocked(call, access) ) return null; + // readable.compose lowers its stages from their syntax, so it needs the + // stream's class: a stream a JavaScript function returns untyped has none. + if (method === "compose") { + const recvT = lowerer.mapTypeOf(lowerer.typeOf(access.expression)); + if ( + recvT?.kind === "object" && + streamSidesOf(lowerer, lowerer.classes.get(recvT.className)) !== null + ) { + lowerer.noLowering( + "readable.compose on a stream held as a checked-dynamic value", + call, + "type the stream where it comes from, such as a JSDoc @returns {Readable} on the function that returns it", + ); + } + } if (call.arguments.nodes.some((arg) => ts.isSpreadElement(arg))) { const loc = locOf(call); const local = lowerer.declareHiddenLocal("%spreadReceiver", DYN); @@ -4341,7 +4555,25 @@ export function lowerDynDispatchMethodCall( } } } + // `String`, `Number` or `Boolean` as the callback of an array method + // (`values.map(String)` over an unknown array): the method calls it with + // each element, whatever its type, and cannot observe which function + // value it received, so it gets the constructor's form that converts any + // argument rather than the string-input form typed code stores. + const arrayCallbackReceiver = + ARRAY_CALLBACK_METHODS.has(method) && + lowerer.checker.isArrayType(lowerer.typeOf(access.expression)); const args = call.arguments.nodes.map((arg, i) => { + const primitive = + i === 0 && arrayCallbackReceiver && ts.isIdentifier(arg) + ? stdlibGlobalNameOf(lowerer, arg) + : null; + if (primitive === "String" || primitive === "Number" || primitive === "Boolean") + return lowerer.coerceInto( + arg, + primitiveCtorClosure(lowerer, primitive, locOf(arg), true), + DYN, + ); if (i === 0 && predicate) return lowerer.coerceInto(arg, predicate, DYN); const undefinedArg = lowerStaticallyUndefinedArgument(lowerer, arg); return undefinedArg @@ -4359,6 +4591,21 @@ export function lowerDynDispatchMethodCall( }; } +/** Array.prototype methods whose first argument is a callback they call + * with the elements. */ +const ARRAY_CALLBACK_METHODS = new Set([ + "map", + "filter", + "forEach", + "some", + "every", + "find", + "findIndex", + "findLast", + "findLastIndex", + "flatMap", +]); + /** Every String.prototype method name a typed or dyn string lowering * answers. */ function isStringMethodName(name: string): boolean { @@ -4372,6 +4619,29 @@ function isStringMethodName(name: string): boolean { ); } +/** How many arguments each DYN_STRING_ONLY_METHODS method reads. */ +const DYN_STRING_ONLY_ARITY: Readonly> = { + charCodeAt: 1, + charAt: 1, + startsWith: 2, + endsWith: 2, + substring: 2, + repeat: 1, + trim: 0, + trimStart: 0, + trimEnd: 0, + split: 2, + padStart: 2, + padEnd: 2, + toLowerCase: 0, + toUpperCase: 0, + replace: 2, + replaceAll: 2, + match: 1, + matchAll: 1, + search: 1, +}; + /** STR_METHODS ∪ the regex-form names, MINUS everything Array (or any * other dyn kind's prototype) also declares. */ const DYN_STRING_ONLY_METHODS = new Set([ @@ -4706,7 +4976,7 @@ function lowerDefaultToStringCall( const key = `objToStr:${typeKey(recv.type)}${missing ? `:${missing}` : ""}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = `%obj.tostr.${lowerer.valueHelpers.size}`; + helper = keyedHelperName(lowerer, "%obj.tostr", key); lowerer.valueHelpers.set(key, helper); const o = varRef("o.0", recv.type, loc); lowerer.liftedFns.push({ @@ -5393,7 +5663,7 @@ function loweredTemplateStrings( const site = lowerer.globalsList.length; const globalId = `%g.templateStrings.${site}`; const readyId = `%g.templateStringsReady.${site}`; - getter = `%templateStrings.get.${lowerer.valueHelpers.size}`; + getter = keyedHelperName(lowerer, "%templateStrings.get", key); lowerer.valueHelpers.set(key, getter); lowerer.globalsList.push( { id: globalId, name: "%templateStrings", type, mutable: true }, @@ -5574,7 +5844,7 @@ export function lowerPromiseMethodCall( // IS the spec's identity/thrower/no-op substitution for all three // members. An argument expression, when present, is undefined/null // by construction — nothing to evaluate. - const fnName = `%fn${lowerer.lambdaCounter++}_${member}pass`; + const fnName = lowerer.closureName(loc, `_${member}pass`); const funcType: IrType & { kind: "func" } = { kind: "func", params: [promT], ret: promT }; const fnCtx = newFnCtx(true, null, funcType, inner); fnCtx.isAsync = true; @@ -5671,7 +5941,7 @@ export function lowerPromiseMethodCall( // Evaluate both callback expressions before the wrapper runs, in source order. const fulfilled = fulfilledAbsent ? null : boxHandler(fulfilledNode, true); const rejected = rejectedAbsent ? null : boxHandler(rejectedNode, false); - const fnName = `%fn${lowerer.lambdaCounter++}_then2`; + const fnName = lowerer.closureName(loc, "_then2"); const paramTypes: IrType[] = [ promT, ...(fulfilled ? [fulfilled.value.type] : []), @@ -5920,7 +6190,7 @@ export function lowerPromiseMethodCall( ); }; const resultT: IrType & { kind: "promise" } = { kind: "promise", inner: DYN }; - const fnName = `%fn${lowerer.lambdaCounter++}_then`; + const fnName = lowerer.closureName(loc, "_then"); const funcType: IrType & { kind: "func" } = { kind: "func", params: [promT, DYN], @@ -6006,7 +6276,21 @@ export function lowerPromiseMethodCall( `then handlers whose parameter is not the settled value's type (expected '${lowerer.fmt(inner)}', got '${lowerer.fmt(param)}')`, ); } - const resultT = lowerer.mapTypeOf(lowerer.typeOf(call)); + let resultT = lowerer.mapTypeOf(lowerer.typeOf(call)); + // JavaScript whose declared result type has no mapping (zod's + // `Promise.all(items).then((r) => ParseStatus.mergeArray(status, r))`, + // typed by a .d.ts union): the handler's value settles the promise as + // a checked-dynamic value, checked where it is used. + if ( + resultT?.kind !== "promise" && + isJsSourceFile(ts.getSourceFileOfNode(call)) && + cb.type.kind === "func" && + cb.type.ret.kind !== "promise" && + cb.type.ret.kind !== "void" && + (cb.type.ret.kind === "dyn" || lowerer.dynConvertible(cb.type.ret)) + ) { + resultT = { kind: "promise", inner: DYN }; + } if (resultT?.kind !== "promise") { lowerer.noLowering( "then with this handler's result type", @@ -6015,7 +6299,7 @@ export function lowerPromiseMethodCall( ); } const R = resultT.inner; - const fnName = `%fn${lowerer.lambdaCounter++}_then`; + const fnName = lowerer.closureName(loc, "_then"); const funcType: IrType & { kind: "func" } = { kind: "func", params: [promT, cb.type], @@ -6118,7 +6402,7 @@ export function lowerPromiseMethodCall( "finally callbacks with parameters or a return value (use () => { ... })", ); } - const fnName = `%fn${lowerer.lambdaCounter++}_finally`; + const fnName = lowerer.closureName(loc, "_finally"); const funcType: IrType & { kind: "func" } = { kind: "func", params: [promT, cb.type], @@ -6221,7 +6505,7 @@ export function lowerPromiseMethodCall( } if (cb.type.kind === "dyn") { const resultT: IrType & { kind: "promise" } = { kind: "promise", inner: DYN }; - const fnName = `%fn${lowerer.lambdaCounter++}_catchdyn`; + const fnName = lowerer.closureName(loc, "_catchdyn"); const funcType: IrType & { kind: "func" } = { kind: "func", params: [promT, DYN], @@ -6351,7 +6635,7 @@ export function lowerPromiseMethodCall( ); } const R = resultT.inner; - const fnName = `%fn${lowerer.lambdaCounter++}_catch`; + const fnName = lowerer.closureName(loc, "_catch"); const funcType: IrType & { kind: "func" } = { kind: "func", params: [promT], ret: resultT }; const fnCtx = newFnCtx(true, null, funcType, R); fnCtx.isAsync = true; @@ -6499,6 +6783,15 @@ export function lowerFilterNarrowCall( } const narrowed = outElem !== null && !typeEquals(outElem, elem); if (!narrowed && !isBooleanArg) return null; + // A written predicate (`(p): p is Cat => ...`, a guard function value) + // proves nothing at run time: the generic array HOF path filters the + // receiver's elements and converts the kept ones checked + // (filterResultElem). + if ( + !isBooleanArg && + ((!ts.isArrowFunction(argNode) && !ts.isFunctionExpression(argNode)) || argNode.type) + ) + return null; const annotateEscape = "keep the receiver's element type instead — annotate the callback's return ': boolean' " + @@ -6510,6 +6803,9 @@ export function lowerFilterNarrowCall( lowerer.badType(call, callT); // defensive: a narrowed non-union receiver } tag = lowerer.armTag(elem.unionId, outElem); + // Several kept arms: the generic path converts the kept elements to + // the narrower union (filterResultElem). + if (tag < 0 && !isBooleanArg) return null; if (tag < 0) { lowerer.unsupported( "SC1090", @@ -6531,25 +6827,8 @@ export function lowerFilterNarrowCall( return { kind: "call", callee: helper, args: [receiver], type: arrayOf(outElem ?? elem), loc }; } - // Inferred type predicate: inline function literal, NO return - // annotation (a written one is an unchecked assertion), and the - // checker reports a predicate over parameter 0. - if (!ts.isArrowFunction(argNode) && !ts.isFunctionExpression(argNode)) { - lowerer.unsupported( - "SC1090", - argNode, - `narrowing '.filter' through a callback VALUE ` + - `(only an inline callback whose predicate the checker inferred can re-tag — ${annotateEscape})`, - ); - } - if (argNode.type) { - lowerer.unsupported( - "SC1090", - argNode, - `narrowing '.filter' with a hand-written type predicate ` + - `(a written 'x is T' is an unchecked assertion nothing validates at runtime — ${annotateEscape})`, - ); - } + // An inferred type predicate: an inline function literal with no return + // annotation, over parameter 0 (written predicates returned above). // The receiver evaluates FIRST, in the enclosing function, like JS. const receiver = lowerer.lowerExpr(access.expression); const fnArg = lowerer.lowerExpr(argNode); @@ -6588,7 +6867,7 @@ function filterNarrowHelper( const key = `filterNarrow:${test}:${typeKey(elem)}:${typeKey(outElem)}`; const existing = lowerer.arrHofHelpers.get(key); if (existing) return existing; - const name = `%arr.filterNarrow.${lowerer.arrHofHelpers.size}`; + const name = keyedHelperName(lowerer, "%arr.filterNarrow", key); lowerer.arrHofHelpers.set(key, name); const arrT = arrayOf(elem); @@ -6834,7 +7113,7 @@ export function recordKeysArrayCall( const key = `obj.keys:${argIr.shapeId}:${typeKey(resultT)}`; let helper = lowerer.arrHofHelpers.get(key); if (!helper) { - helper = `%obj.keys.${lowerer.arrHofHelpers.size}`; + helper = keyedHelperName(lowerer, "%obj.keys", key); const ref: IrExpr = { kind: "varRef", localId: "r.0", type: argIr, loc }; const outRef: IrExpr = { kind: "varRef", localId: "out.0", type: resultT, loc }; lowerer.arrHofHelpers.set(key, helper); @@ -6904,7 +7183,7 @@ function recordHasOwnHelper(lowerer: Lowerer, shapeId: string, loc: SrcLoc): str const key = `obj.hasOwn:${shapeId}`; const existing = lowerer.arrHofHelpers.get(key); if (existing) return existing; - const helper = `%obj.hasOwn.${lowerer.arrHofHelpers.size}`; + const helper = keyedHelperName(lowerer, "%obj.hasOwn", key); lowerer.arrHofHelpers.set(key, helper); const shape = lowerer.shapes.get(shapeId)!; const recT: IrType = { kind: "record", shapeId }; @@ -6989,7 +7268,7 @@ function classAssignHelper( const key = `obj.assignClass:${className}:${srcShapeId}`; const existing = lowerer.arrHofHelpers.get(key); if (existing) return existing; - const helper = `%obj.assignClass.${lowerer.arrHofHelpers.size}`; + const helper = keyedHelperName(lowerer, "%obj.assignClass", key); lowerer.arrHofHelpers.set(key, helper); const sShape = lowerer.shapes.get(srcShapeId)!; const oT: IrType = { kind: "object", className }; @@ -7057,7 +7336,7 @@ function recordAssignHelper( const key = `obj.assign:${targetShapeId}:${srcShapeId}`; const existing = lowerer.arrHofHelpers.get(key); if (existing) return existing; - const helper = `%obj.assign.${lowerer.arrHofHelpers.size}`; + const helper = keyedHelperName(lowerer, "%obj.assign", key); lowerer.arrHofHelpers.set(key, helper); const sShape = lowerer.shapes.get(srcShapeId)!; const tShape = lowerer.shapes.get(targetShapeId)!; @@ -7270,6 +7549,35 @@ function lowerObjectStaticCall( if (call.questionDotToken || access.questionDotToken) return null; if (!lowerer.isStdlibGlobal(access.expression, "Object")) return null; const member = access.name.text; + // `Object.getOwnPropertyDescriptor(Error, "stackTraceLimit")` (Effect's + // isStackTraceLimitWritable): Error's own writable, enumerable, + // configurable data property holding the current limit. The interned + // Error value models no other statics (builtinGlobalValueAt). + const [first, second] = call.arguments.nodes; + if ( + member === "getOwnPropertyDescriptor" && + call.arguments.nodes.length === 2 && + lowerer.isStdlibGlobal(first!, "Error") && + ts.isStringLiteralLike(second!) && + second.text === "stackTraceLimit" + ) { + const loc = locOf(call); + const dyn = (value: IrExpr): IrExpr => ({ kind: "dynFrom", value, type: DYN, loc }); + const yes = dyn({ kind: "boolLit", value: true, type: BOOL, loc }); + const limit: IrExpr = { kind: "libCall", fn: "error.stackLimitGet", args: [], type: F64, loc }; + return { + kind: "dynObjLit", + fields: [ + { key: { kind: "strLit", value: "value", type: STRING, loc }, value: dyn(limit) }, + ...["writable", "enumerable", "configurable"].map((key) => ({ + key: { kind: "strLit" as const, value: key, type: STRING, loc }, + value: yes, + })), + ], + type: DYN, + loc, + }; + } if ( (member === "getOwnPropertyNames" || member === "getOwnPropertySymbols" || @@ -8525,7 +8833,7 @@ function lowerObjectStaticCall( const key = `obj.${member}:${argIr.shapeId}:${typeKey(resultT)}`; let helper = lowerer.arrHofHelpers.get(key); if (!helper) { - helper = `%obj.${member}.${lowerer.arrHofHelpers.size}`; + helper = keyedHelperName(lowerer, `%obj.${member}`, key); const recT = argIr; const ref: IrExpr = { kind: "varRef", localId: "r.0", type: recT, loc }; const outRef: IrExpr = { kind: "varRef", localId: "out.0", type: resultT, loc }; @@ -8994,7 +9302,16 @@ export function lowerRecordFieldCall( // A HYBRID (function-with-properties) field is callable through its // reserved %call slot — `colors.blue("x")` where blue also carries // `.bold` (the chalk shape). - if (callee.type.kind === "record") callee = lowerer.hybridCallUnwrap(callee); + if (callee.type.kind === "object" && !init) { + const direct = callableInstanceStringCall(lowerer, call, callee, loc); + if (direct) return direct; + // Other argument counts call the %call closure through its value, as + // a call on the builder itself does (`theme.error("a", "b")`). + const closure = lowerer.hybridCallUnwrap(callee); + if (closure !== callee) return lowerCallThroughValue(lowerer, call, closure, loc); + } + if (callee.type.kind === "record" || callee.type.kind === "object") + callee = lowerer.hybridCallUnwrap(callee); // Inferred JavaScript option records can retain checked callables in // fields even when the checker only describes those members as any. // TypeScript reaches here for callable library types that are checked @@ -9161,7 +9478,7 @@ function lowerInlineArrowBind( const length = firstDefault < 0 ? arrow.parameters.nodes.length : firstDefault; const key = `arrow.bind:${typeKey(type)}:${length}`; const existing = lowerer.arrHofHelpers.get(key); - const name = existing ?? `%arrow.bind.${lowerer.arrHofHelpers.size}`; + const name = existing ?? keyedHelperName(lowerer, "%arrow.bind", key); if (!existing) { lowerer.arrHofHelpers.set(key, name); lowerer.freshClosureAdapters.add(name); @@ -9656,7 +9973,9 @@ export function lowerObjectMethodCall( if ( info && !found && - (STREAM_API_MEMBERS.has(access.name.text) || STREAM_OPERATORS.has(access.name.text)) && + (STREAM_API_MEMBERS.has(access.name.text) || + STREAM_OPERATORS.has(access.name.text) || + access.name.text === "compose") && streamSidesOf(lowerer, info) !== null ) { const stream = lowerStreamMethodCall(lowerer, call, access, info); @@ -9681,6 +10000,10 @@ export function lowerObjectMethodCall( if (info && !found && eventTargetApiMethod(info, access.name.text)) { return lowerEventTargetMethodCall(lowerer, call, access, info, lowerReceiver()); } + // The Date methods a class declared `extends Date` does not declare. + if (info && !found && dateRootOf(info) && isDatePrototypeMethod(access.name.text)) { + return lowerInheritedDateMethodCall(lowerer, call, access.name.text, info, lowerReceiver()); + } // GENERIC methods (own type parameters) never enter the methods table: // they monomorphize per call site and dispatch statically // (lowerClassGenericMethodCall has the exactness rules). @@ -10090,7 +10413,7 @@ function lowerUnionObjectDynFieldCall( const receiverRef = varRef(receiverLocal.id, receiverT, loc); let helper = lowerer.unionCallHelpers.get(key); if (!helper) { - helper = `%union.call.${lowerer.unionCallHelpers.size}`; + helper = keyedHelperName(lowerer, "%union.call", key); lowerer.unionCallHelpers.set(key, helper); const receiverRef = varRef("this.0", receiverT, loc); const branch = (plan: (typeof plans)[number]): IrStmt[] => { @@ -10183,7 +10506,7 @@ function unionObjectMethodHelper( const key = `${receiverT.unionId}:${method}:${shapes.map((shape) => `${shape.mode}:${typeKey(shape.type)}`).join(",")}:${typeKey(resultT)}`; const existing = lowerer.unionCallHelpers.get(key); if (existing) return existing; - const name = `%union.call.${lowerer.unionCallHelpers.size}`; + const name = keyedHelperName(lowerer, "%union.call", key); lowerer.unionCallHelpers.set(key, name); // A probe that catches a refusal while the body lowers must not leave // the name registered for a helper that was never emitted. @@ -10377,7 +10700,7 @@ export function lowerStaticNumberGlobal( const key = `parseInt.optional:${unionT.unionId}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = `%parseInt.optional.${lowerer.valueHelpers.size}`; + helper = keyedHelperName(lowerer, "%parseInt.optional", key); lowerer.valueHelpers.set(key, helper); const value: IrExpr = { kind: "varRef", localId: "value.0", type: unionT, loc }; const radixRef: IrExpr = { kind: "varRef", localId: "radix.0", type: F64, loc }; @@ -10469,6 +10792,17 @@ export function lowerStaticNumberGlobal( : lowerer.lowerExprExpecting(args[0]!, STRING); return { kind: "libCall", fn: "num.parseInt", args: [s, radix], type: F64, loc }; } + // parseFloat takes one argument; Node ignores the rest after evaluating + // them (`parseFloat(text, 10)`). Literal and identifier extras have + // nothing to evaluate. + if ( + name === "parseFloat" && + args.length > 1 && + args + .slice(1) + .every((arg) => ts.isNumericLiteral(arg) || ts.isStringLiteral(arg) || ts.isIdentifier(arg)) + ) + return lowerStaticNumberGlobal(lowerer, name, call, args.slice(0, 1), loc); // STATIC parseFloat over string arguments — parseInt's sibling // (num.parseFloat is ECMA 19.2.4's decimal-literal prefix parse in // scr_string.c). Other argument types retain their native coercion @@ -10503,20 +10837,40 @@ export function lowerStaticNumberGlobal( return null; } -/** `crypto.getRandomValues(view)` on the WebCrypto global or webcrypto. */ -function lowerWebCryptoGetRandomValues( +/** `crypto.getRandomValues(view)` and `crypto.randomUUID()` on the + * WebCrypto global or webcrypto. Other argument counts (JavaScript only) + * invoke the dynamic object's method, which ignores extra arguments and + * throws Node's missing-argument TypeError. */ +function lowerWebCryptoMethodCall( lowerer: Lowerer, call: ts.CallExpression, access: ts.PropertyAccessExpression, ): IrExpr | null { + const member = access.name.text; if ( - access.name.text !== "getRandomValues" || + (member !== "getRandomValues" && member !== "randomUUID") || call.questionDotToken || access.questionDotToken || !isWebCryptoReceiver(lowerer, access.expression) ) return null; - return lowerCryptoGetRandomValues(lowerer, call); + const args = call.arguments.nodes; + if (member === "getRandomValues" && args.length === 1) { + return lowerCryptoGetRandomValues(lowerer, call); + } + if (member === "randomUUID" && args.length === 0) { + return { kind: "libCall", fn: "crypto.randomUUID", args: [], type: STRING, loc: locOf(call) }; + } + if (args.some(ts.isSpreadElement)) return null; + return { + kind: "dynInvoke", + recv: lowerer.lowerExprExpecting(access.expression, DYN), + method: member, + calleeName: v8CalleeText(access), + args: args.map((arg) => lowerer.lowerExprExpecting(arg, DYN)), + type: DYN, + loc: locOf(call), + }; } /** A then handler's promise-armed result (`.then(() => cached ?? load())` @@ -10717,3 +11071,124 @@ function fenceClassCopyIntoFreshObject( `Object.assign copying a '${lowerer.fmt(rawSource.type)}' instance into a fresh object typed as the class (the copy is a plain object holding the instance's own fields, not an instance — build the object literal from the fields you need)`, ); } + +/** True when an untyped JavaScript receiver names a binding whose declaring + * file assigns it an own `toString` (the TypeScript namespace downlevel + * `errorUtil.toString = (message) => ...` in zod): its calls answer what + * that function returns, not Object.prototype.toString's string. */ +function jsAssignsOwnToString(lowerer: Lowerer, receiver: ts.Expression): boolean { + if (!ts.isIdentifier(receiver)) return false; + const decl = bindingDeclaration(lowerer, receiver); + if (decl === undefined) return false; + const sf = ts.getSourceFileOfNode(decl); + if (!isJsSourceFile(sf)) return false; + let targets = lowerer.ownToStringTargets.get(sf); + if (targets === undefined) { + targets = ownToStringTargets(lowerer, sf); + lowerer.ownToStringTargets.set(sf, targets); + } + return targets.has(decl); +} + +const unparenthesized = (e: ts.Expression): ts.Expression => { + let out = e; + while (ts.isParenthesizedExpression(out)) out = out.expression; + return out; +}; + +/** The declaration of the binding an identifier names, through imports. */ +function bindingDeclaration(lowerer: Lowerer, id: ts.Identifier): ts.Node | undefined { + let sym = lowerer.checker.getSymbolAtLocation(id); + if (sym !== undefined && (sym.flags & ts.SymbolFlags.Alias) !== 0) + sym = lowerer.checker.getAliasedSymbol(sym); + return sym?.valueDeclaration ?? sym?.declarations?.[0]; +} + +/** The declarations of the bindings a file's assignments `x.toString = ...` + * (or `x["toString"] = ...`) give an own `toString`. An assignment through + * the parameter of an immediately called function counts for the binding + * the call passes (`(function (ns) { ns.toString = f; })(ns || (ns = {}))`). */ +function ownToStringTargets(lowerer: Lowerer, sf: ts.SourceFile): Set { + const targets = new Set(); + const visit = (node: ts.Node): void => { + if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken) { + const left = unparenthesized(node.left); + const named = + (ts.isPropertyAccessExpression(left) && left.name.text === "toString") || + (ts.isElementAccessExpression(left) && + ts.isStringLiteralLike(left.argumentExpression) && + left.argumentExpression.text === "toString"); + const target = named + ? unparenthesized( + (left as ts.PropertyAccessExpression | ts.ElementAccessExpression).expression, + ) + : undefined; + if (target !== undefined && ts.isIdentifier(target)) { + const decl = bindingDeclaration(lowerer, target); + if (decl !== undefined) { + targets.add(decl); + const passed = iifeArgumentDeclaration(lowerer, decl); + if (passed !== undefined) targets.add(passed); + } + } + } + ts.forEachChild(node, visit); + }; + visit(sf); + return targets; +} + +/** For a parameter of an immediately called function, the declaration of + * the binding its argument names: `x`, `x || (x = {})` or `(x = {})`. */ +function iifeArgumentDeclaration(lowerer: Lowerer, param: ts.Node): ts.Node | undefined { + if (!ts.isParameter(param)) return undefined; + const fn = param.parent; + if (!ts.isFunctionExpression(fn) && !ts.isArrowFunction(fn)) return undefined; + let callee: ts.Node = fn; + while (ts.isParenthesizedExpression(callee.parent)) callee = callee.parent; + const call = callee.parent; + if (!ts.isCallExpression(call) || call.expression !== callee) return undefined; + const index = fn.parameters.nodes.indexOf(param); + let arg = index < 0 ? undefined : call.arguments.nodes[index]; + if (arg === undefined) return undefined; + arg = unparenthesized(arg); + if (ts.isBinaryExpression(arg) && arg.operatorToken.kind === ts.SyntaxKind.BarBarToken) + arg = unparenthesized(arg.left); + if (ts.isBinaryExpression(arg) && arg.operatorToken.kind === ts.SyntaxKind.EqualsToken) + arg = unparenthesized(arg.left); + return ts.isIdentifier(arg) ? bindingDeclaration(lowerer, arg) : undefined; +} + +/** The runtime calls package shims declare as bodiless functions. */ +const SHIM_INTRINSICS: ReadonlyMap = new Map< + string, + { fn: IrLibFn; args: IrType[]; ret: IrType } +>([ + ["scriptcUnixDgramSocket", { fn: "dgram.unixSocket", args: [], ret: F64 }], + ["scriptcUnixDgramConnect", { fn: "dgram.unixConnect", args: [F64, STRING], ret: F64 }], + ["scriptcUnixDgramSend", { fn: "dgram.unixSend", args: [F64, BYTES_U8], ret: F64 }], + ["scriptcUnixDgramClose", { fn: "dgram.unixClose", args: [F64], ret: F64 }], +]); + +function lowerShimIntrinsicCall( + lowerer: Lowerer, + expr: ts.CallExpression, + callee: ts.Identifier, + loc: SrcLoc, +): IrExpr | null { + const intrinsic = SHIM_INTRINSICS.get(callee.text); + if (intrinsic === undefined) return null; + const decl = lowerer.checker.getSymbolAtLocation(callee)?.valueDeclaration; + if ( + decl === undefined || + !ts.isFunctionDeclaration(decl) || + decl.body || + !isPackageShimFile(ts.getSourceFileOfNode(decl).fileName) || + expr.arguments.nodes.length !== intrinsic.args.length + ) + return null; + const args = expr.arguments.nodes.map((arg, i) => + lowerer.lowerExprExpecting(arg, intrinsic.args[i]!), + ); + return { kind: "libCall", fn: intrinsic.fn, args, type: intrinsic.ret, loc }; +} diff --git a/packages/compiler/src/frontend/lowering/lower-classes.ts b/packages/compiler/src/frontend/lowering/lower-classes.ts index 790efe988..ba3fcba05 100644 --- a/packages/compiler/src/frontend/lowering/lower-classes.ts +++ b/packages/compiler/src/frontend/lowering/lower-classes.ts @@ -1,3 +1,12 @@ +import { + DATE_TIME_FIELD, + dateRootOf, + dateSuperCall, + isDatePrototypeMethod, + lowerDateSuperMethodCall, +} from "./builtins/date-classes.js"; +import { lowerDateStaticCall } from "./builtins/dates.js"; +import { keyedHelperName } from "./stable-names.js"; import { lowerValueReturningConstructorNew } from "./js-dynamic-objects.js"; import { adaptPromiseExecutor } from "./promise-executor-adapter.js"; import { dynUndefinedExpr, nodeThrowExpr, varRef } from "../../ir/build.js"; @@ -84,6 +93,7 @@ import { } from "./call-signatures.js"; import { omittedArgFor } from "./call-arguments.js"; import { + checkerTypeDescription, isGenericCallableMemberType, jsOpenObjectType, typeKey, @@ -123,6 +133,7 @@ import { STREAM_PROP_MEMBERS, STREAM_COMPLETION_CALLBACK_INDEX, UNDERSCORE_METHODS, + streamExtraCallbacks, lowerStreamNew, lowerStreamSuperCall, streamCtorShape, @@ -148,7 +159,7 @@ import { classSymbolKeyOfSymbol, symbolFieldDisplayName, } from "./symbol-fields.js"; -import { lowerHttpAgentNew, lowerHttpServerNew } from "./lower-server.js"; +import { lowerHttpAgentNew, lowerHttpServerNew, lowerTlsSocketNew } from "./lower-server.js"; import { ambientNsRootOf, ambientUndefReadType, @@ -174,6 +185,7 @@ import { constructionEscape } from "./construction-escapes.js"; import { checkedClassConstruction, checkedClassConstructionPacked } from "./class-construction.js"; import { initializeRuntimeStatics, hasRuntimeStatics } from "./class-runtime-statics.js"; import { reflectedClassStaticMethodValue } from "./class-method-values.js"; +import { identifierReadSymbol } from "./surfaces.js"; export function returnsOnlyThis(member: ts.MethodDeclaration): boolean { const body = member.body; @@ -564,6 +576,11 @@ export interface ClassInfo { * lower-event-target.ts over any class rooted here. Subclass structs * embed the runtime prefix. */ builtinEventTarget?: "target" | "event"; + /** A class declared `extends Date` (builtins/date-classes.ts): its first + * field is the hidden `%time` value, super() sets it with the Date + * constructor's rules, and the Date methods it does not declare lower + * over that value. Subclasses inherit the field. */ + extendsDate?: true; /** The synthetic LifetimeRegion class (@scriptc/experimental, * lifetime-regions.ts): its constructor is synthesized with the class, * and its methods lower at their call sites. */ @@ -1951,6 +1968,7 @@ export function collectClassShapeInner( : (computedBase?.classInfo ?? null); let genericBase: ts.ExpressionWithTypeArguments | undefined; let callableBase: ClassInfo["callableBase"]; + let extendsDate = false; let factoryBaseExpression: ts.Expression | undefined; const adoptCallableBase = (expression: ts.Expression): boolean => { if (familyMode || inst || mixin) return false; @@ -2151,6 +2169,11 @@ export function collectClassShapeInner( if (t && adoptCallableBase(t.expression)) continue; lowerer.unsupported("SC1090", clause, "extending computed expressions"); } + if (!familyMode && !inst && !mixin && lowerer.isStdlibGlobal(t.expression, "Date")) { + if (t.typeArguments?.nodes) lowerer.unsupported("SC1090", t, "extending generic classes"); + extendsDate = true; + continue; + } const symbol = lowerer.resolveValueSymbol(t.expression); // Extending a REBINDABLE decorated class (analysis already ran — // this collection is a class expression or a generic @@ -2404,7 +2427,8 @@ export function collectClassShapeInner( for (const member of decl.members.nodes) { if ( (functionLocalClass(decl) || checkedStatics) && - isJsSourceFile(ts.getSourceFileOfNode(decl)) && + (isJsSourceFile(ts.getSourceFileOfNode(decl)) || + (functionLocalClass(decl) && ts.isMethodDeclaration(member))) && (ts.isClassStaticBlockDeclaration(member) || ts .getModifiers(member) @@ -2724,11 +2748,11 @@ export function collectClassShapeInner( `overriding the stream member '${name}' (the runtime owns the stream surface)`, ); } - if (name === "_writev" || name === "_construct") { + if (name === "_writev" && !streamExtraCallbacks(streamBase.def.name).includes("writev")) { lowerer.unsupported( "SC1090", memberName, - `declaring '${name}' on a stream subclass (${name === "_writev" ? "batched writes are" : "deferred construction is"} not lowered — writes deliver one chunk at a time)`, + `declaring '_writev' on a ${streamBase.def.name.slice(1)} subclass (batched writes are supported on Writable and Duplex subclasses)`, ); } const accepted = streamCtorShape(streamBase.def.name).accepted; @@ -4350,7 +4374,8 @@ export function collectClassShapeInner( const ctorParams: ParamShape[] = ctor && !mixinForwarding ? lowerer.paramShapes(ctor.parameters.nodes) - : (base?.ctorParams ?? (callableBase ? [{ type: DYN, mode: "dynRest" }] : [])); + : (base?.ctorParams ?? + (callableBase || extendsDate ? [{ type: DYN, mode: "dynRest" }] : [])); if ( ctor && !mixinForwarding && @@ -4388,6 +4413,7 @@ export function collectClassShapeInner( // Redeclared INHERITED fields contribute no slot (their // initializers assign the prefix slot). fields: [ + ...(extendsDate ? [{ name: DATE_TIME_FIELD, type: DATE_T }] : []), ...(base?.def.fields ?? []), ...fieldOrder .filter((f) => f.redeclared !== true) @@ -4419,6 +4445,7 @@ export function collectClassShapeInner( base, ...(genericBase ? { genericBase } : {}), ...(callableBase ? { callableBase } : {}), + ...(extendsDate ? { extendsDate: true as const } : {}), ...(factoryBaseExpression ? { factoryBaseExpression } : {}), subclasses: [], throwingSetters, @@ -4663,7 +4690,25 @@ export function genericClassInstanceType( ); } const ordinal = gci.instances.size; - const name = `${gci.family.def.name}%${ordinal}`; + // The name does not take the checker type ids of the key: a literal + // argument is named by its text, another checker type by its + // description. Two keys that still describe alike number the later one. + const nameKey = + mapped.map(typeKey).join(",") + + (gci.literalSensitive.size > 0 + ? `@${gci.typeParams + .map((_, i) => + sensitive(i) + ? (literalText(i) ?? checkerTypeDescription(tsArgs[i]!, lowerer.typeCtx)) + : "*", + ) + .join(",")}` + : ""); + const prefix = `${gci.family.def.name}%`; + const taken = new Set([...gci.instances.values()].map((instance) => instance.name)); + let name = keyedHelperName(lowerer, prefix, nameKey, ""); + for (let n = 1; taken.has(name); n++) + name = keyedHelperName(lowerer, prefix, `${nameKey}#${n}`, ""); const entry: { name: string; info: ClassInfo | null; poisoned?: boolean } = { name, info: null }; gci.instances.set(key, entry); const bindings = new Map(); @@ -5647,6 +5692,15 @@ export function lowerStaticFieldRead( if (info.classDecorators?.valueGlobalId !== undefined) return null; const loc = locOf(expr); const found = findStaticOn(lowerer, info, expr.name.text); + // A Date static read as a value through a class declared `extends Date`: + // the statics lower only as calls. + if ( + !found && + dateRootOf(info) && + ["now", "parse", "UTC"].includes(expr.name.text) && + !(ts.isCallExpression(expr.parent) && expr.parent.expression === expr) + ) + lowerer.noLowering(`Date.${expr.name.text} read through a class that extends Date`, expr); if (hasRuntimeStatics(info) && !found?.field) return { kind: "dynKeyGet", @@ -5872,9 +5926,10 @@ export function lowerClassExpressionInfo( decoratorNodesOf(member).length || (!isJsSourceFile(ts.getSourceFileOfNode(expr)) && (ts.isClassStaticBlockDeclaration(member) || - ts - .getModifiers(member) - ?.some((modifier) => modifier.kind === ts.SyntaxKind.StaticKeyword))) || + (!ts.isMethodDeclaration(member) && + ts + .getModifiers(member) + ?.some((modifier) => modifier.kind === ts.SyntaxKind.StaticKeyword)))) || (ts.isMethodDeclaration(member) && member.typeParameters?.nodes.length), )) ) { @@ -5981,6 +6036,28 @@ export function lowerClassExpressionInfo( return info; } +/** True when a named class expression's body refers to the class value by + * its own name (`class Box { static of() { return new Box(); } }`, a + * shorthand property `{ Box }` included); type annotations naming it + * (`again(): Box`) do not count. */ +function classExpressionNamesItself(lowerer: Lowerer, expr: ts.ClassExpression): boolean { + const name = expr.name; + if (!name) return false; + const symbol = lowerer.checker.getSymbolAtLocation(name); + if (!symbol) return false; + let found = false; + for (const member of expr.members.nodes) { + ts.walkPreorder(member, (n) => { + if (found || ts.isTypeNode(n)) return "skip"; + if (ts.isIdentifier(n) && n.text === name.text && identifierReadSymbol(lowerer, n) === symbol) + found = true; + return undefined; + }); + if (found) return true; + } + return false; +} + /** `class {…}` in expression position: a class definition bound to no * statement — once the static side is a value, the expression IS the * definition plus a classRef over it. A DECORATED class expression @@ -5988,8 +6065,16 @@ export function lowerClassExpressionInfo( * mints a class at all: evaluating the expression IS the * ReferenceError, so it lowers to exactly that read — every evaluation * throws identically, which is why the once-evaluated restriction and - * the member fences don't apply. */ -export function lowerClassExpression(lowerer: Lowerer, expr: ts.ClassLikeDeclaration): IrExpr { + * the member fences don't apply. + * + * `binding` is the local of a function-local class declaration's name, + * declared without a value; the class value assigns it before the class's + * static members are defined (see initializeRuntimeStatics). */ +export function lowerClassExpression( + lowerer: Lowerer, + expr: ts.ClassLikeDeclaration, + binding?: IrLocal, +): IrExpr { if ( decoratorNodesOf(expr).length > 0 || expr.members.nodes.some((m) => decoratorNodesOf(m).length > 0) @@ -6005,6 +6090,41 @@ export function lowerClassExpression(lowerer: Lowerer, expr: ts.ClassLikeDeclara } } const info = lowerClassExpressionInfo(lowerer, expr); + // A function-local class expression's own name is a binding of its body: + // declared before the members lower, so their references to the name + // resolve to it. The class value captures it before it is assigned, as + // it captures a class declaration's binding. + if ( + !binding && + info.localClass && + ts.isClassExpression(expr) && + expr.name && + classExpressionNamesItself(lowerer, expr) + ) { + const own = lowerer.declareLocal( + expr.name, + expr.name.text, + { kind: "classval", className: info.def.name }, + true, + ); + const value = lowerClassValue(lowerer, expr, info, own); + return { + kind: "seqExpr", + stmts: [{ kind: "varDecl", localId: own.id, init: null, loc: value.loc }], + result: value, + type: value.type, + loc: value.loc, + }; + } + return lowerClassValue(lowerer, expr, info, binding); +} + +function lowerClassValue( + lowerer: Lowerer, + expr: ts.ClassLikeDeclaration, + info: ClassInfo, + binding: IrLocal | undefined, +): IrExpr { if ( !info.localClass && !info.expressionInitializationEmitted && @@ -6051,7 +6171,7 @@ export function lowerClassExpression(lowerer: Lowerer, expr: ts.ClassLikeDeclara const clsRef: IrExpr = { kind: "varRef", localId: clsLocal.id, type: value.type, loc }; const boxed: IrExpr = { kind: "dynFrom", value: clsRef, type: DYN, loc }; info.localPrototypeData = true; - return initializeRuntimeStatics(lowerer, info, { + const built: IrExpr = { kind: "seqExpr", stmts: [ { kind: "varDecl", localId: baseLocal.id, init: base, loc }, @@ -6084,7 +6204,8 @@ export function lowerClassExpression(lowerer: Lowerer, expr: ts.ClassLikeDeclara result: clsRef, type: value.type, loc, - }); + }; + return initializeRuntimeStatics(lowerer, info, built, binding); } if (info.localClass?.baseExpression && info.base && value.kind === "classRef") { const loc = locOf(expr); @@ -6099,7 +6220,7 @@ export function lowerClassExpression(lowerer: Lowerer, expr: ts.ClassLikeDeclara const clsRef: IrExpr = { kind: "varRef", localId: clsLocal.id, type: value.type, loc }; const basePrototype = classPrototypeData(lowerer, info.base, loc, baseRef)!; info.localPrototypeData = true; - return initializeRuntimeStatics(lowerer, info, { + const built: IrExpr = { kind: "seqExpr", stmts: [ { kind: "varDecl", localId: baseLocal.id, init: base, loc }, @@ -6138,15 +6259,59 @@ export function lowerClassExpression(lowerer: Lowerer, expr: ts.ClassLikeDeclara result: clsRef, type: value.type, loc, - }); + }; + return initializeRuntimeStatics(lowerer, info, built, binding); } - return info.localClass - ? initializeRuntimeStatics( - lowerer, - info, - value.kind === "classRef" ? { ...value, captures: info.localClass.captureSources } : value, - ) - : value; + if (!info.localClass) return value; + const classValue = initializeRuntimeStatics( + lowerer, + info, + value.kind === "classRef" ? { ...value, captures: info.localClass.captureSources } : value, + binding, + ); + // The base resolves statically here, but Node still evaluates the + // heritage expression each time the class definition runs, first. + const heritage = heritageWithEffects(expr); + if (heritage === undefined) return classValue; + return { + kind: "seqExpr", + stmts: [lowerer.lowerExprStatement(heritage)], + result: classValue, + type: classValue.type, + loc: classValue.loc, + }; +} + +/** The `extends` expression of `decl` when evaluating it can have effects + * (a call, construction, assignment, update, delete, await or yield + * outside nested functions). */ +function heritageWithEffects(decl: ts.ClassLikeDeclaration): ts.Expression | undefined { + const heritage = decl.heritageClauses?.nodes.find( + (clause) => clause.token === ts.SyntaxKind.ExtendsKeyword, + )?.types?.nodes[0]?.expression; + if (heritage === undefined) return undefined; + const effects = (node: ts.Node): boolean => { + if (ts.isFunctionLike(node) || ts.isClassDeclaration(node) || ts.isClassExpression(node)) + return false; + if ( + ts.isCallExpression(node) || + ts.isNewExpression(node) || + ts.isTaggedTemplateExpression(node) || + ts.isDeleteExpression(node) || + ts.isAwaitExpression(node) || + ts.isYieldExpression(node) || + (ts.isPrefixUnaryExpression(node) && + (node.operator === ts.SyntaxKind.PlusPlusToken || + node.operator === ts.SyntaxKind.MinusMinusToken)) || + ts.isPostfixUnaryExpression(node) || + (ts.isBinaryExpression(node) && + node.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && + node.operatorToken.kind <= ts.SyntaxKind.LastAssignment) + ) + return true; + return ts.forEachChild(node, (child) => effects(child) || undefined) ?? false; + }; + return effects(heritage) ? heritage : undefined; } /** The EXACT class a receiver expression is statically known to BE (not @@ -6422,6 +6587,12 @@ function staticCallOn( const loc = locOf(call); const runtimeStatic = directRuntimeStaticCall(lowerer, call, access, info, throughValue); if (runtimeStatic) return runtimeStatic; + // Date's statics through a class declared `extends Date` + // (`Moment.UTC(...)`), which inherits them. + if (dateRootOf(info) && !findStaticOn(lowerer, info, access.name.text)) { + const date = lowerDateStaticCall(lowerer, call, access.name.text); + if (date) return date; + } if ( (hasRuntimeStatics(info) && !findStaticOn(lowerer, info, access.name.text)?.field) || (info.callableBase && @@ -6467,7 +6638,7 @@ function staticCallOn( // functions, called directly as `%C.static:m%n` — with the same // through-a-VALUE shadowing fence as plain statics. const gfound = findGenericStaticOn(lowerer, info, access.name.text); - if (!gfound) return null; + if (!gfound) return classConstructorCall(lowerer, call, access, info); if (throughValue && staticShadowBelow(info, access.name.text)) { lowerer.unsupported( "SC1090", @@ -6560,6 +6731,89 @@ function staticCallOn( return { kind: "call", callee: fnName, args, type: found.method.ret, loc }; } +/** `C.call(thisArg, ...)` / `C.apply(thisArg, args)` on a program class that + * declares no such static: Function.prototype.call/apply invoke the class + * constructor without `new`, which throws Node's TypeError "Class + * constructor C cannot be invoked without 'new'" after the arguments are + * evaluated (and, for apply, after the argument list is read). The boxed + * class value's call path throws exactly that. Neither expando statics nor + * writes through untyped values can give a class an own `call` or `apply`. + * A receiver that may hold a subclass at run time (a class value, `this` in + * a static method) needs every subclass to lack such a static too. The + * receiver must be one the caller does not evaluate again (a name, `this`, + * or a namespace member). Null otherwise. */ +function classConstructorCall( + lowerer: Lowerer, + call: ts.CallExpression, + access: ts.PropertyAccessExpression, + info: ClassInfo, +): IrExpr | null { + const name = access.name.text; + const receiver = access.expression; + if ( + (name !== "call" && name !== "apply") || + !info.decl || + info.def.runtime || + info.builtinError || + info.builtinEmitter || + info.builtinStream || + info.builtinEventTarget || + info.runtimeStatics?.length || + declaresStaticAbove(info, name) || + (exactClassOfReceiver(lowerer, receiver) !== info && + info.subclasses.some((subclass) => declaresStaticBelow(subclass, name))) || + call.arguments.nodes.some(ts.isSpreadElement) || + !( + ts.isIdentifier(receiver) || + receiver.kind === ts.SyntaxKind.ThisKeyword || + (ts.isPropertyAccessExpression(receiver) && nsMemberIdentOf(lowerer, receiver) !== null) + ) + ) + return null; + return { + kind: "dynInvoke", + recv: lowerer.lowerExprExpecting(receiver, DYN), + method: name, + calleeName: ts.getTextOfNode(access), + args: call.arguments.nodes.map((argument) => lowerer.lowerExprExpecting(argument, DYN)), + type: DYN, + loc: locOf(call), + }; +} + +/** Whether `info`'s declaration has a static member that may be named `name` + * (a method, field or accessor of that name, or a computed name), or `info` + * has no declaration to tell. */ +function declaresStatic(info: ClassInfo, name: string): boolean { + if (!info.decl) return true; + return info.decl.members.nodes.some( + (member) => + member.name !== undefined && + ts.canHaveModifiers(member) && + ts.getModifiers(member)?.some((modifier) => modifier.kind === ts.SyntaxKind.StaticKeyword) === + true && + (ts.isComputedPropertyName(member.name) || + ((ts.isIdentifier(member.name) || ts.isStringLiteral(member.name)) && + member.name.text === name)), + ); +} + +/** declaresStatic over `info` and its bases, which it inherits statics from. */ +function declaresStaticAbove(info: ClassInfo, name: string): boolean { + for (let c: ClassInfo | null = info; c; c = c.base) if (declaresStatic(c, name)) return true; + return false; +} + +/** declaresStatic over `info` and its subclasses, or runtime statics, which a + * function-local JavaScript class defines at run time. */ +function declaresStaticBelow(info: ClassInfo, name: string): boolean { + return ( + declaresStatic(info, name) || + !!info.runtimeStatics?.length || + info.subclasses.some((subclass) => declaresStaticBelow(subclass, name)) + ); +} + /** `C.m(...)` where `m` is a static method that a function-local * JavaScript class defines at runtime (a factory's `class extends base`), * inherited by `C` through its statically known base chain. When the body @@ -7023,12 +7277,102 @@ export function inHierarchy(lowerer: Lowerer, info: ClassInfo): boolean { * dynamically. Abstract re-declarations don't count (they carry no * implementation; the concrete ones below them do, via the recursion). */ export function overrideBelow(lowerer: Lowerer, info: ClassInfo, name: string): boolean { + if (info.decl !== null && localOverrideBelow(lowerer, info.decl, name)) return true; return info.subclasses.some((s) => { const m = s.methods.get(name); return (m !== undefined && m.abstract !== true) || lowerer.overrideBelow(s, name); }); } +/** The class node an `extends` clause names: a class declaration, or the + * class expression a variable is initialized with. */ +function extendedClassNode(lowerer: Lowerer, decl: ts.ClassLikeDeclaration): ts.Node | null { + const heritage = decl.heritageClauses?.nodes.find( + (clause) => clause.token === ts.SyntaxKind.ExtendsKeyword, + )?.types?.nodes[0]?.expression; + if (!heritage || !ts.isIdentifier(heritage)) return null; + let symbol = lowerer.checker.getSymbolAtLocation(heritage); + if (symbol && symbol.flags & ts.SymbolFlags.Alias) + symbol = lowerer.checker.getAliasedSymbol(symbol); + const target = symbol?.valueDeclaration; + if (!target) return null; + if (ts.isClassDeclaration(target) || ts.isClassExpression(target)) return target; + if (ts.isVariableDeclaration(target) && target.initializer) { + let init: ts.Expression = target.initializer; + while (ts.isParenthesizedExpression(init)) init = init.expression; + if (ts.isClassExpression(init)) return init; + } + return null; +} + +/** The function-local classes that extend the class node `base`. Function + * bodies lower on demand, after code that may already call methods of a + * class their local classes extend, so such a subclass is not yet in its + * base's `subclasses` when those calls lower. */ +function localSubclassesOf(lowerer: Lowerer, base: ts.Node): readonly ts.ClassLikeDeclaration[] { + let index = lowerer.localSubclassIndex; + if (index === null) { + index = new Map(); + const files = lowerer.moduleOrder.length > 0 ? lowerer.moduleOrder : [lowerer.entry]; + for (const sf of files) { + if (!sf.text.includes("extends")) continue; + ts.walkPreorder(sf, (node) => { + if ( + (ts.isClassDeclaration(node) || ts.isClassExpression(node)) && + node.heritageClauses !== undefined && + functionLocalClass(node) + ) { + const extended = extendedClassNode(lowerer, node); + if (extended) { + const list = index!.get(extended); + if (list) list.push(node); + else index!.set(extended, [node]); + } + } + return undefined; + }); + } + lowerer.localSubclassIndex = index; + } + return index.get(base) ?? []; +} + +/** True when a function-local class below the class node `base` declares + * a concrete instance method or accessor `name` (accessors are keyed + * `get:x` and `set:x`). A call on `base`'s class then dispatches on the + * receiver; devirtualization turns it back into a direct call when no such + * override is reachable. */ +function localOverrideBelow( + lowerer: Lowerer, + base: ts.Node, + name: string, + visited?: Set, +): boolean { + const subclasses = localSubclassesOf(lowerer, base); + if (subclasses.length === 0) return false; + visited ??= new Set(); + if (visited.has(base)) return false; + visited.add(base); + const accessor = name.startsWith("get:") ? "get" : name.startsWith("set:") ? "set" : null; + const member = accessor ? name.slice(4) : name; + return subclasses.some( + (sub) => + sub.members.nodes.some( + (m) => + (accessor === null + ? ts.isMethodDeclaration(m) + : accessor === "get" + ? ts.isGetAccessorDeclaration(m) + : ts.isSetAccessorDeclaration(m)) && + m.body !== undefined && + m.name !== undefined && + (ts.isIdentifier(m.name) || ts.isStringLiteral(m.name)) && + m.name.text === member && + !ts.getModifiers(m)?.some((modifier) => modifier.kind === ts.SyntaxKind.StaticKeyword), + ) || localOverrideBelow(lowerer, sub, name, visited), + ); +} + /** The nearest GENERIC-method declaration of `name` at/above `info` — * findMethodOn's twin over the genericMethods tables. */ export function findGenericMethodOn( @@ -7683,7 +8027,7 @@ function lowerClassCtorInner(lowerer: Lowerer, info: ClassInfo): IrFunction { lowerer.ctx.argumentsLocal = local; } body.push(...declared.prologue); - if (!ctorBase && !info.callableBase) { + if (!ctorBase && !info.callableBase && !info.extendsDate) { // Node's base-class order: field initializers run at the start // of construction, the parameter-property assignments open the // constructor body (probed — a field initializer reading a @@ -7695,7 +8039,7 @@ function lowerClassCtorInner(lowerer: Lowerer, info: ClassInfo): IrFunction { body.push(...lowerer.lowerDerivedCtorBody(info, thisLocal)); } } else { - if (ctorBase || info.callableBase) { + if (ctorBase || info.callableBase || info.extendsDate) { // Synthetic forwarding params (the inherited ABI signature). // Nothing references them by symbol — only the super call below, // which forwards the already-completed values UNCHANGED (defaults @@ -7910,7 +8254,7 @@ export function classIteratorDrainCall( const key = `${cit.className}:${typeKey(outElem)}`; let name = lowerer.iterDrainHelpers.get(key); if (!name) { - name = `%iter.drain.${lowerer.iterDrainHelpers.size}`; + name = keyedHelperName(lowerer, "%iter.drain", key); lowerer.iterDrainHelpers.set(key, name); const recvT: IrType = { kind: "object", className: cit.className }; const recvRef: IrExpr = { kind: "varRef", localId: "r.0", type: recvT, loc }; @@ -8024,7 +8368,7 @@ export function classIteratorRestDrainCall( const key = `it:${cit.iterT.className}`; let name = lowerer.iterDrainHelpers.get(key); if (!name) { - name = `%iter.drain.${lowerer.iterDrainHelpers.size}`; + name = keyedHelperName(lowerer, "%iter.drain", key); lowerer.iterDrainHelpers.set(key, name); const itRef: IrExpr = { kind: "varRef", localId: "it.0", type: cit.iterT, loc }; const outRef: IrExpr = { kind: "varRef", localId: "out.0", type: outT, loc }; @@ -8614,12 +8958,14 @@ export function lowerDerivedCtorBody( loc, }, ]; - if (info.callableBase) { + if (info.callableBase || info.extendsDate) { if (superCall.arguments.nodes.some(ts.isSpreadElement)) lowerer.unsupported( "SC1090", superCall, - "spreading explicit super arguments into an ordinary constructor", + info.extendsDate + ? "spreading super arguments into the Date constructor" + : "spreading explicit super arguments into an ordinary constructor", ); const pack: IrExpr = { kind: "dynArrLit", @@ -8804,6 +9150,7 @@ export function superCallStmt( type: { kind: "object", className: info.def.name }, loc, }; + if (info.extendsDate) return dateSuperCall(thisRef, info, args[0]!, loc); if (info.callableBase) return { kind: "exprStmt", @@ -8883,8 +9230,9 @@ export function superCallStmt( // The SYNTHESIZED constructor of a ctor-less stream subclass: // super() with default options (underscore methods still bind; a // construction passing options requires a declared constructor — - // lowerNew fences that). Zero options ⇒ exactly one init stmt. - return lowerStreamSuperCall( + // lowerNew fences that). Zero options ⇒ the init stmt, then the + // class's _writev/_construct follow-ups. + const stmts = lowerStreamSuperCall( lowerer, info, base, @@ -8892,7 +9240,8 @@ export function superCallStmt( thisLocal, loc, info.decl ?? info.ctor!, - )[0]!; + ); + return stmts.length === 1 ? stmts[0]! : { kind: "block", body: stmts, loc }; } lowerer.noteSuperConstructorEdge(`%${base.def.name}.constructor`); const call: IrStmt = { @@ -8925,6 +9274,24 @@ export function lowerSuperMethodCall( access: ts.PropertyAccessExpression, ): IrExpr { const cls = lowerer.currentClass; + // `super.toISOString()` in a class declared `extends Date`. + if (cls?.extendsDate && !cls.base) { + const thisL = lowerer.resolveThis(); + if (!thisL) lowerer.unsupported("SC1080", access); + const thisRef: IrExpr = { + kind: "varRef", + localId: thisL.id, + type: thisL.type, + loc: locOf(call), + }; + const date = lowerDateSuperMethodCall(lowerer, call, access.name.text, cls, thisRef); + if (date) return date; + lowerer.unsupported( + "SC1090", + access, + `'super.${access.name.text}' (Date.prototype does not declare it)`, + ); + } if (!cls?.base) { // tsc rejects super outside derived-class bodies first; defensive. lowerer.unsupported("SC1090", access, "'super' outside a derived class"); @@ -8969,6 +9336,17 @@ export function lowerSuperMethodCall( // `super.dispatchEvent(e)`, `super.preventDefault()`: the inherited // runtime members over this method's own `this` (subclasses cannot // override them, so the static answer is the runtime's). + if (dateRootOf(cls.base) && isDatePrototypeMethod(access.name.text)) { + const thisL = lowerer.resolveThis(); + if (!thisL) lowerer.unsupported("SC1080", access); + const thisRef: IrExpr = { + kind: "varRef", + localId: thisL.id, + type: thisL.type, + loc: locOf(call), + }; + return lowerDateSuperMethodCall(lowerer, call, access.name.text, cls.base, thisRef)!; + } if (eventTargetApiMethod(cls.base, access.name.text)) { const thisL = lowerer.resolveThis(); if (!thisL) lowerer.unsupported("SC1080", access); @@ -9703,6 +10081,12 @@ export function lowerNew(lowerer: Lowerer, expr: ts.NewExpression): IrExpr { const httpServer = lowerHttpServerNew(lowerer, expr); if (httpServer) return httpServer; } + // `new tls.TLSSocket(socket, options)` — the server-mode wrap of an open + // socket (lower-server). + { + const tlsSocket = lowerTlsSocketNew(lowerer, expr); + if (tlsSocket) return tlsSocket; + } // `new http.Agent(opts?)` / `new https.Agent(opts?)` — the Agent // handle (lower-server): getName/destroy/counters through the dyn // handle ops, requests thread it via the agent option. @@ -10255,6 +10639,45 @@ export function lowerNew(lowerer: Lowerer, expr: ts.NewExpression): IrExpr { loc, }; } + // A FinalizationRegistry construction: register and unregister keep + // their bookkeeping, and the cleanup callback never runs, which + // ECMAScript allows (scr_finalization_registry_new). + if ( + symbol !== null && + ts.symbolName(symbol) === "FinalizationRegistry" && + lowerer.isStdlibSymbol(symbol) + ) { + const args = expr.arguments?.nodes ?? []; + if (args.some(ts.isSpreadElement)) { + lowerer.unsupported( + "SC1090", + expr, + "FinalizationRegistry construction with spread arguments", + ); + } + const cleanup = args[0] ? lowerer.lowerExprExpecting(args[0], DYN) : dynUndefinedExpr(loc); + const surplus = args.slice(1).map((arg) => lowerer.lowerExpr(arg)); + const created: IrExpr = { + kind: "libCall", + fn: "finalizationRegistry.new", + args: [cleanup], + type: DYN, + loc, + }; + if (surplus.length === 0) return created; + // Surplus arguments evaluate after the cleanup argument and are ignored. + const local = lowerer.declareHiddenLocal("%finalizationCleanup", DYN); + return { + kind: "seqExpr", + stmts: [ + { kind: "varDecl", localId: local.id, init: cleanup, loc }, + ...surplus.map((value): IrStmt => ({ kind: "exprStmt", expr: value, loc })), + ], + result: { ...created, args: [varRef(local.id, DYN, loc)] }, + type: DYN, + loc, + }; + } // `new Set()`: construct + bulk add from supported values, // including live collection cursors. Duplicates collapse in insertion order. if (ts.isIdentifier(identifier) && lowerer.isStdlibGlobal(identifier, "Set")) { @@ -10466,8 +10889,6 @@ export function lowerNew(lowerer: Lowerer, expr: ts.NewExpression): IrExpr { Boolean: "boxed wrapper objects have no lowering — use the boolean primitive", WeakRef: "deref()-after-collect exposes GC timing — genuinely dynamic; hold a strong reference instead", - FinalizationRegistry: - "finalization callbacks expose GC timing — genuinely dynamic; release resources explicitly instead", SharedArrayBuffer: "no shared-memory threads exist in a compiled program — Uint8Array is the byte storage", ArrayBuffer: @@ -10532,7 +10953,7 @@ export function lowerNew(lowerer: Lowerer, expr: ts.NewExpression): IrExpr { const key = `x509.record:${isBytes ? "bytes" : "str"}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = `%x509.record.${lowerer.valueHelpers.size}`; + helper = keyedHelperName(lowerer, "%x509.record", key); lowerer.valueHelpers.set(key, helper); const dataT = data.type; const dRef: IrExpr = { kind: "varRef", localId: "d.0", type: dataT, loc }; diff --git a/packages/compiler/src/frontend/lowering/lower-dgram.ts b/packages/compiler/src/frontend/lowering/lower-dgram.ts index 5c99ebc82..0e0ddf975 100644 --- a/packages/compiler/src/frontend/lowering/lower-dgram.ts +++ b/packages/compiler/src/frontend/lowering/lower-dgram.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "./stable-names.js"; import { dynUndefinedExpr, boolLit } from "../../ir/build.js"; /* The dgram/dns-surface lowering (node:dgram + node:dns — a spoke module * like lower-server.ts): module-function calls (dgram createSocket, dns @@ -357,7 +358,7 @@ function checkedDynPromise( const key = `dns.promise:${typeKey(declared)}`; let helper = lowerer.valueHelpers.get(key); if (!helper) { - helper = `%dns.promise.${lowerer.valueHelpers.size}`; + helper = keyedHelperName(lowerer, "%dns.promise", key); lowerer.valueHelpers.set(key, helper); const promiseT: IrType = { kind: "promise", inner: DYN }; lowerer.liftedFns.push({ @@ -611,8 +612,10 @@ export function lowerDgramMethodCall( const fn: IrLibFn = data.type.kind === "string" ? "dgram.sendStr" : "dgram.sendBytes"; return { kind: "libCall", fn, args: [receiver, data, port, host], type: VOID, loc }; } + // TypeScript reaches the ladder for the completion-callback form + // send(msg, port, address, callback) (the hot-shots package shim). if ( - isJsSourceFile(ts.getSourceFileOfNode(call)) && + (isJsSourceFile(ts.getSourceFileOfNode(call)) || args.length === 4) && args.length <= 6 && !args.some(ts.isSpreadElement) ) { @@ -891,7 +894,7 @@ export function lowerPromisifiedDnsCall( const key = `dnsPromise:${JSON.stringify(value)}`; let name = lowerer.valueHelpers.get(key); if (!name) { - name = `%dnsPromise.${lowerer.valueHelpers.size}`; + name = keyedHelperName(lowerer, "%dnsPromise", key); lowerer.valueHelpers.set(key, name); lowerer.liftedFns.push({ name, diff --git a/packages/compiler/src/frontend/lowering/lower-event-emitter.ts b/packages/compiler/src/frontend/lowering/lower-event-emitter.ts index f472672b2..f44a3d6d8 100644 --- a/packages/compiler/src/frontend/lowering/lower-event-emitter.ts +++ b/packages/compiler/src/frontend/lowering/lower-event-emitter.ts @@ -42,6 +42,7 @@ * emit-overrides block at the bottom of this file (per-event * monomorphization of the override body, dispatch on the dynamic class, * super.emit as the prototype chain). */ +import { keyedHelperName } from "./stable-names.js"; import { checkKeypressListener } from "./builtins/readline.js"; import * as ts from "../ts7/adapter.js"; import type { Lowerer } from "./lowerer.js"; @@ -631,7 +632,7 @@ function lowerFlexListenerCall( const key = `emitter.${registering ? "onFlex" : "offDyn"}:${typeKey(recvT)}`; let helper = lowerer.arrHofHelpers.get(key); if (!helper) { - helper = `%emitter.${registering ? "onFlex" : "offFlex"}.${lowerer.arrHofHelpers.size}`; + helper = keyedHelperName(lowerer, `%emitter.${registering ? "onFlex" : "offFlex"}`, key); lowerer.arrHofHelpers.set(key, helper); const params: IrParam[] = [ { localId: "r.0", name: "r", type: recvT }, @@ -850,7 +851,7 @@ function lowerDynListenerCall( const existing = lowerer.arrHofHelpers.get(key); let helper = existing; if (!helper) { - helper = `%emitter.${registering ? "onDyn" : "offDyn"}.${lowerer.arrHofHelpers.size}`; + helper = keyedHelperName(lowerer, `%emitter.${registering ? "onDyn" : "offDyn"}`, key); lowerer.arrHofHelpers.set(key, helper); const check: IrStmt = { kind: "exprStmt", @@ -1000,7 +1001,7 @@ export function lowerDynamicEmitterEmit( const key = `emitter.dynEmit:${typeKey(recvT)}:${k}`; let helper = lowerer.arrHofHelpers.get(key); if (!helper) { - helper = `%emitter.dynEmit.${lowerer.arrHofHelpers.size}`; + helper = keyedHelperName(lowerer, "%emitter.dynEmit", key); lowerer.arrHofHelpers.set(key, helper); const params: IrParam[] = [ { localId: "r.0", name: "r", type: recvT }, @@ -1092,7 +1093,7 @@ export function lowerDynamicEmitterOn( const key = `emitter.dynOn:${typeKey(recvT)}`; let helper = lowerer.arrHofHelpers.get(key); if (!helper) { - helper = `%emitter.dynOn.${lowerer.arrHofHelpers.size}`; + helper = keyedHelperName(lowerer, "%emitter.dynOn", key); lowerer.arrHofHelpers.set(key, helper); const params: IrParam[] = [ { localId: "r.0", name: "r", type: recvT }, @@ -1457,10 +1458,11 @@ export function lowerEmitterMethodCall( const receiver = lowerReceiver(); const once = member === "once" || member === "prependOnceListener"; const prepend = member === "prependListener" || member === "prependOnceListener"; - // Stream 'data' rides its own two-slot payload ABI (bytes + string — - // encoded streams deliver strings; scr_stream_emit_data): listeners - // on readable-sided receivers register through DATA thunks that - // unwrap the declared side (typed) or box by tag (dyn). + // Stream 'data' rides its own three-slot payload ABI (bytes, string — + // encoded streams deliver strings — and an object-mode value; + // scr_stream_emit_data): listeners on readable-sided receivers + // register through DATA thunks that unwrap the declared side, convert + // to the declared type, or take the value (dyn). const sides = streamSidesOf(lowerer, info); if (name === "data" && (sides === "r" || sides === "rw")) { const dynFlavor = dynListenerFlavor(lowerer, args[1]!); @@ -1499,16 +1501,25 @@ export function lowerEmitterMethodCall( (lowerer.unions.get(p.unionId)?.arms ?? []).every( (arm) => (arm.kind === "bytes" && arm.elem === "u8") || arm.kind === "string", ); + // Any other chunk type converts from the chunk's value (an + // object-mode stream's value, or the Buffer or string) when the + // listener runs, or throws a TypeError there. if ( p !== undefined && !(p.kind === "bytes" && p.elem === "u8") && p.kind !== "string" && - !chunkUnion + !chunkUnion && + (p.kind === "func" || + !canConvertToDyn( + p, + (id) => lowerer.shapes.get(id), + (id) => lowerer.unions.get(id), + )) ) { lowerer.noLowering( `a 'data' listener whose chunk parameter is '${lowerer.fmt(p)}'`, args[1]!, - "chunks are Buffers — or strings once setEncoding/the encoding option applies", + "declare the chunk as a type that converts from a checked-dynamic value", ); } if (!registering) { @@ -1653,8 +1664,10 @@ export function lowerEmitterMethodCall( loc, ); } - // Stream 'data' rides the two-slot payload ABI: a user emit fills - // the chunk's slot (bytes or string), NULLs the other. + // Stream 'data' rides the three-slot payload ABI: a user emit fills + // the chunk's slot (bytes or string) and NULLs the others; any other + // value is emitted as a checked-dynamic value, filling the slots by + // its tag. const emitSides = streamSidesOf(lowerer, info); if (name === "data" && (emitSides === "r" || emitSides === "rw")) { if (args.length !== 2) { @@ -1664,16 +1677,27 @@ export function lowerEmitterMethodCall( "the event carries one chunk (a Buffer or string)", ); } - const chunk = lowerer.lowerExpr(args[1]!); + let chunk = lowerer.lowerExpr(args[1]!); if ( !(chunk.type.kind === "bytes" && chunk.type.elem === "u8") && chunk.type.kind !== "string" ) { - lowerer.noLowering( - `emit('data') with a '${lowerer.fmt(chunk.type)}' chunk`, - args[1]!, - "chunks are Buffers or strings", - ); + if ( + chunk.type.kind === "func" || + (chunk.type.kind !== "dyn" && + !canConvertToDyn( + chunk.type, + (id) => lowerer.shapes.get(id), + (id) => lowerer.unions.get(id), + )) + ) { + lowerer.noLowering( + `emit('data') with a '${lowerer.fmt(chunk.type)}' chunk`, + args[1]!, + "the chunk is a value that converts to a checked-dynamic value", + ); + } + chunk = lowerer.coerceToExpected(chunk, DYN); } return { kind: "libCall", @@ -2359,7 +2383,7 @@ function emitDispatchExpr( const key = `emitter.emitDispatch:${typeKey(recvT)}:${name}`; let helper = lowerer.arrHofHelpers.get(key); if (!helper) { - helper = `%emitter.emitDispatch.${lowerer.arrHofHelpers.size}`; + helper = keyedHelperName(lowerer, "%emitter.emitDispatch", key); lowerer.arrHofHelpers.set(key, helper); const params: IrParam[] = [ { localId: "r.0", name: "r", type: recvT }, @@ -2424,7 +2448,7 @@ function eventsOnceBoxer( const key = `eventsOnce:${typeKey(fnType)}`; let name = lowerer.valueHelpers.get(key); if (name === undefined) { - name = `%events.onceArgs.${lowerer.valueHelpers.size}`; + name = keyedHelperName(lowerer, "%events.onceArgs", key); lowerer.valueHelpers.set(key, name); const params: IrParam[] = tuple.map((type, i) => ({ localId: `%once.a${i}`, diff --git a/packages/compiler/src/frontend/lowering/lower-exprs.ts b/packages/compiler/src/frontend/lowering/lower-exprs.ts index e7a1b79a8..ac8b02b69 100644 --- a/packages/compiler/src/frontend/lowering/lower-exprs.ts +++ b/packages/compiler/src/frontend/lowering/lower-exprs.ts @@ -1,4 +1,6 @@ +import { keyedHelperName } from "./stable-names.js"; import { lowerWebAssemblyValue, refuseWebAssemblyUse } from "./builtins/webassembly.js"; +import { lowerAwaitedUniformPromiseAll } from "./builtins/promises.js"; import { dynUndefinedExpr, nodeThrowExpr, numLit, strLit, varRef } from "../../ir/build.js"; import { InternalCompilerError } from "../../errors.js"; /* Expression lowering: the expression dispatch (lowerExpr), literals @@ -574,6 +576,8 @@ function lowerExprInner(lowerer: Lowerer, expr: ts.Expression): IrExpr { // boundary for malformed/upstream ASTs. lowerer.unsupported("SC1090", expr, "top-level await (await outside async functions)"); } + const uniformAll = lowerAwaitedUniformPromiseAll(lowerer, expr); + if (uniformAll) return uniformAll; const value = lowerer.lowerExpr(expr.expression); // A promise-or-absent union (`Promise | undefined` values, calls // of `(...) => Promise | void` callbacks): the await handles @@ -2091,6 +2095,7 @@ export function typeofAnswer(arm: IrType): string | null { case "array": case "map": case "set": + case "generator": case "regex": case "bytes": case "url": @@ -2274,7 +2279,11 @@ export function cjsAccessorSnapshotOf( if (!lexerVisibleAccessors(ts.getSourceFileOfNode(getter)).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 }; + const at = locOf(getter); + const snapshot = { + id: keyedHelperName(lowerer, "%g.cjsSnapshot", `${at.file}:${at.start}:${at.end}`), + type: call.type, + }; lowerer.globalsList.push({ id: snapshot.id, name: "%cjsSnapshot", @@ -2299,7 +2308,7 @@ export function cjsAccessorSnapshotStores( if (getters.length === 0) return []; let readyId = lowerer.cjsSnapshotReady.get(dep); if (readyId === undefined) { - readyId = `%g.cjsSnapshotReady.${lowerer.cjsSnapshotReady.size}`; + readyId = keyedHelperName(lowerer, "%g.cjsSnapshotReady", dep.fileName); lowerer.globalsList.push({ id: readyId, name: "%cjsSnapshotReady", type: BOOL, mutable: true }); lowerer.cjsSnapshotReady.set(dep, readyId); } @@ -3052,8 +3061,10 @@ export function lowerFieldCompound( * returns the zero-capture closure over it. Typed sources use the mapped * `(value: string) => primitive` signature; a recognized JavaScript * concise-arrow selector (`() => String`, the picocolors fallback) takes - * dyn so its ordinary coercion signature survives inference residue. The - * dyn bodies run exact ToString/ToNumber/ToBoolean, including object hooks. + * dyn so its ordinary coercion signature survives inference residue, and a + * boxed constructor value takes dyn too (coerceToExpected). The dyn bodies + * run what the constructors do for any argument: String() (a symbol's + * description form included), ToNumber and ToBoolean, with object hooks. * Interning makes every reference under one ABI the SAME immortal closure, * so `opt.type === String` compares like JS function identity. */ export function primitiveCtorClosure( @@ -3076,7 +3087,7 @@ export function primitiveCtorClosure( ? name === "BigInt" ? { kind: "libCall", fn: "dyn.bigintConstructor", args: [v], type: BIGINT_T, loc } : name === "String" - ? { kind: "libCall", fn: "dyn.toStringCoerce", args: [v], type: STRING, loc } + ? { kind: "libCall", fn: "dyn.stringConstructor", args: [v], type: STRING, loc } : name === "Number" ? { kind: "libCall", fn: "dyn.numberConstructor", args: [v], type: F64, loc } : { kind: "dynTest", test: "truthy", value: v, type: BOOL, loc } diff --git a/packages/compiler/src/frontend/lowering/lower-functions.ts b/packages/compiler/src/frontend/lowering/lower-functions.ts index cd8dc31d1..c1cca9c64 100644 --- a/packages/compiler/src/frontend/lowering/lower-functions.ts +++ b/packages/compiler/src/frontend/lowering/lower-functions.ts @@ -1,3 +1,4 @@ +import type { ScrDiagnostic } from "../../diagnostics/diagnostic.js"; import { declareTypedArguments } from "./typed-arguments.js"; import { dynUndefinedExpr, varRef } from "../../ir/build.js"; import { everyStmtList, transformStmtList } from "../../ir/traverse.js"; @@ -17,6 +18,7 @@ import { type IrLocal, type IrParam, type IrStmt, + type IrType, type SrcLoc, VOID, canBoxFuncIntoDyn, @@ -270,7 +272,7 @@ export function lowerLambda( const nameIdent = !ts.isArrowFunction(node) && node.name && ts.isIdentifier(node.name) ? node.name : null; const baseName = nameIdent ? nameIdent.text : ""; - const fnName = `%fn${lowerer.lambdaCounter++}${baseName ? `_${baseName}` : ""}`; + const fnName = lowerer.closureName(locOf(node), baseName ? `_${baseName}` : ""); // Named function expressions/declarations can self-reference by name; an // object-literal method's name is a PROPERTY, not a binding — no self. const selfSymbol = @@ -858,3 +860,79 @@ function isBufferCheckOf(e: IrExpr, slotId: string): boolean { e.type.elem === "u8" ); } + +/** The diagnostics of a TypeScript function whose signature did not + * compile, for the coverage remainder: its statements lower for their + * diagnostics only (the remainder's output is discarded), so the report + * lists them with the signature's blocker instead of hiding them behind it. + * Each parameter whose type maps is declared, and a use of any other + * parameter reports SC2004 back to the declaration. The statements already + * count as failed (countSkippedBody), so the pass leaves the stats alone. + * The pass adds diagnostics only: an internal error while it lowers drops + * what it found, and the signature's blocker stands alone as before. */ +export function blockedBodyDiagnostics( + lowerer: Lowerer, + decl: ts.FunctionDeclaration, +): ScrDiagnostic[] { + const body = decl.body; + if (!body || decl.typeParameters || decl.asteriskToken) return []; + if (isJsSourceFile(ts.getSourceFileOfNode(decl))) return []; + const symbol = declSymbolOf(lowerer, decl); + if (!symbol || lowerer.fnSigsBySymbol.has(symbol)) return []; + const diagsBefore = lowerer.diags.length; + const fencesBefore = lowerer.runtimeFences.length; + const suppressStats = lowerer.suppressStats; + lowerer.suppressStats = true; + let declared: IrType = DYN; + lowersCleanly(lowerer, () => { + declared = lowerer.declaredReturnType(decl, decl); + }); + const isAsync = decl.modifiers?.nodes.some((m) => m.kind === ts.SyntaxKind.AsyncKeyword) ?? false; + const ctx = newFnCtx(false, null, null, lowerer.bodyReturnType(isAsync, declared)); + ctx.isAsync = isAsync; + lowerer.fnStack.push(ctx); + let internal = false; + try { + // A declared `this` parameter gives the body its receiver, as + // lowerFunction declares it. + if (decl.parameters.nodes.some(isThisParameter)) declareCallReceiver(lowerer, decl, false); + for (const param of decl.parameters.nodes) { + if (isThisParameter(param)) continue; + const declaredParam = lowersCleanly(lowerer, () => { + lowerer.declareParams([param], lowerer.paramShapes([param])); + }); + if (declaredParam) continue; + const symbol = ts.isIdentifier(param.name) + ? lowerer.checker.getSymbolAtLocation(param.name) + : undefined; + if (symbol) lowerer.blockedBindings.add(symbol); + } + lowersCleanly(lowerer, () => { + lowerer.lowerStmts(body.statements.nodes); + }); + } catch (error) { + if (!(error instanceof InternalCompilerError)) throw error; + internal = true; + } finally { + lowerer.fnStack.pop(); + lowerer.suppressStats = suppressStats; + } + lowerer.runtimeFences.splice(fencesBefore); + const diags = lowerer.diags.splice(diagsBefore); + return internal || diags.some((d) => d.code === "SC9001") ? [] : diags; +} + +/** Runs `lower`, for blockedBodyDiagnostics: false when it poisons, with the + * diagnostics it recorded dropped (a failed mapping reports what the + * signature's blocker already reports). */ +function lowersCleanly(lowerer: Lowerer, lower: () => void): boolean { + const before = lowerer.diags.length; + try { + lower(); + return true; + } catch (error) { + if (!(error instanceof PoisonError)) throw error; + lowerer.diags.splice(before); + return false; + } +} diff --git a/packages/compiler/src/frontend/lowering/lower-generators.ts b/packages/compiler/src/frontend/lowering/lower-generators.ts index b4e3ac102..80463fa6c 100644 --- a/packages/compiler/src/frontend/lowering/lower-generators.ts +++ b/packages/compiler/src/frontend/lowering/lower-generators.ts @@ -687,8 +687,12 @@ export function lowerForAwaitGenerator( lowerer.scopes.push(new Map()); try { const g = lowerer.declareHiddenLocal("%fag", genT); - const done = lowerer.declareHiddenLocal("%fagdone", BOOL); - done.mutable = true; + // Whether a value has arrived and the body holds the generator open: + // leaving the loop then (break, return, a throw, or a return() at a + // yield in the body) closes it, as AsyncIteratorClose does; an + // exhausted generator and a rejected next() are not closed. + const active = lowerer.declareHiddenLocal("%fagactive", BOOL); + active.mutable = true; const p = lowerer.declareHiddenLocal("%fagpromise", promiseT); const r = lowerer.declareHiddenLocal("%fagresult", recT); const gRef = (): IrExpr => ({ kind: "varRef", localId: g.id, type: genT, loc }); @@ -709,7 +713,14 @@ export function lowerForAwaitGenerator( `for-await over an async generator yielding '${lowerer.fmt(genT.yieldT)}' (no per-element extraction exists)`, ); } + const setActive = (value: boolean): IrStmt => ({ + kind: "assign", + localId: active.id, + value: { kind: "boolLit", value, type: BOOL, loc }, + loc, + }); const head: IrStmt[] = [ + setActive(false), { kind: "varDecl", localId: p.id, @@ -737,19 +748,12 @@ export function lowerForAwaitGenerator( type: BOOL, loc, }, - then: [ - { - kind: "assign", - localId: done.id, - value: { kind: "boolLit", value: true, type: BOOL, loc }, - loc, - }, - { kind: "break", loc }, - ], + then: [{ kind: "break", loc }], else_: null, loc, }, ...generatorLoopBinding(lowerer, stmt, extracted, genT.yieldT), + setActive(true), ]; const body = lowerer.inCtl("loop", () => lowerer.lowerScopedBlock(stmt.statement), labels); const closePromise: IrExpr = { @@ -766,34 +770,40 @@ export function lowerForAwaitGenerator( { kind: "varDecl", localId: g.id, init: iterable, loc }, { kind: "varDecl", - localId: done.id, + localId: active.id, init: { kind: "boolLit", value: false, type: BOOL, loc }, loc, }, { - kind: "while", - cond: { kind: "boolLit", value: true, type: BOOL, loc }, - body: [...head, ...body], - ...(labels && { labels }), - loc, - }, - { - kind: "if", - cond: { - kind: "unary", - op: "!", - operand: { kind: "varRef", localId: done.id, type: BOOL, loc }, - type: BOOL, - loc, - }, - then: [ + kind: "tryCatch", + tryBody: [ { - kind: "exprStmt", - expr: { kind: "awaitExpr", value: closePromise, type: recT, loc }, + kind: "while", + cond: { kind: "boolLit", value: true, type: BOOL, loc }, + body: [...head, ...body], + ...(labels && { labels }), + loc, + }, + ], + catchBody: null, + catchLocalId: null, + // After a throw, an error from closing the generator is dropped. + dropFinallyErrors: true, + finallyBody: [ + { + kind: "if", + cond: { kind: "varRef", localId: active.id, type: BOOL, loc }, + then: [ + { + kind: "exprStmt", + expr: { kind: "awaitExpr", value: closePromise, type: recT, loc }, + loc, + }, + ], + else_: null, loc, }, ], - else_: null, loc, }, ], diff --git a/packages/compiler/src/frontend/lowering/lower-global-value.ts b/packages/compiler/src/frontend/lowering/lower-global-value.ts index 4b8e7b10a..e7ab6b0f0 100644 --- a/packages/compiler/src/frontend/lowering/lower-global-value.ts +++ b/packages/compiler/src/frontend/lowering/lower-global-value.ts @@ -1,6 +1,5 @@ import * as ts from "../ts7/adapter.js"; import { DYN, STRING, arrayOf, type IrExpr } from "../../ir/ir.js"; -import { strLit } from "../../ir/build.js"; import { locOf } from "../program.js"; import type { Lowerer } from "./lowerer.js"; import { TEMPORAL_GLOBAL } from "../builtin-modules.js"; @@ -19,10 +18,14 @@ export function lowerGlobalValue(lowerer: Lowerer, expr: ts.Expression): IrExpr return { kind: "libCall", fn: "global.native", + // One immortal name table per program (keyed by its contents): reading + // the global object in a hot path allocates nothing, and the runtime + // recognizes a table it has already registered. args: [ { - kind: "arrayLit", - elems: names.map((name) => strLit(name, loc)), + kind: "templateStrings", + key: `%globalThis.names:${names.join(",")}`, + cooked: names, type: arrayOf(STRING), loc, }, diff --git a/packages/compiler/src/frontend/lowering/lower-inspect.ts b/packages/compiler/src/frontend/lowering/lower-inspect.ts index 14c67f70a..7c2ec4a2d 100644 --- a/packages/compiler/src/frontend/lowering/lower-inspect.ts +++ b/packages/compiler/src/frontend/lowering/lower-inspect.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "./stable-names.js"; import { dynUndefinedExpr, boolLit, @@ -45,6 +46,7 @@ import type { ClassInfo } from "./lower-classes.js"; import { isSafeToDiscard, isSafeToRepeat } from "./expressions/evaluation-safety.js"; import { symbolFieldDisplayName } from "./symbol-fields.js"; import { eventTargetRootOf } from "./lower-event-target.js"; +import { dateRootOf } from "./builtins/date-classes.js"; import { lowerSystemErrorMap } from "./lower-system-errors.js"; import { isPerfEntryType, perfEntryJson } from "./builtins/performance.js"; import { recordMayKeepSource, recordSourceTest } from "./record-sources.js"; @@ -268,7 +270,7 @@ function errorInspectHelper( const key = `insp.userError:${typeKey(t)}`; const existing = lowerer.inspectHelpers.get(key); if (existing) return existing; - const name = `%util.insp.${lowerer.inspectHelpers.size}`; + const name = keyedHelperName(lowerer, "%util.insp", key); lowerer.inspectHelpers.set(key, name); const v = (): IrExpr => varRef("v.0", t, loc); const r = (): IrExpr => varRef("r.0", F64, loc); @@ -804,8 +806,9 @@ function inspectSupport( const info = lowerer.classes.get(t.className); if (!info) return `class '${t.className}' has no inspect lowering`; // EventTarget and Event subclasses render through Node's inspectors - // for those classes (the runtime's capsule view). - if (eventTargetRootOf(info) !== null) return null; + // for those classes (the runtime's capsule view), and so do classes + // declared `extends Date`. + if (eventTargetRootOf(info) !== null || dateRootOf(info) !== null) return null; if (isErrorClass(lowerer, t.className)) { if (userErrorClasses(info).length > 0 && errorHeaderOverridden(lowerer, info)) return "error subclasses whose name, message or stack is an accessor or a prototype property have no inspect lowering yet"; @@ -957,7 +960,10 @@ export function inspectExpr( loc, }; case "object": - if (eventTargetRootOf(lowerer.classes.get(t.className)) !== null) { + if ( + eventTargetRootOf(lowerer.classes.get(t.className)) !== null || + dateRootOf(lowerer.classes.get(t.className)) !== null + ) { return { kind: "libCall", fn: "insp.dyn", @@ -1145,7 +1151,7 @@ function inspectHelper(lowerer: Lowerer, t: IrType, loc: SrcLoc): string { const key = `insp:${typeKey(t)}`; const existing = lowerer.inspectHelpers.get(key); if (existing) return existing; - const name = `%util.insp.${lowerer.inspectHelpers.size}`; + const name = keyedHelperName(lowerer, "%util.insp", key); lowerer.inspectHelpers.set(key, name); const v = (): IrExpr => varRef("v.0", t, loc); @@ -2082,7 +2088,7 @@ function formatUnionHelper( const existing = lowerer.inspectHelpers.get(key); if (existing) return existing; const loc = helperLoc(site); - const name = `%util.fmtv.${lowerer.inspectHelpers.size}`; + const name = keyedHelperName(lowerer, "%util.fmtv", key); lowerer.inspectHelpers.set(key, name); const def = lowerer.unions.get(t.unionId); if (!def) throw new InternalCompilerError(`format value over unknown union ${t.unionId}`); diff --git a/packages/compiler/src/frontend/lowering/lower-mixins.ts b/packages/compiler/src/frontend/lowering/lower-mixins.ts index 766059dfb..9de027563 100644 --- a/packages/compiler/src/frontend/lowering/lower-mixins.ts +++ b/packages/compiler/src/frontend/lowering/lower-mixins.ts @@ -34,6 +34,7 @@ * statics-bearing mixin classes outside a plain top-level statement * (their declaration-time code must run exactly where the call * evaluates). */ +import { positionTag } from "./structural-positions.js"; import * as ts from "../ts7/adapter.js"; import type { Lowerer } from "./lowerer.js"; import { PoisonError } from "./lowerer.js"; @@ -452,7 +453,7 @@ function instantiateMixinCall( const base = mixinBaseClassOf(lowerer, call.arguments.nodes[0]!); const instName = lowerer.qualify( ts.getSourceFileOfNode(call), - `%mx${ts.tokenStartOfNode(call)}.${shape.classNode.name?.text ?? ""}`, + `%mx${positionTag(lowerer, call)}.${shape.classNode.name?.text ?? ""}`, ); const ordinal = lowerer.mixinOrdinals.get(shape.classNode) ?? 0; lowerer.mixinOrdinals.set(shape.classNode, ordinal + 1); diff --git a/packages/compiler/src/frontend/lowering/lower-mock.ts b/packages/compiler/src/frontend/lowering/lower-mock.ts index fcc68c787..8c50dee46 100644 --- a/packages/compiler/src/frontend/lowering/lower-mock.ts +++ b/packages/compiler/src/frontend/lowering/lower-mock.ts @@ -17,6 +17,7 @@ * writes the original back on restore(). Each mock registers a closure * that calls its restore() with its tracker (scr_test.c): the module's * `mock`, or the test's t.mock, which is reset when the test ends. */ +import { keyedHelperName } from "./stable-names.js"; import * as ts from "../ts7/adapter.js"; import { BOOL, @@ -136,7 +137,7 @@ function liftOnce( const key = `mock.${role}:${owner}`; const existing = lowerer.assertHelpers.get(key); if (existing) return existing; - const name = `%mock.${role}.${lowerer.assertHelpers.size}`; + const name = keyedHelperName(lowerer, `%mock.${role}`, key); lowerer.assertHelpers.set(key, name); build(name); return name; diff --git a/packages/compiler/src/frontend/lowering/lower-modules.test.ts b/packages/compiler/src/frontend/lowering/lower-modules.test.ts index 84cc96e7d..f1021e4da 100644 --- a/packages/compiler/src/frontend/lowering/lower-modules.test.ts +++ b/packages/compiler/src/frontend/lowering/lower-modules.test.ts @@ -34,7 +34,7 @@ test("retains dependencies from function storage, captures, generator channels a const completed = record("completed"); const body = record("body"); const global = record("global", record("nested")); - const wanted = lowerer.shapes.shapes.map((shape) => shape.id); + const wanted = lowerer.shapes.shapes.map((shape) => shape.id).sort(); record("unused"); const unionId = lowerer.unions.intern([body, UNDEFINED_T]); const unusedUnion = lowerer.unions.intern([F64, UNDEFINED_T]); @@ -162,7 +162,7 @@ test("closes nested structural types and index-signature values", () => { sent = record("sent"), indexed = record("indexed"); const containerId = lowerer.shapes.intern([], false, indexed); - const wanted = lowerer.shapes.shapes.map((shape) => shape.id); + const wanted = lowerer.shapes.shapes.map((shape) => shape.id).sort(); record("unused"); const nested: IrType = { kind: "func", diff --git a/packages/compiler/src/frontend/lowering/lower-modules.ts b/packages/compiler/src/frontend/lowering/lower-modules.ts index d1f276d44..5238333ad 100644 --- a/packages/compiler/src/frontend/lowering/lower-modules.ts +++ b/packages/compiler/src/frontend/lowering/lower-modules.ts @@ -1,4 +1,5 @@ import { THREADS_MODULE } from "../threads-import.js"; +import { positionTag } from "./structural-positions.js"; import { EXPERIMENTAL_MODULE } from "../experimental-import.js"; import { dynUndefinedExpr } from "../../ir/build.js"; import { everyStmtList, everyTypeChild } from "../../ir/traverse.js"; @@ -148,6 +149,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 { dateClassOperationPrelude } from "./builtins/date-classes.js"; import { cjsAccessorSnapshotStores, jsHoldsDynObject } from "./lower-exprs.js"; import { keptIdentityAssertion } from "./assertion-identity.js"; @@ -1074,8 +1076,14 @@ export function moduleArtifacts( else delete rest.abstractMethods; return rest; }), - records: lowerer.shapes.shapes.filter((r) => shapeIds.has(r.id)), - unions: lowerer.unions.unions.filter((u) => unionIds.has(u.id)), + // Ids come from what each shape and union is (keyedHelperName), so + // ordering by id gives every lowering order the same module. + records: lowerer.shapes.shapes + .filter((r) => shapeIds.has(r.id)) + .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)), + unions: lowerer.unions.unions + .filter((u) => unionIds.has(u.id)) + .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)), }; } @@ -1677,7 +1685,7 @@ export function collectGlobals( } if (type.kind === "void") lowerer.badType(stmt.name, lowerer.typeOf(stmt.name)); const g: IrGlobal = { - id: `%g.${tag}${nsPathPrefix(stmt)}%alias.${stmt.name.text}%${ts.tokenStartOfNode(stmt)}`, + id: `%g.${tag}${nsPathPrefix(lowerer, stmt)}%alias.${stmt.name.text}%${positionTag(lowerer, stmt)}`, name: stmt.name.text, type, mutable: false, @@ -1754,7 +1762,7 @@ export function collectGlobals( // (`%g.e.A%B.x`), so `namespace A { export const x }` and a // top-level `const x` never collide; non-exported members add the // declaring block's position (block-local bindings). - const nsPrefix = nsPathPrefix(stmt, list.declarations.nodes[0]); + const nsPrefix = nsPathPrefix(lowerer, stmt, list.declarations.nodes[0]); for (const decl of list.declarations.nodes) { // --provenance-sources: an elided pure-annotated dead const in a // fetched source module registers no global (the statement @@ -2921,6 +2929,38 @@ export function lowerDefaultExport(lowerer: Lowerer, stmt: ts.ExportAssignment): return { kind: "assign", localId: g.id, value, loc: locOf(stmt) }; } +/** Marks the runtime fences recorded since `fencesBefore` that lie in + * `sf`'s top-level code: they run when the module initializes. A fence + * inside a function, or inside a class member that runs later (a method, + * accessor, constructor or instance field initializer), runs when that + * code is called. */ +function markModuleInitFences(lowerer: Lowerer, sf: ts.SourceFile, fencesBefore: number): void { + for (let i = fencesBefore; i < lowerer.runtimeFences.length; i++) { + const fence = lowerer.runtimeFences[i]!; + if (fence.loc.file !== sf.fileName || runsAfterModuleInit(sf, fence.loc.start)) continue; + lowerer.runtimeFences[i] = { ...fence, startup: true }; + } +} + +/** Whether the code at `pos` sits in a function or a later-running class + * member body. */ +function runsAfterModuleInit(sf: ts.SourceFile, pos: number): boolean { + let later = false; + ts.walkPreorder(sf, (node) => { + if (node.pos > pos || node.end <= pos) return "skip"; + if ( + ts.isFunctionLike(node) || + (ts.isPropertyDeclaration(node) && + !node.modifiers?.nodes.some((m) => m.kind === ts.SyntaxKind.StaticKeyword)) + ) { + later = true; + return "stop"; + } + return undefined; + }); + return later; +} + export function lowerFileInit( lowerer: Lowerer, sf: ts.SourceFile, @@ -2930,6 +2970,7 @@ export function lowerFileInit( const isAsync = lowerer.asyncInitFiles.has(sf); const ctx = newFnCtx(false, null, null, VOID); ctx.isAsync = isAsync; + const fencesBefore = lowerer.runtimeFences.length; lowerer.fnStack.push(ctx); try { const loc0: SrcLoc = { file: sf.fileName, start: 0, end: 0 }; @@ -3280,6 +3321,7 @@ export function lowerFileInit( }; } finally { lowerer.fnStack.pop(); + markModuleInitFences(lowerer, sf, fencesBefore); } } @@ -3376,6 +3418,7 @@ export function buildMain(lowerer: Lowerer): IrFunction { ...lowerer.mainPrelude, ...cjsModuleRegistryPrelude(lowerer, loc), ...handleEventReaderPrelude(lowerer, loc), + ...dateClassOperationPrelude(lowerer, loc), ]; const roots = [lowerer.entry, ...lowerer.forkTargets, ...lowerer.workerTargets]; const isAsync = roots.some((root) => lowerer.asyncInitFiles.has(root)); diff --git a/packages/compiler/src/frontend/lowering/lower-namespaces.ts b/packages/compiler/src/frontend/lowering/lower-namespaces.ts index dca835d77..ea844ab1e 100644 --- a/packages/compiler/src/frontend/lowering/lower-namespaces.ts +++ b/packages/compiler/src/frontend/lowering/lower-namespaces.ts @@ -36,8 +36,9 @@ * of the compiler already takes (a body running before the declaring * statement is not modeled — same as top-level const reads through early * calls). */ +import { positionTag, type PositionTagOwner } from "./structural-positions.js"; import * as ts from "../ts7/adapter.js"; -import { packageShimFor } from "../package-shims.js"; +import { isPackageShimFile, isShimIntrinsicName, packageShimFor } from "../package-shims.js"; import type { Lowerer } from "./lowerer.js"; import { boundIdentifiersOf } from "./lowerer.js"; import type { FileParts } from "./lower-modules.js"; @@ -164,7 +165,11 @@ function registerTypeOnlyBlocks(lowerer: Lowerer, decl: ts.ModuleDeclaration): v * distinct (resolution is by symbol; names only need uniqueness and * determinism). `modifierDecl` carries the declaration whose modifiers * decide exportedness (the first declarator of a variable statement). */ -export function nsPathPrefix(node: ts.Node, modifierDecl?: ts.Node): string { +export function nsPathPrefix( + owner: PositionTagOwner, + node: ts.Node, + modifierDecl?: ts.Node, +): string { const parent = node.parent; if (parent === undefined || !ts.isModuleBlock(parent)) return ""; const flagsHost = modifierDecl ?? node; @@ -179,10 +184,10 @@ export function nsPathPrefix(node: ts.Node, modifierDecl?: ts.Node): string { const nested = p.parent !== undefined && ts.isModuleBlock(p.parent); const nonExported = nested && (ts.getCombinedModifierFlags(p) & ts.ModifierFlags.Export) === 0; - segs.unshift(p.name.text + (nonExported ? `%${ts.tokenStartOfNode(p)}` : "")); + segs.unshift(p.name.text + (nonExported ? `%${positionTag(owner, p)}` : "")); } } - return `${segs.join("%")}${exported ? "" : `%${ts.tokenStartOfNode(parent)}`}.`; + return `${segs.join("%")}${exported ? "" : `%${positionTag(owner, parent)}`}.`; } /** The registered namespace-block kind a symbol's declaration sits in @@ -649,6 +654,12 @@ export function ambientUndefinedFnSymbolOf( const sym = lowerer.resolveValueSymbol(ident); if (!sym || !(sym.flags & ts.SymbolFlags.Function)) return null; if (lowerer.isStdlibSymbol(sym)) return null; + // A package shim's runtime intrinsic (lower-calls.ts) is defined. + if ( + isShimIntrinsicName(ident.text) && + sym.declarations.some((d) => isPackageShimFile(ts.getSourceFileOfNode(d).fileName)) + ) + return null; let sawFn = false; for (const d of sym.declarations) { if (ts.isInterfaceDeclaration(d) || ts.isTypeAliasDeclaration(d)) continue; // type-world merge partners diff --git a/packages/compiler/src/frontend/lowering/lower-server.ts b/packages/compiler/src/frontend/lowering/lower-server.ts index 058d7874a..d9746e1f6 100644 --- a/packages/compiler/src/frontend/lowering/lower-server.ts +++ b/packages/compiler/src/frontend/lowering/lower-server.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "./stable-names.js"; import { dynUndefinedExpr, nodeThrowExpr, @@ -183,7 +184,7 @@ export function voidizedCallback(lowerer: Lowerer, cb: IrExpr, loc: SrcLoc): IrE const toT = funcOf([...fromT.params], VOID); const key = `server.voidcb:${typeKey(fromT)}`; const existing = lowerer.arrHofHelpers.get(key); - const name = existing ?? `%server.voidcb.${lowerer.arrHofHelpers.size}`; + const name = existing ?? keyedHelperName(lowerer, "%server.voidcb", key); if (!existing) { lowerer.arrHofHelpers.set(key, name); const impl = `${name}.impl`; @@ -279,7 +280,7 @@ function receiverReturningCall( ): IrExpr { const key = `server.recvret:${fn}:${opts?.prefix?.fn ?? ""}:${(opts?.mainArgIndices ?? []).join(".")}:${callArgs.map((a) => typeKey(a.type)).join(",")}`; const existing = lowerer.arrHofHelpers.get(key); - const name = existing ?? `%server.recvret.${lowerer.arrHofHelpers.size}`; + const name = existing ?? keyedHelperName(lowerer, "%server.recvret", key); if (!existing) { lowerer.arrHofHelpers.set(key, name); const params = callArgs.map((a, i) => ({ localId: `p${i}.0`, name: `p${i}`, type: a.type })); @@ -590,7 +591,7 @@ function h2HeadersCallbackAdapter( ); const key = `h2.hdrcb:${handleKind}:${withStatus}:${typeKey(fromT)}:${shapeId ?? ""}`; const existing = lowerer.arrHofHelpers.get(key); - const name = existing ?? `%h2.hdrcb.${lowerer.arrHofHelpers.size}`; + const name = existing ?? keyedHelperName(lowerer, "%h2.hdrcb", key); if (!existing) { lowerer.arrHofHelpers.set(key, name); const impl = `${name}.impl`; @@ -2938,6 +2939,26 @@ function lowerNetSocketMethodCall( loc, }; } + if (event === "secure") { + // The handshake's completion on a TLS socket (after secureConnect on + // a client); plain sockets never fire it. + const { cb } = lowerCallbackArg( + lowerer, + args[1]!, + "secure listeners", + 0, + () => false, + "use ()", + [], + ); + return { + kind: "libCall", + fn: "tls.sockOnSecure", + args: [receiver, cb, once], + type: VOID, + loc, + }; + } if (event === "session") { // The received-ticket event: fires once per TLS client socket with // the serialized session (a Buffer); plain sockets never fire it. @@ -2961,7 +2982,7 @@ function lowerNetSocketMethodCall( lowerer.noLowering( `socket.${name}(${event === null ? "non-literal event" : `"${event}"`}, ...)`, args[0]!, - '"data", "end", "close", "error", "connect", "lookup", "ready", "timeout", "readable", "secureConnect", and "session" are the supported socket events (as literals)', + '"data", "end", "close", "error", "connect", "lookup", "ready", "timeout", "readable", "secureConnect", "secure", and "session" are the supported socket events (as literals)', ); } lowerer.noLowering( @@ -3583,7 +3604,7 @@ export function lowerCompatReqStreamOptionalCall( type: unionT, loc, }; - const id = `chain.${lowerer.chainCounter++}`; + const id = lowerer.closureName(loc, "", "chain"); const body = lowerH2StreamMethodCall(lowerer, call, call.expression, { kind: "chainRecv", id, @@ -4424,7 +4445,7 @@ function lowerHttpCreateServerForms( const hasMax = opts.maxHeaderSize !== null; const key = `server.opts:${opts.joinDup ? 1 : 0}:${opts.allowMissingHost ? 1 : 0}:${hasBuffer ? 1 : 0}:${hasMax ? 1 : 0}`; const existing = lowerer.arrHofHelpers.get(key); - const name = existing ?? `%server.opts.${lowerer.arrHofHelpers.size}`; + const name = existing ?? keyedHelperName(lowerer, "%server.opts", key); if (!existing) { lowerer.arrHofHelpers.set(key, name); const params = [ @@ -4675,6 +4696,125 @@ export function lowerHttpServerNew(lowerer: Lowerer, expr: ts.NewExpression): Ir return lowerHttpCreateServerForms(lowerer, expr, "new http.Server", locOf(expr)); } +/** `new tls.TLSSocket(socket, options)` in server mode: a new TLS socket + * takes over the socket's connection and runs the server handshake + * (scr_tls_wrap_socket). The options record reads at runtime, the + * tls.connect precedent. A literal's secureContext member is a + * SecureContext handle, which the checked-dynamic record cannot hold, so + * it passes as its own argument; members after it must be free of side + * effects, because it is read after them. Node never starts the handshake + * of a client-mode TLSSocket, so a literal without isServer: true fences + * here. */ +export function lowerTlsSocketNew(lowerer: Lowerer, expr: ts.NewExpression): IrExpr | null { + const callee = expr.expression; + const isTlsSocket = + (ts.isPropertyAccessExpression(callee) && + callee.name.text === "TLSSocket" && + lowerer.builtinMemberOf(callee)?.module === "tls") || + (ts.isIdentifier(callee) && + lowerer.builtinImportOf(callee)?.module === "tls" && + lowerer.builtinImportOf(callee)?.member === "TLSSocket"); + if (!isTlsSocket) return null; + const loc = locOf(expr); + const HINT = + "the supported forms are new tls.TLSSocket(socket, { isServer: true, cert, key }) and new tls.TLSSocket(socket, { isServer: true, secureContext })"; + const args = expr.arguments?.nodes ?? []; + if (args.length !== 2 || args.some(ts.isSpreadElement)) { + lowerer.noLowering(`new tls.TLSSocket with ${args.length} argument(s)`, expr, HINT); + } + const socket = lowerer.lowerExpr(args[0]!); + if (socket.type.kind !== "netSocket") { + lowerer.noLowering( + `new tls.TLSSocket over a '${lowerer.fmt(socket.type)}' value`, + args[0]!, + "the wrapped value must be a net.Socket (a server connection or an http CONNECT socket)", + ); + } + let optsNode: ts.Expression = args[1]!; + while (ts.isParenthesizedExpression(optsNode)) optsNode = optsNode.expression; + if (!ts.isObjectLiteralExpression(optsNode)) { + const o = lowerer.lowerExpr(optsNode); + const opts: IrExpr = + o.type.kind === "dyn" + ? o + : canConvertToDyn( + o.type, + (id) => lowerer.shapes.get(id), + (id) => lowerer.unions.get(id), + ) + ? { kind: "dynFrom", value: o, type: DYN, loc } + : lowerer.noLowering( + `new tls.TLSSocket with a '${lowerer.fmt(o.type)}' options record`, + optsNode, + `${HINT} — a secureContext member lowers in an options object literal`, + ); + return { kind: "libCall", fn: "tls.wrapSocket", args: [socket, opts], type: NETSOCKET_T, loc }; + } + const props = optsNode.properties.nodes; + const nameOf = (p: ts.ObjectLiteralElementLike): string | null => + (ts.isPropertyAssignment(p) || ts.isShorthandPropertyAssignment(p)) && + (ts.isIdentifier(p.name) || ts.isStringLiteral(p.name)) + ? p.name.text + : null; + const isServer = props.find((p) => nameOf(p) === "isServer"); + if ( + isServer === undefined || + (ts.isPropertyAssignment(isServer) && isServer.initializer.kind === ts.SyntaxKind.FalseKeyword) + ) { + lowerer.noLowering( + "new tls.TLSSocket in client mode", + optsNode, + "Node starts no handshake for a client-mode TLSSocket — pass isServer: true for the server side; tls.connect makes client sockets", + ); + } + const ctxIndex = props.findIndex((p) => nameOf(p) === "secureContext"); + if (ctxIndex < 0) { + const opts = lowerDynObjectLiteral(lowerer, optsNode); + return { kind: "libCall", fn: "tls.wrapSocket", args: [socket, opts], type: NETSOCKET_T, loc }; + } + const ctxProp = props[ctxIndex]!; + const ctxNode = ts.isShorthandPropertyAssignment(ctxProp) + ? ctxProp.name + : (ctxProp as ts.PropertyAssignment).initializer; + for (const p of props.slice(ctxIndex + 1)) { + const pure = + ts.isShorthandPropertyAssignment(p) || + (ts.isPropertyAssignment(p) && sideEffectFreeOptionValue(p.initializer)); + if (!pure) { + lowerer.noLowering( + "a new tls.TLSSocket options literal with side effects after secureContext", + p, + "secureContext is read after the other members — move it to the end of the object", + ); + } + } + let ctx: IrExpr | null = null; + const opts = lowerDynObjectLiteral(lowerer, optsNode, (node, value) => { + if (node !== ctxNode) return lowerer.coerceToExpected(value, DYN); + if (value.type.kind !== "secureCtx") { + lowerer.noLowering( + `a '${lowerer.fmt(value.type)}' secureContext`, + node, + "pass a tls.createSecureContext({ cert, key }) result", + ); + } + ctx = value; + return { + kind: "dynFrom", + value: { kind: "unitLit", unit: "undefined", type: UNDEFINED_T, loc }, + type: DYN, + loc, + }; + }); + return { + kind: "libCall", + fn: "tls.wrapSocketCtx", + args: [socket, opts, ctx!], + type: NETSOCKET_T, + loc, + }; +} + /** Module-function calls on http import bindings: createServer([options][, * handler]) and the call-form Server (Node's constructor works without * `new` — test/parallel's http.Server(fn) spelling). The handler takes @@ -4984,14 +5124,14 @@ function lowerTlsServerOptionsOrDyn( * connect(options[, cb]) and connect(port[, host][, options][, cb]) with * a RUNTIME options record (the checked-dynamic JS lane's shape — a dyn * value, or a record that converts): the runtime walk implements - * port/host/rejectUnauthorized/ca/servername/ALPNProtocols/minVersion/maxVersion/timeout and throws the catchable + * port/host/socket/rejectUnauthorized/ca/servername/ALPNProtocols/minVersion/maxVersion/timeout and throws the catchable * fence for other documented members (the divergence-66 stance). The * callback (and 'secureConnect'/'connect' listeners) fires * post-handshake — Node's secureConnect timing. */ function lowerTlsConnectCall(lowerer: Lowerer, expr: ts.CallExpression, loc: SrcLoc): IrExpr { const args = expr.arguments.nodes; const FORMS_HINT = - "the supported forms are connect(options[, cb]) and connect(port[, host][, options][, cb]) — options implement port/host/rejectUnauthorized/ca/servername/ALPNProtocols/minVersion/maxVersion/timeout"; + "the supported forms are connect(options[, cb]) and connect(port[, host][, options][, cb]) — options implement port/host/socket/rejectUnauthorized/ca/servername/ALPNProtocols/minVersion/maxVersion/timeout"; if (args.length < 1 || args.length > 4 || args.some(ts.isSpreadElement)) { lowerer.noLowering(`tls.connect with ${args.length} arguments`, expr, FORMS_HINT); } @@ -5042,7 +5182,22 @@ function lowerTlsConnectCall(lowerer: Lowerer, expr: ts.CallExpression, loc: Src // The options value rides whole to the runtime walk: dyn passes // directly; a typed record that converts boxes into the checked-dynamic tree. let opts: IrExpr; - if (optsNode !== null) { + let literal: ts.Expression | null = optsNode; + while (literal !== null && ts.isParenthesizedExpression(literal)) literal = literal.expression; + if ( + literal !== null && + ts.isObjectLiteralExpression(literal) && + literal.properties.nodes.some( + (p) => + (ts.isPropertyAssignment(p) || ts.isShorthandPropertyAssignment(p)) && + ts.isIdentifier(p.name) && + p.name.text === "socket", + ) + ) { + // A socket member is a handle the record form cannot box: the literal + // builds the checked-dynamic object member by member. + opts = lowerDynObjectLiteral(lowerer, literal); + } else if (optsNode !== null) { const o = lowerer.lowerExpr(optsNode); if (o.type.kind === "dyn") { opts = o; @@ -8009,7 +8164,7 @@ function lowerHttpResMethodCall( const all = [...callArgs, cb]; const key = `server.endcb:${fn}:${all.map((a) => typeKey(a.type)).join(",")}`; const existing = lowerer.arrHofHelpers.get(key); - const helper = existing ?? `%server.endcb.${lowerer.arrHofHelpers.size}`; + const helper = existing ?? keyedHelperName(lowerer, "%server.endcb", key); if (!existing) { lowerer.arrHofHelpers.set(key, helper); const params = all.map((a, i) => ({ localId: `p${i}.0`, name: `p${i}`, type: a.type })); diff --git a/packages/compiler/src/frontend/lowering/lower-stdlib.ts b/packages/compiler/src/frontend/lowering/lower-stdlib.ts index 2ad3657c7..0beb24a0e 100644 --- a/packages/compiler/src/frontend/lowering/lower-stdlib.ts +++ b/packages/compiler/src/frontend/lowering/lower-stdlib.ts @@ -2278,7 +2278,7 @@ function lowerStaticNamespaceImport( ): IrExpr { const loc = locOf(call); const resultT: IrType & { kind: "promise" } = { kind: "promise", inner: ns }; - const fnName = `%fn${lowerer.lambdaCounter++}_staticImport`; + const fnName = lowerer.closureName(loc, "_staticImport"); const fnType: IrType & { kind: "func" } = { kind: "func", params: [], ret: resultT }; const fnCtx = newFnCtx(true, null, fnType, ns); fnCtx.isAsync = true; diff --git a/packages/compiler/src/frontend/lowering/lower-stmts.ts b/packages/compiler/src/frontend/lowering/lower-stmts.ts index e3480cf9c..ea5ef72ac 100644 --- a/packages/compiler/src/frontend/lowering/lower-stmts.ts +++ b/packages/compiler/src/frontend/lowering/lower-stmts.ts @@ -2,7 +2,8 @@ import { lowerTupleAliasDecl, stripTypeWrappers } from "./typed-arguments.js"; import { declaredMemberOf, isPromisePrototypeRead } from "./expressions/property-access.js"; import { hostsAll } from "./expressions/hosted-narrowing.js"; import { requestGeneralStreamSurface } from "./general-streams.js"; -import { lowerForAwaitDynStream } from "./dyn-streams.js"; +import { lowerForAwaitDynStream, nodeStreamInterfaceSide } from "./dyn-streams.js"; +import { lowerForAwaitValueStream } from "./builtins/hash-stream.js"; import { lowerChildPropertyWrite } from "./handle-properties.js"; import { matchAllRowsReadByElements, @@ -66,9 +67,11 @@ import { F64, type IrExpr, type IrGlobal, + type IrLibFn, type IrLocal, type IrStmt, type IrType, + SEARCH_PARAMS_T, STRING, type SrcLoc, UNDEFINED_T, @@ -105,6 +108,7 @@ import { COMPOUND_ASSIGN_OPS, type CompoundOp, STR_METHODS, + NARROW_FIRST, UNSUPPORTED_STMT, isStdlibMember, sideEffectFreeOptionValue, @@ -138,6 +142,8 @@ import { bindingGenericFnAliasInfoOf, bindingGenericFnInfoOf, bindingGenericFnNodeOf, + genericBindingPresenceStore, + genericBindingStoredValue, implicitLocalFnInfoOf, implicitLocalFnNodeOf, implicitMethodCallInfersReturn, @@ -160,7 +166,11 @@ import { objectFactorySignature } from "./object-factory-new.js"; import { isClassCallback, lowerClassCallbackAssign } from "./class-callbacks.js"; import { classForInHasKey, classPropertiesHelper } from "./class-dynamic-dispatch.js"; import { genericIfaceBindingKeepsClass, superConditionLead } from "./lower-classes.js"; -import { lowerStreamUnderscoreAssign, streamClassAliasDecl } from "./lower-stream.js"; +import { + lowerStreamUnderscoreAssign, + streamClassAliasDecl, + streamSidesOf, +} from "./lower-stream.js"; import { staticAssertInstanceDecl } from "./assert-instances.js"; import { lowerHttpResPropertyAssignment, @@ -236,6 +246,7 @@ 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"; +import { iterableUnionOf, lowerForOfIterable } from "./iterable-values.js"; interface UsingRegistration { acquire: IrStmt[]; @@ -1520,6 +1531,14 @@ export function lowerStmt(lowerer: Lowerer, stmt: ts.Statement): IrStmt | IrStmt const info = lowerer.lowerClassExpressionInfo(stmt); const type: IrType = { kind: "classval", className: info.def.name }; const local = lowerer.declareLocal(stmt.name, stmt.name.text, type, true); + // Static members of a function-local class run while the class value is + // built and may read the class by name: the class value assigns the + // binding before them. + if (info.localClass && (info.runtimeStatics || info.runtimePrototypeMembers)) + return [ + { kind: "varDecl", localId: local.id, init: null, loc: locOf(stmt) }, + { kind: "exprStmt", expr: lowerer.lowerClassExpression(stmt, local), loc: locOf(stmt) }, + ]; const init = lowerer.lowerClassExpression(stmt); return { kind: "varDecl", localId: local.id, init, loc: locOf(stmt) }; } @@ -3207,6 +3226,20 @@ export function lowerBindingPattern( lowerModuleNamespacePattern(lowerer, pattern, nsSource, isLet, out); return; } + if (srcType.kind === "url") { + lowerUrlObjectPattern(lowerer, pattern, srcRef, isLet, out); + return; + } + if ( + srcType.kind === "union" && + !isJsSourceFile(ts.getSourceFileOfNode(pattern)) && + lowerer.unions + .get(srcType.unionId) + ?.arms.every((arm) => arm.kind === "record" || arm.kind === "object") + ) { + lowerUnionObjectPattern(lowerer, pattern, srcRef, srcType, isLet, out); + return; + } if (srcType.kind !== "record") { lowerer.unsupported( "SC1031", @@ -3421,7 +3454,10 @@ function patternSourceValue( !arms || !present?.length || present.length === arms.length || - (present.length > 1 && !(arrayPattern && present.every((arm) => arm.kind === "array"))) + (present.length > 1 && + !(arrayPattern + ? present.every((arm) => arm.kind === "array") + : present.every((arm) => arm.kind === "record" || arm.kind === "object"))) ) return value; for (const [tag, arm] of arms.entries()) { @@ -3538,6 +3574,149 @@ function lowerModuleNamespacePattern( } } +/** The URL getters an object pattern reads (`const { protocol, hostname } + * = new URL(text)`), each a read of the URL's current serialization. */ +const URL_PATTERN_GETTERS: Record = { + href: "url.href", + origin: "url.origin", + protocol: "url.protocol", + username: "url.username", + password: "url.password", + host: "url.host", + hostname: "url.hostname", + port: "url.port", + pathname: "url.pathname", + search: "url.search", + hash: "url.hash", +}; + +/** An object pattern over a URL: each element reads its getter in pattern + * order, as `url.name` does; `searchParams` binds the URL's live view. + * Methods and rest elements stay fenced. */ +function lowerUrlObjectPattern( + lowerer: Lowerer, + pattern: ts.ObjectBindingPattern, + srcRef: () => IrExpr, + isLet: boolean, + out: IrStmt[], +): void { + for (const el of pattern.elements.nodes) { + if (el.name === undefined) continue; + if (el.dotDotDotToken) { + lowerer.unsupported( + "SC1031", + el, + "rest bindings over URL sources (a URL's properties are prototype getters, which rest elements do not copy)", + ); + } + const prop = el.propertyName ?? el.name; + const propName = + ts.isIdentifier(prop) || + ts.isComputedPropertyName(prop) || + ts.isStringLiteralLike(prop) || + ts.isNumericLiteral(prop) + ? patternKeyNameOf(lowerer, prop as ts.PropertyName) + : null; + const loc = locOf(el); + let value: IrExpr; + if (propName !== null && Object.hasOwn(URL_PATTERN_GETTERS, propName)) { + value = { + kind: "libCall", + fn: URL_PATTERN_GETTERS[propName]!, + args: [srcRef()], + type: STRING, + loc, + }; + } else if (propName === "searchParams") { + value = { + kind: "libCall", + fn: "url.searchParams", + args: [srcRef()], + type: SEARCH_PARAMS_T, + loc, + }; + } else { + lowerer.unsupported( + "SC1031", + el, + propName === null + ? "destructuring with computed keys that do not fold to one property name" + : `destructuring '${propName}' from a URL (${Object.keys(URL_PATTERN_GETTERS).join(", ")} and searchParams are the supported URL properties)`, + ); + } + if (el.initializer) value = applyBindingDefault(lowerer, el, value); + lowerer.bindPatternTarget(el.name, value, isLet, out); + } +} + +/** An object pattern over a union of records and class instances + * (`function f({ kind, path }: Add | Remove)`): each element reads a data + * field every arm declares with one type, through the runtime tag, as + * `value.field` does. Rest elements and fields the arms type differently + * stay fenced. */ +function lowerUnionObjectPattern( + lowerer: Lowerer, + pattern: ts.ObjectBindingPattern, + srcRef: () => IrExpr, + srcType: IrType & { kind: "union" }, + isLet: boolean, + out: IrStmt[], +): void { + const arms = lowerer.unions.get(srcType.unionId)?.arms ?? []; + for (const el of pattern.elements.nodes) { + if (el.name === undefined) continue; + if (el.dotDotDotToken) { + lowerer.unsupported("SC1031", el, `rest bindings over union sources (${NARROW_FIRST})`); + } + const prop = el.propertyName ?? el.name; + const propName = + ts.isIdentifier(prop) || + ts.isComputedPropertyName(prop) || + ts.isStringLiteralLike(prop) || + ts.isNumericLiteral(prop) + ? patternKeyNameOf(lowerer, prop as ts.PropertyName) + : null; + if (propName === null) { + lowerer.unsupported( + "SC1031", + el, + "destructuring with computed keys that do not fold to one property name", + ); + } + let common: IrType | null = null; + for (const arm of arms) { + let ft: IrType | undefined; + if (arm.kind === "record") { + ft = lowerer.shapes.get(arm.shapeId)?.fields.find((f) => f.name === propName)?.type; + } else if (arm.kind === "object") { + ft = lowerer.classes.get(arm.className)?.fields.get(propName); + } + if (!ft || ft.kind === "void" || isUnitType(ft) || (common && !typeEquals(common, ft))) { + common = null; + break; + } + common = ft; + } + if (common === null) { + lowerer.unsupported( + "SC1031", + el, + `destructuring '${propName}' from a union whose arms type it differently (every arm must be a record or class with a same-typed field '${propName}' — ${NARROW_FIRST})`, + ); + } + let value: IrExpr = { + kind: "unionDisc", + unionId: srcType.unionId, + field: propName, + value: srcRef(), + type: common, + loc: locOf(el), + }; + if (el.initializer) value = applyBindingDefault(lowerer, el, value); + lowerer.bindPatternTarget(el.name, value, isLet, out); + } +} + /** Whether a pattern's first element has a computed key that does not * fold to one property name, so the key evaluates at run time. */ function startsWithRuntimeKey(lowerer: Lowerer, pattern: ts.ObjectBindingPattern): boolean { @@ -3888,6 +4067,9 @@ function stdlibGlobalTokenDestructure( if (decl.initializer === undefined || !isJsSourceFile(ts.getSourceFileOfNode(decl))) return null; const globalName = stdlibGlobalNameOf(lowerer, decl.initializer); if (globalName === null) return null; + // `workerData` is a value (the data the worker was started with), not an + // API surface: its members destructure as any untyped value's do. + if (globalName === "workerData") return null; if (!ts.isObjectBindingPattern(decl.name)) { lowerer.unsupported( "SC1031", @@ -3964,9 +4146,13 @@ function stdlibGlobalTokenDestructure( const canonical = ts.symbolName(member) === "global" ? "globalThis" : ts.symbolName(member); 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); + // Builtin constructors read as their interned function values, and + // crypto as the WebCrypto object: the same values the bare and + // `globalThis.X` spellings read. + value = + canonical === "crypto" + ? { kind: "libCall", fn: "webcrypto.object", args: [], type: DYN, loc: locOf(el) } + : 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)) { @@ -4789,9 +4975,10 @@ export function lowerVarDeclList( * `never[]` or `any[]` and each later read by the elements written before * it, and reads inside closures as the unsettled array. When every read * with a settled element type maps to the same array type, the binding has - * that type. When reads disagree or the binding is reassigned, it is - * checked-dynamic, as the same binding is at module scope. Null for other - * bindings. */ + * that type. When reads disagree, a write (`xs.push(v)`, `xs.unshift(v)`, + * `xs.push(...values)`, `xs[i] = v`) stores a value that type's element does + * not hold, or the binding is reassigned, it is checked-dynamic, as the same + * binding is at module scope. Null for other bindings. */ function evolvingArrayType(lowerer: Lowerer, decl: ts.VariableDeclaration): IrType | null { if (!ts.isIdentifier(decl.name) || decl.initializer === undefined) return null; let initializer: ts.Expression = decl.initializer; @@ -4813,6 +5000,9 @@ function evolvingArrayType(lowerer: Lowerer, decl: ts.VariableDeclaration): IrTy }; const scope = owner(decl); let result: IrType | null = null; + // The values the binding's writes store, checked against the element + // type once the reads settle it. + const written: ts.Expression[] = []; // The file's identifiers are indexed by name once (identifiersNamed), so // each binding resolves only the uses spelled like it. for (const node of identifiersNamed(lowerer, ts.getSourceFileOfNode(decl), decl.name.text)) { @@ -4832,6 +5022,22 @@ function evolvingArrayType(lowerer: Lowerer, decl: ts.VariableDeclaration): IrTy parent.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && parent.operatorToken.kind <= ts.SyntaxKind.LastAssignment; if (reassigned) return DYN; + if ( + ts.isPropertyAccessExpression(parent) && + parent.expression === target && + (parent.name.text === "push" || parent.name.text === "unshift") && + ts.isCallExpression(parent.parent) && + parent.parent.expression === parent + ) + written.push(...parent.parent.arguments.nodes); + else if ( + ts.isElementAccessExpression(parent) && + parent.expression === target && + ts.isBinaryExpression(parent.parent) && + parent.parent.left === parent && + parent.parent.operatorToken.kind === ts.SyntaxKind.EqualsToken + ) + written.push(parent.parent.right); const t = lowerer.typeOf(node); if (unsettled(t)) continue; const mapped = lowerer.mapTypeOf(t); @@ -4839,7 +5045,49 @@ function evolvingArrayType(lowerer: Lowerer, decl: ts.VariableDeclaration): IrTy return DYN; result = mapped; } - return result ?? DYN; + if (result === null || result.kind !== "array") return DYN; + // The element types a write stores: its value's, or for a spread + // (`xs.push(...values)`) the source array's element or tuple's elements. + // Another spread source stores elements this check cannot see. + const storedTypes = (value: ts.Expression): ts.Type[] | null => { + if (!ts.isSpreadElement(value)) return [lowerer.typeOf(value)]; + const source = lowerer.typeOf(value.expression); + if (lowerer.checker.isArrayType(source) || lowerer.checker.isTupleType(source)) + return [...lowerer.checker.getTypeArguments(source as ts.TypeReference)]; + return null; + }; + for (const value of written) { + const stored = storedTypes(value); + if (stored === null) return DYN; + for (const type of stored) { + const t = lowerer.mapTypeOf(lowerer.checker.getBaseTypeOfLiteralType(type)); + if (!t || (!typeEquals(t, result.elem) && lowerer.widthLiftPlan(t, result.elem) === null)) + return DYN; + } + } + return result; +} + +/** An unannotated alias of an evolving array binding whose reads disagree + * (`const alias = xs` between `xs.push(1)` and `xs.push("two")`): the + * checker types the alias by the elements written before it, but both names + * hold one array, so the alias takes the binding's checked-dynamic type and + * sees the later writes. Aliases of such an alias follow it. Null for other + * bindings. */ +function evolvingArrayAliasType(lowerer: Lowerer, decl: ts.VariableDeclaration): IrType | null { + let current = decl; + for (let depth = 0; depth < 8; depth++) { + let initializer = current.initializer; + while (initializer !== undefined && ts.isParenthesizedExpression(initializer)) + initializer = initializer.expression; + if (initializer === undefined || !ts.isIdentifier(initializer)) return null; + const source = lowerer.checker.getSymbolAtLocation(initializer)?.valueDeclaration; + if (source === undefined || !ts.isVariableDeclaration(source) || source.type) return null; + const evolved = evolvingArrayType(lowerer, source); + if (evolved !== null) return evolved.kind === "dyn" ? evolved : null; + current = source; + } + return null; } /** A single static type for an initializer-less JavaScript `let` whose @@ -5108,8 +5356,19 @@ export function lowerVarDecl( { const gfnNode = bindingGenericFnNodeOf(decl) ?? bindingContextualGenericFnNodeOf(lowerer, decl); if (gfnNode) { - bindingGenericFnInfoOf(lowerer, decl, gfnNode); - return null; + const info = bindingGenericFnInfoOf(lowerer, decl, gfnNode); + // A nested function that lowered before this declaration read the + // binding as an ordinary TDZ box (predeclareForwardCapture); the + // declaration initializes it, so those reads see the function once + // it runs and a ReferenceError before. + const symbol = lowerer.checker.getSymbolAtLocation(decl.name); + const pre = symbol ? lowerer.ctx.tdzPredeclared.get(symbol) : undefined; + if (pre) { + lowerer.ctx.tdzPredeclared.delete(symbol!); + const value = genericBindingStoredValue(lowerer, decl, info); + return { kind: "assign", localId: pre.id, value, initializes: true, loc: locOf(decl) }; + } + return genericBindingPresenceStore(info, decl); } } @@ -5544,7 +5803,7 @@ export function lowerVarDecl( !decl.type && !isJsSourceFile(ts.getSourceFileOfNode(decl)) ) { - const evolved = evolvingArrayType(lowerer, decl); + const evolved = evolvingArrayType(lowerer, decl) ?? evolvingArrayAliasType(lowerer, decl); if (evolved !== null) { type = evolved; init = lowerer.lowerExprExpecting(decl.initializer, evolved); @@ -6110,6 +6369,20 @@ export function jsBindingHasOpenWrites(lowerer: Lowerer, decl: ts.VariableDeclar ) ) return true; + // A write that can store null or undefined into a binding the checker + // types as a primitive (`offset = match[3] || null`): JavaScript files + // are checked without strict null checks, so the declared type does not + // admit them. + // The declared type is mapped only when such a write exists. + if ( + candidates.some( + (node) => node.operatorToken.kind === ts.SyntaxKind.EqualsToken && mayBeNullish(node.right), + ) + ) { + const primitive = lowerer.mapTypeOf(lowerer.typeOf(decl.name)); + if (primitive?.kind === "string" || primitive?.kind === "f64" || primitive?.kind === "bool") + return true; + } // A plain JavaScript write of a value the declared type cannot hold (the // checker does not report it): buffer-crc32 replaces its number[] table // with `new Int32Array(table)`. Only a different representation counts; @@ -6140,6 +6413,31 @@ export function jsBindingHasOpenWrites(lowerer: Lowerer, decl: ts.VariableDeclar }); } +/** Whether `node` can evaluate to null or undefined by its form: the + * literals, `void`, and conditional or logical expressions with such an + * operand in result position. */ +function mayBeNullish(node: ts.Expression): boolean { + while (ts.isParenthesizedExpression(node)) node = node.expression; + if (node.kind === ts.SyntaxKind.NullKeyword || ts.isVoidExpression(node)) return true; + if (ts.isIdentifier(node)) return node.text === "undefined"; + if (ts.isConditionalExpression(node)) + return mayBeNullish(node.whenTrue) || mayBeNullish(node.whenFalse); + if (ts.isBinaryExpression(node)) { + const op = node.operatorToken.kind; + if ( + op === ts.SyntaxKind.BarBarToken || + op === ts.SyntaxKind.QuestionQuestionToken || + op === ts.SyntaxKind.AmpersandAmpersandToken + ) + return ( + mayBeNullish(node.right) || + (op === ts.SyntaxKind.AmpersandAmpersandToken && mayBeNullish(node.left)) + ); + if (op === ts.SyntaxKind.CommaToken) return mayBeNullish(node.right); + } + return false; +} + function immediatelyGuardedAbsenceProbe(lowerer: Lowerer, decl: ts.VariableDeclaration): boolean { const guard = immediateAbsenceGuard(lowerer, decl); // `if (!x)`: the falsy test sees a missing value. @@ -7560,8 +7858,9 @@ export function lowerExprStatement(lowerer: Lowerer, expr: ts.Expression): IrStm // (closures box), the runtime sets the member on OBJ receivers // and throws Node's TypeErrors on the rest. The receiver is // PROBED (tryLowerExpression) and claimed exactly when it lowers to - // dyn; typed receivers keep their own lowerings and fences. - if (!expr.left.questionDotToken) { + // dyn; typed receivers keep their own lowerings and fences. A + // private name is the field of its class (fieldTarget). + if (!expr.left.questionDotToken && !ts.isPrivateIdentifier(expr.left.name)) { const recv = tryLowerExpression(lowerer, expr.left.expression); if (recv && recv.type.kind === "dyn") { const loc = locOf(expr); @@ -9390,10 +9689,26 @@ export function lowerForOf(lowerer: Lowerer, stmt: ts.ForOfStatement): IrStmt { ) { return lowerForAwaitStdin(lowerer, stmt); } - // A checked-dynamic NodeJS.ReadableStream iterates its native stream. - const dynStream = lowerForAwaitDynStream(lowerer, stmt, () => - lowerForAwaitBuiltin(lowerer, stmt), - ); + // NodeJS.WritableStream is what @types/node answers for pipeline() + // with a function destination, whose value is a PassThrough. + if (nodeStreamInterfaceSide(lowerer, lowerer.typeOf(stmt.expression)) === "w") { + const mapped = lowerer.mapTypeOf(lowerer.typeOf(stmt.expression)); + const sides = + mapped?.kind === "object" + ? streamSidesOf(lowerer, lowerer.classes.get(mapped.className)) + : null; + if (sides !== "r" && sides !== "rw") + lowerer.noLowering( + "for await over a NodeJS.WritableStream", + stmt.expression, + "type the stream as the readable class it is: pipeline() answers a PassThrough for a function destination (pipeline(...) as PassThrough, or a JSDoc @type)", + ); + } + // A checked-dynamic NodeJS.ReadableStream iterates its native stream, + // and a Hash, Hmac, Cipheriv or Decipheriv iterates its Transform. + const dynStream = + lowerForAwaitDynStream(lowerer, stmt, () => lowerForAwaitBuiltin(lowerer, stmt)) ?? + lowerForAwaitValueStream(lowerer, stmt, () => lowerForAwaitBuiltin(lowerer, stmt)); if (dynStream) return dynStream; const builtin = lowerForAwaitBuiltin(lowerer, stmt); if (builtin) return builtin; @@ -9575,6 +9890,10 @@ export function lowerForOf(lowerer: Lowerer, stmt: ts.ForOfStatement): IrStmt { } iterSrc ??= stmt.expression; let iterable = lowerer.lowerExpr(iterSrc); + { + const iterableUnion = iterableUnionOf(lowerer, iterable.type); + if (iterableUnion) return lowerForOfIterable(lowerer, stmt, iterable, iterableUnion, labels); + } let tupleSource: { shapeId: string; fields: { name: string; type: IrType }[]; @@ -11422,11 +11741,13 @@ function lowerForIn(lowerer: Lowerer, stmt: ts.ForInStatement): IrStmt { keysT, loc, ); + // The overflow map's hashed key set answers presence directly; a + // fresh key list per visit would make the walk quadratic. const guard = (kRef: IrExpr): IrExpr => ({ - kind: "arrIntrinsic", - method: "includes", - receiver: { kind: "recordOvfKeys", obj: recvRef(), shapeId, type: keysT, loc }, - args: [kRef], + kind: "recordOvfHas", + obj: recvRef(), + shapeId, + key: kRef, type: BOOL, loc, }); diff --git a/packages/compiler/src/frontend/lowering/lower-stream.ts b/packages/compiler/src/frontend/lowering/lower-stream.ts index b9add95a6..e35f5564f 100644 --- a/packages/compiler/src/frontend/lowering/lower-stream.ts +++ b/packages/compiler/src/frontend/lowering/lower-stream.ts @@ -1,5 +1,6 @@ +import { keyedHelperName } from "./stable-names.js"; import { nodeThrowExpr, boolLit, numLit, strLit } from "../../ir/build.js"; -import { hashStreamOf, isHashValueType } from "./builtins/hash-stream.js"; +import { isValueStream, valueStreamOf } from "./builtins/hash-stream.js"; import { InternalCompilerError } from "../../errors.js"; /* The node:stream lowering (the spoke-module pattern, like * lower-event-emitter.ts): construction of the five runtime stream classes @@ -51,7 +52,11 @@ import { dynUndefinedExpr, varRef } from "../../ir/build.js"; import { genResultRecord } from "../type-mapper.js"; import { noteUntypedStreamFlow, requestGeneralStreamSurface } from "./general-streams.js"; import { dynNativeBranch } from "./dyn-streams.js"; +import { bindingNeverReassigned } from "./binding-analysis.js"; import { extractIteratorValue, genStep, genValue, stepDrivable } from "./lower-generators.js"; +import { LiftedFrame, driveGenerator } from "./containers/iterator-helpers.js"; +import { lowerArrayIteratorValue, lowerStringIteratorValue } from "./iterator-adapters.js"; +import { staticReadableStreamElementType } from "./lower-stdlib.js"; import { BOOL, DYN, @@ -73,6 +78,7 @@ import { funcOf, typeEquals, typeKey, + UNDEFINED_T, } from "../../ir/ir.js"; const BYTES = BYTES_U8; @@ -171,10 +177,25 @@ export const UNDERSCORE_METHODS: ReadonlyMap = new Map([ ["flush", "_flush"], ]); +/** The option callbacks applied after construction rather than through + * the constructor's callback slots (option name → method name): construct + * on every stream class, and writev on the writable classes whose + * machinery hands it batches (Writable and Duplex). */ +export const STREAM_EXTRA_CALLBACKS: ReadonlyMap = new Map([ + ["construct", "_construct"], + ["writev", "_writev"], +]); + +export function streamExtraCallbacks(cls: string): readonly string[] { + return cls === "%Writable" || cls === "%Duplex" ? ["construct", "writev"] : ["construct"]; +} + /** The completion callback's parameter position in each underscore * method that takes one (cbTuples' "fn" positions). */ export const STREAM_COMPLETION_CALLBACK_INDEX: ReadonlyMap = new Map([ ["_write", 2], + ["_writev", 1], + ["_construct", 0], ["_final", 0], ["_destroy", 1], ["_transform", 2], @@ -284,6 +305,7 @@ function lowerStreamCallback( node: ts.MethodDeclaration | ts.FunctionExpression | ts.ArrowFunction, thisType: IrType, fullTuple: IrType[], + chunkValues = true, ): IrExpr { const loc = locOf(node); const { shapes, funcType } = lowerer.lambdaSignature(node); @@ -303,6 +325,27 @@ function lowerStreamCallback( // boxes each position by kind (the completion callback arrives as a // callable dyn whose glue dispatches to the runtime's *_done). if (funcType.params[i]!.kind === "dyn") continue; + // A write or transform chunk of another type converts from the + // chunk's value when the callback runs (an object-mode side's value), + // or throws a TypeError there — on a side known to be byte mode the + // chunk is a Buffer, so the declared type must be Node's or a + // supertype of it (`Buffer | string`); an encoding of another type + // (`string | null | undefined`) converts from the encoding argument's + // value. + if ( + ((((i === 0 && + (chunkValues || widensInto(lowerer, fullTuple[0]!, funcType.params[0]!, loc))) || + i === 1) && + (which === "write" || which === "transform")) || + (i === 0 && which === "writev")) && + funcType.params[i]!.kind !== "func" && + canConvertToDyn( + funcType.params[i]!, + (id) => lowerer.shapes.get(id), + (id) => lowerer.unions.get(id), + ) + ) + continue; if (!typeEquals(funcType.params[i]!, fullTuple[i]!)) { lowerer.noLowering( `a '${which}' callback whose parameter ${i} is '${lowerer.fmt(funcType.params[i]!)}' where Node passes '${lowerer.fmt(fullTuple[i]!)}'`, @@ -311,7 +354,7 @@ function lowerStreamCallback( ); } } - const fnName = `%fn${lowerer.lambdaCounter++}_${which}cb`; + const fnName = lowerer.closureName(loc, `_${which}cb`); const fnCtx = newFnCtx(true, null, funcType, funcType.ret); lowerer.fnStack.push(fnCtx); try { @@ -399,11 +442,81 @@ interface StreamOptions { * right after construction (Node's constructors call addAbortSignal * once the state exists), or null when absent. */ signal: IrExpr | null; + /** The objectMode option's sides (a Duplex's readableObjectMode and + * writableObjectMode set one side): applied with stream.objectMode + * right after construction. */ + readableObject: boolean; + writableObject: boolean; + /** decodeStrings: false (string writes stay strings), applied with + * stream.decodeStrings right after construction. */ + decodeStringsOff: boolean; + /** A writable side's non-utf8 `defaultEncoding` as written, applied + * with writable.writeEncoding. */ + writeEncoding: string | null; + /** The construct and writev callbacks (options or the class's + * _construct/_writev), applied with stream.setWritev and + * stream.setConstruct right after construction. */ + extras: { name: string; cb: IrExpr }[]; /** Present callbacks in canonical order with their flag bits. */ flags: number; cbs: IrExpr[]; } +/** The objectMode, readableObjectMode and writableObjectMode members of a + * stream options literal (boolean literals; the sided keys count only on + * a Duplex, Transform or PassThrough, as in Node). */ +function streamObjectModes( + lowerer: Lowerer, + ctorName: string, + optsLit: ts.ObjectLiteralExpression | undefined, +): { readable: boolean; writable: boolean } { + const out = { readable: false, writable: false }; + const duplexish = ctorName !== "Readable" && ctorName !== "Writable"; + for (const prop of optsLit?.properties?.nodes ?? []) { + if (!ts.isPropertyAssignment(prop)) continue; + const name = + ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name) ? prop.name.text : null; + if (name !== "objectMode" && name !== "readableObjectMode" && name !== "writableObjectMode") + continue; + const value = prop.initializer; + if (value.kind === ts.SyntaxKind.FalseKeyword) continue; + if (value.kind !== ts.SyntaxKind.TrueKeyword) { + lowerer.noLowering( + `${ctorName} with a runtime '${name}' value`, + prop, + `write '${name}: true' or '${name}: false'`, + ); + } + if (name === "objectMode") { + out.readable = true; + out.writable = true; + } else if (duplexish) { + if (name === "readableObjectMode") out.readable = true; + else out.writable = true; + } + } + return out; +} + +/** Whether an options literal makes the writable side hold values: its + * object mode set with a `true` literal (objectMode, or writableObjectMode + * on a duplex stream), or decodeStrings: false (strings stay strings). + * Reports nothing: the options parse fences the other value forms. */ +function literalWritesValues(opts: ts.ObjectLiteralExpression, duplexish: boolean): boolean { + for (const prop of opts.properties?.nodes ?? []) { + if (!ts.isPropertyAssignment(prop)) continue; + const name = + ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name) ? prop.name.text : null; + if (name === "decodeStrings") { + if (prop.initializer.kind !== ts.SyntaxKind.TrueKeyword) return true; + continue; + } + if (name !== "objectMode" && !(duplexish && name === "writableObjectMode")) continue; + if (prop.initializer.kind !== ts.SyntaxKind.FalseKeyword) return true; + } + return false; +} + /** The full Node parameter tuples of the option callbacks, given the * concrete stream's `this` type. The trailing completion callbacks keep * whatever func type the checker contextually gave the user's parameter @@ -414,6 +527,8 @@ function cbTuples(lowerer: Lowerer): Record { read: [F64], write: [BYTES, STRING, "fn"], final: ["fn"], + construct: ["fn"], + writev: [DYN, "fn"], destroy: [errorOrNull(lowerer), "fn"], transform: [BYTES, STRING, "fn"], flush: ["fn"], @@ -652,9 +767,16 @@ function parseStreamOptions( badEncoding: null, pushEncoding: null, signal: null, + readableObject: false, + writableObject: false, + decodeStringsOff: false, + writeEncoding: null, + extras: [], flags: 0, cbs: [], }; + const extraNames = streamExtraCallbacks(`%${ctorName}`); + const writableClass = ctorName !== "Readable"; const followed = followOptionsArg(lowerer, arg); const optsLit = followed === null ? undefined : followed; if (optsLit !== undefined && !ts.isObjectLiteralExpression(optsLit)) { @@ -664,6 +786,24 @@ function parseStreamOptions( "the options must be an object literal, inline or through const-initialized bindings (the callbacks lower as compile-time closures)", ); } + // Read before the callbacks lower: an object-mode readable side keeps a + // completion callback's `data: any` (its values are not only strings and + // Buffers). An object-mode side's high-water mark defaults to 16. + const objectModes = streamObjectModes( + lowerer, + ctorName, + optsLit !== undefined && ts.isObjectLiteralExpression(optsLit) ? optsLit : undefined, + ); + out.readableObject = objectModes.readable; + out.writableObject = objectModes.writable; + // the chunk an option callback receives can be another value than a + // Buffer (literalWritesValues), read before any callback lowers + const writesValues = + optsLit !== undefined && + ts.isObjectLiteralExpression(optsLit) && + literalWritesValues(optsLit, ctorName !== "Readable" && ctorName !== "Writable"); + if (out.readableObject) out.hwmR = numLit(16, loc); + if (out.writableObject) out.hwmW = numLit(16, loc); const tuples = cbTuples(lowerer); const present = new Map(); for (const prop of optsLit?.properties?.nodes ?? []) { @@ -678,7 +818,7 @@ function parseStreamOptions( lowerer.unsupported("SC1090", prop, `computed or spread members in ${ctorName} options`); } // Callback members: shorthand methods and function-valued properties. - if (accepted.includes(name)) { + if (accepted.includes(name) || extraNames.includes(name)) { let fnNode: ts.MethodDeclaration | ts.FunctionExpression | ts.ArrowFunction | null = null; if (ts.isMethodDeclaration(prop)) fnNode = prop; else if ( @@ -710,7 +850,7 @@ function parseStreamOptions( continue; } const full = tuples[name]!.map((t) => (t === "fn" ? null : t)); - const pinned = pinAnyDataCompletion(lowerer, name, fnNode); + const pinned = out.readableObject ? null : pinAnyDataCompletion(lowerer, name, fnNode); try { // The completion-callback tail: typed by the checker contextually; // accept the user's declared func type as the tuple's entry so the @@ -727,7 +867,10 @@ function parseStreamOptions( } return declared ?? funcOf([], VOID); }); - present.set(name, lowerStreamCallback(lowerer, name, fnNode, thisType, tuple)); + present.set( + name, + lowerStreamCallback(lowerer, name, fnNode, thisType, tuple, writesValues), + ); } finally { if (pinned) lowerer.stageSourceTypes.delete(pinned); } @@ -771,22 +914,21 @@ function parseStreamOptions( break; case "objectMode": case "readableObjectMode": - case "writableObjectMode": { - // `objectMode: false` is the byte default — admit the literal. - if (value.kind === ts.SyntaxKind.FalseKeyword) break; - lowerer.noLowering( - `${ctorName} in objectMode`, - prop, - "object-mode streams have no static chunk type yet — chunks are Buffers (utf8 strings convert at push/write)", - ); + case "writableObjectMode": + // read up front (streamObjectModes) break; - } case "decodeStrings": { + // WritableState's `options.decodeStrings === false`; a Readable + // ignores the option if (value.kind === ts.SyntaxKind.TrueKeyword) break; // Node's default + if (value.kind === ts.SyntaxKind.FalseKeyword) { + if (writableClass) out.decodeStringsOff = true; + break; + } lowerer.noLowering( - `${ctorName} with decodeStrings: false`, + `${ctorName} with a runtime 'decodeStrings' value`, prop, - "chunks always decode to Buffers here (Node's default)", + "write 'decodeStrings: true' or 'decodeStrings: false'", ); break; } @@ -821,15 +963,20 @@ function parseStreamOptions( out.badEncoding = t.value; break; } - if (t.isStringLiteralType() && ctorName === "Readable") { - out.pushEncoding = knownBufEncoding(t.value)!; + if (t.isStringLiteralType()) { + // the readable side decodes push(string) with it, and the + // writable side encodes write(string) with it (the name as + // written reaches _write when decodeStrings is false) + if (ctorName !== "Writable" && !out.readableObject) + out.pushEncoding = knownBufEncoding(t.value)!; + if (writableClass) out.writeEncoding = t.value; break; } } lowerer.noLowering( - `the ${ctorName} option 'defaultEncoding'`, + `the ${ctorName} option 'defaultEncoding' with a runtime value`, prop, - "utf8 (the default) is the supported write-side string encoding", + "write the encoding as a string literal", ); break; case "signal": { @@ -890,18 +1037,13 @@ function parseStreamOptions( ); break; } - case "construct": - lowerer.noLowering( - `the ${ctorName} option 'construct'`, - prop, - "deferred construction (_construct) is not lowered yet", - ); - break; case "writev": lowerer.noLowering( `the ${ctorName} option 'writev'`, prop, - "batched writes (_writev) are not lowered yet — writes deliver one chunk at a time", + ctorName === "Readable" + ? "a Readable has no writable side" + : "batched writes on a Transform would bypass its transform — writev is supported on Writable and Duplex", ); break; default: @@ -918,6 +1060,10 @@ function parseStreamOptions( out.cbs.push(cb); } } + for (const name of extraNames) { + const cb = present.get(name) ?? fallbackCb?.(name) ?? null; + if (cb) out.extras.push({ name, cb }); + } return out; } @@ -937,6 +1083,11 @@ function streamCtorArgs( badEncoding: string | null; pushEncoding: string | null; signal: IrExpr | null; + readableObject: boolean; + writableObject: boolean; + decodeStringsOff: boolean; + writeEncoding: string | null; + extras: { name: string; cb: IrExpr }[]; } { const shape = streamCtorShape(cls); const o = parseStreamOptions( @@ -966,9 +1117,74 @@ function streamCtorArgs( badEncoding: o.badEncoding, pushEncoding: o.pushEncoding, signal: o.signal, + readableObject: o.readableObject, + writableObject: o.writableObject, + decodeStringsOff: o.decodeStringsOff, + writeEncoding: o.writeEncoding, + extras: o.extras, }; } +/** The follow-ups a stream's options apply over the fresh stream `recv` + * after the chained ones: decodeStrings, the writable defaultEncoding, + * then writev and construct (Node's constructors schedule construct + * last). */ +function streamOptionFollowUps( + parsed: { + decodeStringsOff: boolean; + writeEncoding: string | null; + extras: { name: string; cb: IrExpr }[]; + }, + recv: () => IrExpr, + thisType: IrType, + loc: SrcLoc, + writevFn: IrLibFn = "stream.setWritev", +): IrStmt[] { + const out: IrStmt[] = []; + if (parsed.decodeStringsOff) { + out.push({ + kind: "exprStmt", + expr: { + kind: "libCall", + fn: "stream.decodeStrings", + args: [recv(), boolLit(false, loc)], + type: thisType, + loc, + }, + loc, + }); + } + if (parsed.writeEncoding !== null) { + out.push({ + kind: "exprStmt", + expr: { + kind: "libCall", + fn: "writable.writeEncoding", + args: [recv(), strLit(parsed.writeEncoding, loc)], + type: thisType, + loc, + }, + loc, + }); + } + for (const name of ["writev", "construct"]) { + const extra = parsed.extras.find((x) => x.name === name); + if (!extra) continue; + out.push({ + kind: "exprStmt", + expr: { + kind: "libCall", + fn: name === "writev" ? writevFn : "stream.setConstruct", + args: [recv(), extra.cb], + type: VOID, + loc, + }, + loc, + }); + } + return out; +} + /** `new Readable(opts?)` and friends — called from lowerNew once the * callee resolved to a builtin stream class. */ export function lowerStreamNew(lowerer: Lowerer, expr: ts.NewExpression, info: ClassInfo): IrExpr { @@ -1010,6 +1226,17 @@ export function lowerStreamNew(lowerer: Lowerer, expr: ts.NewExpression, info: C ); } let built: IrExpr = { kind: "libCall", fn, args: parsed.args, type: thisType, loc }; + if (parsed.readableObject || parsed.writableObject) { + // { objectMode }: applied before any other follow-up (answers the + // receiver +1). + built = { + kind: "libCall", + fn: "stream.objectMode", + args: [built, boolLit(parsed.readableObject, loc), boolLit(parsed.writableObject, loc)], + type: thisType, + loc, + }; + } if (parsed.pushEncoding !== null) { // { defaultEncoding }: chain the push-side decode default (the // setEncoding chaining shape — answers the receiver +1). @@ -1032,12 +1259,29 @@ export function lowerStreamNew(lowerer: Lowerer, expr: ts.NewExpression, info: C loc, }; } - if (parsed.signal === null) return built; - // { signal }: addAbortSignal over the fresh stream (answers it +1). + if (parsed.signal !== null) { + // { signal }: addAbortSignal over the fresh stream (answers it +1). + built = { + kind: "libCall", + fn: "stream.addAbortSignal", + args: [built, parsed.signal], + type: thisType, + loc, + }; + } + if (!parsed.decodeStringsOff && parsed.writeEncoding === null && parsed.extras.length === 0) + return built; + const fresh = lowerer.declareHiddenLocal("%stream", thisType); + const followUps = streamOptionFollowUps( + parsed, + () => varRef(fresh.id, thisType, loc), + thisType, + loc, + ); return { - kind: "libCall", - fn: "stream.addAbortSignal", - args: [built, parsed.signal], + kind: "seqExpr", + stmts: [{ kind: "varDecl", localId: fresh.id, init: built, loc }, ...followUps], + result: varRef(fresh.id, thisType, loc), type: thisType, loc, }; @@ -1068,6 +1312,7 @@ function streamMethodWrapper( thisType: IrType, loc: SrcLoc, blame: ts.Node, + chunkValues = true, ): IrExpr | null { const found = lowerer.findMethodOn(info, methodName); if (!found) { @@ -1128,6 +1373,24 @@ function streamMethodWrapper( ); } } else if (!typeEquals(got.type, want)) { + // A write or transform encoding of another type (`string | null | + // undefined`) converts from the encoding argument's value: an + // object-mode write passes undefined, null or the name. A chunk of + // another type (`string | Buffer` under decodeStrings: false) + // converts from the chunk's value. + if ( + (i === 1 || (i === 0 && (chunkValues || which === "writev"))) && + (which === "write" || which === "transform" || which === "writev") && + got.type.kind !== "func" && + canConvertToDyn( + got.type, + (id) => lowerer.shapes.get(id), + (id) => lowerer.unions.get(id), + ) + ) { + paramTypes.push(got.type); + continue; + } // 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. @@ -1135,6 +1398,22 @@ function streamMethodWrapper( paramTypes.push(want); continue; } + // A write or transform chunk of another type converts from the + // chunk's value when the method runs (an object-mode side's value), + // or throws a TypeError there; a byte-mode side's chunk is a Buffer. + if ( + i === 0 && + (which === "writev" || (chunkValues && (which === "write" || which === "transform"))) && + got.type.kind !== "func" && + canConvertToDyn( + got.type, + (id) => lowerer.shapes.get(id), + (id) => lowerer.unions.get(id), + ) + ) { + paramTypes.push(got.type); + continue; + } lowerer.noLowering( `a '${methodName}' method whose parameter ${i} is '${lowerer.fmt(got.type)}' where Node passes '${lowerer.fmt(want)}'`, blame, @@ -1144,7 +1423,7 @@ function streamMethodWrapper( paramTypes.push(got.type); } const ret = found.sig.ret; - const fnName = `%fn${lowerer.lambdaCounter++}_${which}vt`; + const fnName = lowerer.closureName(loc, `_${which}vt`); const funcType = funcOf([thisType, ...paramTypes], ret); lowerer.fnStack.push(newFnCtx(true, null, funcType, ret)); try { @@ -1228,10 +1507,22 @@ export function lowerStreamSuperCall( ); } const shape = streamCtorShape(cls); + // Whether the writable side holds values: options read at run time may + // set objectMode, and a literal says so with objectMode (or a Duplex's + // writableObjectMode) true; otherwise _write and _transform receive + // Buffers. + // super(undefined) and super(null) pass no options (followOptionsArg + // answers null), so their sides are byte mode too. + const optsNode = argNodes[0] !== undefined ? followOptionsArg(lowerer, argNodes[0]) : null; + const chunkValues = + optsNode !== null && + optsNode !== undefined && + (!ts.isObjectLiteralExpression(optsNode) || + literalWritesValues(optsNode, cls !== "%Readable" && cls !== "%Writable")); const fallback = (name: string): IrExpr | null => { - const methodName = UNDERSCORE_METHODS.get(name); + const methodName = UNDERSCORE_METHODS.get(name) ?? STREAM_EXTRA_CALLBACKS.get(name); return methodName - ? streamMethodWrapper(lowerer, info, name, methodName, thisType, loc, blame) + ? streamMethodWrapper(lowerer, info, name, methodName, thisType, loc, blame, chunkValues) : null; }; const thisRef = (): IrExpr => ({ kind: "varRef", localId: thisLocal.id, type: thisType, loc }); @@ -1250,6 +1541,13 @@ export function lowerStreamSuperCall( cbs.push(cb); } } + // The class's _writev and _construct ride the same way: an options + // writev or construct (applied by initDyn) wins. + const extras: { name: string; cb: IrExpr }[] = []; + for (const name of streamExtraCallbacks(cls)) { + const cb = fallback(name); + if (cb) extras.push({ name, cb }); + } return [ { kind: "exprStmt", @@ -1262,6 +1560,13 @@ export function lowerStreamSuperCall( }, loc, }, + ...streamOptionFollowUps( + { decodeStringsOff: false, writeEncoding: null, extras }, + thisRef, + thisType, + loc, + "stream.setWritevDefault", + ), ]; } } @@ -1296,6 +1601,19 @@ export function lowerStreamSuperCall( loc, }, ]; + if (parsed.readableObject || parsed.writableObject) { + out.push({ + kind: "exprStmt", + expr: { + kind: "libCall", + fn: "stream.objectMode", + args: [thisRef(), boolLit(parsed.readableObject, loc), boolLit(parsed.writableObject, loc)], + type: thisType, + loc, + }, + loc, + }); + } if (parsed.pushEncoding !== null) { out.push({ kind: "exprStmt", @@ -1335,6 +1653,7 @@ export function lowerStreamSuperCall( loc, }); } + out.push(...streamOptionFollowUps(parsed, thisRef, thisType, loc)); return out; } @@ -1378,18 +1697,18 @@ export function lowerStreamUnderscoreAssign( const loc = locOf(expr); const cls = base.def.name; const clsName = cls.slice(1); - if (methodName === "_writev" || methodName === "_construct") { + if (methodName === "_construct") { + // Node's constructor reads _construct once; a later assignment has no + // effect there lowerer.noLowering( `assigning '${methodName}' on a ${clsName}`, expr.left, - methodName === "_writev" - ? "batched writes (_writev) are not lowered yet — writes deliver one chunk at a time" - : "deferred construction (_construct) is not lowered yet", + "declare _construct on the class or pass the construct option", ); } - const which = optionByMethod.get(methodName)!; + const which = methodName === "_writev" ? "writev" : optionByMethod.get(methodName)!; const { accepted } = streamCtorShape(cls); - if (!accepted.includes(which)) { + if (!accepted.includes(which) && !streamExtraCallbacks(cls).includes(which)) { lowerer.noLowering( `assigning '${methodName}' on a ${clsName}`, expr.left, @@ -1425,6 +1744,7 @@ export function lowerStreamUnderscoreAssign( destroy: "stream.setDestroy", transform: "stream.setTransform", flush: "stream.setFlush", + writev: "stream.setWritev", }; return { kind: "exprStmt", @@ -1494,11 +1814,27 @@ export function lowerStreamStaticCall( } } } + if (member === "fromWeb" && cls === "%Readable") return lowerReadableFromWeb(lowerer, call, loc); if (member !== "from") { lowerer.noLowering(`${cls.slice(1)}.${member}`, call); } + if (cls === "%Duplex") { + const fromArgs = call.arguments.nodes; + if (fromArgs.length !== 1) { + lowerer.noLowering( + `Duplex.from with ${fromArgs.length} arguments`, + call, + "Duplex.from takes one body", + ); + } + return duplexFromBody(lowerer, fromArgs[0]!, locOf(call)); + } if (cls !== "%Readable") { - lowerer.noLowering(`${cls.slice(1)}.from`, call, "Readable.from is the lowered form"); + lowerer.noLowering( + `${cls.slice(1)}.from`, + call, + "Readable.from and Duplex.from are the lowered forms", + ); } const args = call.arguments.nodes; if (args.length > 2) { @@ -1508,16 +1844,184 @@ export function lowerStreamStaticCall( "Readable.from(iterable, options) is the supported form", ); } - const type: IrType = { kind: "object", className: "%Readable" }; + return lowerFromSource(lowerer, call, args[0], args[1], false); +} + +/** Readable.fromWeb(readableStream, options): Node's adapter over the web + * stream's reader (scr_stream_from_web.c). The options are an object + * literal: objectMode a boolean literal, highWaterMark a number, encoding + * a literal name, and signal a variable or property read, applied with + * addAbortSignal as the constructors do. */ +function lowerReadableFromWeb(lowerer: Lowerer, call: ts.CallExpression, loc: SrcLoc): IrExpr { + const args = call.arguments.nodes; + const readable: IrType = { kind: "object", className: "%Readable" }; + if (args.length === 0 || args.length > 2 || args.some((a) => ts.isSpreadElement(a))) { + lowerer.noLowering( + `Readable.fromWeb with ${args.length} arguments`, + call, + "the supported form is Readable.fromWeb(readableStream, options)", + ); + } + const web = lowerer.lowerExprExpecting(args[0]!, DYN); + let objectMode = false; + let hwm: IrExpr = numLit(-1, loc); + let encoding = ""; + let signal: IrExpr | null = null; + const options = args[1]; + if (options !== undefined) { + if (!ts.isObjectLiteralExpression(options)) { + lowerer.noLowering( + "Readable.fromWeb options that are not an object literal", + options, + "pass { objectMode, highWaterMark, encoding, signal } as an object literal", + ); + } + for (const p of options.properties.nodes) { + const key = + (ts.isPropertyAssignment(p) || ts.isShorthandPropertyAssignment(p)) && + ts.isIdentifier(p.name) + ? p.name.text + : null; + const value = + key === null + ? null + : ts.isShorthandPropertyAssignment(p) + ? (p.name as ts.Identifier) + : (p as ts.PropertyAssignment).initializer; + if (key === "objectMode" && value) { + if (value.kind === ts.SyntaxKind.TrueKeyword) objectMode = true; + else if (value.kind !== ts.SyntaxKind.FalseKeyword) + lowerer.noLowering( + "the Readable.fromWeb option 'objectMode' with this value", + p, + "write true or false", + ); + continue; + } + if (key === "highWaterMark" && value) { + hwm = lowerer.lowerExprExpecting(value, F64); + continue; + } + if (key === "encoding" && value) { + const t = lowerer.typeOf(value); + if (t.isStringLiteralType() && knownBufEncoding(t.value) === undefined) { + return nodeThrowExpr( + 1, + "ERR_INVALID_ARG_VALUE", + `The property 'options.encoding' is invalid. Received '${t.value}'`, + readable, + loc, + ); + } + encoding = bufEncoding(lowerer, "the Readable.fromWeb option 'encoding'", value); + continue; + } + if (key === "signal" && value) { + if (!sideEffectFreeOptionValue(value) && !pureRead(value)) { + lowerer.noLowering( + "the Readable.fromWeb option 'signal' with this value", + p, + "pass a variable or property read (const signal = controller.signal)", + ); + } + signal = lowerer.lowerExprExpecting(value, DYN); + continue; + } + lowerer.noLowering( + key === null + ? "Readable.fromWeb options with this member" + : `the Readable.fromWeb option '${key}'`, + p, + "objectMode, highWaterMark, encoding and signal are the Readable.fromWeb options", + ); + } + } + const built: IrExpr = { + kind: "libCall", + fn: "fetch.readableFromWeb", + args: [web, boolLit(objectMode, loc), hwm, strLit(encoding, loc)], + type: readable, + loc, + }; + if (signal === null) return built; + return { + kind: "libCall", + fn: "stream.addAbortSignal", + args: [built, signal], + type: readable, + loc, + }; +} + +/** Readable.from(source, options), and for Duplex.from over an iterable + * (duplex) duplexify.js's from(Duplexify, body, { objectMode: true, + * writable: false }): the same builders with SCR_FROM_DUPLEX, answering a + * Duplexify without a writable side. */ +function lowerFromSource( + lowerer: Lowerer, + at: ts.Node, + srcNode: ts.Expression | undefined, + optsNode: ts.Expression | undefined, + duplex: boolean, +): IrExpr { + const loc = locOf(at); + const call = at; + const type: IrType = { kind: "object", className: duplex ? "%Duplex" : "%Readable" }; + const what = duplex ? "Duplex.from" : "Readable.from"; + // SCR_FROM_DUPLEX + const duplexFlag = duplex ? 32 : 0; const js = isJsSourceFile(ts.getSourceFileOfNode(call)); - const srcNode = args[0]; - const optsNode = args[1]; + // A web ReadableStream is async iterable: from.js reads its iterator. + // Duplex.from takes _duplexify({ readable: Readable.fromWeb(body) }). + const webElem = srcNode ? staticReadableStreamElementType(lowerer, srcNode) : null; + if (srcNode && webElem !== null && duplex) { + const fromWeb: IrExpr = { + kind: "libCall", + fn: "fetch.readableFromWeb", + args: [ + lowerer.lowerExprExpecting(srcNode, DYN), + boolLit(false, loc), + numLit(-1, loc), + strLit("", loc), + ], + type: { kind: "object", className: "%Readable" }, + loc, + }; + return { kind: "libCall", fn: "stream.duplexifyReadable", args: [fromWeb], type, loc }; + } + if (srcNode && webElem !== null) { + const source = lowerWebStreamSource(lowerer, srcNode, webElem, loc); + const helpers = source ? fromGenHelpers(lowerer, source.out, loc) : null; + const opts = optsNode ? fromOptions(lowerer, optsNode) : { flags: 0, hwm: null }; + if (!source || !helpers || !opts || !fromGenChunk(lowerer, webElem)) { + lowerer.noLowering( + `Readable.from over a web ReadableStream of '${lowerer.fmt(webElem)}'`, + srcNode, + ); + } + const hwm = opts!.hwm ? lowerer.lowerExprExpecting(opts!.hwm, F64) : numLit(0, loc); + const gen: IrExpr = { + kind: "callValue", + callee: source!.closure, + args: [], + type: source!.out, + loc, + }; + return { + kind: "libCall", + fn: "readable.fromAsyncGen", + args: [gen, ...helpers!, numLit(opts!.flags, loc), hwm], + type, + loc, + }; + } const srcT = srcNode ? lowerer.mapTypeOf(lowerer.typeOf(srcNode)) : null; const typedElem = (t: IrType | null | undefined): "string" | "bytes" | null => t?.kind === "string" ? "string" : t?.kind === "bytes" && t.elem === "u8" ? "bytes" : null; const single = typedElem(srcT); const elem = srcT?.kind === "array" ? typedElem(srcT.elem) : null; - const opts = optsNode ? fromOptions(lowerer, optsNode) : { flags: 0, hwm: null }; + const opts0 = optsNode ? fromOptions(lowerer, optsNode) : { flags: 0, hwm: null }; + const opts = opts0 ? { ...opts0, flags: opts0.flags | duplexFlag } : opts0; // A class whose [Symbol.iterator]() or [Symbol.asyncIterator]() is a // generator method: from.js calls the method when the stream is built, // then reads the generator like any other. @@ -1597,7 +2101,17 @@ export function lowerStreamStaticCall( } const anySrc = srcT?.kind === "dyn" || - (srcT?.kind === "set" && typedElem(srcT.elem) !== null) || + // a Set or Map (entry arrays) of other values: the checked-dynamic + // view iterates the collection itself + ((srcT?.kind === "set" || srcT?.kind === "map") && + canConvertToDyn( + srcT, + (id) => lowerer.shapes.get(id), + (id) => lowerer.unions.get(id), + )) || + // an array of other values: the object-mode entries come from its + // checked-dynamic copy + (srcT?.kind === "array" && fromGenChunk(lowerer, srcT.elem) && typedElem(srcT.elem) === null) || (srcNode !== undefined && srcT === null && (lowerer.typeOf(srcNode).flags & ts.TypeFlags.Any) !== 0); @@ -1605,6 +2119,7 @@ export function lowerStreamStaticCall( // The checked-dynamic form: the runtime takes from.js's ladder // (ERR_INVALID_ARG_TYPE for a non-iterable, the options, null values). const src = srcNode ? lowerer.lowerExprExpecting(srcNode, DYN) : dynUndefinedExpr(loc); + if (duplex) return { kind: "libCall", fn: "stream.duplexFromDyn", args: [src], type, loc }; const o = lowerOperatorValue(lowerer, optsNode, "Readable.from options", loc, true); return { kind: "libCall", fn: "readable.fromDyn", args: [src, o], type, loc }; } @@ -1616,22 +2131,26 @@ export function lowerStreamStaticCall( ); } lowerer.noLowering( - `Readable.from over a '${srcT ? lowerer.fmt(srcT) : "?"}' source`, + `${what} over a '${srcT ? lowerer.fmt(srcT) : "?"}' source`, srcNode ?? call, - "the supported sources are a string or Buffer, and arrays, Sets, generators and class iterables of strings or Buffers", + "the supported sources are a string or Buffer, and arrays, Sets, Maps, generators and class iterables of values that convert to checked-dynamic values", ); } -/** Whether a generator's yields are stream chunks: strings, Buffers, a - * union of them (null included: the runtime destroys the stream with - * ERR_STREAM_NULL_VALUES), or checked-dynamic values (checked when - * pushed). */ +/** Whether a generator's yields can be stream chunks: values that box + * into checked-dynamic values (null included: the runtime destroys the + * stream with ERR_STREAM_NULL_VALUES). An object-mode stream takes any of + * them; a byte-mode one checks them when they are pushed or written. */ function fromGenChunk(lowerer: Lowerer, t: IrType): boolean { - const chunk = (a: IrType): boolean => - a.kind === "string" || (a.kind === "bytes" && a.elem === "u8") || a.kind === "nullT"; - if (t.kind === "dyn" || (chunk(t) && t.kind !== "nullT")) return true; - if (t.kind !== "union") return false; - return lowerer.unions.get(t.unionId)?.arms.every(chunk) ?? false; + if (t.kind === "nullT" || t.kind === "void" || t.kind === "func") return false; + return ( + t.kind === "dyn" || + canConvertToDyn( + t, + (id) => lowerer.shapes.get(id), + (id) => lowerer.unions.get(id), + ) + ); } /** The helpers Readable.from pulls a compiled generator through, as @@ -1690,7 +2209,7 @@ function fromGenHelpers( const key = `streamFromGen:${role}:${typeKey(gen)}`; let name = lowerer.valueHelpers.get(key); if (!name) { - name = `%stream.fromGen.${role}.${lowerer.valueHelpers.size}`; + name = keyedHelperName(lowerer, `%stream.fromGen.${role}`, key); lowerer.valueHelpers.set(key, name); lowerer.liftedFns.push({ name, @@ -1779,7 +2298,7 @@ function classIteratorObject( const key = `streamFromIter:${cit.iterT.className}`; let name = lowerer.valueHelpers.get(key); if (!name) { - name = `%stream.fromIter.${lowerer.valueHelpers.size}`; + name = keyedHelperName(lowerer, "%stream.fromIter", key); lowerer.valueHelpers.set(key, name); const nextName = `${name}.next`; const nextT = funcOf([], DYN); @@ -1940,7 +2459,7 @@ function classAsyncIteratorObject( const key = `streamFromAsyncIter:${cit.className}`; let name = lowerer.valueHelpers.get(key); if (!name) { - name = `%stream.fromAsyncIter.${lowerer.valueHelpers.size}`; + name = keyedHelperName(lowerer, "%stream.fromAsyncIter", key); lowerer.valueHelpers.set(key, name); const it: IrLocal = { id: "it.0", name: "it", type: cit.iterT, mutable: false, boxed: true }; const src: IrLocal = { @@ -2083,10 +2602,10 @@ function lowerStreamArg( what: "finished" | "pipeline" | "addAbortSignal" | "compose", ): IrExpr { const lowered = lowerer.lowerExpr(node); - // A Hash or Hmac stage is its Transform; pipeline and compose stages - // keep the value alive until the stream settles. - const v = isHashValueType(lowered.type) - ? hashStreamOf(lowered, what === "pipeline" || what === "compose") + // A Hash, Hmac, Cipheriv or Decipheriv stage is its Transform; pipeline + // and compose stages keep the value alive until the stream settles. + const v = isValueStream(lowerer, node) + ? valueStreamOf(lowered, what === "pipeline" || what === "compose") : lowered; // A checked-dynamic pipeline stage (an untyped source or destination): // a boxed native stream unwraps at run time; other values (iterables, @@ -2428,23 +2947,29 @@ export function lowerStreamModuleCall( ? pipelineOptions(lowerer, lastArg) : null; const stageArgs = opts ? args.slice(0, -1) : args; - if (stageArgs.some(isPipelineFunctionStage)) { - if (opts) { - lowerer.noLowering( - "pipeline with function stages and options", - lastArg, - "pipeline(source, async function* (source) { ... }, destination) without options is supported", - ); - } + if (hasPipelineFunctionStage(lowerer, stageArgs)) { const staged = lowerPipelineStages(lowerer, stageArgs, loc); + const type = staged.destPromise ?? { kind: "promise", inner: VOID }; // A promise destination's value settles the result (same type). - return staged.wrap({ - kind: "libCall", - fn: "sp.pipelineStages", - args: staged.args, - type: staged.destPromise ?? { kind: "promise", inner: VOID }, - loc, - }); + if (!opts) { + return staged.wrap({ + kind: "libCall", + fn: "sp.pipelineStages", + args: staged.args, + type, + loc, + }); + } + // the options: end, and the signal (flags bit 6) + const flagsArg = staged.args[3]!; + if (flagsArg.kind !== "numLit") + throw new InternalCompilerError("pipeline flags not a literal"); + const args = [...staged.args, boolLit(opts.end, loc)]; + if (opts.signal) { + args[3] = numLit(flagsArg.value | 64, loc); + args.push(opts.signal); + } + return staged.wrap({ kind: "libCall", fn: "sp.pipelineStagesOpts", args, type, loc }); } let streams: IrExpr[]; try { @@ -2502,7 +3027,10 @@ export function lowerStreamModuleCall( // (finished/pipeline throw synchronously; consumers do not). A // sync throw here would be observably wrong timing, so the // provable case takes the named fence instead. - const argV = lowerer.lowerExpr(args[0]!); + // A Hash, Hmac, Cipheriv or Decipheriv is read through its Transform. + const argV = isValueStream(lowerer, args[0]!) + ? valueStreamOf(lowerer.lowerExpr(args[0]!)) + : lowerer.lowerExpr(args[0]!); const argInfo = argV.type.kind === "object" ? lowerer.classes.get(argV.type.className) : undefined; if (argV.type.kind !== "dyn" && !streamSidesOf(lowerer, argInfo)) { @@ -2620,24 +3148,29 @@ export function lowerStreamModuleCall( "the supported form is pipeline(source, ...streams, callback)", ); } - if (args.slice(0, -1).some(isPipelineFunctionStage)) { + if (hasPipelineFunctionStage(lowerer, args.slice(0, -1))) { const staged = lowerPipelineStages(lowerer, args.slice(0, -1), loc); - if (staged.dest !== 0) { - // callback(err, value): the destination's value reaches the - // callback through the checked-dynamic path. Node answers an - // object-mode PassThrough here; reading it has no lowering. - if (!ts.isExpressionStatement(call.parent)) { - lowerer.noLowering( - "using the PassThrough that pipeline() answers for a function destination", - call, - "read the destination's value in the callback", - ); - } + const cbNode = args[args.length - 1]!; + const cbParams = + ts.isArrowFunction(cbNode) || ts.isFunctionExpression(cbNode) + ? cbNode.parameters.nodes.length + : 0; + if (staged.dest === 2 || (staged.dest === 1 && cbParams > 1)) { + // callback(err, value): the destination's value (undefined for + // an async generator) reaches the callback through the + // checked-dynamic path. const cb = lowerer.lowerExprExpecting(args[args.length - 1]!, DYN); + // SCR_PIPE_TYPED_CB: typed code's callback takes null for no error + const stagedArgs = [...staged.args]; + const flagsArg = stagedArgs[3]!; + if (flagsArg.kind !== "numLit") + throw new InternalCompilerError("pipeline flags not a literal"); + if (!isJsSourceFile(ts.getSourceFileOfNode(call))) + stagedArgs[3] = numLit(flagsArg.value | 128, loc); return staged.wrap({ kind: "libCall", fn: "stream.pipelineStagesDyn", - args: [...staged.args, cb], + args: [...stagedArgs, cb], type: staged.last, loc, }); @@ -2674,85 +3207,558 @@ export function lowerStreamModuleCall( }; } - if (bi.member === "compose") return lowerStreamCompose(lowerer, call, loc); + if (bi.member === "compose") { + if (call.arguments.nodes.some((a) => ts.isSpreadElement(a))) { + lowerer.noLowering("compose with spread arguments", call, "pass the streams directly"); + } + return lowerStreamCompose(lowerer, call.arguments.nodes, loc); + } return null; } -/** A pipeline() argument written as a function: an async generator - * function stage. */ -function isPipelineFunctionStage(node: ts.Expression): boolean { - return ts.isFunctionExpression(node) || ts.isArrowFunction(node); +/** A pipeline() function stage: an inline function or arrow function, or + * an identifier bound to a function declaration or to a `const` + * initialized with one, which nothing reassigns. */ +type StageFunction = ts.FunctionExpression | ts.ArrowFunction | ts.FunctionDeclaration; + +/** The function a pipeline() argument writes or names, or null when the + * argument is not a function stage. */ +function pipelineStageFunction(lowerer: Lowerer, node: ts.Expression): StageFunction | null { + if (ts.isFunctionExpression(node) || ts.isArrowFunction(node)) return node; + if (!ts.isIdentifier(node)) return null; + // The stage lowers the declaration's body again with its source typed + // by the pipeline, so resolving it here must not report what collecting + // the declaration's own signature deferred (resolveValueSymbol would). + const resolve = (ident: ts.Identifier): ts.Symbol | undefined => { + const found = lowerer.checker.getSymbolAtLocation(ident); + return found && found.flags & ts.SymbolFlags.Alias + ? lowerer.checker.getAliasedSymbol(found) + : found; + }; + const symbol = resolve(node); + const declarations = symbol?.declarations ?? []; + const bodies = declarations.filter((d) => !ts.isFunctionDeclaration(d) || d.body !== undefined); + if (!symbol || bodies.length !== 1) return null; + const decl = bodies[0]!; + if (lowerer.isStdlibFile(ts.getSourceFileOfNode(decl))) return null; + if (ts.isFunctionDeclaration(decl)) { + return bindingNeverReassigned(lowerer, symbol, decl, resolve) ? decl : null; + } + if ( + ts.isVariableDeclaration(decl) && + decl.initializer && + ts.isVariableDeclarationList(decl.parent) && + (decl.parent.flags & ts.NodeFlags.Const) !== 0 + ) { + let init: ts.Expression = decl.initializer; + while (ts.isParenthesizedExpression(init)) init = init.expression; + if (ts.isFunctionExpression(init) || ts.isArrowFunction(init)) return init; + } + return null; } -/** The lowered function stages of a pipeline: the libcall head [n, at, k, - * flags, mask, streams..., stages..., (next, read, return)?, box?, +function hasPipelineFunctionStage(lowerer: Lowerer, args: readonly ts.Expression[]): boolean { + return ( + args.some((a) => pipelineStageFunction(lowerer, a) !== null) || + (args.length > 0 && iterableSourceType(lowerer, args[0]!) !== null) + ); +} + +type SyncGenType = IrType & { kind: "generator" }; + +/** The element type of a pipeline source that is an iterable value (an + * array, a string or a synchronous generator object), or null. */ +function iterableSourceType(lowerer: Lowerer, node: ts.Expression): IrType | null { + if (pipelineStageFunction(lowerer, node) !== null) return null; + const webElem = staticReadableStreamElementType(lowerer, node); + if (webElem !== null) return webElem; + let t: IrType | null; + try { + t = lowerer.mapTypeOf(lowerer.typeOf(node)); + } catch { + return null; + } + if (t?.kind === "array") return t.elem; + if (t?.kind === "string") return STRING; + if (t?.kind === "generator" && t.async !== true && stepDrivable(t)) return t.yieldT; + return null; +} + +/** A pipeline source that is an iterable value or a synchronous generator + * function without parameters, as an async generator closure that steps + * the value's iterator (or the generator the function returns) and yields + * each element. Node's pipeline iterates such a source with `for await`, + * through an async-from-sync iterator, and an async generator that + * yields the same elements resumes its consumer on the same ticks. Null + * when the source has no such lowering. */ +/** A web ReadableStream source, as an async generator closure over its + * reader: each pass awaits reader.read() and yields the chunk, as the + * stream's async iterator does; leaving early cancels the stream (its + * iterator's return()), and the reader's lock is released either way. */ +function lowerWebStreamSource( + lowerer: Lowerer, + node: ts.Expression, + elemT: IrType, + loc: SrcLoc, +): { closure: IrExpr; out: SyncGenType } | null { + const resultT = genResultRecord(elemT, VOID, lowerer.shapes, lowerer.unions); + if (!resultT) return null; + const valueField = lowerer.shapes.get(resultT.shapeId)?.fields.find((f) => f.name === "value"); + if (!valueField) return null; + const out: SyncGenType = { + kind: "generator", + async: true, + yieldT: elemT, + retT: VOID, + nextT: UNDEFINED_T, + }; + const genResultT = genResultRecord(elemT, VOID, lowerer.shapes, lowerer.unions); + if (!genResultT) return null; + const value = lowerer.lowerExprExpecting(node, DYN); + const key = `webStreamSource:${typeKey(elemT)}`; + let maker = lowerer.valueHelpers.get(key); + if (!maker) { + maker = `%stream.webStreamSource.${lowerer.valueHelpers.size}`; + const genName = `${maker}.gen`; + const frame = new LiftedFrame(loc); + const srcId = frame.local("src", DYN, false); + const readerId = frame.local("reader", DYN, false); + const activeId = frame.local("active", BOOL, true); + const promiseT: IrType = { kind: "promise", inner: resultT }; + const pId = frame.local("p", promiseT, false); + const rId = frame.local("r", resultT, false); + const reader = (): IrExpr => varRef(readerId, DYN, loc); + const r = (): IrExpr => varRef(rId, resultT, loc); + const setActive = (on: boolean): IrStmt => ({ + kind: "assign", + localId: activeId, + value: { kind: "boolLit", value: on, type: BOOL, loc }, + loc, + }); + const extracted = extractIteratorValue( + lowerer, + elemT, + valueField.type, + { + kind: "recordGet", + obj: r(), + shapeId: resultT.shapeId, + field: "value", + type: valueField.type, + loc, + }, + loc, + ); + if (!extracted) return null; + const invoke = (method: string, args: IrExpr[], calleeName: string): IrExpr => ({ + kind: "dynInvoke", + recv: reader(), + method, + calleeName, + args, + type: DYN, + loc, + }); + const body: IrStmt[] = [ + { + kind: "varDecl", + localId: readerId, + init: { + kind: "dynInvoke", + recv: varRef(srcId, DYN, loc), + method: "getReader", + calleeName: "ReadableStream async iterator", + args: [], + type: DYN, + loc, + }, + loc, + }, + { + kind: "varDecl", + localId: activeId, + init: { kind: "boolLit", value: false, type: BOOL, loc }, + loc, + }, + { + kind: "tryCatch", + tryBody: [ + { + kind: "while", + cond: { kind: "boolLit", value: true, type: BOOL, loc }, + body: [ + setActive(false), + { + kind: "varDecl", + localId: pId, + init: { + kind: "libCall", + fn: "fetch.readerRead", + args: [reader()], + type: promiseT, + loc, + }, + loc, + }, + { + kind: "varDecl", + localId: rId, + init: { kind: "awaitExpr", value: varRef(pId, promiseT, loc), type: resultT, loc }, + loc, + }, + { + kind: "if", + cond: { + kind: "recordGet", + obj: r(), + shapeId: resultT.shapeId, + field: "done", + type: BOOL, + loc, + }, + then: [{ kind: "break", loc }], + else_: null, + loc, + }, + setActive(true), + { + kind: "exprStmt", + expr: { kind: "yieldExpr", value: extracted, type: VOID, loc }, + loc, + }, + ], + loc, + }, + ], + catchBody: null, + catchLocalId: null, + finallyBody: [ + { + kind: "tryCatch", + tryBody: [ + { + kind: "if", + cond: varRef(activeId, BOOL, loc), + then: [ + { + kind: "exprStmt", + expr: { + kind: "libCall", + fn: "async.awaitDyn", + args: [ + invoke( + "cancel", + [dynUndefinedExpr(loc)], + "ReadableStream async iterator return", + ), + ], + type: DYN, + loc, + }, + loc, + }, + ], + else_: null, + loc, + }, + ], + catchBody: null, + catchLocalId: null, + finallyBody: [ + { + kind: "exprStmt", + expr: invoke("releaseLock", [], "ReadableStream async iterator releaseLock"), + loc, + }, + ], + loc, + }, + ], + loc, + }, + { kind: "return", value: null, loc }, + ]; + const srcLocal = frame.locals.find((l) => l.id === srcId)!; + srcLocal.boxed = true; + lowerer.valueHelpers.set(key, maker); + lowerer.liftedFns.push({ + name: genName, + params: [], + returnType: VOID, + async: true, + captures: [{ localId: srcId, name: "src", type: DYN }], + locals: frame.locals, + body, + generator: { yieldT: elemT, nextT: UNDEFINED_T, resultType: genResultT }, + loc, + }); + const makerSrc: IrLocal = { id: "src.0", name: "src", type: DYN, mutable: false, boxed: true }; + lowerer.liftedFns.push({ + name: maker, + params: [{ localId: makerSrc.id, name: makerSrc.name, type: DYN }], + returnType: funcOf([], out), + locals: [makerSrc], + body: [ + { + kind: "return", + value: { + kind: "closure", + fnName: genName, + captures: [makerSrc.id], + type: funcOf([], out), + loc, + }, + loc, + }, + ], + loc, + }); + } + return { + closure: { kind: "call", callee: maker, args: [value], type: funcOf([], out), loc }, + out, + }; +} + +function lowerIterableSource( + lowerer: Lowerer, + node: ts.Expression, + fn: StageFunction | null, + loc: SrcLoc, +): { closure: IrExpr; out: SyncGenType } | null { + if (fn === null) { + const webElem = staticReadableStreamElementType(lowerer, node); + if (webElem !== null) return lowerWebStreamSource(lowerer, node, webElem, loc); + } + let value: IrExpr; + if (fn !== null) { + if (fn.parameters.nodes.length > 0) { + lowerer.noLowering( + "a synchronous generator function pipeline source with parameters", + fn.parameters.nodes[0]!, + "declare the source without parameters, or make it an async generator function", + ); + } + value = lowerer.lowerLambda(fn); + if (value.type.kind !== "func" || value.type.ret.kind !== "generator") return null; + } else { + value = lowerer.lowerExpr(node); + } + const srcT = value.type; + const elemT: IrType | null = + srcT.kind === "func" && srcT.ret.kind === "generator" + ? srcT.ret.yieldT + : srcT.kind === "array" + ? srcT.elem + : srcT.kind === "string" + ? STRING + : srcT.kind === "generator" && srcT.async !== true + ? srcT.yieldT + : null; + if (elemT === null) return null; + const out: SyncGenType = { + kind: "generator", + async: true, + yieldT: elemT, + retT: VOID, + nextT: UNDEFINED_T, + }; + const resultType = genResultRecord(elemT, VOID, lowerer.shapes, lowerer.unions); + if (!resultType) return null; + const key = `pipelineSource:${typeKey(srcT)}`; + let maker = lowerer.valueHelpers.get(key); + if (!maker) { + maker = `%stream.pipelineSource.${lowerer.valueHelpers.size}`; + const genName = `${maker}.gen`; + // The generator: g = the source's iterator; for (v of g) yield v. + const frame = new LiftedFrame(loc); + const srcId = frame.local("src", srcT, false); + const src = varRef(srcId, srcT, loc); + const syncT: SyncGenType = { + kind: "generator", + yieldT: elemT, + retT: VOID, + nextT: UNDEFINED_T, + }; + let iterator: IrExpr | null; + if (srcT.kind === "func") { + iterator = { kind: "callValue", callee: src, args: [], type: srcT.ret, loc }; + } else if (srcT.kind === "array") { + iterator = lowerArrayIteratorValue(lowerer, src, "values", syncT, loc); + } else if (srcT.kind === "string") { + iterator = lowerStringIteratorValue(lowerer, src, syncT, loc); + } else { + iterator = src; + } + if (iterator === null || iterator.type.kind !== "generator" || !stepDrivable(iterator.type)) + return null; + const iterT = iterator.type; + const gId = frame.local("g", iterT, false); + const body: IrStmt[] = [ + { kind: "varDecl", localId: gId, init: iterator, loc }, + ...driveGenerator( + lowerer, + frame, + gId, + iterT, + elemT, + [], + (v) => [{ kind: "exprStmt", expr: { kind: "yieldExpr", value: v, type: VOID, loc }, loc }], + loc, + ), + { kind: "return", value: null, loc }, + ]; + const srcLocal = frame.locals.find((l) => l.id === srcId)!; + srcLocal.boxed = true; + lowerer.valueHelpers.set(key, maker); + lowerer.liftedFns.push({ + name: genName, + params: [], + returnType: VOID, + async: true, + captures: [{ localId: srcId, name: "src", type: srcT }], + locals: frame.locals, + body, + generator: { yieldT: elemT, nextT: UNDEFINED_T, resultType }, + loc, + }); + // The maker: (src) => the generator function closed over src. + const makerSrc: IrLocal = { id: "src.0", name: "src", type: srcT, mutable: false, boxed: true }; + lowerer.liftedFns.push({ + name: maker, + params: [{ localId: makerSrc.id, name: makerSrc.name, type: srcT }], + returnType: funcOf([], out), + locals: [makerSrc], + body: [ + { + kind: "return", + value: { + kind: "closure", + fnName: genName, + captures: [makerSrc.id], + type: funcOf([], out), + loc, + }, + loc, + }, + ], + loc, + }); + } + return { + closure: { kind: "call", callee: maker, args: [value], type: funcOf([], out), loc }, + out, + }; +} + +/** The lowered function stages of a pipeline: the libcall head [n, k, + * positions, flags, mask, streams..., stages..., helpers..., box?, * (signal, abort)?], the destination's type (the last stream, or the * PassThrough a function destination answers), the destination kind * (SCR_PIPE_DEST_*), a promise destination's promise type, and a wrapper * that binds the pipeline's AbortController around the call when a - * stage takes `{ signal }`. */ + * stage takes `{ signal }`. positions has bit j set when the pipeline's + * j-th stage is a function; helpers holds (next, read, return) for each + * generator pumped into a stream. */ interface PipelineStagesLowering { args: IrExpr[]; last: IrType; - dest: 0 | 2; + dest: 0 | 1 | 2; destPromise: (IrType & { kind: "promise" }) | null; wrap: (call: IrExpr) => IrExpr; } -/** pipeline(...) with one run of function stages (pipeline.js). The run - * may start the pipeline (a source function, called with `{ signal }`) - * and may end it (a destination function: an async generator pumped into - * a PassThrough, or an async function whose promise's value reaches the - * callback or the promise). Each stage's `source` parameter is typed as - * what the pipeline passes it: makeAsyncIterable answers the previous - * stream itself (a Readable is async iterable) or the previous stage's +/** pipeline(...) with function stages (pipeline.js). A function may + * start the pipeline (a source function, called with `{ signal }`), may + * end it (an async function whose promise's value reaches the callback or + * the promise, or an async generator function), and runs of async + * generator functions may sit between streams; the last generator of a + * run that a stream follows is pumped into that stream. A function + * destination feeds the object-mode PassThrough that pipeline() answers. Each stage's `source` parameter is typed as what the + * pipeline passes it: makeAsyncIterable answers the previous stream + * itself (a Readable is async iterable) or the previous stage's * generator. */ function lowerPipelineStages( lowerer: Lowerer, stageArgs: readonly ts.Expression[], loc: SrcLoc, + preLowered?: ReadonlyMap, ): PipelineStagesLowering { - const first = stageArgs.findIndex(isPipelineFunctionStage); - let end = first; - while (end < stageArgs.length && isPipelineFunctionStage(stageArgs[end]!)) end++; - if (stageArgs.slice(end).some(isPipelineFunctionStage)) { + if (stageArgs.length > 52) { lowerer.noLowering( - "pipeline with function stages separated by streams", - stageArgs[end]!, - "one run of function stages is supported", + "pipeline with function stages and more than 52 stages", + stageArgs[52]!, + "split the pipeline", ); } - const source = first === 0; - const destFn = end === stageArgs.length; - const before: IrExpr[] = []; - const after: IrExpr[] = []; - try { - for (const a of stageArgs.slice(0, first)) before.push(lowerStreamArg(lowerer, a, "pipeline")); - } catch (e) { - if (e instanceof StreamArgTypeThrow) - lowerer.noLowering("pipeline over this value", stageArgs[0]!); - throw e; - } - let srcT: IrType | null = source ? null : before[before.length - 1]!.type; + const streams: IrExpr[] = []; const stages: IrExpr[] = []; + const helperArgs: IrExpr[] = []; + let positions = 0; let mask = 0; - let dest: 0 | 2 = 0; + let dest: 0 | 1 | 2 = 0; let destPromise: (IrType & { kind: "promise" }) | null = null; - for (let i = first; i < end; i++) { - const fn = stageArgs[i] as ts.FunctionExpression | ts.ArrowFunction; - const isLast = destFn && i === end - 1; - const isAsync = (fn.modifiers?.nodes ?? []).some((m) => m.kind === ts.SyntaxKind.AsyncKeyword); - const isGen = ts.isFunctionExpression(fn) && fn.asteriskToken !== undefined; - if (isLast && isGen) { - // pipeline() pumps it into an object-mode PassThrough, whose - // buffering decides when the pipeline finishes - lowerer.noLowering( - "a pipeline destination that is an async generator function", - fn, - "end the pipeline with a stream or an async function (source) { for await (const chunk of source) ... }", - ); + // What the next function stage receives: null before the first stage, + // else the previous stream's type or the previous stage's generator. + let srcT: IrType | null = null; + // The streams and stages in argument order: the head lists all streams + // before all stages, so when a stage precedes a stream the arguments + // are bound to locals first, keeping JavaScript's evaluation order. + const argOrder: { list: IrExpr[]; index: number }[] = []; + for (let j = 0; j < stageArgs.length; j++) { + const arg = stageArgs[j]!; + // compose's head and tail functions arrive as Duplex.from streams + const fn = preLowered?.has(j) ? null : pipelineStageFunction(lowerer, arg); + const syncSourceFn = + j === 0 && + fn !== null && + !ts.isArrowFunction(fn) && + fn.asteriskToken !== undefined && + !(fn.modifiers?.nodes ?? []).some((m) => m.kind === ts.SyntaxKind.AsyncKeyword); + if ( + j === 0 && + !preLowered?.has(j) && + (syncSourceFn || (fn === null && iterableSourceType(lowerer, arg) !== null)) + ) { + const source = lowerIterableSource(lowerer, arg, syncSourceFn ? fn : null, loc); + if (source === null) lowerer.noLowering("pipeline over this source", arg); + positions += 1; + argOrder.push({ list: stages, index: stages.length }); + stages.push(source!.closure); + srcT = source!.out; + continue; } + if (fn === null) { + if (srcT?.kind === "generator") { + // the generator before this stream, pumped into it + if (!fromGenChunk(lowerer, srcT.yieldT)) { + lowerer.noLowering( + `a pipeline stage yielding '${lowerer.fmt(srcT.yieldT)}'`, + stageArgs[j - 1]!, + "stage values written to a stream are strings or Buffers", + ); + } + const helpers = fromGenHelpers(lowerer, srcT, loc); + if (!helpers) + lowerer.noLowering("a pipeline stage with this generator type", stageArgs[j - 1]!); + helperArgs.push(helpers![0]!, helpers![1]!, helpers![2]!); + } + let stream: IrExpr; + try { + stream = preLowered?.get(j) ?? lowerStreamArg(lowerer, arg, "pipeline"); + } catch (e) { + if (e instanceof StreamArgTypeThrow) lowerer.noLowering("pipeline over this value", arg); + throw e; + } + argOrder.push({ list: streams, index: streams.length }); + streams.push(stream); + srcT = stream.type; + continue; + } + const isLast = j === stageArgs.length - 1; + const isAsync = (fn.modifiers?.nodes ?? []).some((m) => m.kind === ts.SyntaxKind.AsyncKeyword); + const isGen = !ts.isArrowFunction(fn) && fn.asteriskToken !== undefined; if (!isAsync || (!isGen && !isLast)) { lowerer.noLowering( isLast @@ -2760,7 +3766,7 @@ function lowerPipelineStages( : srcT === null ? "a pipeline source function that is not an async generator function" : "pipeline stages that are not async generator functions", - fn, + arg, "write the stage as async function* (source) { for await (const chunk of source) ... }", ); } @@ -2782,40 +3788,28 @@ function lowerPipelineStages( "type it as { signal: AbortSignal }", ); } - mask |= 1 << (i - first); + mask |= 1 << stages.length; } + positions += 2 ** j; + argOrder.push({ list: stages, index: stages.length }); stages.push(lowered.closure); if (lowered.out.kind === "promise") { dest = 2; destPromise = lowered.out; srcT = null; + } else if (isLast) { + // an async generator destination: pumped into the object-mode + // PassThrough that pipeline() answers + const helpers = fromGenHelpers(lowerer, lowered.out, loc); + if (!helpers) lowerer.noLowering("a pipeline destination with this generator type", arg); + helperArgs.push(helpers![0]!, helpers![1]!, helpers![2]!); + dest = 1; + srcT = null; } else { srcT = lowered.out; } } - try { - for (const a of stageArgs.slice(end)) after.push(lowerStreamArg(lowerer, a, "pipeline")); - } catch (e) { - if (e instanceof StreamArgTypeThrow) - lowerer.noLowering("pipeline over this value", stageArgs[end]!); - throw e; - } - const helperArgs: IrExpr[] = []; - if (dest !== 2) { - // the generator pumped into the next stream or the PassThrough - const lastGen = srcT as IrType & { kind: "generator" }; - if (!fromGenChunk(lowerer, lastGen.yieldT)) { - lowerer.noLowering( - `a pipeline stage yielding '${lowerer.fmt(lastGen.yieldT)}'`, - stageArgs[end - 1]!, - "stage values written to a stream are strings or Buffers", - ); - } - const helpers = fromGenHelpers(lowerer, lastGen, loc); - if (!helpers) - lowerer.noLowering("a pipeline stage with this generator type", stageArgs[end - 1]!); - helperArgs.push(helpers![0]!, helpers![1]!, helpers![2]!); - } else { + if (dest === 2) { const valueT = destPromise!.inner; if ( valueT.kind !== "void" && @@ -2827,29 +3821,41 @@ function lowerPipelineStages( ) { lowerer.noLowering( `a pipeline destination resolving to '${lowerer.fmt(valueT)}'`, - stageArgs[end - 1]!, + stageArgs[stageArgs.length - 1]!, ); } helperArgs.push(pipelineBoxHelper(lowerer, destPromise!, loc)); } - const streams = [...before, ...after]; - // SCR_PIPE_* flags: bit 0 a source function, bits 1-2 the destination, - // bit 3 the helpers, bit 4 the box, bit 5 the signal and abort. - const flags = (source ? 1 : 0) | (dest << 1) | (dest !== 2 ? 8 : 16) | (mask !== 0 ? 32 : 0); + const argDecls: IrStmt[] = []; + const firstStage = argOrder.findIndex((a) => a.list === stages); + if (firstStage >= 0 && argOrder.slice(firstStage).some((a) => a.list === streams)) { + for (const a of argOrder) { + const init = a.list[a.index]!; + const local = lowerer.declareHiddenLocal("%pipelineArg", init.type); + argDecls.push({ kind: "varDecl", localId: local.id, init, loc: init.loc }); + a.list[a.index] = varRef(local.id, init.type, init.loc); + } + } + const bindArgs = (call: IrExpr): IrExpr => + argDecls.length === 0 + ? call + : { kind: "seqExpr", stmts: argDecls, result: call, type: call.type, loc }; + // SCR_PIPE_* flags: bits 1-2 the destination, bit 5 the signal and + // abort (bit 6, the promise form's options signal, is set by its caller). + const flags = (dest << 1) | (mask !== 0 ? 32 : 0); const head: IrExpr[] = [ numLit(streams.length, loc), - numLit(before.length, loc), numLit(stages.length, loc), + numLit(positions, loc), numLit(flags, loc), numLit(mask, loc), ...streams, ...stages, ...helperArgs, ]; - const last: IrType = destFn - ? { kind: "object", className: "%PassThrough" } - : streams[streams.length - 1]!.type; - if (mask === 0) return { args: head, last, dest, destPromise, wrap: (call) => call }; + const last: IrType = + dest !== 0 ? { kind: "object", className: "%PassThrough" } : streams[streams.length - 1]!.type; + if (mask === 0) return { args: head, last, dest, destPromise, wrap: bindArgs }; // const ac = new AbortController(): its signal goes to the stages, and // finishImpl's ac.abort() runs through the abort closure. const ac = lowerer.declareHiddenLocal("%pipelineAbort", DYN); @@ -2866,20 +3872,21 @@ function lowerPipelineStages( last, dest, destPromise, - wrap: (call) => ({ - kind: "seqExpr", - stmts: [ - { - kind: "varDecl", - localId: ac.id, - init: { kind: "libCall", fn: "fetch.abortControllerNew", args: [], type: DYN, loc }, - loc, - }, - ], - result: call, - type: call.type, - loc, - }), + wrap: (call) => + bindArgs({ + kind: "seqExpr", + stmts: [ + { + kind: "varDecl", + localId: ac.id, + init: { kind: "libCall", fn: "fetch.abortControllerNew", args: [], type: DYN, loc }, + loc, + }, + ], + result: call, + type: call.type, + loc, + }), }; } @@ -2894,7 +3901,7 @@ function pipelineBoxHelper( const key = `pipelineBox:${typeKey(promiseT)}`; let name = lowerer.valueHelpers.get(key); if (!name) { - name = `%stream.pipelineBox.${lowerer.valueHelpers.size}`; + name = keyedHelperName(lowerer, "%stream.pipelineBox", key); lowerer.valueHelpers.set(key, name); lowerer.liftedFns.push({ name, @@ -2916,21 +3923,27 @@ function pipelineBoxHelper( /** `() => ac.abort()` over the pipeline's AbortController: an interned * lifted function takes the controller and answers the closure. */ -function pipelineAbortHelper(lowerer: Lowerer, ac: IrExpr, loc: SrcLoc): IrExpr { - const key = "pipelineAbort"; +function pipelineAbortHelper( + lowerer: Lowerer, + ac: IrExpr, + loc: SrcLoc, + withReason = false, +): IrExpr { + const key = withReason ? "pipelineAbortReason" : "pipelineAbort"; let name = lowerer.valueHelpers.get(key); - const abortT = funcOf([], VOID); + const abortT = funcOf(withReason ? [DYN] : [], VOID); if (!name) { - name = `%stream.pipelineAbort.${lowerer.valueHelpers.size}`; + name = keyedHelperName(lowerer, "%stream.pipelineAbort", key); lowerer.valueHelpers.set(key, name); const acLocal: IrLocal = { id: "ac.0", name: "ac", type: DYN, mutable: false, boxed: true }; const acRef = varRef(acLocal.id, DYN, loc); + const reasonLocal: IrLocal = { id: "reason.0", name: "reason", type: DYN, mutable: false }; lowerer.liftedFns.push({ name: `${name}.abort`, - params: [], + params: withReason ? [{ localId: reasonLocal.id, name: reasonLocal.name, type: DYN }] : [], returnType: VOID, captures: [{ localId: acLocal.id, name: acLocal.name, type: DYN }], - locals: [acLocal], + locals: withReason ? [acLocal, reasonLocal] : [acLocal], body: [ { kind: "exprStmt", @@ -2939,7 +3952,7 @@ function pipelineAbortHelper(lowerer: Lowerer, ac: IrExpr, loc: SrcLoc): IrExpr recv: acRef, method: "abort", calleeName: "ac.abort", - args: [], + args: withReason ? [varRef(reasonLocal.id, DYN, loc)] : [], type: DYN, loc, }, @@ -2979,7 +3992,7 @@ function pipelineAbortHelper(lowerer: Lowerer, ac: IrExpr, loc: SrcLoc): IrExpr * generator, or a promise for a destination async function. */ function lowerStageFunction( lowerer: Lowerer, - fn: ts.FunctionExpression | ts.ArrowFunction, + fn: StageFunction, srcT: IrType | null, ): { closure: IrExpr; out: IrType & ({ kind: "generator" } | { kind: "promise" }) } { const param = srcT === null ? undefined : fn.parameters.nodes[0]; @@ -2994,6 +4007,8 @@ function lowerStageFunction( "name the source parameter", ); } + // The loop variables of the `for await` loops over the source. + const chunkSymbols: ts.Symbol[] = []; if (symbol && fn.body) { const visit = (node: ts.Node): void => { if ( @@ -3016,14 +4031,36 @@ function lowerStageFunction( "iterate the source with for await (const chunk of source)", ); } + const binding = ts.isVariableDeclarationList(parent.initializer) + ? parent.initializer.declarations.nodes[0]?.name + : undefined; + const chunk = + binding && ts.isIdentifier(binding) + ? lowerer.checker.getSymbolAtLocation(binding) + : undefined; + if (chunk) chunkSymbols.push(chunk); } ts.forEachChild(node, visit); }; visit(fn.body); } if (symbol) lowerer.stageSourceTypes.set(symbol, srcT!); + // In JavaScript the checker types the chunks of a source that is the + // previous stage's generator `any`; they read as the strings or Buffers + // the generator yields, so their members take the string and Buffer + // lowerings. + const previousImplicit = lowerer.implicitParamTypes; + const chunkType = + srcT?.kind === "generator" && isJsSourceFile(ts.getSourceFileOfNode(fn)) + ? stageChunkCheckerType(lowerer, srcT.yieldT, fn) + : null; + if (chunkType && chunkSymbols.length > 0) { + const implicit = new Map(previousImplicit ?? []); + for (const chunk of chunkSymbols) implicit.set(chunk, chunkType); + lowerer.implicitParamTypes = implicit; + } try { - const closure = lowerer.lowerExpr(fn); + const closure = lowerer.lowerLambda(fn); const out = closure.type.kind === "func" ? closure.type.ret : null; if (!(out?.kind === "generator" && out.async) && out?.kind !== "promise") { lowerer.noLowering("a pipeline stage that does not return an async generator", fn); @@ -3031,20 +4068,393 @@ function lowerStageFunction( return { closure, out: out as IrType & ({ kind: "generator" } | { kind: "promise" }) }; } finally { if (symbol) lowerer.stageSourceTypes.delete(symbol); + lowerer.implicitParamTypes = previousImplicit; } } +/** The async generator a Duplex.from body iterates (duplexify.js's + * fromAsyncGen source), as a closure the runtime calls with next() and + * ack(): each pass awaits next() (the deferred a write or the final + * settles), calls ack() (process.nextTick(cb) and a fresh deferred), + * returns at the done marker, and yields the chunk. */ +function duplexSourceHelper(lowerer: Lowerer, genT: SyncGenType, loc: SrcLoc): IrExpr | null { + const nextT = funcOf([], { kind: "promise", inner: DYN }); + const ackT = funcOf([], VOID); + const type = funcOf([nextT, ackT], genT); + const key = "duplexSource"; + let name = lowerer.valueHelpers.get(key); + if (!name) { + const resultType = genResultRecord(DYN, VOID, lowerer.shapes, lowerer.unions); + if (!resultType) return null; + name = `%stream.duplexSource.${lowerer.valueHelpers.size}`; + const frame = new LiftedFrame(loc); + const nextId = frame.param("next", nextT); + const ackId = frame.param("ack", ackT); + const valueId = frame.local("value", DYN, false); + const value = varRef(valueId, DYN, loc); + const body: IrStmt[] = [ + { + kind: "while", + cond: { kind: "boolLit", value: true, type: BOOL, loc }, + body: [ + { + kind: "varDecl", + localId: valueId, + init: { + kind: "awaitExpr", + value: { + kind: "callValue", + callee: varRef(nextId, nextT, loc), + args: [], + type: { kind: "promise", inner: DYN }, + loc, + }, + type: DYN, + loc, + }, + loc, + }, + { + kind: "exprStmt", + expr: { + kind: "callValue", + callee: varRef(ackId, ackT, loc), + args: [], + type: VOID, + loc, + }, + loc, + }, + { + kind: "if", + cond: { kind: "libCall", fn: "stream.chunkDone", args: [value], type: BOOL, loc }, + then: [{ kind: "return", value: null, loc }], + else_: null, + loc, + }, + { kind: "exprStmt", expr: { kind: "yieldExpr", value, type: VOID, loc }, loc }, + ], + loc, + }, + { kind: "return", value: null, loc }, + ]; + lowerer.valueHelpers.set(key, name); + lowerer.liftedFns.push({ + name, + params: frame.params, + returnType: VOID, + async: true, + locals: frame.locals, + body, + generator: { yieldT: DYN, nextT: UNDEFINED_T, resultType }, + loc, + }); + } + return { kind: "closure", fnName: name, captures: [], type, loc }; +} + +/** Duplex.from(body) (duplexify.js) for the bodies with a lowering: an + * async generator function, whose source generator the Duplex's writes + * feed (stream.duplexFromGen); a duplex stream, which answers itself; and + * the bodies Readable.from reads (iterables, strings, generators), as a + * Duplexify that is not writable. */ +function duplexFromBody(lowerer: Lowerer, node: ts.Expression, loc: SrcLoc): IrExpr { + const duplex: IrType = { kind: "object", className: "%Duplex" }; + const fn = pipelineStageFunction(lowerer, node); + if (fn !== null) { + const isAsync = (fn.modifiers?.nodes ?? []).some((m) => m.kind === ts.SyntaxKind.AsyncKeyword); + const isGen = !ts.isArrowFunction(fn) && fn.asteriskToken !== undefined; + if (!isAsync) { + lowerer.noLowering( + "Duplex.from over a function that is not async", + node, + "write the body as async function* (source) { ... } or async function (source) { ... }", + ); + } + if (fn.parameters.nodes.length > 2) { + lowerer.noLowering( + "a Duplex.from body with parameters after the options argument", + fn.parameters.nodes[2]!, + "the body takes the source and { signal }", + ); + } + const sourceT: SyncGenType = { + kind: "generator", + async: true, + yieldT: DYN, + retT: VOID, + nextT: UNDEFINED_T, + }; + const lowered = lowerStageFunction(lowerer, fn, sourceT); + const params = lowered.closure.type.kind === "func" ? lowered.closure.type.params : []; + // fromAsyncGen calls the body with { signal } of an AbortController + // that destroy aborts with its error. + let signalArgs: IrExpr[] = []; + let signalDecls: IrStmt[] = []; + if (params.length > 1) { + if (params[1]!.kind !== "dyn") { + lowerer.noLowering( + "a Duplex.from body's options argument with this type", + fn.parameters.nodes[1]!, + "type it as { signal: AbortSignal }", + ); + } + const acLocal = lowerer.declareHiddenLocal("%duplexAbort", DYN); + const ac = varRef(acLocal.id, DYN, loc); + signalDecls = [ + { + kind: "varDecl", + localId: acLocal.id, + init: { kind: "libCall", fn: "fetch.abortControllerNew", args: [], type: DYN, loc }, + loc, + }, + ]; + signalArgs = [ + pipelineAbortHelper(lowerer, ac, loc, true), + { kind: "dynKeyGet", value: ac, key: strLit("signal", loc), type: DYN, loc }, + ]; + } + const withSignal = (fnName: IrLibFn, args: IrExpr[]): IrExpr => { + const call: IrExpr = { + kind: "libCall", + fn: signalArgs.length > 0 ? (`${fnName}Signal` as IrLibFn) : fnName, + args: [...args, ...signalArgs], + type: duplex, + loc, + }; + return signalDecls.length > 0 + ? { kind: "seqExpr", stmts: signalDecls, result: call, type: duplex, loc } + : call; + }; + if (!isGen) { + // an async function: a writable Duplexify whose final waits for + // the function's promise + const asyncSource = duplexSourceHelper(lowerer, sourceT, loc); + const out = lowered.out; + if (out.kind !== "promise" || !asyncSource) + return lowerer.noLowering("Duplex.from over a function with this return type", node); + if ( + out.inner.kind !== "void" && + !canConvertToDyn( + out.inner, + (id) => lowerer.shapes.get(id), + (id) => lowerer.unions.get(id), + ) + ) { + lowerer.noLowering( + `Duplex.from over a function resolving to '${lowerer.fmt(out.inner)}'`, + node, + ); + } + return withSignal("stream.duplexFromAsyncFn", [ + lowered.closure, + asyncSource, + pipelineBoxHelper(lowerer, out, loc), + ]); + } + const helpers = + lowered.out.kind === "generator" ? fromGenHelpers(lowerer, lowered.out, loc) : null; + const source = duplexSourceHelper(lowerer, sourceT, loc); + if (!helpers || !source) + lowerer.noLowering("Duplex.from over a function with this generator type", node); + return withSignal("stream.duplexFromGen", [lowered.closure, source!, ...helpers!]); + } + // duplexify.js: a stream answers itself (a Duplex) or is wrapped; any + // other body reads as from(Duplexify, body, { objectMode: true, + // writable: false }) + let bodyT: IrType | null; + try { + bodyT = lowerer.mapTypeOf(lowerer.typeOf(node)); + } catch { + bodyT = null; + } + const bodySides = + bodyT?.kind === "object" ? streamSidesOf(lowerer, lowerer.classes.get(bodyT.className)) : null; + let literal: ts.Expression = node; + while (ts.isParenthesizedExpression(literal)) literal = literal.expression; + if (bodySides === null && ts.isObjectLiteralExpression(literal)) + return duplexFromPair(lowerer, literal, loc); + if (bodyT?.kind === "promise") { + // a Duplexify that reads the promise's value + const valueT = bodyT.inner; + if ( + valueT.kind !== "void" && + !canConvertToDyn( + valueT, + (id) => lowerer.shapes.get(id), + (id) => lowerer.unions.get(id), + ) + ) { + lowerer.noLowering(`Duplex.from over a promise of '${lowerer.fmt(valueT)}'`, node); + } + const promise = lowerer.lowerExpr(node); + if (promise.type.kind !== "promise") { + // a checked-dynamic promise (an untyped function's result) + return { + kind: "libCall", + fn: "stream.duplexFromDyn", + args: [lowerer.coerceToExpected(promise, DYN)], + type: { kind: "object", className: "%Duplex" }, + loc, + }; + } + return { + kind: "libCall", + fn: "stream.duplexFromPromise", + args: [ + promise, + pipelineBoxHelper(lowerer, promise.type as IrType & { kind: "promise" }, loc), + ], + type: { kind: "object", className: "%Duplex" }, + loc, + }; + } + if (bodySides === null) return lowerFromSource(lowerer, node, node, undefined, true); + let stream: IrExpr; + try { + stream = lowerStreamArg(lowerer, node, "compose"); + } catch (e) { + if (e instanceof StreamArgTypeThrow) return e.expr; + throw e; + } + const sides = + stream.type.kind === "object" + ? streamSidesOf(lowerer, lowerer.classes.get(stream.type.className)) + : null; + // _duplexify({ readable }) / _duplexify({ writable }) + if (sides === "r" || sides === "w") { + return { + kind: "libCall", + fn: sides === "r" ? "stream.duplexifyReadable" : "stream.duplexifyWritable", + args: [stream], + type: duplex, + loc, + }; + } + if (sides !== "rw") { + lowerer.noLowering( + "Duplex.from over a value of this type", + node, + "an async generator function, an iterable, a stream, or a { readable, writable } pair is the lowered body", + ); + } + return stream; +} + +/** Duplex.from({ readable, writable }): each member that is a stream with + * that side is used as it is, any other member is Duplex.from of it, and + * the pair reads and writes through _duplexify (duplexify.js). The + * members evaluate in source order. */ +function duplexFromPair( + lowerer: Lowerer, + literal: ts.ObjectLiteralExpression, + loc: SrcLoc, +): IrExpr { + const duplex: IrType = { kind: "object", className: "%Duplex" }; + const sides: { readable?: IrExpr; writable?: IrExpr } = {}; + // The members in source order; when that is not (readable, writable), + // each value is bound to a local first, keeping the literal's + // evaluation order. + const members: { key: "readable" | "writable"; value: IrExpr }[] = []; + for (const p of literal.properties.nodes) { + const key = + (ts.isPropertyAssignment(p) || ts.isShorthandPropertyAssignment(p)) && ts.isIdentifier(p.name) + ? p.name.text + : null; + if (key !== "readable" && key !== "writable") { + lowerer.noLowering( + "Duplex.from over an object with members other than readable and writable", + p, + "pass { readable, writable } with streams or Duplex.from bodies", + ); + } + const value = ts.isShorthandPropertyAssignment(p) + ? (p.name as ts.Identifier) + : (p as ts.PropertyAssignment).initializer; + let valueT: IrType | null; + try { + valueT = lowerer.mapTypeOf(lowerer.typeOf(value)); + } catch { + valueT = null; + } + const valueSides = + valueT?.kind === "object" + ? streamSidesOf(lowerer, lowerer.classes.get(valueT.className)) + : null; + const wanted = key === "readable" ? "r" : "w"; + const direct = valueSides === "rw" || valueSides === wanted; + members.push({ + key: key!, + value: direct + ? lowerStreamArg(lowerer, value, "compose") + : duplexFromBody(lowerer, value, loc), + }); + } + const decls: IrStmt[] = []; + const inOrder = + members.length <= 1 || + (members.length === 2 && members[0]!.key === "readable" && members[1]!.key === "writable"); + for (const m of members) { + if (inOrder) { + sides[m.key] = m.value; + continue; + } + const local = lowerer.declareHiddenLocal(`%duplex${m.key}`, m.value.type); + decls.push({ kind: "varDecl", localId: local.id, init: m.value, loc }); + sides[m.key] = varRef(local.id, m.value.type, loc); + } + const { readable, writable } = sides; + if (readable && writable) { + const call: IrExpr = { + kind: "libCall", + fn: "stream.duplexifyPair", + args: [readable, writable], + type: duplex, + loc, + }; + return decls.length > 0 + ? { kind: "seqExpr", stmts: decls, result: call, type: duplex, loc } + : call; + } + if (decls.length > 0) { + // a repeated member: every value is evaluated, the last one is used + const one = readable ?? writable!; + const call: IrExpr = { + kind: "libCall", + fn: readable ? "stream.duplexifyReadable" : "stream.duplexifyWritable", + args: [one], + type: duplex, + loc, + }; + return { kind: "seqExpr", stmts: decls, result: call, type: duplex, loc }; + } + if (readable) + return { kind: "libCall", fn: "stream.duplexifyReadable", args: [readable], type: duplex, loc }; + if (writable) + return { kind: "libCall", fn: "stream.duplexifyWritable", args: [writable], type: duplex, loc }; + return lowerer.noLowering( + "Duplex.from over an object with neither readable nor writable", + literal, + "pass { readable, writable } with streams or Duplex.from bodies", + ); +} + +/** The checker type of a stage's string or Buffer chunks, or null for + * other chunk types. */ +function stageChunkCheckerType(lowerer: Lowerer, chunk: IrType, at: ts.Node): ts.Type | null { + if (chunk.kind === "string") return lowerer.checker.getStringType(); + if (chunk.kind !== "bytes") return null; + const buffer = lowerer.checker.resolveName("Buffer", ts.SymbolFlags.Type, at, false); + return buffer ? lowerer.checker.getDeclaredTypeOfSymbol(buffer) : null; +} + /** `stream.compose(...streams)` over stream instances: a Duplex writing * to the first stream and reading from the last (scr_stream_compose). The * classes fix which positions can be readable and writable; a stream in * the wrong position, a single Readable or Writable (Duplex.from wraps * those), and functions, iterables or web streams have no lowering. */ -function lowerStreamCompose(lowerer: Lowerer, call: ts.CallExpression, loc: SrcLoc): IrExpr { - const args = call.arguments.nodes; +function lowerStreamCompose(lowerer: Lowerer, args: readonly ts.Expression[], loc: SrcLoc): IrExpr { const duplex: IrType = { kind: "object", className: "%Duplex" }; - if (args.some((a) => ts.isSpreadElement(a))) { - lowerer.noLowering("compose with spread arguments", call, "pass the streams directly"); - } if (args.length === 0) { return nodeThrowExpr( 1, @@ -3054,9 +4464,47 @@ function lowerStreamCompose(lowerer: Lowerer, call: ts.CallExpression, loc: SrcL loc, ); } + // A web ReadableStream first stage reads as an async iterable (the + // pipeline's source), and alone it is Duplex.from of it; a later stage + // would be Duplex.fromWeb of it. + for (let i = 1; i < args.length; i++) { + const a = args[i]!; + // (typeOf on a stage function's name would report what collecting its + // declared signature deferred) + if (pipelineStageFunction(lowerer, a) !== null) continue; + if (staticReadableStreamElementType(lowerer, a) !== null) { + lowerer.noLowering( + "compose with a web ReadableStream after the first stage", + a, + "a web ReadableStream is supported as the first stage of compose or pipeline, and in Readable.from", + ); + } + } + // Duplex.from(stage) for one stage (duplexify.js), and for a function at + // either end; functions between, an iterable first stage or a source + // function run as the pipeline's function stages (compose.js) + if (args.length === 1) return duplexFromBody(lowerer, args[0]!, loc); + const last = args.length - 1; + const isFn = (i: number): boolean => pipelineStageFunction(lowerer, args[i]!) !== null; + const pre = new Map(); + if (isFn(0)) pre.set(0, duplexFromBody(lowerer, args[0]!, loc)); + if (isFn(last)) pre.set(last, duplexFromBody(lowerer, args[last]!, loc)); + const staged = + args.some((_, i) => !pre.has(i) && isFn(i)) || + (!pre.has(0) && iterableSourceType(lowerer, args[0]!) !== null); + if (staged) { + const lowered = lowerPipelineStages(lowerer, args, loc, pre); + return lowered.wrap({ + kind: "libCall", + fn: "stream.composeStages", + args: lowered.args, + type: duplex, + loc, + }); + } let streams: IrExpr[]; try { - streams = args.map((a) => lowerStreamArg(lowerer, a, "compose")); + streams = args.map((a, i) => pre.get(i) ?? lowerStreamArg(lowerer, a, "compose")); } catch (e) { if (e instanceof StreamArgTypeThrow) return e.expr; throw e; @@ -3099,6 +4547,29 @@ function lowerStreamCompose(lowerer: Lowerer, call: ts.CallExpression, loc: SrcL /* ── the Readable operators ──────────────────────────────────────────── */ /** The Readable operators (scr_stream_ops.c — Node's operators.js). */ +/** A stream member's receiver, lowered: a value the checker types as a + * stream class whose lowering is checked-dynamic (a JavaScript binding + * that holds an untyped call's result) or a union (an element read) + * converts to that class, checked where the member runs. */ +function streamReceiverExpr(lowerer: Lowerer, node: ts.Expression): IrExpr { + const value = lowerer.lowerExpr(node); + if (value.type.kind !== "dyn" && value.type.kind !== "union") return value; + let classT: IrType | null; + try { + classT = lowerer.mapTypeOf(lowerer.typeOf(node)); + } catch { + return value; + } + if ( + classT?.kind !== "object" || + streamSidesOf(lowerer, lowerer.classes.get(classT.className)) === null + ) + return value; + return value.type.kind === "dyn" + ? { kind: "dynCheck", value, type: classT, loc: value.loc } + : lowerer.coerceToExpected(value, classT); +} + export const STREAM_OPERATORS: ReadonlySet = new Set([ "map", "filter", @@ -3113,39 +4584,40 @@ export const STREAM_OPERATORS: ReadonlySet = new Set([ "reduce", ]); -/** An operator callback as a checked-dynamic function value. Callbacks - * that declare the options argument ({ signal }) are refused: the - * AbortSignal Node passes there has no representation. map and flatMap - * callbacks must produce strings or Buffers (flatMap: arrays of them, or - * strings) — or checked-dynamic values, which the runtime checks. */ +/** An operator callback as a checked-dynamic function value, and whether + * it declares the options argument ({ signal }), which the runtime then + * passes. Its results convert to checked-dynamic values (flatMap's are + * iterated with yield*). */ function lowerOperatorCallback( lowerer: Lowerer, node: ts.Expression, member: string, maxParams: number, -): IrExpr { +): { fn: IrExpr; takesOptions: boolean; gen?: IrType & { kind: "generator" } } { const loc = locOf(node); const optionsParam = (at: ts.Node): never => lowerer.noLowering( - `${member} callbacks that declare the options argument`, + `${member} callbacks with parameters after the options argument`, at, - "the { signal } argument has no lowering — take only the chunk", + "the callback takes the chunk and { signal }", ); - if ( - (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) && - node.parameters.nodes.length > maxParams - ) { - optionsParam(node.parameters.nodes[maxParams]!); + let takesOptions = false; + if (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) { + if (node.parameters.nodes.length > maxParams + 1) + optionsParam(node.parameters.nodes[maxParams + 1]!); + takesOptions = node.parameters.nodes.length > maxParams; } const v = lowerer.lowerExpr(node); - if (v.type.kind === "dyn") return v; + // A checked-dynamic function's parameters are not known here: it gets + // the { signal } argument, as Node passes it to every callback. + if (v.type.kind === "dyn") return { fn: v, takesOptions: true }; if ( v.type.kind !== "func" && isJsSourceFile(ts.getSourceFileOfNode(node)) && lowerer.dynConvertible(v.type) ) { // JavaScript passes any value; Node's validateFunction throws. - return { kind: "dynFrom", value: v, type: DYN, loc }; + return { fn: { kind: "dynFrom", value: v, type: DYN, loc }, takesOptions: false }; } if (v.type.kind !== "func") { lowerer.noLowering( @@ -3154,25 +4626,8 @@ function lowerOperatorCallback( "pass a function", ); } - if (v.type.params.length > maxParams) optionsParam(node); - if (member === "map" || member === "flatMap") { - const ret = v.type.ret.kind === "promise" ? v.type.ret.inner : v.type.ret; - const chunk = (t: IrType): boolean => - t.kind === "string" || t.kind === "dyn" || (t.kind === "bytes" && t.elem === "u8"); - const ok = - member === "map" - ? chunk(ret) - : ret.kind === "dyn" || ret.kind === "string" || (ret.kind === "array" && chunk(ret.elem)); - if (!ok) { - lowerer.noLowering( - `${member} callbacks that return '${lowerer.fmt(ret)}'`, - node, - member === "map" - ? "map results are stream chunks: strings or Buffers (object-mode streams of other values are not lowered)" - : "flatMap results are arrays of strings or Buffers, or strings", - ); - } - } + if (v.type.params.length > maxParams + 1) optionsParam(node); + if (v.type.params.length > maxParams) takesOptions = true; const getRecord = (id: string) => lowerer.shapes.get(id); const getUnion = (id: string) => lowerer.unions.get(id); if (!canBoxFuncIntoDyn(v.type, getRecord, getUnion)) { @@ -3182,7 +4637,97 @@ function lowerOperatorCallback( "the callback's parameter and result types must cross the checked-dynamic boundary", ); } - return { kind: "dynFrom", value: v, type: DYN, loc }; + const fn: IrExpr = { kind: "dynFrom", value: v, type: DYN, loc }; + // flatMap over a compiled generator: the runtime steps it through the + // helpers over its type + if (member === "flatMap" && v.type.ret.kind === "generator") + return { fn, takesOptions, gen: v.type.ret }; + return { fn, takesOptions }; +} + +/** The operator callbacks' `{ signal }` (operators.js): map and the + * operators over it pass `{ signal: AbortSignal.any([options?.signal] + * .filter(Boolean)) }`. options is the operator's options value. */ +export function operatorSignalOptions(lowerer: Lowerer, options: IrExpr, loc: SrcLoc): IrExpr { + void lowerer; + const list: IrExpr = { + kind: "libCall", + fn: "readable.opSignalList", + args: [options], + type: DYN, + loc, + }; + const signal: IrExpr = { kind: "libCall", fn: "fetch.abortAny", args: [list], type: DYN, loc }; + return { kind: "libCall", fn: "readable.opSignalOpts", args: [signal], type: DYN, loc }; +} + +/** reduce's signal for a reducer that reads it (operators.js): `const ac + * = new AbortController()`, `options.signal.addEventListener('abort', () + * => ac.abort(), { once: true })`, then reduceSignal's ac.abort() closure + * and `{ signal: ac.signal }`. options is the bound options value. */ +export function reduceSignalSetup( + lowerer: Lowerer, + options: IrExpr, + loc: SrcLoc, + declare: (name: string, type: IrType) => IrLocal = (name, type) => + lowerer.declareHiddenLocal(name, type), +): { stmts: IrStmt[]; abort: IrExpr; cbOpts: IrExpr } { + const acLocal = declare("%opAbort", DYN); + const ac = varRef(acLocal.id, DYN, loc); + const sigLocal = declare("%opUserSignal", DYN); + const sig = varRef(sigLocal.id, DYN, loc); + const abort = pipelineAbortHelper(lowerer, ac, loc); + const stmts: IrStmt[] = [ + { + kind: "varDecl", + localId: acLocal.id, + init: { kind: "libCall", fn: "fetch.abortControllerNew", args: [], type: DYN, loc }, + loc, + }, + { + kind: "varDecl", + localId: sigLocal.id, + init: { kind: "libCall", fn: "readable.opSignalOf", args: [options], type: DYN, loc }, + loc, + }, + { + kind: "if", + cond: { kind: "dynTest", test: "truthy", value: sig, type: BOOL, loc }, + then: [ + { + kind: "exprStmt", + expr: { + kind: "dynInvoke", + recv: sig, + method: "addEventListener", + calleeName: "options.signal.addEventListener", + args: [ + { kind: "dynFrom", value: strLit("abort", loc), type: DYN, loc }, + { kind: "dynFrom", value: pipelineAbortHelper(lowerer, ac, loc), type: DYN, loc }, + { kind: "libCall", fn: "readable.opOnceOptions", args: [], type: DYN, loc }, + ], + type: DYN, + loc, + }, + loc, + }, + ], + else_: null, + loc, + }, + ]; + const signal: IrExpr = { + kind: "dynKeyGet", + value: ac, + key: strLit("signal", loc), + type: DYN, + loc, + }; + return { + stmts, + abort, + cbOpts: { kind: "libCall", fn: "readable.opSignalOpts", args: [signal], type: DYN, loc }, + }; } /** An operator's options (or reduce's initial value): an object literal @@ -3221,21 +4766,37 @@ function lowerStreamOperator( ): IrExpr { const loc = locOf(call); const args = call.arguments.nodes; - const recv = lowerer.lowerExpr(access.expression); + // JS order: the receiver, the callback, then the options; the + // callback's { signal } is built over the options value afterwards. + const decls: IrStmt[] = []; + const bind = (value: IrExpr, name: string): IrExpr => { + const local = lowerer.declareHiddenLocal(name, value.type); + decls.push({ kind: "varDecl", localId: local.id, init: value, loc }); + return varRef(local.id, value.type, loc); + }; + const recv = bind(streamReceiverExpr(lowerer, access.expression), "%opRecv"); const readable: IrType = { kind: "object", className: "%Readable" }; const opts = (i: number): IrExpr => lowerOperatorValue(lowerer, args[i], `${member} options`, loc, true); + let takesOptions = false; + let callbackGen: (IrType & { kind: "generator" }) | undefined; const fnArg = (maxParams: number): IrExpr => { if (args[0] === undefined) return dynUndefinedExpr(loc); - return lowerOperatorCallback(lowerer, args[0], member, maxParams); + const lowered = lowerOperatorCallback(lowerer, args[0], member, maxParams); + takesOptions = lowered.takesOptions; + callbackGen = lowered.gen; + return bind(lowered.fn, "%opFn"); + }; + const lib = (fn: string, a: IrExpr[], type: IrType): IrExpr => { + const call: IrExpr = { kind: "libCall", fn: fn as IrLibFn, args: a, type, loc }; + return { kind: "seqExpr", stmts: decls, result: call, type, loc }; + }; + // the options argument (bound), and the callback's { signal } when it + // declares one + const withSignal = (optsValue: IrExpr): IrExpr[] => { + const o = bind(optsValue, "%opOptions"); + return [o, takesOptions ? operatorSignalOptions(lowerer, o, loc) : dynUndefinedExpr(loc)]; }; - const lib = (fn: string, a: IrExpr[], type: IrType): IrExpr => ({ - kind: "libCall", - fn: fn as IrLibFn, - args: a, - type, - loc, - }); switch (member) { case "map": case "filter": @@ -3247,7 +4808,16 @@ function lowerStreamOperator( : member === "filter" ? "readable.opFilter" : "readable.opFlatMap"; - return lib(fnName, [recv, fn, opts(1)], readable); + const rest = withSignal(opts(1)); + const genHelpers = callbackGen ? fromGenHelpers(lowerer, callbackGen, loc) : null; + if (callbackGen && genHelpers) { + return lib( + callbackGen.async ? "readable.opFlatMapAsyncGen" : "readable.opFlatMapSyncGen", + [recv, fn, ...rest, ...genHelpers], + readable, + ); + } + return lib(fnName, [recv, fn, ...rest], readable); } case "drop": case "take": { @@ -3260,15 +4830,24 @@ function lowerStreamOperator( } case "toArray": return lib("readable.opToArray", [recv, opts(0)], { kind: "promise", inner: DYN }); - case "forEach": - return lib("readable.opForEach", [recv, fnArg(1), opts(1)], { kind: "promise", inner: VOID }); + case "forEach": { + const fn = fnArg(1); + return lib("readable.opForEach", [recv, fn, ...withSignal(opts(1))], { + kind: "promise", + inner: VOID, + }); + } case "some": case "every": { const fn = fnArg(1); - return lib(member === "some" ? "readable.opSome" : "readable.opEvery", [recv, fn, opts(1)], { - kind: "promise", - inner: BOOL, - }); + return lib( + member === "some" ? "readable.opSome" : "readable.opEvery", + [recv, fn, ...withSignal(opts(1))], + { + kind: "promise", + inner: BOOL, + }, + ); } case "find": { const t = lowerer.typeOf(call); @@ -3280,7 +4859,11 @@ function lowerStreamOperator( "the result is a checked-dynamic value — use a boolean predicate and narrow the result", ); } - return lib("readable.opFind", [recv, fnArg(1), opts(1)], { kind: "promise", inner: DYN }); + const fn = fnArg(1); + return lib("readable.opFind", [recv, fn, ...withSignal(opts(1))], { + kind: "promise", + inner: DYN, + }); } case "reduce": { const t = lowerer.typeOf(call); @@ -3307,25 +4890,24 @@ function lowerStreamOperator( } } const fn = fnArg(2); - const init = lowerOperatorValue(lowerer, args[1], "reduce's initial value", loc, false); - return lib( - "readable.opReduce", - [recv, fn, init, boolLit(args.length >= 2, loc), opts(2), numLit(kind, loc)], - { kind: "promise", inner }, + const init = bind( + lowerOperatorValue(lowerer, args[1], "reduce's initial value", loc, false), + "%opInit", ); + const o = bind(opts(2), "%opOptions"); + const head = [recv, fn, init, boolLit(args.length >= 2, loc), o, numLit(kind, loc)]; + if (!takesOptions) return lib("readable.opReduce", head, { kind: "promise", inner }); + const setup = reduceSignalSetup(lowerer, o, loc); + decls.push(...setup.stmts); + return lib("readable.opReduceSignal", [...head, setup.abort, setup.cbOpts], { + kind: "promise", + inner, + }); } } throw new InternalCompilerError(`unknown stream operator ${member}`); } -/** The literal 'buffer' encoding on write()/end(): Node 24 takes it for a - * Buffer chunk and throws ERR_UNKNOWN_ENCODING for a string chunk. */ -function isBufferEncoding(lowerer: Lowerer, arg: ts.Expression | undefined): boolean { - if (arg === undefined) return false; - const t = lowerer.typeOf(arg); - return t.isStringLiteralType() && t.value === "buffer"; -} - /** The one supported encoding argument: utf8 (Node's default), as a * compile-time literal or absent. */ function checkUtf8Encoding(lowerer: Lowerer, member: string, arg: ts.Expression | undefined): void { @@ -3373,7 +4955,7 @@ function pipeIntoStdio( ): IrExpr { const loc = locOf(call); // JS order: the receiver, then the destination, then the options. - const receiverValue = lowerer.lowerExpr(access.expression); + const receiverValue = streamReceiverExpr(lowerer, access.expression); const source = lowerer.declareHiddenLocal("%pipeSource", receiverValue.type); const stdio = lowerer.declareHiddenLocal("%pipeStdio", target.type); const options = call.arguments.nodes[1]; @@ -3495,7 +5077,7 @@ function pipeIntoDyn( ): IrExpr { const loc = locOf(call); noteUntypedStreamFlow(lowerer, null); - const receiverValue = lowerer.lowerExpr(access.expression); + const receiverValue = streamReceiverExpr(lowerer, access.expression); const source = lowerer.declareHiddenLocal("%pipeSource", receiverValue.type); const destination = lowerer.declareHiddenLocal("%pipeDestination", target.type); const stmts: IrStmt[] = [ @@ -3590,6 +5172,80 @@ function pipeIntoDyn( }; } +/** readable.compose(stage, options): compose(this, stage), with + * addAbortSignal(options.signal, composed) when the signal is set + * (operators.js). */ +function lowerReadableCompose( + lowerer: Lowerer, + call: ts.CallExpression, + access: ts.PropertyAccessExpression, +): IrExpr { + const loc = locOf(call); + const args = call.arguments.nodes; + if (args.length === 0 || args.length > 2 || args.some((a) => ts.isSpreadElement(a))) { + lowerer.noLowering( + `readable.compose with ${args.length === 0 ? "no stage" : "these arguments"}`, + call, + "the supported form is readable.compose(stage) or readable.compose(stage, { signal })", + ); + } + let signalNode: ts.Expression | null = null; + const options = args[1]; + if ( + options !== undefined && + options.kind !== ts.SyntaxKind.NullKeyword && + !(ts.isIdentifier(options) && options.text === "undefined") + ) { + if (!ts.isObjectLiteralExpression(options)) { + lowerer.noLowering( + "readable.compose options that are not an object literal", + options, + "pass { signal } as an object literal", + ); + } + for (const p of options.properties.nodes) { + const key = + (ts.isPropertyAssignment(p) || ts.isShorthandPropertyAssignment(p)) && + ts.isIdentifier(p.name) + ? p.name.text + : null; + if (key !== "signal") { + lowerer.noLowering( + key === null + ? "readable.compose options with this member" + : `the readable.compose option '${key}'`, + p, + "signal is the readable.compose option", + ); + } + const value = ts.isShorthandPropertyAssignment(p) + ? (p.name as ts.Identifier) + : (p as ts.PropertyAssignment).initializer; + if (value.kind === ts.SyntaxKind.NullKeyword) continue; + if (ts.isIdentifier(value) && value.text === "undefined") continue; + // The signal is read after compose runs, so only values whose + // evaluation has no effects. + if (!sideEffectFreeOptionValue(value) && !pureRead(value)) { + lowerer.noLowering( + "the readable.compose option 'signal' with this value", + p, + "pass a variable or property read (const signal = controller.signal)", + ); + } + signalNode = value; + } + } + const composed = lowerStreamCompose(lowerer, [access.expression, args[0]!], loc); + if (signalNode === null) return composed; + return { + kind: "libCall", + fn: "stream.addAbortSignal", + args: [composed, lowerer.lowerExprExpecting(signalNode, DYN)], + type: composed.type, + loc, + }; +} + export function lowerStreamMethodCall( lowerer: Lowerer, call: ts.CallExpression, @@ -3602,6 +5258,12 @@ export function lowerStreamMethodCall( if (opSides === "r" || opSides === "rw") return lowerStreamOperator(lowerer, call, access, member); } + if (member === "compose") { + const composeSides = streamSidesOf(lowerer, info); + return composeSides === "r" || composeSides === "rw" + ? lowerReadableCompose(lowerer, call, access) + : null; + } if (!STREAM_API_MEMBERS.has(member)) return null; const sides = streamSidesOf(lowerer, info); if (!sides) return null; @@ -3656,10 +5318,24 @@ export function lowerStreamMethodCall( if (probed?.type.kind === "dyn") return "dyn"; if (probed?.type.kind === "nullT") return "null"; } + // Any other value is a checked-dynamic chunk: one entry on an + // object-mode side, Node's chunk type error on a byte-mode one + // (undefined, which a byte-mode push ignores, included). + if (t?.kind === "void" || t?.kind === "undefinedT") return "dyn"; + if ( + t !== null && + t.kind !== "func" && + canConvertToDyn( + t, + (id) => lowerer.shapes.get(id), + (id) => lowerer.unions.get(id), + ) + ) + return "dyn"; lowerer.noLowering( `${member} with a '${t ? lowerer.fmt(t) : "?"}' chunk`, node, - "chunks are Buffers or utf8 strings — or unions of those with null (objectMode is not lowered)", + "chunks are values that convert to checked-dynamic values: Buffers, strings, numbers, records, arrays and class instances", ); }; @@ -3690,7 +5366,7 @@ export function lowerStreamMethodCall( loc, ); } - const receiver = lowerer.lowerExpr(access.expression); + const receiver = streamReceiverExpr(lowerer, access.expression); const chunk = lowerer.lowerExprExpecting(args[0]!, STRING); return { kind: "libCall", @@ -3704,13 +5380,19 @@ export function lowerStreamMethodCall( checkUtf8Encoding(lowerer, member, args[1]); const kind = chunkKind(args[0]!); if ((kind === "null" || kind === "union" || kind === "dyn") && member === "unshift") { - lowerer.noLowering( - kind === "null" ? "unshift(null)" : "unshift with a nullable or dynamic chunk", - call, - "EOF signals through push(null)", - ); + // unshift(value): an object-mode stream's value at the front, null + // the end of the stream, as Node's readableAddChunk takes them + const receiver = streamReceiverExpr(lowerer, access.expression); + const chunk = lowerer.lowerExprExpecting(args[0]!, DYN); + return { + kind: "libCall", + fn: "readable.unshiftDyn", + args: [receiver, chunk], + type: VOID, + loc, + }; } - const receiver = lowerer.lowerExpr(access.expression); + const receiver = streamReceiverExpr(lowerer, access.expression); if (kind === "null") { return { kind: "libCall", fn: "readable.pushNull", args: [receiver], type: BOOL, loc }; } @@ -3763,7 +5445,23 @@ export function lowerStreamMethodCall( if (member === "read") { requireSide(readableSide, "read"); if (args.length > 1) lowerer.noLowering(`read with ${args.length} arguments`, call); - const receiver = lowerer.lowerExpr(access.expression); + const receiver = streamReceiverExpr(lowerer, access.expression); + // JavaScript (and a result the declarations type as any) reads any + // chunk: a Buffer, a string once encoded, or an object-mode value. + const resultTs = lowerer.typeOf(call); + if ( + isJsSourceFile(ts.getSourceFileOfNode(call)) || + (resultTs.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) !== 0 + ) { + const sizeDyn = args[0] ? lowerer.lowerExprExpecting(args[0], DYN) : dynUndefinedExpr(loc); + return { + kind: "libCall", + fn: "readable.readDyn", + args: [receiver, sizeDyn], + type: DYN, + loc, + }; + } const size = args[0] ? lowerer.lowerExprExpecting(args[0], F64) : numLit(-1, loc); const type: IrType = unionOf(lowerer, [BYTES, { kind: "nullT" }]); const read: IrExpr = { @@ -3779,7 +5477,7 @@ export function lowerStreamMethodCall( if (member === "pause" || member === "resume") { requireSide(readableSide, member); if (args.length !== 0) lowerer.noLowering(`${member} with arguments`, call); - const receiver = lowerer.lowerExpr(access.expression); + const receiver = streamReceiverExpr(lowerer, access.expression); return { kind: "libCall", fn: member === "pause" ? "readable.pause" : "readable.resume", @@ -3792,7 +5490,7 @@ export function lowerStreamMethodCall( if (member === "isPaused") { requireSide(readableSide, "isPaused"); if (args.length !== 0) lowerer.noLowering(`isPaused with arguments`, call); - const receiver = lowerer.lowerExpr(access.expression); + const receiver = streamReceiverExpr(lowerer, access.expression); return { kind: "libCall", fn: "readable.isPaused", args: [receiver], type: BOOL, loc }; } @@ -3805,10 +5503,11 @@ export function lowerStreamMethodCall( "the supported forms are (destination) and (destination, { end })", ); } - // A Hash or Hmac destination pipes into its Transform, and pipe() - // answers the Hash itself (the receiver evaluates first, as in JS). - if (isHashValueType(lowerer.mapTypeOf(lowerer.typeOf(args[0]!)))) { - const receiverValue = lowerer.lowerExpr(access.expression); + // A Hash, Hmac, Cipheriv or Decipheriv destination pipes into its + // Transform, and pipe() answers the value itself (the receiver + // evaluates first, as in JS). + if (isValueStream(lowerer, args[0]!)) { + const receiverValue = streamReceiverExpr(lowerer, access.expression); const source = lowerer.declareHiddenLocal("%pipeSource", receiverValue.type); const hashValue = lowerer.lowerExpr(args[0]!); const hash = lowerer.declareHiddenLocal("%pipeHash", hashValue.type); @@ -3825,7 +5524,10 @@ export function lowerStreamMethodCall( fn: "readable.pipe", args: [ { kind: "varRef", localId: source.id, type: receiverValue.type, loc }, - hashStreamOf({ kind: "varRef", localId: hash.id, type: hashValue.type, loc }, true), + valueStreamOf( + { kind: "varRef", localId: hash.id, type: hashValue.type, loc }, + true, + ), end, ], type: { kind: "object", className: "%Transform" }, @@ -3855,7 +5557,7 @@ export function lowerStreamMethodCall( ); } const end = pipeEndOption(lowerer, args[1], loc); - const receiver = lowerer.lowerExpr(access.expression); + const receiver = streamReceiverExpr(lowerer, access.expression); return { kind: "libCall", fn: generalPipe(lowerer, dst.type), @@ -3868,7 +5570,7 @@ export function lowerStreamMethodCall( if (member === "unpipe") { requireSide(readableSide, "unpipe"); if (args.length > 1) lowerer.noLowering(`unpipe with ${args.length} arguments`, call); - const receiver = lowerer.lowerExpr(access.expression); + const receiver = streamReceiverExpr(lowerer, access.expression); if (args[0] !== undefined) { const dst = lowerer.lowerExpr(args[0]); if (dst.type.kind === "dyn") return unpipeDyn(lowerer, receiver, dst, loc); @@ -3929,7 +5631,7 @@ export function lowerStreamMethodCall( if (member === "destroy") { if (args.length > 1) lowerer.noLowering(`destroy with ${args.length} arguments`, call); - const receiver = lowerer.lowerExpr(access.expression); + const receiver = streamReceiverExpr(lowerer, access.expression); if (args[0] !== undefined) { const err = lowerer.lowerExpr(args[0]); const rootsAtError = (t: IrType): boolean => { @@ -3964,10 +5666,55 @@ export function lowerStreamMethodCall( } const kind = chunkKind(args[0]!); if (kind === "null") lowerer.noLowering("write(null)", call, "end() finishes a writable"); + const lowerWriteCb = (cbArg: ts.Expression): IrExpr => { + 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, + "() => void callbacks are supported (listen for 'error' to observe failures)", + ); + } + return cb!; + }; + // write(chunk, encoding[, cb]), and write(value, cb): the encoding + // argument reaches an object-mode side's _write as passed, null when + // the callback took its place (a byte-mode side encodes a string + // chunk with it). + const writeEnc = (encArg: ts.Expression | undefined, cbArg: ts.Expression | undefined) => { + const receiver = streamReceiverExpr(lowerer, access.expression); + const chunk = lowerer.lowerExprExpecting(args[0]!, DYN); + const tail: IrExpr[] = []; + if (encArg !== undefined) tail.push(lowerer.lowerExprExpecting(encArg, DYN)); + if (cbArg !== undefined) tail.push(lowerWriteCb(cbArg)); + const flags = (encArg !== undefined ? 1 : 0) | (cbArg !== undefined ? 2 : 0); + return { + kind: "libCall", + fn: "writable.writeEnc", + args: [receiver, numLit(flags, loc), chunk, ...tail], + type: BOOL, + loc, + } satisfies IrExpr; + }; if (kind === "dyn") { - if (args.length > 1) - lowerer.noLowering("write with a dynamic chunk and more arguments", call); - const receiver = lowerer.lowerExpr(access.expression); + if (args.length === 3) return writeEnc(args[1], args[2]); + if (args.length === 2) { + // Node's write takes a function there as the callback, anything + // else as the encoding + const t = lowerer.mapTypeOf(lowerer.typeOf(args[1]!)); + if (t?.kind === "func") return writeEnc(undefined, args[1]); + if (t === null || t === undefined || t.kind === "dyn") { + lowerer.noLowering( + "write with a dynamic second argument", + args[1]!, + "pass an encoding string or a completion callback", + ); + } + return writeEnc(args[1], undefined); + } + const receiver = streamReceiverExpr(lowerer, access.expression); const chunk = lowerer.lowerExprExpecting(args[0]!, DYN); return { kind: "libCall", fn: "writable.writeDyn", args: [receiver, chunk], type: BOOL, loc }; } @@ -3977,7 +5724,7 @@ export function lowerStreamMethodCall( // lowered value may have collapsed to one arm (checker narrowing) — // re-dispatch on its IR type. if (args.length > 1) lowerer.noLowering("write with a union chunk and more arguments", call); - const receiver = lowerer.lowerExpr(access.expression); + const receiver = streamReceiverExpr(lowerer, access.expression); const chunk = lowerer.lowerExpr(args[0]!); const fn = chunk.type.kind === "union" @@ -3990,37 +5737,24 @@ export function lowerStreamMethodCall( return { kind: "libCall", fn, args: [receiver, chunk], type: BOOL, loc }; } // Disambiguate (chunk, cb?) vs (chunk, encoding, cb?) by the second - // argument's static type. + // argument's static type. A write with an encoding runs through + // writeEnc, whose runtime checks and applies it as Node's _write does. let cbArg: ts.Expression | undefined; - if (args.length >= 2 && isBufferEncoding(lowerer, args[1])) { - if (kind !== "bytes") - return nodeThrowExpr(1, "ERR_UNKNOWN_ENCODING", "Unknown encoding: buffer", BOOL, loc); - cbArg = args[2]; - } else if (args.length === 2) { + if (args.length === 3) return writeEnc(args[1], args[2]); + if (args.length === 2) { const t = lowerer.mapTypeOf(lowerer.typeOf(args[1]!)); - if (t?.kind === "string") checkUtf8Encoding(lowerer, "write", args[1]); - else cbArg = args[1]; - } else if (args.length === 3) { - checkUtf8Encoding(lowerer, "write", args[1]); - cbArg = args[2]; + if (t?.kind === "string" || t?.kind === "nullT" || t?.kind === "undefinedT") + return writeEnc(args[1], undefined); + cbArg = args[1]; } - const receiver = lowerer.lowerExpr(access.expression); + const receiver = streamReceiverExpr(lowerer, access.expression); const chunk = kind === "bytes" ? lowerer.lowerExprExpecting(args[0]!, BYTES) : lowerer.lowerExprExpecting(args[0]!, STRING); const fn = kind === "bytes" ? "writable.write" : "writable.writeStr"; if (cbArg !== undefined) { - 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, - "() => void callbacks are supported (listen for 'error' to observe failures)", - ); - } + const cb = lowerWriteCb(cbArg); return { kind: "libCall", fn, args: [receiver, chunk, cb], type: BOOL, loc }; } return { kind: "libCall", fn, args: [receiver, chunk], type: BOOL, loc }; @@ -4032,34 +5766,29 @@ export function lowerStreamMethodCall( // Forms: (), (cb), (chunk), (chunk, cb), (chunk, encoding, cb). let chunkNode: ts.Expression | undefined; let cbArg: ts.Expression | undefined; + let encNode: ts.Expression | undefined; if (args.length === 1) { const t = lowerer.mapTypeOf(lowerer.typeOf(args[0]!)); if (t?.kind === "func") cbArg = args[0]; else chunkNode = args[0]; - } else if (args.length >= 2 && isBufferEncoding(lowerer, args[1])) { - chunkNode = args[0]; - const endKind = chunkKind(args[0]!); - if (endKind === "string") { - const endT = lowerer.mapTypeOf(lowerer.typeOf(call)) ?? DYN; - return nodeThrowExpr(1, "ERR_UNKNOWN_ENCODING", "Unknown encoding: buffer", endT, loc); - } - if (endKind !== "bytes") checkUtf8Encoding(lowerer, "end", args[1]); - cbArg = args[2]; } else if (args.length === 2) { chunkNode = args[0]; const t = lowerer.mapTypeOf(lowerer.typeOf(args[1]!)); - if (t?.kind === "string") checkUtf8Encoding(lowerer, "end", args[1]); + if (t?.kind === "string" || t?.kind === "nullT" || t?.kind === "undefinedT") + encNode = args[1]; else cbArg = args[1]; } else if (args.length === 3) { chunkNode = args[0]; - checkUtf8Encoding(lowerer, "end", args[1]); + encNode = args[1]; cbArg = args[2]; } - const receiver = lowerer.lowerExpr(access.expression); + const receiver = streamReceiverExpr(lowerer, access.expression); let flags = 0; const tail: IrExpr[] = []; if (chunkNode !== undefined) { - const kind = chunkKind(chunkNode); + // end(chunk, encoding[, cb]) writes the chunk with the encoding + // argument as passed (flags 16), through the dyn write + const kind = encNode !== undefined ? "dyn" : chunkKind(chunkNode); if (kind === "null" || kind === "union") lowerer.noLowering("end(null)", call); flags |= kind === "bytes" ? 1 : kind === "dyn" ? 8 : 2; tail.push( @@ -4069,6 +5798,10 @@ export function lowerStreamMethodCall( ? lowerer.lowerExprExpecting(chunkNode, DYN) : lowerer.lowerExprExpecting(chunkNode, STRING), ); + if (encNode !== undefined) { + flags |= 16; + tail.push(lowerer.lowerExprExpecting(encNode, DYN)); + } } if (cbArg !== undefined) { const cb = callbackDeclaresParameters(cbArg) @@ -4096,7 +5829,7 @@ export function lowerStreamMethodCall( if (member === "cork" || member === "uncork") { requireSide(writableSide, member); if (args.length !== 0) lowerer.noLowering(`${member} with arguments`, call); - const receiver = lowerer.lowerExpr(access.expression); + const receiver = streamReceiverExpr(lowerer, access.expression); return { kind: "libCall", fn: member === "cork" ? "writable.cork" : "writable.uncork", @@ -4116,7 +5849,7 @@ export function lowerStreamMethodCall( ); } const enc = bufEncoding(lowerer, "setEncoding", args[0]!); - const receiver = lowerer.lowerExpr(access.expression); + const receiver = streamReceiverExpr(lowerer, access.expression); return { kind: "libCall", fn: "readable.setEncoding", @@ -4127,18 +5860,20 @@ export function lowerStreamMethodCall( } if (member === "setDefaultEncoding") { - // The write-side default: utf8 IS the default — admit it; other - // encodings would change what write(string) means. + // The write-side default: lowercased and validated (ERR_UNKNOWN_ENCODING, + // thrown) at run time; answers the stream. requireSide(writableSide, "setDefaultEncoding"); - const t = args[0] ? lowerer.typeOf(args[0]) : null; - if (t?.isStringLiteralType() && (t.value === "utf8" || t.value === "utf-8")) { - return lowerer.lowerExpr(access.expression); - } - lowerer.noLowering( - "setDefaultEncoding", - call, - "utf8 (the default, as a compile-time literal) is the supported write-side string encoding", - ); + if (args.length > 1) + lowerer.noLowering(`setDefaultEncoding with ${args.length} arguments`, call); + const receiver = streamReceiverExpr(lowerer, access.expression); + const enc = args[0] ? lowerer.lowerExprExpecting(args[0], DYN) : dynUndefinedExpr(loc); + return { + kind: "libCall", + fn: "writable.setDefaultEncoding", + args: [receiver, enc], + type: receiver.type, + loc, + }; } return null; @@ -4283,7 +6018,7 @@ export function lowerStreamProperty( const propCall = (type: IrType): IrExpr => ({ kind: "libCall", fn: "stream.prop", - args: [lowerer.lowerExpr(expr.expression), strLit(name, loc)], + args: [streamReceiverExpr(lowerer, expr.expression), strLit(name, loc)], type, loc, }); @@ -4306,7 +6041,7 @@ export function lowerStreamProperty( const read: IrExpr = { kind: "libCall", fn: "readable.flowing", - args: [lowerer.lowerExpr(expr.expression)], + args: [streamReceiverExpr(lowerer, expr.expression)], type, loc, }; @@ -4320,7 +6055,7 @@ export function lowerStreamProperty( const read: IrExpr = { kind: "libCall", fn: "stream.errored", - args: [lowerer.lowerExpr(expr.expression)], + args: [streamReceiverExpr(lowerer, expr.expression)], type, loc, }; @@ -4331,8 +6066,7 @@ export function lowerStreamProperty( return propCall(BOOL); } if (name === "writableObjectMode" && writableSide) { - // objectMode construction fences, so the answer is compile-time false. - return boolLit(false, loc); + return propCall(BOOL); } if (name === "allowHalfOpen" && sides === "rw") { return propCall(BOOL); diff --git a/packages/compiler/src/frontend/lowering/lower-timers.ts b/packages/compiler/src/frontend/lowering/lower-timers.ts index 7d4bba34b..03c9c5c1f 100644 --- a/packages/compiler/src/frontend/lowering/lower-timers.ts +++ b/packages/compiler/src/frontend/lowering/lower-timers.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "./stable-names.js"; import { dynUndefinedExpr, numLit, varRef } from "../../ir/build.js"; import * as ts from "../ts7/adapter.js"; import { isJsSourceFile } from "../program.js"; @@ -55,7 +56,7 @@ export function adaptZeroArgTimerCallback( const toT: IrType = { kind: "func", params: [], ret: VOID }; const key = `timer.dropret:${typeKey(fromT)}`; const existing = lowerer.arrHofHelpers.get(key); - const name = existing ?? `%timer.dropret.${lowerer.arrHofHelpers.size}`; + const name = existing ?? keyedHelperName(lowerer, "%timer.dropret", key); if (!existing) { lowerer.arrHofHelpers.set(key, name); lowerer.liftedFns.push( @@ -117,7 +118,7 @@ export function adaptZeroArgTimerCallback( const toT: IrType = { kind: "func", params: [], ret: VOID }; const key = `timer.droparg:${typeKey(fromT)}`; const existing = lowerer.arrHofHelpers.get(key); - const name = existing ?? `%timer.droparg.${lowerer.arrHofHelpers.size}`; + const name = existing ?? keyedHelperName(lowerer, "%timer.droparg", key); if (!existing) { lowerer.arrHofHelpers.set(key, name); lowerer.liftedFns.push( @@ -203,7 +204,7 @@ function makeTimerArgsThunk( const toT: IrType = { kind: "func", params: [], ret: VOID }; const key = `timer.argsthunk:${n}`; const existing = lowerer.arrHofHelpers.get(key); - const name = existing ?? `%timer.argsthunk.${lowerer.arrHofHelpers.size}`; + const name = existing ?? keyedHelperName(lowerer, "%timer.argsthunk", key); if (!existing) { lowerer.arrHofHelpers.set(key, name); const impl = `${name}.impl`; diff --git a/packages/compiler/src/frontend/lowering/lowerer.test.ts b/packages/compiler/src/frontend/lowering/lowerer.test.ts index bacdc7941..7fbb9661f 100644 --- a/packages/compiler/src/frontend/lowering/lowerer.test.ts +++ b/packages/compiler/src/frontend/lowering/lowerer.test.ts @@ -10,6 +10,7 @@ import { } from "../../ir/ir.js"; import type { Node, Program, SourceFile, Symbol, Type } from "../ts7/adapter.js"; import { Lowerer } from "./lowerer.js"; +import { UnionRegistry } from "../type-mapper.js"; import { classMethodValue } from "./class-method-values.js"; const loc = { file: "island.ts", start: 0, end: 1 }; @@ -32,7 +33,7 @@ test("reuses complete copy routes without repeating discriminator planning", () expect(plan).not.toHaveBeenCalled(); expect(lowerer.liftedFns.filter((fn) => fn.name === helper)).toHaveLength(1); const recursive = {} as Type; - lowerer.shapes.recursiveRef(recursive); + lowerer.shapes.recursiveRef(recursive, () => "Recursive"); lowerer.shapes.finalizeRecursive(recursive, [{ name: "kind", type: STRING }]); expect(lowerer.unionRetagHelper(from, to, loc)).toBe(helper); expect(plan).toHaveBeenCalled(); @@ -54,7 +55,7 @@ test("replans after a recursive union gains its final arms", () => { const lowerer = context(); const recursive = {} as Type; const from = lowerer.unions.intern([UNDEFINED_T, NULL_T]); - const to = lowerer.unions.recursiveRef(recursive); + const to = lowerer.unions.recursiveRef(recursive, () => "Recursive"); const trapped = lowerer.unionRetagHelper(from, to, loc); expect(trapped).not.toBeNull(); lowerer.unions.finalizeRecursive(recursive, [UNDEFINED_T]); @@ -75,7 +76,7 @@ test("rechecks width conversions after recursive record definitions settle", () const lowerer = context(); const recursive = {} as Type; const source = record(lowerer.shapes.intern([{ name: "value", type: F64 }])); - const target = record(lowerer.shapes.recursiveRef(recursive)); + const target = record(lowerer.shapes.recursiveRef(recursive, () => "Recursive")); const from = lowerer.unions.intern([source, UNDEFINED_T]); const to = lowerer.unions.intern([target, NULL_T]); expect(lowerer.unionRetagHelper(from, to, loc)).not.toBeNull(); @@ -129,7 +130,7 @@ test("literal ownership is reused across values and rechecked when recursive rec expect(inspect).not.toHaveBeenCalled(); const recursive = {} as Type; - const pendingShape = record(lowerer.shapes.recursiveRef(recursive)); + const pendingShape = record(lowerer.shapes.recursiveRef(recursive, () => "Recursive")); const pending = lowerer.unions.intern([pendingShape], { field: "kind", cases: [{ tag: 0, values: ["a"] }], @@ -143,7 +144,7 @@ test("literal ownership is reused across values and rechecked when recursive rec test("literal ownership sees a recursive union's finalized discriminator", () => { const lowerer = context(); const recursive = {} as Type; - const union = lowerer.unions.recursiveRef(recursive); + const union = lowerer.unions.recursiveRef(recursive, () => "Recursive"); const shape = record(lowerer.shapes.intern([{ name: "kind", type: STRING }])); expect(lowerer.literalUnionArm(union, ["ready"])).toBeNull(); lowerer.unions.finalizeRecursive(recursive, [shape], { @@ -182,7 +183,10 @@ test("removing undefined reuses the discriminator transformation without hiding ); const recursive = {} as Type; - const pending: IrType = { kind: "union", unionId: lowerer.unions.recursiveRef(recursive) }; + const pending: IrType = { + kind: "union", + unionId: lowerer.unions.recursiveRef(recursive, () => "Recursive"), + }; expect(lowerer.stripUndefinedArm(pending)).toEqual(pending); lowerer.unions.finalizeRecursive(recursive, [STRING, UNDEFINED_T]); expect(lowerer.stripUndefinedArm(pending)).toEqual(STRING); @@ -215,7 +219,10 @@ test("adding undefined reuses semantic union transformations and sees recursive expect(lowerer.unions.get(added.unionId)?.discriminant).toEqual(discriminant); const recursive = {} as Type; - const pending: IrType = { kind: "union", unionId: lowerer.unions.recursiveRef(recursive) }; + const pending: IrType = { + kind: "union", + unionId: lowerer.unions.recursiveRef(recursive, () => "Recursive"), + }; const before = lowerer.withUndefinedArmOf(pending); lowerer.unions.finalizeRecursive(recursive, [a, b], discriminant); expect(lowerer.withUndefinedArmOf(pending)).toEqual(added); @@ -227,13 +234,18 @@ test("adding undefined reuses semantic union transformations and sees recursive test("optional union widening keeps refused and missing contracts current", () => { const lowerer = context(); const recursive = {} as Type; - const pending: IrType = { kind: "union", unionId: lowerer.unions.recursiveRef(recursive) }; + const pending: IrType = { + kind: "union", + unionId: lowerer.unions.recursiveRef(recursive, () => "Recursive"), + }; expect(lowerer.withUndefinedArmOf(pending)).not.toBeNull(); lowerer.unions.finalizeRecursive(recursive, [{ kind: "date" }, STRING]); expect(lowerer.withUndefinedArmOf(pending)).toBeNull(); expect(lowerer.withUndefinedArmOf(pending)).toBeNull(); - const missing: IrType = { kind: "union", unionId: `u${lowerer.unions.unions.length}` }; + // Union ids come from their arms, so a fresh registry names the union + // this one has not interned yet. + const missing: IrType = { kind: "union", unionId: new UnionRegistry().intern([F64, STRING]) }; expect(lowerer.withUndefinedArmOf(missing)).toBeNull(); expect(lowerer.unions.intern([F64, STRING])).toBe(missing.unionId); expect(lowerer.withUndefinedArmOf(missing)?.kind).toBe("union"); diff --git a/packages/compiler/src/frontend/lowering/lowerer.ts b/packages/compiler/src/frontend/lowering/lowerer.ts index ee8ba7ecb..3ba81dd6b 100644 --- a/packages/compiler/src/frontend/lowering/lowerer.ts +++ b/packages/compiler/src/frontend/lowering/lowerer.ts @@ -1,4 +1,6 @@ import { relieveHeapPressure } from "../../heap-pressure.js"; +import { keyedHelperName } from "./stable-names.js"; +import { positionTag, StructuralPositions } from "./structural-positions.js"; import { onlyForwarded, stripTypeWrappers } from "./typed-arguments.js"; import { needsGeneralNodeStreams, @@ -59,11 +61,13 @@ import { encodeBase64 } from "../../wasm/base64.js"; import { resolveRequireRuntime } from "../runtime-resolve.js"; import { lowerKeyObjectCall } from "./builtins/key-object.js"; import { isEcdhType, lowerEcdhCall } from "./builtins/ecdh.js"; +import { isDiffieHellmanType, lowerDiffieHellmanCall } from "./builtins/dh.js"; import { fenceWebCryptoMember, lowerWebCryptoCall } from "./builtins/webcrypto.js"; -import { hashStreamOf } from "./builtins/hash-stream.js"; +import { valueStreamOf } from "./builtins/hash-stream.js"; import { lowerNetAddressCall, lowerNetAddressNew } from "./builtins/net-address.js"; import { dynUndefinedExpr, nodeThrowExpr, numLit, varRef } from "../../ir/build.js"; import { iteratorSlotAdapter } from "./iterator-adapters.js"; +import { iterableSlotValue } from "./iterable-values.js"; import type { FieldLift } from "./coercions/structural-plans.js"; import { lowerBuiltinCall } from "./builtin-calls.js"; import { CoercionState } from "./coercions/state.js"; @@ -178,7 +182,7 @@ export { newFnCtx, type FnCtx } from "./function-context.js"; * - Lexical scoping is resolved here: locals get function-unique ids * ("x.0", "x.1" for shadowing); the IR is scope-flat. */ -import { dirname, resolve } from "node:path"; +import { dirname, relative, resolve } from "node:path"; import { bindingSource } from "../binding-source.js"; import { tsgoPath } from "../dts-paths.js"; import * as ts from "../ts7/adapter.js"; @@ -227,6 +231,7 @@ import { arrayOf, BOOL, canAdaptDynFuncTo, + canBoxFuncIntoDyn, canDynCheckTo, canConvertToDyn, DYN, @@ -442,6 +447,7 @@ import { lowerNestedFunctionDecl, lowerLambda, lowerFunction, + blockedBodyDiagnostics, } from "./lower-functions.js"; import { lowerArrayMethodCall } from "./containers/array-methods.js"; import { type ArrayHofInfo, fuseArrayPipelines } from "./containers/array-pipelines.js"; @@ -497,7 +503,8 @@ import { lowerTracingChannelProperty, } from "./builtins/async-context.js"; import { lowerDisposableStackNew } from "./builtins/disposable-stack.js"; -import { lowerErrorCodeProperty } from "./builtins/errors.js"; +import { lowerErrorCodeProperty, lowerErrorFunctionCall } from "./builtins/errors.js"; +import { noteDateClassMethods } from "./builtins/date-classes.js"; import { lowerProcessProperty, lowerProcessMethodCall, @@ -1004,6 +1011,11 @@ function lowerShuffle(): ((wave: string[]) => void) | null { * the bodies reachable emit did NOT mark (plus deferred collection * diagnostics nothing flushed), reported separately: whole-program analysis without * letting unreached code fail builds. */ +/** The closure root of an emit-override specialization body. */ +function emitSpecRoot(spec: EmitSpecRequest): string { + return `%emit.${spec.info.def.name}.${spec.event}.${spec.ordinal}`; +} + export function lowerToIr( program: ts.Program, entry: ts.SourceFile, @@ -1338,6 +1350,7 @@ export function lowerToIr( // travel with them: a failed statement is never left unexplained. const covered: LowerResult = { ...result, + diagnostics: [...result.diagnostics, ...remainder.reachedBlockedBodyDiagnostics], stats: { ...result.stats, statementsDynamic }, unreached: { diagnostics: rem.diagnostics, @@ -1906,6 +1919,12 @@ export class Lowerer { * pinned values resolve through genericFnOf exactly like top-level * generic function declarations (bindingGenericFnInfoOf). */ readonly bindingGenericFns = new Map(); + /** Identifiers by spelling, per file, for the generic bindings' use + * ordering (runsAfterDeclaration). */ + readonly bindingIdentifiers = new Map>(); + /** Per JavaScript file, the declarations of the bindings it assigns an + * own `toString` (jsAssignsOwnToString in lower-calls.ts). */ + readonly ownToStringTargets = new Map>(); /** Per-symbol result of the never-reassigned file scan * (bindingNeverReassigned — object-literal generic-method receivers). */ readonly neverReassignedCache = new Map(); @@ -2171,6 +2190,12 @@ export class Lowerer { /** Instance types (by checker type id) of the local classes generic * factory calls return, and the per-instance class each names. */ readonly localClassInstanceTypes = new Map(); + /** A generic factory's instantiated result type → the class value of the + * local class it returns (TypeMapperCtx.localClassValue). */ + readonly localClassValueTypes = new Map(); + /** While a generic factory instance lowers: its declared result type → the + * class value of the local class it returns. */ + instanceResultClass: { declared: number; value: IrType } | null = null; /** The ts-level twin of typeParamBindings, non-null while a CALL-keyed * instance body lowers: type-parameter symbol → the bound CHECKER type, * consulted where the mapped IrType has already widened away information @@ -2801,6 +2826,8 @@ export class Lowerer { /** Generated value helpers, keyed by operation and type. Callers own * their key prefixes; this includes more than structural conversions. */ readonly valueHelpers = new Map(); + /** Each name keyedHelperName made, with a second hash of its key. */ + readonly keyedNameKeys = new Map(); /** structuralNarrowing's assignable classes, keyed by static and * narrowed class name. */ readonly structuralClassPeers = new Map(); @@ -2937,13 +2964,16 @@ export class Lowerer { ctx: FnCtx; } >(); - chainCounter = 0; /** Keyed by program-wide qualified class name (what IR object types carry). */ readonly classes = new Map(); readonly classBySymbol = new Map(); /** Named method slots observed before class collection need a callable * ABI and shared prototype descriptors instead of call-site specialization. */ readonly prototypeMethodAccesses = new Map(); + /** Whether the program reads `Error.prototype`, the checked-dynamic + * object an ES5 constructor function can inherit from: only then can a + * value that is not an Error instance be `instanceof Error`. */ + errorPrototypeValues = false; /** Well-known symbol methods (`sym:iterator`) the program may replace * through a symbol-keyed write: an instance or prototype property, or a * reflection call. */ @@ -3022,10 +3052,10 @@ export class Lowerer { /** Inline Promise.then parameters whose contextual type is a builtin * module namespace anonymous object. The settled native token is the * ABI truth even when the checker type has no stable module symbol. */ - /** Receivers of a stream call on a Hash or Hmac (lowerHashStreamCall): - * for the duration of that call, the receiver lowers to the Transform of - * the value held in the named local. */ - readonly hashStreamReceivers = new Map(); + /** Receivers of a stream call on a Hash, Hmac, Cipheriv or Decipheriv + * (lowerHashStreamCall): for the duration of that call, the receiver + * lowers to the Transform of the value held in the named local. */ + readonly valueStreamReceivers = new Map(); /** fs call arguments evaluated ahead of a URL path's conversion * (builtins/fs-paths.ts): each lowers to the hidden local that holds its * value, which is null until the path's lowering has saved it. */ @@ -3167,7 +3197,55 @@ export class Lowerer { * dispatch revision needs no weak-key identity or process-global state. */ errorMethodDispatchRevision: string | null = null; errorPropertyDispatchRevision: string | null = null; - lambdaCounter = 0; + /** Structural source positions (structural-positions.ts) for names that + * stay the same when unrelated code moves. */ + /** Files are named by their path relative to the entry's directory, so + * names do not depend on where the program sits, and default library + * files by their base name: two checkers install them in different + * directories. */ + readonly positions = new StructuralPositions((sf) => + this.program.isSourceFileDefaultLibrary(sf) + ? `lib:${sf.fileName.slice(sf.fileName.lastIndexOf("/") + 1)}` + : relative(dirname(this.entry.fileName), sf.fileName), + ); + + /** The outermost node whose token span is exactly `loc`, or null. */ + nodeAtLoc(loc: SrcLoc): ts.Node | null { + const sf = this.program.getSourceFile(loc.file); + return sf === undefined ? null : (ts.nodeAtSpan(sf, loc.start, loc.end) ?? null); + } + + /** The lowering unit whose name scopes the closures it lifts. */ + private closureRoot = "%pre"; + private readonly closureNameCounts = new Map(); + + /** Runs `fn` with the closures it lifts named under `root`. */ + withClosureRoot(root: string, fn: () => T): T { + const previous = this.closureRoot; + this.closureRoot = root; + try { + return fn(); + } finally { + this.closureRoot = previous; + } + } + + /** The name of a closure (or wrapper) lifted for the source at `loc`: + * `.` of the current lowering unit, the location and + * `suffix`, then `suffix`. A unit that lifts several functions for the same + * location and suffix numbers them in the order it lifts them, so a + * closure's name depends only on its unit, not on which units lowered + * before it. */ + closureName(loc: SrcLoc, suffix = "", prefix = "%fn"): string { + const node = this.nodeAtLoc(loc); + const where = node === null ? `${loc.file}:${loc.start}:${loc.end}` : this.positions.of(node); + const key = `${prefix}|${this.closureRoot}|${where}|${suffix}`; + const first = keyedHelperName(this, prefix, key); + const seen = this.closureNameCounts.get(first) ?? 0; + this.closureNameCounts.set(first, seen + 1); + return (seen === 0 ? first : keyedHelperName(this, prefix, `${key}|${seen}`)) + suffix; + } + readonly preparedClassFactories = new Map(); readonly preparingClassFactories = new Set(); @@ -3235,6 +3313,9 @@ export class Lowerer { * the class and constructed-class counts, it tells caches over the class * graph when the graph changed. */ subclassLinks = 0; + /** Function-local classes by the class node they extend, built on first + * use (localSubclassesOf in lower-classes.ts). */ + localSubclassIndex: Map | null = null; /** Set while a subclass constructor's super() call notes its base * constructor edge: that edge does not instantiate the base exactly. */ private superConstructorEdge = false; @@ -3520,6 +3601,7 @@ export class Lowerer { this.checker = program.getTypeChecker(); this.typeCtx = { checker: this.checker, + positionOf: (node) => this.positions.of(node), shapes: this.shapes, unions: this.unions, classNamer: this.classNamer, @@ -3529,6 +3611,10 @@ export class Lowerer { genericClassInstance: (decl, ref, mapArgument) => this.genericClassInstanceType(decl, ref, mapArgument), runtimeClassValue: (type) => runtimeClassValueOfType(this, type), + localClassValue: (type) => + this.instanceResultClass !== null && this.instanceResultClass.declared === type.id + ? this.instanceResultClass.value + : (this.localClassValueTypes.get(type.id) ?? null), mixinClassInstance: (decl) => this.mixinTypeContext && this.mixinTypeContext.classNode === decl ? { kind: "object", className: this.mixinTypeContext.className } @@ -3670,9 +3756,9 @@ export class Lowerer { * is `unknown` or `object` (also with `null` or `undefined`, or an array * of those), names checked protocol identity, is an owned runtime * handle (a Worker or MessagePort, a fetch Headers/Request/Response, or - * a node:crypto ECDH), or is a WeakMap/WeakSet (native weak collections - * live in checked-dynamic storage, as locals of those types do); `any` - * fields stay refused. */ + * a node:crypto ECDH, DiffieHellman or DiffieHellmanGroup), or is a + * WeakMap/WeakSet (native weak collections live in checked-dynamic + * storage, as locals of those types do); `any` fields stay refused. */ classFieldStoresDyn(type: ts.Type): boolean { return ( this.opaqueValueType(type) || @@ -3680,7 +3766,10 @@ export class Lowerer { isWorkerHandleType(type, this.typeCtx) || isFetchHandleType(type, this.typeCtx) || this.weakCollectionType(type) || - this.stdlibHandleType(type, (part) => isEcdhType(this, part)) + this.stdlibHandleType( + type, + (part) => isEcdhType(this, part) || isDiffieHellmanType(this, part), + ) ); } @@ -3808,11 +3897,11 @@ export class Lowerer { })() ? this.qualify( ts.getSourceFileOfNode(decl), - `%cx${ts.tokenStartOfNode(decl)}.${decl.name?.text ?? ""}`, + `%cx${positionTag(this, decl)}.${decl.name?.text ?? ""}`, ) : this.qualify( ts.getSourceFileOfNode(decl), - nsPathPrefix(decl) + (decl.name ? decl.name.text : "%anon"), + nsPathPrefix(this, decl) + (decl.name ? decl.name.text : "%anon"), ); for (let index = this.localClassInstantiations.length - 1; index >= 0; index--) { const entry = this.localClassInstantiations[index]!; @@ -6542,7 +6631,10 @@ export class Lowerer { node.expression.name.text, node.arguments.nodes.length >= 2, ); - const callback = node.arguments.nodes[0]; + // `xs.map(((x) => x))`: the parenthesized callback is the arrow. + let callback = node.arguments.nodes[0]; + while (callback !== undefined && ts.isParenthesizedExpression(callback)) + callback = callback.expression; if (callbackIndices !== null && callback !== undefined && !ts.isSpreadElement(callback)) { const receiverNode = node.expression.expression; const receiverTs = this.typeOf(receiverNode); @@ -6601,13 +6693,26 @@ export class Lowerer { presentSites.set(node, elementsPresent && !reduce); if (elementsPresent && reduce && retypeInlineCallback(callback, callbackIndices)) changed = true; - if ( - (method === "reduce" || method === "reduceRight") && - ((!elementsPresent && node.arguments.nodes.length < 2) || - callbackReturnsOptional(callback)) - ) { - if (promoteHofCallback(callback, [0, 1])) changed = true; - const result = this.runtimeOptionalType(this.irTypeOf(node)); + // The accumulator holds undefined when the callback can return + // it, when an initial value can be missing, or when elements can + // be absent and there is no initial value. It holds another + // primitive when the callback's result can be one at run time + // (`missing[0] ?? "fallback"`). + const initial = node.arguments.nodes[1]; + const optional = + (!elementsPresent && initial === undefined) || + (initial !== undefined && !ts.isSpreadElement(initial) && mayBeOptional(initial)) || + callbackReturnsOptional(callback); + const arithmetic = + reduce && (ts.isArrowFunction(callback) || ts.isFunctionExpression(callback)) + ? lambdaArithmeticReturn(callback) + : null; + if (reduce && (optional || arithmetic !== null)) { + if (optional && promoteHofCallback(callback, [0, 1])) changed = true; + let result = this.irTypeOf(node); + if (arithmetic !== null) + result = joinPrimitiveTypes([result, arithmetic]) ?? result; + if (optional) result = this.runtimeOptionalType(result); siteDependencies?.read(node); const previous = this.runtimeOptionalReduceTypes.get(node); if (!previous || !typeEquals(previous, result)) { @@ -7367,11 +7472,17 @@ export class Lowerer { if (sig && !this.wantBody(sig.name)) continue; const fn = this.lowerFunction(decl); if (fn) functions.push(fn); - else if (this.countsSkips()) this.countSkippedBody(decl); + else if (this.countsSkips()) { + this.countSkippedBody(decl); + if (this.remainder) this.reportBlockedBody(decl); + } } for (const decl of fp.classDecls) { const info = this.classes.get(this.classNamer(decl)); - if (info) functions.push(...this.lowerClassMembers(info)); + if (info) + functions.push( + ...this.withClosureRoot(info.def.name, () => this.lowerClassMembers(info)), + ); else if (this.countsSkips()) this.countSkippedBody(decl); } } @@ -7384,7 +7495,10 @@ export class Lowerer { // are reachable by definition, already counted by reachable emit. if (!this.remainder) { for (const fp of parts) { - functions.push(this.lowerFileInit(fp.sf, fp.topStmts, this.initNameOf.get(fp.sf)!)); + const initName = this.initNameOf.get(fp.sf)!; + functions.push( + this.withClosureRoot(initName, () => this.lowerFileInit(fp.sf, fp.topStmts, initName)), + ); } functions.push(this.buildMain()); } @@ -7426,7 +7540,9 @@ export class Lowerer { // default): the diagnostic is recorded — the instance skips // like a signature-blocked function (lowerFunction's rule). try { - functions.push(this.lowerGenericInstance(info, inst)); + functions.push( + this.withClosureRoot(inst.name, () => this.lowerGenericInstance(info, inst)), + ); } catch (e) { if (!(e instanceof PoisonError)) throw e; } @@ -7436,7 +7552,10 @@ export class Lowerer { // instances of its own; the joint fixpoint covers both). while (es < this.emitSpecQueue.length) { try { - const fn = lowerEmitOverrideSpec(this, this.emitSpecQueue[es++]!); + const spec = this.emitSpecQueue[es++]!; + const fn = this.withClosureRoot(emitSpecRoot(spec), () => + lowerEmitOverrideSpec(this, spec), + ); if (fn) functions.push(fn); } catch (e) { if (!(e instanceof PoisonError)) throw e; @@ -7687,6 +7806,19 @@ export class Lowerer { } } + /** Coverage remainder: the body diagnostics of a function whose + * signature blocked (blockedBodyDiagnostics). A function reachable emit + * reached (its signature's diagnostics flushed there) reports them with + * the reached diagnostics; any other reports them as unreached. */ + readonly reachedBlockedBodyDiagnostics: ScrDiagnostic[] = []; + private reportBlockedBody(decl: ts.FunctionDeclaration): void { + const diags = blockedBodyDiagnostics(this, decl); + const symbol = declSymbolOf(this, decl); + if (symbol && this.alreadyFlushed.has(symbol)) + this.reachedBlockedBodyDiagnostics.push(...diags); + else for (const d of diags) this.pushDiag(d); + } + /** Whether run() counts a signature-blocked declaration in * stats.functionsSkipped: whole-program passes and the coverage * remainder do; an externally-gated emit pass leaves the counting to the @@ -7990,7 +8122,9 @@ export class Lowerer { this.genericClassDemandPriority.set(info, ref); instanceFunctions.push( ...this.withGenericDemandOwner(owner, () => - this.shapes.withDeclaredOrderPriority(ref, () => this.lowerClassMembers(info)), + this.shapes.withDeclaredOrderPriority(ref, () => + this.withClosureRoot(info.def.name, () => this.lowerClassMembers(info)), + ), ), ); relieveHeapPressure(); @@ -8017,7 +8151,7 @@ export class Lowerer { instanceFunctions.push( this.withGenericDemandOwner(owner, () => this.shapes.withDeclaredOrderPriority(ref, () => - this.lowerGenericInstance(info, inst), + this.withClosureRoot(inst.name, () => this.lowerGenericInstance(info, inst)), ), ), ); @@ -8050,9 +8184,12 @@ export class Lowerer { ); while (specLowered < waveEnd) { try { - const fn = this.shapes.withDeclaredOrderPriority([4, instanceMetadataOrder++], () => - lowerEmitOverrideSpec(this, this.emitSpecQueue[specLowered++]!), - ); + const fn = this.shapes.withDeclaredOrderPriority([4, instanceMetadataOrder++], () => { + const spec = this.emitSpecQueue[specLowered++]!; + return this.withClosureRoot(emitSpecRoot(spec), () => + lowerEmitOverrideSpec(this, spec), + ); + }); if (fn) instanceFunctions.push(fn); } catch (e) { if (!(e instanceof PoisonError)) throw e; @@ -8080,7 +8217,9 @@ export class Lowerer { initFunctions.push( this.withGenericDemandOwner(owner, () => this.shapes.withDeclaredOrderPriority(priority, () => - this.lowerFileInit(fp.sf, fp.topStmts, this.initNameOf.get(fp.sf)!), + this.withClosureRoot(this.initNameOf.get(fp.sf)!, () => + this.lowerFileInit(fp.sf, fp.topStmts, this.initNameOf.get(fp.sf)!), + ), ), ), ); @@ -8106,7 +8245,9 @@ export class Lowerer { const priority = metadataPriority.get(name) ?? [3, expressionMetadataOrder++]; const owner = demandOwner(priority); const fn = this.withGenericDemandOwner(owner, () => - this.shapes.withDeclaredOrderPriority(priority, unit.lower), + this.shapes.withDeclaredOrderPriority(priority, () => + this.withClosureRoot(name, unit.lower), + ), ); if (fn) loweredUnits.set(name, fn); relieveHeapPressure(); @@ -8123,6 +8264,7 @@ export class Lowerer { // turn queue more instances. Continue to the joint fixpoint; the initial // queue above is the only portion whose discovery order differed from // historical emit order. + noteDateClassMethods(this); const classDispatch = new ClassDynamicDispatch(extraRoots !== undefined); // Units in declaration order, so the passes below meet functions, and the // classes they collect, in an order that does not depend on lowering order. @@ -8133,13 +8275,17 @@ export class Lowerer { for (;;) { drainInstances(); const declared = unitsInOrder(); - const initializerChanged = this.deferredModuleInitializers.process(this, [ - ...declared, - ...initFunctions, - ...instanceFunctions, - ...byName(this.liftedFns), - ...byName(this.implicitFns), - ]); + const initializerChanged = this.deferredModuleInitializers.process( + this, + [ + ...declared, + ...initFunctions, + ...instanceFunctions, + ...byName(this.liftedFns), + ...byName(this.implicitFns), + ], + (fn) => classDispatch.sites.forget(fn), + ); const dispatchChanged = classDispatch.process(this, [ ...declared, ...initFunctions, @@ -9196,6 +9342,21 @@ export class Lowerer { * type-mapper.ts's chalk-shape mapping — call paths and func-slot coercions * share it. */ hybridCallUnwrap(expr: IrExpr): IrExpr { + // A callable CLASS instance: a class whose merged interface carries a + // call signature stores its call behavior in a `%call` field (the + // chalk package shim's builder). Calls read the field. + if (expr.type.kind === "object") { + const callType = this.classes.get(expr.type.className)?.fields.get("%call"); + if (callType === undefined || callType.kind !== "func") return expr; + return { + kind: "fieldGet", + obj: expr, + className: expr.type.className, + field: "%call", + type: callType, + loc: expr.loc, + }; + } if (expr.type.kind !== "record") return expr; const shape = this.shapes.get(expr.type.shapeId); const call = shape?.fields.find((f) => f.name === "%call"); @@ -9296,6 +9457,11 @@ export class Lowerer { const adapted = iteratorSlotAdapter(this, expr, expected); if (adapted) return adapted; } + // Iterable-typed slots: other iterators enter the generator arm. + if (expected.kind === "union" && !typeEquals(expr.type, expected)) { + const iterable = iterableSlotValue(this, expr, expected); + if (iterable) return iterable; + } // an any-typed slot marshals implicitly (tsc allows the assignment; // the marshal is where its semantics live). OUT: an 'any' value @@ -9526,9 +9692,27 @@ export class Lowerer { // A HYBRID (function-with-properties) record flowing into a plain // func slot extracts its reserved %call field — the chalk shape's // "the value IS callable" half (type-mapper.ts's hybrid mapping). - if (expected.kind === "func" && expr.type.kind === "record") { + if (expected.kind === "func" && (expr.type.kind === "record" || expr.type.kind === "object")) { const un = this.hybridCallUnwrap(expr); if (un !== expr && typeEquals(un.type, expected)) return un; + // A callable class instance (the chalk shim's variadic builder) in a + // narrower function slot: its call closure crosses the checked + // function boundary, which adapts the arity. + if ( + un !== expr && + expr.type.kind === "object" && + un.type.kind === "func" && + canBoxFuncIntoDyn( + un.type, + (id) => this.shapes.get(id), + (id) => this.unions.get(id), + ) + ) { + return this.coerceToExpected( + { kind: "dynFrom", value: un, type: DYN, loc: un.loc }, + expected, + ); + } } // A zero-param function whose RETURN is a wider record array than the // slot's (`getRoutes: () => cachedRoutes` against `() => Narrow[]`): @@ -10686,9 +10870,29 @@ export class Lowerer { // Contextual types (such as Proxy descriptors' symbol-valued fields) // must not force an intermediate record with incompatible field slots. if (this.returnsLiteralIntoDyn(node, expected)) return this.lowerExprExpecting(node, expected); + if (this.returnsFreshCollection(node) && expected.kind !== "void") + return this.lowerExprExpecting(node, expected); return this.asyncReturnValueOf(node, this.lowerExpr(node), expected); } + /** An array literal or a `new Map(...)`, `new Set(...)` or `new + * Array(...)` of the builtins: a fresh collection, never a thenable, so + * an async return takes the declared result type as its construction + * layout the way a synchronous return does (`return []` in a function + * whose inferred result is `Promise`). */ + private returnsFreshCollection(node: ts.Expression): boolean { + let e = node; + while (ts.isParenthesizedExpression(e)) e = e.expression; + if (ts.isArrayLiteralExpression(e)) return true; + return ( + ts.isNewExpression(e) && + ts.isIdentifier(e.expression) && + (this.isStdlibGlobal(e.expression, "Map") || + this.isStdlibGlobal(e.expression, "Set") || + this.isStdlibGlobal(e.expression, "Array")) + ); + } + /** A fresh JS object literal returned into a checked-native (dyn) result, * which lowers straight into that storage. */ private returnsLiteralIntoDyn(node: ts.Expression, expected: IrType): boolean { @@ -10820,7 +11024,11 @@ export class Lowerer { loc, }; } - if (this.adoptsReturnedPromise() && !this.returnsLiteralIntoDyn(node, expected)) { + if ( + this.adoptsReturnedPromise() && + !this.returnsLiteralIntoDyn(node, expected) && + !this.returnsFreshCollection(node) + ) { // The async return lowers its operand untyped first (a promise // adopts before its payload converts); a maybe-promise union needs // the statement form, which branches between adoption and fulfillment. @@ -11283,8 +11491,8 @@ export class Lowerer { } } - lowerClassExpression(expr: ts.ClassLikeDeclaration): IrExpr { - return lowerClassExpression(this, expr); + lowerClassExpression(expr: ts.ClassLikeDeclaration, binding?: IrLocal): IrExpr { + return lowerClassExpression(this, expr, binding); } /* ── the class graph (single inheritance) ─────────────────────────── */ @@ -12417,8 +12625,9 @@ export class Lowerer { /* ── expressions ──────────────────────────────────────────────────── */ lowerExpr(expr: ts.Expression): IrExpr { - const hash = this.hashStreamReceivers.get(expr); - if (hash) return hashStreamOf(varRef(hash.localId, hash.type, locOf(expr))); + const streamValue = this.valueStreamReceivers.get(expr); + if (streamValue) + return valueStreamOf(varRef(streamValue.localId, streamValue.type, locOf(expr))); return this.stagedArgument(expr) ?? lowerExpr(this, expr); } @@ -12758,6 +12967,25 @@ export class Lowerer { ); } + /** withExpressionOverride for several nodes at once. */ + withExpressionOverrides( + overrides: readonly { node: ts.Expression; value: IrExpr }[], + lower: () => T, + ): T { + const previous = overrides.map((override) => this.chainRecvByNode.get(override.node)); + for (const override of overrides) this.chainRecvByNode.set(override.node, override.value); + try { + return lower(); + } finally { + for (let i = overrides.length - 1; i >= 0; i--) { + const node = overrides[i]!.node; + const value = previous[i]; + if (value) this.chainRecvByNode.set(node, value); + else this.chainRecvByNode.delete(node); + } + } + } + withExpressionOverride(node: ts.Expression, value: IrExpr, lower: () => T): T { const previous = this.chainRecvByNode.get(node); this.chainRecvByNode.set(node, value); @@ -12777,6 +13005,7 @@ export class Lowerer { if (webAssembly !== null) return webAssembly; refuseWebAssemblyUse(this, expr.expression); return ( + lowerErrorFunctionCall(this, expr) ?? lowerLifetimeRegionCall(this, expr) ?? lowerInternTableCall(this, expr) ?? lowerThreadSlotsCall(this, expr) ?? @@ -12793,6 +13022,7 @@ export class Lowerer { lowerWebCryptoCall(this, expr) ?? lowerKeyObjectCall(this, expr) ?? lowerEcdhCall(this, expr) ?? + lowerDiffieHellmanCall(this, expr) ?? lowerNetAddressCall(this, expr) ?? lowerFetchElementMethodCall(this, expr) ?? lowerDynamicImportCall(this, expr) ?? @@ -13410,6 +13640,10 @@ export class Lowerer { const callable = this.lowerBuiltinCallableValue(bi, loc); if (callable) return callable; } + // node:crypto's webcrypto is the WebCrypto global's object. + if (bi.module === "crypto" && bi.member === "webcrypto") { + return { kind: "libCall", fn: "webcrypto.object", args: [], type: DYN, loc }; + } // node:stream/web's exports are the web stream globals themselves: in // JavaScript sources the same identity token as the global spelling // (`require("stream/web").ReadableStream === globalThis.ReadableStream`). @@ -13489,7 +13723,7 @@ export class Lowerer { const key = `${fn.valueFn ?? fn.fn}:${typeKey(funcType)}:${adapterShape}`; let fnName = this.builtinCallableValueFns.get(key); if (!fnName) { - fnName = `%builtin.value.${fn.valueFn ?? fn.fn}.${this.builtinCallableValueFns.size}`; + fnName = keyedHelperName(this, `%builtin.value.${fn.valueFn ?? fn.fn}`, key); this.builtinCallableValueFns.set(key, fnName); this.builtinCallableValueNames.set(fnName, display.slice(display.lastIndexOf(".") + 1)); const params = funcType.params.map((type, index) => ({ diff --git a/packages/compiler/src/frontend/lowering/narrowing-stability.ts b/packages/compiler/src/frontend/lowering/narrowing-stability.ts index 1c991c6ea..63e503221 100644 --- a/packages/compiler/src/frontend/lowering/narrowing-stability.ts +++ b/packages/compiler/src/frontend/lowering/narrowing-stability.ts @@ -454,6 +454,10 @@ export class NarrowingStability { const found = new Map(); writes = found; this.identifierWrites.set(file, found); + // A declaration file holds no code that runs, so none of its writes + // happen. Its bindings (`console`, `JSON`) are read in most programs, + // and the walk would read every node of the file. + if (file.isDeclarationFile) return writes; const add = (target: ts.Node): void => { forEachWriteTarget(target, (t) => { if (!ts.isIdentifier(t)) return; diff --git a/packages/compiler/src/frontend/lowering/native-ffi.ts b/packages/compiler/src/frontend/lowering/native-ffi.ts index 0f932ba93..62f2be9f1 100644 --- a/packages/compiler/src/frontend/lowering/native-ffi.ts +++ b/packages/compiler/src/frontend/lowering/native-ffi.ts @@ -562,7 +562,7 @@ export function lowerFfiMemoryModule(lowerer: Lowerer, loc: SrcLoc): IrExpr { const entries = lowerer.ffiImports .filter((entry) => entry.library !== undefined) .map((entry) => { - const name = `%ffi.module.${lowerer.lambdaCounter++}`; + const name = lowerer.closureName(loc, "", "%ffi.module"); const sourceTypes = ffiSourceParamTypes(entry.params); const locals: IrLocal[] = sourceTypes.map((_, i) => ({ id: `%arg${i}`, diff --git a/packages/compiler/src/frontend/lowering/object-enumeration-receiver.ts b/packages/compiler/src/frontend/lowering/object-enumeration-receiver.ts index 855da3bda..388ac3904 100644 --- a/packages/compiler/src/frontend/lowering/object-enumeration-receiver.ts +++ b/packages/compiler/src/frontend/lowering/object-enumeration-receiver.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "./stable-names.js"; import { BOOL, STRING, @@ -27,7 +28,7 @@ export function objectEnumerationReceiver( const key = `obj.receiver:${source.unionId}:${expected.shapeId}`; let name = lowerer.arrHofHelpers.get(key); if (name === undefined) { - name = `%obj.receiver.${lowerer.arrHofHelpers.size}`; + name = keyedHelperName(lowerer, "%obj.receiver", key); lowerer.arrHofHelpers.set(key, name); const value = varRef("value.0", source, loc); lowerer.liftedFns.push({ diff --git a/packages/compiler/src/frontend/lowering/pairs-snapshot.ts b/packages/compiler/src/frontend/lowering/pairs-snapshot.ts index 3b33fb0cd..acf7b3bf9 100644 --- a/packages/compiler/src/frontend/lowering/pairs-snapshot.ts +++ b/packages/compiler/src/frontend/lowering/pairs-snapshot.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "./stable-names.js"; import { arrayOf, BOOL, @@ -49,7 +50,7 @@ export function pairsSnapshotHelper( const key = `${options.keyPrefix}.snapshot:${shapeId}`; const existing = lowerer.valueHelpers.get(key); if (existing) return existing; - const name = `%${options.keyPrefix}.snapshot.${lowerer.valueHelpers.size}`; + const name = keyedHelperName(lowerer, `%${options.keyPrefix}.snapshot`, key); lowerer.valueHelpers.set(key, name); const recordType: IrType = { kind: "record", shapeId }; const pairsType = arrayOf(STRING); diff --git a/packages/compiler/src/frontend/lowering/private-brands.ts b/packages/compiler/src/frontend/lowering/private-brands.ts index 8507cc81a..c7881bce1 100644 --- a/packages/compiler/src/frontend/lowering/private-brands.ts +++ b/packages/compiler/src/frontend/lowering/private-brands.ts @@ -160,6 +160,60 @@ function brandCall( return { kind: "call", callee: helper, args: [receiver, evaluation], type: resultType, loc }; } +/** The class whose body declares the private name `priv` (the nearest + * enclosing one, as JavaScript scoping resolves it), when it is a + * declaration-level class, or null. */ +export function privateNameClass(lowerer: Lowerer, priv: ts.PrivateIdentifier): ClassInfo | null { + for (let node: ts.Node | undefined = priv.parent; node; node = node.parent) { + if (!ts.isClassDeclaration(node) && !ts.isClassExpression(node)) continue; + const declares = node.members.nodes.some((member) => { + const name = (member as { name?: ts.PropertyName }).name; + return name !== undefined && ts.isPrivateIdentifier(name) && name.text === priv.text; + }); + if (!declares) continue; + const symbol = node.name ? lowerer.checker.getSymbolAtLocation(node.name) : undefined; + const info = + lowerer.currentClass?.decl === node + ? lowerer.currentClass + : symbol + ? lowerer.classBySymbol.get(symbol) + : undefined; + if (!info || info.localClass || info.generic || info.genericInstance) return null; + return info; + } + return null; +} + +/** `value.#x` on a checked-dynamic `value` in a declaration-level class + * `info`: the receiver as an instance of `info` when the value is one (an + * instance of the class or a subclass), else Node's TypeError for a missing + * private member (also for undefined and null). */ +export function checkedPrivateValue( + lowerer: Lowerer, + info: ClassInfo, + access: ts.PropertyAccessExpression, + receiver: IrExpr, + loc: SrcLoc, +): IrExpr { + const use: BrandUse = isPrivateWriteTarget(access) ? "write" : "read"; + const className = info.def.name; + const resultType: IrType = { kind: "object", className }; + const helper = `${PREFIX}${use}:${className}:${access.name.text}`; + if (!lowerer.valueHelpers.has(helper)) { + lowerer.liftedFns.push({ + name: helper, + params: [{ localId: "value.0", name: "value", type: DYN }], + returnType: resultType, + locals: [{ id: "value.0", name: "value", type: DYN, mutable: false }], + // finalizePrivateBrands fills the body. + body: [], + loc: helperLoc(loc), + }); + lowerer.valueHelpers.set(helper, helper); + } + return { kind: "call", callee: helper, args: [receiver], type: resultType, loc }; +} + /** A plain assignment, a destructuring target, or a for-in/of target writes * the field. Compound assignments and updates read it first, and Node * reports the failed read. */ @@ -203,7 +257,9 @@ export function finalizePrivateBrands(lowerer: Lowerer, functions: IrFunction[]) const name = spec.slice(spec.lastIndexOf(":") + 1); const loc = fn.loc; const value = varRef("value.0", DYN, loc); - const evaluation = varRef("class.0", { kind: "classval", className }, loc); + // A declaration-level class has one brand: the helper takes no class. + const evaluation = + fn.params.length > 1 ? varRef("class.0", { kind: "classval", className }, loc) : null; const ownerType: IrType = { kind: "object", className }; const body: IrStmt[] = []; let matches = 0; @@ -218,21 +274,23 @@ export function finalizePrivateBrands(lowerer: Lowerer, functions: IrFunction[]) const local = `receiver.${matches++}`; fn.locals.push({ id: local, name: "receiver", type: ownerType, mutable: false }); const receiver = varRef(local, ownerType, loc); - const sameEvaluation: IrExpr = { - kind: "bin", - op: "===", - left: { - kind: "fieldGet", - obj: receiver, - className, - field: `%classEnvironment:${className}`, - type: evaluation.type, - loc, - }, - right: evaluation, - type: BOOL, - loc, - }; + const sameEvaluation: IrExpr = evaluation + ? { + kind: "bin", + op: "===", + left: { + kind: "fieldGet", + obj: receiver, + className, + field: `%classEnvironment:${className}`, + type: evaluation.type, + loc, + }, + right: evaluation, + type: BOOL, + loc, + } + : { kind: "boolLit", value: true, type: BOOL, loc }; const match = (typed: IrExpr): IrStmt[] => [ { kind: "varDecl", localId: local, init: typed, loc }, { diff --git a/packages/compiler/src/frontend/lowering/promise-executor-adapter.ts b/packages/compiler/src/frontend/lowering/promise-executor-adapter.ts index 09d228b05..84aa8dac0 100644 --- a/packages/compiler/src/frontend/lowering/promise-executor-adapter.ts +++ b/packages/compiler/src/frontend/lowering/promise-executor-adapter.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "./stable-names.js"; import { varRef } from "../../ir/build.js"; import { type IrExpr, @@ -40,7 +41,7 @@ export function adaptPromiseExecutor( const key = `promise.executor:${typeKey(execT)}:${typeKey(inner)}`; let name = lowerer.arrHofHelpers.get(key); if (name === undefined) { - name = `%promise.executor.${lowerer.arrHofHelpers.size}`; + name = keyedHelperName(lowerer, "%promise.executor", key); lowerer.arrHofHelpers.set(key, name); const impl = `${name}.impl`; const captured: IrLocal = { id: "f.0", name: "f", type: execT, mutable: false, boxed: true }; diff --git a/packages/compiler/src/frontend/lowering/require-initialization.ts b/packages/compiler/src/frontend/lowering/require-initialization.ts index d979423b0..c8fc9c730 100644 --- a/packages/compiler/src/frontend/lowering/require-initialization.ts +++ b/packages/compiler/src/frontend/lowering/require-initialization.ts @@ -9,6 +9,7 @@ * and every reference that can run earlier checks it first — the same * module.tdzCheck the import-cycle bindings use. A reference whose lowering * leaves no expression to check keeps the SC1013 fence. */ +import { positionTag } from "./structural-positions.js"; import * as ts from "../ts7/adapter.js"; import type { Lowerer } from "./lowerer.js"; import { @@ -119,7 +120,7 @@ export function markRequireEarlyBindings(lowerer: Lowerer): void { const tag = rawTag === "" ? "e." : rawTag.replace(/^%/, ""); const bySymbol = new Map(); for (const { decl } of declared) { - const flagId = `%g.${tag}%required.${ts.tokenStartOfNode(decl)}`; + const flagId = `%g.${tag}%required.${positionTag(lowerer, decl)}`; lowerer.globalsList.push({ id: flagId, name: "%initialized", type: BOOL, mutable: true }); const flag: RequireInitFlag = { flagId, names: new Map() }; for (const id of boundNames(decl.name)) { diff --git a/packages/compiler/src/frontend/lowering/stable-names.ts b/packages/compiler/src/frontend/lowering/stable-names.ts new file mode 100644 index 000000000..8f7d0967e --- /dev/null +++ b/packages/compiler/src/frontend/lowering/stable-names.ts @@ -0,0 +1,48 @@ +import { InternalCompilerError } from "../../errors.js"; + +/** The owner of the names keyedHelperName hands out. */ +export interface KeyedNameOwner { + /** Each keyed name with a second hash of the key it was made from, which + * tells a repeated key from a different key with the same name. */ + readonly keyedNameKeys: Map; +} + +/** 48 bits of two FNV-1a hashes of `key`, as 12 hex digits. */ +function keyHash(key: string): string { + let a = 0x811c9dc5; + let b = 0x01000193 ^ 0x5bd1e995; + for (let i = 0; i < key.length; i++) { + const c = key.charCodeAt(i); + a = Math.imul(a ^ c, 0x01000193); + b = Math.imul(b ^ c, 0x01000193) ^ (b >>> 13); + } + const high = (b >>> 0).toString(16).padStart(8, "0").slice(4); + return high + (a >>> 0).toString(16).padStart(8, "0"); +} + +/** A 32-bit hash of `key` independent of keyHash's bits. */ +function checkHash(key: string): number { + let h = 0x9e3779b9; + for (let i = 0; i < key.length; i++) + h = Math.imul(h ^ key.charCodeAt(i), 0x85ebca6b) ^ (h >>> 15); + return h >>> 0; +} + +/** The name of a helper interned by `key`: ``. It depends only on the key, not on how many helpers were interned + * before, so a helper has the same name whichever unit first needs it. Two + * keys that hash to the same name throw an InternalCompilerError. */ +export function keyedHelperName( + owner: KeyedNameOwner, + prefix: string, + key: string, + separator = ".", +): string { + const name = `${prefix}${separator}${keyHash(key)}`; + const check = checkHash(key); + const previous = owner.keyedNameKeys.get(name); + if (previous === undefined) owner.keyedNameKeys.set(name, check); + else if (previous !== check) + throw new InternalCompilerError(`helper name ${name} is shared by two helper keys`); + return name; +} diff --git a/packages/compiler/src/frontend/lowering/strict-equality.ts b/packages/compiler/src/frontend/lowering/strict-equality.ts index 7b9b6902b..8a87c8111 100644 --- a/packages/compiler/src/frontend/lowering/strict-equality.ts +++ b/packages/compiler/src/frontend/lowering/strict-equality.ts @@ -1,3 +1,4 @@ +import { keyedHelperName } from "./stable-names.js"; import { boolLit, varRef } from "../../ir/build.js"; import { BOOL, @@ -135,7 +136,7 @@ export function lowerUnionEquality( loc, ); if (!result) return null; - name = `%value.eq.${lowerer.equalityHelpers.size}`; + name = keyedHelperName(lowerer, "%value.eq", key); lowerer.equalityHelpers.set(key, name); lowerer.liftedFns.push({ name, diff --git a/packages/compiler/src/frontend/lowering/structural-positions.ts b/packages/compiler/src/frontend/lowering/structural-positions.ts new file mode 100644 index 000000000..43b6d4a79 --- /dev/null +++ b/packages/compiler/src/frontend/lowering/structural-positions.ts @@ -0,0 +1,111 @@ +import * as ts from "../ts7/adapter.js"; +import { keyedHelperName, type KeyedNameOwner } from "./stable-names.js"; + +/** The declaration kinds whose names anchor the positions inside them. */ +const ANCHOR_KINDS: ReadonlySet = new Set([ + ts.SyntaxKind.FunctionDeclaration, + ts.SyntaxKind.ClassDeclaration, + ts.SyntaxKind.ClassExpression, + ts.SyntaxKind.VariableDeclaration, + ts.SyntaxKind.MethodDeclaration, + ts.SyntaxKind.GetAccessor, + ts.SyntaxKind.SetAccessor, + ts.SyntaxKind.PropertyDeclaration, + ts.SyntaxKind.PropertyAssignment, + ts.SyntaxKind.ModuleDeclaration, + ts.SyntaxKind.EnumDeclaration, + ts.SyntaxKind.Constructor, + ts.SyntaxKind.InterfaceDeclaration, + ts.SyntaxKind.TypeAliasDeclaration, +]); + +/** The name of `node` when it is a named declaration that anchors the + * positions of the nodes inside it, or null. */ +function anchorName(node: ts.Node): string | null { + return ts.declarationNameAt(node, node.index, ANCHOR_KINDS); +} + +/** The nearest enclosing anchor of `node` (not `node` itself), or its + * source file. */ +function anchorOf(node: ts.Node): ts.Node { + for (let parent = node.parent; parent !== undefined; parent = parent.parent) { + if (ts.isSourceFile(parent) || anchorName(parent) !== null) return parent; + } + return ts.getSourceFileOfNode(node); +} + +/** Source positions that stay the same when code outside the enclosing + * declaration changes. A node's structural position is its file, the chain + * of enclosing named declarations (each with its kind, its name and its + * ordinal among the declarations of the same kind and name in its own + * anchor), and its ordinal among the nodes of its kind whose nearest anchor + * is the same declaration. Editing another declaration, or code nested in another + * named declaration of the same anchor, leaves the position unchanged. */ +export class StructuralPositions { + /** Per anchor and key: the indices of the nodes with that key whose + * nearest anchor it is, in preorder (anchoredNodes). */ + private readonly nodesByKey = new Map>(); + private readonly paths = new Map(); + + /** `fileKey` names a source file in positions (its file name when + * absent). */ + constructor(private readonly fileKey?: (sf: ts.SourceFile) => string) {} + + /** The ordinal of `node` among the nodes of `anchor` with its key. */ + private ordinalIn(anchor: ts.Node, node: ts.Node, key: string): number { + let byKey = this.nodesByKey.get(anchor); + if (byKey === undefined) this.nodesByKey.set(anchor, (byKey = new Map())); + let indices = byKey.get(key); + if (indices === undefined) { + indices = ts.anchoredNodes(anchor, key, ANCHOR_KINDS); + byKey.set(key, indices); + } + // Indices increase in preorder. + let low = 0; + let high = indices.length - 1; + while (low <= high) { + const middle = (low + high) >> 1; + const at = indices[middle]!; + if (at === node.index) return middle; + if (at < node.index) low = middle + 1; + else high = middle - 1; + } + return -1; + } + + /** The anchor chain of `anchor` from the file down. */ + private pathOf(anchor: ts.Node): string { + const cached = this.paths.get(anchor); + if (cached !== undefined) return cached; + let path: string; + if (ts.isSourceFile(anchor)) path = this.fileKey?.(anchor) ?? anchor.fileName; + else { + const parent = anchorOf(anchor); + // The kind keeps declarations of one name apart: a getter and its + // setter, or a class and the namespace merged with it. + const key = `${anchor.kind}:${anchorName(anchor)}`; + path = `${this.pathOf(parent)}/${key}#${this.ordinalIn(parent, anchor, key)}`; + } + this.paths.set(anchor, path); + return path; + } + + /** The structural position of `node`. */ + of(node: ts.Node): string { + const anchor = anchorOf(node); + const name = anchorName(node); + const key = name === null ? `${node.kind}` : `${node.kind}:${name}`; + return `${this.pathOf(anchor)}|${key}#${this.ordinalIn(anchor, node, key)}`; + } +} + +/** The owner of structural positions and the names made from them. */ +export interface PositionTagOwner extends KeyedNameOwner { + readonly positions: StructuralPositions; +} + +/** A short tag for `node`'s structural position, for names that must stay + * unique per source node (class expressions, namespace blocks). */ +export function positionTag(owner: PositionTagOwner, node: ts.Node): string { + return keyedHelperName(owner, "", owner.positions.of(node), ""); +} diff --git a/packages/compiler/src/frontend/lowering/surfaces.ts b/packages/compiler/src/frontend/lowering/surfaces.ts index c77938337..8b826304b 100644 --- a/packages/compiler/src/frontend/lowering/surfaces.ts +++ b/packages/compiler/src/frontend/lowering/surfaces.ts @@ -1553,6 +1553,16 @@ export const BUILTIN_MODULE_FNS: Record< createSecretKey: { fn: "crypto.createSecretKey", params: [DYN, DYN], result: DYN }, generateKeySync: { fn: "crypto.generateKeySync", params: [DYN, DYN], result: DYN }, generateKey: { fn: "crypto.generateKeyCb", params: [], result: VOID }, + // Asymmetric keys and signatures (lowerPkiCall): checked-dynamic + // arguments, results converted to the call site's type. + createPrivateKey: { fn: "crypto.createPrivateKey", params: [DYN], result: DYN }, + createPublicKey: { fn: "crypto.createPublicKey", params: [DYN], result: DYN }, + createSign: { fn: "crypto.createSign", params: [DYN], result: DYN }, + createVerify: { fn: "crypto.createVerify", params: [DYN], result: DYN }, + generateKeyPairSync: { fn: "crypto.generateKeyPairSync", params: [], result: DYN }, + generateKeyPair: { fn: "crypto.generateKeyPairCb", params: [], result: VOID }, + sign: { fn: "crypto.signOneshot", params: [], result: DYN }, + verify: { fn: "crypto.verifyOneshot", params: [], result: DYN }, pbkdf2Sync: { fn: "crypto.pbkdf2", params: [BYTES_U8, BYTES_U8, F64, F64, STRING], @@ -1574,6 +1584,18 @@ export const BUILTIN_MODULE_FNS: Record< // A checked-dynamic curve name; the result is a native ECDH handle // (lowerCreateEcdh). createECDH: { fn: "crypto.ecdhNew", params: [DYN], result: DYN }, + // Checked-dynamic arguments; the result is a native DiffieHellman or + // DiffieHellmanGroup handle (lowerCreateDiffieHellman and + // lowerGetDiffieHellman). + createDiffieHellman: { fn: "crypto.dhNew", params: [DYN, DYN, DYN, DYN], result: DYN }, + getDiffieHellman: { fn: "crypto.dhGroupNew", params: [DYN], result: DYN }, + createDiffieHellmanGroup: { fn: "crypto.dhGroupNew", params: [DYN], result: DYN }, + // Prime checks and generation (lowerPrimeCall): checked-dynamic + // arguments, results converted to the call site's type. + checkPrimeSync: { fn: "crypto.checkPrimeSync", params: [], result: DYN }, + checkPrime: { fn: "crypto.checkPrimeCb", params: [], result: VOID }, + generatePrimeSync: { fn: "crypto.generatePrimeSync", params: [], result: DYN }, + generatePrime: { fn: "crypto.generatePrimeCb", params: [], result: VOID }, }, zlib: { // The default-options convenience family is special-cased in @@ -2210,15 +2232,28 @@ export const AMBIENT_SURFACE_FNS: readonly AmbientSurfaceRow[] = [ id: "stdlib.webcrypto.subtle", kind: "stdlib", name: "globalThis.crypto.subtle", - fns: ["webcrypto.importKey", "webcrypto.sign", "webcrypto.verify", "webcrypto.digest"], - note: "importKey('raw') for HMAC keys, HMAC sign and verify, and SHA-1/SHA-2 digest; other methods, algorithms and key formats are refused", + fns: [ + "webcrypto.generateKey", + "webcrypto.importKey", + "webcrypto.exportKey", + "webcrypto.encrypt", + "webcrypto.decrypt", + "webcrypto.wrapKey", + "webcrypto.unwrapKey", + "webcrypto.deriveBits", + "webcrypto.deriveKey", + "webcrypto.sign", + "webcrypto.verify", + "webcrypto.digest", + ], + note: "importKey, generateKey and exportKey (raw and jwk) for HMAC and AES keys, importKey for PBKDF2 and HKDF keys, AES-GCM, AES-CBC and AES-CTR encrypt and decrypt, wrapKey and unwrapKey of secret keys with AES-KW or those ciphers, PBKDF2 and HKDF deriveBits and deriveKey, HMAC sign and verify, generateKey, importKey, exportKey, sign and verify for ECDSA, Ed25519, RSASSA-PKCS1-v1_5 and RSA-PSS, and SHA-1/SHA-2 digest; other methods, algorithms and key formats are refused", }, { id: "stdlib.webcrypto.CryptoKey", kind: "stdlib", name: "CryptoKey", fns: ["webcrypto.isCryptoKey"], - note: "secret HMAC keys with type, extractable, algorithm and usages, and instanceof CryptoKey", + note: "secret HMAC, AES, PBKDF2 and HKDF keys with type, extractable, algorithm and usages, and instanceof CryptoKey", }, { id: "stdlib.atomics", @@ -2262,6 +2297,8 @@ export const AMBIENT_SURFACE_FNS: readonly AmbientSurfaceRow[] = [ "date.newLocal", "date.nativeNewFields", "date.nativeNewValue", + "date.argumentsTime", + "date.classOperation", ], note: "zero arguments, one milliseconds/date-string argument, or local-time year/month fields; values are the read-only TimeClip scalar slice", }, @@ -3054,43 +3091,27 @@ export const BUILTIN_MODULE_FENCE_HINTS: Record< }, crypto: { ...Object.fromEntries( - [ - "generateKeyPair", - "generateKeyPairSync", - "createPrivateKey", - "createPublicKey", - "createSign", - "createVerify", - "sign", - "verify", - "createDiffieHellman", - "createDiffieHellmanGroup", - "getDiffieHellman", - "diffieHellman", - "publicEncrypt", - "publicDecrypt", - "privateEncrypt", - "privateDecrypt", - ].map((m) => [ + ["publicEncrypt", "publicDecrypt", "privateEncrypt", "privateDecrypt"].map((m) => [ m, - "asymmetric-key operations need a public-key stack (bignum, RSA/EC/EdDSA math) and " + - "public and private KeyObjects — neither exists in the static runtime, so no faithful lowering " + - "can be small; the lowered crypto surface is hashing, randomness, secret KeyObjects, and the introspection statics", + "RSA encryption has no lowering — the asymmetric crypto surface is " + + "RSA and EC KeyObjects (generateKeyPair, createPrivateKey, createPublicKey), sign, verify, " + + "createSign, createVerify, createECDH, and createDiffieHellman", ]), ), + diffieHellman: + "crypto.diffieHellman takes DH, EC or X25519 KeyObjects and has no lowering; " + + "the objects of createDiffieHellman, getDiffieHellman and createECDH compute shared secrets", ...Object.fromEntries( ["getCipherInfo"].map((m) => [ m, "cipher metadata has no lowering — createCipheriv and createDecipheriv support " + - "aes-128/192/256 in cbc, ctr, and gcm modes and chacha20-poly1305", + "aes-128/192/256 in cbc, ctr, gcm, ecb, cfb, cfb8, cfb1, and ofb modes, des-ede3 and " + + "des-ede, chacha20, and chacha20-poly1305", ]), ), setFips: "a compiled binary has no FIPS provider to enable, and Node itself throws on setFips(true) " + "in a non-FIPS build — getFips() answers 0 here", - webcrypto: - "the WebCrypto object has no lowering — the lowered crypto surface is randomUUID, " + - "randomBytes, and the createHash chain", }, zlib: { brotliCompressSync: BROTLI_HINT, @@ -3354,6 +3375,17 @@ export function isStdlibSymbol(lowerer: Lowerer, symbol: ts.Symbol | undefined): * tamper-guard prologue) registered in stdlibGlobalAliases; * - a const binding of the Map or Set constructor (`const M = Map`, * builtinClassAliasOf). */ +/** The symbol an identifier reads. A shorthand property's name (`{ Date }`) + * reads the binding of the same name, not the property it declares. */ +export function identifierReadSymbol(lowerer: Lowerer, expr: ts.Identifier): ts.Symbol | undefined { + if (expr.parent && ts.isShorthandPropertyAssignment(expr.parent) && expr.parent.name === expr) + return ( + lowerer.checker.getShorthandAssignmentValueSymbol(expr.parent) ?? + lowerer.checker.getSymbolAtLocation(expr) + ); + return lowerer.checker.getSymbolAtLocation(expr); +} + export function stdlibGlobalNameOf(lowerer: Lowerer, expr: ts.Expression): string | null { if (ts.isParenthesizedExpression(expr)) return stdlibGlobalNameOf(lowerer, expr.expression); // The global-object detection chain (`typeof global < "u" ? global : @@ -3365,7 +3397,7 @@ export function stdlibGlobalNameOf(lowerer: Lowerer, expr: ts.Expression): strin return stdlibGlobalNameOf(lowerer, taken ? expr.whenTrue : expr.whenFalse); } if (ts.isIdentifier(expr)) { - const symbol = lowerer.checker.getSymbolAtLocation(expr); + const symbol = identifierReadSymbol(lowerer, expr); // `globalThis` itself: a reserved intrinsic — tsc rejects user // global bindings, but local parameters can shadow it. Its special // symbol has no ordinary declarations for the provenance check. diff --git a/packages/compiler/src/frontend/lowering/width-lift.ts b/packages/compiler/src/frontend/lowering/width-lift.ts index e3722bc32..126f80f93 100644 --- a/packages/compiler/src/frontend/lowering/width-lift.ts +++ b/packages/compiler/src/frontend/lowering/width-lift.ts @@ -11,6 +11,16 @@ export type WidthLift = | { how: "retag" } | { how: "unitRetag" } | { how: "liftWrap"; tag: number; arm: IrType } + /** A record into a union of two record arms that differ by one field: + * the source field `field` (`T | undefined`) selects `present` when it + * holds a value and `absent`, which lacks the field, when it is + * undefined. */ + | { + how: "presenceRoute"; + field: string; + present: { tag: number; arm: IrType }; + absent: { tag: number; arm: IrType }; + } | { how: "width" } | { how: "unionWidth" } | { how: "arr" } @@ -20,5 +30,6 @@ export type WidthLift = | { how: "clsWidth" } | { how: "narrow" } | { how: "dynIn" } + | { how: "dynOut" } | { how: "upcast" } | { how: "funcAdapt" }; diff --git a/packages/compiler/src/frontend/package-shims.ts b/packages/compiler/src/frontend/package-shims.ts index 86a41d3a6..a0c2e4cb9 100644 --- a/packages/compiler/src/frontend/package-shims.ts +++ b/packages/compiler/src/frontend/package-shims.ts @@ -62,9 +62,20 @@ interface ImplementationShim { * of it (a __commonJS chunk whose key names the package, its version * and this file) is the package itself. */ mainFile: string; + /** The package's declaration entry relative to its directory, when it + * is not `index.d.ts`. */ + typesFile?: string; + /** An alternative entry for this installation (relative to the shim + * root), or undefined for the version's own entry. */ + variant?: (pkgDir: string) => string | undefined; + /** Every variant entry, for the guard test that compiles each one. */ + variants?: readonly string[]; } -const IMPLEMENTATION_SHIMS: ReadonlyMap = new Map([ +const IMPLEMENTATION_SHIMS: ReadonlyMap = new Map< + string, + ImplementationShim +>([ [ "fs-extra", { @@ -79,6 +90,33 @@ const IMPLEMENTATION_SHIMS: ReadonlyMap = new Map([ ]), }, ], + [ + "chalk", + { + name: "chalk", + defaultExport: true, + mainFile: "source/index.js", + typesFile: "source/index.d.ts", + versions: new Map([[5, "chalk/v5.ts"]]), + }, + ], + [ + "hot-shots", + { + name: "hot-shots", + defaultExport: true, + mainFile: "index.js", + typesFile: "types.d.ts", + versions: new Map([[8, "hot-shots/v8.ts"]]), + // hot-shots' uds protocol loads the optional unix-dgram addon: where + // it is installed, the entry with the native Unix datagram transport. + variant: (pkgDir: string) => + installedPackageDir(join(pkgDir, "index.js"), "unix-dgram") === null + ? undefined + : "hot-shots/v8-unix-dgram.ts", + variants: ["hot-shots/v8-unix-dgram.ts"], + }, + ], [ "undici", { @@ -141,8 +179,10 @@ export function throughBundledShimForwarder(resolved: string): string { * the guard test that compiles each one. */ export function packageShimEntries(): string[] { const entries = new Set(); - for (const shim of IMPLEMENTATION_SHIMS.values()) + for (const shim of IMPLEMENTATION_SHIMS.values()) { for (const entry of shim.versions.values()) entries.add(join(packageShimRoot(), entry)); + for (const entry of shim.variants ?? []) entries.add(join(packageShimRoot(), entry)); + } return [...entries].sort(); } @@ -240,7 +280,8 @@ function shimEntryForPackageDir(pkgDir: string, expectedName: string | null): st if (shim === undefined) return null; const major = Number(/^(\d+)\./.exec(pkg.version)?.[1] ?? NaN); const entry = shim.versions.get(major); - return entry === undefined ? null : join(packageShimRoot(), entry); + if (entry === undefined) return null; + return join(packageShimRoot(), shim.variant?.(pkgDir) ?? entry); } /** The shim module `specifier` resolves to from `fromFile`, or null. Only @@ -280,16 +321,33 @@ export function isShimmedImport(fromFile: string, specifier: string): boolean { return isUnloadedPackage(specifier) || packageShimFor(fromFile, specifier) !== null; } +/** The shimmed package whose declaration entry `path` is, with the + * package directory: `/index.d.ts`, or the entry's own `typesFile`. */ +function shimOfDeclarationPath(path: string): { pkgDir: string; shim: ImplementationShim } | null { + if (!path.endsWith(".d.ts")) return null; + if (path.endsWith("/index.d.ts")) { + const pkgDir = dirname(path); + const shim = IMPLEMENTATION_SHIMS.get(pkgDir.slice(pkgDir.lastIndexOf("/") + 1)); + if (shim !== undefined && shim.typesFile === undefined) return { pkgDir, shim }; + } + for (const shim of IMPLEMENTATION_SHIMS.values()) { + if (shim.typesFile === undefined) continue; + const suffix = `/${shim.name}/${shim.typesFile}`; + if (path.endsWith(suffix)) + return { pkgDir: path.slice(0, path.length - suffix.length + shim.name.length + 1), shim }; + } + return null; +} + /** The fs-shadow answer for a shimmed package's declaration entry: the * installed `index.d.ts` reads as a re-export of the version's shim module, * so the checker types each importer against its own version. Undefined * for every other path. */ export function packageShimDeclarationText(path: string): string | undefined { - if (!path.endsWith("/index.d.ts")) return undefined; - const pkgDir = dirname(path); - const name = pkgDir.slice(pkgDir.lastIndexOf("/") + 1); - const shim = IMPLEMENTATION_SHIMS.get(name); - if (shim === undefined) return undefined; + const located = shimOfDeclarationPath(path); + if (located === null) return undefined; + const { pkgDir, shim } = located; + const name = shim.name; // A DefinitelyTyped twin (`@types/fs-extra`) types a package that ships no // declarations. Nothing at its path names the installed runtime version, // so it reads as the shim only when every supported version shares one @@ -316,6 +374,12 @@ export function isPackageShimFile(fileName: string): boolean { return fileName.startsWith(root.endsWith("/") ? root : `${root}/`); } +/** True for a name a shipped shim may declare as a bodiless runtime + * intrinsic (lower-calls.ts lowers its calls to runtime calls). */ +export function isShimIntrinsicName(name: string): boolean { + return name.startsWith("scriptcUnixDgram"); +} + /** Resets per-compile caches. */ export function clearPackageShimCaches(): void { installedCache.clear(); diff --git a/packages/compiler/src/frontend/process-fork.ts b/packages/compiler/src/frontend/process-fork.ts new file mode 100644 index 000000000..744d57aa5 --- /dev/null +++ b/packages/compiler/src/frontend/process-fork.ts @@ -0,0 +1,26 @@ +/** Process primitives for forked lowering workers (unit-journal.ts). The + * native compiler fills these in; under Node they stay unset and reachable + * emit lowers every wave in-process. */ +export interface ProcessFork { + /** fork(): 0 in the worker, the worker's pid in the parent, -1 on failure. */ + fork(): number; + /** Ends the worker without running exit handlers. */ + exit(code: number): void; + /** The worker's exit status, 128 plus a signal number, or -1. */ + wait(pid: number): number; + /** Opens the lock file checker requests from workers take. */ + openLock(path: string): boolean; + lock(): void; + unlock(): void; +} + +export const processFork: { + primitives: ProcessFork | null; + /** True in a worker: checker requests take the lock (rpc-client.ts). */ + worker: boolean; + /** A worker's checker requests and the time it waited for the lock and + * for responses (SCRIPTC_TIMING). */ + requests: number; + lockWaitMs: number; + requestMs: number; +} = { primitives: null, worker: false, requests: 0, lockWaitMs: 0, requestMs: 0 }; diff --git a/packages/compiler/src/frontend/program.ts b/packages/compiler/src/frontend/program.ts index e398e59df..507d3392d 100644 --- a/packages/compiler/src/frontend/program.ts +++ b/packages/compiler/src/frontend/program.ts @@ -140,6 +140,15 @@ import { } from "./type-only-imports.js"; import { moduleSourceCandidates } from "./module-source-candidates.js"; import { inferredJsDiagnosticSuppressed } from "./inferred-js-diagnostics.js"; +import { + containsJsx, + firstJsx, + jsxEmitName, + jsxEmitPlan, + jsxPragmas, + lowerJsx, + type LoweredJsx, +} from "./jsx-source.js"; const BASE_OPTIONS: ts.Ts7CompilerOptions = { strict: true, @@ -377,6 +386,18 @@ export interface LoadResult { * checkPreflight. */ startupCrash?: StartupCrash | null; configDiags: ScrDiagnostic[]; + /** The files whose JSX the program lowers (jsx-source.ts), by file name. + * The program holds their rewritten text; positions in diagnostics refer + * to it. */ + jsxSources?: ReadonlyMap; + /** With JSX sources: the program over the original text, whose TypeScript + * errors are the program's, and its project world when it has errors. */ + tscWorld?: { + program: ts.Program; + /** The program's pre-emit diagnostics, computed once. */ + diagnostics: readonly ts.Diagnostic[]; + projectWorld: ts.Program | null; + }; /** How scriptc's type world differs from the project's own tsc setup — * used only to label the TypeScript errors those differences cause. */ typeWorld?: TypeWorldDifferences; @@ -778,6 +799,47 @@ function moduleSpecifierKind7(specifier: ts.StringLiteralLike): "import" | "requ : "import"; } +/** The program's files with JSX, lowered with the project's jsx settings + * and each file's pragmas, or the refusal of a setting that emits no calls. + * TypeScript files (.ts, .mts, .cts) cannot hold JSX; without a jsx setting + * the checker already rejects any JSX (TS17004). */ +function lowerProgramJsx7( + program: ts.Program, + options: ts.Ts7CompilerOptions, +): { sources: Map; refusal: ScrDiagnostic | null } { + const sources = new Map(); + const mode = jsxEmitName(options.jsx as string | number | undefined); + if (mode === undefined) return { sources, refusal: null }; + for (const sf of program.getImplementationSourceFiles()) { + if (sf.isDeclarationFile || /\.[mc]?ts$/.test(sf.fileName) || !containsJsx(sf)) continue; + const at = firstJsx(sf)!; + const loc = { file: sf.fileName, start: ts.tokenStartOfNode(at), end: at.end }; + if (mode === "preserve" || mode === "react-native") { + return { + sources, + refusal: { + code: "SC1090", + message: `JSX with "jsx": "${mode}" is not supported: that setting keeps JSX in the output instead of lowering it to calls`, + loc, + hint: 'set "jsx" to "react", "react-jsx" or "react-jsxdev" in the project tsconfig', + }, + }; + } + const plan = jsxEmitPlan( + { + jsx: mode, + jsxFactory: options.jsxFactory as string | undefined, + jsxFragmentFactory: options.jsxFragmentFactory as string | undefined, + jsxImportSource: options.jsxImportSource as string | undefined, + reactNamespace: options.reactNamespace as string | undefined, + }, + jsxPragmas(sf.text), + ); + sources.set(sf.fileName, lowerJsx(sf, plan)); + } + return { sources, refusal: null }; +} + function loadProgram7( host: ts.Ts7Host, entryPath: string, @@ -859,6 +921,26 @@ function loadProgram7( }; program = host.createProgram([...programRoots, overridesDtsPath()], options); } + // JSX: the program above checks the files as written; the program the + // lowering compiles holds them with their JSX lowered. + const jsx = lowerProgramJsx7(program, options); + let tscWorld: LoadResult["tscWorld"]; + if (jsx.refusal !== null) { + config.diags.push(jsx.refusal); + } else if (jsx.sources.size > 0) { + const original = program; + // The project world must read the original text too, so it is built + // before the rewritten files are served, and only when it is needed. + const diagnostics = ts.getPreEmitDiagnostics(original); + const errors = diagnostics.some((d) => d.category === ts.DiagnosticCategory.Error); + tscWorld = { + program: original, + diagnostics, + projectWorld: errors ? host.createProgram(programRoots, options) : null, + }; + for (const [file, lowered] of jsx.sources) host.addVirtualFile(file, lowered.text); + program = host.createProgram([...programRoots, overridesDtsPath()], options); + } const entry = program.getSourceFile(entryPath); if (!entry) throw new Error(`could not load ${entryPath}`); const externalTypeSpecifiersByFile = externalTypeFileClosure7(program, externalTypes); @@ -876,10 +958,14 @@ function loadProgram7( }, externalTypes, externalTypeSpecifiersByFile, + ...(tscWorld === undefined ? {} : { jsxSources: jsx.sources }), + ...(tscWorld === undefined ? {} : { tscWorld }), projectWorld: () => (projectWorld ??= host.createProgram(programRoots, options)), disposeAll: () => { try { projectWorld?.dispose(); + tscWorld?.projectWorld?.dispose(); + tscWorld?.program.dispose(); } finally { program.dispose(); } @@ -4665,8 +4751,8 @@ function preflight7(load: LoadResult): { const sf = p.getSourceFile(d.fileName); return sf !== undefined && isCheckedJsSourceFile(sf, projectCheckJs); }; - const errorsOf = (p: ts.Program): ts.Diagnostic[] => { - const all = ts.getPreEmitDiagnostics(p); + const errorsOf = (p: ts.Program): ts.Diagnostic[] => keptErrors(p, ts.getPreEmitDiagnostics(p)); + const keptErrors = (p: ts.Program, all: readonly ts.Diagnostic[]): ts.Diagnostic[] => { // First pass: every comment-side 2300's (file, name) — the partners // the second pass forgives. const commentDup = new Set(); @@ -4706,9 +4792,39 @@ function preflight7(load: LoadResult): { // instead (the SC1100 checked-cast family). Dirty there → the project- // world errors are the ones reported: they are reproducible with the // project's own tsc, which is what "fix type errors first" asks for. - const tscErrors = errorsOf(program); + // With JSX sources, the program over the original text answers the tsc + // gate; its positions move into the rewritten text the program holds. + // Errors only the rewritten text has come from the calls the JSX lowers + // to (a factory whose signature does not accept them). + const tscWorld = load.tscWorld; + const tscErrors = + tscWorld === undefined ? errorsOf(program) : keptErrors(tscWorld.program, tscWorld.diagnostics); if (tscErrors.length > 0) { - for (const d of errorsOf(load.projectWorld())) diags.push(toPassthrough(d)); + const world = + tscWorld === undefined ? load.projectWorld() : (tscWorld.projectWorld ?? tscWorld.program); + for (const d of errorsOf(world)) { + const diag = toPassthrough(d); + const lowered = tscWorld === undefined ? undefined : load.jsxSources?.get(diag.loc.file); + if (lowered !== undefined) { + diag.loc = { + ...diag.loc, + start: lowered.rewrittenPosition(diag.loc.start, false), + end: lowered.rewrittenPosition(diag.loc.end, true), + }; + } + diags.push(diag); + } + } else if (load.jsxSources !== undefined) { + for (const file of load.jsxSources.keys()) { + const sf = program.getSourceFile(file); + if (sf === undefined) continue; + const own = [...program.getSyntacticDiagnostics(sf), ...program.getSemanticDiagnostics(sf)]; + for (const d of keptErrors(program, own)) { + const diag = toPassthrough(d); + diag.message = `${diag.message} (in the call this JSX lowers to)`; + diags.push(diag); + } + } } // Preflight and lowering share this CheckerFacade. Claim executable diff --git a/packages/compiler/src/frontend/ts7/ast-node.test.ts b/packages/compiler/src/frontend/ts7/ast-node.test.ts index 6b2725b93..8b391e622 100644 --- a/packages/compiler/src/frontend/ts7/ast-node.test.ts +++ b/packages/compiler/src/frontend/ts7/ast-node.test.ts @@ -169,6 +169,30 @@ function ids( return nodes?.map((n) => (n as OracleNode).index); } +test("generated child getters select the child their name selects", () => { + // These getters adapt their raw child; their slot functions are compared instead. + const adapted = ["body", "initializer", "left", "modifiers", "operand", "questionToken"]; + const names = [...new Set(Object.values(childProperties).flat())]; + const lists = (value: unknown): unknown => (value instanceof AstNodeList ? value.nodes : value); + let compared = 0; + for (const { file } of decoded.values()) { + walkPreorder(file.root, (node) => { + const view = node as unknown as Record; + for (const name of names) { + if (adapted.includes(name)) { + const slot = (view[`${name}Slot`] as () => number).call(node); + expect(slot, `${node.kind}.${name}`).toBe(astChildOrder(node.kind, name)); + } else { + expect(lists(view[name]), `${node.kind}.${name}`).toBe(lists(node.child(name))); + } + compared++; + } + return undefined; + }); + } + expect(compared).toBeGreaterThan(100_000); +}); + test("the writeTargets option answers write targets without their wrappers", () => { const { bytes, file: plain } = decoded.get("targets.ts")!; const file = new AstFile(bytes, undefined, { writeTargets: true }); diff --git a/packages/compiler/src/frontend/ts7/ast-node.ts b/packages/compiler/src/frontend/ts7/ast-node.ts index be2745616..92c71aeba 100644 --- a/packages/compiler/src/frontend/ts7/ast-node.ts +++ b/packages/compiler/src/frontend/ts7/ast-node.ts @@ -85,6 +85,8 @@ export class AstFile { private readonly strings = new Map(); private lines: number[] | undefined; private childIndices: Uint32Array | undefined; + /** The root source file's name (AstNode.fileName). */ + private rootFileName: string | undefined; /** Whether nodes answer write targets without their wrappers (see * AstFileOptions.writeTargets). */ @@ -113,7 +115,8 @@ export class AstFile { } node(index: number): AstNode { - if (Object.hasOwn(this.nodes, index)) return this.nodes[index]!; + const existing: AstNode | undefined = this.nodes[index]; + if (existing !== undefined) return existing; if (index === 0 || this.wire.kind(index) === KIND_NODE_LIST) throw new AstDecodeError("expected a node index"); const node = new AstNode(this, index); @@ -140,8 +143,13 @@ export class AstFile { } namedChild(node: AstNode, name: string): number { + return this.namedChildAt(node, astChildOrder(node.kind, name)); + } + + /** The child in wire slot `order` (astChildOrder), or 0 when the slot is + * negative or empty. */ + namedChildAt(node: AstNode, order: number): number { if (node.file !== this) throw new AstDecodeError("named child belongs to another source file"); - const order = astChildOrder(node.kind, name); if (order < 0) return 0; const mask = node.data >>> 30 === 0 ? node.data & 0xff : 0xff; if ((mask & (1 << order)) === 0) return 0; @@ -202,6 +210,15 @@ export class AstFile { return result; } + /** The file name of the source file node at `index`; the root's is + * read once. */ + sourceFileName(index: number): string { + if (index === 1 && this.rootFileName !== undefined) return this.rootFileName; + const name = this.wire.string(this.wire.extendedWord(index, 4)); + if (index === 1) this.rootFileName = name; + return name; + } + lineStarts(): number[] { if (this.lines === undefined) this.lines = astLineStarts(this.root.text ?? ""); return this.lines; @@ -327,6 +344,22 @@ export class AstNode { const index = this.file.namedChild(this, name); return index === 0 ? undefined : this.file.node(index); } + /** childNode by wire slot, as the generated getters select it. */ + childNodeAt(order: number): AstNode | undefined { + const index = this.file.namedChildAt(this, order); + return index === 0 ? undefined : this.file.node(index); + } + childListAt(order: number): AstNodeList | undefined { + const index = this.file.namedChildAt(this, order); + return index === 0 ? undefined : this.file.list(index); + } + childAt(order: number): AstNode | AstNodeList | undefined { + const index = this.file.namedChildAt(this, order); + if (index === 0) return undefined; + return this.file.wire.kind(index) === KIND_NODE_LIST + ? this.file.list(index) + : this.file.node(index); + } childList(name: string): AstNodeList | undefined { const index = this.file.namedChild(this, name); return index === 0 ? undefined : this.file.list(index); @@ -564,18 +597,18 @@ export class AstNode { } get modifierFlags(): number { let result = 0; - for (const modifier of this.childList("modifiers")?.nodes ?? []) + for (const modifier of this.childListAt(this.modifiersSlot())?.nodes ?? []) result |= astModifierFlag(modifier.kind); return result; } get modifiers(): AstModifierList | undefined { - const index = this.file.namedChild(this, "modifiers"); + const index = this.file.namedChildAt(this, this.modifiersSlot()); return index === 0 ? undefined : this.file.modifierList(index); } get body(): AstNode | undefined { - const body = this.childNode("body"); + const body = this.childNodeAt(this.bodySlot()); // TS7 can serialize a reparsed @type callable before a method's // body without setting the type presence bit. The linked Block is // still the real body; keep the JSDoc node out of this view. @@ -597,11 +630,11 @@ export class AstNode { } get questionToken(): AstNode | undefined { - const direct = this.childNode("questionToken"); + const direct = this.childNodeAt(this.questionTokenSlot()); if (direct !== undefined) return direct; // TypeScript 7 shares one postfix slot for optional and definite- // assignment declarations. The familiar helper surface keeps them apart. - const token = this.childNode("postfixToken"); + const token = this.postfixToken; return token?.kind === SyntaxKind.QuestionToken ? token : undefined; } @@ -609,21 +642,21 @@ export class AstNode { // tree; with AstFileOptions.writeTargets these views return the target // without them. get initializer(): AstNode | undefined { - const initializer = this.childNode("initializer"); + const initializer = this.childNodeAt(this.initializerSlot()); return initializer !== undefined && this.file.writeTargets && writesTarget(this, "initializer") ? unwrapTarget(initializer) : initializer; } get left(): AstNode | undefined { - const left = this.childNode("left"); + const left = this.childNodeAt(this.leftSlot()); return left !== undefined && this.file.writeTargets && writesTarget(this, "left") ? unwrapTarget(left) : left; } get operand(): AstNode | undefined { - const operand = this.childNode("operand"); + const operand = this.childNodeAt(this.operandSlot()); return operand !== undefined && this.file.writeTargets && writesTarget(this, "operand") ? unwrapTarget(operand) : operand; @@ -632,281 +665,1173 @@ export class AstNode { // BEGIN GENERATED CHILD GETTERS // Generated from typescript@7.0.2; run scripts/generate-ts7-ast-schema.mjs. get argument(): AstNode | undefined { - return this.childNode("argument"); + switch (this.kind) { + case 206: + return this.childNodeAt(0); + default: + return undefined; + } } get argumentExpression(): AstNode | undefined { - return this.childNode("argumentExpression"); + switch (this.kind) { + case 213: + return this.childNodeAt(2); + default: + return undefined; + } } get arguments(): AstNodeList | undefined { - return this.childList("arguments"); + switch (this.kind) { + case 215: + return this.childListAt(2); + case 214: + return this.childListAt(3); + default: + return undefined; + } } get assertsModifier(): AstNode | undefined { - return this.childNode("assertsModifier"); + switch (this.kind) { + case 183: + return this.childNodeAt(0); + default: + return undefined; + } } get asteriskToken(): AstNode | undefined { - return this.childNode("asteriskToken"); + switch (this.kind) { + case 230: + return this.childNodeAt(0); + case 175: + case 219: + case 263: + return this.childNodeAt(1); + default: + return undefined; + } } get attributes(): AstNode | AstNodeList | undefined { - return this.child("attributes"); + switch (this.kind) { + case 301: + return this.childAt(0); + case 206: + return this.childAt(1); + case 286: + case 287: + return this.childAt(2); + case 273: + case 279: + case 343: + case 346: + return this.childAt(3); + default: + return undefined; + } } get awaitModifier(): AstNode | undefined { - return this.childNode("awaitModifier"); + switch (this.kind) { + case 250: + case 251: + return this.childNodeAt(0); + default: + return undefined; + } } get block(): AstNode | undefined { - return this.childNode("block"); + switch (this.kind) { + case 300: + return this.childNodeAt(1); + default: + return undefined; + } } get caseBlock(): AstNode | undefined { - return this.childNode("caseBlock"); + switch (this.kind) { + case 256: + return this.childNodeAt(1); + default: + return undefined; + } } get catchClause(): AstNode | undefined { - return this.childNode("catchClause"); + switch (this.kind) { + case 259: + return this.childNodeAt(1); + default: + return undefined; + } } get checkType(): AstNode | undefined { - return this.childNode("checkType"); + switch (this.kind) { + case 195: + return this.childNodeAt(0); + default: + return undefined; + } } get children(): AstNode | AstNodeList | undefined { - return this.child("children"); + switch (this.kind) { + case 344: + return this.childAt(0); + case 285: + case 289: + return this.childAt(1); + default: + return undefined; + } } get className(): AstNode | undefined { - return this.childNode("className"); + switch (this.kind) { + case 323: + case 324: + return this.childNodeAt(1); + default: + return undefined; + } } get clauses(): AstNodeList | undefined { - return this.childList("clauses"); + switch (this.kind) { + case 270: + return this.childListAt(0); + default: + return undefined; + } } get closingElement(): AstNode | undefined { - return this.childNode("closingElement"); + switch (this.kind) { + case 285: + return this.childNodeAt(2); + default: + return undefined; + } } get closingFragment(): AstNode | undefined { - return this.childNode("closingFragment"); + switch (this.kind) { + case 289: + return this.childNodeAt(2); + default: + return undefined; + } } get colonToken(): AstNode | undefined { - return this.childNode("colonToken"); + switch (this.kind) { + case 228: + return this.childNodeAt(3); + default: + return undefined; + } } get comment(): AstNodeList | undefined { - return this.childList("comment"); + switch (this.kind) { + case 315: + return this.childListAt(0); + case 322: + case 325: + case 326: + case 327: + case 328: + case 329: + case 330: + return this.childListAt(1); + case 323: + case 324: + case 332: + case 334: + case 335: + case 336: + case 339: + case 341: + case 342: + return this.childListAt(2); + case 331: + case 333: + case 337: + case 338: + case 340: + return this.childListAt(3); + case 343: + return this.childListAt(4); + default: + return undefined; + } } get condition(): AstNode | undefined { - return this.childNode("condition"); + switch (this.kind) { + case 228: + return this.childNodeAt(0); + case 249: + return this.childNodeAt(1); + default: + return undefined; + } } get constraint(): AstNode | undefined { - return this.childNode("constraint"); + switch (this.kind) { + case 337: + return this.childNodeAt(1); + case 169: + return this.childNodeAt(2); + default: + return undefined; + } } get declarationList(): AstNode | undefined { - return this.childNode("declarationList"); + switch (this.kind) { + case 244: + return this.childNodeAt(1); + default: + return undefined; + } } get declarations(): AstNodeList | undefined { - return this.childList("declarations"); + switch (this.kind) { + case 262: + return this.childListAt(0); + default: + return undefined; + } } get defaultType(): AstNode | undefined { - return this.childNode("defaultType"); + switch (this.kind) { + case 169: + return this.childNodeAt(4); + default: + return undefined; + } } get dotDotDotToken(): AstNode | undefined { - return this.childNode("dotDotDotToken"); + switch (this.kind) { + case 203: + case 209: + case 295: + return this.childNodeAt(0); + case 170: + return this.childNodeAt(1); + default: + return undefined; + } } get elementType(): AstNode | undefined { - return this.childNode("elementType"); + switch (this.kind) { + case 189: + return this.childNodeAt(0); + default: + return undefined; + } } get elements(): AstNodeList | undefined { - return this.childList("elements"); + switch (this.kind) { + case 190: + case 207: + case 208: + case 210: + case 276: + case 280: + return this.childListAt(0); + default: + return undefined; + } } get elseStatement(): AstNode | undefined { - return this.childNode("elseStatement"); + switch (this.kind) { + case 246: + return this.childNodeAt(2); + default: + return undefined; + } } get endOfFileToken(): AstNode | undefined { - return this.childNode("endOfFileToken"); + switch (this.kind) { + case 307: + return this.childNodeAt(1); + default: + return undefined; + } } get equalsGreaterThanToken(): AstNode | undefined { - return this.childNode("equalsGreaterThanToken"); + switch (this.kind) { + case 220: + return this.childNodeAt(4); + default: + return undefined; + } } get equalsToken(): AstNode | undefined { - return this.childNode("equalsToken"); + switch (this.kind) { + case 304: + return this.childNodeAt(4); + default: + return undefined; + } } get exclamationToken(): AstNode | undefined { - return this.childNode("exclamationToken"); + switch (this.kind) { + case 261: + return this.childNodeAt(1); + default: + return undefined; + } } get exportClause(): AstNode | undefined { - return this.childNode("exportClause"); + switch (this.kind) { + case 279: + return this.childNodeAt(1); + default: + return undefined; + } } get exprName(): AstNode | undefined { - return this.childNode("exprName"); + switch (this.kind) { + case 187: + return this.childNodeAt(0); + default: + return undefined; + } } get expression(): AstNode | undefined { - return this.childNode("expression"); + switch (this.kind) { + case 168: + case 171: + case 212: + case 213: + case 214: + case 215: + case 218: + case 221: + case 222: + case 223: + case 224: + case 231: + case 234: + case 235: + case 236: + case 239: + case 240: + case 245: + case 246: + case 248: + case 254: + case 255: + case 256: + case 258: + case 284: + case 294: + case 297: + case 298: + case 305: + case 348: + case 349: + return this.childNodeAt(0); + case 217: + case 230: + case 247: + case 295: + return this.childNodeAt(1); + case 250: + case 251: + case 278: + return this.childNodeAt(2); + case 169: + return this.childNodeAt(3); + default: + return undefined; + } } get extendsType(): AstNode | undefined { - return this.childNode("extendsType"); + switch (this.kind) { + case 195: + return this.childNodeAt(1); + default: + return undefined; + } } get falseType(): AstNode | undefined { - return this.childNode("falseType"); + switch (this.kind) { + case 195: + return this.childNodeAt(3); + default: + return undefined; + } } get finallyBlock(): AstNode | undefined { - return this.childNode("finallyBlock"); + switch (this.kind) { + case 259: + return this.childNodeAt(2); + default: + return undefined; + } } get head(): AstNode | undefined { - return this.childNode("head"); + switch (this.kind) { + case 204: + case 229: + return this.childNodeAt(0); + default: + return undefined; + } } get heritageClauses(): AstNodeList | undefined { - return this.childList("heritageClauses"); + switch (this.kind) { + case 232: + case 264: + case 265: + return this.childListAt(3); + default: + return undefined; + } } get importClause(): AstNode | undefined { - return this.childNode("importClause"); + switch (this.kind) { + case 273: + case 343: + case 346: + return this.childNodeAt(1); + default: + return undefined; + } } get incrementor(): AstNode | undefined { - return this.childNode("incrementor"); + switch (this.kind) { + case 249: + return this.childNodeAt(2); + default: + return undefined; + } } get indexType(): AstNode | undefined { - return this.childNode("indexType"); + switch (this.kind) { + case 200: + return this.childNodeAt(1); + default: + return undefined; + } } get jsdocPropertyTags(): AstNode | undefined { - return this.childNode("jsdocPropertyTags"); + switch (this.kind) { + case 317: + return this.childNodeAt(0); + default: + return undefined; + } } get label(): AstNode | undefined { - return this.childNode("label"); + switch (this.kind) { + case 252: + case 253: + case 257: + return this.childNodeAt(0); + default: + return undefined; + } } get literal(): AstNode | undefined { - return this.childNode("literal"); + switch (this.kind) { + case 202: + return this.childNodeAt(0); + case 205: + case 240: + return this.childNodeAt(1); + default: + return undefined; + } } get members(): AstNodeList | undefined { - return this.childList("members"); + switch (this.kind) { + case 188: + return this.childListAt(0); + case 267: + return this.childListAt(2); + case 232: + case 264: + case 265: + return this.childListAt(4); + case 201: + return this.childListAt(5); + default: + return undefined; + } } get moduleReference(): AstNode | undefined { - return this.childNode("moduleReference"); + switch (this.kind) { + case 272: + return this.childNodeAt(2); + default: + return undefined; + } } get moduleSpecifier(): AstNode | undefined { - return this.childNode("moduleSpecifier"); + switch (this.kind) { + case 273: + case 279: + case 343: + case 346: + return this.childNodeAt(2); + default: + return undefined; + } } get name(): AstNode | undefined { - return this.childNode("name"); + switch (this.kind) { + case 237: + case 261: + case 274: + case 275: + case 281: + case 292: + case 302: + case 306: + case 309: + case 319: + case 320: + case 321: + return this.childNodeAt(0); + case 169: + case 172: + case 173: + case 174: + case 178: + case 179: + case 203: + case 232: + case 264: + case 265: + case 266: + case 267: + case 268: + case 271: + case 272: + case 277: + case 282: + case 296: + case 303: + case 304: + case 333: + case 340: + case 345: + return this.childNodeAt(1); + case 170: + case 175: + case 209: + case 212: + case 219: + case 263: + case 331: + case 338: + return this.childNodeAt(2); + default: + return undefined; + } } get nameExpression(): AstNode | undefined { - return this.childNode("nameExpression"); + switch (this.kind) { + case 339: + return this.childNodeAt(1); + default: + return undefined; + } } get nameType(): AstNode | undefined { - return this.childNode("nameType"); + switch (this.kind) { + case 201: + return this.childNodeAt(2); + default: + return undefined; + } } get namedBindings(): AstNode | undefined { - return this.childNode("namedBindings"); + switch (this.kind) { + case 274: + return this.childNodeAt(1); + default: + return undefined; + } } get namespace(): AstNode | undefined { - return this.childNode("namespace"); + switch (this.kind) { + case 296: + return this.childNodeAt(0); + default: + return undefined; + } } get objectAssignmentInitializer(): AstNode | undefined { - return this.childNode("objectAssignmentInitializer"); + switch (this.kind) { + case 304: + return this.childNodeAt(5); + default: + return undefined; + } } get objectType(): AstNode | undefined { - return this.childNode("objectType"); + switch (this.kind) { + case 200: + return this.childNodeAt(0); + default: + return undefined; + } } get openingElement(): AstNode | undefined { - return this.childNode("openingElement"); + switch (this.kind) { + case 285: + return this.childNodeAt(0); + default: + return undefined; + } } get openingFragment(): AstNode | undefined { - return this.childNode("openingFragment"); + switch (this.kind) { + case 289: + return this.childNodeAt(0); + default: + return undefined; + } } get operatorToken(): AstNode | undefined { - return this.childNode("operatorToken"); + switch (this.kind) { + case 227: + return this.childNodeAt(3); + default: + return undefined; + } } get parameterName(): AstNode | undefined { - return this.childNode("parameterName"); + switch (this.kind) { + case 183: + return this.childNodeAt(1); + default: + return undefined; + } } get parameters(): AstNodeList | undefined { - return this.childList("parameters"); + switch (this.kind) { + case 180: + case 181: + case 182: + case 185: + case 318: + return this.childListAt(1); + case 177: + case 186: + case 220: + return this.childListAt(2); + case 178: + case 179: + return this.childListAt(3); + case 174: + case 219: + case 263: + return this.childListAt(4); + case 175: + return this.childListAt(5); + default: + return undefined; + } } get postfixToken(): AstNode | undefined { - return this.childNode("postfixToken"); + switch (this.kind) { + case 172: + case 173: + case 174: + case 303: + case 304: + return this.childNodeAt(2); + case 175: + return this.childNodeAt(3); + default: + return undefined; + } } get properties(): AstNodeList | undefined { - return this.childList("properties"); + switch (this.kind) { + case 211: + case 293: + return this.childListAt(0); + default: + return undefined; + } } get propertyName(): AstNode | undefined { - return this.childNode("propertyName"); + switch (this.kind) { + case 277: + case 282: + return this.childNodeAt(0); + case 209: + return this.childNodeAt(1); + default: + return undefined; + } } get qualifier(): AstNode | undefined { - return this.childNode("qualifier"); + switch (this.kind) { + case 206: + return this.childNodeAt(2); + default: + return undefined; + } } get questionDotToken(): AstNode | undefined { - return this.childNode("questionDotToken"); + switch (this.kind) { + case 212: + case 213: + case 214: + case 216: + return this.childNodeAt(1); + default: + return undefined; + } } get readonlyToken(): AstNode | undefined { - return this.childNode("readonlyToken"); + switch (this.kind) { + case 201: + return this.childNodeAt(0); + default: + return undefined; + } } get right(): AstNode | undefined { - return this.childNode("right"); + switch (this.kind) { + case 167: + return this.childNodeAt(1); + case 227: + return this.childNodeAt(4); + default: + return undefined; + } } get statement(): AstNode | undefined { - return this.childNode("statement"); + switch (this.kind) { + case 247: + return this.childNodeAt(0); + case 248: + case 255: + case 257: + return this.childNodeAt(1); + case 249: + case 250: + case 251: + return this.childNodeAt(3); + default: + return undefined; + } } get statements(): AstNodeList | undefined { - return this.childList("statements"); + switch (this.kind) { + case 242: + case 269: + case 307: + return this.childListAt(0); + case 297: + case 298: + return this.childListAt(1); + default: + return undefined; + } } get tag(): AstNode | undefined { - return this.childNode("tag"); + switch (this.kind) { + case 216: + return this.childNodeAt(0); + default: + return undefined; + } } get tagName(): AstNode | undefined { - return this.childNode("tagName"); + switch (this.kind) { + case 286: + case 287: + case 288: + case 322: + case 323: + case 324: + case 325: + case 326: + case 327: + case 328: + case 329: + case 330: + case 331: + case 332: + case 333: + case 334: + case 335: + case 336: + case 337: + case 338: + case 339: + case 340: + case 341: + case 342: + case 343: + return this.childNodeAt(0); + default: + return undefined; + } } get tags(): AstNodeList | undefined { - return this.childList("tags"); + switch (this.kind) { + case 315: + return this.childListAt(1); + default: + return undefined; + } } get template(): AstNode | undefined { - return this.childNode("template"); + switch (this.kind) { + case 216: + return this.childNodeAt(3); + default: + return undefined; + } } get templateSpans(): AstNodeList | undefined { - return this.childList("templateSpans"); + switch (this.kind) { + case 204: + case 229: + return this.childListAt(1); + default: + return undefined; + } } get thenStatement(): AstNode | undefined { - return this.childNode("thenStatement"); + switch (this.kind) { + case 246: + return this.childNodeAt(1); + default: + return undefined; + } } get thisArg(): AstNode | undefined { - return this.childNode("thisArg"); + switch (this.kind) { + case 349: + return this.childNodeAt(1); + default: + return undefined; + } } get trueType(): AstNode | undefined { - return this.childNode("trueType"); + switch (this.kind) { + case 195: + return this.childNodeAt(2); + default: + return undefined; + } } get tryBlock(): AstNode | undefined { - return this.childNode("tryBlock"); + switch (this.kind) { + case 259: + return this.childNodeAt(0); + default: + return undefined; + } } get tupleNameSource(): AstNode | undefined { - return this.childNode("tupleNameSource"); + switch (this.kind) { + case 238: + return this.childNodeAt(0); + default: + return undefined; + } } get type(): AstNode | undefined { - return this.childNode("type"); + switch (this.kind) { + case 191: + case 192: + case 197: + case 199: + case 205: + case 217: + case 308: + case 311: + case 312: + case 313: + case 314: + return this.childNodeAt(0); + case 235: + case 239: + case 278: + return this.childNodeAt(1); + case 180: + case 181: + case 182: + case 183: + case 185: + case 227: + case 261: + case 318: + return this.childNodeAt(2); + case 172: + case 173: + case 177: + case 186: + case 203: + case 220: + case 266: + case 303: + case 304: + case 345: + return this.childNodeAt(3); + case 170: + case 178: + case 179: + case 201: + return this.childNodeAt(4); + case 174: + case 219: + case 263: + return this.childNodeAt(5); + case 175: + return this.childNodeAt(6); + default: + return undefined; + } } get typeArguments(): AstNodeList | undefined { - return this.childList("typeArguments"); + switch (this.kind) { + case 184: + case 187: + case 215: + case 234: + case 286: + case 287: + return this.childListAt(1); + case 214: + case 216: + return this.childListAt(2); + case 206: + return this.childListAt(3); + default: + return undefined; + } } get typeExpression(): AstNode | undefined { - return this.childNode("typeExpression"); + switch (this.kind) { + case 331: + case 332: + case 334: + case 335: + case 336: + case 338: + case 341: + case 342: + return this.childNodeAt(1); + case 333: + case 340: + return this.childNodeAt(2); + default: + return undefined; + } } get typeName(): AstNode | undefined { - return this.childNode("typeName"); + switch (this.kind) { + case 184: + return this.childNodeAt(0); + default: + return undefined; + } } get typeParameter(): AstNode | undefined { - return this.childNode("typeParameter"); + switch (this.kind) { + case 196: + return this.childNodeAt(0); + case 201: + return this.childNodeAt(1); + default: + return undefined; + } } get typeParameters(): AstNodeList | undefined { - return this.childList("typeParameters"); + switch (this.kind) { + case 180: + case 181: + case 185: + case 318: + return this.childListAt(0); + case 177: + case 186: + case 220: + return this.childListAt(1); + case 178: + case 179: + case 232: + case 264: + case 265: + case 266: + case 337: + case 345: + return this.childListAt(2); + case 174: + case 219: + case 263: + return this.childListAt(3); + case 175: + return this.childListAt(4); + default: + return undefined; + } } get types(): AstNodeList | undefined { - return this.childList("types"); + switch (this.kind) { + case 193: + case 194: + case 299: + return this.childListAt(0); + default: + return undefined; + } } get value(): AstNode | undefined { - return this.childNode("value"); + switch (this.kind) { + case 302: + return this.childNodeAt(1); + default: + return undefined; + } } get variableDeclaration(): AstNode | undefined { - return this.childNode("variableDeclaration"); + switch (this.kind) { + case 300: + return this.childNodeAt(0); + default: + return undefined; + } } get whenFalse(): AstNode | undefined { - return this.childNode("whenFalse"); + switch (this.kind) { + case 228: + return this.childNodeAt(4); + default: + return undefined; + } } get whenTrue(): AstNode | undefined { - return this.childNode("whenTrue"); + switch (this.kind) { + case 228: + return this.childNodeAt(2); + default: + return undefined; + } + } + private bodySlot(): number { + switch (this.kind) { + case 176: + return 1; + case 268: + return 2; + case 177: + return 4; + case 178: + case 179: + case 220: + return 5; + case 219: + case 263: + return 6; + case 175: + return 7; + default: + return -1; + } + } + private initializerSlot(): number { + switch (this.kind) { + case 249: + return 0; + case 250: + case 251: + case 292: + case 306: + return 1; + case 209: + case 261: + return 3; + case 172: + case 173: + case 303: + return 4; + case 170: + return 5; + default: + return -1; + } + } + private leftSlot(): number { + switch (this.kind) { + case 167: + return 0; + case 227: + return 1; + default: + return -1; + } + } + private modifiersSlot(): number { + switch (this.kind) { + case 169: + case 170: + case 172: + case 173: + case 174: + case 175: + case 176: + case 177: + case 178: + case 179: + case 182: + case 186: + case 219: + case 220: + case 227: + case 232: + case 244: + case 263: + case 264: + case 265: + case 266: + case 267: + case 268: + case 271: + case 272: + case 273: + case 278: + case 279: + case 283: + case 303: + case 304: + case 345: + case 346: + return 0; + default: + return -1; + } + } + private operandSlot(): number { + switch (this.kind) { + case 225: + case 226: + return 0; + default: + return -1; + } + } + private questionTokenSlot(): number { + switch (this.kind) { + case 228: + return 1; + case 203: + return 2; + case 170: + case 201: + return 3; + default: + return -1; + } } // END GENERATED CHILD GETTERS // Source-file fields stay on the same nominal class, matching the wire's // single node representation. Their extended-data accesses are checked. get fileName(): string { - return this.file.wire.string(this.file.wire.extendedWord(this.index, 4)); + return this.file.sourceFileName(this.index); } get path(): string { return this.file.wire.string(this.file.wire.extendedWord(this.index, 8)); diff --git a/packages/compiler/src/frontend/ts7/ast-wire.test.ts b/packages/compiler/src/frontend/ts7/ast-wire.test.ts index 03a98a2dc..fd3e611e2 100644 --- a/packages/compiler/src/frontend/ts7/ast-wire.test.ts +++ b/packages/compiler/src/frontend/ts7/ast-wire.test.ts @@ -101,6 +101,30 @@ test("node words respect a byte view's offset, signed spans and unsigned flags", expect(() => file.kind(5)).toThrow(AstDecodeError); }); +test("strings, string offsets and node words read alike at every byte alignment", () => { + const original = response(); + for (let shift = 0; shift < 4; shift++) { + const padded = new Uint8Array(original.length + 8).fill(0xff); + padded.set(original, shift); + const bytes = padded.subarray(shift, shift + original.length); + const file = new AstWireFile(bytes); + expect([file.string(0), file.string(2), file.text(1), file.text(3)]).toEqual([ + "abcfile!", + "file", + "abcfile!", + "file", + ]); + expect([file.kind(3), file.next(3), file.parent(4), file.data(4)]).toEqual([ + AstKind.Identifier, + 4, + 2, + 0x40000002, + ]); + word(bytes, 56, 9); + expect(() => new AstWireFile(bytes)).toThrow("invalid string table offset"); + } +}); + test("truncated headers, sections and node tables are rejected", () => { for (let size = 0; size < HEADER_SIZE; size++) expect(() => new AstWireFile(new Uint8Array(size))).toThrow(AstDecodeError); diff --git a/packages/compiler/src/frontend/ts7/ast-wire.ts b/packages/compiler/src/frontend/ts7/ast-wire.ts index ff70148df..6b2222eae 100644 --- a/packages/compiler/src/frontend/ts7/ast-wire.ts +++ b/packages/compiler/src/frontend/ts7/ast-wire.ts @@ -109,6 +109,20 @@ function invalidNodeIndex(index: number): never { * byte order. */ const LITTLE_ENDIAN = new Uint8Array(new Uint32Array([1]).buffer)[0] === 1; +/** `count` little-endian words of `bytes` from `offset`, which the caller has + * bounds-checked: a view of the response when the words are aligned on a + * little-endian host, a copy of their bytes when they are not, and a decoded + * copy on a big-endian host. Where a section starts depends on the lengths of + * the strings before it (file paths among them), so most files are unaligned. */ +function astWords(bytes: Uint8Array, offset: number, count: number): Uint32Array { + const start = bytes.byteOffset + offset; + if (LITTLE_ENDIAN && start % 4 === 0) return new Uint32Array(bytes.buffer, start, count); + const words = new Uint32Array(count); + if (LITTLE_ENDIAN) new Uint8Array(words.buffer).set(bytes.subarray(offset, offset + count * 4)); + else for (let i = 0; i < count; i++) words[i] = astU32(bytes, offset + i * 4); + return words; +} + function hexWord(value: number): string { const digits = "0123456789abcdef"; let result = ""; @@ -125,14 +139,15 @@ export class AstWireFile { readonly stringCount: number; readonly contentHash: string; readonly parseOptionsKey: string; - private readonly stringOffsets: number; private readonly strings: number; private readonly extended: number; private readonly structured: number; private readonly nodes: number; - /** The node table as 32-bit words: a view of the response when it is - * word-aligned on a little-endian host, otherwise a decoded copy. */ + /** The node table as 32-bit words (astWords). */ private readonly words: Uint32Array; + /** The string table's start and end offsets, two words per string + * (astWords). */ + private readonly stringWords: Uint32Array; /** Decoded strings by string word index / 2. */ private readonly stringCache: (string | undefined)[]; private preorderTree: AstPreorder | null | undefined; @@ -142,34 +157,28 @@ export class AstWireFile { const metadata = astU32(bytes, HEADER_OFFSET_METADATA); if (metadata >>> 24 !== PROTOCOL_VERSION) throw new AstDecodeError(`unsupported protocol version ${metadata >>> 24}`); - this.stringOffsets = astU32(bytes, HEADER_OFFSET_STRING_TABLE_OFFSETS); + const stringOffsets = astU32(bytes, HEADER_OFFSET_STRING_TABLE_OFFSETS); this.strings = astU32(bytes, HEADER_OFFSET_STRING_TABLE); this.extended = astU32(bytes, HEADER_OFFSET_EXTENDED_DATA); this.structured = astU32(bytes, HEADER_OFFSET_STRUCTURED_DATA); this.nodes = astU32(bytes, HEADER_OFFSET_NODES); if ( - this.stringOffsets < HEADER_SIZE || - this.strings < this.stringOffsets || + stringOffsets < HEADER_SIZE || + this.strings < stringOffsets || this.extended < this.strings || this.structured < this.extended || this.nodes < this.structured || this.nodes > bytes.length || - (this.strings - this.stringOffsets) % 8 !== 0 || + (this.strings - stringOffsets) % 8 !== 0 || (this.structured - this.extended) % 4 !== 0 || (bytes.length - this.nodes) % NODE_LEN !== 0 ) { throw new AstDecodeError("invalid section layout"); } this.nodeCount = (bytes.length - this.nodes) / NODE_LEN; - this.stringCount = (this.strings - this.stringOffsets) / 8; - const wordCount = this.nodeCount * NODE_WORDS; - const start = bytes.byteOffset + this.nodes; - if (LITTLE_ENDIAN && start % 4 === 0) { - this.words = new Uint32Array(bytes.buffer, start, wordCount); - } else { - this.words = new Uint32Array(wordCount); - for (let i = 0; i < wordCount; i++) this.words[i] = astU32(bytes, this.nodes + i * 4); - } + this.stringCount = (this.strings - stringOffsets) / 8; + this.words = astWords(bytes, this.nodes, this.nodeCount * NODE_WORDS); + this.stringWords = astWords(bytes, stringOffsets, this.stringCount * 2); this.stringCache = new Array(this.stringCount).fill(undefined); if (this.nodeCount < 2) throw new AstDecodeError("missing root"); if (this.kind(1) === KIND_NODE_LIST || this.parent(1) > 1) @@ -184,8 +193,8 @@ export class AstWireFile { // source text, so pairs overlap and are not globally monotone. Handles // address words (0, 2, 4...), not pair ordinals. for (let i = 0; i < this.stringCount; i++) { - const start = astU32(bytes, this.stringOffsets + i * 8); - const end = astU32(bytes, this.stringOffsets + i * 8 + 4); + const start = this.stringWords[i * 2]!; + const end = this.stringWords[i * 2 + 1]!; if (end < start || end > this.extended - this.strings) throw new AstDecodeError("invalid string table offset"); } @@ -240,12 +249,12 @@ export class AstWireFile { string(index: number): string { if (index >>> 0 !== index || index % 2 !== 0 || index >= this.stringCount * 2) throw new AstDecodeError(`invalid string index ${index}`); - const cached = this.stringCache[index / 2]; + const cached = this.stringCache[index >>> 1]; if (cached !== undefined) return cached; - const start = astU32(this.bytes, this.stringOffsets + index * 4); - const end = astU32(this.bytes, this.stringOffsets + (index + 1) * 4); + const start = this.stringWords[index]!; + const end = this.stringWords[index + 1]!; const text = decodeAstString(this.bytes, this.strings + start, end - start); - this.stringCache[index / 2] = text; + this.stringCache[index >>> 1] = text; return text; } diff --git a/packages/compiler/src/frontend/ts7/ast.ts b/packages/compiler/src/frontend/ts7/ast.ts index 369213d89..0bddd1a80 100644 --- a/packages/compiler/src/frontend/ts7/ast.ts +++ b/packages/compiler/src/frontend/ts7/ast.ts @@ -47,8 +47,9 @@ import { } from "./ast-guards.generated.js"; import type { Ts7DiagnosticData as Diagnostic } from "./session-schema.generated.js"; import { ModifierFlags, SyntaxKind } from "./enums.js"; -import { AstKind } from "./ast-schema.generated.js"; +import { AstKind, KIND_NODE_LIST } from "./ast-schema.generated.js"; import { PREORDER_LIST } from "./ast-wire.js"; +import { tokenStartOfNode } from "./node-functions.js"; /* ---- everything 7 kept under the same name ---- */ @@ -196,6 +197,93 @@ function walkLinkedPreorder( } } +/** The semantic children of a wire node: list items stand in for their + * list, and attached JSDoc trees are left out (the walkPreorder view). */ +function semanticChildIndices(root: Node, index: number, out: number[]): void { + const wire = root.file.wire; + for (let child = wire.firstChild(index); child !== 0; child = wire.next(child)) { + const kind = wire.kind(child); + if (kind === KIND_NODE_LIST) { + for (let item = wire.firstChild(child); item !== 0; item = wire.next(item)) out.push(item); + } else if (kind !== AstKind.JSDoc) out.push(child); + } +} + +/** The outermost node of `sourceFile` whose token span is exactly + * [start, end), or undefined. Only nodes ending at `end` are + * materialized. */ +export function nodeAtSpan(sourceFile: SourceFile, start: number, end: number): Node | undefined { + const wire = sourceFile.file.wire; + const children: number[] = []; + let index = sourceFile.index; + for (;;) { + children.length = 0; + semanticChildIndices(sourceFile, index, children); + let next = 0; + for (const child of children) { + if (wire.pos(child) > start || wire.end(child) < end) continue; + if (wire.end(child) === end) { + const node = sourceFile.file.node(child); + if (tokenStartOfNode(node) === start) return node; + } + next = child; + break; + } + if (next === 0) return undefined; + index = next; + } +} + +/** The name of the declaration at wire `index` in `root`'s file when its + * kind is in `kinds`: its identifier, private identifier or string literal + * name, "constructor" for a constructor, or null. Reads the wire without + * materializing nodes. */ +export function declarationNameAt( + root: Node, + index: number, + kinds: ReadonlySet, +): string | null { + const wire = root.file.wire; + const kind = wire.kind(index); + if (!kinds.has(kind)) return null; + if (kind === SyntaxKind.Constructor) return "constructor"; + const name = wire.namedChild(index, "name"); + if (name === 0) return null; + const nameKind = wire.kind(name); + if ( + nameKind !== SyntaxKind.Identifier && + nameKind !== SyntaxKind.PrivateIdentifier && + nameKind !== SyntaxKind.StringLiteral + ) + return null; + return wire.text(name) ?? null; +} + +/** The indices, in preorder, of the nodes below `root` that have `key` and + * are not inside a nested named declaration (declarationNameAt with + * `kinds`). A named declaration is keyed `:` and its subtree is + * not visited; other nodes are keyed by their kind. No node is + * materialized. */ +export function anchoredNodes(root: Node, key: string, kinds: ReadonlySet): number[] { + const wire = root.file.wire; + const out: number[] = []; + const children: number[] = []; + const stack: number[] = []; + semanticChildIndices(root, root.index, children); + for (let i = children.length - 1; i >= 0; i--) stack.push(children[i]!); + while (stack.length > 0) { + const index = stack.pop()!; + const kind = wire.kind(index); + const name = declarationNameAt(root, index, kinds); + if ((name === null ? String(kind) : `${kind}:${name}`) === key) out.push(index); + if (name !== null) continue; + children.length = 0; + semanticChildIndices(root, index, children); + for (let i = children.length - 1; i >= 0; i--) stack.push(children[i]!); + } + return out; +} + export function getLineAndCharacterOfPosition( sourceFile: SourceFile, position: number, diff --git a/packages/compiler/src/frontend/ts7/checker.test.ts b/packages/compiler/src/frontend/ts7/checker.test.ts index ac062b283..cb4a2e5fb 100644 --- a/packages/compiler/src/frontend/ts7/checker.test.ts +++ b/packages/compiler/src/frontend/ts7/checker.test.ts @@ -283,8 +283,9 @@ test("negative assignability answers remain independent in both directions", () requests.push(query); return JSON.stringify(query.source === 1 && query.target === 2); }, - binary: () => { - throw new Error("unexpected binary request"); + // Object replies are read as bytes; they carry the same JSON. + binary(method, payload) { + return Buffer.from(this.text(method, payload), "utf8"); }, }); const project = snapshot.addProject("project", () => undefined); @@ -324,8 +325,9 @@ test("property lookup caches hits and misses by type and name within each projec checkFlags: 0, }); }, - binary: () => { - throw new Error("unexpected binary request"); + // Object replies are read as bytes; they carry the same JSON. + binary(method, payload) { + return Buffer.from(this.text(method, payload), "utf8"); }, }); const first = snapshot.addProject("first", () => undefined); @@ -397,8 +399,9 @@ test("member type batches are bounded, reuse warm entries, and isolate absent or if (ids.includes(7)) throw new Error("checker panic"); return JSON.stringify(ids.map((id) => (id === 11 ? null : { id, flags: TypeFlags.Number }))); }, - binary: () => { - throw new Error("unexpected binary query"); + // Object replies are read as bytes; they carry the same JSON. + binary(method, payload) { + return Buffer.from(this.text(method, payload), "utf8"); }, }); const project = snapshot.addProject("members", () => undefined); diff --git a/packages/compiler/src/frontend/ts7/checker.ts b/packages/compiler/src/frontend/ts7/checker.ts index 4f2d60294..9550d1dc2 100644 --- a/packages/compiler/src/frontend/ts7/checker.ts +++ b/packages/compiler/src/frontend/ts7/checker.ts @@ -45,7 +45,7 @@ import type { TypePredicate, TypeReference, } from "./semantic-types.js"; -import type { SemanticChecker as Checker } from "./semantic-checker.js"; +import { NODE_BATCH_QUERIES, type SemanticChecker as Checker } from "./semantic-checker.js"; import { symbolNameOf, type SemanticProject as Project } from "./semantic-model.js"; import { isTypeNode, walkPreorder } from "./ast.js"; import { SignatureKind, SyntaxKind, TypeFlags, type SymbolFlags } from "./enums.js"; @@ -79,6 +79,44 @@ function withPanicFence( } } +/** Answers for `items` in chunks, each answer given to `store`. A chunk + * that throws is split until the throwing items are alone; those get no + * answer, so their direct query throws again where it is made. */ +function batchAnswers( + items: readonly I[], + fetch: (chunk: readonly I[]) => readonly (O | undefined)[], + store: (item: I, answer: O | undefined) => void, + unknown: (error: unknown) => boolean = () => false, +): boolean { + let known = true; + const answer = (chunk: readonly I[]): void => { + if (!known) return; + let answers: readonly (O | undefined)[]; + try { + answers = fetch(chunk); + } catch (error) { + if (unknown(error)) { + known = false; + return; + } + if (chunk.length === 1) return; + const mid = chunk.length >> 1; + answer(chunk.slice(0, mid)); + answer(chunk.slice(mid)); + return; + } + chunk.forEach((item, index) => store(item, answers[index])); + }; + for (let i = 0; i < items.length; i += BATCH_CHUNK) answer(items.slice(i, i + BATCH_CHUNK)); + return known; +} + +/** Whether a request failed because the server has no such method: tsgo, + * and tsc-ts before 0.0.7, answer the batch methods this way. */ +function unknownMethod(error: unknown, method: string): boolean { + return error instanceof Error && error.message.includes(`unknown API method "${method}"`); +} + function chunked(items: readonly T[], fetch: (chunk: readonly T[]) => readonly R[]): R[] { const out: R[] = []; for (let i = 0; i < items.length; i += BATCH_CHUNK) { @@ -215,6 +253,9 @@ function collectNodes(roots: readonly Node[], walk: PrefetchWalk = "all"): Node[ export class CheckerFacade { private readonly cache = new CheckerCache(); + /** Batch methods the server answered as unknown. Lowering asks those + * node by node from then on, without a failed request per prefetch. */ + private readonly unknownBatchMethods = new Set(); constructor( /** The underlying 7.0.2 sync checker — exposed for methods the facade @@ -322,7 +363,66 @@ export class CheckerFacade { prefetchRoots(roots: readonly Node[]): void { this.ensureActive(); this.markManaged(roots); - this.prefetchNodes(collectNodes(roots, "reachable")); + const nodes = collectNodes(roots, "reachable"); + this.prefetchNodes(nodes); + if (!NODE_BATCH_QUERIES) return; + // Lowering a call resolves its signature (reconcileOverloadReturn). + this.prefetchResolvedSignatures( + nodes.filter( + (node) => + node.kind === SyntaxKind.CallExpression || + node.kind === SyntaxKind.TaggedTemplateExpression, + ), + ); + // Lowering an array literal or a conditional asks its contextual type. + this.prefetchContextualTypes( + nodes.filter( + (node) => + node.kind === SyntaxKind.ArrayLiteralExpression || + node.kind === SyntaxKind.ConditionalExpression, + ), + ); + } + + /** Batches the contextual type of each node, for an analysis that asks it + * of many nodes (class-protocols.ts). A query that fails stays out of the + * memo, so a later getContextualType asks again as it would have. */ + prefetchContextualTypes(nodes: readonly Node[]): void { + if (!NODE_BATCH_QUERIES) return; + this.ensureActive(); + const missing = [...new Set(nodes)].filter((node) => !this.cache.contextualType.has(node)); + this.batchNodes( + "getContextualTypes", + missing, + (chunk) => this.raw.getContextualTypes(chunk), + (node, type) => this.cache.contextualType.set(node, type), + ); + } + + /** Batches the resolved signature of each call (getResolvedSignature). */ + prefetchResolvedSignatures(nodes: readonly Node[]): void { + if (!NODE_BATCH_QUERIES) return; + this.ensureActive(); + const missing = [...new Set(nodes)].filter((node) => !this.cache.resolvedSignature.has(node)); + this.batchNodes( + "getResolvedSignatures", + missing, + (chunk) => this.raw.getResolvedSignatures(chunk), + (node, signature) => this.cache.resolvedSignature.set(node, signature), + ); + } + + /** Answers a node batch method's chunks (batchAnswers), unless the server + * has answered the method as unknown. */ + private batchNodes( + method: string, + nodes: readonly Node[], + fetch: (chunk: readonly Node[]) => readonly (O | undefined)[], + store: (node: Node, answer: O | undefined) => void, + ): void { + if (nodes.length === 0 || this.unknownBatchMethods.has(method)) return; + if (!batchAnswers(nodes, fetch, store, (error) => unknownMethod(error, method))) + this.unknownBatchMethods.add(method); } /** Batches symbol queries for every identifier under roots without the diff --git a/packages/compiler/src/frontend/ts7/enums.generated.ts b/packages/compiler/src/frontend/ts7/enums.generated.ts index f21134bb6..4551ab428 100644 --- a/packages/compiler/src/frontend/ts7/enums.generated.ts +++ b/packages/compiler/src/frontend/ts7/enums.generated.ts @@ -1315,3 +1315,25 @@ export enum LanguageVariant { Standard = 0, JSX = 1 } + +export enum JsxEmit { + None = 0, + Preserve = 1, + ReactNative = 2, + React = 3, + ReactJSX = 4, + ReactJSXDev = 5 +} + +/** Numeric lookup with the SDK's aliases and undefined for unknown values. */ +export function jsxEmitName(value: number): string | undefined { + switch (value) { + case 0: return "None"; + case 1: return "Preserve"; + case 2: return "ReactNative"; + case 3: return "React"; + case 4: return "ReactJSX"; + case 5: return "ReactJSXDev"; + default: return undefined; + } +} diff --git a/packages/compiler/src/frontend/ts7/enums.ts b/packages/compiler/src/frontend/ts7/enums.ts index 6eba358f2..844643e80 100644 --- a/packages/compiler/src/frontend/ts7/enums.ts +++ b/packages/compiler/src/frontend/ts7/enums.ts @@ -1,4 +1,25 @@ /** Runtime enums generated from the pinned TypeScript 7 declarations. * Their nominal names and values match the SDK; TypeScript 5 remains a * separate world. No package loader runs on the compiler's native path. */ +import { jsxEmitName } from "./enums.generated.js"; + export * from "./enums.generated.js"; + +/** The tsconfig spelling of a `jsx` option value: "preserve", "react-native", + * "react", "react-jsx" or "react-jsxdev". */ +export function jsxOptionName(value: number): string | undefined { + switch (jsxEmitName(value)) { + case "Preserve": + return "preserve"; + case "ReactNative": + return "react-native"; + case "React": + return "react"; + case "ReactJSX": + return "react-jsx"; + case "ReactJSXDev": + return "react-jsxdev"; + default: + return undefined; + } +} diff --git a/packages/compiler/src/frontend/ts7/program-host.ts b/packages/compiler/src/frontend/ts7/program-host.ts index cc867d208..639086e94 100644 --- a/packages/compiler/src/frontend/ts7/program-host.ts +++ b/packages/compiler/src/frontend/ts7/program-host.ts @@ -30,6 +30,7 @@ import type { } from "./session.js"; import { CheckerFacade } from "./checker.js"; import { + jsxOptionName, moduleDetectionKindName, moduleKindName, moduleResolutionKindName, @@ -82,6 +83,9 @@ function serializeOptions(options: Ts7CompilerOptions): Record case "moduleDetection": out[key] = moduleDetectionKindName(value as number)?.toLowerCase() ?? value; break; + case "jsx": + out[key] = typeof value === "number" ? (jsxOptionName(value) ?? value) : value; + break; case "lib": // 5.9.3 spells lib entries "lib.es2025.d.ts"; tsconfig wants "es2025". out[key] = (value as string[]).map((lib) => @@ -188,7 +192,10 @@ export class Ts7Host { const key = tsgoPath(path); if (this.virtualFiles.get(key) === content) return; if (!this.virtualChanges.has(key)) - this.virtualChanges.set(key, this.virtualFiles.has(key) ? "changed" : "created"); + this.virtualChanges.set( + key, + this.virtualFiles.has(key) || trackedFileExists(path) ? "changed" : "created", + ); this.virtualFiles.set(key, content); } diff --git a/packages/compiler/src/frontend/ts7/semantic-checker.ts b/packages/compiler/src/frontend/ts7/semantic-checker.ts index 92aa77333..c19f93598 100644 --- a/packages/compiler/src/frontend/ts7/semantic-checker.ts +++ b/packages/compiler/src/frontend/ts7/semantic-checker.ts @@ -1,9 +1,7 @@ import type { SemanticIndexInfoData as IndexInfoResponse, - SemanticSignatureData as SignatureResponse, SemanticSymbolData as SymbolResponse, SemanticTypePredicateData as TypePredicateResponse, - SemanticTypeData as TypeResponse, } from "./semantic-schema.generated.js"; import { AstFile, AstNode } from "./ast-node.js"; import { @@ -14,6 +12,7 @@ import { SemanticType, type SemanticDocument, type SemanticQuery, + present, } from "./semantic-model.js"; import { SemanticSymbolFlags } from "./semantic-schema.generated.js"; import type { TypePredicateKind } from "./enums.generated.js"; @@ -97,6 +96,13 @@ export interface SemanticCompletion { symbol: SemanticSymbol | undefined; } +/** Whether lowering asks the checker for contextual types and resolved + * signatures in batches (`getContextualTypes`, `getResolvedSignatures`, + * answered from tsc-ts 0.0.7 on). Off, the batch prefetches (checker.ts) do + * nothing and lowering asks node by node. A server without a batch method + * (tsgo) answers it as unknown once, and the facade stops asking. */ +export const NODE_BATCH_QUERIES = true; + /** The pinned checker's request surface over native objects. Every query * converges on the same snapshot/project registries, including batch and * lazy-object queries. No SDK object is constructed or consulted here. */ @@ -106,32 +112,25 @@ export class SemanticChecker { constructor(readonly project: SemanticProject) {} private type(method: string, query: SemanticQuery): SemanticType | undefined { - const data = this.project.request(method, query); - return data === null ? undefined : this.project.type(data); + return this.project.requestType(method, query); } private symbol(method: string, query: SemanticQuery): SemanticSymbol | undefined { - const data = this.project.request(method, query); - return data === null ? undefined : this.project.symbol(data); + return this.project.requestSymbol(method, query); } private signature(method: string, query: SemanticQuery): SemanticSignature | undefined { - const data = this.project.request(method, query); - return data === null ? undefined : this.project.signature(data); + return this.project.requestSignature(method, query); } private types(method: string, query: SemanticQuery): SemanticType[] { - const data = this.project.request(method, query); - return (data ?? []).map((item) => this.project.type(item)); + return present(this.project.requestTypes(method, query), method); } private symbols(method: string, query: SemanticQuery): SemanticSymbol[] { - const data = this.project.request(method, query); - return (data ?? []).map((item) => this.project.symbol(item)); + return present(this.project.requestSymbols(method, query), method); } private optionalTypes(method: string, query: SemanticQuery): (SemanticType | undefined)[] { - const data = this.project.request<(TypeResponse | null)[]>(method, query); - return data.map((item) => (item === null ? undefined : this.project.type(item))); + return this.project.requestTypes(method, query); } private optionalSymbols(method: string, query: SemanticQuery): (SemanticSymbol | undefined)[] { - const data = this.project.request<(SymbolResponse | null)[]>(method, query); - return data.map((item) => (item === null ? undefined : this.project.symbol(item))); + return this.project.requestSymbols(method, query); } getTypeAtLocation(node: AstNode): SemanticType | undefined; @@ -209,6 +208,10 @@ export class SemanticChecker { getContextualType(node: AstNode): SemanticType | undefined { return this.type("getContextualType", { location: node.id }); } + /** getContextualType for each node. */ + getContextualTypes(nodes: readonly AstNode[]): (SemanticType | undefined)[] { + return this.optionalTypes("getContextualTypes", { locations: nodes.map((node) => node.id) }); + } getTypeFromTypeNode(node: AstNode): SemanticType | undefined { return this.type("getTypeFromTypeNode", { location: node.id }); } @@ -221,6 +224,12 @@ export class SemanticChecker { getResolvedSignature(node: AstNode): SemanticSignature | undefined { return this.signature("getResolvedSignature", { location: node.id }); } + /** getResolvedSignature for each node. */ + getResolvedSignatures(nodes: readonly AstNode[]): (SemanticSignature | undefined)[] { + return this.project.requestSignatures("getResolvedSignatures", { + locations: nodes.map((node) => node.id), + }); + } getSignatureFromDeclaration(node: AstNode): SemanticSignature | undefined { return this.signature("getSignatureFromDeclaration", { location: node.id }); } @@ -375,11 +384,10 @@ export class SemanticChecker { ); } getSignaturesOfType(type: SemanticType, kind: number): SemanticSignature[] { - const data = this.project.request("getSignaturesOfType", { - type: type.id, - kind, - }); - return data.map((item) => this.project.signature(item)); + return present( + this.project.requestSignatures("getSignaturesOfType", { type: type.id, kind }), + "getSignaturesOfType", + ); } getTypePredicateOfSignature(signature: SemanticSignature): SemanticTypePredicate | undefined { const data = this.project.request("getTypePredicateOfSignature", { diff --git a/packages/compiler/src/frontend/ts7/semantic-json.test.ts b/packages/compiler/src/frontend/ts7/semantic-json.test.ts index d3b8c4ae3..95bf220f2 100644 --- a/packages/compiler/src/frontend/ts7/semantic-json.test.ts +++ b/packages/compiler/src/frontend/ts7/semantic-json.test.ts @@ -1,5 +1,10 @@ import { expect, test } from "vitest"; -import { checkSemanticJsonStrings, parseSemanticJson } from "./semantic-json.js"; +import { + checkSemanticJsonStrings, + decodeSemanticObject, + decodeSemanticObjects, + parseSemanticJson, +} from "./semantic-json.js"; test("semantic JSON preserves ordinary strings, escaped slashes, quotes, pairs and nulls", () => { const values = [ @@ -57,3 +62,75 @@ test("malformed JSON remains a parse error rather than an accepted response", () expect(() => parseSemanticJson(json)).toThrow(SyntaxError); } }); + +const replyBytes = (json: string): Uint8Array => Buffer.from(json, "utf8"); + +test("semantic object replies resolve held ids without decoding them and decode the rest", () => { + const held = new Map([[7, { from: "held", id: 7 }]]); + const built: unknown[] = []; + const build = (data: { id: number }) => { + built.push(data); + return { from: "built", id: data.id }; + }; + const reply = JSON.stringify([ + { id: 7, name: "held {not} [read]", declarations: ["1.2./a.ts"] }, + null, + { id: 8, name: 'a "quoted" \\ name ]}', nested: { id: 1, list: [1, { x: "}" }] } }, + { name: "id last", id: 9 }, + ]); + expect(decodeSemanticObjects(replyBytes(reply), (id) => held.get(id), build)).toEqual([ + { from: "held", id: 7 }, + null, + { from: "built", id: 8 }, + { from: "built", id: 9 }, + ]); + expect(built).toEqual([JSON.parse(reply)[2], JSON.parse(reply)[3]]); + // The text of a held object is not decoded. + expect( + decodeSemanticObjects( + replyBytes('[{"id":7,"bad":\\ud800}, {"id":7}]'), + (id) => held.get(id), + build, + ), + ).toEqual([ + { from: "held", id: 7 }, + { from: "held", id: 7 }, + ]); +}); + +test("semantic object replies accept null, empty and single replies", () => { + const build = (data: { id: number }) => data.id; + const none = (): number | undefined => undefined; + expect(decodeSemanticObjects(replyBytes(""), none, build)).toBeNull(); + expect(decodeSemanticObjects(replyBytes("null"), none, build)).toBeNull(); + expect(decodeSemanticObjects(replyBytes(" [ ] "), none, build)).toEqual([]); + expect(decodeSemanticObjects(replyBytes('[{"id":3},\n{"id":4}]'), none, build)).toEqual([3, 4]); + expect(decodeSemanticObject(replyBytes(""), none, build)).toBeNull(); + expect(decodeSemanticObject(replyBytes("null"), none, build)).toBeNull(); + expect(decodeSemanticObject(replyBytes('{"id":12,"name":"x"}'), none, build)).toBe(12); + expect(decodeSemanticObject(replyBytes('{"id":12}'), (id) => id * 2, build)).toBe(24); + // Non-ASCII text in a decoded object round-trips. + expect( + decodeSemanticObject( + replyBytes(JSON.stringify({ id: 5, name: "héllo 🌍" })), + (): string | undefined => undefined, + (data: { id: number; name: string }) => data.name, + ), + ).toBe("héllo 🌍"); +}); + +test("semantic object replies reject malformed JSON", () => { + const build = (data: { id: number }) => data.id; + const none = (): number | undefined => undefined; + for (const json of [ + '[{"id":1}', + '[{"id":1},]', + '{"id":1} {"id":2}', + '[{"id":1} {"id":2}]', + '"open', + "nul", + ]) + expect(() => decodeSemanticObjects(replyBytes(json), none, build)).toThrow(); + for (const json of ['{"id":1', '{"id":1}}', "nul"]) + expect(() => decodeSemanticObject(replyBytes(json), none, build)).toThrow(); +}); diff --git a/packages/compiler/src/frontend/ts7/semantic-json.ts b/packages/compiler/src/frontend/ts7/semantic-json.ts index 32456c95a..3a04c741f 100644 --- a/packages/compiler/src/frontend/ts7/semantic-json.ts +++ b/packages/compiler/src/frontend/ts7/semantic-json.ts @@ -49,3 +49,156 @@ export function parseSemanticJson(json: string): T { checkSemanticJsonStrings(json, preservesJsonSurrogates); return JSON.parse(json) as T; } + +const OPEN_BRACE = 0x7b; +const CLOSE_BRACE = 0x7d; +const OPEN_BRACKET = 0x5b; +const CLOSE_BRACKET = 0x5d; +const QUOTE = 0x22; +const BACKSLASH = 0x5c; +const COMMA = 0x2c; +const LOWER_N = 0x6e; +/** `{"id":`, the start of every object reply the checker sends. */ +const ID_PREFIX = [OPEN_BRACE, QUOTE, 0x69, 0x64, QUOTE, 0x3a]; + +function isJsonSpace(byte: number): boolean { + return byte === 0x20 || byte === 0x0a || byte === 0x0d || byte === 0x09; +} + +function skipJsonSpace(bytes: Uint8Array, index: number): number { + while (index < bytes.length && isJsonSpace(bytes[index]!)) index++; + return index; +} + +function malformedReply(): never { + throw new Error("TypeScript semantic response: malformed JSON"); +} + +/** The index after the JSON value that starts at `start`: an object, an + * array, a string or a bare literal. Strings are skipped with their escapes, + * so brackets inside them do not count. */ +function jsonValueEnd(bytes: Uint8Array, start: number): number { + let depth = 0; + let index = start; + while (index < bytes.length) { + const byte = bytes[index]!; + if (byte === QUOTE) { + index++; + while (index < bytes.length && bytes[index] !== QUOTE) + index += bytes[index] === BACKSLASH ? 2 : 1; + if (index >= bytes.length) malformedReply(); + index++; + if (depth === 0) return index; + continue; + } + if (byte === OPEN_BRACE || byte === OPEN_BRACKET) depth++; + else if (byte === CLOSE_BRACE || byte === CLOSE_BRACKET) { + if (depth === 0) return index; + depth--; + if (depth === 0) return index + 1; + } else if (depth === 0 && (byte === COMMA || isJsonSpace(byte))) return index; + index++; + } + if (depth !== 0) malformedReply(); + return index; +} + +/** The id an object reply starts with (`{"id":N`), or -1 when it starts + * otherwise. */ +function leadingId(bytes: Uint8Array, start: number, end: number): number { + if (end - start < ID_PREFIX.length + 1) return -1; + for (let k = 0; k < ID_PREFIX.length; k++) if (bytes[start + k] !== ID_PREFIX[k]) return -1; + let index = start + ID_PREFIX.length; + let id = 0; + let digits = 0; + while (index < end && bytes[index]! >= 0x30 && bytes[index]! <= 0x39) { + id = id * 10 + (bytes[index]! - 0x30); + index++; + digits++; + } + if (digits === 0 || digits > 15 || (bytes[index] !== COMMA && bytes[index] !== CLOSE_BRACE)) + return -1; + return id; +} + +function parseJsonSlice(bytes: Uint8Array, start: number, end: number): T { + const text = Buffer.from(bytes.buffer, bytes.byteOffset + start, end - start).toString("utf8"); + return parseSemanticJson(text); +} + +/** One element of a reply: null, or the object with leading id `id`. Objects + * the caller already holds under that id are not decoded. */ +function replyElement( + bytes: Uint8Array, + start: number, + end: number, + cached: (id: number) => R | undefined, + build: (data: T) => R, +): R | null { + if (bytes[start] === LOWER_N) { + if (parseJsonSlice(bytes, start, end) !== null) malformedReply(); + return null; + } + const id = leadingId(bytes, start, end); + if (id >= 0) { + const known = cached(id); + if (known !== undefined) return known; + } + return build(parseJsonSlice(bytes, start, end)); +} + +/** A checker reply that is one object (with a numeric `id`) or null. An empty + * reply is null. Objects the caller already holds under their id, which a + * reply repeats whenever it names them, are returned from `cached` without + * decoding their text; the rest are decoded and handed to `build`. */ +export function decodeSemanticObject( + bytes: Uint8Array, + cached: (id: number) => R | undefined, + build: (data: T) => R, +): R | null { + const start = skipJsonSpace(bytes, 0); + if (start === bytes.length) return null; + const end = jsonValueEnd(bytes, start); + if (skipJsonSpace(bytes, end) !== bytes.length) malformedReply(); + return replyElement(bytes, start, end, cached, build); +} + +/** A checker reply that is an array of objects (each with a numeric `id`) and + * nulls, or null. An empty reply is null. Elements are resolved as in + * decodeSemanticObject. */ +export function decodeSemanticObjects( + bytes: Uint8Array, + cached: (id: number) => R | undefined, + build: (data: T) => R, +): (R | null)[] | null { + let index = skipJsonSpace(bytes, 0); + if (index === bytes.length) return null; + if (bytes[index] !== OPEN_BRACKET) { + const end = jsonValueEnd(bytes, index); + if ( + skipJsonSpace(bytes, end) !== bytes.length || + parseJsonSlice(bytes, index, end) !== null + ) + malformedReply(); + return null; + } + const result: (R | null)[] = []; + index = skipJsonSpace(bytes, index + 1); + if (bytes[index] === CLOSE_BRACKET) { + if (skipJsonSpace(bytes, index + 1) !== bytes.length) malformedReply(); + return result; + } + for (;;) { + const end = jsonValueEnd(bytes, index); + if (end === index) malformedReply(); + result.push(replyElement(bytes, index, end, cached, build)); + index = skipJsonSpace(bytes, end); + if (bytes[index] === COMMA) { + index = skipJsonSpace(bytes, index + 1); + continue; + } + if (bytes[index] !== CLOSE_BRACKET || skipJsonSpace(bytes, index + 1) !== bytes.length) + malformedReply(); + return result; + } +} diff --git a/packages/compiler/src/frontend/ts7/semantic-model.test.ts b/packages/compiler/src/frontend/ts7/semantic-model.test.ts index 36a445bc8..9d0f61a4e 100644 --- a/packages/compiler/src/frontend/ts7/semantic-model.test.ts +++ b/packages/compiler/src/frontend/ts7/semantic-model.test.ts @@ -45,8 +45,9 @@ function harness() { if (!answers.has(method)) throw new Error(`Unexpected request ${method}`); return JSON.stringify(answers.get(method)); }, - binary() { - throw new Error("Unexpected binary request"); + // Object replies are read as bytes; they carry the same JSON. + binary(method, payload) { + return Buffer.from(this.text(method, payload), "utf8"); }, }); const first = snapshot.addProject("/first.json", () => undefined); diff --git a/packages/compiler/src/frontend/ts7/semantic-model.ts b/packages/compiler/src/frontend/ts7/semantic-model.ts index 125e324c7..d3d5fe61a 100644 --- a/packages/compiler/src/frontend/ts7/semantic-model.ts +++ b/packages/compiler/src/frontend/ts7/semantic-model.ts @@ -8,7 +8,7 @@ import type { __String } from "./ast-types.js"; import type * as enums from "./enums.generated.js"; import { parseAstNodeHandle } from "./ast-wire.js"; import type { SemanticChecker, SemanticJsDocTag } from "./semantic-checker.js"; -import { parseSemanticJson } from "./semantic-json.js"; +import { decodeSemanticObject, decodeSemanticObjects, parseSemanticJson } from "./semantic-json.js"; import { SemanticObjectFlags as ObjectFlags, SemanticSignatureFlags as SignatureFlags, @@ -17,6 +17,14 @@ import { /** JSON and binary operations stay at the transport boundary. The concrete * semantic objects below need neither the SDK nor a JavaScript engine. */ +/** The elements of a reply that has no nulls: a null element fails as it + * would when read as an object. */ +export function present(items: (T | undefined)[], method: string): T[] { + for (const item of items) + if (item === undefined) throw new TypeError(`${method} returned a null element`); + return items as T[]; +} + export interface SemanticTransport { text: (method: string, payload: string) => string; binary: (method: string, payload: string) => Uint8Array; @@ -154,6 +162,54 @@ export class SemanticProject { return this.snapshot.transport.binary(method, JSON.stringify(query)); } + /** A reply of one type, or undefined for null. */ + requestType(method: string, query: SemanticQuery): SemanticType | undefined { + const bytes = this.requestBinary(method, query); + const cached = (id: number): SemanticType | undefined => this.types.get(id); + const build = (data: TypeResponse): SemanticType => this.type(data); + return decodeSemanticObject(bytes, cached, build) ?? undefined; + } + + /** A reply of types and nulls (undefined here), or [] for null. */ + requestTypes(method: string, query: SemanticQuery): (SemanticType | undefined)[] { + const bytes = this.requestBinary(method, query); + const cached = (id: number): SemanticType | undefined => this.types.get(id); + const build = (data: TypeResponse): SemanticType => this.type(data); + return (decodeSemanticObjects(bytes, cached, build) ?? []).map((item) => item ?? undefined); + } + + /** A reply of one symbol, or undefined for null. */ + requestSymbol(method: string, query: SemanticQuery): SemanticSymbol | undefined { + const bytes = this.requestBinary(method, query); + const cached = (id: number): SemanticSymbol | undefined => this.snapshot.cachedSymbol(id); + const build = (data: SymbolResponse): SemanticSymbol => this.symbol(data); + return decodeSemanticObject(bytes, cached, build) ?? undefined; + } + + /** A reply of symbols and nulls (undefined here), or [] for null. */ + requestSymbols(method: string, query: SemanticQuery): (SemanticSymbol | undefined)[] { + const bytes = this.requestBinary(method, query); + const cached = (id: number): SemanticSymbol | undefined => this.snapshot.cachedSymbol(id); + const build = (data: SymbolResponse): SemanticSymbol => this.symbol(data); + return (decodeSemanticObjects(bytes, cached, build) ?? []).map((item) => item ?? undefined); + } + + /** A reply of one signature, or undefined for null. */ + requestSignature(method: string, query: SemanticQuery): SemanticSignature | undefined { + const bytes = this.requestBinary(method, query); + const cached = (id: number): SemanticSignature | undefined => this.signatures.get(id); + const build = (data: SignatureResponse): SemanticSignature => this.signature(data); + return decodeSemanticObject(bytes, cached, build) ?? undefined; + } + + /** A reply of signatures and nulls (undefined here), or [] for null. */ + requestSignatures(method: string, query: SemanticQuery): (SemanticSignature | undefined)[] { + const bytes = this.requestBinary(method, query); + const cached = (id: number): SemanticSignature | undefined => this.signatures.get(id); + const build = (data: SignatureResponse): SemanticSignature => this.signature(data); + return (decodeSemanticObjects(bytes, cached, build) ?? []).map((item) => item ?? undefined); + } + type(data: TypeResponse): SemanticType { this.ensureActive(); let type = this.types.get(data.id); @@ -190,9 +246,9 @@ export class SemanticProject { const cached = this.types.get(handle); if (cached !== undefined) return cached; } - const data = this.request(method, { objectId: source }); - if (data === null) throw new Error(`${method} returned null type for ${source}`); - return this.type(data); + const type = this.requestType(method, { objectId: source }); + if (type === undefined) throw new Error(`${method} returned null type for ${source}`); + return type; } fetchSymbol( @@ -204,9 +260,9 @@ export class SemanticProject { if (handle === undefined || handle === 0) return undefined; const cached = this.snapshot.cachedSymbol(handle); if (cached !== undefined) return cached; - const data = this.request(method, { objectId: source }); - if (data === null) throw new Error(`${method} returned null symbol for ${source}`); - return this.symbol(data); + const symbol = this.requestSymbol(method, { objectId: source }); + if (symbol === undefined) throw new Error(`${method} returned null symbol for ${source}`); + return symbol; } fetchSignature( @@ -218,9 +274,9 @@ export class SemanticProject { if (handle === undefined || handle === 0) return undefined; const cached = this.signatures.get(handle); if (cached !== undefined) return cached; - const data = this.request(method, { objectId: source }); - if (data === null) throw new Error(`${method} returned null signature for ${source}`); - return this.signature(data); + const signature = this.requestSignature(method, { objectId: source }); + if (signature === undefined) throw new Error(`${method} returned null signature for ${source}`); + return signature; } fetchTypes(source: number, method: string, handles?: readonly number[]): SemanticType[] { @@ -234,8 +290,7 @@ export class SemanticProject { } if (cached.length === handles.length) return cached; } - const data = this.request(method, { objectId: source }); - return (data ?? []).map((item) => this.type(item)); + return present(this.requestTypes(method, { objectId: source }), method); } fetchSymbols(source: number, method: string, handles?: readonly number[]): SemanticSymbol[] { @@ -249,8 +304,7 @@ export class SemanticProject { } if (cached.length === handles.length) return cached; } - const data = this.request(method, { objectId: source }); - return (data ?? []).map((item) => this.symbol(item)); + return present(this.requestSymbols(method, { objectId: source }), method); } dispose(): void { @@ -577,9 +631,8 @@ export class SemanticType { * changes nothing or its members are unreadable too. */ private widenedConstituents(): SemanticType[] | undefined { try { - const data = this.project.request("getWidenedType", { type: this.id }); - if (data === null || data.id === this.id) return undefined; - const widened = this.project.type(data); + const widened = this.project.requestType("getWidenedType", { type: this.id }); + if (widened === undefined || widened.id === this.id) return undefined; if ((widened.flags & TypeFlags.Union) === 0) return [widened]; return this.project.fetchTypes(widened.id, "getTypesOfType"); } catch (e) { @@ -594,8 +647,7 @@ export class SemanticType { getBaseTypes(): SemanticType[] | undefined { this.project.ensureActive(); if (!this.isClassOrInterface()) return undefined; - const data = this.project.request("getBaseTypes", { type: this.id }); - return (data ?? []).map((item) => this.project.type(item)); + return present(this.project.requestTypes("getBaseTypes", { type: this.id }), "getBaseTypes"); } getTrueType(): SemanticType { const result = this.project.fetchType(this.id, "getTrueTypeOfConditionalType", this.trueType); diff --git a/packages/compiler/src/frontend/tsc-codes.ts b/packages/compiler/src/frontend/tsc-codes.ts index fe48c8855..e6c0be7cd 100644 --- a/packages/compiler/src/frontend/tsc-codes.ts +++ b/packages/compiler/src/frontend/tsc-codes.ts @@ -27,6 +27,13 @@ export const ADOPTED_OPTIONS = [ // SC1012 "not supported yet" beats a raw TS1259 at the same site. "esModuleInterop", "allowSyntheticDefaultImports", + // JSX: the checker types JSX as the project's tsc does, and the JSX + // lowering (jsx-source.ts) emits the calls that setting selects. + "jsx", + "jsxFactory", + "jsxFragmentFactory", + "jsxImportSource", + "reactNamespace", ] as const; export const JS_RELAXED_TSC_CODES: ReadonlySet = new Set([ diff --git a/packages/compiler/src/frontend/type-mapper.test.ts b/packages/compiler/src/frontend/type-mapper.test.ts index cf78554b4..163ba7b9e 100644 --- a/packages/compiler/src/frontend/type-mapper.test.ts +++ b/packages/compiler/src/frontend/type-mapper.test.ts @@ -41,7 +41,7 @@ describe("union arm lookup", () => { test("sees finalized recursive arms after a missing lookup", () => { const unions = new UnionRegistry(); const recursive = {} as Type; - const union = unions.recursiveRef(recursive); + const union = unions.recursiveRef(recursive, () => "Recursive"); expect(unions.armTag(union, STRING)).toBe(-1); unions.finalizeRecursive(recursive, [ F64, diff --git a/packages/compiler/src/frontend/type-mapper.ts b/packages/compiler/src/frontend/type-mapper.ts index a233f0186..35514d992 100644 --- a/packages/compiler/src/frontend/type-mapper.ts +++ b/packages/compiler/src/frontend/type-mapper.ts @@ -1,4 +1,5 @@ import { InternalCompilerError } from "../errors.js"; +import { keyedHelperName, type KeyedNameOwner } from "./lowering/stable-names.js"; import { mockCallRecordType, mockContextType } from "./mock-shapes.js"; import * as ts from "./ts7/adapter.js"; import { bodyReadsArguments } from "./arguments-usage.js"; @@ -23,6 +24,7 @@ import { isSupportedMapKey, isSupportedMapValue, isSupportedSetElem, + iterableArmsElem, isUnitType, mapOf, NULL_T, @@ -146,6 +148,47 @@ export const WEBCRYPTO_DYN_TYPES: ReadonlySet = new Set([ "KeyAlgorithm", "HmacImportParams", "HmacKeyAlgorithm", + "CryptoKeyPair", + "EcKeyAlgorithm", + "RsaHashedKeyAlgorithm", + "EcKeyGenParams", + "EcKeyImportParams", + "EcdsaParams", + "RsaHashedKeyGenParams", + "RsaHashedImportParams", + "RsaPssParams", + "HmacKeyGenParams", + "AesKeyGenParams", + "AesKeyAlgorithm", + "JsonWebKey", + "AesGcmParams", + "AesCbcParams", + "AesCtrParams", + "Pbkdf2Params", + "HkdfParams", + "AesDerivedKeyParams", +]); + +/** node:crypto's key and signature option interfaces: the key functions, + * KeyObject.export and sign/verify take them as checked-dynamic arguments + * (scr_lib.c, scr_pki.c). */ +export const CRYPTO_KEY_OPTION_DYN_TYPES: ReadonlySet = new Set([ + "AsymmetricKeyExportOptions", + "ECKeyPairKeyObjectOptions", + "ECKeyPairOptions", + "ED25519KeyPairOptions", + "JsonWebKeyInput", + "JwkKeyExportOptions", + "KeyExportOptions", + "PrivateKeyInput", + "PublicKeyInput", + "RSAKeyPairKeyObjectOptions", + "RSAKeyPairOptions", + "SignKeyObjectInput", + "SignPrivateKeyInput", + "SigningOptions", + "VerifyKeyObjectInput", + "VerifyPublicKeyInput", ]); export const FETCH_AMBIENT_TYPES = [ @@ -252,6 +295,8 @@ function comparePriority(left: DeclaredOrderPriority, right: DeclaredOrderPriori export class ShapeRegistry { /** Existing layouts change only when a recursive placeholder closes. */ revision = 0; + /** Each shape id with a second hash of its key (keyedHelperName). */ + readonly keyedNameKeys = new Map(); private readonly byKey = new Map(); private readonly byId = new Map(); /** Historical emit-order rank of the declaration-order metadata each @@ -270,7 +315,7 @@ export class ShapeRegistry { * writer after all priority candidates have closed. */ private readonly derivedDeclaredOrderFinalizers: (() => void)[] = []; private currentDeclaredOrderPriority: DeclaredOrderPriority = [0, 0]; - /** All interned shapes in first-seen (`r0`, `r1`, ...) order. */ + /** All interned shapes in first-seen order. */ readonly shapes: IrRecordShape[] = []; /** ts.Types currently being mapped — a BACK-REFERENCE to one of these is * the recursive knot (`interface TreeNode { children: TreeNode[] }`): @@ -390,11 +435,12 @@ export class ShapeRegistry { /** The shape id a back-reference to an in-progress type resolves to: * reuses the type's persistent recursive id or mints a PLACEHOLDER - * entry (empty fields) the outer frame finalizes. */ - recursiveRef(t: ts.Type): string { + * entry (empty fields) the outer frame finalizes. `describe` names a new + * placeholder (checkerTypeDescription). */ + recursiveRef(t: ts.Type, describe: () => string): string { let id = this.recIds.get(t); if (id === undefined) { - id = `r${this.shapes.length}`; + id = recursivePlaceholderName(this, "r", describe(), (name) => this.byId.has(name)); const shape: IrRecordShape = { id, fields: [] }; this.byId.set(id, shape); this.shapes.push(shape); @@ -463,7 +509,7 @@ export class ShapeRegistry { const key = this.keyOf(fields, tuple, indexValue); let id = this.byKey.get(key); if (id === undefined) { - id = `r${this.shapes.length}`; + id = keyedHelperName(this, "r", key, ""); const shape: IrRecordShape = { id, fields, @@ -541,6 +587,58 @@ export class ShapeRegistry { } } +/** The id of a recursive placeholder described by `description`. Two + * different types can still share a description (checkerTypeDescription stops + * after a few levels of type arguments); the later one takes the first free + * name with a numbered suffix. */ +function recursivePlaceholderName( + owner: KeyedNameOwner, + prefix: string, + description: string, + taken: (name: string) => boolean, +): string { + let name = keyedHelperName(owner, prefix, `recursive:${description}`, ""); + for (let n = 1; taken(name); n++) + name = keyedHelperName(owner, prefix, `recursive:${description}#${n}`, ""); + return name; +} + +/** How many levels of type arguments checkerTypeDescription describes. */ +const RECURSIVE_NAME_DEPTH = 3; + +/** A checker type's description for names that must not depend on checker + * type ids (a recursive placeholder, a generic class instance keyed by a + * literal): its printed form, the structural position of its first + * declaration, and the same for its type arguments (two instantiations + * print the same when their type arguments are type parameters or classes + * of the same name from different declarations). */ +export function checkerTypeDescription( + t: ts.Type, + ctx: Pick, + depth = 0, +): string { + const symbol = t.getAliasSymbol() ?? t.getSymbol(); + const declaration = symbol?.declarations[0]; + const where = declaration + ? (ctx.positionOf?.(declaration) ?? + `${ts.getSourceFileOfNode(declaration).fileName}:${declaration.pos}`) + : ""; + let description = `${ctx.checker.typeToString(t)}@${where}`; + if (depth < RECURSIVE_NAME_DEPTH) { + const aliasArguments = + t.getAliasSymbol() !== undefined ? (t.getAliasTypeArguments() ?? []) : []; + const typeArguments = + aliasArguments.length > 0 + ? aliasArguments + : t.isTypeReference() + ? ctx.checker.getTypeArguments(t) + : []; + if (typeArguments.length > 0) + description += `<${typeArguments.map((arg) => checkerTypeDescription(arg, ctx, depth + 1)).join(",")}>`; + } + return description; +} + /** The frontend's union interner — mirrors ShapeRegistry. A union's * canonical identity includes its typeKey-sorted arms and literal * discriminator contract. An arm's index in that list IS its runtime tag. @@ -548,10 +646,12 @@ export class ShapeRegistry { export class UnionRegistry { /** Existing arm/discriminator contracts change when a placeholder closes. */ revision = 0; + /** Each union id with a second hash of its key (keyedHelperName). */ + readonly keyedNameKeys = new Map(); private readonly byKey = new Map(); private readonly byId = new Map(); private readonly armTags = new Map>(); - /** All interned unions in first-seen (`u0`, `u1`, ...) order. */ + /** All interned unions in first-seen order. */ readonly unions: IrUnionDef[] = []; /** ts.Types currently being mapped — a back-reference to one is the * recursive knot passing through a union (`type Tree = Leaf | Branch` @@ -567,11 +667,12 @@ export class UnionRegistry { /** The union id a back-reference to an in-progress union resolves to: * reuses the type's persistent recursive id or mints a PLACEHOLDER - * entry (empty arms) the outer frame finalizes. */ - recursiveRef(t: ts.Type): string { + * entry (empty arms) the outer frame finalizes. `describe` names a new + * placeholder (checkerTypeDescription). */ + recursiveRef(t: ts.Type, describe: () => string): string { let id = this.recIds.get(t); if (id === undefined) { - id = `u${this.unions.length}`; + id = recursivePlaceholderName(this, "u", describe(), (name) => this.byId.has(name)); const def: IrUnionDef = { id, arms: [] }; this.byId.set(id, def); this.unions.push(def); @@ -621,7 +722,7 @@ export class UnionRegistry { const key = JSON.stringify([arms.map(typeKey), discriminant]); let id = this.byKey.get(key); if (id === undefined) { - id = `u${this.unions.length}`; + id = keyedHelperName(this, "u", key, ""); const def: IrUnionDef = { id, arms, ...(discriminant ? { discriminant } : {}) }; this.byKey.set(key, id); this.byId.set(id, def); @@ -1114,7 +1215,17 @@ export interface TypeMapperCtx { * only the literal's objects, so it maps to the empty record (see the * empty object type rule in the object mapping). */ emptyLiteralArm?: boolean; + /** The class value a generic factory's result type names when the factory + * returns one of its own local classes through a constructor type + * (`function struct(v: S): Struct { class Base {}; return Base as + * Struct; }`), by the checker type: the declared result inside the + * instance being lowered, the instantiated result at its calls. */ + localClassValue?: (type: ts.Type) => IrType | null; checker: ts.TypeChecker; + /** The structural position of a declaration (structural-positions.ts), + * which names recursive placeholders independently of where unrelated + * code sits. The Lowerer supplies it. */ + positionOf?: (node: ts.Node) => string; /** JavaScript declarations whose instance or object-literal types only * the checked-dynamic representation holds (js-dynamic-objects.ts). * Absent when the program has none: every mapping is unchanged. */ @@ -1653,6 +1764,11 @@ export function mapType(type: ts.Type, ctx: TypeMapperCtx): IrType | null { return STRING; if (flags & (ts.TypeFlags.Boolean | ts.TypeFlags.BooleanLiteral)) return BOOL; } + const localValue = ctx.localClassValue?.(type); + if (localValue) { + contextResolutions++; + return localValue; + } const topLevel = mapTypeDepth === 0; const typeId = (type as { id?: number }).id; const memoizable = typeId !== undefined && (ctx.canMemoizeType?.() ?? true); @@ -1729,10 +1845,16 @@ function mapTypeInner(type: ts.Type, ctx: TypeMapperCtx): IrType | null { // TypeScript's intrinsic globalThis symbol has no declaration. A stored // reference needs native object identity, including var's undefined state. const intrinsic = type.getSymbol(); + const isIntrinsicGlobal = (symbol: ts.Symbol | undefined): boolean => + symbol !== undefined && + ts.symbolName(symbol) === "globalThis" && + symbol.declarations.length === 0; + if (isIntrinsicGlobal(intrinsic)) return DYN; + // `typeof globalThis & { key?: T }` (the global-singleton spelling) is the + // same global object with declared extra members. if ( - intrinsic !== undefined && - ts.symbolName(intrinsic) === "globalThis" && - intrinsic.declarations.length === 0 + type.isIntersectionType() && + ts.constituentTypes(type).some((part) => isIntrinsicGlobal(part.getSymbol())) ) return DYN; if (ctx.jsDynamicDeclaration !== undefined && intrinsic !== undefined) { @@ -2246,6 +2368,27 @@ function mapTypeInner(type: ts.Type, ctx: TypeMapperCtx): IrType | null { const args = checker.getTypeArguments(ref); if (args.length === 0) return arrayOf(unitOnlyUnion(unions)); if (tupleShape?.elementFlags === undefined) return null; + // A leading-required tuple ending in a rest element whose positions + // all share one type (`[string, ...string[]]`, the non-empty list) + // is an array of that type: every read, write and method behaves as + // the array's, and tsc already proves the required positions exist. + const flags = tupleShape.elementFlags; + if ( + flags.length >= 2 && + (flags[flags.length - 1]! & ts.ElementFlags.Rest) !== 0 && + flags.slice(0, -1).every((f) => (f & ts.ElementFlags.Required) !== 0) + ) { + const elems = args.map((a) => mapType(a, ctx)); + const first = elems[0]; + if ( + first && + first.kind !== "void" && + isSupportedArrayElem(first) && + elems.every((e) => e !== null && typeEquals(e, first)) + ) + return arrayOf(first); + return null; + } // Optional/rest elements have no fixed native tuple layout. if (tupleShape.elementFlags.some((f) => !(f & ts.ElementFlags.Required))) { return null; @@ -2903,9 +3046,10 @@ function mapTypeInner(type: ts.Type, ctx: TypeMapperCtx): IrType | null { ) { return DYN; } - // node:crypto's KeyObject: secret keys are native handles (scr_lib.c) - // whose getters and methods dispatch through the handle. The JsonWebKey - // that export() returns is a plain checked-dynamic object. + // node:crypto's KeyObject: secret keys (scr_lib.c) and private and + // public keys (scr_pki.c) are native handles whose getters and methods + // dispatch through the handle. The JsonWebKey that export() returns is a + // plain checked-dynamic object. if ( ((psym !== undefined && ts.symbolName(psym) === "KeyObject") || (psym !== undefined && ts.symbolName(psym) === "JsonWebKey")) && @@ -2917,6 +3061,35 @@ function mapTypeInner(type: ts.Type, ctx: TypeMapperCtx): IrType | null { ) { return DYN; } + // node:crypto's key and signature options are plain checked-dynamic + // objects, so a value asserted to one (`opts as + // crypto.AsymmetricKeyExportOptions<"pem">`) reaches the call unchanged. + if ( + psym !== undefined && + CRYPTO_KEY_OPTION_DYN_TYPES.has(ts.symbolName(psym)) && + psym.declarations.some( + (d) => + ts.isInterfaceDeclaration(d) && + ctx.isStdlibFile(ts.getSourceFileOfNode(d)) && + isDeclaredInAmbientModule(d, "crypto"), + ) + ) { + return DYN; + } + // node:crypto's Sign and Verify (createSign/createVerify): native + // handles over the digest state (scr_pki.c). + if ( + psym !== undefined && + (ts.symbolName(psym) === "Sign" || ts.symbolName(psym) === "Verify") && + psym.declarations.some( + (d) => + ts.isClassDeclaration(d) && + ctx.isStdlibFile(ts.getSourceFileOfNode(d)) && + isDeclaredInAmbientModule(d, "crypto"), + ) + ) { + return DYN; + } if ( psym && (FETCH_AMBIENT_TYPES as readonly string[]).includes(ts.symbolName(psym)) && @@ -2973,6 +3146,23 @@ function mapTypeInner(type: ts.Type, ctx: TypeMapperCtx): IrType | null { ) { return DYN; } + // node:crypto DiffieHellman values, and @types/node's DiffieHellmanGroup + // alias over them, are native handles carried by the checked-dynamic + // representation; lowerDiffieHellmanCall dispatches their methods. + { + const dhSym = widened.getAliasSymbol() ?? psym; + if ( + dhSym !== undefined && + (ts.symbolName(dhSym) === "DiffieHellman" || ts.symbolName(dhSym) === "DiffieHellmanGroup") && + dhSym.declarations.some( + (d) => + (ts.isClassDeclaration(d) || ts.isTypeAliasDeclaration(d)) && + ctx.isStdlibFile(ts.getSourceFileOfNode(d)), + ) + ) { + return DYN; + } + } // ReadonlyMap/ReadonlySet are the SAME runtime values as Map/Set — the // readonly-ness is a checker-only view (no mutating members on the // interface), so both map to the identical IR kinds and the read-side @@ -2993,6 +3183,8 @@ function mapTypeInner(type: ts.Type, ctx: TypeMapperCtx): IrType | null { // Native WeakMap keeps reference identities in checked-dynamic storage. // The runtime rejects reference kinds without a weak lifetime contract. if (isStdlibInterface("WeakMap") || isStdlibInterface("WeakSet")) return DYN; + // FinalizationRegistry is a native handle with register and unregister. + if (isStdlibInterface("FinalizationRegistry")) return DYN; // Set: Map's sibling — same provenance rule and key domain. // Anything else stays unmapped; // the `new Set` lowering names the offending element type specifically. @@ -3773,6 +3965,14 @@ function mapTypeInner(type: ts.Type, ctx: TypeMapperCtx): IrType | null { ...channels, }; } + // Iterable: the iterable union (iterableUnionType) — the source value + // itself in its own arm, so an array stays the same multi-pass object and + // a generator stays single-pass. + if (isStdlibInterface("Iterable")) { + const arg = checker.getTypeArguments(widened as ts.TypeReference)[0]; + const elem = arg ? mapType(arg, ctx) : null; + return elem ? iterableUnionType(elem, ctx.shapes, unions) : null; + } // IteratorResult — the checker's type of `g.next()` (an // alias for IteratorYieldResult | IteratorReturnResult): // maps to the SAME interned record genResume answers, so `const r = @@ -4183,6 +4383,41 @@ function mapTypeInner(type: ts.Type, ctx: TypeMapperCtx): IrType | null { }; } } + // crypto.generateKeyPairSync's results: KeyPairKeyObjectResult and + // KeyPairSyncResult as { publicKey, privateKey } records over the + // mapped property types (KeyObjects, PEM strings or DER Buffers), in + // Node's key order. + if ( + psym !== undefined && + (ts.symbolName(psym) === "KeyPairKeyObjectResult" || + ts.symbolName(psym) === "KeyPairSyncResult") && + psym.declarations.some( + (d) => + ts.isInterfaceDeclaration(d) && + ctx.isStdlibFile(ts.getSourceFileOfNode(d)) && + isDeclaredInAmbientModule(d, "crypto"), + ) + ) { + const field = (name: string): IrType | null => { + const prop = ctx.checker.getPropertyOfType(type, name); + return prop ? mapType(ctx.checker.getTypeOfSymbol(prop), ctx) : null; + }; + const publicKey = field("publicKey"); + const privateKey = field("privateKey"); + if (!publicKey || !privateKey) return null; + return { + kind: "record", + shapeId: ctx.shapes.intern( + [ + { name: "privateKey", type: privateKey }, + { name: "publicKey", type: publicKey }, + ], + false, + undefined, + ["publicKey", "privateKey"], + ), + }; + } // crypto.X509Certificate — the Dirent-style data record: THREE visible // fields (fingerprint and the validFrom/validTo validity window, all // computed at construction by the new-expression lowering). Module- @@ -4651,7 +4886,10 @@ function mapTypeInner(type: ts.Type, ctx: TypeMapperCtx): IrType | null { const knownRecursive = unions.recursiveUnionFor(widened); if (knownRecursive !== undefined) return { kind: "union", unionId: knownRecursive }; if (unions.inProgress.has(widened)) { - return { kind: "union", unionId: unions.recursiveRef(widened) }; + return { + kind: "union", + unionId: unions.recursiveRef(widened, () => checkerTypeDescription(widened, ctx)), + }; } unions.inProgress.add(widened); const sensitivityAtEntry = contextResolutions; @@ -4789,7 +5027,9 @@ function mapTypeInner(type: ts.Type, ctx: TypeMapperCtx): IrType | null { a.kind === "union" || a.kind === "date" || a.kind === "dyn" || - a.kind === "generator", + // A generator arm only comes from an Iterable (an optional + // one keeps its unit arms beside the iterable union's). + (a.kind === "generator" && iterableArmsElem(arms) === null), ) || !maybePromiseUnionOk(parts, arms, ctx) ) { @@ -5644,6 +5884,60 @@ function constAssertedEmptyArrayProp(p: ts.Symbol): boolean { return underConstAssertion(d); } +/** A TypeScript property assignment `name: []` whose type is `never[]`. */ +function emptyNeverArrayProp(p: ts.Symbol, fieldTs: ts.Type, checker: ts.TypeChecker): boolean { + const d = p.valueDeclaration; + if (d === undefined || !ts.isPropertyAssignment(d)) return false; + if (isJsSourceFile(ts.getSourceFileOfNode(d))) return false; + if (!ts.isArrayLiteralExpression(d.initializer) || d.initializer.elements.nodes.length > 0) + return false; + return ( + checker.isArrayType(fieldTs) && + (checker.getTypeArguments(fieldTs as ts.TypeReference)[0]!.flags & ts.TypeFlags.Never) !== 0 + ); +} + +/** A JavaScript object literal's property typed `never[]` (`{ issues: [] }`). + * Nothing checks a JavaScript file's later writes, which can push any value + * onto it (`ctx.common.issues.push(issue)`), so it holds the checked-dynamic + * array rather than never's f64 element array. */ +function jsNeverArrayProp(p: ts.Symbol, fieldTs: ts.Type, checker: ts.TypeChecker): boolean { + return ( + jsObjectLiteralProperty(p) && + checker.isArrayType(fieldTs) && + (checker.getTypeArguments(fieldTs as ts.TypeReference)[0]!.flags & ts.TypeFlags.Never) !== 0 + ); +} + +/** A JavaScript object literal's property (`{ lastComponent: undefined }`, + * `{ user: null }`). Nothing checks a JavaScript file's later writes, which + * can store any value in it (`path.lastComponent = { ... }`), so a + * property whose only initializer is a unit holds the checked-dynamic value + * rather than the unit-only union. */ +function isUnitOnlyIr(t: IrType, ctx: TypeMapperCtx): boolean { + if (t.kind !== "union") return false; + const def = ctx.unions.get(t.unionId); + return def !== undefined && def.arms.every((arm) => isUnitType(arm)); +} + +/** A property a JavaScript object literal declares. The checker also adds + * each missing property, optional and `undefined`, to every literal of a + * union of literals (`{ _tag, value } | { _tag, error }` gains + * `error?: undefined` and `value?: undefined`); those keep their unit-only + * type, so a literal still converts to the one arm whose properties it + * has. */ +function jsObjectLiteralProperty(p: ts.Symbol): boolean { + const d = p.valueDeclaration; + // `__proto__: null` sets the literal's prototype; it declares no property. + return ( + d !== undefined && + (ts.isPropertyAssignment(d) || ts.isShorthandPropertyAssignment(d)) && + ts.symbolName(p) !== "__proto__" && + (p.flags & ts.SymbolFlags.Optional) === 0 && + isJsSourceFile(ts.getSourceFileOfNode(d)) + ); +} + function mapGenericAwaitedAlias(type: ts.Type, ctx: TypeMapperCtx): IrType | null { const { resolveTypeParam } = ctx; if (!resolveTypeParam) return null; @@ -6197,6 +6491,46 @@ export function unitOnlyUnion(unions: UnionRegistry): IrType { return { kind: "union", unionId: unions.intern(arms) }; } +/** `Iterable`: a union whose arms are the sources that keep their own + * representation — `T[]`, a `Set`, a `Map` (T the `[K, V]` + * tuple), a string (T string) — and a generator over T, which also holds + * every other iterator (Map/Set and array iterators adapt into one). The + * generator arm marks the union as iterable (iterableArmsElem): no other + * union has one. Null when T has no array or generator form. */ +export function iterableUnionType( + elem: IrType, + shapes: ShapeRegistry, + unions: UnionRegistry, +): IrType | null { + if (elem.kind === "void" || elem.kind === "generator" || !isSupportedArrayElem(elem)) return null; + if (!genResultRecord(elem, VOID, shapes, unions)) return null; + const arms: IrType[] = [ + { kind: "array", elem }, + { kind: "generator", yieldT: elem, retT: VOID, nextT: UNDEFINED_T }, + ]; + const elemArms = elem.kind === "union" ? unions.get(elem.unionId)?.arms : undefined; + if (isSupportedSetElem(elem, elemArms)) arms.push({ kind: "set", elem }); + if (elem.kind === "string") arms.push(STRING); + if (elem.kind === "record") { + const shape = shapes.get(elem.shapeId); + const [k, v] = shape?.fields ?? []; + if ( + shape?.tuple && + shape.fields.length === 2 && + k?.name === "0" && + v?.name === "1" && + isSupportedMapKey( + k.type, + k.type.kind === "union" ? unions.get(k.type.unionId)?.arms : undefined, + ) && + isSupportedMapValue(v.type) + ) + arms.push({ kind: "map", key: k.type, value: v.type }); + } + arms.sort((a, b) => (typeKey(a) < typeKey(b) ? -1 : 1)); + return { kind: "union", unionId: unions.intern(arms) }; +} + /** The IteratorResult record of a generator's value channels: `{ done: * boolean, value: V }` where V is dyn (an any/unknown channel) or the * canonical union of the yield arms, the return arms (when the return @@ -6995,7 +7329,10 @@ function mapRecordType(widened: ts.Type, ctx: TypeMapperCtx): IrType | null { // frame completes (finalizeRecursive below). Backends represent records // as heap references, so the self-reference is an ordinary pointer. if (shapes.inProgress.has(widened)) { - return { kind: "record", shapeId: shapes.recursiveRef(widened) }; + return { + kind: "record", + shapeId: shapes.recursiveRef(widened, () => checkerTypeDescription(widened, ctx)), + }; } shapes.inProgress.add(widened); const sensitivityAtEntry = contextResolutions; @@ -7389,6 +7726,22 @@ function wideningAddedProperties( return added; } +/** Whether `type` is an interface one of whose `extends` clauses names a + * type the checker answers `any` (or an error type) for. */ +function interfaceExtendsAny(type: ts.Type, checker: ts.TypeChecker): boolean { + const symbol = type.getSymbol(); + if (symbol === undefined || (symbol.flags & ts.SymbolFlags.Interface) === 0) return false; + for (const decl of symbol.declarations) { + if (!ts.isInterfaceDeclaration(decl)) continue; + for (const clause of decl.heritageClauses?.nodes ?? []) { + for (const base of clause.types.nodes) { + if ((checker.getTypeAtLocation(base).flags & ts.TypeFlags.Any) !== 0) return true; + } + } + } + return false; +} + function mapRecordTypeInner( widened: ts.Type, ctx: TypeMapperCtx, @@ -7404,6 +7757,13 @@ function mapRecordTypeInner( // names the construct. const widenedSym = widened.getSymbol(); if (widenedSym !== undefined && (widenedSym.flags & ts.SymbolFlags.Enum) !== 0) return null; + // An interface extending a type the checker answers `any` for (in the + // compiled world, a package type computed from members only its .d.ts + // declares, such as `interface P extends z.infer`) has members + // the checker cannot list: its own declared fields are not the whole + // object. The value is checked-dynamic, never a record of the declared + // fields alone. + if (interfaceExtendsAny(widened, checker)) return DYN; // An index signature maps to a hybrid shape: declared fields keep // struct slots, undeclared keys ride the shape's overflow map, valued // uniformly by the signature's value type (`unknown` → dyn — a model-pricing table's @@ -7677,6 +8037,14 @@ function mapRecordTypeInner( ) { pt = arrayOf(unitOnlyUnion(ctx.unions)); } + // A TypeScript property initialized with an empty literal and typed + // `never[]` (`const out = { files: [] }`) holds no element, so it maps + // like the empty tuple: the unit-only element array, which a + // destination's typed array field (`files: string[]`) receives through + // the checked empty-array lift. never's f64 element would make it a + // `number[]` field. + if (pt?.kind === "array" && emptyNeverArrayProp(p, fieldTs, checker)) + pt = arrayOf(unitOnlyUnion(ctx.unions)); if (pt === null && (fieldTs.flags & ts.TypeFlags.Any) !== 0) pt = DYN; // An `any[]` field (`list: any[]` in an SDK's message type, also // optional or nullable) is the checked-dynamic array, exactly as @@ -7700,6 +8068,8 @@ function mapRecordTypeInner( // omits the undefined arm exactly like an omitted optional. if (pt?.kind === "void" && isUnitOnlyTsType(fieldTs, ctx.resolveTypeParam)) pt = unitOnlyUnion(ctx.unions); + if (pt !== null && isUnitOnlyIr(pt, ctx) && jsObjectLiteralProperty(p)) pt = DYN; + if (pt?.kind === "array" && jsNeverArrayProp(p, fieldTs, checker)) pt = DYN; // dyn FIELDS map now (`{ v: unknown }`, `[string, unknown]` tuples): // the slot carries a dyn value exactly like an `unknown`-valued // overflow entry — same RC adapters, same dynFrom conversion on the diff --git a/packages/compiler/src/index.ts b/packages/compiler/src/index.ts index 2b216c77d..f0f19a408 100644 --- a/packages/compiler/src/index.ts +++ b/packages/compiler/src/index.ts @@ -49,7 +49,8 @@ import { frontendProcessExecArgv } from "./frontend-process-args.js"; import { type ChildProcess, spawn } from "node:child_process"; import { createHash } from "node:crypto"; import { existsSync } from "node:fs"; -import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; +import { copyFile, mkdir, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; import { basename, dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { @@ -524,6 +525,9 @@ async function compileExecutableNative( onArtifactReady?: NonNullable[0]["onArtifactReady"]>, programPartitions: readonly string[] = [], profileGenerate = false, + /** The kept LLVM text's shared name, when `llvmPath` is the build's private copy of it + * (BuildSources): the spelling clang sees and native cache keys name. */ + llvmVisiblePath?: string, ): Promise { const programIsObject = /\.(?:o|obj)$/.test(llvmPath); const runtimePackTarget = programIsObject && !sanitize ? nativeCodegenTarget() : null; @@ -563,7 +567,9 @@ async function compileExecutableNative( if (programIsObject) throw new InternalCompilerError("program objects must link against a precompiled runtime pack"); await compileExternalC({ - cPath: llvmPath, + ...(llvmVisiblePath === undefined || llvmVisiblePath === llvmPath + ? { cPath: llvmPath } + : { cPath: llvmVisiblePath, cSourcePath: llvmPath }), outPath, cacheIdentity: "scriptc-generated-v1", ...optimizationField(features.optimization), @@ -624,6 +630,9 @@ async function compileExecutableNative( tlsCa: features.tlsCa, cipher: features.cipher, ecdh: features.ecdh, + dh: features.dh, + pki: features.pki, + ed25519: features.ed25519, webcrypto: features.webcrypto, perfLoop: features.perfLoop, ...(onArtifactReady === undefined ? {} : { onArtifactReady }), @@ -729,8 +738,12 @@ function runtimePackDiagnostic(error: RuntimePackError, entryPath: string): ScrD interface PreparedExecutable { llvmSource: LlvmInput; + /** The kept LLVM text beside the executable, installed when the build ends. */ llvmPath: string; + /** This build's private copy of the LLVM text (BuildSources). */ + llvmSourcePath: string; irPath: string | undefined; + irSourcePath: string | undefined; nativeFeatures: EarlyExecutableNativeFeatures; programSplit: ReturnType; sourceTexts: Map; @@ -841,6 +854,8 @@ async function prepareExecutableInput( await mkdir(opts.outDir, { recursive: true }); const llvmPath = defaultSourcePaths.llvm; + // The extension keeps clang reading the copy as LLVM IR rather than as a linker input. + const llvmSourcePath = `${privateSiblingPath(llvmPath, "llvm")}.ll`; const backend = "llvm" as const; const useRuntimePack = opts.nativeProgramObject === true || usesPrecompiledRuntimePack(opts, backend); @@ -863,12 +878,14 @@ async function prepareExecutableInput( return { ok: false, diagnostics: [llvmRefusalDiag(err, entryPath)], sourceTexts }; } timing("llvm-emit"); - await writeLlvmSource(llvmPath, llvmSource); + await writeLlvmSource(llvmSourcePath, llvmSource); timing("llvm-write"); let irPath: string | undefined; + let irSourcePath: string | undefined; if (opts.emitIr) { irPath = defaultSourcePaths.ir; - await writeTextParts(irPath, serializeModuleParts(mod)); + irSourcePath = privateSiblingPath(irPath, "ir"); + await writeTextParts(irSourcePath, serializeModuleParts(mod)); } const nativeFeatures = executableNativeFeatures(mod, backend, opts.optimization ?? "release"); @@ -882,7 +899,87 @@ async function prepareExecutableInput( ? splitLlvmProgram(llvmSource) : null; timing("llvm-split"); - return { llvmSource, llvmPath, irPath, nativeFeatures, programSplit, sourceTexts }; + return { + llvmSource, + llvmPath, + llvmSourcePath, + irPath, + irSourcePath, + nativeFeatures, + programSplit, + sourceTexts, + }; +} + +/** + * The kept LLVM text (`.ll`) and IR (`.ir.json`) sit beside the executable, + * so programs whose entries share a name and are built into one output directory share them. Each + * build therefore writes, compiles and caches private copies (privateSiblingPath) and moves them to + * the shared names only when it is done (rename replaces a file in one step): a concurrent build of + * another program cannot replace the text a build compiles or the translation unit it caches. + * Builds that compile with the C driver install them before the native build instead + * (stageDriverBuildSources). + */ +interface BuildSources { + llvmPath: string; + llvmSourcePath: string; + irPath?: string | undefined; + irSourcePath?: string | undefined; + /** The shared name already holds the private copy's bytes (a cache hit's restored files): it is + * left as it is, with its time stamps. */ + llvmPathCurrent?: boolean | undefined; + irPathCurrent?: boolean | undefined; +} + +/** Moves a build's private copies to the shared names, or drops them when that fails. */ +async function installBuildSources(sources: BuildSources): Promise { + const install = async ( + source: string | undefined, + destination: string | undefined, + current: boolean | undefined, + ) => { + if (source === undefined || destination === undefined || source === destination) return; + if (current === true) await rm(source, { force: true }); + else await rename(source, destination).catch(() => rm(source, { force: true })); + }; + await Promise.all([ + install(sources.llvmSourcePath, sources.llvmPath, sources.llvmPathCurrent), + install(sources.irSourcePath, sources.irPath, sources.irPathCurrent), + ]); +} + +/** + * A build that compiles the LLVM text with the C driver (no precompiled runtime pack) records the + * output directory in its native cache proofs, so that directory has to be in its final state before + * the native build starts. The build therefore installs the shared names first and compiles and + * caches copies in a private directory outside the output directory. Returns that directory and the + * copies. + */ +async function stageDriverBuildSources( + sources: BuildSources, +): Promise<{ dir: string; sources: BuildSources }> { + const dir = await mkdtemp(join(tmpdir(), "scriptc-program-")); + const llvmSourcePath = join(dir, basename(sources.llvmPath)); + const irSourcePath = + sources.irPath === undefined || sources.irSourcePath === undefined + ? undefined + : join(dir, basename(sources.irPath)); + try { + await Promise.all([ + copyFile(sources.llvmSourcePath, llvmSourcePath), + irSourcePath === undefined || sources.irSourcePath === undefined + ? undefined + : copyFile(sources.irSourcePath, irSourcePath), + ]); + } catch (err) { + await rm(dir, { recursive: true, force: true }); + throw err; + } + await installBuildSources(sources); + return { + dir, + sources: { llvmPath: sources.llvmPath, llvmSourcePath, irPath: sources.irPath, irSourcePath }, + }; } /** @@ -976,10 +1073,11 @@ type FrontendProcessResult = | { kind: "prepared"; llvmPath: string; - /** A private copy of the LLVM text, which the native helper reads (`nativeInputPath`). */ + /** The build's private copy of the LLVM text (BuildSources), which the native helper reads. */ nativeInputPath: string; llvmBytes: number; irPath: string | undefined; + irSourcePath: string | undefined; nativeFeatures: EarlyExecutableNativeFeatures; sourceTexts: [string, string][]; warnings: ScrDiagnostic[]; @@ -1047,7 +1145,9 @@ async function prepareExecutableInputInChild( return { llvmSource: { file: result.nativeInputPath, bytes: result.llvmBytes }, llvmPath: result.llvmPath, + llvmSourcePath: result.nativeInputPath, irPath: result.irPath, + irSourcePath: result.irSourcePath, nativeFeatures: result.nativeFeatures, programSplit: null, sourceTexts, @@ -1085,18 +1185,15 @@ export async function runFrontendProcess(requestPath: string, resultPath: string ); const frontend = frontendInputs.snapshot(); if (!("ok" in prepared)) { - // The public .ll file may be rewritten by a concurrent build of another entry with the - // same output stem before the native helper reads it (see emitNativeArtifact). if (isLlvmFile(prepared.llvmSource)) throw new InternalCompilerError("in-process preparation returned LLVM text as a file"); - const nativeInputPath = privateSiblingPath(prepared.llvmPath, "frontend-llvm"); - await writeLlvmSource(nativeInputPath, prepared.llvmSource, 0o600); result = { kind: "prepared", llvmPath: prepared.llvmPath, - nativeInputPath, + nativeInputPath: prepared.llvmSourcePath, llvmBytes: llvmInputBytes(prepared.llvmSource), irPath: prepared.irPath, + irSourcePath: prepared.irSourcePath, nativeFeatures: prepared.nativeFeatures, sourceTexts: [...prepared.sourceTexts], warnings: warnings.warnings, @@ -1450,37 +1547,54 @@ async function compileTracked( ...(earlyHit.irPath === undefined ? {} : { irPath: earlyHit.irPath }), }; } - let nativeInputPath = earlyHit.llvmPath; + // The build's private copies of the cached LLVM text and IR (BuildSources). + const hitSources: BuildSources = { + llvmPath: earlyHit.llvmPath, + llvmSourcePath: earlyHit.llvmSourcePath ?? earlyHit.llvmPath, + irPath: earlyHit.irPath, + irSourcePath: earlyHit.irSourcePath, + llvmPathCurrent: earlyHit.llvmPathCurrent, + irPathCurrent: earlyHit.irPathCurrent, + }; + // What the native build compiles and the cache publishes: hitSources, or their staged copies. + let nativeSources = hitSources; + let stagedDir: string | null = null; + let nativeInputPath = hitSources.llvmSourcePath; let nativeProgramObject: NativeProgramObject | null = null; const useRuntimePack = opts.nativeProgramObject === true || usesPrecompiledRuntimePack(opts, earlyHit.native.backend); - if (useRuntimePack) { - if (earlyHit.native.backend !== "llvm") { - throw new InternalCompilerError( - "native program-object cache hit restored a non-LLVM translation unit", - ); - } - try { - nativeProgramObject = await emitNativeProgramObject( - entryPath, - opts, - // A large program's LLVM exceeds the engine's string limit as one - // string; the emitter takes it in parts, as on a cold build. - await readTextParts(earlyHit.llvmPath), - profile, - ); - nativeInputPath = nativeProgramObject.linkPath; - } catch (err) { - if (!(err instanceof NativeCodegenError)) throw err; - return { - ok: false, - diagnostics: [nativeCodegenDiag(err.diagnosticCode, err.message, entryPath)], - sourceTexts: new Map(), - }; - } - } try { + if (useRuntimePack) { + if (earlyHit.native.backend !== "llvm") { + throw new InternalCompilerError( + "native program-object cache hit restored a non-LLVM translation unit", + ); + } + try { + nativeProgramObject = await emitNativeProgramObject( + entryPath, + opts, + // A large program's LLVM exceeds the engine's string limit as one + // string; the emitter takes it in parts, as on a cold build. + await readTextParts(hitSources.llvmSourcePath), + profile, + ); + nativeInputPath = nativeProgramObject.linkPath; + } catch (err) { + if (!(err instanceof NativeCodegenError)) throw err; + return { + ok: false, + diagnostics: [nativeCodegenDiag(err.diagnosticCode, err.message, entryPath)], + sourceTexts: new Map(), + }; + } + } else { + const staged = await stageDriverBuildSources(hitSources); + stagedDir = staged.dir; + nativeSources = staged.sources; + nativeInputPath = nativeSources.llvmSourcePath; + } await compileExecutableNative( earlyHit.native, nativeInputPath, @@ -1496,6 +1610,10 @@ async function compileTracked( : async ({ dependencies }) => { await publishEarlyExecutableCache(cacheRoot, executableCacheOptions, { ...earlyHit, + llvmPath: nativeSources.llvmSourcePath, + ...(nativeSources.irSourcePath === undefined + ? {} + : { irPath: nativeSources.irSourcePath }), executableRestored: true, nativeDependencies: dependencies, frontend: earlyHit.frontend, @@ -1503,6 +1621,7 @@ async function compileTracked( }, nativeProgramObject?.partitionPaths, profile?.generate !== undefined, + hitSources.llvmPath, ); if (nativeProgramObject !== null && opts.nativeProgramObject === true) { await rename(nativeProgramObject.linkPath, nativeProgramObject.artifactPath); @@ -1532,6 +1651,8 @@ async function compileTracked( nativeProgramObject.partitionPaths, ); } + if (stagedDir === null) await installBuildSources(hitSources); + else await rm(stagedDir, { recursive: true, force: true }); } await pruneBuildCache(cacheRoot); return { @@ -1564,7 +1685,17 @@ async function compileTracked( ) : await prepareExecutableInput(entryPath, opts, ffi, buildPlatform, timing, warningSink); if ("ok" in prepared) return prepared; - const { llvmSource, llvmPath, irPath, nativeFeatures, programSplit, sourceTexts } = prepared; + const buildSources: BuildSources = { + llvmPath: prepared.llvmPath, + llvmSourcePath: prepared.llvmSourcePath, + irPath: prepared.irPath, + irSourcePath: prepared.irSourcePath, + }; + const { llvmSource, llvmPath, irPath } = prepared; + const { nativeFeatures, programSplit, sourceTexts } = prepared; + // What the native build compiles and the cache publishes: buildSources, or their staged copies. + let { llvmSourcePath, irSourcePath } = buildSources; + let stagedDir: string | null = null; const backend = "llvm" as const; await mkdir(dirname(opts.outPath), { recursive: true }); if (earlyCacheOptions === null) { @@ -1596,10 +1727,14 @@ async function compileTracked( sourceTexts, }; } + } else { + const staged = await stageDriverBuildSources(buildSources); + stagedDir = staged.dir; + ({ llvmSourcePath, irSourcePath } = staged.sources); } await compileExecutableNative( nativeFeatures, - nativeProgramObject?.linkPath ?? llvmPath, + nativeProgramObject?.linkPath ?? llvmSourcePath, opts.outPath, opts.sanitize ?? false, ffi, @@ -1611,23 +1746,34 @@ async function compileTracked( ? undefined : async ({ dependencies }) => { await publishEarlyExecutableCache(cacheRoot, executableCacheOptions, { - llvmPath, + llvmPath: llvmSourcePath, native: nativeFeatures, executableRestored: true, nativeDependencies: dependencies, frontend: frontendInputs.snapshot(), - ...(irPath === undefined ? {} : { irPath }), + ...(irSourcePath === undefined ? {} : { irPath: irSourcePath }), ...performanceWarnings(warningSink), }); publishedExecutable = true; }, nativeProgramObject?.partitionPaths, profile?.generate !== undefined, + llvmPath, ); timing("native-link"); if (nativeProgramObject !== null && opts.nativeProgramObject === true) { await rename(nativeProgramObject.linkPath, nativeProgramObject.artifactPath); } + if (!publishedExecutable) { + await publishEarlyExecutableCache(cacheRoot, executableCacheOptions, { + llvmPath: llvmSourcePath, + native: nativeFeatures, + executableRestored: false, + frontend: frontendInputs.snapshot(), + ...(irSourcePath === undefined ? {} : { irPath: irSourcePath }), + ...performanceWarnings(warningSink), + }).catch(() => undefined); + } } catch (err) { if (err instanceof RuntimePackError) { return { ok: false, diagnostics: [runtimePackDiagnostic(err, entryPath)], sourceTexts }; @@ -1649,18 +1795,8 @@ async function compileTracked( nativeProgramObject.partitionPaths, ); } - // The frontend process's private copy of the LLVM text. - if (isLlvmFile(llvmSource)) await rm(llvmSource.file, { force: true }); - } - if (!publishedExecutable) { - await publishEarlyExecutableCache(cacheRoot, executableCacheOptions, { - llvmPath, - native: nativeFeatures, - executableRestored: false, - frontend: frontendInputs.snapshot(), - ...(irPath === undefined ? {} : { irPath }), - ...performanceWarnings(warningSink), - }).catch(() => undefined); + if (stagedDir === null) await installBuildSources(buildSources); + else await rm(stagedDir, { recursive: true, force: true }); } await pruneBuildCache(cacheRoot); timing("complete"); diff --git a/packages/compiler/src/ir/array-length-stability.test.ts b/packages/compiler/src/ir/array-length-stability.test.ts index a0d0e49a7..f9b3cc9c2 100644 --- a/packages/compiler/src/ir/array-length-stability.test.ts +++ b/packages/compiler/src/ir/array-length-stability.test.ts @@ -167,3 +167,29 @@ test("fresh local arrays read only as receivers have no alias", () => { const rebound = [...body, { kind: "assign", localId: "out", value: arr("a"), loc } as IrStmt]; expect(findUnaliasedLocalArrays(fn(rebound)).has("out")).toBe(false); }); + +test("number and boolean writes to class fields run no user code", () => { + const obj: IrExpr = { + kind: "varRef", + localId: "o", + type: { kind: "object", className: "P" }, + loc, + }; + const scope = new Map(locals).set("o", { + id: "o", + name: "o", + type: { kind: "object", className: "P" }, + mutable: false, + }); + const fieldSet = (value: IrExpr): IrStmt => ({ + kind: "fieldSet", + obj, + className: "P", + field: "x", + value, + loc, + }); + expect(preserves([fieldSet(read("a", ref("i")))], "i", new Set(), scope)).toBe(true); + // A reference stored into a field releases the old one. + expect(preserves([fieldSet(arr("b"))], "i", new Set(), scope)).toBe(false); +}); diff --git a/packages/compiler/src/ir/array-length-stability.ts b/packages/compiler/src/ir/array-length-stability.ts index 3f9c3b9ca..ed57972b6 100644 --- a/packages/compiler/src/ir/array-length-stability.ts +++ b/packages/compiler/src/ir/array-length-stability.ts @@ -264,6 +264,15 @@ export function preservesArrayLength( ); case "return": return s.value === null || expr(s.value); + case "fieldSet": + // A number or boolean stored into a class field: accessors are + // calls, not field writes, and the old value holds no reference to + // release, so the write runs no user code. + return ( + (s.value.type.kind === "f64" || s.value.type.kind === "bool") && + expr(s.obj) && + expr(s.value) + ); default: if (!PLAIN_STATEMENTS.has(s.kind)) return false; } diff --git a/packages/compiler/src/ir/builtin-effects.ts b/packages/compiler/src/ir/builtin-effects.ts index ca8c52118..3dc6dcebd 100644 --- a/packages/compiler/src/ir/builtin-effects.ts +++ b/packages/compiler/src/ir/builtin-effects.ts @@ -13,6 +13,15 @@ export const MAY_THROW_LIB_FNS: ReadonlySet = new Set([ // Node's curve, key, point, encoding and format errors. "crypto.ecdhNew", "crypto.ecdhConvertKey", + // Node's prime, generator, size, encoding and group-name errors. + "crypto.dhNew", + "crypto.dhGroupNew", + // Node's candidate, size, options, add and rem errors, and OpenSSL's + // generation errors. + "crypto.checkPrimeSync", + "crypto.checkPrimeCb", + "crypto.generatePrimeSync", + "crypto.generatePrimeCb", // node:test's { timeout } and { concurrency } range checks. "test.register", "test.registerEmpty", @@ -80,10 +89,13 @@ export const MAY_THROW_LIB_FNS: ReadonlySet = new Set([ "procStream.write", "child.stdioStream", "stream.unboxDyn", + "stream.handleStream", "stream.pipeDyn", "stream.unpipeDyn", "weakMap.new", "weakSet.new", + // Node's "cleanup must be callable" TypeError. + "finalizationRegistry.new", "dyn.fromEntries", "bytes.constructor", "bytes.instanceOf", @@ -97,6 +109,9 @@ export const MAY_THROW_LIB_FNS: ReadonlySet = new Set([ "atomics.op", "atomics.wait", "atomics.notify", + "atomics.opDyn", + "atomics.waitDyn", + "atomics.notifyDyn", "arrayBuffer.byteLengthGetter", "arrayBuffer.viewU8C", "arrayBuffer.viewI8", @@ -226,6 +241,8 @@ export const MAY_THROW_LIB_FNS: ReadonlySet = new Set([ "http2.createSecureServerDynCb", "tls.connect", "tls.connectCb", + "tls.wrapSocket", + "tls.wrapSocketCtx", // The CA-store surface: an unknown getCACertificates type throws // Node's ERR_INVALID_ARG_VALUE TypeError; setDefaultCACertificates // throws Node's ERR_CRYPTO_OPERATION_FAILED on a certificate-free @@ -331,7 +348,9 @@ export const MAY_THROW_LIB_FNS: ReadonlySet = new Set([ "sp.finished", "sp.pipeline", "sp.pipelineStages", + "sp.pipelineStagesOpts", "stream.pipelineStages", + "stream.composeStages", "stream.pipelineStagesDyn", "sc.text", "sc.json", @@ -354,6 +373,7 @@ export const MAY_THROW_LIB_FNS: ReadonlySet = new Set([ "readable.pushU", "readable.pushDyn", "readable.unshift", + "readable.unshiftDyn", "readable.unshiftStr", "readable.read", "readable.readDyn", @@ -366,8 +386,17 @@ export const MAY_THROW_LIB_FNS: ReadonlySet = new Set([ "writable.writeStr", "writable.writeU", "writable.writeDyn", + "writable.writeEnc", "writable.end", "writable.uncork", + "writable.setDefaultEncoding", + "stream.duplexFromGen", + "stream.duplexFromDyn", + "stream.duplexFromPromise", + "stream.duplexFromAsyncFn", + "stream.duplexFromGenSignal", + "stream.duplexFromAsyncFnSignal", + "fetch.readableFromWeb", "stream.destroy", "stream.destroyErr", "stream.iteratorClose", @@ -502,6 +531,8 @@ export const MAY_THROW_LIB_FNS: ReadonlySet = new Set([ "readable.opMap", "readable.opFilter", "readable.opFlatMap", + "readable.opFlatMapAsyncGen", + "readable.opFlatMapSyncGen", "readable.opDrop", "readable.opTake", "rl.createSignal", @@ -534,6 +565,7 @@ export const MAY_THROW_LIB_FNS: ReadonlySet = new Set([ "date.nativeNew", "date.nativeNewFields", "date.nativeNewValue", + "date.argumentsTime", "date.checkedValue", "util.parseArgs", "util.parseEnv", @@ -601,6 +633,9 @@ export const MAY_THROW_LIB_FNS: ReadonlySet = new Set([ "dyn.objCreateWithProperties", "dyn.getPrototype", "dyn.setPrototype", + // Error.captureStackTrace: Node's TypeError for a primitive target, and + // the error string conversion of name and message + "dyn.errorCaptureStackTrace", // a proxy in the prototype chain can throw "dyn.builtinInstanceOf", "dyn.functionInstanceOf", @@ -786,6 +821,7 @@ export const MAY_THROW_LIB_FNS: ReadonlySet = new Set([ "buffer.poolFromArray", "buffer.poolFromDyn", "buffer.poolFromDynRef", + "buffer.poolFromDynOffset", // The checked-dynamic compare/equals validators: Node's argument // ladders throw ERR_INVALID_ARG_TYPE / ERR_OUT_OF_RANGE catchably. "buffer.compareChk", @@ -976,4 +1012,34 @@ export const MAY_THROW_LIB_FNS: ReadonlySet = new Set([ "crypto.x509ValidFromStr", "crypto.x509ValidTo", "crypto.x509ValidToStr", + "crypto.createPrivateKey", + "crypto.createPublicKey", + "crypto.generateKeyPairSync", + "crypto.generateKeyPairCb", + "crypto.signOneshot", + "crypto.verifyOneshot", + "crypto.createSign", + "crypto.createVerify", +]); + +/** libCall members that always throw. Their result type is the replaced + * expression's own and is never materialized: global.undefRead's is the + * declared type of the undefined global; the others stand in for a value + * of the expression they replace. The fs Chk ladders qualify: every + * validation failure throws Node's typed error, and a full pass throws the + * trailing compiler-rendered fence. */ +export const ALWAYS_THROW_LIB_FNS: ReadonlySet = new Set([ + "global.undefRead", + "error.nodeThrow", + "error.argTypeThrow", + "error.propTypeThrow", + "fs.mkdtempChk", + "fs.readFileChk", + "fs.opendirChk", + "fs.watchFileChk", + "fs.lchmodChk", + "fs.readChk", + "fs.streamOptsChk", + "net.connectOptsChk", + "tls.caCertsChk", ]); diff --git a/packages/compiler/src/ir/builtin-signatures.ts b/packages/compiler/src/ir/builtin-signatures.ts index 054b16201..a8feab74c 100644 --- a/packages/compiler/src/ir/builtin-signatures.ts +++ b/packages/compiler/src/ir/builtin-signatures.ts @@ -170,6 +170,9 @@ export const LIB_FN_SIGS = defineLibFnSignatures({ "fetch.streamFrom": { argTypes: [null], result: DYN }, // The chunk/result record depends on ReadableStream; validated by validate.ts. "fetch.readerRead": { argTypes: [DYN], result: VOID }, + /** Readable.fromWeb (scr_stream_from_web.c): the stream, objectMode, + * highWaterMark (< 0: the mode's default) and encoding ("": none). */ + "fetch.readableFromWeb": { argTypes: [DYN, BOOL, F64, STRING], result: VOID }, "json.parse": { argTypes: [STRING], result: DYN }, "json.parseReviver": { argTypes: [STRING, DYN], result: DYN }, "json.stringifyReplacer": { argTypes: [DYN, DYN, STRING], result: DYN }, @@ -272,6 +275,7 @@ export const LIB_FN_SIGS = defineLibFnSignatures({ "dyn.nativeMapIs": { argTypes: [DYN], result: BOOL }, "dyn.nativeUrlIs": { argTypes: [DYN], result: BOOL }, "dyn.nativeDateIs": { argTypes: [DYN], result: BOOL }, + "dyn.nativeDateHandleIs": { argTypes: [DYN], result: BOOL }, /** A builtin constructor (`Object`, `Date`, `RegExp`, `Map`, `Set`, * `Promise`, `WeakMap`, `WeakSet`) read as a JavaScript value: one * interned function per name, the same one dynamic values answer for @@ -291,6 +295,8 @@ export const LIB_FN_SIGS = defineLibFnSignatures({ /** `new Date(value)` in JavaScript: a string argument parses with V8's * full date parser; every other value constructs as date.nativeNew. */ "date.nativeNewValue": { argTypes: [DYN], result: DYN }, + "date.argumentsTime": { argTypes: [DYN], result: DATE_T }, + "date.classOperation": { argTypes: [DYN, DYN], result: VOID }, "date.checkedValue": { argTypes: [DYN], result: DATE_T }, "dyn.nativeRegexIs": { argTypes: [DYN], result: BOOL }, /** toString() on a checked-dynamic receiver: runtime kind dispatch @@ -1252,6 +1258,9 @@ export const LIB_FN_SIGS = defineLibFnSignatures({ "atomics.wait": { argTypes: [bytesOf("i32"), F64, F64, F64], result: STRING }, "atomics.notify": { argTypes: [bytesOf("i32"), F64, F64], result: F64 }, "atomics.op": { argTypes: [null, F64, F64, F64, F64], result: F64 }, + "atomics.opDyn": { argTypes: [DYN, F64, F64, F64, F64], result: F64 }, + "atomics.waitDyn": { argTypes: [DYN, F64, F64, F64], result: STRING }, + "atomics.notifyDyn": { argTypes: [DYN, F64, F64], result: F64 }, "worker.new": { argTypes: [F64, STRING, DYN], result: DYN }, "worker.isMainThread": { argTypes: [], result: BOOL }, "worker.threadId": { argTypes: [], result: F64 }, @@ -1312,6 +1321,12 @@ export const LIB_FN_SIGS = defineLibFnSignatures({ argTypes: [STRING, arrayOf(STRING), F64, STRING, F64, F64, F64], result: SPAWNRES_T, }, + /** cp.spawnSyncOpts with the `env` option: the trailing [k,v,...] + * pairs replace the child's environment (recordToEnvPairs). */ + "cp.spawnSyncEnv": { + argTypes: [STRING, arrayOf(STRING), F64, STRING, F64, F64, F64, arrayOf(STRING)], + result: SPAWNRES_T, + }, /** cp.spawnSyncOpts with the stdio carried as a RUNTIME string — * "pipe" | "ignore" | "inherit", proven by the call site's TYPE (the * defaultRunner idiom `stdio: options?.stdio ?? "pipe"`); the runtime @@ -1522,6 +1537,13 @@ export const LIB_FN_SIGS = defineLibFnSignatures({ }, "dgram.sendStr": { argTypes: [DGRAMSOCK_T, STRING, F64, STRING], result: VOID }, "dgram.sendBytes": { argTypes: [DGRAMSOCK_T, BYTES_U8, F64, STRING], result: VOID }, + /** Connected AF_UNIX datagram sockets for the hot-shots package shim + * (the unix-dgram addon's surface): fd or result >= 0, -errno on + * failure; send answers 1 when the socket would block. */ + "dgram.unixSocket": { argTypes: [], result: F64 }, + "dgram.unixConnect": { argTypes: [F64, STRING], result: F64 }, + "dgram.unixSend": { argTypes: [F64, BYTES_U8], result: F64 }, + "dgram.unixClose": { argTypes: [F64], result: F64 }, /** The send argument-validation ladder over dyn arguments (Node's * signature shuffle: slice bounds, list/type contracts, port/address * validation, connected-state errors), then the send: lists, connected @@ -2176,6 +2198,20 @@ export const LIB_FN_SIGS = defineLibFnSignatures({ result: VOID, }, "tls.sockOnSession": { argTypes: [NETSOCKET_T, null, BOOL], result: VOID }, + /** The 'secure' event: the handshake completed (after secureConnect on + * a client). Plain sockets never fire it. */ + "tls.sockOnSecure": { + argTypes: [NETSOCKET_T, { kind: "func", params: [], ret: VOID }, BOOL], + result: VOID, + }, + /** new tls.TLSSocket(socket, options) in server mode: a new TLS socket + * takes over the socket's connection (wrapSocketCtx passes a literal's + * secureContext member apart from the runtime options record). The + * record reads at runtime: isServer, cert, key, ALPNProtocols, + * minVersion and maxVersion are implemented, the client mode and other + * documented members throw the runtime fence. MAY THROW. */ + "tls.wrapSocket": { argTypes: [NETSOCKET_T, DYN], result: NETSOCKET_T }, + "tls.wrapSocketCtx": { argTypes: [NETSOCKET_T, DYN, SECURECTX_T], result: NETSOCKET_T }, // createSecureContext({ cert, key }) mints the opaque SNI-answer handle. /** tls.createSecureContext({ cert, key }) — parses the PEM pair into an * opaque SecureContext handle (secureCtx kind) for SNI callbacks to @@ -2712,6 +2748,12 @@ export const LIB_FN_SIGS = defineLibFnSignatures({ argTypes: [DYN, STRING], result: { kind: "object", className: "%Duplex" }, }, + /** The Transform a Cipheriv or Decipheriv reads and writes as a stream + * (+1, created on first use and owned by the cipher). */ + "stream.handleStream": { + argTypes: [DYN], + result: { kind: "object", className: "%Transform" }, + }, /** Checked-dynamic stream slots (dyn-streams.ts): the native stream a * checked-dynamic value boxes (+1) — a runtime stream with the readable * (1) or writable (2) side — or null for any other value. Never throws; @@ -2787,6 +2829,23 @@ export const LIB_FN_SIGS = defineLibFnSignatures({ /** ECDH.convertKey(key, curve, inputEncoding, outputEncoding, format): * the converted point as a Buffer or string. */ "crypto.ecdhConvertKey": { argTypes: [DYN, DYN, DYN, DYN, DYN], result: DYN }, + /** createDiffieHellman(sizeOrKey, keyEncoding, generator, + * generatorEncoding) over checked-dynamic arguments (scr_dh.c): a native + * DiffieHellman handle whose methods dispatch through dynInvoke. */ + "crypto.dhNew": { argTypes: [DYN, DYN, DYN, DYN], result: DYN }, + /** getDiffieHellman(groupName) and createDiffieHellmanGroup(name): a + * native DiffieHellmanGroup handle. */ + "crypto.dhGroupNew": { argTypes: [DYN], result: DYN }, + /** checkPrimeSync(candidate, options) and generatePrimeSync(size, + * options) over checked-dynamic arguments (scr_dh.c): a boolean, and an + * ArrayBuffer or bigint, as checked-dynamic results. The Cb forms take + * the callback and whether its error parameter takes null for Node's + * undefined, and call it in a later macrotask; Node's argument errors + * throw (may-throw). */ + "crypto.checkPrimeSync": { argTypes: [DYN, DYN], result: DYN }, + "crypto.checkPrimeCb": { argTypes: [DYN, DYN, DYN, BOOL], result: VOID }, + "crypto.generatePrimeSync": { argTypes: [DYN, DYN], result: DYN }, + "crypto.generatePrimeCb": { argTypes: [DYN, DYN, DYN, BOOL], result: VOID }, "crypto.hmacNewStr": { argTypes: [STRING, STRING], result: CRYPTOHMAC_T }, "crypto.hmacNewBytes": { argTypes: [STRING, BYTES_U8], result: CRYPTOHMAC_T }, "crypto.hashUpdateStr": { argTypes: [CRYPTOHASH_T, STRING], result: CRYPTOHASH_T }, @@ -2845,11 +2904,20 @@ export const LIB_FN_SIGS = defineLibFnSignatures({ /** WebCrypto (scr_webcrypto.c): each method takes its argument vector as * one dyn array and answers a promise that argument and validation * failures reject. CryptoKey values are native handles. */ + "webcrypto.generateKey": { argTypes: [DYN], result: { kind: "promise", inner: DYN } }, "webcrypto.importKey": { argTypes: [DYN], result: { kind: "promise", inner: DYN } }, + "webcrypto.exportKey": { argTypes: [DYN], result: { kind: "promise", inner: DYN } }, + "webcrypto.encrypt": { argTypes: [DYN], result: { kind: "promise", inner: DYN } }, + "webcrypto.decrypt": { argTypes: [DYN], result: { kind: "promise", inner: DYN } }, + "webcrypto.wrapKey": { argTypes: [DYN], result: { kind: "promise", inner: DYN } }, + "webcrypto.unwrapKey": { argTypes: [DYN], result: { kind: "promise", inner: DYN } }, + "webcrypto.deriveBits": { argTypes: [DYN], result: { kind: "promise", inner: DYN } }, + "webcrypto.deriveKey": { argTypes: [DYN], result: { kind: "promise", inner: DYN } }, "webcrypto.sign": { argTypes: [DYN], result: { kind: "promise", inner: DYN } }, "webcrypto.verify": { argTypes: [DYN], result: { kind: "promise", inner: BOOL } }, "webcrypto.digest": { argTypes: [DYN], result: { kind: "promise", inner: DYN } }, "webcrypto.isCryptoKey": { argTypes: [DYN], result: BOOL }, + "webcrypto.object": { argTypes: [], result: DYN }, "crypto.randomUUIDv7": { argTypes: [DYN], result: STRING }, "crypto.pbkdf2": { argTypes: [BYTES_U8, BYTES_U8, F64, F64, STRING], result: BYTES_U8 }, "crypto.randomBytesCb": { argTypes: [F64, null], result: VOID }, @@ -2918,6 +2986,7 @@ export const LIB_FN_SIGS = defineLibFnSignatures({ "buffer.poolFromDyn": { argTypes: [DYN, STRING], result: BYTES_U8 }, /** poolFromDyn that also copies an array crossing by reference. */ "buffer.poolFromDynRef": { argTypes: [DYN, STRING], result: BYTES_U8 }, + "buffer.poolFromDynOffset": { argTypes: [DYN, DYN], result: BYTES_U8 }, "buffer.poolSize": { argTypes: [], result: F64 }, "buffer.setPoolSize": { argTypes: [F64], result: VOID }, /** Buffer.byteLength(string, enc) — enc a NORMALIZED literal like @@ -3548,9 +3617,11 @@ export const LIB_FN_SIGS = defineLibFnSignatures({ "weakSet.is": { argTypes: [DYN], result: BOOL }, "weakMap.new": { argTypes: [DYN], result: DYN }, "weakSet.new": { argTypes: [DYN], result: DYN }, + "finalizationRegistry.new": { argTypes: [DYN], result: DYN }, + "finalizationRegistry.is": { argTypes: [DYN], result: BOOL }, "dyn.fromEntries": { argTypes: [DYN], result: DYN }, "bytes.constructor": { argTypes: [STRING], result: DYN }, - "bytes.instanceOf": { argTypes: [DYN, DYN], result: BOOL }, + "bytes.instanceOf": { argTypes: [DYN, DYN, STRING], result: BOOL }, "bytes.construct": { argTypes: [DYN, DYN, STRING], result: DYN }, /** The ambient receiver — JS `this` in a plain (non-method) function * body: the innermost binding the current firing/dispatch window @@ -3646,6 +3717,10 @@ export const LIB_FN_SIGS = defineLibFnSignatures({ "dyn.arrayPrototype": { argTypes: [], result: DYN }, "dyn.arrayConstructor": { argTypes: [], result: DYN }, "dyn.objectPrototype": { argTypes: [], result: DYN }, + "dyn.errorPrototype": { argTypes: [], result: DYN }, + "dyn.inheritsErrorPrototype": { argTypes: [DYN], result: BOOL }, + "dyn.errorCaptureStackTrace": { argTypes: [DYN], result: DYN }, + "dyn.errorCaptureStackTraceFunction": { argTypes: [], result: DYN }, "dyn.functionApply": { argTypes: [], result: DYN }, "dyn.builtinMethod": { argTypes: [STRING, STRING], result: DYN }, "dyn.classPrototype": { argTypes: [DYN, DYN], result: DYN }, @@ -3855,7 +3930,11 @@ export const LIB_FN_SIGS = defineLibFnSignatures({ * readable.unpipe (recv[, dst]) → recv +1. * writable.write/writeStr: (recv, chunk[, cb]) → below-hwm bool (cb * MOVES when present, called after the user write completes). - * writable.end: (recv, flags[, chunk][, cb]) → recv +1. cork/uncork are + * writable.writeEnc: (recv, flags, chunk[, encoding][, cb]) — flags 1 + * an encoding argument, 2 a callback (the encoding is then null, as + * Node's write shifts it). + * writable.end: (recv, flags[, chunk][, encoding][, cb]) → recv +1; + * flags 16: an encoding argument follows the dyn chunk. cork/uncork are * void. stream.destroy/destroyErr: (recv[, err]) → recv +1. * stream.prop: (recv, name-literal) → the flag/number the name asks * for; stream.errored → Error|null union; readable.flowing → @@ -3883,6 +3962,9 @@ export const LIB_FN_SIGS = defineLibFnSignatures({ "stream.setDestroy": { argTypes: [null, null], result: VOID }, "stream.setTransform": { argTypes: [null, null], result: VOID }, "stream.setFlush": { argTypes: [null, null], result: VOID }, + "stream.setConstruct": { argTypes: [null, null], result: VOID }, + "stream.setWritev": { argTypes: [null, null], result: VOID }, + "stream.setWritevDefault": { argTypes: [null, null], result: VOID }, /** The dyn-options twins (a checked-dynamic options record — the JS * lane's `super(options)` forwarding and `new Readable(dynVar)`): the * option walk runs at RUNTIME with Node's reading rules. newDyn: @@ -3909,6 +3991,7 @@ export const LIB_FN_SIGS = defineLibFnSignatures({ "stream.pipeline": { argTypes: [F64], result: VOID }, "stream.pipelineDyn": { argTypes: [F64], result: VOID }, "stream.pipelineStages": { argTypes: [F64, F64, F64, F64, F64], result: VOID }, + "stream.composeStages": { argTypes: [F64, F64, F64, F64, F64], result: VOID }, "stream.pipelineStagesDyn": { argTypes: [F64, F64, F64, F64, F64], result: VOID }, /** stream.compose(count, s1..sn): the Duplex over a pipeline of the * streams (+1). MAY THROW (ERR_INVALID_ARG_VALUE for a stream that is @@ -3940,18 +4023,25 @@ export const LIB_FN_SIGS = defineLibFnSignatures({ "stream.finishedOpts": { argTypes: [null, F64, F64, BOOL, null], result: VOID }, "stream.finishedOptsSignal": { argTypes: [null, F64, F64, BOOL, DYN, null], result: VOID }, "sp.pipeline": { argTypes: [F64], result: { kind: "promise", inner: VOID } }, - /** pipeline with a run of function stages: [n, at, k, flags, mask, - * s1..sn, stage1..stagek, (next, read, return)?, box?, (signal, - * abort)?] (+ the callback for the stream.* forms): the user's stage - * functions, the frontend's helpers over the pumped generator or a - * promise destination's box, and the pipeline's AbortSignal with its - * abort closure; flags names which groups are present - * (scr_stream_pipeline_stages). A promise destination's promise type is - * sp.pipelineStages' result. */ + /** pipeline with function stages: [n, k, positions, flags, mask, + * s1..sn, stage1..stagek, helpers..., box?, (signal, abort)?] (+ the + * callback for the stream.* forms): the user's stage functions at the + * positions the bitmask names, the frontend's (next, read, return) + * helpers for each pumped generator (pipelinePumpedRuns) and a promise + * destination's box, and the pipeline's AbortSignal with its abort + * closure; flags bits 1-2 give the destination kind and bit 5 the + * signal group (scr_stream_pipeline_stages). A promise destination's + * promise type is sp.pipelineStages' result. */ "sp.pipelineStages": { argTypes: [F64, F64, F64, F64, F64], result: { kind: "promise", inner: VOID }, }, + /** sp.pipelineStages with the options argument: the same head, then + * end (a bool) and, with flags bit 6, the options' signal (dyn). */ + "sp.pipelineStagesOpts": { + argTypes: [F64, F64, F64, F64, F64], + result: { kind: "promise", inner: VOID }, + }, /** node:stream/consumers — the promise consumers over the readable * machinery: (s) → a pending promise settled at the terminal point * with the accumulated result (sc.text: the utf8 decode, sc.json: the @@ -3993,6 +4083,7 @@ export const LIB_FN_SIGS = defineLibFnSignatures({ "readable.pushU": { argTypes: [null, null], result: BOOL }, "readable.pushDyn": { argTypes: [null, DYN], result: BOOL }, "readable.unshift": { argTypes: [null, BYTES_U8], result: VOID }, + "readable.unshiftDyn": { argTypes: [null, DYN], result: VOID }, "readable.unshiftStr": { argTypes: [null, STRING], result: VOID }, "stream.onDyn": { argTypes: [null, STRING, DYN, BOOL, BOOL], result: VOID }, "readable.readDyn": { argTypes: [null, DYN], result: DYN }, @@ -4004,6 +4095,34 @@ export const LIB_FN_SIGS = defineLibFnSignatures({ * Buffer.from(chunk, enc)); both carry the CANONICAL literal. */ "readable.pushStrEnc": { argTypes: [null, STRING, STRING], result: BOOL }, "readable.pushEncoding": { argTypes: [null, STRING], result: VOID }, + /** The objectMode option's sides (readable, writable), applied right + * after construction; answers the receiver (+1, the chaining shape). */ + "stream.objectMode": { argTypes: [null, BOOL, BOOL], result: VOID }, + "stream.decodeStrings": { argTypes: [null, BOOL], result: VOID }, + "stream.duplexFromGen": { argTypes: [null, null, null, null, null, null], result: VOID }, + "stream.duplexFromDyn": { argTypes: [DYN], result: VOID }, + /** Duplex.from over a lone Readable or Writable, or a { readable, + * writable } pair of streams (duplexify.js's _duplexify). */ + "stream.duplexifyReadable": { argTypes: [null], result: VOID }, + "stream.duplexifyWritable": { argTypes: [null], result: VOID }, + "stream.duplexifyPair": { argTypes: [null, null], result: VOID }, + /** Duplex.from(promise): the promise and its box helper. */ + "stream.duplexFromPromise": { argTypes: [null, null], result: VOID }, + /** Duplex.from(asyncFunction): the stage, its source helper and the + * promise's box helper. */ + "stream.duplexFromAsyncFn": { argTypes: [null, null, null], result: VOID }, + /** The same for a body that declares the options argument: then the + * AbortController's abort() and its signal. */ + "stream.duplexFromGenSignal": { + argTypes: [null, null, null, null, null, null, null, DYN], + result: VOID, + }, + "stream.duplexFromAsyncFnSignal": { argTypes: [null, null, null, null, DYN], result: VOID }, + "writable.writeEncoding": { argTypes: [null, STRING], result: VOID }, + "writable.setDefaultEncoding": { argTypes: [null, DYN], result: VOID }, + /** Whether a readable.nextChunkDyn step answered the end (the done + * marker; an object-mode stream can yield undefined). */ + "stream.chunkDone": { argTypes: [DYN], result: BOOL }, /** for-await over a readable (the desugared loop's per-pass promise): * +1 promise of the next chunk — buffered content, the EOF sentinel * (empty Buffer / dyn undefined), or a rejection with the stream's @@ -4036,17 +4155,39 @@ export const LIB_FN_SIGS = defineLibFnSignatures({ * forEach nothing; reduce: [stream, fn, init, hasInit, options, kind] * with the payload kind (0 dyn, 1 number, 2 boolean, 3 string). The * promise-returning ones reject instead of throwing. */ - "readable.opMap": { argTypes: [null, DYN, DYN], result: VOID }, - "readable.opFilter": { argTypes: [null, DYN, DYN], result: VOID }, - "readable.opFlatMap": { argTypes: [null, DYN, DYN], result: VOID }, + "readable.opMap": { argTypes: [null, DYN, DYN, DYN], result: VOID }, + "readable.opFilter": { argTypes: [null, DYN, DYN, DYN], result: VOID }, + "readable.opFlatMap": { argTypes: [null, DYN, DYN, DYN], result: VOID }, + /** flatMap whose callback returns a compiled generator: the helpers + * over its type follow (async: next, read, return, throw; sync: next, + * return, throw). */ + "readable.opFlatMapAsyncGen": { + argTypes: [null, DYN, DYN, DYN, null, null, null, null], + result: VOID, + }, + "readable.opFlatMapSyncGen": { argTypes: [null, DYN, DYN, DYN, null, null, null], result: VOID }, "readable.opDrop": { argTypes: [null, DYN, DYN], result: VOID }, "readable.opTake": { argTypes: [null, DYN, DYN], result: VOID }, "readable.opToArray": { argTypes: [null, DYN], result: { kind: "promise", inner: DYN } }, - "readable.opForEach": { argTypes: [null, DYN, DYN], result: { kind: "promise", inner: VOID } }, - "readable.opSome": { argTypes: [null, DYN, DYN], result: { kind: "promise", inner: BOOL } }, - "readable.opEvery": { argTypes: [null, DYN, DYN], result: { kind: "promise", inner: BOOL } }, - "readable.opFind": { argTypes: [null, DYN, DYN], result: { kind: "promise", inner: DYN } }, + "readable.opForEach": { + argTypes: [null, DYN, DYN, DYN], + result: { kind: "promise", inner: VOID }, + }, + "readable.opSome": { argTypes: [null, DYN, DYN, DYN], result: { kind: "promise", inner: BOOL } }, + "readable.opEvery": { argTypes: [null, DYN, DYN, DYN], result: { kind: "promise", inner: BOOL } }, + "readable.opFind": { argTypes: [null, DYN, DYN, DYN], result: { kind: "promise", inner: DYN } }, + /** The map family's last argument is the callback's { signal } (or + * undefined). reduceSignal adds ac.abort() (a closure) and + * { signal: ac.signal } for a reducer that reads them. */ "readable.opReduce": { argTypes: [null, DYN, DYN, BOOL, DYN, F64], result: VOID }, + "readable.opReduceSignal": { + argTypes: [null, DYN, DYN, BOOL, DYN, F64, null, DYN], + result: VOID, + }, + "readable.opSignalList": { argTypes: [DYN], result: DYN }, + "readable.opSignalOpts": { argTypes: [DYN], result: DYN }, + "readable.opSignalOf": { argTypes: [DYN], result: DYN }, + "readable.opOnceOptions": { argTypes: [], result: DYN }, "readable.resume": { argTypes: [null], result: VOID }, "readable.isPaused": { argTypes: [null], result: BOOL }, "readable.pipe": { argTypes: [null, null, BOOL], result: VOID }, @@ -4057,6 +4198,7 @@ export const LIB_FN_SIGS = defineLibFnSignatures({ "writable.writeStr": { argTypes: [null, STRING], result: BOOL }, "writable.writeU": { argTypes: [null, null], result: BOOL }, "writable.writeDyn": { argTypes: [null, DYN], result: BOOL }, + "writable.writeEnc": { argTypes: [null, F64, DYN], result: BOOL }, "writable.end": { argTypes: [null, F64], result: VOID }, "writable.cork": { argTypes: [null], result: VOID }, "writable.uncork": { argTypes: [null], result: VOID }, @@ -4642,6 +4784,19 @@ export const LIB_FN_SIGS = defineLibFnSignatures({ * body passes its undefined result on into a Buffer slot. Owned (+1); * never throws. */ "bytes.absent": { argTypes: [], result: BYTES_U8 }, + /** node:crypto asymmetric keys and signatures (scr_pki.c): checked- + * dynamic arguments, borrowed; KeyObject, Sign and Verify handles, + * Buffers and booleans as checked-dynamic results (+1). Node's argument + * and decoder errors throw (may-throw); generateKeyPairCb's callback + * receives (null, publicKey, privateKey) in a later macrotask. */ + "crypto.createPrivateKey": { argTypes: [DYN], result: DYN }, + "crypto.createPublicKey": { argTypes: [DYN], result: DYN }, + "crypto.generateKeyPairSync": { argTypes: [DYN, DYN], result: DYN }, + "crypto.generateKeyPairCb": { argTypes: [DYN, DYN, DYN], result: VOID }, + "crypto.signOneshot": { argTypes: [DYN, DYN, DYN], result: DYN }, + "crypto.verifyOneshot": { argTypes: [DYN, DYN, DYN, DYN], result: DYN }, + "crypto.createSign": { argTypes: [DYN], result: DYN }, + "crypto.createVerify": { argTypes: [DYN], result: DYN }, /** The Buffer brand of a Uint8Array source onto a fresh Uint8Array * result (map and filter of a Buffer return a Buffer). */ "bytes.copyBrand": { argTypes: [BYTES_U8, BYTES_U8], result: VOID }, @@ -4738,3 +4893,17 @@ export const LIB_FN_SIGS = defineLibFnSignatures({ /** A builtin name exists exactly when its runtime signature exists. */ export type IrLibFn = keyof typeof LIB_FN_SIGS; + +/** The function-stage runs of a pipeline of `total` stages that a stream + * follows (positions bit j: stage j is a function), and an async + * generator destination's run (flags bits 1-2 = 1, pumped into the + * PassThrough pipeline() answers): each pumps its last generator through + * one (next, read, return) triple. */ +export function pipelinePumpedRuns(total: number, positions: number, flags: number): number { + let runs = ((flags >> 1) & 3) === 1 ? 1 : 0; + for (let j = 0; j + 1 < total; j++) { + if (Math.floor(positions / 2 ** j) % 2 === 1 && Math.floor(positions / 2 ** (j + 1)) % 2 === 0) + runs++; + } + return runs; +} diff --git a/packages/compiler/src/ir/char-unit-locals.test.ts b/packages/compiler/src/ir/char-unit-locals.test.ts new file mode 100644 index 000000000..ad16ecebd --- /dev/null +++ b/packages/compiler/src/ir/char-unit-locals.test.ts @@ -0,0 +1,98 @@ +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { expect, test } from "vitest"; +import { compile, deserializeModule } from "../index.js"; +import { holdCharLocalsAsUnits } from "./char-unit-locals.js"; +import type { IrFunction, IrModule } from "./ir.js"; +import { everyStmtList } from "./traverse.js"; + +async function lower(source: string): Promise { + const dir = await mkdtemp(join(tmpdir(), "scriptc-char-units-")); + try { + const entry = join(dir, "main.ts"); + const outPath = join(dir, "main.ir.json"); + await writeFile(entry, source); + const result = await compile(entry, { outDir: dir, outPath, outputKind: "ir" }); + if (!result.ok) + throw new Error(result.diagnostics.map((d) => `${d.code}: ${d.message}`).join("\n")); + return deserializeModule(await readFile(outPath, "utf8")); + } finally { + await rm(dir, { recursive: true, force: true }); + } +} + +const fn = (mod: IrModule, name: string): IrFunction => mod.functions.find((f) => f.name === name)!; + +/** The kinds of the function's string tests and string intrinsics. */ +function reads(f: IrFunction): string[] { + const out: string[] = []; + everyStmtList(f.body, { + stmt: () => true, + expr: (e) => { + if (e.kind === "strEq" || e.kind === "strCmp") out.push(e.kind); + if (e.kind === "strIntrinsic") out.push(e.method); + return true; + }, + }); + return out; +} + +test("a character local used only in one-unit tests holds its code unit", async () => { + const mod = holdCharLocalsAsUnits( + await lower(` +function classify(s: string, i: number): number { + const c = s.charAt(i); + let n = 0; + if (c === " ") n += 1; + if (c !== "\\t") n += 2; + if ("a" <= c && c <= "z") n += 4; + if (c < "0" || c > "9") n += 8; + switch (c) { + case "5": + n += 16; + break; + default: + n += 32; + } + return n; +} +console.log(classify("a b", 1), classify("x", 0), classify("7", 0), classify("5", 0), classify("", 3)); +`), + ); + const classify = fn(mod, "classify"); + expect(reads(classify)).toEqual(["charCodeAt"]); + expect(classify.locals.find((l) => l.name === "c")!.type).toEqual({ kind: "f64" }); +}); + +test("a character local with any other use stays a string", async () => { + const before = await lower(` +function escapes(s: string, i: number): string { + const c = s.charAt(i); + return c === " " ? "space" : c; +} +function rebound(s: string, i: number): boolean { + let c = s.charAt(i); + if (c === " ") c = s.charAt(i + 1); + return c === "x"; +} +function wide(s: string, i: number): boolean { + const c = s.charAt(i); + return c === "ab" || c < "b"; +} +function against(s: string, t: string, i: number): boolean { + const c = s.charAt(i); + return c < t; +} +function captured(s: string, i: number): () => boolean { + const c = s.charAt(i); + return () => c === "y"; +} +console.log(escapes("a b", 1), rebound(" x", 0), wide("ab", 0), against("a", "b", 0), captured("y", 0)()); +`); + const after = holdCharLocalsAsUnits(before); + for (const name of ["escapes", "rebound", "wide", "against", "captured"]) { + expect(fn(before, name)).toBeDefined(); + expect(fn(after, name)).toBe(fn(before, name)); + } +}); diff --git a/packages/compiler/src/ir/char-unit-locals.ts b/packages/compiler/src/ir/char-unit-locals.ts new file mode 100644 index 000000000..4008f4e1e --- /dev/null +++ b/packages/compiler/src/ir/char-unit-locals.ts @@ -0,0 +1,190 @@ +import { + BOOL, + F64, + type IrExpr, + type IrFunction, + type IrLocal, + type IrModule, + type IrStmt, +} from "./ir.js"; +import { mapExprChildren, mapStmtChildren } from "./traverse.js"; + +type CharAt = IrExpr & { kind: "strIntrinsic" }; +type UnitUse = IrExpr & { kind: "strEq" | "strCmp" }; + +/** Character locals held as their code unit. + * + * `const c = s[i]` (or `s.charAt(i)`) followed only by tests such as + * `c === " "`, `c >= "a" && c <= "z"` or `switch (c) { case "x": ... }` + * against literals of one UTF-16 code unit builds a one-character string + * and compares strings, though every answer follows from the code unit. + * Such a local holds `s.charCodeAt(i)` instead, and each test compares + * numbers: + * - a one-unit string compares as its unit; + * - charAt reads "" for an index out of range, and charCodeAt reads NaN. + * "" equals no one-unit literal and is below each, while NaN equals no + * unit and fails every ordered comparison, so `c < "x"` becomes + * `!(c >= 120)`. + * + * Only immutable unboxed string locals qualify, with one declaration whose + * initializer is a one-argument charAt, and with no other mention of the + * local. */ +export function holdCharLocalsAsUnits(mod: IrModule): IrModule { + let changed = false; + const functions = mod.functions.map((fn) => { + const next = rewriteFunction(fn); + if (next !== fn) changed = true; + return next; + }); + return changed ? { ...mod, functions } : mod; +} + +function rewriteFunction(fn: IrFunction): IrFunction { + const candidates = new Set( + fn.locals.filter((l) => !l.mutable && !l.boxed && l.type.kind === "string").map((l) => l.id), + ); + if (candidates.size === 0) return fn; + // Every mention of a candidate, in any field, against the mentions the + // rewrite understands. + const mentions = new Map(); + const understood = new Map(); + const declarations = new Map(); + const note = (map: Map, id: string): void => { + map.set(id, (map.get(id) ?? 0) + 1); + }; + const count = (value: unknown): void => { + if (typeof value === "string") { + if (candidates.has(value)) note(mentions, value); + } else if (Array.isArray(value)) { + for (const item of value) count(item); + } else if (value !== null && typeof value === "object") { + const node = value as Record; + const id = understoodMention(node); + if (id !== null && candidates.has(id)) { + note(understood, id); + if (node.kind === "varDecl") note(declarations, id); + } + for (const key in node) if (key !== "loc") count(node[key]); + } + }; + count(fn.body); + const held = new Set(); + for (const id of candidates) + if ( + declarations.get(id) === 1 && + (mentions.get(id) ?? 0) > 0 && + mentions.get(id) === understood.get(id) + ) + held.add(id); + if (held.size === 0) return fn; + + const unitRef = (id: string, loc: IrExpr["loc"]): IrExpr => ({ + kind: "varRef", + localId: id, + type: F64, + loc, + }); + const rewriteExpr = (e: IrExpr): IrExpr => { + if (e.kind === "strEq" || e.kind === "strCmp") { + const use = unitUse(e); + if (use && held.has(use.id)) { + const code: IrExpr = { kind: "numLit", value: use.code, type: F64, loc: e.loc }; + const c = unitRef(use.id, e.loc); + if (e.kind === "strEq") + return { + kind: "bin", + op: e.negated ? "!==" : "===", + left: c, + right: code, + type: BOOL, + loc: e.loc, + }; + // The comparison with the local on the left. + const op = use.left + ? e.op + : ({ "<": ">", "<=": ">=", ">": "<", ">=": "<=" } as const)[e.op]; + if (op === ">" || op === ">=") + return { kind: "bin", op, left: c, right: code, type: BOOL, loc: e.loc }; + const negation: IrExpr = { + kind: "bin", + op: op === "<" ? ">=" : ">", + left: c, + right: code, + type: BOOL, + loc: e.loc, + }; + return { kind: "unary", op: "!", operand: negation, type: BOOL, loc: e.loc }; + } + } + return mapExprChildren(e, rewriteExpr, rewriteStmt); + }; + const rewriteStmt = (s: IrStmt): IrStmt => { + if (s.kind === "varDecl" && held.has(s.localId) && s.init?.kind === "strIntrinsic") + return { + ...s, + init: { + ...s.init, + method: "charCodeAt", + receiver: rewriteExpr(s.init.receiver), + args: s.init.args.map(rewriteExpr), + type: F64, + }, + }; + if (s.kind === "switch" && s.disc.kind === "varRef" && held.has(s.disc.localId)) + return { + ...s, + disc: unitRef(s.disc.localId, s.disc.loc), + cases: s.cases.map((c) => ({ + ...c, + test: + c.test?.kind === "strLit" + ? { kind: "numLit", value: c.test.value.charCodeAt(0), type: F64, loc: c.test.loc } + : c.test, + body: c.body.map(rewriteStmt), + })), + }; + return mapStmtChildren(s, rewriteExpr, rewriteStmt); + }; + return { + ...fn, + body: fn.body.map(rewriteStmt), + locals: fn.locals.map((l) => (held.has(l.id) ? unitLocal(l) : l)), + }; +} + +/** The local, holding the code unit instead of the one-character string. */ +function unitLocal(local: IrLocal): IrLocal { + return { ...local, type: F64 }; +} + +/** The local a node mentions in a form the rewrite handles: the + * declaration from a one-argument charAt, a one-unit test, or a switch + * over one-unit cases. */ +function understoodMention(node: Record): string | null { + const n = node as unknown as IrExpr | IrStmt; + if (n.kind === "varDecl") return n.init && isCharAt(n.init) ? n.localId : null; + if (n.kind === "strEq" || n.kind === "strCmp") return unitUse(n)?.id ?? null; + if (n.kind === "switch") { + if (n.disc.kind !== "varRef") return null; + if (!n.cases.some((c) => c.test !== null)) return null; + const units = n.cases.every( + (c) => c.test === null || (c.test.kind === "strLit" && c.test.value.length === 1), + ); + return units ? n.disc.localId : null; + } + return null; +} + +function isCharAt(e: IrExpr): e is CharAt { + return e.kind === "strIntrinsic" && e.method === "charAt" && e.args.length === 1; +} + +/** A test between a local and a literal of one code unit. */ +function unitUse(e: UnitUse): { id: string; code: number; left: boolean } | null { + const literalRight = e.right.kind === "strLit"; + const literal = literalRight ? e.right : e.left; + const other = literalRight ? e.left : e.right; + if (literal.kind !== "strLit" || literal.value.length !== 1 || other.kind !== "varRef") + return null; + return { id: other.localId, code: literal.value.charCodeAt(0), left: literalRight }; +} diff --git a/packages/compiler/src/ir/int32-slots.ts b/packages/compiler/src/ir/int32-slots.ts index 6ff148c55..ac0747276 100644 --- a/packages/compiler/src/ir/int32-slots.ts +++ b/packages/compiler/src/ir/int32-slots.ts @@ -349,6 +349,7 @@ const DYN_READ_ONLY = new Set([ "date.nativeNew", "date.nativeNewFields", "date.nativeNewValue", + "date.argumentsTime", // The dynamic operators run the ToPrimitive and coercion helpers of // dyn.compare, dyn.numberConstructor and dyn.toStringCoerce, then build a // fresh number, string or bigint. dyn.increment steps dyn.toNumeric's result. @@ -507,7 +508,10 @@ export function dynamicFieldStores( }; const dynWritten = new Set(); let dynWritesAll = false; - for (const fn of mod.functions) + // A store whose key is not a literal names every field: later stores add + // nothing, so the walk stops there. + for (const fn of mod.functions) { + if (dynWritesAll) break; walkFunction(fn, { expr: (e) => { if (dynWritesAll) return; @@ -523,6 +527,7 @@ export function dynamicFieldStores( } }, }); + } return { all: dynWritesAll, names: dynWritten }; } @@ -535,6 +540,22 @@ export function dynamicallyStoredFamilies( slots: Int32Slots, stores?: DynamicFieldStores, ): Set { + const records = new Map((mod.records ?? []).map((r) => [r.id, r])); + const unions = new Map((mod.unions ?? []).map((u) => [u.id, u])); + // A live dyn view (typed-ref capsule) of an instance writes back into + // its fields only after a runtime store into the capsule; the commit then + // writes every field from the view, which holds the exact snapshot value + // of any property no store named. So reaching dynamic code disqualifies + // exactly the field names some dynamic store in the program can name. + const { all: dynWritesAll, names: dynWritten } = + stores ?? dynamicFieldStores(mod, records, unions); + const storable = (field: { name: string; type: IrType }): boolean => + field.type.kind === "f64" && + !field.name.startsWith("%") && + (dynWritesAll || dynWritten.has(field.name)); + const families = new Set(); + // Without a field some store can name, no class is worth exposing. + if (!(mod.classes ?? []).some((cls) => cls.fields.some(storable))) return families; const classes = new Map((mod.classes ?? []).map((c) => [c.name, c])); const children = new Map(); for (const cls of classes.values()) @@ -553,8 +574,6 @@ export function dynamicallyStoredFamilies( } return out; }; - const records = new Map((mod.records ?? []).map((r) => [r.id, r])); - const unions = new Map((mod.unions ?? []).map((u) => [u.id, u])); const exposedClasses = new Set(); const seenNamed = new Set(); let exposeAll = false; @@ -595,13 +614,6 @@ export function dynamicallyStoredFamilies( }); } }; - // A live dyn view (typed-ref capsule) of an instance writes back into - // its fields only after a runtime store into the capsule; the commit then - // writes every field from the view, which holds the exact snapshot value - // of any property no store named. So reaching dynamic code disqualifies - // exactly the field names some dynamic store in the program can name. - const { all: dynWritesAll, names: dynWritten } = - stores ?? dynamicFieldStores(mod, records, unions); for (const fn of mod.functions) walkFunction(fn, { expr: (e) => { @@ -627,16 +639,10 @@ export function dynamicallyStoredFamilies( if (s.kind === "throw") expose(s.value.type); }, }); - const families = new Set(); for (const cls of classes.values()) { if (!exposeAll && !exposedClasses.has(cls.name)) continue; for (const field of cls.fields) - if ( - field.type.kind === "f64" && - !field.name.startsWith("%") && - (dynWritesAll || dynWritten.has(field.name)) - ) - families.add(slots.family(cls.name, field.name)!); + if (storable(field)) families.add(slots.family(cls.name, field.name)!); } return families; } @@ -1057,12 +1063,18 @@ export function analyzeInt32Slots(mod: IrModule, inputs: Int32SlotInputs = {}): if (params) for (const id of params.keys()) reads(`param:${fn.name}\0${id}`, fn.name); // Range facts are consulted only at writes into candidate slots; slots // are only ever dropped, so a body without such a write needs none. - const ranges: IntegerRanges = hasCandidateWrite(fn) + const candidate = hasCandidateWrite(fn); + const ranges: IntegerRanges = candidate ? analyzeIntegerRanges(numeric(fn), slots.facts(fn.name)) : new Map(); if (ranges.size > 0) lastWrites.set(fn.name, slotWrites(fn, ranges, functions)); else lastWrites.delete(fn.name); const proven: IrExpr[] = []; + // The walk below acts only at writes into candidate slots. + if (!candidate) { + provenByFunction.set(fn.name, proven); + continue; + } const int32 = (e: IrExpr): boolean => withinInt32(ranges.get(e)); // An int32 written into a slot still assumed non-negative: widen the // assumption when the value may be negative, and reanalyze its readers. diff --git a/packages/compiler/src/ir/integer-loops.test.ts b/packages/compiler/src/ir/integer-loops.test.ts index 24bbf5be0..b6ac27e3a 100644 --- a/packages/compiler/src/ir/integer-loops.test.ts +++ b/packages/compiler/src/ir/integer-loops.test.ts @@ -426,3 +426,119 @@ test("paired counters closing in on each other run as integers", () => { unused.body = []; expect(matchIntegerPairedForLoop(unused, vars)).toBeNull(); }); + +test("counters stepped beside the tested one run as integers", () => { + const vars = new Map(locals); + for (const id of ["j", "k", "limit", "from"]) + vars.set(id, { id, name: id, type: F64, mutable: true }); + vars.set("s", { id: "s", name: "s", type: STRING, mutable: false }); + const step = (id: string, op: "+" | "-", value = 1): IrStmt => ({ + kind: "assign", + localId: id, + value: { kind: "bin", op, left: ref(id), right: number(value), type: F64, loc }, + loc, + }); + const read = (index: IrExpr): IrStmt => ({ + kind: "exprStmt", + expr: { + kind: "strIntrinsic", + method: "charCodeAt", + receiver: { kind: "varRef", localId: "s", type: STRING, loc }, + args: [index], + type: F64, + loc, + }, + loc, + }); + const comoving = ( + limit: IrExpr, + followerStart: IrExpr = number(0), + update: IrStmt = { kind: "block", body: [step("i", "+"), step("j", "+", 4)], loc }, + ) => + ({ + kind: "for", + loc, + init: { + kind: "block", + body: [ + { kind: "varDecl", localId: "i", init: number(0), loc }, + { kind: "varDecl", localId: "j", init: followerStart, loc }, + ], + loc, + }, + cond: { kind: "bin", op: "<", left: ref("i"), right: limit, type: BOOL, loc }, + update, + body: [read(ref("j"))], + }) as IrStmt & { kind: "for" }; + // A literal limit bounds the follower: at most 9 updates of 4 before the + // last body entry. + expect(matchIntegerCountedForLoop(comoving(number(10)), vars)).toMatchObject({ + localId: "i", + guarded: false, + range: { min: 0, max: 9 }, + followers: [ + { + localId: "j", + step: 4, + startGuarded: false, + tripGuarded: false, + range: { min: 0, max: 36 }, + }, + ], + }); + // An unknown limit or start is tested at run time. + expect(matchIntegerCountedForLoop(comoving(ref("limit")), vars)).toMatchObject({ + guarded: true, + followers: [{ tripGuarded: true, range: { min: 0, max: 2 ** 52 + 2 } }], + }); + expect(matchIntegerCountedForLoop(comoving(number(10), ref("from")), vars)).toMatchObject({ + guarded: true, + followers: [{ startGuarded: true, tripGuarded: true }], + }); + // A literal limit with known starts that can pass 2^53 is refused. + expect(matchIntegerCountedForLoop(comoving(number(10), number(2 ** 53 - 9)), vars)).toBeNull(); + // Nested update blocks (`i++, j += 4, k--`) step three counters. + const three = comoving(number(10), number(0), { + kind: "block", + body: [{ kind: "block", body: [step("i", "+"), step("j", "+", 4)], loc }, step("k", "-")], + loc, + }); + if (three.init?.kind === "block") + three.init.body.push({ kind: "varDecl", localId: "k", init: number(5), loc }); + expect(matchIntegerCountedForLoop(three, vars)?.followers).toMatchObject([ + { localId: "j", range: { min: 0, max: 36 } }, + { localId: "k", step: -1, range: { min: -4, max: 5 } }, + ]); + // A follower without a step, one the body writes, one the limit reads, a + // captured one, and a start that reads another counter are refused. + expect( + matchIntegerCountedForLoop( + comoving(number(10), number(0), { kind: "block", body: [step("i", "+")], loc }), + vars, + ), + ).toBeNull(); + const writing = comoving(number(10)); + writing.body.push(step("j", "+")); + expect(matchIntegerCountedForLoop(writing, vars)).toBeNull(); + expect(matchIntegerCountedForLoop(comoving(ref("j")), vars)).toBeNull(); + const boxed = new Map(vars); + boxed.set("j", { ...vars.get("j")!, boxed: true }); + expect(matchIntegerCountedForLoop(comoving(number(10)), boxed)).toBeNull(); + expect(matchIntegerCountedForLoop(comoving(number(10), ref("i")), vars)).toBeNull(); + // A driver span above 2^53 - 1 bounds no trip count. From -(2^53 - 1) to + // below 2^52 - 1 the span 3 * 2^52 - 3 rounds down to 3 * 2^52 - 4, which + // would put this follower's last value at 2^53 - 1 instead of 2^53. + const wide = comoving(number(2 ** 52 - 1), number(-(2 ** 52) + 3), { + kind: "block", + body: [step("i", "+"), step("j", "+")], + loc, + }); + if (wide.init?.kind === "block" && wide.init.body[0]?.kind === "varDecl") + wide.init.body[0].init = number(-Number.MAX_SAFE_INTEGER); + expect(matchIntegerCountedForLoop(wide, vars)).toBeNull(); + if (wide.init?.kind === "block" && wide.init.body[1]?.kind === "varDecl") + wide.init.body[1].init = ref("from"); + expect(matchIntegerCountedForLoop(wide, vars)?.followers).toMatchObject([ + { startGuarded: true, tripGuarded: true }, + ]); +}); diff --git a/packages/compiler/src/ir/integer-loops.ts b/packages/compiler/src/ir/integer-loops.ts index e80680d6e..f54f6618b 100644 --- a/packages/compiler/src/ir/integer-loops.ts +++ b/packages/compiler/src/ir/integer-loops.ts @@ -28,8 +28,36 @@ export interface IntegerCountedForLoop { startGuarded: boolean; guardLimit: number; range: IntegerRange; + /** Counters declared and stepped beside this one that the condition does + * not test, such as `j` in `for (let i = 0, j = 0; i < n; i++, j += 4)`. */ + followers: IntegerLoopFollower[]; } +/** A counter that steps by a constant on every update of a counted loop. + * After `k` updates it holds `start + step * k`. */ +export interface IntegerLoopFollower { + localId: string; + start: IrExpr; + step: number; + /** As the driver's `startGuarded` (part of the loop's `guarded`). */ + startGuarded: boolean; + /** The follower's range depends on the run-time trip count: the versioned + * loop also tests `|start| + |step| * span / |driver step|` against + * `FOLLOWER_GUARD_LIMIT`, where `span` is the distance from the driver's + * start to the limit (part of the loop's `guarded`). */ + tripGuarded: boolean; + /** The follower's values on every body entry. */ + range: IntegerRange; +} + +/** The bound of the run-time follower test. */ +export const FOLLOWER_GUARD_LIMIT = 2 ** 52; +/** The magnitude a follower that passed the test can reach. The test's four + * f64 operations (the step ratio, the span, its product and the sum) each + * round down by at most a factor of 1 - 2^-53, so the exact sum is below + * `2^52 / (1 - 2^-53)^4`, which is less than 2^52 + 3. */ +const FOLLOWER_GUARD_RANGE = FOLLOWER_GUARD_LIMIT + 2; + function constantStep(update: IrStmt | null, id: string): number | null { if (update?.kind === "exprStmt" && update.expr.kind === "incDec" && update.expr.localId === id) return update.expr.op === "+" ? 1 : -1; @@ -115,33 +143,61 @@ export function matchIntegerCountedForLoop( ranges: IntegerRanges = new Map(), unaliased: ReadonlySet | null = null, ): IntegerCountedForLoop | null { - const init = stmt.init; - if (init?.kind !== "varDecl" || !init.init) return null; - const local = locals.get(init.localId); - if (local?.type.kind !== "f64" || !local.mutable || local.boxed || local.tdz) return null; - const start = init.init; - let startRange = - start.kind === "numLit" && Number.isSafeInteger(start.value) && !Object.is(start.value, -0) - ? { min: start.value, max: start.value } - : ranges.get(start); - // An unproven start is tested at run time, on a versioned loop. - const startGuarded = !startRange && start.kind !== "numLit" && start.type.kind === "f64"; - if (startGuarded) startRange = { min: -Number.MAX_SAFE_INTEGER, max: Number.MAX_SAFE_INTEGER }; - if ( - !startRange || - startRange.min < -Number.MAX_SAFE_INTEGER || - startRange.max > Number.MAX_SAFE_INTEGER || - !stableLoopValue(start, locals, stmt.body, false, local.id) - ) - return null; - const step = constantStep(stmt.update, local.id); - if (step === null || writesLocal(stmt.body, local.id)) return null; const cond = stmt.cond; if (cond?.kind !== "bin") return null; + const decls = stmt.init?.kind === "block" ? stmt.init.body : stmt.init ? [stmt.init] : []; + // `i++, j += 2, k--` lowers to nested blocks of steps. + const flat = (u: IrStmt | null): (IrStmt | null)[] => + u?.kind === "block" ? u.body.flatMap(flat) : [u]; + const updates = flat(stmt.update); + if (decls.length === 0 || updates.length !== decls.length) return null; + const declared = (e: IrExpr): string | null => + e.kind === "varRef" && decls.some((d) => d.kind === "varDecl" && d.localId === e.localId) + ? e.localId + : null; + // The condition tests the driving counter; every other declaration + // follows it. + const driver = declared(cond.left) ?? declared(cond.right); + const counterIds = decls.map((d) => (d.kind === "varDecl" ? d.localId : "")); + const stepOf = (id: string): number | null => { + const steps = updates.map((u) => constantStep(u, id)).filter((v) => v !== null); + return steps.length === 1 ? steps[0]! : null; + }; + // A counter's start is a stable integer that refers to no counter. An + // unproven start is tested at run time, on a versioned loop. + const counterStart = ( + id: string, + ): { start: IrExpr; range: IntegerRange; guarded: boolean; step: number } | null => { + const decl = decls.find((d) => d.kind === "varDecl" && d.localId === id); + if (decl?.kind !== "varDecl" || !decl.init) return null; + const local = locals.get(id); + if (local?.type.kind !== "f64" || !local.mutable || local.boxed || local.tdz) return null; + const start = decl.init; + const known = + start.kind === "numLit" && Number.isSafeInteger(start.value) && !Object.is(start.value, -0) + ? { min: start.value, max: start.value } + : ranges.get(start); + const guarded = !known && start.kind !== "numLit" && start.type.kind === "f64"; + const range = guarded ? { min: -Number.MAX_SAFE_INTEGER, max: Number.MAX_SAFE_INTEGER } : known; + const step = stepOf(id); + if ( + !range || + range.min < -Number.MAX_SAFE_INTEGER || + range.max > Number.MAX_SAFE_INTEGER || + !counterIds.every((counter) => stableLoopValue(start, locals, stmt.body, false, counter)) || + step === null || + writesLocal(stmt.body, id) + ) + return null; + return { start, range, guarded, step }; + }; + const head = driver === null ? null : counterStart(driver); + if (!head) return null; + const local = locals.get(driver!)!; + const { start, step, guarded: startGuarded, range: startRange } = head; let limit = cond.right, op: string = cond.op; if (cond.left.kind !== "varRef" || cond.left.localId !== local.id) { - if (cond.right.kind !== "varRef" || cond.right.localId !== local.id) return null; limit = cond.left; op = ({ "<": ">", "<=": ">=", ">": "<", ">=": "<=" } as Record)[op] ?? ""; } @@ -185,11 +241,70 @@ export function matchIntegerCountedForLoop( const limitGuarded = !boundRange || (step > 0 ? !(boundRange.max <= guardLimit) : !(boundRange.min >= guardLimit)); if (limitGuarded && limit.kind === "numLit") return null; - const guarded = limitGuarded || startGuarded; + const range = + step > 0 + ? { + min: startRange.min, + max: Math.max( + startRange.min, + Math.min( + Number.MAX_SAFE_INTEGER, + boundRange + ? Math.ceil(boundRange.max) - (inclusive ? 0 : 1) + : Number.MAX_SAFE_INTEGER, + ), + ), + } + : { + min: Math.min( + startRange.max, + Math.max( + -Number.MAX_SAFE_INTEGER, + boundRange + ? Math.floor(boundRange.min) + (inclusive ? 0 : 1) + : -Number.MAX_SAFE_INTEGER, + ), + ), + max: startRange.max, + }; + // On body entry k the driver holds `start + step * k`, so k is at most the + // driver's span over |step|, and a follower holds its start plus its own + // step times k. A span above 2^53 - 1 can round down, so it bounds no + // trip count. Below it the quotient rounds to at least its floor, and the + // follower's products and sums below are exact while they stay within + // ±(2^53 - 1) and round outside it otherwise. + const span = step > 0 ? range.max - startRange.min : startRange.max - range.min; + const trips = span <= Number.MAX_SAFE_INTEGER ? Math.floor(span / Math.abs(step)) : Infinity; + const followers: IntegerLoopFollower[] = []; + for (const id of counterIds) { + if (id === local.id) continue; + const follower = counterStart(id); + // The limit is evaluated once; a follower changes on every update. + if (!follower || !stableLoopValue(limit, locals, stmt.body, false, id)) return null; + const reach = follower.step * trips; + const min = follower.range.min + Math.min(0, reach), + max = follower.range.max + Math.max(0, reach); + const tripGuarded = min < -Number.MAX_SAFE_INTEGER || max > Number.MAX_SAFE_INTEGER; + // Known starts and a literal limit are not tested at run time. + if (tripGuarded && !follower.guarded && !startGuarded && limit.kind === "numLit") return null; + followers.push({ + localId: id, + start: follower.start, + step: follower.step, + startGuarded: follower.guarded, + tripGuarded, + range: tripGuarded + ? { min: Math.max(-FOLLOWER_GUARD_RANGE, min), max: Math.min(FOLLOWER_GUARD_RANGE, max) } + : { min, max }, + }); + } + const guarded = + limitGuarded || startGuarded || followers.some((f) => f.startGuarded || f.tripGuarded); let useful = false; let cost = 0; const counter = (e: IrExpr): boolean => - (e.kind === "varRef" && e.localId === local.id) || + (e.kind === "varRef" && + (e.localId === local.id || followers.some((f) => f.localId === e.localId))) || (e.kind === "bin" && (e.op === "+" || e.op === "-" || e.op === "*") && (counter(e.left) || counter(e.right))); @@ -218,7 +333,12 @@ export function matchIntegerCountedForLoop( ) useful = true; // A string read at the counter indexes with the integer directly. - if (e.kind === "strIntrinsic" && e.method === "charCodeAt" && e.args[0] && counter(e.args[0])) + if ( + e.kind === "strIntrinsic" && + (e.method === "charCodeAt" || e.method === "charAt") && + e.args[0] && + counter(e.args[0]) + ) useful = true; // So does an array element read; only a loop that needs no versioned // copy takes the integer counter for it. @@ -241,32 +361,6 @@ export function matchIntegerCountedForLoop( return (!guarded || ++cost <= 80) && everyStmtChild(s, expr, bodyStmt); }; if (!stmt.body.every(bodyStmt) || !useful) return null; - const range = - step > 0 - ? { - min: startRange.min, - max: Math.max( - startRange.min, - Math.min( - Number.MAX_SAFE_INTEGER, - boundRange - ? Math.ceil(boundRange.max) - (inclusive ? 0 : 1) - : Number.MAX_SAFE_INTEGER, - ), - ), - } - : { - min: Math.min( - startRange.max, - Math.max( - -Number.MAX_SAFE_INTEGER, - boundRange - ? Math.floor(boundRange.min) + (inclusive ? 0 : 1) - : -Number.MAX_SAFE_INTEGER, - ), - ), - max: startRange.max, - }; return { localId: local.id, start, @@ -278,6 +372,7 @@ export function matchIntegerCountedForLoop( startGuarded, guardLimit, range, + followers, }; } @@ -366,7 +461,12 @@ export function matchIntegerPairedForLoop( (isCounter(e.left) || isCounter(e.right))); const expr = (e: IrExpr): boolean => { if (e.kind === "arrayGet" && isCounter(e.index)) useful = true; - if (e.kind === "strIntrinsic" && e.method === "charCodeAt" && e.args[0] && isCounter(e.args[0])) + if ( + e.kind === "strIntrinsic" && + (e.method === "charCodeAt" || e.method === "charAt") && + e.args[0] && + isCounter(e.args[0]) + ) useful = true; if (e.kind === "bytesIntrinsic" && e.method === "get" && e.args[0] && isCounter(e.args[0])) useful = true; diff --git a/packages/compiler/src/ir/ir.test.ts b/packages/compiler/src/ir/ir.test.ts index 52ef9b9c1..d62c9c83c 100644 --- a/packages/compiler/src/ir/ir.test.ts +++ b/packages/compiler/src/ir/ir.test.ts @@ -10,6 +10,7 @@ import { canDynCheckTo, type IrBytesElem, isJsonSafeType, + iterableArmsElem, isJsonStringifySafeType, isJsonStringifyDynamicType, type IrRecordShape, @@ -22,6 +23,29 @@ import { typeKey, } from "./ir.js"; +describe("iterable unions", () => { + const gen = (yieldT: IrType): IrType => ({ + kind: "generator", + yieldT, + retT: { kind: "void" }, + nextT: { kind: "undefinedT" }, + }); + + test("names the element type of an Iterable union", () => { + expect(iterableArmsElem([arrayOf(F64), gen(F64), { kind: "set", elem: F64 }])).toEqual(F64); + expect(iterableArmsElem([arrayOf(STRING), gen(STRING), STRING])).toEqual(STRING); + expect(iterableArmsElem([arrayOf(F64), gen(F64), { kind: "undefinedT" }])).toEqual(F64); + }); + + test("rejects unions without exactly one plain generator arm over the same element", () => { + expect(iterableArmsElem([arrayOf(F64), STRING])).toBeNull(); + expect(iterableArmsElem([arrayOf(STRING), gen(F64)])).toBeNull(); + expect(iterableArmsElem([arrayOf(F64), gen(F64), gen(STRING)])).toBeNull(); + expect(iterableArmsElem([gen(F64), STRING])).toBeNull(); + expect(iterableArmsElem([arrayOf(F64), { ...gen(F64), nextT: F64 } as IrType])).toBeNull(); + }); +}); + describe("IR kind sets", () => { test("keeps procStream as the scalar handle exception", () => { expect(HANDLE_KINDS.has("procStream")).toBe(true); diff --git a/packages/compiler/src/ir/ir.ts b/packages/compiler/src/ir/ir.ts index 4a395feb2..12400fee9 100644 --- a/packages/compiler/src/ir/ir.ts +++ b/packages/compiler/src/ir/ir.ts @@ -730,6 +730,32 @@ function isCollectionValueKey(t: IrType): boolean { ); } +/** The element type of an ITERABLE union (`Iterable`, + * iterableUnionType): its one generator arm — a synchronous generator over + * T that returns nothing and takes no `.next()` values — beside source arms + * (T[], Set, a Map of [K, V] entries, a string), and the undefined and + * null arms of an optional Iterable. A generator arm is legal only in such + * a union. Null for every other union. */ +export function iterableArmsElem(arms: readonly IrType[]): IrType | null { + let elem: IrType | null = null; + for (const arm of arms) { + if (arm.kind !== "generator") continue; + if (elem !== null || arm.async || arm.retT.kind !== "void" || arm.nextT.kind !== "undefinedT") + return null; + elem = arm.yieldT; + } + if (elem === null) return null; + for (const arm of arms) { + if (arm.kind === "generator" || arm.kind === "undefinedT" || arm.kind === "nullT") continue; + if (arm.kind === "array" || arm.kind === "set") { + if (!typeEquals(arm.elem, elem)) return null; + } else if (arm.kind === "string") { + if (elem.kind !== "string") return null; + } else if (arm.kind !== "map") return null; + } + return elem; +} + /** Set elements and Map keys share storage, equality and ownership rules. */ export function isSupportedSetElem(t: IrType, unionArms?: IrType[]): boolean { return isSupportedMapKey(t, unionArms); @@ -1943,8 +1969,18 @@ export type IrStmt = * RangeError from the runtime. `pop` marks the stores that implement * `pop()`: a frozen (published) array fails with pop's TypeError rather * than the length assignment's, and pop's `length = 0` store on an empty - * array is dropped unless the array may be frozen. */ - | { kind: "arraySetLength"; arr: IrExpr; length: IrExpr; loc: SrcLoc; pop?: boolean } + * array is dropped unless the array may be frozen. `reserve` marks a + * capacity hint instead: dense storage for `length` elements of a fresh + * array that statements fill next, with no change to its length and no + * observable effect. */ + | { + kind: "arraySetLength"; + arr: IrExpr; + length: IrExpr; + loc: SrcLoc; + pop?: boolean; + reserve?: boolean; + } /** Write an explicit present `undefined` state without shrinking length. */ | { kind: "arraySetUndefined"; arr: IrExpr; index: IrExpr; loc: SrcLoc } /** Delete an indexed/property slot without changing Array.length. */ diff --git a/packages/compiler/src/ir/parameter-versions.ts b/packages/compiler/src/ir/parameter-versions.ts new file mode 100644 index 000000000..88232251c --- /dev/null +++ b/packages/compiler/src/ir/parameter-versions.ts @@ -0,0 +1,307 @@ +import { analyzeInt32Slots } from "./int32-slots.js"; +import { BOOL, F64, type IrExpr, type IrFunction, type IrModule, type IrStmt } from "./ir.js"; +import { reparseStmt } from "./serialize.js"; +import { everyExprChild, everyStmtChild, everyStmtList } from "./traverse.js"; + +const MAX_FUNCTION_NODES = 2048; +const MAX_VERSIONS = 16; + +function size(fn: IrFunction): number { + let nodes = 0; + everyStmtList(fn.body, { + stmt: () => ++nodes <= MAX_FUNCTION_NODES, + expr: () => ++nodes <= MAX_FUNCTION_NODES, + }); + return nodes; +} + +/** The function a direct call or construction runs, if any. */ +function callee(e: IrExpr): string | null { + if (e.kind === "call") return e.callee; + if (e.kind === "new") return `%${e.className}.constructor`; + return null; +} + +/** Direct call and construction sites of each function in the module. */ +function callSites(mod: IrModule): Map { + const sites = new Map(); + for (const fn of mod.functions) + everyStmtList(fn.body, { + stmt: () => true, + expr: (e) => { + const name = callee(e); + if (name !== null) sites.set(name, (sites.get(name) ?? 0) + 1); + return true; + }, + }); + return sites; +} + +/** Expressions and statements of a callee that LLVM inlines at any number + * of call sites: scalar arithmetic and reads, no calls or allocations. */ +const SIMPLE_EXPRESSIONS = new Set([ + "varRef", + "numLit", + "boolLit", + "bin", + "unary", + "logical", + "ternary", + "toBool", + "incDec", + "assignExpr", + "arrayGet", + "fieldGet", + "recordGet", + "unionNarrow", + "unionIsTag", +]); +const SIMPLE_STATEMENTS = new Set([ + "varDecl", + "assign", + "exprStmt", + "if", + "block", + "return", +]); + +function simple(fn: IrFunction): boolean { + return ( + (fn.returnType.kind === "f64" || fn.returnType.kind === "bool") && + everyStmtList(fn.body, { + stmt: (s) => SIMPLE_STATEMENTS.has(s.kind), + expr: (e) => SIMPLE_EXPRESSIONS.has(e.kind), + }) + ); +} + +/** Whether a copy of `fn` would cost a callee its only call site. LLVM + * inlines a function called once wherever its size allows; with a second + * site, both calls can stay out of line, with the records and arguments + * they pass built in memory. A callee that only computes a number or a + * boolean from scalar reads inlines either way. A function calling itself + * would also dispatch on every call. */ +function keepsSingleBody( + fn: IrFunction, + sites: ReadonlyMap, + functions: ReadonlyMap, +): boolean { + return !everyStmtList(fn.body, { + stmt: () => true, + expr: (e) => { + const name = callee(e); + if (name === null) return true; + if (name === fn.name) return false; + if (sites.get(name) !== 1) return true; + const target = functions.get(name); + return target !== undefined && simple(target); + }, + }); +} + +/** Statements and expressions of a loop whose work is numeric: arithmetic, + * element and field reads and writes, `Math` calls and calls of simple + * functions. Loops that allocate, build strings or call other code gain + * little from an integer bound and would only grow the copy. */ +const NUMERIC_STATEMENTS = new Set([ + ...SIMPLE_STATEMENTS, + "for", + "while", + "doWhile", + "break", + "continue", + "arraySet", + "fieldSet", +]); +const NUMERIC_EXPRESSIONS = new Set([...SIMPLE_EXPRESSIONS, "arrayHas", "arrayState"]); + +function numericLoop(loop: IrStmt, functions: ReadonlyMap): boolean { + const expr = (e: IrExpr): boolean => { + let allowed = NUMERIC_EXPRESSIONS.has(e.kind); + if (e.kind === "call") { + const target = functions.get(e.callee); + allowed = target !== undefined && simple(target); + } else if (e.kind === "libCall") allowed = e.fn.startsWith("math."); + else if (e.kind === "arrIntrinsic") allowed = e.method === "length"; + return allowed && everyExprChild(e, expr, stmt); + }; + const stmt = (s: IrStmt): boolean => + NUMERIC_STATEMENTS.has(s.kind) && everyStmtChild(s, expr, stmt); + return stmt(loop); +} + +/** Number parameters of `fn` that bound one of its numeric loops: read in + * the loop's condition or in its `for` initializer. */ +function loopBounds(fn: IrFunction, functions: ReadonlyMap): Set { + const params = new Set( + fn.params.filter((param) => param.type.kind === "f64").map((param) => param.localId), + ); + const result = new Set(); + if (params.size === 0) return result; + const reads = (e: IrExpr): boolean => { + if (e.kind === "varRef" && params.has(e.localId)) result.add(e.localId); + return everyExprChild(e, reads, readsStmt); + }; + const readsStmt = (s: IrStmt): boolean => everyStmtChild(s, reads, readsStmt); + everyStmtList(fn.body, { + stmt: (s) => { + if (s.kind !== "for" && s.kind !== "while" && s.kind !== "doWhile") return true; + if (!numericLoop(s, functions)) return true; + if (s.cond) reads(s.cond); + if (s.kind === "for" && s.init) readsStmt(s.init); + return true; + }, + expr: () => true, + }); + return result; +} + +/** Versions of functions whose number parameters bound their loops. + * + * A parameter that every call site proves an int32 already reaches the + * function's i32 entry (int32-abi.ts). One that some caller passes as an + * unproven number (a value read from a message, a field, a parse) keeps + * its double, so the loops it bounds compare a counter with a double and + * the values derived from it stay doubles. + * + * A parameter qualifies when it bounds a numeric loop (`numericLoop`). + * Such a function gets a copy of its body under a new name, and its own + * body starts by calling the copy when every such parameter holds an + * int32: `(p | 0) === p` (an integer in the int32 range, not NaN) and not + * -0 (`1 / p` is not -Infinity). The copy then receives `p | 0`, which is + * the same double, so it computes what the body would; its only caller + * proves the parameter an int32, so it gets the i32 entry. Other values + * run the body as before. + * + * Only plain synchronous functions qualify: not class members, no + * captures, not the module entry, not dynamic-tier, at most + * MAX_FUNCTION_NODES nodes, not calling themselves, and not holding the + * only call site of another function (`keepsSingleBody`). The caller + * skips modules that observe call stacks, where the copy's frame could be + * seen. */ +export function versionLoopBoundParameters( + mod: IrModule, + symbolName: (name: string) => string = (name) => name, +): IrModule { + const candidates: { fn: IrFunction; params: Set }[] = []; + const sites = callSites(mod); + const functions = new Map(mod.functions.map((fn) => [fn.name, fn])); + const members = new Set((mod.classes ?? []).flatMap((cls) => cls.methods ?? [])); + for (const fn of mod.functions) { + if ( + // Constructors, methods and accessors (`%C.m`) and generated helper + // families (`%arr.map_…`) keep their single body. + fn.name.includes(".") || + members.has(fn.name) || + fn.async || + fn.generator || + fn.captures !== undefined || + fn.classCaptures?.length || + fn.tier === "dynamic" || + fn.name === mod.entry + ) + continue; + const params = loopBounds(fn, functions); + const locals = new Map(fn.locals.map((local) => [local.id, local])); + for (const id of params) { + const local = locals.get(id); + if (!local || local.boxed || local.tdz) params.delete(id); + } + if (params.size === 0 || size(fn) > MAX_FUNCTION_NODES || keepsSingleBody(fn, sites, functions)) + continue; + candidates.push({ fn, params }); + } + if (candidates.length === 0) return mod; + const slots = analyzeInt32Slots(mod); + const names = new Set(mod.functions.map((fn) => symbolName(fn.name))); + const replaced = new Map(); + const added: IrFunction[] = []; + for (const { fn, params } of candidates) { + if (added.length >= MAX_VERSIONS) break; + const unproven = fn.params.filter( + (param) => params.has(param.localId) && !slots.hasParam(fn.name, param.localId), + ); + if (unproven.length === 0) continue; + let name = `${fn.name}.int32Params`; + while (names.has(symbolName(name))) name += "_"; + names.add(symbolName(name)); + const { ownsPrototype: _ownsPrototype, ...implementation } = fn; + added.push({ ...implementation, name, body: fn.body.map(reparseStmt) }); + const loc = fn.body[0]?.loc ?? { file: mod.sourceFile, start: 0, end: 0 }; + const read = (localId: string): IrExpr => ({ kind: "varRef", localId, type: F64, loc }); + const int32 = (localId: string): IrExpr => ({ + kind: "bin", + op: "|", + left: read(localId), + right: { kind: "numLit", value: 0, type: F64, loc }, + type: F64, + loc, + }); + let test: IrExpr | null = null; + for (const param of unproven) { + const exact: IrExpr = { + kind: "bin", + op: "===", + left: int32(param.localId), + right: read(param.localId), + type: BOOL, + loc, + }; + const notNegativeZero: IrExpr = { + kind: "bin", + op: "!==", + left: { + kind: "bin", + op: "/", + left: { kind: "numLit", value: 1, type: F64, loc }, + right: read(param.localId), + type: F64, + loc, + }, + right: { kind: "numLit", value: -Infinity, type: F64, loc }, + type: BOOL, + loc, + }; + const both: IrExpr = { + kind: "logical", + op: "&&", + left: exact, + right: notNegativeZero, + type: BOOL, + loc, + }; + test = + test === null + ? both + : { kind: "logical", op: "&&", left: test, right: both, type: BOOL, loc }; + } + const versioned = new Set(unproven.map((param) => param.localId)); + const call: IrExpr = { + kind: "call", + callee: name, + args: fn.params.map((param) => + versioned.has(param.localId) + ? int32(param.localId) + : { kind: "varRef", localId: param.localId, type: param.type, loc }, + ), + type: fn.returnType, + loc, + }; + const run: IrStmt[] = + fn.returnType.kind === "void" + ? [ + { kind: "exprStmt", expr: call, loc }, + { kind: "return", value: null, loc }, + ] + : [{ kind: "return", value: call, loc }]; + replaced.set(fn, { + ...fn, + body: [{ kind: "if", cond: test!, then: run, else_: null, loc }, ...fn.body], + }); + } + if (added.length === 0) return mod; + return { + ...mod, + functions: [...mod.functions.map((fn) => replaced.get(fn) ?? fn), ...added], + }; +} diff --git a/packages/compiler/src/ir/runtime-features.ts b/packages/compiler/src/ir/runtime-features.ts index 4142b6efe..85910369a 100644 --- a/packages/compiler/src/ir/runtime-features.ts +++ b/packages/compiler/src/ir/runtime-features.ts @@ -75,6 +75,8 @@ const DYN_ASYNC_LIB_FNS: ReadonlySet = new Set([ "child.propsInstall", "child.propsResolve", "crypto.native", + // The crypto global's object extends crypto.native's. + "webcrypto.object", "dyn.promiseAll", "dyn.promiseAllSettled", "dyn.promiseAny", @@ -214,6 +216,19 @@ const ABORT_SIGNAL_LIB_FNS: ReadonlySet = new Set([ /** Entry points that link the stream unit (with STREAM_LIB_PREFIXES). */ const STREAM_LIB_FNS: ReadonlySet = new Set([ "child.stdioStream", + "stream.chunkDone", + "stream.objectMode", + "stream.decodeStrings", + "stream.duplexFromGen", + "stream.duplexFromDyn", + "stream.duplexFromPromise", + "stream.duplexFromAsyncFn", + "stream.duplexFromGenSignal", + "stream.duplexFromAsyncFnSignal", + "fetch.readableFromWeb", + "stream.duplexifyReadable", + "stream.duplexifyWritable", + "stream.duplexifyPair", "console.bind", "crypto.hashStream", "crypto.hashStreamPiped", @@ -226,6 +241,7 @@ const STREAM_LIB_FNS: ReadonlySet = new Set([ "sp.finished", "sp.pipeline", "sp.pipelineStages", + "sp.pipelineStagesOpts", "stream.addAbortSignal", "stream.addAbortSignalFn", "stream.destroy", @@ -237,6 +253,7 @@ const STREAM_LIB_FNS: ReadonlySet = new Set([ "stream.prop", "stream.stdioWritable", "stream.unboxDyn", + "stream.handleStream", "stream.unpipeDyn", "stream.workerStdio", ]); @@ -252,6 +269,7 @@ const STREAM_LIB_PREFIXES: readonly string[] = [ "sp.pipelineOpts", "stream.finishedOpts", "stream.pipelineStages", + "stream.composeStages", "stream.set", "transform.", "writable.", @@ -265,6 +283,12 @@ const READABLE_DYN_ASYNC_LIB_FNS: ReadonlySet = new Set([ "readable.fromDone", "readable.fromDyn", "readable.fromIter", + "stream.duplexFromGen", + "stream.duplexFromDyn", + "stream.duplexFromPromise", + "stream.duplexFromAsyncFn", + "stream.duplexFromGenSignal", + "stream.duplexFromAsyncFnSignal", ]); /** libCall name prefixes of the Readable entry points that await through the dyn-async unit. */ @@ -600,14 +624,23 @@ const STDIO_EXTENDED_NAMES: ReadonlySet = new Set(["setEncoding", "resiz /** The libCall nodes the rules below test. */ type LibCallNode = IrExpr & { kind: "libCall" }; +/** A condition over several nodes of the module (a WebCrypto call and an + * algorithm name): the scan's one walk shows it every expression, and the + * feature is set when `result` answers true after the walk. */ +interface RuleScan { + expr(node: IrExpr): void; + result(): boolean; +} + /** What makes a program need one optional runtime unit. The feature is set * when any condition holds: `initial` from the module's declarations, a * libCall named in `fns` or starting with one of `prefixes`, a libCall - * `libCall` accepts, another expression node `expr` accepts, or a type - * slot of one of the `types` kinds. A libCall or type that needs several - * units appears in each unit's rule. */ + * `libCall` accepts, another expression node `expr` accepts, a type slot of + * one of the `types` kinds, or a `scan` over the whole module. A libCall or + * type that needs several units appears in each unit's rule. */ interface RuntimeFeatureRule { initial?: (mod: IrModule) => boolean; + scan?: () => RuleScan; fns?: readonly IrLibFn[]; prefixes?: readonly string[]; libCall?: (node: LibCallNode) => boolean; @@ -621,6 +654,88 @@ const rule = (r: RuntimeFeatureRule): RuntimeFeatureRule => r; /* The HTTP, HTTPS, HTTP/2 and TLS surfaces, which link the net unit. */ const NET_PREFIXES: readonly string[] = ["net.", "http.", "tls.", "https.", "http2."]; +/** The scr_dh.c entry points (the dh unit). */ +export const DH_LIB_FNS: ReadonlySet = new Set([ + "crypto.dhNew", + "crypto.dhGroupNew", + "crypto.checkPrimeSync", + "crypto.checkPrimeCb", + "crypto.generatePrimeSync", + "crypto.generatePrimeCb", +]); + +/** The scr_pki.c entry points (the pki unit). */ +export const PKI_LIB_FNS: ReadonlySet = new Set([ + "crypto.createPrivateKey", + "crypto.createPublicKey", + "crypto.createSign", + "crypto.createVerify", + "crypto.generateKeyPairCb", + "crypto.generateKeyPairSync", + "crypto.signOneshot", + "crypto.verifyOneshot", +]); + +/** The WebCrypto algorithms scr_webcrypto_pki.c implements over the pki + * unit (lowercased). */ +const WEBCRYPTO_ASYMMETRIC_NAMES: ReadonlySet = new Set([ + "ecdsa", + "ed25519", + "rsa-pss", + "rsassa-pkcs1-v1_5", +]); + +/** Whether a string literal in the module names Ed25519, without regard + * to case ("ed25519" for node:crypto, "Ed25519" for WebCrypto): the + * Ed25519 unit links then, alongside the pki unit. */ +function ed25519NameScan(): RuleScan { + let named = false; + return { + expr: (node) => { + if (!named && node.kind === "strLit" && node.value.toLowerCase() === "ed25519") named = true; + }, + result: () => named, + }; +} + +/** moduleUsesWebCryptoAsymmetric's condition as a runtime-feature scan. */ +function webCryptoAsymmetricScan(): RuleScan { + let webcrypto = false; + let named = false; + return { + expr: (node) => { + if (node.kind === "libCall" && node.fn.startsWith("webcrypto.")) webcrypto = true; + else if ( + !named && + node.kind === "strLit" && + WEBCRYPTO_ASYMMETRIC_NAMES.has(node.value.toLowerCase()) + ) + named = true; + }, + result: () => webcrypto && named, + }; +} + +/** Whether the module calls WebCrypto and a string literal in it names one + * of the asymmetric algorithms (matched without regard to case, as + * normalizeAlgorithm matches names): scr_webcrypto_pki.c and the pki unit + * link then. */ +export function moduleUsesWebCryptoAsymmetric(mod: IrModule): boolean { + let webcrypto = false; + let named = false; + everyModuleNode(mod, { + expr: (node) => { + if (node.kind === "libCall" && node.fn.startsWith("webcrypto.")) webcrypto = true; + if (node.kind === "strLit" && WEBCRYPTO_ASYMMETRIC_NAMES.has(node.value.toLowerCase())) + named = true; + return !(webcrypto && named); + }, + stmt: () => !(webcrypto && named), + type: () => true, + }); + return webcrypto && named; +} + /** One rule per runtime feature, sorted by name. A new feature is an * entry here and its line in noRuntimeFeatures; RuntimeFeatures, the scan * and its early exit derive from this table. The lists above keep one @@ -647,8 +762,17 @@ const RUNTIME_FEATURE_RULES = { }), /** scr_cipher.c over the mbedTLS archive; DEP0182 reports through the * process-warning unit, and unknown output encodings render through the - * inspect unit. */ - cipher: rule({ fns: ["crypto.cipherNew"] }), + * inspect unit. WebCrypto's encrypt, decrypt, wrapKey and unwrapKey + * (scr_webcrypto_aes.c) link the same archive. */ + cipher: rule({ + fns: [ + "crypto.cipherNew", + "webcrypto.encrypt", + "webcrypto.decrypt", + "webcrypto.wrapKey", + "webcrypto.unwrapKey", + ], + }), copying: rule({ expr: (node, _tables) => (node.kind === "arrIntrinsic" && COPYING_ARR_METHODS.has(node.method)) || @@ -675,12 +799,17 @@ const RUNTIME_FEATURE_RULES = { ), // The legacy url functions, crypto.createCipheriv and // ecdh.setPublicKey emit their deprecation warnings through the - // dyn-async unit; scr_wasm.c boxes its handles and promises through it. + // dyn-async unit (WebCrypto's encrypt and decrypt link scr_cipher.c + // too); scr_wasm.c boxes its handles and promises through it. fns: [ ...DYN_ASYNC_LIB_FNS, ...READABLE_DYN_ASYNC_LIB_FNS, ...LEGACY_URL_LIB_FNS, "crypto.cipherNew", + "webcrypto.encrypt", + "webcrypto.decrypt", + "webcrypto.wrapKey", + "webcrypto.unwrapKey", "crypto.ecdhNew", ], prefixes: [...READABLE_DYN_ASYNC_PREFIXES, "wasm."], @@ -744,6 +873,10 @@ const RUNTIME_FEATURE_RULES = { * process-warning unit, and unknown encodings and formats render through * the inspect unit. */ ecdh: rule({ fns: ["crypto.ecdhNew", "crypto.ecdhConvertKey"] }), + /** scr_dh.c over the mbedTLS archive, also for checkPrime and + * generatePrime; unknown encodings and argument values render through + * the inspect unit. */ + dh: rule({ fns: [...DH_LIB_FNS] }), emitter: rule({ initial: (mod) => mod.workers === true || (mod.classes ?? []).some((c) => c.name === RUNTIME_EMITTER_CLASS), @@ -787,8 +920,13 @@ const RUNTIME_FEATURE_RULES = { "global.native", "util.styleText", "crypto.cipherNew", + "webcrypto.encrypt", + "webcrypto.decrypt", + "webcrypto.wrapKey", + "webcrypto.unwrapKey", "crypto.ecdhNew", "crypto.ecdhConvertKey", + ...DH_LIB_FNS, ...BUILTIN_CLASS_LIB_FNS, ...UTIL_CALLABLE_LIB_FNS, ], @@ -819,6 +957,12 @@ const RUNTIME_FEATURE_RULES = { /** perf_hooks event-loop metrics (eventLoopUtilization, * monitorEventLoopDelay): scr_perf_loop.c. */ perfLoop: rule({ fns: ["perf.idleTime"], prefixes: ["perf.loop", "perf.eld"] }), + /** scr_pki.c over the mbedTLS archive: asymmetric KeyObjects and + * signatures. */ + pki: rule({ scan: webCryptoAsymmetricScan, fns: [...PKI_LIB_FNS] }), + /** scr_ed25519.c (the vendored libsodium Ed25519), linked with pki: a + * string literal in the module names Ed25519. */ + ed25519: rule({ scan: ed25519NameScan }), processEvents: rule({ fns: [...PROCESS_EVENT_LIB_FNS, "util.styleText"], types: ["procStream"] }), /** scr_url_legacy.c parses and stringifies queries. */ qs: rule({ fns: [...QS_LIB_FNS, ...LEGACY_URL_LIB_FNS] }), @@ -910,6 +1054,7 @@ function noRuntimeFeatures(): RuntimeFeatures { dynInvoke: false, dynTier: false, ecdh: false, + dh: false, emitter: false, eventTarget: false, eventsOnceSignal: false, @@ -926,6 +1071,8 @@ function noRuntimeFeatures(): RuntimeFeatures { nodeTest: false, parseArgs: false, perfLoop: false, + pki: false, + ed25519: false, processEvents: false, qs: false, regex: false, @@ -976,9 +1123,11 @@ for (const name of RUNTIME_FEATURE_NAMES) { function scanRuntimeFeatures(mod: IrModule, stopAt?: RuntimeFeatureName): RuntimeFeatures { const features = noRuntimeFeatures(); + const scans: { name: RuntimeFeatureName; scan: RuleScan }[] = []; for (const name of RUNTIME_FEATURE_NAMES) { - const initial = ruleOf(name).initial; + const { initial, scan } = ruleOf(name); if (initial && initial(mod)) features[name] = true; + if (scan) scans.push({ name, scan: scan() }); } const keepGoing = (): boolean => stopAt === undefined || !features[stopAt]; let tables: TypeTables | undefined; @@ -989,6 +1138,7 @@ function scanRuntimeFeatures(mod: IrModule, stopAt?: RuntimeFeatureName): Runtim classes: new Map((mod.classes ?? []).map((c) => [c.name, c])), }); const expr = (node: IrExpr): boolean => { + for (let i = 0; i < scans.length; i++) scans[i]!.scan.expr(node); if (node.kind === "libCall") { const fn = node.fn; for (const name of FEATURES_BY_FN.get(fn) ?? []) features[name] = true; @@ -1007,6 +1157,7 @@ function scanRuntimeFeatures(mod: IrModule, stopAt?: RuntimeFeatureName): Runtim return keepGoing(); }; if (keepGoing()) everyModuleNode(mod, { expr, stmt: keepGoing, type }); + for (const { name, scan } of scans) if (scan.result()) features[name] = true; // Inline-cache sites of dynamic-tier functions use the tier's shapes // (scr_js_object.c, with the SCR_JS_TIER build of scr_json.c). if (!features.dynTier && mod.functions.some((fn) => fn.tier === "dynamic")) { diff --git a/packages/compiler/src/ir/tiers.ts b/packages/compiler/src/ir/tiers.ts index ce2fdf0f4..13c464149 100644 --- a/packages/compiler/src/ir/tiers.ts +++ b/packages/compiler/src/ir/tiers.ts @@ -72,6 +72,7 @@ const DYN_KIND_TESTS: ReadonlySet = new Set([ "dyn.nativeMapIs", "dyn.nativeUrlIs", "dyn.nativeDateIs", + "dyn.nativeDateHandleIs", "dyn.nativeRegexIs", "dyn.dataViewIs", "dyn.typeof", diff --git a/packages/compiler/src/ir/traverse.ts b/packages/compiler/src/ir/traverse.ts index 11b20a210..251904351 100644 --- a/packages/compiler/src/ir/traverse.ts +++ b/packages/compiler/src/ir/traverse.ts @@ -109,8 +109,15 @@ export interface IrModuleVisitor extends IrVisitor { * source text, locations, labels, or other metadata. A false predicate stops * the whole walk. Results are never retained across mutable compiler passes. */ export function everyModuleNode(mod: IrModule, visitor: IrModuleVisitor): boolean { - const type = (node: IrType, loc: SrcLoc): boolean => - visitor.type(node, loc) && everyTypeChild(node, (child) => type(child, loc)); + // Every node of one type tree reports the tree's location: one shared + // child callback serves them all. + let typeLoc: SrcLoc; + const typeNode = (node: IrType): boolean => + visitor.type(node, typeLoc) && everyTypeChild(node, typeNode); + const type = (node: IrType, loc: SrcLoc): boolean => { + typeLoc = loc; + return typeNode(node); + }; const expr = (node: IrExpr): boolean => visitor.expr(node) && everyExprChild(node, expr, stmt) && type(node.type, node.loc); const stmt = (node: IrStmt): boolean => visitor.stmt(node) && everyStmtChild(node, expr, stmt); diff --git a/packages/compiler/src/ir/validate.ts b/packages/compiler/src/ir/validate.ts index bdfe75f2e..770fee6c6 100644 --- a/packages/compiler/src/ir/validate.ts +++ b/packages/compiler/src/ir/validate.ts @@ -18,6 +18,7 @@ import type { } from "./ir.js"; import { arrayOf, + iterableArmsElem, BYTES_ELEMENT_NAME, BOOL, BYTES_U8, @@ -60,7 +61,8 @@ import { DYN_CLASS_PROPERTIES, callSiteReturnType, classValueConstructor } from import { unionWideningTags } from "./analysis.js"; import { alwaysReturns } from "./control-flow.js"; import { dynamicOperationOf, functionTier } from "./tiers.js"; -import { LIB_FN_SIGS } from "./builtin-signatures.js"; +import { LIB_FN_SIGS, pipelinePumpedRuns } from "./builtin-signatures.js"; +import { ALWAYS_THROW_LIB_FNS } from "./builtin-effects.js"; /** The promisified crypto calls' value kinds besides checked-dynamic. */ const CRYPTO_PROMISE_VALUES: Readonly> = { @@ -800,7 +802,7 @@ export function validateModule(mod: IrModule): IrValidationError[] { arm.kind === "union" || arm.kind === "dyn" || arm.kind === "date" || - arm.kind === "generator" + (arm.kind === "generator" && iterableArmsElem(u.arms) === null) ) { errors.push({ message: `union ${u.id}: arm ${i} is ${arm.kind}`, loc: noLoc }); } @@ -4101,14 +4103,17 @@ function validateFunction( e.fn === "stream.pipelineDyn" || e.fn === "stream.compose" || e.fn === "stream.pipelineStages" || + e.fn === "stream.composeStages" || e.fn === "stream.pipelineStagesDyn" || e.fn === "sp.pipelineStages" || + e.fn === "sp.pipelineStagesOpts" || e.fn === "sp.pipeline" || e.fn === "sp.pipelineOpts" || e.fn === "sp.pipelineOptsSignal" || e.fn === "writable.write" || e.fn === "writable.writeStr" || e.fn === "writable.writeU" || + e.fn === "writable.writeEnc" || e.fn === "writable.end" || e.fn === "readable.unpipe" || e.fn === "rl.create" || @@ -4289,6 +4294,22 @@ function validateFunction( } return true; } + if (e.fn === "fetch.readableFromWeb") { + // Readable.fromWeb: (stream, objectMode, highWaterMark, encoding) → a Readable. + if ( + e.args.length !== 4 || + e.args[0]?.type.kind !== "dyn" || + e.args[1]?.type.kind !== "bool" || + e.args[2]?.type.kind !== "f64" || + e.args[3]?.type.kind !== "string" || + e.type.kind !== "object" + ) + err( + `libCall ${e.fn} must take (stream, objectMode, highWaterMark, encoding) and return a Readable`, + e.loc, + ); + return true; + } if (e.fn === "fetch.readerRead") { if (e.type.kind !== "promise" || e.type.inner.kind !== "record") { err(`libCall fetch.readerRead must return a promise of a read-result record`, e.loc); @@ -5348,32 +5369,8 @@ function validateFunction( const callback = e.args[e.args.length - 1]?.type; if (callback?.kind !== "func") err(`libCall ${e.fn} callback must be a function`, e.loc); } - if (e.fn === "global.undefRead") { - // Always throws — the result type is whatever the declared type - // of the undefined global mapped to (never materialized). - return true; - } - if ( - e.fn === "error.nodeThrow" || - e.fn === "error.argTypeThrow" || - e.fn === "error.propTypeThrow" || - e.fn === "fs.mkdtempChk" || - e.fn === "fs.readFileChk" || - e.fn === "fs.opendirChk" || - e.fn === "fs.watchFileChk" || - e.fn === "fs.lchmodChk" || - e.fn === "fs.readChk" || - e.fn === "fs.streamOptsChk" || - e.fn === "net.connectOptsChk" || - e.fn === "tls.caCertsChk" - ) { - // Always throws — the result type is the replaced expression's - // own (never materialized; the global.undefRead pattern). The - // fs Chk ladders qualify: every validation failure throws - // Node's typed error, and a full pass throws the trailing - // compiler-rendered fence. - return true; - } + // Always throws: the result type is never materialized. + if (ALWAYS_THROW_LIB_FNS.has(e.fn)) return true; if (e.fn === "error.new" || e.fn === "error.newOptions") { // Which builtin the runtime constructs is named by the result type. if (!isBuiltinErrorObject(e.type)) { @@ -5496,6 +5493,20 @@ function validateFunction( e.fn.startsWith("passthrough.") || e.fn === "stream.destroy" || e.fn === "stream.destroyErr" || + e.fn === "stream.objectMode" || + e.fn === "stream.decodeStrings" || + e.fn === "stream.duplexFromGen" || + e.fn === "stream.duplexFromDyn" || + e.fn === "stream.duplexifyReadable" || + e.fn === "stream.duplexifyWritable" || + e.fn === "stream.duplexifyPair" || + e.fn === "stream.duplexFromPromise" || + e.fn === "stream.duplexFromAsyncFn" || + e.fn === "stream.duplexFromGenSignal" || + e.fn === "stream.duplexFromAsyncFnSignal" || + e.fn === "stream.setConstruct" || + e.fn === "stream.setWritev" || + e.fn === "stream.setWritevDefault" || e.fn === "stream.iteratorClose" || e.fn === "stream.prop" || e.fn === "stream.errored" || @@ -5505,8 +5516,10 @@ function validateFunction( e.fn === "stream.pipelineDyn" || e.fn === "stream.compose" || e.fn === "stream.pipelineStages" || + e.fn === "stream.composeStages" || e.fn === "stream.pipelineStagesDyn" || e.fn === "sp.pipelineStages" || + e.fn === "sp.pipelineStagesOpts" || e.fn === "stream.addAbortSignal" || e.fn === "stream.addAbortSignalFn" || e.fn === "stream.finishedOpts" || @@ -5546,6 +5559,38 @@ function validateFunction( } return true; } + if (e.fn === "stream.duplexFromPromise") { + // Duplex.from(promise): (promise, box) → a Duplex. + if (e.args[0]?.type.kind !== "promise" || e.args[1]?.type.kind !== "func") + err(`libCall ${e.fn} takes a promise and its box helper`, e.loc); + if (!isStreamObject(e.type)) err(`libCall ${e.fn} must return a stream class`, e.loc); + return true; + } + if ( + e.fn === "stream.duplexifyReadable" || + e.fn === "stream.duplexifyWritable" || + e.fn === "stream.duplexifyPair" + ) { + // Duplex.from over streams: (r), (w) or (r, w) → a Duplex. + const want = e.fn === "stream.duplexifyPair" ? 2 : 1; + if (e.args.length !== want || !e.args.every((a) => isStreamObject(a.type))) + err(`libCall ${e.fn} takes ${want} stream argument(s)`, e.loc); + if (!isStreamObject(e.type)) err(`libCall ${e.fn} must return a stream class`, e.loc); + return true; + } + if ( + e.fn === "stream.duplexFromGen" || + e.fn === "stream.duplexFromDyn" || + e.fn === "stream.duplexFromAsyncFn" || + e.fn === "stream.duplexFromGenSignal" || + e.fn === "stream.duplexFromAsyncFnSignal" + ) { + // Duplex.from: (stage, source, helpers...) or (body) → a Duplex. + if (!isStreamObject(e.type)) { + err(`libCall ${e.fn} must return a stream class, got ${e.type.kind}`, e.loc); + } + return true; + } if (e.fn.endsWith(".newDyn")) { // The dyn-options constructor: (optsDyn) → the stream class. if (!isStreamObject(e.type)) { @@ -5616,25 +5661,44 @@ function validateFunction( if ( e.fn === "stream.pipelineStages" || e.fn === "stream.pipelineStagesDyn" || - e.fn === "sp.pipelineStages" + e.fn === "sp.pipelineStages" || + e.fn === "sp.pipelineStagesOpts" || + e.fn === "stream.composeStages" ) { - // (n, at, k, flags, mask, s1..sn, stage1..stagek, (next, read, - // return)?, box?, (signal, abort)?[, cb]): flags bit 0 a source - // function, bits 1-2 the destination, bits 3/4/5 the groups. - const [n, at, k, flags] = e.args + // (n, k, positions, flags, mask, s1..sn, stage1..stagek, + // helpers..., box?, (signal, abort)?[, cb | end, signal?]): + // positions bit j marks stage j a function, flags bits 1-2 the + // destination, bit 5 the signal group, bit 6 the options' signal; + // helpers are three per pumped function run. + const [n, k, positions, flags] = e.args .slice(0, 4) .map((a) => (a?.kind === "numLit" ? a.value : -1)); - const source = (flags! & 1) !== 0; + const total = n! + k!; const destKind = (flags! >> 1) & 3; - const groups = (flags! & 8 ? 3 : 0) + (flags! & 16 ? 1 : 0) + (flags! & 32 ? 2 : 0); - const cbArgs = e.fn === "sp.pipelineStages" ? 0 : 1; + let functions = 0; + for (let j = 0; j < total && j < 53; j++) { + if (Math.floor(positions! / 2 ** j) % 2 === 1) functions++; + } + const lastIsFunction = Math.floor(positions! / 2 ** (total - 1)) % 2 === 1; + const helperCount = 3 * pipelinePumpedRuns(total, positions!, flags!); + const groups = helperCount + (destKind === 2 ? 1 : 0) + (flags! & 32 ? 2 : 0); + const cbArgs = + e.fn === "sp.pipelineStagesOpts" + ? 1 + (flags! & 64 ? 1 : 0) + : e.fn === "sp.pipelineStages" || e.fn === "stream.composeStages" + ? 0 + : 1; if ( flags! < 0 || n! < 0 || k! < 1 || - (source ? at !== 0 : at! < 1) || - (destKind === 0 ? at! + 0 >= n! : at! !== n!) || - n! + k! < 2 || + positions! < 1 || + total > 52 || + positions! >= 2 ** total || + functions !== k || + destKind === 3 || + (destKind !== 0) !== lastIsFunction || + total < 2 || e.args.length !== 5 + n! + k! + groups + cbArgs ) { err(`libCall ${e.fn} count/arity mismatch`, e.loc); @@ -5651,7 +5715,7 @@ function validateFunction( err(`libCall ${e.fn} stage function ${i} must be a func`, e.loc); } at2 += k!; - const helpers = (flags! & 8 ? 3 : 0) + (flags! & 16 ? 1 : 0); + const helpers = helperCount + (destKind === 2 ? 1 : 0); for (let i = at2; i < at2 + helpers; i++) { if (e.args[i]?.type.kind !== "func") err(`libCall ${e.fn} helper ${i} must be a func`, e.loc); @@ -5661,12 +5725,19 @@ function validateFunction( if (e.args[at2]?.type.kind !== "dyn" || e.args[at2 + 1]?.type.kind !== "func") err(`libCall ${e.fn} signal and abort must be a dyn and a func`, e.loc); } - if (cbArgs) { + if (e.fn === "sp.pipelineStagesOpts") { + const tail = e.args.slice(e.args.length - cbArgs); + if (tail[0]?.type.kind !== "bool" || (cbArgs > 1 && tail[1]?.type.kind !== "dyn")) + err(`libCall ${e.fn} end and signal must be a bool and a dyn`, e.loc); + if (e.type.kind !== "promise") err(`libCall ${e.fn} must return a promise`, e.loc); + } else if (cbArgs) { const cbK = e.args[e.args.length - 1]?.type.kind; if (e.fn === "stream.pipelineStages" ? cbK !== "func" : cbK !== "dyn") { err(`libCall ${e.fn} callback has the wrong kind`, e.loc); } if (!isStreamObject(e.type)) err(`libCall ${e.fn} must return a stream`, e.loc); + } else if (e.fn === "stream.composeStages") { + if (!isStreamObject(e.type)) err(`libCall ${e.fn} must return a stream`, e.loc); } else if (e.type.kind !== "promise") { err(`libCall ${e.fn} must return a promise`, e.loc); } @@ -5701,6 +5772,8 @@ function validateFunction( e.fn === "readable.opMap" || e.fn === "readable.opFilter" || e.fn === "readable.opFlatMap" || + e.fn === "readable.opFlatMapAsyncGen" || + e.fn === "readable.opFlatMapSyncGen" || e.fn === "readable.opDrop" || e.fn === "readable.opTake" ) { @@ -5709,13 +5782,30 @@ function validateFunction( } return true; } - if (e.fn === "readable.opReduce") { + if (e.fn === "readable.opReduce" || e.fn === "readable.opReduceSignal") { const inner = e.type.kind === "promise" ? e.type.inner : null; const kind = e.args[5]?.kind === "numLit" ? e.args[5].value : -1; const want = [DYN, F64, BOOL, STRING][kind]; if (!isStreamObject(e.args[0]?.type) || !inner || !want || !typeEquals(inner, want)) { err(`libCall readable.opReduce must return the promise its kind names`, e.loc); } + if (e.fn === "readable.opReduceSignal" && e.args[6]?.type.kind !== "func") + err(`libCall ${e.fn} takes ac.abort() as a closure`, e.loc); + return true; + } + if (e.fn === "readable.opOnceOptions") { + if (e.args.length !== 0 || e.type.kind !== "dyn") + err(`libCall ${e.fn} takes no arguments`, e.loc); + return true; + } + if ( + e.fn === "readable.opSignalList" || + e.fn === "readable.opSignalOpts" || + e.fn === "readable.opSignalOf" + ) { + // The operator callbacks' { signal }: (dyn) → dyn. + if (e.args.length !== 1 || e.args[0]?.type.kind !== "dyn" || e.type.kind !== "dyn") + err(`libCall ${e.fn} takes and returns a checked-dynamic value`, e.loc); return true; } if (e.fn === "readable.fromDone") { @@ -5775,6 +5865,10 @@ function validateFunction( e.fn === "writable.end" || e.fn === "readable.setEncoding" || e.fn === "readable.pushEncoding" || + e.fn === "stream.objectMode" || + e.fn === "stream.decodeStrings" || + e.fn === "writable.writeEncoding" || + e.fn === "writable.setDefaultEncoding" || e.fn === "stream.destroy" || e.fn === "stream.destroyErr" || e.fn === "stream.iteratorClose" @@ -5891,8 +5985,10 @@ function validateFunction( const chunkT = e.args[2]?.type; const ok = chunkT !== undefined && - ((chunkT.kind === "bytes" && chunkT.elem === "u8") || chunkT.kind === "string"); - if (!ok) err(`libCall emitter.emitData chunk must be bytes or string`, e.loc); + ((chunkT.kind === "bytes" && chunkT.elem === "u8") || + chunkT.kind === "string" || + chunkT.kind === "dyn"); + if (!ok) err(`libCall emitter.emitData chunk must be bytes, string or dyn`, e.loc); if (e.type.kind !== "bool") err(`libCall emitter.emitData must be bool`, e.loc); return true; } diff --git a/packages/compiler/src/library/ir-policy.ts b/packages/compiler/src/library/ir-policy.ts index 51aeb6146..e8fad6dd1 100644 --- a/packages/compiler/src/library/ir-policy.ts +++ b/packages/compiler/src/library/ir-policy.ts @@ -52,6 +52,17 @@ const LIB_MODE_REFUSED_PREFIXES: readonly [string, string][] = [ ["tls.", "the node:tls surface"], ["crypto.cipherNew", "crypto.createCipheriv and createDecipheriv"], ["crypto.ecdh", "crypto.createECDH and ECDH.convertKey"], + ["crypto.dhNew", "crypto.createDiffieHellman"], + ["crypto.dhGroupNew", "crypto.getDiffieHellman and createDiffieHellmanGroup"], + ["crypto.checkPrime", "crypto.checkPrime and checkPrimeSync"], + ["crypto.generatePrime", "crypto.generatePrime and generatePrimeSync"], + ["crypto.createPrivateKey", "asymmetric KeyObjects, generateKeyPair, sign and verify"], + ["crypto.createPublicKey", "asymmetric KeyObjects, generateKeyPair, sign and verify"], + ["crypto.createSign", "asymmetric KeyObjects, generateKeyPair, sign and verify"], + ["crypto.createVerify", "asymmetric KeyObjects, generateKeyPair, sign and verify"], + ["crypto.generateKeyPair", "asymmetric KeyObjects, generateKeyPair, sign and verify"], + ["crypto.signOneshot", "asymmetric KeyObjects, generateKeyPair, sign and verify"], + ["crypto.verifyOneshot", "asymmetric KeyObjects, generateKeyPair, sign and verify"], ["webcrypto.", "WebCrypto (crypto.subtle)"], ["fs.watch", "fs.watch"], ["watcher.", "fs.watch"], @@ -159,6 +170,7 @@ export function moduleLibAsyncSurface(mod: IrModule): { surface: string; loc: Sr [features.fsWatch, "fs.watch"], [features.stream, "the node:stream surface"], [features.tls, "the node:tls surface"], + [features.pki, "asymmetric KeyObjects, generateKeyPair, sign and verify"], [features.fetch, "fetch"], [features.eventTarget, "the EventTarget surface"], [features.nodeTest, "the node:test surface"], diff --git a/packages/compiler/src/native/cache.test.ts b/packages/compiler/src/native/cache.test.ts index 3ffdf2335..f4910ff23 100644 --- a/packages/compiler/src/native/cache.test.ts +++ b/packages/compiler/src/native/cache.test.ts @@ -11,7 +11,7 @@ import { import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, expect, test, vi } from "vitest"; -import { contentDigest, NativeCache, openNativeCache } from "./cache.js"; +import { contentDigest, fileDigest, NativeCache, openNativeCache } from "./cache.js"; const directories: string[] = []; function directory(): string { @@ -19,11 +19,24 @@ function directory(): string { directories.push(path); return path; } +function* generate(parts: readonly string[]): Generator { + yield* parts; +} afterEach(() => { vi.unstubAllEnvs(); for (const path of directories.splice(0)) rmSync(path, { recursive: true, force: true }); }); +test("a file's digest read in blocks is the digest of its bytes", () => { + const path = join(directory(), "module.ll"); + const bytes = Buffer.alloc(3 * 1024 * 1024 + 17); + for (let index = 0; index < bytes.length; index++) bytes[index] = (index * 31) & 0xff; + writeFileSync(path, bytes); + expect(fileDigest(path)).toBe(contentDigest(bytes)); + writeFileSync(path, ""); + expect(fileDigest(path)).toBe(contentDigest("")); +}); + test("cache hits require an intact payload and digest", () => { const cache = new NativeCache(directory()); const key = contentDigest("program identity"); @@ -42,7 +55,8 @@ test("text parts publish one digest-checked entry and oversized reads are misses const cache = new NativeCache(directory()); const key = contentDigest("parts identity"); const parts = ['{"a":', '"\u00e9é😀"', ",", "", '"b":1}']; - cache.writeParts("frontend", key, parts); + // Parts are generated while they are written, and hashed in the same pass. + cache.writeParts("frontend", key, generate(parts)); const bytes = cache.read("frontend", key); expect(bytes?.toString("utf8")).toBe(parts.join("")); expect(readFileSync(join(cache.root, "frontend", key + ".sha256"), "utf8").trim()).toBe( diff --git a/packages/compiler/src/native/cache.ts b/packages/compiler/src/native/cache.ts index f81311f52..566df308a 100644 --- a/packages/compiler/src/native/cache.ts +++ b/packages/compiler/src/native/cache.ts @@ -1,8 +1,11 @@ import { createHash } from "node:crypto"; import { + closeSync, mkdirSync, mkdtempSync, + openSync, readFileSync, + readSync, readdirSync, renameSync, rmSync, @@ -11,7 +14,7 @@ import { } from "node:fs"; import { join } from "node:path"; import { resolveBuildCacheRoot } from "../backend/cache-root.js"; -import { writeTextPartsSync } from "./text-file.js"; +import { writeTextGeneratedSync } from "./text-file.js"; /** UTF-8 bytes one native compiler string can hold (the runtime's * SCR_STR_MAX_CAP). Exceeding it traps rather than throwing, so payloads @@ -25,6 +28,23 @@ export function contentDigest(value: string | Uint8Array): string { return hash.digest("hex"); } +/** contentDigest of a file's bytes, read in 1 MiB blocks so a large file + * (a module's LLVM text) is never held whole. */ +export function fileDigest(path: string): string { + const hash = createHash("sha256"); + const block = Buffer.alloc(1024 * 1024); + const fd = openSync(path, "r"); + try { + for (let read = readSync(fd, block, 0, block.length, null); read > 0;) { + hash.update(block.subarray(0, read)); + read = readSync(fd, block, 0, block.length, null); + } + } finally { + closeSync(fd); + } + return hash.digest("hex"); +} + /** A compiler cache contains private source and executable data. The host * checks ownership and permissions before this class accepts a root. */ export class NativeCache { @@ -86,15 +106,15 @@ export class NativeCache { } /** Publish text parts without joining them into one string. */ - writeParts(family: string, key: string, parts: readonly string[]): void { + writeParts(family: string, key: string, parts: Generator): void { let stage: string | null = null; try { const directory = join(this.root, family); mkdirSync(directory, { recursive: true, mode: 0o700 }); stage = mkdtempSync(join(directory, ".write-")); - writeTextPartsSync(join(stage, "payload"), parts); + // One pass over the parts: they may be generated while they are written. const hash = createHash("sha256"); - for (const part of parts) hash.update(part); + writeTextGeneratedSync(join(stage, "payload"), parts, (slice) => hash.update(slice)); writeFileSync(join(stage, "digest"), hash.digest("hex") + "\n"); const path = join(directory, key); renameSync(join(stage, "payload"), path); diff --git a/packages/compiler/src/native/cli.ts b/packages/compiler/src/native/cli.ts index ed8d52293..21047b929 100644 --- a/packages/compiler/src/native/cli.ts +++ b/packages/compiler/src/native/cli.ts @@ -20,12 +20,30 @@ import { openNativeCache } from "./cache.js"; import { loadNativeToolchain } from "./toolchain.js"; import { buildSanitizedRuntime } from "./sanitizer.js"; import { runCompilerTask } from "./task.js"; +import { processFork } from "../frontend/process-fork.js"; declare function compilerNativePrivateDirectory(path: string, harden: boolean): boolean; declare function compilerNativeCollectCycles(): void; +declare function compilerNativeFork(): number; +declare function compilerNativeExit(code: number): void; +declare function compilerNativeWait(pid: number): number; +declare function compilerNativeLockOpen(path: string): boolean; +declare function compilerNativeLock(): void; +declare function compilerNativeUnlock(): void; +declare function compilerNativeBoundCycleGrowth(): void; async function main(): Promise { + compilerNativeBoundCycleGrowth(); setFrontendDisposedHook(() => compilerNativeCollectCycles()); + if (process.platform !== "win32") + processFork.primitives = { + fork: () => compilerNativeFork(), + exit: (code) => compilerNativeExit(code), + wait: (pid) => compilerNativeWait(pid), + openLock: (path) => compilerNativeLockOpen(path), + lock: () => compilerNativeLock(), + unlock: () => compilerNativeUnlock(), + }; const manifestPath = process.env["SCRIPTC_TOOLCHAIN"] ?? process.execPath + ".json"; let compiler: NativeCompiler | null = null; let cache: ReturnType = null; @@ -110,6 +128,9 @@ async function main(): Promise { tls: false, cipher: false, ecdh: false, + dh: false, + pki: false, + ed25519: false, webcrypto: false, perfLoop: false, tlsCa: false, diff --git a/packages/compiler/src/native/compiler.ts b/packages/compiler/src/native/compiler.ts index d4487aba4..2c850cb14 100644 --- a/packages/compiler/src/native/compiler.ts +++ b/packages/compiler/src/native/compiler.ts @@ -56,7 +56,7 @@ import { clearFenceEvalCaches } from "../library/fence-eval.js"; import { archiveNativeLibrary, localizeNativeLibrary, linkNativeWasmLibrary } from "./library.js"; import type { NativeToolchain } from "./toolchain.js"; import { evaluateNativeComptime } from "./comptime.js"; -import { contentDigest, type NativeCache } from "./cache.js"; +import { contentDigest, fileDigest, type NativeCache } from "./cache.js"; import { nativeProfileKey, nativeProfileRefusal, @@ -186,7 +186,7 @@ export class NativeCompiler { key = contentDigest( JSON.stringify({ schema: 1, - llvm: contentDigest(readFileSync(input)), + llvm: fileDigest(input), outputKind, optimization, source, @@ -361,7 +361,8 @@ export class NativeCompiler { const inputDirectory = join(stage, "input"); mkdirSync(inputDirectory); const llvmInput = outputKind === "llvm" ? stagedOutput : join(inputDirectory, "program.ll"); - writeFileSync(llvmInput, llvm); + // In slices: the module text is never encoded whole. + writeTextPartsSync(llvmInput, [llvm]); timing("llvm-write"); if (outputKind === "llvm") { renameSync(stagedOutput, output); @@ -495,7 +496,7 @@ export class NativeCompiler { renameSync(stagedOutput + ".dSYM", output + ".dSYM"); } mkdirSync(options.outDir, { recursive: true }); - writeFileSync(llvmPath, llvm); + writeTextPartsSync(llvmPath, [llvm]); let irPath: string | undefined; if (options.emitIr) { irPath = join(options.outDir, `${stem}.ir.json`); @@ -583,7 +584,8 @@ export class NativeCompiler { stage = mkdtempSync(join(dirname(archivePath), ".scriptc-library-")); const llvm = prepared.llvm; const llvmInput = join(stage, "program.ll"); - writeFileSync(llvmInput, llvm); + // In slices: the module text is never encoded whole. + writeTextPartsSync(llvmInput, [llvm]); timing("llvm-write"); const features = prepared.features; const pack = selectNativeRuntimePack( @@ -646,7 +648,7 @@ export class NativeCompiler { }); } timing("native-archive"); - writeFileSync(llvmPath, llvm); + writeTextPartsSync(llvmPath, [llvm]); let irPath: string | undefined; if (options.emitIr) { irPath = join(options.outDir, `${stem}.lib.ir.json`); diff --git a/packages/compiler/src/native/prepare.ts b/packages/compiler/src/native/prepare.ts index 6b0a2fea5..edc90c449 100644 --- a/packages/compiler/src/native/prepare.ts +++ b/packages/compiler/src/native/prepare.ts @@ -7,7 +7,7 @@ import type { CompileLibraryOptions, CompileRequestOptions, } from "../compile-types.js"; -import { emitLlvmModule, lowRegionTarget } from "../backend/llvm/emitter.js"; +import { emitLlvmModule, type ForkPrimitives, lowRegionTarget } from "../backend/llvm/emitter.js"; import { inlineRcOption } from "../backend/llvm/shapes.js"; import { executableLinkFeatures } from "../backend/executable-features.js"; import type { NativeLinkFeatures } from "../backend/native-link-info-core.js"; @@ -23,12 +23,13 @@ import { trackedReadFile, } from "../frontend/input-tracker.js"; import { provenanceSources } from "../frontend/provenance-registry.js"; +import { processFork } from "../frontend/process-fork.js"; import { prepareLibrary } from "../library/prepare.js"; import type { LibraryProfile } from "../library/library-profile.js"; import type { IrModule } from "../ir/ir.js"; import { deserializeModuleBytes, serializeModuleParts } from "../ir/serialize.js"; import { contentDigest, NATIVE_STRING_BYTES, type NativeCache } from "./cache.js"; -import { batchTextParts } from "./text-file.js"; +import { batchTextParts, textSlices } from "./text-file.js"; import type { NativeToolchain } from "./toolchain.js"; import { nativeFileIdentity } from "./file-identity.js"; @@ -57,37 +58,57 @@ interface FrontendCacheEntry { ir: string[] | null; } -function frontendCacheParts(probes: FrontendInputSnapshot, input: NativeExecutableInput): string[] { +/** The entry's JSON text, generated as it is written. The LLVM text is + * escaped in slices (`textSlices`), the same JSON string as escaping it + * whole, so a large module is never copied whole. */ +function* frontendCacheParts( + probes: FrontendInputSnapshot, + input: NativeExecutableInput, +): Generator { const metadata = JSON.stringify({ schema: "scriptc.native-frontend.v3", probes, input: { ...input, llvm: "", ir: null }, }); - const parts = [metadata.slice(0, metadata.length - 1) + ',"llvm":', JSON.stringify(input.llvm)]; - if (input.ir === null) parts.push(',"ir":null}'); + yield metadata.slice(0, metadata.length - 1) + ',"llvm":"'; + for (const slice of textSlices(input.llvm)) yield JSON.stringify(slice).slice(1, -1); + yield '"'; + if (input.ir === null) yield ',"ir":null}'; else { - parts.push(',"ir":['); + yield ',"ir":['; for (let index = 0; index < input.ir.length; index++) { - if (index > 0) parts.push(","); - parts.push(JSON.stringify(input.ir[index]!)); + if (index > 0) yield ","; + yield JSON.stringify(input.ir[index]!); } - parts.push("]}"); + yield "]}"; + } +} + +/** The parts while their total length stays within `limit`; past it, a + * throw abandons the write. */ +function* boundedParts(parts: Generator, limit: number): Generator { + let length = 0; + for (const part of parts) { + length += part.length; + if (length > limit) throw new Error("frontend cache entry exceeds one native string"); + yield part; } - return parts; } /** Publish an entry only when a native reader can decode it as one string; - * UTF-16 length never exceeds the UTF-8 byte length. */ + * UTF-16 length never exceeds the UTF-8 byte length. A longer entry + * abandons its write, which writeParts discards. */ function publishFrontendCache( cache: NativeCache, key: string, probes: FrontendInputSnapshot, input: NativeExecutableInput, ): void { - const parts = frontendCacheParts(probes, input); - let length = 0; - for (const part of parts) length += part.length; - if (length <= NATIVE_STRING_BYTES) cache.writeParts("frontend", key, parts); + cache.writeParts( + "frontend", + key, + boundedParts(frontendCacheParts(probes, input), NATIVE_STRING_BYTES), + ); } function readFrontendCache( @@ -161,6 +182,9 @@ function validFeatures(value: unknown): value is NativeLinkFeatures { "tlsCa", "cipher", "ecdh", + "dh", + "pki", + "ed25519", "webcrypto", "perfLoop", ].every((name) => typeof features[name] === "boolean"); @@ -294,6 +318,8 @@ export function prepareNativeExecutable( runtimeAbiMarker: outputKind === "obj" || outputKind === "exe", objectAudit: options.sanitize === true, lowRegion: lowRegionTarget(toolchain.target.platform, options.sanitize === true), + functionWorkers: emitWorkers(), + forkPrimitives: emitForkPrimitives(), ...inlineRcOption(options.optimization, options.sanitize === true), ...(options.detachedExit === true && outputKind === "exe" ? { detachedExit: true } : {}), ...(options.optimization === "dev" && !options.strip @@ -430,3 +456,22 @@ export function prepareNativeLibrary( timing("frontend-cache-publish"); return input; } + +/** Worker processes that emit function bodies at a time + * (SCRIPTC_EMIT_WORKERS; 0 or 1 emits in this process). */ +function emitWorkers(): number { + const value = Number(process.env["SCRIPTC_EMIT_WORKERS"] ?? "4"); + return Number.isFinite(value) && value > 1 ? Math.floor(value) : 1; +} + +/** The process primitives emission workers fork with, unless the host + * cannot fork or this process is a worker itself. */ +function emitForkPrimitives(): ForkPrimitives | undefined { + const primitives = processFork.primitives; + if (primitives === null || processFork.worker) return undefined; + return { + fork: () => primitives.fork(), + exit: (code) => primitives.exit(code), + wait: (pid) => primitives.wait(pid), + }; +} diff --git a/packages/compiler/src/native/sanitizer.test.ts b/packages/compiler/src/native/sanitizer.test.ts index e6beb24cc..49867f0ad 100644 --- a/packages/compiler/src/native/sanitizer.test.ts +++ b/packages/compiler/src/native/sanitizer.test.ts @@ -120,6 +120,9 @@ test.skipIf(process.platform !== "linux" && process.platform !== "darwin")( tlsCa: false, cipher: false, ecdh: false, + dh: false, + pki: false, + ed25519: false, webcrypto: false, perfLoop: false, nativeFetch: false, diff --git a/packages/compiler/src/native/text-file.test.ts b/packages/compiler/src/native/text-file.test.ts new file mode 100644 index 000000000..b497bc4a2 --- /dev/null +++ b/packages/compiler/src/native/text-file.test.ts @@ -0,0 +1,42 @@ +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, expect, test } from "vitest"; +import { textSlices, writeTextPartsSync } from "./text-file.js"; + +const directories: string[] = []; +afterEach(() => { + for (const path of directories.splice(0)) rmSync(path, { recursive: true, force: true }); +}); + +test("text slices keep surrogate pairs whole and escape as the whole text does", () => { + const text = 'ab😀cé😀😀\ud800x"\\\n' + "z".repeat(5); + for (let length = 2; length <= 8; length++) { + const slices = [...textSlices(text, length)]; + expect(slices.join("")).toBe(text); + for (const slice of slices) { + expect(slice.length).toBeLessThanOrEqual(length); + const last = slice.charCodeAt(slice.length - 1); + // A lone high surrogate of the text may end a slice; a pair's never does. + if (last >= 0xd800 && last <= 0xdbff) expect(slice.endsWith("\ud800")).toBe(true); + } + expect(slices.map((slice) => JSON.stringify(slice).slice(1, -1)).join("")).toBe( + JSON.stringify(text).slice(1, -1), + ); + } + expect([...textSlices("")]).toEqual([]); +}); + +test("a part larger than one slice is written as its UTF-8 bytes", () => { + const dir = mkdtempSync(join(tmpdir(), "scriptc-text-file-")); + directories.push(dir); + // A surrogate pair across the first slice boundary (1 MiB units). + const large = "a".repeat(1024 * 1024 - 1) + "😀" + "b".repeat(1024 * 1024 + 3); + const path = join(dir, "out.txt"); + const seen: string[] = []; + writeTextPartsSync(path, ["head,", large, "", "tail"], (slice) => seen.push(slice)); + const expected = Buffer.from("head," + large + "tail", "utf8"); + expect(readFileSync(path).equals(expected)).toBe(true); + expect(seen.join("")).toBe("head," + large + "tail"); + expect(Math.max(...seen.map((slice) => slice.length))).toBeLessThanOrEqual(1024 * 1024); +}); diff --git a/packages/compiler/src/native/text-file.ts b/packages/compiler/src/native/text-file.ts index 6f8990339..d377c5273 100644 --- a/packages/compiler/src/native/text-file.ts +++ b/packages/compiler/src/native/text-file.ts @@ -24,17 +24,61 @@ export function batchTextParts(parts: readonly string[]): string[] { return batches; } -/** Write text parts to `path` in order without joining them first. Each part - * is one write; pass batched parts (`batchTextParts`) for many small ones. */ -export function writeTextPartsSync(path: string, parts: readonly string[]): void { +/** The most UTF-16 units of a part that one write encodes. */ +const TEXT_WRITE_LENGTH = 1024 * 1024; + +/** `text` in slices of at most `length` (2 or more) UTF-16 units. A slice + * never ends between the two halves of a surrogate pair, so the slices + * encode, as UTF-8 or as JSON string contents, to the encoding of `text`. */ +export function* textSlices(text: string, length = TEXT_WRITE_LENGTH): Generator { + for (let start = 0; start < text.length;) { + let end = Math.min(text.length, start + length); + if (end < text.length) { + const unit = text.charCodeAt(end - 1); + if (unit >= 0xd800 && unit <= 0xdbff) end--; + } + yield text.slice(start, end); + start = end; + } +} + +/** Encodes and writes `part` to `fd` in slices (`textSlices`), so a large + * part is never encoded whole. `written` sees each slice after it is + * written. */ +function writeTextPart(fd: number, part: string, written?: (slice: string) => void): void { + for (const slice of textSlices(part)) { + const bytes = Buffer.from(slice, "utf8"); + for (let offset = 0; offset < bytes.length;) { + offset += writeSync(fd, bytes, offset, bytes.length - offset); + } + written?.(slice); + } +} + +/** Write text parts to `path` in order without joining them first; pass + * batched parts (`batchTextParts`) for many small ones. */ +export function writeTextPartsSync( + path: string, + parts: readonly string[], + written?: (slice: string) => void, +): void { const fd = openSync(path, "w"); try { - for (const part of parts) { - const bytes = Buffer.from(part, "utf8"); - for (let offset = 0; offset < bytes.length;) { - offset += writeSync(fd, bytes, offset, bytes.length - offset); - } - } + for (const part of parts) writeTextPart(fd, part, written); + } finally { + closeSync(fd); + } +} + +/** writeTextPartsSync for parts generated while they are written. */ +export function writeTextGeneratedSync( + path: string, + parts: Generator, + written?: (slice: string) => void, +): void { + const fd = openSync(path, "w"); + try { + for (const part of parts) writeTextPart(fd, part, written); } finally { closeSync(fd); } diff --git a/packages/compiler/surface-manifest.json b/packages/compiler/surface-manifest.json index c05e994a8..81fb23ae2 100644 --- a/packages/compiler/surface-manifest.json +++ b/packages/compiler/surface-manifest.json @@ -1,6 +1,6 @@ { "schemaVersion": 2, - "compilerVersion": "0.4.1", + "compilerVersion": "0.4.2", "coverage": [ "Entries are projected mechanically from the compiler's own decision tables: the diagnostics registry, the unsupported-syntax dispatch tables, the stdlib and node-builtin lowering tables, and the supported-builtin-module list. Nothing is hand-maintained; the manifest regenerates byte-identically from the source tree at this version.", "Absence from this manifest means 'not projected', never 'unsupported'. Surfaces lowered through dedicated code paths rather than tables are not yet projected: console, JSON, Promise/async and the timer surface, the net/http/tls/https/dgram/dns/assert/test/stream/readline module member surfaces, template literals, the regex slice, global functions (parseInt, parseFloat, isNaN, isFinite), and the process surface outside its ambient slice.", @@ -480,6 +480,18 @@ "status": "static", "note": "recognized module (bare and node:-prefixed specifiers)" }, + { + "id": "node-builtin.crypto.checkPrime", + "kind": "node-builtin", + "name": "crypto.checkPrime", + "status": "static" + }, + { + "id": "node-builtin.crypto.checkPrimeSync", + "kind": "node-builtin", + "name": "crypto.checkPrimeSync", + "status": "static" + }, { "id": "node-builtin.crypto.createCipheriv", "kind": "node-builtin", @@ -496,17 +508,13 @@ "id": "node-builtin.crypto.createDiffieHellman", "kind": "node-builtin", "name": "crypto.createDiffieHellman", - "status": "unsupported", - "code": "SC2020", - "note": "asymmetric-key operations need a public-key stack (bignum, RSA/EC/EdDSA math) and public and private KeyObjects — neither exists in the static runtime, so no faithful lowering can be small; the lowered crypto surface is hashing, randomness, secret KeyObjects, and the introspection statics" + "status": "static" }, { "id": "node-builtin.crypto.createDiffieHellmanGroup", "kind": "node-builtin", "name": "crypto.createDiffieHellmanGroup", - "status": "unsupported", - "code": "SC2020", - "note": "asymmetric-key operations need a public-key stack (bignum, RSA/EC/EdDSA math) and public and private KeyObjects — neither exists in the static runtime, so no faithful lowering can be small; the lowered crypto surface is hashing, randomness, secret KeyObjects, and the introspection statics" + "status": "static" }, { "id": "node-builtin.crypto.createECDH", @@ -530,17 +538,13 @@ "id": "node-builtin.crypto.createPrivateKey", "kind": "node-builtin", "name": "crypto.createPrivateKey", - "status": "unsupported", - "code": "SC2020", - "note": "asymmetric-key operations need a public-key stack (bignum, RSA/EC/EdDSA math) and public and private KeyObjects — neither exists in the static runtime, so no faithful lowering can be small; the lowered crypto surface is hashing, randomness, secret KeyObjects, and the introspection statics" + "status": "static" }, { "id": "node-builtin.crypto.createPublicKey", "kind": "node-builtin", "name": "crypto.createPublicKey", - "status": "unsupported", - "code": "SC2020", - "note": "asymmetric-key operations need a public-key stack (bignum, RSA/EC/EdDSA math) and public and private KeyObjects — neither exists in the static runtime, so no faithful lowering can be small; the lowered crypto surface is hashing, randomness, secret KeyObjects, and the introspection statics" + "status": "static" }, { "id": "node-builtin.crypto.createSecretKey", @@ -552,17 +556,13 @@ "id": "node-builtin.crypto.createSign", "kind": "node-builtin", "name": "crypto.createSign", - "status": "unsupported", - "code": "SC2020", - "note": "asymmetric-key operations need a public-key stack (bignum, RSA/EC/EdDSA math) and public and private KeyObjects — neither exists in the static runtime, so no faithful lowering can be small; the lowered crypto surface is hashing, randomness, secret KeyObjects, and the introspection statics" + "status": "static" }, { "id": "node-builtin.crypto.createVerify", "kind": "node-builtin", "name": "crypto.createVerify", - "status": "unsupported", - "code": "SC2020", - "note": "asymmetric-key operations need a public-key stack (bignum, RSA/EC/EdDSA math) and public and private KeyObjects — neither exists in the static runtime, so no faithful lowering can be small; the lowered crypto surface is hashing, randomness, secret KeyObjects, and the introspection statics" + "status": "static" }, { "id": "node-builtin.crypto.diffieHellman", @@ -570,7 +570,7 @@ "name": "crypto.diffieHellman", "status": "unsupported", "code": "SC2020", - "note": "asymmetric-key operations need a public-key stack (bignum, RSA/EC/EdDSA math) and public and private KeyObjects — neither exists in the static runtime, so no faithful lowering can be small; the lowered crypto surface is hashing, randomness, secret KeyObjects, and the introspection statics" + "note": "crypto.diffieHellman takes DH, EC or X25519 KeyObjects and has no lowering; the objects of createDiffieHellman, getDiffieHellman and createECDH compute shared secrets" }, { "id": "node-builtin.crypto.generateKey", @@ -582,17 +582,13 @@ "id": "node-builtin.crypto.generateKeyPair", "kind": "node-builtin", "name": "crypto.generateKeyPair", - "status": "unsupported", - "code": "SC2020", - "note": "asymmetric-key operations need a public-key stack (bignum, RSA/EC/EdDSA math) and public and private KeyObjects — neither exists in the static runtime, so no faithful lowering can be small; the lowered crypto surface is hashing, randomness, secret KeyObjects, and the introspection statics" + "status": "static" }, { "id": "node-builtin.crypto.generateKeyPairSync", "kind": "node-builtin", "name": "crypto.generateKeyPairSync", - "status": "unsupported", - "code": "SC2020", - "note": "asymmetric-key operations need a public-key stack (bignum, RSA/EC/EdDSA math) and public and private KeyObjects — neither exists in the static runtime, so no faithful lowering can be small; the lowered crypto surface is hashing, randomness, secret KeyObjects, and the introspection statics" + "status": "static" }, { "id": "node-builtin.crypto.generateKeySync", @@ -600,21 +596,31 @@ "name": "crypto.generateKeySync", "status": "static" }, + { + "id": "node-builtin.crypto.generatePrime", + "kind": "node-builtin", + "name": "crypto.generatePrime", + "status": "static" + }, + { + "id": "node-builtin.crypto.generatePrimeSync", + "kind": "node-builtin", + "name": "crypto.generatePrimeSync", + "status": "static" + }, { "id": "node-builtin.crypto.getCipherInfo", "kind": "node-builtin", "name": "crypto.getCipherInfo", "status": "unsupported", "code": "SC2020", - "note": "cipher metadata has no lowering — createCipheriv and createDecipheriv support aes-128/192/256 in cbc, ctr, and gcm modes and chacha20-poly1305" + "note": "cipher metadata has no lowering — createCipheriv and createDecipheriv support aes-128/192/256 in cbc, ctr, gcm, ecb, cfb, cfb8, cfb1, and ofb modes, des-ede3 and des-ede, chacha20, and chacha20-poly1305" }, { "id": "node-builtin.crypto.getDiffieHellman", "kind": "node-builtin", "name": "crypto.getDiffieHellman", - "status": "unsupported", - "code": "SC2020", - "note": "asymmetric-key operations need a public-key stack (bignum, RSA/EC/EdDSA math) and public and private KeyObjects — neither exists in the static runtime, so no faithful lowering can be small; the lowered crypto surface is hashing, randomness, secret KeyObjects, and the introspection statics" + "status": "static" }, { "id": "node-builtin.crypto.getRandomValues", @@ -658,7 +664,7 @@ "name": "crypto.privateDecrypt", "status": "unsupported", "code": "SC2020", - "note": "asymmetric-key operations need a public-key stack (bignum, RSA/EC/EdDSA math) and public and private KeyObjects — neither exists in the static runtime, so no faithful lowering can be small; the lowered crypto surface is hashing, randomness, secret KeyObjects, and the introspection statics" + "note": "RSA encryption has no lowering — the asymmetric crypto surface is RSA and EC KeyObjects (generateKeyPair, createPrivateKey, createPublicKey), sign, verify, createSign, createVerify, createECDH, and createDiffieHellman" }, { "id": "node-builtin.crypto.privateEncrypt", @@ -666,7 +672,7 @@ "name": "crypto.privateEncrypt", "status": "unsupported", "code": "SC2020", - "note": "asymmetric-key operations need a public-key stack (bignum, RSA/EC/EdDSA math) and public and private KeyObjects — neither exists in the static runtime, so no faithful lowering can be small; the lowered crypto surface is hashing, randomness, secret KeyObjects, and the introspection statics" + "note": "RSA encryption has no lowering — the asymmetric crypto surface is RSA and EC KeyObjects (generateKeyPair, createPrivateKey, createPublicKey), sign, verify, createSign, createVerify, createECDH, and createDiffieHellman" }, { "id": "node-builtin.crypto.publicDecrypt", @@ -674,7 +680,7 @@ "name": "crypto.publicDecrypt", "status": "unsupported", "code": "SC2020", - "note": "asymmetric-key operations need a public-key stack (bignum, RSA/EC/EdDSA math) and public and private KeyObjects — neither exists in the static runtime, so no faithful lowering can be small; the lowered crypto surface is hashing, randomness, secret KeyObjects, and the introspection statics" + "note": "RSA encryption has no lowering — the asymmetric crypto surface is RSA and EC KeyObjects (generateKeyPair, createPrivateKey, createPublicKey), sign, verify, createSign, createVerify, createECDH, and createDiffieHellman" }, { "id": "node-builtin.crypto.publicEncrypt", @@ -682,7 +688,7 @@ "name": "crypto.publicEncrypt", "status": "unsupported", "code": "SC2020", - "note": "asymmetric-key operations need a public-key stack (bignum, RSA/EC/EdDSA math) and public and private KeyObjects — neither exists in the static runtime, so no faithful lowering can be small; the lowered crypto surface is hashing, randomness, secret KeyObjects, and the introspection statics" + "note": "RSA encryption has no lowering — the asymmetric crypto surface is RSA and EC KeyObjects (generateKeyPair, createPrivateKey, createPublicKey), sign, verify, createSign, createVerify, createECDH, and createDiffieHellman" }, { "id": "node-builtin.crypto.randomBytes", @@ -744,9 +750,7 @@ "id": "node-builtin.crypto.sign", "kind": "node-builtin", "name": "crypto.sign", - "status": "unsupported", - "code": "SC2020", - "note": "asymmetric-key operations need a public-key stack (bignum, RSA/EC/EdDSA math) and public and private KeyObjects — neither exists in the static runtime, so no faithful lowering can be small; the lowered crypto surface is hashing, randomness, secret KeyObjects, and the introspection statics" + "status": "static" }, { "id": "node-builtin.crypto.timingSafeEqual", @@ -758,17 +762,7 @@ "id": "node-builtin.crypto.verify", "kind": "node-builtin", "name": "crypto.verify", - "status": "unsupported", - "code": "SC2020", - "note": "asymmetric-key operations need a public-key stack (bignum, RSA/EC/EdDSA math) and public and private KeyObjects — neither exists in the static runtime, so no faithful lowering can be small; the lowered crypto surface is hashing, randomness, secret KeyObjects, and the introspection statics" - }, - { - "id": "node-builtin.crypto.webcrypto", - "kind": "node-builtin", - "name": "crypto.webcrypto", - "status": "unsupported", - "code": "SC2020", - "note": "the WebCrypto object has no lowering — the lowered crypto surface is randomUUID, randomBytes, and the createHash chain" + "status": "static" }, { "id": "node-builtin.dgram", @@ -5719,14 +5713,14 @@ "kind": "stdlib", "name": "CryptoKey", "status": "static", - "note": "secret HMAC keys with type, extractable, algorithm and usages, and instanceof CryptoKey" + "note": "secret HMAC, AES, PBKDF2 and HKDF keys with type, extractable, algorithm and usages, and instanceof CryptoKey" }, { "id": "stdlib.webcrypto.subtle", "kind": "stdlib", "name": "globalThis.crypto.subtle", "status": "static", - "note": "importKey('raw') for HMAC keys, HMAC sign and verify, and SHA-1/SHA-2 digest; other methods, algorithms and key formats are refused" + "note": "importKey, generateKey and exportKey (raw and jwk) for HMAC and AES keys, importKey for PBKDF2 and HKDF keys, AES-GCM, AES-CBC and AES-CTR encrypt and decrypt, wrapKey and unwrapKey of secret keys with AES-KW or those ciphers, PBKDF2 and HKDF deriveBits and deriveKey, HMAC sign and verify, generateKey, importKey, exportKey, sign and verify for ECDSA, Ed25519, RSASSA-PKCS1-v1_5 and RSA-PSS, and SHA-1/SHA-2 digest; other methods, algorithms and key formats are refused" }, { "id": "syntax.async-generators", diff --git a/packages/compiler/test/array-pipeline-fusion.test.ts b/packages/compiler/test/array-pipeline-fusion.test.ts index f5d743265..55cd0025e 100644 --- a/packages/compiler/test/array-pipeline-fusion.test.ts +++ b/packages/compiler/test/array-pipeline-fusion.test.ts @@ -26,7 +26,7 @@ function helperCalls(fn: IrFunction): string[] { everyStmtList(fn.body, { expr: (e) => { if (e.kind === "call" && e.callee.startsWith("%arr.")) - calls.push(e.callee.replace(/\.\d+$/, "")); + calls.push(e.callee.replace(/\.[0-9a-f]+$/, "")); return true; }, stmt: () => true, diff --git a/packages/compiler/test/await-call-emission.test.ts b/packages/compiler/test/await-call-emission.test.ts index 96c039155..5a967cc5f 100644 --- a/packages/compiler/test/await-call-emission.test.ts +++ b/packages/compiler/test/await-call-emission.test.ts @@ -222,7 +222,8 @@ test("bodies that suspend only at their own awaits compile to stackless coroutin }); const framedSources = { - // Entering a store makes the frame isolate the AsyncLocalStorage context. + // Entering a store needs no frame: the body runs in its caller's context, + // as Node runs an async body's synchronous prefix. context: ` import { AsyncLocalStorage } from "node:async_hooks"; const store = new AsyncLocalStorage(); @@ -238,7 +239,7 @@ async function leaf(x: number): Promise { }`, }; -test("fiberless bodies keep their frame where it isolates a context or a stack", async () => { +test("fiberless bodies keep their frame only where it isolates a stack", async () => { for (const [name, prefix] of Object.entries(framedSources)) { const llvm = await emit(`${prefix} async function slow(x: number): Promise { @@ -262,9 +263,12 @@ async function main(): Promise { void main(); `); for (const symbol of ["sc_ai_leaf", "sc_aw_leaf", "sc_as_leaf"]) { - expect(definition(llvm, symbol), `${name} ${symbol}`).toContain( - "call void @scr_async_inline_enter(ptr %frame)", - ); + const body = definition(llvm, symbol); + if (name === "stack") + expect(body, `${name} ${symbol}`).toContain( + "call void @scr_async_inline_enter(ptr %frame)", + ); + else expect(body, `${name} ${symbol}`).not.toContain("@scr_async_inline_enter"); } } }); diff --git a/packages/compiler/test/bytes-callback-helpers.test.ts b/packages/compiler/test/bytes-callback-helpers.test.ts new file mode 100644 index 000000000..c47d106c4 --- /dev/null +++ b/packages/compiler/test/bytes-callback-helpers.test.ts @@ -0,0 +1,68 @@ +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { expect, test } from "vitest"; +import { compile, deserializeModule, validateModule } from "../src/index.js"; +import type { IrFunction, IrModule, IrStmt } from "../src/ir/ir.js"; + +async function lower(source: string): Promise { + const dir = await mkdtemp(join(tmpdir(), "scriptc-bytes-callbacks-")); + try { + const entry = join(dir, "main.ts"); + const outPath = join(dir, "main.ir.json"); + await writeFile(entry, source); + const result = await compile(entry, { outDir: dir, outPath, outputKind: "ir" }); + if (!result.ok) + throw new Error(result.diagnostics.map((d) => `${d.code}: ${d.message}`).join("\n")); + const mod = deserializeModule(await readFile(outPath, "utf8")); + expect(validateModule(mod)).toEqual([]); + return mod; + } finally { + await rm(dir, { recursive: true, force: true }); + } +} + +const helpers = (mod: IrModule, method: string): IrFunction[] => + mod.functions.filter((f) => f.name.startsWith(`%bytes.${method}.`)); + +const visitLoop = (fn: IrFunction): IrStmt & { kind: "for" } => { + const loop = fn.body.find((s): s is IrStmt & { kind: "for" } => s.kind === "for"); + if (!loop) throw new Error(`no loop in ${fn.name}`); + return loop; +}; + +test("literal callbacks get helpers of their own; function values share one", async () => { + const mod = await lower(` + const a = new Int32Array([1, 2, 3]); + const double = (v: number): number => v * 2; + console.log(a.map((v) => v + 1).join(","), a.map((v) => v - 1).join(",")); + console.log(a.map(double).join(","), new Int32Array([4]).map(double).join(",")); + `); + expect(helpers(mod, "map")).toHaveLength(3); +}); + +test("typed-array callback loops run on their own counter", async () => { + const mod = await lower(` + const a = new Float64Array([1.5, 2.5, 3.5]); + console.log(a.some((v) => v > 2), a.reduce((s, v) => s + v)); + console.log(a.reduceRight((s, v) => s - v), a.findLastIndex((v) => v < 3)); + `); + for (const method of ["some", "reduce"]) { + const loop = visitLoop(helpers(mod, method)[0]!); + // for (let i = <0 or 1 past reduce's seed>; i < a.length; i = i + 1) + expect(loop.init).toMatchObject({ kind: "varDecl", localId: "i.0", init: { kind: "numLit" } }); + expect(loop.cond).toMatchObject({ + kind: "bin", + op: "<", + right: { kind: "bytesIntrinsic", method: "length" }, + }); + } + expect(visitLoop(helpers(mod, "reduce")[0]!).init).toMatchObject({ init: { value: 1 } }); + // Backward: from n - 2 past reduceRight's seed, and from n - 1. + expect(visitLoop(helpers(mod, "reduceRight")[0]!).init).toMatchObject({ + init: { kind: "bin", op: "-", right: { value: 2 } }, + }); + expect(visitLoop(helpers(mod, "findLastIndex")[0]!).init).toMatchObject({ + init: { kind: "bin", op: "-", right: { value: 1 } }, + }); +}); diff --git a/packages/compiler/test/callback-loop-versions.test.ts b/packages/compiler/test/callback-loop-versions.test.ts new file mode 100644 index 000000000..63a669fd4 --- /dev/null +++ b/packages/compiler/test/callback-loop-versions.test.ts @@ -0,0 +1,114 @@ +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { expect, test } from "vitest"; +import { compile } from "../src/index.js"; + +async function emitLlvm(source: string): Promise { + const dir = await mkdtemp(join(tmpdir(), "scriptc-callback-versions-")); + try { + const entry = join(dir, "main.ts"); + const outPath = join(dir, "main.ll"); + await writeFile(entry, source); + const result = await compile(entry, { outDir: dir, outPath, outputKind: "llvm" }); + if (!result.ok) throw new Error(result.diagnostics.map((d) => d.message).join("\n")); + return await readFile(outPath, "utf8"); + } finally { + await rm(dir, { recursive: true, force: true }); + } +} + +const body = (llvm: string, marker: string): string => { + const match = new RegExp(`^define internal [^\\n]*${marker}[^]*?^}`, "m").exec(llvm); + if (!match) throw new Error(`no function ${marker}`); + return match[0]; +}; + +test("loops that call a known callback test its closure once and call it directly", async () => { + const llvm = await emitLlvm(` + function each(values: number[], visit: (v: number) => void): void { + for (let i = 0; i < values.length; i++) visit(values[i]!); + } + let sum = 0; + each([1, 2, 3], (v) => { sum += v; }); + console.log(sum); + `); + const fn = body(llvm, "@sc_bf_each"); + const fast = /^callback\.version\.fast\d+:$[^]*?^callback\.version\.done\d+:$/m.exec(fn)![0]; + // The guard compares the closure's code pointer once, before the loop. + expect(fn.slice(0, fn.indexOf(fast))).toMatch(/icmp eq ptr %\S+, @/); + expect(fast).not.toContain("callback.indirect"); + expect(fast).not.toContain("scr_dyn_this_push_dyn"); + // The ordinary copy keeps the fallback through the closure's pointer. + expect(fn).toContain("callback.indirect"); +}); + +test("captured number payloads carry their own alias tag", async () => { + const llvm = await emitLlvm(` + function total(values: number[]): number { + let sum = 0; + values.forEach((v) => { sum += v; }); + return sum; + } + console.log(total([1, 2, 3])); + `); + // Every read and write through a box's payload slot (field 5) is tagged. + const slots = [ + ...llvm.matchAll(/(%\S+) = getelementptr inbounds %ScrBox, ptr %\S+, i32 0, i32 5/g), + ]; + expect(slots.length).toBeGreaterThan(0); + for (const [, slot] of slots) { + for (const access of llvm.matchAll( + new RegExp(`(load double, ptr|store double %\\S+, ptr) \\${slot}\\b[^\\n]*`, "g"), + )) + expect(access[0]).toMatch(/!tbaa !\d+$/); + } + expect(llvm).toMatch(/load double, ptr %\S+, !tbaa !\d+/); +}); + +test("a callback declared in the loop body is not read before the loop", async () => { + const llvm = await emitLlvm(` + function strides(): number { + let calls = 0; + for (let i = 0; i < 10; i++) { + const bump = (): void => { i += 2; }; + bump(); + calls++; + } + return calls; + } + console.log(strides()); + `); + expect(llvm).not.toContain("callback.version"); +}); + +test("loops inside a callback version are not versioned again", async () => { + // Each inner loop calls a callback a factory builds just before it; without + // the limit, every copy of a version would version the next loop again. + const llvm = await emitLlvm(` + function adder(k: number): (v: number) => number { + return (v: number) => v + k; + } + function nest(n: number, f: (v: number) => number): number { + let s = 0; + for (let i = 0; i < n; i++) { + s += f(i); + const g = adder(i); + for (let j = 0; j < n; j++) { + s += g(j); + const h = adder(j); + for (let k = 0; k < n; k++) s += h(k); + } + } + return s; + } + console.log(nest(3, (v) => v - 1), nest(2, (v) => v * 3)); + `); + // One version for the outer loop of each compiled `nest`; its two copies + // keep the inner loops whole. + const versions = [...llvm.matchAll(/^define [^\n]*@sc_bf_nest[^]*?^}/gm)].map( + ([body]) => body.match(/^callback\.version\.fast\d+:$/gm)?.length ?? 0, + ); + expect(versions.every((count) => count <= 1)).toBe(true); + expect(versions.some((count) => count === 1)).toBe(true); +}); diff --git a/packages/compiler/test/cc-driver.test.ts b/packages/compiler/test/cc-driver.test.ts index b9f0403c6..5ddae6534 100644 --- a/packages/compiler/test/cc-driver.test.ts +++ b/packages/compiler/test/cc-driver.test.ts @@ -291,6 +291,11 @@ test.skipIf(!zigOnPath())( options: { ecdh: true, dynAsync: true, dynInvoke: true, inspect: true }, call: "scr_dyn_release(scr_crypto_ecdh_new(scr_dyn_undefined()))", }, + { + name: "dh", + options: { dh: true, dynInvoke: true, inspect: true }, + call: "scr_dyn_release(scr_crypto_dh_group_new(scr_dyn_undefined()))", + }, ]; try { await withCcEnv("zigcc", "x86_64-windows-gnu", async () => { diff --git a/packages/compiler/test/chunked-emission.test.ts b/packages/compiler/test/chunked-emission.test.ts new file mode 100644 index 000000000..b4912c9f6 --- /dev/null +++ b/packages/compiler/test/chunked-emission.test.ts @@ -0,0 +1,122 @@ +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { expect, test } from "vitest"; +import { compile, deserializeModule } from "../src/index.js"; +import type { IrModule } from "../src/ir/ir.js"; +import { emitLlvmModuleSource, type LlvmTargetOptions } from "../src/backend/llvm/emitter.js"; +import { inlineRcOption } from "../src/backend/llvm/shapes.js"; + +// Programs whose function bodies request module-level helpers and tables +// that the chunk journal (emit-journal.ts) carries: checked-dynamic +// conversions, inspection, publication walkers, live record views, stream +// adapters, regex instances, colliding literal digests, interned C strings, +// speculative loop sites, typed message listeners and readers. +const PROGRAMS = [ + "1003-json-parse-unions.ts", + "114-live-record-delete.ts", + "1200-regex-test-basics.ts", + "1631-inspect-arrays.ts", + "4598-publish-constructor-stores.ts", + "4900-console-instances.ts", + "5612-readable-from-iterables.cjs", + "5702-publish-candidate-buffers.ts", + "7321-speculative-loop-bail-sites.ts", + "7360-worker-typed-records.ts", + "node24-text-utilities-coercion.js", +]; + +const OPTIONS: Record = { + release: {}, + speed: { + targetTriple: "x86_64-unknown-linux-gnu", + pointerBits: 64, + runtimeAbiMarker: true, + lowRegion: true, + ...inlineRcOption("speed", false), + }, +}; + +const text = (out: string | readonly string[]): string => + typeof out === "string" ? out : out.join(""); + +async function lower(program: string, dir: string): Promise { + const entry = join(import.meta.dirname, "../../../tests/corpus", program); + const outPath = join(dir, `${program}.ir.json`); + const result = await compile(entry, { outDir: dir, outPath, outputKind: "ir" }); + if (!result.ok) + throw new Error(result.diagnostics.map((d) => `${d.code}: ${d.message}`).join("\n")); + return readFile(outPath, "utf8"); +} + +test("function bodies emitted in chunks merge into the text one emitter gives", async () => { + const dir = await mkdtemp(join(tmpdir(), "scriptc-chunked-emission-")); + try { + for (const program of PROGRAMS) { + const ir = await lower(program, dir); + const fresh = (): IrModule => deserializeModule(ir); + for (const [name, options] of Object.entries(OPTIONS)) { + const serial = text(emitLlvmModuleSource(fresh(), options)); + for (const functionChunks of [3, 7]) { + const chunked = text(emitLlvmModuleSource(fresh(), { ...options, functionChunks })); + expect(chunked === serial, `${program}, ${name}, ${functionChunks} chunks`).toBe(true); + } + } + } + } finally { + await rm(dir, { recursive: true, force: true }); + } +}, 600_000); + +// Debug metadata is numbered per emitter (debug-info.ts) and not journaled: +// a debug build emits its function bodies in one emitter. +test("debug builds emit function bodies serially, with every metadata reference defined", async () => { + const dir = await mkdtemp(join(tmpdir(), "scriptc-chunked-debug-")); + const minFunctions = process.env["SCRIPTC_EMIT_WORKER_FUNCTIONS"]; + try { + const corpus = join(import.meta.dirname, "../../../tests/corpus/3066-source-debugging"); + const entry = join(corpus, "main.ts"); + const outPath = join(dir, "main.ir.json"); + const result = await compile(entry, { + outDir: dir, + outPath, + outputKind: "ir", + optimization: "dev", + }); + if (!result.ok) + throw new Error(result.diagnostics.map((d) => `${d.code}: ${d.message}`).join("\n")); + const ir = await readFile(outPath, "utf8"); + const debugSources = new Map(); + for (const name of ["main.ts", "helper.ts"]) + debugSources.set(join(corpus, name), await readFile(join(corpus, name), "utf8")); + const options: LlvmTargetOptions = { debugSources }; + const serial = text(emitLlvmModuleSource(deserializeModule(ir), options)); + expect(serial).toContain("!DILocation"); + + let forks = 0; + process.env["SCRIPTC_EMIT_WORKER_FUNCTIONS"] = "1"; + const forkPrimitives = { + fork: (): number => { + forks++; + return -1; + }, + exit: (): void => {}, + wait: (): number => -1, + }; + for (const variant of [ + { functionChunks: 3 }, + { functionWorkers: 4, forkPrimitives }, + ] satisfies LlvmTargetOptions[]) { + const emitted = text(emitLlvmModuleSource(deserializeModule(ir), { ...options, ...variant })); + expect(emitted === serial, JSON.stringify(Object.keys(variant))).toBe(true); + const defined = new Set([...emitted.matchAll(/^(![0-9]+) = /gm)].map((m) => m[1])); + const referenced = new Set([...emitted.matchAll(/(![0-9]+)\b/g)].map((m) => m[1])); + expect([...referenced].filter((id) => !defined.has(id))).toEqual([]); + } + expect(forks).toBe(0); + } finally { + if (minFunctions === undefined) delete process.env["SCRIPTC_EMIT_WORKER_FUNCTIONS"]; + else process.env["SCRIPTC_EMIT_WORKER_FUNCTIONS"] = minFunctions; + await rm(dir, { recursive: true, force: true }); + } +}, 120_000); diff --git a/packages/compiler/test/format-float-arguments.test.ts b/packages/compiler/test/format-float-arguments.test.ts index e59e023ca..6ce9c4bc0 100644 --- a/packages/compiler/test/format-float-arguments.test.ts +++ b/packages/compiler/test/format-float-arguments.test.ts @@ -27,7 +27,7 @@ test("util.format %f lowers a boolean argument once", async () => { const helpers = mod.functions .map((f) => f.name) .filter((name) => name.startsWith("%arr.")) - .map((name) => name.replace(/\.\d+$/, "")) + .map((name) => name.replace(/\.[0-9a-f]+$/, "")) .sort(); expect(helpers).toEqual(["%arr.every", "%arr.some"]); } finally { diff --git a/packages/compiler/test/in-runtime-key-emission.test.ts b/packages/compiler/test/in-runtime-key-emission.test.ts index aebbb2ea4..589685a7a 100644 --- a/packages/compiler/test/in-runtime-key-emission.test.ts +++ b/packages/compiler/test/in-runtime-key-emission.test.ts @@ -55,7 +55,7 @@ const d: Record = {}; d["a"] = 1; console.log(has(d, "a"), has(d, "b")); `); - const helper = body(llvm, /sc_b?f__x25_rec_haskey_\d+/); + const helper = body(llvm, /sc_b?f__x25_rec_haskey_[0-9a-f]+/); expect(helper).toContain("@scr_map_has_str("); // Not a scan over a fresh key snapshot per probe. expect(helper).not.toContain("@scr_map_keys_js_order("); diff --git a/packages/compiler/test/native-codegen-integration.test.ts b/packages/compiler/test/native-codegen-integration.test.ts index d8f158ebc..0fd5249d3 100644 --- a/packages/compiler/test/native-codegen-integration.test.ts +++ b/packages/compiler/test/native-codegen-integration.test.ts @@ -378,7 +378,7 @@ done: expect(await symbols(helperObject, ["-u"])).toEqual(await symbols(clangObject, ["-u"])); expect(await symbols(helperObject, ["-gU"])).toEqual(await symbols(clangObject, ["-gU"])); expect(await symbols(helperObject, ["-gU"])).toEqual(["0000000000000000 T _main"]); - expect(await symbols(helperObject, ["-u"])).toContain("_scr_runtime_abi_v24"); + expect(await symbols(helperObject, ["-u"])).toContain("_scr_runtime_abi_v33"); const clangExe = join(dir, "clang-program"); const linkDriver = join(dir, "clang-driver.c"); @@ -712,7 +712,7 @@ done: .split("\n"); expect(undefinedSymbols).toContain("_sf_scale"); expect(undefinedSymbols).toContain("_sf_callback_mix"); - expect(undefinedSymbols).toContain("_scr_runtime_abi_v24"); + expect(undefinedSymbols).toContain("_scr_runtime_abi_v33"); }); test("helper and clang object paths retain the same outbound FFI C ABI", async () => { diff --git a/packages/compiler/test/package-shim-guard.test.ts b/packages/compiler/test/package-shim-guard.test.ts index ff01acbb8..a8620c1ce 100644 --- a/packages/compiler/test/package-shim-guard.test.ts +++ b/packages/compiler/test/package-shim-guard.test.ts @@ -49,7 +49,10 @@ describe("package shims compile without refusals", () => { const entries = packageShimEntries(); test("the registry lists its shim modules", () => { expect(entries.map((e) => e.slice(shimRoot.length + 1))).toEqual([ + "chalk/v5.ts", "fs-extra/index.ts", + "hot-shots/v8-unix-dgram.ts", + "hot-shots/v8.ts", "undici/v5.ts", "undici/v7.ts", ]); diff --git a/packages/compiler/test/parameter-version-emission.test.ts b/packages/compiler/test/parameter-version-emission.test.ts new file mode 100644 index 000000000..eb6daff56 --- /dev/null +++ b/packages/compiler/test/parameter-version-emission.test.ts @@ -0,0 +1,71 @@ +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { expect, test } from "vitest"; +import { compile } from "../src/index.js"; + +async function emitLlvm(source: string): Promise { + const dir = await mkdtemp(join(tmpdir(), "scriptc-parameter-version-")); + try { + const entry = join(dir, "main.ts"); + const outPath = join(dir, "main.ll"); + await writeFile(entry, source); + const result = await compile(entry, { outDir: dir, outPath, outputKind: "llvm" }); + expect(result.ok, JSON.stringify(result.diagnostics)).toBe(true); + return await readFile(outPath, "utf8"); + } finally { + await rm(dir, { recursive: true, force: true }); + } +} + +const versions = (llvm: string): string[] => [ + ...new Set([...llvm.matchAll(/^define [^@]*@sc_\w+?_(\w+?)_int32Params\b/gm)].map((m) => m[1]!)), +]; + +const loops = ` +function sumTo(n: number): number { + let s = 0; + for (let i = 0; i < n; i++) s += i; + return s; +} +function literal(n: number): number { + let s = 0; + for (let i = 0; i < n; i++) s += i; + return s; +} +function recursive(n: number): number { + let s = 0; + for (let i = 0; i < n; i++) s += i; + return n > 0 ? s + recursive(n - 1) : s; +} +function unbounded(n: number): number { + let s = 0; + for (let i = 0; i < 10; i++) s += n; + return s; +} +class Counter { + total(n: number): number { + let s = 0; + for (let i = 0; i < n; i++) s += i; + return s; + } +} +const n = Number(process.argv.length > 5 ? "7.5" : "6"); +console.log(sumTo(n), literal(4), literal(5), recursive(n), unbounded(n), new Counter().total(n)); +`; + +test("a loop-bounding parameter some caller passes unproven gets an int32 version", async () => { + const llvm = await emitLlvm(loops); + expect(versions(llvm)).toEqual(["sumTo"]); + // The version takes the parameter as an i32, and the body dispatches to it + // after testing for an int32 that is not -0. + expect(llvm).toMatch(/^define [^@]*@sc_\w+_sumTo_int32Params\.i32\(i32 /m); + const body = /^define [^@]*@sc_\w+?_sumTo\([^]*?^}/m.exec(llvm)?.[0] ?? ""; + expect(body).toMatch(/call [^@]*@sc_\w+_sumTo_int32Params/); + expect(body).toMatch(/fdiv double 0x3FF0000000000000, %\S+/); +}); + +test("a module that reads stacks keeps a single body", async () => { + const llvm = await emitLlvm(`${loops}\nconsole.log(typeof new Error("x").stack);\n`); + expect(versions(llvm)).toEqual([]); +}); diff --git a/packages/compiler/test/regex-matcher-bounds.test.ts b/packages/compiler/test/regex-matcher-bounds.test.ts new file mode 100644 index 000000000..3e0ec7f1b --- /dev/null +++ b/packages/compiler/test/regex-matcher-bounds.test.ts @@ -0,0 +1,91 @@ +/* Compiled regex matchers bound every read by the characters left in the + * subject, so subjects near the runtime's 2^31 - 2 character limit are + * read only inside the subject. Each matcher runs on a subject of exactly + * that length whose last byte sits just before an inaccessible page: a + * bounds check that wraps past INT32_MAX reads that page and faults. The + * subject is a lazily mapped zero region (no memory is committed for it) + * with the characters each case needs written near its end. */ +import { execFileSync } from "node:child_process"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { expect, test } from "vitest"; +import { compileRegexMatcher, REGEX_MATCHER_DECLS } from "../src/backend/llvm/regex-matchers.js"; + +const LIMIT = 2 ** 31 - 2; + +/** [symbol, pattern, flags, start offset from the end, tail text]. */ +const CASES: [string, string, string, number, string][] = [ + // The first-character vector search, 10 characters before the end. + ["seek", "[b-d]", "", 10, "c"], + // The start filter (two 8-character alternatives), 20 before the end. + ["filter", "agggtaaa|tttaccct", "i", 20, "TTTACCCT"], + // A run of 8 literal characters beginning 2 before the end. + ["run", "xy234567", "", 30, "xy"], + // A greedy class over the whole subject, 16 characters per step. + ["greedy", "[^x]+", "", LIMIT, ""], +]; + +const DRIVER = ` +#include +#include +#include +#include +#include +void scr_regex_stack_grow(void *a, void *b, void *c, int32_t d) { (void)a; (void)b; (void)c; (void)d; _exit(3); } +void scr_regex_stack_free(void *p) { (void)p; } +${CASES.map(([sym]) => `int32_t ${sym}(const char *, int32_t, int32_t, const char **);`).join("\n")} +static void check(const char *name, int32_t (*m)(const char *, int32_t, int32_t, const char **), + int32_t start, const char *tail) { + const int32_t len = ${LIMIT}; + size_t page = (size_t)sysconf(_SC_PAGESIZE); + size_t body = ((size_t)len + page - 1) / page * page; + char *base = mmap(NULL, body + page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0); + if (base == MAP_FAILED || mprotect(base + body, page, PROT_NONE) != 0) _exit(4); + char *s = base + (body - (size_t)len); + memcpy(s + len - strlen(tail), tail, strlen(tail)); + const char *out[16] = {0}; + int32_t found = m(s, len, start, out); + if (found) printf("%s %ld %ld\\n", name, (long)(out[0] - s), (long)(out[1] - s)); + else printf("%s none\\n", name); + fflush(stdout); + munmap(base, body + page); +} +int main(void) { +${CASES.map(([sym, , , back, tail]) => ` check("${sym}", ${sym}, ${LIMIT - back}, ${JSON.stringify(tail)});`).join("\n")} + return 0; +} +`; + +test.skipIf(process.platform === "win32")( + "compiled regex matchers stay inside subjects near 2^31 characters", + { timeout: 120_000 }, + () => { + const lines: string[] = []; + const decls = new Set(REGEX_MATCHER_DECLS); + for (const [sym, pattern, flags] of CASES) { + const code = compileRegexMatcher(sym, pattern, flags, "i64", true); + if (code === null) throw new Error(`/${pattern}/${flags} did not compile`); + lines.push(...code.lines.map((line) => line.replace(/^define internal /, "define "))); + for (const decl of code.decls) decls.add(decl); + } + const dir = mkdtempSync(join(tmpdir(), "scriptc-regex-bounds-")); + try { + const ir = join(dir, "matchers.ll"); + const driver = join(dir, "driver.c"); + const binary = join(dir, "bounds"); + writeFileSync(ir, [...decls, ...lines, "attributes #0 = { nounwind }", ""].join("\n")); + writeFileSync(driver, DRIVER); + execFileSync("clang", ["-O2", "-Wno-override-module", ir, driver, "-o", binary]); + const output = execFileSync(binary, { encoding: "utf8" }); + expect(output.trim().split("\n")).toEqual([ + `seek ${LIMIT - 1} ${LIMIT}`, + `filter ${LIMIT - 8} ${LIMIT}`, + "run none", + `greedy 0 ${LIMIT}`, + ]); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }, +); diff --git a/packages/compiler/test/running-extrema-branches.test.ts b/packages/compiler/test/running-extrema-branches.test.ts new file mode 100644 index 000000000..e1f5a7837 --- /dev/null +++ b/packages/compiler/test/running-extrema-branches.test.ts @@ -0,0 +1,75 @@ +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { expect, test } from "vitest"; +import { compile } from "../src/index.js"; + +async function emitLlvm(source: string): Promise { + const dir = await mkdtemp(join(tmpdir(), "scriptc-running-extrema-")); + try { + const entry = join(dir, "main.ts"); + const outPath = join(dir, "main.ll"); + await writeFile(entry, source); + const result = await compile(entry, { outDir: dir, outPath, outputKind: "llvm" }); + if (!result.ok) throw new Error(result.diagnostics.map((d) => d.message).join("\n")); + return await readFile(outPath, "utf8"); + } finally { + await rm(dir, { recursive: true, force: true }); + } +} + +const RARE = + /br i1 %\S+, label %if\.t\d+, label %if\.j\d+, !prof !\{!"branch_weights", i32 1, i32 1000\}/; + +test("a running maximum's update is weighted as rarely taken", async () => { + const llvm = await emitLlvm(` + function argmax(a: Float64Array): number { + let max = -Infinity; + let at = -1; + for (let i = 0; i < a.length; i++) { + const v = a[i]!; + if (v > max) { max = v; at = i; } + } + return at; + } + console.log(argmax(new Float64Array([1, 3, 2]))); + `); + expect(llvm).toMatch(RARE); +}); + +test("a callback's update of a captured minimum is weighted", async () => { + const llvm = await emitLlvm(` + function least(values: number[]): number { + let min = Infinity; + values.forEach((v) => { if (min > v) min = v; }); + return min; + } + console.log(least([3, 1, 2])); + `); + expect(llvm).toMatch(RARE); +}); + +test("clamps and saturating sums keep their selects", async () => { + const llvm = await emitLlvm(` + function clampSum(a: Float64Array, hi: number): number { + let s = 0; + for (let i = 0; i < a.length; i++) { + let v = a[i]!; + if (hi < v) v = hi; + s += v; + } + return s; + } + function saturate(a: Float64Array, hi: number): number { + let v = 0; + for (let i = 0; i < a.length; i++) { + v += a[i]!; + if (hi < v) v = hi; + } + return v; + } + const a = new Float64Array([0.5, 2, 0.25]); + console.log(clampSum(a, 1), saturate(a, 1)); + `); + expect(llvm).not.toContain("branch_weights"); +}); diff --git a/packages/compiler/test/speculative-loop-emission.test.ts b/packages/compiler/test/speculative-loop-emission.test.ts new file mode 100644 index 000000000..a81348102 --- /dev/null +++ b/packages/compiler/test/speculative-loop-emission.test.ts @@ -0,0 +1,93 @@ +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { expect, test } from "vitest"; +import { compile } from "../src/index.js"; + +async function emitLlvm(source: string): Promise { + const dir = await mkdtemp(join(tmpdir(), "scriptc-speculative-loop-")); + try { + const entry = join(dir, "main.ts"); + const outPath = join(dir, "main.ll"); + await writeFile(entry, source); + const result = await compile(entry, { outDir: dir, outPath, outputKind: "llvm" }); + expect(result.ok, JSON.stringify(result.diagnostics)).toBe(true); + return await readFile(outPath, "utf8"); + } finally { + await rm(dir, { recursive: true, force: true }); + } +} + +const source = ` +class Point { + x: number; + w = 0; + constructor(x: number) { + this.x = x; + } +} +function scaled(points: Point[], scale: number): number { + let s = 0; + for (let i = 0; i < points.length; i++) { + const p = points[i]!; + p.w += 1; + const k = p.x * scale; + s += k * k; + } + return s; +} +console.log(scaled([new Point(1), new Point(2)], 2), scaled([new Point(1)], 0.5)); +`; + +function labels(fn: string): string[] { + return [...fn.matchAll(/^([\w.]+):/gm)].map((m) => m[1]!); +} + +test("a failed check finishes its iteration outside the ordinary copy", async () => { + const llvm = await emitLlvm(source); + const fn = /^define internal double @sc_bf_scaled\([^]*?^}/m.exec(llvm)?.[0] ?? ""; + const order = labels(fn); + // The loop may have several speculative sites (one in each copy of a + // dense-array loop). Each site emits its ordinary copy, its third copy + // and its fast copy in that order. + const slows = order.flatMap((l, i) => (l.startsWith("spec.slow") ? [i] : [])); + expect(slows.length).toBeGreaterThan(0); + let resumes = 0; + for (const slow of slows) { + const next = (prefix: string): number => + order.findIndex((l, i) => i > slow && l.startsWith(prefix)); + const tail = next("spec.tail"); + const fast = next("spec.fast"); + expect(tail).toBeGreaterThan(slow); + expect(fast).toBeGreaterThan(tail); + // Every resume point of the site is in its third copy, between that + // copy's start and the fast copy, so the ordinary copy has one entry. + for (let i = slow + 1; i < fast; i++) { + if (!order[i]!.startsWith("spec.resume")) continue; + expect(i).toBeGreaterThan(tail); + resumes++; + } + // The third copy's header leaves for the ordinary copy's header. + const header = order[slow + 1]!; + const third = fn.slice(fn.indexOf(`\n${order[tail]}:`), fn.indexOf(`\n${order[fast]}:`)); + expect(third).toContain(`br label %${header}`); + } + expect(resumes).toBe(order.filter((l) => l.startsWith("spec.resume")).length); + expect(resumes).toBeGreaterThan(0); +}); + +test("a loop site stops entering its fast copy after repeated bails", async () => { + const llvm = await emitLlvm(source); + const site = /^(@sc_spec_bails_\d+) = internal global i8 0$/m.exec(llvm)?.[1]; + expect(site).toBeDefined(); + const fn = /^define internal double @sc_bf_scaled\([^]*?^}/m.exec(llvm)?.[0] ?? ""; + // The entry test reads the count, a bail adds one, and a completed fast + // copy clears it. + expect(fn).toMatch( + new RegExp( + `(%\\S+) = load atomic i8, ptr ${site} unordered, align 1\\n\\s*%\\S+ = icmp ult i8 \\1, 8`, + ), + ); + expect(fn).toMatch(new RegExp(`call i8 @llvm\\.uadd\\.sat\\.i8\\(i8 %\\S+, i8 1\\)`)); + expect(fn).toContain(`store atomic i8 0, ptr ${site} unordered, align 1`); +}); diff --git a/packages/compiler/test/stable-names.test.ts b/packages/compiler/test/stable-names.test.ts new file mode 100644 index 000000000..c82db039d --- /dev/null +++ b/packages/compiler/test/stable-names.test.ts @@ -0,0 +1,119 @@ +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { expect, test } from "vitest"; +import { compile, deserializeModule, type IrModule } from "../src/index.js"; + +/** Lowers each source in turn as the same file, so names that include the + * file's path compare equal. */ +async function lower(...sources: string[]): Promise { + const dir = await mkdtemp(join(tmpdir(), "scriptc-stable-names-")); + try { + const entry = join(dir, "main.ts"); + const outPath = join(dir, "main.ir.json"); + const modules: IrModule[] = []; + for (const source of sources) { + await writeFile(entry, source); + const result = await compile(entry, { outDir: dir, outPath, outputKind: "ir" }); + if (!result.ok) + throw new Error(result.diagnostics.map((d) => `${d.code}: ${d.message}`).join("\n")); + modules.push(deserializeModule(await readFile(outPath, "utf8"))); + } + return modules; + } finally { + await rm(dir, { recursive: true, force: true }); + } +} + +function names(mod: IrModule): string[] { + return [ + ...mod.records.map((record) => record.id), + ...mod.unions.map((union) => union.id), + ...mod.functions.map((fn) => fn.name), + ...mod.classes.map((cls) => cls.name), + ].sort(); +} + +const recursive = ` +type Tree = { value: number; children: Tree[]; parent: Tree | null }; +function total(tree: Tree): number { + let sum = tree.value; + for (const child of tree.children) sum += total(child); + return sum; +} +const root: Tree = { value: 1, children: [], parent: null }; +root.children.push({ value: 2, children: [], parent: root }); +console.log(total(root)); +`; + +test("recursive record and union ids do not depend on the code above the type", async () => { + const [before, after] = await lower( + recursive, + `// A comment above the type.\n\ntype Unrelated = { name: string };\n\n${recursive}`, + ); + expect(before.records.some((record) => record.fields.some((f) => f.name === "children"))).toBe( + true, + ); + expect(names(after)).toEqual(names(before)); +}); + +test("recursive instantiations that print alike get distinct placeholders", async () => { + const [mod] = await lower(` +namespace A { + export class Item { + a = 1; + } +} +namespace B { + export class Item { + b = "b"; + } +} +type Chain = { item: T; next: Chain | null }; +const first: Chain = { item: new A.Item(), next: null }; +const second: Chain = { item: new B.Item(), next: null }; +first.next = { item: new A.Item(), next: null }; +second.next = { item: new B.Item(), next: null }; +console.log(first.next.item.a, second.next.item.b); +`); + const chains = mod.records.filter((record) => record.fields.some((f) => f.name === "next")); + expect(new Set(chains.map((record) => record.id)).size).toBe(chains.length); + expect(chains.length).toBeGreaterThanOrEqual(2); +}); + +test("a getter and a setter of one name keep their local classes apart", async () => { + const [mod] = await lower(` +class Box { + private v = 0; + get value(): number { + class Local { + n(): number { + return 1; + } + } + return new Local().n() + this.v; + } + set value(x: number) { + class Local { + n(): number { + return 2; + } + } + this.v = x * new Local().n(); + } +} +const box = new Box(); +box.value = 5; +console.log(box.value); +`); + const locals = mod.classes.filter((cls) => cls.name.includes("Local")); + expect(locals).toHaveLength(2); + expect(locals[0]!.name).not.toBe(locals[1]!.name); +}); + +test("names do not depend on the directory the program sits in", async () => { + // Each call lowers in its own temporary directory. + const [first] = await lower(recursive); + const [second] = await lower(recursive); + expect(names(second!)).toEqual(names(first!)); +}); diff --git a/packages/compiler/test/string-char-loop-emission.test.ts b/packages/compiler/test/string-char-loop-emission.test.ts new file mode 100644 index 000000000..6f5756ce8 --- /dev/null +++ b/packages/compiler/test/string-char-loop-emission.test.ts @@ -0,0 +1,71 @@ +import { execFileSync } from "node:child_process"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { expect, test } from "vitest"; +import { compile, deserializeModule } from "../src/index.js"; +import { emitLlvmModule } from "../src/backend/llvm/emitter.js"; + +test("character reads of ASCII strings in versioned loops read bytes", async () => { + const dir = await mkdtemp(join(tmpdir(), "scriptc-char-loops-")); + try { + const entry = join(dir, "main.ts"); + await writeFile( + entry, + ` +function spaces(s: string): number { + let n = 0; + for (let i = 0; i < s.length; i++) if (s[i] === " ") n++; + return n; +} +function letters(s: string): number { + let n = 0; + for (let i = 0; i < s.length; i++) { + const c = s.charAt(i); + if (c >= "a" && c <= "z") n++; + } + return n; +} +function chars(s: string): string[] { + const out: string[] = []; + for (let i = 0; i < s.length; i++) out.push(s.charAt(i)); + return out; +} +console.log(spaces("a b c"), letters("abC1z"), chars("xyz").join("-"), chars("é!").join("-")); +`, + ); + const outPath = join(dir, "main.ir.json"); + const lowered = await compile(entry, { outDir: dir, outPath, outputKind: "ir" }); + if (!lowered.ok) + throw new Error(lowered.diagnostics.map((d) => `${d.code}: ${d.message}`).join("\n")); + const ll = emitLlvmModule(deserializeModule(await readFile(outPath, "utf8"))); + const body = (name: string): string => + ll.match( + new RegExp(`define internal [^\\n]+ @sc_bf_${name}\\([^\\n]*\\) #0 \\{[\\s\\S]*?\\n\\}`), + )![0]; + // The fast copy follows the checked one. + const fast = (fn: string): string => fn.slice(fn.lastIndexOf("bytes.version.fast")); + + // `s[i] === " "` compares the byte; the checked copy keeps the helper. + const spaces = body("spaces"); + expect(fast(spaces)).toMatch(/load i8, ptr %\S+\n\s+%\S+ = uitofp i8/); + expect(fast(spaces)).not.toContain("@sc_str_char_code_at_int"); + expect(spaces).toContain("@sc_str_char_code_at_int"); + // A character local compared with one-unit literals holds its unit. + const letters = body("letters"); + expect(letters).not.toContain("@sc_str_cmp_u16"); + expect(fast(letters)).toMatch(/load i8, ptr %\S+\n\s+%\S+ = uitofp i8/); + // A character used as a string is its immortal table entry. + const chars = body("chars"); + expect(fast(chars)).toContain("@sc_ascii_chars"); + expect(fast(chars)).not.toContain("@sc_str_char_at_int"); + expect(chars).toContain("@sc_str_char_at_int"); + + const exe = join(dir, "main"); + const built = await compile(entry, { outputKind: "exe", outDir: dir, outPath: exe }); + if (!built.ok) throw new Error(JSON.stringify(built.diagnostics)); + expect(execFileSync(exe, { encoding: "utf8" })).toBe("2 3 x-y-z é-!\n"); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/4638-contract-program-lifetime-arrays.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/4638-contract-program-lifetime-arrays.ts.json new file mode 100644 index 000000000..a89ae97b8 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/4638-contract-program-lifetime-arrays.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/4638-contract-program-lifetime-arrays.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/4639-contract-program-lifetime-maps.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/4639-contract-program-lifetime-maps.ts.json new file mode 100644 index 000000000..5f7afb8e7 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/4639-contract-program-lifetime-maps.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/4639-contract-program-lifetime-maps.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/4814-integer-or-nan-indexes.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/4814-integer-or-nan-indexes.ts.json new file mode 100644 index 000000000..0a6abb5a5 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/4814-integer-or-nan-indexes.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/4814-integer-or-nan-indexes.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/4815-touint32-wide-magnitudes.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/4815-touint32-wide-magnitudes.ts.json new file mode 100644 index 000000000..80dcce24d --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/4815-touint32-wide-magnitudes.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/4815-touint32-wide-magnitudes.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6706-dh-groups.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6706-dh-groups.ts.json new file mode 100644 index 000000000..d8f5b48c3 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6706-dh-groups.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6706-dh-groups.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6707-dh-explicit-params.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6707-dh-explicit-params.ts.json new file mode 100644 index 000000000..4cb3c882c --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6707-dh-explicit-params.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6707-dh-explicit-params.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6708-dh-errors.js.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6708-dh-errors.js.json new file mode 100644 index 000000000..c252657a8 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6708-dh-errors.js.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6708-dh-errors.js" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6709-dh-generate.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6709-dh-generate.ts.json new file mode 100644 index 000000000..5c50c8ec1 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6709-dh-generate.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6709-dh-generate.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6710-dh-encodings.cjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6710-dh-encodings.cjs.json new file mode 100644 index 000000000..86abbb6ba --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6710-dh-encodings.cjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6710-dh-encodings.cjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6711-dh-handles.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6711-dh-handles.ts.json new file mode 100644 index 000000000..ae8daf9f1 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6711-dh-handles.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6711-dh-handles.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6712-dh-peer-keys.js.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6712-dh-peer-keys.js.json new file mode 100644 index 000000000..101260f54 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6712-dh-peer-keys.js.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6712-dh-peer-keys.js" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6822-jsx-classic-runtime/main.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6822-jsx-classic-runtime/main.ts.json new file mode 100644 index 000000000..9d97dc765 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6822-jsx-classic-runtime/main.ts.json @@ -0,0 +1,11 @@ +{ + "order": [ + "/tests/corpus/6822-jsx-classic-runtime/html.ts", + "/tests/corpus/6822-jsx-classic-runtime/list.jsx", + "/tests/corpus/6822-jsx-classic-runtime/page.tsx", + "/tests/corpus/6822-jsx-classic-runtime/factory.ts", + "/tests/corpus/6822-jsx-classic-runtime/pragma.tsx", + "/tests/corpus/6822-jsx-classic-runtime/main.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6824-jsx-automatic-runtime/main.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6824-jsx-automatic-runtime/main.ts.json new file mode 100644 index 000000000..95ba5cd15 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6824-jsx-automatic-runtime/main.ts.json @@ -0,0 +1,12 @@ +{ + "order": [ + "/tests/corpus/6824-jsx-automatic-runtime/runtime/jsx-runtime.ts", + "/tests/corpus/6824-jsx-automatic-runtime/alt/jsx-runtime.ts", + "/tests/corpus/6824-jsx-automatic-runtime/alt.tsx", + "/tests/corpus/6824-jsx-automatic-runtime/runtime/index.ts", + "/tests/corpus/6824-jsx-automatic-runtime/page.tsx", + "/tests/corpus/6824-jsx-automatic-runtime/render.ts", + "/tests/corpus/6824-jsx-automatic-runtime/main.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6825-jsx-automatic-development/main.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6825-jsx-automatic-development/main.ts.json new file mode 100644 index 000000000..649f0bdff --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6825-jsx-automatic-development/main.ts.json @@ -0,0 +1,8 @@ +{ + "order": [ + "/tests/corpus/6825-jsx-automatic-development/runtime/jsx-dev-runtime.ts", + "/tests/corpus/6825-jsx-automatic-development/view.tsx", + "/tests/corpus/6825-jsx-automatic-development/main.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6826-map-primitive-constructors.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6826-map-primitive-constructors.ts.json new file mode 100644 index 000000000..0bf7b0871 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6826-map-primitive-constructors.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6826-map-primitive-constructors.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6827-recursive-union-nested-literals.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6827-recursive-union-nested-literals.ts.json new file mode 100644 index 000000000..6e11aa685 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6827-recursive-union-nested-literals.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6827-recursive-union-nested-literals.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6828-recursive-union-object-walkers.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6828-recursive-union-object-walkers.ts.json new file mode 100644 index 000000000..65c965b9e --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6828-recursive-union-object-walkers.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6828-recursive-union-object-walkers.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6862-readline-chained-listeners.cjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6862-readline-chained-listeners.cjs.json new file mode 100644 index 000000000..5beb42eaf --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6862-readline-chained-listeners.cjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6862-readline-chained-listeners.cjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6865-number-parseint-default-radix.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6865-number-parseint-default-radix.ts.json new file mode 100644 index 000000000..225f2c462 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6865-number-parseint-default-radix.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6865-number-parseint-default-radix.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6866-number-parseint-untyped.js.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6866-number-parseint-untyped.js.json new file mode 100644 index 000000000..f000b3a36 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6866-number-parseint-untyped.js.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6866-number-parseint-untyped.js" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6867-string-match-optional-regexp.js.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6867-string-match-optional-regexp.js.json new file mode 100644 index 000000000..1d1105bab --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6867-string-match-optional-regexp.js.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6867-string-match-optional-regexp.js" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6868-buffer-from-untyped-array-buffer.cjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6868-buffer-from-untyped-array-buffer.cjs.json new file mode 100644 index 000000000..baa6e1935 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6868-buffer-from-untyped-array-buffer.cjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6868-buffer-from-untyped-array-buffer.cjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6869-atomics-untyped-arrays.cjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6869-atomics-untyped-arrays.cjs.json new file mode 100644 index 000000000..f91624eb9 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6869-atomics-untyped-arrays.cjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6869-atomics-untyped-arrays.cjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6870-error-constructor-values.js.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6870-error-constructor-values.js.json new file mode 100644 index 000000000..a2f0e02ea --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6870-error-constructor-values.js.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6870-error-constructor-values.js" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6871-worker-data-destructuring.cjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6871-worker-data-destructuring.cjs.json new file mode 100644 index 000000000..b610a5878 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6871-worker-data-destructuring.cjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6871-worker-data-destructuring.cjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6872-regex-start-filter.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6872-regex-start-filter.ts.json new file mode 100644 index 000000000..e2c97c71f --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6872-regex-start-filter.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6872-regex-start-filter.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6912-extend-factory-local-class.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6912-extend-factory-local-class.ts.json new file mode 100644 index 000000000..5fc7da1eb --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6912-extend-factory-local-class.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6912-extend-factory-local-class.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6913-builtin-constructor-shorthand.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6913-builtin-constructor-shorthand.ts.json new file mode 100644 index 000000000..bd7194022 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6913-builtin-constructor-shorthand.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6913-builtin-constructor-shorthand.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6914-dynamic-builtin-construct.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6914-dynamic-builtin-construct.ts.json new file mode 100644 index 000000000..9bc7d8342 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6914-dynamic-builtin-construct.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6914-dynamic-builtin-construct.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6915-dynamic-builtin-construct.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6915-dynamic-builtin-construct.mjs.json new file mode 100644 index 000000000..a817ad3d2 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6915-dynamic-builtin-construct.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6915-dynamic-builtin-construct.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6915-key-order-narrowed-throw.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6915-key-order-narrowed-throw.ts.json new file mode 100644 index 000000000..83f8cc5d5 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6915-key-order-narrowed-throw.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6915-key-order-narrowed-throw.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6916-index-record-spread-overrides.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6916-index-record-spread-overrides.ts.json new file mode 100644 index 000000000..db4bc557f --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6916-index-record-spread-overrides.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6916-index-record-spread-overrides.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6916-local-class-static-self-reference.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6916-local-class-static-self-reference.mjs.json new file mode 100644 index 000000000..aaefe846a --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6916-local-class-static-self-reference.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6916-local-class-static-self-reference.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6917-local-class-expression-self-reference.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6917-local-class-expression-self-reference.ts.json new file mode 100644 index 000000000..41d005bd0 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6917-local-class-expression-self-reference.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6917-local-class-expression-self-reference.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6918-local-class-expression-self-reference.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6918-local-class-expression-self-reference.mjs.json new file mode 100644 index 000000000..afed7a70d --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6918-local-class-expression-self-reference.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6918-local-class-expression-self-reference.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6919-local-class-inspect-name.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6919-local-class-inspect-name.mjs.json new file mode 100644 index 000000000..229c01bcd --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6919-local-class-inspect-name.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6919-local-class-inspect-name.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6921-local-subclass-override-dispatch.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6921-local-subclass-override-dispatch.ts.json new file mode 100644 index 000000000..1878554c1 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6921-local-subclass-override-dispatch.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6921-local-subclass-override-dispatch.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6922-local-subclass-override-dispatch.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6922-local-subclass-override-dispatch.mjs.json new file mode 100644 index 000000000..4da840cbc --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6922-local-subclass-override-dispatch.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6922-local-subclass-override-dispatch.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6926-dynamic-collection-seeds.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6926-dynamic-collection-seeds.mjs.json new file mode 100644 index 000000000..32edfc402 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6926-dynamic-collection-seeds.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6926-dynamic-collection-seeds.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6927-dynamic-collection-seeds.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6927-dynamic-collection-seeds.ts.json new file mode 100644 index 000000000..89c591dd7 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6927-dynamic-collection-seeds.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6927-dynamic-collection-seeds.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6996-typed-array-index-temps.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6996-typed-array-index-temps.ts.json new file mode 100644 index 000000000..b5f88af99 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6996-typed-array-index-temps.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6996-typed-array-index-temps.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6997-typed-array-invariant-index-terms.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6997-typed-array-invariant-index-terms.ts.json new file mode 100644 index 000000000..6d60d2635 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6997-typed-array-invariant-index-terms.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6997-typed-array-invariant-index-terms.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6998-typed-array-while-loop-versions.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6998-typed-array-while-loop-versions.ts.json new file mode 100644 index 000000000..f5cfba0cc --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6998-typed-array-while-loop-versions.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6998-typed-array-while-loop-versions.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6999-typed-array-callback-loops.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6999-typed-array-callback-loops.ts.json new file mode 100644 index 000000000..de7ab0a69 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/6999-typed-array-callback-loops.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/6999-typed-array-callback-loops.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7002-empty-array-contextual-slots/main.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7002-empty-array-contextual-slots/main.ts.json new file mode 100644 index 000000000..d22715215 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7002-empty-array-contextual-slots/main.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7002-empty-array-contextual-slots/main.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7005-dyn-constructor-instanceof/main.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7005-dyn-constructor-instanceof/main.ts.json new file mode 100644 index 000000000..313888b49 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7005-dyn-constructor-instanceof/main.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7005-dyn-constructor-instanceof/main.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7006-evolving-array-aliases.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7006-evolving-array-aliases.ts.json new file mode 100644 index 000000000..cb3d36498 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7006-evolving-array-aliases.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7006-evolving-array-aliases.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7007-filter-written-type-predicates.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7007-filter-written-type-predicates.ts.json new file mode 100644 index 000000000..d77ee1a57 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7007-filter-written-type-predicates.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7007-filter-written-type-predicates.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7008-js-unit-initialized-properties/main.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7008-js-unit-initialized-properties/main.ts.json new file mode 100644 index 000000000..85f5a6e12 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7008-js-unit-initialized-properties/main.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7008-js-unit-initialized-properties/main.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7009-finalization-registry-wasm-loader/main.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7009-finalization-registry-wasm-loader/main.ts.json new file mode 100644 index 000000000..89ee292b3 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7009-finalization-registry-wasm-loader/main.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7009-finalization-registry-wasm-loader/main.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7011-for-in-dictionary-deletes.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7011-for-in-dictionary-deletes.ts.json new file mode 100644 index 000000000..3b2b79c3b --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7011-for-in-dictionary-deletes.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7011-for-in-dictionary-deletes.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7014-js-never-array-literal-fields/main.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7014-js-never-array-literal-fields/main.ts.json new file mode 100644 index 000000000..a67c77476 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7014-js-never-array-literal-fields/main.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7014-js-never-array-literal-fields/main.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7020-conditional-spread-fields.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7020-conditional-spread-fields.ts.json new file mode 100644 index 000000000..f6c5594a1 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7020-conditional-spread-fields.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7020-conditional-spread-fields.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7021-promise-all-uniform-tuple.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7021-promise-all-uniform-tuple.ts.json new file mode 100644 index 000000000..c1e5f1ae4 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7021-promise-all-uniform-tuple.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7021-promise-all-uniform-tuple.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7022-promise-all-dynamic-arrays.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7022-promise-all-dynamic-arrays.ts.json new file mode 100644 index 000000000..c1856ac5a --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7022-promise-all-dynamic-arrays.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7022-promise-all-dynamic-arrays.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7023-union-object-patterns.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7023-union-object-patterns.ts.json new file mode 100644 index 000000000..bae130837 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7023-union-object-patterns.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7023-union-object-patterns.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7024-async-return-fresh-collections.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7024-async-return-fresh-collections.ts.json new file mode 100644 index 000000000..c4b9855ef --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7024-async-return-fresh-collections.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7024-async-return-fresh-collections.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7025-child-listener-chaining.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7025-child-listener-chaining.ts.json new file mode 100644 index 000000000..ed0e7b650 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7025-child-listener-chaining.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7025-child-listener-chaining.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7026-url-object-patterns.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7026-url-object-patterns.ts.json new file mode 100644 index 000000000..f050c4d1a --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7026-url-object-patterns.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7026-url-object-patterns.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7027-search-params-conditional-init.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7027-search-params-conditional-init.ts.json new file mode 100644 index 000000000..9b69861b1 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7027-search-params-conditional-init.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7027-search-params-conditional-init.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7028-non-empty-rest-tuples.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7028-non-empty-rest-tuples.ts.json new file mode 100644 index 000000000..a40ef1180 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7028-non-empty-rest-tuples.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7028-non-empty-rest-tuples.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7029-flatmap-union-results.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7029-flatmap-union-results.ts.json new file mode 100644 index 000000000..72d564d3b --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7029-flatmap-union-results.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7029-flatmap-union-results.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7030-spawn-sync-env.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7030-spawn-sync-env.ts.json new file mode 100644 index 000000000..f8afbe00b --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7030-spawn-sync-env.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7030-spawn-sync-env.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7033-any-fields-into-declared-records.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7033-any-fields-into-declared-records.ts.json new file mode 100644 index 000000000..57e76b621 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7033-any-fields-into-declared-records.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7033-any-fields-into-declared-records.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7034-optional-field-union-routes.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7034-optional-field-union-routes.ts.json new file mode 100644 index 000000000..a78b23cb1 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7034-optional-field-union-routes.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7034-optional-field-union-routes.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7036-child-env-path-lookup.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7036-child-env-path-lookup.ts.json new file mode 100644 index 000000000..171ab060a --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7036-child-env-path-lookup.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7036-child-env-path-lookup.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7040-es5-error-constructor.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7040-es5-error-constructor.mjs.json new file mode 100644 index 000000000..1a1a6951c --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7040-es5-error-constructor.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7040-es5-error-constructor.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7041-error-called-without-new.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7041-error-called-without-new.mjs.json new file mode 100644 index 000000000..f40c04116 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7041-error-called-without-new.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7041-error-called-without-new.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7042-string-method-names-on-objects.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7042-string-method-names-on-objects.mjs.json new file mode 100644 index 000000000..c867cd88c --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7042-string-method-names-on-objects.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7042-string-method-names-on-objects.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7043-date-set-time.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7043-date-set-time.mjs.json new file mode 100644 index 000000000..8b369c633 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7043-date-set-time.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7043-date-set-time.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7044-nested-empty-object-maps.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7044-nested-empty-object-maps.mjs.json new file mode 100644 index 000000000..ee3592ba6 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7044-nested-empty-object-maps.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7044-nested-empty-object-maps.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7045-instanceof-constructor-values.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7045-instanceof-constructor-values.mjs.json new file mode 100644 index 000000000..530aca0ad --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7045-instanceof-constructor-values.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7045-instanceof-constructor-values.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7046-parse-float-extra-arguments.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7046-parse-float-extra-arguments.mjs.json new file mode 100644 index 000000000..0f37ad2a2 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7046-parse-float-extra-arguments.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7046-parse-float-extra-arguments.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7047-dynamic-string-index.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7047-dynamic-string-index.mjs.json new file mode 100644 index 000000000..7cd38cfb9 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7047-dynamic-string-index.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7047-dynamic-string-index.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7048-unary-number-coercions.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7048-unary-number-coercions.mjs.json new file mode 100644 index 000000000..10c99f165 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7048-unary-number-coercions.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7048-unary-number-coercions.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7049-member-assignment-values.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7049-member-assignment-values.mjs.json new file mode 100644 index 000000000..5dc066127 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7049-member-assignment-values.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7049-member-assignment-values.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7050-date-subclass.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7050-date-subclass.mjs.json new file mode 100644 index 000000000..fc73bb479 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7050-date-subclass.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7050-date-subclass.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7051-date-subclass-typed.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7051-date-subclass-typed.ts.json new file mode 100644 index 000000000..f37cd9763 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7051-date-subclass-typed.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7051-date-subclass-typed.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7052-date-subclass-dynamic.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7052-date-subclass-dynamic.mjs.json new file mode 100644 index 000000000..7077aa5bb --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7052-date-subclass-dynamic.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7052-date-subclass-dynamic.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7053-private-fields-untyped-receivers.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7053-private-fields-untyped-receivers.mjs.json new file mode 100644 index 000000000..d7d8ba2e1 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7053-private-fields-untyped-receivers.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7053-private-fields-untyped-receivers.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7054-let-bindings-with-null-writes.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7054-let-bindings-with-null-writes.mjs.json new file mode 100644 index 000000000..25dcd3680 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7054-let-bindings-with-null-writes.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7054-let-bindings-with-null-writes.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7055-cipher-streams.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7055-cipher-streams.ts.json new file mode 100644 index 000000000..989c7f452 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7055-cipher-streams.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7055-cipher-streams.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7056-cipher-stream-errors.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7056-cipher-stream-errors.ts.json new file mode 100644 index 000000000..16bd2586c --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7056-cipher-stream-errors.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7056-cipher-stream-errors.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7057-cipher-streams.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7057-cipher-streams.mjs.json new file mode 100644 index 000000000..1304933ae --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7057-cipher-streams.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7057-cipher-streams.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7058-pipeline-function-stages.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7058-pipeline-function-stages.mjs.json new file mode 100644 index 000000000..3b9fd5a0f --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7058-pipeline-function-stages.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7058-pipeline-function-stages.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7059-transform-backpressure.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7059-transform-backpressure.ts.json new file mode 100644 index 000000000..311882a39 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7059-transform-backpressure.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7059-transform-backpressure.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7080-crypto-ed25519.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7080-crypto-ed25519.mjs.json new file mode 100644 index 000000000..035d9d765 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7080-crypto-ed25519.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7080-crypto-ed25519.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7081-webcrypto-ed25519.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7081-webcrypto-ed25519.mjs.json new file mode 100644 index 000000000..bbd2d1ebc --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7081-webcrypto-ed25519.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7081-webcrypto-ed25519.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7082-crypto-key-objects.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7082-crypto-key-objects.ts.json new file mode 100644 index 000000000..c2e50cc97 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7082-crypto-key-objects.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7082-crypto-key-objects.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7083-crypto-sign-verify.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7083-crypto-sign-verify.ts.json new file mode 100644 index 000000000..385c9347c --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7083-crypto-sign-verify.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7083-crypto-sign-verify.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7084-crypto-key-pairs.cjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7084-crypto-key-pairs.cjs.json new file mode 100644 index 000000000..e1ac90536 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7084-crypto-key-pairs.cjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7084-crypto-key-pairs.cjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7085-webcrypto-ecdsa-rsa.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7085-webcrypto-ecdsa-rsa.ts.json new file mode 100644 index 000000000..3fc5406e8 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7085-webcrypto-ecdsa-rsa.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7085-webcrypto-ecdsa-rsa.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7086-webcrypto-ecdsa-rsa-errors.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7086-webcrypto-ecdsa-rsa-errors.mjs.json new file mode 100644 index 000000000..ef44f9180 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7086-webcrypto-ecdsa-rsa-errors.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7086-webcrypto-ecdsa-rsa-errors.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7087-tls-socket-wrap.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7087-tls-socket-wrap.ts.json new file mode 100644 index 000000000..37009eaea --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7087-tls-socket-wrap.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7087-tls-socket-wrap.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7088-tls-socket-connect-tunnel.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7088-tls-socket-connect-tunnel.ts.json new file mode 100644 index 000000000..71947ecdd --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7088-tls-socket-connect-tunnel.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7088-tls-socket-connect-tunnel.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7089-http-host-header-tunnels.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7089-http-host-header-tunnels.ts.json new file mode 100644 index 000000000..9b3002173 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7089-http-host-header-tunnels.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7089-http-host-header-tunnels.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7094-tls-socket-failed-handshakes.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7094-tls-socket-failed-handshakes.ts.json new file mode 100644 index 000000000..8fa524155 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7094-tls-socket-failed-handshakes.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7094-tls-socket-failed-handshakes.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7106-async-prefix-enter-with.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7106-async-prefix-enter-with.ts.json new file mode 100644 index 000000000..2945faca5 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7106-async-prefix-enter-with.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7106-async-prefix-enter-with.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7107-for-await-context.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7107-for-await-context.ts.json new file mode 100644 index 000000000..331f64937 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7107-for-await-context.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7107-for-await-context.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7108-generator-step-context.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7108-generator-step-context.ts.json new file mode 100644 index 000000000..e7c5876ac --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7108-generator-step-context.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7108-generator-step-context.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7109-uninitialized-let-assignment-expressions.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7109-uninitialized-let-assignment-expressions.ts.json new file mode 100644 index 000000000..47973fee5 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7109-uninitialized-let-assignment-expressions.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7109-uninitialized-let-assignment-expressions.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7120-webcrypto-random-uuid.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7120-webcrypto-random-uuid.ts.json new file mode 100644 index 000000000..c70fdfa63 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7120-webcrypto-random-uuid.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7120-webcrypto-random-uuid.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7121-webcrypto-crypto-object.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7121-webcrypto-crypto-object.mjs.json new file mode 100644 index 000000000..b152699ba --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7121-webcrypto-crypto-object.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7121-webcrypto-crypto-object.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7122-webcrypto-node-crypto.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7122-webcrypto-node-crypto.ts.json new file mode 100644 index 000000000..02451a516 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7122-webcrypto-node-crypto.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7122-webcrypto-node-crypto.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7123-webcrypto-node-crypto.cjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7123-webcrypto-node-crypto.cjs.json new file mode 100644 index 000000000..821fb378d --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7123-webcrypto-node-crypto.cjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7123-webcrypto-node-crypto.cjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7124-webcrypto-secret-keys.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7124-webcrypto-secret-keys.ts.json new file mode 100644 index 000000000..8fc0dab2a --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7124-webcrypto-secret-keys.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7124-webcrypto-secret-keys.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7125-webcrypto-key-errors.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7125-webcrypto-key-errors.mjs.json new file mode 100644 index 000000000..942de8c10 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7125-webcrypto-key-errors.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7125-webcrypto-key-errors.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7126-webcrypto-aes.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7126-webcrypto-aes.ts.json new file mode 100644 index 000000000..f113a3ca9 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7126-webcrypto-aes.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7126-webcrypto-aes.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7127-webcrypto-aes-errors.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7127-webcrypto-aes-errors.mjs.json new file mode 100644 index 000000000..3ec3d26f2 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7127-webcrypto-aes-errors.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7127-webcrypto-aes-errors.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7128-webcrypto-derive.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7128-webcrypto-derive.ts.json new file mode 100644 index 000000000..b613fbce6 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7128-webcrypto-derive.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7128-webcrypto-derive.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7129-webcrypto-derive-errors.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7129-webcrypto-derive-errors.mjs.json new file mode 100644 index 000000000..11fc8c721 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7129-webcrypto-derive-errors.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7129-webcrypto-derive-errors.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7130-typed-message-listeners.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7130-typed-message-listeners.ts.json new file mode 100644 index 000000000..f02244324 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7130-typed-message-listeners.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7130-typed-message-listeners.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7130-webcrypto-wrap-key.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7130-webcrypto-wrap-key.ts.json new file mode 100644 index 000000000..fa5b5529f --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7130-webcrypto-wrap-key.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7130-webcrypto-wrap-key.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7131-typed-worker-messages.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7131-typed-worker-messages.ts.json new file mode 100644 index 000000000..89a6c125a --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7131-typed-worker-messages.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7131-typed-worker-messages.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7131-webcrypto-wrap-key-errors.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7131-webcrypto-wrap-key-errors.mjs.json new file mode 100644 index 000000000..275ffa418 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7131-webcrypto-wrap-key-errors.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7131-webcrypto-wrap-key-errors.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7132-jose-pbes2/main.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7132-jose-pbes2/main.mjs.json new file mode 100644 index 000000000..9fbd24555 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7132-jose-pbes2/main.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7132-jose-pbes2/main.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7139-message-typed-records.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7139-message-typed-records.ts.json new file mode 100644 index 000000000..5e50dcd13 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7139-message-typed-records.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7139-message-typed-records.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7141-comoving-loop-counters.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7141-comoving-loop-counters.ts.json new file mode 100644 index 000000000..392c9f10d --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7141-comoving-loop-counters.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7141-comoving-loop-counters.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7142-array-read-filled-prefix.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7142-array-read-filled-prefix.ts.json new file mode 100644 index 000000000..188cd12d4 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7142-array-read-filled-prefix.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7142-array-read-filled-prefix.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7143-optional-read-integer-index.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7143-optional-read-integer-index.ts.json new file mode 100644 index 000000000..ae0d1f610 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7143-optional-read-integer-index.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7143-optional-read-integer-index.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7150-cipher-legacy-modes.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7150-cipher-legacy-modes.ts.json new file mode 100644 index 000000000..c0e5f9812 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7150-cipher-legacy-modes.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7150-cipher-legacy-modes.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7151-cipher-legacy-errors.cjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7151-cipher-legacy-errors.cjs.json new file mode 100644 index 000000000..1f37c6b64 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7151-cipher-legacy-errors.cjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7151-cipher-legacy-errors.cjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7152-crypto-prime.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7152-crypto-prime.ts.json new file mode 100644 index 000000000..722ebaacb --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7152-crypto-prime.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7152-crypto-prime.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7153-crypto-prime-errors.cjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7153-crypto-prime-errors.cjs.json new file mode 100644 index 000000000..9d121895a --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7153-crypto-prime-errors.cjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7153-crypto-prime-errors.cjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7180-generic-local-binding-early-uses.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7180-generic-local-binding-early-uses.ts.json new file mode 100644 index 000000000..5fb971826 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7180-generic-local-binding-early-uses.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7180-generic-local-binding-early-uses.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7181-generic-module-binding-tdz.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7181-generic-module-binding-tdz.ts.json new file mode 100644 index 000000000..a67424e94 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7181-generic-module-binding-tdz.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7181-generic-module-binding-tdz.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7182-generic-binding-direct-calls.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7182-generic-binding-direct-calls.ts.json new file mode 100644 index 000000000..b641615f8 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7182-generic-binding-direct-calls.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7182-generic-binding-direct-calls.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7183-local-class-heritage-effects.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7183-local-class-heritage-effects.ts.json new file mode 100644 index 000000000..8f0ebb3c2 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7183-local-class-heritage-effects.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7183-local-class-heritage-effects.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7184-reduce-runtime-accumulator.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7184-reduce-runtime-accumulator.ts.json new file mode 100644 index 000000000..b93eb61b6 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7184-reduce-runtime-accumulator.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7184-reduce-runtime-accumulator.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7185-array-callback-arguments-length.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7185-array-callback-arguments-length.ts.json new file mode 100644 index 000000000..2514bcaa8 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7185-array-callback-arguments-length.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7185-array-callback-arguments-length.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7240-objectmode-streams.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7240-objectmode-streams.ts.json new file mode 100644 index 000000000..0b212fb07 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7240-objectmode-streams.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7240-objectmode-streams.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7241-objectmode-streams.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7241-objectmode-streams.mjs.json new file mode 100644 index 000000000..22dc5abc4 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7241-objectmode-streams.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7241-objectmode-streams.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7242-objectmode-dynamic.cjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7242-objectmode-dynamic.cjs.json new file mode 100644 index 000000000..1b932b82b --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7242-objectmode-dynamic.cjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7242-objectmode-dynamic.cjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7243-for-await-close-order.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7243-for-await-close-order.mjs.json new file mode 100644 index 000000000..ec479cf59 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7243-for-await-close-order.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7243-for-await-close-order.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7244-objectmode-subclasses.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7244-objectmode-subclasses.ts.json new file mode 100644 index 000000000..827bba4c0 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7244-objectmode-subclasses.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7244-objectmode-subclasses.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7245-writable-callback-order.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7245-writable-callback-order.mjs.json new file mode 100644 index 000000000..9485562b3 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7245-writable-callback-order.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7245-writable-callback-order.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7246-stream-construct.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7246-stream-construct.ts.json new file mode 100644 index 000000000..f1dcb625f --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7246-stream-construct.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7246-stream-construct.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7247-stream-construct.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7247-stream-construct.mjs.json new file mode 100644 index 000000000..00c6c7f0c --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7247-stream-construct.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7247-stream-construct.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7248-stream-writev.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7248-stream-writev.ts.json new file mode 100644 index 000000000..0faf76b0f --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7248-stream-writev.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7248-stream-writev.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7249-buffer-index-of-candidates.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7249-buffer-index-of-candidates.ts.json new file mode 100644 index 000000000..f5299cb9a --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7249-buffer-index-of-candidates.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7249-buffer-index-of-candidates.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7249-stream-writev.cjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7249-stream-writev.cjs.json new file mode 100644 index 000000000..5374e215e --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7249-stream-writev.cjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7249-stream-writev.cjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7250-stream-decode-strings.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7250-stream-decode-strings.ts.json new file mode 100644 index 000000000..67d2b759b --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7250-stream-decode-strings.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7250-stream-decode-strings.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7251-stream-write-encodings.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7251-stream-write-encodings.mjs.json new file mode 100644 index 000000000..d4c01fab9 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7251-stream-write-encodings.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7251-stream-write-encodings.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7252-duplex-from-generator.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7252-duplex-from-generator.ts.json new file mode 100644 index 000000000..d29eed123 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7252-duplex-from-generator.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7252-duplex-from-generator.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7253-duplex-from.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7253-duplex-from.mjs.json new file mode 100644 index 000000000..e12ce5a52 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7253-duplex-from.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7253-duplex-from.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7254-compose-functions.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7254-compose-functions.ts.json new file mode 100644 index 000000000..07e468aa2 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7254-compose-functions.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7254-compose-functions.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7255-compose-stages.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7255-compose-stages.mjs.json new file mode 100644 index 000000000..036d9836e --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7255-compose-stages.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7255-compose-stages.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7256-readable-compose.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7256-readable-compose.mjs.json new file mode 100644 index 000000000..0b5993d32 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7256-readable-compose.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7256-readable-compose.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7257-pipeline-generator-destination.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7257-pipeline-generator-destination.mjs.json new file mode 100644 index 000000000..79354d9ce --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7257-pipeline-generator-destination.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7257-pipeline-generator-destination.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7258-pipeline-generator-destination.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7258-pipeline-generator-destination.ts.json new file mode 100644 index 000000000..313c9f19e --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7258-pipeline-generator-destination.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7258-pipeline-generator-destination.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7259-promises-pipeline-stage-options.cjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7259-promises-pipeline-stage-options.cjs.json new file mode 100644 index 000000000..6fc082ea1 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7259-promises-pipeline-stage-options.cjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7259-promises-pipeline-stage-options.cjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7261-acyclic-result-builders.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7261-acyclic-result-builders.ts.json new file mode 100644 index 000000000..4f4afd821 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7261-acyclic-result-builders.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7261-acyclic-result-builders.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7280-named-reads-hole-receivers.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7280-named-reads-hole-receivers.ts.json new file mode 100644 index 000000000..febb008f7 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7280-named-reads-hole-receivers.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7280-named-reads-hole-receivers.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7300-callback-captured-scalars.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7300-callback-captured-scalars.ts.json new file mode 100644 index 000000000..dc1158934 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7300-callback-captured-scalars.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7300-callback-captured-scalars.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7301-running-extrema-branches.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7301-running-extrema-branches.ts.json new file mode 100644 index 000000000..6dcb4b57d --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7301-running-extrema-branches.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7301-running-extrema-branches.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7302-string-scan-loop-versions.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7302-string-scan-loop-versions.ts.json new file mode 100644 index 000000000..feda0ecf7 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7302-string-scan-loop-versions.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7302-string-scan-loop-versions.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7303-string-char-loop-versions.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7303-string-char-loop-versions.ts.json new file mode 100644 index 000000000..58242e583 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7303-string-char-loop-versions.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7303-string-char-loop-versions.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7320-array-dense-loop-invariant-limits.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7320-array-dense-loop-invariant-limits.ts.json new file mode 100644 index 000000000..785bf9d82 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7320-array-dense-loop-invariant-limits.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7320-array-dense-loop-invariant-limits.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7321-speculative-loop-bail-sites.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7321-speculative-loop-bail-sites.ts.json new file mode 100644 index 000000000..113eeedb7 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7321-speculative-loop-bail-sites.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7321-speculative-loop-bail-sites.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7322-union-scalar-equality.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7322-union-scalar-equality.ts.json new file mode 100644 index 000000000..73257a3f4 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7322-union-scalar-equality.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7322-union-scalar-equality.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7323-loop-bound-parameter-versions.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7323-loop-bound-parameter-versions.ts.json new file mode 100644 index 000000000..0a79c8cdb --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7323-loop-bound-parameter-versions.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7323-loop-bound-parameter-versions.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7324-loop-bound-parameter-window-sums.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7324-loop-bound-parameter-window-sums.ts.json new file mode 100644 index 000000000..aedd853fb --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7324-loop-bound-parameter-window-sums.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7324-loop-bound-parameter-window-sums.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7360-worker-typed-records.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7360-worker-typed-records.ts.json new file mode 100644 index 000000000..4925143ad --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7360-worker-typed-records.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7360-worker-typed-records.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7361-message-listeners-share-value.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7361-message-listeners-share-value.ts.json new file mode 100644 index 000000000..f6a78ee9a --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7361-message-listeners-share-value.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7361-message-listeners-share-value.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7362-globalthis-intersection-singleton.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7362-globalthis-intersection-singleton.ts.json new file mode 100644 index 000000000..74a21dfc5 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7362-globalthis-intersection-singleton.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7362-globalthis-intersection-singleton.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7363-json-stringify-live-capsules.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7363-json-stringify-live-capsules.ts.json new file mode 100644 index 000000000..580e84ff0 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7363-json-stringify-live-capsules.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7363-json-stringify-live-capsules.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7380-iterable-values.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7380-iterable-values.ts.json new file mode 100644 index 000000000..cf42c1888 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7380-iterable-values.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7380-iterable-values.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7381-iterable-forof-semantics.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7381-iterable-forof-semantics.ts.json new file mode 100644 index 000000000..824dfe11c --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7381-iterable-forof-semantics.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7381-iterable-forof-semantics.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7382-iterable-generic-repository.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7382-iterable-generic-repository.ts.json new file mode 100644 index 000000000..7ac2b807f --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7382-iterable-generic-repository.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7382-iterable-generic-repository.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7383-iterable-union-sources.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7383-iterable-union-sources.ts.json new file mode 100644 index 000000000..ea8476397 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7383-iterable-union-sources.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7383-iterable-union-sources.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7400-record-keyof-union-read.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7400-record-keyof-union-read.ts.json new file mode 100644 index 000000000..4f2a4c712 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7400-record-keyof-union-read.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7400-record-keyof-union-read.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7401-any-spread-into-typed-literal.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7401-any-spread-into-typed-literal.ts.json new file mode 100644 index 000000000..3e3749b3f --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7401-any-spread-into-typed-literal.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7401-any-spread-into-typed-literal.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7401-program-lifetime-array-teardown.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7401-program-lifetime-array-teardown.ts.json new file mode 100644 index 000000000..4341cdbdc --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7401-program-lifetime-array-teardown.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7401-program-lifetime-array-teardown.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7420-for-await-close.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7420-for-await-close.ts.json new file mode 100644 index 000000000..6e48bbc1c --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7420-for-await-close.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7420-for-await-close.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7421-for-await-close.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7421-for-await-close.mjs.json new file mode 100644 index 000000000..dea911d1b --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7421-for-await-close.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7421-for-await-close.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7422-for-await-untyped-streams.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7422-for-await-untyped-streams.mjs.json new file mode 100644 index 000000000..c2677d0b9 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7422-for-await-untyped-streams.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7422-for-await-untyped-streams.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7423-stream-untyped-bindings.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7423-stream-untyped-bindings.mjs.json new file mode 100644 index 000000000..180721bd6 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7423-stream-untyped-bindings.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7423-stream-untyped-bindings.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7424-duplex-from-streams.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7424-duplex-from-streams.mjs.json new file mode 100644 index 000000000..a3801c775 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7424-duplex-from-streams.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7424-duplex-from-streams.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7425-duplex-from-streams.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7425-duplex-from-streams.ts.json new file mode 100644 index 000000000..069ae4ef4 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7425-duplex-from-streams.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7425-duplex-from-streams.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7426-duplex-from-promise.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7426-duplex-from-promise.mjs.json new file mode 100644 index 000000000..e44b3f001 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7426-duplex-from-promise.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7426-duplex-from-promise.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7427-duplex-from-async-function.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7427-duplex-from-async-function.mjs.json new file mode 100644 index 000000000..22d092c60 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7427-duplex-from-async-function.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7427-duplex-from-async-function.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7428-web-stream-sources.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7428-web-stream-sources.mjs.json new file mode 100644 index 000000000..e17735658 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7428-web-stream-sources.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7428-web-stream-sources.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7429-web-stream-sources.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7429-web-stream-sources.ts.json new file mode 100644 index 000000000..8707c2f2b --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7429-web-stream-sources.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7429-web-stream-sources.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7430-readable-from-web.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7430-readable-from-web.mjs.json new file mode 100644 index 000000000..3e26c3ba0 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7430-readable-from-web.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7430-readable-from-web.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7431-readable-from-web.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7431-readable-from-web.ts.json new file mode 100644 index 000000000..6461c53af --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7431-readable-from-web.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7431-readable-from-web.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7432-readable-push-views.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7432-readable-push-views.mjs.json new file mode 100644 index 000000000..ffde7918d --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7432-readable-push-views.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7432-readable-push-views.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7433-readable-operator-signal.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7433-readable-operator-signal.mjs.json new file mode 100644 index 000000000..5de5d9839 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7433-readable-operator-signal.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7433-readable-operator-signal.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7434-readable-operator-values.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7434-readable-operator-values.ts.json new file mode 100644 index 000000000..c374d9f03 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7434-readable-operator-values.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7434-readable-operator-values.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7435-readable-flatmap-iterables.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7435-readable-flatmap-iterables.mjs.json new file mode 100644 index 000000000..0c3697807 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7435-readable-flatmap-iterables.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7435-readable-flatmap-iterables.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7436-readable-read-any-value.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7436-readable-read-any-value.mjs.json new file mode 100644 index 000000000..6c2f63e17 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7436-readable-read-any-value.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7436-readable-read-any-value.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7437-duplex-from-signal.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7437-duplex-from-signal.mjs.json new file mode 100644 index 000000000..3b0699407 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7437-duplex-from-signal.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7437-duplex-from-signal.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7438-duplex-from-signal.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7438-duplex-from-signal.ts.json new file mode 100644 index 000000000..0702ed0da --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7438-duplex-from-signal.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7438-duplex-from-signal.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7439-readable-read-string-chunks.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7439-readable-read-string-chunks.ts.json new file mode 100644 index 000000000..e3dab7078 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7439-readable-read-string-chunks.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7439-readable-read-string-chunks.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7440-fromentries-aliased-entries.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7440-fromentries-aliased-entries.ts.json new file mode 100644 index 000000000..108193bac --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7440-fromentries-aliased-entries.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7440-fromentries-aliased-entries.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7480-class-call-without-new.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7480-class-call-without-new.ts.json new file mode 100644 index 000000000..8e5ed83bc --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7480-class-call-without-new.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7480-class-call-without-new.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7481-class-call-without-new.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7481-class-call-without-new.mjs.json new file mode 100644 index 000000000..7f55a233d --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/7481-class-call-without-new.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/7481-class-call-without-new.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/class-quoted-accessor-keys.mjs.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/class-quoted-accessor-keys.mjs.json new file mode 100644 index 000000000..234634ebd --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/class-quoted-accessor-keys.mjs.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/class-quoted-accessor-keys.mjs" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/arguments-length-self-call.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/arguments-length-self-call.ts.json new file mode 100644 index 000000000..8ed5027e5 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/arguments-length-self-call.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/diagnostics/arguments-length-self-call.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/class-call-shadowed-static.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/class-call-shadowed-static.ts.json new file mode 100644 index 000000000..6c87e5f66 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/class-call-shadowed-static.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/diagnostics/class-call-shadowed-static.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/filter-narrow.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/filter-narrow.ts.json deleted file mode 100644 index 40d5e462a..000000000 --- a/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/filter-narrow.ts.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "order": [ - "/tests/diagnostics/filter-narrow.ts" - ], - "diags": [] -} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/fromentries-aliased-entries.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/fromentries-aliased-entries.ts.json deleted file mode 100644 index 7388f2b71..000000000 --- a/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/fromentries-aliased-entries.ts.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "order": [ - "/tests/diagnostics/fromentries-aliased-entries.ts" - ], - "diags": [] -} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/iterable-sources.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/iterable-sources.ts.json new file mode 100644 index 000000000..1b47e8dd2 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/iterable-sources.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/diagnostics/iterable-sources.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/jsx-factory-mismatch/main.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/jsx-factory-mismatch/main.ts.json new file mode 100644 index 000000000..9552906dd --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/jsx-factory-mismatch/main.ts.json @@ -0,0 +1,17 @@ +{ + "order": [ + "/tests/diagnostics/jsx-factory-mismatch/view.tsx", + "/tests/diagnostics/jsx-factory-mismatch/main.ts" + ], + "diags": [ + { + "code": "SC0001", + "message": "Argument of type 'number' is not assignable to parameter of type 'string'. (in the call this JSX lowers to)", + "loc": { + "file": "/tests/diagnostics/jsx-factory-mismatch/view.tsx", + "start": 337, + "end": 342 + } + } + ] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/jsx-preserve/main.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/jsx-preserve/main.ts.json new file mode 100644 index 000000000..eb5e492f4 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/jsx-preserve/main.ts.json @@ -0,0 +1,18 @@ +{ + "order": [ + "/tests/diagnostics/jsx-preserve/view.tsx", + "/tests/diagnostics/jsx-preserve/main.ts" + ], + "diags": [ + { + "code": "SC1090", + "message": "JSX with \"jsx\": \"preserve\" is not supported: that setting keeps JSX in the output instead of lowering it to calls", + "loc": { + "file": "/tests/diagnostics/jsx-preserve/view.tsx", + "start": 158, + "end": 176 + }, + "hint": "set \"jsx\" to \"react\", \"react-jsx\" or \"react-jsxdev\" in the project tsconfig" + } + ] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/jsx-type-errors/main.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/jsx-type-errors/main.ts.json new file mode 100644 index 000000000..62a162ee2 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/jsx-type-errors/main.ts.json @@ -0,0 +1,26 @@ +{ + "order": [ + "/tests/diagnostics/jsx-type-errors/view.tsx", + "/tests/diagnostics/jsx-type-errors/main.ts" + ], + "diags": [ + { + "code": "SC0001", + "message": "Type 'number' is not assignable to type 'string'.", + "loc": { + "file": "/tests/diagnostics/jsx-type-errors/view.tsx", + "start": 488, + "end": 495 + } + }, + { + "code": "SC0001", + "message": "Type 'string' is not assignable to type 'number'.", + "loc": { + "file": "/tests/diagnostics/jsx-type-errors/view.tsx", + "start": 520, + "end": 527 + } + } + ] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/retired-engine-1123-any-conditional-spread.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/retired-engine-1123-any-conditional-spread.ts.json deleted file mode 100644 index 057d24d55..000000000 --- a/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/retired-engine-1123-any-conditional-spread.ts.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "order": [ - "/tests/diagnostics/retired-engine-1123-any-conditional-spread.ts" - ], - "diags": [] -} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/stream-byte-mode-chunk-fences.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/stream-byte-mode-chunk-fences.ts.json new file mode 100644 index 000000000..8a02db2be --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/stream-byte-mode-chunk-fences.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/diagnostics/stream-byte-mode-chunk-fences.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/tls-socket-fences.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/tls-socket-fences.ts.json new file mode 100644 index 000000000..409766067 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/tls-socket-fences.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/diagnostics/tls-socket-fences.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/node-types/dh.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/node-types/dh.ts.json new file mode 100644 index 000000000..db078292a --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/node-types/dh.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/fixtures/node-types/dh.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/node-types/keys.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/node-types/keys.ts.json new file mode 100644 index 000000000..b0b79568d --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/node-types/keys.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/fixtures/node-types/keys.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/node-types/tls-socket-wrap.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/node-types/tls-socket-wrap.ts.json new file mode 100644 index 000000000..68346a115 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/node-types/tls-socket-wrap.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/fixtures/node-types/tls-socket-wrap.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/node-types/webcrypto-ecdsa.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/node-types/webcrypto-ecdsa.ts.json new file mode 100644 index 000000000..2c4a3b15b --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/node-types/webcrypto-ecdsa.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/fixtures/node-types/webcrypto-ecdsa.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/node-types/webcrypto-keys.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/node-types/webcrypto-keys.ts.json new file mode 100644 index 000000000..19f14ed02 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/node-types/webcrypto-keys.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/fixtures/node-types/webcrypto-keys.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/npm/cases/chalk5-builder/main.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/npm/cases/chalk5-builder/main.ts.json new file mode 100644 index 000000000..8f7268daf --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/npm/cases/chalk5-builder/main.ts.json @@ -0,0 +1,7 @@ +{ + "order": [ + "/packages/compiler/shims/chalk/v5.ts", + "/tests/fixtures/npm/cases/chalk5-builder/main.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/npm/cases/chalk5/main.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/npm/cases/chalk5/main.ts.json index 065c96347..8365d4db9 100644 --- a/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/npm/cases/chalk5/main.ts.json +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/npm/cases/chalk5/main.ts.json @@ -1,5 +1,6 @@ { "order": [ + "/packages/compiler/shims/chalk/v5.ts", "/tests/fixtures/npm/cases/chalk5/main.ts" ], "diags": [] diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/npm/cases/hot-shots-buffered/main.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/npm/cases/hot-shots-buffered/main.ts.json new file mode 100644 index 000000000..a48e1af78 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/npm/cases/hot-shots-buffered/main.ts.json @@ -0,0 +1,8 @@ +{ + "order": [ + "/packages/compiler/shims/hot-shots/client.ts", + "/packages/compiler/shims/hot-shots/v8.ts", + "/tests/fixtures/npm/cases/hot-shots-buffered/main.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/npm/cases/hot-shots-send-error/main.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/npm/cases/hot-shots-send-error/main.ts.json new file mode 100644 index 000000000..716cfe02f --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/npm/cases/hot-shots-send-error/main.ts.json @@ -0,0 +1,8 @@ +{ + "order": [ + "/packages/compiler/shims/hot-shots/client.ts", + "/packages/compiler/shims/hot-shots/v8.ts", + "/tests/fixtures/npm/cases/hot-shots-send-error/main.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/npm/cases/hot-shots-tcp/main.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/npm/cases/hot-shots-tcp/main.ts.json new file mode 100644 index 000000000..f131361e8 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/npm/cases/hot-shots-tcp/main.ts.json @@ -0,0 +1,8 @@ +{ + "order": [ + "/packages/compiler/shims/hot-shots/client.ts", + "/packages/compiler/shims/hot-shots/v8.ts", + "/tests/fixtures/npm/cases/hot-shots-tcp/main.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/npm/cases/hot-shots-udp/main.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/npm/cases/hot-shots-udp/main.ts.json index 54baff890..a3014fb9f 100644 --- a/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/npm/cases/hot-shots-udp/main.ts.json +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/npm/cases/hot-shots-udp/main.ts.json @@ -1,5 +1,7 @@ { "order": [ + "/packages/compiler/shims/hot-shots/client.ts", + "/packages/compiler/shims/hot-shots/v8.ts", "/tests/fixtures/npm/cases/hot-shots-udp/main.ts" ], "diags": [] diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/npm/cases/js-own-tostring/main.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/npm/cases/js-own-tostring/main.ts.json new file mode 100644 index 000000000..eacdfc1d4 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/npm/cases/js-own-tostring/main.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/fixtures/npm/cases/js-own-tostring/main.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/npm/cases/zod3-infer/main.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/npm/cases/zod3-infer/main.ts.json new file mode 100644 index 000000000..80cbb3523 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/npm/cases/zod3-infer/main.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/fixtures/npm/cases/zod3-infer/main.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/npm/cases/zod3/main.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/npm/cases/zod3/main.ts.json new file mode 100644 index 000000000..c9ff338fa --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/npm/cases/zod3/main.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/fixtures/npm/cases/zod3/main.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/facade.test.ts b/packages/compiler/test/ts7/facade.test.ts index 94bab8b31..8e03400a2 100644 --- a/packages/compiler/test/ts7/facade.test.ts +++ b/packages/compiler/test/ts7/facade.test.ts @@ -835,6 +835,37 @@ export function f(input: number): number { expect(panics).toBe(warmPanics); }); +test("a batch method the server answers as unknown is asked once, then node by node", () => { + const w = buildTwoWorlds(RICH_TS, host); + worlds.push(w); + const sf = w.p7.getSourceFile(w.files[0]!)!; + const raw = w.p7.project.checker; + const requests: Record = {}; + // A server without the batch methods, as tsgo is. + const older = new Proxy(raw, { + get(target, prop, receiver) { + const value = Reflect.get(target, prop, receiver); + if (prop === "getContextualTypes" || prop === "getResolvedSignatures") { + return () => { + requests[prop] = (requests[prop] ?? 0) + 1; + throw new Error(`unknown API method "${prop}"`); + }; + } + return typeof value === "function" ? value.bind(target) : value; + }, + }) as Checker; + const facade = new CheckerFacade(older); + + facade.prefetchRoots([sf]); + expect(requests).toEqual({ getContextualTypes: 1, getResolvedSignatures: 1 }); + facade.prefetchRoots(sf.statements.nodes); + facade.prefetchContextualTypes(collectNodes(w)); + expect(requests).toEqual({ getContextualTypes: 1, getResolvedSignatures: 1 }); + // The node-by-node queries still answer. + const call = collectNodes(w).find(ad.isCallExpression)!; + expect(facade.getResolvedSignature(call)).toBe(raw.getResolvedSignature(call)); +}); + test("autoPrefetch: false degrades to per-call queries (the escape hatch works)", () => { const w = buildTwoWorlds(RICH_TS, host); worlds.push(w); diff --git a/packages/compiler/test/type-mapper-unions.test.ts b/packages/compiler/test/type-mapper-unions.test.ts index c714df4d7..684960002 100644 --- a/packages/compiler/test/type-mapper-unions.test.ts +++ b/packages/compiler/test/type-mapper-unions.test.ts @@ -139,7 +139,8 @@ describe("checker and synthesized optional union identity", () => { nullable.arms.filter((arm) => arm.kind !== "nullT" && arm.kind !== "undefinedT"), ), ).toBe(required.unionId); - expect(nullable.discriminant!.cases.map((entry) => entry.values)).toEqual([ + // Cases follow the arms, which are ordered by their type keys. + expect(nullable.discriminant!.cases.map((entry) => entry.values).sort()).toEqual([ ["a", "alias"], ["b"], ]); diff --git a/packages/compiler/test/union-scalar-equality-emission.test.ts b/packages/compiler/test/union-scalar-equality-emission.test.ts new file mode 100644 index 000000000..62d59e258 --- /dev/null +++ b/packages/compiler/test/union-scalar-equality-emission.test.ts @@ -0,0 +1,45 @@ +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { expect, test } from "vitest"; +import { compile } from "../src/index.js"; + +async function emitLlvm(source: string): Promise { + const dir = await mkdtemp(join(tmpdir(), "scriptc-union-scalar-eq-")); + try { + const entry = join(dir, "main.ts"); + const outPath = join(dir, "main.ll"); + await writeFile(entry, source); + const result = await compile(entry, { outDir: dir, outPath, outputKind: "llvm" }); + expect(result.ok, JSON.stringify(result.diagnostics)).toBe(true); + return await readFile(outPath, "utf8"); + } finally { + await rm(dir, { recursive: true, force: true }); + } +} + +const source = ` +function zeros(a: number[], at: number[]): number { + let n = 0; + for (const i of at) if (a[i] === 0) n++; + return n; +} +function flags(a: (boolean | undefined)[]): number { + let n = 0; + for (let i = 0; i < a.length; i++) if (a[i] === true) n++; + return n; +} +console.log(zeros([0, 1, 0], [0, 1, 2, 5]), flags([true, undefined, false])); +`; + +test("comparing a union with a number or boolean reads its payload inline", async () => { + const llvm = await emitLlvm(source); + for (const name of ["zeros", "flags"]) { + const fn = new RegExp(`^define internal double @sc_bf_${name}\\([^]*?^}`, "m").exec(llvm)?.[0]; + expect(fn, name).toBeDefined(); + // The tag test and the payload load stay in the function, so the + // union's stack box has no escaping use. + expect(fn).not.toMatch(/@scr_union_get_(f64|bool)\(/); + expect(fn).toMatch(/getelementptr inbounds %ScrUnion, ptr %\S+, i64 0, i32 5/); + } +}); diff --git a/packages/experimental/package.json b/packages/experimental/package.json index 5b6906de6..cfb4151a4 100644 --- a/packages/experimental/package.json +++ b/packages/experimental/package.json @@ -1,6 +1,6 @@ { "name": "@scriptc/experimental", - "version": "0.4.1", + "version": "0.4.2", "description": "Experimental scriptc APIs, with Node.js implementations: lifetime regions for ProgramLifetime objects, intern tables shared between threads, and per-thread slots on shared objects", "license": "Apache-2.0", "homepage": "https://scriptc.dev", diff --git a/packages/llvm-darwin-arm64/package.json b/packages/llvm-darwin-arm64/package.json index 472056c39..615fe9d81 100644 --- a/packages/llvm-darwin-arm64/package.json +++ b/packages/llvm-darwin-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@scriptc/llvm-darwin-arm64", - "version": "0.4.1", + "version": "0.4.2", "description": "Pinned LLVM code-generation helper for scriptc on macOS arm64", "license": "Apache-2.0 WITH LLVM-exception", "homepage": "https://scriptc.dev", diff --git a/packages/llvm-darwin-x64/package.json b/packages/llvm-darwin-x64/package.json index 7f55cb6b5..fd6caf976 100644 --- a/packages/llvm-darwin-x64/package.json +++ b/packages/llvm-darwin-x64/package.json @@ -1,6 +1,6 @@ { "name": "@scriptc/llvm-darwin-x64", - "version": "0.4.1", + "version": "0.4.2", "description": "Pinned LLVM code-generation helper for scriptc on macOS x64", "license": "Apache-2.0 WITH LLVM-exception", "homepage": "https://scriptc.dev", diff --git a/packages/llvm-linux-arm64-gnu/package.json b/packages/llvm-linux-arm64-gnu/package.json index 0e1a55b22..7d66257f4 100644 --- a/packages/llvm-linux-arm64-gnu/package.json +++ b/packages/llvm-linux-arm64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@scriptc/llvm-linux-arm64-gnu", - "version": "0.4.1", + "version": "0.4.2", "description": "Pinned LLVM code-generation helper for scriptc on Linux arm64", "license": "Apache-2.0 WITH LLVM-exception", "homepage": "https://scriptc.dev", diff --git a/packages/llvm-linux-arm64-musl/package.json b/packages/llvm-linux-arm64-musl/package.json index efdd97444..b3a01089d 100644 --- a/packages/llvm-linux-arm64-musl/package.json +++ b/packages/llvm-linux-arm64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@scriptc/llvm-linux-arm64-musl", - "version": "0.4.1", + "version": "0.4.2", "description": "Statically linked LLVM code-generation helper for scriptc on Linux arm64 musl", "license": "Apache-2.0 WITH LLVM-exception", "homepage": "https://scriptc.dev", diff --git a/packages/llvm-linux-x64-gnu/package.json b/packages/llvm-linux-x64-gnu/package.json index 39667d535..0b3264ec7 100644 --- a/packages/llvm-linux-x64-gnu/package.json +++ b/packages/llvm-linux-x64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@scriptc/llvm-linux-x64-gnu", - "version": "0.4.1", + "version": "0.4.2", "description": "Pinned LLVM code-generation helper for scriptc on Linux x64", "license": "Apache-2.0 WITH LLVM-exception", "homepage": "https://scriptc.dev", diff --git a/packages/llvm-linux-x64-musl/package.json b/packages/llvm-linux-x64-musl/package.json index 9efd41845..6c83d1cb9 100644 --- a/packages/llvm-linux-x64-musl/package.json +++ b/packages/llvm-linux-x64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@scriptc/llvm-linux-x64-musl", - "version": "0.4.1", + "version": "0.4.2", "description": "Statically linked LLVM code-generation helper for scriptc on Linux x64 musl", "license": "Apache-2.0 WITH LLVM-exception", "homepage": "https://scriptc.dev", diff --git a/packages/llvm-win32-x64-msvc/package.json b/packages/llvm-win32-x64-msvc/package.json index 329fa308c..9fb682f0f 100644 --- a/packages/llvm-win32-x64-msvc/package.json +++ b/packages/llvm-win32-x64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@scriptc/llvm-win32-x64-msvc", - "version": "0.4.1", + "version": "0.4.2", "description": "Pinned LLVM code-generation helper for scriptc on Windows x64", "license": "Apache-2.0 WITH LLVM-exception", "homepage": "https://scriptc.dev", diff --git a/packages/runtime-android-arm64/package.json b/packages/runtime-android-arm64/package.json index 75c54e9c3..362fbc572 100644 --- a/packages/runtime-android-arm64/package.json +++ b/packages/runtime-android-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@scriptc/runtime-android-arm64", - "version": "0.4.1", + "version": "0.4.2", "description": "Precompiled scriptc library runtime pack for Android arm64", "license": "Apache-2.0", "homepage": "https://scriptc.dev", diff --git a/packages/runtime-darwin-arm64/package.json b/packages/runtime-darwin-arm64/package.json index 7473b05f3..a4176ed60 100644 --- a/packages/runtime-darwin-arm64/package.json +++ b/packages/runtime-darwin-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@scriptc/runtime-darwin-arm64", - "version": "0.4.1", + "version": "0.4.2", "description": "Precompiled scriptc runtime pack for macOS arm64", "license": "Apache-2.0", "homepage": "https://scriptc.dev", diff --git a/packages/runtime-darwin-arm64/runtime-pack-matrix.mjs b/packages/runtime-darwin-arm64/runtime-pack-matrix.mjs index db72284f6..7b2d3e115 100644 --- a/packages/runtime-darwin-arm64/runtime-pack-matrix.mjs +++ b/packages/runtime-darwin-arm64/runtime-pack-matrix.mjs @@ -43,7 +43,7 @@ export const RUNTIME_PACK_MATRIX = withLibraryRuntimeFlavors( { id: "quickjs", predicate: false }, { id: "libregexp", predicate: "regex" }, { id: "zlib", predicate: "zlibEffective" }, - { id: "mbedtls", predicate: any("tlsEffective", "cipher", "ecdh") }, + { id: "mbedtls", predicate: any("tlsEffective", "cipher", "ecdh", "dh", "pki") }, ], system_libraries: [{ name: "System", predicate: true }], }), diff --git a/packages/runtime-darwin-arm64/scripts/build.mjs b/packages/runtime-darwin-arm64/scripts/build.mjs index 85c5ffb00..e17312713 100644 --- a/packages/runtime-darwin-arm64/scripts/build.mjs +++ b/packages/runtime-darwin-arm64/scripts/build.mjs @@ -172,7 +172,10 @@ async function build() { ...(unit.source === "scr_regex.c" ? ["-I", quickjs] : []), ...(unit.source === "scr_tls.c" || unit.source === "scr_cipher.c" || - unit.source === "scr_ecdh.c" + unit.source === "scr_ecdh.c" || + unit.source === "scr_dh.c" || + unit.source === "scr_pki.c" || + unit.source === "scr_webcrypto_aes.c" ? ["-I", join(mbedtls, "include")] : []), ...(unit.source === "scr_zlib.c" || unit.source === "scr_fetch.c" @@ -337,7 +340,7 @@ async function build() { package: packageManifest.name, version: packageManifest.version, target: RUNTIME_PACK_MATRIX.target, - runtime_abi: { version: 24, marker: "scr_runtime_abi_v24" }, + runtime_abi: { version: 33, marker: "scr_runtime_abi_v33" }, compiler: { command: compiler, identity: compilerVersion, diff --git a/packages/runtime-darwin-x64/package.json b/packages/runtime-darwin-x64/package.json index ab8666c88..91bc4182b 100644 --- a/packages/runtime-darwin-x64/package.json +++ b/packages/runtime-darwin-x64/package.json @@ -1,6 +1,6 @@ { "name": "@scriptc/runtime-darwin-x64", - "version": "0.4.1", + "version": "0.4.2", "description": "Precompiled scriptc runtime pack for macOS x64", "license": "Apache-2.0", "homepage": "https://scriptc.dev", diff --git a/packages/runtime-ios-arm64/package.json b/packages/runtime-ios-arm64/package.json index a3a254685..2fdd68897 100644 --- a/packages/runtime-ios-arm64/package.json +++ b/packages/runtime-ios-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@scriptc/runtime-ios-arm64", - "version": "0.4.1", + "version": "0.4.2", "description": "Precompiled scriptc library runtime pack for iOS arm64", "license": "Apache-2.0", "homepage": "https://scriptc.dev", diff --git a/packages/runtime-ios-simulator-arm64/package.json b/packages/runtime-ios-simulator-arm64/package.json index 7981422b8..cbdf96d1d 100644 --- a/packages/runtime-ios-simulator-arm64/package.json +++ b/packages/runtime-ios-simulator-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@scriptc/runtime-ios-simulator-arm64", - "version": "0.4.1", + "version": "0.4.2", "description": "Precompiled scriptc library runtime pack for iOS simulator arm64", "license": "Apache-2.0", "homepage": "https://scriptc.dev", diff --git a/packages/runtime-linux-arm64-gnu/package.json b/packages/runtime-linux-arm64-gnu/package.json index d633ac303..e0d228925 100644 --- a/packages/runtime-linux-arm64-gnu/package.json +++ b/packages/runtime-linux-arm64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@scriptc/runtime-linux-arm64-gnu", - "version": "0.4.1", + "version": "0.4.2", "description": "Precompiled scriptc runtime pack for Linux arm64 glibc", "license": "Apache-2.0", "homepage": "https://scriptc.dev", diff --git a/packages/runtime-linux-arm64-musl/package.json b/packages/runtime-linux-arm64-musl/package.json index 460ca25fa..70eee223f 100644 --- a/packages/runtime-linux-arm64-musl/package.json +++ b/packages/runtime-linux-arm64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@scriptc/runtime-linux-arm64-musl", - "version": "0.4.1", + "version": "0.4.2", "description": "Precompiled scriptc runtime pack for Linux arm64 musl", "license": "Apache-2.0", "homepage": "https://scriptc.dev", diff --git a/packages/runtime-linux-x64-gnu/package.json b/packages/runtime-linux-x64-gnu/package.json index 9c6336a04..5822fd21d 100644 --- a/packages/runtime-linux-x64-gnu/package.json +++ b/packages/runtime-linux-x64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@scriptc/runtime-linux-x64-gnu", - "version": "0.4.1", + "version": "0.4.2", "description": "Precompiled scriptc runtime pack for Linux x64 glibc", "license": "Apache-2.0", "homepage": "https://scriptc.dev", diff --git a/packages/runtime-linux-x64-musl/package.json b/packages/runtime-linux-x64-musl/package.json index e9f885a5c..1db34d4a7 100644 --- a/packages/runtime-linux-x64-musl/package.json +++ b/packages/runtime-linux-x64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@scriptc/runtime-linux-x64-musl", - "version": "0.4.1", + "version": "0.4.2", "description": "Precompiled scriptc runtime pack for Linux x64 musl", "license": "Apache-2.0", "homepage": "https://scriptc.dev", diff --git a/packages/runtime-pack-common/runtime-pack-matrix.mjs b/packages/runtime-pack-common/runtime-pack-matrix.mjs index 0f40218a1..d0194be05 100644 --- a/packages/runtime-pack-common/runtime-pack-matrix.mjs +++ b/packages/runtime-pack-common/runtime-pack-matrix.mjs @@ -72,6 +72,8 @@ export const OPTIONAL_RUNTIME_SOURCES = [ ["scr_js_object.c", "dynTier"], ["scr_event_target.c", any("eventTarget", "nativeFetch")], ["scr_async_dyn.c", any("dynAsync", "dynInvoke", "dc", "fileHandle", "nativeFetch")], + // The crypto global's object extends scr_async_dyn.c's crypto object. + ["scr_webcrypto_object.c", all("webcrypto", "dynAsync")], // The performance timeline emits its buffer warning through scr_async_dyn.c. ["scr_perf.c", "dynAsync"], // perf_hooks event-loop metrics, only for programs that read them. @@ -127,6 +129,7 @@ export const OPTIONAL_RUNTIME_SOURCES = [ ["scr_dyn_handle_props.c", "handleProps"], // for await over checked-dynamic values. ["scr_dyn_for_await.c", "dynForAwait"], + ["scr_dyn_for_await_stream.c", all("dynForAwait", "stream", "dynAsync")], // fs.ReadStream / fs.WriteStream reference only the stream unit and base units. ["scr_fs_stream.c", "stream"], // FileHandle streams reference both the stream unit and FileHandle. @@ -149,9 +152,16 @@ export const OPTIONAL_RUNTIME_SOURCES = [ ["scr_tls.c", "tlsEffective"], ["scr_cipher.c", "cipher"], ["scr_ecdh.c", "ecdh"], + ["scr_dh.c", "dh"], + ["scr_pki.c", "pki"], ["scr_wasm.c", "wasm"], ["scr_webcrypto.c", "webcrypto"], + ["scr_webcrypto_pki.c", all("webcrypto", "pki")], + ["scr_ed25519.c", all("pki", "ed25519")], + // WebCrypto's AES ciphers run over the cipher feature's mbedTLS archive. + ["scr_webcrypto_aes.c", all("cipher", "webcrypto")], ["scr_fetch.c", "nativeFetch"], + ["scr_stream_from_web.c", all("stream", "nativeFetch")], ]; export function variantsFor(source) { @@ -212,7 +222,7 @@ export function createRuntimePackMatrix({ { id: "quickjs", predicate: false }, { id: "libregexp", predicate: "regex" }, { id: "zlib", predicate: "zlibEffective" }, - { id: "mbedtls", predicate: any("tlsEffective", "cipher", "ecdh") }, + { id: "mbedtls", predicate: any("tlsEffective", "cipher", "ecdh", "dh", "pki") }, ]; const matrix = withLibraryRuntimeFlavors( withWorkerRuntimeVariants({ diff --git a/packages/runtime-pack-common/scripts/build.mjs b/packages/runtime-pack-common/scripts/build.mjs index b242b78aa..60ef9dc49 100644 --- a/packages/runtime-pack-common/scripts/build.mjs +++ b/packages/runtime-pack-common/scripts/build.mjs @@ -223,7 +223,10 @@ async function build() { ...(unit.source === "scr_regex.c" ? ["-I", quickjs] : []), ...(unit.source === "scr_tls.c" || unit.source === "scr_cipher.c" || - unit.source === "scr_ecdh.c" + unit.source === "scr_ecdh.c" || + unit.source === "scr_dh.c" || + unit.source === "scr_pki.c" || + unit.source === "scr_webcrypto_aes.c" ? ["-I", join(mbedtls, "include")] : []), ...(unit.source === "scr_zlib.c" || unit.source === "scr_fetch.c" @@ -434,7 +437,7 @@ async function build() { package: packageManifest.name, version: packageManifest.version, target: matrix.target, - runtime_abi: { version: 24, marker: "scr_runtime_abi_v24" }, + runtime_abi: { version: 33, marker: "scr_runtime_abi_v33" }, compiler: { command: compiler, identity: compilerVersion, diff --git a/packages/runtime-wasm32-wasi/package.json b/packages/runtime-wasm32-wasi/package.json index c9a40c2c0..5bbd23755 100644 --- a/packages/runtime-wasm32-wasi/package.json +++ b/packages/runtime-wasm32-wasi/package.json @@ -1,6 +1,6 @@ { "name": "@scriptc/runtime-wasm32-wasi", - "version": "0.4.1", + "version": "0.4.2", "description": "Precompiled scriptc runtime pack for WASI Preview 1", "license": "Apache-2.0", "homepage": "https://scriptc.dev", diff --git a/packages/runtime-wasm32-wasi/scripts/build.mjs b/packages/runtime-wasm32-wasi/scripts/build.mjs index 2dd983973..cbe744e4e 100644 --- a/packages/runtime-wasm32-wasi/scripts/build.mjs +++ b/packages/runtime-wasm32-wasi/scripts/build.mjs @@ -22,6 +22,11 @@ process.env.SCRIPTC_RUNTIME_PACK_CONFIG = JSON.stringify({ "scr_tls.c", "scr_cipher.c", "scr_ecdh.c", + "scr_dh.c", + "scr_pki.c", + "scr_webcrypto_pki.c", + "scr_ed25519.c", + "scr_webcrypto_aes.c", "scr_wasm.c", "scr_fetch.c", ], diff --git a/packages/runtime-win32-x64-msvc/package.json b/packages/runtime-win32-x64-msvc/package.json index f7e4c9860..df4a9a109 100644 --- a/packages/runtime-win32-x64-msvc/package.json +++ b/packages/runtime-win32-x64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@scriptc/runtime-win32-x64-msvc", - "version": "0.4.1", + "version": "0.4.2", "description": "Precompiled scriptc runtime pack for Windows x64 MSVC", "license": "Apache-2.0", "homepage": "https://scriptc.dev", diff --git a/packages/runtime/package.json b/packages/runtime/package.json index 1af249b9d..9232266af 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -1,6 +1,6 @@ { "name": "@scriptc/runtime", - "version": "0.4.1", + "version": "0.4.2", "description": "scriptc native runtime sources and vendored dependencies", "license": "Apache-2.0", "homepage": "https://scriptc.dev", diff --git a/packages/runtime/src/scr_array.c b/packages/runtime/src/scr_array.c index 3d7da0c37..7f5f5bc5b 100644 --- a/packages/runtime/src/scr_array.c +++ b/packages/runtime/src/scr_array.c @@ -48,7 +48,7 @@ static inline const ScrArrExt *scr_arr_ax(const ScrArr *a) { } #define SCR_AX(a) scr_arr_ax(a) -static void scr_arr_move_inline(ScrArr *a, size_t cap, size_t unit); +static void scr_arr_move_inline(ScrArr *a, size_t cap); /* Bytes before the dense slots' allocation start: the ext pointer's word. */ static size_t scr_arr_prefix(const ScrArr *a) { @@ -60,9 +60,10 @@ static void *scr_arr_alloc_start(const ScrArr *a) { return (char *)scr_arr_block(a) - scr_arr_prefix(a); } -/* Bytes per dense slot with its state: an 8-byte value, or a boolean byte. */ +/* Bytes per dense slot: an 8-byte value or a boolean byte, and its state + * byte when the array has states. */ static size_t scr_arr_slot_unit(const ScrArr *a) { - return a->elem == SCR_ELEM_BOOL ? 2 * sizeof(uint8_t) : sizeof(uint64_t) + sizeof(uint8_t); + return scr_arr_slot_width(a) + (scr_arr_has_states(a) ? 1 : 0); } /* Bytes of dense storage (head room included) after the prefix. */ @@ -78,7 +79,7 @@ ScrArrExt *scr_arr_ext(ScrArr *a) { /* The pointer goes in the word before the dense allocation, which an * array with ext always has: inline slots move out, and an array without * storage gets an allocation of the word alone. */ - if (a->spare & SCR_ARR_INLINE_SLOTS) scr_arr_move_inline(a, a->cap, scr_arr_slot_unit(a)); + if (a->spare & SCR_ARR_INLINE_SLOTS) scr_arr_move_inline(a, a->cap); char *start; if (!a->data) { start = scr_mem_alloc(SCR_ARR_EXT_PREFIX); @@ -107,6 +108,7 @@ ScrArrExt *scr_arr_ext(ScrArr *a) { /* Registry of element ops by id (scr_arr_ops); slot 0 is no ops. */ const ScrArrOps *scr_arr_ops_table[SCR_ARR_OPS_OVERFLOW] = {0}; +uint8_t scr_arr_ops_release_nothing[SCR_ARR_OPS_OVERFLOW + 1] = {0}; static uint32_t scr_arr_ops_count = 1; /* Assign `ops` its id on its first array; any thread may get there first, @@ -118,6 +120,9 @@ uint32_t scr_arr_ops_register(ScrArrOps *ops) { if (id) return id; uint32_t fresh = __atomic_fetch_add(&scr_arr_ops_count, 1, __ATOMIC_RELAXED); if (fresh < SCR_ARR_OPS_OVERFLOW) { + /* Before the id is published: an array that carries the id can be + * released on any thread. */ + scr_arr_ops_release_nothing[fresh] = scr_arr_ops_release_nothing_flag(ops); __atomic_store_n(&scr_arr_ops_table[fresh], ops, __ATOMIC_RELEASE); } else { fresh = SCR_ARR_OPS_OVERFLOW; @@ -212,6 +217,11 @@ static bool scr_elem_is_ref(ScrElemKind k) { k == SCR_ELEM_REF; } +/* Whether `a`'s element type comes with element ops (scr_arr_ops). */ +static bool scr_arr_has_ops(const ScrArr *a) { + return a->elem == SCR_ELEM_REF || a->elem == SCR_ELEM_CREF; +} + /* Releases an element slot of kind `elem`, with element ops `ops` for * SCR_ELEM_REF. An array's kind and ops never change, so loops look them up * once (element releases may run teardown, which reloads anything read @@ -266,6 +276,7 @@ typedef struct { static uint64_t scr_arr_storage_get(const ScrArrStorage *s, size_t index) { if (s->elem == SCR_ELEM_BOOL) return ((const uint8_t *)s->data)[index]; + if (s->elem == SCR_ELEM_CREF) return scr_cref_decode(((const uint32_t *)s->data)[index]); return s->data[index]; } @@ -387,18 +398,14 @@ static void scr_arr_sparse_drop_prefix(ScrArr *a, size_t count) { x->sparse_len -= count; } -/* Bytes per dense slot: the value and its state byte. Boolean arrays - * store a one-byte value. */ -#define SCR_ARR_SLOT_BYTES (sizeof(uint64_t) + sizeof(uint8_t)) -#define SCR_ARR_BOOL_SLOT_BYTES (2 * sizeof(uint8_t)) /* Appends to an array smaller than this grow straight to it. */ #define SCR_ARR_MIN_GROWTH ((size_t)4) /* Inline slots: an array built by scr_arr_new_small / scr_arr_new_ops_small * (empty literals the compiler sees appended to), or constructed with a * known element count of up to SCR_ARR_KNOWN_INLINE_MAX, keeps its first - * dense slots and states in its own block, right after the ScrArr, so it - * costs one allocation and its first elements share the header's cache lines. + * dense slots in its own block, right after the ScrArr, so it costs one + * allocation and its first elements share the header's cache lines. * `spare` records it. Growth past the inline capacity moves the slots to an * ordinary allocation; the inline room then stays unused until the array is * freed. */ @@ -449,8 +456,14 @@ static void scr_arr_drop_head(ScrArr *a) { a->spare &= (uint16_t)~SCR_ARR_HEAD_ROOM; if (head == 0) return; size_t cap = a->cap, total = cap + head, live = a->len < cap ? a->len : cap; - uint8_t *end = scr_arr_states_end(a); uint64_t *data = a->data - head; + if (!scr_arr_has_states(a)) { + if (live) memmove(data, a->data, live * scr_arr_slot_width(a)); + a->data = data; + a->cap = total; + return; + } + uint8_t *end = scr_arr_states_end(a); /* The states end moves to the end of the allocation, past the `head` * vacated states: the live states move up with it, and every other state * becomes a hole. */ @@ -469,10 +482,10 @@ static void scr_arr_drop_head(ScrArr *a) { * for storage without head room (booleans, inline slots); the caller then * moves the tail down itself. */ static bool scr_arr_drop_front(ScrArr *a, size_t count) { - if (a->elem == SCR_ELEM_BOOL || scr_arr_inline(a)) return false; + if (scr_arr_slot_width(a) != sizeof(uint64_t) || scr_arr_inline(a)) return false; if (count == 0) return true; size_t head = scr_arr_head(a); - memset(scr_arr_state_run(a, 0, count), SCR_ARR_HOLE, count); + if (scr_arr_has_states(a)) memset(scr_arr_state_run(a, 0, count), SCR_ARR_HOLE, count); memset(a->data, 0, count * sizeof(uint64_t)); if (head) a->data[-1] = 0; a->data += count; @@ -492,9 +505,9 @@ static bool scr_arr_drop_front(ScrArr *a, size_t count) { } /* Slots requested by the small constructions. The small allocator rounds - * them up to fill its block: 3 eight-byte slots after a plain header in a - * 64-byte block (72 after a collector header), or 4 booleans in a 40-byte - * block. Most small arrays hold up to three elements; two slots make + * them up to fill its block: 4 eight-byte slots after a plain header in a + * 64-byte block (3 in 72 bytes after a collector header), or 8 booleans in + * a 40-byte block. Most small arrays hold up to three elements; two slots make * arrays that grow past them move their storage often enough to slow * programs that build many short lists. */ #if SCR_SMALL_ALLOC @@ -504,18 +517,14 @@ static bool scr_arr_drop_front(ScrArr *a, size_t count) { #endif /* Inline capacity of a small construction with `prefix` bytes of block - * before the slots. */ -static size_t scr_arr_small_cap(size_t prefix, bool bools) { + * before slots of `unit` bytes. Inlined, so it folds to a constant for a + * constant unit. */ +static inline size_t scr_arr_small_cap(size_t prefix, size_t unit) { #if SCR_SMALL_ALLOC - /* One return per slot unit, so each folds to a constant at its callers. */ - if (bools) - return (scr_sa_class_size(scr_sa_class(prefix + SCR_ARR_SMALL_SLOTS * SCR_ARR_BOOL_SLOT_BYTES)) - prefix) / - SCR_ARR_BOOL_SLOT_BYTES; - return (scr_sa_class_size(scr_sa_class(prefix + SCR_ARR_SMALL_SLOTS * SCR_ARR_SLOT_BYTES)) - prefix) / - SCR_ARR_SLOT_BYTES; + return (scr_sa_class_size(scr_sa_class(prefix + SCR_ARR_SMALL_SLOTS * unit)) - prefix) / unit; #else (void)prefix; - (void)bools; + (void)unit; return SCR_ARR_SMALL_SLOTS; #endif } @@ -528,39 +537,42 @@ static size_t scr_arr_small_cap(size_t prefix, bool bools) { #define SCR_ARR_KNOWN_INLINE_MAX ((size_t)16) /* Inline capacity of a construction of `need` elements with `prefix` bytes - * of block before the slots, rounded up to fill the block; 0 when its slots - * stay separate. */ -static size_t scr_arr_known_cap(size_t prefix, size_t need, bool bools) { + * of block before slots of `unit` bytes, rounded up to fill the block; 0 + * when its slots stay separate. */ +static size_t scr_arr_known_cap(size_t prefix, size_t need, size_t unit) { if (need == 0 || need > SCR_ARR_KNOWN_INLINE_MAX) return 0; #if SCR_SMALL_ALLOC - size_t unit = bools ? SCR_ARR_BOOL_SLOT_BYTES : SCR_ARR_SLOT_BYTES; size_t bytes = prefix + need * unit; if (bytes > SCR_SA_MAX) return 0; return (scr_sa_class_size(scr_sa_class(bytes)) - prefix) / unit; #else (void)prefix; - (void)bools; + (void)unit; return need; #endif } -static void scr_arr_use_inline(ScrArr *a, size_t cap) { +/* Points `a` at `cap` inline slots of `unit` bytes: the slot width, plus + * the state byte when the array has states (then all holes). */ +static void scr_arr_use_inline(ScrArr *a, size_t cap, size_t unit) { a->data = (uint64_t *)((char *)a + SCR_ARR_INLINE_OFFSET); a->cap = (uint32_t)cap; - memset(scr_arr_state_run(a, 0, cap), SCR_ARR_HOLE, cap); + if (scr_arr_has_states(a)) memset((char *)a->data + cap * (unit - 1), SCR_ARR_HOLE, cap); a->spare |= SCR_ARR_INLINE_SLOTS; } /* Move inline slots to their own allocation of `cap` (>= a->cap) slots; the * array's block keeps the unused room until it is freed. */ -static void scr_arr_move_inline(ScrArr *a, size_t cap, size_t unit) { +static void scr_arr_move_inline(ScrArr *a, size_t cap) { size_t width = scr_arr_slot_width(a); - uint64_t *data = scr_mem_alloc(cap * unit); + uint64_t *data = scr_mem_alloc(cap * scr_arr_slot_unit(a)); if (!data) scr_arr_oom(); - uint8_t *end = (uint8_t *)data + cap * (width + 1); memcpy(data, a->data, a->cap * width); - memcpy(end - a->cap, scr_arr_state_run(a, 0, a->cap), a->cap); - memset(end - cap, SCR_ARR_HOLE, cap - a->cap); + if (scr_arr_has_states(a)) { + uint8_t *end = (uint8_t *)data + cap * (width + 1); + memcpy(end - a->cap, scr_arr_state_run(a, 0, a->cap), a->cap); + memset(end - cap, SCR_ARR_HOLE, cap - a->cap); + } a->data = data; a->cap = cap; a->spare &= (uint16_t)~SCR_ARR_INLINE_SLOTS; @@ -582,15 +594,15 @@ typedef enum { * reallocation. Growth keeps its own sequence (4, 8, 16, ...): rounding it * as well moves array storage into other size classes and measured * slower. */ -static size_t scr_arr_block_cap(size_t cap, bool bools) { +static size_t scr_arr_block_cap(size_t cap, size_t unit) { #if SCR_SMALL_ALLOC - size_t bytes = cap * (bools ? SCR_ARR_BOOL_SLOT_BYTES : SCR_ARR_SLOT_BYTES); + size_t bytes = cap * unit; if (bytes <= SCR_SA_MAX) { size_t block = scr_sa_class_size(scr_sa_class((bytes + 15) & ~(size_t)15)); - return bools ? block / SCR_ARR_BOOL_SLOT_BYTES : block / SCR_ARR_SLOT_BYTES; + return block / unit; } #else - (void)bools; + (void)unit; #endif return cap; } @@ -609,27 +621,30 @@ static void scr_arr_grow_dense_slow(ScrArr *a, size_t need, ScrArrGrow mode); * paths pick the same capacity. */ static inline void scr_arr_grow_dense_to(ScrArr *a, size_t need, ScrArrGrow mode) { if (need <= a->cap) return; - if (a->elem == SCR_ELEM_BOOL || (a->spare & (SCR_ARR_INLINE_SLOTS | SCR_ARR_HEAD_ROOM | SCR_ARR_HAS_EXT)) || - need > SCR_ARR_DENSE_LIMIT) { + if (a->elem == SCR_ELEM_BOOL || a->elem == SCR_ELEM_CREF || + (a->spare & (SCR_ARR_INLINE_SLOTS | SCR_ARR_HEAD_ROOM | SCR_ARR_HAS_EXT)) || need > SCR_ARR_DENSE_LIMIT) { scr_arr_grow_dense_slow(a, need, mode); return; } + bool states = scr_arr_has_states(a); + size_t unit = sizeof(uint64_t) + (states ? 1 : 0); size_t cap; if (mode == SCR_ARR_GROW_EXACT) { - cap = scr_arr_block_cap(need, false); + cap = scr_arr_block_cap(need, unit); } else { cap = a->cap < SCR_ARR_MIN_GROWTH ? SCR_ARR_MIN_GROWTH : a->cap; while (cap < need) cap += cap; if (cap > SCR_ARR_DENSE_LIMIT) cap = SCR_ARR_DENSE_LIMIT; } size_t old = a->cap; - uint64_t *data = a->data ? scr_mem_realloc(a->data, cap * SCR_ARR_SLOT_BYTES) - : scr_mem_alloc(cap * SCR_ARR_SLOT_BYTES); + uint64_t *data = a->data ? scr_mem_realloc(a->data, cap * unit) : scr_mem_alloc(cap * unit); if (!data) scr_arr_oom(); - /* The states end the allocation: move them to its new end. */ - uint8_t *end = (uint8_t *)(data + cap) + cap; - if (old) memmove(end - old, (uint8_t *)(data + old), old); - memset(end - cap, SCR_ARR_HOLE, cap - old); + if (states) { + /* The states end the allocation: move them to its new end. */ + uint8_t *end = (uint8_t *)(data + cap) + cap; + if (old) memmove(end - old, (uint8_t *)(data + old), old); + memset(end - cap, SCR_ARR_HOLE, cap - old); + } a->data = data; a->cap = cap; } @@ -660,12 +675,12 @@ static void scr_arr_grow_dense_slow(ScrArr *a, size_t need, ScrArrGrow mode) { mode = SCR_ARR_GROW_APPEND; } } - bool bools = a->elem == SCR_ELEM_BOOL; + bool states = scr_arr_has_states(a); size_t width = scr_arr_slot_width(a); - size_t unit = bools ? SCR_ARR_BOOL_SLOT_BYTES : SCR_ARR_SLOT_BYTES; + size_t unit = scr_arr_slot_unit(a); size_t cap; if (mode == SCR_ARR_GROW_EXACT) { - cap = scr_arr_block_cap(need, bools); + cap = scr_arr_block_cap(need, unit); } else { /* Inline slots overflow into the ordinary sequence (4, 8, 16, ...). */ size_t from = scr_arr_inline(a) ? 0 : a->cap; @@ -680,9 +695,9 @@ static void scr_arr_grow_dense_slow(ScrArr *a, size_t need, ScrArrGrow mode) { * appends benefit from geometric headroom. */ if (mode == SCR_ARR_GROW_SPAN && need > SCR_ARR_DENSE_LIMIT) cap = need; } - if (cap > SIZE_MAX / SCR_ARR_SLOT_BYTES) scr_arr_oom(); /* bounds both slot sizes */ + if (cap > SIZE_MAX / (sizeof(uint64_t) + 1)) scr_arr_oom(); /* bounds every slot unit */ if (scr_arr_inline(a)) { - scr_arr_move_inline(a, cap, unit); + scr_arr_move_inline(a, cap); scr_arr_absorb_sparse(a); return; } @@ -692,7 +707,7 @@ static void scr_arr_grow_dense_slow(ScrArr *a, size_t need, ScrArrGrow mode) { if (!data) scr_arr_oom(); a->data = data; a->cap = (uint32_t)cap; - memset(scr_arr_state_run(a, 0, cap), SCR_ARR_HOLE, cap); + if (states) memset(scr_arr_state_run(a, 0, cap), SCR_ARR_HOLE, cap); return; } /* Values and states share one allocation. Move the old states to its new @@ -702,9 +717,11 @@ static void scr_arr_grow_dense_slow(ScrArr *a, size_t need, ScrArrGrow mode) { char *start = scr_mem_realloc((char *)a->data - prefix, prefix + cap * unit); if (!start) scr_arr_oom(); uint64_t *data = (uint64_t *)(start + prefix); - uint8_t *end = (uint8_t *)data + cap * (width + 1); - if (a->cap) memmove(end - a->cap, (uint8_t *)data + a->cap * width, a->cap); - memset(end - cap, SCR_ARR_HOLE, cap - a->cap); + if (states) { + uint8_t *end = (uint8_t *)data + cap * (width + 1); + if (a->cap) memmove(end - a->cap, (uint8_t *)data + a->cap * width, a->cap); + memset(end - cap, SCR_ARR_HOLE, cap - a->cap); + } a->data = data; a->cap = cap; scr_arr_absorb_sparse(a); @@ -714,6 +731,44 @@ static void scr_arr_grow_dense(ScrArr *a, size_t need) { scr_arr_grow_dense_to(a, need, SCR_ARR_GROW_APPEND); } +/* States follow the value slots, and the capacity stays: inline slots + * move to an allocation of their own, and other storage grows by the state + * bytes (immortal storage, which may be static, is copied instead). */ +void scr_arr_add_states(ScrArr *a) { + if (scr_arr_has_states(a)) return; + size_t width = scr_arr_slot_width(a), len = a->len; + if (a->cap == 0) { + a->spare |= SCR_ARR_STATES; + return; + } + if (scr_arr_inline(a)) { + uint64_t *data = scr_mem_alloc(a->cap * (width + 1)); + if (!data) scr_arr_oom(); + memcpy(data, a->data, len * width); + a->data = data; + a->spare &= (uint16_t)~SCR_ARR_INLINE_SLOTS; + } else if (a->rc == SIZE_MAX) { + size_t prefix = scr_arr_prefix(a); + char *start = scr_mem_alloc(prefix + a->cap * (width + 1)); + if (!start) scr_arr_oom(); + if (prefix) memcpy(start, scr_arr_alloc_start(a), prefix); + memcpy(start + prefix, a->data, len * width); + a->data = (uint64_t *)(start + prefix); + a->spare &= (uint16_t)~SCR_ARR_HEAD_ROOM; + } else { + /* Head room goes back to the capacity first. */ + scr_arr_drop_head(a); + size_t prefix = scr_arr_prefix(a); + char *start = scr_mem_realloc(scr_arr_alloc_start(a), prefix + a->cap * (width + 1)); + if (!start) scr_arr_oom(); + a->data = (uint64_t *)(start + prefix); + } + a->spare |= SCR_ARR_STATES; + uint8_t *end = scr_arr_states_end(a); + memset(end - len, SCR_ARR_VALUE, len); + memset(end - a->cap, SCR_ARR_HOLE, a->cap - len); +} + /* Room for `count` values in front of the first element of a dense array: * moves `data` back into head room, raising `cap`; the caller * stores the new first `count` slots and states. A shifted array reuses the @@ -723,7 +778,7 @@ static void scr_arr_grow_dense(ScrArr *a, size_t need) { * array's allocation. Returns false when the caller must move the elements * itself. */ static bool scr_arr_open_head(ScrArr *a, size_t count) { - if (a->elem == SCR_ELEM_BOOL || scr_arr_inline(a)) return false; + if (scr_arr_slot_width(a) != sizeof(uint64_t) || scr_arr_inline(a)) return false; size_t head = scr_arr_head(a); if (head < count) { size_t len = a->len; @@ -734,21 +789,24 @@ static bool scr_arr_open_head(ScrArr *a, size_t count) { /* The new allocation: head room for the new values plus half the new * length, then the current dense window (its tail capacity included). */ size_t room = count + (len + count) / 2; - if (room > SCR_ARR_MAX_LENGTH || a->cap > SIZE_MAX / SCR_ARR_SLOT_BYTES - room) return false; + size_t unit = scr_arr_slot_unit(a); + if (room > SCR_ARR_MAX_LENGTH || a->cap > SIZE_MAX / unit - room) return false; size_t total = room + a->cap; size_t prefix = scr_arr_prefix(a); - char *start = scr_mem_alloc(prefix + total * SCR_ARR_SLOT_BYTES); + char *start = scr_mem_alloc(prefix + total * unit); if (!start) scr_arr_oom(); /* The ext pointer's word moves with the allocation. */ if (prefix) memcpy(start, scr_arr_alloc_start(a), prefix); uint64_t *block = (uint64_t *)(start + prefix); - /* The window's states end `room` bytes before the allocation does; the - * room's states past it are holes. */ - uint8_t *end = (uint8_t *)(block + total) + a->cap; memcpy(block + room, a->data, len * sizeof(uint64_t)); - memset(end, SCR_ARR_HOLE, room); - memcpy(end - len, scr_arr_state_run(a, 0, len), len); - memset(end - a->cap, SCR_ARR_HOLE, a->cap - len); + if (scr_arr_has_states(a)) { + /* The window's states end `room` bytes before the allocation does; + * the room's states past it are holes. */ + uint8_t *end = (uint8_t *)(block + total) + a->cap; + memset(end, SCR_ARR_HOLE, room); + memcpy(end - len, scr_arr_state_run(a, 0, len), len); + memset(end - a->cap, SCR_ARR_HOLE, a->cap - len); + } scr_mem_free(scr_arr_alloc_start(a)); a->data = block + room; head = room; @@ -764,10 +822,9 @@ static bool scr_arr_open_head(ScrArr *a, size_t count) { * within that gap past capacity. */ static bool scr_arr_dense_tail_populated(const ScrArr *a) { size_t window = a->cap < SCR_ARR_DENSE_GAP ? a->cap : SCR_ARR_DENSE_GAP; - const uint8_t *states = scr_arr_states_end(a); - if (window == 0 || *scr_arr_state_in(states, a->cap - 1) == SCR_ARR_HOLE) return false; + if (window == 0 || scr_arr_dense_state(a, a->cap - 1) == SCR_ARR_HOLE) return false; size_t populated = 0; - for (size_t i = a->cap - window; i < a->cap; i++) populated += *scr_arr_state_in(states, i) != SCR_ARR_HOLE; + for (size_t i = a->cap - window; i < a->cap; i++) populated += scr_arr_dense_state(a, i) != SCR_ARR_HOLE; return populated * 16 >= window * 3; } @@ -841,7 +898,7 @@ static __attribute__((noinline, pure)) ScrArrStateSlot scr_arr_sparse_state_at(c * sparse entries above it. */ static inline uint8_t scr_arr_state_at(const ScrArr *a, size_t index, uint64_t *out) { if (index < a->cap) { - uint8_t state = *scr_arr_state_in(scr_arr_states_end(a), index); + uint8_t state = scr_arr_dense_state(a, index); if (state == SCR_ARR_HOLE) return SCR_ARR_HOLE; if (out) *out = scr_arr_dense_get(a, index); return state; @@ -851,19 +908,38 @@ static inline uint8_t scr_arr_state_at(const ScrArr *a, size_t index, uint64_t * return sparse.state; } +/* scr_arr_state_at for a number[] (SCR_ELEM_F64): 8-byte slots, with no + * element-kind test. */ +static inline uint8_t scr_arr_f64_state_at(const ScrArr *a, size_t index, uint64_t *out) { + if (index < a->cap) { + uint8_t state = !scr_arr_has_states(a) ? (index < a->len ? SCR_ARR_VALUE : SCR_ARR_HOLE) + : *scr_arr_state_in(scr_arr_states_end_w(a, 8), index); + if (state == SCR_ARR_HOLE) return SCR_ARR_HOLE; + *out = a->data[index]; + return state; + } + ScrArrStateSlot sparse = scr_arr_sparse_state_at(a, index); + if (sparse.state != SCR_ARR_HOLE) *out = sparse.slot; + return sparse.state; +} + static inline bool scr_arr_slot_at(const ScrArr *a, size_t index, uint64_t *out) { return scr_arr_state_at(a, index, out) != SCR_ARR_HOLE; } -/* Store an owned slot into an empty index. The caller has already established - * the destination length and does not need a retain. */ +/* Store an owned slot into an empty index. The caller does not need a + * retain. An array with states has its destination length established + * already; an array without states takes only a value at its length, + * whose caller then raises the length, and gets states for any other + * store. */ static void scr_arr_store_state_owned(ScrArr *a, size_t index, uint64_t slot, uint8_t state) { if (state != SCR_ARR_VALUE) scr_arr_cut(a, index); + if (!scr_arr_has_states(a) && (state != SCR_ARR_VALUE || index != a->len)) scr_arr_add_states(a); scr_arr_grow_for_index(a, index); if (index < a->cap) { scr_arr_dense_put(a, index, slot); - *scr_arr_state_ptr(a, index) = state; + if (scr_arr_has_states(a)) *scr_arr_state_ptr(a, index) = state; return; } size_t pos = scr_arr_sparse_lower_bound(SCR_AX(a)->sparse, SCR_AX(a)->sparse_len, index); @@ -879,12 +955,15 @@ static void scr_arr_store_owned(ScrArr *a, size_t index, uint64_t slot) { scr_arr_store_state_owned(a, index, slot, SCR_ARR_VALUE); } +/* Take the slot at `index`, leaving a hole: an array without states gets + * them. */ static bool scr_arr_take_state(ScrArr *a, size_t index, uint64_t *out, uint8_t *state_out) { if (index < a->cap) { - uint8_t state = *scr_arr_state_ptr(a, index); + uint8_t state = scr_arr_dense_state(a, index); if (state == SCR_ARR_HOLE) return false; scr_arr_cut(a, index); + scr_arr_need_states(a); *out = scr_arr_dense_get(a, index); *scr_arr_state_ptr(a, index) = SCR_ARR_HOLE; scr_arr_dense_put(a, index, 0); @@ -909,11 +988,19 @@ static void scr_arr_replace_state_owned(ScrArr *a, size_t index, uint64_t slot, uint8_t old_state; uint64_t old = 0; if (state != SCR_ARR_VALUE) scr_arr_cut(a, index); + /* Without states, a value below the length replaces a value. */ + if (!scr_arr_has_states(a) && (state != SCR_ARR_VALUE || index >= a->len)) { + if (state == SCR_ARR_VALUE && index == a->len) { + scr_arr_store_state_owned(a, index, slot, state); + return; + } + scr_arr_add_states(a); + } if (index < a->cap) { - old_state = *scr_arr_state_ptr(a, index); + old_state = scr_arr_dense_state(a, index); if (old_state == SCR_ARR_VALUE) old = scr_arr_dense_get(a, index); scr_arr_dense_put(a, index, slot); - *scr_arr_state_ptr(a, index) = state; + if (scr_arr_has_states(a)) *scr_arr_state_ptr(a, index) = state; } else { size_t pos = scr_arr_sparse_lower_bound(SCR_AX(a)->sparse, SCR_AX(a)->sparse_len, index); if (pos == SCR_AX(a)->sparse_len || SCR_AX(a)->sparse[pos].index != index) { @@ -941,6 +1028,10 @@ static void scr_arr_note_value(ScrArr *a, size_t index) { /* scr_arr_refill bounded to [0, limit): for range operations whose cost is * proportional to the range, not to the whole array. */ static void scr_arr_refill_to(ScrArr *a, size_t limit) { + if (!scr_arr_has_states(a)) { + scr_arr_refill(a); + return; + } size_t end = a->len < a->cap ? a->len : a->cap; if (limit < end) end = limit; size_t f = a->filled; @@ -1022,7 +1113,11 @@ static bool scr_arr_prop_delete(ScrArr *a, double key) { return true; } +/* Detach the storage of `a` for a rebuild through the element stores. Both + * have states: the detached storage for its readers, and the array for + * stores at any index. */ static ScrArrStorage scr_arr_take_storage(ScrArr *a) { + scr_arr_need_states(a); ScrArrExt *x = scr_arr_ext_of(a); ScrArrStorage old = {a->data, scr_arr_states_end(a), a->cap, SCR_AX(a)->sparse, SCR_AX(a)->sparse_len, SCR_AX(a)->sparse_cap, a->elem, @@ -1059,17 +1154,20 @@ static bool scr_arr_is_dense(const ScrArr *a) { return a->len <= a->cap && (!(a->spare & SCR_ARR_HAS_EXT) || scr_arr_ext_of(a)->sparse_len == 0); } +/* Without states, both move the values only: the caller keeps the + * elements contiguous from 0 and sets the length to their count. */ static void scr_arr_move_dense(ScrArr *a, size_t to, size_t from, size_t count) { if (count == 0) return; scr_arr_cut(a, to); memmove(scr_arr_dense_at(a, to), scr_arr_dense_at(a, from), count * scr_arr_slot_width(a)); - memmove(scr_arr_state_run(a, to, count), scr_arr_state_run(a, from, count), count); + if (scr_arr_has_states(a)) + memmove(scr_arr_state_run(a, to, count), scr_arr_state_run(a, from, count), count); } static void scr_arr_clear_dense(ScrArr *a, size_t from, size_t count) { if (count == 0) return; scr_arr_cut(a, from); - memset(scr_arr_state_run(a, from, count), SCR_ARR_HOLE, count); + if (scr_arr_has_states(a)) memset(scr_arr_state_run(a, from, count), SCR_ARR_HOLE, count); memset(scr_arr_dense_at(a, from), 0, count * scr_arr_slot_width(a)); } @@ -1138,39 +1236,75 @@ static inline void scr_arr_copy_slots(uint64_t *dst, const uint64_t *src, size_t } } +/* Whether dense slots [from, from + count) of `a` all hold values. */ +static bool scr_arr_dense_run_values(const ScrArr *a, size_t from, size_t count) { + if (!scr_arr_has_states(a)) return from + count <= a->len; + if (from + count <= a->filled) return true; + return scr_arr_value_run(scr_arr_states_end(a), from, from + count) == from + count; +} + /* The destination owns no values in this range. Only retain adapters run * while copying references: no release can collect an intermediate copy. * Self-appends use disjoint ranges after reserving capacity. Both arrays - * hold the same element kind, so their slots have the same width. */ + * hold the same element kind, so their slots have the same width. A + * destination without states keeps none for a range of values: its caller + * makes the range contiguous with its elements and sets the length; any + * other range gives it states. */ static void scr_arr_copy_dense(ScrArr *dst, size_t to, const ScrArr *src, size_t from, size_t count, bool reverse, bool materialize_holes) { if (count == 0) return; scr_arr_cut(dst, to); /* 8-byte slots: a constant slot size, and constant-width state ends. */ - bool wide = dst->elem != SCR_ELEM_BOOL; - uint8_t *dst_states = wide ? scr_arr_states_end_w(dst, 8) : scr_arr_states_end_w(dst, 1); - const uint8_t *src_states = wide ? scr_arr_states_end_w(src, 8) : scr_arr_states_end_w(src, 1); + size_t width = scr_arr_slot_width(dst); + bool wide = width == sizeof(uint64_t); + /* Callers copy from an array without states only from its elements + * (which a self-copy reads after moving them, past the length). */ + bool values = !scr_arr_has_states(src) || scr_arr_dense_run_values(src, from, count); + if (!values) scr_arr_need_states(dst); + bool refs = scr_elem_is_ref(src->elem); + if (!scr_arr_has_states(dst)) { + if (!reverse && wide) { + scr_arr_copy_slots(dst->data + to, src->data + from, count); + } else if (!reverse) { + memcpy(scr_arr_dense_at(dst, to), scr_arr_dense_at(src, from), count * width); + } else { + for (size_t i = 0; i < count; i++) + scr_arr_dense_put(dst, to + i, scr_arr_dense_get(src, from + count - i - 1)); + } + if (!refs) return; + uint8_t elem = src->elem; + const ScrArrOps *ops = scr_arr_ops(src); + if (wide) + for (size_t i = to; i < to + count; i++) dst->data[i] = scr_elem_retain_with(elem, ops, dst->data[i]); + else + for (size_t i = to; i < to + count; i++) + scr_arr_dense_put(dst, i, scr_elem_retain_with(elem, ops, scr_arr_dense_get(dst, i))); + return; + } + uint8_t *dst_states = wide ? scr_arr_states_end_w(dst, 8) : scr_arr_states_end_w(dst, width); + const uint8_t *src_states = values ? NULL : wide ? scr_arr_states_end_w(src, 8) : scr_arr_states_end_w(src, width); if (!reverse && wide) { scr_arr_copy_slots(dst->data + to, src->data + from, count); - /* A range below the source's hole-free prefix holds only values. */ - if (from + count <= src->filled) + if (values) scr_arr_set_states(dst_states - to - count, SCR_ARR_VALUE, count); else scr_arr_copy_states(dst_states - to - count, src_states - from - count, count); } else if (!reverse) { memcpy(scr_arr_dense_at(dst, to), scr_arr_dense_at(src, from), count * scr_arr_slot_width(dst)); - scr_arr_copy_states(dst_states - to - count, src_states - from - count, count); + if (values) + scr_arr_set_states(dst_states - to - count, SCR_ARR_VALUE, count); + else + scr_arr_copy_states(dst_states - to - count, src_states - from - count, count); } else { for (size_t i = 0; i < count; i++) { size_t source = from + count - i - 1; scr_arr_dense_put(dst, to + i, scr_arr_dense_get(src, source)); - *scr_arr_state_in(dst_states, to + i) = *scr_arr_state_in(src_states, source); + *scr_arr_state_in(dst_states, to + i) = values ? SCR_ARR_VALUE : *scr_arr_state_in(src_states, source); } } - bool refs = scr_elem_is_ref(src->elem); - if (!refs && !materialize_holes) return; + if (!refs && (!materialize_holes || values)) return; uint8_t elem = src->elem; const ScrArrOps *ops = scr_arr_ops(src); for (size_t i = to; i < to + count; i++) { @@ -1185,7 +1319,7 @@ static void scr_arr_copy_dense(ScrArr *dst, size_t to, const ScrArr *src, /* Store `count` 8-byte value slots into dense storage starting at `to`. */ static void scr_arr_put_slots(ScrArr *a, size_t to, size_t count, const uint64_t *slots) { - if (a->elem != SCR_ELEM_BOOL) { + if (scr_arr_slot_width(a) == sizeof(uint64_t)) { scr_arr_copy_slots(a->data + to, slots, count); return; } @@ -1197,9 +1331,9 @@ static void scr_arr_put_slots(ScrArr *a, size_t to, size_t count, const uint64_t static inline __attribute__((always_inline)) ScrArr *scr_arr_make(ScrElemKind elem, size_t initial_cap, bool small) { - size_t unit = elem == SCR_ELEM_BOOL ? SCR_ARR_BOOL_SLOT_BYTES : SCR_ARR_SLOT_BYTES; - size_t inline_cap = small ? scr_arr_small_cap(SCR_ARR_INLINE_OFFSET, elem == SCR_ELEM_BOOL) - : scr_arr_known_cap(SCR_ARR_INLINE_OFFSET, initial_cap, elem == SCR_ELEM_BOOL); + size_t unit = scr_elem_slot_width(elem); + size_t inline_cap = small ? scr_arr_small_cap(SCR_ARR_INLINE_OFFSET, unit) + : scr_arr_known_cap(SCR_ARR_INLINE_OFFSET, initial_cap, unit); ScrArr *a = scr_mem_alloc(inline_cap ? SCR_ARR_INLINE_OFFSET + inline_cap * unit : sizeof(ScrArr)); if (!a) scr_arr_oom(); a->rc = 1; @@ -1210,7 +1344,7 @@ static inline __attribute__((always_inline)) ScrArr *scr_arr_make(ScrElemKind el a->spare = 0; a->filled = 0; a->data = NULL; - if (inline_cap) scr_arr_use_inline(a, inline_cap); + if (inline_cap) scr_arr_use_inline(a, inline_cap, unit); else if (initial_cap > 0) scr_arr_grow_dense_to(a, initial_cap, SCR_ARR_GROW_EXACT); #ifdef SCR_RC_AUDIT scr_live_arrays++; @@ -1225,13 +1359,18 @@ ScrArr *scr_arr_new(ScrElemKind elem, size_t initial_cap) { ScrArr *scr_arr_new_small(ScrElemKind elem) { return scr_arr_make(elem, 0, true); } /* A non-cycle array whose final length the runtime knows when it builds - * it (regex match results): its `cap` slots and states share the header's - * block, so construction and teardown cost one allocation. Growth past + * it (regex match results): its `cap` slots share the header's block, so + * construction and teardown cost one allocation. With `states`, the array + * starts with states, whose bytes share the block as well. Growth past * `cap` moves the slots out like any inline array. */ -ScrArr *scr_arr_new_inline(ScrElemKind elem, size_t cap) { - if (cap == 0) return scr_arr_make(elem, 0, false); +ScrArr *scr_arr_new_inline(ScrElemKind elem, size_t cap, bool states) { + if (cap == 0) { + ScrArr *a = scr_arr_make(elem, 0, false); + if (states) a->spare |= SCR_ARR_STATES; + return a; + } if (cap > SCR_ARR_MAX_LENGTH) scr_arr_oom(); - size_t unit = elem == SCR_ELEM_BOOL ? SCR_ARR_BOOL_SLOT_BYTES : SCR_ARR_SLOT_BYTES; + size_t unit = scr_elem_slot_width(elem) + (states ? 1 : 0); ScrArr *a = scr_mem_alloc(SCR_ARR_INLINE_OFFSET + cap * unit); if (!a) scr_arr_oom(); a->rc = 1; @@ -1239,10 +1378,10 @@ ScrArr *scr_arr_new_inline(ScrElemKind elem, size_t cap) { a->cap = 0; a->elem = (uint8_t)elem; a->cyc = 0; - a->spare = 0; + a->spare = states ? SCR_ARR_STATES : 0; a->filled = 0; a->data = NULL; - scr_arr_use_inline(a, cap); + scr_arr_use_inline(a, cap, unit); #ifdef SCR_RC_AUDIT scr_live_arrays++; #endif @@ -1250,10 +1389,9 @@ ScrArr *scr_arr_new_inline(ScrElemKind elem, size_t cap) { } void scr_arr_outline(ScrArr *a) { - if (scr_arr_inline(a)) - scr_arr_move_inline(a, a->cap, - a->elem == SCR_ELEM_BOOL ? SCR_ARR_BOOL_SLOT_BYTES : SCR_ARR_SLOT_BYTES); - /* The swapped fields do not include `spare`: no head room either. */ + if (scr_arr_inline(a)) scr_arr_move_inline(a, a->cap); + /* Of `spare`, a swap of the storage fields may move only the states + * flag: no head room either. */ if (a->spare & SCR_ARR_HEAD_ROOM) { scr_arr_drop_head(a); scr_arr_absorb_sparse(a); @@ -1287,9 +1425,14 @@ void scr_arr_trace_v(void *a0, ScrTraceVisit visit, void *ctx) { if (SCR_AX(a)->metadata) visit(SCR_AX(a)->metadata, ctx); /* Growth and truncation leave spare capacity empty. Sparse slots and * named properties are separate edges, independent of dense length. */ - const uint8_t *states = scr_arr_states_end(a); - for (size_t i = 0, end = a->len < a->cap ? a->len : a->cap; i < end; i++) { - if (*scr_arr_state_in(states, i) == SCR_ARR_VALUE) visit(scr_slot_to_ptr(a->data[i]), ctx); + size_t end = a->len < a->cap ? a->len : a->cap; + if (!scr_arr_has_states(a)) { + for (size_t i = 0; i < end; i++) visit(scr_slot_to_ptr(a->data[i]), ctx); + } else { + const uint8_t *states = scr_arr_states_end(a); + for (size_t i = 0; i < end; i++) { + if (*scr_arr_state_in(states, i) == SCR_ARR_VALUE) visit(scr_slot_to_ptr(a->data[i]), ctx); + } } for (size_t i = 0; i < SCR_AX(a)->sparse_len; i++) { if (SCR_AX(a)->sparse[i].state == SCR_ARR_VALUE) { @@ -1329,18 +1472,21 @@ static void scr_arr_gc_free(void *a0) { scr_cyc_free_inline(a); } -/* Inlined into each constructor like scr_arr_make: with `small` and the - * count constant, scr_arr_new_ops_small's size class folds to a table - * index. */ -static inline __attribute__((always_inline)) ScrArr *scr_arr_make_ops(const ScrArrOps *ops, - size_t initial_cap, - bool small) { +/* Inlined into each constructor like scr_arr_make: with `small`, the count + * and `elem` constant, scr_arr_new_ops_small's size class folds to a table + * index and the slot sizes to constants. */ +static inline __attribute__((always_inline)) ScrArr *scr_arr_make_ops_kind(const ScrArrOps *ops, + size_t initial_cap, + bool small, + uint8_t elem) { ScrArr *a; bool cyc = ops->trace != NULL; + /* The array starts without states: slots of the value width alone. */ + size_t unit = scr_elem_slot_width(elem); size_t prefix = SCR_ARR_INLINE_OFFSET + (cyc ? sizeof(ScrCycHdr) : 0); size_t inline_cap = - small ? scr_arr_small_cap(prefix, false) : scr_arr_known_cap(prefix, initial_cap, false); - size_t size = inline_cap ? SCR_ARR_INLINE_OFFSET + inline_cap * SCR_ARR_SLOT_BYTES : sizeof(ScrArr); + small ? scr_arr_small_cap(prefix, unit) : scr_arr_known_cap(prefix, initial_cap, unit); + size_t size = inline_cap ? SCR_ARR_INLINE_OFFSET + inline_cap * unit : sizeof(ScrArr); if (cyc) { static ScrCycType cyc_type = { &scr_arr_trace_v, &scr_arr_gc_free, SCR_CYC_KIND_ARRAY }; a = scr_cyc_alloc_inline(size, &cyc_type); @@ -1351,7 +1497,7 @@ static inline __attribute__((always_inline)) ScrArr *scr_arr_make_ops(const ScrA a->rc = 1; a->len = 0; a->cap = 0; - a->elem = SCR_ELEM_REF; + a->elem = elem; a->cyc = cyc; /* The ops id is written with the other header fields: reading `spare` * back after scr_arr_use_inline sets its inline flag stalls the @@ -1360,7 +1506,7 @@ static inline __attribute__((always_inline)) ScrArr *scr_arr_make_ops(const ScrA a->spare = (uint16_t)(id << SCR_ARR_OPS_SHIFT); a->filled = 0; a->data = NULL; - if (inline_cap) scr_arr_use_inline(a, inline_cap); + if (inline_cap) scr_arr_use_inline(a, inline_cap, unit); else if (initial_cap > 0) scr_arr_grow_dense_to(a, initial_cap, SCR_ARR_GROW_EXACT); /* After the storage: ops past the registry live in the ext, whose * pointer precedes the dense allocation, so inline slots move out first @@ -1372,12 +1518,32 @@ static inline __attribute__((always_inline)) ScrArr *scr_arr_make_ops(const ScrA return a; } +/* SCR_ELEM_CREF for compact element types, SCR_ELEM_REF otherwise. Each + * branch inlines scr_arr_make_ops_kind with a constant kind. */ +static inline __attribute__((always_inline)) ScrArr *scr_arr_make_ops(const ScrArrOps *ops, + size_t initial_cap, + bool small) { + if (__builtin_expect(scr_arr_ops_compact(ops), 0)) + return scr_arr_make_ops_kind(ops, initial_cap, small, SCR_ELEM_CREF); + return scr_arr_make_ops_kind(ops, initial_cap, small, SCR_ELEM_REF); +} + ScrArr *scr_arr_new_ops(const ScrArrOps *ops, size_t initial_cap) { return scr_arr_make_ops(ops, initial_cap, false); } ScrArr *scr_arr_new_ops_small(const ScrArrOps *ops) { return scr_arr_make_ops(ops, 0, true); } +/* Frees an acyclic array whose elements are already released. */ +static inline __attribute__((always_inline)) void scr_arr_free(ScrArr *a) { + scr_arr_free_parts(a); +#ifdef SCR_RC_AUDIT + scr_live_arrays--; +#endif + scr_weak_dispose_inline(a); + scr_mem_free(a); +} + static void scr_arr_destroy(void *object) { ScrArr *a = object; if (scr_arr_ext_of(a)) { @@ -1391,18 +1557,28 @@ static void scr_arr_destroy(void *object) { * first (and the storage cannot move under the loop); immortal strings * (interned characters, literals) need no call. */ const uint64_t *data = a->data; - const uint8_t *states = scr_arr_states_end_w(a, 8); - /* Slots below the hole-free prefix bound hold values. */ - size_t filled = a->filled < end ? a->filled : end; + /* Slots below the hole-free prefix bound hold values, as do all + * slots below the length of an array without states. */ + size_t filled = !scr_arr_has_states(a) ? end : a->filled < end ? a->filled : end; for (size_t i = 0; i < filled; i++) { ScrStr *s = (ScrStr *)scr_slot_to_ptr(data[i]); if (s && s->rc != SIZE_MAX) scr_str_release(s); } + const uint8_t *states = scr_arr_states_end_w(a, 8); for (size_t i = filled; i < end; i++) { if (*scr_arr_state_in(states, i) != SCR_ARR_VALUE) continue; ScrStr *s = (ScrStr *)scr_slot_to_ptr(data[i]); if (s && s->rc != SIZE_MAX) scr_str_release(s); } + } else if (!scr_arr_has_states(a)) { + /* Each slot is cleared before its release, as with states. */ + uint8_t elem = a->elem; + const ScrArrOps *ops = scr_arr_ops(a); + for (size_t i = 0; i < end; i++) { + uint64_t old = a->data[i]; + a->data[i] = 0; + scr_elem_release_with(elem, ops, old); + } } else { uint8_t *states = scr_arr_states_end(a); uint8_t elem = a->elem; @@ -1435,21 +1611,29 @@ static void scr_arr_destroy(void *object) { } } } - if (a->cyc) { - scr_arr_gc_free(a); - } else { - scr_arr_free_parts(a); -#ifdef SCR_RC_AUDIT - scr_live_arrays--; -#endif - scr_weak_dispose_inline(a); - scr_mem_free(a); - } + if (a->cyc) scr_arr_gc_free(a); + else scr_arr_free(a); +} + +/* Whether destroying `a`, an acyclic array, releases nothing: it has no ext + * and its elements are numbers, booleans or compact references, or + * references whose release does nothing (SCR_ARR_OPS_RELEASE_NOTHING). */ +static inline bool scr_arr_releases_nothing(const ScrArr *a) { + if (a->spare & SCR_ARR_HAS_EXT) return false; + if (!scr_elem_is_ref(a->elem)) return true; + return a->elem == SCR_ELEM_REF && + scr_arr_ops_release_nothing[(uint32_t)a->spare >> SCR_ARR_OPS_SHIFT]; } void scr_arr_release(ScrArr *a) { if (!a || a->rc == SIZE_MAX) return; /* NULL: an uninitialized `let` local */ if (--a->rc == 0) { + /* Nothing to tear down: free the storage without scr_rc_destroy's + * queue (no release can recurse) or the element loop. */ + if (!a->cyc && scr_arr_releases_nothing(a)) { + scr_arr_free(a); + return; + } if (a->cyc) scr_cyc_dead(a); scr_rc_destroy(a, scr_arr_destroy); } else if (a->cyc) { @@ -1485,6 +1669,7 @@ double scr_arr_next_present(const ScrArr *a, double start) { if (!(start < SCR_ARR_LEN_F64(a->len))) return SCR_ARR_LEN_F64(a->len); size_t i = start > 0 ? (size_t)ceil(start) : 0; size_t end = a->cap < a->len ? a->cap : a->len; + if (!scr_arr_has_states(a)) return (double)i; const uint8_t *states = scr_arr_states_end(a); for (; i < end; i++) { if (*scr_arr_state_in(states, i) != SCR_ARR_HOLE) return (double)i; @@ -1523,6 +1708,22 @@ void scr_arr_set_len(ScrArr *a, double length) { * array must cost only the elements removed, not its historical peak. */ size_t dense_end = a->len < a->cap ? a->len : a->cap; size_t dense_stop = next < dense_end ? next : dense_end; + if (!scr_arr_has_states(a)) { + /* Values only: each slot is cleared before its release. The + * length drops first, so a release that reads the array sees the + * values that remain. */ + a->len = (uint32_t)next; + if (scr_elem_is_ref(a->elem)) { + for (size_t i = dense_stop; i < dense_end; i++) { + uint64_t old = a->data[i]; + a->data[i] = 0; + scr_elem_release(a, old); + } + } else if (dense_stop < dense_end) { + memset(scr_arr_dense_at(a, dense_stop), 0, (dense_end - dense_stop) * scr_arr_slot_width(a)); + } + return; + } if (scr_elem_is_ref(a->elem)) { for (size_t i = dense_stop; i < dense_end; i++) { if (*scr_arr_state_ptr(a, i) != SCR_ARR_HOLE) { @@ -1551,8 +1752,20 @@ void scr_arr_set_len(ScrArr *a, double length) { } if (scr_arr_ext_of(a)) scr_arr_ext_of(a)->sparse_len = scr_arr_sparse_lower_bound(scr_arr_ext_of(a)->sparse, scr_arr_ext_of(a)->sparse_len, next); } - } else if (a->len == 0 && next <= SCR_ARR_PRESIZE_LIMIT && (a->cap == 0 || scr_arr_inline(a))) { - scr_arr_reserve_exact(a, next); + } else if (next > a->len) { + /* The indices past the elements are holes. An empty array gives up + * its inline slots first, so its slots and states take one allocation. */ + if (a->len == 0 && next <= SCR_ARR_PRESIZE_LIMIT && (a->cap == 0 || scr_arr_inline(a))) { + if (scr_arr_inline(a)) { + a->spare &= (uint16_t)~SCR_ARR_INLINE_SLOTS; + a->cap = 0; + a->data = NULL; + } + scr_arr_need_states(a); + scr_arr_reserve_exact(a, next); + } else { + scr_arr_need_states(a); + } } a->len = next; } @@ -1583,11 +1796,24 @@ void scr_arr_copy_range_ex(ScrArr *dst, size_t dst_start, const ScrArr *src, scr_arr_refill_to(dst, dst_start + count); } +/* A destination without states takes a dense copy at its length, whose + * caller then raises the length over the copy; any other copy gives it + * states first. */ static void scr_arr_copy_range_states(ScrArr *dst, size_t dst_start, const ScrArr *src, size_t src_start, size_t count, bool reverse, bool materialize_holes) { - if (src != dst && src_start <= src->cap && count <= src->cap - src_start && - dst_start <= dst->cap && count <= dst->cap - dst_start) { + size_t src_end = scr_arr_has_states(src) ? src->cap : src->len; + bool fits = src != dst && src_start <= src_end && count <= src_end - src_start && + dst_start <= dst->cap && count <= dst->cap - dst_start; + if (!scr_arr_has_states(dst)) { + if (fits && dst_start == dst->len) { + scr_arr_copy_dense(dst, dst_start, src, src_start, count, reverse, materialize_holes); + return; + } + scr_arr_add_states(dst); + fits = fits && dst_start <= dst->cap && count <= dst->cap - dst_start; + } + if (fits) { const uint8_t *dst_states = scr_arr_states_end(dst); size_t empty = 0; while (empty < count && *scr_arr_state_in(dst_states, dst_start + empty) == SCR_ARR_HOLE) empty++; @@ -1673,11 +1899,13 @@ static ScrArr *scr_arr_fill_slot(ScrArr *a, uint64_t slot, uint8_t state, if (from >= until) return scr_arr_retain(a); bool refs = scr_elem_is_ref(a->elem); if (scr_arr_dense_ok(a, until, until - from)) scr_arr_grow_dense(a, until); + if (state != SCR_ARR_VALUE) scr_arr_need_states(a); if (!refs && until <= a->cap) { if (state != SCR_ARR_VALUE) scr_arr_cut(a, from); if (a->elem == SCR_ELEM_BOOL) memset(scr_arr_dense_at(a, from), (int)slot, until - from); + else if (a->elem == SCR_ELEM_CREF) for (size_t i = from; i < until; i++) scr_arr_dense_put(a, i, slot); else for (size_t i = from; i < until; i++) a->data[i] = slot; - memset(scr_arr_state_run(a, from, until - from), state, until - from); + if (scr_arr_has_states(a)) memset(scr_arr_state_run(a, from, until - from), state, until - from); } else { for (size_t i = from; i < until; i++) { uint64_t value = refs && state == SCR_ARR_VALUE ? scr_elem_retain_slot(a, slot) : slot; @@ -1712,7 +1940,7 @@ double scr_math_max_arr(ScrArr *a) { double best = -INFINITY; for (size_t i = 0; i < a->len; i++) { uint64_t slot; - if (scr_arr_state_at(a, i, &slot) != SCR_ARR_VALUE) return NAN; + if (scr_arr_f64_state_at(a, i, &slot) != SCR_ARR_VALUE) return NAN; double v = scr_slot_to_f64(slot); if (isnan(v)) return v; if (v > best || (v == 0.0 && best == 0.0 && !signbit(v))) best = v; @@ -1724,7 +1952,7 @@ double scr_math_min_arr(ScrArr *a) { double best = INFINITY; for (size_t i = 0; i < a->len; i++) { uint64_t slot; - if (scr_arr_state_at(a, i, &slot) != SCR_ARR_VALUE) return NAN; + if (scr_arr_f64_state_at(a, i, &slot) != SCR_ARR_VALUE) return NAN; double v = scr_slot_to_f64(slot); if (isnan(v)) return v; if (v < best || (v == 0.0 && best == 0.0 && signbit(v))) best = v; @@ -1739,7 +1967,7 @@ double scr_math_hypot_arr(ScrArr *a) { bool has_nan = false; for (size_t i = 0; i < a->len; i++) { uint64_t slot; - if (scr_arr_state_at(a, i, &slot) != SCR_ARR_VALUE) { + if (scr_arr_f64_state_at(a, i, &slot) != SCR_ARR_VALUE) { has_nan = true; continue; } @@ -1754,7 +1982,7 @@ double scr_math_hypot_arr(ScrArr *a) { double correction = 0.0; for (size_t i = 0; i < a->len; i++) { uint64_t slot; - (void)scr_arr_state_at(a, i, &slot); + (void)scr_arr_f64_state_at(a, i, &slot); double v = scr_slot_to_f64(slot) / scale; double term = v * v - correction; double next = sum + term; @@ -1830,9 +2058,9 @@ void *scr_arr_peek_ref(const ScrArr *a, double i) { if (i >= 0 && i < (double)a->cap) { size_t idx = (size_t)i; if ((double)idx == i) { - if (idx < a->filled) return scr_slot_to_ptr(a->data[idx]); - if (idx >= a->len || *scr_arr_state_ptr(a, idx) != SCR_ARR_VALUE) return NULL; - return scr_slot_to_ptr(a->data[idx]); + if (idx < a->filled) return scr_slot_to_ptr(scr_arr_dense_get(a, idx)); + if (idx >= a->len || scr_arr_dense_state(a, idx) != SCR_ARR_VALUE) return NULL; + return scr_slot_to_ptr(scr_arr_dense_get(a, idx)); } } uint64_t slot; @@ -1861,8 +2089,8 @@ bool scr_arr_index_eq(const ScrArr *a, double i, const ScrArr *b, double j) { if (i >= 0 && i < (double)a->cap && i == trunc(i) && j >= 0 && j < (double)b->cap && j == trunc(j)) { size_t ai = (size_t)i, bi = (size_t)j; - bool ap = ai < a->len && *scr_arr_state_ptr(a, ai) == SCR_ARR_VALUE; - bool bp = bi < b->len && *scr_arr_state_ptr(b, bi) == SCR_ARR_VALUE; + bool ap = ai < a->len && scr_arr_dense_state(a, ai) == SCR_ARR_VALUE; + bool bp = bi < b->len && scr_arr_dense_state(b, bi) == SCR_ARR_VALUE; if (!ap || !bp) return ap == bp; av = scr_arr_dense_get(a, ai); bv = scr_arr_dense_get(b, bi); @@ -1886,7 +2114,7 @@ void *scr_arr_get_ref(ScrArr *a, double i) { if (a->elem == SCR_ELEM_STR) scr_str_retain((ScrStr *)p); else if (a->elem == SCR_ELEM_BYTES) scr_bytes_retain((ScrBytes *)p); else if (a->elem == SCR_ELEM_REF) p = scr_arr_ops(a)->retain(p); - else scr_arr_retain((ScrArr *)p); + else if (a->elem == SCR_ELEM_ARR) scr_arr_retain((ScrArr *)p); return p; } @@ -1902,6 +2130,17 @@ static void scr_arr_set_slot(ScrArr *a, double i, uint64_t slot) { scr_arr_prop_set(a, i, slot); return; } + if (!scr_arr_has_states(a) && idx >= a->len) { + /* An append keeps the array without states; a write past the length + * leaves holes. */ + if (idx == a->len) { + scr_arr_store_owned(a, idx, slot); + a->len = (uint32_t)(idx + 1); + scr_arr_note_value(a, idx); + return; + } + scr_arr_add_states(a); + } if (idx >= a->len) a->len = idx + 1; /* Unlink-then-release: a release can trigger a cycle collection, which * must never see a heap edge whose count was already given up. */ @@ -1927,6 +2166,7 @@ void scr_arr_set_undefined(ScrArr *a, double i) { scr_arr_prop_set_undefined(a, i); return; } + scr_arr_need_states(a); if (idx >= a->len) a->len = idx + 1; scr_arr_replace_state_owned(a, idx, 0, SCR_ARR_UNDEFINED); } @@ -1976,7 +2216,7 @@ double scr_arr_push_many(ScrArr *a, size_t count, const uint64_t *slots) { scr_arr_grow_dense(a, next); if (count) { scr_arr_put_slots(a, from, count, slots); - scr_arr_set_states(scr_arr_state_run(a, from, count), SCR_ARR_VALUE, count); + if (scr_arr_has_states(a)) scr_arr_set_states(scr_arr_state_run(a, from, count), SCR_ARR_VALUE, count); } a->len = (uint32_t)next; /* The appended states are values: a bound at the old length moves to @@ -1985,6 +2225,7 @@ double scr_arr_push_many(ScrArr *a, size_t count, const uint64_t *slots) { else scr_arr_refill(a); return (double)next; } + scr_arr_need_states(a); for (size_t i = 0; i < count; i++) scr_arr_store_owned(a, from + i, slots[i]); a->len = (uint32_t)next; scr_arr_refill(a); @@ -2021,6 +2262,7 @@ double scr_arr_push_spread(ScrArr *a, const ScrArr *src) { scr_arr_refill(a); return SCR_ARR_LEN_F64(a->len); } + scr_arr_need_states(a); a->len = old_len + add; for (size_t i = 0; i < add; i++) { uint64_t slot; @@ -2065,9 +2307,10 @@ double scr_arr_concat_copy(ScrArr *a, const ScrArr *src) { scr_arr_refill(a); return SCR_ARR_LEN_F64(a->len); } + scr_arr_need_states(a); a->len = old_len + add; for (size_t i = 0; i < src->cap; i++) { - if (*scr_arr_state_ptr(src, i) != SCR_ARR_HOLE) { + if (scr_arr_dense_state(src, i) != SCR_ARR_HOLE) { scr_arr_copy_index(a, old_len + i, src, i); } } @@ -2121,7 +2364,7 @@ static double scr_arr_unshift_slot(ScrArr *a, uint64_t slot) { /* The prefix stays put in front of the new first value. */ size_t f = a->filled; a->data[0] = slot; - *scr_arr_state_ptr(a, 0) = SCR_ARR_VALUE; + if (scr_arr_has_states(a)) *scr_arr_state_ptr(a, 0) = SCR_ARR_VALUE; a->len++; a->filled = (uint32_t)(f + 1); return SCR_ARR_LEN_F64(a->len); @@ -2132,7 +2375,7 @@ static double scr_arr_unshift_slot(ScrArr *a, uint64_t slot) { size_t f = a->filled; scr_arr_move_dense(a, 1, 0, old_len); scr_arr_dense_put(a, 0, slot); - *scr_arr_state_ptr(a, 0) = SCR_ARR_VALUE; + if (scr_arr_has_states(a)) *scr_arr_state_ptr(a, 0) = SCR_ARR_VALUE; a->len++; a->filled = (uint32_t)(f + 1); return SCR_ARR_LEN_F64(a->len); @@ -2173,7 +2416,7 @@ double scr_arr_unshift_many(ScrArr *a, size_t count, const uint64_t *slots) { if (scr_arr_is_dense(a) && scr_arr_open_head(a, count)) { size_t f = a->filled; scr_arr_put_slots(a, 0, count, slots); - memset(scr_arr_state_run(a, 0, count), SCR_ARR_VALUE, count); + if (scr_arr_has_states(a)) memset(scr_arr_state_run(a, 0, count), SCR_ARR_VALUE, count); a->len = old_len + count; a->filled = (uint32_t)(f + count); return SCR_ARR_LEN_F64(a->len); @@ -2183,7 +2426,7 @@ double scr_arr_unshift_many(ScrArr *a, size_t count, const uint64_t *slots) { size_t f = a->filled; scr_arr_move_dense(a, count, 0, old_len); scr_arr_put_slots(a, 0, count, slots); - memset(scr_arr_state_run(a, 0, count), SCR_ARR_VALUE, count); + if (scr_arr_has_states(a)) memset(scr_arr_state_run(a, 0, count), SCR_ARR_VALUE, count); a->len = old_len + count; a->filled = (uint32_t)(f + count); return SCR_ARR_LEN_F64(a->len); @@ -2210,6 +2453,10 @@ double scr_arr_unshift_spread(ScrArr *a, const ScrArr *src) { size_t add = src->len; if (add == 0) return (double)old_len; if (add > SCR_ARR_MAX_LENGTH - old_len) scr_arr_oom(); + /* Holes and present undefined in the source become present undefined: + * the receiver needs states, before its elements move. */ + if (!scr_arr_has_states(a) && (!scr_arr_is_dense(src) || !scr_arr_dense_run_values(src, 0, add))) + scr_arr_add_states(a); if (scr_arr_is_dense(a) && scr_arr_is_dense(src) && scr_arr_open_head(a, add)) { /* A self-spread reads the original values behind the opened room. */ scr_arr_copy_dense(a, 0, src, src == a ? add : 0, add, false, true); @@ -2257,6 +2504,15 @@ double scr_arr_unshift_spread(ScrArr *a, const ScrArr *src) { ScrArr *scr_arr_reverse(ScrArr *a) { size_t len = a->len; + if (!scr_arr_has_states(a)) { + for (size_t i = 0; i < len / 2; i++) { + size_t j = len - i - 1; + uint64_t slot = scr_arr_dense_get(a, i); + scr_arr_dense_put(a, i, scr_arr_dense_get(a, j)); + scr_arr_dense_put(a, j, slot); + } + return scr_arr_retain(a); + } if (scr_arr_is_dense(a)) { /* A hole-free array stays hole-free; any other prefix is recomputed. */ if (a->filled != len) scr_arr_cut(a, 0); @@ -2292,6 +2548,13 @@ uint8_t scr_arr_pop_state(ScrArr *a, uint64_t *slot_out) { if (slot_out) *slot_out = 0; if (a->len == 0) return SCR_ARR_HOLE; size_t idx = a->len - 1; + if (!scr_arr_has_states(a)) { + if (slot_out) *slot_out = scr_arr_dense_get(a, idx); + scr_arr_dense_put(a, idx, 0); + scr_arr_cut(a, idx); + a->len = (uint32_t)idx; + return SCR_ARR_VALUE; + } uint64_t slot = 0; uint8_t state = SCR_ARR_HOLE; if (!scr_arr_take_state(a, idx, &slot, &state)) state = SCR_ARR_HOLE; @@ -2327,7 +2590,7 @@ uint8_t scr_arr_shift_state(ScrArr *a, uint64_t *slot_out) { if (a->len == 0) return SCR_ARR_HOLE; size_t old_len = a->len; if (scr_arr_is_dense(a)) { - uint8_t state = *scr_arr_state_ptr(a, 0); + uint8_t state = scr_arr_dense_state(a, 0); if (slot_out && state == SCR_ARR_VALUE) *slot_out = scr_arr_dense_get(a, 0); /* The first slot becomes head room; the tail stays where it is. */ if (scr_arr_drop_front(a, 1)) return state; @@ -2395,16 +2658,18 @@ ScrArr *scr_arr_splice(ScrArr *a, double start, double deleteCount) { * otherwise the range may be mostly holes, so the capacity is a hint. */ size_t hint = scr_arr_is_dense(a) || n <= SCR_ARR_DENSE_LIMIT ? n : SCR_ARR_DENSE_LIMIT; ScrArr *out = - a->elem == SCR_ELEM_REF + scr_arr_has_ops(a) ? scr_arr_new_ops(scr_arr_ops(a), hint ? hint : 1) : scr_arr_new(a->elem, hint ? hint : 1); - out->len = n; size_t old_len = a->len; if (scr_arr_is_dense(a)) { if (n) { + /* The removed elements keep their states unless all are values. */ + if (!scr_arr_dense_run_values(a, from, n)) scr_arr_add_states(out); memcpy(out->data, scr_arr_dense_at(a, from), n * scr_arr_slot_width(a)); - memcpy(scr_arr_state_run(out, 0, n), scr_arr_state_run(a, from, n), n); + if (scr_arr_has_states(out)) memcpy(scr_arr_state_run(out, 0, n), scr_arr_state_run(a, from, n), n); } + out->len = n; scr_arr_refill(out); /* A removed prefix becomes head room. */ if (from == 0 && scr_arr_drop_front(a, n)) return out; @@ -2418,6 +2683,8 @@ ScrArr *scr_arr_splice(ScrArr *a, double start, double deleteCount) { else scr_arr_refill(a); return out; } + scr_arr_add_states(out); + out->len = n; ScrArrStorage old = scr_arr_take_storage(a); a->len = 0; for (size_t i = 0; i < old.cap; i++) { @@ -2475,12 +2742,17 @@ ScrArr *scr_arr_splice_insert(ScrArr *a, double start, double deleteCount, * is needed only by direct self-spread runtime callers. */ ScrArr *snapshot = items == a ? scr_arr_slice(a, 0, INFINITY) : NULL; if (snapshot) items = snapshot; - ScrArr *removed = a->elem == SCR_ELEM_REF + /* Holes and present undefined among the items become present + * undefined: the receiver needs states, before its elements move. */ + if (!scr_arr_dense_run_values(items, 0, add)) scr_arr_need_states(a); + ScrArr *removed = scr_arr_has_ops(a) ? scr_arr_new_ops(scr_arr_ops(a), n) : scr_arr_new(a->elem, n); if (n) { + if (!scr_arr_dense_run_values(a, from, n)) scr_arr_add_states(removed); memcpy(removed->data, scr_arr_dense_at(a, from), n * scr_arr_slot_width(a)); - memcpy(scr_arr_state_run(removed, 0, n), scr_arr_state_run(a, from, n), n); + if (scr_arr_has_states(removed)) + memcpy(scr_arr_state_run(removed, 0, n), scr_arr_state_run(a, from, n), n); } removed->len = n; scr_arr_refill(removed); @@ -2521,7 +2793,7 @@ void scr_arr_splice_drop(ScrArr *a, double start, double deleteCount, size_t cou size_t next_len = a->len - n + count; bool refs = scr_elem_is_ref(a->elem); if (!scr_arr_is_dense(a) || !scr_arr_dense_ok(a, next_len, count)) { - ScrArr *items = a->elem == SCR_ELEM_REF + ScrArr *items = scr_arr_has_ops(a) ? scr_arr_new_ops(scr_arr_ops(a), count) : scr_arr_new(a->elem, count); scr_arr_push_many(items, count, slots); @@ -2538,9 +2810,8 @@ void scr_arr_splice_drop(ScrArr *a, double start, double deleteCount, size_t cou removed = scr_mem_alloc(n * sizeof(uint64_t)); if (!removed) scr_arr_oom(); } - const uint8_t *states = scr_arr_states_end(a); for (size_t i = from; i < from + n; i++) { - if (*scr_arr_state_in(states, i) == SCR_ARR_VALUE) removed[kept++] = a->data[i]; + if (scr_arr_dense_state(a, i) == SCR_ARR_VALUE) removed[kept++] = a->data[i]; } } size_t old_len = a->len; @@ -2555,7 +2826,7 @@ void scr_arr_splice_drop(ScrArr *a, double start, double deleteCount, size_t cou scr_arr_move_dense(a, from + count, from + n, old_len - from - n); if (count) { scr_arr_put_slots(a, from, count, slots); - memset(scr_arr_state_run(a, from, count), SCR_ARR_VALUE, count); + if (scr_arr_has_states(a)) memset(scr_arr_state_run(a, from, count), SCR_ARR_VALUE, count); } if (next_len < old_len) scr_arr_clear_dense(a, next_len, old_len - next_len); a->len = next_len; @@ -2580,13 +2851,15 @@ ScrArr *scr_arr_flat_copy(const ScrArr *a, ScrArr *out, bool flatten) { for (size_t j = 0; j < inner->len; j++) { if (scr_arr_state_at(inner, j, NULL) == SCR_ARR_HOLE) continue; if (out->len == SCR_ARR_MAX_LENGTH) scr_arr_oom(); - size_t at = out->len++; + size_t at = out->len; scr_arr_copy_index(out, at, inner, j); + out->len = (uint32_t)(at + 1); } } else { if (out->len == SCR_ARR_MAX_LENGTH) scr_arr_oom(); - size_t at = out->len++; + size_t at = out->len; scr_arr_copy_index(out, at, a, i); + out->len = (uint32_t)(at + 1); } } scr_arr_refill(out); @@ -2611,10 +2884,12 @@ static bool scr_arr_ref_eq(const ScrArr *a, uint64_t slot, void *v) { return p == v; } +#define SCR_ARR_SCAN_VALUE(states, i) (!(states) || *scr_arr_state_in((states), (i)) == SCR_ARR_VALUE) + double scr_arr_index_of_f64(ScrArr *a, double v) { - const uint8_t *states = scr_arr_states_end(a); + const uint8_t *states = scr_arr_scan_states(a); for (size_t i = 0; i < a->cap && i < a->len; i++) { - if (*scr_arr_state_in(states, i) == SCR_ARR_VALUE && scr_slot_to_f64(a->data[i]) == v) return (double)i; + if (SCR_ARR_SCAN_VALUE(states, i) && scr_slot_to_f64(a->data[i]) == v) return (double)i; } for (size_t i = 0; i < SCR_AX(a)->sparse_len; i++) { if (SCR_AX(a)->sparse[i].state == SCR_ARR_VALUE && scr_slot_to_f64(SCR_AX(a)->sparse[i].slot) == v) return (double)SCR_AX(a)->sparse[i].index; @@ -2623,9 +2898,9 @@ double scr_arr_index_of_f64(ScrArr *a, double v) { } double scr_arr_index_of_bool(ScrArr *a, bool v) { - const uint8_t *states = scr_arr_states_end(a); + const uint8_t *states = scr_arr_scan_states(a); for (size_t i = 0; i < a->cap && i < a->len; i++) { - if (*scr_arr_state_in(states, i) == SCR_ARR_VALUE && ((scr_arr_dense_get(a, i) != 0) == v)) return (double)i; + if (SCR_ARR_SCAN_VALUE(states, i) && ((scr_arr_dense_get(a, i) != 0) == v)) return (double)i; } for (size_t i = 0; i < SCR_AX(a)->sparse_len; i++) { if (SCR_AX(a)->sparse[i].state == SCR_ARR_VALUE && (SCR_AX(a)->sparse[i].slot != 0) == v) return (double)SCR_AX(a)->sparse[i].index; @@ -2634,9 +2909,9 @@ double scr_arr_index_of_bool(ScrArr *a, bool v) { } double scr_arr_index_of_ref(ScrArr *a, void *v) { - const uint8_t *states = scr_arr_states_end(a); + const uint8_t *states = scr_arr_scan_states(a); for (size_t i = 0; i < a->cap && i < a->len; i++) { - if (*scr_arr_state_in(states, i) == SCR_ARR_VALUE && scr_arr_ref_eq(a, a->data[i], v)) return (double)i; + if (SCR_ARR_SCAN_VALUE(states, i) && scr_arr_ref_eq(a, scr_arr_dense_get(a, i), v)) return (double)i; } for (size_t i = 0; i < SCR_AX(a)->sparse_len; i++) { if (SCR_AX(a)->sparse[i].state == SCR_ARR_VALUE && scr_arr_ref_eq(a, SCR_AX(a)->sparse[i].slot, v)) return (double)SCR_AX(a)->sparse[i].index; @@ -2645,9 +2920,9 @@ double scr_arr_index_of_ref(ScrArr *a, void *v) { } bool scr_arr_includes_f64(ScrArr *a, double v) { - const uint8_t *states = scr_arr_states_end(a); + const uint8_t *states = scr_arr_scan_states(a); for (size_t i = 0; i < a->cap && i < a->len; i++) { - if (*scr_arr_state_in(states, i) != SCR_ARR_VALUE) continue; + if (!SCR_ARR_SCAN_VALUE(states, i)) continue; double x = scr_slot_to_f64(a->data[i]); if (x == v || (x != x && v != v)) return true; /* SameValueZero: NaN hits */ } @@ -2667,9 +2942,9 @@ bool scr_arr_includes_ref(ScrArr *a, void *v) { if (a->elem == SCR_ELEM_REF && scr_arr_ops(a)->retain == scr_dyn_retain_v) { const ScrDyn *needle = (const ScrDyn *)v; if (needle->kind == SCR_DYN_NUM && needle->v.num != needle->v.num) { - const uint8_t *states = scr_arr_states_end(a); + const uint8_t *states = scr_arr_scan_states(a); for (size_t i = 0; i < a->cap && i < a->len; i++) { - if (*scr_arr_state_in(states, i) != SCR_ARR_VALUE) continue; + if (!SCR_ARR_SCAN_VALUE(states, i)) continue; const ScrDyn *d = (const ScrDyn *)scr_slot_to_ptr(a->data[i]); if (d->kind == SCR_DYN_NUM && d->v.num != d->v.num) return true; } @@ -2727,25 +3002,30 @@ ScrArr *scr_arr_slice(ScrArr *a, double start, double end) { * sparse side store may be mostly holes, so its capacity is a hint. */ size_t hint = to <= a->cap || n <= SCR_ARR_DENSE_LIMIT ? n : SCR_ARR_DENSE_LIMIT; ScrArr *out = - a->elem == SCR_ELEM_REF + scr_arr_has_ops(a) ? scr_arr_new_ops(scr_arr_ops(a), hint ? hint : 1) : scr_arr_new(a->elem, hint ? hint : 1); - out->len = n; - if (to <= a->cap && to <= a->filled && a->elem != SCR_ELEM_BOOL && !scr_elem_is_ref(a->elem)) { + if (to <= a->cap && to <= a->filled && scr_arr_slot_width(a) == sizeof(uint64_t) && + !scr_elem_is_ref(a->elem)) { /* Numbers below the source's hole-free prefix: values only. */ scr_arr_copy_slots(out->data, a->data + from, n); - scr_arr_set_states(scr_arr_states_end_w(out, 8) - n, SCR_ARR_VALUE, n); + out->len = (uint32_t)n; out->filled = (uint32_t)n; return out; } if (to <= a->cap) { scr_arr_copy_dense(out, 0, a, from, n, false, false); + out->len = (uint32_t)n; /* States copied from below the source's bound are present values. */ if (n > 0 && from < a->filled) out->filled = (uint32_t)((to < a->filled ? to : a->filled) - from); scr_arr_refill(out); return out; } + /* A range reaching the sparse entries: the source has states, and so + * does the copy. */ + scr_arr_add_states(out); + out->len = (uint32_t)n; const uint8_t *states = scr_arr_states_end(a); for (size_t i = 0; i < a->cap && i < to; i++) { if (i < from || *scr_arr_state_in(states, i) == SCR_ARR_HOLE) continue; @@ -2875,8 +3155,9 @@ ScrArr *scr_arr_sort_primitive(ScrArr *a, bool copy) { if (a->len == 0) return copy ? scr_arr_new(a->elem, 0) : scr_arr_retain(a); size_t dense = a->len < a->cap ? a->len : a->cap; size_t count = 0, undefined_count = 0; - const uint8_t *states = scr_arr_states_end(a); - for (size_t i = 0; i < dense; i++) { + const uint8_t *states = scr_arr_scan_states(a); + if (!states) count = dense; + for (size_t i = 0; states && i < dense; i++) { count += *scr_arr_state_in(states, i) == SCR_ARR_VALUE; undefined_count += *scr_arr_state_in(states, i) == SCR_ARR_UNDEFINED; } @@ -2889,7 +3170,7 @@ ScrArr *scr_arr_sort_primitive(ScrArr *a, bool copy) { if (count && !values) scr_arr_oom(); size_t used = 0; for (size_t i = 0; i < dense; i++) - if (*scr_arr_state_in(states, i) == SCR_ARR_VALUE) values[used++] = scr_arr_dense_get(a, i); + if (SCR_ARR_SCAN_VALUE(states, i)) values[used++] = scr_arr_dense_get(a, i); for (size_t i = 0; i < SCR_AX(a)->sparse_len; i++) if (SCR_AX(a)->sparse[i].state == SCR_ARR_VALUE) values[used++] = SCR_AX(a)->sparse[i].slot; ScrNumberSortKey *numbers = NULL; @@ -2911,8 +3192,10 @@ ScrArr *scr_arr_sort_primitive(ScrArr *a, bool copy) { } size_t present = copy ? a->len : count + undefined_count; ScrArr *out = copy ? scr_arr_new(a->elem, present) : a; - if (copy) out->len = a->len; - if (!copy && scr_arr_is_dense(a)) { + if (!copy && !states) { + /* Values only, in place. */ + if (count) scr_arr_put_slots(a, 0, count, values); + } else if (!copy && scr_arr_is_dense(a)) { if (count) scr_arr_put_slots(a, 0, count, values); scr_arr_cut(a, count); memset(scr_arr_state_run(a, 0, count), SCR_ARR_VALUE, count); @@ -2920,14 +3203,20 @@ ScrArr *scr_arr_sort_primitive(ScrArr *a, bool copy) { scr_arr_clear_dense(a, count + undefined_count, a->len - count - undefined_count); if (undefined_count) memset(scr_arr_dense_at(a, count), 0, undefined_count * scr_arr_slot_width(a)); + } else if (copy) { + /* The values, then present undefined for every other index. */ + for (size_t i = 0; i < count; i++) values[i] = scr_elem_retain_slot(a, values[i]); + scr_arr_push_many(out, count, values); + for (size_t i = count; i < present; i++) { + scr_arr_store_state_owned(out, i, 0, SCR_ARR_UNDEFINED); + out->len = (uint32_t)(i + 1); + } } else { - ScrArrStorage old = {0}; - if (!copy) old = scr_arr_take_storage(a); - for (size_t i = 0; i < count; i++) - scr_arr_store_owned(out, i, copy ? scr_elem_retain_slot(a, values[i]) : values[i]); + ScrArrStorage old = scr_arr_take_storage(a); + for (size_t i = 0; i < count; i++) scr_arr_store_owned(out, i, values[i]); for (size_t i = count; i < present; i++) scr_arr_store_state_owned(out, i, 0, SCR_ARR_UNDEFINED); - if (!copy) scr_arr_free_storage(&old); + scr_arr_free_storage(&old); } free(values); scr_arr_refill(out); @@ -3024,14 +3313,14 @@ static ScrSortCompare scr_sort_compare_for(const ScrArr *a, ScrClosure *f, uint3 bool multi = order >= 2; if (order != 0 && (arity != 2 || (order != 1 && order != -1 && !scr_sort_keys_valid(order)) || - (c.numbers ? key != NULL || multi : a->elem != SCR_ELEM_REF || key == NULL))) + (c.numbers ? key != NULL || multi : !scr_arr_has_ops(a) || key == NULL))) scr_trap("scriptc: invalid keyed sort\n"); if (!c.numbers) { c.borrowing = f->fn_borrowed != NULL; if (a->elem == SCR_ELEM_STR) c.retain = scr_sort_retain_str; else if (a->elem == SCR_ELEM_ARR) c.retain = scr_sort_retain_arr; else if (a->elem == SCR_ELEM_BYTES) c.retain = scr_sort_retain_bytes; - else if (a->elem == SCR_ELEM_REF) c.retain = scr_arr_ops(a)->retain; + else if (scr_arr_has_ops(a)) c.retain = scr_arr_ops(a)->retain; else scr_trap("scriptc: invalid comparator sort element kind\n"); } return c; @@ -4606,7 +4895,7 @@ void scr_arr_sort_values(ScrArr *a, double count, ScrClosure *f, uint32_t arity, * holes, no storage-level undefined and no sparse tail. */ static bool scr_arr_dense_values(const ScrArr *a) { if (!scr_arr_is_dense(a)) return false; - if (a->filled == a->len) return true; + if (a->filled == a->len || !scr_arr_has_states(a)) return true; const uint8_t *states = scr_arr_states_end(a); bool all = true; for (size_t i = 0; i < a->len; i++) all &= *scr_arr_state_in(states, i) == SCR_ARR_VALUE; @@ -4619,7 +4908,7 @@ static bool scr_arr_dense_values(const ScrArr *a) { * elements (stored in 1-byte slots). The slots are borrowed and stay valid * while nothing writes the array. */ const uint64_t *scr_arr_dense_slots(const ScrArr *a, size_t *len) { - if (a->len == 0 || a->elem == SCR_ELEM_BOOL || !scr_arr_dense_values(a)) return NULL; + if (a->len == 0 || scr_arr_slot_width(a) != sizeof(uint64_t) || !scr_arr_dense_values(a)) return NULL; *len = a->len; return a->data; } @@ -4646,7 +4935,9 @@ bool scr_arr_sort_dense(ScrArr *a, ScrClosure *f, uint32_t arity, bool owned, in ScrClosure *key) { uint8_t elem = a->elem; const ScrArrOps *ops = scr_arr_ops(a); - if (a->rc == SIZE_MAX || !scr_arr_dense_values(a)) return false; + /* Compact references sort through the snapshot path, which reads and + * writes 8-byte slots. */ + if (a->rc == SIZE_MAX || elem == SCR_ELEM_CREF || !scr_arr_dense_values(a)) return false; size_t n = a->len; if (n < 2) return true; if (n > SIZE_MAX / 2 / sizeof(uint64_t)) scr_arr_oom(); @@ -4683,16 +4974,16 @@ bool scr_arr_sort_dense(ScrArr *a, ScrClosure *f, uint32_t arity, bool owned, in } else if (a->len >= n && a->cap >= n) { if (!retained) { memcpy(a->data, src, n * sizeof(*src)); - memset(scr_arr_state_run(a, 0, n), SCR_ARR_VALUE, n); + if (scr_arr_has_states(a)) memset(scr_arr_state_run(a, 0, n), SCR_ARR_VALUE, n); } else { /* Publish each new edge before releasing the value it replaces: a * release can collect cycles. The buffer still holds the slots not * yet written. */ for (size_t i = 0; i < n; i++) { - bool held = *scr_arr_state_ptr(a, i) == SCR_ARR_VALUE; + bool held = scr_arr_dense_state(a, i) == SCR_ARR_VALUE; uint64_t old = held ? a->data[i] : 0; a->data[i] = src[i]; - *scr_arr_state_ptr(a, i) = SCR_ARR_VALUE; + if (scr_arr_has_states(a)) *scr_arr_state_ptr(a, i) = SCR_ARR_VALUE; if (held) scr_elem_release(a, old); } } @@ -4787,6 +5078,7 @@ ScrStr *scr_arr_join(ScrArr *a, ScrStr *sep) { case SCR_ELEM_ARR: case SCR_ELEM_BYTES: case SCR_ELEM_REF: + case SCR_ELEM_CREF: /* The compiler rejects join on ref-element arrays (SC1090). */ scr_trap("scriptc: internal error: join on a ref-element array\n"); } diff --git a/packages/runtime/src/scr_array.h b/packages/runtime/src/scr_array.h index d08b94c14..042636ca4 100644 --- a/packages/runtime/src/scr_array.h +++ b/packages/runtime/src/scr_array.h @@ -43,6 +43,11 @@ typedef enum { * constant descriptor per element type, stored once per array; every * array is still monomorphic (one element type, one set of entry points). */ SCR_ELEM_REF, + /* An SCR_ELEM_REF type whose elements are compact class instances in the + * program-lifetime region (SCR_ARR_OPS_COMPACT): 4-byte slots holding the + * address over 8, 0 for NULL. Compact instances are never counted or + * traced, so these arrays retain, release and trace nothing. */ + SCR_ELEM_CREF, } ScrElemKind; typedef enum { @@ -63,8 +68,43 @@ typedef struct ScrArrOps { /* Registry id (scr_arr_ops_table), 0 until scr_arr_ops_register assigns * it on the first array of the type. Descriptors are writable for it. */ uint32_t id; + /* SCR_ARR_OPS_*. On 64-bit targets the field takes the struct's former + * tail padding, so descriptors emitted without it read 0 here; on 32-bit + * targets it lies past their end and is never read (scr_arr_ops_compact). */ + uint32_t flags; } ScrArrOps; +/* The elements are compact class instances in the program-lifetime region: + * arrays of the type are SCR_ELEM_CREF (llvm/shapes.ts arrOps). */ +#define SCR_ARR_OPS_COMPACT 1u + +/* Whether `ops` describes compact class elements. Compact instances exist + * only on 64-bit targets. */ +static inline bool scr_arr_ops_compact(const ScrArrOps *ops) { +#if UINTPTR_MAX > 0xffffffffu + return (ops->flags & SCR_ARR_OPS_COMPACT) != 0; +#else + (void)ops; + return false; +#endif +} + +/* `release` does nothing: the element type's instances live until the + * process exits (llvm/shapes.ts arrOps). Destroying such an array frees only + * its storage. */ +#define SCR_ARR_OPS_RELEASE_NOTHING 2u + +/* Whether `ops` has SCR_ARR_OPS_RELEASE_NOTHING. 32-bit descriptors end + * before the flags word, so they never have it. */ +static inline bool scr_arr_ops_release_nothing_flag(const ScrArrOps *ops) { +#if UINTPTR_MAX > 0xffffffffu + return (ops->flags & SCR_ARR_OPS_RELEASE_NOTHING) != 0; +#else + (void)ops; + return false; +#endif +} + typedef struct ScrArr { size_t rc; /* SIZE_MAX = immortal (unused for arrays; kept per convention) */ /* Length and dense capacity are at most SCR_ARR_MAX_LENGTH (2^32 - 1); @@ -82,9 +122,9 @@ typedef struct ScrArr { * header. Kept beside `elem` so the RC fast paths test it with one load. */ uint8_t cyc; /* The low SCR_ARR_OPS_SHIFT bits: storage flags (SCR_ARR_INLINE_SLOTS, - * SCR_ARR_HEAD_ROOM, SCR_ARR_UNSHIFTED, SCR_ARR_HAS_EXT). The rest: the + * SCR_ARR_HEAD_ROOM, SCR_ARR_UNSHIFTED, SCR_ARR_HAS_EXT, SCR_ARR_STATES). The rest: the * registry id of the element type's ops (scr_arr_ops), 0 for every kind - * but SCR_ELEM_REF. */ + * but SCR_ELEM_REF and SCR_ELEM_CREF. */ uint16_t spare; /* A lower bound on the hole-free prefix: filled <= len, filled <= cap, * and every dense state below it is SCR_ARR_VALUE. Element reads below @@ -93,10 +133,13 @@ typedef struct ScrArr { * undefined) or move states below it lowers it first (scr_arr_cut); * 0 is always valid. */ uint32_t filled; - /* Dense values: `cap` 8-byte slots, or `cap` bytes for SCR_ELEM_BOOL - * (scr_arr_slot_width), followed in the same allocation by one state byte - * per slot in reverse slot order (scr_arr_states_end). Sparse entries and properties keep 8-byte - * slots for every kind; a bool slot is 0 or 1 wherever it lives. Rarely + /* Dense values: `cap` 8-byte slots, `cap` bytes for SCR_ELEM_BOOL or + * `cap` 4-byte slots for SCR_ELEM_CREF (scr_arr_slot_width), followed in + * the same allocation, when the array has states (SCR_ARR_STATES), by one + * state byte per slot in reverse slot order (scr_arr_states_end). Sparse + * entries and properties keep 8-byte slots for every kind; a bool slot is + * 0 or 1 wherever it lives, and a CREF slot's 8-byte form is the pointer + * (scr_arr_dense_get). Rarely * used storage (sparse indices, noncanonical numeric properties, * match-result metadata) lives out of line, and an array that has it * (SCR_ARR_HAS_EXT) keeps a pointer to it in the word before the dense @@ -124,14 +167,17 @@ typedef struct ScrArrExt { /* The LLVM backend mirrors ScrArr as %ScrArr: its inline retain/release read * `cyc` (field 4, i8) to decide mark-live / candidate buffering exactly like * scr_arr_retain and scr_arr_release; its inline element access uses len and - * cap (fields 1 and 2, i32), filled (field 6, i32) and data (field 7), and - * finds the state of slot i at data + cap * (slot width + 1) - 1 - i. */ + * cap (fields 1 and 2, i32), spare (field 5, i16, for SCR_ARR_STATES), + * filled (field 6, i32) and data (field 7), and finds the state of slot i + * of an array with states at data + cap * (slot width + 1) - 1 - i. */ _Static_assert(offsetof(ScrArr, len) == sizeof(size_t) && sizeof(((ScrArr *)0)->len) == 4, "emitted length reads load ScrArr.len as %ScrArr field 1, an i32"); _Static_assert(offsetof(ScrArr, cap) == sizeof(size_t) + 4 && sizeof(((ScrArr *)0)->cap) == 4, "emitted capacity reads load ScrArr.cap as %ScrArr field 2, an i32"); _Static_assert(offsetof(ScrArr, cyc) == sizeof(size_t) + 9, "inline RC fast paths read ScrArr.cyc as %ScrArr field 4"); +_Static_assert(offsetof(ScrArr, spare) == sizeof(size_t) + 10, + "inline element access reads ScrArr.spare as %ScrArr field 5"); _Static_assert(offsetof(ScrArr, filled) == sizeof(size_t) + 12, "inline element access reads ScrArr.filled as %ScrArr field 6"); _Static_assert(offsetof(ScrArr, data) == sizeof(size_t) + 16, @@ -145,11 +191,21 @@ _Static_assert(sizeof(ScrArr) == sizeof(size_t) + 16 + sizeof(void *), * count. Unshifted: an unshift had to move every element. Has ext: the word * before the dense allocation (head room included) points at the array's * ScrArrExt; such an array always has an allocation of its own, without - * inline slots. */ + * inline slots. States: the dense slots carry state bytes (see below). */ #define SCR_ARR_INLINE_SLOTS 1u #define SCR_ARR_HEAD_ROOM 2u #define SCR_ARR_UNSHIFTED 4u #define SCR_ARR_HAS_EXT 8u +#define SCR_ARR_STATES 16u + +/* An array starts without state bytes. Without them, every index below + * `len` is a present value in dense storage: len <= cap, there are no + * sparse entries, and `filled` equals `len` whenever emitted code can read + * the array (its inline reads load a state only at or past `filled`). The + * first hole or present `undefined` below the length, + * a length set past the elements, or a sparse entry gives the array its + * states (scr_arr_add_states), which it keeps. */ +static inline bool scr_arr_has_states(const ScrArr *a) { return (a->spare & SCR_ARR_STATES) != 0; } /* The start of the dense slots' allocation: `data` less any head room. */ static inline uint64_t *scr_arr_block(const ScrArr *a) { @@ -173,9 +229,12 @@ static inline struct ScrArrExt *scr_arr_ext_of(const ScrArr *a) { * Id 0 is no ops; ids are assigned on each descriptor's first array, in * any thread. A program with more element types than the field holds keeps * the ops of the rest in the array's ext (SCR_ARR_OPS_OVERFLOW). */ -#define SCR_ARR_OPS_SHIFT 4 +#define SCR_ARR_OPS_SHIFT 5 #define SCR_ARR_OPS_OVERFLOW (UINT16_MAX >> SCR_ARR_OPS_SHIFT) extern const ScrArrOps *scr_arr_ops_table[SCR_ARR_OPS_OVERFLOW]; +/* By registry id: 1 when the descriptor has SCR_ARR_OPS_RELEASE_NOTHING. + * Written before the id is published; the overflow id stays 0. */ +extern uint8_t scr_arr_ops_release_nothing[SCR_ARR_OPS_OVERFLOW + 1]; /* Assigns the id on a descriptor's first array; out of line, so the id * load in scr_arr_ops_id stays the only cost on later arrays. */ __attribute__((cold, noinline)) uint32_t scr_arr_ops_register(ScrArrOps *ops); @@ -190,24 +249,33 @@ static inline uint32_t scr_arr_ops_id(const ScrArrOps *ops) { /* The element ops of an array whose ops have no registry id. */ const ScrArrOps *scr_arr_ops_overflow(const ScrArr *a); -/* The element ops of `a`: NULL for every kind but SCR_ELEM_REF. */ +/* The element ops of `a`: NULL for every kind but SCR_ELEM_REF and + * SCR_ELEM_CREF. */ static inline const ScrArrOps *scr_arr_ops(const ScrArr *a) { uint32_t id = (uint32_t)a->spare >> SCR_ARR_OPS_SHIFT; if (__builtin_expect(id == SCR_ARR_OPS_OVERFLOW, 0)) return scr_arr_ops_overflow(a); return scr_arr_ops_table[id]; } -/* Bytes per dense value slot. */ -static inline size_t scr_arr_slot_width(const ScrArr *a) { - return a->elem == SCR_ELEM_BOOL ? 1 : sizeof(uint64_t); +/* Bytes per dense value slot of element kind `elem`. */ +static inline size_t scr_elem_slot_width(uint8_t elem) { + if (elem == SCR_ELEM_BOOL) return 1; + if (__builtin_expect(elem == SCR_ELEM_CREF, 0)) return sizeof(uint32_t); + return sizeof(uint64_t); } -/* The dense states, one byte per slot, share the values' allocation (inline - * slots included). They follow the `cap` value slots in reverse slot order: - * the state of slot i is the byte i + 1 before scr_arr_states_end(a). Removing - * slots from the front (head room: `data` advances, `cap` drops) leaves every - * remaining state at its address. The address is computed on integers, so a - * NULL `data` stays NULL. */ +/* Bytes per dense value slot. */ +static inline size_t scr_arr_slot_width(const ScrArr *a) { + return scr_elem_slot_width(a->elem); +} + +/* The dense states of an array with states, one byte per slot, share the + * values' allocation (inline slots included). They follow the `cap` value + * slots in reverse slot order: the state of slot i is the byte i + 1 before + * scr_arr_states_end(a). Removing slots from the front (head room: `data` + * advances, `cap` drops) leaves every remaining state at its address. The + * address is computed on integers, so a NULL `data` stays NULL. Arrays + * without states have no bytes there. */ static inline uint8_t *scr_arr_states_end(const ScrArr *a) { return (uint8_t *)((uintptr_t)a->data + (uintptr_t)a->cap * (scr_arr_slot_width(a) + 1)); } @@ -233,14 +301,42 @@ static inline uint8_t *scr_arr_state_run(const ScrArr *a, size_t from, size_t co return scr_arr_states_end(a) - from - count; } +/* The state of dense slot `index` (< cap), with or without state bytes. */ +static inline uint8_t scr_arr_dense_state(const ScrArr *a, size_t index) { + if (!scr_arr_has_states(a)) return index < a->len ? SCR_ARR_VALUE : SCR_ARR_HOLE; + return *scr_arr_state_ptr(a, index); +} + +/* The dense states of `a` for a scan (scr_arr_state_in), or NULL when it + * has none: every index below its length is then a value. */ +static inline const uint8_t *scr_arr_scan_states(const ScrArr *a) { + return scr_arr_has_states(a) ? scr_arr_states_end(a) : NULL; +} + +/* Give `a` state bytes: present values below the length, holes above it. + * May move the dense slots. */ +void scr_arr_add_states(ScrArr *a); + +static inline void scr_arr_need_states(ScrArr *a) { + if (!scr_arr_has_states(a)) scr_arr_add_states(a); +} +/* A CREF slot's pointer, and the slot of a pointer (NULL or a compact + * instance below 32 GiB). */ +static inline uint64_t scr_cref_decode(uint32_t ref) { return (uint64_t)ref << 3; } +static inline uint32_t scr_cref_encode(uint64_t slot) { return (uint32_t)(slot >> 3); } + /* The dense value at `index` (< cap) as an 8-byte slot, and its store. */ static inline uint64_t scr_arr_dense_get(const ScrArr *a, size_t index) { if (a->elem == SCR_ELEM_BOOL) return ((const uint8_t *)a->data)[index]; + if (__builtin_expect(a->elem == SCR_ELEM_CREF, 0)) + return scr_cref_decode(((const uint32_t *)a->data)[index]); return a->data[index]; } static inline void scr_arr_dense_put(ScrArr *a, size_t index, uint64_t slot) { if (a->elem == SCR_ELEM_BOOL) ((uint8_t *)a->data)[index] = (uint8_t)slot; + else if (__builtin_expect(a->elem == SCR_ELEM_CREF, 0)) + ((uint32_t *)a->data)[index] = scr_cref_encode(slot); else a->data[index] = slot; } @@ -270,7 +366,8 @@ static inline size_t scr_arr_value_run(const uint8_t *states_end, size_t f, size static inline void scr_arr_refill(ScrArr *a) { size_t end = a->len < a->cap ? a->len : a->cap; size_t f = a->filled; - if (f < end) f = scr_arr_value_run(scr_arr_states_end(a), f, end); + if (!scr_arr_has_states(a)) f = end; + else if (f < end) f = scr_arr_value_run(scr_arr_states_end(a), f, end); a->filled = (uint32_t)f; } @@ -302,8 +399,9 @@ ScrArr *scr_arr_new_ops(const ScrArrOps *ops, size_t initial_cap); ScrArr *scr_arr_new_small(ScrElemKind elem); ScrArr *scr_arr_new_ops_small(const ScrArrOps *ops); /* scr_arr_new(elem, cap) for a known final length: the `cap` slots share - * the array's own block (one allocation). Returns +1. */ -ScrArr *scr_arr_new_inline(ScrElemKind elem, size_t cap); + * the array's own block (one allocation). With `states`, the array starts + * with states (for holes or present undefined). Returns +1. */ +ScrArr *scr_arr_new_inline(ScrElemKind elem, size_t cap, bool states); static inline ScrArr *scr_arr_retain(ScrArr *a) { if (a->rc != SIZE_MAX) { diff --git a/packages/runtime/src/scr_async.c b/packages/runtime/src/scr_async.c index db1e54295..9e3365fbe 100644 --- a/packages/runtime/src/scr_async.c +++ b/packages/runtime/src/scr_async.c @@ -623,6 +623,10 @@ struct ScrFiber { * awaiter destroys the record when it takes the result. */ bool direct; struct ScrFiber *direct_awaiter; + /* While an async body runs its synchronous prefix (until its first await + * or its end), the AsyncLocalStorage slot of the execution that spawned + * it; NULL afterwards (scr_als_prefix_end). */ + ScrAlsCtx **prefix_slot; #ifdef SCR_ASAN_FIBERS void *fake_stack; /* Live stackless async fibers (scr_async_spawn_stackless) form a list @@ -670,6 +674,61 @@ void scr_als_ctx_release(ScrAlsCtx *c) { free(c); } +/* enterWith on the main stack lasts until that code returns to the loop, + * so the store does not reach callbacks scheduled without it: the loop + * clears the main slot when the main module's body returns, and an + * enterWith inside a callback the loop runs puts a tick that clears it at + * the front of the tick queue, so it runs as soon as that callback + * returns. A store that an async callee's prefix or a generator step + * enters becomes the caller's at scr_als_prefix_end and is cleared the + * same way. */ +static SCR_TL bool scr_loop_started = false; + +static void scr_als_main_clear(void) { + scr_als_ctx_release(scr_als_main_slot); + scr_als_main_slot = NULL; +} + +static void scr_next_tick_raw_first(void (*fn)(void)); + +/* A new store on the main slot: one a loop callback enters ends with it. */ +static void scr_als_main_entered(void) { + if (scr_loop_started) scr_next_tick_raw_first(scr_als_main_clear); +} + +void scr_als_entered_with(void) { + if (SCR_ALS_SLOT() == &scr_als_main_slot) scr_als_main_entered(); +} + +/* The end of an async body's synchronous prefix: its first await, or its + * end. Node runs that prefix inside the caller's execution, so a store it + * entered (enterWith) is still the caller's store after the call; the body + * keeps its own copy of the context for what runs after its await. */ +static void scr_als_prefix_end(ScrFiber *f) { + ScrAlsCtx **slot = f->prefix_slot; + if (slot == NULL) return; + f->prefix_slot = NULL; + if (*slot != f->als) { + scr_als_ctx_release(*slot); + *slot = scr_als_ctx_retain(f->als); + if (f->als != NULL && slot == &scr_als_main_slot) scr_als_main_entered(); + } +} + +/* A synchronous generator has no context of its own: each step runs in its + * resumer's execution, as Node runs it. A fiber-backed one switches to its + * own slot, so its step starts from the resumer's store and a store it + * enters is the resumer's after the step (scr_als_prefix_end on the way + * back); a stackless one runs in the resumer's slot (scr_gen_coro_hop). */ +static void scr_als_step_begin(ScrFiber *f) { + ScrAlsCtx **slot = SCR_ALS_SLOT(); + if (f->als != *slot) { + scr_als_ctx_release(f->als); + f->als = scr_als_ctx_retain(*slot); + } + f->prefix_slot = slot; +} + /* The lifetime region a new async fiber carries (ScrFiber.region). */ static inline void *scr_fiber_region_capture(void) { const ScrRgnFiberHooks *regions = atomic_load_explicit(&scr_region_fiber_hooks, memory_order_relaxed); @@ -726,26 +785,6 @@ ScrDyn *scr_als_peek(double id) { return NULL; } -/* enterWith on the main stack lasts until that code returns to the loop, - * so the store does not reach callbacks scheduled without it: the loop - * clears the main slot when the main module's body returns, and an - * enterWith inside a callback the loop runs puts a tick that clears it at - * the front of the tick queue, so it runs as soon as that callback - * returns. */ -static SCR_TL bool scr_loop_started = false; - -static void scr_als_main_clear(void) { - scr_als_ctx_release(scr_als_main_slot); - scr_als_main_slot = NULL; -} - -static void scr_next_tick_raw_first(void (*fn)(void)); - -void scr_als_entered_with(void) { - if (scr_loop_started && SCR_ALS_SLOT() == &scr_als_main_slot) - scr_next_tick_raw_first(scr_als_main_clear); -} - static SCR_TL ScrCtx scr_loop_ctx; /* the main stack (scheduler home) */ static SCR_TL ScrFiber *scr_current = NULL; /* A finished fiber whose last switch went to the loop (scr_resume_fiber). */ @@ -1889,6 +1928,7 @@ static void scr_trampoline(void) { ScrFiber *self = scr_current; self->entry(self, self->argpack); scr_fiber_finish(self); + scr_als_prefix_end(self); /* The loop reaps the fiber that comes back to it finished, which need * not be the one it resumed: a fiber that continued in place for the * awaiters it parked (scr_await_yield) returns to the loop too. */ @@ -2010,6 +2050,7 @@ static ScrPromise *scr_async_spawn_impl(void (*entry)(ScrFiber *, void *), void /* AsyncLocalStorage: the child runs in the SPAWNER's context (Node's * init-time capture); snapshots are immutable, so a retain suffices. */ f->als = scr_als_ctx_retain(*SCR_ALS_SLOT()); + f->prefix_slot = SCR_ALS_SLOT(); f->region = scr_fiber_region_capture(); scr_fibers_live++; @@ -2023,13 +2064,15 @@ static ScrPromise *scr_async_spawn_impl(void (*entry)(ScrFiber *, void *), void #elif defined(__wasi__) (void)awaiter; ScrFiber *spawner = scr_current; + ScrAlsCtx **spawner_slot = scr_als_active; scr_current = f; scr_exc_swap_cell(&f->exc); scr_als_active = &f->als; entry(f, argpack); /* eager prefix; returns at suspend/final suspend */ + scr_als_prefix_end(f); scr_current = spawner; scr_exc_swap_cell(spawner ? &spawner->exc : NULL); - scr_als_active = spawner ? &spawner->als : &scr_als_main_slot; + scr_als_active = spawner_slot; ScrPromise *result = scr_promise_retain(f->promise); if (f->done) { scr_promise_release(f->promise); @@ -2057,6 +2100,7 @@ static ScrPromise *scr_async_spawn_impl(void (*entry)(ScrFiber *, void *), void #endif f->return_to = home; ScrFiber *spawner = scr_current; + ScrAlsCtx **spawner_slot = scr_als_active; scr_switch(home, &f->ctx, f); /* back: the fiber suspended or finished. The switch back targeted NULL * (the child doesn't know who spawned it), which pointed both the current @@ -2066,7 +2110,7 @@ static ScrPromise *scr_async_spawn_impl(void (*entry)(ScrFiber *, void *), void * `undefined` rejection while the real payload leaks). */ scr_current = spawner; scr_exc_swap_cell(spawner ? &spawner->exc : NULL); - scr_als_active = spawner ? &spawner->als : &scr_als_main_slot; + scr_als_active = spawner_slot; if (awaited != NULL) { /* Parked by the child: the loop owns (and may have reaped) it. */ if (awaiter->await_parked) return awaited; @@ -2172,6 +2216,7 @@ static ScrFiber *scr_spawn_stackless_fiber(void (*entry)(ScrFiber *, void *), vo scr_fiber_track(f); f->stackless = true; f->als = scr_als_ctx_retain(*SCR_ALS_SLOT()); + f->prefix_slot = SCR_ALS_SLOT(); /* The lifetime region the eager prefix runs in, which every later step * resumes in (scr_resume_fiber), as a fiber's body does. */ f->region = scr_fiber_region_capture(); @@ -2183,6 +2228,7 @@ static ScrFiber *scr_spawn_stackless_fiber(void (*entry)(ScrFiber *, void *), vo scr_stackless_fibers = f; #endif ScrFiber *spawner = scr_current; + ScrAlsCtx **spawner_slot = scr_als_active; #ifndef _WIN32 uintptr_t guard = scr_stack_guard; if (guard != 0 && (uintptr_t)__builtin_frame_address(0) < guard + SCR_STACKLESS_PREFIX_ROOM) { @@ -2195,9 +2241,10 @@ static ScrFiber *scr_spawn_stackless_fiber(void (*entry)(ScrFiber *, void *), vo scr_als_active = &f->als; entry(f, argpack); /* the eager prefix: returns at a suspension or the end */ } + scr_als_prefix_end(f); scr_current = spawner; scr_exc_swap_cell(spawner ? &spawner->exc : NULL); - scr_als_active = spawner ? &spawner->als : &scr_als_main_slot; + scr_als_active = spawner_slot; return f; } @@ -2303,8 +2350,10 @@ void *scr_async_spawn_await_ref(void (*entry)(ScrFiber *, void *), void *argpack * settled promise is created and settled in the same order, rejections * enter the unhandled ledger through the same settle path, and the frame * isolates what a fresh fiber would — the Error.stack frame chain - * (cell->stack) and the AsyncLocalStorage context (enterWith inside the - * body stays inside it). The caller's exception cell is clean at any call + * (cell->stack). The AsyncLocalStorage context is the caller's throughout: + * the whole body is the synchronous prefix Node runs in the caller's + * execution, so a store it enters stays entered after the call + * (scr_als_prefix_end). The caller's exception cell is clean at any call * (try/finally stashes in-flight exceptions), so a pending exception * after the body is the body's own throw. */ static void scr_inline_park_trap(void) { @@ -2321,21 +2370,12 @@ void scr_async_inline_enter(ScrAsyncInline *frame) { ScrExcCell *cell = scr_exc_current_cell(); frame->stack = cell->stack; cell->stack = NULL; - frame->als = scr_als_ctx_retain(*SCR_ALS_SLOT()); if (scr_current != NULL) scr_current->inline_depth++; } void scr_async_inline_exit(ScrAsyncInline *frame) { if (scr_current != NULL) scr_current->inline_depth--; scr_exc_current_cell()->stack = (ScrStackFrame *)frame->stack; - ScrAlsCtx *saved = (ScrAlsCtx *)frame->als; - ScrAlsCtx **slot = SCR_ALS_SLOT(); - if (*slot != saved) { - scr_als_ctx_release(*slot); - *slot = saved; /* the frame's reference moves back in */ - } else { - scr_als_ctx_release(saved); - } } ScrPromise *scr_async_inline_leave(ScrAsyncInline *frame) { @@ -2379,11 +2419,14 @@ ScrPromise *scr_async_spawn_after(ScrPromise *dependency, * switch to its own resumer: park it here, for each such awaiter up the * chain, and switch there directly. Nothing runs in between either way. */ static ScrCtx *scr_fiber_park_awaiters(ScrFiber *self) { + scr_als_prefix_end(self); ScrCtx *to = self->return_to; #ifdef SCR_SPAWN_AWAIT for (ScrFiber *cur = self; cur->awaiter != NULL;) { ScrFiber *aw = cur->awaiter; cur->awaiter = NULL; + /* The awaiter's await is its own suspension: its prefix ends here. */ + scr_als_prefix_end(aw); scr_promise_add_waiter(cur->promise, aw); aw->await_parked = true; to = aw->return_to; @@ -5675,9 +5718,13 @@ __attribute__((always_inline)) static inline void scr_gen_coro_hop(ScrGen *g, bo if (retain) scr_gen_retain(g); g->state = SCR_GEN_RUNNING; f->resumer = scr_current; + ScrAlsCtx **resumer_slot = scr_als_active; scr_current = f; scr_exc_swap_cell(&f->exc); - scr_als_active = &f->als; + /* A synchronous generator has no AsyncLocalStorage context of its own: + * its step runs in the resumer's slot, as Node runs it in the execution + * that called next(). An async generator's step runs in its own. */ + if (g->is_async) scr_als_active = &f->als; if (f->coro == NULL) f->entry(f, f->argpack); else scr_coro_resume(f->coro); /* A running generator cannot be resumed again, so neither its fiber nor @@ -5686,7 +5733,7 @@ __attribute__((always_inline)) static inline void scr_gen_coro_hop(ScrGen *g, bo ScrFiber *me = f->resumer; scr_current = me; scr_exc_swap_cell(me != NULL ? &me->exc : NULL); - scr_als_active = me != NULL ? &me->als : &scr_als_main_slot; + scr_als_active = resumer_slot; scr_gen_switched_back(g, f, retain, true); } @@ -5708,6 +5755,7 @@ static void scr_gen_switch_in(ScrGen *g) { #endif scr_gen_retain(g); g->state = SCR_GEN_RUNNING; + if (!g->is_async) scr_als_step_begin(f); #ifdef _WIN32 ScrCtx here = scr_win_self(); #elif defined(__wasi__) @@ -5717,6 +5765,7 @@ static void scr_gen_switch_in(ScrGen *g) { #endif f->return_to = &here; ScrFiber *me = scr_current; + ScrAlsCtx **resumer_slot = scr_als_active; #ifdef __wasi__ scr_current = f; scr_exc_swap_cell(&f->exc); @@ -5725,14 +5774,17 @@ static void scr_gen_switch_in(ScrGen *g) { else scr_wasi_coro_resume(f->coro); scr_current = me; scr_exc_swap_cell(me != NULL ? &me->exc : NULL); - scr_als_active = me != NULL ? &me->als : &scr_als_main_slot; + scr_als_active = resumer_slot; #else scr_switch(&here, &f->ctx, f); - /* Back on the consumer: restore identity + the consumer's cell (the - * yield/finish switch targeted NULL — main's cell). */ + /* Back on the consumer: restore identity, the consumer's cell and its + * AsyncLocalStorage slot (the yield/finish switch targeted NULL — main's + * cell and slot). */ scr_current = me; scr_exc_swap_cell(me != NULL ? &me->exc : NULL); + scr_als_active = resumer_slot; #endif + scr_als_prefix_end(f); scr_gen_switched_back(g, f, true, false); } diff --git a/packages/runtime/src/scr_async.h b/packages/runtime/src/scr_async.h index 827c303f9..fc0128294 100644 --- a/packages/runtime/src/scr_async.h +++ b/packages/runtime/src/scr_async.h @@ -62,12 +62,14 @@ ScrPromise *scr_async_spawn_after(ScrPromise *dependency, /* Fiberless async call (native targets): the compiler proves an async body * can never park its execution context and runs it directly on the * caller's stack between enter and leave. The frame saves what a fresh - * fiber would isolate — the Error.stack frame chain and the - * AsyncLocalStorage context — and leave restores both, returning a fresh - * pending promise (+1) the caller settles from the body's outcome. */ + * fiber would isolate, the Error.stack frame chain, and leave restores it, + * returning a fresh pending promise (+1) the caller settles from the body's + * outcome. The body runs in the caller's AsyncLocalStorage context, as + * Node runs an async body's synchronous prefix. The second word is unused; + * emitted frames keep its size. */ typedef struct ScrAsyncInline { void *stack; - void *als; + void *reserved; } ScrAsyncInline; void scr_async_inline_enter(ScrAsyncInline *frame); ScrPromise *scr_async_inline_leave(ScrAsyncInline *frame); diff --git a/packages/runtime/src/scr_bytes.c b/packages/runtime/src/scr_bytes.c index 7a6a76cf9..7bcfd0cfb 100644 --- a/packages/runtime/src/scr_bytes.c +++ b/packages/runtime/src/scr_bytes.c @@ -3122,7 +3122,7 @@ static void scr_bytes_fill_from_arr(uint8_t *out, ScrBytesElem elem, const ScrAr /* Sparse tails and explicit undefined retain ordinary iteration * semantics. Numeric array slots own no conversion callbacks. */ if (index < arr->cap) { - if (*scr_arr_state_ptr(arr, index) == SCR_ARR_VALUE) + if (scr_arr_dense_state(arr, index) == SCR_ARR_VALUE) memcpy(&values[i], &arr->data[index], sizeof(double)); else values[i] = NAN; } else values[i] = scr_arr_get_number(arr, (double)index); @@ -3271,16 +3271,24 @@ double scr_bytes_index_of(const ScrBytes *b, const ScrBytes *needle, double off, } if (nlen == 0) return o > (double)len ? (double)len : o; /* '' matches at the clamp */ if (nlen > len) return -1; + /* Candidates are the positions holding the needle's first byte; only + * those compare the rest. */ + const uint8_t first = needle->data[0]; if (fwd) { size_t start = o > (double)len ? len : (size_t)o; - for (size_t i = start; i + nlen <= len; i++) { - if (memcmp(b->data + i, needle->data, nlen) == 0) return (double)i; + const uint8_t *at = b->data + start, *end = b->data + (len - nlen) + 1; + while (at < end) { + at = memchr(at, first, (size_t)(end - at)); + if (!at) return -1; + if (nlen == 1 || memcmp(at + 1, needle->data + 1, nlen - 1) == 0) return (double)(at - b->data); + at++; } return -1; } size_t start = o > (double)(len - nlen) ? len - nlen : (size_t)o; for (size_t i = start;; i--) { - if (memcmp(b->data + i, needle->data, nlen) == 0) return (double)i; + if (b->data[i] == first && (nlen == 1 || memcmp(b->data + i + 1, needle->data + 1, nlen - 1) == 0)) + return (double)i; if (i == 0) break; } return -1; diff --git a/packages/runtime/src/scr_bytes.h b/packages/runtime/src/scr_bytes.h index 9c81caea5..9b382dda5 100644 --- a/packages/runtime/src/scr_bytes.h +++ b/packages/runtime/src/scr_bytes.h @@ -397,6 +397,7 @@ ScrBytes *scr_buffer_from_bytes(const ScrBytes *src); /* a copy of any typed arr ScrBytes *scr_buffer_from_arr(const ScrArr *arr); /* number[] */ ScrBytes *scr_buffer_from_dyn_pooled(const ScrDyn *value, const ScrStr *encoding); ScrBytes *scr_buffer_from_dyn_ref_pooled(const ScrDyn *value, const ScrStr *encoding); +ScrBytes *scr_buffer_from_dyn_offset_pooled(const ScrDyn *value, const ScrDyn *second); ScrBytes *scr_buffer_concat(const ScrArr *list); ScrBytes *scr_buffer_concat_len(const ScrArr *list, double total); /* The untyped-list forms: Node's ERR_INVALID_ARG_TYPE checks on the list diff --git a/packages/runtime/src/scr_bytes_io.c b/packages/runtime/src/scr_bytes_io.c index 5532d96da..137208938 100644 --- a/packages/runtime/src/scr_bytes_io.c +++ b/packages/runtime/src/scr_bytes_io.c @@ -1299,8 +1299,48 @@ ScrBytes *scr_buffer_concat_len_dyn(const ScrDyn *list, double total) { return scr_buffer_concat_dyn_impl(list, total, true); } +/* Buffer.from(arrayBuffer, byteOffset) over a checked ArrayBuffer or + * SharedArrayBuffer, as Node's fromArrayBuffer: a Buffer from the offset to + * the end of the buffer that shares its memory. The offset converts with + * ToNumber, where a missing offset (NULL) or undefined and NaN are 0; an + * offset past the end throws ERR_BUFFER_OUT_OF_BOUNDS, and one at or below + * -1 V8's start-offset RangeError. NULL with the exception pending. */ +static ScrBytes *scr_buffer_from_storage(const ScrDyn *storage, const ScrDyn *offset_value) { + double offset = 0; + if (offset_value && offset_value->kind != SCR_DYN_UNDEF) { + if (!scr_dyn_number_coerce_js(offset_value, &offset)) return NULL; + if (isnan(offset)) offset = 0; + } + ScrBytes *bytes = storage->v.handle.ptr; + ScrBytes *owner = bytes->backing ? bytes->backing : bytes; + if ((double)scr_bytes_byte_len(owner) - offset < 0) { + static const char msg[] = "\"offset\" is outside of buffer bounds"; + scr_throw_error_msg_code(SCR_ERR_RANGE, msg, sizeof msg - 1, "ERR_BUFFER_OUT_OF_BOUNDS"); + return NULL; + } + double start = trunc(offset); + if (start < 0) { + /* The offset as JavaScript prints it (-1.5, -1e+21, -Infinity). */ + ScrStr *parts[3] = { + scr_str_new("Start offset ", 13), + scr_f64_to_scrstr(offset), + scr_str_new(" is outside the bounds of the buffer", 36), + }; + ScrStr *message = scr_str_concat_parts(parts, 3); + for (size_t i = 0; i < 3; i++) scr_str_release(parts[i]); + scr_throw_error(SCR_ERR_RANGE, message); + return NULL; + } + ScrBytes *out = scr_bytes_buffer_view(bytes, SCR_BYTES_U8, start, false, 0); + if (out) out->is_buffer = true; + return out; +} + ScrBytes *scr_buffer_from_dyn(const ScrDyn *value, const ScrStr *encoding) { if (value->kind == SCR_DYN_STR) return scr_bytes_from_str(value->v.str, encoding); + /* The second argument here is an encoding name, which as a byte offset + * converts to NaN: offset 0. */ + if (scr_buffer_storage_is(value)) return scr_buffer_from_storage(value, NULL); if (value->kind == SCR_DYN_BYTES) return scr_bytes_convert(SCR_BYTES_U8, value->v.bytes); if (value->kind == SCR_DYN_ARR) { return scr_buffer_from_array_like(value, (double)value->v.arr.len); @@ -1344,6 +1384,9 @@ ScrBytes *scr_buffer_from_dyn_pooled(const ScrDyn *value, const ScrStr *encoding if (value->kind == SCR_DYN_STR) return scr_buffer_from_str(value->v.str, encoding); if (value->kind == SCR_DYN_BYTES && !value->v.bytes->is_data_view) return scr_buffer_from_bytes(value->v.bytes); + /* A view of an ArrayBuffer shares its memory, so it never comes from the + * pool. The second argument here is an encoding name: offset 0. */ + if (scr_buffer_storage_is(value)) return scr_buffer_from_storage(value, NULL); ScrBytes *out = scr_buffer_from_dyn(value, encoding); if (!out) return NULL; out->is_buffer = true; @@ -1368,6 +1411,20 @@ ScrBytes *scr_buffer_from_dyn_ref_pooled(const ScrDyn *value, const ScrStr *enco return scr_buffer_from_dyn_pooled(value, encoding); } +/* Buffer.from(value, second) over checked values whose second argument is + * not a literal encoding name: an ArrayBuffer or SharedArrayBuffer takes it + * as the byte offset (scr_buffer_from_storage); other values convert as + * scr_buffer_from_dyn_ref_pooled with utf8. */ +ScrBytes *scr_buffer_from_dyn_offset_pooled(const ScrDyn *value, const ScrDyn *second) { + if (!scr_buffer_storage_is(value)) { + ScrStr *utf8 = scr_str_new("utf8", 4); + ScrBytes *out = scr_buffer_from_dyn_ref_pooled(value, utf8); + scr_str_release(utf8); + return out; + } + return scr_buffer_from_storage(value, second); +} + /* new Buffer(number, encoding) — the deprecated ctor's string arm with a * non-string first argument: Node's exact ERR_INVALID_ARG_TYPE (the * throwing path never fires DEP0005, so compiled silence matches). */ diff --git a/packages/runtime/src/scr_child.c b/packages/runtime/src/scr_child.c index ec685656d..df7543500 100644 --- a/packages/runtime/src/scr_child.c +++ b/packages/runtime/src/scr_child.c @@ -1105,9 +1105,9 @@ char **scr_child_argv(ScrStr *cmd, ScrArr *args) { static ScrSpawnRes *scr_spawn_sync_core(ScrStr *cmd, ScrArr *args, double timeout_ms, int killsig, int in_mode, int out_mode, - int err_mode) { + int err_mode, ScrArr *env_pairs) { ScrWinSyncRes w; - scr_win_run_sync(cmd, args, NULL, in_mode, out_mode, err_mode, NULL, NULL, + scr_win_run_sync(cmd, args, NULL, in_mode, out_mode, err_mode, NULL, env_pairs, timeout_ms, &w); if (w.spawn_errname != NULL) { free(w.out.data); @@ -1136,19 +1136,26 @@ static ScrSpawnRes *scr_spawn_sync_core(ScrStr *cmd, ScrArr *args, double timeou } ScrSpawnRes *scr_spawn_sync(ScrStr *cmd, ScrArr *args) { - return scr_spawn_sync_core(cmd, args, 0, SIGTERM, 0, 0, 0); + return scr_spawn_sync_core(cmd, args, 0, SIGTERM, 0, 0, 0, NULL); } ScrSpawnRes *scr_spawn_sync_opts(ScrStr *cmd, ScrArr *args, double timeout_ms, ScrStr *killsignal, double in_mode, double out_mode, double err_mode) { + return scr_spawn_sync_env(cmd, args, timeout_ms, killsignal, in_mode, out_mode, err_mode, + NULL); +} + +ScrSpawnRes *scr_spawn_sync_env(ScrStr *cmd, ScrArr *args, double timeout_ms, + ScrStr *killsignal, double in_mode, double out_mode, + double err_mode, ScrArr *env_pairs) { int killsig = SIGTERM; if (killsignal->len > 0) { int resolved = scr_signal_from_name(killsignal); if (resolved > 0) killsig = resolved; } return scr_spawn_sync_core(cmd, args, timeout_ms, killsig, (int)in_mode, - (int)out_mode, (int)err_mode); + (int)out_mode, (int)err_mode, env_pairs); } ScrSpawnRes *scr_spawn_sync_stdio_str(ScrStr *cmd, ScrArr *args, double timeout_ms, @@ -3101,9 +3108,61 @@ static ScrSpawnRes *scr_spawn_res_new(bool has_status, double status, * documented divergence). timeout_ms > 0 sends `killsig` at the deadline * and the result carries error: ETIMEDOUT + the signal — never a throw, * Node's spawnSync shape. */ +static char **scr_exec_envp(ScrArr *pairs); +static void scr_exec_envp_free(char **envp); + +/* posix_spawnp for the child_process spawns. Without `envp` the command + * resolves on this process's PATH over `environ`. With `envp` (a + * replacement environment) it resolves the way Node's libuv runs execvp + * in the child: a name with a '/' runs as given; otherwise each entry of + * the replacement's PATH (an empty entry is the current directory), or of + * the default path when the replacement has no PATH, is tried in order, + * and a candidate whose exec fails with ENOENT, ENOTDIR or EACCES (a + * missing file, or a script whose interpreter is missing) moves on to the + * next entry. The last such failure is EACCES if any candidate was denied, + * else ENOENT. Relative entries are resolved by the child, which starts in + * `cwd`. Returns posix_spawn's error number. */ +static int scr_spawn_command(pid_t *pid, const char *file, const posix_spawn_file_actions_t *fa, + const posix_spawnattr_t *attr, char *const *argv, + char *const *envp, const char *cwd) { + (void)cwd; /* the file actions change into it before the exec */ + if (envp == NULL) return posix_spawnp(pid, file, fa, attr, argv, environ); + if (strchr(file, '/')) return posix_spawn(pid, file, fa, attr, argv, envp); + const char *path = "/usr/bin:/bin"; + for (char *const *e = envp; *e; e++) { + if (strncmp(*e, "PATH=", 5) == 0) { + path = *e + 5; + break; + } + } + size_t file_len = strlen(file); + bool denied = false; + for (const char *dir = path;;) { + const char *end = strchr(dir, ':'); + size_t dir_len = end ? (size_t)(end - dir) : strlen(dir); + const char *prefix = dir_len ? dir : "."; + size_t prefix_len = dir_len ? dir_len : 1; + char *candidate = malloc(prefix_len + 1 + file_len + 1); + if (!candidate) scr_child_oom(); + memcpy(candidate, prefix, prefix_len); + candidate[prefix_len] = '/'; + memcpy(candidate + prefix_len + 1, file, file_len + 1); + int err = posix_spawn(pid, candidate, fa, attr, argv, envp); + free(candidate); + if (err == EACCES) denied = true; + else if (err != ENOENT && err != ENOTDIR) return err; + if (!end) break; + dir = end + 1; + } + return denied ? EACCES : ENOENT; +} + +/* env_pairs: NULL inherits the parent's environment; else [k,v,...] + * replaces it, as Node's `env` option does, and the command is looked up + * on the replacement's PATH (scr_spawn_command). */ static ScrSpawnRes *scr_spawn_sync_core(ScrStr *cmd, ScrArr *args, double timeout_ms, int killsig, int in_mode, int out_mode, - int err_mode) { + int err_mode, ScrArr *env_pairs) { if (out_mode == 2 || err_mode == 2) { /* Inherited output fds: flush the parent's buffers first so earlier * logs precede the child's writes (Node's practical ordering). */ @@ -3138,10 +3197,12 @@ static ScrSpawnRes *scr_spawn_sync_core(ScrStr *cmd, ScrArr *args, double timeou } char **argv = scr_child_argv(cmd, args); + char **envp = env_pairs != NULL ? scr_exec_envp(env_pairs) : NULL; pid_t pid = -1; - int spawn_err = posix_spawnp(&pid, cmd->data, &fa, NULL, argv, environ); + int spawn_err = scr_spawn_command(&pid, cmd->data, &fa, NULL, argv, envp, NULL); posix_spawn_file_actions_destroy(&fa); free(argv); + scr_exec_envp_free(envp); if (cap_out) close(outfd[1]); if (cap_err) close(errfd[1]); @@ -3242,7 +3303,7 @@ static ScrSpawnRes *scr_spawn_sync_core(ScrStr *cmd, ScrArr *args, double timeou } ScrSpawnRes *scr_spawn_sync(ScrStr *cmd, ScrArr *args) { - return scr_spawn_sync_core(cmd, args, 0, SIGTERM, 0, 0, 0); + return scr_spawn_sync_core(cmd, args, 0, SIGTERM, 0, 0, 0, NULL); } /* The options entry (cp.spawnSyncOpts): killSignal as a NAME ("" = the @@ -3252,13 +3313,20 @@ ScrSpawnRes *scr_spawn_sync(ScrStr *cmd, ScrArr *args) { ScrSpawnRes *scr_spawn_sync_opts(ScrStr *cmd, ScrArr *args, double timeout_ms, ScrStr *killsignal, double in_mode, double out_mode, double err_mode) { + return scr_spawn_sync_env(cmd, args, timeout_ms, killsignal, in_mode, out_mode, err_mode, + NULL); +} + +ScrSpawnRes *scr_spawn_sync_env(ScrStr *cmd, ScrArr *args, double timeout_ms, + ScrStr *killsignal, double in_mode, double out_mode, + double err_mode, ScrArr *env_pairs) { int killsig = SIGTERM; if (killsignal->len > 0) { int resolved = scr_signal_from_name(killsignal); if (resolved > 0) killsig = resolved; } return scr_spawn_sync_core(cmd, args, timeout_ms, killsig, (int)in_mode, - (int)out_mode, (int)err_mode); + (int)out_mode, (int)err_mode, env_pairs); } /* The runtime-string stdio entry (cp.spawnSyncStdioStr): the compiler @@ -3478,8 +3546,8 @@ ScrStr *scr_exec_sync_core(ScrStr *cmd, ScrArr *args, const ScrExecOpts *o) { char **argv = scr_child_argv(cmd, args); char **envp = o->env_pairs != NULL ? scr_exec_envp(o->env_pairs) : NULL; pid_t pid = -1; - int spawn_err = posix_spawnp(&pid, cmd->data, &fa, NULL, argv, - envp != NULL ? envp : environ); + int spawn_err = scr_spawn_command(&pid, cmd->data, &fa, NULL, argv, envp, + o->cwd != NULL ? o->cwd->data : NULL); posix_spawn_file_actions_destroy(&fa); free(argv); scr_exec_envp_free(envp); @@ -5037,8 +5105,8 @@ ScrChild *scr_spawn_opts(ScrStr *cmd, ScrArr *args, double in_mode, char **envp = has_env && env_pairs != NULL ? scr_exec_envp(env_pairs) : NULL; pid_t pid = -1; const char *file = shell ? "/bin/sh" : cmd->data; - int spawn_err = posix_spawnp(&pid, file, &fa, &at, argv, - envp != NULL ? envp : environ); + int spawn_err = scr_spawn_command(&pid, file, &fa, &at, argv, envp, + cwd != NULL && cwd->len > 0 ? cwd->data : NULL); posix_spawnattr_destroy(&at); posix_spawn_file_actions_destroy(&fa); if (!shell) free(argv); diff --git a/packages/runtime/src/scr_child.h b/packages/runtime/src/scr_child.h index e899130d8..a5853ad59 100644 --- a/packages/runtime/src/scr_child.h +++ b/packages/runtime/src/scr_child.h @@ -23,6 +23,11 @@ ScrSpawnRes *scr_spawn_sync(ScrStr *cmd, ScrArr *args); /* +1, never throws */ ScrSpawnRes *scr_spawn_sync_opts(ScrStr *cmd, ScrArr *args, double timeout_ms, ScrStr *killsignal, double in_mode, double out_mode, double err_mode); +/* scr_spawn_sync_opts with an `env` option: [k,v,...] pairs replace the + * child's environment (NULL inherits the parent's). */ +ScrSpawnRes *scr_spawn_sync_env(ScrStr *cmd, ScrArr *args, double timeout_ms, + ScrStr *killsignal, double in_mode, double out_mode, + double err_mode, ScrArr *env_pairs); /* The runtime-string stdio entry: the compiler proved the value is * "pipe" | "ignore" | "inherit" by type; the mode mapping happens here. */ ScrSpawnRes *scr_spawn_sync_stdio_str(ScrStr *cmd, ScrArr *args, double timeout_ms, diff --git a/packages/runtime/src/scr_cipher.c b/packages/runtime/src/scr_cipher.c index df62a79a3..00d229bad 100644 --- a/packages/runtime/src/scr_cipher.c +++ b/packages/runtime/src/scr_cipher.c @@ -9,7 +9,9 @@ * the runtime StringDecoder, which carries partial characters and base64 * groups between calls as Node's does. chacha20-poly1305 follows OpenSSL's * construction, which also accepts AAD after data. Authentication tags are - * compared in constant time. All arguments are borrowed. */ + * compared in constant time. A cipher used as a stream reads and writes + * through its own native Transform, which the stream unit builds on first + * use, as Node's LazyTransform is. All arguments are borrowed. */ #include "scr_runtime.h" #include @@ -18,16 +20,30 @@ #include "mbedtls/aes.h" #include "mbedtls/chacha20.h" +#include "mbedtls/des.h" #include "mbedtls/gcm.h" #include "mbedtls/poly1305.h" #include "mbedtls/platform_util.h" -typedef enum { SC_CBC, SC_CTR, SC_GCM, SC_CHACHA } ScCipherMode; +/* SC_CHACHA is chacha20-poly1305; SC_CHACHA20 the bare stream cipher. */ +typedef enum { + SC_CBC, + SC_CTR, + SC_GCM, + SC_CHACHA, + SC_ECB, + SC_CFB, + SC_CFB8, + SC_CFB1, + SC_OFB, + SC_CHACHA20, +} ScCipherMode; typedef struct { const char *name; ScCipherMode mode; unsigned key_len; + bool des; /* triple DES (two- or three-key) rather than AES */ } ScCipherSpec; /* Node's names for the implemented ciphers, including OpenSSL's aliases. @@ -39,6 +55,35 @@ static const ScCipherSpec sc_specs[] = { {"aes-128-gcm", SC_GCM, 16}, {"aes-192-gcm", SC_GCM, 24}, {"aes-256-gcm", SC_GCM, 32}, {"id-aes128-gcm", SC_GCM, 16}, {"id-aes192-gcm", SC_GCM, 24}, {"id-aes256-gcm", SC_GCM, 32}, {"chacha20-poly1305", SC_CHACHA, 32}, + {"aes-128-ecb", SC_ECB, 16}, {"aes-192-ecb", SC_ECB, 24}, {"aes-256-ecb", SC_ECB, 32}, + {"aes-128-cfb", SC_CFB, 16}, {"aes-192-cfb", SC_CFB, 24}, {"aes-256-cfb", SC_CFB, 32}, + {"aes-128-cfb8", SC_CFB8, 16}, {"aes-192-cfb8", SC_CFB8, 24}, {"aes-256-cfb8", SC_CFB8, 32}, + {"aes-128-cfb1", SC_CFB1, 16}, {"aes-192-cfb1", SC_CFB1, 24}, {"aes-256-cfb1", SC_CFB1, 32}, + {"aes-128-ofb", SC_OFB, 16}, {"aes-192-ofb", SC_OFB, 24}, {"aes-256-ofb", SC_OFB, 32}, + {"des-ede3-cbc", SC_CBC, 24, true}, {"des3", SC_CBC, 24, true}, + {"des-ede3", SC_ECB, 24, true}, {"des-ede3-ecb", SC_ECB, 24, true}, + {"des-ede3-cfb", SC_CFB, 24, true}, {"des-ede3-cfb8", SC_CFB8, 24, true}, + {"des-ede3-cfb1", SC_CFB1, 24, true}, {"des-ede3-ofb", SC_OFB, 24, true}, + {"des-ede-cbc", SC_CBC, 16, true}, {"des-ede", SC_ECB, 16, true}, + {"des-ede-ecb", SC_ECB, 16, true}, {"des-ede-cfb", SC_CFB, 16, true}, + {"des-ede-ofb", SC_OFB, 16, true}, + {"chacha20", SC_CHACHA20, 32}, +}; + +/* Ciphers OpenSSL 3 keeps in its legacy provider, which Node 24 does not + * load: crypto.getCipherInfo() knows them, and createCipheriv checks their + * IV length, then fails with OpenSSL's "unsupported" error. */ +static const struct { + const char *name; + unsigned iv_len; +} sc_legacy[] = { + {"des", 8}, {"des-cbc", 8}, {"des-ecb", 0}, {"des-cfb", 8}, {"des-cfb1", 8}, {"des-cfb8", 8}, + {"des-ofb", 8}, {"desx", 8}, {"desx-cbc", 8}, {"bf", 8}, {"bf-cbc", 8}, {"bf-ecb", 0}, + {"bf-cfb", 8}, {"bf-ofb", 8}, {"blowfish", 8}, {"cast", 8}, {"cast-cbc", 8}, {"cast5-cbc", 8}, + {"cast5-ecb", 0}, {"cast5-cfb", 8}, {"cast5-ofb", 8}, {"rc2", 8}, {"rc2-cbc", 8}, {"rc2-ecb", 0}, + {"rc2-cfb", 8}, {"rc2-ofb", 8}, {"rc2-40-cbc", 8}, {"rc2-64-cbc", 8}, {"rc4", 0}, {"rc4-40", 0}, + {"rc4-hmac-md5", 0}, {"seed", 16}, {"seed-cbc", 16}, {"seed-ecb", 0}, {"seed-cfb", 16}, + {"seed-ofb", 16}, {"idea", 8}, {"idea-cbc", 8}, {"idea-ecb", 0}, {"idea-cfb", 8}, {"idea-ofb", 8}, }; /* crypto.getCiphers() on Node 24.22 (OpenSSL 3.5). Names in this list that @@ -86,15 +131,21 @@ typedef struct ScCipher { ScCipherMode mode; bool decrypt; bool active; /* false after final() or a failed backend call */ - bool pad; /* CBC automatic padding */ + bool pad; /* CBC and ECB automatic padding */ + bool des; /* triple DES rather than AES */ + unsigned bs; /* the block size: 16 for AES, 8 for triple DES */ bool data_started; /* a non-empty update() ran, so non-empty AAD is refused */ int tag_len; /* SC_NO_TAG until known */ int tag_state; unsigned char tag[16]; - unsigned char block[16]; /* CBC: chaining value; CTR: counter block */ - unsigned char buf[16]; /* CBC: buffered input; CTR: keystream block */ - size_t bufsz; /* CBC: buffered bytes; CTR: keystream offset */ + unsigned char block[16]; /* CBC: chaining value; CTR: counter block; CFB, OFB: + shift register; chacha20: the IV */ + unsigned char buf[16]; /* CBC, ECB: buffered input; CTR: keystream block */ + size_t bufsz; /* CBC, ECB: buffered bytes; CTR, CFB, OFB: keystream + offset */ + uint64_t chacha_left; /* chacha20: bytes before the low counter word wraps */ mbedtls_aes_context aes; + mbedtls_des3_context des3; mbedtls_gcm_context gcm; mbedtls_chacha20_context chacha; mbedtls_poly1305_context poly; @@ -103,6 +154,12 @@ typedef struct ScCipher { bool aad_open; /* AAD was added since the last data or padding */ ScrStr *decoder; /* the StringDecoder encoding once string output starts */ double pending; /* the decoder's carried bytes */ + /* The Transform of a cipher used as a stream (+1) and its release + * (scr_stream.c). Its steps hold the cipher, so the cipher is a + * collector-headered object behind a traced handle, and the pair is + * reclaimed as a cycle. */ + void *stream; + void (*stream_release)(void *); } ScCipher; static void *sc_retain(void *h) { @@ -110,16 +167,39 @@ static void *sc_retain(void *h) { return h; } -static void sc_release(void *h) { +static void sc_trace(void *h, ScrTraceVisit visit, void *ctx) { + ScCipher *c = h; + if (c->stream) visit(c->stream, ctx); +} + +/* The collector frees the stream itself; the rest is released here. */ +static void sc_gcfree(void *h) { ScCipher *c = h; - if (--c->rc) return; mbedtls_aes_free(&c->aes); + mbedtls_des3_free(&c->des3); mbedtls_gcm_free(&c->gcm); mbedtls_chacha20_free(&c->chacha); mbedtls_poly1305_free(&c->poly); scr_str_release(c->decoder); mbedtls_platform_zeroize(c, sizeof *c); - free(c); + scr_obj_free_note(); + scr_cyc_free(c); +} + +static void sc_destroy(void *h) { + ScCipher *c = h; + void *stream = c->stream; + c->stream = NULL; + if (stream) c->stream_release(stream); + sc_gcfree(c); +} + +static void sc_release(void *h) { + ScCipher *c = h; + if (--c->rc == 0) { + scr_cyc_dead(c); + scr_rc_destroy(c, sc_destroy); + } else scr_cyc_released(c); } /* ── errors ───────────────────────────────────────────────────────────── */ @@ -154,18 +234,21 @@ static void sc_invalid_tag(unsigned long length) { /* An OpenSSL provider error as Node reports it: the formatted message plus * own opensslErrorStack, library, reason and code properties, in Node's * key order. */ -static void sc_throw_openssl(const char *packed, const char *reason, const char *code) { +/* OpenSSL's error with its library, reason and error stack; Node's + * code. */ +static void sc_throw_openssl_in(const char *packed, const char *library, const char *reason, + const char *code) { char message[128]; - snprintf(message, sizeof message, "error:%s:Provider routines::%s", packed, reason); + snprintf(message, sizeof message, "error:%s:%s::%s", packed, library, reason); ScrStr *text = scr_str_new(message, strlen(message)); ScrError *e = scr_error_new(SCR_ERR_ERROR, text); ScrDyn *stack = scr_dyn_new_arr(); scr_dyn_arr_push(stack, scr_dyn_new_str(text)); scr_str_release(text); scr_error_set_prop(e, "opensslErrorStack", 17, stack); - ScrStr *library = scr_str_new("Provider routines", 17); - scr_error_set_prop(e, "library", 7, scr_dyn_new_str(library)); - scr_str_release(library); + ScrStr *library_text = scr_str_new(library, strlen(library)); + scr_error_set_prop(e, "library", 7, scr_dyn_new_str(library_text)); + scr_str_release(library_text); ScrStr *reason_text = scr_str_new(reason, strlen(reason)); scr_error_set_prop(e, "reason", 6, scr_dyn_new_str(reason_text)); scr_str_release(reason_text); @@ -176,6 +259,10 @@ static void sc_throw_openssl(const char *packed, const char *reason, const char scr_throw_obj(e, &scr_error_retain_v, &scr_error_release_v, scr_error_trace_arg()); } +static void sc_throw_openssl(const char *packed, const char *reason, const char *code) { + sc_throw_openssl_in(packed, "Provider routines", reason, code); +} + /* ERR_INVALID_ARG_VALUE's property flavor: "The property 'options.x' is * invalid. Received ". */ static void sc_invalid_property(const char *name, const ScrDyn *value) { @@ -410,6 +497,27 @@ static const ScCipherSpec *sc_lookup(const ScrStr *name) { return NULL; } +/* The legacy-provider IV length of `name`, or -1 for other names. */ +static int sc_legacy_iv(const ScrStr *name) { + for (size_t i = 0; i < sizeof sc_legacy / sizeof sc_legacy[0]; i++) + if (sc_ascii_eq_ci(name->data, name->len, sc_legacy[i].name)) return (int)sc_legacy[i].iv_len; + return -1; +} + +/* The IV length a mode takes; SC_GCM takes any nonzero length. */ +static size_t sc_iv_length(ScCipherMode mode, bool des) { + switch (mode) { + case SC_ECB: + return 0; + case SC_CHACHA: + return 12; + case SC_CHACHA20: + return 16; + default: + return des ? 8 : 16; + } +} + static bool sc_known_name(const ScrStr *name) { for (size_t i = 0; i < sizeof sc_known / sizeof sc_known[0]; i++) if (sc_ascii_eq_ci(name->data, name->len, sc_known[i])) return true; @@ -421,9 +529,10 @@ static void sc_unsupported_cipher(const ScrStr *name) { scr_jb_init(&b); scr_jb_puts(&b, "The cipher '"); scr_jb_put_str(&b, name); - scr_jb_puts(&b, "' has no native implementation; the supported ciphers are aes-128-cbc, aes-192-cbc, " - "aes-256-cbc, aes-128-ctr, aes-192-ctr, aes-256-ctr, aes-128-gcm, aes-192-gcm, " - "aes-256-gcm and chacha20-poly1305"); + scr_jb_puts(&b, "' has no native implementation; the supported ciphers are aes-128, aes-192 and " + "aes-256 in cbc, ctr, gcm, ecb, cfb, cfb8, cfb1 and ofb modes, des-ede3 in cbc, ecb, " + "cfb, cfb8, cfb1 and ofb modes, des-ede in cbc, ecb, cfb and ofb modes, chacha20 and " + "chacha20-poly1305"); ScrStr *message = scr_jb_finish(&b); scr_throw_error_msg_code(SCR_ERR_ERROR, message->data, message->len, "SC2020"); scr_str_release(message); @@ -492,14 +601,24 @@ static ScrDyn *sc_cipher_new(bool decrypt, ScrDyn *cipher, ScrDyn *key, ScrDyn * goto done; } const ScCipherSpec *spec = sc_lookup(cipher->v.str); + size_t iv_len = iv_bytes ? iv_bytes->len : 0; if (!spec) { - if (sc_known_name(cipher->v.str)) sc_unsupported_cipher(cipher->v.str); - else sc_throw(SCR_ERR_ERROR, "ERR_CRYPTO_UNKNOWN_CIPHER", "Unknown cipher"); + int legacy_iv = sc_legacy_iv(cipher->v.str); + if (legacy_iv >= 0) { + if (iv_len != (size_t)legacy_iv || (legacy_iv > 0 && !iv_bytes)) + sc_throw(SCR_ERR_TYPE, "ERR_CRYPTO_INVALID_IV", "Invalid initialization vector"); + else + sc_throw_openssl_in("0308010C", "digital envelope routines", "unsupported", + "ERR_OSSL_EVP_UNSUPPORTED"); + } else if (sc_known_name(cipher->v.str)) { + sc_unsupported_cipher(cipher->v.str); + } else { + sc_throw(SCR_ERR_ERROR, "ERR_CRYPTO_UNKNOWN_CIPHER", "Unknown cipher"); + } goto done; } - size_t iv_len = iv_bytes ? iv_bytes->len : 0; - bool aead = spec->mode == SC_GCM || spec->mode == SC_CHACHA; - if (iv_len == 0 || (!aead && iv_len != 16) || (spec->mode == SC_CHACHA && iv_len != 12)) { + size_t expected_iv = sc_iv_length(spec->mode, spec->des); + if (spec->mode == SC_GCM ? iv_len == 0 : iv_len != expected_iv || (expected_iv > 0 && !iv_bytes)) { sc_throw(SCR_ERR_TYPE, "ERR_CRYPTO_INVALID_IV", "Invalid initialization vector"); goto done; } @@ -532,15 +651,19 @@ static ScrDyn *sc_cipher_new(bool decrypt, ScrDyn *cipher, ScrDyn *key, ScrDyn * sc_throw(SCR_ERR_RANGE, "ERR_CRYPTO_INVALID_KEYLEN", "Invalid key length"); goto done; } - ScCipher *c = calloc(1, sizeof *c); - if (!c) scr_trap("scriptc: out of memory\n"); + static ScrCycType cyc_type = {&sc_trace, &sc_gcfree, SCR_CYC_KIND_NONE, 0}; + ScCipher *c = scr_cyc_alloc(sizeof *c, &cyc_type); c->rc = 1; + scr_obj_alloc_note(); c->mode = spec->mode; c->decrypt = decrypt; c->active = true; c->pad = true; + c->des = spec->des; + c->bs = spec->des ? 8 : 16; c->tag_len = tag_len; mbedtls_aes_init(&c->aes); + mbedtls_des3_init(&c->des3); mbedtls_gcm_init(&c->gcm); mbedtls_chacha20_init(&c->chacha); mbedtls_poly1305_init(&c->poly); @@ -548,9 +671,39 @@ static ScrDyn *sc_cipher_new(bool decrypt, ScrDyn *cipher, ScrDyn *key, ScrDyn * unsigned bits = spec->key_len * 8; switch (spec->mode) { case SC_CBC: - rc = decrypt ? mbedtls_aes_setkey_dec(&c->aes, key_bytes->data, bits) - : mbedtls_aes_setkey_enc(&c->aes, key_bytes->data, bits); + case SC_ECB: + case SC_CFB: + case SC_CFB8: + case SC_CFB1: + case SC_OFB: { + /* CBC and ECB decrypt with the inverse cipher; the feedback modes run + * the forward cipher both ways. */ + bool inverse = decrypt && (spec->mode == SC_CBC || spec->mode == SC_ECB); + if (spec->des && spec->key_len == 24) + rc = inverse ? mbedtls_des3_set3key_dec(&c->des3, key_bytes->data) + : mbedtls_des3_set3key_enc(&c->des3, key_bytes->data); + else if (spec->des) + rc = inverse ? mbedtls_des3_set2key_dec(&c->des3, key_bytes->data) + : mbedtls_des3_set2key_enc(&c->des3, key_bytes->data); + else + rc = inverse ? mbedtls_aes_setkey_dec(&c->aes, key_bytes->data, bits) + : mbedtls_aes_setkey_enc(&c->aes, key_bytes->data, bits); + if (expected_iv) memcpy(c->block, iv_bytes->data, expected_iv); + break; + } + case SC_CHACHA20: + /* OpenSSL's IV is a 64-bit little-endian block counter and an 8-byte + * nonce; mbedTLS takes a 32-bit counter and a 12-byte nonce, so the + * stream restarts each time the low counter word wraps. */ memcpy(c->block, iv_bytes->data, 16); + rc = mbedtls_chacha20_setkey(&c->chacha, key_bytes->data); + if (rc == 0) { + uint32_t low = (uint32_t)c->block[0] | (uint32_t)c->block[1] << 8 | + (uint32_t)c->block[2] << 16 | (uint32_t)c->block[3] << 24; + c->chacha_left = ((uint64_t)1 << 32) - low; + c->chacha_left *= 64; + rc = mbedtls_chacha20_starts(&c->chacha, c->block + 4, low); + } break; case SC_CTR: rc = mbedtls_aes_setkey_enc(&c->aes, key_bytes->data, bits); @@ -604,39 +757,123 @@ done: /* ── the cipher transforms ────────────────────────────────────────────── */ -/* Raw CBC over whole blocks. */ +/* Raw CBC or ECB over whole blocks. */ static bool sc_cbc_blocks(ScCipher *c, const unsigned char *in, size_t len, unsigned char *out) { + if (c->mode == SC_ECB) { + for (size_t off = 0; off < len; off += c->bs) { + int rc = c->des ? mbedtls_des3_crypt_ecb(&c->des3, in + off, out + off) + : mbedtls_aes_crypt_ecb(&c->aes, c->decrypt ? MBEDTLS_AES_DECRYPT : MBEDTLS_AES_ENCRYPT, + in + off, out + off); + if (rc != 0) return false; + } + return true; + } + if (c->des) + return mbedtls_des3_crypt_cbc(&c->des3, c->decrypt ? MBEDTLS_DES_DECRYPT : MBEDTLS_DES_ENCRYPT, len, c->block, + in, out) == 0; return mbedtls_aes_crypt_cbc(&c->aes, c->decrypt ? MBEDTLS_AES_DECRYPT : MBEDTLS_AES_ENCRYPT, len, c->block, in, out) == 0; } -/* OpenSSL's ossl_cipher_generic_block_update for CBC: complete blocks - * are processed, the remainder is buffered, and a decryption that ends on - * a block boundary holds the last block back for padding removal. Returns - * the output length, or -1 when the backend fails; out has room for - * len + 16 bytes. */ +/* One forward block of the feedback modes' cipher. */ +static bool sc_forward(ScCipher *c, const unsigned char *in, unsigned char *out) { + return (c->des ? mbedtls_des3_crypt_ecb(&c->des3, in, out) + : mbedtls_aes_crypt_ecb(&c->aes, MBEDTLS_AES_ENCRYPT, in, out)) == 0; +} + +/* CFB (full-block feedback), CFB8, CFB1 and OFB, as OpenSSL's + * CRYPTO_cfb128_encrypt, CRYPTO_cfb128_8_encrypt, CRYPTO_cfb128_1_encrypt + * and CRYPTO_ofb128_encrypt: CFB and OFB keep their keystream offset across + * updates; CFB1 feeds back one bit at a time, most significant first. */ +static bool sc_feedback(ScCipher *c, const unsigned char *in, size_t len, unsigned char *out) { + unsigned char stream[16]; + size_t bs = c->bs; + for (size_t i = 0; i < len; i++) { + switch (c->mode) { + case SC_CFB: + case SC_OFB: + if (c->bufsz == 0 && !sc_forward(c, c->block, c->block)) return false; + out[i] = (unsigned char)(in[i] ^ c->block[c->bufsz]); + if (c->mode == SC_CFB) c->block[c->bufsz] = c->decrypt ? in[i] : out[i]; + c->bufsz = (c->bufsz + 1) % bs; + break; + case SC_CFB8: { + if (!sc_forward(c, c->block, stream)) return false; + unsigned char byte = (unsigned char)(in[i] ^ stream[0]); + memmove(c->block, c->block + 1, bs - 1); + c->block[bs - 1] = c->decrypt ? in[i] : byte; + out[i] = byte; + break; + } + default: { + unsigned char result = 0; + for (int bit = 7; bit >= 0; bit--) { + if (!sc_forward(c, c->block, stream)) return false; + unsigned in_bit = (in[i] >> bit) & 1u; + unsigned out_bit = in_bit ^ (stream[0] >> 7); + unsigned feed = c->decrypt ? in_bit : out_bit; + for (size_t k = 0; k + 1 < bs; k++) + c->block[k] = (unsigned char)(c->block[k] << 1 | c->block[k + 1] >> 7); + c->block[bs - 1] = (unsigned char)(c->block[bs - 1] << 1 | feed); + result |= (unsigned char)(out_bit << bit); + } + out[i] = result; + break; + } + } + } + mbedtls_platform_zeroize(stream, sizeof stream); + return true; +} + +/* chacha20 over len bytes: when the 64-bit counter's low word wraps, the + * high word steps (and wraps itself, as OpenSSL's does) and the stream + * restarts from block 0 of the next word. */ +static bool sc_chacha20_update(ScCipher *c, const unsigned char *in, size_t len, unsigned char *out) { + while (len > 0) { + size_t n = len < c->chacha_left ? len : (size_t)c->chacha_left; + if (mbedtls_chacha20_update(&c->chacha, n, in, out) != 0) return false; + in += n; + out += n; + len -= n; + c->chacha_left -= n; + if (c->chacha_left == 0) { + for (int k = 4; k < 8 && ++c->block[k] == 0; k++) { + } + memset(c->block, 0, 4); + c->chacha_left = (uint64_t)1 << 38; + if (mbedtls_chacha20_starts(&c->chacha, c->block + 4, 0) != 0) return false; + } + } + return true; +} + +/* OpenSSL's ossl_cipher_generic_block_update for CBC and ECB: complete + * blocks are processed, the remainder is buffered, and a decryption that + * ends on a block boundary holds the last block back for padding removal. + * Returns the output length, or -1 when the backend fails; out has room + * for len + 16 bytes. */ static long sc_cbc_update(ScCipher *c, const unsigned char *in, size_t inl, unsigned char *out) { + size_t bs = c->bs; size_t outl = 0; size_t nextblocks; if (c->bufsz != 0) { - size_t remain = 16 - c->bufsz; + size_t remain = bs - c->bufsz; if (inl < remain) remain = inl; memcpy(c->buf + c->bufsz, in, remain); in += remain; inl -= remain; c->bufsz += remain; - nextblocks = inl & ~(size_t)15; - } else { - nextblocks = inl & ~(size_t)15; } - if (c->bufsz == 16 && (!c->decrypt || inl > 0 || !c->pad)) { - if (!sc_cbc_blocks(c, c->buf, 16, out)) return -1; + nextblocks = inl - inl % bs; + if (c->bufsz == bs && (!c->decrypt || inl > 0 || !c->pad)) { + if (!sc_cbc_blocks(c, c->buf, bs, out)) return -1; c->bufsz = 0; - outl = 16; - out += 16; + outl = bs; + out += bs; } if (nextblocks > 0) { - if (c->decrypt && c->pad && nextblocks == inl) nextblocks -= 16; + if (c->decrypt && c->pad && nextblocks == inl) nextblocks -= bs; if (nextblocks > 0) { if (!sc_cbc_blocks(c, in, nextblocks, out)) return -1; outl += nextblocks; @@ -651,33 +888,35 @@ static long sc_cbc_update(ScCipher *c, const unsigned char *in, size_t inl, unsi return (long)outl; } -/* ossl_cipher_generic_block_final for CBC. Returns the output length, -1 - * after throwing OpenSSL's error, or -2 when the backend fails. */ +/* ossl_cipher_generic_block_final for CBC and ECB. Returns the output + * length, -1 after throwing OpenSSL's error, or -2 when the backend + * fails. */ static long sc_cbc_final(ScCipher *c, unsigned char out[16]) { + size_t bs = c->bs; if (!c->decrypt) { if (c->pad) { - unsigned char fill = (unsigned char)(16 - c->bufsz); - for (size_t i = c->bufsz; i < 16; i++) c->buf[i] = fill; + unsigned char fill = (unsigned char)(bs - c->bufsz); + for (size_t i = c->bufsz; i < bs; i++) c->buf[i] = fill; } else if (c->bufsz == 0) { return 0; - } else if (c->bufsz != 16) { + } else if (c->bufsz != bs) { sc_throw_openssl("1C80006B", "wrong final block length", "ERR_OSSL_WRONG_FINAL_BLOCK_LENGTH"); return -1; } - if (!sc_cbc_blocks(c, c->buf, 16, out)) return -2; + if (!sc_cbc_blocks(c, c->buf, bs, out)) return -2; c->bufsz = 0; - return 16; + return (long)bs; } - if (c->bufsz != 16) { + if (c->bufsz != bs) { if (c->bufsz == 0 && !c->pad) return 0; sc_throw_openssl("1C80006B", "wrong final block length", "ERR_OSSL_WRONG_FINAL_BLOCK_LENGTH"); return -1; } - if (!sc_cbc_blocks(c, c->buf, 16, c->buf)) return -2; - size_t len = 16; + if (!sc_cbc_blocks(c, c->buf, bs, c->buf)) return -2; + size_t len = bs; if (c->pad) { - unsigned char fill = c->buf[15]; - bool bad = fill == 0 || fill > 16; + unsigned char fill = c->buf[bs - 1]; + bool bad = fill == 0 || fill > bs; for (size_t i = 0; !bad && i < fill; i++) bad = c->buf[--len] != fill; if (bad) { sc_throw_openssl("1C800064", "bad decrypt", "ERR_OSSL_BAD_DECRYPT"); @@ -738,7 +977,8 @@ static ScrBytes *sc_transform(ScCipher *c, const unsigned char *in, size_t len) size_t produced = 0; bool ok = true; switch (c->mode) { - case SC_CBC: { + case SC_CBC: + case SC_ECB: { long n = sc_cbc_update(c, in, len, out->data); ok = n >= 0; produced = ok ? (size_t)n : 0; @@ -755,6 +995,17 @@ static ScrBytes *sc_transform(ScCipher *c, const unsigned char *in, size_t len) ok = len == 0 || sc_chacha_update(c, in, len, out->data); produced = len; break; + case SC_CFB: + case SC_CFB8: + case SC_CFB1: + case SC_OFB: + ok = sc_feedback(c, in, len, out->data); + produced = len; + break; + case SC_CHACHA20: + ok = len == 0 || sc_chacha20_update(c, in, len, out->data); + produced = len; + break; } if (!ok) { mbedtls_platform_zeroize(out->data, room); @@ -883,7 +1134,8 @@ static bool sc_aead(const ScCipher *c) { return c->mode == SC_GCM || c->mode == SC_CHACHA; } -static ScrDyn *sc_final(ScCipher *c, ScrDyn *output_encoding) { +/* final()'s output bytes (+1 Buffer), or NULL with the error thrown. */ +static ScrBytes *sc_final_bytes(ScCipher *c) { if (!c->active) { sc_throw(SCR_ERR_ERROR, "ERR_CRYPTO_INVALID_STATE", "Invalid state"); return NULL; @@ -894,7 +1146,8 @@ static ScrDyn *sc_final(ScCipher *c, ScrDyn *output_encoding) { out->len = 0; bool ok = true, backend = true; switch (c->mode) { - case SC_CBC: { + case SC_CBC: + case SC_ECB: { long produced = sc_cbc_final(c, out->data); if (produced == -1) { scr_bytes_release(out); @@ -905,6 +1158,11 @@ static ScrDyn *sc_final(ScCipher *c, ScrDyn *output_encoding) { break; } case SC_CTR: + case SC_CFB: + case SC_CFB8: + case SC_CFB1: + case SC_OFB: + case SC_CHACHA20: break; case SC_GCM: { unsigned char full[16]; @@ -953,7 +1211,12 @@ static ScrDyn *sc_final(ScCipher *c, ScrDyn *output_encoding) { sc_throw(SCR_ERR_ERROR, NULL, "Unsupported state or unable to authenticate data"); return NULL; } - return sc_output(c, out, output_encoding, true); + return out; +} + +static ScrDyn *sc_final(ScCipher *c, ScrDyn *output_encoding) { + ScrBytes *out = sc_final_bytes(c); + return out ? sc_output(c, out, output_encoding, true) : NULL; } static ScrDyn *sc_set_aad(ScCipher *c, ScrDyn *self, ScrDyn *buffer, ScrDyn *options) { @@ -1055,6 +1318,49 @@ static ScrDyn *sc_set_auth_tag(ScCipher *c, ScrDyn *self, ScrDyn *buffer, ScrDyn return scr_dyn_retain(self); } +/* ── Cipheriv and Decipheriv as streams ─────────────────────────────── + * The stream unit builds a cipher's Transform from these operations + * (ScrDynHandleTransform): each chunk goes through the handle's update(), + * and the end pushes final() or reports its error, as Node's cipher.js + * _transform and _flush do. */ + +static void *sc_stream_get(void *h) { + return ((ScCipher *)h)->stream; +} + +static void sc_stream_set(void *h, void *stream, void (*release)(void *)) { + ScCipher *c = h; + c->stream = stream; + c->stream_release = release; +} + +/* The handle's update(): it throws out of the write, as in Node, once + * the cipher has finished. */ +static ScrBytes *sc_stream_update(void *h, ScrBytes *chunk) { + ScCipher *c = h; + if (!c->active) { + sc_throw(SCR_ERR_ERROR, NULL, "Trying to add data in unsupported state"); + return NULL; + } + SCR_BYTES_SNAPSHOT(chunk); + return sc_transform(c, chunk->data, chunk->len * scr_bytes_elem_size(chunk->elem)); +} + +static ScrBytes *sc_stream_final(void *h) { + return sc_final_bytes(h); +} + +static const ScrDynHandleTransform sc_transform_ops = { + sc_stream_get, sc_stream_set, sc_stream_update, sc_stream_final, sc_trace, +}; + +static ScrDynHandleOps sc_ops_cipher; +static ScrDynHandleOps sc_ops_decipher; + +static const ScrDynHandleOps *sc_ops_of(const ScCipher *c) { + return c->decrypt ? &sc_ops_decipher : &sc_ops_cipher; +} + static bool sc_name_is(const char *method, const char *name) { return strcmp(method, name) == 0; } @@ -1076,8 +1382,12 @@ static bool sc_stream_member(const char *name) { static void sc_stream_fence(void) { static const char message[] = - "Cipheriv and Decipheriv stream members have no lowering; call update() and final()"; - scr_throw_error_msg_code(SCR_ERR_ERROR, message, sizeof message - 1, "SC2020"); + "This Cipheriv and Decipheriv stream member has no lowering when called through an untyped value"; + static const char streamless[] = + "Cipheriv and Decipheriv stream members called through an untyped value have no lowering in a " + "program that uses no streams"; + if (scr_handle_stream_hooks) scr_throw_error_msg_code(SCR_ERR_ERROR, message, sizeof message - 1, "SC2020"); + else scr_throw_error_msg_code(SCR_ERR_ERROR, streamless, sizeof streamless - 1, "SC2020"); } static ScrDyn *sc_dispatch(ScCipher *c, ScrDyn *self, const char *method, ScrDyn *const *args, size_t argc, @@ -1091,6 +1401,12 @@ static ScrDyn *sc_dispatch(ScCipher *c, ScrDyn *self, const char *method, ScrDyn if (c->decrypt && sc_name_is(method, "setAuthTag")) return sc_set_auth_tag(c, self, sc_arg(args, argc, 0), sc_arg(args, argc, 1)); if (sc_stream_member(method)) { + /* The members a native stream answers to checked-dynamic calls run + * on the cipher's Transform; the others have no lowering. */ + ScrDyn *result = NULL; + if (scr_handle_stream_hooks && + scr_handle_stream_hooks->call(sc_ops_of(c), c, self, method, args, argc, &result)) + return result; sc_stream_fence(); return NULL; } @@ -1117,11 +1433,19 @@ done: } static ScrDyn *sc_get(void *h, const char *key, size_t key_len) { - (void)h; (void)key; (void)key_len; + /* The stream properties read the cipher's Transform. */ + if (scr_handle_stream_hooks) { + ScrDyn *value = scr_handle_stream_hooks->get(sc_ops_of(h), h, key, key_len); + if (value || scr_exc_pending()) return value; + } static const char message[] = - "Cipheriv and Decipheriv property reads have no lowering; call update(), final(), setAAD(), " - "setAutoPadding(), getAuthTag() or setAuthTag()"; - scr_throw_error_msg_code(SCR_ERR_ERROR, message, sizeof message - 1, "SC2020"); + "Cipheriv and Decipheriv property reads have no lowering other than the stream properties; call " + "update(), final(), setAAD(), setAutoPadding(), getAuthTag() or setAuthTag()"; + static const char streamless[] = + "Cipheriv and Decipheriv property reads through an untyped value have no lowering in a program " + "that uses no streams"; + if (scr_handle_stream_hooks) scr_throw_error_msg_code(SCR_ERR_ERROR, message, sizeof message - 1, "SC2020"); + else scr_throw_error_msg_code(SCR_ERR_ERROR, streamless, sizeof streamless - 1, "SC2020"); return NULL; } @@ -1132,5 +1456,7 @@ static bool sc_set(void *h, const char *key, size_t key_len, const ScrDyn *value return true; } -static ScrDynHandleOps sc_ops_cipher = {"Cipheriv", sc_retain, sc_release, sc_invoke, sc_get, sc_set, NULL, NULL, NULL}; -static ScrDynHandleOps sc_ops_decipher = {"Decipheriv", sc_retain, sc_release, sc_invoke, sc_get, sc_set, NULL, NULL, NULL}; +static ScrDynHandleOps sc_ops_cipher = {"Cipheriv", sc_retain, sc_release, sc_invoke, sc_get, sc_set, NULL, NULL, NULL, + .transform = &sc_transform_ops}; +static ScrDynHandleOps sc_ops_decipher = {"Decipheriv", sc_retain, sc_release, sc_invoke, sc_get, sc_set, NULL, NULL, NULL, + .transform = &sc_transform_ops}; diff --git a/packages/runtime/src/scr_console.c b/packages/runtime/src/scr_console.c index c29126a4a..f8dd9a0c0 100644 --- a/packages/runtime/src/scr_console.c +++ b/packages/runtime/src/scr_console.c @@ -148,7 +148,7 @@ static void scr_enable_utf8_console_output(void) { } #endif -void scr_runtime_abi_v24(void) {} +void scr_runtime_abi_v33(void) {} void scr_init(void) { #ifdef SCR_WORKERS diff --git a/packages/runtime/src/scr_copying.c b/packages/runtime/src/scr_copying.c index df4da1738..6cdc0683c 100644 --- a/packages/runtime/src/scr_copying.c +++ b/packages/runtime/src/scr_copying.c @@ -22,13 +22,22 @@ static bool copying_elem_is_ref(ScrElemKind kind) { } static ScrArr *copying_arr_new_like(const ScrArr *a, size_t cap) { - ScrArr *out = a->elem == SCR_ELEM_REF + ScrArr *out = a->elem == SCR_ELEM_REF || a->elem == SCR_ELEM_CREF ? scr_arr_new_ops(scr_arr_ops(a), cap ? cap : 1) : scr_arr_new(a->elem, cap ? cap : 1); - out->len = cap; return out; } +/* Copy [from, from + count) of `src` to the end of `out` and raise its + * length over the copy. */ +static void copying_arr_append_range(ScrArr *out, const ScrArr *src, size_t from, size_t count, + bool reverse) { + size_t at = out->len; + scr_arr_copy_range_ex(out, at, src, from, count, reverse, true); + out->len = (uint32_t)(at + count); + scr_arr_refill(out); +} + static uint64_t copying_arr_retain_slot(const ScrArr *a, uint64_t slot) { if (!copying_elem_is_ref(a->elem)) return slot; void *p = copying_slot_to_ptr(slot); @@ -41,7 +50,7 @@ static uint64_t copying_arr_retain_slot(const ScrArr *a, uint64_t slot) { ScrArr *scr_arr_to_reversed(const ScrArr *a) { ScrArr *out = copying_arr_new_like(a, a->len); - scr_arr_copy_range_ex(out, 0, a, 0, a->len, true, true); + copying_arr_append_range(out, a, 0, a->len, true); return out; } @@ -60,10 +69,9 @@ ScrArr *scr_arr_to_spliced(const ScrArr *a, double start, } size_t out_len = a->len - ndelete + items->len; ScrArr *out = copying_arr_new_like(a, out_len); - scr_arr_copy_range_ex(out, 0, a, 0, from, false, true); - scr_arr_copy_range_ex(out, from, items, 0, items->len, false, true); - scr_arr_copy_range_ex(out, from + items->len, a, from + ndelete, - a->len - from - ndelete, false, true); + copying_arr_append_range(out, a, 0, from, false); + copying_arr_append_range(out, items, 0, items->len, false); + copying_arr_append_range(out, a, from + ndelete, a->len - from - ndelete, false); return out; } @@ -88,7 +96,7 @@ ScrArr *scr_arr_with_f64(ScrArr *a, double index, double value) { size_t i; if (!copying_arr_with_index(a, index, &i)) return NULL; ScrArr *out = copying_arr_new_like(a, a->len); - scr_arr_copy_range_ex(out, 0, a, 0, a->len, false, true); + copying_arr_append_range(out, a, 0, a->len, false); scr_arr_set_f64(out, (double)i, value); return out; } @@ -97,7 +105,7 @@ ScrArr *scr_arr_with_bool(ScrArr *a, double index, bool value) { size_t i; if (!copying_arr_with_index(a, index, &i)) return NULL; ScrArr *out = copying_arr_new_like(a, a->len); - scr_arr_copy_range_ex(out, 0, a, 0, a->len, false, true); + copying_arr_append_range(out, a, 0, a->len, false); scr_arr_set_bool(out, (double)i, value); return out; } @@ -106,7 +114,7 @@ ScrArr *scr_arr_with_ref(ScrArr *a, double index, void *value) { size_t i; if (!copying_arr_with_index(a, index, &i)) return NULL; ScrArr *out = copying_arr_new_like(a, a->len); - scr_arr_copy_range_ex(out, 0, a, 0, a->len, false, true); + copying_arr_append_range(out, a, 0, a->len, false); uint64_t retained = copying_arr_retain_slot(a, copying_slot_from_ptr(value)); scr_arr_set_ref(out, (double)i, copying_slot_to_ptr(retained)); @@ -117,7 +125,7 @@ ScrArr *scr_arr_with_undefined(ScrArr *a, double index) { size_t i; if (!copying_arr_with_index(a, index, &i)) return NULL; ScrArr *out = copying_arr_new_like(a, a->len); - scr_arr_copy_range_ex(out, 0, a, 0, a->len, false, true); + copying_arr_append_range(out, a, 0, a->len, false); scr_arr_set_undefined(out, (double)i); return out; } diff --git a/packages/runtime/src/scr_core.h b/packages/runtime/src/scr_core.h index 94936a8aa..d716f0de3 100644 --- a/packages/runtime/src/scr_core.h +++ b/packages/runtime/src/scr_core.h @@ -81,7 +81,7 @@ void scr_init(void); /* Program objects emitted by the bundled LLVM helper reference this symbol. * Its versioned spelling makes a mismatched manual runtime link fail before * the program can start. */ -void scr_runtime_abi_v24(void); +void scr_runtime_abi_v33(void); void scr_runtime_workers_v8(void); /* ── the trap funnel (scr_console.c; scr_library.c under -DSCR_LIB) ────── diff --git a/packages/runtime/src/scr_crypto.h b/packages/runtime/src/scr_crypto.h index d12858abf..0e6c6e07f 100644 --- a/packages/runtime/src/scr_crypto.h +++ b/packages/runtime/src/scr_crypto.h @@ -20,6 +20,9 @@ ScrStr *scr_crypto_hash_digest_bytes(ScrStr *alg, ScrBytes *data, ScrStr *enc); typedef struct ScrCryptoHash ScrCryptoHash; ScrCryptoHash *scr_crypto_hash_new(ScrStr *alg); ScrDyn *scr_crypto_native(void); +/* The crypto global as a value: scr_crypto_native's object with the Crypto + * methods (scr_webcrypto_object.c, linked with the webcrypto feature). */ +ScrDyn *scr_webcrypto_object(void); ScrCryptoHash *scr_crypto_hmac_new_str(ScrStr *alg, ScrStr *key); ScrCryptoHash *scr_crypto_hmac_new_bytes(ScrStr *alg, ScrBytes *key); ScrCryptoHash *scr_crypto_hash_retain(ScrCryptoHash *h); @@ -82,6 +85,10 @@ ScrDyn *scr_crypto_create_secret_key(ScrDyn *key, ScrDyn *encoding); ScrDyn *scr_crypto_generate_key_sync(ScrDyn *type, ScrDyn *options); ScrBytes *scr_crypto_key_object_input(ScrDyn *key); bool scr_crypto_is_key_object(const ScrDyn *value); +/* Throws Node's ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE for a private or public + * KeyObject used as a secret key. scr_pki.c, which makes those keys, + * installs it with them, so its messages stay out of other programs. */ +extern void (*scr_crypto_reject_asymmetric_secret)(const ScrDyn *key); const unsigned char *scr_key_object_bytes(const ScrDyn *value, size_t *len); /* crypto.createCipheriv (decrypt false) and crypto.createDecipheriv * (decrypt true) over checked-dynamic arguments (scr_cipher.c, linked @@ -94,6 +101,21 @@ ScrDyn *scr_crypto_cipher_new(bool decrypt, ScrDyn *cipher, ScrDyn *key, ScrDyn * or result, or NULL with Node's error pending. */ ScrDyn *scr_crypto_ecdh_new(ScrDyn *curve); ScrDyn *scr_crypto_ecdh_convert_key(ScrDyn *key, ScrDyn *curve, ScrDyn *in_enc, ScrDyn *out_enc, ScrDyn *format); +/* crypto.createDiffieHellman(sizeOrKey, keyEncoding, generator, + * generatorEncoding) and crypto.getDiffieHellman(groupName) over + * checked-dynamic arguments (scr_dh.c, linked with the vendored mbedTLS + * archive). +1 DiffieHellman or DiffieHellmanGroup handle, or NULL with + * Node's error pending. */ +ScrDyn *scr_crypto_dh_new(ScrDyn *size_or_key, ScrDyn *key_encoding, ScrDyn *generator, ScrDyn *generator_encoding); +ScrDyn *scr_crypto_dh_group_new(ScrDyn *name); +/* crypto.checkPrimeSync, checkPrime, generatePrimeSync and generatePrime + * (scr_dh.c): checked-dynamic arguments, borrowed; the sync forms answer + * +1 or NULL with the error pending. The callbacks receive undefined as + * the error, as Node passes it, or null when `null_error`. */ +ScrDyn *scr_crypto_check_prime_sync(ScrDyn *candidate, ScrDyn *options); +void scr_crypto_check_prime_async(ScrDyn *candidate, ScrDyn *options, ScrDyn *callback, bool null_error); +ScrDyn *scr_crypto_generate_prime_sync(ScrDyn *size, ScrDyn *options); +void scr_crypto_generate_prime_async(ScrDyn *size, ScrDyn *options, ScrDyn *callback, bool null_error); ScrBytes *scr_crypto_pbkdf2(ScrBytes *password, ScrBytes *salt, double iterations, double keylen, ScrStr *digest); ScrBytes *scr_crypto_pbkdf2_job(ScrBytes *password, ScrBytes *salt, double iterations, @@ -202,19 +224,55 @@ size_t scr_crypto_digest_raw(const char *alg, const unsigned char *data, size_t size_t scr_crypto_hmac_raw(const char *alg, const unsigned char *key, size_t keylen, const unsigned char *data, size_t len, unsigned char out[64]); /* ── WebCrypto (scr_webcrypto.c) ───────────────────────────────────── - * crypto.subtle.importKey (raw HMAC keys), sign and verify (HMAC) and - * digest (SHA-1/SHA-2) over node:crypto's digest core. Each takes the + * crypto.subtle.importKey (HMAC, AES, PBKDF2 and HKDF keys, raw and jwk), + * generateKey and exportKey (HMAC and AES keys), sign and verify (HMAC) + * and digest (SHA-1/SHA-2) over node:crypto's digest core. Each takes the * call's argument vector as one dyn array (borrowed) and answers a +1 * promise that every argument or validation failure rejects with Node's * TypeError or DOMException; algorithms and formats outside the slice - * reject with a coded SC2020 Error. importKey settles at once with a - * CryptoKey handle; sign and digest fulfill with an ArrayBuffer and - * verify with a boolean on a later loop turn. scr_webcrypto_is_crypto_key - * answers `value instanceof CryptoKey`. */ + * reject with a coded SC2020 Error. importKey and exportKey settle at + * once with a CryptoKey handle, an ArrayBuffer or a JWK object; + * generateKey fulfills with a CryptoKey, sign and digest with an + * ArrayBuffer and verify with a boolean on a later loop turn. + * scr_webcrypto_is_crypto_key answers `value instanceof CryptoKey`. */ ScrPromise *scr_webcrypto_import_key(ScrDyn *args); +ScrPromise *scr_webcrypto_generate_key(ScrDyn *args); +ScrPromise *scr_webcrypto_export_key(ScrDyn *args); ScrPromise *scr_webcrypto_sign(ScrDyn *args); ScrPromise *scr_webcrypto_verify(ScrDyn *args); ScrPromise *scr_webcrypto_digest(ScrDyn *args); +/* encrypt and decrypt (scr_webcrypto_aes.c, linked with the cipher + * feature's mbedTLS archive) run scr_webcrypto_cipher with the AES cipher + * as `aes`, which answers the +1 output bytes or NULL when the operation + * fails. encrypt and decrypt fulfill with an ArrayBuffer, or reject with + * a job failure, on a later loop turn. */ +typedef struct { + const unsigned char *iv; /* the IV, or the CTR counter block */ + size_t iv_len; + const unsigned char *aad; + size_t aad_len; + size_t tag_len; /* bytes */ + unsigned counter_bits; +} ScrWebCryptoAesParams; +typedef ScrBytes *(*ScrWebCryptoAesFn)(const char *name, bool decrypt, const unsigned char *key, + size_t key_len, const ScrWebCryptoAesParams *params, + const unsigned char *in, size_t len); +ScrPromise *scr_webcrypto_cipher(ScrDyn *args, bool decrypt, ScrWebCryptoAesFn aes); +ScrPromise *scr_webcrypto_encrypt(ScrDyn *args); +ScrPromise *scr_webcrypto_decrypt(ScrDyn *args); +/* wrapKey and unwrapKey run the same way (AES-KW wrapping, or the AES + * ciphers): wrapKey fulfills with an ArrayBuffer and unwrapKey with a + * CryptoKey on a later loop turn. */ +ScrPromise *scr_webcrypto_wrap(ScrDyn *args, ScrWebCryptoAesFn aes); +ScrPromise *scr_webcrypto_unwrap(ScrDyn *args, ScrWebCryptoAesFn aes); +ScrPromise *scr_webcrypto_wrap_key(ScrDyn *args); +ScrPromise *scr_webcrypto_unwrap_key(ScrDyn *args); +/* deriveBits and deriveKey (PBKDF2 and HKDF) over node:crypto's KDF core: + * deriveBits fulfills with an ArrayBuffer (at once for a zero length) and + * deriveKey with a CryptoKey of the derived key type, on a later loop + * turn. */ +ScrPromise *scr_webcrypto_derive_bits(ScrDyn *args); +ScrPromise *scr_webcrypto_derive_key(ScrDyn *args); bool scr_webcrypto_is_crypto_key(const ScrDyn *value); /* The composed `new crypto.X509Certificate(data).fingerprint` read (the @@ -229,5 +287,17 @@ ScrStr *scr_crypto_x509_valid_from(ScrBytes *data); ScrStr *scr_crypto_x509_valid_from_str(ScrStr *pem); ScrStr *scr_crypto_x509_valid_to(ScrBytes *data); ScrStr *scr_crypto_x509_valid_to_str(ScrStr *pem); +/* Asymmetric keys and signatures (scr_pki.c, the pki unit). Arguments + * borrowed; results +1, or NULL with the error pending. */ +ScrDyn *scr_crypto_create_private_key(ScrDyn *key); +ScrDyn *scr_crypto_create_public_key(ScrDyn *key); +ScrDyn *scr_crypto_generate_key_pair_sync(ScrDyn *type, ScrDyn *options); +void scr_crypto_generate_key_pair_async(ScrDyn *type, ScrDyn *options, ScrDyn *callback); +ScrDyn *scr_crypto_sign_oneshot(ScrDyn *algorithm, ScrDyn *data, ScrDyn *key); +ScrDyn *scr_crypto_verify_oneshot(ScrDyn *algorithm, ScrDyn *data, ScrDyn *key, ScrDyn *signature); +ScrDyn *scr_crypto_create_sign(ScrDyn *algorithm); +ScrDyn *scr_crypto_create_verify(ScrDyn *algorithm); +bool scr_crypto_is_asymmetric_key(const ScrDyn *value); +const char *scr_crypto_asymmetric_key_type(const ScrDyn *value); #endif /* SCR_CRYPTO_H */ diff --git a/packages/runtime/src/scr_crypto_args.h b/packages/runtime/src/scr_crypto_args.h new file mode 100644 index 000000000..b8bdcc1c9 --- /dev/null +++ b/packages/runtime/src/scr_crypto_args.h @@ -0,0 +1,181 @@ +/* Argument and result handling shared by the checked-dynamic node:crypto + * key-exchange handles (scr_ecdh.c and scr_dh.c), as Node 24's + * lib/internal/crypto/diffiehellman.js and lib/internal/crypto/util.js + * read keys and encodings: getArrayBufferOrView for key inputs and + * encode() for Buffer results. `subject` names the value in the coded + * SC2020 error for encodings that have no lowering ("An ECDH encoding or + * format"). All arguments are borrowed. */ +#ifndef SCR_CRYPTO_ARGS_H +#define SCR_CRYPTO_ARGS_H + +#include "scr_runtime.h" + +#include + +/* An object's toString the program defined, as an own or inherited + * function property. */ +static bool ca_custom_to_string(ScrDyn *value) { + if (value->kind != SCR_DYN_OBJ && value->kind != SCR_DYN_TYPED_REF) return false; + ScrDyn *member = scr_dyn_obj_read(value, "toString", 8); + bool custom = member && member->kind == SCR_DYN_FUNC; + scr_dyn_release(member); + return custom; +} + +/* Whether value is a class instance whose class defines toString. */ +static bool ca_class_to_string(const ScrDyn *value) { + ScrStr *name = scr_str_new("toString", 8); + bool method = scr_dyn_typed_ref_class_has(value, name); + scr_str_release(name); + return method; +} + +/* `prefix` and the value as util.format's %s renders it: strings and + * objects with a program-defined toString as String(value), numbers as + * util.inspect does, other values inspected at depth 0. Functions and + * class instances that define toString have no lowering. */ +static void ca_throw_formatted(const char *subject, const char *code, const char *prefix, const ScrDyn *value) { + ScrDyn *v = (ScrDyn *)value; + if (v->kind == SCR_DYN_FUNC || ca_class_to_string(v)) { + ScrJsonBuf b; + scr_jb_init(&b); + scr_jb_puts(&b, subject); + scr_jb_puts(&b, " that is a function or an instance of a class defining toString has no lowering; " + "pass the name as a string"); + ScrStr *message = scr_jb_finish(&b); + scr_throw_error_msg_code(SCR_ERR_ERROR, message->data, message->len, "SC2020"); + scr_str_release(message); + return; + } + ScrStr *text; + if (v->kind == SCR_DYN_STR || ca_custom_to_string(v)) text = scr_dyn_string_coerce_js(v); + else if (v->kind == SCR_DYN_NUM) text = scr_insp_f64(v->v.num); + else text = scr_insp_dyn_s(v, 0); + if (!text) return; + ScrJsonBuf b; + scr_jb_init(&b); + scr_jb_puts(&b, prefix); + scr_jb_put_str(&b, text); + scr_str_release(text); + ScrStr *message = scr_jb_finish(&b); + scr_throw_error_msg_code(SCR_ERR_TYPE, message->data, message->len, code); + scr_str_release(message); +} + +static bool ca_ascii_eq_ci(const char *a, size_t a_len, const char *b) { + size_t b_len = strlen(b); + if (a_len != b_len) return false; + for (size_t i = 0; i < a_len; i++) { + char x = a[i]; + if (x >= 'A' && x <= 'Z') x = (char)(x - 'A' + 'a'); + if (x != b[i]) return false; + } + return true; +} + +static bool ca_str_is(const ScrStr *text, const char *literal) { + size_t len = strlen(literal); + return text->len == len && memcmp(text->data, literal, len) == 0; +} + +/* Node's normalizeEncoding: the canonical name, or NULL. */ +static const char *ca_normalize_encoding(const ScrStr *name) { + static const struct { const char *from; const char *to; } map[] = { + {"utf8", "utf8"}, {"utf-8", "utf8"}, {"hex", "hex"}, + {"base64", "base64"}, {"base64url", "base64url"}, {"latin1", "latin1"}, + {"binary", "latin1"}, {"ascii", "ascii"}, {"utf16le", "utf16le"}, + {"utf-16le", "utf16le"}, {"ucs2", "utf16le"}, {"ucs-2", "utf16le"}, + }; + for (size_t i = 0; i < sizeof map / sizeof map[0]; i++) + if (ca_ascii_eq_ci(name->data, name->len, map[i].from)) return map[i].to; + return NULL; +} + +/* The value a typed-ref box holds when it is a string, view, ArrayBuffer + * or native handle (+1). Other values are retained as passed, so argument + * errors describe the original value. NULL after throwing. */ +static ScrDyn *ca_unbox(ScrDyn *value) { + if (value->kind != SCR_DYN_TYPED_REF) return scr_dyn_retain(value); + ScrDyn *view = scr_dyn_typed_ref_materialize(value); + if (!view) return NULL; + if (view->kind == SCR_DYN_STR || view->kind == SCR_DYN_BYTES || view->kind == SCR_DYN_HANDLE || + scr_buffer_storage_is(view)) + return view; + scr_dyn_release(view); + return scr_dyn_retain(value); +} + +/* Buffer.from(text, encoding) as toBuf calls it: an encoding that is not + * a non-empty string, or is 'buffer', reads as utf8. +1 or NULL after + * throwing. */ +static ScrBytes *ca_string_bytes(const char *subject, const ScrStr *text, const ScrDyn *encoding) { + const char *name = "utf8"; + if (encoding->kind == SCR_DYN_STR && encoding->v.str->len > 0 && !ca_str_is(encoding->v.str, "buffer")) { + name = ca_normalize_encoding(encoding->v.str); + if (!name) { + ca_throw_formatted(subject, "ERR_UNKNOWN_ENCODING", "Unknown encoding: ", encoding); + return NULL; + } + } + ScrStr *canonical = scr_str_new(name, strlen(name)); + ScrBytes *bytes = scr_bytes_from_str(text, canonical); + scr_str_release(canonical); + return bytes; +} + +/* getArrayBufferOrView(key, 'key', encoding): a string is Buffer.from(key, + * encoding) with 'buffer' read as utf8; views and ArrayBuffers are their + * bytes. +1 or NULL after throwing. */ +static ScrBytes *ca_key_bytes(const char *subject, const ScrDyn *key, const ScrDyn *encoding) { + if (key->kind == SCR_DYN_STR) return ca_string_bytes(subject, key->v.str, encoding); + if (key->kind == SCR_DYN_BYTES || scr_buffer_storage_is(key)) return scr_bytes_buffer_source(key); + scr_dyn_arg_type_fail("key", "of type string or an instance of ArrayBuffer, Buffer, TypedArray, or DataView", key); + return NULL; +} + +/* encode(buffer, encoding): the Buffer, or buffer.toString(encoding) for + * a truthy encoding other than 'buffer'. Consumes bytes. */ +static ScrDyn *ca_encode(const char *subject, ScrBytes *bytes, const ScrDyn *encoding) { + if (!scr_dyn_truthy(encoding) || (encoding->kind == SCR_DYN_STR && ca_str_is(encoding->v.str, "buffer"))) { + ScrDyn *result = scr_dyn_new_buffer(bytes); + scr_bytes_release(bytes); + return result; + } + /* toString answers "" for no bytes before it reads the encoding. */ + ScrStr *text = NULL; + if (bytes->len == 0) { + text = scr_str_new("", 0); + } else { + /* getEncodingOps reads `encoding + ''`. */ + ScrStr *name = encoding->kind == SCR_DYN_STR ? scr_str_retain(encoding->v.str) : NULL; + if (!name) { + if (encoding->kind == SCR_DYN_FUNC || ca_class_to_string(encoding)) { + ca_throw_formatted(subject, "ERR_UNKNOWN_ENCODING", "Unknown encoding: ", encoding); + scr_bytes_release(bytes); + return NULL; + } + name = scr_dyn_string_coerce_js(encoding); + if (!name) { + scr_bytes_release(bytes); + return NULL; + } + } + const char *canonical = ca_normalize_encoding(name); + scr_str_release(name); + if (!canonical) { + ca_throw_formatted(subject, "ERR_UNKNOWN_ENCODING", "Unknown encoding: ", encoding); + scr_bytes_release(bytes); + return NULL; + } + ScrStr *canonical_text = scr_str_new(canonical, strlen(canonical)); + text = scr_bytes_to_str(bytes, canonical_text); + scr_str_release(canonical_text); + } + scr_bytes_release(bytes); + if (!text) return NULL; + ScrDyn *result = scr_dyn_new_str(text); + scr_str_release(text); + return result; +} + +#endif diff --git a/packages/runtime/src/scr_cycle.c b/packages/runtime/src/scr_cycle.c index 5e5029e14..6dcd546b0 100644 --- a/packages/runtime/src/scr_cycle.c +++ b/packages/runtime/src/scr_cycle.c @@ -529,7 +529,8 @@ static SCR_TL size_t scr_cyc_live_after[SCR_CYC_NGENS]; * large program, say) those walks dominate collection time. The cap trades * that walking for memory only when passes find nothing: while they find * garbage, the yield keeps the fraction narrow. SCR_CYCLE_GROWTH_CAP lowers - * the cap for memory-sensitive programs: a power of two from 1 to 16, with + * the cap for memory-sensitive programs, as scr_cyc_set_growth_cap does for + * a program that sets its own: a power of two from 1 to 16, with * other positive values rounded down to a power of two and larger ones read * as 16. At 1 the heap may at most double past its size after the last pass * at a level before the next. */ @@ -539,20 +540,34 @@ static SCR_TL unsigned char scr_cyc_growth_shift[SCR_CYC_NGENS]; static SCR_TL unsigned char scr_cyc_growth_streak[SCR_CYC_NGENS]; #endif +/* The growth cap a program sets for itself (scr_cyc_set_growth_cap), 0 for + * the default; SCR_CYCLE_GROWTH_CAP takes precedence over it. */ +static long scr_cyc_growth_cap_set = 0; +static SCR_TL unsigned char scr_cyc_growth_max_shift_cached = 0; + /* Shift of the configured growth cap: 2 + log2(cap), since the base * fraction is 1/4. */ static unsigned scr_cyc_growth_max_shift(void) { - static SCR_TL unsigned char cached = 0; - if (cached == 0) { + if (scr_cyc_growth_max_shift_cached == 0) { const char *env = scr_getenv("SCR_CYCLE_GROWTH_CAP"); long v = env ? strtol(env, NULL, 10) : 0; + if (v <= 0) v = scr_cyc_growth_cap_set; unsigned shift = SCR_CYC_GROWTH_MAX_SHIFT; if (v > 0) for (shift = 2; shift < SCR_CYC_GROWTH_MAX_SHIFT && (2L << (shift - 2)) <= v;) shift++; - cached = (unsigned char)shift; + scr_cyc_growth_max_shift_cached = (unsigned char)shift; } - return cached; + return scr_cyc_growth_max_shift_cached; +} + +void scr_cyc_set_growth_cap(long cap) { + scr_cyc_growth_cap_set = cap; + scr_cyc_growth_max_shift_cached = 0; + /* Fractions already widened past the new cap start at it. */ + unsigned max = scr_cyc_growth_max_shift(); + for (unsigned gen = 0; gen < SCR_CYC_NGENS; gen++) + if (scr_cyc_growth_shift[gen] > max) scr_cyc_growth_shift[gen] = (unsigned char)max; } /* Doublings of each generation's backlog threshold earned by consecutive @@ -1244,9 +1259,9 @@ void scr_cyc_on_release(void *obj) { #define SCR_CYC_ARRAY_WALK(name, visit) \ static __attribute__((noinline)) void name(const ScrArr *arr, void *ctx) { \ size_t end = arr->len < arr->cap ? arr->len : arr->cap; \ - size_t filled = arr->filled < end ? arr->filled : end; \ + const uint8_t *states = scr_arr_scan_states(arr); \ + size_t filled = !states || arr->filled > end ? end : arr->filled; \ for (size_t i = 0; i < filled; i++) visit((void *)(uintptr_t)arr->data[i], ctx); \ - const uint8_t *states = scr_arr_states_end(arr); \ for (size_t i = filled; i < end; i++) \ if (*scr_arr_state_in(states, i) == SCR_ARR_VALUE) \ visit((void *)(uintptr_t)arr->data[i], ctx); \ diff --git a/packages/runtime/src/scr_dgram.c b/packages/runtime/src/scr_dgram.c index bb14d063e..8d1c7b058 100644 --- a/packages/runtime/src/scr_dgram.c +++ b/packages/runtime/src/scr_dgram.c @@ -2158,3 +2158,73 @@ void scr_dgram_send_chk(ScrDgramSocket *s, const ScrDyn *buffer, const ScrDyn *a * it removes a 'message' listener. Defined last so the functions above * keep their emission order. */ void scr_dgram_rearm(ScrDgramSocket *s) { scr_dgram_update_read(s); } + +/* ── Unix datagram sockets for the hot-shots package shim ────────────── + * The unix-dgram addon's surface, which hot-shots' uds transport uses: a + * non-blocking AF_UNIX datagram socket connected to a path. Each call + * answers its result (fd, 0) or a negative errno, as the addon's binding + * does; send answers 1 when the socket would block (the addon's + * "congestion"). Defined after the functions above so their emission + * order is unchanged. */ +#ifndef _WIN32 +#include +#endif + +double scr_dgram_unix_socket(void) { +#ifdef _WIN32 + return -(double)ENOSYS; +#else + int fd = socket(AF_UNIX, SOCK_DGRAM, 0); + if (fd < 0) return -(double)errno; + int flags = fcntl(fd, F_GETFL, 0); + if (flags >= 0) (void)fcntl(fd, F_SETFL, flags | O_NONBLOCK); + (void)fcntl(fd, F_SETFD, FD_CLOEXEC); + return (double)fd; +#endif +} + +double scr_dgram_unix_connect(double fd, ScrStr *path) { +#ifdef _WIN32 + (void)fd; + (void)path; + return -(double)ENOSYS; +#else + struct sockaddr_un addr; + memset(&addr, 0, sizeof addr); + addr.sun_family = AF_UNIX; + char *owned; + const char *bytes = scr_str_utf8(path, &owned); + size_t n = strlen(bytes); + if (n > sizeof addr.sun_path - 1) n = sizeof addr.sun_path - 1; + memcpy(addr.sun_path, bytes, n); + scr_str_utf8_end(owned); + if (connect((int)fd, (struct sockaddr *)&addr, sizeof addr) != 0) return -(double)errno; + return 0; +#endif +} + +double scr_dgram_unix_send(double fd, ScrBytes *data) { +#ifdef _WIN32 + (void)fd; + (void)data; + return -(double)ENOSYS; +#else + SCR_BYTES_SNAPSHOT(data); + ssize_t sent; + do { + sent = send((int)fd, data->data, data->len, 0); + } while (sent < 0 && errno == EINTR); + if (sent >= 0) return 0; + if (errno == EAGAIN || errno == EWOULDBLOCK) return 1; + return -(double)errno; +#endif +} + +double scr_dgram_unix_close(double fd) { +#ifdef _WIN32 + (void)fd; + return -(double)ENOSYS; +#else + return close((int)fd) != 0 ? -(double)errno : 0; +#endif +} diff --git a/packages/runtime/src/scr_dgram.h b/packages/runtime/src/scr_dgram.h index 8396f0693..08db077df 100644 --- a/packages/runtime/src/scr_dgram.h +++ b/packages/runtime/src/scr_dgram.h @@ -55,6 +55,13 @@ double scr_dgram_addr_port(ScrDgramSocket *s); void scr_dgram_close(ScrDgramSocket *s, ScrClosure *cb /*moves, nullable*/); /* throws on closed */ void scr_dgram_unref(ScrDgramSocket *s); void scr_dgram_ref(ScrDgramSocket *s); +/* Unix datagram sockets for the hot-shots package shim (the unix-dgram + * addon's surface): each answers its result (fd, 0) or a negative errno; + * send answers 1 when the socket would block. */ +double scr_dgram_unix_socket(void); +double scr_dgram_unix_connect(double fd, ScrStr *path /*borrowed*/); +double scr_dgram_unix_send(double fd, ScrBytes *data /*borrowed*/); +double scr_dgram_unix_close(double fd); /* Socket options: Node's checks and errors (ErrnoException " * ", ERR_SOCKET_BAD_BUFFER_SIZE, ERR_SOCKET_BUFFER_SIZE, the * TypeError after close()). The TTL setters and setMulticastLoopback diff --git a/packages/runtime/src/scr_dh.c b/packages/runtime/src/scr_dh.c new file mode 100644 index 000000000..dfa6fd2f3 --- /dev/null +++ b/packages/runtime/src/scr_dh.c @@ -0,0 +1,1780 @@ +/* node:crypto DiffieHellman over the vendored mbedTLS bignum arithmetic: + * crypto.createDiffieHellman, crypto.getDiffieHellman and + * crypto.createDiffieHellmanGroup. A DiffieHellman or DiffieHellmanGroup + * is a native dyn handle. Construction follows Node 24's + * lib/internal/crypto/diffiehellman.js argument handling and + * src/crypto/crypto_dh.cc; key generation, verifyError, the public key + * range check and computeSecret follow the OpenSSL 3 paths of + * deps/ncrypto and OpenSSL 3.5's DH provider: + * - a group draws modp5 through modp18 private keys of a fixed width + * (200 to 400 bits) and modp1 and modp2 keys in [2, p - 2], and its + * verifyError is 0; + * - createDiffieHellman parameters that equal an OpenSSL named group + * draw keys below min(2^N, q) for the group's key length N; other + * parameters draw keys of bits(p) - 2 bits, and key generation and + * computeSecret need a 512- to 10000-bit prime; + * - createDiffieHellman(primeLength, generator) generates a safe prime + * p ≡ 23 (mod 24) for the generator 2, p ≡ 59 (mod 60) for 5 and + * p ≡ 11 (mod 12) otherwise, as OpenSSL's dh_builtin_genparams does. + * Primes longer than mbedTLS's 8192-bit limit throw a coded SC2020 + * error, as do keys and generators past mbedTLS's 80000-byte limit (leading + * zero bytes aside). All arguments are borrowed. */ +#include "scr_runtime.h" + +#include +#include +#include +#include +#include + +#include "mbedtls/bignum.h" +#include "mbedtls/platform_util.h" + +#include "scr_crypto_args.h" +#include "scr_dh_groups.h" + +/* The value the SC2020 error for an unlowered encoding names. */ +#define SD_SUBJECT "A DiffieHellman encoding" + +/* DH_MIN_MODULUS_BITS and OPENSSL_DH_MAX_MODULUS_BITS. */ +#define SD_MIN_MODULUS_BITS 512 +#define SD_MAX_MODULUS_BITS 10000 + +/* The longest value an mbedtls_mpi holds, in bytes. */ +#define SD_MAX_VALUE_BYTES (MBEDTLS_MPI_MAX_LIMBS * sizeof(mbedtls_mpi_uint)) + +/* DH_check result bits, as verifyError reports them. */ +enum { + SD_P_NOT_PRIME = 0x01, + SD_P_NOT_SAFE_PRIME = 0x02, + SD_NOT_SUITABLE_GENERATOR = 0x08, + SD_MODULUS_TOO_SMALL = 0x80, +}; + +/* A crypto.getDiffieHellman group. */ +typedef struct { + const char *name; + const unsigned char *p; + size_t p_len; + int private_bits; /* ncrypto's GetDhGroupPrivateBits; 0 draws keys in [2, p - 2] */ +} ScDhGroup; + +static const ScDhGroup sd_groups[] = { + {"modp1", scr_dh_modp1_p, sizeof scr_dh_modp1_p, 0}, + {"modp2", scr_dh_modp2_p, sizeof scr_dh_modp2_p, 0}, + {"modp5", scr_dh_modp5_p, sizeof scr_dh_modp5_p, 200}, + {"modp14", scr_dh_modp14_p, sizeof scr_dh_modp14_p, 225}, + {"modp15", scr_dh_modp15_p, sizeof scr_dh_modp15_p, 275}, + {"modp16", scr_dh_modp16_p, sizeof scr_dh_modp16_p, 325}, + {"modp17", scr_dh_modp17_p, sizeof scr_dh_modp17_p, 375}, + {"modp18", scr_dh_modp18_p, sizeof scr_dh_modp18_p, 400}, +}; + +/* An OpenSSL DH named group, which the DH provider recognizes in explicit + * p and g. A NULL q is (p - 1) / 2. */ +typedef struct { + const unsigned char *p; + size_t p_len; + const unsigned char *g; + size_t g_len; + const unsigned char *q; + size_t q_len; + int keylength; +} ScDhNamed; + +static const unsigned char sd_two[] = {2}; + +#define SD_SAFE(p, keylength) {p, sizeof p, sd_two, 1, NULL, 0, keylength} +#define SD_RFC5114(name, keylength) \ + {scr_dh_##name##_p, sizeof scr_dh_##name##_p, scr_dh_##name##_g, sizeof scr_dh_##name##_g, \ + scr_dh_##name##_q, sizeof scr_dh_##name##_q, keylength} + +static const ScDhNamed sd_named[] = { + SD_SAFE(scr_dh_ffdhe2048_p, 225), SD_SAFE(scr_dh_ffdhe3072_p, 275), SD_SAFE(scr_dh_ffdhe4096_p, 325), + SD_SAFE(scr_dh_ffdhe6144_p, 375), SD_SAFE(scr_dh_ffdhe8192_p, 400), SD_SAFE(scr_dh_modp5_p, 200), + SD_SAFE(scr_dh_modp14_p, 225), SD_SAFE(scr_dh_modp15_p, 275), SD_SAFE(scr_dh_modp16_p, 325), + SD_SAFE(scr_dh_modp17_p, 375), SD_SAFE(scr_dh_modp18_p, 400), SD_RFC5114(dh_1024_160, 160), + SD_RFC5114(dh_2048_224, 224), SD_RFC5114(dh_2048_256, 224), +}; + +typedef struct ScDh { + size_t rc; + const ScDhGroup *group; /* crypto.getDiffieHellman's group, or NULL */ + const ScDhNamed *named; /* the named group createDiffieHellman's parameters equal, or NULL */ + mbedtls_mpi p, g; + mbedtls_mpi pub; /* when has_pub */ + mbedtls_mpi priv; /* when has_priv */ + bool has_pub; + bool has_priv; + int verify_error; /* -1 until computed */ +} ScDh; + +static ScrDynHandleOps sd_ops; +static ScrDynHandleOps sd_group_ops; + +static void *sd_retain(void *h) { + ((ScDh *)h)->rc++; + return h; +} + +static void sd_release(void *h) { + ScDh *d = h; + if (--d->rc) return; + mbedtls_mpi_free(&d->p); + mbedtls_mpi_free(&d->g); + mbedtls_mpi_free(&d->pub); + mbedtls_mpi_free(&d->priv); + mbedtls_platform_zeroize(d, sizeof *d); + free(d); +} + +static int sd_random(void *state, unsigned char *out, size_t len) { + (void)state; + arc4random_buf(out, len); + return 0; +} + +/* ── errors ───────────────────────────────────────────────────────────── */ + +static void sd_throw(int kind, const char *code, const char *message) { + scr_throw_error_msg_code(kind, message, strlen(message), code); +} + +static void sd_operation_failed(const char *message) { + sd_throw(SCR_ERR_ERROR, "ERR_CRYPTO_OPERATION_FAILED", message); +} + +/* An OpenSSL DH error as ThrowCryptoError reports it: the formatted + * message plus own library, reason and code properties, in Node's key + * order. */ +static void sd_throw_openssl(const char *packed, const char *reason, const char *code) { + char message[96]; + snprintf(message, sizeof message, "error:%s:Diffie-Hellman routines::%s", packed, reason); + ScrStr *text = scr_str_new(message, strlen(message)); + ScrError *e = scr_error_new(SCR_ERR_ERROR, text); + scr_str_release(text); + ScrStr *library = scr_str_new("Diffie-Hellman routines", 23); + scr_error_set_prop(e, "library", 7, scr_dyn_new_str(library)); + scr_str_release(library); + ScrStr *reason_text = scr_str_new(reason, strlen(reason)); + scr_error_set_prop(e, "reason", 6, scr_dyn_new_str(reason_text)); + scr_str_release(reason_text); + scr_error_set_code(e, code); + ScrStr *code_text = scr_str_new(code, strlen(code)); + scr_error_set_prop(e, "code", 4, scr_dyn_new_str(code_text)); + scr_str_release(code_text); + scr_throw_obj(e, &scr_error_retain_v, &scr_error_release_v, scr_error_trace_arg()); +} + +static void sd_bad_generator(void) { + sd_throw_openssl("02800065", "bad generator", "ERR_OSSL_DH_BAD_GENERATOR"); +} + +static void sd_too_long(void) { + static const char message[] = "DiffieHellman primes longer than 8192 bits have no native implementation"; + scr_throw_error_msg_code(SCR_ERR_ERROR, message, sizeof message - 1, "SC2020"); +} + +/* A key or generator past SD_MAX_VALUE_BYTES, which BN_bin2bn reads. */ +static void sd_value_too_long(void) { + char message[96]; + int n = snprintf(message, sizeof message, "DiffieHellman values longer than %zu bytes have no native implementation", + (size_t)SD_MAX_VALUE_BYTES); + scr_throw_error_msg_code(SCR_ERR_ERROR, message, n < 0 ? 0 : (size_t)n, "SC2020"); +} + +/* validateInt32(value, name, min). */ +static bool sd_validate_int32_min(const char *name, double value, int32_t min) { + bool integer = isfinite(value) && trunc(value) == value; + if (integer && value >= min && value <= INT32_MAX) return true; + char received[48]; + scr_num_received(value, received); + char text[192]; + int n = integer ? snprintf(text, sizeof text, + "The value of \"%s\" is out of range. It must be >= %ld && <= 2147483647. " + "Received %s", + name, (long)min, received) + : snprintf(text, sizeof text, + "The value of \"%s\" is out of range. It must be an integer. Received %s", name, + received); + scr_throw_error_msg_code(SCR_ERR_RANGE, text, n < 0 ? 0 : (size_t)n, "ERR_OUT_OF_RANGE"); + return false; +} + +/* validateInt32(value, name). */ +static bool sd_validate_int32(const char *name, double value) { + return sd_validate_int32_min(name, value, INT32_MIN); +} + +/* ── arithmetic ───────────────────────────────────────────────────────── */ + +/* The exponent digit width that keeps every mbedtls_mpi_exp_mod exponent + * within its 8192-bit limit. */ +#define SD_DIGIT_BITS (MBEDTLS_MPI_MAX_BITS - 1) + +/* base^e mod p, as BN_mod_exp_mont_consttime computes it: false for an + * even modulus or one below 3. Exponents past 8192 bits are split into + * SD_DIGIT_BITS-bit digits. */ +static bool sd_exp(mbedtls_mpi *out, const mbedtls_mpi *base, const mbedtls_mpi *e, const mbedtls_mpi *p) { + if (mbedtls_mpi_cmp_int(p, 1) <= 0 || mbedtls_mpi_get_bit(p, 0) == 0) return false; + size_t ebits = mbedtls_mpi_bitlen(e); + if (ebits <= MBEDTLS_MPI_MAX_BITS) return mbedtls_mpi_exp_mod(out, base, e, p, NULL) == 0; + /* base^e = Π (base^(2^(k·w)))^digit_k for the w-bit digits of e. */ + mbedtls_mpi acc, power, digit, term, step; + mbedtls_mpi_init(&acc); + mbedtls_mpi_init(&power); + mbedtls_mpi_init(&digit); + mbedtls_mpi_init(&term); + mbedtls_mpi_init(&step); + int ret = 0; + MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&acc, 1)); + MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&power, base)); + MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&step, 1)); + MBEDTLS_MPI_CHK(mbedtls_mpi_shift_l(&step, SD_DIGIT_BITS)); + for (size_t offset = 0; offset < ebits; offset += SD_DIGIT_BITS) { + /* Bit by bit, so each digit costs its own width, not the exponent's. */ + MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&digit, 0)); + for (size_t bit = 0; bit < SD_DIGIT_BITS && offset + bit < ebits; bit++) + if (mbedtls_mpi_get_bit(e, offset + bit)) MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(&digit, bit, 1)); + MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&term, &power, &digit, p, NULL)); + MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&acc, &acc, &term)); + MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&acc, &acc, p)); + if (offset + SD_DIGIT_BITS < ebits) MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&power, &power, &step, p, NULL)); + } + MBEDTLS_MPI_CHK(mbedtls_mpi_copy(out, &acc)); +cleanup: + mbedtls_mpi_free(&acc); + mbedtls_mpi_free(&power); + mbedtls_mpi_free(&digit); + mbedtls_mpi_free(&term); + mbedtls_mpi_free(&step); + return ret == 0; +} + +/* Drops a big-endian value's leading zero bytes, which BN_bin2bn ignores + * but mbedtls_mpi_read_binary counts against SD_MAX_VALUE_BYTES. */ +static void sd_strip(const unsigned char **data, size_t *len) { + while (*len > 0 && **data == 0) { + (*data)++; + (*len)--; + } +} + +/* BN_bin2bn: false when the value, without its leading zeros, is longer + * than SD_MAX_VALUE_BYTES. */ +static bool sd_read(mbedtls_mpi *x, const ScrBytes *bytes) { + const unsigned char *data = bytes->data; + size_t len = bytes->len; + sd_strip(&data, &len); + if (len > SD_MAX_VALUE_BYTES) return false; + if (mbedtls_mpi_read_binary(x, data, len) != 0) scr_trap("scriptc: out of memory\n"); + return true; +} + +/* BN_cmp over two big-endian values, for ones sd_read cannot hold. */ +static int sd_cmp_bytes(const ScrBytes *a, const ScrBytes *b) { + const unsigned char *a_data = a->data, *b_data = b->data; + size_t a_len = a->len, b_len = b->len; + sd_strip(&a_data, &a_len); + sd_strip(&b_data, &b_len); + if (a_len != b_len) return a_len < b_len ? -1 : 1; + return a_len ? memcmp(a_data, b_data, a_len) : 0; +} + +/* A uniformly random number of exactly `bits` bits (the top bit set), and + * odd when `odd`, as BN_priv_rand writes it. */ +static bool sd_random_bits(mbedtls_mpi *x, size_t bits, bool odd) { + size_t len = (bits + 7) / 8; + unsigned char *buf = malloc(len); + if (!buf) scr_trap("scriptc: out of memory\n"); + arc4random_buf(buf, len); + unsigned extra = (unsigned)(len * 8 - bits); + buf[0] &= (unsigned char)(0xff >> extra); + buf[0] |= (unsigned char)(0x80 >> extra); + if (odd) buf[len - 1] |= 1; + bool ok = mbedtls_mpi_read_binary(x, buf, len) == 0; + mbedtls_platform_zeroize(buf, len); + free(buf); + return ok; +} + +/* ── primes ───────────────────────────────────────────────────────────── */ + +/* The odd primes below 17864 (OpenSSL's first 2048 primes but 2), which + * trial division divides by. Consecutive primes are grouped into products + * below the half-limb bound mbedtls_mpi_mod_int divides correctly by, so + * one call reduces by several. */ +#define SD_SMALL_PRIMES 2047 +#define SD_SMALL_LIMIT 17864 +#define SD_PRODUCT_LIMIT ((uint64_t)1 << (sizeof(mbedtls_mpi_uint) * 4)) + +typedef struct { + uint16_t primes[SD_SMALL_PRIMES]; + uint64_t products[SD_SMALL_PRIMES]; + uint16_t starts[SD_SMALL_PRIMES + 1]; /* products[g] covers primes[starts[g]] to primes[starts[g + 1] - 1] */ + size_t groups; + uint32_t mods[SD_SMALL_PRIMES]; +} ScDhSmallPrimes; + +static ScDhSmallPrimes *sd_small_primes(void) { + ScDhSmallPrimes *t = calloc(1, sizeof *t); + unsigned char *composite = calloc(SD_SMALL_LIMIT, 1); + if (!t || !composite) scr_trap("scriptc: out of memory\n"); + size_t count = 0; + for (uint32_t n = 3; n < SD_SMALL_LIMIT && count < SD_SMALL_PRIMES; n += 2) { + if (composite[n]) continue; + t->primes[count++] = (uint16_t)n; + for (uint32_t m = n * n; m < SD_SMALL_LIMIT; m += 2 * n) composite[m] = 1; + } + free(composite); + uint64_t product = 1; + for (size_t i = 0; i < SD_SMALL_PRIMES; i++) { + if (product > SD_PRODUCT_LIMIT / t->primes[i]) { + t->products[t->groups++] = product; + t->starts[t->groups] = (uint16_t)i; + product = 1; + } + product *= t->primes[i]; + } + t->products[t->groups++] = product; + t->starts[t->groups] = SD_SMALL_PRIMES; + return t; +} + +/* x mod each small prime, into t->mods. */ +static bool sd_small_residues(ScDhSmallPrimes *t, const mbedtls_mpi *x) { + for (size_t g = 0; g < t->groups; g++) { + mbedtls_mpi_uint r; + if (mbedtls_mpi_mod_int(&r, x, (mbedtls_mpi_sint)t->products[g]) != 0) return false; + for (size_t i = t->starts[g]; i < t->starts[g + 1]; i++) t->mods[i] = (uint32_t)(r % t->primes[i]); + } + return true; +} + +#if defined(__SIZEOF_INT128__) +#define SD_MONT 1 +typedef unsigned __int128 sd_u128; + +/* Montgomery arithmetic modulo an odd n of k 64-bit limbs, little-endian, + * with R = 2^(64k), for the Miller-Rabin rounds. It runs in variable time + * and reads only public values. */ +typedef struct { + size_t k; + uint64_t mm; /* -n^-1 mod 2^64 */ + uint64_t *n; /* k limbs */ + uint64_t *rr; /* R^2 mod n, k limbs */ + uint64_t *acc; /* k limbs */ + uint64_t *table; /* 16·k limbs: base^i·R mod n */ + uint64_t *t; /* 2k + 1 limbs of products */ +} ScDhMont; + +static void sd_limbs_read(uint64_t *out, size_t k, const mbedtls_mpi *x, unsigned char *buf) { + if (mbedtls_mpi_write_binary_le(x, buf, 8 * k) != 0) scr_trap("scriptc: internal error: limb overflow\n"); + for (size_t i = 0; i < k; i++) { + uint64_t w = 0; + for (size_t b = 8; b-- > 0;) w = (w << 8) | buf[8 * i + b]; + out[i] = w; + } +} + +static bool sd_limbs_write(mbedtls_mpi *x, const uint64_t *in, size_t k, unsigned char *buf) { + for (size_t i = 0; i < k; i++) + for (size_t b = 0; b < 8; b++) buf[8 * i + b] = (unsigned char)(in[i] >> (8 * b)); + return mbedtls_mpi_read_binary_le(x, buf, 8 * k) == 0; +} + +static bool sd_mont_init(ScDhMont *m, const mbedtls_mpi *n) { + size_t k = (mbedtls_mpi_bitlen(n) + 63) / 64; + m->k = k; + m->n = calloc(21 * k + 1, sizeof(uint64_t)); + if (!m->n) scr_trap("scriptc: out of memory\n"); + m->rr = m->n + k; + m->acc = m->rr + k; + m->table = m->acc + k; + m->t = m->table + 16 * k; + unsigned char *buf = malloc(8 * k); + if (!buf) scr_trap("scriptc: out of memory\n"); + sd_limbs_read(m->n, k, n, buf); + /* Newton's iteration doubles the correct low bits of n^-1 from 3. */ + uint64_t inverse = m->n[0]; + for (int i = 0; i < 6; i++) inverse *= 2 - m->n[0] * inverse; + m->mm = (uint64_t)0 - inverse; + mbedtls_mpi rr; + mbedtls_mpi_init(&rr); + bool ok = mbedtls_mpi_lset(&rr, 1) == 0 && mbedtls_mpi_shift_l(&rr, 128 * k) == 0 && + mbedtls_mpi_mod_mpi(&rr, &rr, n) == 0; + if (ok) sd_limbs_read(m->rr, k, &rr, buf); + mbedtls_mpi_free(&rr); + free(buf); + return ok; +} + +static void sd_mont_free(ScDhMont *m) { + free(m->n); +} + +/* r = v mod n for v < 2n, given as k limbs and a top limb. */ +static void sd_mont_final(const ScDhMont *m, uint64_t *r, const uint64_t *v, uint64_t top) { + size_t k = m->k; + bool ge = top != 0; + if (!ge) { + ge = true; + for (size_t j = k; j-- > 0;) + if (v[j] != m->n[j]) { + ge = v[j] > m->n[j]; + break; + } + } + if (!ge) { + if (r != v) memmove(r, v, k * sizeof *r); + return; + } + uint64_t borrow = 0; + for (size_t j = 0; j < k; j++) { + sd_u128 d = (sd_u128)v[j] - m->n[j] - borrow; + r[j] = (uint64_t)d; + borrow = (uint64_t)(d >> 64) & 1; + } +} + +/* r = t·R^-1 mod n for the 2k-limb product in t. */ +static void sd_mont_redc(ScDhMont *m, uint64_t *r) { + size_t k = m->k; + uint64_t *t = m->t; + t[2 * k] = 0; + for (size_t i = 0; i < k; i++) { + uint64_t q = t[i] * m->mm; + uint64_t carry = 0; + for (size_t j = 0; j < k; j++) { + sd_u128 v = (sd_u128)q * m->n[j] + t[i + j] + carry; + t[i + j] = (uint64_t)v; + carry = (uint64_t)(v >> 64); + } + for (size_t j = i + k; carry != 0 && j <= 2 * k; j++) { + sd_u128 v = (sd_u128)t[j] + carry; + t[j] = (uint64_t)v; + carry = (uint64_t)(v >> 64); + } + } + sd_mont_final(m, r, t + k, t[2 * k]); +} + +static void sd_mont_mul(ScDhMont *m, uint64_t *r, const uint64_t *a, const uint64_t *b) { + size_t k = m->k; + uint64_t *t = m->t; + memset(t, 0, 2 * k * sizeof *t); + for (size_t i = 0; i < k; i++) { + uint64_t carry = 0; + for (size_t j = 0; j < k; j++) { + sd_u128 v = (sd_u128)a[i] * b[j] + t[i + j] + carry; + t[i + j] = (uint64_t)v; + carry = (uint64_t)(v >> 64); + } + t[i + k] = carry; + } + sd_mont_redc(m, r); +} + +/* r = a^2·R^-1 mod n: the cross products once, doubled, plus the squares. */ +static void sd_mont_sqr(ScDhMont *m, uint64_t *r, const uint64_t *a) { + size_t k = m->k; + uint64_t *t = m->t; + memset(t, 0, 2 * k * sizeof *t); + for (size_t i = 0; i < k; i++) { + uint64_t carry = 0; + for (size_t j = i + 1; j < k; j++) { + sd_u128 v = (sd_u128)a[i] * a[j] + t[i + j] + carry; + t[i + j] = (uint64_t)v; + carry = (uint64_t)(v >> 64); + } + t[i + k] = carry; + } + uint64_t shifted = 0; + for (size_t i = 0; i < 2 * k; i++) { + uint64_t v = t[i]; + t[i] = (v << 1) | shifted; + shifted = v >> 63; + } + uint64_t carry = 0; + for (size_t i = 0; i < k; i++) { + sd_u128 square = (sd_u128)a[i] * a[i]; + sd_u128 low = (sd_u128)t[2 * i] + (uint64_t)square + carry; + t[2 * i] = (uint64_t)low; + sd_u128 high = (sd_u128)t[2 * i + 1] + (uint64_t)(square >> 64) + (uint64_t)(low >> 64); + t[2 * i + 1] = (uint64_t)high; + carry = (uint64_t)(high >> 64); + } + sd_mont_redc(m, r); +} + +/* x = 2x mod n. */ +static void sd_mont_double(const ScDhMont *m, uint64_t *x) { + size_t k = m->k; + uint64_t top = x[k - 1] >> 63; + for (size_t j = k; j-- > 1;) x[j] = (x[j] << 1) | (x[j - 1] >> 63); + x[0] <<= 1; + sd_mont_final(m, x, x, top); +} + +/* out = base^e mod n, or 2^e mod n for a NULL base. A base of 2 doubles + * instead of multiplying; others use a 4-bit fixed window. */ +static bool sd_mont_pow(ScDhMont *m, mbedtls_mpi *out, const mbedtls_mpi *base, const mbedtls_mpi *e) { + size_t k = m->k; + unsigned char *buf = malloc(8 * k); + if (!buf) scr_trap("scriptc: out of memory\n"); + /* acc = R mod n, the Montgomery form of 1. */ + memset(m->t, 0, 2 * k * sizeof *m->t); + memcpy(m->t, m->rr, k * sizeof *m->t); + sd_mont_redc(m, m->acc); + size_t bits = mbedtls_mpi_bitlen(e); + if (!base) { + for (size_t i = bits; i-- > 0;) { + sd_mont_sqr(m, m->acc, m->acc); + if (mbedtls_mpi_get_bit(e, i)) sd_mont_double(m, m->acc); + } + } else { + memcpy(m->table, m->acc, k * sizeof *m->table); + sd_limbs_read(m->table + k, k, base, buf); + sd_mont_mul(m, m->table + k, m->table + k, m->rr); + for (size_t i = 2; i < 16; i++) sd_mont_mul(m, m->table + i * k, m->table + (i - 1) * k, m->table + k); + size_t windows = (bits + 3) / 4; + for (size_t w = windows; w-- > 0;) { + if (w + 1 < windows) + for (int s = 0; s < 4; s++) sd_mont_sqr(m, m->acc, m->acc); + unsigned digit = 0; + for (size_t b = 4; b-- > 0;) digit = (digit << 1) | (unsigned)mbedtls_mpi_get_bit(e, 4 * w + b); + if (digit) sd_mont_mul(m, m->acc, m->acc, m->table + digit * k); + } + } + /* Leave the Montgomery form. */ + memset(m->t, 0, 2 * k * sizeof *m->t); + memcpy(m->t, m->acc, k * sizeof *m->t); + sd_mont_redc(m, m->acc); + bool ok = sd_limbs_write(out, m->acc, k, buf); + free(buf); + return ok; +} +#else +#define SD_MONT 0 +#endif + +/* Miller-Rabin state for an odd n > 3: n - 1 = d·2^s. */ +typedef struct { + mbedtls_mpi n1, d, a, x; + size_t s; +#if SD_MONT + ScDhMont mont; +#else + mbedtls_mpi rr; /* the Montgomery constant mbedtls_mpi_exp_mod caches */ +#endif +} ScDhMillerRabin; + +static bool sd_mr_init(ScDhMillerRabin *m, const mbedtls_mpi *n) { + mbedtls_mpi_init(&m->n1); + mbedtls_mpi_init(&m->d); + mbedtls_mpi_init(&m->a); + mbedtls_mpi_init(&m->x); +#if SD_MONT + if (!sd_mont_init(&m->mont, n)) return false; +#else + mbedtls_mpi_init(&m->rr); +#endif + if (mbedtls_mpi_sub_int(&m->n1, n, 1) != 0 || mbedtls_mpi_copy(&m->d, &m->n1) != 0) return false; + m->s = mbedtls_mpi_lsb(&m->d); + return mbedtls_mpi_shift_r(&m->d, m->s) == 0; +} + +static void sd_mr_free(ScDhMillerRabin *m) { + mbedtls_mpi_free(&m->n1); + mbedtls_mpi_free(&m->d); + mbedtls_mpi_free(&m->a); + mbedtls_mpi_free(&m->x); +#if SD_MONT + sd_mont_free(&m->mont); +#else + mbedtls_mpi_free(&m->rr); +#endif +} + +/* x = a^e mod n, or 2^e mod n when base2. */ +static bool sd_mr_pow(ScDhMillerRabin *m, const mbedtls_mpi *n, const mbedtls_mpi *e, bool base2) { +#if SD_MONT + (void)n; + return sd_mont_pow(&m->mont, &m->x, base2 ? NULL : &m->a, e); +#else + if (base2 && mbedtls_mpi_lset(&m->a, 2) != 0) return false; + return mbedtls_mpi_exp_mod(&m->x, &m->a, e, n, &m->rr) == 0; +#endif +} + +/* One round with the base 2, or with a uniformly random base in + * [2, n - 2]: 1 when n is a strong probable prime to the base, 0 when it + * is composite, -1 when an operation fails. */ +static int sd_mr_round(ScDhMillerRabin *m, const mbedtls_mpi *n, bool base2) { + if (!base2 && mbedtls_mpi_random(&m->a, 2, &m->n1, sd_random, NULL) != 0) return -1; + if (!sd_mr_pow(m, n, &m->d, base2)) return -1; + if (mbedtls_mpi_cmp_int(&m->x, 1) == 0 || mbedtls_mpi_cmp_mpi(&m->x, &m->n1) == 0) return 1; + for (size_t i = 1; i < m->s; i++) { + if (mbedtls_mpi_mul_mpi(&m->x, &m->x, &m->x) != 0 || mbedtls_mpi_mod_mpi(&m->x, &m->x, n) != 0) return -1; + if (mbedtls_mpi_cmp_mpi(&m->x, &m->n1) == 0) return 1; + if (mbedtls_mpi_cmp_int(&m->x, 1) == 0) return 0; + } + return 0; +} + +/* 2^(n-1) ≡ 1 (mod n) for an odd n > 3. */ +static int sd_fermat2(const mbedtls_mpi *n) { + ScDhMillerRabin m; + int ret = sd_mr_init(&m, n) && sd_mr_pow(&m, n, &m.n1, true) ? mbedtls_mpi_cmp_int(&m.x, 1) == 0 : -1; + sd_mr_free(&m); + return ret; +} + +/* OpenSSL's Miller-Rabin round count: 64, or 128 past 2048 bits. */ +static int sd_mr_rounds(size_t bits) { + return bits > 2048 ? 128 : 64; +} + +/* BN_is_prime_ex(x, checks): trial division by the small primes, then + * Miller-Rabin rounds with random bases, at least OpenSSL's round count. */ +static bool sd_is_prime_checks(ScDhSmallPrimes *t, const mbedtls_mpi *x, int checks) { + if (mbedtls_mpi_cmp_int(x, 2) < 0) return false; + if (mbedtls_mpi_get_bit(x, 0) == 0) return mbedtls_mpi_cmp_int(x, 2) == 0; + if (!sd_small_residues(t, x)) return false; + for (size_t i = 0; i < SD_SMALL_PRIMES; i++) + if (t->mods[i] == 0) return mbedtls_mpi_cmp_int(x, t->primes[i]) == 0; + /* No prime factor up to sqrt(x). */ + if (mbedtls_mpi_cmp_int(x, (mbedtls_mpi_sint)SD_SMALL_LIMIT * SD_SMALL_LIMIT) < 0) return true; + ScDhMillerRabin m; + bool prime = sd_mr_init(&m, x); + int rounds = sd_mr_rounds(mbedtls_mpi_bitlen(x)); + if (checks > rounds) rounds = checks; + for (int i = 0; i < rounds && prime; i++) prime = sd_mr_round(&m, x, false) == 1; + sd_mr_free(&m); + return prime; +} + +/* BN_check_prime. */ +static bool sd_is_prime(ScDhSmallPrimes *t, const mbedtls_mpi *x) { + return sd_is_prime_checks(t, x, 0); +} + +/* DH_check for parameters without q, as ncrypto's CheckDhParams reports + * it. */ +static int sd_check_params(const mbedtls_mpi *p, const mbedtls_mpi *g) { + int codes = 0; + if (mbedtls_mpi_get_bit(p, 0) == 0) codes |= SD_P_NOT_PRIME; + if (mbedtls_mpi_cmp_int(g, 1) <= 0) codes |= SD_NOT_SUITABLE_GENERATOR; + if (mbedtls_mpi_bitlen(p) < SD_MIN_MODULUS_BITS) codes |= SD_MODULUS_TOO_SMALL; + mbedtls_mpi t; + mbedtls_mpi_init(&t); + if (mbedtls_mpi_sub_int(&t, p, 1) != 0) scr_trap("scriptc: out of memory\n"); + if (mbedtls_mpi_cmp_mpi(g, &t) >= 0) codes |= SD_NOT_SUITABLE_GENERATOR; + /* BN_check_prime(p), then BN_check_prime((p - 1) / 2) for a prime p. + * For an odd p > 3 whose (p - 1) / 2 is prime, p is prime exactly when + * 3 does not divide it and 2^(p-1) ≡ 1 (mod p) (Pocklington's + * criterion), so (p - 1) / 2 is tested first. */ + ScDhSmallPrimes *small = sd_small_primes(); + if (mbedtls_mpi_copy(&t, p) != 0 || mbedtls_mpi_shift_r(&t, 1) != 0) scr_trap("scriptc: out of memory\n"); + bool p_prime, q_prime; + if (mbedtls_mpi_get_bit(p, 0) == 0 || mbedtls_mpi_cmp_int(p, 3) <= 0) { + p_prime = sd_is_prime(small, p); + q_prime = p_prime && sd_is_prime(small, &t); + } else { + q_prime = sd_is_prime(small, &t); + mbedtls_mpi_uint r = 0; + if (!q_prime) p_prime = sd_is_prime(small, p); + else p_prime = mbedtls_mpi_mod_int(&r, p, 3) == 0 && r != 0 && sd_fermat2(p) == 1; + } + if (!p_prime) codes |= SD_P_NOT_PRIME; + else if (!q_prime) codes |= SD_P_NOT_SAFE_PRIME; + free(small); + mbedtls_mpi_free(&t); + return codes; +} + +/* The named group whose p and g equal these, as ossl_dh_cache_named_group + * finds it, or NULL. */ +static const ScDhNamed *sd_find_named(const mbedtls_mpi *p, const mbedtls_mpi *g) { + size_t p_len = mbedtls_mpi_size(p); + const ScDhNamed *found = NULL; + mbedtls_mpi x; + mbedtls_mpi_init(&x); + for (size_t i = 0; i < sizeof sd_named / sizeof sd_named[0] && !found; i++) { + const ScDhNamed *n = &sd_named[i]; + if (n->p_len != p_len) continue; + if (mbedtls_mpi_read_binary(&x, n->p, n->p_len) != 0 || mbedtls_mpi_cmp_mpi(&x, p) != 0) continue; + if (mbedtls_mpi_read_binary(&x, n->g, n->g_len) == 0 && mbedtls_mpi_cmp_mpi(&x, g) == 0) found = n; + } + mbedtls_mpi_free(&x); + return found; +} + +/* The safe-prime sieve: the odd primes below a bound that grows with the + * prime's length and do not divide the step `add`, each with add^-1 and a + * start's residue modulo it, and the marks of a window of candidates + * start + k·add. */ +#define SD_SIEVE_WINDOW 65536 + +static uint32_t sd_sieve_bound(size_t bits) { + /* mbedtls_mpi_mod_int divides correctly by values below 2^(limb bits / 2). */ + if (sizeof(mbedtls_mpi_uint) < 8) return 1u << 16; + return bits < 1024 ? 1u << 18 : bits < 2048 ? 1u << 22 : 1u << 24; +} + +typedef struct { + uint32_t *primes; + uint32_t *inverse; + uint32_t *residue; + size_t count; + unsigned char marks[SD_SIEVE_WINDOW]; +} ScDhSieve; + +/* a^-1 mod m for gcd(a, m) = 1. */ +static uint32_t sd_inverse(uint32_t a, uint32_t m) { + int64_t t = 0, next = 1; + int64_t r = m, rest = a; + while (rest != 0) { + int64_t quotient = r / rest; + int64_t t_next = t - quotient * next; + t = next; + next = t_next; + int64_t r_next = r - quotient * rest; + r = rest; + rest = r_next; + } + return (uint32_t)(t < 0 ? t + m : t); +} + +static ScDhSieve *sd_sieve_new(size_t bits, unsigned add) { + uint32_t bound = sd_sieve_bound(bits); + ScDhSieve *sv = calloc(1, sizeof *sv); + unsigned char *composite = calloc(bound / 2, 1); /* composite[i] for 2i + 1 */ + if (!sv || !composite) scr_trap("scriptc: out of memory\n"); + size_t count = 0; + for (uint32_t i = 1; i < bound / 2; i++) { + if (composite[i]) continue; + uint32_t n = 2 * i + 1; + for (uint64_t m = (uint64_t)n * n; m < bound; m += 2 * n) composite[m / 2] = 1; + if (add % n != 0) count++; + } + sv->primes = malloc(count * sizeof(uint32_t)); + sv->inverse = malloc(count * sizeof(uint32_t)); + sv->residue = malloc(count * sizeof(uint32_t)); + if (!sv->primes || !sv->inverse || !sv->residue) scr_trap("scriptc: out of memory\n"); + for (uint32_t i = 1; i < bound / 2; i++) { + uint32_t n = 2 * i + 1; + if (composite[i] || add % n == 0) continue; + sv->inverse[sv->count] = sd_inverse(add % n, n); + sv->primes[sv->count++] = n; + } + free(composite); + return sv; +} + +static void sd_sieve_free(ScDhSieve *sv) { + free(sv->primes); + free(sv->inverse); + free(sv->residue); + free(sv); +} + +/* Marks the candidates start + k·add of the window that a sieve prime + * divides, or whose (p - 1) / 2 it divides, then moves the residues to + * the next window. */ +static void sd_sieve_window(ScDhSieve *sv, unsigned add) { + memset(sv->marks, 0, sizeof sv->marks); + for (size_t i = 0; i < sv->count; i++) { + uint64_t r = sv->primes[i]; + uint64_t s = sv->residue[i]; + /* start + k·add ≡ t (mod r) for t = 0 and t = 1. */ + for (uint64_t t = 0; t < 2; t++) { + uint64_t k = (r + t - s) % r * sv->inverse[i] % r; + for (; k < SD_SIEVE_WINDOW; k += r) sv->marks[k] = 1; + } + sv->residue[i] = (uint32_t)((s + (uint64_t)SD_SIEVE_WINDOW * add) % r); + } +} + +/* A random safe prime of exactly `bits` bits with p ≡ rem (mod add), + * rem ≡ 2 (mod 3), as BN_generate_prime_ex2(p, bits, safe = 1, add, rem) + * draws one: a random start of `bits` bits moved to p ≡ rem (mod add), + * then candidates stepping by `add` past values that a sieve prime + * divides or that make (p - 1) / 2 divisible by one. A candidate is kept + * when p is a strong probable prime to the base 2 and q = (p - 1) / 2 + * passes OpenSSL's Miller-Rabin round count; a prime q then proves p prime + * (Pocklington's criterion with 2^(p-1) ≡ 1 and gcd(2^2 - 1, p) = 1). + * Candidates past `bits` bits take a new start. With `top_two`, starts + * also set the second-highest bit, as BN_RAND_TOP_TWO does. */ +static bool sd_generate_safe_prime(mbedtls_mpi *p, size_t bits, unsigned add, unsigned rem, bool top_two) { + ScDhSieve *sv = sd_sieve_new(bits, add); + int rounds = sd_mr_rounds(bits); + mbedtls_mpi start, q; + mbedtls_mpi_init(&start); + mbedtls_mpi_init(&q); + int ret = 0; + while (ret == 0) { + mbedtls_mpi_uint r; + if (!sd_random_bits(&start, bits, true) || (top_two && mbedtls_mpi_set_bit(&start, bits - 2, 1) != 0) || + mbedtls_mpi_mod_int(&r, &start, add) != 0 || + mbedtls_mpi_sub_int(&start, &start, (mbedtls_mpi_sint)r) != 0 || + mbedtls_mpi_add_int(&start, &start, rem) != 0 || + (mbedtls_mpi_bitlen(&start) < bits && mbedtls_mpi_add_int(&start, &start, add) != 0)) { + ret = -1; + break; + } + for (size_t i = 0; i < sv->count && ret == 0; i++) { + if (mbedtls_mpi_mod_int(&r, &start, sv->primes[i]) != 0) ret = -1; + sv->residue[i] = (uint32_t)r; + } + bool fits = true; + while (ret == 0 && fits) { + sd_sieve_window(sv, add); + for (uint32_t k = 0; k < SD_SIEVE_WINDOW && ret == 0 && fits; k++) { + if (sv->marks[k]) continue; + if (mbedtls_mpi_add_int(p, &start, (mbedtls_mpi_sint)k * add) != 0 || mbedtls_mpi_copy(&q, p) != 0 || + mbedtls_mpi_shift_r(&q, 1) != 0) { + ret = -1; + break; + } + fits = mbedtls_mpi_bitlen(p) == bits; + if (!fits) break; + ScDhMillerRabin mr; + ret = sd_mr_init(&mr, p) ? sd_mr_round(&mr, p, true) : -1; + sd_mr_free(&mr); + if (ret != 1) continue; + ret = sd_mr_init(&mr, &q) ? sd_mr_round(&mr, &q, true) : -1; + for (int i = 1; i < rounds && ret == 1; i++) ret = sd_mr_round(&mr, &q, false); + sd_mr_free(&mr); + } + if (ret == 0 && fits && mbedtls_mpi_add_int(&start, &start, (mbedtls_mpi_sint)SD_SIEVE_WINDOW * add) != 0) + ret = -1; + } + } + sd_sieve_free(sv); + mbedtls_mpi_free(&start); + mbedtls_mpi_free(&q); + return ret == 1; +} + +/* ── construction ─────────────────────────────────────────────────────── */ + +static ScDh *sd_alloc(void) { + ScDh *d = calloc(1, sizeof *d); + if (!d) scr_trap("scriptc: out of memory\n"); + d->rc = 1; + mbedtls_mpi_init(&d->p); + mbedtls_mpi_init(&d->g); + mbedtls_mpi_init(&d->pub); + mbedtls_mpi_init(&d->priv); + return d; +} + +static ScrDyn *sd_box(ScDh *d) { + ScrDynHandleTag tag = d->group ? SCR_DYNH_DIFFIE_HELLMAN_GROUP : SCR_DYNH_DIFFIE_HELLMAN; + scr_dyn_handle_install(tag, d->group ? &sd_group_ops : &sd_ops); + ScrDyn *result = scr_dyn_new_handle(d, tag); /* retains */ + sd_release(d); + return result; +} + +static bool sd_is_view(const ScrDyn *value) { + return value->kind == SCR_DYN_BYTES || scr_buffer_storage_is(value); +} + +/* Buffer.isEncoding(value). */ +static bool sd_is_encoding(const ScrDyn *value) { + return value->kind == SCR_DYN_STR && value->v.str->len > 0 && ca_normalize_encoding(value->v.str) != NULL; +} + +/* new DiffieHellman(primeLength, generator): generated parameters. */ +static ScrDyn *sd_generate(double bits, const ScrBytes *generator_bytes, double generator) { + if (bits < 2) { + sd_throw_openssl("0280007E", "modulus too small", "ERR_OSSL_DH_MODULUS_TOO_SMALL"); + return NULL; + } + if (generator_bytes) { + sd_throw(SCR_ERR_TYPE, "ERR_INVALID_ARG_TYPE", "Second argument must be an int32"); + return NULL; + } + if (generator < 2) { + sd_bad_generator(); + return NULL; + } + if (bits < SD_MIN_MODULUS_BITS || bits > SD_MAX_MODULUS_BITS) { + sd_throw(SCR_ERR_TYPE, "ERR_INVALID_ARG_VALUE", "Invalid DH parameters"); + return NULL; + } + if (bits > MBEDTLS_MPI_MAX_BITS) { + sd_too_long(); + return NULL; + } + unsigned add = 12; + if (generator == 2) add = 24; + else if (generator == 5) add = 60; + ScDh *d = sd_alloc(); + if (!sd_generate_safe_prime(&d->p, (size_t)bits, add, add - 1, false) || mbedtls_mpi_lset(&d->g, (mbedtls_mpi_sint)generator) != 0) { + sd_release(d); + sd_throw(SCR_ERR_TYPE, "ERR_INVALID_ARG_VALUE", "Invalid DH parameters"); + return NULL; + } + /* A safe prime of at least 512 bits with a generator below p - 1 has no + * DH_check findings. */ + d->verify_error = 0; + return sd_box(d); +} + +/* new DiffieHellman(prime, generator) over explicit parameters. */ +static ScrDyn *sd_from_prime(const ScrBytes *prime, const ScrBytes *generator_bytes, double generator) { + ScDh *d = sd_alloc(); + bool p_held = sd_read(&d->p, prime); + bool g_held = true; + if (generator_bytes) g_held = sd_read(&d->g, generator_bytes); + else if (mbedtls_mpi_lset(&d->g, (mbedtls_mpi_sint)generator) != 0) scr_trap("scriptc: out of memory\n"); + if (!p_held || !g_held) { + /* A prime this long is past MBEDTLS_MPI_MAX_BITS, and a generator + * this long is at least a prime of SD_MIN_MODULUS_BITS. */ + bool bad = g_held ? mbedtls_mpi_cmp_int(&d->g, 2) < 0 + : !p_held ? sd_cmp_bytes(generator_bytes, prime) >= 0 + : mbedtls_mpi_bitlen(&d->p) >= SD_MIN_MODULUS_BITS; + sd_release(d); + if (bad) sd_bad_generator(); + else if (!p_held) sd_too_long(); + else sd_value_too_long(); + return NULL; + } + if (mbedtls_mpi_cmp_int(&d->g, 2) < 0 || + (mbedtls_mpi_bitlen(&d->p) >= SD_MIN_MODULUS_BITS && mbedtls_mpi_cmp_mpi(&d->g, &d->p) >= 0)) { + sd_release(d); + sd_bad_generator(); + return NULL; + } + if (mbedtls_mpi_bitlen(&d->p) > MBEDTLS_MPI_MAX_BITS) { + sd_release(d); + sd_too_long(); + return NULL; + } + d->named = sd_find_named(&d->p, &d->g); + /* A named group's parameters have no DH_check findings. Other + * parameters are checked when verifyError is first read. */ + d->verify_error = d->named ? 0 : -1; + return sd_box(d); +} + +/* new DiffieHellman(sizeOrKey, keyEncoding, generator, genEncoding). */ +static ScrDyn *sd_new(const ScrDyn *size_or_key, const ScrDyn *key_encoding, const ScrDyn *generator, + const ScrDyn *generator_encoding) { + static const char *const types = + "one of type number or string or an instance of ArrayBuffer, Buffer, TypedArray, or DataView"; + bool size = size_or_key->kind == SCR_DYN_NUM; + if (!size && size_or_key->kind != SCR_DYN_STR && !sd_is_view(size_or_key)) { + scr_dyn_arg_type_fail("sizeOrKey", types, size_or_key); + return NULL; + } + if (size && !sd_validate_int32("sizeOrKey", size_or_key->v.num)) return NULL; + /* A truthy keyEncoding that names no encoding is the generator. */ + const ScrDyn *gen = generator; + const ScrDyn *gen_encoding = generator_encoding; + const ScrDyn *encoding = key_encoding; + if (scr_dyn_truthy(key_encoding) && !sd_is_encoding(key_encoding) && + !(key_encoding->kind == SCR_DYN_STR && ca_str_is(key_encoding->v.str, "buffer"))) { + gen_encoding = generator; + gen = key_encoding; + encoding = scr_dyn_undefined(); + } + ScrBytes *prime = NULL; + if (size_or_key->kind == SCR_DYN_STR) prime = ca_string_bytes(SD_SUBJECT, size_or_key->v.str, encoding); + else if (!size) prime = scr_bytes_buffer_source(size_or_key); + if (!size && !prime) return NULL; + ScrBytes *gen_bytes = NULL; + double gen_number = 2; + ScrDyn *result = NULL; + if (!scr_dyn_truthy(gen)) { + gen_number = 2; + } else if (gen->kind == SCR_DYN_NUM) { + if (!sd_validate_int32("generator", gen->v.num)) goto done; + gen_number = gen->v.num; + } else if (gen->kind == SCR_DYN_STR) { + if (!(gen_bytes = ca_string_bytes(SD_SUBJECT, gen->v.str, gen_encoding))) goto done; + } else if (sd_is_view(gen)) { + gen_bytes = scr_bytes_buffer_source(gen); + } else { + scr_dyn_arg_type_fail("generator", types, gen); + goto done; + } + result = size ? sd_generate(size_or_key->v.num + 0, gen_bytes, gen_number) + : sd_from_prime(prime, gen_bytes, gen_number); +done: + if (prime) scr_bytes_release(prime); + if (gen_bytes) scr_bytes_release(gen_bytes); + return result; +} + +ScrDyn *scr_crypto_dh_new(ScrDyn *size_or_key, ScrDyn *key_encoding, ScrDyn *generator, ScrDyn *generator_encoding) { + ScrDyn *args[4] = {size_or_key, key_encoding, generator, generator_encoding}; + ScrDyn *unboxed[4] = {NULL, NULL, NULL, NULL}; + ScrDyn *result = NULL; + for (size_t i = 0; i < 4; i++) + if (!(unboxed[i] = ca_unbox(args[i]))) goto done; + result = sd_new(unboxed[0], unboxed[1], unboxed[2], unboxed[3]); +done: + for (size_t i = 0; i < 4; i++) scr_dyn_release(unboxed[i]); + return result; +} + +/* new DiffieHellmanGroup(name): names match case-insensitively. */ +ScrDyn *scr_crypto_dh_group_new(ScrDyn *name) { + ScrDyn *unboxed = ca_unbox(name); + if (!unboxed) return NULL; + if (unboxed->kind != SCR_DYN_STR) { + scr_dyn_release(unboxed); + sd_throw(SCR_ERR_TYPE, "ERR_INVALID_ARG_TYPE", "Group name must be a string"); + return NULL; + } + const ScDhGroup *group = NULL; + for (size_t i = 0; i < sizeof sd_groups / sizeof sd_groups[0] && !group; i++) + if (ca_ascii_eq_ci(unboxed->v.str->data, unboxed->v.str->len, sd_groups[i].name)) group = &sd_groups[i]; + scr_dyn_release(unboxed); + if (!group) { + sd_throw(SCR_ERR_ERROR, "ERR_CRYPTO_UNKNOWN_DH_GROUP", "Unknown DH group"); + return NULL; + } + ScDh *d = sd_alloc(); + d->group = group; + if (mbedtls_mpi_read_binary(&d->p, group->p, group->p_len) != 0 || mbedtls_mpi_lset(&d->g, 2) != 0) + scr_trap("scriptc: out of memory\n"); + d->verify_error = 0; + return sd_box(d); +} + +/* ── checkPrime and generatePrime ───────────────────────────────────────── + * crypto.checkPrime(Sync) and generatePrime(Sync) over the primality test + * and prime search above, with random.js's argument checks and ncrypto's + * RandomPrimeConfig and BN_generate_prime_ex2 errors. The callback forms + * compute at once and call back in a later macrotask. */ + +/* The longest candidate the Miller-Rabin rounds take: sd_mont_init's R^2 + * has twice the candidate's limbs, within MBEDTLS_MPI_MAX_LIMBS, and + * mbedtls_mpi_exp_mod stops at MBEDTLS_MPI_MAX_BITS. */ +#if SD_MONT +#define SD_MAX_PRIME_BITS 262144 +#else +#define SD_MAX_PRIME_BITS MBEDTLS_MPI_MAX_BITS +#endif + +static void sd_prime_too_long(const char *what) { + char message[128]; + int n = snprintf(message, sizeof message, "%s longer than %d bits have no native implementation", what, + SD_MAX_PRIME_BITS); + scr_throw_error_msg_code(SCR_ERR_ERROR, message, n < 0 ? 0 : (size_t)n, "SC2020"); +} + +/* An OpenSSL bignum error as a crypto job reports it: an Error with the + * formatted message and no other properties. */ +static void sd_throw_bignum(const char *packed, const char *reason) { + char message[96]; + int n = snprintf(message, sizeof message, "error:%s:bignum routines::%s", packed, reason); + ScrStr *text = scr_str_new(message, n < 0 ? 0 : (size_t)n); + ScrError *e = scr_error_new(SCR_ERR_ERROR, text); + scr_str_release(text); + scr_throw_obj(e, &scr_error_retain_v, &scr_error_release_v, scr_error_trace_arg()); +} + +/* validateObject(value, name): an object that is neither null nor an + * array. */ +static bool sd_validate_object(const char *name, const ScrDyn *value) { + ScrStr *type = scr_dyn_typeof(value); + bool object = type->len == 6 && memcmp(type->data, "object", 6) == 0; + scr_str_release(type); + if (object && value->kind != SCR_DYN_NULL && value->kind != SCR_DYN_ARR) return true; + scr_dyn_arg_type_fail(name, "of type object", value); + return false; +} + +static bool sd_validate_function(const char *name, const ScrDyn *value) { + if (scr_dyn_is_callable(value)) return true; + scr_dyn_arg_type_fail(name, "of type function", value); + return false; +} + +/* options[key] (borrowed), or undefined. */ +static const ScrDyn *sd_option(const ScrDyn *options, const char *key) { + const ScrDyn *value = options->kind == SCR_DYN_OBJ ? scr_dyn_obj_get(options, key, strlen(key)) : NULL; + return value ? value : scr_dyn_undefined(); +} + +static const char sd_large_number_types[] = + "of type bigint or an instance of ArrayBuffer, TypedArray, Buffer, or DataView"; + +/* A LargeNumberLike argument as a bignum: a bigint (unsignedBigIntToBuffer, + * which rejects negative values), or the bytes of an ArrayBuffer or view. + * False with the error pending. */ +static bool sd_large_number(mbedtls_mpi *x, const char *name, bool property, const ScrDyn *value) { + if (value->kind == SCR_DYN_BIGINT) { + ScrStr *text = scr_bigint_to_string(value->v.bigint, 16); + if (!text) return false; + bool negative = text->len > 0 && text->data[0] == '-'; + if (negative) { + scr_str_release(text); + ScrStr *decimal = scr_bigint_to_string(value->v.bigint, 10); + if (!decimal) return false; + /* ERR_OUT_OF_RANGE's received value groups the digits of a bigint + * past 2^32 in threes. */ + ScrBigInt *limit = scr_bigint_from_i64(-((int64_t)1 << 32)); + bool group = scr_bigint_cmp_f64(value->v.bigint, limit) < 0; + scr_bigint_release(limit); + char digits[160]; + size_t len = decimal->len < 120 ? decimal->len : 120, out = 0; + for (size_t i = 0; i < len; i++) { + size_t rest = len - i; + if (group && i > 1 && rest % 3 == 0) digits[out++] = '_'; + digits[out++] = decimal->data[i]; + } + digits[out] = '\0'; + scr_str_release(decimal); + char message[256]; + int n = snprintf(message, sizeof message, "The value of \"%s\" is out of range. It must be >= 0. Received %sn", + name, digits); + scr_throw_error_msg_code(SCR_ERR_RANGE, message, n < 0 ? 0 : (size_t)n, "ERR_OUT_OF_RANGE"); + return false; + } + char *hex = malloc(text->len + 1); + if (!hex) scr_trap("scriptc: out of memory\n"); + memcpy(hex, text->data, text->len); + hex[text->len] = '\0'; + scr_str_release(text); + bool ok = strlen(hex) <= SD_MAX_VALUE_BYTES * 2; + if (ok && mbedtls_mpi_read_string(x, 16, hex) != 0) scr_trap("scriptc: out of memory\n"); + free(hex); + if (!ok) sd_value_too_long(); + return ok; + } + if (!sd_is_view(value)) { + if (property) scr_dyn_prop_type_fail(name, sd_large_number_types, value); + else scr_dyn_arg_type_fail(name, sd_large_number_types, value); + return false; + } + ScrBytes *bytes = scr_bytes_buffer_source(value); + if (!bytes) return false; + bool held = sd_read(x, bytes); + scr_bytes_release(bytes); + if (!held) sd_value_too_long(); + return held; +} + +/* calc_trial_divisions: how many of the first primes (2 included) the + * search divides a candidate of `bits` bits by. */ +static size_t sd_trial_divisions(size_t bits) { + return bits <= 512 ? 64 : bits <= 1024 ? 128 : bits <= 2048 ? 384 : bits <= 4096 ? 1024 : 2048; +} + +static uint64_t sd_word(const mbedtls_mpi *x) { + if (mbedtls_mpi_bitlen(x) > 64) return UINT64_MAX; + unsigned char buf[8]; + if (mbedtls_mpi_write_binary(x, buf, 8) != 0) return UINT64_MAX; + uint64_t w = 0; + for (int i = 0; i < 8; i++) w = w << 8 | buf[i]; + return w; +} + +static bool sd_add_word(mbedtls_mpi *x, uint64_t w) { + unsigned char buf[8]; + for (int i = 7; i >= 0; i--, w >>= 8) buf[i] = (unsigned char)w; + mbedtls_mpi t; + mbedtls_mpi_init(&t); + bool ok = mbedtls_mpi_read_binary(&t, buf, 8) == 0 && mbedtls_mpi_add_mpi(x, x, &t) == 0; + mbedtls_mpi_free(&t); + return ok; +} + +/* probable_prime and bn_probable_prime_dh: a random odd candidate of + * `bits` bits (the top two bits set, or with `add` the top bit, moved to + * rem modulo add), then the first one stepping by 2, by 4 for a safe + * prime, or by add, that no trial-division prime divides, nor for a safe + * prime divides (p - 1) / 2. */ +static bool sd_probable_prime(ScDhSmallPrimes *t, mbedtls_mpi *rnd, size_t bits, bool safe, const mbedtls_mpi *add, + const mbedtls_mpi *rem) { + size_t trials = sd_trial_divisions(bits) - 1; /* odd primes */ + uint64_t step = safe ? 4 : 2; + uint64_t maxdelta = UINT64_MAX - t->primes[trials - 1]; + if (add) { + step = sd_word(add); + if (maxdelta > UINT64_MAX - step) maxdelta = UINT64_MAX - step; + } + mbedtls_mpi r; + mbedtls_mpi_init(&r); + bool ok = true; + for (;;) { + if (!sd_random_bits(rnd, bits, true)) ok = false; + if (ok && !add) { + if ((bits >= 2 && mbedtls_mpi_set_bit(rnd, bits - 2, 1) != 0) || (safe && mbedtls_mpi_set_bit(rnd, 1, 1) != 0)) + ok = false; + } else if (ok) { + ok = mbedtls_mpi_mod_mpi(&r, rnd, add) == 0 && mbedtls_mpi_sub_mpi(rnd, rnd, &r) == 0 && + (rem ? mbedtls_mpi_add_mpi(rnd, rnd, rem) == 0 : mbedtls_mpi_add_int(rnd, rnd, safe ? 3 : 1) == 0); + if (ok && (mbedtls_mpi_bitlen(rnd) < bits || sd_word(rnd) < (safe ? 5u : 3u))) + ok = mbedtls_mpi_add_mpi(rnd, rnd, add) == 0; + } + if (!ok || !sd_small_residues(t, rnd)) { + ok = false; + break; + } + uint64_t delta = 0, word = sd_word(rnd); + bool again = false; + for (size_t i = 0; i < trials && !again;) { + uint64_t prime = t->primes[i]; + /* A one-word candidate needs only the primes up to its square root. */ + if (bits <= 31 && delta <= 0x7fffffff && prime * prime > word + delta) break; + uint64_t m = (t->mods[i] + delta) % prime; + if (safe ? m <= 1 : m == 0) { + delta += step; + if (delta > maxdelta) again = true; + i = 0; + continue; + } + i++; + } + if (again) continue; + if (!sd_add_word(rnd, delta)) { + ok = false; + break; + } + if (add || mbedtls_mpi_bitlen(rnd) == bits) break; + } + mbedtls_mpi_free(&r); + return ok; +} + +/* BN_generate_prime_ex2(p, bits, safe, add, rem): false with OpenSSL's + * error pending. Long safe primes without add take the sieve over + * p ≡ 11 (mod 12), which every safe prime above 7 satisfies. */ +static bool sd_generate_prime(mbedtls_mpi *p, size_t bits, bool safe, const mbedtls_mpi *add, const mbedtls_mpi *rem) { + if (bits < 2 || (!add && safe && bits < 6 && bits != 3)) { + sd_throw_bignum("01800076", "bits too small"); + return false; + } + if (add && mbedtls_mpi_cmp_int(add, 0) == 0) { + sd_throw_bignum("01800067", "div by zero"); + return false; + } + if (!add && safe && bits >= 64) { + if (!sd_generate_safe_prime(p, bits, 12, 11, true)) scr_trap("scriptc: out of memory\n"); + return true; + } + ScDhSmallPrimes *t = sd_small_primes(); + mbedtls_mpi q; + mbedtls_mpi_init(&q); + bool found = false; + while (!found) { + if (!sd_probable_prime(t, p, bits, safe, add, rem)) scr_trap("scriptc: out of memory\n"); + if (!safe) { + found = sd_is_prime(t, p); + } else { + if (mbedtls_mpi_copy(&q, p) != 0 || mbedtls_mpi_shift_r(&q, 1) != 0) scr_trap("scriptc: out of memory\n"); + found = sd_is_prime(t, p) && sd_is_prime(t, &q); + } + } + mbedtls_mpi_free(&q); + free(t); + return true; +} + +/* checkPrime's arguments after the candidate: Node's options and checks + * rules. -1 with the error pending. */ +static int sd_prime_checks(const ScrDyn *options) { + if (!sd_validate_object("options", options)) return -1; + const ScrDyn *checks = sd_option(options, "checks"); + if (checks->kind == SCR_DYN_UNDEF) return 0; + if (checks->kind != SCR_DYN_NUM) { + scr_dyn_prop_type_fail("options.checks", "of type number", checks); + return -1; + } + if (!sd_validate_int32_min("options.checks", checks->v.num, 0)) return -1; + return (int)checks->v.num; +} + +/* The candidate's verdict as a boolean dyn (+1), or NULL with the error + * pending. */ +static ScrDyn *sd_check_prime(const mbedtls_mpi *candidate, int checks) { + if (mbedtls_mpi_bitlen(candidate) > SD_MAX_PRIME_BITS) { + sd_prime_too_long("checkPrime candidates"); + return NULL; + } + ScDhSmallPrimes *t = sd_small_primes(); + bool prime = sd_is_prime_checks(t, candidate, checks); + free(t); + return scr_dyn_new_bool(prime); +} + +/* A borrowed, unboxed view of each argument (+1 each); false after a + * throw. */ +static bool sd_unbox_all(ScrDyn **out, ScrDyn *const *args, size_t count) { + for (size_t i = 0; i < count; i++) out[i] = NULL; + for (size_t i = 0; i < count; i++) { + ScrDyn *value = args[i]; + out[i] = value->kind == SCR_DYN_TYPED_REF ? scr_dyn_typed_ref_materialize(value) : scr_dyn_retain(value); + if (!out[i]) return false; + } + return true; +} + +static void sd_release_all(ScrDyn **values, size_t count) { + for (size_t i = 0; i < count; i++) + if (values[i]) scr_dyn_release(values[i]); +} + +/* checkPrimeSync(candidate[, options]). */ +ScrDyn *scr_crypto_check_prime_sync(ScrDyn *candidate, ScrDyn *options) { + ScrDyn *args[2] = {candidate, options}; + ScrDyn *v[2]; + ScrDyn *result = NULL; + mbedtls_mpi x; + mbedtls_mpi_init(&x); + if (sd_unbox_all(v, args, 2) && sd_large_number(&x, "candidate", false, v[0])) { + ScrDyn *empty = v[1]->kind == SCR_DYN_UNDEF ? scr_dyn_new_obj() : NULL; + int checks = sd_prime_checks(empty ? empty : v[1]); + if (empty) scr_dyn_release(empty); + if (checks >= 0) result = sd_check_prime(&x, checks); + } + mbedtls_mpi_free(&x); + sd_release_all(v, 2); + return result; +} + +/* A deferred callback(...args): the callback and its one or two + * arguments, each in a box. */ +static void sd_deliver(ScrClosure *self) { + ScrDyn *callback = (ScrDyn *)scr_box_get_ref(self->caps[0]); + size_t argc = self->ncaps - 1; + ScrDyn *args[2] = {NULL, NULL}; + for (size_t i = 0; i < argc; i++) args[i] = (ScrDyn *)scr_box_get_ref(self->caps[i + 1]); + ScrDyn *result = scr_dyn_call(callback, args, argc, "callback"); + if (result) scr_dyn_release(result); + for (size_t i = 0; i < argc; i++) scr_dyn_release(args[i]); + scr_dyn_release(callback); +} + +/* Calls callback(first[, second]) in a later macrotask (moves first and + * second). */ +static void sd_defer(const ScrDyn *callback, ScrDyn *first, ScrDyn *second) { + ScrDyn *values[3] = {scr_dyn_retain((ScrDyn *)callback), first, second}; + size_t count = second ? 3 : 2; + ScrClosure *c = scr_closure_new((void *)sd_deliver, count); + for (size_t i = 0; i < count; i++) { + c->caps[i] = scr_box_new_obj(scr_dyn_retain_v, scr_dyn_release_v, NULL); + scr_box_set_ref(c->caps[i], values[i]); + } + scr_loop_defer(c); +} + +/* The callback's error argument on success (+1): Node's undefined, or + * null for a callback typed to take Error | null. */ +static ScrDyn *sd_no_error(bool null_error) { + return null_error ? scr_dyn_new_null() : scr_dyn_retain((ScrDyn *)scr_dyn_undefined()); +} + +/* The pending error, taken as a dyn value (+1). */ +static ScrDyn *sd_take_error(void) { + ScrCaught *caught = scr_exc_take(); + ScrDyn *error = scr_caught_to_dyn(caught); + scr_caught_release(caught); + return error; +} + +/* checkPrime(candidate[, options], callback): argument errors throw; the + * callback receives (undefined, verdict) in a later macrotask (null for + * undefined when `null_error`). */ +void scr_crypto_check_prime_async(ScrDyn *candidate, ScrDyn *options, ScrDyn *callback, bool null_error) { + ScrDyn *args[3] = {candidate, options, callback}; + ScrDyn *v[3]; + mbedtls_mpi x; + mbedtls_mpi_init(&x); + if (sd_unbox_all(v, args, 3) && sd_large_number(&x, "candidate", false, v[0])) { + ScrDyn *bag = v[1], *fn = v[2]; + ScrDyn *empty = NULL; + if (scr_dyn_is_callable(bag)) { + fn = bag; + bag = empty = scr_dyn_new_obj(); + } else if (bag->kind == SCR_DYN_UNDEF) { + bag = empty = scr_dyn_new_obj(); + } + int checks = sd_validate_function("callback", fn) ? sd_prime_checks(bag) : -1; + ScrDyn *verdict = checks >= 0 ? sd_check_prime(&x, checks) : NULL; + if (verdict) sd_defer(fn, sd_no_error(null_error), verdict); + if (empty) scr_dyn_release(empty); + } + mbedtls_mpi_free(&x); + sd_release_all(v, 3); +} + +/* RandomPrimeConfig: the size and options checks, then the add and rem + * bounds. False with the error pending. */ +typedef struct { + size_t bits; + bool safe, bigint, has_add, has_rem; + mbedtls_mpi add, rem; +} ScDhPrimeConfig; + +static void sd_prime_config_free(ScDhPrimeConfig *c) { + mbedtls_mpi_free(&c->add); + mbedtls_mpi_free(&c->rem); +} + +static bool sd_prime_size(const ScrDyn *size) { + if (size->kind != SCR_DYN_NUM) { + scr_dyn_arg_type_fail("size", "of type number", size); + return false; + } + return sd_validate_int32_min("size", size->v.num, 1); +} + +static bool sd_prime_config(ScDhPrimeConfig *c, double size, const ScrDyn *options) { + if (!sd_validate_object("options", options)) return false; + const ScrDyn *safe = sd_option(options, "safe"); + const ScrDyn *bigint = sd_option(options, "bigint"); + const ScrDyn *add = sd_option(options, "add"); + const ScrDyn *rem = sd_option(options, "rem"); + if (safe->kind != SCR_DYN_UNDEF && safe->kind != SCR_DYN_BOOL) { + scr_dyn_prop_type_fail("options.safe", "of type boolean", safe); + return false; + } + if (bigint->kind != SCR_DYN_UNDEF && bigint->kind != SCR_DYN_BOOL) { + scr_dyn_prop_type_fail("options.bigint", "of type boolean", bigint); + return false; + } + c->safe = safe->kind == SCR_DYN_BOOL && safe->v.b; + c->bigint = bigint->kind == SCR_DYN_BOOL && bigint->v.b; + c->has_add = add->kind != SCR_DYN_UNDEF; + c->has_rem = rem->kind != SCR_DYN_UNDEF; + if (c->has_add && !sd_large_number(&c->add, "options.add", true, add)) return false; + if (c->has_rem && !sd_large_number(&c->rem, "options.rem", true, rem)) return false; + c->bits = (size_t)size; + if (c->has_add) { + if (mbedtls_mpi_bitlen(&c->add) > c->bits) { + sd_throw(SCR_ERR_RANGE, "ERR_OUT_OF_RANGE", "invalid options.add"); + return false; + } + if (c->has_rem && mbedtls_mpi_cmp_mpi(&c->add, &c->rem) <= 0) { + sd_throw(SCR_ERR_RANGE, "ERR_OUT_OF_RANGE", "invalid options.rem"); + return false; + } + } + if (c->bits > SD_MAX_PRIME_BITS) { + sd_prime_too_long("generatePrime sizes"); + return false; + } + return true; +} + +/* The generated prime as an ArrayBuffer of its bytes, or a bigint (+1), + * or NULL with OpenSSL's error pending. */ +static ScrDyn *sd_prime_result(ScDhPrimeConfig *c) { + mbedtls_mpi p; + mbedtls_mpi_init(&p); + ScrDyn *result = NULL; + if (sd_generate_prime(&p, c->bits, c->safe, c->has_add ? &c->add : NULL, c->has_add && c->has_rem ? &c->rem : NULL)) { + if (c->bigint) { + size_t len = 0; + mbedtls_mpi_write_string(&p, 16, NULL, 0, &len); + char *hex = malloc(len + 2); + if (!hex) scr_trap("scriptc: out of memory\n"); + hex[0] = '0'; + hex[1] = 'x'; + if (mbedtls_mpi_write_string(&p, 16, hex + 2, len, &len) != 0) scr_trap("scriptc: out of memory\n"); + ScrStr *text = scr_str_new(hex, strlen(hex)); + free(hex); + ScrBigInt *value = scr_bigint_parse(text); + scr_str_release(text); + if (value) { + result = scr_dyn_new_bigint(value); + scr_bigint_release(value); + } + } else { + size_t len = mbedtls_mpi_size(&p); + ScrBytes *bytes = scr_bytes_new(SCR_BYTES_U8, (double)len); + if (mbedtls_mpi_write_binary(&p, bytes->data, len) != 0) scr_trap("scriptc: out of memory\n"); + result = scr_array_buffer_from_bytes(bytes); + scr_bytes_release(bytes); + } + } + mbedtls_mpi_free(&p); + return result; +} + +/* generatePrimeSync(size[, options]). */ +ScrDyn *scr_crypto_generate_prime_sync(ScrDyn *size, ScrDyn *options) { + ScrDyn *args[2] = {size, options}; + ScrDyn *v[2]; + ScrDyn *result = NULL; + ScDhPrimeConfig c = {0}; + mbedtls_mpi_init(&c.add); + mbedtls_mpi_init(&c.rem); + if (sd_unbox_all(v, args, 2) && sd_prime_size(v[0])) { + ScrDyn *empty = v[1]->kind == SCR_DYN_UNDEF ? scr_dyn_new_obj() : NULL; + if (sd_prime_config(&c, v[0]->v.num, empty ? empty : v[1])) result = sd_prime_result(&c); + if (empty) scr_dyn_release(empty); + } + sd_prime_config_free(&c); + sd_release_all(v, 2); + return result; +} + +/* generatePrime(size[, options], callback): argument errors throw; the + * callback receives (undefined, prime), or OpenSSL's error alone, in a + * later macrotask (null for undefined when `null_error`). */ +void scr_crypto_generate_prime_async(ScrDyn *size, ScrDyn *options, ScrDyn *callback, bool null_error) { + ScrDyn *args[3] = {size, options, callback}; + ScrDyn *v[3]; + ScDhPrimeConfig c = {0}; + mbedtls_mpi_init(&c.add); + mbedtls_mpi_init(&c.rem); + if (sd_unbox_all(v, args, 3) && sd_prime_size(v[0])) { + ScrDyn *bag = v[1], *fn = v[2]; + ScrDyn *empty = NULL; + if (scr_dyn_is_callable(bag)) { + fn = bag; + bag = empty = scr_dyn_new_obj(); + } + if (sd_validate_function("callback", fn) && sd_prime_config(&c, v[0]->v.num, bag)) { + ScrDyn *prime = sd_prime_result(&c); + if (prime) sd_defer(fn, sd_no_error(null_error), prime); + else sd_defer(fn, sd_take_error(), NULL); + } + if (empty) scr_dyn_release(empty); + } + sd_prime_config_free(&c); + sd_release_all(v, 3); +} + +/* ── methods ──────────────────────────────────────────────────────────── */ + +static ScrDyn *sd_arg(ScrDyn *const *args, size_t argc, size_t index) { + return index < argc ? args[index] : scr_dyn_undefined(); +} + +/* The minimal big-endian bytes of a value, as BignumPointer::Encode + * writes them (none for 0), passed through encode(). */ +static ScrDyn *sd_encode_value(const mbedtls_mpi *value, const ScrDyn *encoding) { + size_t len = mbedtls_mpi_size(value); + ScrBytes *out = scr_bytes_new(SCR_BYTES_U8, (double)len); + if (mbedtls_mpi_write_binary(value, out->data, len) != 0) scr_trap("scriptc: out of memory\n"); + return ca_encode(SD_SUBJECT, out, encoding); +} + +/* A new private key for generateKeys(). */ +static bool sd_new_private_key(ScDh *d, mbedtls_mpi *priv) { + if (d->group) { + if (d->group->private_bits) return sd_random_bits(priv, (size_t)d->group->private_bits, false); + /* BN_priv_rand_range(p - 3) + 2. */ + mbedtls_mpi bound; + mbedtls_mpi_init(&bound); + bool ok = mbedtls_mpi_sub_int(&bound, &d->p, 1) == 0 && mbedtls_mpi_random(priv, 2, &bound, sd_random, NULL) == 0; + mbedtls_mpi_free(&bound); + return ok; + } + size_t bits = mbedtls_mpi_bitlen(&d->p); + if (bits < SD_MIN_MODULUS_BITS || bits > SD_MAX_MODULUS_BITS) return false; + if (!d->named) return sd_random_bits(priv, bits - 2, false); + /* ossl_ffc_generate_private_key: 1 <= priv < min(2^N, q). */ + mbedtls_mpi bound, q; + mbedtls_mpi_init(&bound); + mbedtls_mpi_init(&q); + bool ok = mbedtls_mpi_lset(&bound, 1) == 0 && mbedtls_mpi_shift_l(&bound, (size_t)d->named->keylength) == 0; + if (ok && d->named->q) ok = mbedtls_mpi_read_binary(&q, d->named->q, d->named->q_len) == 0; + else if (ok) ok = mbedtls_mpi_copy(&q, &d->p) == 0 && mbedtls_mpi_shift_r(&q, 1) == 0; + if (ok && mbedtls_mpi_cmp_mpi(&q, &bound) < 0) ok = mbedtls_mpi_copy(&bound, &q) == 0; + ok = ok && mbedtls_mpi_random(priv, 1, &bound, sd_random, NULL) == 0; + mbedtls_mpi_free(&bound); + mbedtls_mpi_free(&q); + return ok; +} + +/* generateKeys(encoding): a new key pair, or the public key of the + * private key the object has. */ +static ScrDyn *sd_generate_keys(ScDh *d, const ScrDyn *encoding) { + mbedtls_mpi priv, pub; + mbedtls_mpi_init(&priv); + mbedtls_mpi_init(&pub); + bool fresh = !d->has_priv; + bool ok = fresh ? sd_new_private_key(d, &priv) : mbedtls_mpi_copy(&priv, &d->priv) == 0; + ok = ok && sd_exp(&pub, &d->g, &priv, &d->p); + if (ok) { + mbedtls_mpi_swap(&d->priv, &priv); + mbedtls_mpi_swap(&d->pub, &pub); + d->has_priv = true; + d->has_pub = true; + } + mbedtls_mpi_free(&priv); + mbedtls_mpi_free(&pub); + if (!ok || mbedtls_mpi_cmp_int(&d->pub, 0) == 0) { + sd_operation_failed("Key generation failed"); + return NULL; + } + return sd_encode_value(&d->pub, encoding); +} + +/* Whether OpenSSL's DH derivation accepts explicit parameters' private + * key: a nonzero key and a 512- to 10000-bit prime. */ +static bool sd_derives(const ScDh *d) { + size_t bits = mbedtls_mpi_bitlen(&d->p); + return mbedtls_mpi_cmp_int(&d->priv, 0) != 0 && bits >= SD_MIN_MODULUS_BITS && bits <= SD_MAX_MODULUS_BITS; +} + +/* DH_check_pub_key's subgroup test: under a named group with its own q + * (the RFC 5114 groups), a peer key must have key^q mod p = 1. The safe + * prime groups' q is (p - 1) / 2, which OpenSSL does not test. */ +static bool sd_in_subgroup(const ScDh *d, const mbedtls_mpi *peer) { + if (!d->named || !d->named->q) return true; + mbedtls_mpi q, r; + mbedtls_mpi_init(&q); + mbedtls_mpi_init(&r); + if (mbedtls_mpi_read_binary(&q, d->named->q, d->named->q_len) != 0 || !sd_exp(&r, peer, &q, &d->p)) + scr_trap("scriptc: out of memory\n"); + bool in = mbedtls_mpi_cmp_int(&r, 1) == 0; + mbedtls_mpi_free(&q); + mbedtls_mpi_free(&r); + return in; +} + +/* computeSecret(key, inputEncoding, outputEncoding): key^priv mod p, + * padded to the prime's length. A key outside [2, p - 2], or outside a + * named group's order-q subgroup, is rejected as DH_check_pub_key does. + * A secret of 0, 1 or p - 1 is predictable (a peer key of small order, + * or a composite modulus), so it fails like OpenSSL's derivation does. */ +static ScrDyn *sd_compute_secret(ScDh *d, const ScrDyn *key, const ScrDyn *in_enc, const ScrDyn *out_enc) { + ScrBytes *bytes = ca_key_bytes(SD_SUBJECT, key, in_enc); + if (!bytes) return NULL; + ScrDyn *result = NULL; + mbedtls_mpi peer, bound, secret; + mbedtls_mpi_init(&peer); + mbedtls_mpi_init(&bound); + mbedtls_mpi_init(&secret); + /* A key longer than p, past its leading zeros, is above p - 1. */ + const unsigned char *data = bytes->data; + size_t len = bytes->len; + sd_strip(&data, &len); + bool longer = len > mbedtls_mpi_size(&d->p); + if ((!longer && mbedtls_mpi_read_binary(&peer, data, len) != 0) || mbedtls_mpi_sub_int(&bound, &d->p, 1) != 0) + scr_trap("scriptc: out of memory\n"); + if (!longer && mbedtls_mpi_cmp_int(&peer, 1) <= 0) { + sd_throw(SCR_ERR_RANGE, "ERR_CRYPTO_INVALID_KEYLEN", "Supplied key is too small"); + } else if (longer || mbedtls_mpi_cmp_mpi(&peer, &bound) >= 0) { + sd_throw(SCR_ERR_RANGE, "ERR_CRYPTO_INVALID_KEYLEN", "Supplied key is too large"); + } else if (!sd_in_subgroup(d, &peer)) { + sd_throw(SCR_ERR_RANGE, "ERR_CRYPTO_INVALID_KEYTYPE", "Supplied key is invalid"); + } else if (!d->has_priv || (!d->group && !sd_derives(d)) || !sd_exp(&secret, &peer, &d->priv, &d->p) || + mbedtls_mpi_cmp_int(&secret, 1) <= 0 || mbedtls_mpi_cmp_mpi(&secret, &bound) == 0) { + sd_operation_failed("Failed to compute shared secret"); + } else { + size_t len = mbedtls_mpi_size(&d->p); + ScrBytes *out = scr_bytes_new(SCR_BYTES_U8, (double)len); + if (mbedtls_mpi_write_binary(&secret, out->data, len) != 0) scr_trap("scriptc: out of memory\n"); + result = ca_encode(SD_SUBJECT, out, out_enc); + } + mbedtls_mpi_free(&peer); + mbedtls_mpi_free(&bound); + mbedtls_mpi_free(&secret); + scr_bytes_release(bytes); + return result; +} + +static ScrDyn *sd_get_value(const mbedtls_mpi *value, bool present, const char *missing, const ScrDyn *encoding) { + if (!present || mbedtls_mpi_cmp_int(value, 0) == 0) { + sd_throw(SCR_ERR_ERROR, "ERR_CRYPTO_INVALID_STATE", missing); + return NULL; + } + return sd_encode_value(value, encoding); +} + +/* setPublicKey(key, encoding) and setPrivateKey(key, encoding). */ +static ScrDyn *sd_set_value(mbedtls_mpi *value, bool *present, ScrDyn *self, const ScrDyn *key, const ScrDyn *encoding) { + ScrBytes *bytes = ca_key_bytes(SD_SUBJECT, key, encoding); + if (!bytes) return NULL; + bool held = sd_read(value, bytes); + scr_bytes_release(bytes); + if (!held) { + sd_value_too_long(); + return NULL; + } + *present = true; + return scr_dyn_retain(self); +} + +static bool sd_name_is(const char *method, const char *name) { + return strcmp(method, name) == 0; +} + +static ScrDyn *sd_dispatch(ScDh *d, ScrDyn *self, const char *method, ScrDyn *const *args, size_t argc, + const char *what) { + const ScrDyn *a0 = sd_arg(args, argc, 0); + if (sd_name_is(method, "generateKeys")) return sd_generate_keys(d, a0); + if (sd_name_is(method, "computeSecret")) + return sd_compute_secret(d, a0, sd_arg(args, argc, 1), sd_arg(args, argc, 2)); + if (sd_name_is(method, "getPrime")) return sd_get_value(&d->p, true, "p is null", a0); + if (sd_name_is(method, "getGenerator")) return sd_get_value(&d->g, true, "g is null", a0); + if (sd_name_is(method, "getPublicKey")) + return sd_get_value(&d->pub, d->has_pub, "No public key - did you forget to generate one?", a0); + if (sd_name_is(method, "getPrivateKey")) + return sd_get_value(&d->priv, d->has_priv, "No private key - did you forget to generate one?", a0); + /* DiffieHellmanGroup has no key setters. */ + if (!d->group && sd_name_is(method, "setPublicKey")) + return sd_set_value(&d->pub, &d->has_pub, self, a0, sd_arg(args, argc, 1)); + if (!d->group && sd_name_is(method, "setPrivateKey")) + return sd_set_value(&d->priv, &d->has_priv, self, a0, sd_arg(args, argc, 1)); + /* The Object.prototype methods a DiffieHellman inherits. */ + static const char *const inherited[] = {"constructor", "hasOwnProperty", "isPrototypeOf", + "propertyIsEnumerable", "toLocaleString", "toString", + "valueOf"}; + for (size_t i = 0; i < sizeof inherited / sizeof inherited[0]; i++) + if (sd_name_is(method, inherited[i])) { + static const char message[] = "DiffieHellman's Object.prototype methods have no lowering"; + scr_throw_error_msg_code(SCR_ERR_ERROR, message, sizeof message - 1, "SC2020"); + return NULL; + } + ScrJsonBuf b; + scr_jb_init(&b); + scr_jb_puts(&b, what); + scr_jb_puts(&b, " is not a function"); + scr_throw_error(SCR_ERR_TYPE, scr_jb_finish(&b)); + return NULL; +} + +/* Every method reads at most three arguments. */ +static ScrDyn *sd_invoke(void *h, ScrDyn *self, const char *method, ScrDyn *const *args, size_t argc, + const char *what) { + ScrDyn *unboxed[3] = {NULL, NULL, NULL}; + size_t count = argc < 3 ? argc : 3; + ScrDyn *result = NULL; + for (size_t i = 0; i < count; i++) + if (!(unboxed[i] = ca_unbox(args[i]))) goto done; + result = sd_dispatch(h, self, method, unboxed, count, what); +done: + for (size_t i = 0; i < count; i++) scr_dyn_release(unboxed[i]); + return result; +} + +/* verifyError, the one own data property. */ +static ScrDyn *sd_get(void *h, const char *key, size_t key_len) { + ScDh *d = h; + if (key_len == 11 && memcmp(key, "verifyError", 11) == 0) { + if (d->verify_error < 0) d->verify_error = sd_check_params(&d->p, &d->g); + return scr_dyn_new_num(d->verify_error); + } + static const char message[] = + "DiffieHellman property reads other than verifyError have no lowering; call generateKeys(), " + "computeSecret(), getPrime(), getGenerator(), getPublicKey(), getPrivateKey(), setPublicKey() or " + "setPrivateKey()"; + scr_throw_error_msg_code(SCR_ERR_ERROR, message, sizeof message - 1, "SC2020"); + return NULL; +} + +static bool sd_set(void *h, const char *key, size_t key_len, const ScrDyn *value) { + (void)h; (void)key; (void)key_len; (void)value; + static const char message[] = "Writing DiffieHellman properties has no lowering"; + scr_throw_error_msg_code(SCR_ERR_ERROR, message, sizeof message - 1, "SC2020"); + return true; +} + +static ScrDynHandleOps sd_ops = {"DiffieHellman", sd_retain, sd_release, sd_invoke, sd_get, sd_set, NULL, NULL, NULL}; +static ScrDynHandleOps sd_group_ops = {"DiffieHellmanGroup", sd_retain, sd_release, sd_invoke, sd_get, sd_set, + NULL, NULL, NULL}; diff --git a/packages/runtime/src/scr_dh_groups.h b/packages/runtime/src/scr_dh_groups.h new file mode 100644 index 000000000..c82ec7270 --- /dev/null +++ b/packages/runtime/src/scr_dh_groups.h @@ -0,0 +1,557 @@ +/* Diffie-Hellman group parameters, big-endian: the primes behind Node 24's + * crypto.getDiffieHellman groups (modp1 and modp2 from RFC 2409, modp5 and + * modp14 through modp18 from RFC 3526), and the RFC 7919 (ffdhe2048 through + * ffdhe8192) and RFC 5114 (dh_1024_160, dh_2048_224 and dh_2048_256) + * parameters OpenSSL 3.5 lists among its DH named groups + * (crypto/ffc/ffc_dh.c). Every group but RFC 5114's uses the generator 2 + * and a safe prime. */ +#ifndef SCR_DH_GROUPS_H +#define SCR_DH_GROUPS_H + +static const unsigned char scr_dh_modp1_p[96] = { + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, 0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, + 0xc4, 0xc6, 0x62, 0x8b, 0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, 0xcc, 0x74, + 0x02, 0x0b, 0xbe, 0xa6, 0x3b, 0x13, 0x9b, 0x22, 0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd, + 0xef, 0x95, 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, 0xf2, 0x5f, 0x14, 0x37, + 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, 0xc2, 0x45, 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, + 0xf4, 0x4c, 0x42, 0xe9, 0xa6, 0x3a, 0x36, 0x20, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +}; + +static const unsigned char scr_dh_modp2_p[128] = { + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, 0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, + 0xc4, 0xc6, 0x62, 0x8b, 0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, 0xcc, 0x74, + 0x02, 0x0b, 0xbe, 0xa6, 0x3b, 0x13, 0x9b, 0x22, 0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd, + 0xef, 0x95, 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, 0xf2, 0x5f, 0x14, 0x37, + 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, 0xc2, 0x45, 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, + 0xf4, 0x4c, 0x42, 0xe9, 0xa6, 0x37, 0xed, 0x6b, 0x0b, 0xff, 0x5c, 0xb6, 0xf4, 0x06, 0xb7, 0xed, + 0xee, 0x38, 0x6b, 0xfb, 0x5a, 0x89, 0x9f, 0xa5, 0xae, 0x9f, 0x24, 0x11, 0x7c, 0x4b, 0x1f, 0xe6, + 0x49, 0x28, 0x66, 0x51, 0xec, 0xe6, 0x53, 0x81, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +}; + +static const unsigned char scr_dh_modp5_p[192] = { + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, 0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, + 0xc4, 0xc6, 0x62, 0x8b, 0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, 0xcc, 0x74, + 0x02, 0x0b, 0xbe, 0xa6, 0x3b, 0x13, 0x9b, 0x22, 0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd, + 0xef, 0x95, 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, 0xf2, 0x5f, 0x14, 0x37, + 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, 0xc2, 0x45, 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, + 0xf4, 0x4c, 0x42, 0xe9, 0xa6, 0x37, 0xed, 0x6b, 0x0b, 0xff, 0x5c, 0xb6, 0xf4, 0x06, 0xb7, 0xed, + 0xee, 0x38, 0x6b, 0xfb, 0x5a, 0x89, 0x9f, 0xa5, 0xae, 0x9f, 0x24, 0x11, 0x7c, 0x4b, 0x1f, 0xe6, + 0x49, 0x28, 0x66, 0x51, 0xec, 0xe4, 0x5b, 0x3d, 0xc2, 0x00, 0x7c, 0xb8, 0xa1, 0x63, 0xbf, 0x05, + 0x98, 0xda, 0x48, 0x36, 0x1c, 0x55, 0xd3, 0x9a, 0x69, 0x16, 0x3f, 0xa8, 0xfd, 0x24, 0xcf, 0x5f, + 0x83, 0x65, 0x5d, 0x23, 0xdc, 0xa3, 0xad, 0x96, 0x1c, 0x62, 0xf3, 0x56, 0x20, 0x85, 0x52, 0xbb, + 0x9e, 0xd5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6d, 0x67, 0x0c, 0x35, 0x4e, 0x4a, 0xbc, 0x98, 0x04, + 0xf1, 0x74, 0x6c, 0x08, 0xca, 0x23, 0x73, 0x27, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +}; + +static const unsigned char scr_dh_modp14_p[256] = { + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, 0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, + 0xc4, 0xc6, 0x62, 0x8b, 0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, 0xcc, 0x74, + 0x02, 0x0b, 0xbe, 0xa6, 0x3b, 0x13, 0x9b, 0x22, 0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd, + 0xef, 0x95, 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, 0xf2, 0x5f, 0x14, 0x37, + 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, 0xc2, 0x45, 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, + 0xf4, 0x4c, 0x42, 0xe9, 0xa6, 0x37, 0xed, 0x6b, 0x0b, 0xff, 0x5c, 0xb6, 0xf4, 0x06, 0xb7, 0xed, + 0xee, 0x38, 0x6b, 0xfb, 0x5a, 0x89, 0x9f, 0xa5, 0xae, 0x9f, 0x24, 0x11, 0x7c, 0x4b, 0x1f, 0xe6, + 0x49, 0x28, 0x66, 0x51, 0xec, 0xe4, 0x5b, 0x3d, 0xc2, 0x00, 0x7c, 0xb8, 0xa1, 0x63, 0xbf, 0x05, + 0x98, 0xda, 0x48, 0x36, 0x1c, 0x55, 0xd3, 0x9a, 0x69, 0x16, 0x3f, 0xa8, 0xfd, 0x24, 0xcf, 0x5f, + 0x83, 0x65, 0x5d, 0x23, 0xdc, 0xa3, 0xad, 0x96, 0x1c, 0x62, 0xf3, 0x56, 0x20, 0x85, 0x52, 0xbb, + 0x9e, 0xd5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6d, 0x67, 0x0c, 0x35, 0x4e, 0x4a, 0xbc, 0x98, 0x04, + 0xf1, 0x74, 0x6c, 0x08, 0xca, 0x18, 0x21, 0x7c, 0x32, 0x90, 0x5e, 0x46, 0x2e, 0x36, 0xce, 0x3b, + 0xe3, 0x9e, 0x77, 0x2c, 0x18, 0x0e, 0x86, 0x03, 0x9b, 0x27, 0x83, 0xa2, 0xec, 0x07, 0xa2, 0x8f, + 0xb5, 0xc5, 0x5d, 0xf0, 0x6f, 0x4c, 0x52, 0xc9, 0xde, 0x2b, 0xcb, 0xf6, 0x95, 0x58, 0x17, 0x18, + 0x39, 0x95, 0x49, 0x7c, 0xea, 0x95, 0x6a, 0xe5, 0x15, 0xd2, 0x26, 0x18, 0x98, 0xfa, 0x05, 0x10, + 0x15, 0x72, 0x8e, 0x5a, 0x8a, 0xac, 0xaa, 0x68, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +}; + +static const unsigned char scr_dh_modp15_p[384] = { + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, 0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, + 0xc4, 0xc6, 0x62, 0x8b, 0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, 0xcc, 0x74, + 0x02, 0x0b, 0xbe, 0xa6, 0x3b, 0x13, 0x9b, 0x22, 0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd, + 0xef, 0x95, 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, 0xf2, 0x5f, 0x14, 0x37, + 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, 0xc2, 0x45, 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, + 0xf4, 0x4c, 0x42, 0xe9, 0xa6, 0x37, 0xed, 0x6b, 0x0b, 0xff, 0x5c, 0xb6, 0xf4, 0x06, 0xb7, 0xed, + 0xee, 0x38, 0x6b, 0xfb, 0x5a, 0x89, 0x9f, 0xa5, 0xae, 0x9f, 0x24, 0x11, 0x7c, 0x4b, 0x1f, 0xe6, + 0x49, 0x28, 0x66, 0x51, 0xec, 0xe4, 0x5b, 0x3d, 0xc2, 0x00, 0x7c, 0xb8, 0xa1, 0x63, 0xbf, 0x05, + 0x98, 0xda, 0x48, 0x36, 0x1c, 0x55, 0xd3, 0x9a, 0x69, 0x16, 0x3f, 0xa8, 0xfd, 0x24, 0xcf, 0x5f, + 0x83, 0x65, 0x5d, 0x23, 0xdc, 0xa3, 0xad, 0x96, 0x1c, 0x62, 0xf3, 0x56, 0x20, 0x85, 0x52, 0xbb, + 0x9e, 0xd5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6d, 0x67, 0x0c, 0x35, 0x4e, 0x4a, 0xbc, 0x98, 0x04, + 0xf1, 0x74, 0x6c, 0x08, 0xca, 0x18, 0x21, 0x7c, 0x32, 0x90, 0x5e, 0x46, 0x2e, 0x36, 0xce, 0x3b, + 0xe3, 0x9e, 0x77, 0x2c, 0x18, 0x0e, 0x86, 0x03, 0x9b, 0x27, 0x83, 0xa2, 0xec, 0x07, 0xa2, 0x8f, + 0xb5, 0xc5, 0x5d, 0xf0, 0x6f, 0x4c, 0x52, 0xc9, 0xde, 0x2b, 0xcb, 0xf6, 0x95, 0x58, 0x17, 0x18, + 0x39, 0x95, 0x49, 0x7c, 0xea, 0x95, 0x6a, 0xe5, 0x15, 0xd2, 0x26, 0x18, 0x98, 0xfa, 0x05, 0x10, + 0x15, 0x72, 0x8e, 0x5a, 0x8a, 0xaa, 0xc4, 0x2d, 0xad, 0x33, 0x17, 0x0d, 0x04, 0x50, 0x7a, 0x33, + 0xa8, 0x55, 0x21, 0xab, 0xdf, 0x1c, 0xba, 0x64, 0xec, 0xfb, 0x85, 0x04, 0x58, 0xdb, 0xef, 0x0a, + 0x8a, 0xea, 0x71, 0x57, 0x5d, 0x06, 0x0c, 0x7d, 0xb3, 0x97, 0x0f, 0x85, 0xa6, 0xe1, 0xe4, 0xc7, + 0xab, 0xf5, 0xae, 0x8c, 0xdb, 0x09, 0x33, 0xd7, 0x1e, 0x8c, 0x94, 0xe0, 0x4a, 0x25, 0x61, 0x9d, + 0xce, 0xe3, 0xd2, 0x26, 0x1a, 0xd2, 0xee, 0x6b, 0xf1, 0x2f, 0xfa, 0x06, 0xd9, 0x8a, 0x08, 0x64, + 0xd8, 0x76, 0x02, 0x73, 0x3e, 0xc8, 0x6a, 0x64, 0x52, 0x1f, 0x2b, 0x18, 0x17, 0x7b, 0x20, 0x0c, + 0xbb, 0xe1, 0x17, 0x57, 0x7a, 0x61, 0x5d, 0x6c, 0x77, 0x09, 0x88, 0xc0, 0xba, 0xd9, 0x46, 0xe2, + 0x08, 0xe2, 0x4f, 0xa0, 0x74, 0xe5, 0xab, 0x31, 0x43, 0xdb, 0x5b, 0xfc, 0xe0, 0xfd, 0x10, 0x8e, + 0x4b, 0x82, 0xd1, 0x20, 0xa9, 0x3a, 0xd2, 0xca, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +}; + +static const unsigned char scr_dh_modp16_p[512] = { + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, 0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, + 0xc4, 0xc6, 0x62, 0x8b, 0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, 0xcc, 0x74, + 0x02, 0x0b, 0xbe, 0xa6, 0x3b, 0x13, 0x9b, 0x22, 0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd, + 0xef, 0x95, 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, 0xf2, 0x5f, 0x14, 0x37, + 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, 0xc2, 0x45, 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, + 0xf4, 0x4c, 0x42, 0xe9, 0xa6, 0x37, 0xed, 0x6b, 0x0b, 0xff, 0x5c, 0xb6, 0xf4, 0x06, 0xb7, 0xed, + 0xee, 0x38, 0x6b, 0xfb, 0x5a, 0x89, 0x9f, 0xa5, 0xae, 0x9f, 0x24, 0x11, 0x7c, 0x4b, 0x1f, 0xe6, + 0x49, 0x28, 0x66, 0x51, 0xec, 0xe4, 0x5b, 0x3d, 0xc2, 0x00, 0x7c, 0xb8, 0xa1, 0x63, 0xbf, 0x05, + 0x98, 0xda, 0x48, 0x36, 0x1c, 0x55, 0xd3, 0x9a, 0x69, 0x16, 0x3f, 0xa8, 0xfd, 0x24, 0xcf, 0x5f, + 0x83, 0x65, 0x5d, 0x23, 0xdc, 0xa3, 0xad, 0x96, 0x1c, 0x62, 0xf3, 0x56, 0x20, 0x85, 0x52, 0xbb, + 0x9e, 0xd5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6d, 0x67, 0x0c, 0x35, 0x4e, 0x4a, 0xbc, 0x98, 0x04, + 0xf1, 0x74, 0x6c, 0x08, 0xca, 0x18, 0x21, 0x7c, 0x32, 0x90, 0x5e, 0x46, 0x2e, 0x36, 0xce, 0x3b, + 0xe3, 0x9e, 0x77, 0x2c, 0x18, 0x0e, 0x86, 0x03, 0x9b, 0x27, 0x83, 0xa2, 0xec, 0x07, 0xa2, 0x8f, + 0xb5, 0xc5, 0x5d, 0xf0, 0x6f, 0x4c, 0x52, 0xc9, 0xde, 0x2b, 0xcb, 0xf6, 0x95, 0x58, 0x17, 0x18, + 0x39, 0x95, 0x49, 0x7c, 0xea, 0x95, 0x6a, 0xe5, 0x15, 0xd2, 0x26, 0x18, 0x98, 0xfa, 0x05, 0x10, + 0x15, 0x72, 0x8e, 0x5a, 0x8a, 0xaa, 0xc4, 0x2d, 0xad, 0x33, 0x17, 0x0d, 0x04, 0x50, 0x7a, 0x33, + 0xa8, 0x55, 0x21, 0xab, 0xdf, 0x1c, 0xba, 0x64, 0xec, 0xfb, 0x85, 0x04, 0x58, 0xdb, 0xef, 0x0a, + 0x8a, 0xea, 0x71, 0x57, 0x5d, 0x06, 0x0c, 0x7d, 0xb3, 0x97, 0x0f, 0x85, 0xa6, 0xe1, 0xe4, 0xc7, + 0xab, 0xf5, 0xae, 0x8c, 0xdb, 0x09, 0x33, 0xd7, 0x1e, 0x8c, 0x94, 0xe0, 0x4a, 0x25, 0x61, 0x9d, + 0xce, 0xe3, 0xd2, 0x26, 0x1a, 0xd2, 0xee, 0x6b, 0xf1, 0x2f, 0xfa, 0x06, 0xd9, 0x8a, 0x08, 0x64, + 0xd8, 0x76, 0x02, 0x73, 0x3e, 0xc8, 0x6a, 0x64, 0x52, 0x1f, 0x2b, 0x18, 0x17, 0x7b, 0x20, 0x0c, + 0xbb, 0xe1, 0x17, 0x57, 0x7a, 0x61, 0x5d, 0x6c, 0x77, 0x09, 0x88, 0xc0, 0xba, 0xd9, 0x46, 0xe2, + 0x08, 0xe2, 0x4f, 0xa0, 0x74, 0xe5, 0xab, 0x31, 0x43, 0xdb, 0x5b, 0xfc, 0xe0, 0xfd, 0x10, 0x8e, + 0x4b, 0x82, 0xd1, 0x20, 0xa9, 0x21, 0x08, 0x01, 0x1a, 0x72, 0x3c, 0x12, 0xa7, 0x87, 0xe6, 0xd7, + 0x88, 0x71, 0x9a, 0x10, 0xbd, 0xba, 0x5b, 0x26, 0x99, 0xc3, 0x27, 0x18, 0x6a, 0xf4, 0xe2, 0x3c, + 0x1a, 0x94, 0x68, 0x34, 0xb6, 0x15, 0x0b, 0xda, 0x25, 0x83, 0xe9, 0xca, 0x2a, 0xd4, 0x4c, 0xe8, + 0xdb, 0xbb, 0xc2, 0xdb, 0x04, 0xde, 0x8e, 0xf9, 0x2e, 0x8e, 0xfc, 0x14, 0x1f, 0xbe, 0xca, 0xa6, + 0x28, 0x7c, 0x59, 0x47, 0x4e, 0x6b, 0xc0, 0x5d, 0x99, 0xb2, 0x96, 0x4f, 0xa0, 0x90, 0xc3, 0xa2, + 0x23, 0x3b, 0xa1, 0x86, 0x51, 0x5b, 0xe7, 0xed, 0x1f, 0x61, 0x29, 0x70, 0xce, 0xe2, 0xd7, 0xaf, + 0xb8, 0x1b, 0xdd, 0x76, 0x21, 0x70, 0x48, 0x1c, 0xd0, 0x06, 0x91, 0x27, 0xd5, 0xb0, 0x5a, 0xa9, + 0x93, 0xb4, 0xea, 0x98, 0x8d, 0x8f, 0xdd, 0xc1, 0x86, 0xff, 0xb7, 0xdc, 0x90, 0xa6, 0xc0, 0x8f, + 0x4d, 0xf4, 0x35, 0xc9, 0x34, 0x06, 0x31, 0x99, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +}; + +static const unsigned char scr_dh_modp17_p[768] = { + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, 0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, + 0xc4, 0xc6, 0x62, 0x8b, 0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, 0xcc, 0x74, + 0x02, 0x0b, 0xbe, 0xa6, 0x3b, 0x13, 0x9b, 0x22, 0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd, + 0xef, 0x95, 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, 0xf2, 0x5f, 0x14, 0x37, + 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, 0xc2, 0x45, 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, + 0xf4, 0x4c, 0x42, 0xe9, 0xa6, 0x37, 0xed, 0x6b, 0x0b, 0xff, 0x5c, 0xb6, 0xf4, 0x06, 0xb7, 0xed, + 0xee, 0x38, 0x6b, 0xfb, 0x5a, 0x89, 0x9f, 0xa5, 0xae, 0x9f, 0x24, 0x11, 0x7c, 0x4b, 0x1f, 0xe6, + 0x49, 0x28, 0x66, 0x51, 0xec, 0xe4, 0x5b, 0x3d, 0xc2, 0x00, 0x7c, 0xb8, 0xa1, 0x63, 0xbf, 0x05, + 0x98, 0xda, 0x48, 0x36, 0x1c, 0x55, 0xd3, 0x9a, 0x69, 0x16, 0x3f, 0xa8, 0xfd, 0x24, 0xcf, 0x5f, + 0x83, 0x65, 0x5d, 0x23, 0xdc, 0xa3, 0xad, 0x96, 0x1c, 0x62, 0xf3, 0x56, 0x20, 0x85, 0x52, 0xbb, + 0x9e, 0xd5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6d, 0x67, 0x0c, 0x35, 0x4e, 0x4a, 0xbc, 0x98, 0x04, + 0xf1, 0x74, 0x6c, 0x08, 0xca, 0x18, 0x21, 0x7c, 0x32, 0x90, 0x5e, 0x46, 0x2e, 0x36, 0xce, 0x3b, + 0xe3, 0x9e, 0x77, 0x2c, 0x18, 0x0e, 0x86, 0x03, 0x9b, 0x27, 0x83, 0xa2, 0xec, 0x07, 0xa2, 0x8f, + 0xb5, 0xc5, 0x5d, 0xf0, 0x6f, 0x4c, 0x52, 0xc9, 0xde, 0x2b, 0xcb, 0xf6, 0x95, 0x58, 0x17, 0x18, + 0x39, 0x95, 0x49, 0x7c, 0xea, 0x95, 0x6a, 0xe5, 0x15, 0xd2, 0x26, 0x18, 0x98, 0xfa, 0x05, 0x10, + 0x15, 0x72, 0x8e, 0x5a, 0x8a, 0xaa, 0xc4, 0x2d, 0xad, 0x33, 0x17, 0x0d, 0x04, 0x50, 0x7a, 0x33, + 0xa8, 0x55, 0x21, 0xab, 0xdf, 0x1c, 0xba, 0x64, 0xec, 0xfb, 0x85, 0x04, 0x58, 0xdb, 0xef, 0x0a, + 0x8a, 0xea, 0x71, 0x57, 0x5d, 0x06, 0x0c, 0x7d, 0xb3, 0x97, 0x0f, 0x85, 0xa6, 0xe1, 0xe4, 0xc7, + 0xab, 0xf5, 0xae, 0x8c, 0xdb, 0x09, 0x33, 0xd7, 0x1e, 0x8c, 0x94, 0xe0, 0x4a, 0x25, 0x61, 0x9d, + 0xce, 0xe3, 0xd2, 0x26, 0x1a, 0xd2, 0xee, 0x6b, 0xf1, 0x2f, 0xfa, 0x06, 0xd9, 0x8a, 0x08, 0x64, + 0xd8, 0x76, 0x02, 0x73, 0x3e, 0xc8, 0x6a, 0x64, 0x52, 0x1f, 0x2b, 0x18, 0x17, 0x7b, 0x20, 0x0c, + 0xbb, 0xe1, 0x17, 0x57, 0x7a, 0x61, 0x5d, 0x6c, 0x77, 0x09, 0x88, 0xc0, 0xba, 0xd9, 0x46, 0xe2, + 0x08, 0xe2, 0x4f, 0xa0, 0x74, 0xe5, 0xab, 0x31, 0x43, 0xdb, 0x5b, 0xfc, 0xe0, 0xfd, 0x10, 0x8e, + 0x4b, 0x82, 0xd1, 0x20, 0xa9, 0x21, 0x08, 0x01, 0x1a, 0x72, 0x3c, 0x12, 0xa7, 0x87, 0xe6, 0xd7, + 0x88, 0x71, 0x9a, 0x10, 0xbd, 0xba, 0x5b, 0x26, 0x99, 0xc3, 0x27, 0x18, 0x6a, 0xf4, 0xe2, 0x3c, + 0x1a, 0x94, 0x68, 0x34, 0xb6, 0x15, 0x0b, 0xda, 0x25, 0x83, 0xe9, 0xca, 0x2a, 0xd4, 0x4c, 0xe8, + 0xdb, 0xbb, 0xc2, 0xdb, 0x04, 0xde, 0x8e, 0xf9, 0x2e, 0x8e, 0xfc, 0x14, 0x1f, 0xbe, 0xca, 0xa6, + 0x28, 0x7c, 0x59, 0x47, 0x4e, 0x6b, 0xc0, 0x5d, 0x99, 0xb2, 0x96, 0x4f, 0xa0, 0x90, 0xc3, 0xa2, + 0x23, 0x3b, 0xa1, 0x86, 0x51, 0x5b, 0xe7, 0xed, 0x1f, 0x61, 0x29, 0x70, 0xce, 0xe2, 0xd7, 0xaf, + 0xb8, 0x1b, 0xdd, 0x76, 0x21, 0x70, 0x48, 0x1c, 0xd0, 0x06, 0x91, 0x27, 0xd5, 0xb0, 0x5a, 0xa9, + 0x93, 0xb4, 0xea, 0x98, 0x8d, 0x8f, 0xdd, 0xc1, 0x86, 0xff, 0xb7, 0xdc, 0x90, 0xa6, 0xc0, 0x8f, + 0x4d, 0xf4, 0x35, 0xc9, 0x34, 0x02, 0x84, 0x92, 0x36, 0xc3, 0xfa, 0xb4, 0xd2, 0x7c, 0x70, 0x26, + 0xc1, 0xd4, 0xdc, 0xb2, 0x60, 0x26, 0x46, 0xde, 0xc9, 0x75, 0x1e, 0x76, 0x3d, 0xba, 0x37, 0xbd, + 0xf8, 0xff, 0x94, 0x06, 0xad, 0x9e, 0x53, 0x0e, 0xe5, 0xdb, 0x38, 0x2f, 0x41, 0x30, 0x01, 0xae, + 0xb0, 0x6a, 0x53, 0xed, 0x90, 0x27, 0xd8, 0x31, 0x17, 0x97, 0x27, 0xb0, 0x86, 0x5a, 0x89, 0x18, + 0xda, 0x3e, 0xdb, 0xeb, 0xcf, 0x9b, 0x14, 0xed, 0x44, 0xce, 0x6c, 0xba, 0xce, 0xd4, 0xbb, 0x1b, + 0xdb, 0x7f, 0x14, 0x47, 0xe6, 0xcc, 0x25, 0x4b, 0x33, 0x20, 0x51, 0x51, 0x2b, 0xd7, 0xaf, 0x42, + 0x6f, 0xb8, 0xf4, 0x01, 0x37, 0x8c, 0xd2, 0xbf, 0x59, 0x83, 0xca, 0x01, 0xc6, 0x4b, 0x92, 0xec, + 0xf0, 0x32, 0xea, 0x15, 0xd1, 0x72, 0x1d, 0x03, 0xf4, 0x82, 0xd7, 0xce, 0x6e, 0x74, 0xfe, 0xf6, + 0xd5, 0x5e, 0x70, 0x2f, 0x46, 0x98, 0x0c, 0x82, 0xb5, 0xa8, 0x40, 0x31, 0x90, 0x0b, 0x1c, 0x9e, + 0x59, 0xe7, 0xc9, 0x7f, 0xbe, 0xc7, 0xe8, 0xf3, 0x23, 0xa9, 0x7a, 0x7e, 0x36, 0xcc, 0x88, 0xbe, + 0x0f, 0x1d, 0x45, 0xb7, 0xff, 0x58, 0x5a, 0xc5, 0x4b, 0xd4, 0x07, 0xb2, 0x2b, 0x41, 0x54, 0xaa, + 0xcc, 0x8f, 0x6d, 0x7e, 0xbf, 0x48, 0xe1, 0xd8, 0x14, 0xcc, 0x5e, 0xd2, 0x0f, 0x80, 0x37, 0xe0, + 0xa7, 0x97, 0x15, 0xee, 0xf2, 0x9b, 0xe3, 0x28, 0x06, 0xa1, 0xd5, 0x8b, 0xb7, 0xc5, 0xda, 0x76, + 0xf5, 0x50, 0xaa, 0x3d, 0x8a, 0x1f, 0xbf, 0xf0, 0xeb, 0x19, 0xcc, 0xb1, 0xa3, 0x13, 0xd5, 0x5c, + 0xda, 0x56, 0xc9, 0xec, 0x2e, 0xf2, 0x96, 0x32, 0x38, 0x7f, 0xe8, 0xd7, 0x6e, 0x3c, 0x04, 0x68, + 0x04, 0x3e, 0x8f, 0x66, 0x3f, 0x48, 0x60, 0xee, 0x12, 0xbf, 0x2d, 0x5b, 0x0b, 0x74, 0x74, 0xd6, + 0xe6, 0x94, 0xf9, 0x1e, 0x6d, 0xcc, 0x40, 0x24, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +}; + +static const unsigned char scr_dh_modp18_p[1024] = { + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, 0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, + 0xc4, 0xc6, 0x62, 0x8b, 0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, 0xcc, 0x74, + 0x02, 0x0b, 0xbe, 0xa6, 0x3b, 0x13, 0x9b, 0x22, 0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd, + 0xef, 0x95, 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, 0xf2, 0x5f, 0x14, 0x37, + 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, 0xc2, 0x45, 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, + 0xf4, 0x4c, 0x42, 0xe9, 0xa6, 0x37, 0xed, 0x6b, 0x0b, 0xff, 0x5c, 0xb6, 0xf4, 0x06, 0xb7, 0xed, + 0xee, 0x38, 0x6b, 0xfb, 0x5a, 0x89, 0x9f, 0xa5, 0xae, 0x9f, 0x24, 0x11, 0x7c, 0x4b, 0x1f, 0xe6, + 0x49, 0x28, 0x66, 0x51, 0xec, 0xe4, 0x5b, 0x3d, 0xc2, 0x00, 0x7c, 0xb8, 0xa1, 0x63, 0xbf, 0x05, + 0x98, 0xda, 0x48, 0x36, 0x1c, 0x55, 0xd3, 0x9a, 0x69, 0x16, 0x3f, 0xa8, 0xfd, 0x24, 0xcf, 0x5f, + 0x83, 0x65, 0x5d, 0x23, 0xdc, 0xa3, 0xad, 0x96, 0x1c, 0x62, 0xf3, 0x56, 0x20, 0x85, 0x52, 0xbb, + 0x9e, 0xd5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6d, 0x67, 0x0c, 0x35, 0x4e, 0x4a, 0xbc, 0x98, 0x04, + 0xf1, 0x74, 0x6c, 0x08, 0xca, 0x18, 0x21, 0x7c, 0x32, 0x90, 0x5e, 0x46, 0x2e, 0x36, 0xce, 0x3b, + 0xe3, 0x9e, 0x77, 0x2c, 0x18, 0x0e, 0x86, 0x03, 0x9b, 0x27, 0x83, 0xa2, 0xec, 0x07, 0xa2, 0x8f, + 0xb5, 0xc5, 0x5d, 0xf0, 0x6f, 0x4c, 0x52, 0xc9, 0xde, 0x2b, 0xcb, 0xf6, 0x95, 0x58, 0x17, 0x18, + 0x39, 0x95, 0x49, 0x7c, 0xea, 0x95, 0x6a, 0xe5, 0x15, 0xd2, 0x26, 0x18, 0x98, 0xfa, 0x05, 0x10, + 0x15, 0x72, 0x8e, 0x5a, 0x8a, 0xaa, 0xc4, 0x2d, 0xad, 0x33, 0x17, 0x0d, 0x04, 0x50, 0x7a, 0x33, + 0xa8, 0x55, 0x21, 0xab, 0xdf, 0x1c, 0xba, 0x64, 0xec, 0xfb, 0x85, 0x04, 0x58, 0xdb, 0xef, 0x0a, + 0x8a, 0xea, 0x71, 0x57, 0x5d, 0x06, 0x0c, 0x7d, 0xb3, 0x97, 0x0f, 0x85, 0xa6, 0xe1, 0xe4, 0xc7, + 0xab, 0xf5, 0xae, 0x8c, 0xdb, 0x09, 0x33, 0xd7, 0x1e, 0x8c, 0x94, 0xe0, 0x4a, 0x25, 0x61, 0x9d, + 0xce, 0xe3, 0xd2, 0x26, 0x1a, 0xd2, 0xee, 0x6b, 0xf1, 0x2f, 0xfa, 0x06, 0xd9, 0x8a, 0x08, 0x64, + 0xd8, 0x76, 0x02, 0x73, 0x3e, 0xc8, 0x6a, 0x64, 0x52, 0x1f, 0x2b, 0x18, 0x17, 0x7b, 0x20, 0x0c, + 0xbb, 0xe1, 0x17, 0x57, 0x7a, 0x61, 0x5d, 0x6c, 0x77, 0x09, 0x88, 0xc0, 0xba, 0xd9, 0x46, 0xe2, + 0x08, 0xe2, 0x4f, 0xa0, 0x74, 0xe5, 0xab, 0x31, 0x43, 0xdb, 0x5b, 0xfc, 0xe0, 0xfd, 0x10, 0x8e, + 0x4b, 0x82, 0xd1, 0x20, 0xa9, 0x21, 0x08, 0x01, 0x1a, 0x72, 0x3c, 0x12, 0xa7, 0x87, 0xe6, 0xd7, + 0x88, 0x71, 0x9a, 0x10, 0xbd, 0xba, 0x5b, 0x26, 0x99, 0xc3, 0x27, 0x18, 0x6a, 0xf4, 0xe2, 0x3c, + 0x1a, 0x94, 0x68, 0x34, 0xb6, 0x15, 0x0b, 0xda, 0x25, 0x83, 0xe9, 0xca, 0x2a, 0xd4, 0x4c, 0xe8, + 0xdb, 0xbb, 0xc2, 0xdb, 0x04, 0xde, 0x8e, 0xf9, 0x2e, 0x8e, 0xfc, 0x14, 0x1f, 0xbe, 0xca, 0xa6, + 0x28, 0x7c, 0x59, 0x47, 0x4e, 0x6b, 0xc0, 0x5d, 0x99, 0xb2, 0x96, 0x4f, 0xa0, 0x90, 0xc3, 0xa2, + 0x23, 0x3b, 0xa1, 0x86, 0x51, 0x5b, 0xe7, 0xed, 0x1f, 0x61, 0x29, 0x70, 0xce, 0xe2, 0xd7, 0xaf, + 0xb8, 0x1b, 0xdd, 0x76, 0x21, 0x70, 0x48, 0x1c, 0xd0, 0x06, 0x91, 0x27, 0xd5, 0xb0, 0x5a, 0xa9, + 0x93, 0xb4, 0xea, 0x98, 0x8d, 0x8f, 0xdd, 0xc1, 0x86, 0xff, 0xb7, 0xdc, 0x90, 0xa6, 0xc0, 0x8f, + 0x4d, 0xf4, 0x35, 0xc9, 0x34, 0x02, 0x84, 0x92, 0x36, 0xc3, 0xfa, 0xb4, 0xd2, 0x7c, 0x70, 0x26, + 0xc1, 0xd4, 0xdc, 0xb2, 0x60, 0x26, 0x46, 0xde, 0xc9, 0x75, 0x1e, 0x76, 0x3d, 0xba, 0x37, 0xbd, + 0xf8, 0xff, 0x94, 0x06, 0xad, 0x9e, 0x53, 0x0e, 0xe5, 0xdb, 0x38, 0x2f, 0x41, 0x30, 0x01, 0xae, + 0xb0, 0x6a, 0x53, 0xed, 0x90, 0x27, 0xd8, 0x31, 0x17, 0x97, 0x27, 0xb0, 0x86, 0x5a, 0x89, 0x18, + 0xda, 0x3e, 0xdb, 0xeb, 0xcf, 0x9b, 0x14, 0xed, 0x44, 0xce, 0x6c, 0xba, 0xce, 0xd4, 0xbb, 0x1b, + 0xdb, 0x7f, 0x14, 0x47, 0xe6, 0xcc, 0x25, 0x4b, 0x33, 0x20, 0x51, 0x51, 0x2b, 0xd7, 0xaf, 0x42, + 0x6f, 0xb8, 0xf4, 0x01, 0x37, 0x8c, 0xd2, 0xbf, 0x59, 0x83, 0xca, 0x01, 0xc6, 0x4b, 0x92, 0xec, + 0xf0, 0x32, 0xea, 0x15, 0xd1, 0x72, 0x1d, 0x03, 0xf4, 0x82, 0xd7, 0xce, 0x6e, 0x74, 0xfe, 0xf6, + 0xd5, 0x5e, 0x70, 0x2f, 0x46, 0x98, 0x0c, 0x82, 0xb5, 0xa8, 0x40, 0x31, 0x90, 0x0b, 0x1c, 0x9e, + 0x59, 0xe7, 0xc9, 0x7f, 0xbe, 0xc7, 0xe8, 0xf3, 0x23, 0xa9, 0x7a, 0x7e, 0x36, 0xcc, 0x88, 0xbe, + 0x0f, 0x1d, 0x45, 0xb7, 0xff, 0x58, 0x5a, 0xc5, 0x4b, 0xd4, 0x07, 0xb2, 0x2b, 0x41, 0x54, 0xaa, + 0xcc, 0x8f, 0x6d, 0x7e, 0xbf, 0x48, 0xe1, 0xd8, 0x14, 0xcc, 0x5e, 0xd2, 0x0f, 0x80, 0x37, 0xe0, + 0xa7, 0x97, 0x15, 0xee, 0xf2, 0x9b, 0xe3, 0x28, 0x06, 0xa1, 0xd5, 0x8b, 0xb7, 0xc5, 0xda, 0x76, + 0xf5, 0x50, 0xaa, 0x3d, 0x8a, 0x1f, 0xbf, 0xf0, 0xeb, 0x19, 0xcc, 0xb1, 0xa3, 0x13, 0xd5, 0x5c, + 0xda, 0x56, 0xc9, 0xec, 0x2e, 0xf2, 0x96, 0x32, 0x38, 0x7f, 0xe8, 0xd7, 0x6e, 0x3c, 0x04, 0x68, + 0x04, 0x3e, 0x8f, 0x66, 0x3f, 0x48, 0x60, 0xee, 0x12, 0xbf, 0x2d, 0x5b, 0x0b, 0x74, 0x74, 0xd6, + 0xe6, 0x94, 0xf9, 0x1e, 0x6d, 0xbe, 0x11, 0x59, 0x74, 0xa3, 0x92, 0x6f, 0x12, 0xfe, 0xe5, 0xe4, + 0x38, 0x77, 0x7c, 0xb6, 0xa9, 0x32, 0xdf, 0x8c, 0xd8, 0xbe, 0xc4, 0xd0, 0x73, 0xb9, 0x31, 0xba, + 0x3b, 0xc8, 0x32, 0xb6, 0x8d, 0x9d, 0xd3, 0x00, 0x74, 0x1f, 0xa7, 0xbf, 0x8a, 0xfc, 0x47, 0xed, + 0x25, 0x76, 0xf6, 0x93, 0x6b, 0xa4, 0x24, 0x66, 0x3a, 0xab, 0x63, 0x9c, 0x5a, 0xe4, 0xf5, 0x68, + 0x34, 0x23, 0xb4, 0x74, 0x2b, 0xf1, 0xc9, 0x78, 0x23, 0x8f, 0x16, 0xcb, 0xe3, 0x9d, 0x65, 0x2d, + 0xe3, 0xfd, 0xb8, 0xbe, 0xfc, 0x84, 0x8a, 0xd9, 0x22, 0x22, 0x2e, 0x04, 0xa4, 0x03, 0x7c, 0x07, + 0x13, 0xeb, 0x57, 0xa8, 0x1a, 0x23, 0xf0, 0xc7, 0x34, 0x73, 0xfc, 0x64, 0x6c, 0xea, 0x30, 0x6b, + 0x4b, 0xcb, 0xc8, 0x86, 0x2f, 0x83, 0x85, 0xdd, 0xfa, 0x9d, 0x4b, 0x7f, 0xa2, 0xc0, 0x87, 0xe8, + 0x79, 0x68, 0x33, 0x03, 0xed, 0x5b, 0xdd, 0x3a, 0x06, 0x2b, 0x3c, 0xf5, 0xb3, 0xa2, 0x78, 0xa6, + 0x6d, 0x2a, 0x13, 0xf8, 0x3f, 0x44, 0xf8, 0x2d, 0xdf, 0x31, 0x0e, 0xe0, 0x74, 0xab, 0x6a, 0x36, + 0x45, 0x97, 0xe8, 0x99, 0xa0, 0x25, 0x5d, 0xc1, 0x64, 0xf3, 0x1c, 0xc5, 0x08, 0x46, 0x85, 0x1d, + 0xf9, 0xab, 0x48, 0x19, 0x5d, 0xed, 0x7e, 0xa1, 0xb1, 0xd5, 0x10, 0xbd, 0x7e, 0xe7, 0x4d, 0x73, + 0xfa, 0xf3, 0x6b, 0xc3, 0x1e, 0xcf, 0xa2, 0x68, 0x35, 0x90, 0x46, 0xf4, 0xeb, 0x87, 0x9f, 0x92, + 0x40, 0x09, 0x43, 0x8b, 0x48, 0x1c, 0x6c, 0xd7, 0x88, 0x9a, 0x00, 0x2e, 0xd5, 0xee, 0x38, 0x2b, + 0xc9, 0x19, 0x0d, 0xa6, 0xfc, 0x02, 0x6e, 0x47, 0x95, 0x58, 0xe4, 0x47, 0x56, 0x77, 0xe9, 0xaa, + 0x9e, 0x30, 0x50, 0xe2, 0x76, 0x56, 0x94, 0xdf, 0xc8, 0x1f, 0x56, 0xe8, 0x80, 0xb9, 0x6e, 0x71, + 0x60, 0xc9, 0x80, 0xdd, 0x98, 0xed, 0xd3, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +}; + +static const unsigned char scr_dh_ffdhe2048_p[256] = { + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xad, 0xf8, 0x54, 0x58, 0xa2, 0xbb, 0x4a, 0x9a, + 0xaf, 0xdc, 0x56, 0x20, 0x27, 0x3d, 0x3c, 0xf1, 0xd8, 0xb9, 0xc5, 0x83, 0xce, 0x2d, 0x36, 0x95, + 0xa9, 0xe1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xfb, 0xcc, 0x93, 0x9d, 0xce, 0x24, 0x9b, 0x3e, 0xf9, + 0x7d, 0x2f, 0xe3, 0x63, 0x63, 0x0c, 0x75, 0xd8, 0xf6, 0x81, 0xb2, 0x02, 0xae, 0xc4, 0x61, 0x7a, + 0xd3, 0xdf, 0x1e, 0xd5, 0xd5, 0xfd, 0x65, 0x61, 0x24, 0x33, 0xf5, 0x1f, 0x5f, 0x06, 0x6e, 0xd0, + 0x85, 0x63, 0x65, 0x55, 0x3d, 0xed, 0x1a, 0xf3, 0xb5, 0x57, 0x13, 0x5e, 0x7f, 0x57, 0xc9, 0x35, + 0x98, 0x4f, 0x0c, 0x70, 0xe0, 0xe6, 0x8b, 0x77, 0xe2, 0xa6, 0x89, 0xda, 0xf3, 0xef, 0xe8, 0x72, + 0x1d, 0xf1, 0x58, 0xa1, 0x36, 0xad, 0xe7, 0x35, 0x30, 0xac, 0xca, 0x4f, 0x48, 0x3a, 0x79, 0x7a, + 0xbc, 0x0a, 0xb1, 0x82, 0xb3, 0x24, 0xfb, 0x61, 0xd1, 0x08, 0xa9, 0x4b, 0xb2, 0xc8, 0xe3, 0xfb, + 0xb9, 0x6a, 0xda, 0xb7, 0x60, 0xd7, 0xf4, 0x68, 0x1d, 0x4f, 0x42, 0xa3, 0xde, 0x39, 0x4d, 0xf4, + 0xae, 0x56, 0xed, 0xe7, 0x63, 0x72, 0xbb, 0x19, 0x0b, 0x07, 0xa7, 0xc8, 0xee, 0x0a, 0x6d, 0x70, + 0x9e, 0x02, 0xfc, 0xe1, 0xcd, 0xf7, 0xe2, 0xec, 0xc0, 0x34, 0x04, 0xcd, 0x28, 0x34, 0x2f, 0x61, + 0x91, 0x72, 0xfe, 0x9c, 0xe9, 0x85, 0x83, 0xff, 0x8e, 0x4f, 0x12, 0x32, 0xee, 0xf2, 0x81, 0x83, + 0xc3, 0xfe, 0x3b, 0x1b, 0x4c, 0x6f, 0xad, 0x73, 0x3b, 0xb5, 0xfc, 0xbc, 0x2e, 0xc2, 0x20, 0x05, + 0xc5, 0x8e, 0xf1, 0x83, 0x7d, 0x16, 0x83, 0xb2, 0xc6, 0xf3, 0x4a, 0x26, 0xc1, 0xb2, 0xef, 0xfa, + 0x88, 0x6b, 0x42, 0x38, 0x61, 0x28, 0x5c, 0x97, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +}; + +static const unsigned char scr_dh_ffdhe3072_p[384] = { + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xad, 0xf8, 0x54, 0x58, 0xa2, 0xbb, 0x4a, 0x9a, + 0xaf, 0xdc, 0x56, 0x20, 0x27, 0x3d, 0x3c, 0xf1, 0xd8, 0xb9, 0xc5, 0x83, 0xce, 0x2d, 0x36, 0x95, + 0xa9, 0xe1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xfb, 0xcc, 0x93, 0x9d, 0xce, 0x24, 0x9b, 0x3e, 0xf9, + 0x7d, 0x2f, 0xe3, 0x63, 0x63, 0x0c, 0x75, 0xd8, 0xf6, 0x81, 0xb2, 0x02, 0xae, 0xc4, 0x61, 0x7a, + 0xd3, 0xdf, 0x1e, 0xd5, 0xd5, 0xfd, 0x65, 0x61, 0x24, 0x33, 0xf5, 0x1f, 0x5f, 0x06, 0x6e, 0xd0, + 0x85, 0x63, 0x65, 0x55, 0x3d, 0xed, 0x1a, 0xf3, 0xb5, 0x57, 0x13, 0x5e, 0x7f, 0x57, 0xc9, 0x35, + 0x98, 0x4f, 0x0c, 0x70, 0xe0, 0xe6, 0x8b, 0x77, 0xe2, 0xa6, 0x89, 0xda, 0xf3, 0xef, 0xe8, 0x72, + 0x1d, 0xf1, 0x58, 0xa1, 0x36, 0xad, 0xe7, 0x35, 0x30, 0xac, 0xca, 0x4f, 0x48, 0x3a, 0x79, 0x7a, + 0xbc, 0x0a, 0xb1, 0x82, 0xb3, 0x24, 0xfb, 0x61, 0xd1, 0x08, 0xa9, 0x4b, 0xb2, 0xc8, 0xe3, 0xfb, + 0xb9, 0x6a, 0xda, 0xb7, 0x60, 0xd7, 0xf4, 0x68, 0x1d, 0x4f, 0x42, 0xa3, 0xde, 0x39, 0x4d, 0xf4, + 0xae, 0x56, 0xed, 0xe7, 0x63, 0x72, 0xbb, 0x19, 0x0b, 0x07, 0xa7, 0xc8, 0xee, 0x0a, 0x6d, 0x70, + 0x9e, 0x02, 0xfc, 0xe1, 0xcd, 0xf7, 0xe2, 0xec, 0xc0, 0x34, 0x04, 0xcd, 0x28, 0x34, 0x2f, 0x61, + 0x91, 0x72, 0xfe, 0x9c, 0xe9, 0x85, 0x83, 0xff, 0x8e, 0x4f, 0x12, 0x32, 0xee, 0xf2, 0x81, 0x83, + 0xc3, 0xfe, 0x3b, 0x1b, 0x4c, 0x6f, 0xad, 0x73, 0x3b, 0xb5, 0xfc, 0xbc, 0x2e, 0xc2, 0x20, 0x05, + 0xc5, 0x8e, 0xf1, 0x83, 0x7d, 0x16, 0x83, 0xb2, 0xc6, 0xf3, 0x4a, 0x26, 0xc1, 0xb2, 0xef, 0xfa, + 0x88, 0x6b, 0x42, 0x38, 0x61, 0x1f, 0xcf, 0xdc, 0xde, 0x35, 0x5b, 0x3b, 0x65, 0x19, 0x03, 0x5b, + 0xbc, 0x34, 0xf4, 0xde, 0xf9, 0x9c, 0x02, 0x38, 0x61, 0xb4, 0x6f, 0xc9, 0xd6, 0xe6, 0xc9, 0x07, + 0x7a, 0xd9, 0x1d, 0x26, 0x91, 0xf7, 0xf7, 0xee, 0x59, 0x8c, 0xb0, 0xfa, 0xc1, 0x86, 0xd9, 0x1c, + 0xae, 0xfe, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70, 0xb4, 0x13, 0x0c, 0x93, 0xbc, 0x43, 0x79, 0x44, + 0xf4, 0xfd, 0x44, 0x52, 0xe2, 0xd7, 0x4d, 0xd3, 0x64, 0xf2, 0xe2, 0x1e, 0x71, 0xf5, 0x4b, 0xff, + 0x5c, 0xae, 0x82, 0xab, 0x9c, 0x9d, 0xf6, 0x9e, 0xe8, 0x6d, 0x2b, 0xc5, 0x22, 0x36, 0x3a, 0x0d, + 0xab, 0xc5, 0x21, 0x97, 0x9b, 0x0d, 0xea, 0xda, 0x1d, 0xbf, 0x9a, 0x42, 0xd5, 0xc4, 0x48, 0x4e, + 0x0a, 0xbc, 0xd0, 0x6b, 0xfa, 0x53, 0xdd, 0xef, 0x3c, 0x1b, 0x20, 0xee, 0x3f, 0xd5, 0x9d, 0x7c, + 0x25, 0xe4, 0x1d, 0x2b, 0x66, 0xc6, 0x2e, 0x37, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +}; + +static const unsigned char scr_dh_ffdhe4096_p[512] = { + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xad, 0xf8, 0x54, 0x58, 0xa2, 0xbb, 0x4a, 0x9a, + 0xaf, 0xdc, 0x56, 0x20, 0x27, 0x3d, 0x3c, 0xf1, 0xd8, 0xb9, 0xc5, 0x83, 0xce, 0x2d, 0x36, 0x95, + 0xa9, 0xe1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xfb, 0xcc, 0x93, 0x9d, 0xce, 0x24, 0x9b, 0x3e, 0xf9, + 0x7d, 0x2f, 0xe3, 0x63, 0x63, 0x0c, 0x75, 0xd8, 0xf6, 0x81, 0xb2, 0x02, 0xae, 0xc4, 0x61, 0x7a, + 0xd3, 0xdf, 0x1e, 0xd5, 0xd5, 0xfd, 0x65, 0x61, 0x24, 0x33, 0xf5, 0x1f, 0x5f, 0x06, 0x6e, 0xd0, + 0x85, 0x63, 0x65, 0x55, 0x3d, 0xed, 0x1a, 0xf3, 0xb5, 0x57, 0x13, 0x5e, 0x7f, 0x57, 0xc9, 0x35, + 0x98, 0x4f, 0x0c, 0x70, 0xe0, 0xe6, 0x8b, 0x77, 0xe2, 0xa6, 0x89, 0xda, 0xf3, 0xef, 0xe8, 0x72, + 0x1d, 0xf1, 0x58, 0xa1, 0x36, 0xad, 0xe7, 0x35, 0x30, 0xac, 0xca, 0x4f, 0x48, 0x3a, 0x79, 0x7a, + 0xbc, 0x0a, 0xb1, 0x82, 0xb3, 0x24, 0xfb, 0x61, 0xd1, 0x08, 0xa9, 0x4b, 0xb2, 0xc8, 0xe3, 0xfb, + 0xb9, 0x6a, 0xda, 0xb7, 0x60, 0xd7, 0xf4, 0x68, 0x1d, 0x4f, 0x42, 0xa3, 0xde, 0x39, 0x4d, 0xf4, + 0xae, 0x56, 0xed, 0xe7, 0x63, 0x72, 0xbb, 0x19, 0x0b, 0x07, 0xa7, 0xc8, 0xee, 0x0a, 0x6d, 0x70, + 0x9e, 0x02, 0xfc, 0xe1, 0xcd, 0xf7, 0xe2, 0xec, 0xc0, 0x34, 0x04, 0xcd, 0x28, 0x34, 0x2f, 0x61, + 0x91, 0x72, 0xfe, 0x9c, 0xe9, 0x85, 0x83, 0xff, 0x8e, 0x4f, 0x12, 0x32, 0xee, 0xf2, 0x81, 0x83, + 0xc3, 0xfe, 0x3b, 0x1b, 0x4c, 0x6f, 0xad, 0x73, 0x3b, 0xb5, 0xfc, 0xbc, 0x2e, 0xc2, 0x20, 0x05, + 0xc5, 0x8e, 0xf1, 0x83, 0x7d, 0x16, 0x83, 0xb2, 0xc6, 0xf3, 0x4a, 0x26, 0xc1, 0xb2, 0xef, 0xfa, + 0x88, 0x6b, 0x42, 0x38, 0x61, 0x1f, 0xcf, 0xdc, 0xde, 0x35, 0x5b, 0x3b, 0x65, 0x19, 0x03, 0x5b, + 0xbc, 0x34, 0xf4, 0xde, 0xf9, 0x9c, 0x02, 0x38, 0x61, 0xb4, 0x6f, 0xc9, 0xd6, 0xe6, 0xc9, 0x07, + 0x7a, 0xd9, 0x1d, 0x26, 0x91, 0xf7, 0xf7, 0xee, 0x59, 0x8c, 0xb0, 0xfa, 0xc1, 0x86, 0xd9, 0x1c, + 0xae, 0xfe, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70, 0xb4, 0x13, 0x0c, 0x93, 0xbc, 0x43, 0x79, 0x44, + 0xf4, 0xfd, 0x44, 0x52, 0xe2, 0xd7, 0x4d, 0xd3, 0x64, 0xf2, 0xe2, 0x1e, 0x71, 0xf5, 0x4b, 0xff, + 0x5c, 0xae, 0x82, 0xab, 0x9c, 0x9d, 0xf6, 0x9e, 0xe8, 0x6d, 0x2b, 0xc5, 0x22, 0x36, 0x3a, 0x0d, + 0xab, 0xc5, 0x21, 0x97, 0x9b, 0x0d, 0xea, 0xda, 0x1d, 0xbf, 0x9a, 0x42, 0xd5, 0xc4, 0x48, 0x4e, + 0x0a, 0xbc, 0xd0, 0x6b, 0xfa, 0x53, 0xdd, 0xef, 0x3c, 0x1b, 0x20, 0xee, 0x3f, 0xd5, 0x9d, 0x7c, + 0x25, 0xe4, 0x1d, 0x2b, 0x66, 0x9e, 0x1e, 0xf1, 0x6e, 0x6f, 0x52, 0xc3, 0x16, 0x4d, 0xf4, 0xfb, + 0x79, 0x30, 0xe9, 0xe4, 0xe5, 0x88, 0x57, 0xb6, 0xac, 0x7d, 0x5f, 0x42, 0xd6, 0x9f, 0x6d, 0x18, + 0x77, 0x63, 0xcf, 0x1d, 0x55, 0x03, 0x40, 0x04, 0x87, 0xf5, 0x5b, 0xa5, 0x7e, 0x31, 0xcc, 0x7a, + 0x71, 0x35, 0xc8, 0x86, 0xef, 0xb4, 0x31, 0x8a, 0xed, 0x6a, 0x1e, 0x01, 0x2d, 0x9e, 0x68, 0x32, + 0xa9, 0x07, 0x60, 0x0a, 0x91, 0x81, 0x30, 0xc4, 0x6d, 0xc7, 0x78, 0xf9, 0x71, 0xad, 0x00, 0x38, + 0x09, 0x29, 0x99, 0xa3, 0x33, 0xcb, 0x8b, 0x7a, 0x1a, 0x1d, 0xb9, 0x3d, 0x71, 0x40, 0x00, 0x3c, + 0x2a, 0x4e, 0xce, 0xa9, 0xf9, 0x8d, 0x0a, 0xcc, 0x0a, 0x82, 0x91, 0xcd, 0xce, 0xc9, 0x7d, 0xcf, + 0x8e, 0xc9, 0xb5, 0x5a, 0x7f, 0x88, 0xa4, 0x6b, 0x4d, 0xb5, 0xa8, 0x51, 0xf4, 0x41, 0x82, 0xe1, + 0xc6, 0x8a, 0x00, 0x7e, 0x5e, 0x65, 0x5f, 0x6a, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +}; + +static const unsigned char scr_dh_ffdhe6144_p[768] = { + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xad, 0xf8, 0x54, 0x58, 0xa2, 0xbb, 0x4a, 0x9a, + 0xaf, 0xdc, 0x56, 0x20, 0x27, 0x3d, 0x3c, 0xf1, 0xd8, 0xb9, 0xc5, 0x83, 0xce, 0x2d, 0x36, 0x95, + 0xa9, 0xe1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xfb, 0xcc, 0x93, 0x9d, 0xce, 0x24, 0x9b, 0x3e, 0xf9, + 0x7d, 0x2f, 0xe3, 0x63, 0x63, 0x0c, 0x75, 0xd8, 0xf6, 0x81, 0xb2, 0x02, 0xae, 0xc4, 0x61, 0x7a, + 0xd3, 0xdf, 0x1e, 0xd5, 0xd5, 0xfd, 0x65, 0x61, 0x24, 0x33, 0xf5, 0x1f, 0x5f, 0x06, 0x6e, 0xd0, + 0x85, 0x63, 0x65, 0x55, 0x3d, 0xed, 0x1a, 0xf3, 0xb5, 0x57, 0x13, 0x5e, 0x7f, 0x57, 0xc9, 0x35, + 0x98, 0x4f, 0x0c, 0x70, 0xe0, 0xe6, 0x8b, 0x77, 0xe2, 0xa6, 0x89, 0xda, 0xf3, 0xef, 0xe8, 0x72, + 0x1d, 0xf1, 0x58, 0xa1, 0x36, 0xad, 0xe7, 0x35, 0x30, 0xac, 0xca, 0x4f, 0x48, 0x3a, 0x79, 0x7a, + 0xbc, 0x0a, 0xb1, 0x82, 0xb3, 0x24, 0xfb, 0x61, 0xd1, 0x08, 0xa9, 0x4b, 0xb2, 0xc8, 0xe3, 0xfb, + 0xb9, 0x6a, 0xda, 0xb7, 0x60, 0xd7, 0xf4, 0x68, 0x1d, 0x4f, 0x42, 0xa3, 0xde, 0x39, 0x4d, 0xf4, + 0xae, 0x56, 0xed, 0xe7, 0x63, 0x72, 0xbb, 0x19, 0x0b, 0x07, 0xa7, 0xc8, 0xee, 0x0a, 0x6d, 0x70, + 0x9e, 0x02, 0xfc, 0xe1, 0xcd, 0xf7, 0xe2, 0xec, 0xc0, 0x34, 0x04, 0xcd, 0x28, 0x34, 0x2f, 0x61, + 0x91, 0x72, 0xfe, 0x9c, 0xe9, 0x85, 0x83, 0xff, 0x8e, 0x4f, 0x12, 0x32, 0xee, 0xf2, 0x81, 0x83, + 0xc3, 0xfe, 0x3b, 0x1b, 0x4c, 0x6f, 0xad, 0x73, 0x3b, 0xb5, 0xfc, 0xbc, 0x2e, 0xc2, 0x20, 0x05, + 0xc5, 0x8e, 0xf1, 0x83, 0x7d, 0x16, 0x83, 0xb2, 0xc6, 0xf3, 0x4a, 0x26, 0xc1, 0xb2, 0xef, 0xfa, + 0x88, 0x6b, 0x42, 0x38, 0x61, 0x1f, 0xcf, 0xdc, 0xde, 0x35, 0x5b, 0x3b, 0x65, 0x19, 0x03, 0x5b, + 0xbc, 0x34, 0xf4, 0xde, 0xf9, 0x9c, 0x02, 0x38, 0x61, 0xb4, 0x6f, 0xc9, 0xd6, 0xe6, 0xc9, 0x07, + 0x7a, 0xd9, 0x1d, 0x26, 0x91, 0xf7, 0xf7, 0xee, 0x59, 0x8c, 0xb0, 0xfa, 0xc1, 0x86, 0xd9, 0x1c, + 0xae, 0xfe, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70, 0xb4, 0x13, 0x0c, 0x93, 0xbc, 0x43, 0x79, 0x44, + 0xf4, 0xfd, 0x44, 0x52, 0xe2, 0xd7, 0x4d, 0xd3, 0x64, 0xf2, 0xe2, 0x1e, 0x71, 0xf5, 0x4b, 0xff, + 0x5c, 0xae, 0x82, 0xab, 0x9c, 0x9d, 0xf6, 0x9e, 0xe8, 0x6d, 0x2b, 0xc5, 0x22, 0x36, 0x3a, 0x0d, + 0xab, 0xc5, 0x21, 0x97, 0x9b, 0x0d, 0xea, 0xda, 0x1d, 0xbf, 0x9a, 0x42, 0xd5, 0xc4, 0x48, 0x4e, + 0x0a, 0xbc, 0xd0, 0x6b, 0xfa, 0x53, 0xdd, 0xef, 0x3c, 0x1b, 0x20, 0xee, 0x3f, 0xd5, 0x9d, 0x7c, + 0x25, 0xe4, 0x1d, 0x2b, 0x66, 0x9e, 0x1e, 0xf1, 0x6e, 0x6f, 0x52, 0xc3, 0x16, 0x4d, 0xf4, 0xfb, + 0x79, 0x30, 0xe9, 0xe4, 0xe5, 0x88, 0x57, 0xb6, 0xac, 0x7d, 0x5f, 0x42, 0xd6, 0x9f, 0x6d, 0x18, + 0x77, 0x63, 0xcf, 0x1d, 0x55, 0x03, 0x40, 0x04, 0x87, 0xf5, 0x5b, 0xa5, 0x7e, 0x31, 0xcc, 0x7a, + 0x71, 0x35, 0xc8, 0x86, 0xef, 0xb4, 0x31, 0x8a, 0xed, 0x6a, 0x1e, 0x01, 0x2d, 0x9e, 0x68, 0x32, + 0xa9, 0x07, 0x60, 0x0a, 0x91, 0x81, 0x30, 0xc4, 0x6d, 0xc7, 0x78, 0xf9, 0x71, 0xad, 0x00, 0x38, + 0x09, 0x29, 0x99, 0xa3, 0x33, 0xcb, 0x8b, 0x7a, 0x1a, 0x1d, 0xb9, 0x3d, 0x71, 0x40, 0x00, 0x3c, + 0x2a, 0x4e, 0xce, 0xa9, 0xf9, 0x8d, 0x0a, 0xcc, 0x0a, 0x82, 0x91, 0xcd, 0xce, 0xc9, 0x7d, 0xcf, + 0x8e, 0xc9, 0xb5, 0x5a, 0x7f, 0x88, 0xa4, 0x6b, 0x4d, 0xb5, 0xa8, 0x51, 0xf4, 0x41, 0x82, 0xe1, + 0xc6, 0x8a, 0x00, 0x7e, 0x5e, 0x0d, 0xd9, 0x02, 0x0b, 0xfd, 0x64, 0xb6, 0x45, 0x03, 0x6c, 0x7a, + 0x4e, 0x67, 0x7d, 0x2c, 0x38, 0x53, 0x2a, 0x3a, 0x23, 0xba, 0x44, 0x42, 0xca, 0xf5, 0x3e, 0xa6, + 0x3b, 0xb4, 0x54, 0x32, 0x9b, 0x76, 0x24, 0xc8, 0x91, 0x7b, 0xdd, 0x64, 0xb1, 0xc0, 0xfd, 0x4c, + 0xb3, 0x8e, 0x8c, 0x33, 0x4c, 0x70, 0x1c, 0x3a, 0xcd, 0xad, 0x06, 0x57, 0xfc, 0xcf, 0xec, 0x71, + 0x9b, 0x1f, 0x5c, 0x3e, 0x4e, 0x46, 0x04, 0x1f, 0x38, 0x81, 0x47, 0xfb, 0x4c, 0xfd, 0xb4, 0x77, + 0xa5, 0x24, 0x71, 0xf7, 0xa9, 0xa9, 0x69, 0x10, 0xb8, 0x55, 0x32, 0x2e, 0xdb, 0x63, 0x40, 0xd8, + 0xa0, 0x0e, 0xf0, 0x92, 0x35, 0x05, 0x11, 0xe3, 0x0a, 0xbe, 0xc1, 0xff, 0xf9, 0xe3, 0xa2, 0x6e, + 0x7f, 0xb2, 0x9f, 0x8c, 0x18, 0x30, 0x23, 0xc3, 0x58, 0x7e, 0x38, 0xda, 0x00, 0x77, 0xd9, 0xb4, + 0x76, 0x3e, 0x4e, 0x4b, 0x94, 0xb2, 0xbb, 0xc1, 0x94, 0xc6, 0x65, 0x1e, 0x77, 0xca, 0xf9, 0x92, + 0xee, 0xaa, 0xc0, 0x23, 0x2a, 0x28, 0x1b, 0xf6, 0xb3, 0xa7, 0x39, 0xc1, 0x22, 0x61, 0x16, 0x82, + 0x0a, 0xe8, 0xdb, 0x58, 0x47, 0xa6, 0x7c, 0xbe, 0xf9, 0xc9, 0x09, 0x1b, 0x46, 0x2d, 0x53, 0x8c, + 0xd7, 0x2b, 0x03, 0x74, 0x6a, 0xe7, 0x7f, 0x5e, 0x62, 0x29, 0x2c, 0x31, 0x15, 0x62, 0xa8, 0x46, + 0x50, 0x5d, 0xc8, 0x2d, 0xb8, 0x54, 0x33, 0x8a, 0xe4, 0x9f, 0x52, 0x35, 0xc9, 0x5b, 0x91, 0x17, + 0x8c, 0xcf, 0x2d, 0xd5, 0xca, 0xce, 0xf4, 0x03, 0xec, 0x9d, 0x18, 0x10, 0xc6, 0x27, 0x2b, 0x04, + 0x5b, 0x3b, 0x71, 0xf9, 0xdc, 0x6b, 0x80, 0xd6, 0x3f, 0xdd, 0x4a, 0x8e, 0x9a, 0xdb, 0x1e, 0x69, + 0x62, 0xa6, 0x95, 0x26, 0xd4, 0x31, 0x61, 0xc1, 0xa4, 0x1d, 0x57, 0x0d, 0x79, 0x38, 0xda, 0xd4, + 0xa4, 0x0e, 0x32, 0x9c, 0xd0, 0xe4, 0x0e, 0x65, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +}; + +static const unsigned char scr_dh_ffdhe8192_p[1024] = { + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xad, 0xf8, 0x54, 0x58, 0xa2, 0xbb, 0x4a, 0x9a, + 0xaf, 0xdc, 0x56, 0x20, 0x27, 0x3d, 0x3c, 0xf1, 0xd8, 0xb9, 0xc5, 0x83, 0xce, 0x2d, 0x36, 0x95, + 0xa9, 0xe1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xfb, 0xcc, 0x93, 0x9d, 0xce, 0x24, 0x9b, 0x3e, 0xf9, + 0x7d, 0x2f, 0xe3, 0x63, 0x63, 0x0c, 0x75, 0xd8, 0xf6, 0x81, 0xb2, 0x02, 0xae, 0xc4, 0x61, 0x7a, + 0xd3, 0xdf, 0x1e, 0xd5, 0xd5, 0xfd, 0x65, 0x61, 0x24, 0x33, 0xf5, 0x1f, 0x5f, 0x06, 0x6e, 0xd0, + 0x85, 0x63, 0x65, 0x55, 0x3d, 0xed, 0x1a, 0xf3, 0xb5, 0x57, 0x13, 0x5e, 0x7f, 0x57, 0xc9, 0x35, + 0x98, 0x4f, 0x0c, 0x70, 0xe0, 0xe6, 0x8b, 0x77, 0xe2, 0xa6, 0x89, 0xda, 0xf3, 0xef, 0xe8, 0x72, + 0x1d, 0xf1, 0x58, 0xa1, 0x36, 0xad, 0xe7, 0x35, 0x30, 0xac, 0xca, 0x4f, 0x48, 0x3a, 0x79, 0x7a, + 0xbc, 0x0a, 0xb1, 0x82, 0xb3, 0x24, 0xfb, 0x61, 0xd1, 0x08, 0xa9, 0x4b, 0xb2, 0xc8, 0xe3, 0xfb, + 0xb9, 0x6a, 0xda, 0xb7, 0x60, 0xd7, 0xf4, 0x68, 0x1d, 0x4f, 0x42, 0xa3, 0xde, 0x39, 0x4d, 0xf4, + 0xae, 0x56, 0xed, 0xe7, 0x63, 0x72, 0xbb, 0x19, 0x0b, 0x07, 0xa7, 0xc8, 0xee, 0x0a, 0x6d, 0x70, + 0x9e, 0x02, 0xfc, 0xe1, 0xcd, 0xf7, 0xe2, 0xec, 0xc0, 0x34, 0x04, 0xcd, 0x28, 0x34, 0x2f, 0x61, + 0x91, 0x72, 0xfe, 0x9c, 0xe9, 0x85, 0x83, 0xff, 0x8e, 0x4f, 0x12, 0x32, 0xee, 0xf2, 0x81, 0x83, + 0xc3, 0xfe, 0x3b, 0x1b, 0x4c, 0x6f, 0xad, 0x73, 0x3b, 0xb5, 0xfc, 0xbc, 0x2e, 0xc2, 0x20, 0x05, + 0xc5, 0x8e, 0xf1, 0x83, 0x7d, 0x16, 0x83, 0xb2, 0xc6, 0xf3, 0x4a, 0x26, 0xc1, 0xb2, 0xef, 0xfa, + 0x88, 0x6b, 0x42, 0x38, 0x61, 0x1f, 0xcf, 0xdc, 0xde, 0x35, 0x5b, 0x3b, 0x65, 0x19, 0x03, 0x5b, + 0xbc, 0x34, 0xf4, 0xde, 0xf9, 0x9c, 0x02, 0x38, 0x61, 0xb4, 0x6f, 0xc9, 0xd6, 0xe6, 0xc9, 0x07, + 0x7a, 0xd9, 0x1d, 0x26, 0x91, 0xf7, 0xf7, 0xee, 0x59, 0x8c, 0xb0, 0xfa, 0xc1, 0x86, 0xd9, 0x1c, + 0xae, 0xfe, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70, 0xb4, 0x13, 0x0c, 0x93, 0xbc, 0x43, 0x79, 0x44, + 0xf4, 0xfd, 0x44, 0x52, 0xe2, 0xd7, 0x4d, 0xd3, 0x64, 0xf2, 0xe2, 0x1e, 0x71, 0xf5, 0x4b, 0xff, + 0x5c, 0xae, 0x82, 0xab, 0x9c, 0x9d, 0xf6, 0x9e, 0xe8, 0x6d, 0x2b, 0xc5, 0x22, 0x36, 0x3a, 0x0d, + 0xab, 0xc5, 0x21, 0x97, 0x9b, 0x0d, 0xea, 0xda, 0x1d, 0xbf, 0x9a, 0x42, 0xd5, 0xc4, 0x48, 0x4e, + 0x0a, 0xbc, 0xd0, 0x6b, 0xfa, 0x53, 0xdd, 0xef, 0x3c, 0x1b, 0x20, 0xee, 0x3f, 0xd5, 0x9d, 0x7c, + 0x25, 0xe4, 0x1d, 0x2b, 0x66, 0x9e, 0x1e, 0xf1, 0x6e, 0x6f, 0x52, 0xc3, 0x16, 0x4d, 0xf4, 0xfb, + 0x79, 0x30, 0xe9, 0xe4, 0xe5, 0x88, 0x57, 0xb6, 0xac, 0x7d, 0x5f, 0x42, 0xd6, 0x9f, 0x6d, 0x18, + 0x77, 0x63, 0xcf, 0x1d, 0x55, 0x03, 0x40, 0x04, 0x87, 0xf5, 0x5b, 0xa5, 0x7e, 0x31, 0xcc, 0x7a, + 0x71, 0x35, 0xc8, 0x86, 0xef, 0xb4, 0x31, 0x8a, 0xed, 0x6a, 0x1e, 0x01, 0x2d, 0x9e, 0x68, 0x32, + 0xa9, 0x07, 0x60, 0x0a, 0x91, 0x81, 0x30, 0xc4, 0x6d, 0xc7, 0x78, 0xf9, 0x71, 0xad, 0x00, 0x38, + 0x09, 0x29, 0x99, 0xa3, 0x33, 0xcb, 0x8b, 0x7a, 0x1a, 0x1d, 0xb9, 0x3d, 0x71, 0x40, 0x00, 0x3c, + 0x2a, 0x4e, 0xce, 0xa9, 0xf9, 0x8d, 0x0a, 0xcc, 0x0a, 0x82, 0x91, 0xcd, 0xce, 0xc9, 0x7d, 0xcf, + 0x8e, 0xc9, 0xb5, 0x5a, 0x7f, 0x88, 0xa4, 0x6b, 0x4d, 0xb5, 0xa8, 0x51, 0xf4, 0x41, 0x82, 0xe1, + 0xc6, 0x8a, 0x00, 0x7e, 0x5e, 0x0d, 0xd9, 0x02, 0x0b, 0xfd, 0x64, 0xb6, 0x45, 0x03, 0x6c, 0x7a, + 0x4e, 0x67, 0x7d, 0x2c, 0x38, 0x53, 0x2a, 0x3a, 0x23, 0xba, 0x44, 0x42, 0xca, 0xf5, 0x3e, 0xa6, + 0x3b, 0xb4, 0x54, 0x32, 0x9b, 0x76, 0x24, 0xc8, 0x91, 0x7b, 0xdd, 0x64, 0xb1, 0xc0, 0xfd, 0x4c, + 0xb3, 0x8e, 0x8c, 0x33, 0x4c, 0x70, 0x1c, 0x3a, 0xcd, 0xad, 0x06, 0x57, 0xfc, 0xcf, 0xec, 0x71, + 0x9b, 0x1f, 0x5c, 0x3e, 0x4e, 0x46, 0x04, 0x1f, 0x38, 0x81, 0x47, 0xfb, 0x4c, 0xfd, 0xb4, 0x77, + 0xa5, 0x24, 0x71, 0xf7, 0xa9, 0xa9, 0x69, 0x10, 0xb8, 0x55, 0x32, 0x2e, 0xdb, 0x63, 0x40, 0xd8, + 0xa0, 0x0e, 0xf0, 0x92, 0x35, 0x05, 0x11, 0xe3, 0x0a, 0xbe, 0xc1, 0xff, 0xf9, 0xe3, 0xa2, 0x6e, + 0x7f, 0xb2, 0x9f, 0x8c, 0x18, 0x30, 0x23, 0xc3, 0x58, 0x7e, 0x38, 0xda, 0x00, 0x77, 0xd9, 0xb4, + 0x76, 0x3e, 0x4e, 0x4b, 0x94, 0xb2, 0xbb, 0xc1, 0x94, 0xc6, 0x65, 0x1e, 0x77, 0xca, 0xf9, 0x92, + 0xee, 0xaa, 0xc0, 0x23, 0x2a, 0x28, 0x1b, 0xf6, 0xb3, 0xa7, 0x39, 0xc1, 0x22, 0x61, 0x16, 0x82, + 0x0a, 0xe8, 0xdb, 0x58, 0x47, 0xa6, 0x7c, 0xbe, 0xf9, 0xc9, 0x09, 0x1b, 0x46, 0x2d, 0x53, 0x8c, + 0xd7, 0x2b, 0x03, 0x74, 0x6a, 0xe7, 0x7f, 0x5e, 0x62, 0x29, 0x2c, 0x31, 0x15, 0x62, 0xa8, 0x46, + 0x50, 0x5d, 0xc8, 0x2d, 0xb8, 0x54, 0x33, 0x8a, 0xe4, 0x9f, 0x52, 0x35, 0xc9, 0x5b, 0x91, 0x17, + 0x8c, 0xcf, 0x2d, 0xd5, 0xca, 0xce, 0xf4, 0x03, 0xec, 0x9d, 0x18, 0x10, 0xc6, 0x27, 0x2b, 0x04, + 0x5b, 0x3b, 0x71, 0xf9, 0xdc, 0x6b, 0x80, 0xd6, 0x3f, 0xdd, 0x4a, 0x8e, 0x9a, 0xdb, 0x1e, 0x69, + 0x62, 0xa6, 0x95, 0x26, 0xd4, 0x31, 0x61, 0xc1, 0xa4, 0x1d, 0x57, 0x0d, 0x79, 0x38, 0xda, 0xd4, + 0xa4, 0x0e, 0x32, 0x9c, 0xcf, 0xf4, 0x6a, 0xaa, 0x36, 0xad, 0x00, 0x4c, 0xf6, 0x00, 0xc8, 0x38, + 0x1e, 0x42, 0x5a, 0x31, 0xd9, 0x51, 0xae, 0x64, 0xfd, 0xb2, 0x3f, 0xce, 0xc9, 0x50, 0x9d, 0x43, + 0x68, 0x7f, 0xeb, 0x69, 0xed, 0xd1, 0xcc, 0x5e, 0x0b, 0x8c, 0xc3, 0xbd, 0xf6, 0x4b, 0x10, 0xef, + 0x86, 0xb6, 0x31, 0x42, 0xa3, 0xab, 0x88, 0x29, 0x55, 0x5b, 0x2f, 0x74, 0x7c, 0x93, 0x26, 0x65, + 0xcb, 0x2c, 0x0f, 0x1c, 0xc0, 0x1b, 0xd7, 0x02, 0x29, 0x38, 0x88, 0x39, 0xd2, 0xaf, 0x05, 0xe4, + 0x54, 0x50, 0x4a, 0xc7, 0x8b, 0x75, 0x82, 0x82, 0x28, 0x46, 0xc0, 0xba, 0x35, 0xc3, 0x5f, 0x5c, + 0x59, 0x16, 0x0c, 0xc0, 0x46, 0xfd, 0x82, 0x51, 0x54, 0x1f, 0xc6, 0x8c, 0x9c, 0x86, 0xb0, 0x22, + 0xbb, 0x70, 0x99, 0x87, 0x6a, 0x46, 0x0e, 0x74, 0x51, 0xa8, 0xa9, 0x31, 0x09, 0x70, 0x3f, 0xee, + 0x1c, 0x21, 0x7e, 0x6c, 0x38, 0x26, 0xe5, 0x2c, 0x51, 0xaa, 0x69, 0x1e, 0x0e, 0x42, 0x3c, 0xfc, + 0x99, 0xe9, 0xe3, 0x16, 0x50, 0xc1, 0x21, 0x7b, 0x62, 0x48, 0x16, 0xcd, 0xad, 0x9a, 0x95, 0xf9, + 0xd5, 0xb8, 0x01, 0x94, 0x88, 0xd9, 0xc0, 0xa0, 0xa1, 0xfe, 0x30, 0x75, 0xa5, 0x77, 0xe2, 0x31, + 0x83, 0xf8, 0x1d, 0x4a, 0x3f, 0x2f, 0xa4, 0x57, 0x1e, 0xfc, 0x8c, 0xe0, 0xba, 0x8a, 0x4f, 0xe8, + 0xb6, 0x85, 0x5d, 0xfe, 0x72, 0xb0, 0xa6, 0x6e, 0xde, 0xd2, 0xfb, 0xab, 0xfb, 0xe5, 0x8a, 0x30, + 0xfa, 0xfa, 0xbe, 0x1c, 0x5d, 0x71, 0xa8, 0x7e, 0x2f, 0x74, 0x1e, 0xf8, 0xc1, 0xfe, 0x86, 0xfe, + 0xa6, 0xbb, 0xfd, 0xe5, 0x30, 0x67, 0x7f, 0x0d, 0x97, 0xd1, 0x1d, 0x49, 0xf7, 0xa8, 0x44, 0x3d, + 0x08, 0x22, 0xe5, 0x06, 0xa9, 0xf4, 0x61, 0x4e, 0x01, 0x1e, 0x2a, 0x94, 0x83, 0x8f, 0xf8, 0x8c, + 0xd6, 0x8c, 0x8b, 0xb7, 0xc5, 0xc6, 0x42, 0x4c, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +}; + +static const unsigned char scr_dh_dh_1024_160_p[128] = { + 0xb1, 0x0b, 0x8f, 0x96, 0xa0, 0x80, 0xe0, 0x1d, 0xde, 0x92, 0xde, 0x5e, 0xae, 0x5d, 0x54, 0xec, + 0x52, 0xc9, 0x9f, 0xbc, 0xfb, 0x06, 0xa3, 0xc6, 0x9a, 0x6a, 0x9d, 0xca, 0x52, 0xd2, 0x3b, 0x61, + 0x60, 0x73, 0xe2, 0x86, 0x75, 0xa2, 0x3d, 0x18, 0x98, 0x38, 0xef, 0x1e, 0x2e, 0xe6, 0x52, 0xc0, + 0x13, 0xec, 0xb4, 0xae, 0xa9, 0x06, 0x11, 0x23, 0x24, 0x97, 0x5c, 0x3c, 0xd4, 0x9b, 0x83, 0xbf, + 0xac, 0xcb, 0xdd, 0x7d, 0x90, 0xc4, 0xbd, 0x70, 0x98, 0x48, 0x8e, 0x9c, 0x21, 0x9a, 0x73, 0x72, + 0x4e, 0xff, 0xd6, 0xfa, 0xe5, 0x64, 0x47, 0x38, 0xfa, 0xa3, 0x1a, 0x4f, 0xf5, 0x5b, 0xcc, 0xc0, + 0xa1, 0x51, 0xaf, 0x5f, 0x0d, 0xc8, 0xb4, 0xbd, 0x45, 0xbf, 0x37, 0xdf, 0x36, 0x5c, 0x1a, 0x65, + 0xe6, 0x8c, 0xfd, 0xa7, 0x6d, 0x4d, 0xa7, 0x08, 0xdf, 0x1f, 0xb2, 0xbc, 0x2e, 0x4a, 0x43, 0x71, +}; + +static const unsigned char scr_dh_dh_1024_160_g[128] = { + 0xa4, 0xd1, 0xcb, 0xd5, 0xc3, 0xfd, 0x34, 0x12, 0x67, 0x65, 0xa4, 0x42, 0xef, 0xb9, 0x99, 0x05, + 0xf8, 0x10, 0x4d, 0xd2, 0x58, 0xac, 0x50, 0x7f, 0xd6, 0x40, 0x6c, 0xff, 0x14, 0x26, 0x6d, 0x31, + 0x26, 0x6f, 0xea, 0x1e, 0x5c, 0x41, 0x56, 0x4b, 0x77, 0x7e, 0x69, 0x0f, 0x55, 0x04, 0xf2, 0x13, + 0x16, 0x02, 0x17, 0xb4, 0xb0, 0x1b, 0x88, 0x6a, 0x5e, 0x91, 0x54, 0x7f, 0x9e, 0x27, 0x49, 0xf4, + 0xd7, 0xfb, 0xd7, 0xd3, 0xb9, 0xa9, 0x2e, 0xe1, 0x90, 0x9d, 0x0d, 0x22, 0x63, 0xf8, 0x0a, 0x76, + 0xa6, 0xa2, 0x4c, 0x08, 0x7a, 0x09, 0x1f, 0x53, 0x1d, 0xbf, 0x0a, 0x01, 0x69, 0xb6, 0xa2, 0x8a, + 0xd6, 0x62, 0xa4, 0xd1, 0x8e, 0x73, 0xaf, 0xa3, 0x2d, 0x77, 0x9d, 0x59, 0x18, 0xd0, 0x8b, 0xc8, + 0x85, 0x8f, 0x4d, 0xce, 0xf9, 0x7c, 0x2a, 0x24, 0x85, 0x5e, 0x6e, 0xeb, 0x22, 0xb3, 0xb2, 0xe5, +}; + +static const unsigned char scr_dh_dh_1024_160_q[20] = { + 0xf5, 0x18, 0xaa, 0x87, 0x81, 0xa8, 0xdf, 0x27, 0x8a, 0xba, 0x4e, 0x7d, 0x64, 0xb7, 0xcb, 0x9d, + 0x49, 0x46, 0x23, 0x53, +}; + +static const unsigned char scr_dh_dh_2048_224_p[256] = { + 0xad, 0x10, 0x7e, 0x1e, 0x91, 0x23, 0xa9, 0xd0, 0xd6, 0x60, 0xfa, 0xa7, 0x95, 0x59, 0xc5, 0x1f, + 0xa2, 0x0d, 0x64, 0xe5, 0x68, 0x3b, 0x9f, 0xd1, 0xb5, 0x4b, 0x15, 0x97, 0xb6, 0x1d, 0x0a, 0x75, + 0xe6, 0xfa, 0x14, 0x1d, 0xf9, 0x5a, 0x56, 0xdb, 0xaf, 0x9a, 0x3c, 0x40, 0x7b, 0xa1, 0xdf, 0x15, + 0xeb, 0x3d, 0x68, 0x8a, 0x30, 0x9c, 0x18, 0x0e, 0x1d, 0xe6, 0xb8, 0x5a, 0x12, 0x74, 0xa0, 0xa6, + 0x6d, 0x3f, 0x81, 0x52, 0xad, 0x6a, 0xc2, 0x12, 0x90, 0x37, 0xc9, 0xed, 0xef, 0xda, 0x4d, 0xf8, + 0xd9, 0x1e, 0x8f, 0xef, 0x55, 0xb7, 0x39, 0x4b, 0x7a, 0xd5, 0xb7, 0xd0, 0xb6, 0xc1, 0x22, 0x07, + 0xc9, 0xf9, 0x8d, 0x11, 0xed, 0x34, 0xdb, 0xf6, 0xc6, 0xba, 0x0b, 0x2c, 0x8b, 0xbc, 0x27, 0xbe, + 0x6a, 0x00, 0xe0, 0xa0, 0xb9, 0xc4, 0x97, 0x08, 0xb3, 0xbf, 0x8a, 0x31, 0x70, 0x91, 0x88, 0x36, + 0x81, 0x28, 0x61, 0x30, 0xbc, 0x89, 0x85, 0xdb, 0x16, 0x02, 0xe7, 0x14, 0x41, 0x5d, 0x93, 0x30, + 0x27, 0x82, 0x73, 0xc7, 0xde, 0x31, 0xef, 0xdc, 0x73, 0x10, 0xf7, 0x12, 0x1f, 0xd5, 0xa0, 0x74, + 0x15, 0x98, 0x7d, 0x9a, 0xdc, 0x0a, 0x48, 0x6d, 0xcd, 0xf9, 0x3a, 0xcc, 0x44, 0x32, 0x83, 0x87, + 0x31, 0x5d, 0x75, 0xe1, 0x98, 0xc6, 0x41, 0xa4, 0x80, 0xcd, 0x86, 0xa1, 0xb9, 0xe5, 0x87, 0xe8, + 0xbe, 0x60, 0xe6, 0x9c, 0xc9, 0x28, 0xb2, 0xb9, 0xc5, 0x21, 0x72, 0xe4, 0x13, 0x04, 0x2e, 0x9b, + 0x23, 0xf1, 0x0b, 0x0e, 0x16, 0xe7, 0x97, 0x63, 0xc9, 0xb5, 0x3d, 0xcf, 0x4b, 0xa8, 0x0a, 0x29, + 0xe3, 0xfb, 0x73, 0xc1, 0x6b, 0x8e, 0x75, 0xb9, 0x7e, 0xf3, 0x63, 0xe2, 0xff, 0xa3, 0x1f, 0x71, + 0xcf, 0x9d, 0xe5, 0x38, 0x4e, 0x71, 0xb8, 0x1c, 0x0a, 0xc4, 0xdf, 0xfe, 0x0c, 0x10, 0xe6, 0x4f, +}; + +static const unsigned char scr_dh_dh_2048_224_g[256] = { + 0xac, 0x40, 0x32, 0xef, 0x4f, 0x2d, 0x9a, 0xe3, 0x9d, 0xf3, 0x0b, 0x5c, 0x8f, 0xfd, 0xac, 0x50, + 0x6c, 0xde, 0xbe, 0x7b, 0x89, 0x99, 0x8c, 0xaf, 0x74, 0x86, 0x6a, 0x08, 0xcf, 0xe4, 0xff, 0xe3, + 0xa6, 0x82, 0x4a, 0x4e, 0x10, 0xb9, 0xa6, 0xf0, 0xdd, 0x92, 0x1f, 0x01, 0xa7, 0x0c, 0x4a, 0xfa, + 0xab, 0x73, 0x9d, 0x77, 0x00, 0xc2, 0x9f, 0x52, 0xc5, 0x7d, 0xb1, 0x7c, 0x62, 0x0a, 0x86, 0x52, + 0xbe, 0x5e, 0x90, 0x01, 0xa8, 0xd6, 0x6a, 0xd7, 0xc1, 0x76, 0x69, 0x10, 0x19, 0x99, 0x02, 0x4a, + 0xf4, 0xd0, 0x27, 0x27, 0x5a, 0xc1, 0x34, 0x8b, 0xb8, 0xa7, 0x62, 0xd0, 0x52, 0x1b, 0xc9, 0x8a, + 0xe2, 0x47, 0x15, 0x04, 0x22, 0xea, 0x1e, 0xd4, 0x09, 0x93, 0x9d, 0x54, 0xda, 0x74, 0x60, 0xcd, + 0xb5, 0xf6, 0xc6, 0xb2, 0x50, 0x71, 0x7c, 0xbe, 0xf1, 0x80, 0xeb, 0x34, 0x11, 0x8e, 0x98, 0xd1, + 0x19, 0x52, 0x9a, 0x45, 0xd6, 0xf8, 0x34, 0x56, 0x6e, 0x30, 0x25, 0xe3, 0x16, 0xa3, 0x30, 0xef, + 0xbb, 0x77, 0xa8, 0x6f, 0x0c, 0x1a, 0xb1, 0x5b, 0x05, 0x1a, 0xe3, 0xd4, 0x28, 0xc8, 0xf8, 0xac, + 0xb7, 0x0a, 0x81, 0x37, 0x15, 0x0b, 0x8e, 0xeb, 0x10, 0xe1, 0x83, 0xed, 0xd1, 0x99, 0x63, 0xdd, + 0xd9, 0xe2, 0x63, 0xe4, 0x77, 0x05, 0x89, 0xef, 0x6a, 0xa2, 0x1e, 0x7f, 0x5f, 0x2f, 0xf3, 0x81, + 0xb5, 0x39, 0xcc, 0xe3, 0x40, 0x9d, 0x13, 0xcd, 0x56, 0x6a, 0xfb, 0xb4, 0x8d, 0x6c, 0x01, 0x91, + 0x81, 0xe1, 0xbc, 0xfe, 0x94, 0xb3, 0x02, 0x69, 0xed, 0xfe, 0x72, 0xfe, 0x9b, 0x6a, 0xa4, 0xbd, + 0x7b, 0x5a, 0x0f, 0x1c, 0x71, 0xcf, 0xff, 0x4c, 0x19, 0xc4, 0x18, 0xe1, 0xf6, 0xec, 0x01, 0x79, + 0x81, 0xbc, 0x08, 0x7f, 0x2a, 0x70, 0x65, 0xb3, 0x84, 0xb8, 0x90, 0xd3, 0x19, 0x1f, 0x2b, 0xfa, +}; + +static const unsigned char scr_dh_dh_2048_224_q[28] = { + 0x80, 0x1c, 0x0d, 0x34, 0xc5, 0x8d, 0x93, 0xfe, 0x99, 0x71, 0x77, 0x10, 0x1f, 0x80, 0x53, 0x5a, + 0x47, 0x38, 0xce, 0xbc, 0xbf, 0x38, 0x9a, 0x99, 0xb3, 0x63, 0x71, 0xeb, +}; + +static const unsigned char scr_dh_dh_2048_256_p[256] = { + 0x87, 0xa8, 0xe6, 0x1d, 0xb4, 0xb6, 0x66, 0x3c, 0xff, 0xbb, 0xd1, 0x9c, 0x65, 0x19, 0x59, 0x99, + 0x8c, 0xee, 0xf6, 0x08, 0x66, 0x0d, 0xd0, 0xf2, 0x5d, 0x2c, 0xee, 0xd4, 0x43, 0x5e, 0x3b, 0x00, + 0xe0, 0x0d, 0xf8, 0xf1, 0xd6, 0x19, 0x57, 0xd4, 0xfa, 0xf7, 0xdf, 0x45, 0x61, 0xb2, 0xaa, 0x30, + 0x16, 0xc3, 0xd9, 0x11, 0x34, 0x09, 0x6f, 0xaa, 0x3b, 0xf4, 0x29, 0x6d, 0x83, 0x0e, 0x9a, 0x7c, + 0x20, 0x9e, 0x0c, 0x64, 0x97, 0x51, 0x7a, 0xbd, 0x5a, 0x8a, 0x9d, 0x30, 0x6b, 0xcf, 0x67, 0xed, + 0x91, 0xf9, 0xe6, 0x72, 0x5b, 0x47, 0x58, 0xc0, 0x22, 0xe0, 0xb1, 0xef, 0x42, 0x75, 0xbf, 0x7b, + 0x6c, 0x5b, 0xfc, 0x11, 0xd4, 0x5f, 0x90, 0x88, 0xb9, 0x41, 0xf5, 0x4e, 0xb1, 0xe5, 0x9b, 0xb8, + 0xbc, 0x39, 0xa0, 0xbf, 0x12, 0x30, 0x7f, 0x5c, 0x4f, 0xdb, 0x70, 0xc5, 0x81, 0xb2, 0x3f, 0x76, + 0xb6, 0x3a, 0xca, 0xe1, 0xca, 0xa6, 0xb7, 0x90, 0x2d, 0x52, 0x52, 0x67, 0x35, 0x48, 0x8a, 0x0e, + 0xf1, 0x3c, 0x6d, 0x9a, 0x51, 0xbf, 0xa4, 0xab, 0x3a, 0xd8, 0x34, 0x77, 0x96, 0x52, 0x4d, 0x8e, + 0xf6, 0xa1, 0x67, 0xb5, 0xa4, 0x18, 0x25, 0xd9, 0x67, 0xe1, 0x44, 0xe5, 0x14, 0x05, 0x64, 0x25, + 0x1c, 0xca, 0xcb, 0x83, 0xe6, 0xb4, 0x86, 0xf6, 0xb3, 0xca, 0x3f, 0x79, 0x71, 0x50, 0x60, 0x26, + 0xc0, 0xb8, 0x57, 0xf6, 0x89, 0x96, 0x28, 0x56, 0xde, 0xd4, 0x01, 0x0a, 0xbd, 0x0b, 0xe6, 0x21, + 0xc3, 0xa3, 0x96, 0x0a, 0x54, 0xe7, 0x10, 0xc3, 0x75, 0xf2, 0x63, 0x75, 0xd7, 0x01, 0x41, 0x03, + 0xa4, 0xb5, 0x43, 0x30, 0xc1, 0x98, 0xaf, 0x12, 0x61, 0x16, 0xd2, 0x27, 0x6e, 0x11, 0x71, 0x5f, + 0x69, 0x38, 0x77, 0xfa, 0xd7, 0xef, 0x09, 0xca, 0xdb, 0x09, 0x4a, 0xe9, 0x1e, 0x1a, 0x15, 0x97, +}; + +static const unsigned char scr_dh_dh_2048_256_g[256] = { + 0x3f, 0xb3, 0x2c, 0x9b, 0x73, 0x13, 0x4d, 0x0b, 0x2e, 0x77, 0x50, 0x66, 0x60, 0xed, 0xbd, 0x48, + 0x4c, 0xa7, 0xb1, 0x8f, 0x21, 0xef, 0x20, 0x54, 0x07, 0xf4, 0x79, 0x3a, 0x1a, 0x0b, 0xa1, 0x25, + 0x10, 0xdb, 0xc1, 0x50, 0x77, 0xbe, 0x46, 0x3f, 0xff, 0x4f, 0xed, 0x4a, 0xac, 0x0b, 0xb5, 0x55, + 0xbe, 0x3a, 0x6c, 0x1b, 0x0c, 0x6b, 0x47, 0xb1, 0xbc, 0x37, 0x73, 0xbf, 0x7e, 0x8c, 0x6f, 0x62, + 0x90, 0x12, 0x28, 0xf8, 0xc2, 0x8c, 0xbb, 0x18, 0xa5, 0x5a, 0xe3, 0x13, 0x41, 0x00, 0x0a, 0x65, + 0x01, 0x96, 0xf9, 0x31, 0xc7, 0x7a, 0x57, 0xf2, 0xdd, 0xf4, 0x63, 0xe5, 0xe9, 0xec, 0x14, 0x4b, + 0x77, 0x7d, 0xe6, 0x2a, 0xaa, 0xb8, 0xa8, 0x62, 0x8a, 0xc3, 0x76, 0xd2, 0x82, 0xd6, 0xed, 0x38, + 0x64, 0xe6, 0x79, 0x82, 0x42, 0x8e, 0xbc, 0x83, 0x1d, 0x14, 0x34, 0x8f, 0x6f, 0x2f, 0x91, 0x93, + 0xb5, 0x04, 0x5a, 0xf2, 0x76, 0x71, 0x64, 0xe1, 0xdf, 0xc9, 0x67, 0xc1, 0xfb, 0x3f, 0x2e, 0x55, + 0xa4, 0xbd, 0x1b, 0xff, 0xe8, 0x3b, 0x9c, 0x80, 0xd0, 0x52, 0xb9, 0x85, 0xd1, 0x82, 0xea, 0x0a, + 0xdb, 0x2a, 0x3b, 0x73, 0x13, 0xd3, 0xfe, 0x14, 0xc8, 0x48, 0x4b, 0x1e, 0x05, 0x25, 0x88, 0xb9, + 0xb7, 0xd2, 0xbb, 0xd2, 0xdf, 0x01, 0x61, 0x99, 0xec, 0xd0, 0x6e, 0x15, 0x57, 0xcd, 0x09, 0x15, + 0xb3, 0x35, 0x3b, 0xbb, 0x64, 0xe0, 0xec, 0x37, 0x7f, 0xd0, 0x28, 0x37, 0x0d, 0xf9, 0x2b, 0x52, + 0xc7, 0x89, 0x14, 0x28, 0xcd, 0xc6, 0x7e, 0xb6, 0x18, 0x4b, 0x52, 0x3d, 0x1d, 0xb2, 0x46, 0xc3, + 0x2f, 0x63, 0x07, 0x84, 0x90, 0xf0, 0x0e, 0xf8, 0xd6, 0x47, 0xd1, 0x48, 0xd4, 0x79, 0x54, 0x51, + 0x5e, 0x23, 0x27, 0xcf, 0xef, 0x98, 0xc5, 0x82, 0x66, 0x4b, 0x4c, 0x0f, 0x6c, 0xc4, 0x16, 0x59, +}; + +static const unsigned char scr_dh_dh_2048_256_q[32] = { + 0x8c, 0xf8, 0x36, 0x42, 0xa7, 0x09, 0xa0, 0x97, 0xb4, 0x47, 0x99, 0x76, 0x40, 0x12, 0x9d, 0xa2, + 0x99, 0xb1, 0xa4, 0x7d, 0x1e, 0xb3, 0x75, 0x0b, 0xa3, 0x08, 0xb0, 0xfe, 0x64, 0xf5, 0xfb, 0xd3, +}; + +#endif diff --git a/packages/runtime/src/scr_dyn.h b/packages/runtime/src/scr_dyn.h index 8974fc7ce..2593e38da 100644 --- a/packages/runtime/src/scr_dyn.h +++ b/packages/runtime/src/scr_dyn.h @@ -1,6 +1,7 @@ /* scriptc runtime — dynamic values: the checked-dynamic tree, native handles, * dyn promises, the ambient receiver and listener adapters (scr_json.c, - * scr_dyn_handle.c, scr_async_dyn.c). Included by scr_runtime.h, which says + * scr_dyn_handle.c, scr_async_dyn.c), and the message readers of typed + * 'message' listeners (scr_message.c). Included by scr_runtime.h, which says * where new declarations go. */ #ifndef SCR_DYN_H #define SCR_DYN_H @@ -143,6 +144,7 @@ typedef enum { X(ABORT_CONTROLLER, 15) /* native static-fetch AbortController */ \ X(ABORT_SIGNAL, 8) /* native static-fetch AbortSignal */ \ X(ARRAY_BUFFER, 18) /* fixed-length ArrayBuffer storage */ \ + X(ASYMMETRIC_CRYPTO_KEY, 69) /* WebCrypto ECDSA and RSA CryptoKey (scr_webcrypto_pki.c) */ \ X(BLOB, 41) /* ScrBlob — new Blob() and Blob#slice() */ \ X(BROADCAST_CHANNEL, 51) /* worker_threads BroadcastChannel (scr_worker_events.c) */ \ X(BUILTIN_MODULE, 21) /* native builtin export object */ \ @@ -155,6 +157,8 @@ typedef enum { X(DATE, 30) /* JavaScript Date with stable native identity */ \ X(DECIPHER, 46) /* node:crypto Decipheriv (scr_cipher.c) */ \ X(DGRAM_SOCKET, 62) /* dgram.Socket (scr_dgram.c) */ \ + X(DIFFIE_HELLMAN, 70) /* node:crypto DiffieHellman (scr_dh.c) */ \ + X(DIFFIE_HELLMAN_GROUP, 71) /* node:crypto DiffieHellmanGroup (scr_dh.c) */ \ X(DIR, 44) /* fs.Dir (scr_lib.c) */ \ X(DISPOSABLE_STACK, 49) /* DisposableStack (scr_symbol.c) */ \ X(ECDH, 64) /* node:crypto ECDH (scr_ecdh.c) */ \ @@ -165,6 +169,7 @@ typedef enum { X(FETCH_RESPONSE, 12) /* native static-fetch Response */ \ X(FILE, 42) /* ScrBlob with a name — new File() */ \ X(FILE_HANDLE, 17) /* fs/promises.FileHandle */ \ + X(FINALIZATION_REGISTRY, 72) /* FinalizationRegistry (bookkeeping only) */ \ X(GLOBAL, 22) /* native global object identity */ \ X(H2_SESSION, 4) /* ScrH2Session — Http2Session (client & server) */ \ X(H2_STREAM, 5) /* ScrH2Stream — Http2Stream (client & server) */ \ @@ -185,14 +190,18 @@ typedef enum { X(NET_SERVER, 3) /* ScrNetServer — net.Server (http.Server rides the same handle) */ \ X(NET_SOCKET, 2) /* ScrNetSocket — net.Socket */ \ X(NET_SOCKET_ADDRESS, 47) /* net.SocketAddress (scr_net.c) */ \ + X(PRIVATE_KEY, 65) /* node:crypto PrivateKeyObject (scr_pki.c) */ \ + X(PUBLIC_KEY, 66) /* node:crypto PublicKeyObject (scr_pki.c) */ \ X(REGEXP, 26) /* native RegExp, shared compiled pattern */ \ X(SEARCH_PARAMS, 33) /* live WHATWG URLSearchParams */ \ X(SEGMENTER, 19) /* default Unicode grapheme segmentation */ \ X(SEGMENTS, 20) /* iterable immutable segmentation result */ \ X(SET, 25) /* native Set, shared backing map */ \ X(SHARED_ARRAY_BUFFER, 37) \ + X(SIGN, 67) /* node:crypto Sign (scr_pki.c) */ \ X(STDIO, 27) /* stable process stdin/stdout/stderr values */ \ X(URL, 28) /* native WHATWG URL */ \ + X(VERIFY, 68) /* node:crypto Verify (scr_pki.c) */ \ X(WASM_GLOBAL, 61) /* WebAssembly.Global */ \ X(WASM_INSTANCE, 58) /* WebAssembly.Instance */ \ X(WASM_MEMORY, 59) /* WebAssembly.Memory */ \ @@ -247,6 +256,55 @@ typedef struct ScrDynTypedCast { * result as an owned (+1) dyn value. `args` entries are BORROWED. */ typedef ScrDyn *(*ScrDynThunk)(ScrClosure *clo, ScrDyn *const *args, size_t argc); +/* A compiled 'message' listener's typed entry: builds the closure's + * parameter from the message's nodes (the readers below) and calls + * the closure. Answers false, without calling it, when the message does + * not have the parameter's layout; the caller then decodes the message + * and calls the thunk. */ +struct ScrMessage; +typedef bool (*ScrDynMessageListener)(ScrClosure *clo, const struct ScrMessage *message); + +/* The kinds of a message's nodes (scr_message.c). */ +typedef enum { + SCR_MESSAGE_UNDEFINED, + SCR_MESSAGE_NULL, + SCR_MESSAGE_BOOL, + SCR_MESSAGE_NUMBER, + SCR_MESSAGE_STRING, + SCR_MESSAGE_BIGINT, + SCR_MESSAGE_ARRAY, + SCR_MESSAGE_OBJECT, + SCR_MESSAGE_STORAGE, + SCR_MESSAGE_BYTES, + SCR_MESSAGE_ARRAY_BUFFER, + SCR_MESSAGE_ERROR, + /* A deeply frozen plain-data graph shared by pointer (see publication). */ + SCR_MESSAGE_PUBLISHED, + /* A typed value published with @scriptc/threads (immortal), delivered as + * a fresh typed-ref capsule over the same pointer. */ + SCR_MESSAGE_TYPED_REF, + /* A transferred MessagePort: its channel end (+1) and side. */ + SCR_MESSAGE_PORT, + /* A native handle cloned through its unit's ScrDynHandleTransfer. */ + SCR_MESSAGE_HANDLE, +} ScrMessageKind; + +/* Readers for compiled 'message' listeners (ScrDynMessageListener), which + * build their typed parameter from the nodes. Node 0 is the root, and a + * node's values have higher numbers. scr_message_readable answers whether + * the message can reach these listeners: no node is reached twice, and it + * holds no ports or native handles, which the receiver adopts when it + * decodes the message. kind answers a ScrMessageKind; number reads a + * NUMBER or BOOL node, string a STRING node (+1). fields answers whether an + * OBJECT node has exactly the given keys, in order, and writes their value + * nodes. */ +bool scr_message_readable(const struct ScrMessage *message); +int32_t scr_message_kind(const struct ScrMessage *message, size_t node); +double scr_message_number(const struct ScrMessage *message, size_t node); +ScrStr *scr_message_string(const struct ScrMessage *message, size_t node); +bool scr_message_fields(const struct ScrMessage *message, size_t node, const char *const *names, + const size_t *lengths, size_t count, size_t *values); + /* Object member. Keys own shared immutable UTF-8 bytes (NUL-terminated for * convenience; key_len excludes the NUL) — duplicate keys were already * collapsed at parse time (later wins, like JS JSON.parse). */ @@ -307,6 +365,9 @@ typedef struct ScrDynTypedRecordOps { * for-in over a record with every field present (atomic slot). */ ScrArr *keys; } ScrDynTypedRecordOps; +/* A record capsule's ops while it answers from the native record (no view + * created yet), or NULL. */ +const ScrDynTypedRecordOps *scr_dyn_typed_ref_live_record(const ScrDyn *d); /* Prototype members of a compiled class seen as `unknown`, emitted per * class by the compiler: the string names of methods, getters and setters @@ -365,11 +426,13 @@ struct ScrDyn { void *source_identity; ScrDyn *(*source_access)(void *, bool materialize); struct ScrDynObjectIndex *index; /* optional wide-object lookup; owns no values */ - /* On a runtime-built class prototype (e.g. url.Url.prototype): the - * constructor name (static text) util.inspect prints for objects - * inheriting from it (scr_dyn_class_name). NULL otherwise. Only - * prototypes that live until their thread exits set it, and they - * clear it before release, so freelist reuse never sees it. */ + /* On a runtime-built class prototype (e.g. url.Url.prototype) and + * on a compiled class's prototype object: the constructor name + * (static or immortal text) util.inspect prints for objects + * inheriting from it (scr_dyn_class_name). NULL otherwise. Names + * that are copies live on prototypes that live until their thread + * exits, and those clear it before release; reuse of a freed object + * resets it (scr_dyn_alloc). */ const char *class_name; struct ScrDynRegion *region; /* see ScrDynRegion */ /* The dynamic tier's hidden class (scr_js_object.c): the transition @@ -384,7 +447,7 @@ struct ScrDyn { * and `name` are static compiler-emitted literals (never freed); name * may be NULL (anonymous — inspect prints [Function (anonymous)]). * The dyn→closure ownership edge is traced by the cycle collector. */ - struct { ScrClosure *clo; ScrDynThunk thunk; const char *sig; const char *name; uint32_t arity; ScrClassObj *class_obj; } fn; + struct { ScrClosure *clo; ScrDynThunk thunk; const char *sig; const char *name; uint32_t arity; ScrClassObj *class_obj; ScrDynMessageListener message; } fn; /* Native handles normally keep conservative ownership edges. Sets * backed by cycle-capable maps expose their edge to the collector. * Cache that allocation property: during collection the map may be @@ -657,6 +720,9 @@ ScrDyn *scr_dyn_native_set_new(const ScrDyn *seed); ScrDyn *scr_dyn_native_set(ScrMap *value); /* borrowed backing, +1 box */ bool scr_dyn_native_set_is(const ScrDyn *value); ScrDyn *scr_dyn_native_map(ScrMap *value); /* borrowed backing, +1 box */ +/* `new Map(entries)` over a checked-dynamic seed: +1, or NULL with the + * exception pending. */ +ScrDyn *scr_dyn_native_map_new(const ScrDyn *seed); bool scr_dyn_native_map_is(const ScrDyn *value); void scr_regex_reset_last_index(ScrRegex *re, double index); ScrRegex *scr_regex_new_checked(const ScrDyn *pattern, const ScrDyn *flags); @@ -665,6 +731,40 @@ bool scr_dyn_native_url_is(const ScrDyn *value); ScrDyn *scr_dyn_native_search_params(ScrSearchParams *value); bool scr_dyn_native_search_params_is(const ScrDyn *value); bool scr_dyn_native_date_is(const ScrDyn *value); +/* Instances of program classes declared `extends Date` (scr_lib.c). */ +void scr_date_class_operation_install(ScrDyn *time, ScrDyn *methods); +/* Set by scr_date_class_operation_install; NULL in a program without such + * a class, where every wrapper below answers false or NULL. */ +typedef struct { + bool (*time)(const ScrDyn *value, double *time); + ScrDyn *(*to_json)(const ScrDyn *value, const ScrDyn *key); + ScrDyn *(*to_string)(const ScrDyn *value); + ScrDyn *(*value_of)(const ScrDyn *value); + ScrStr *(*name)(const ScrDyn *value); + ScrDyn *(*method)(const ScrDyn *value, const char *key, size_t key_len); +} ScrDateClassHooks; +extern const ScrDateClassHooks *scr_date_class_hooks; +static inline bool scr_dyn_date_class_time(const ScrDyn *value, double *time) { + return scr_date_class_hooks && scr_date_class_hooks->time(value, time); +} +static inline ScrDyn *scr_dyn_date_class_to_json(const ScrDyn *value, const ScrDyn *key) { + return scr_date_class_hooks->to_json(value, key); +} +static inline ScrDyn *scr_dyn_date_class_to_string(const ScrDyn *value) { + return scr_date_class_hooks->to_string(value); +} +static inline ScrDyn *scr_dyn_date_class_value_of(const ScrDyn *value) { + return scr_date_class_hooks->value_of(value); +} +static inline ScrStr *scr_dyn_date_class_name(const ScrDyn *value) { + return scr_date_class_hooks ? scr_date_class_hooks->name(value) : NULL; +} +static inline ScrDyn *scr_dyn_date_class_method(const ScrDyn *value, const char *key, size_t key_len) { + return scr_date_class_hooks ? scr_date_class_hooks->method(value, key, key_len) : NULL; +} +bool scr_dyn_date_instance_is(const ScrDyn *value); +ScrDyn *scr_dyn_date_class_member(const ScrDyn *d, const char *key, size_t key_len); +double scr_dyn_date_arguments_time(const ScrDyn *arguments); ScrDyn *scr_dyn_native_date_new(const ScrDyn *arguments); ScrDyn *scr_dyn_native_date_new_fields(const ScrDyn *arguments); ScrDyn *scr_dyn_native_date_new_value(const ScrDyn *arguments); @@ -728,6 +828,9 @@ ScrDyn *scr_dyn_array_constructor(void); /* The interned builtin constructor `name` (Object, Date, RegExp, Map, Set, * Promise, WeakMap, WeakSet) as a dynamic function value: +1. */ ScrDyn *scr_dyn_global_constructor(const ScrStr *name); +/* The interned function value of an error constructor ("TypeError"), or + * NULL for other names. */ +ScrDyn *scr_dyn_error_constructor(const char *name); /* A builtin global function (setTimeout, setImmediate, process.nextTick, ...) * as an interned dynamic function value: +1. */ ScrDyn *scr_dyn_builtin_function(const ScrStr *name); @@ -745,6 +848,7 @@ ScrDyn *scr_dyn_iterator(const ScrDyn *value, const ScrStr *spell); /* for await over a checked-dynamic value (scr_dyn_for_await.c). */ ScrDyn *scr_dyn_async_iterator_open(ScrDyn *value, ScrStr *spell); bool scr_dyn_async_iterator_was_sync(void); +void scr_dyn_async_iterator_set_sync(bool sync); ScrDyn *scr_dyn_iterator_optional(const ScrDyn *value); /* from.js's probe: 2 when value[Symbol.asyncIterator] is set, 1 when * value[Symbol.iterator] is, 0 for neither, -1 with an error pending. */ @@ -837,9 +941,16 @@ void scr_dyn_proxy_unsupported(const char *operation); ScrDyn *scr_dyn_new_bytes(const ScrBytes *b); ScrDyn *scr_bytes_constructor(const ScrStr *name); bool scr_bytes_instanceof(const ScrDyn *value, const ScrDyn *callee); +bool scr_bytes_instanceof_at(const ScrDyn *value, const ScrDyn *callee, const ScrStr *refusal); bool scr_dyn_data_view_is(const ScrDyn *value); ScrDyn *scr_dyn_construct(const ScrDyn *callee, const ScrDyn *args, const ScrStr *what); ScrDyn *scr_bytes_construct(const ScrDyn *callee, const ScrDyn *args, const ScrStr *what); +/* Installed by scr_dyn_invoke.c when it interns a builtin constructor value + * (scr_dyn_global_constructor): false when `callee` is not one of them; + * otherwise true with `new callee(...args)` in *result (+1, or NULL with + * the exception pending). */ +extern SCR_TL bool (*scr_dyn_global_construct_fn)(const ScrDyn *callee, const ScrDyn *args, + ScrDyn **result); ScrDyn *scr_dyn_bytes_key_get(const ScrDyn *value, const ScrStr *key); /* The Buffer-flavored twin (stream chunks): string coercion/toString * decode utf8 instead of joining elements. */ @@ -972,6 +1083,8 @@ ScrDyn *scr_dyn_map_seed_entry(const ScrDyn *entry); bool scr_weak_map_is(const ScrDyn *value); bool scr_weak_set_is(const ScrDyn *value); ScrDyn *scr_weak_map_new(ScrDyn *entries); +ScrDyn *scr_finalization_registry_new(ScrDyn *cleanup); +bool scr_finalization_registry_is(const ScrDyn *value); ScrDyn *scr_weak_set_new(ScrDyn *values); ScrDyn *scr_dyn_from_entries(ScrDyn *entries); ScrDyn *scr_dyn_mark_snapshot(ScrDyn *value); /* consumes and returns +1 */ @@ -1051,6 +1164,10 @@ ScrStr *scr_dyn_to_string(const ScrDyn *d, const ScrStr *enc); * prototype chain has no toString (Node's answer). */ ScrStr *scr_dyn_to_string_method(const ScrDyn *d, const ScrStr *enc, const ScrStr *what); ScrDyn *scr_dyn_object_prototype(void); +ScrDyn *scr_dyn_error_prototype(void); +bool scr_dyn_inherits_error_prototype(const ScrDyn *value); +ScrDyn *scr_dyn_error_capture_stack_trace(ScrDyn *target); +ScrDyn *scr_dyn_error_capture_stack_trace_function(void); ScrDyn *scr_dyn_function_apply(void); ScrDyn *scr_dyn_reflect_apply(ScrDyn *target, ScrDyn *receiver, ScrDyn *arguments_list); ScrDyn *scr_dyn_apply_array_like(const ScrDyn *target, const ScrDyn *receiver, const ScrDyn *arguments, const char *what); @@ -1201,6 +1318,9 @@ ScrDyn *scr_dyn_define_prototype_props(ScrDyn *target, ScrDyn *descs, ScrDyn *pr * (callers retain first when they keep their own reference); `sig`/`name` * must be static literals (the box never frees them; name may be NULL). */ ScrDyn *scr_dyn_new_func(ScrClosure *clo, ScrDynThunk thunk, uint32_t arity, const char *sig, const char *name); +/* Gives a function box made with thunk its typed message entry (an + * EventEmitter listener registered from it keeps the entry). */ +void scr_dyn_func_set_message(ScrDyn *fn, ScrDynThunk thunk, ScrDynMessageListener listener); ScrDyn *scr_dyn_new_class(ScrClassObj *cls, const char *type_key); /* EventEmitter and the stream constructors as untyped constructor values, * and instanceof over untyped constructor functions @@ -1391,8 +1511,37 @@ typedef struct ScrDynHandleOps { /* Cross-thread structured clone (postMessage, workerData); NULL = * DataCloneError. See ScrDynHandleTransfer. */ const struct ScrDynHandleTransfer *transfer; + /* A handle that is also a Node Transform (Cipheriv, Decipheriv): the + * stream unit builds the handle's Transform from these operations on its + * first stream use. NULL = the class is not a stream. */ + const struct ScrDynHandleTransform *transform; } ScrDynHandleOps; +/* The operations a Transform handle gives the stream unit (scr_stream.c): + * the slot where the handle keeps its stream (+1) with the stream's + * release, update() and final() over bytes (+1 Buffer, or NULL with the + * exception pending), and the handle's collector trace, since the + * stream's steps hold the handle. */ +typedef struct ScrDynHandleTransform { + void *(*stream)(void *h); + void (*set_stream)(void *h, void *stream, void (*release)(void *)); + struct ScrBytes *(*update)(void *h, struct ScrBytes *chunk); + struct ScrBytes *(*final)(void *h); + ScrTraceFn trace; +} ScrDynHandleTransform; + +/* Checked-dynamic member calls and property reads on a Transform handle, + * installed by the stream unit (scr_stream_install); NULL in a program + * without it. call answers true with *result set (+1, or NULL with the + * exception pending) for the members a native stream answers, and get + * answers a stream property (+1), or NULL for other keys. */ +typedef struct ScrHandleStreamHooks { + bool (*call)(const ScrDynHandleOps *ops, void *h, ScrDyn *self, const char *method, + ScrDyn *const *args, size_t argc, ScrDyn **result); + ScrDyn *(*get)(const ScrDynHandleOps *ops, void *h, const char *key, size_t key_len); +} ScrHandleStreamHooks; +extern SCR_TL const ScrHandleStreamHooks *scr_handle_stream_hooks; + /* How a handle crosses threads, supplied by the handle's owning unit so the * message encoder (scr_message.c) needs no reference to gated units and no * per-tag registry. share runs on the sending thread: it answers a payload diff --git a/packages/runtime/src/scr_dyn_builtin_stream.c b/packages/runtime/src/scr_dyn_builtin_stream.c index 209c8c39a..926f85eea 100644 --- a/packages/runtime/src/scr_dyn_builtin_stream.c +++ b/packages/runtime/src/scr_dyn_builtin_stream.c @@ -34,8 +34,7 @@ * receiver without a reference; the hook closures outlive the record. * * Not supported here (each throws the "not supported yet" Error where it - * runs): objectMode and the other options scr_stream.c's dyn option walk - * refuses, `_writev` and `_construct`, symbol event names, listeners() / + * runs): the options scr_stream.c's dyn option walk refuses, `_writev` and `_construct`, symbol event names, listeners() / * rawListeners(), `wrap()`, and pipes into values that are neither runtime * streams nor constructor-function streams. */ #include "scr_runtime.h" @@ -109,10 +108,6 @@ static ScrDyn *bcs_undefined(void) { return scr_dyn_retain(scr_dyn_undefined()); } -static ScrDyn *bcs_str(const char *text) { - return bcs_key(text); -} - static void bcs_unsupported(const char *message) { scr_throw_error_msg_code(SCR_ERR_ERROR, message, strlen(message), "SC2020"); } @@ -232,7 +227,7 @@ static ScrStream *bcs_need(ScrDyn *self, const char *reading) { /* ── completion callbacks ───────────────────────────────────────────── */ -enum { BCS_DONE_WRITE, BCS_DONE_FINAL, BCS_DONE_DESTROY, BCS_DONE_TRANSFORM, BCS_DONE_FLUSH }; +enum { BCS_DONE_WRITE, BCS_DONE_FINAL, BCS_DONE_DESTROY, BCS_DONE_TRANSFORM, BCS_DONE_FLUSH, BCS_DONE_CONSTRUCT }; static void bcs_run_destroy_cbs(ScrStream *s, ScrError *err) { BcsRec *rec = bcs_rec(s); @@ -267,6 +262,9 @@ static ScrDyn *bcs_done_call(ScrClosure *closure, ScrDyn *const *args, size_t ar case BCS_DONE_FINAL: scr_stream_final_done(s, err); break; + case BCS_DONE_CONSTRUCT: + scr_stream_construct_done(s, err); + break; case BCS_DONE_DESTROY: { ScrError *kept = err ? scr_error_retain(err) : NULL; scr_stream_destroy_done(s, err); @@ -275,11 +273,10 @@ static ScrDyn *bcs_done_call(ScrClosure *closure, ScrDyn *const *args, size_t ar break; } default: { + /* the data is pushed as push(data) pushes it */ ScrDyn *data = bcs_arg(args, argc, 1); - ScrBytes *bytes = data->kind == SCR_DYN_BYTES ? scr_bytes_raw_view(data->v.bytes) : NULL; - ScrStr *text = data->kind == SCR_DYN_STR ? scr_str_retain(data->v.str) : NULL; - if (which == BCS_DONE_TRANSFORM) scr_stream_transform_done(s, err, bytes, text); - else scr_stream_flush_done(s, err, bytes, text); + if (which == BCS_DONE_TRANSFORM) scr_stream_transform_done_value(s, err, data); + else scr_stream_flush_done_value(s, err, data); break; } } @@ -362,13 +359,14 @@ static void bcs_read_inv(ScrClosure *cb, ScrStream *s, double size) { scr_dyn_release(object); } -/* _write(chunk, 'buffer', cb) and _transform(chunk, 'buffer', cb): a - * throw propagates to the write() caller, as in Node. */ +/* _write(chunk, 'buffer', cb) and _transform(chunk, 'buffer', cb), or the + * value and the write's encoding argument on an object-mode writable + * side: a throw propagates to the write() caller, as in Node. */ static void bcs_chunk_call(ScrClosure *cb, ScrStream *s, ScrBytes *chunk, const char *method, int done) { ScrDyn *object = scr_box_get_ref(cb->caps[0]); ScrDyn *args[3]; - args[0] = scr_dyn_new_buffer(chunk); - args[1] = bcs_str("buffer"); + args[0] = scr_stream_chunk_value(s, chunk); + args[1] = scr_stream_chunk_encoding_value(s); args[2] = bcs_done(s, done); ScrDyn *result = bcs_invoke(object, method, args, 3); for (int i = 0; i < 3; i++) scr_dyn_release(args[i]); @@ -402,6 +400,30 @@ static void bcs_plain_call(ScrClosure *cb, ScrStream *s, const char *method, int static bool bcs_is_function(ScrDyn *object, const char *name, bool *failed); +/* constructNT: `try { stream._construct(cb) } catch (err) { onConstruct(err) }`. */ +static void bcs_construct_inv(ScrClosure *cb, ScrStream *s) { + ScrDyn *object = scr_box_get_ref(cb->caps[0]); + ScrDyn *callback = bcs_done(s, BCS_DONE_CONSTRUCT); + ScrDyn *result = bcs_invoke(object, "_construct", &callback, 1); + scr_dyn_release(callback); + if (result) scr_dyn_release(result); + else if (scr_exc_pending()) scr_stream_construct_done(s, bcs_take_error()); + scr_dyn_release(object); +} + +/* clearBuffer's batch: this._writev(chunks, cb); a throw reaches the + * write() caller, as in Node. */ +static void bcs_writev_inv(ScrClosure *cb, ScrStream *s, ScrDyn *chunks) { + ScrDyn *object = scr_box_get_ref(cb->caps[0]); + ScrDyn *args[2]; + args[0] = scr_dyn_retain(chunks); + args[1] = bcs_done(s, BCS_DONE_WRITE); + ScrDyn *result = bcs_invoke(object, "_writev", args, 2); + for (int i = 0; i < 2; i++) scr_dyn_release(args[i]); + if (result) scr_dyn_release(result); + scr_dyn_release(object); +} + /* prefinish reads `stream._final` when the writable side finishes, so a * method assigned after the constructor runs; without one the finish goes * on as Node's does when `typeof stream._final !== 'function'`. */ @@ -488,8 +510,8 @@ static void bcs_listener0(ScrClosure *adapter) { bcs_listener_call(adapter, NULL, 0); } -static void bcs_listener_data(ScrClosure *adapter, ScrBytes *bytes, ScrStr *text) { - ScrDyn *arg = text ? scr_dyn_new_str(text) : scr_dyn_new_buffer(bytes); +static void bcs_listener_data(ScrClosure *adapter, ScrBytes *bytes, ScrStr *text, ScrDyn *value) { + ScrDyn *arg = value ? scr_dyn_retain(value) : text ? scr_dyn_new_str(text) : scr_dyn_new_buffer(bytes); bcs_listener_call(adapter, &arg, 1); scr_dyn_release(arg); } @@ -583,7 +605,7 @@ static bool bcs_add_listener(ScrStream *s, ScrDyn *self, ScrDyn *type, ScrDyn *l break; case 1: chained = scr_emitter_on_dyn(em, name, listener, bcs_adapter(listener, self, (void *)bcs_listener_data), - scr_ee_inv_fixed2, once, prepend); + scr_ee_inv_fixed3, once, prepend); break; case 2: chained = scr_emitter_on_dyn(em, name, listener, bcs_adapter(listener, self, (void *)bcs_listener_error), @@ -625,14 +647,15 @@ static ScrDyn *bcs_emit(ScrStream *s, ScrDyn *const *args, size_t argc) { had = scr_emitter_emit(em, name); break; case 1: + /* 'data' carries the bytes, string and value slots (scr_stream_emit_data) */ if (first->kind == SCR_DYN_BYTES) { ScrBytes *bytes = scr_bytes_raw_view(first->v.bytes); - had = scr_emitter_emit(em, name, bytes, (ScrStr *)NULL); + had = scr_emitter_emit(em, name, bytes, (ScrStr *)NULL, first); scr_bytes_release(bytes); } else if (first->kind == SCR_DYN_STR) { - had = scr_emitter_emit(em, name, (ScrBytes *)NULL, first->v.str); + had = scr_emitter_emit(em, name, (ScrBytes *)NULL, first->v.str, first); } else { - bcs_unsupported("emit('data') with a chunk other than a Buffer or string on a constructor-function stream is not supported yet"); + had = scr_emitter_emit(em, name, (ScrBytes *)NULL, (ScrStr *)NULL, first); } break; case 2: @@ -875,16 +898,22 @@ static ScrDyn *bcs_construct(int kind, ScrDyn *self, ScrDyn *const *args, size_t } bool failed = false; bool writes = kind != BCS_READABLE; - if (writes && bcs_is_function(self, "_writev", &failed)) { - bcs_unsupported("_writev on a constructor-function stream is not supported yet"); - return NULL; - } - if (!failed && bcs_is_function(self, "_construct", &failed)) { - bcs_unsupported("_construct on a constructor-function stream is not supported yet"); - return NULL; - } - if (failed) return NULL; + bool transformish = kind == BCS_TRANSFORM || kind == BCS_PASSTHROUGH; ScrDyn *opts = bcs_arg(args, argc, 0); + /* Node's constructors assign options.writev and options.construct to + * the instance (this._writev = options.writev), then read _writev and + * _construct, so an option shadows the prototype's method. */ + if (opts->kind == SCR_DYN_OBJ) { + if (writes && !transformish && !bcs_copy_option(self, opts, "writev", "_writev")) return NULL; + if (!bcs_copy_option(self, opts, "construct", "_construct")) return NULL; + } + bool has_writev = writes && bcs_is_function(self, "_writev", &failed); + if (has_writev && transformish) { + bcs_unsupported("_writev on a constructor-function Transform is not supported yet"); + return NULL; + } + bool has_construct = !failed && bcs_is_function(self, "_construct", &failed); + if (failed) return NULL; ScrStream *s = kind == BCS_READABLE ? scr_stream_new_readable_dyn(opts) : kind == BCS_WRITABLE ? scr_stream_new_writable_dyn(opts) : kind == BCS_DUPLEX ? scr_stream_new_duplex_dyn(opts) @@ -936,6 +965,9 @@ static ScrDyn *bcs_construct(int kind, ScrDyn *self, ScrDyn *const *args, size_t } } scr_stream_set_destroy(s, bcs_hook(self, (void *)bcs_destroy_inv), bcs_destroy_inv); + if (has_writev) scr_stream_set_writev(s, bcs_hook(self, (void *)bcs_writev_inv), bcs_writev_inv); + if (has_construct) + scr_stream_set_construct(s, bcs_hook(self, (void *)bcs_construct_inv), bcs_construct_inv); bcs_hide(self, s); if (!failed) failed = !bcs_adopt_listeners(s, self); if (!failed && kind != BCS_WRITABLE) failed = !bcs_state_view(self, s, true); @@ -1020,27 +1052,17 @@ static ScrClosure *bcs_callback(ScrDyn *fn, ScrDyn *self, ScrStream *s) { return closure; } -/* Strings in another encoding than utf8 have no write path here. */ -static bool bcs_utf8_only(const ScrDyn *encoding) { - if (encoding->kind != SCR_DYN_STR) return true; - ScrStr *canonical = bcs_encoding(encoding); - if (!canonical) return false; - bool utf8 = bcs_is(canonical, "utf8"); - scr_str_release(canonical); - if (!utf8) bcs_unsupported("writing strings in an encoding other than utf8 to a constructor-function stream is not supported yet"); - return utf8; -} - static ScrDyn *bcs_write(ScrStream *s, ScrDyn *self, ScrDyn *const *args, size_t argc) { ScrDyn *chunk = bcs_arg(args, argc, 0); ScrDyn *encoding = bcs_arg(args, argc, 1); ScrDyn *cb = bcs_arg(args, argc, 2); if (scr_dyn_is_callable(encoding)) { cb = encoding; - encoding = scr_dyn_undefined(); + encoding = scr_stream_writes_values(s) ? scr_dyn_new_null() : scr_dyn_undefined(); } - if (chunk->kind == SCR_DYN_STR && !bcs_utf8_only(encoding)) return NULL; - bool below = scr_stream_write_dyn(s, chunk, bcs_callback(cb, self, s)); + /* an object-mode side hands the encoding argument to _write; a byte-mode + * side encodes a string with it (or the default encoding) */ + bool below = scr_stream_write_enc(s, chunk, encoding, bcs_callback(cb, self, s)); if (scr_exc_pending()) return NULL; return scr_dyn_new_bool(below); } @@ -1055,21 +1077,20 @@ static ScrDyn *bcs_end(ScrStream *s, ScrDyn *self, ScrDyn *const *args, size_t a encoding = scr_dyn_undefined(); } else if (scr_dyn_is_callable(encoding)) { cb = encoding; - encoding = scr_dyn_undefined(); + encoding = scr_dyn_new_null(); } - if (chunk->kind == SCR_DYN_STR && !bcs_utf8_only(encoding)) return NULL; ScrStream *chained = NULL; - if (bcs_nullish(chunk)) { - chained = scr_stream_end(s, NULL, NULL, bcs_callback(cb, self, s)); - } else if (chunk->kind == SCR_DYN_STR) { - chained = scr_stream_end(s, NULL, chunk->v.str, bcs_callback(cb, self, s)); - } else if (chunk->kind == SCR_DYN_BYTES) { - ScrBytes *bytes = scr_bytes_raw_view(chunk->v.bytes); - chained = scr_stream_end(s, bytes, NULL, bcs_callback(cb, self, s)); - scr_bytes_release(bytes); - } else { - scr_dyn_arg_type_fail("chunk", "of type string or an instance of Buffer, TypedArray, or DataView", chunk); + if (!bcs_nullish(chunk)) { + /* end(chunk) writes the chunk with the encoding argument first */ + if (scr_stream_prop(s, "writableObjectMode") == 0 && chunk->kind != SCR_DYN_STR && + chunk->kind != SCR_DYN_BYTES) { + scr_dyn_arg_type_fail("chunk", "of type string or an instance of Buffer, TypedArray, or DataView", chunk); + return NULL; + } + scr_stream_write_enc(s, chunk, encoding, NULL); + if (scr_exc_pending()) return NULL; } + chained = scr_stream_end(s, NULL, NULL, bcs_callback(cb, self, s)); if (chained) scr_stream_release(chained); if (scr_exc_pending()) return NULL; return scr_dyn_retain(self); @@ -1152,8 +1173,26 @@ static ScrDyn *bcs_method_call(ScrClosure *closure, ScrDyn *const *args, size_t switch (method) { case BCS_M_READ_DEFAULT: return bcs_not_implemented("_read()"); - case BCS_M_WRITE_DEFAULT: + case BCS_M_WRITE_DEFAULT: { + /* Writable.prototype._write: this._writev([{ chunk, encoding }], cb) */ + ScrDyn *self = scr_dyn_this_get(); + bool failed = false; + if (bcs_is_function(self, "_writev", &failed)) { + ScrDyn *chunks = scr_dyn_new_arr(); + ScrDyn *entry = scr_dyn_new_obj(); + scr_dyn_obj_set(entry, "chunk", 5, scr_dyn_retain(bcs_arg(args, argc, 0))); + scr_dyn_obj_set(entry, "encoding", 8, scr_dyn_retain(bcs_arg(args, argc, 1))); + scr_dyn_arr_push(chunks, entry); + ScrDyn *pass[2] = {chunks, bcs_arg(args, argc, 2)}; + ScrDyn *result = bcs_invoke(self, "_writev", pass, 2); + scr_dyn_release(chunks); + scr_dyn_release(self); + return result; + } + scr_dyn_release(self); + if (failed) return NULL; return bcs_not_implemented("_write()"); + } case BCS_M_TRANSFORM_DEFAULT: return bcs_not_implemented("_transform()"); case BCS_M_DESTROY_DEFAULT: @@ -1305,9 +1344,12 @@ static ScrDyn *bcs_method_call(ScrClosure *closure, ScrDyn *const *args, size_t scr_stream_uncork(s); result = bcs_undefined(); break; - case BCS_M_SET_DEFAULT_ENCODING: - if (bcs_utf8_only(first)) result = scr_dyn_retain(self); + case BCS_M_SET_DEFAULT_ENCODING: { + ScrStream *chained = scr_stream_set_default_encoding(s, first); + if (chained) scr_stream_release(chained); + if (!scr_exc_pending()) result = scr_dyn_retain(self); break; + } default: bcs_unsupported("Readable.prototype.wrap on a constructor-function stream is not supported yet"); break; @@ -1376,8 +1418,6 @@ static ScrDyn *bcs_getter_call(ScrClosure *closure, ScrDyn *const *args, size_t return bcs_flowing(s); case BCS_P_ERRORED: return bcs_errored(s); - case BCS_P_WRITABLE_OBJECT_MODE: - return scr_dyn_new_bool(false); case BCS_P_READABLE_LENGTH: case BCS_P_READABLE_HWM: case BCS_P_WRITABLE_LENGTH: diff --git a/packages/runtime/src/scr_dyn_for_await.c b/packages/runtime/src/scr_dyn_for_await.c index 25183c4ee..3a1a6458d 100644 --- a/packages/runtime/src/scr_dyn_for_await.c +++ b/packages/runtime/src/scr_dyn_for_await.c @@ -38,6 +38,11 @@ ScrDyn *scr_dyn_async_iterator_open(ScrDyn *value, ScrStr *spell) { return iterator; } +/* For an iterator another open path made (scr_dyn_for_await_stream.c). */ +void scr_dyn_async_iterator_set_sync(bool sync) { + scr_for_await_sync = sync; +} + /* Whether the iterator the last scr_dyn_async_iterator_open returned is a * synchronous one. Read immediately after the open. */ bool scr_dyn_async_iterator_was_sync(void) { diff --git a/packages/runtime/src/scr_dyn_for_await_stream.c b/packages/runtime/src/scr_dyn_for_await_stream.c new file mode 100644 index 000000000..6facf916c --- /dev/null +++ b/packages/runtime/src/scr_dyn_for_await_stream.c @@ -0,0 +1,61 @@ +/* `for await` over a checked-dynamic value in a program that links the + * stream unit: a native readable stream behind the value (a boxed stream, + * or a Cipheriv/Decipheriv handle's Transform) iterates through an + * iterator object whose next() answers the readable iterator's step as + * { value, done } and whose return() closes it as a typed loop does + * (destroy with an AbortError). Any other value takes + * scr_dyn_async_iterator_open. Linked only by programs with such a loop + * and streams. */ +#include "scr_runtime.h" +#include "scr_stream.h" + +/* caps[0]: the stream */ +static ScrStream *iter_stream(ScrClosure *clo) { + return scr_box_get_ref(clo->caps[0]); /* +1 */ +} + +static ScrDyn *iter_next_thunk(ScrClosure *clo, ScrDyn *const *args, size_t argc) { + (void)args; + (void)argc; + ScrStream *s = iter_stream(clo); + ScrPromise *p = scr_stream_next_result_dyn(s); + scr_stream_release(s); + ScrDyn *d = scr_dyn_new_promise(p); + scr_promise_release(p); + return d; +} + +static ScrDyn *iter_return_thunk(ScrClosure *clo, ScrDyn *const *args, size_t argc) { + (void)args; + (void)argc; + ScrStream *s = iter_stream(clo); + scr_stream_release(scr_stream_iterator_close(s)); + scr_stream_release(s); + ScrDyn *result = scr_dyn_new_obj(); + scr_dyn_obj_set(result, "value", 5, scr_dyn_retain(scr_dyn_undefined())); + scr_dyn_obj_set(result, "done", 4, scr_dyn_new_bool(true)); + ScrPromise *p = scr_promise_new(); + scr_promise_fulfill_ref(p, result, scr_dyn_retain_v, scr_dyn_release_v, NULL); + ScrDyn *d = scr_dyn_new_promise(p); + scr_promise_release(p); + return d; +} + +static ScrDyn *iter_method(ScrStream *s, ScrDynThunk thunk, const char *name) { + ScrClosure *clo = scr_closure_new((void *)thunk, 1); + clo->caps[0] = scr_box_new_obj(&scr_stream_retain_v, &scr_stream_release_v, &scr_stream_trace); + scr_box_set_ref(clo->caps[0], scr_stream_retain(s)); + return scr_dyn_new_func(clo, thunk, 0, "()", name); +} + +ScrDyn *scr_stream_dyn_async_iterator_open(ScrDyn *value, ScrStr *spell) { + ScrStream *s = scr_stream_native_readable_of_dyn(value); + if (!s) return scr_dyn_async_iterator_open(value, spell); + /* the loop awaits its results with the async protocol */ + scr_dyn_async_iterator_set_sync(false); + ScrDyn *it = scr_dyn_new_obj(); + scr_dyn_obj_set(it, "next", 4, iter_method(s, &iter_next_thunk, "next")); + scr_dyn_obj_set(it, "return", 6, iter_method(s, &iter_return_thunk, "return")); + scr_stream_release(s); + return it; +} diff --git a/packages/runtime/src/scr_dyn_invoke.c b/packages/runtime/src/scr_dyn_invoke.c index 2a010f213..14d11dc67 100644 --- a/packages/runtime/src/scr_dyn_invoke.c +++ b/packages/runtime/src/scr_dyn_invoke.c @@ -845,6 +845,16 @@ static ScrDyn *scr_dyn_invoke_impl( if (scr_event_ref_hooks && scr_event_ref_hooks->invoke(recv, method, args, argc, what, &fast)) return fast; + /* An inherited Date method of an instance of a class declared `extends + * Date`. */ + ScrDyn *date_method = scr_dyn_date_class_member(recv, method, strlen(method)); + if (date_method) { + scr_dyn_this_push_dyn(recv); + ScrDyn *result = scr_dyn_call(date_method, args, argc, what); + scr_dyn_this_pop(); + scr_dyn_release(date_method); + return result; + } ScrDyn *materialized = scr_dyn_typed_ref_materialize(recv); if (scr_exc_pending()) { scr_dyn_release(materialized); @@ -1844,9 +1854,12 @@ static const char dyn_s29[] SCR_DYN_COMPAT_STR = "Date"; static const char dyn_s30[] SCR_DYN_COMPAT_STR = "Map"; static const char dyn_s31[] SCR_DYN_COMPAT_STR = "Set"; static const char dyn_s32[] SCR_DYN_COMPAT_STR = ""; +static const char dyn_s33[] SCR_DYN_COMPAT_STR = "constructing %s%s through a stored value is not supported yet"; +static const char dyn_s34[] SCR_DYN_COMPAT_STR = " from a primitive"; +static const char dyn_s35[] SCR_DYN_COMPAT_STR = "FinalizationRegistry"; static const char *const dyn_global_ctor_names[] = { - dyn_s26, dyn_s29, dyn_s25, dyn_s30, dyn_s31, dyn_s21, dyn_s22, dyn_s24, + dyn_s26, dyn_s29, dyn_s25, dyn_s30, dyn_s31, dyn_s21, dyn_s22, dyn_s24, dyn_s35, }; #define DYN_GLOBAL_CTORS (sizeof dyn_global_ctor_names / sizeof dyn_global_ctor_names[0]) static SCR_TL ScrDyn *dyn_global_ctors[DYN_GLOBAL_CTORS]; @@ -1877,17 +1890,47 @@ static ScrDyn *dyn_global_ctor_call(ScrClosure *closure, ScrDyn *const *args, si return NULL; } +/* `new C(...args)` through a stored Object, Date, Map, Set, WeakMap or + * WeakSet builds what the `new` expression builds. RegExp, Promise, and + * Object over a primitive (a wrapper object) are fenced. */ +static bool dyn_global_construct(const ScrDyn *callee, const ScrDyn *args, ScrDyn **result) { + if (callee->kind != SCR_DYN_FUNC || callee->v.fn.thunk != dyn_global_ctor_call) return false; + const char *name = callee->v.fn.clo->fn; + ScrDyn *const *items = args->v.arr.items; + size_t argc = args->v.arr.len; + const ScrDyn *first = argc ? items[0] : scr_dyn_undefined(); + bool primitive = first->kind == SCR_DYN_NUM || first->kind == SCR_DYN_STR || first->kind == SCR_DYN_BOOL || + first->kind == SCR_DYN_BIGINT || first->kind == SCR_DYN_SYMBOL; + if (strcmp(name, dyn_s26) == 0 && !primitive) *result = dyn_global_ctor_call(callee->v.fn.clo, items, argc); + else if (strcmp(name, dyn_s29) == 0) + *result = argc == 0 ? scr_dyn_native_date_new(args) + : argc == 1 ? scr_dyn_native_date_new_value(args) + : scr_dyn_native_date_new_fields(args); + else if (strcmp(name, dyn_s30) == 0) *result = scr_dyn_native_map_new(first); + else if (strcmp(name, dyn_s31) == 0) *result = scr_dyn_native_set_new(first); + else if (strcmp(name, dyn_s22) == 0) *result = scr_weak_map_new((ScrDyn *)first); + else if (strcmp(name, dyn_s24) == 0) *result = scr_weak_set_new((ScrDyn *)first); + else { + char message[128]; + int length = snprintf(message, sizeof message, dyn_s33, name, strcmp(name, dyn_s26) == 0 ? dyn_s34 : dyn_s32); + scr_throw_error_msg_code(SCR_ERR_ERROR, message, (size_t)length, dyn_s27); + *result = NULL; + } + return true; +} + static ScrDyn *dyn_global_ctor(const char *name) { for (size_t i = 0; i < DYN_GLOBAL_CTORS; i++) { if (strcmp(dyn_global_ctor_names[i], name) != 0) continue; if (!dyn_global_ctors_registered) { dyn_global_ctors_registered = true; scr_atexit(dyn_global_ctors_cleanup); + scr_dyn_global_construct_fn = dyn_global_construct; } if (!dyn_global_ctors[i]) { /* Each constructor's own length: Object 1, Date 7, RegExp 2, Promise 1, - * the collections 0. */ - uint32_t length = i == 0 || i == 5 ? 1 : i == 1 ? 7 : i == 2 ? 2 : 0; + * the collections 0, FinalizationRegistry 1. */ + uint32_t length = i == 0 || i == 5 || i == 8 ? 1 : i == 1 ? 7 : i == 2 ? 2 : 0; dyn_global_ctors[i] = scr_dyn_new_func(scr_closure_new((void *)dyn_global_ctor_names[i], 0), dyn_global_ctor_call, length, dyn_s6, dyn_global_ctor_names[i]); @@ -1913,6 +1956,8 @@ static ScrDyn *dyn_function_constructor(void) { ScrDyn *scr_dyn_global_constructor(const ScrStr *name) { if (strcmp(name->data, dyn_s20) == 0) return dyn_function_constructor(); + ScrDyn *error = scr_dyn_error_constructor(name->data); + if (error) return error; ScrDyn *ctor = dyn_global_ctor(name->data); if (!ctor) scr_trap(dyn_s3); return ctor; diff --git a/packages/runtime/src/scr_ecdh.c b/packages/runtime/src/scr_ecdh.c index fc8797571..5edbadba6 100644 --- a/packages/runtime/src/scr_ecdh.c +++ b/packages/runtime/src/scr_ecdh.c @@ -21,6 +21,7 @@ #include "mbedtls/ecp.h" #include "mbedtls/platform_util.h" +#include "scr_crypto_args.h" #include "scr_ecdh_names.h" typedef struct { @@ -73,6 +74,9 @@ static int se_random(void *state, unsigned char *out, size_t len) { return 0; } +/* The value the SC2020 error for an unlowered encoding or format names. */ +#define SE_SUBJECT "An ECDH encoding or format" + /* ── errors ───────────────────────────────────────────────────────────── */ static void se_throw(int kind, const char *code, const char *message) { @@ -83,51 +87,6 @@ static void se_operation_failed(const char *message) { se_throw(SCR_ERR_ERROR, "ERR_CRYPTO_OPERATION_FAILED", message); } -/* An object's toString the program defined, as an own or inherited - * function property. */ -static bool se_custom_to_string(ScrDyn *value) { - if (value->kind != SCR_DYN_OBJ && value->kind != SCR_DYN_TYPED_REF) return false; - ScrDyn *member = scr_dyn_obj_read(value, "toString", 8); - bool custom = member && member->kind == SCR_DYN_FUNC; - scr_dyn_release(member); - return custom; -} - -/* Whether value is a class instance whose class defines toString. */ -static bool se_class_to_string(const ScrDyn *value) { - ScrStr *name = scr_str_new("toString", 8); - bool method = scr_dyn_typed_ref_class_has(value, name); - scr_str_release(name); - return method; -} - -/* `prefix` and the value as util.format's %s renders it: strings and - * objects with a program-defined toString as String(value), numbers as - * util.inspect does, other values inspected at depth 0. Functions and - * class instances that define toString have no lowering. */ -static void se_throw_formatted(const char *code, const char *prefix, const ScrDyn *value) { - ScrDyn *v = (ScrDyn *)value; - if (v->kind == SCR_DYN_FUNC || se_class_to_string(v)) { - static const char message[] = "An ECDH encoding or format that is a function or an instance of a class " - "defining toString has no lowering; pass the name as a string"; - scr_throw_error_msg_code(SCR_ERR_ERROR, message, sizeof message - 1, "SC2020"); - return; - } - ScrStr *text; - if (v->kind == SCR_DYN_STR || se_custom_to_string(v)) text = scr_dyn_string_coerce_js(v); - else if (v->kind == SCR_DYN_NUM) text = scr_insp_f64(v->v.num); - else text = scr_insp_dyn_s(v, 0); - if (!text) return; - ScrJsonBuf b; - scr_jb_init(&b); - scr_jb_puts(&b, prefix); - scr_jb_put_str(&b, text); - scr_str_release(text); - ScrStr *message = scr_jb_finish(&b); - scr_throw_error_msg_code(SCR_ERR_TYPE, message->data, message->len, code); - scr_str_release(message); -} - /* ── names and encodings ──────────────────────────────────────────────── */ static int se_name_cmp(const void *key, const void *entry) { @@ -198,129 +157,16 @@ static bool se_load_group(const ScrStr *name, mbedtls_ecp_group *grp, const char return false; } -static bool se_ascii_eq_ci(const char *a, size_t a_len, const char *b) { - size_t b_len = strlen(b); - if (a_len != b_len) return false; - for (size_t i = 0; i < a_len; i++) { - char x = a[i]; - if (x >= 'A' && x <= 'Z') x = (char)(x - 'A' + 'a'); - if (x != b[i]) return false; - } - return true; -} - -static bool se_str_is(const ScrStr *text, const char *literal) { - size_t len = strlen(literal); - return text->len == len && memcmp(text->data, literal, len) == 0; -} - -/* Node's normalizeEncoding: the canonical name, or NULL. */ -static const char *se_normalize_encoding(const ScrStr *name) { - static const struct { const char *from; const char *to; } map[] = { - {"utf8", "utf8"}, {"utf-8", "utf8"}, {"hex", "hex"}, - {"base64", "base64"}, {"base64url", "base64url"}, {"latin1", "latin1"}, - {"binary", "latin1"}, {"ascii", "ascii"}, {"utf16le", "utf16le"}, - {"utf-16le", "utf16le"}, {"ucs2", "utf16le"}, {"ucs-2", "utf16le"}, - }; - for (size_t i = 0; i < sizeof map / sizeof map[0]; i++) - if (se_ascii_eq_ci(name->data, name->len, map[i].from)) return map[i].to; - return NULL; -} - -/* The value a typed-ref box holds when it is a string, view, ArrayBuffer - * or native handle (+1). Other values are retained as passed, so argument - * errors describe the original value. NULL after throwing. */ -static ScrDyn *se_unbox(ScrDyn *value) { - if (value->kind != SCR_DYN_TYPED_REF) return scr_dyn_retain(value); - ScrDyn *view = scr_dyn_typed_ref_materialize(value); - if (!view) return NULL; - if (view->kind == SCR_DYN_STR || view->kind == SCR_DYN_BYTES || view->kind == SCR_DYN_HANDLE || - scr_buffer_storage_is(view)) - return view; - scr_dyn_release(view); - return scr_dyn_retain(value); -} - -/* getArrayBufferOrView(key, 'key', encoding): a string is Buffer.from(key, - * encoding) with 'buffer' read as utf8; views and ArrayBuffers are their - * bytes. +1 or NULL after throwing. */ -static ScrBytes *se_key_bytes(const ScrDyn *key, const ScrDyn *encoding) { - if (key->kind == SCR_DYN_STR) { - /* Buffer.from(string, encoding): an encoding that is not a non-empty - * string reads as utf8. */ - const char *name = "utf8"; - if (encoding->kind == SCR_DYN_STR && encoding->v.str->len > 0 && !se_str_is(encoding->v.str, "buffer")) { - name = se_normalize_encoding(encoding->v.str); - if (!name) { - se_throw_formatted("ERR_UNKNOWN_ENCODING", "Unknown encoding: ", encoding); - return NULL; - } - } - ScrStr *canonical = scr_str_new(name, strlen(name)); - ScrBytes *bytes = scr_bytes_from_str(key->v.str, canonical); - scr_str_release(canonical); - return bytes; - } - if (key->kind == SCR_DYN_BYTES || scr_buffer_storage_is(key)) return scr_bytes_buffer_source(key); - scr_dyn_arg_type_fail("key", "of type string or an instance of ArrayBuffer, Buffer, TypedArray, or DataView", key); - return NULL; -} - -/* encode(buffer, encoding): the Buffer, or buffer.toString(encoding) for - * a truthy encoding other than 'buffer'. Consumes bytes. */ -static ScrDyn *se_encode(ScrBytes *bytes, const ScrDyn *encoding) { - if (!scr_dyn_truthy(encoding) || (encoding->kind == SCR_DYN_STR && se_str_is(encoding->v.str, "buffer"))) { - ScrDyn *result = scr_dyn_new_buffer(bytes); - scr_bytes_release(bytes); - return result; - } - /* toString answers "" for no bytes before it reads the encoding. */ - ScrStr *text = NULL; - if (bytes->len == 0) { - text = scr_str_new("", 0); - } else { - /* getEncodingOps reads `encoding + ''`. */ - ScrStr *name = encoding->kind == SCR_DYN_STR ? scr_str_retain(encoding->v.str) : NULL; - if (!name) { - if (encoding->kind == SCR_DYN_FUNC || se_class_to_string(encoding)) { - se_throw_formatted("ERR_UNKNOWN_ENCODING", "Unknown encoding: ", encoding); - scr_bytes_release(bytes); - return NULL; - } - name = scr_dyn_string_coerce_js(encoding); - if (!name) { - scr_bytes_release(bytes); - return NULL; - } - } - const char *canonical = se_normalize_encoding(name); - scr_str_release(name); - if (!canonical) { - se_throw_formatted("ERR_UNKNOWN_ENCODING", "Unknown encoding: ", encoding); - scr_bytes_release(bytes); - return NULL; - } - ScrStr *canonical_text = scr_str_new(canonical, strlen(canonical)); - text = scr_bytes_to_str(bytes, canonical_text); - scr_str_release(canonical_text); - } - scr_bytes_release(bytes); - if (!text) return NULL; - ScrDyn *result = scr_dyn_new_str(text); - scr_str_release(text); - return result; -} - /* getFormat: a falsy format is uncompressed; other values must be * 'compressed', 'hybrid' or 'uncompressed'. 0 after throwing. */ static int se_format(const ScrDyn *format) { if (!scr_dyn_truthy(format)) return SE_UNCOMPRESSED; if (format->kind == SCR_DYN_STR) { - if (se_str_is(format->v.str, "compressed")) return SE_COMPRESSED; - if (se_str_is(format->v.str, "hybrid")) return SE_HYBRID; - if (se_str_is(format->v.str, "uncompressed")) return SE_UNCOMPRESSED; + if (ca_str_is(format->v.str, "compressed")) return SE_COMPRESSED; + if (ca_str_is(format->v.str, "hybrid")) return SE_HYBRID; + if (ca_str_is(format->v.str, "uncompressed")) return SE_UNCOMPRESSED; } - se_throw_formatted("ERR_CRYPTO_ECDH_INVALID_FORMAT", "Invalid ECDH format: ", format); + ca_throw_formatted(SE_SUBJECT, "ERR_CRYPTO_ECDH_INVALID_FORMAT", "Invalid ECDH format: ", format); return 0; } @@ -516,7 +362,7 @@ static ScrDyn *se_new(const ScrDyn *curve) { } ScrDyn *scr_crypto_ecdh_new(ScrDyn *curve) { - ScrDyn *unboxed = se_unbox(curve); + ScrDyn *unboxed = ca_unbox(curve); if (!unboxed) return NULL; ScrDyn *result = se_new(unboxed); scr_dyn_release(unboxed); @@ -530,7 +376,7 @@ static ScrDyn *se_convert_key(const ScrDyn *key, const ScrDyn *curve, const ScrD scr_dyn_arg_type_fail("curve", "of type string", curve); return NULL; } - ScrBytes *bytes = se_key_bytes(key, in_enc); + ScrBytes *bytes = ca_key_bytes(SE_SUBJECT, key, in_enc); if (!bytes) return NULL; int form = se_format(format); if (!form) { @@ -557,7 +403,7 @@ static ScrDyn *se_convert_key(const ScrDyn *key, const ScrDyn *curve, const ScrD } else { ScrBytes *out = se_write_point(&grp, &pt, form); if (!out) se_operation_failed("Failed to convert EC_POINT to Buffer"); - else result = se_encode(out, out_enc); + else result = ca_encode(SE_SUBJECT, out, out_enc); } } mbedtls_ecp_point_free(&pt); @@ -571,7 +417,7 @@ ScrDyn *scr_crypto_ecdh_convert_key(ScrDyn *key, ScrDyn *curve, ScrDyn *in_enc, ScrDyn *unboxed[5] = {NULL, NULL, NULL, NULL, NULL}; ScrDyn *result = NULL; for (size_t i = 0; i < 5; i++) - if (!(unboxed[i] = se_unbox(args[i]))) goto done; + if (!(unboxed[i] = ca_unbox(args[i]))) goto done; result = se_convert_key(unboxed[0], unboxed[1], unboxed[2], unboxed[3], unboxed[4]); done: for (size_t i = 0; i < 5; i++) scr_dyn_release(unboxed[i]); @@ -597,7 +443,7 @@ static ScrDyn *se_get_public_key(ScEcdh *e, const ScrDyn *encoding, const ScrDyn se_operation_failed("Failed to get ECDH public key"); return NULL; } - return se_encode(out, encoding); + return ca_encode(SE_SUBJECT, out, encoding); } static ScrDyn *se_generate_keys(ScEcdh *e, const ScrDyn *encoding, const ScrDyn *format) { @@ -628,12 +474,12 @@ static ScrDyn *se_get_private_key(ScEcdh *e, const ScrDyn *encoding) { se_operation_failed("Failed to get ECDH private key"); return NULL; } - return se_encode(out, encoding); + return ca_encode(SE_SUBJECT, out, encoding); } /* setPrivateKey(key, encoding): 1 <= d < n, and the public key d·G. */ static ScrDyn *se_set_private_key(ScEcdh *e, ScrDyn *self, const ScrDyn *key, const ScrDyn *encoding) { - ScrBytes *bytes = se_key_bytes(key, encoding); + ScrBytes *bytes = ca_key_bytes(SE_SUBJECT, key, encoding); if (!bytes) return NULL; mbedtls_mpi d; mbedtls_ecp_point q; @@ -680,7 +526,7 @@ static void se_dep0031(void) { static ScrDyn *se_set_public_key(ScEcdh *e, ScrDyn *self, const ScrDyn *key, const ScrDyn *encoding) { se_dep0031(); - ScrBytes *bytes = se_key_bytes(key, encoding); + ScrBytes *bytes = ca_key_bytes(SE_SUBJECT, key, encoding); if (!bytes) return NULL; mbedtls_ecp_point q; mbedtls_ecp_point_init(&q); @@ -716,7 +562,7 @@ static bool se_pair_valid(ScEcdh *e) { /* computeSecret(key, inputEncoding, outputEncoding): the x coordinate of * d·P, padded to the field size as ECDH_compute_key writes it. */ static ScrDyn *se_compute_secret(ScEcdh *e, const ScrDyn *key, const ScrDyn *in_enc, const ScrDyn *out_enc) { - ScrBytes *bytes = se_key_bytes(key, in_enc); + ScrBytes *bytes = ca_key_bytes(SE_SUBJECT, key, in_enc); if (!bytes) return NULL; ScrDyn *result = NULL; mbedtls_ecp_point pub; @@ -737,7 +583,7 @@ static ScrDyn *se_compute_secret(ScEcdh *e, const ScrDyn *key, const ScrDyn *in_ scr_bytes_release(out); se_operation_failed("Failed to compute ECDH key"); } else { - result = se_encode(out, out_enc); + result = ca_encode(SE_SUBJECT, out, out_enc); } } mbedtls_mpi_free(&z); @@ -776,7 +622,7 @@ static ScrDyn *se_invoke(void *h, ScrDyn *self, const char *method, ScrDyn *cons size_t count = argc < 3 ? argc : 3; ScrDyn *result = NULL; for (size_t i = 0; i < count; i++) - if (!(unboxed[i] = se_unbox(args[i]))) goto done; + if (!(unboxed[i] = ca_unbox(args[i]))) goto done; result = se_dispatch(h, self, method, unboxed, count, what); done: for (size_t i = 0; i < count; i++) scr_dyn_release(unboxed[i]); diff --git a/packages/runtime/src/scr_ed25519.c b/packages/runtime/src/scr_ed25519.c new file mode 100644 index 000000000..c6d6ce370 --- /dev/null +++ b/packages/runtime/src/scr_ed25519.c @@ -0,0 +1,76 @@ +/* Ed25519 for scr_pki.c: libsodium's ref10 implementation (vendored, see + * ../vendor/README.md), textually included so it builds as this one unit. + * It links only into programs that name Ed25519 (the ed25519 runtime + * feature) and installs itself into scr_pki.c at startup; without it, + * Ed25519 signing, verification and public-key derivation throw a coded + * SC2020 error. + * + * Signing runs in constant time. Verification rejects a non-canonical S + * and the small-order R and public-key encodings, then checks the + * cofactorless equation, which is what Node 24 answers. */ +#include "scr_runtime.h" + +#include +#include +#include +#include + +#include "scr_pki.h" + +#define CONFIGURED 1 +#include "../vendor/libsodium/ed25519_ref10.c" +#include "../vendor/libsodium/hash_sha512_cp.c" +#include "../vendor/libsodium/verify.c" +#include "../vendor/libsodium/sign.c" +#include "../vendor/libsodium/open.c" +#include "../vendor/libsodium/keypair.c" +#undef CONFIGURED + +/* The libsodium utilities those units call. */ +void sodium_memzero(void *const pnt, const size_t len) { + volatile unsigned char *p = (volatile unsigned char *)pnt; + for (size_t i = 0; i < len; i++) p[i] = 0U; +} + +int sodium_memcmp(const void *const b1_, const void *const b2_, size_t len) { + const volatile unsigned char *b1 = (const volatile unsigned char *)b1_; + const volatile unsigned char *b2 = (const volatile unsigned char *)b2_; + volatile unsigned char d = 0U; + for (size_t i = 0; i < len; i++) d |= b1[i] ^ b2[i]; + return (1 & ((d - 1) >> 8)) - 1; +} + +int sodium_is_zero(const unsigned char *n, const size_t nlen) { + volatile unsigned char d = 0U; + for (size_t i = 0; i < nlen; i++) d |= n[i]; + return 1 & ((d - 1) >> 8); +} + +void randombytes_buf(void *const buf, const size_t size) { arc4random_buf(buf, size); } + +static void se_public_key(uint8_t pub[32], const uint8_t seed[32]) { + uint8_t sk[64]; + crypto_sign_ed25519_seed_keypair(pub, sk, seed); + sodium_memzero(sk, sizeof sk); +} + +static void se_sign(uint8_t sig[64], const uint8_t seed[32], const uint8_t pub[32], const uint8_t *m, + size_t n) { + uint8_t sk[64]; + memcpy(sk, seed, 32); + memcpy(sk + 32, pub, 32); + crypto_sign_ed25519_detached(sig, NULL, m, n, sk); + sodium_memzero(sk, sizeof sk); +} + +static bool se_verify(const uint8_t pub[32], const uint8_t *m, size_t n, const uint8_t sig[64]) { + return crypto_sign_ed25519_verify_detached(sig, m, n, pub) == 0; +} + +static const ScrPkiEd25519 se_table = { + .public_key = se_public_key, + .sign = se_sign, + .verify = se_verify, +}; + +__attribute__((constructor)) static void se_install(void) { scr_pki_ed25519 = &se_table; } diff --git a/packages/runtime/src/scr_events_emitter.c b/packages/runtime/src/scr_events_emitter.c index 901e2d114..93a724ecb 100644 --- a/packages/runtime/src/scr_events_emitter.c +++ b/packages/runtime/src/scr_events_emitter.c @@ -82,6 +82,8 @@ typedef struct ScrEeEntry { * the meta events. */ ScrClosure *flex_cb; ScrDynThunk flex_invoke; + /* The function box's typed message entry (scr_emitter_emit_message). */ + ScrDynMessageListener flex_message; const char *flex_sig; const char *flex_name; uint32_t flex_arity; @@ -512,6 +514,7 @@ static ScrEmitter *scr_ee_add(ScrEmitter *em, ScrStr *name, ScrClosure *cb /*mov if (dyn) { e->flex_cb = scr_closure_retain(dyn->v.fn.clo); e->flex_invoke = dyn->v.fn.thunk; + e->flex_message = dyn->v.fn.message; e->flex_sig = dyn->v.fn.sig; e->flex_name = dyn->v.fn.name; e->flex_arity = dyn->v.fn.arity; @@ -1013,15 +1016,16 @@ static ScrDyn *const scr_ee_no_args[1] = { NULL }; * a nested emit's snapshot still holds it (the shared fired flag — Node's * wrapper.fired). A listener throw stops the pass (the exception stays * pending for the caller). Returns whether the bucket had listeners. */ +typedef struct ScrEeMessage ScrEeMessage; static bool scr_ee_emit_core(ScrEmitter *em, ScrStr *name, va_list *ap_template, - ScrDyn *const *flex_args, size_t flex_argc); + ScrDyn *const *flex_args, size_t flex_argc, ScrEeMessage *message); /* emit('error', ...) first emits the same arguments to errorMonitor. */ static void scr_ee_emit_error_monitor(ScrEmitter *em, va_list *ap_template, ScrDyn *const *flex_args, size_t flex_argc) { ScrEeBucket *b = scr_ee_bucket_of(em->reg, SCR_EE_ERROR_MONITOR); if (!b || b->n == 0) return; - scr_ee_emit_core(em, SCR_EE_ERROR_MONITOR, ap_template, flex_args, flex_argc); + scr_ee_emit_core(em, SCR_EE_ERROR_MONITOR, ap_template, flex_args, flex_argc, NULL); } /* A listener this emit has no argument form for: an untyped emit whose @@ -1044,8 +1048,17 @@ SCR_COLD static void scr_ee_listener_mismatch(const ScrStr *name, bool typed_emi scr_throw_error(typed_emit ? SCR_ERR_ERROR : SCR_ERR_TYPE, message); } +/* A message emit (scr_emitter_emit_message): listeners with a typed message + * entry read the message until a listener without one runs; that listener + * and every later one share one decoded argument. */ +struct ScrEeMessage { + const struct ScrMessage *message; + ScrDyn *(*decode)(const struct ScrMessage *); + ScrDyn *decoded; +}; + static bool scr_ee_emit_core(ScrEmitter *em, ScrStr *name, va_list *ap_template, - ScrDyn *const *flex_args, size_t flex_argc) { + ScrDyn *const *flex_args, size_t flex_argc, ScrEeMessage *message) { if (name->len == 5 && memcmp(name->data, "error", 5) == 0) { scr_ee_emit_error_monitor(em, ap_template, flex_args, flex_argc); if (scr_exc_pending()) return true; @@ -1088,6 +1101,22 @@ static bool scr_ee_emit_core(ScrEmitter *em, ScrStr *name, va_list *ap_template, continue; } } + /* Once a listener has the decoded value, later listeners read that + * value: an earlier listener may have changed it, as in Node. */ + if (message && !message->decoded && e->flex_message && + e->flex_message(e->flex_cb, message->message)) { + scr_ee_entry_unref(e); + continue; + } + if (message && !message->decoded) { + message->decoded = message->decode(message->message); + if (!message->decoded) { + scr_ee_entry_unref(e); + continue; + } + flex_args = &message->decoded; + flex_argc = 1; + } if (flex_args && e->flex_invoke) { ScrDyn *answer = e->flex_invoke(e->flex_cb, flex_args, flex_argc); scr_dyn_release(answer); /* EventEmitter ignores callback results. */ @@ -1108,7 +1137,7 @@ static bool scr_ee_emit_core(ScrEmitter *em, ScrStr *name, va_list *ap_template, static bool scr_ee_emit_va(ScrEmitter *em, ScrStr *name, ...) { va_list ap; va_start(ap, name); - bool had = scr_ee_emit_core(em, name, &ap, NULL, 0); + bool had = scr_ee_emit_core(em, name, &ap, NULL, 0, NULL); va_end(ap); return had; } @@ -1119,7 +1148,7 @@ static bool scr_ee_emit_mixed_va(ScrEmitter *em, ScrStr *name, ScrDyn *const *ar int typed, ...) { va_list ap; va_start(ap, typed); - bool had = scr_ee_emit_core(em, name, typed ? &ap : NULL, args ? args : scr_ee_no_args, argc); + bool had = scr_ee_emit_core(em, name, typed ? &ap : NULL, args ? args : scr_ee_no_args, argc, NULL); va_end(ap); return had; } @@ -1131,7 +1160,7 @@ static bool scr_ee_emit_mixed_va(ScrEmitter *em, ScrStr *name, ScrDyn *const *ar bool scr_emitter_emit(ScrEmitter *em, ScrStr *name, ...) { va_list ap; va_start(ap, name); - bool had = scr_ee_emit_core(em, name, &ap, NULL, 0); + bool had = scr_ee_emit_core(em, name, &ap, NULL, 0, NULL); va_end(ap); return had; } @@ -1143,7 +1172,7 @@ bool scr_emitter_emit(ScrEmitter *em, ScrStr *name, ...) { bool scr_emitter_emit_mixed(ScrEmitter *em, ScrStr *name, ScrDyn *const *args, size_t argc, ...) { va_list ap; va_start(ap, argc); - bool had = scr_ee_emit_core(em, name, &ap, args ? args : scr_ee_no_args, argc); + bool had = scr_ee_emit_core(em, name, &ap, args ? args : scr_ee_no_args, argc, NULL); va_end(ap); return had; } @@ -1241,7 +1270,15 @@ static bool scr_ee_emit_error_dyn(ScrEmitter *em, ScrStr *name, ScrDyn *const *a /* An untyped emit of a name typed code never fixes a tuple for (computed * names, runtime-internal registries): the arguments as given. */ bool scr_emitter_emit_flex(ScrEmitter *em, ScrStr *name, ScrDyn *const *args, size_t argc) { - return scr_ee_emit_core(em, name, NULL, args ? args : scr_ee_no_args, argc); + return scr_ee_emit_core(em, name, NULL, args ? args : scr_ee_no_args, argc, NULL); +} + +bool scr_emitter_emit_message(ScrEmitter *em, ScrStr *name, const struct ScrMessage *message, + ScrDyn *(*decode)(const struct ScrMessage *)) { + ScrEeMessage state = {message, decode, NULL}; + bool had = scr_ee_emit_core(em, name, NULL, NULL, 0, &state); + scr_dyn_release(state.decoded); + return had; } /* emit(name, ...args) through an untyped value: the arguments as given. @@ -1255,7 +1292,7 @@ bool scr_emitter_emit_any(ScrEmitter *em, ScrStr *name, ScrDyn *const *args, siz return scr_ee_emit_mixed_va(em, name, args, argc, s != NULL, s); } } - return scr_ee_emit_core(em, name, NULL, args ? args : scr_ee_no_args, argc); + return scr_ee_emit_core(em, name, NULL, args ? args : scr_ee_no_args, argc, NULL); } /* Handle event registries use checked callbacks for every tuple, including @@ -1268,7 +1305,7 @@ bool scr_emitter_emit_error_flex(ScrEmitter *em, ScrDyn *error) { return false; } ScrStr *name = scr_str_new("error", 5); - bool had = scr_ee_emit_core(em, name, NULL, &error, 1); + bool had = scr_ee_emit_core(em, name, NULL, &error, 1, NULL); scr_str_release(name); return had; } diff --git a/packages/runtime/src/scr_events_emitter.h b/packages/runtime/src/scr_events_emitter.h index b66de9e5a..29d4c397f 100644 --- a/packages/runtime/src/scr_events_emitter.h +++ b/packages/runtime/src/scr_events_emitter.h @@ -154,6 +154,14 @@ ScrEmitter *scr_emitter_remove_all(ScrEmitter *em, ScrStr *name, bool all); * emit('error', err): no listener ⇒ THROWS err (borrowed; +1 taken). */ bool scr_emitter_emit(ScrEmitter *em, ScrStr *name, ...); bool scr_emitter_emit_flex(ScrEmitter *em, ScrStr *name, ScrDyn *const *args, size_t argc); +/* An untyped emit of one message: a listener registered from a function + * box with a typed message entry (scr_dyn_func_set_message) reads the + * message itself while no listener has needed the decoded value; from the + * first listener without an entry on, every listener gets decode(message), + * made once. */ +struct ScrMessage; +bool scr_emitter_emit_message(ScrEmitter *em, ScrStr *name, const struct ScrMessage *message, + ScrDyn *(*decode)(const struct ScrMessage *)); /* An untyped emit of an event with a fixed tuple: the arguments as given * for dynamic listeners, plus the tuple converted by the caller as * scr_emitter_emit's variadics for typed listeners. has_typed answers diff --git a/packages/runtime/src/scr_fetch.c b/packages/runtime/src/scr_fetch.c index 735183b89..96e90e47c 100644 --- a/packages/runtime/src/scr_fetch.c +++ b/packages/runtime/src/scr_fetch.c @@ -44,7 +44,9 @@ typedef struct SfChunk { } SfChunk; struct SfReadRequest { - ScrPromise *promise; + ScrPromise *promise; /* or NULL for a sink request */ + const ScrFetchReadSink *sink; /* readableStreamDefaultReaderRead's read request */ + void *sink_ctx; SfReadRequest *next; }; @@ -776,6 +778,11 @@ static SfReadRequest *sf_reader_take_request(SfReader *r) { static void sf_reader_reject_message_all(SfReader *r, const char *message) { SfReadRequest *request; while ((request = sf_reader_take_request(r)) != NULL) { + if (request->sink) { + request->sink->error(request->sink_ctx, NULL); + free(request); + continue; + } sf_type_error(message); scr_promise_reject_pending(request->promise); scr_promise_release(request->promise); @@ -958,6 +965,12 @@ static void sf_reader_fulfill_one(SfReader *r, bool done, ScrDyn *value) { if (!r) return; SfReadRequest *request = sf_reader_take_request(r); if (!request) return; + if (request->sink) { + if (done) request->sink->close(request->sink_ctx); + else request->sink->chunk(request->sink_ctx, value); + free(request); + return; + } scr_promise_fulfill_ref(request->promise, sf_read_result(done, value), &scr_dyn_retain_v, &scr_dyn_release_v, NULL); scr_promise_release(request->promise); @@ -968,6 +981,11 @@ static void sf_reader_reject_all(SfReader *r, ScrDyn *reason) { if (!r) return; SfReadRequest *request; while ((request = sf_reader_take_request(r)) != NULL) { + if (request->sink) { + request->sink->error(request->sink_ctx, reason); + free(request); + continue; + } sf_reject_promise_reason(request->promise, reason); scr_promise_release(request->promise); free(request); @@ -1654,18 +1672,21 @@ static SfReader *sf_stream_get_reader(SfStream *s) { return r; } -static ScrPromise *sf_reader_read(SfReader *r) { - ScrPromise *p = scr_promise_new(); +/* readableStreamDefaultReaderRead: queue the request, then serve it from + * the queue or a pull. false (TypeError pending) for a released reader. */ +static bool sf_reader_read_request(SfReader *r, ScrPromise *p, const ScrFetchReadSink *sink, + void *sink_ctx) { SfStream *s = r->stream; if (!s || s->reader != r) { sf_type_error("This reader has been released"); - scr_promise_reject_pending(p); - return p; + return false; } s->disturbed = true; SfReadRequest *request = calloc(1, sizeof *request); if (!request) sf_oom(); - request->promise = scr_promise_retain(p); + request->promise = p ? scr_promise_retain(p) : NULL; + request->sink = sink; + request->sink_ctx = sink_ctx; if (r->pending_tail) r->pending_tail->next = request; else r->pending_head = request; r->pending_tail = request; @@ -1674,6 +1695,12 @@ static ScrPromise *sf_reader_read(SfReader *r) { sf_stream_pull(s); sf_stream_drain(s); } + return true; +} + +static ScrPromise *sf_reader_read(SfReader *r) { + ScrPromise *p = scr_promise_new(); + if (!sf_reader_read_request(r, p, NULL, NULL)) scr_promise_reject_pending(p); return p; } @@ -1960,6 +1987,15 @@ ScrDyn *scr_fetch_stream_from_string(ScrStr *iterable) { return out; } +bool scr_fetch_reader_read_into(ScrDyn *reader, const ScrFetchReadSink *sink, void *ctx) { + if (!reader || reader->kind != SCR_DYN_HANDLE || + reader->v.handle.tag != SCR_DYNH_WEB_READER) { + sf_type_error("Expected a ReadableStreamDefaultReader"); + return false; + } + return sf_reader_read_request((SfReader *)reader->v.handle.ptr, NULL, sink, ctx); +} + ScrPromise *scr_fetch_reader_read(ScrDyn *reader) { if (!reader || reader->kind != SCR_DYN_HANDLE || reader->v.handle.tag != SCR_DYNH_WEB_READER) { diff --git a/packages/runtime/src/scr_generator.h b/packages/runtime/src/scr_generator.h index c4397e021..c3dac861d 100644 --- a/packages/runtime/src/scr_generator.h +++ b/packages/runtime/src/scr_generator.h @@ -200,5 +200,17 @@ ScrDyn *scr_fetch_stream_from_bytes( ScrDyn *scr_fetch_stream_from_string( ScrStr *iterable); /* borrowed string; +1 handle */ ScrPromise *scr_fetch_reader_read(ScrDyn *reader); /* borrowed handle; +1 */ +/* A read request served by callbacks instead of a promise (the streams + * spec's readableStreamDefaultReaderRead with a read request; Node's + * Readable.fromWeb adapter uses one). chunk and error borrow their value; + * error's reason is NULL when the reader was released. */ +typedef struct ScrFetchReadSink { + void (*chunk)(void *ctx, ScrDyn *value); + void (*close)(void *ctx); + void (*error)(void *ctx, ScrDyn *reason); +} ScrFetchReadSink; +/* Queue a sink read request on a reader handle (borrowed). false with a + * TypeError pending for a value that is not a reader or a released one. */ +bool scr_fetch_reader_read_into(ScrDyn *reader, const ScrFetchReadSink *sink, void *ctx); #endif /* SCR_GENERATOR_H */ diff --git a/packages/runtime/src/scr_http.c b/packages/runtime/src/scr_http.c index d9876c30b..cb88297bf 100644 --- a/packages/runtime/src/scr_http.c +++ b/packages/runtime/src/scr_http.c @@ -2918,22 +2918,6 @@ static bool scr_http_conn_parse_head(ScrHttpConn *conn, size_t head_len, bool *o conn->trailer_bytes = 0; conn->trailer_fields = 0; - if (!http10 && conn->srv->require_host_header) { - bool has_host = false; - for (size_t i = 0; i < req->nheaders; i++) { - const ScrStr *name = req->hnames[i]; - if (name->len == 4 && memcmp(name->data, "host", 4) == 0) { - has_host = true; - break; - } - } - if (!has_host) { - scr_http_req_release(req); - scr_http_conn_missing_host(conn); - return true; - } - } - /* framing: chunked wins over Content-Length (RFC 9112) */ bool chunked = false; long long content_length = 0; @@ -2958,12 +2942,33 @@ static bool scr_http_conn_parse_head(ScrHttpConn *conn, size_t head_len, bool *o } } + /* HTTP/1.1 requires Host (requireHostHeader). CONNECT requests, and + * upgrade requests an 'upgrade' listener takes, leave the parser before + * Node's check. */ + bool is_connect = req->method->len == 7 && memcmp(req->method->data, "CONNECT", 7) == 0; + bool takes_upgrade = has_upgrade_hdr && conn_upgrade_token && conn->srv->upgrade_ls.n > 0; + if (!http10 && conn->srv->require_host_header && !is_connect && !takes_upgrade) { + bool has_host = false; + for (size_t i = 0; i < req->nheaders; i++) { + const ScrStr *name = req->hnames[i]; + if (name->len == 4 && memcmp(name->data, "host", 4) == 0) { + has_host = true; + break; + } + } + if (!has_host) { + scr_http_req_release(req); + scr_http_conn_missing_host(conn); + return true; + } + } + /* A CONNECT request: 'connect' fires INSTEAD of 'request' — the * upgrade machinery's exact shape ((req, socket, head); the parser * steps aside; no listener destroys the socket, Node's default). The * h2 compat server's HTTP/1.1 arm lands here too; its HTTP/2 arm is * dispatched separately with the compatibility response handle. */ - if (req->method->len == 7 && memcmp(req->method->data, "CONNECT", 7) == 0) { + if (is_connect) { memmove(conn->buf, conn->buf + head_len, conn->len - head_len); conn->len -= head_len; if (!scr_net_ls_has_live(&conn->srv->connect_ls)) { @@ -4318,14 +4323,32 @@ static void scr_http_client_end_raw(ScrHttpClientReq *c, const char *data, size_ } if (!c->head_sent) { /* whole body known NOW: Content-Length framing (or none — the head - * serializer's empty-body method split) */ + * serializer's empty-body method split). Head and body go out as one + * write, as Node sends them: on a connected (reused) socket two writes + * would be two segments, and the server could answer before the body + * arrives. */ + c->hold_head = true; scr_http_client_send_head(c, (long long)len); + c->hold_head = false; if (scr_exc_pending()) return; if (c->chunked) { scr_http_client_write_raw(c, data, len); if (c->sock) scr_http_send_chunk_end(c->sock, &c->trailers); - } else if (c->sock && len > 0) { - scr_net_sock_write_native(c->sock, data, len); + } else if (c->held_head != NULL) { + char *head = c->held_head; + size_t head_len = c->held_head_len; + c->held_head = NULL; + c->held_head_len = c->held_head_cap = 0; + if (c->sock) { + if (len > 0) { + char *joined = realloc(head, head_len + len); + if (!joined) scr_http_oom(); + head = joined; + memcpy(head + head_len, data, len); + } + scr_net_sock_write_native(c->sock, head, head_len + len); + } + free(head); } } else { scr_http_client_write_raw(c, data, len); diff --git a/packages/runtime/src/scr_inspect.c b/packages/runtime/src/scr_inspect.c index 7a1685a02..bca2b88fe 100644 --- a/packages/runtime/src/scr_inspect.c +++ b/packages/runtime/src/scr_inspect.c @@ -1681,7 +1681,40 @@ ScrStr *scr_insp_dyn(ScrDyn *d, double recurse, double depth) { * view of its fields does not carry. */ const ScrStr *name = scr_dyn_typed_ref_class_name(d); ScrStr *out; - if (name && materialized->kind == SCR_DYN_OBJ && + double time; + ScrStr *date_class = materialized->kind == SCR_DYN_OBJ && scr_dyn_date_class_time(d, &time) + ? scr_dyn_date_class_name(d) : NULL; + if (date_class) { + /* An instance of a class declared `extends Date`: the class name and + * the time as Date.prototype.toISOString formats it, then its own + * enumerable properties when it has any. */ + ScrStr *iso = scr_insp_date(time); + InspBuf head = {0}; + ib_bytes(&head, date_class->data, date_class->len); + scr_str_release(date_class); + ib_char(&head, ' '); + ib_bytes(&head, iso->data, iso->len); + scr_str_release(iso); + ScrStr *prefix = ib_take(&head); + bool fields = false; + for (size_t i = 0; i < materialized->v.obj.len && !fields; i++) + fields = materialized->v.obj.entries[i].enumerable; + if (!fields || recurse > depth) { + scr_dyn_release(materialized); + return prefix; + } + char *cls = malloc(prefix->len + 1); + if (!cls) scr_trap("scriptc: out of memory\n"); + memcpy(cls, prefix->data, prefix->len); + cls[prefix->len] = '\0'; + scr_str_release(prefix); + size_t nseen = g_nseen; + g_pending_seen = instance; + out = scr_insp_obj(materialized, recurse, depth, cls); + g_pending_seen = NULL; + if (g_nseen > nseen) g_nseen = nseen; + free(cls); + } else if (name && materialized->kind == SCR_DYN_OBJ && scr_dyn_obj_get(materialized, "%error", 6) == NULL) { char *cls = malloc(name->len + 1); if (!cls) scr_trap("scriptc: out of memory\n"); diff --git a/packages/runtime/src/scr_itable.c b/packages/runtime/src/scr_itable.c index a333aab95..25a074f49 100644 --- a/packages/runtime/src/scr_itable.c +++ b/packages/runtime/src/scr_itable.c @@ -472,7 +472,7 @@ static ScrArrState scr_itable_element(ScrITableElements *w, size_t i, uint64_t * } if (i < a->cap) { *slot = a->data[i]; - return (ScrArrState)*scr_arr_state_ptr(a, i); + return (ScrArrState)scr_arr_dense_state(a, i); } if (scr_arr_ext_of(a)) { while (w->sparse < scr_arr_ext_of(a)->sparse_len && scr_arr_ext_of(a)->sparse[w->sparse].index < i) w->sparse++; diff --git a/packages/runtime/src/scr_itable.test.c b/packages/runtime/src/scr_itable.test.c index f6d98654a..c85370add 100644 --- a/packages/runtime/src/scr_itable.test.c +++ b/packages/runtime/src/scr_itable.test.c @@ -55,6 +55,7 @@ static ScrArr *make_f64s(const double *values, size_t n) { a->filled = (uint32_t)n; a->elem = SCR_ELEM_F64; /* Values, then one state byte per slot (scr_arr_states_end). */ + a->spare = SCR_ARR_STATES; a->data = calloc(n ? n : 1, sizeof(uint64_t) + 1); for (size_t i = 0; i < n; i++) memcpy(&a->data[i], &values[i], sizeof(double)); memset(scr_arr_state_run(a, 0, n), SCR_ARR_VALUE, n); @@ -170,6 +171,7 @@ int main(void) { assert(scr_itable_size(lists) == 4); ScrArr *big = make_f64s(NULL, 0); big->len = big->cap = big->filled = 100; + big->spare = 0; /* values without states */ free(big->data); big->data = calloc(100, sizeof(uint64_t)); for (unsigned i = 0; i < 100; i++) memcpy(&big->data[i], &(double){i}, sizeof(double)); diff --git a/packages/runtime/src/scr_json.c b/packages/runtime/src/scr_json.c index e8b75e5fa..46d3495ff 100644 --- a/packages/runtime/src/scr_json.c +++ b/packages/runtime/src/scr_json.c @@ -37,6 +37,21 @@ static SCR_TL ScrDyn *scr_builtin_object_prototype; +const ScrDateClassHooks *scr_date_class_hooks = NULL; + +/* The checked-dynamic Error.prototype (scr_dyn_error_prototype) is not the + * prototype of scriptc's Error instances, so a change to it would not reach + * them: every mutation throws. */ +static SCR_TL ScrDyn *scr_builtin_error_prototype; +static bool scr_dyn_error_prototype_fence(const ScrDyn *value) { + if (!value || value != scr_builtin_error_prototype) return false; + static const char message[] = "Error.prototype mutation is not supported yet"; + scr_throw_error_msg_code(SCR_ERR_ERROR, message, sizeof message - 1, "SC2020"); + return true; +} + +SCR_TL const ScrHandleStreamHooks *scr_handle_stream_hooks = NULL; + /* Constructor capsules expose identity and name/length, but do not model * per-class static property tables yet. Never report a fabricated empty view. */ static bool scr_dyn_class_reflection_fence(const ScrDyn *value) { @@ -1006,6 +1021,7 @@ static ScrDyn *scr_dyn_alloc(ScrDynKind kind) { } else if (kind == SCR_DYN_OBJ) { d->v.obj.len = 0; /* cap/entries preserved */ d->v.obj.region = NULL; + d->v.obj.class_name = NULL; /* a released class prototype's name */ SCR_JS_SHAPE_RESET(d); if (d->v.obj.cap <= SCR_DYN_KEY_CACHE_SLOTS) { for (size_t i = 0; i < d->v.obj.cap; i++) { @@ -1562,6 +1578,20 @@ ScrDyn *scr_dyn_iter_pack(const ScrDyn *src, const ScrStr *msg) { static ScrDyn *scr_native_iterator_drain(const ScrDyn *src); +/* The values a collection constructor's iterable seed gives, in order: +1 + * array, or NULL with the exception pending. A native iterator (a Map's + * keys(), a Set's values()) drains, which runs no program code; arrays, + * strings, typed arrays and collections pack; other iterables (a + * generator, an object with a Symbol.iterator method) step their + * iterator to the end, so their values are all taken before the + * constructor adds the first one. */ +static ScrDyn *scr_dyn_seed_values(const ScrDyn *src) { + if (src->kind == SCR_DYN_HANDLE && + (src->v.handle.tag == SCR_DYNH_ITERATOR || scr_dyn_handle_ops_of(src)->iter_step)) + return scr_native_iterator_drain(src); + return scr_dyn_destructure_rest(src, NULL); +} + /* The for-of-over-dyn pack accessors: the emitted index loop drives them * over a scr_dyn_iter_pack result (ARR by construction — the defensive * arms cover nothing reachable from that lowering). Never throw. */ @@ -1577,18 +1607,10 @@ ScrDyn *scr_dyn_map_seed_entries(const ScrDyn *src) { if (scr_exc_pending()) return NULL; } /* A native iterator (sp.entries(), a Map's entries()) or a handle that - * steps through live entries (URLSearchParams): producing its entries - * runs no program code, so draining them first is what the consumer - * observes. */ - if (src->kind == SCR_DYN_HANDLE && - (src->v.handle.tag == SCR_DYNH_ITERATOR || scr_dyn_handle_ops_of(src)->iter_step)) - return scr_native_iterator_drain(src); - if (src->kind == SCR_DYN_HANDLE || src->kind == SCR_DYN_TYPED_REF) { - static const char message[] = "new Map(entries) over native non-array iterables has no lowering"; - scr_throw_error_msg_code(SCR_ERR_ERROR, message, sizeof message - 1, "SC2020"); - return NULL; - } - return scr_dyn_iter_pack(src, NULL); + * steps through live entries (URLSearchParams) drains; a Set, a + * generator or another iterable gives its values in order + * (scr_dyn_seed_values). */ + return scr_dyn_seed_values(src); } ScrDyn *scr_dyn_map_seed_entry(const ScrDyn *entry) { @@ -1799,6 +1821,55 @@ static void scr_builtin_object_prototype_cleanup(void) { scr_dyn_release(prototype); } +/* The error constructors as values (an error's `constructor`, and the + * globals in JavaScript): one interned function per constructor and thread, + * indexed like scr_error_vts, with the constructor's name and length. + * Calling one through the value is not supported yet, as for the other + * interned constructors (scr_dyn_global_constructor). */ +static const char *const scr_error_ctor_names[] = { + "Error", "TypeError", "RangeError", "SyntaxError", NULL, + "ReferenceError", "EvalError", "URIError", "AggregateError", +}; +#define SCR_ERROR_CTORS (sizeof scr_error_ctor_names / sizeof scr_error_ctor_names[0]) +static SCR_TL ScrDyn *scr_error_ctor_values[SCR_ERROR_CTORS]; +static SCR_TL bool scr_error_ctors_registered; + +static void scr_error_ctors_cleanup(void) { + for (size_t i = 0; i < SCR_ERROR_CTORS; i++) { + scr_dyn_release(scr_error_ctor_values[i]); + scr_error_ctor_values[i] = NULL; + } +} + +static ScrDyn *scr_error_ctor_call(ScrClosure *closure, ScrDyn *const *args, size_t argc) { + (void)args; + (void)argc; + char message[128]; + int length = snprintf(message, sizeof message, + "calling the %s constructor through a stored value is not supported yet", + (const char *)closure->fn); + scr_throw_error_msg_code(SCR_ERR_ERROR, message, (size_t)length, "SC2020"); + return NULL; +} + +ScrDyn *scr_dyn_error_constructor(const char *name) { + for (size_t i = 0; i < SCR_ERROR_CTORS; i++) { + if (!scr_error_ctor_names[i] || strcmp(scr_error_ctor_names[i], name) != 0) continue; + if (!scr_error_ctors_registered) { + scr_error_ctors_registered = true; + scr_atexit(scr_error_ctors_cleanup); + } + if (!scr_error_ctor_values[i]) { + uint32_t length = strcmp(name, "AggregateError") == 0 ? 2 : 1; + scr_error_ctor_values[i] = + scr_dyn_new_func(scr_closure_new((void *)scr_error_ctor_names[i], 0), scr_error_ctor_call, length, + "native:constructor", scr_error_ctor_names[i]); + } + return scr_dyn_retain(scr_error_ctor_values[i]); + } + return NULL; +} + ScrDyn *scr_dyn_object_prototype(void) { if (!scr_builtin_object_prototype) { scr_builtin_object_prototype = scr_dyn_alloc(SCR_DYN_OBJ); @@ -1816,6 +1887,149 @@ ScrDyn *scr_dyn_array_prototype_base(void) { return scr_dyn_retain(scr_builtin_array_prototype); } +/* Error.prototype as a checked-dynamic object, for JavaScript constructor + * functions that inherit from it (`F.prototype = + * Object.create(Error.prototype)`): non-enumerable `constructor`, `name` + * ("Error"), `message` ("") and `toString`, on Object.prototype. The Error + * constructor has no checked-dynamic value, so `constructor` is a function + * named Error that throws when called. */ +static const ScrDyn *scr_dyn_proto_next(const ScrDyn *object); +static void scr_builtin_error_prototype_cleanup(void) { + ScrDyn *prototype = scr_builtin_error_prototype; + scr_builtin_error_prototype = NULL; + scr_dyn_release(prototype); +} +static ScrDyn *scr_error_prototype_to_string(ScrClosure *closure, ScrDyn *const *args, size_t argc) { + (void)closure; (void)args; (void)argc; + ScrDyn *self = scr_dyn_this_get(); + ScrDyn *result = NULL; + if (self->kind == SCR_DYN_OBJ || self->kind == SCR_DYN_ARR || self->kind == SCR_DYN_FUNC) { + ScrStr *text = scr_dyn_error_string(self); + if (text) { + result = scr_dyn_new_str(text); + scr_str_release(text); + } + } else { + ScrJsonBuf message; + scr_jb_init(&message); + scr_jb_puts(&message, "Method Error.prototype.toString called on incompatible receiver "); + ScrStr *shown = self->kind == SCR_DYN_SYMBOL ? self->v.symbol.render(self->v.symbol.value) + : scr_dyn_string_coerce_js(self); + if (shown) { + scr_jb_put_str(&message, shown); + scr_str_release(shown); + } + scr_throw_error(SCR_ERR_TYPE, scr_jb_finish(&message)); + } + scr_dyn_release(self); + return result; +} +static ScrDyn *scr_error_prototype_constructor(ScrClosure *closure, ScrDyn *const *args, size_t argc) { + (void)closure; (void)args; (void)argc; + static const char message[] = "calling Error.prototype.constructor is not supported yet"; + scr_throw_error_msg_code(SCR_ERR_ERROR, message, sizeof message - 1, "SC2020"); + return NULL; +} +static void scr_error_prototype_hide(ScrDyn *object, const char *key, size_t key_len) { + ScrDynEntry *entry = scr_dyn_find_entry(object, key, key_len); + entry->enumerable = false; +} +ScrDyn *scr_dyn_error_prototype(void) { + if (!scr_builtin_error_prototype) { + ScrDyn *prototype = scr_dyn_alloc(SCR_DYN_OBJ); + scr_dyn_obj_set(prototype, "constructor", 11, + scr_dyn_new_func(scr_closure_new(NULL, 0), scr_error_prototype_constructor, 1, "native:Error", "Error")); + scr_error_prototype_hide(prototype, "constructor", 11); + ScrStr *name = scr_str_new("Error", 5); + scr_dyn_obj_set(prototype, "name", 4, scr_dyn_new_str(name)); + scr_str_release(name); + scr_error_prototype_hide(prototype, "name", 4); + ScrStr *empty = scr_str_new("", 0); + scr_dyn_obj_set(prototype, "message", 7, scr_dyn_new_str(empty)); + scr_str_release(empty); + scr_error_prototype_hide(prototype, "message", 7); + scr_dyn_obj_set(prototype, "toString", 8, + scr_dyn_new_func(scr_closure_new(NULL, 0), scr_error_prototype_to_string, 0, "native:Error", "toString")); + scr_error_prototype_hide(prototype, "toString", 8); + scr_builtin_error_prototype = prototype; + scr_atexit(scr_builtin_error_prototype_cleanup); + } + return scr_dyn_retain(scr_builtin_error_prototype); +} + +/* Error.captureStackTrace(target): defines a non-enumerable own `stack` + * on target. Node's value is the Error.prototype.toString text of target + * (read without calling an overriding toString) followed by stack frames; + * here, as for scriptc's own Error instances, it is the text alone. + * Answers undefined, or NULL with the exception pending. */ +ScrDyn *scr_dyn_error_capture_stack_trace(ScrDyn *target) { + /* An instance of a class that extends Error derives its stack from its + * name and message when the stack is read. */ + if (target->kind == SCR_DYN_TYPED_REF) { + ScrDyn *view = scr_dyn_typed_ref_materialize(target); + bool error = view && view->kind == SCR_DYN_OBJ && scr_dyn_obj_get(view, "%error", 6) != NULL; + scr_dyn_release(view); + if (scr_exc_pending()) return NULL; + if (error) return scr_dyn_retain(scr_dyn_undefined()); + } + if (target->kind != SCR_DYN_OBJ) { + if (target->kind == SCR_DYN_ARR || target->kind == SCR_DYN_FUNC || target->kind == SCR_DYN_TYPED_REF || + target->kind == SCR_DYN_HANDLE || target->kind == SCR_DYN_PROXY) { + static const char message[] = "Error.captureStackTrace on this object is not supported yet"; + scr_throw_error_msg_code(SCR_ERR_ERROR, message, sizeof message - 1, "SC2020"); + } else { + static const char message[] = "invalid_argument"; + scr_throw_error_msg(SCR_ERR_TYPE, message, sizeof message - 1); + } + return NULL; + } + ScrDynEntry *existing = scr_dyn_find_entry(target, "stack", 5); + if (existing ? existing->accessor || !existing->configurable : target->non_extensible) { + static const char message[] = "Cannot redefine property: stack"; + static const char extensible[] = "Cannot define property stack, object is not extensible"; + if (existing) scr_throw_error_msg(SCR_ERR_TYPE, message, sizeof message - 1); + else scr_throw_error_msg(SCR_ERR_TYPE, extensible, sizeof extensible - 1); + return NULL; + } + ScrStr *text = scr_dyn_error_string(target); + if (!text) return NULL; + scr_dyn_obj_set_field(target, "stack", 5, scr_dyn_new_str(text)); + scr_str_release(text); + ScrDynEntry *entry = scr_dyn_find_entry(target, "stack", 5); + entry->enumerable = false; + entry->writable = entry->configurable = true; + return scr_dyn_retain(scr_dyn_undefined()); +} +static ScrDyn *scr_error_capture_stack_trace_call(ScrClosure *closure, ScrDyn *const *args, size_t argc) { + (void)closure; + return scr_dyn_error_capture_stack_trace(argc > 0 ? args[0] : scr_dyn_undefined()); +} +/* Error.captureStackTrace read as a value: one function per thread. */ +static SCR_TL ScrDyn *scr_error_capture_stack_trace_fn; +static void scr_error_capture_stack_trace_fn_cleanup(void) { + ScrDyn *function = scr_error_capture_stack_trace_fn; + scr_error_capture_stack_trace_fn = NULL; + scr_dyn_release(function); +} +ScrDyn *scr_dyn_error_capture_stack_trace_function(void) { + if (!scr_error_capture_stack_trace_fn) { + scr_error_capture_stack_trace_fn = scr_dyn_new_func(scr_closure_new(NULL, 0), + scr_error_capture_stack_trace_call, 2, "native:Error", "captureStackTrace"); + scr_atexit(scr_error_capture_stack_trace_fn_cleanup); + } + return scr_dyn_retain(scr_error_capture_stack_trace_fn); +} + +/* `value instanceof Error` for a value that is not an Error instance: true + * when Error.prototype is on its prototype chain. */ +bool scr_dyn_inherits_error_prototype(const ScrDyn *value) { + if (!scr_builtin_error_prototype || !value || value->kind != SCR_DYN_OBJ) return false; + for (const ScrDyn *current = scr_dyn_proto_next(value); current; current = scr_dyn_proto_next(current)) { + if (current == scr_builtin_error_prototype) return true; + } + return false; +} + ScrDyn *scr_dyn_new_arr(void) { return scr_dyn_alloc(SCR_DYN_ARR); } ScrDyn *scr_dyn_new_obj(void) { return scr_dyn_alloc(SCR_DYN_OBJ); } ScrDyn *scr_dyn_new_obj_with_identity( @@ -1847,7 +2061,6 @@ ScrDyn *scr_dyn_new_obj_null_proto(void) { } static const ScrDyn *scr_dyn_chain_link(const ScrDyn *link); -static const ScrDyn *scr_dyn_proto_next(const ScrDyn *object); /* A typed capsule can be a prototype when its checked view is an object. */ static bool scr_dyn_typed_ref_prototype(const ScrDyn *value) { @@ -1942,7 +2155,7 @@ ScrDyn *scr_dyn_set_prototype(ScrDyn *object, ScrDyn *prototype) { object->kind == SCR_DYN_BIGINT || object->kind == SCR_DYN_SYMBOL) { return scr_dyn_prototype_valid(prototype) ? scr_dyn_retain(object) : NULL; } - if (scr_dyn_class_reflection_fence(object) || scr_dyn_class_reflection_fence(prototype)) return NULL; + if (scr_dyn_class_reflection_fence(object) || scr_dyn_error_prototype_fence(object) || scr_dyn_class_reflection_fence(prototype)) return NULL; if (object->kind == SCR_DYN_TYPED_REF) { ScrDyn *view = scr_dyn_typed_ref_materialize(object); if (scr_exc_pending()) { scr_dyn_release(view); return NULL; } @@ -2058,7 +2271,7 @@ static ScrDyn *scr_dyn_fn_existing_table(const ScrDyn *function) { } ScrDyn *scr_dyn_prevent_extensions(ScrDyn *object) { - if (scr_dyn_class_reflection_fence(object)) return NULL; + if (scr_dyn_class_reflection_fence(object) || scr_dyn_error_prototype_fence(object)) return NULL; if (object->kind == SCR_DYN_PROXY) { scr_dyn_proxy_unsupported("Object.preventExtensions"); return NULL; } if (scr_dyn_class_integrity_fence(object, "Object.preventExtensions")) return NULL; ScrDyn *table = scr_dyn_fn_integrity_table(object); @@ -2089,7 +2302,7 @@ bool scr_dyn_is_extensible(ScrDyn *object) { } ScrDyn *scr_dyn_seal(ScrDyn *object) { - if (scr_dyn_class_reflection_fence(object)) return NULL; + if (scr_dyn_class_reflection_fence(object) || scr_dyn_error_prototype_fence(object)) return NULL; if (object->kind == SCR_DYN_PROXY) { scr_dyn_proxy_unsupported("Object.seal"); return NULL; } if (scr_dyn_class_integrity_fence(object, "Object.seal")) return NULL; if (object->symbol_properties) scr_dyn_release(scr_dyn_seal(object->symbol_properties)); @@ -3404,6 +3617,7 @@ const ScrStr *scr_dyn_typed_ref_class_name(const ScrDyn *d) { return ops ? ops->class_name : NULL; } + static bool scr_dyn_name_in_strs(const ScrStr *key, ScrStr *const *names, size_t count) { for (size_t i = 0; i < count; i++) { if (names[i] == key || scr_str_eq(names[i], (ScrStr *)key)) return true; @@ -3422,6 +3636,10 @@ static const ScrDynTypedRecordOps *scr_typed_ref_record_ops(const ScrDyn *d) { return (const ScrDynTypedRecordOps *)(const void *)d->v.typed_ref.array; } +const ScrDynTypedRecordOps *scr_dyn_typed_ref_live_record(const ScrDyn *d) { + return d->kind == SCR_DYN_TYPED_REF ? scr_typed_ref_record_ops(d) : NULL; +} + static bool scr_typed_ref_record_field(const ScrDynTypedRecordOps *ops, const ScrStr *key, size_t *out) { /* Compiled reads pass the interned literal the field names also use. */ @@ -3495,6 +3713,18 @@ ScrDyn *scr_dyn_index_get(const ScrDyn *d, double index) { } ScrDyn *scr_dyn_typed_ref_string_view(const ScrDyn *d) { + /* An instance of a class declared `extends Date` converts through its + * toString, declared or inherited. With an exception pending the view is + * the empty string. */ + double time; + if (scr_dyn_date_class_time(d, &time)) { + ScrDyn *text = scr_dyn_date_class_to_string(d); + if (text) return text; + ScrStr *empty = scr_str_new("", 0); + ScrDyn *out = scr_dyn_new_str(empty); + scr_str_release(empty); + return out; + } ScrDyn *view = scr_dyn_typed_ref_materialize(d); const char *tag = scr_event_ref_hooks ? scr_event_ref_hooks->string_tag(d) : NULL; if (!tag || view->kind != SCR_DYN_OBJ || scr_dyn_property_owner(view, "toString", 8)) return view; @@ -3515,12 +3745,28 @@ static ScrDyn *scr_typed_ref_numeric_property(const ScrDyn *d, double key) { return NULL; } +/* An inherited Date method of an instance of a class declared `extends + * Date`, when the instance's own members do not define `key`: +1, or + * NULL. */ +ScrDyn *scr_dyn_date_class_member(const ScrDyn *d, const char *key, size_t key_len) { + ScrDyn *method = scr_dyn_date_class_method(d, key, key_len); + if (!method) return NULL; + ScrDyn *view = scr_dyn_typed_ref_materialize(d); + bool declared = view && !scr_exc_pending() && scr_dyn_property_owner(view, key, key_len); + scr_dyn_release(view); + if (!declared) return method; + scr_dyn_release(method); + return NULL; +} + ScrDyn *scr_dyn_typed_ref_key_get(const ScrDyn *d, const ScrStr *key) { if (d->v.typed_ref.record) return scr_typed_ref_record_get(d, key); if (scr_event_ref_hooks) { ScrDyn *inherited = scr_event_ref_hooks->get(d, key); if (inherited) return inherited; } + ScrDyn *date_method = scr_dyn_date_class_member(d, key->data, key->len); + if (date_method) return date_method; if (!scr_dyn_typed_ref_array_ops(d)) return NULL; if (scr_typed_ref_is_length(key)) return scr_dyn_new_num((double)((ScrArr *)d->v.typed_ref.ptr)->len); double number; @@ -3777,7 +4023,37 @@ ScrDyn *scr_array_buffer_constructor(void) { return scr_dyn_retain(scr_array_buffer_ctor); } -bool scr_bytes_instanceof(const ScrDyn *value, const ScrDyn *callee) { +/* `value instanceof C` for C a global constructor held as a value + * (`{ instanceOf: Date }`, scr_dyn_global_constructor): 1 or 0 by the + * value's native kind, or -1 when callee is not one of them, or for Object + * and for class instances, which these kinds cannot answer (except Date, + * whose subclasses' instances are known). A typed record or array is none + * of these kinds. */ +static int scr_dyn_global_constructor_instanceof(const ScrDyn *value, const ScrDyn *callee) { + if (!callee->v.fn.sig || !callee->v.fn.name || strcmp(callee->v.fn.sig, "native:constructor") != 0 || + strcmp(callee->v.fn.name, "Object") == 0) + return -1; + /* A native Date, or an instance of a class declared `extends Date`. */ + if (strcmp(callee->v.fn.name, "Date") == 0) return scr_dyn_date_instance_is(value); + if (value->kind == SCR_DYN_TYPED_REF) + return strncmp(value->v.typed_ref.type_key, "record:", 7) == 0 || scr_dyn_ref_is_array(value) ? 0 : -1; + static const struct { const char *name; int tag; } kinds[] = { + {"Date", SCR_DYNH_DATE}, {"RegExp", SCR_DYNH_REGEXP}, {"Map", SCR_DYNH_MAP}, {"Set", SCR_DYNH_SET}, + {"WeakMap", SCR_DYNH_WEAK_MAP}, {"WeakSet", SCR_DYNH_WEAK_SET}, + {"FinalizationRegistry", SCR_DYNH_FINALIZATION_REGISTRY}, + }; + if (strcmp(callee->v.fn.name, "Promise") == 0) return value->kind == SCR_DYN_PROMISE; + for (size_t i = 0; i < sizeof kinds / sizeof kinds[0]; i++) { + if (strcmp(callee->v.fn.name, kinds[i].name) == 0) + return value->kind == SCR_DYN_HANDLE && (int)value->v.handle.tag == kinds[i].tag; + } + return -1; +} + +/* `value instanceof callee` for an untyped constructor value. `refusal`, when + * given, is the site's SC1090 message for a runtime constructor with no + * instance test. */ +bool scr_bytes_instanceof_at(const ScrDyn *value, const ScrDyn *callee, const ScrStr *refusal) { if (!callee || callee->kind != SCR_DYN_FUNC) { static const char message[] = "Right-hand side of 'instanceof' is not callable"; scr_throw_error_msg(SCR_ERR_TYPE, message, sizeof message - 1); @@ -3789,10 +4065,65 @@ bool scr_bytes_instanceof(const ScrDyn *value, const ScrDyn *callee) { if (scr_bytes_ctors[i] && callee->v.fn.clo == scr_bytes_ctors[i]->v.fn.clo) return scr_dyn_typed_array_is(value, (int)i); } + int global = scr_dyn_global_constructor_instanceof(value, callee); + if (global >= 0) return global; + /* An ordinary constructor function (an untyped JavaScript function whose + * prototype is an object): OrdinaryHasInstance walks the value's + * prototype chain for callee.prototype. */ + { + ScrStr *name = scr_str_new("prototype", 9); + ScrDyn *key = scr_dyn_new_str(name); + scr_str_release(name); + ScrDyn *prototype = scr_dyn_reflect_get((ScrDyn *)callee, key, (ScrDyn *)callee); + scr_dyn_release(key); + if (!prototype) return false; /* the read threw: pending */ + if (prototype->kind == SCR_DYN_OBJ) { + bool found = false; + if (value->kind == SCR_DYN_OBJ || value->kind == SCR_DYN_ARR || value->kind == SCR_DYN_FUNC) { + ScrDyn *current = scr_dyn_get_prototype((ScrDyn *)value); + while (current && current->kind != SCR_DYN_NULL) { + if (current == prototype) { + found = true; + break; + } + ScrDyn *next = scr_dyn_get_prototype(current); + scr_dyn_release(current); + current = next; + } + if (current) scr_dyn_release(current); + } + scr_dyn_release(prototype); + return found; + } + bool undefined_prototype = prototype->kind == SCR_DYN_UNDEF; + scr_dyn_release(prototype); + /* A function the program compiled with no prototype (an arrow function + * or a method): false for a primitive, and Node's TypeError for every + * object, typed arrays, native handles, promises and typed references + * included. The runtime's own constructors carry "native:" signatures. */ + if (undefined_prototype && (!callee->v.fn.sig || strncmp(callee->v.fn.sig, "native:", 7) != 0)) { + if (value->kind == SCR_DYN_UNDEF || value->kind == SCR_DYN_NULL || value->kind == SCR_DYN_BOOL || + value->kind == SCR_DYN_NUM || value->kind == SCR_DYN_STR || value->kind == SCR_DYN_BIGINT || + value->kind == SCR_DYN_SYMBOL) + return false; + static const char message[] = "Function has non-object prototype 'undefined' in instanceof check"; + scr_throw_error_msg(SCR_ERR_TYPE, message, sizeof message - 1); + return false; + } + } + if (refusal) { + scr_throw_error_msg_code(SCR_ERR_ERROR, refusal->data, refusal->len, "SC1090"); + return false; + } static const char message[] = "instanceof against this native constructor is not supported yet"; scr_throw_error_msg_code(SCR_ERR_ERROR, message, sizeof message - 1, "SC1090"); return false; } +bool scr_bytes_instanceof(const ScrDyn *value, const ScrDyn *callee) { + return scr_bytes_instanceof_at(value, callee, NULL); +} +SCR_TL bool (*scr_dyn_global_construct_fn)(const ScrDyn *callee, const ScrDyn *args, ScrDyn **result) = NULL; + ScrDyn *scr_bytes_construct(const ScrDyn *callee, const ScrDyn *args, const ScrStr *what) { if (callee->kind == SCR_DYN_FUNC && scr_array_ctor && callee->v.fn.clo == scr_array_ctor->v.fn.clo) return scr_array_ctor_call(callee->v.fn.clo, args->v.arr.items, args->v.arr.len); @@ -3809,6 +4140,9 @@ ScrDyn *scr_bytes_construct(const ScrDyn *callee, const ScrDyn *args, const ScrS scr_bytes_release(bytes); return result; } + ScrDyn *constructed = NULL; + if (scr_dyn_global_construct_fn && scr_dyn_global_construct_fn(callee, args, &constructed)) + return constructed; ScrJsonBuf message; scr_jb_init(&message); scr_jb_write(&message, what->data, what->len); @@ -3898,9 +4232,16 @@ ScrDyn *scr_dyn_new_func(ScrClosure *clo, ScrDynThunk thunk, uint32_t arity, con /* A signature adapter reports the length of the function it adapts. */ d->v.fn.arity = clo->identity != NULL ? clo->identity_length : arity; d->v.fn.class_obj = NULL; + d->v.fn.message = NULL; return d; } +void scr_dyn_func_set_message(ScrDyn *fn, ScrDynThunk thunk, ScrDynMessageListener listener) { + /* scr_dyn_new_func answers an adapted function's original box, whose + * closure has other parameter types. */ + if (fn && fn->kind == SCR_DYN_FUNC && fn->v.fn.thunk == thunk) fn->v.fn.message = listener; +} + /* A class is function-shaped for typeof and identity, but calling it without * new always throws. The closure owns the class object and its lexical boxes. */ static ScrDyn *scr_dyn_class_call(ScrClosure *closure, ScrDyn *const *args, size_t argc) { @@ -3956,6 +4297,11 @@ ScrDyn *scr_dyn_class_prototype(ScrDyn *value, ScrDyn *base) { if (!cls->prototype_data) { ScrDyn *data = base->kind == SCR_DYN_UNDEF ? scr_dyn_new_obj() : scr_dyn_obj_create(base); if (!data) return NULL; + /* util.inspect prints an instance with its class's name: the class + * object's interned name, which is immortal. The prototype is owned by + * the class object and no registry keeps it alive, so evaluating a + * function-local class again releases the previous one's prototype. */ + if (cls->name && cls->name->len) data->v.obj.class_name = cls->name->data; cls->prototype_data = scr_box_new_obj(scr_dyn_retain_v, scr_dyn_release_v, scr_dyn_trace_v); scr_box_set_ref(cls->prototype_data, data); } @@ -4378,6 +4724,7 @@ ScrDyn *scr_dyn_new_handle(void *h, ScrDynHandleTag tag) { d->v.handle.tag = tag; d->v.handle.traced = tag == SCR_DYNH_WEAK_MAP || tag == SCR_DYNH_WEAK_SET || tag == SCR_DYNH_WORKER || tag == SCR_DYNH_MESSAGE_PORT || tag == SCR_DYNH_DISPOSABLE_STACK || + tag == SCR_DYNH_CIPHER || tag == SCR_DYNH_DECIPHER || ((tag == SCR_DYNH_SET || tag == SCR_DYNH_MAP) && ((ScrMap *)h)->traced != 0); return d; @@ -6260,6 +6607,7 @@ void scr_dyn_symbol_key_placeholder(ScrDyn *value, ScrDyn *key) { } void scr_dyn_symbol_key_set(ScrDyn *value, ScrDyn *key, ScrDyn *stored) { + if (scr_dyn_error_prototype_fence(value)) return; ScrDyn *receiver = scr_dyn_symbol_receiver(value); if (!receiver) { if (!scr_exc_pending()) { @@ -6410,6 +6758,7 @@ static bool scr_dyn_fn_property_fence(const ScrStr *key) { } ScrDyn *scr_dyn_define_property(ScrDyn *target, ScrDyn *key, ScrDyn *descriptor) { + if (scr_dyn_error_prototype_fence(target)) return NULL; if (target->kind == SCR_DYN_TYPED_REF && scr_dyn_typed_ref_array_ops(target) && key->kind == SCR_DYN_STR) { /* A native array's numeric properties ("-1", "1.5") live in its * property table, which holds values without attributes. */ @@ -6802,6 +7151,7 @@ ScrStr *scr_dyn_object_tag(const ScrDyn *d) { d->v.handle.tag <= SCR_DYNH_ABORT_CONTROLLER) || d->v.handle.tag == SCR_DYNH_EVENT_TARGET || d->v.handle.tag == SCR_DYNH_CUSTOM_EVENT || d->v.handle.tag == SCR_DYNH_ARRAY_BUFFER || d->v.handle.tag == SCR_DYNH_SHARED_ARRAY_BUFFER || d->v.handle.tag == SCR_DYNH_WEAK_MAP || d->v.handle.tag == SCR_DYNH_WEAK_SET || + d->v.handle.tag == SCR_DYNH_FINALIZATION_REGISTRY || d->v.handle.tag == SCR_DYNH_SET || d->v.handle.tag == SCR_DYNH_MAP || d->v.handle.tag == SCR_DYNH_REGEXP || d->v.handle.tag == SCR_DYNH_DATE || d->v.handle.tag == SCR_DYNH_BLOB || d->v.handle.tag == SCR_DYNH_FILE || d->v.handle.tag == SCR_DYNH_DISPOSABLE_STACK) { @@ -7783,6 +8133,17 @@ ScrStr *scr_dyn_to_string(const ScrDyn *d, const ScrStr *enc) { return out; } case SCR_DYN_FUNC: { + /* The interned builtin constructors print with their names, as in Node + * (function Map() { [native code] }); other functions without a source + * text print the anonymous native form. */ + if (d->v.fn.sig && strcmp(d->v.fn.sig, "native:constructor") == 0 && d->v.fn.name) { + ScrJsonBuf b; + scr_jb_init(&b); + scr_jb_puts(&b, "function "); + scr_jb_puts(&b, d->v.fn.name); + scr_jb_puts(&b, "() { [native code] }"); + return scr_jb_finish(&b); + } static const char f[] = "function () { [native code] }"; return scr_str_new(f, sizeof f - 1); } @@ -7805,6 +8166,9 @@ ScrStr *scr_dyn_to_string(const ScrDyn *d, const ScrStr *enc) { } } +static ScrStr *scr_dyn_to_string_method_args(const ScrDyn *d, const ScrStr *enc, const ScrStr *what, + ScrDyn *const *args, size_t argc); + /* The METHOD-CALL spelling `d.toString(enc?)` — scr_dyn_to_string with * the one receiver whose prototype LACKS the method carved out: a * null-prototype dictionary (Object.create(null)) has no toString at @@ -7834,7 +8198,10 @@ ScrStr *scr_dyn_to_string_argument(const ScrDyn *d, const ScrDyn *argument, cons scr_throw_error(SCR_ERR_TYPE, scr_jb_finish(&b)); return scr_str_new("", 0); } - return scr_dyn_to_string_method(d, NULL, what); + /* A toString the program defines receives the argument + * (`error.toString(compact)`); undefined passes none. */ + ScrDyn *args[1] = {(ScrDyn *)argument}; + return scr_dyn_to_string_method_args(d, NULL, what, args, argument->kind == SCR_DYN_UNDEF ? 0 : 1); } /* The METHOD-CALL spelling `d.valueOf()`: a primitive answers itself (the @@ -8074,7 +8441,12 @@ bool scr_dyn_number_coerce_js(const ScrDyn *d, double *out) { return false; } if (d->kind == SCR_DYN_TYPED_REF) { - ScrDyn *materialized = scr_dyn_typed_ref_materialize(d); + /* An instance of a class declared `extends Date` converts through its + * valueOf, declared or inherited. */ + double time; + ScrDyn *materialized = scr_dyn_date_class_time(d, &time) ? scr_dyn_date_class_value_of(d) + : scr_dyn_typed_ref_materialize(d); + if (!materialized) return false; bool ok = scr_dyn_number_coerce_js(materialized, out); scr_dyn_release(materialized); return ok; @@ -8177,9 +8549,18 @@ double scr_dyn_number_coerce(const ScrDyn *d) { static ScrDyn *scr_dyn_add_primitive(const ScrDyn *d); /* ToPrimitive with the number hint, which differs from the default hint - * only for a Date: its time value. */ + * only for a Date: its time value, or the valueOf of an instance of a class + * declared `extends Date`. */ static ScrDyn *scr_dyn_number_primitive(const ScrDyn *d) { - return scr_dyn_is_date(d) ? scr_dyn_date_value_of(d) : scr_dyn_add_primitive(d); + if (scr_dyn_is_date(d)) return scr_dyn_date_value_of(d); + double time; + if (d->kind == SCR_DYN_TYPED_REF && scr_dyn_date_class_time(d, &time)) { + ScrDyn *value = scr_dyn_date_class_value_of(d); + ScrDyn *out = value ? scr_dyn_add_primitive(value) : NULL; + scr_dyn_release(value); + return out; + } + return scr_dyn_add_primitive(d); } double scr_dyn_number_constructor(const ScrDyn *d) { @@ -8240,6 +8621,15 @@ static ScrDyn *scr_dyn_add_primitive(const ScrDyn *d) { return NULL; } if (d->kind == SCR_DYN_TYPED_REF) { + /* A Date's default hint is string: an instance of a class declared + * `extends Date` adds through its toString. */ + double time; + if (scr_dyn_date_class_time(d, &time)) { + ScrDyn *text = scr_dyn_date_class_to_string(d); + ScrDyn *out = text ? scr_dyn_add_primitive(text) : NULL; + scr_dyn_release(text); + return out; + } ScrDyn *view = scr_dyn_typed_ref_materialize(d); ScrDyn *out = scr_exc_pending() ? NULL : scr_dyn_add_primitive(view); scr_dyn_release(view); @@ -8659,7 +9049,7 @@ void scr_dyn_arr_named_put(ScrDyn *arr, const char *key, size_t key_len, ScrDyn } void scr_dyn_key_set(ScrDyn *recv, ScrStr *key, ScrDyn *value) { - if (scr_dyn_class_reflection_fence(recv)) return; + if (scr_dyn_class_reflection_fence(recv) || scr_dyn_error_prototype_fence(recv)) return; if (recv->kind == SCR_DYN_PROXY) { scr_dyn_proxy_set(recv, key, value); return; } if (recv->kind == SCR_DYN_TYPED_REF) { if (scr_typed_ref_array_set(recv, key, value)) return; @@ -10435,8 +10825,9 @@ static bool scr_json_callback_depth(size_t depth) { static ScrStr *scr_json_index_key(size_t index) { char bytes[32]; - int length = snprintf(bytes, sizeof bytes, "%zu", index); - return scr_str_new(bytes, (size_t)length); + /* array indexes are below 2^32: exact doubles, printed as integers */ + size_t length = scr_f64_to_str((double)index, bytes); + return scr_str_new(bytes, length); } /* Keys passed here come from our own index formatter or own-key walk. */ @@ -10487,7 +10878,7 @@ static void scr_json_delete_member(ScrDyn *object, const ScrStr *key) { * arrays, typed references and handles keep their explicit boundary; * deleting from a materialized snapshot would lose the mutation. */ void scr_dyn_key_delete(ScrDyn *recv, const ScrStr *key, bool strict) { - if (scr_dyn_class_reflection_fence(recv)) return; + if (scr_dyn_class_reflection_fence(recv) || scr_dyn_error_prototype_fence(recv)) return; if (recv->kind == SCR_DYN_PROXY) { scr_dyn_proxy_delete(recv, key); return; } if (recv->kind == SCR_DYN_TYPED_REF && recv->v.typed_ref.commit && (!strncmp(recv->v.typed_ref.type_key, "record:", 7) || @@ -10712,7 +11103,27 @@ static bool scr_json_live_container(const ScrDyn *value, bool inspect) { * { type, data } view, and an object with a callable toJSON through that * method, called with the key. Returns the value to serialize (+1), or NULL * with an exception pending. */ -static ScrDyn *scr_json_to_json(ScrDyn *value, const ScrStr *key) { +/* The toJSON key argument: `key`, or the decimal spelling of array index + * `index` when `key` is NULL (formed only for a call that receives it). */ +static ScrDyn *scr_json_key_arg(const ScrStr *key, size_t index) { + if (key) return scr_dyn_new_str((ScrStr *)key); + ScrStr *text = scr_json_index_key(index); + ScrDyn *name = scr_dyn_new_str(text); + scr_str_release(text); + return name; +} + +static ScrDyn *scr_json_to_json_at(ScrDyn *value, const ScrStr *key, size_t index) { + /* An instance of a class declared `extends Date` converts through its + * toJSON, declared or inherited. */ + double time; + if (value->kind == SCR_DYN_TYPED_REF && scr_dyn_date_class_time(value, &time)) { + ScrDyn *name = scr_json_key_arg(key, index); + ScrDyn *converted = scr_dyn_date_class_to_json(value, name); + scr_dyn_release(name); + scr_dyn_release(value); + return converted; + } /* Inspect a typed reference without replacing its live identity. Later * members must read the source again after a callback mutates it. A live * array, or a live record without a `toJSON` field, needs no conversion. */ @@ -10735,7 +11146,7 @@ static ScrDyn *scr_json_to_json(ScrDyn *value, const ScrStr *key) { ScrDyn *method = scr_dyn_obj_read(inspected, "toJSON", 6); if (!method) { scr_dyn_release(view); scr_dyn_release(value); return NULL; } if (method->kind == SCR_DYN_FUNC) { - ScrDyn *name = scr_dyn_new_str((ScrStr *)key); + ScrDyn *name = scr_json_key_arg(key, index); ScrDyn *args[] = { name }; scr_dyn_this_push_dyn(value); ScrDyn *converted = scr_dyn_call(method, args, 1, "toJSON"); @@ -10750,6 +11161,10 @@ static ScrDyn *scr_json_to_json(ScrDyn *value, const ScrStr *key) { return value; } +static ScrDyn *scr_json_to_json(ScrDyn *value, const ScrStr *key) { + return scr_json_to_json_at(value, key, 0); +} + static ScrDyn *scr_json_replace(const ScrDyn *holder, const ScrStr *key, const ScrDyn *replacer) { ScrDyn *value = scr_json_member(holder, key); if (!value) return NULL; @@ -10884,6 +11299,81 @@ static ScrDyn *scr_json_property_list(const ScrDyn *replacer) { return list; } +/* The protocol walk over a live record or array capsule without a replacer + * (the caller entered it on the circular-structure stack). Members are read + * from the native value exactly as scr_json_member reads them, but the walk + * needs no key list: a record's present fields are snapshotted by index (its + * keys are the immortal field names) and an array's indexes are counted, so + * an index key string is formed only for a toJSON call that receives it. */ +static bool scr_json_live_write(ScrJsonBuf *buffer, const ScrDyn *value, bool array, + const ScrStr *gap, size_t depth) { + const ScrDynTypedRecordOps *record = array ? NULL : scr_typed_ref_record_ops(value); + /* EnumerableOwnProperties runs once, before any member's toJSON (the + * caller sends records of more than 64 fields down the key-list walk). */ + uint64_t present = 0; + size_t length; + if (array) { + length = ((ScrArr *)value->v.typed_ref.ptr)->len; + } else { + length = record->count; + for (size_t i = 0; i < length; i++) + if (record->fixed || record->has(value->v.typed_ref.ptr, i)) present |= (uint64_t)1 << i; + } + scr_jb_putc(buffer, array ? '[' : '{'); + bool first = true; + for (size_t i = 0; i < length; i++) { + if (!array && !(present & ((uint64_t)1 << i))) continue; + const ScrStr *key = array ? NULL : record->names[i]; + ScrDyn *child; + if (array) { + scr_jb_edge_idx(buffer, i); + /* scr_json_member's index read, minus the key: a present element + * answers directly; holes, a length a callback shrank, a capsule a + * callback materialized and inherited event members take the keyed + * read */ + child = !scr_event_ref_hooks && scr_dyn_typed_ref_array_ops(value) ? scr_dyn_typed_ref_element(value, i) + : NULL; + if (!child) { + ScrStr *index = scr_json_index_key(i); + child = scr_json_member(value, index); + scr_str_release(index); + } + } else { + scr_jb_edge_key(buffer, key); + child = scr_json_member(value, key); + } + if (child) child = scr_json_to_json_at(child, key, i); + if (!child) return false; + if (!array && scr_json_omitted(child)) { + scr_dyn_release(child); + continue; + } + if (!first) scr_jb_putc(buffer, ','); + first = false; + scr_json_gap(buffer, gap, depth + 1); + if (!array) { + scr_jb_put_json_str(buffer, key); + scr_jb_putc(buffer, ':'); + if (gap->len) scr_jb_putc(buffer, ' '); + } + bool ok = true; + if (scr_json_omitted(child)) scr_jb_puts(buffer, "null"); + else if (scr_json_plain_value(child)) { + /* the protocol walk's depth check, then the primitive itself */ + ok = scr_json_callback_depth(depth + 1); + if (ok) { + scr_dyn_json_write(buffer, child); + ok = !scr_exc_pending(); + } + } else ok = scr_json_replaced_write(buffer, child, scr_dyn_undefined(), NULL, gap, depth + 1); + scr_dyn_release(child); + if (!ok) return false; + } + if (!first) scr_json_gap(buffer, gap, depth); + scr_jb_putc(buffer, array ? ']' : '}'); + return true; +} + /* `properties`, when present, is an array replacer's PropertyList: objects * serialize exactly those keys, own or inherited, in that order; arrays * keep all their indexes. */ @@ -10913,6 +11403,12 @@ static bool scr_json_replaced_write(ScrJsonBuf *buffer, const ScrDyn *value, * after the current frame leaves the traversal stack. */ const void *identity = view || live ? value->v.typed_ref.ptr : (const void *)value; if (!scr_jb_enter(buffer, identity, array)) { scr_dyn_release(view); return false; } + if (live && replacer->kind == SCR_DYN_UNDEF && !properties && + (array || scr_typed_ref_record_ops(value)->count <= 64)) { + bool ok = scr_json_live_write(buffer, value, array, gap, depth); + scr_jb_leave(buffer); + return ok; + } scr_jb_putc(buffer, array ? '[' : '{'); ScrDyn *keys = array ? NULL : properties ? scr_dyn_retain((ScrDyn *)properties) : scr_dyn_obj_keys(observed); if (scr_exc_pending()) { scr_dyn_release(keys); scr_dyn_release(view); scr_jb_leave(buffer); return false; } @@ -11736,21 +12232,18 @@ static ScrDyn *scr_dyn_obj_read_receiver(const ScrDyn *d, const char *key, size_ ScrDyn *own = scr_dyn_obj_get(d, key, key_len); if (own) return scr_dyn_retain(own); if (key_len == 11 && memcmp(key, "constructor", 11) == 0) { - static const char *const tokens[] = { - "[builtin Error]", "[builtin TypeError]", - "[builtin RangeError]", "[builtin SyntaxError]", - NULL, "[builtin ReferenceError]", "[builtin EvalError]", "[builtin URIError]", - "[builtin AggregateError]", + /* An error's constructor: the interned function value its global + * reads as (scr_dyn_error_constructor). */ + static const char *const names[] = { + "Error", "TypeError", "RangeError", "SyntaxError", NULL, + "ReferenceError", "EvalError", "URIError", "AggregateError", }; size_t hit = scr_errdyn_find(d, false); const ScrVt *vt = hit == SIZE_MAX ? NULL : scr_errdyn_cache[hit].err->vt; - for (size_t kind = 0; vt && kind < sizeof tokens / sizeof tokens[0]; kind++) { - if (!tokens[kind]) continue; + for (size_t kind = 0; vt && kind < sizeof names / sizeof names[0]; kind++) { + if (!names[kind]) continue; if (vt != &scr_error_vts[kind]) continue; - ScrStr *token = scr_str_new(tokens[kind], strlen(tokens[kind])); - ScrDyn *result = scr_dyn_new_str(token); - scr_str_release(token); - return result; + return scr_dyn_error_constructor(names[kind]); } } return scr_dyn_retain(scr_dyn_undefined()); @@ -12905,7 +13398,7 @@ static void scr_dyn_assign_from(ScrDyn *target, const ScrDyn *src, bool define) * nothing; index-keyed sources (arrays/strings/bytes) copy their index * keys like Node; the remaining kinds have no own enumerable keys. */ ScrDyn *scr_dyn_assign(ScrDyn *target, const ScrDyn *src) { - if (scr_dyn_class_reflection_fence(target) || scr_dyn_class_reflection_fence(src)) return NULL; + if (scr_dyn_class_reflection_fence(target) || scr_dyn_error_prototype_fence(target) || scr_dyn_class_reflection_fence(src)) return NULL; if (target->kind == SCR_DYN_UNDEF || target->kind == SCR_DYN_NULL) { const char *m = "Cannot convert undefined or null to object"; scr_throw_error_msg(SCR_ERR_TYPE, m, strlen(m)); @@ -14142,7 +14635,8 @@ static int scr_weak_key(const ScrDyn *key, void **ptr, unsigned *kind) { *kind = key->v.fn.class_obj ? 3 : 2; return 1; case SCR_DYN_HANDLE: if (key->v.handle.tag != SCR_DYNH_ARRAY_BUFFER && key->v.handle.tag != SCR_DYNH_SHARED_ARRAY_BUFFER && key->v.handle.tag != SCR_DYNH_WEAK_MAP && - key->v.handle.tag != SCR_DYNH_WEAK_SET && key->v.handle.tag != SCR_DYNH_STDIO && + key->v.handle.tag != SCR_DYNH_WEAK_SET && key->v.handle.tag != SCR_DYNH_FINALIZATION_REGISTRY && + key->v.handle.tag != SCR_DYNH_STDIO && key->v.handle.tag != SCR_DYNH_FETCH_REQUEST && key->v.handle.tag != SCR_DYNH_FETCH_RESPONSE && key->v.handle.tag != SCR_DYNH_MAP && key->v.handle.tag != SCR_DYNH_SET && key->v.handle.tag != SCR_DYNH_NET_SOCKET && key->v.handle.tag != SCR_DYNH_NET_SERVER) return -1; @@ -14321,6 +14815,159 @@ bool scr_weak_set_is(const ScrDyn *value) { ScrDyn *scr_weak_map_new(ScrDyn *seed) { return scr_weak_collection_new(seed, false); } ScrDyn *scr_weak_set_new(ScrDyn *seed) { return scr_weak_collection_new(seed, true); } +/* FinalizationRegistry. register() and unregister() validate and keep their + * bookkeeping as Node does; the cleanup callback never runs, which + * ECMAScript allows (an implementation need not collect a target or call + * its cleanup), so the registry keeps neither the callback nor the held + * values. The unregister tokens are keys of an internal WeakMap counting + * each token's registrations, so the registry keeps no token alive. */ +typedef struct { + size_t rc; + ScrDyn *tokens; /* WeakMap: token -> registration count */ +} ScrFinalizationRegistry; + +static void *scr_finalization_registry_retain(void *ptr) { + ((ScrFinalizationRegistry *)ptr)->rc++; + return ptr; +} + +static void scr_finalization_registry_release(void *ptr) { + ScrFinalizationRegistry *registry = ptr; + if (--registry->rc) return; + /* Weak collections keyed by the registry drop their entries. */ + scr_weak_dispose(registry); + scr_dyn_release(registry->tokens); + free(registry); +} + +static void scr_finalization_type_error(const char *message) { + scr_throw_error_msg(SCR_ERR_TYPE, message, strlen(message)); +} + +/* The weak-key identity of a registration target or token, or false with + * the TypeError (or the SC2020 refusal) pending. */ +static bool scr_finalization_key(const ScrDyn *value, void **ptr, unsigned *kind, + const char *invalid) { + if (value->kind == SCR_DYN_SYMBOL) { + static const char message[] = "FinalizationRegistry with symbol targets or tokens is not supported yet"; + scr_throw_error_msg_code(SCR_ERR_ERROR, message, sizeof message - 1, "SC2020"); + return false; + } + int supported = scr_weak_key(value, ptr, kind); + if (supported < 0) { + static const char message[] = "FinalizationRegistry targets of this native reference type have no weak lifetime lowering"; + scr_throw_error_msg_code(SCR_ERR_ERROR, message, sizeof message - 1, "SC2020"); + return false; + } + if (!supported) { + if (invalid) { + scr_finalization_type_error(invalid); + } else { + /* Node's unregister message quotes the token as String() renders it. */ + ScrStr *text = scr_dyn_string_coerce(value); + ScrJsonBuf b; + scr_jb_init(&b); + scr_jb_puts(&b, "Invalid unregisterToken ('"); + if (text) scr_jb_write(&b, text->data, text->len); + scr_jb_puts(&b, "')"); + scr_str_release(text); + ScrStr *message = scr_jb_finish(&b); + scr_throw_error_msg(SCR_ERR_TYPE, message->data, message->len); + scr_str_release(message); + } + return false; + } + return true; +} + +static ScrDyn *scr_finalization_registry_invoke(void *ptr, ScrDyn *self, const char *method, + ScrDyn *const *args, size_t argc, const char *what) { + (void)self; + ScrFinalizationRegistry *registry = ptr; + ScrWeakMap *tokens = registry->tokens->v.handle.ptr; + ScrDyn *first = argc > 0 ? args[0] : scr_dyn_undefined(); + void *identity = NULL; + unsigned kind = 0; + if (strcmp(method, "register") == 0) { + ScrDyn *held = argc > 1 ? args[1] : scr_dyn_undefined(); + ScrDyn *token = argc > 2 ? args[2] : scr_dyn_undefined(); + if (!scr_finalization_key(first, &identity, &kind, "FinalizationRegistry.prototype.register: invalid target")) + return NULL; + if (scr_dyn_strict_eq(first, held)) { + scr_finalization_type_error("FinalizationRegistry.prototype.register: target and holdings must not be same"); + return NULL; + } + if (token->kind != SCR_DYN_UNDEF) { + if (!scr_finalization_key(token, &identity, &kind, NULL)) return NULL; + ScrWeakEntry *entry = scr_weak_find(tokens, identity, kind); + double count = entry && entry->value->kind == SCR_DYN_NUM ? entry->value->v.num : 0; + ScrDyn *next = scr_dyn_new_num(count + 1); + bool ok = scr_weak_set(tokens, token, next); + scr_dyn_release(next); + if (!ok) return NULL; + } + return scr_dyn_retain(scr_dyn_undefined()); + } + if (strcmp(method, "unregister") == 0) { + if (!scr_finalization_key(first, &identity, &kind, NULL)) return NULL; + ScrWeakEntry *entry = scr_weak_find(tokens, identity, kind); + if (entry) scr_weak_remove(entry); + return scr_dyn_new_bool(entry != NULL); + } + ScrJsonBuf b; + scr_jb_init(&b); + scr_jb_puts(&b, what ? what : method); + scr_jb_puts(&b, " is not a function"); + ScrStr *message = scr_jb_finish(&b); + scr_throw_error_msg(SCR_ERR_TYPE, message->data, message->len); + scr_str_release(message); + return NULL; +} + +/* A property read answers undefined for names the registry does not have. + * Its methods read as values (`const register = registry.register`) are + * refused, as a weak collection's are. */ +static ScrDyn *scr_finalization_registry_get(void *ptr, const char *key, size_t len) { + (void)ptr; + if ((len == 8 && memcmp(key, "register", 8) == 0) || (len == 10 && memcmp(key, "unregister", 10) == 0)) { + static const char message[] = "FinalizationRegistry method values have no native lowering"; + scr_throw_error_msg_code(SCR_ERR_ERROR, message, sizeof message - 1, "SC2020"); + } + return NULL; +} + +static ScrDyn *scr_finalization_registry_view(void *ptr) { + (void)ptr; + return scr_dyn_new_obj(); +} + +ScrDyn *scr_finalization_registry_new(ScrDyn *cleanup) { + if (!scr_dyn_is_callable(cleanup)) { + scr_finalization_type_error("FinalizationRegistry: cleanup must be callable"); + return NULL; + } + static const ScrDynHandleOps ops = { + .cls = "FinalizationRegistry", + .retain = &scr_finalization_registry_retain, + .release = &scr_finalization_registry_release, + .invoke = &scr_finalization_registry_invoke, + .get = &scr_finalization_registry_get, + .inspect_view = &scr_finalization_registry_view, + .inspect_view_empty = true, + }; + scr_dyn_handle_install(SCR_DYNH_FINALIZATION_REGISTRY, &ops); + ScrFinalizationRegistry *registry = calloc(1, sizeof *registry); + if (!registry) scr_json_oom(); + registry->tokens = scr_weak_collection_new(scr_dyn_undefined(), false); + if (!registry->tokens) { free(registry); return NULL; } + ScrDyn *result = scr_dyn_new_handle(registry, SCR_DYNH_FINALIZATION_REGISTRY); + return result; +} + +bool scr_finalization_registry_is(const ScrDyn *value) { + return value->kind == SCR_DYN_HANDLE && value->v.handle.tag == SCR_DYNH_FINALIZATION_REGISTRY; +} + ScrDyn *scr_dyn_from_entries(ScrDyn *seed) { if (seed->kind == SCR_DYN_UNDEF || seed->kind == SCR_DYN_NULL) { static const char message[] = "undefined is not iterable"; @@ -14561,7 +15208,7 @@ ScrDyn *scr_dyn_native_set(ScrMap *value) { ScrDyn *scr_dyn_native_set_new(const ScrDyn *seed) { ScrDyn *items = NULL; if (seed->kind != SCR_DYN_NULL && seed->kind != SCR_DYN_UNDEF) { - items = scr_dyn_iter_pack(seed, NULL); + items = scr_dyn_seed_values(seed); if (!items) return NULL; } ScrMap *set = scr_map_new(SCR_MAP_KEY_DYN, SCR_MAP_VAL_F64, &scr_map_dyn_set_ops); @@ -14675,6 +15322,27 @@ ScrDyn *scr_dyn_native_map(ScrMap *value) { return scr_dyn_new_handle(value, SCR_DYNH_MAP); } +ScrDyn *scr_dyn_native_map_new(const ScrDyn *seed) { + ScrDyn *entries = scr_dyn_map_seed_entries(seed); + if (!entries) return NULL; + ScrMap *map = scr_map_new(SCR_MAP_KEY_DYN, SCR_MAP_VAL_REF, &scr_map_dyn_map_ops); + for (size_t i = 0; i < entries->v.arr.len; i++) { + ScrDyn *entry = scr_dyn_map_seed_entry(entries->v.arr.items[i]); + if (!entry) break; + ScrDyn *key = scr_dyn_entry_read(entry, 0); + ScrDyn *value = scr_exc_pending() ? NULL : scr_dyn_entry_read(entry, 1); + scr_dyn_release(entry); + if (value) scr_map_dyn_set(map, key, value, false); + scr_dyn_release(key); + scr_dyn_release(value); + if (scr_exc_pending()) break; + } + scr_dyn_release(entries); + ScrDyn *result = scr_exc_pending() ? NULL : scr_dyn_native_map(map); + scr_map_release(map); + return result; +} + bool scr_dyn_native_map_is(const ScrDyn *value) { return value && value->kind == SCR_DYN_HANDLE && value->v.handle.tag == SCR_DYNH_MAP; } @@ -14699,7 +15367,10 @@ ScrMap *scr_dyn_native_collection_check(const ScrDyn *value, int map, const char return scr_map_retain(value->v.handle.ptr); } -ScrStr *scr_dyn_to_string_method(const ScrDyn *d, const ScrStr *enc, const ScrStr *what) { +/* scr_dyn_to_string_method, passing `args` to a toString the receiver's + * chain defines. */ +static ScrStr *scr_dyn_to_string_method_args(const ScrDyn *d, const ScrStr *enc, const ScrStr *what, + ScrDyn *const *args, size_t argc) { /* Object.create receivers must run their inherited formatter before the * default object tag; Effect shard keys use it to produce distinct hashes. */ const bool object_method = d->kind == SCR_DYN_OBJ && scr_dyn_property_owner(d, "toString", 8); @@ -14708,7 +15379,7 @@ ScrStr *scr_dyn_to_string_method(const ScrDyn *d, const ScrStr *enc, const ScrSt if (scr_exc_pending()) { scr_dyn_release(member); return NULL; } if (member && (object_method || member->kind != SCR_DYN_UNDEF)) { scr_dyn_this_push_dyn(d); - ScrDyn *value = scr_dyn_call(member, NULL, 0, what->data); + ScrDyn *value = scr_dyn_call(member, args, argc, what->data); scr_dyn_this_pop(); scr_dyn_release(member); if (!value) return NULL; @@ -14730,8 +15401,12 @@ ScrStr *scr_dyn_to_string_method(const ScrDyn *d, const ScrStr *enc, const ScrSt return scr_dyn_to_string(d, enc); } +ScrStr *scr_dyn_to_string_method(const ScrDyn *d, const ScrStr *enc, const ScrStr *what) { + return scr_dyn_to_string_method_args(d, enc, what, NULL, 0); +} + ScrDyn *scr_dyn_freeze(ScrDyn *value) { - if (scr_dyn_class_reflection_fence(value)) return NULL; + if (scr_dyn_class_reflection_fence(value) || scr_dyn_error_prototype_fence(value)) return NULL; if (scr_dyn_class_integrity_fence(value, "Object.freeze")) return NULL; ScrDyn *table = scr_dyn_fn_integrity_table(value); if (!table) return scr_dyn_freeze_data(value); @@ -14742,7 +15417,7 @@ ScrDyn *scr_dyn_freeze(ScrDyn *value) { } ScrDyn *scr_dyn_freeze_data(ScrDyn *value) { - if (scr_dyn_class_reflection_fence(value)) return NULL; + if (scr_dyn_class_reflection_fence(value) || scr_dyn_error_prototype_fence(value)) return NULL; if (scr_dyn_class_integrity_fence(value, "Object.freeze")) return NULL; if (value->symbol_properties) scr_dyn_release(scr_dyn_freeze_data(value->symbol_properties)); if (value->kind == SCR_DYN_ARR) { diff --git a/packages/runtime/src/scr_lib.c b/packages/runtime/src/scr_lib.c index ee4c34592..c17f44f9d 100644 --- a/packages/runtime/src/scr_lib.c +++ b/packages/runtime/src/scr_lib.c @@ -9225,6 +9225,10 @@ ScrCryptoHash *scr_crypto_hmac_new_dyn(ScrStr *alg, ScrDyn *key, ScrDyn *options if (key_object) { bytes = scr_bytes_new(SCR_BYTES_U8, (double)key_object_len); if (key_object_len) memcpy(bytes->data, key_object, key_object_len); + } else if (scr_crypto_is_key_object(key)) { + /* A private or public KeyObject: scr_pki.c reports Node's error. */ + scr_crypto_reject_asymmetric_secret(key); + return NULL; } else if (key->kind == SCR_DYN_STR) { ScrStr *utf8 = encoding ? NULL : scr_str_new("utf8", 4); bytes = scr_bytes_from_str_checked(key->v.str, encoding ? encoding : utf8); @@ -9856,9 +9860,15 @@ const unsigned char *scr_key_object_bytes(const ScrDyn *value, size_t *len) { return key->data; } -/* `value instanceof KeyObject`. */ +void (*scr_crypto_reject_asymmetric_secret)(const ScrDyn *key) = NULL; + +/* `value instanceof KeyObject`: a secret key, or a private or public key + * (scr_pki.c, matched by its handle tags so this unit does not link it). */ bool scr_crypto_is_key_object(const ScrDyn *value) { size_t len; + if (value->kind == SCR_DYN_HANDLE && + (value->v.handle.tag == SCR_DYNH_PRIVATE_KEY || value->v.handle.tag == SCR_DYNH_PUBLIC_KEY)) + return true; return scr_key_object_bytes(value, &len) != NULL; } @@ -12951,50 +12961,51 @@ static bool scr_set_to_arr_sparse(const ScrMap *s, ScrArr *out) { ScrArr *scr_set_to_arr_f64(const ScrMap *s) { ScrArr *out = scr_arr_new(SCR_ELEM_F64, s->nlive); if (scr_set_to_arr_sparse(s, out)) return out; - uint8_t *states = scr_arr_states_end(out); + /* A fresh array without states: the values in order. */ for (size_t i = 0; i < s->nentries; i++) { if (!scr_map_entry_live(s, i)) continue; - out->data[out->len] = scr_map_entry_at(s, i)->key; - *scr_arr_state_in(states, out->len++) = SCR_ARR_VALUE; + out->data[out->len++] = scr_map_entry_at(s, i)->key; } + scr_arr_refill(out); return out; } ScrArr *scr_set_to_arr_bool(const ScrMap *s) { ScrArr *out = scr_arr_new(SCR_ELEM_BOOL, s->nlive); if (scr_set_to_arr_sparse(s, out)) return out; - uint8_t *states = scr_arr_states_end(out); + /* A fresh array without states: the values in order. */ for (size_t i = 0; i < s->nentries; i++) { if (!scr_map_entry_live(s, i)) continue; - scr_arr_dense_put(out, out->len, scr_map_entry_at(s, i)->key != 0); - *scr_arr_state_in(states, out->len++) = SCR_ARR_VALUE; + scr_arr_dense_put(out, out->len++, scr_map_entry_at(s, i)->key != 0); } + scr_arr_refill(out); return out; } ScrArr *scr_set_to_arr_str(const ScrMap *s) { ScrArr *out = scr_arr_new(SCR_ELEM_STR, s->nlive); if (scr_set_to_arr_sparse(s, out)) return out; - uint8_t *states = scr_arr_states_end(out); + /* A fresh array without states: the values in order. */ for (size_t i = 0; i < s->nentries; i++) { if (!scr_map_entry_live(s, i)) continue; scr_str_retain((ScrStr *)(uintptr_t)scr_map_entry_at(s, i)->key); - out->data[out->len] = scr_map_entry_at(s, i)->key; - *scr_arr_state_in(states, out->len++) = SCR_ARR_VALUE; + out->data[out->len++] = scr_map_entry_at(s, i)->key; } + scr_arr_refill(out); return out; } ScrArr *scr_set_to_arr_ref(const ScrMap *s, const ScrArrOps *ops) { ScrArr *out = scr_arr_new_ops(ops, s->nlive); if (scr_set_to_arr_sparse(s, out)) return out; - uint8_t *states = scr_arr_states_end(out); + /* A fresh array without states: the values in order. */ for (size_t i = 0; i < s->nentries; i++) { if (!scr_map_entry_live(s, i)) continue; ops->retain((void *)(uintptr_t)scr_map_entry_at(s, i)->key); - out->data[out->len] = scr_map_entry_at(s, i)->key; - *scr_arr_state_in(states, out->len++) = SCR_ARR_VALUE; + scr_arr_dense_put(out, out->len, scr_map_entry_at(s, i)->key); + out->len++; } + scr_arr_refill(out); return out; } @@ -13008,9 +13019,116 @@ bool scr_dyn_native_date_is(const ScrDyn *value) { return value && value->kind == SCR_DYN_HANDLE && value->v.handle.tag == SCR_DYNH_DATE; } +/* Instances of program classes declared `extends Date` keep their time + * value in a compiled field. In checked-dynamic code such an instance is a + * typed reference, and the runtime reaches its time value and methods + * through the functions %main installs (builtins/date-classes.ts), called + * as (op, value, argument): for op 0 the time function answers the time + * value, or undefined for any other value, and for op 1 sets it; for ops 2 + * to 5 the method function calls the instance's toISOString, + * toJSON(argument), toString and valueOf. */ +enum { + SCR_DATE_CLASS_TIME, + SCR_DATE_CLASS_SET_TIME, + SCR_DATE_CLASS_TO_ISO_STRING, + SCR_DATE_CLASS_TO_JSON, + SCR_DATE_CLASS_TO_STRING, + SCR_DATE_CLASS_VALUE_OF, + SCR_DATE_CLASS_NAME, +}; +static SCR_TL ScrDyn *scr_date_class_operation; +static SCR_TL ScrDyn *scr_date_class_methods; + +static void scr_date_class_operation_cleanup(void) { + ScrDyn *operation = scr_date_class_operation; + ScrDyn *methods = scr_date_class_methods; + scr_date_class_operation = scr_date_class_methods = NULL; + scr_dyn_release(operation); + scr_dyn_release(methods); +} + +static bool scr_date_class_time_of(const ScrDyn *value, double *time); +static ScrDyn *scr_date_class_to_json(const ScrDyn *value, const ScrDyn *key); +static ScrDyn *scr_date_class_to_string(const ScrDyn *value); +static ScrDyn *scr_date_class_value_of(const ScrDyn *value); +static ScrStr *scr_date_class_name(const ScrDyn *value); +static ScrDyn *scr_date_class_method(const ScrDyn *value, const char *key, size_t key_len); + +/* The installation also publishes these functions to the rest of the + * runtime (scr_date_class_hooks), so only a program that declares a class + * extending Date links them. */ +static const ScrDateClassHooks scr_date_class_hook_table = { + scr_date_class_time_of, scr_date_class_to_json, scr_date_class_to_string, + scr_date_class_value_of, scr_date_class_name, scr_date_class_method, +}; + +void scr_date_class_operation_install(ScrDyn *time, ScrDyn *methods) { + scr_date_class_hooks = &scr_date_class_hook_table; + if (!scr_date_class_operation) scr_atexit(scr_date_class_operation_cleanup); + scr_dyn_release(scr_date_class_operation); + scr_dyn_release(scr_date_class_methods); + scr_date_class_operation = scr_dyn_retain(time); + scr_date_class_methods = scr_dyn_retain(methods); +} + +/* The installed operation `op` on `value`: +1, or NULL with an exception + * pending. */ +static ScrDyn *scr_date_class_call(int op, const ScrDyn *value, const ScrDyn *argument) { + ScrDyn *code = scr_dyn_new_num(op); + ScrDyn *args[] = { code, (ScrDyn *)value, (ScrDyn *)(argument ? argument : scr_dyn_undefined()) }; + bool time = op < SCR_DATE_CLASS_TO_ISO_STRING || op == SCR_DATE_CLASS_NAME; + ScrDyn *result = scr_dyn_call(time ? scr_date_class_operation : scr_date_class_methods, args, 3, "Date"); + scr_dyn_release(code); + return result; +} + +/* True, with the time value in *time, when `value` holds an instance of a + * class declared `extends Date`. */ +static bool scr_date_class_time_of(const ScrDyn *value, double *time) { + if (!scr_date_class_operation || !value || value->kind != SCR_DYN_TYPED_REF) return false; + ScrDyn *result = scr_date_class_call(SCR_DATE_CLASS_TIME, value, NULL); + bool found = result && result->kind == SCR_DYN_NUM; + if (found) *time = result->v.num; + scr_dyn_release(result); + return found; +} + +/* `value instanceof Date`: a Date, or an instance of a class declared + * `extends Date`. */ +bool scr_dyn_date_instance_is(const ScrDyn *value) { + double time; + return scr_dyn_native_date_is(value) || scr_dyn_date_class_time(value, &time); +} + +/* toJSON(key), toString() or valueOf() of an instance of a class declared + * `extends Date` (scr_dyn_date_class_time answered true): the class's + * declaration or the Date method. +1, or NULL with an exception pending. */ +static ScrDyn *scr_date_class_to_json(const ScrDyn *value, const ScrDyn *key) { + return scr_date_class_call(SCR_DATE_CLASS_TO_JSON, value, key); +} +static ScrDyn *scr_date_class_to_string(const ScrDyn *value) { + return scr_date_class_call(SCR_DATE_CLASS_TO_STRING, value, NULL); +} +static ScrDyn *scr_date_class_value_of(const ScrDyn *value) { + return scr_date_class_call(SCR_DATE_CLASS_VALUE_OF, value, NULL); +} + +/* The name of the class of an instance of a class declared `extends + * Date`: +1, or NULL for any other value. */ +static ScrStr *scr_date_class_name(const ScrDyn *value) { + if (!scr_date_class_operation || !value || value->kind != SCR_DYN_TYPED_REF) return NULL; + ScrDyn *result = scr_date_class_call(SCR_DATE_CLASS_NAME, value, NULL); + ScrStr *name = result && result->kind == SCR_DYN_STR ? scr_str_retain(result->v.str) : NULL; + scr_dyn_release(result); + return name; +} + double scr_dyn_native_date_value(const ScrDyn *value) { - if (!scr_dyn_native_date_is(value)) { scr_dyn_check_fail(NULL, "Date", value); return NAN; } - return ((ScrNativeDate *)value->v.handle.ptr)->milliseconds; + if (scr_dyn_native_date_is(value)) return ((ScrNativeDate *)value->v.handle.ptr)->milliseconds; + double time; + if (scr_dyn_date_class_time(value, &time)) return time; + scr_dyn_check_fail(NULL, "Date", value); + return NAN; } /* Method names without another use in this file, in named arrays (see @@ -13020,13 +13138,14 @@ static const char scr_date_to_time_string_name[] = "toTimeString"; static ScrDyn *scr_native_date_invoke(void *ptr, ScrDyn *self, const char *method, ScrDyn *const *args, size_t argc, const char *what) { - (void)self; (void)args; (void)argc; (void)what; + (void)self; (void)what; double ms = ((ScrNativeDate *)ptr)->milliseconds; if (!strcmp(method, "getTime") || !strcmp(method, "valueOf")) return scr_dyn_new_num(ms); if (!strcmp(method, "toString") || !strcmp(method, scr_date_to_date_string_name) || - !strcmp(method, scr_date_to_time_string_name)) { + !strcmp(method, scr_date_to_time_string_name) || !strcmp(method, "toUTCString")) { ScrStr *text = !strcmp(method, "toString") ? scr_date_to_string(ms) : !strcmp(method, scr_date_to_date_string_name) ? scr_date_to_date_string(ms) + : !strcmp(method, "toUTCString") ? scr_date_to_utc_string(ms) : scr_date_to_time_string(ms); ScrDyn *result = scr_dyn_new_str(text); scr_str_release(text); @@ -13040,6 +13159,12 @@ static ScrDyn *scr_native_date_invoke(void *ptr, ScrDyn *self, const char *metho scr_str_release(text); return result; } + if (!strcmp(method, "setTime")) { + double time = NAN; + if (argc > 0 && !scr_dyn_number_coerce_js(args[0], &time)) return NULL; + ((ScrNativeDate *)ptr)->milliseconds = scr_date_new_ms(time); + return scr_dyn_new_num(((ScrNativeDate *)ptr)->milliseconds); + } #define DATE_GET(name, fn) if (!strcmp(method, name)) return scr_dyn_new_num(fn(ms)) DATE_GET("getFullYear", scr_date_get_full_year_local); DATE_GET("getUTCFullYear", scr_date_get_full_year_utc); @@ -13070,13 +13195,25 @@ ScrDyn *scr_dyn_native_date_new(const ScrDyn *arguments) { else { ScrDyn *value = arguments->v.arr.items[0]; if (scr_dyn_native_date_is(value)) ms = scr_dyn_native_date_value(value); - else if (value->kind == SCR_DYN_STR) ms = scr_date_parse_get_time(value->v.str); + else if (scr_dyn_date_class_time(value, &ms)) { + } else if (value->kind == SCR_DYN_STR) ms = scr_date_parse_get_time(value->v.str); else if (!scr_dyn_number_coerce_js(value, &ms)) return NULL; ms = scr_date_new_ms(ms); } return scr_dyn_native_date_from_ms(ms); } +/* The time value `new Date(...arguments)` constructs (super(...) in a + * class declared `extends Date`), or NaN with an exception pending. */ +double scr_dyn_date_arguments_time(const ScrDyn *arguments) { + ScrDyn *date = arguments->v.arr.len > 1 ? scr_dyn_native_date_new_fields(arguments) + : scr_dyn_native_date_new_value(arguments); + if (!date) return NAN; + double time = ((ScrNativeDate *)date->v.handle.ptr)->milliseconds; + scr_dyn_release(date); + return time; +} + /* new Date(value) in JavaScript: a string parses with the full parser; * every other value takes scr_dyn_native_date_new. */ ScrDyn *scr_dyn_native_date_new_value(const ScrDyn *arguments) { @@ -13103,11 +13240,11 @@ ScrDyn *scr_dyn_native_date_new_fields(const ScrDyn *arguments) { /* The Date.prototype methods scr_native_date_invoke answers. */ static const char *const scr_native_date_methods[] = { "getTime", "valueOf", "toISOString", "toJSON", "toString", scr_date_to_date_string_name, - scr_date_to_time_string_name, + scr_date_to_time_string_name, "toUTCString", "getFullYear", "getUTCFullYear", "getMonth", "getUTCMonth", "getDate", "getUTCDate", "getDay", "getUTCDay", "getHours", "getUTCHours", "getMinutes", "getUTCMinutes", "getSeconds", "getUTCSeconds", "getMilliseconds", - "getUTCMilliseconds", "getTimezoneOffset", + "getUTCMilliseconds", "getTimezoneOffset", "setTime", }; #define SCR_NATIVE_DATE_METHODS (sizeof scr_native_date_methods / sizeof scr_native_date_methods[0]) static SCR_TL ScrDyn *scr_native_date_method_values[SCR_NATIVE_DATE_METHODS]; @@ -13122,13 +13259,34 @@ static void scr_native_date_methods_cleanup(void) { } /* A Date method read as a value and called later: the closure's function - * slot holds the method's name, and the receiver must be a Date. */ + * slot holds the method's name, and the receiver must be a Date. On an + * instance of a class declared `extends Date` the method runs over its + * time value; toJSON calls the instance's toISOString. */ static ScrDyn *scr_native_date_method_call(ScrClosure *closure, ScrDyn *const *args, size_t argc) { const char *method = closure->fn; ScrDyn *self = scr_dyn_this_get(); ScrDyn *result = NULL; + double time; if (scr_dyn_native_date_is(self)) { result = scr_native_date_invoke(self->v.handle.ptr, self, method, args, argc, method); + } else if (scr_dyn_date_class_time(self, &time)) { + if (!strcmp(method, "toJSON")) { + result = isfinite(time) ? scr_date_class_call(SCR_DATE_CLASS_TO_ISO_STRING, self, NULL) + : scr_dyn_new_null(); + } else { + ScrNativeDate date = { 1, time }; + result = scr_native_date_invoke(&date, self, method, args, argc, method); + if (result && date.milliseconds != time && !(isnan(date.milliseconds) && isnan(time))) { + ScrDyn *stored = scr_dyn_new_num(date.milliseconds); + ScrDyn *set = scr_date_class_call(SCR_DATE_CLASS_SET_TIME, self, stored); + scr_dyn_release(stored); + if (!set) { + scr_dyn_release(result); + result = NULL; + } + scr_dyn_release(set); + } + } } else { static const char message[] = "this is not a Date object."; scr_throw_error_msg(SCR_ERR_TYPE, message, sizeof message - 1); @@ -13137,6 +13295,21 @@ static ScrDyn *scr_native_date_method_call(ScrClosure *closure, ScrDyn *const *a return result; } +static ScrDyn *scr_native_date_get(void *ptr, const char *key, size_t key_len); + +/* The Date method `key` as a function value when `value` holds an instance + * of a class declared `extends Date`, or NULL. The class's own members are + * read first, by the caller. */ +static ScrDyn *scr_date_class_method(const ScrDyn *value, const char *key, size_t key_len) { + if (!scr_date_class_operation) return NULL; + bool named = false; + for (size_t i = 0; i < SCR_NATIVE_DATE_METHODS && !named; i++) + named = strlen(scr_native_date_methods[i]) == key_len && !memcmp(scr_native_date_methods[i], key, key_len); + double time; + if (!named || !scr_dyn_date_class_time(value, &time)) return NULL; + return scr_native_date_get(NULL, key, key_len); +} + /* Property reads of a Date: its methods as function values, one per name * and thread, and NULL (undefined) for other names. */ static ScrDyn *scr_native_date_get(void *ptr, const char *key, size_t key_len) { diff --git a/packages/runtime/src/scr_lib.h b/packages/runtime/src/scr_lib.h index 411d1e684..95f67044a 100644 --- a/packages/runtime/src/scr_lib.h +++ b/packages/runtime/src/scr_lib.h @@ -366,6 +366,9 @@ typedef struct ScrBytes ScrBytes; ScrStr *scr_atomics_wait(ScrBytes *, double, double, double); double scr_atomics_notify(ScrBytes *, double, double); double scr_atomics_op(ScrBytes *, double, double, double, double); +double scr_atomics_op_dyn(const ScrDyn *, double, double, double, double); +ScrStr *scr_atomics_wait_dyn(const ScrDyn *, double, double, double); +double scr_atomics_notify_dyn(const ScrDyn *, double, double); /* isatty(3) over an fd (0/1/2): a real boolean — false where Node's * non-TTY streams expose undefined (SEMANTICS.md). stdin_destroy is a diff --git a/packages/runtime/src/scr_loop_epoll.c b/packages/runtime/src/scr_loop_epoll.c index 484ef36b6..8040c76fe 100644 --- a/packages/runtime/src/scr_loop_epoll.c +++ b/packages/runtime/src/scr_loop_epoll.c @@ -1,6 +1,6 @@ /* The Linux backend of the platform readiness contract (scr_platform.h): - * epoll for fd readiness, one timerfd per armed one-shot timer. This is - * the LIVE Linux poller behind scr_net.c and scr_dgram.c (native-toolchain.ts links it + * epoll for fd readiness, one timerfd for every armed one-shot timer. This + * is the LIVE Linux poller behind scr_net.c and scr_dgram.c (native-toolchain.ts links it * alongside scr_loop_kqueue.c whenever those units compile; each TU is * empty off its platform). Child-exit wakeups are NOT here: scr_child.c * keeps its narrow seam inline (kqueue EVFILT_PROC on BSD, pidfd_open + @@ -9,18 +9,22 @@ * * Design notes: * - Interest is keyed by fd with ONE mask under epoll, so the poller keeps - * a linear fd -> (mask, udata) table and merges read/write interest into - * EPOLL_CTL_MOD. Linear scan is fine at the units' scale (dozens of fds, - * drained in 64-event batches today); swap for a hash if profiles say so. + * an fd -> (mask, udata) table (indexed by fd number) and merges + * read/write interest into EPOLL_CTL_MOD. * - EPOLLHUP/EPOLLERR/EPOLLRDHUP report as READABLE (plus WRITABLE when * write interest is armed): the units learn EOF/errors from read()==0 or * errno exactly as they do from kqueue's EV_EOF today. Note an fd is in * the epoll set ONLY while some interest is armed, so a consumer-less * socket can never busy-report HUP. - * - Timers: EVFILT_TIMER has no epoll analogue, so each armed key owns a - * TFD_NONBLOCK timerfd registered EPOLLIN in the same epoll set, tagged - * through the same table (mask=TIMER). Fired timers are disarmed and - * their timerfd closed at delivery (kqueue's EV_ONESHOT semantics). + * - Timers: EVFILT_TIMER has no epoll analogue. Armed keys live in a + * deadline min-heap (a pointer hash finds a key's slot), and ONE timerfd + * in the epoll set wakes the loop at the earliest deadline. Re-arming, + * arming a later deadline and cancelling make no system call: the + * timerfd is reprogrammed only when a deadline earlier than its own + * arrives, or when it fires early (the heap then holds later deadlines). + * A server's per-request idle-timer churn therefore costs nothing in the + * kernel, like libuv's timer heap. Expired timers are delivered (and + * disarmed: kqueue's EV_ONESHOT semantics) by the next drain. * - Units must scrp_forget a watched fd before close(2) (the contract's * epoll obligation). As a second line of defense against a missed * forget followed by fd-number reuse, watch self-heals: a MOD that @@ -32,47 +36,75 @@ #include "scr_platform.h" #include +#include #include #include #include #include #include +#include #include /* ── fd/timer poller ─────────────────────────────────────────────────── */ typedef struct { - int fd; /* watched fd, or the timer's timerfd */ - unsigned mask; /* SCRP_READABLE|SCRP_WRITABLE, or SCRP_TIMER */ - void *udata; /* delivery tag; for timers: the arm-time udata */ - void *timer_key; /* timers only: the caller's key */ + int fd; /* watched fd */ + unsigned mask; /* SCRP_READABLE|SCRP_WRITABLE */ + void *udata; /* delivery tag */ } ScrpEntry; +typedef struct { + double deadline; /* CLOCK_MONOTONIC milliseconds */ + uint64_t seq; /* arm order: equal deadlines fire first-armed first */ + void *key; + void *udata; +} ScrpTimer; + +typedef struct { + void *key; + size_t idx; /* the key's heap index */ +} ScrpKeySlot; + struct ScrPoller { int ep; ScrpEntry *entries; size_t n, cap; + size_t *slot_of_fd; /* fd -> entry index + 1 (0: unwatched) */ + size_t fd_cap; + int tfd; /* the shared timerfd (-1 until a timer arms) */ + double tfd_deadline; /* what tfd is programmed for; INFINITY: disarmed */ + ScrpTimer *heap; + size_t nt, heap_cap; + ScrpKeySlot *key_slots; /* open addressing over keys (key NULL: empty) */ + size_t key_cap; /* power of two */ + uint64_t seq; }; static ScrpEntry *scrp_find_fd(ScrPoller *p, int fd) { - for (size_t i = 0; i < p->n; i++) - if (p->entries[i].fd == fd) return &p->entries[i]; - return NULL; -} - -static ScrpEntry *scrp_find_key(ScrPoller *p, void *key) { - for (size_t i = 0; i < p->n; i++) - if ((p->entries[i].mask & SCRP_TIMER) != 0 && p->entries[i].timer_key == key) return &p->entries[i]; - return NULL; + if (fd < 0 || (size_t)fd >= p->fd_cap || p->slot_of_fd[fd] == 0) return NULL; + return &p->entries[p->slot_of_fd[fd] - 1]; } static void scrp_remove(ScrPoller *p, ScrpEntry *e) { size_t i = (size_t)(e - p->entries); - p->entries[i] = p->entries[p->n - 1]; + p->slot_of_fd[e->fd] = 0; p->n--; + if (i != p->n) { + p->entries[i] = p->entries[p->n]; + p->slot_of_fd[p->entries[i].fd] = i + 1; + } } static bool scrp_push(ScrPoller *p, ScrpEntry e) { + if ((size_t)e.fd >= p->fd_cap) { + size_t cap = p->fd_cap == 0 ? 64 : p->fd_cap; + while (cap <= (size_t)e.fd) cap *= 2; + size_t *grown = realloc(p->slot_of_fd, cap * sizeof *grown); + if (grown == NULL) return false; + memset(grown + p->fd_cap, 0, (cap - p->fd_cap) * sizeof *grown); + p->slot_of_fd = grown; + p->fd_cap = cap; + } if (p->n == p->cap) { size_t cap = p->cap == 0 ? 16 : p->cap * 2; ScrpEntry *grown = realloc(p->entries, cap * sizeof *grown); @@ -81,6 +113,117 @@ static bool scrp_push(ScrPoller *p, ScrpEntry e) { p->cap = cap; } p->entries[p->n++] = e; + p->slot_of_fd[e.fd] = p->n; + return true; +} + +/* ── the timer heap ── */ + +static double scrp_now_ms(void) { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (double)ts.tv_sec * 1000.0 + (double)ts.tv_nsec / 1e6; +} + +static size_t scrp_key_hash(const ScrPoller *p, const void *key) { + uintptr_t h = (uintptr_t)key; + h ^= h >> 17; + h *= (uintptr_t)0x9E3779B97F4A7C15ull; + h ^= h >> 29; + return (size_t)h & (p->key_cap - 1); +} + +/* The hash slot holding `key`, or the empty slot where it would go. */ +static size_t scrp_key_probe(const ScrPoller *p, const void *key) { + size_t i = scrp_key_hash(p, key); + while (p->key_slots[i].key != NULL && p->key_slots[i].key != key) + i = (i + 1) & (p->key_cap - 1); + return i; +} + +static ScrpKeySlot *scrp_key_find(const ScrPoller *p, const void *key) { + if (p->key_cap == 0) return NULL; + size_t i = scrp_key_probe(p, key); + return p->key_slots[i].key != NULL ? &p->key_slots[i] : NULL; +} + +/* Backward-shift deletion keeps linear probing tombstone-free. */ +static void scrp_key_erase(ScrPoller *p, size_t i) { + size_t mask = p->key_cap - 1; + p->key_slots[i].key = NULL; + for (size_t j = (i + 1) & mask; p->key_slots[j].key != NULL; j = (j + 1) & mask) { + size_t home = scrp_key_hash(p, p->key_slots[j].key); + /* move j into the hole when its home is not cyclically within (i, j] */ + if (((j - home) & mask) >= ((j - i) & mask)) { + p->key_slots[i] = p->key_slots[j]; + p->key_slots[j].key = NULL; + i = j; + } + } +} + +static bool scrp_key_grow(ScrPoller *p) { + size_t cap = p->key_cap == 0 ? 64 : p->key_cap * 2; + ScrpKeySlot *slots = calloc(cap, sizeof *slots); + if (slots == NULL) return false; + free(p->key_slots); + p->key_slots = slots; + p->key_cap = cap; + for (size_t h = 0; h < p->nt; h++) + p->key_slots[scrp_key_probe(p, p->heap[h].key)] = (ScrpKeySlot){p->heap[h].key, h}; + return true; +} + +static bool scrp_timer_less(const ScrpTimer *a, const ScrpTimer *b) { + return a->deadline < b->deadline || (a->deadline == b->deadline && a->seq < b->seq); +} + +/* Place `t` at heap index `i` and record it in the key table. */ +static void scrp_heap_put(ScrPoller *p, size_t i, ScrpTimer t) { + p->heap[i] = t; + scrp_key_find(p, t.key)->idx = i; +} + +static void scrp_heap_fix(ScrPoller *p, size_t i) { + ScrpTimer t = p->heap[i]; + while (i > 0) { + size_t parent = (i - 1) / 2; + if (!scrp_timer_less(&t, &p->heap[parent])) break; + scrp_heap_put(p, i, p->heap[parent]); + i = parent; + } + for (;;) { + size_t child = 2 * i + 1; + if (child >= p->nt) break; + if (child + 1 < p->nt && scrp_timer_less(&p->heap[child + 1], &p->heap[child])) child++; + if (!scrp_timer_less(&p->heap[child], &t)) break; + scrp_heap_put(p, i, p->heap[child]); + i = child; + } + scrp_heap_put(p, i, t); +} + +static void scrp_heap_remove(ScrPoller *p, size_t i) { + scrp_key_erase(p, scrp_key_probe(p, p->heap[i].key)); + p->nt--; + if (i == p->nt) return; + p->heap[i] = p->heap[p->nt]; + scrp_heap_fix(p, i); +} + +/* Program the shared timerfd for `deadline` (INFINITY disarms). */ +static bool scrp_tfd_program(ScrPoller *p, double deadline) { + struct itimerspec its; + memset(&its, 0, sizeof its); + if (deadline != INFINITY) { + if (deadline < 0) deadline = 0; + its.it_value.tv_sec = (time_t)(deadline / 1000.0); + its.it_value.tv_nsec = (long)((deadline - (double)its.it_value.tv_sec * 1000.0) * 1e6); + if (its.it_value.tv_nsec >= 1000000000L) its.it_value.tv_nsec = 999999999L; + if (its.it_value.tv_sec == 0 && its.it_value.tv_nsec == 0) its.it_value.tv_nsec = 1; /* 0 disarms */ + } + if (timerfd_settime(p->tfd, TFD_TIMER_ABSTIME, &its, NULL) != 0) return false; + p->tfd_deadline = deadline; return true; } @@ -92,18 +235,21 @@ ScrPoller *scrp_poller_new(void) { free(p); return NULL; } + p->tfd = -1; + p->tfd_deadline = INFINITY; return p; } void scrp_poller_free(ScrPoller *p) { if (p == NULL) return; - for (size_t i = 0; i < p->n; i++) - if ((p->entries[i].mask & SCRP_TIMER) != 0) close(p->entries[i].fd); + if (p->tfd >= 0) close(p->tfd); close(p->ep); free(p->entries); + free(p->slot_of_fd); + free(p->heap); + free(p->key_slots); free(p); } - int scrp_poller_fd(const ScrPoller *p) { return p->ep; } static uint32_t scrp_epoll_mask(unsigned mask) { @@ -124,7 +270,7 @@ static bool scrp_watch(ScrPoller *p, int fd, void *udata, bool on, unsigned bit) struct epoll_event ev = {.events = scrp_epoll_mask(next), .data = {.fd = fd}}; if (e == NULL) { if (next == 0) return true; /* unwatch of an unwatched fd: no-op */ - if (!scrp_push(p, (ScrpEntry){fd, next, udata, NULL})) return false; + if (!scrp_push(p, (ScrpEntry){fd, next, udata})) return false; int rc = epoll_ctl(p->ep, EPOLL_CTL_ADD, fd, &ev); if (rc != 0 && errno == EEXIST) rc = epoll_ctl(p->ep, EPOLL_CTL_MOD, fd, &ev); if (rc != 0) { @@ -163,41 +309,51 @@ void scrp_forget(ScrPoller *p, int fd) { bool scrp_timer_arm(ScrPoller *p, void *key, double ms, void *udata) { if (!(ms >= 0)) ms = 0; - ScrpEntry *e = scrp_find_key(p, key); - int tfd = e != NULL ? e->fd : timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC); - if (tfd < 0) return false; - struct itimerspec its; - memset(&its, 0, sizeof its); - its.it_value.tv_sec = (time_t)(ms / 1000.0); - its.it_value.tv_nsec = (long)((ms - (double)its.it_value.tv_sec * 1000.0) * 1e6); - if (its.it_value.tv_sec == 0 && its.it_value.tv_nsec == 0) its.it_value.tv_nsec = 1; /* 0 disarms timerfd */ - if (timerfd_settime(tfd, 0, &its, NULL) != 0) { - if (e == NULL) close(tfd); - return false; + if (p->tfd < 0) { + int tfd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC); + if (tfd < 0) return false; + struct epoll_event ev = {.events = EPOLLIN, .data = {.fd = tfd}}; + if (epoll_ctl(p->ep, EPOLL_CTL_ADD, tfd, &ev) != 0) { + close(tfd); + return false; + } + p->tfd = tfd; } - if (e != NULL) { - e->udata = udata; - return true; /* re-arm replaces the deadline */ + ScrpTimer t = {scrp_now_ms() + ms, p->seq++, key, udata}; + ScrpKeySlot *slot = scrp_key_find(p, key); + if (slot != NULL) { + /* re-arm replaces the deadline */ + size_t i = slot->idx; + p->heap[i] = t; + scrp_heap_fix(p, i); + } else { + if (p->nt == p->heap_cap) { + size_t cap = p->heap_cap == 0 ? 16 : p->heap_cap * 2; + ScrpTimer *grown = realloc(p->heap, cap * sizeof *grown); + if (grown == NULL) return false; + p->heap = grown; + p->heap_cap = cap; + } + if ((p->nt + 1) * 2 > p->key_cap && !scrp_key_grow(p)) return false; + p->heap[p->nt] = t; + p->key_slots[scrp_key_probe(p, key)] = (ScrpKeySlot){key, p->nt}; + p->nt++; + scrp_heap_fix(p, p->nt - 1); } - if (!scrp_push(p, (ScrpEntry){tfd, SCRP_TIMER, udata, key})) { - close(tfd); - return false; - } - struct epoll_event ev = {.events = EPOLLIN, .data = {.fd = tfd}}; - if (epoll_ctl(p->ep, EPOLL_CTL_ADD, tfd, &ev) != 0) { - scrp_remove(p, &p->entries[p->n - 1]); - close(tfd); + /* Only an earlier deadline needs the kernel: a later one is found when + * the timerfd fires early. */ + if (p->heap[0].deadline < p->tfd_deadline && !scrp_tfd_program(p, p->heap[0].deadline)) { + scrp_heap_remove(p, scrp_key_find(p, key)->idx); return false; } return true; } void scrp_timer_cancel(ScrPoller *p, void *key) { - ScrpEntry *e = scrp_find_key(p, key); - if (e == NULL) return; /* unarmed or already fired: no-op */ - (void)epoll_ctl(p->ep, EPOLL_CTL_DEL, e->fd, NULL); - close(e->fd); - scrp_remove(p, e); + ScrpKeySlot *slot = scrp_key_find(p, key); + if (slot == NULL) return; /* unarmed or already fired: no-op */ + /* the timerfd keeps its deadline; an early wake finds nothing due */ + scrp_heap_remove(p, slot->idx); } int scrp_drain(ScrPoller *p, ScrPollerEvent *out, int max) { @@ -205,20 +361,17 @@ int scrp_drain(ScrPoller *p, ScrPollerEvent *out, int max) { struct epoll_event evs[64]; int want = max < 64 ? max : 64; int n = epoll_wait(p->ep, evs, want, 0); - if (n <= 0) return 0; /* EINTR/none: a spurious pass */ int filled = 0; + bool timer_woke = false; for (int i = 0; i < n; i++) { - ScrpEntry *e = scrp_find_fd(p, evs[i].data.fd); - if (e == NULL) continue; /* raced with forget */ - if ((e->mask & SCRP_TIMER) != 0) { - out[filled].udata = e->udata; - out[filled++].events = SCRP_TIMER; - /* one-shot: disarm at delivery, EV_ONESHOT semantics */ - (void)epoll_ctl(p->ep, EPOLL_CTL_DEL, e->fd, NULL); - close(e->fd); - scrp_remove(p, e); + if (evs[i].data.fd == p->tfd && p->tfd >= 0) { + uint64_t ticks; + (void)!read(p->tfd, &ticks, sizeof ticks); + timer_woke = true; continue; } + ScrpEntry *e = scrp_find_fd(p, evs[i].data.fd); + if (e == NULL) continue; /* raced with forget */ unsigned got = 0; uint32_t ep = evs[i].events; if ((ep & (EPOLLIN | EPOLLHUP | EPOLLERR | EPOLLRDHUP)) != 0) got |= SCRP_READABLE; @@ -229,6 +382,21 @@ int scrp_drain(ScrPoller *p, ScrPollerEvent *out, int max) { out[filled].udata = e->udata; out[filled++].events = got; } + /* The timerfd always holds a deadline no later than the heap's earliest + * (arming an earlier one reprograms it), so a timer can only be due + * after it fires. */ + if (timer_woke) { + p->tfd_deadline = INFINITY; /* one-shot: it fired */ + /* deliver every expired timer the batch has room for, one-shot */ + double now = scrp_now_ms(); + while (p->nt > 0 && filled < max && p->heap[0].deadline <= now) { + out[filled].udata = p->heap[0].udata; + out[filled++].events = SCRP_TIMER; + scrp_heap_remove(p, 0); + } + /* the next deadline (one already past fires at once) */ + if (p->nt > 0) (void)scrp_tfd_program(p, p->heap[0].deadline); + } return filled; } diff --git a/packages/runtime/src/scr_loop_epoll.test.c b/packages/runtime/src/scr_loop_epoll.test.c new file mode 100644 index 000000000..6ab1621c5 --- /dev/null +++ b/packages/runtime/src/scr_loop_epoll.test.c @@ -0,0 +1,115 @@ +#undef NDEBUG +#define _GNU_SOURCE 1 +#include "scr_platform.h" +#include +#include +#include +#include +#include +#include +#include + +/* The epoll poller alone: timers live in a deadline heap behind one + * timerfd, so arming, re-arming and cancelling many keys must still + * deliver each armed key exactly once, in deadline order, after its + * deadline, and never a cancelled key. */ + +enum { KEYS = 2000 }; + +static double now_ms(void) { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (double)ts.tv_sec * 1000.0 + (double)ts.tv_nsec / 1e6; +} + +static int keys[KEYS]; +static double deadline[KEYS]; +static int state[KEYS]; /* 0 unarmed/cancelled, 1 armed, 2 fired */ + +/* Wait for the poller fd, then drain; returns the events drained. */ +static int pump(ScrPoller *p, ScrPollerEvent *evs, int max, int wait_ms) { + struct pollfd pfd = {.fd = scrp_poller_fd(p), .events = POLLIN}; + (void)poll(&pfd, 1, wait_ms); + return scrp_drain(p, evs, max); +} + +int main(void) { + ScrPoller *p = scrp_poller_new(); + assert(p != NULL); + srand(7); + double start = now_ms(); + /* Each deadline counts from its own arm call: arming takes time, here + * stretched by a pause halfway, and the poller reads the clock at each + * call. */ + for (int i = 0; i < KEYS; i++) { + if (i == KEYS / 2) + for (double until = now_ms() + 3; now_ms() < until;) { + } + double ms = 5 + rand() % 120; + double t = now_ms(); + assert(scrp_timer_arm(p, &keys[i], ms, &keys[i])); + deadline[i] = t + ms; + state[i] = 1; + } + /* re-arm a third later and earlier, cancel a third (the heap and the key + * table move entries on every one of these) */ + for (int i = 0; i < KEYS; i++) { + if (i % 3 == 0) { + double ms = 1 + rand() % 150; + double t = now_ms(); + assert(scrp_timer_arm(p, &keys[i], ms, &keys[i])); + deadline[i] = t + ms; + } else if (i % 3 == 1) { + scrp_timer_cancel(p, &keys[i]); + state[i] = 0; + } + } + scrp_timer_cancel(p, &keys[1]); /* cancel of a cancelled key: no-op */ + /* an fd delivers alongside the timers */ + int fds[2]; + assert(pipe(fds) == 0); + static int pipe_tag; + assert(scrp_watch_read(p, fds[0], &pipe_tag, true)); + assert(write(fds[1], "x", 1) == 1); + int armed = 0; + for (int i = 0; i < KEYS; i++) armed += state[i] == 1; + int fired = 0, piped = 0; + double last = 0; + ScrPollerEvent evs[16]; /* small batches leave due timers for the next drain */ + while (fired < armed) { + int n = pump(p, evs, 16, 1000); + for (int e = 0; e < n; e++) { + if (evs[e].udata == &pipe_tag) { + assert(evs[e].events == SCRP_READABLE); + char c; + assert(read(fds[0], &c, 1) == 1); + piped++; + continue; + } + assert(evs[e].events == SCRP_TIMER); + int i = (int)((int *)evs[e].udata - keys); + assert(i >= 0 && i < KEYS); + assert(state[i] == 1); + double t = now_ms(); + assert(t + 1.0 >= deadline[i]); /* never early (timerfd rounding aside) */ + assert(deadline[i] + 1.0 >= last); /* deadline order */ + if (deadline[i] > last) last = deadline[i]; + state[i] = 2; + fired++; + } + assert(now_ms() - start < 10000); + } + assert(piped == 1); + /* nothing else fires: the cancelled keys stay quiet */ + assert(pump(p, evs, 16, 200) == 0); + /* a key fires again after re-arming once it fired; 0 ms fires at once */ + assert(scrp_timer_arm(p, &keys[0], 0, &keys[0])); + int n = pump(p, evs, 16, 1000); + assert(n == 1 && evs[0].udata == &keys[0] && evs[0].events == SCRP_TIMER); + scrp_forget(p, fds[0]); + close(fds[0]); + close(fds[1]); + scrp_poller_free(p); + puts("epoll timers fire once each, in deadline order, never when cancelled"); + return 0; +} diff --git a/packages/runtime/src/scr_loop_epoll.test.ts b/packages/runtime/src/scr_loop_epoll.test.ts new file mode 100644 index 000000000..89b2e9c3d --- /dev/null +++ b/packages/runtime/src/scr_loop_epoll.test.ts @@ -0,0 +1,41 @@ +import { execFile } from "node:child_process"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { promisify } from "node:util"; +import { expect, test } from "vitest"; + +const exec = promisify(execFile); + +/* The Linux poller links alone (it needs only libc), under AddressSanitizer + * and UndefinedBehaviorSanitizer. */ +test.skipIf(process.platform !== "linux")( + "the epoll poller's timer heap fires each armed key once, in deadline order", + async () => { + const dir = await mkdtemp(join(tmpdir(), "scriptc-epoll-")); + try { + const bin = join(dir, "epoll"); + await exec("clang", [ + "-std=c11", + "-O1", + "-g", + "-fsanitize=address,undefined", + join(import.meta.dirname, "scr_loop_epoll.test.c"), + join(import.meta.dirname, "scr_loop_epoll.c"), + "-lm", + "-o", + bin, + ]); + const result = await exec(bin, [], { + timeout: 60000, + env: { ...process.env, UBSAN_OPTIONS: "halt_on_error=1" }, + }); + expect(result.stdout).toBe( + "epoll timers fire once each, in deadline order, never when cancelled\n", + ); + expect(result.stderr).toBe(""); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }, +); diff --git a/packages/runtime/src/scr_mailbox.c b/packages/runtime/src/scr_mailbox.c index a8dc7e5cc..b2af22774 100644 --- a/packages/runtime/src/scr_mailbox.c +++ b/packages/runtime/src/scr_mailbox.c @@ -140,9 +140,11 @@ ScrMailbox *scr_mailbox_retain(ScrMailbox *mailbox) { void scr_mail_event_free(ScrMailEvent *event) { if (!event) return; - scr_message_free(event->message); free(event->data); - free(event); + ScrMessage *message = event->message; + /* An event in its message's block goes with the message. */ + if (!event->in_message) free(event); + scr_message_free(message); } void scr_mailbox_release(ScrMailbox *mailbox) { @@ -460,7 +462,7 @@ void scr_channel_set_owner(ScrChannel *channel, int side, ScrMailbox *owner, uns * messages as ready, so it does not wait while the queue is non-empty. */ bool scr_channel_post(ScrChannel *channel, int side, ScrMessage *message, unsigned message_kind, unsigned wake_kind) { - ScrMailEvent *event = calloc(1, sizeof(*event)); + ScrMailEvent *event = message ? scr_message_mail_event(message) : calloc(1, sizeof(*event)); if (!event) scr_trap("scriptc: out of memory\n"); event->kind = message_kind; event->message = message; diff --git a/packages/runtime/src/scr_mailbox.h b/packages/runtime/src/scr_mailbox.h index 4e5f253b5..a4acfccd0 100644 --- a/packages/runtime/src/scr_mailbox.h +++ b/packages/runtime/src/scr_mailbox.h @@ -12,8 +12,13 @@ typedef struct ScrMailEvent { unsigned char *data; /* raw bytes (a worker's captured stdout or stderr), owned */ size_t length; struct ScrMailEvent *next; + bool in_message; /* the event is the one message's block holds (scr_message_mail_event) */ } ScrMailEvent; +/* The event that carries `message`, in the message's own block: a queued + * message is then one allocation. Freeing the event frees the message. */ +ScrMailEvent *scr_message_mail_event(ScrMessage *message); + ScrMailbox *scr_mailbox_new(void); ScrMailbox *scr_mailbox_retain(ScrMailbox *mailbox); void scr_mailbox_release(ScrMailbox *mailbox); diff --git a/packages/runtime/src/scr_map.c b/packages/runtime/src/scr_map.c index 99caa31a8..1a6a3fc00 100644 --- a/packages/runtime/src/scr_map.c +++ b/packages/runtime/src/scr_map.c @@ -220,47 +220,106 @@ static bool scr_map_key_eq(const ScrMap *m, uint64_t stored, uint64_t probe) { * the value: its hash is the key word's scr_key_mix, which is cheap to * recompute, and its stored keys are normalized (one NaN pattern, +0), so * a dead entry marks its key with a NaN pattern that no stored key has. + * A SCR_MAP_VAL_CREF map (string keys, compact class values) keeps 16-byte + * entries: the key, its 32-bit hash and the value as an address over 8. * Every other map keeps 24-byte entries with the cached hash, zero for a - * dead entry. Both layouts put the key at byte 0 and the value at byte 8. */ + * dead entry. Every layout puts the key at byte 0; the 8-byte layouts put + * the value at byte 8. */ static inline bool scr_map_num(const ScrMap *m) { return m->key_kind == SCR_MAP_KEY_F64; } +static inline bool scr_map_cref(const ScrMap *m) { + return __builtin_expect(m->val_kind == SCR_MAP_VAL_CREF, 0); +} + static inline size_t scr_map_entry_size(const ScrMap *m) { - return scr_map_num(m) ? sizeof(ScrMapNumEntry) : sizeof(ScrMapEntry); + if (scr_map_num(m)) return sizeof(ScrMapNumEntry); + if (scr_map_cref(m)) return sizeof(ScrMapCEntry); + return sizeof(ScrMapEntry); } /* The entry at index e. A number-key entry has no hash field: read its key - * and value only (scr_map_hash_at gives the hash). */ + * and value only (scr_map_hash_at gives the hash); a SCR_MAP_VAL_CREF + * entry's value is read with scr_map_val_at. */ static inline ScrMapEntry *scr_map_at(const ScrMap *m, size_t e) { return (ScrMapEntry *)((char *)m->entries + e * scr_map_entry_size(m)); } +static inline ScrMapCEntry *scr_map_c_at(const ScrMap *m, size_t e) { + return (ScrMapCEntry *)m->entries + e; +} + static inline bool scr_map_live_at(const ScrMap *m, size_t e) { - const ScrMapEntry *x = scr_map_at(m, e); - return scr_map_num(m) ? x->key != SCR_MAP_NUM_DEAD : x->hash != 0; + if (scr_map_num(m)) return ((const ScrMapNumEntry *)m->entries)[e].key != SCR_MAP_NUM_DEAD; + if (scr_map_cref(m)) return scr_map_c_at(m, e)->hash != 0; + return m->entries[e].hash != 0; } /* The entry's hash, nonzero when it is live and zero for a dead entry. */ static inline uint64_t scr_map_hash_at(const ScrMap *m, size_t e) { - const ScrMapEntry *x = scr_map_at(m, e); - if (!scr_map_num(m)) return x->hash; - if (x->key == SCR_MAP_NUM_DEAD) return 0; - uint64_t hash = scr_map_hash_word(x->key); - return hash ? hash : 1; + if (scr_map_num(m)) { + uint64_t key = ((const ScrMapNumEntry *)m->entries)[e].key; + if (key == SCR_MAP_NUM_DEAD) return 0; + uint64_t hash = scr_map_hash_word(key); + return hash ? hash : 1; + } + if (scr_map_cref(m)) { + uint32_t h = scr_map_c_at(m, e)->hash; + return h ? scr_map_hash_widen(h) : 0; + } + return m->entries[e].hash; } static inline void scr_map_kill_at(ScrMap *m, size_t e) { - ScrMapEntry *x = scr_map_at(m, e); - if (scr_map_num(m)) x->key = SCR_MAP_NUM_DEAD; - else x->hash = 0; + if (scr_map_num(m)) ((ScrMapNumEntry *)m->entries)[e].key = SCR_MAP_NUM_DEAD; + else if (scr_map_cref(m)) scr_map_c_at(m, e)->hash = 0; + else m->entries[e].hash = 0; } +/* A compact value's 4-byte form and back (scr_cref_encode in scr_array.h). */ +static inline uint32_t scr_map_cref_encode(uint64_t val) { return (uint32_t)(val >> 3); } +static inline uint64_t scr_map_cref_decode(uint32_t val) { return (uint64_t)val << 3; } + +/* The value of entry e as an 8-byte slot, and its store. */ +static inline uint64_t scr_map_val_at(const ScrMap *m, size_t e) { + if (scr_map_num(m)) return ((const ScrMapNumEntry *)m->entries)[e].val; + if (scr_map_cref(m)) return scr_map_cref_decode(scr_map_c_at(m, e)->val); + return m->entries[e].val; +} + +static inline void scr_map_val_put(ScrMap *m, size_t e, uint64_t val) { + if (scr_map_num(m)) ((ScrMapNumEntry *)m->entries)[e].val = val; + else if (scr_map_cref(m)) scr_map_c_at(m, e)->val = scr_map_cref_encode(val); + else m->entries[e].val = val; +} + +/* A reference value as a +1 result: compact values are never counted. */ +static inline void *scr_map_val_retain(const ScrMap *m, uint64_t val) { + if (scr_map_cref(m)) return scr_map_slot_to_ptr(val); + return m->ops->val_retain(scr_map_slot_to_ptr(val)); +} + +/* A SCR_MAP_VAL_CREF map's keys are strings, whose hashes are widened + * 32-bit values: the entry keeps the low half. */ static inline void scr_map_put_at(ScrMap *m, size_t e, uint64_t key, uint64_t val, uint64_t hash) { - ScrMapEntry *x = scr_map_at(m, e); + if (scr_map_num(m)) { + ScrMapNumEntry *x = (ScrMapNumEntry *)m->entries + e; + x->key = key; + x->val = val; + return; + } + if (scr_map_cref(m)) { + ScrMapCEntry *x = scr_map_c_at(m, e); + x->key = key; + x->hash = (uint32_t)hash; + x->val = scr_map_cref_encode(val); + return; + } + ScrMapEntry *x = m->entries + e; x->key = key; x->val = val; - if (!scr_map_num(m)) x->hash = hash; + x->hash = hash; } /* ── absent-key filter ───────────────────────────────────────────────── @@ -282,17 +341,25 @@ static inline uint64_t scr_map_filter_bits(uint64_t hash) { * before equality and survive table growth without hashing the keys again. * Remap zero to one so every live entry has a nonzero hash. */ /* SCR_MAP_LOOKUP_NUM is a word compare on a number-key map, so the probe - * reads 16-byte entries; every other lookup is on a map with 24-byte - * entries. Knowing the layout from the lookup keeps the entry stride a - * constant in the inlined probes. */ + * reads 16-byte entries; SCR_MAP_LOOKUP_STR_C and SPAN_C are the string and + * span probes of a SCR_MAP_VAL_CREF map, whose 16-byte entries keep a + * 32-bit hash; every other lookup is on a map with 24-byte entries. Knowing + * the layout from the lookup keeps the entry stride a constant in the + * inlined probes. */ typedef enum { SCR_MAP_LOOKUP_STR, SCR_MAP_LOOKUP_SPAN, SCR_MAP_LOOKUP_WORD, SCR_MAP_LOOKUP_NUM, - SCR_MAP_LOOKUP_GENERIC + SCR_MAP_LOOKUP_GENERIC, + SCR_MAP_LOOKUP_STR_C, + SCR_MAP_LOOKUP_SPAN_C } ScrMapLookup; +static inline bool scr_map_lookup_c(ScrMapLookup lookup) { + return lookup == SCR_MAP_LOOKUP_STR_C || lookup == SCR_MAP_LOOKUP_SPAN_C; +} + typedef struct { const char *bytes; size_t length; } ScrMapSpan; /* Choose equality once per operation. Inlining the traversal with a constant @@ -301,12 +368,12 @@ typedef struct { const char *bytes; size_t length; } ScrMapSpan; static inline bool scr_map_lookup_eq(const ScrMap *m, uint64_t stored, uint64_t key, ScrMapLookup lookup) { if (lookup == SCR_MAP_LOOKUP_WORD || lookup == SCR_MAP_LOOKUP_NUM) return stored == key; - if (lookup == SCR_MAP_LOOKUP_SPAN) { + if (lookup == SCR_MAP_LOOKUP_SPAN || lookup == SCR_MAP_LOOKUP_SPAN_C) { const ScrStr *a = scr_map_slot_to_ptr(stored); const ScrMapSpan *b = scr_map_slot_to_ptr(key); return a->len == b->length && scr_key_equal(a->data, b->bytes, a->len); } - if (lookup == SCR_MAP_LOOKUP_STR) { + if (lookup == SCR_MAP_LOOKUP_STR || lookup == SCR_MAP_LOOKUP_STR_C) { const ScrStr *a = scr_map_slot_to_ptr(stored); const ScrStr *b = scr_map_slot_to_ptr(key); return a == b || (a->len == b->len && scr_key_equal(a->data, b->data, a->len)); @@ -318,6 +385,7 @@ static inline bool scr_map_lookup_eq(const ScrMap *m, uint64_t stored, uint64_t static inline __attribute__((always_inline)) ScrMapEntry *scr_map_at_with(const ScrMap *m, size_t e, ScrMapLookup lookup) { if (lookup == SCR_MAP_LOOKUP_NUM) return (ScrMapEntry *)((ScrMapNumEntry *)m->entries + e); + if (scr_map_lookup_c(lookup)) return (ScrMapEntry *)((ScrMapCEntry *)m->entries + e); return &m->entries[e]; } @@ -328,6 +396,8 @@ static inline __attribute__((always_inline)) bool scr_map_match_at( const ScrMap *m, size_t e, uint64_t hash, uint64_t key, ScrMapLookup lookup) { const ScrMapEntry *x = scr_map_at_with(m, e, lookup); if (lookup == SCR_MAP_LOOKUP_NUM) return x->key == key; + if (scr_map_lookup_c(lookup)) + return ((const ScrMapCEntry *)x)->hash == (uint32_t)hash && scr_map_lookup_eq(m, x->key, key, lookup); return x->hash == hash && scr_map_lookup_eq(m, x->key, key, lookup); } @@ -437,7 +507,7 @@ static inline __attribute__((always_inline)) size_t scr_map_find_with( static ScrMapLookup scr_map_lookup_kind(const ScrMap *m) { switch (m->key_kind) { - case SCR_MAP_KEY_STR: return SCR_MAP_LOOKUP_STR; + case SCR_MAP_KEY_STR: return scr_map_cref(m) ? SCR_MAP_LOOKUP_STR_C : SCR_MAP_LOOKUP_STR; case SCR_MAP_KEY_F64: return SCR_MAP_LOOKUP_NUM; case SCR_MAP_KEY_BOOL: case SCR_MAP_KEY_REF: @@ -484,6 +554,7 @@ static size_t scr_map_find(const ScrMap *m, uint64_t hash, uint64_t key) { if (m->ndense) return scr_map_find_dense(m, scr_map_slot_to_f64(key)); switch (scr_map_lookup_kind(m)) { case SCR_MAP_LOOKUP_STR: return scr_map_find_with(m, hash, key, SCR_MAP_LOOKUP_STR); + case SCR_MAP_LOOKUP_STR_C: return scr_map_find_with(m, hash, key, SCR_MAP_LOOKUP_STR_C); case SCR_MAP_LOOKUP_WORD: return scr_map_find_with(m, hash, key, SCR_MAP_LOOKUP_WORD); case SCR_MAP_LOOKUP_NUM: return scr_map_find_with(m, hash, key, SCR_MAP_LOOKUP_NUM); default: return scr_map_find_with(m, hash, key, SCR_MAP_LOOKUP_GENERIC); @@ -504,9 +575,24 @@ const ScrMapEntry *scr_map_entry_f64(const ScrMap *m, double key) { /* The key's hash is usually cached, so even the small linear scan rejects * entries by hash before touching their bytes. */ +/* The probes of a SCR_MAP_VAL_CREF map, out of line so that the inlined + * probes of other maps keep their size. */ +static __attribute__((noinline)) size_t scr_map_find_str_c(const ScrMap *m, const ScrStr *key) { + return scr_map_find_with(m, scr_map_hash_str(key), scr_map_slot_from_ptr((void *)key), + SCR_MAP_LOOKUP_STR_C); +} + +static __attribute__((noinline)) size_t scr_map_find_span_c(const ScrMap *m, const char *bytes, + size_t length) { + ScrMapSpan key = { bytes, length }; + return scr_map_find_with(m, scr_map_hash_bytes(bytes, length), scr_map_slot_from_ptr(&key), + SCR_MAP_LOOKUP_SPAN_C); +} + static inline __attribute__((always_inline)) size_t scr_map_find_str(const ScrMap *m, const ScrStr *key) { if (m->nlive == 0) return SCR_MAP_EMPTY; + if (scr_map_cref(m)) return scr_map_find_str_c(m, key); return scr_map_find_with(m, scr_map_hash_str(key), scr_map_slot_from_ptr((void *)key), SCR_MAP_LOOKUP_STR); } @@ -515,6 +601,7 @@ static inline __attribute__((always_inline)) size_t scr_map_find_str(const ScrMa * rules as a string key without allocating or copying the probe. */ static size_t scr_map_find_span(const ScrMap *m, const char *bytes, size_t length) { if (m->nlive == 0) return SCR_MAP_EMPTY; + if (scr_map_cref(m)) return scr_map_find_span_c(m, bytes, length); ScrMapSpan key = { bytes, length }; return scr_map_find_with(m, scr_map_hash_bytes(bytes, length), scr_map_slot_from_ptr(&key), SCR_MAP_LOOKUP_SPAN); @@ -523,20 +610,20 @@ static size_t scr_map_find_span(const ScrMap *m, const char *bytes, size_t lengt bool scr_map_get_span_f64(const ScrMap *m, const char *bytes, size_t length, double *out) { size_t e = scr_map_find_span(m, bytes, length); if (e == SCR_MAP_EMPTY) return false; - *out = scr_map_slot_to_f64(scr_map_at(m, e)->val); + *out = scr_map_slot_to_f64(scr_map_val_at(m, e)); return true; } bool scr_map_get_span_bool(const ScrMap *m, const char *bytes, size_t length, bool *out) { size_t e = scr_map_find_span(m, bytes, length); if (e == SCR_MAP_EMPTY) return false; - *out = scr_map_at(m, e)->val != 0; + *out = scr_map_val_at(m, e) != 0; return true; } void *scr_map_get_span_ref(const ScrMap *m, const char *bytes, size_t length) { size_t e = scr_map_find_span(m, bytes, length); - return e == SCR_MAP_EMPTY ? NULL : m->ops->val_retain(scr_map_slot_to_ptr(scr_map_at(m, e)->val)); + return e == SCR_MAP_EMPTY ? NULL : scr_map_val_retain(m, scr_map_val_at(m, e)); } /* Rebuild the bucket table (size must be a power of two >= 2 * nentries): @@ -666,7 +753,12 @@ static void scr_map_compact(ScrMap *m, bool reindex) { if (k > top) top = k; } filter |= scr_map_filter_bits(scr_map_hash_at(m, r)); - if (w != r) memcpy(scr_map_at(m, w), scr_map_at(m, r), scr_map_entry_size(m)); + if (w != r) { + /* A constant size per layout keeps the copy inline. */ + if (scr_map_num(m)) memcpy(scr_map_at(m, w), scr_map_at(m, r), sizeof(ScrMapNumEntry)); + else if (scr_map_cref(m)) memcpy(scr_map_at(m, w), scr_map_at(m, r), sizeof(ScrMapCEntry)); + else memcpy(scr_map_at(m, w), scr_map_at(m, r), sizeof(ScrMapEntry)); + } w++; } m->nentries = (uint32_t)w; @@ -778,7 +870,7 @@ static void scr_map_trace(void *o, ScrTraceVisit visit, void *ctx) { for (size_t e = 0; e < m->nentries; e++) { if (!scr_map_live_at(m, e)) continue; if (keys) visit(scr_map_slot_to_ptr(scr_map_at(m, e)->key), ctx); - if (vals) visit(scr_map_slot_to_ptr(scr_map_at(m, e)->val), ctx); + if (vals) visit(scr_map_slot_to_ptr(scr_map_val_at(m, e)), ctx); } } @@ -791,7 +883,7 @@ static void scr_map_gcfree(void *o) { for (size_t e = 0; e < m->nentries; e++) { if (!scr_map_live_at(m, e)) continue; if (!keys) scr_map_release_key(m, scr_map_at(m, e)->key); - if (!vals) scr_map_release_val(m, scr_map_at(m, e)->val); + if (!vals) scr_map_release_val(m, scr_map_val_at(m, e)); } scr_mem_free(m->entries); scr_mem_free(m->buckets); @@ -843,10 +935,15 @@ ScrMap *scr_map_retain(ScrMap *m) { static void scr_map_destroy(void *object) { ScrMap *m = object; scr_weak_dispose_inline(m); - for (size_t e = 0; e < m->nentries; e++) { - if (!scr_map_live_at(m, e)) continue; - scr_map_release_key(m, scr_map_at(m, e)->key); - scr_map_release_val(m, scr_map_at(m, e)->val); + /* Number and boolean keys, and values other than references, own + * nothing: a map of only those releases no entries. */ + bool keys = m->key_kind == SCR_MAP_KEY_STR || scr_map_ref_key(m->key_kind); + if (keys || m->val_kind == SCR_MAP_VAL_REF) { + for (size_t e = 0; e < m->nentries; e++) { + if (!scr_map_live_at(m, e)) continue; + scr_map_release_key(m, scr_map_at(m, e)->key); + scr_map_release_val(m, scr_map_val_at(m, e)); + } } scr_mem_free(m->entries); scr_mem_free(m->buckets); @@ -897,7 +994,7 @@ void scr_map_clear(ScrMap *m) { uint32_t *dense = m->ndense ? m->dense : NULL; for (size_t e = 0; e < walked; e++) { if (!scr_map_live_at(m, e)) continue; - uint64_t key = scr_map_at(m, e)->key, val = scr_map_at(m, e)->val; + uint64_t key = scr_map_at(m, e)->key, val = scr_map_val_at(m, e); scr_map_kill_at(m, e); if (dense) dense[(size_t)scr_map_slot_to_f64(key)] = 0; scr_map_release_key(m, key); @@ -955,7 +1052,7 @@ bool scr_map_has_str(const ScrMap *m, const ScrStr *key) { static bool scr_map_delete_found(ScrMap *m, size_t e) { if (e == SCR_MAP_EMPTY) return false; - uint64_t key = scr_map_at(m, e)->key, val = scr_map_at(m, e)->val; + uint64_t key = scr_map_at(m, e)->key, val = scr_map_val_at(m, e); scr_map_kill_at(m, e); /* bucket slot stays: probe chains intact */ m->nlive--; if (m->ndense) m->dense[(size_t)scr_map_slot_to_f64(key)] = 0; @@ -1060,6 +1157,11 @@ static inline __attribute__((always_inline)) void scr_map_set_with( e = scr_map_bucket(m, slot); } if (e != SCR_MAP_EMPTY) { + if (scr_map_lookup_c(lookup)) { + /* Compact values are never counted: nothing to release. */ + ((ScrMapCEntry *)m->entries)[e].val = scr_map_cref_encode(val); + return; + } ScrMapEntry *x = scr_map_at_with(m, e, lookup); uint64_t old = x->val; x->val = val; /* unlink before releasing (cycle collector) */ @@ -1069,7 +1171,18 @@ static inline __attribute__((always_inline)) void scr_map_set_with( scr_map_append(m, hash, key, val, slot); } +/* The insert of a SCR_MAP_VAL_CREF map, out of line so that the string-key + * insert of other maps keeps its size. */ +static __attribute__((noinline)) void scr_map_set_str_c(ScrMap *m, uint64_t hash, uint64_t key, + uint64_t val) { + scr_map_set_with(m, hash, key, val, SCR_MAP_LOOKUP_STR_C); +} + static void scr_map_set_str_slot(ScrMap *m, uint64_t hash, uint64_t key, uint64_t val) { + if (scr_map_cref(m)) { + scr_map_set_str_c(m, hash, key, val); + return; + } scr_map_set_with(m, hash, key, val, SCR_MAP_LOOKUP_STR); } @@ -1157,6 +1270,7 @@ static void scr_map_set(ScrMap *m, uint64_t hash, uint64_t key, uint64_t val) { } switch (scr_map_lookup_kind(m)) { case SCR_MAP_LOOKUP_STR: scr_map_set_str_slot(m, hash, key, val); return; + case SCR_MAP_LOOKUP_STR_C: scr_map_set_str_c(m, hash, key, val); return; case SCR_MAP_LOOKUP_WORD: scr_map_set_word(m, hash, key, val); return; case SCR_MAP_LOOKUP_NUM: scr_map_set_num(m, hash, key, val); return; default: scr_map_set_with(m, hash, key, val, SCR_MAP_LOOKUP_GENERIC); return; @@ -1246,10 +1360,14 @@ bool scr_map_get_str_bool(const ScrMap *m, const ScrStr *key, bool *out) { return true; } +/* scr_map_entry_str serves maps with 24-byte entries (generated code reads + * a SCR_MAP_VAL_CREF map through scr_map_entry_str_c). */ static __attribute__((noinline)) const ScrMapEntry *scr_map_entry_str_slow(const ScrMap *m, const ScrStr *key) { - size_t e = scr_map_find_str(m, key); - return e == SCR_MAP_EMPTY ? NULL : scr_map_at(m, e); + if (m->nlive == 0) return NULL; + size_t e = scr_map_find_with(m, scr_map_hash_str(key), scr_map_slot_from_ptr((void *)key), + SCR_MAP_LOOKUP_STR); + return e == SCR_MAP_EMPTY ? NULL : &m->entries[e]; } /* A stored key with the probe's hash but another identity: compare bytes. @@ -1302,10 +1420,60 @@ const ScrMapEntry *scr_map_entry_str(const ScrMap *m, const ScrStr *key) { return scr_map_entry_str_slow(m, key); } +static __attribute__((noinline)) const ScrMapCEntry *scr_map_entry_str_c_slow(const ScrMap *m, + const ScrStr *key) { + size_t e = scr_map_find_str(m, key); + return e == SCR_MAP_EMPTY ? NULL : scr_map_c_at(m, e); +} + +static __attribute__((noinline)) const ScrMapCEntry *scr_map_entry_str_c_bytes(const ScrMap *m, + const ScrStr *key, + const ScrMapCEntry *e) { + const ScrStr *stored = scr_map_slot_to_ptr(e->key); + if (stored->len == key->len && scr_key_equal(stored->data, key->data, key->len)) return e; + return scr_map_entry_str_c_slow(m, key); +} + +/* scr_map_entry_str over a SCR_MAP_VAL_CREF map's 16-byte entries, whose + * hash is the low half of the widened one. */ +const ScrMapCEntry *scr_map_entry_str_c(const ScrMap *m, const ScrStr *key) { +#if SCR_STR_HASH_CACHE + uint32_t h = key->hash; + size_t nbuckets = m->nbuckets; + if (__builtin_expect(h != 0 && scr_map_compact_buckets(nbuckets), 1)) { + uint64_t hash = scr_map_hash_widen(h); + uint64_t bits = scr_map_filter_bits(hash); + if ((m->filter & bits) != bits) return NULL; + const ScrMapCEntry *entries = (const ScrMapCEntry *)m->entries; + if (nbuckets == 0) { + for (size_t e = 0, n = m->nentries; e < n; e++) { + if (entries[e].hash != h) continue; + if (entries[e].key == scr_map_slot_from_ptr((void *)key)) return &entries[e]; + return scr_map_entry_str_c_bytes(m, key, &entries[e]); + } + return NULL; + } + const uint32_t *buckets = m->buckets; + uint32_t tag = (uint32_t)(hash >> 32 & UINT32_C(0xff000000)); + size_t mask = nbuckets - 1; + for (size_t i = hash & mask;; i = (i + 1) & mask) { + uint32_t bucket = buckets[i]; + if (!bucket) return NULL; + if ((bucket & ~SCR_MAP_INDEX_MASK) != tag) continue; + const ScrMapCEntry *e = &entries[(bucket & SCR_MAP_INDEX_MASK) - 1]; + if (e->hash != h) continue; + if (e->key == scr_map_slot_from_ptr((void *)key)) return e; + return scr_map_entry_str_c_bytes(m, key, e); + } + } +#endif + return scr_map_entry_str_c_slow(m, key); +} + void *scr_map_get_str_ref(const ScrMap *m, const ScrStr *key) { size_t e = scr_map_find_str(m, key); if (e == SCR_MAP_EMPTY) return NULL; - return m->ops->val_retain(scr_map_slot_to_ptr(scr_map_at(m, e)->val)); /* +1 */ + return scr_map_val_retain(m, scr_map_val_at(m, e)); /* +1 */ } bool scr_map_get_ref_f64(const ScrMap *m, const void *key, double *out) { @@ -1408,6 +1576,12 @@ static const ScrMapEntry *scr_map_iter_at(const ScrMap *m, double i) { return scr_map_at(m, (size_t)i); } +/* The value of the live entry at iteration index i as an 8-byte slot. */ +static uint64_t scr_map_iter_val_slot(const ScrMap *m, double i) { + (void)scr_map_iter_at(m, i); + return scr_map_val_at(m, (size_t)i); +} + double scr_map_iter_key_f64(const ScrMap *m, double i) { return scr_map_slot_to_f64(scr_map_iter_at(m, i)->key); } @@ -1442,7 +1616,7 @@ ScrDyn *scr_map_dyn_key(const ScrMap *map, double index) { } ScrDyn *scr_map_dyn_value(const ScrMap *map, double index) { - uint64_t slot = scr_map_iter_at(map, index)->val; + uint64_t slot = scr_map_iter_val_slot(map, index); return map->dyn_ops ? map->dyn_ops->val_box(slot) : scr_dyn_retain(scr_map_slot_to_ptr(slot)); } @@ -1491,6 +1665,9 @@ ScrMap *scr_map_clone(const ScrMap *source, bool keys_only, const ScrMapOps *ops if (!out->entries) scr_map_oom(); out->ecap = (uint32_t)count; size_t top = 0; + /* A key-only copy of a SCR_MAP_VAL_CREF map has the 24-byte layout: its + * entries are copied field by field. */ + bool same_layout = scr_map_cref(source) == scr_map_cref(out); for (size_t i = 0; i < source->nentries; i++) { if (!scr_map_live_at(source, i)) continue; const ScrMapEntry *entry = scr_map_at(source, i); @@ -1498,11 +1675,13 @@ ScrMap *scr_map_clone(const ScrMap *source, bool keys_only, const ScrMapOps *ops size_t k = (size_t)scr_map_slot_to_f64(entry->key); if (k > top) top = k; } - ScrMapEntry *copy = scr_map_at(out, out->nentries++); - memcpy(copy, entry, entry_size); + size_t e = out->nentries++; + ScrMapEntry *copy = scr_map_at(out, e); + if (__builtin_expect(same_layout, 1)) memcpy(copy, entry, entry_size); + else scr_map_put_at(out, e, entry->key, keys_only ? 0 : scr_map_val_at(source, i), scr_map_hash_at(source, i)); if (out->key_kind == SCR_MAP_KEY_STR) scr_str_retain(scr_map_slot_to_ptr(copy->key)); else if (scr_map_ref_key(out->key_kind)) out->ops->key_retain(scr_map_slot_to_ptr(copy->key)); - if (keys_only) copy->val = 0; + if (keys_only) scr_map_val_put(out, e, 0); else if (out->val_kind == SCR_MAP_VAL_REF) out->ops->val_retain(scr_map_slot_to_ptr(copy->val)); } out->nlive = (uint32_t)count; @@ -1527,7 +1706,7 @@ ScrMap *scr_map_clone(const ScrMap *source, bool keys_only, const ScrMapOps *ops const ScrMapOps scr_map_dyn_set_ops = { scr_dyn_retain_v, scr_dyn_release_v, scr_dyn_trace_v, NULL, NULL, NULL, NULL }; -static const ScrMapOps scr_map_dyn_map_ops = { +const ScrMapOps scr_map_dyn_map_ops = { scr_dyn_retain_v, scr_dyn_release_v, scr_dyn_trace_v, scr_dyn_retain_v, scr_dyn_release_v, scr_dyn_trace_v, NULL }; @@ -1550,7 +1729,7 @@ ScrMap *scr_map_clone_dyn(const ScrMap *source, bool keys_only) { void scr_map_values_into(ScrMap *set, const ScrMap *source, bool checked) { for (size_t i = 0; i < source->nentries; i++) { if (!scr_map_live_at(source, i)) continue; - uint64_t value = checked ? scr_map_slot_from_ptr(scr_map_dyn_value(source, (double)i)) : scr_map_at(source, i)->val; + uint64_t value = checked ? scr_map_slot_from_ptr(scr_map_dyn_value(source, (double)i)) : scr_map_val_at(source, i); if (set->key_kind == SCR_MAP_KEY_F64) value = scr_map_f64_bits(scr_map_slot_to_f64(value)); scr_map_set(set, scr_map_hash_key(set, value), value, 0); if (checked) scr_dyn_release(scr_map_slot_to_ptr(value)); @@ -1567,7 +1746,7 @@ ScrArr *scr_set_to_arr_dyn(const ScrMap *map) { } void *scr_map_iter_val_ref(const ScrMap *m, double i) { - return m->ops->val_retain(scr_map_slot_to_ptr(scr_map_iter_at(m, i)->val)); /* +1 */ + return scr_map_val_retain(m, scr_map_iter_val_slot(m, i)); /* +1 */ } /* A published (immortal) map never changes, so iterating it needs no @@ -1600,7 +1779,7 @@ void scr_set_add_all(ScrMap *set, ScrArr *values) { /* Packed values stay owned by the seed array throughout construction. * Avoid taking a temporary owner only to release it after insertion. * Sparse/missing positions retain the existing accessor semantics. */ - if (i < values->cap && *scr_arr_state_ptr(values, i) == SCR_ARR_VALUE) { + if (i < values->cap && scr_arr_dense_state(values, i) == SCR_ARR_VALUE) { uint64_t key = scr_arr_dense_get(values, i); if (set->key_kind == SCR_MAP_KEY_F64) key = scr_map_f64_bits(scr_map_slot_to_f64(key)); scr_map_set(set, scr_map_hash_key(set, key), key, 0); diff --git a/packages/runtime/src/scr_map.h b/packages/runtime/src/scr_map.h index c61df9a90..d1ca387bf 100644 --- a/packages/runtime/src/scr_map.h +++ b/packages/runtime/src/scr_map.h @@ -50,7 +50,11 @@ typedef enum { SCR_MAP_KEY_BIGINT, SCR_MAP_KEY_BOOL, SCR_MAP_KEY_UNION_VALUE, SCR_MAP_KEY_NULL, SCR_MAP_KEY_UNDEFINED /* tag-only union arms */ } ScrMapKeyKind; -typedef enum { SCR_MAP_VAL_F64, SCR_MAP_VAL_BOOL, SCR_MAP_VAL_REF } ScrMapValKind; +/* SCR_MAP_VAL_CREF: a string-key map whose values are compact class + * instances in the program-lifetime region (llvm/classes.ts + * LlClassMeta.compact). Its entries are ScrMapCEntry; the values are never + * counted or traced. */ +typedef enum { SCR_MAP_VAL_F64, SCR_MAP_VAL_BOOL, SCR_MAP_VAL_REF, SCR_MAP_VAL_CREF } ScrMapValKind; typedef struct { uint64_t key; /* double bits (normalized), ScrStr* (owned), or ref ptr (owned) */ @@ -65,6 +69,15 @@ typedef struct { uint64_t val; } ScrMapNumEntry; #define SCR_MAP_NUM_DEAD UINT64_C(0x7ff0000000000001) +/* A SCR_MAP_VAL_CREF map's entry: the string key, the key's 32-bit hash + * (its cached 64-bit hash is the same value in both halves, + * scr_map.c scr_map_hash_widen; zero = tombstone), and the value as an + * address over 8 (0 for NULL). */ +typedef struct { + uint64_t key; + uint32_t hash; + uint32_t val; +} ScrMapCEntry; /* Checked views use the original storage. Slot converters borrow on reads * and return owned references on writes, just like typed Map operations. */ @@ -140,16 +153,25 @@ typedef struct ScrMap { * the whole deleted prefix again. */ uint32_t head; } ScrMap; -/* The entry at index i of either layout, and whether it is live (code that - * walks a map's entries outside scr_map.c). Key and value are at bytes 0 - * and 8 in both layouts; a number-key entry has no hash field. */ +/* The entry at index i of any layout, whether it is live, and its value as + * an 8-byte slot (code that walks a map's entries outside scr_map.c). The + * key is at byte 0 in every layout; a number-key entry has no hash field, + * and a SCR_MAP_VAL_CREF entry keeps its value in 4 bytes. */ static inline const ScrMapEntry *scr_map_entry_at(const ScrMap *m, size_t i) { - size_t size = m->key_kind == SCR_MAP_KEY_F64 ? sizeof(ScrMapNumEntry) : sizeof(ScrMapEntry); + size_t size = m->key_kind == SCR_MAP_KEY_F64 ? sizeof(ScrMapNumEntry) + : m->val_kind == SCR_MAP_VAL_CREF ? sizeof(ScrMapCEntry) + : sizeof(ScrMapEntry); return (const ScrMapEntry *)((const char *)m->entries + i * size); } static inline bool scr_map_entry_live(const ScrMap *m, size_t i) { const ScrMapEntry *e = scr_map_entry_at(m, i); - return m->key_kind == SCR_MAP_KEY_F64 ? e->key != SCR_MAP_NUM_DEAD : e->hash != 0; + if (m->key_kind == SCR_MAP_KEY_F64) return e->key != SCR_MAP_NUM_DEAD; + if (m->val_kind == SCR_MAP_VAL_CREF) return ((const ScrMapCEntry *)e)->hash != 0; + return e->hash != 0; +} +static inline uint64_t scr_map_entry_val(const ScrMap *m, const ScrMapEntry *e) { + if (m->val_kind == SCR_MAP_VAL_CREF) return (uint64_t)((const ScrMapCEntry *)e)->val << 3; + return e->val; } /* The LLVM backend reads the header through two types (emitter.ts). Its * inline retain/release test the traced byte as %ScrMapRc field 3, as @@ -162,7 +184,8 @@ static inline bool scr_map_entry_live(const ScrMap *m, size_t i) { * third field (sc_map_iter_entry), or for a number-key map its key against * SCR_MAP_NUM_DEAD (sc_map_iter_entry_num). Iteration over a checked * (unknown-key) Map or Set picks one of the two steps from the key kind, - * %ScrMapIx field 1, compared with SCR_MAP_KEY_F64 (0). */ + * %ScrMapIx field 1, compared with SCR_MAP_KEY_F64 (0). Map.size + * (sc_map_size) reads the live count, field 9, as scr_map_size does. */ _Static_assert(offsetof(ScrMap, key_kind) == sizeof(size_t) && SCR_MAP_KEY_F64 == 0, "inline iteration over checked collections reads ScrMap.key_kind as %ScrMapIx field 1"); _Static_assert(offsetof(ScrMap, traced) == sizeof(size_t) + 2, @@ -193,6 +216,9 @@ _Static_assert(sizeof(ScrMapEntry) == 24 && offsetof(ScrMapEntry, val) == 8, "inline lookups read ScrMapEntry.val at byte 8"); _Static_assert(sizeof(ScrMapNumEntry) == 16 && offsetof(ScrMapNumEntry, val) == 8, "inline number-key lookups and iteration read %ScrMapNumEntry { key, val }"); +_Static_assert(sizeof(ScrMapCEntry) == 16 && offsetof(ScrMapCEntry, hash) == 8 && + offsetof(ScrMapCEntry, val) == 12, + "inline compact-value lookups and iteration read %ScrMapCEntry { key, hash, val }"); _Static_assert(sizeof(ScrMap) <= 11 * sizeof(uint64_t), "the ScrMap header stays within 88 bytes"); /* Entry for a number key, or NULL when absent. The pointer is valid until * the next mutation; generated code reads the value slot through it. */ @@ -201,6 +227,9 @@ const ScrMapEntry *scr_map_entry_f64(const ScrMap *m, double key); * reference reads retain the value with its static type's retain instead * of the collection's adapter. */ const ScrMapEntry *scr_map_entry_str(const ScrMap *m, const ScrStr *key); +/* scr_map_entry_str for a SCR_MAP_VAL_CREF map: its entry is a + * ScrMapCEntry. */ +const ScrMapCEntry *scr_map_entry_str_c(const ScrMap *m, const ScrStr *key); /* String-key lookups borrow an exact byte span. Reference results return * +1; scalar outputs are written only on a hit, like the string getters. */ @@ -214,8 +243,10 @@ void *scr_map_get_span_ref(const ScrMap *m, const char *bytes, size_t length); * adapters); NULL keeps the source's descriptor. */ ScrMap *scr_map_clone(const ScrMap *source, bool keys_only, const ScrMapOps *ops); ScrMap *scr_map_clone_dyn(const ScrMap *source, bool keys_only); -/* The descriptor of a Set of checked values (SCR_MAP_KEY_DYN keys). */ +/* The descriptors of a Set and a Map of checked values (SCR_MAP_KEY_DYN + * keys; the Map's values are checked values too). */ extern const ScrMapOps scr_map_dyn_set_ops; +extern const ScrMapOps scr_map_dyn_map_ops; void scr_map_values_into(ScrMap *set, const ScrMap *source, bool checked); void scr_map_dyn_attach(ScrMap *map, const ScrMapDynOps *ops); diff --git a/packages/runtime/src/scr_message.c b/packages/runtime/src/scr_message.c index 5e1bce37f..d4eb263cf 100644 --- a/packages/runtime/src/scr_message.c +++ b/packages/runtime/src/scr_message.c @@ -1,32 +1,9 @@ #include "scr_message.h" +#include "scr_mailbox.h" #include #include -typedef enum { - SCR_MESSAGE_UNDEFINED, - SCR_MESSAGE_NULL, - SCR_MESSAGE_BOOL, - SCR_MESSAGE_NUMBER, - SCR_MESSAGE_STRING, - SCR_MESSAGE_BIGINT, - SCR_MESSAGE_ARRAY, - SCR_MESSAGE_OBJECT, - SCR_MESSAGE_STORAGE, - SCR_MESSAGE_BYTES, - SCR_MESSAGE_ARRAY_BUFFER, - SCR_MESSAGE_ERROR, - /* A deeply frozen plain-data graph shared by pointer (see publication). */ - SCR_MESSAGE_PUBLISHED, - /* A typed value published with @scriptc/threads (immortal), delivered as - * a fresh typed-ref capsule over the same pointer. */ - SCR_MESSAGE_TYPED_REF, - /* A transferred MessagePort: its channel end (+1) and side. */ - SCR_MESSAGE_PORT, - /* A native handle cloned through its unit's ScrDynHandleTransfer. */ - SCR_MESSAGE_HANDLE, -} ScrMessageKind; - const ScrMessagePortOps *scr_message_port_ops = NULL; typedef struct { @@ -95,6 +72,8 @@ struct ScrMessage { size_t count; bool storage; /* has STORAGE nodes */ bool releases; /* has STORAGE, PORT or HANDLE nodes, which own resources */ + bool readable; /* see scr_message_readable */ + ScrMailEvent event; /* the event that carries the message (scr_message_mail_event) */ }; typedef struct { @@ -121,6 +100,10 @@ typedef struct { * and properties allocates only its block. */ #define SCR_MESSAGE_INLINE 8 +/* How deep live records nest before the rest of a graph encodes through + * the visit stack (scr_message_value recurses for them). */ +#define SCR_MESSAGE_RECORD_DEPTH 32 + typedef struct { ScrMessageNode *nodes; ScrMessageVisit *visits; @@ -143,6 +126,9 @@ typedef struct { bool uncaught; /* the next value is an uncaught exception or its cause */ bool storage; bool releases; + bool shared; /* a node was reached twice */ + size_t record_depth; /* live records being encoded from their fields */ + bool adopts; /* has PORT or HANDLE nodes */ ScrMessageNode inline_nodes[SCR_MESSAGE_INLINE]; ScrMessageVisit inline_visits[SCR_MESSAGE_INLINE]; ScrMessagePending inline_properties[SCR_MESSAGE_INLINE]; @@ -168,7 +154,8 @@ static void scr_message_encoder_init(ScrMessageEncoder *encoder, const ScrDyn *t encoder->stack_capacity = SCR_MESSAGE_INLINE; encoder->transfer = transfer; encoder->uncaught = uncaught; - encoder->storage = encoder->releases = false; + encoder->storage = encoder->releases = encoder->shared = encoder->adopts = false; + encoder->record_depth = 0; } static bool scr_message_listed(const ScrMessageEncoder *encoder, const ScrDyn *value) { @@ -290,7 +277,10 @@ static void scr_message_push(ScrMessageEncoder *encoder, size_t node) { static size_t scr_message_storage(ScrMessageEncoder *encoder, const ScrBytes *bytes) { const ScrBytes *owner = bytes->backing ? bytes->backing : bytes; size_t found = scr_message_find(encoder, owner, SCR_MESSAGE_STORAGE + 1); - if (found != SIZE_MAX) return found; + if (found != SIZE_MAX) { + encoder->shared = true; + return found; + } size_t node = scr_message_node(encoder); scr_message_identify(encoder, owner, SCR_MESSAGE_STORAGE + 1, node); ScrMessageNode *storage = &encoder->nodes[node]; @@ -339,6 +329,10 @@ static ScrDyn *scr_message_uncaught_keys(const ScrDyn *view) { return keys; } +static void scr_message_property(ScrMessageEncoder *encoder, size_t id, + const ScrStr *key, size_t value, bool hidden); +static bool scr_message_drain(ScrMessageEncoder *encoder, size_t base); + static size_t scr_message_value(ScrMessageEncoder *encoder, const ScrDyn *input) { bool uncaught = encoder->uncaught; encoder->uncaught = false; @@ -360,7 +354,10 @@ static size_t scr_message_value(ScrMessageEncoder *encoder, const ScrDyn *input) return SIZE_MAX; } size_t found = scr_message_find(encoder, identity, domain); - if (found != SIZE_MAX) return found; + if (found != SIZE_MAX) { + encoder->shared = true; + return found; + } size_t id = scr_message_node(encoder); scr_message_identify(encoder, identity, domain, id); encoder->visits[id].input = scr_dyn_retain((ScrDyn *)input); @@ -397,6 +394,46 @@ static size_t scr_message_value(ScrMessageEncoder *encoder, const ScrDyn *input) node->v.published = (ScrDyn *)input; return id; } + /* A live record capsule (scr_dyn_typed_ref_bind_record) whose view was + * never created encodes its fields from the record: the view would hold + * exactly those keys, in that order, with the values its ops box. Nested + * records encode the same way up to a depth, then through their views + * and the visit stack. */ + const ScrDynTypedRecordOps *record = + input->kind == SCR_DYN_TYPED_REF && encoder->record_depth < SCR_MESSAGE_RECORD_DEPTH + ? scr_dyn_typed_ref_live_record(input) : NULL; + if (record) { + encoder->visits[id].view = (ScrDyn *)input; + encoder->nodes[id].kind = SCR_MESSAGE_OBJECT; + void *rec = input->v.typed_ref.ptr; + encoder->record_depth++; + size_t result = id; + /* A field's value encodes completely, its containers' properties + * included, before the next field's: getters run in Node's order. */ + size_t base = encoder->depth; + for (size_t i = 0; i < record->count; i++) { + if (!record->fixed && !record->has(rec, i)) continue; + ScrDyn *child = record->get(rec, i); + if (!child || scr_exc_pending()) { + scr_dyn_release(child); + result = SIZE_MAX; + break; + } + size_t next = scr_message_value(encoder, child); + scr_dyn_release(child); + if (next == SIZE_MAX) { + result = SIZE_MAX; + break; + } + scr_message_property(encoder, id, record->names[i], next, false); + if (encoder->depth > base && !scr_message_drain(encoder, base)) { + result = SIZE_MAX; + break; + } + } + encoder->record_depth--; + return result; + } ScrDyn *value = input->kind == SCR_DYN_TYPED_REF ? scr_dyn_typed_ref_materialize(input) : (ScrDyn *)input; encoder->visits[id].view = value; @@ -482,7 +519,7 @@ static size_t scr_message_value(ScrMessageEncoder *encoder, const ScrDyn *input) node->kind = SCR_MESSAGE_PORT; node->v.port.channel = channel; node->v.port.side = side; - encoder->releases = true; + encoder->releases = encoder->adopts = true; break; } bool buffer = scr_buffer_storage_is(value); @@ -498,7 +535,7 @@ static size_t scr_message_value(ScrMessageEncoder *encoder, const ScrDyn *input) node->kind = SCR_MESSAGE_HANDLE; node->v.handle.transfer = transfer; node->v.handle.payload = payload; - encoder->releases = true; + encoder->releases = encoder->adopts = true; break; } const ScrBytes *bytes = buffer ? value->v.handle.ptr : value->v.bytes; @@ -678,6 +715,7 @@ static ScrMessage *scr_message_try_publish(const ScrDyn *value) { message = scr_message_alloc(1, sizeof(*message) + sizeof(*message->nodes)); message->nodes = (ScrMessageNode *)(message + 1); message->count = 1; + message->readable = true; message->nodes[0].kind = SCR_MESSAGE_PUBLISHED; message->nodes[0].v.published = (ScrDyn *)value; if (getenv("SCRIPTC_PUBLISH_TRACE")) @@ -770,7 +808,8 @@ static ScrMessage *scr_message_pack(ScrMessageEncoder *encoder) { ScrMessageProperty *slots = (ScrMessageProperty *)(nodes + count); ScrMessageTyped *records = (ScrMessageTyped *)(slots + properties); char *text = (char *)(records + typed); - *message = (ScrMessage){nodes, count, encoder->storage, encoder->releases}; + *message = (ScrMessage){.nodes = nodes, .count = count, .storage = encoder->storage, + .releases = encoder->releases, .readable = !encoder->shared && !encoder->adopts}; memcpy(nodes, encoder->nodes, count * sizeof(*nodes)); if (typed) memcpy(records, encoder->typed, typed * sizeof(*records)); size_t first = 0; @@ -801,10 +840,11 @@ static ScrMessage *scr_message_pack(ScrMessageEncoder *encoder) { return message; } -static ScrMessage *scr_message_encode_run(ScrMessageEncoder *encoder, const ScrDyn *value) { - ScrMessage *message = NULL; - if (scr_message_value(encoder, value) == SIZE_MAX) goto done; - while (encoder->depth && !scr_exc_pending()) { +/* Encodes the properties of the containers on the visit stack above + * `base`, depth first, as Node's serializer visits them (getters run in + * that order). False when a property could not be read or encoded. */ +static bool scr_message_drain(ScrMessageEncoder *encoder, size_t base) { + while (encoder->depth > base && !scr_exc_pending()) { size_t id = encoder->stack[encoder->depth - 1]; ScrMessageVisit *visit = &encoder->visits[id]; if (visit->cursor == visit->keys->v.arr.len) { encoder->depth--; continue; } @@ -812,7 +852,7 @@ static ScrMessage *scr_message_encode_run(ScrMessageEncoder *encoder, const ScrD bool error = encoder->nodes[id].kind == SCR_MESSAGE_ERROR; if (key->kind != SCR_DYN_STR || (!error && !scr_dyn_property_is_enumerable(visit->view, key->v.str))) continue; ScrDyn *child = scr_dyn_bag_get(visit->view, key->v.str, visit->view); - if (!child || scr_exc_pending()) { scr_dyn_release(child); break; } + if (!child || scr_exc_pending()) { scr_dyn_release(child); return false; } bool hidden = error; if (visit->uncaught) { /* Node keeps an uncaught Error's data properties except functions @@ -823,10 +863,15 @@ static ScrMessage *scr_message_encode_run(ScrMessageEncoder *encoder, const ScrD } size_t next = scr_message_value(encoder, child); scr_dyn_release(child); - if (next == SIZE_MAX) break; + if (next == SIZE_MAX) return false; scr_message_property(encoder, id, key->v.str, next, hidden); } -done: + return !scr_exc_pending(); +} + +static ScrMessage *scr_message_encode_run(ScrMessageEncoder *encoder, const ScrDyn *value) { + ScrMessage *message = NULL; + if (scr_message_value(encoder, value) != SIZE_MAX) scr_message_drain(encoder, 0); if (!scr_exc_pending()) message = scr_message_pack(encoder); else for (size_t i = 0; i < encoder->count; i++) scr_message_drop(&encoder->nodes[i]); @@ -1014,6 +1059,33 @@ done:; return result; } +bool scr_message_readable(const ScrMessage *message) { return message->readable; } + +ScrMailEvent *scr_message_mail_event(ScrMessage *message) { + message->event = (ScrMailEvent){.message = message, .in_message = true}; + return &message->event; +} + +int32_t scr_message_kind(const ScrMessage *message, size_t node) { return message->nodes[node].kind; } + +double scr_message_number(const ScrMessage *message, size_t node) { return message->nodes[node].v.number; } + +ScrStr *scr_message_string(const ScrMessage *message, size_t node) { + return scr_str_new(message->nodes[node].v.text.data, message->nodes[node].v.text.length); +} + +bool scr_message_fields(const ScrMessage *message, size_t node, const char *const *names, + const size_t *lengths, size_t count, size_t *values) { + const ScrMessageNode *object = &message->nodes[node]; + if (object->kind != SCR_MESSAGE_OBJECT || object->count != count) return false; + for (size_t i = 0; i < count; i++) { + const ScrMessageProperty *property = &object->properties[i]; + if (property->length != lengths[i] || memcmp(property->key, names[i], lengths[i])) return false; + values[i] = property->value; + } + return true; +} + void scr_message_free(ScrMessage *message) { if (!message) return; if (message->releases) diff --git a/packages/runtime/src/scr_message.test.c b/packages/runtime/src/scr_message.test.c index bdabc4d12..b6adf34c5 100644 --- a/packages/runtime/src/scr_message.test.c +++ b/packages/runtime/src/scr_message.test.c @@ -250,6 +250,52 @@ static void check_large(void) { scr_message_free(message); } +/* The readers compiled 'message' listeners use: node kinds and values, a + * record's keys in order, and which messages they may read. */ +static void check_readers(void) { + ScrDyn *root = scr_dyn_new_obj(); + put_number(root, "id", 7); + ScrStr *text = scr_str_new("seven", 5); + scr_dyn_obj_set(root, "name", 4, scr_dyn_new_str(text)); + scr_str_release(text); + scr_dyn_obj_set(root, "done", 4, scr_dyn_new_bool(true)); + ScrMessage *message = scr_message_encode(root); + assert(message && scr_message_readable(message)); + assert(scr_message_kind(message, 0) == SCR_MESSAGE_OBJECT); + static const char *const names[] = {"id", "name", "done"}; + static const size_t lengths[] = {2, 4, 4}; + size_t values[3]; + assert(scr_message_fields(message, 0, names, lengths, 3, values)); + assert(scr_message_kind(message, values[0]) == SCR_MESSAGE_NUMBER); + assert(scr_message_number(message, values[0]) == 7); + assert(scr_message_kind(message, values[1]) == SCR_MESSAGE_STRING); + ScrStr *name = scr_message_string(message, values[1]); + assert(name->len == 5 && !memcmp(name->data, "seven", 5)); + scr_str_release(name); + assert(scr_message_kind(message, values[2]) == SCR_MESSAGE_BOOL); + assert(scr_message_number(message, values[2]) == 1); + /* Another order, a missing key or an extra key does not match. */ + static const char *const reordered[] = {"name", "id", "done"}; + static const size_t reordered_lengths[] = {4, 2, 4}; + assert(!scr_message_fields(message, 0, reordered, reordered_lengths, 3, values)); + assert(!scr_message_fields(message, 0, names, lengths, 2, values)); + assert(!scr_message_fields(message, values[0], names, lengths, 3, values)); + scr_message_free(message); + put_number(root, "extra", 1); + message = scr_message_encode(root); + assert(!scr_message_fields(message, 0, names, lengths, 3, values)); + scr_message_free(message); + /* A value reached twice makes the message unreadable. */ + ScrDyn *shared = scr_dyn_new_obj(); + scr_dyn_obj_set(root, "first", 5, scr_dyn_retain(shared)); + scr_dyn_obj_set(root, "second", 6, shared); + message = scr_message_encode(root); + assert(message && !scr_message_readable(message)); + scr_message_free(message); + scr_dyn_release(root); + scr_collect_cycles(); +} + /* A link-gated unit's handle crosses threads through the transfer hooks in * its ops: share on the sender, adopt on the receiver, drop with the * message. The test borrows the last capacity slot, which no unit uses, so @@ -376,6 +422,7 @@ int main(void) { check_rejection(); check_documents(); check_large(); + check_readers(); check_handle_transfer(); scr_context_cleanup(); puts("message graphs preserve identity, sparse values, byte aliases and getter order"); diff --git a/packages/runtime/src/scr_net.c b/packages/runtime/src/scr_net.c index f091daede..29a4af393 100644 --- a/packages/runtime/src/scr_net.c +++ b/packages/runtime/src/scr_net.c @@ -517,6 +517,9 @@ struct ScrNetSocket { int remote_port_cache; bool remote_v6_cache; ScrStr *pending_err; /* deferred connect failure */ + /* pending_err's code when its message does not name one (static + * storage; NULL = the code the message maps to) */ + const char *pending_code; /* the caller-lookup dial (net.connect with a lookup option): true while * the lookup decides; dial_ips holds its answered addresses (+1 each), * dialed in order — a connect failure closes the fd and tries @@ -531,6 +534,9 @@ struct ScrNetSocket { size_t dial_n, dial_i; /* a host name the dial resolves first (+1; NULL for IP literals) */ ScrStr *dial_host; + /* the host a client dial was given, Node's socket._host (+1; NULL on + * server sockets): tls.connect({ socket }) verifies against it */ + ScrStr *host_name; /* the in-flight dial chain's LAST failure — surfaced (moved into * pending_err) only when the list exhausts; a later success drops it */ ScrStr *dial_err; @@ -607,6 +613,12 @@ struct ScrNetSocket { * until the proxy answers 200: writes buffer and the transport * handshake waits until the tunnel is up */ struct ScrNetTunnel *tunnel; + /* new tls.TLSSocket(socket) and tls.connect({ socket }): on the wrapped + * socket, the socket that took over its connection (+1; end() and + * destroy() act on it); on that socket, the one it took over (+1; its + * 'close' fires just before this socket's, as in Node) */ + struct ScrNetSocket *adopted_by; + struct ScrNetSocket *adopted_from; }; /* The CONNECT head still being sent from out_off, and the proxy's @@ -616,6 +628,9 @@ typedef struct ScrNetTunnel { size_t out_len, out_off; char *in; size_t in_len; + /* bytes a wrapped socket left unsent, which go out before the + * transport's own; no response head is read */ + bool send_only; } ScrNetTunnel; /* The 'lookup' event's half of the runtime, installed by the first @@ -712,6 +727,7 @@ void scr_net_sock_release(ScrNetSocket *s) { free(s->dial_ips); scr_str_release(s->dial_err); scr_str_release(s->dial_host); + scr_str_release(s->host_name); scr_str_release(s->unix_path); scr_net_ls_drop(&s->lookup_ls); if (s->lookup_evs != NULL) scr_net_lookup_ops->free(s); @@ -721,6 +737,8 @@ void scr_net_sock_release(ScrNetSocket *s) { if (s->pipe_dst) scr_net_sock_release(s->pipe_dst); if (s->conn_pending) scr_net_server_release(s->conn_pending); if (s->server) scr_net_server_release(s->server); + if (s->adopted_by) scr_net_sock_release(s->adopted_by); + if (s->adopted_from) scr_net_sock_release(s->adopted_from); if (s->fd >= 0) scr_net_close_fd_raw(s->fd); #ifdef SCR_RC_AUDIT scr_net_live--; @@ -962,7 +980,7 @@ static ScrNetSocket *scr_net_sock_new(void) { static void scr_net_sock_update_read(ScrNetSocket *s) { bool want = s->fd >= 0 && !s->connecting && !s->rd_eof && !s->user_paused && (s->data_ls.n > 0 || s->pipe_dst != NULL || s->native_data != NULL || - s->tunnel != NULL /* the proxy's CONNECT answer */ || + (s->tunnel != NULL && !s->tunnel->send_only) /* the proxy's CONNECT answer */ || s->flowing /* resume(): flow (and discard sans listeners) */ || s->readable_ls.n > 0 /* paused-mode consumer: bytes buffer */ || s->tops != NULL /* a transport is ALWAYS a consumer: the TLS @@ -977,7 +995,8 @@ static void scr_net_sock_update_read(ScrNetSocket *s) { * finished socket the same way */ || (!s->eof_pending && s->rlen - s->rhead < SCR_NET_READ_AHEAD) /* no consumer yet: read ahead into the buffer, as Node's - * stream does up to its high-water mark */); + * stream does up to its high-water mark */) && + !(s->tunnel != NULL && s->tunnel->send_only); if (want && !s->read_armed) { scr_net_watch_read(s->fd, s, true); s->read_armed = true; @@ -1056,6 +1075,23 @@ static void scr_net_sock_buffer(ScrNetSocket *s, const char *data, size_t len) { * dead or ended write half (Node fires 'error' there; this slice drops — * SEMANTICS.md documents the bound). */ static void scr_net_sock_write_raw(ScrNetSocket *s, const char *data, size_t len) { + if (s->adopted_by != NULL) { + /* Node writes these bytes to the wire as they are, between the TLS + * records of the socket that took over (the peer then fails the + * session). Bytes the kernel cannot take now end that socket. */ + ScrNetSocket *t = s->adopted_by; + while (len > 0 && t->fd >= 0) { + ssize_t sent = scr_net_send(t->fd, data, len); + if (sent < 0 && errno == EINTR) continue; + if (sent <= 0) { + scr_net_sock_destroy(t); + break; + } + data += sent; + len -= (size_t)sent; + } + return; + } /* A socket whose dial hasn't STARTED yet (the agent's deferred dial, * the caller-lookup wait) has no fd but is logically connecting — * bytes buffer and flush at establishment like any mid-connect write. */ @@ -1490,6 +1526,12 @@ static void scr_net_sock_tunnel_pump(ScrNetSocket *s) { } scr_net_sock_update_write(s); if (s->fd < 0 || t->out_off < t->out_len) return; + if (t->send_only) { + scr_net_tunnel_free(t); + s->tunnel = NULL; + scr_net_sock_connected(s); + return; + } for (;;) { char buf[4096]; ssize_t n = read(s->fd, buf, sizeof buf); @@ -1592,6 +1634,10 @@ static void scr_net_sock_transport_pump(ScrNetSocket *s) { if (scr_exc_pending()) return; scr_net_fire0_this(&s->ready_ls, s, SCR_DYNH_NET_SOCKET); if (scr_exc_pending()) return; + if (s->tops->after_established) { + s->tops->after_established(s->tctx); + if (scr_exc_pending()) return; + } scr_net_sock_flush(s); scr_net_sock_update_read(s); scr_net_sock_update_write(s); @@ -2250,6 +2296,8 @@ ScrStr *scr_net_blocking_lookup(ScrStr *host /*borrowed*/) { * autoselect), and any other name is resolved when the dial starts. */ static void scr_net_sock_set_peer(ScrNetSocket *s, ScrStr *host /*borrowed, nullable*/) { const char *h = host && host->len > 0 ? host->data : "localhost"; + scr_str_release(s->host_name); + s->host_name = scr_str_new(h, strlen(h)); if (strcmp(h, "localhost") == 0) { h = "127.0.0.1"; if (scr_net_lookup_ops != NULL) scr_net_lookup_ops->record(s, "localhost", 9, h, 4, NULL); @@ -3024,6 +3072,10 @@ void scr_net_sock_write_bytes(ScrNetSocket *s, ScrBytes *data /*borrowed*/) { } void scr_net_sock_end(ScrNetSocket *s) { + if (s->adopted_by != NULL) { + scr_net_sock_end(s->adopted_by); + return; + } if (s->fd < 0 || s->wr_ending) return; s->wr_ending = true; scr_net_sock_maybe_finish_write(s); @@ -3136,7 +3188,10 @@ void scr_net_sock_on_write_flush(ScrNetSocket *s, ScrClosure *cb /*moves*/) { double scr_net_sock_bytes_written(ScrNetSocket *s) { return (double)s->bytes_written; } /* socket.readable: true until the read half is done (peer FIN / destroy). */ -bool scr_net_sock_readable(ScrNetSocket *s) { return s->fd >= 0 && !s->rd_eof; } +bool scr_net_sock_readable(ScrNetSocket *s) { + if (s->adopted_by != NULL) return scr_net_sock_readable(s->adopted_by); + return s->fd >= 0 && !s->rd_eof; +} /* socket.setTimeout(ms): ms > 0 arms the idle timer NOW (Node starts the * clock at the call — connecting time counts), ms <= 0 disables. */ @@ -3206,6 +3261,7 @@ ScrStr *scr_net_sock_remote_family(ScrNetSocket *s) { /* socket.localAddress / localPort / localFamily: read from the open * socket (undefined while connecting and after close, as in Node). */ static bool scr_net_sock_local(ScrNetSocket *s, char *addr, size_t cap, int *port, bool *v6) { + if (s->adopted_by != NULL) return scr_net_sock_local(s->adopted_by, addr, cap, port, v6); if (s->fd < 0 || s->connecting || s->dial_deferred || s->lookup_wait) return false; struct sockaddr_storage ss; socklen_t len = sizeof ss; @@ -4652,6 +4708,10 @@ bool scr_net_is_ipv4(const ScrDyn *input) { return scr_net_is_ip(input) == 4; } bool scr_net_is_ipv6(const ScrDyn *input) { return scr_net_is_ip(input) == 6; } void scr_net_sock_destroy(ScrNetSocket *s) { + if (s->adopted_by != NULL) { + scr_net_sock_destroy(s->adopted_by); + return; + } if (s->fd < 0 && !s->in_registry) return; s->rd_eof = true; s->wr_done = true; @@ -4833,7 +4893,8 @@ void scr_net_sock_on_error(ScrNetSocket *s, ScrClosure *cb /*moves*/, ScrChildEr } void scr_net_sock_on_connect(ScrNetSocket *s, ScrClosure *cb /*moves*/, bool once) { - if (s->close_emitted || (!s->connecting && s->fd < 0)) { + /* a socket that took over another's connection never emits 'connect' */ + if (s->close_emitted || (!s->connecting && s->fd < 0) || s->adopted_from != NULL) { scr_closure_release(cb); return; } @@ -4939,12 +5000,15 @@ void scr_net_sock_clear_native_reader(ScrNetSocket *s) { /* socket.destroyed — true once the fd is gone (destroy() or full close), * Node's flag for "this stream is done". */ -bool scr_net_sock_destroyed(ScrNetSocket *s) { return s->fd < 0; } +bool scr_net_sock_destroyed(ScrNetSocket *s) { + return s->adopted_by != NULL ? scr_net_sock_destroyed(s->adopted_by) : s->fd < 0; +} /* socket.writable — Node's stream flag: the write half is open (no end() * yet, no FIN sent, fd alive). Connecting sockets answer true — writes * queue, exactly Node. */ bool scr_net_sock_writable(ScrNetSocket *s) { + if (s->adopted_by != NULL) return scr_net_sock_writable(s->adopted_by); return s->fd >= 0 && !s->wr_ending && !s->wr_done; } @@ -4996,8 +5060,78 @@ void scr_net_sock_set_transport(ScrNetSocket *s, const ScrNetTransportOps *ops, scr_net_sock_update_write(s); } +/* A fresh socket takes over raw's open connection: the fd, the bytes it + * buffered either way and the peer identity. raw keeps its listeners and + * its server's accounting but does no I/O of its own; end() and destroy() + * on it act on the new socket, and its 'close' fires just before the new + * socket's. Bytes raw had not sent yet go out first. +1; the caller sets + * the transport, then starts it with scr_net_sock_adopt_start. NULL when + * raw has no open, idle connection to give (connecting, closed, already + * wrapped, or carrying a transport). */ +ScrNetSocket *scr_net_sock_adopt(ScrNetSocket *raw) { + if (raw->fd < 0 || scr_net_sock_connecting(raw) || raw->adopted_by != NULL || raw->tops != NULL) + return NULL; + ScrNetSocket *t = scr_net_sock_new(); + scr_str_release(scr_net_sock_remote_address(raw)); /* cache the peer while the fd is raw's */ + if (raw->remote_cache) { + t->remote_cache = scr_str_retain(raw->remote_cache); + t->remote_port_cache = raw->remote_port_cache; + t->remote_v6_cache = raw->remote_v6_cache; + } + memcpy(t->peer_ip, raw->peer_ip, sizeof t->peer_ip); + t->peer_port = raw->peer_port; + t->unrefd = raw->unrefd; + t->rd_eof = raw->rd_eof; + scr_net_sock_timer_cancel(raw); + if (raw->read_armed) scr_net_watch_read(raw->fd, raw, false); + if (raw->write_armed) scr_net_watch_write(raw->fd, raw, false); + raw->read_armed = raw->write_armed = false; + t->fd = raw->fd; + raw->fd = -1; + if (raw->rlen > raw->rhead) scr_net_sock_append_rbuf(t, raw->rbuf + raw->rhead, raw->rlen - raw->rhead); + raw->rhead = raw->rlen = 0; + while (raw->wlen > raw->whead) { + ssize_t sent = scr_net_send(t->fd, raw->wbuf + raw->whead, raw->wlen - raw->whead); + if (sent < 0 && errno == EINTR) continue; + if (sent <= 0) break; /* EAGAIN, or an error the transport will meet */ + raw->whead += (size_t)sent; + } + if (raw->wlen > raw->whead) { + ScrNetTunnel *tun = calloc(1, sizeof *tun); + if (!tun) scr_net_oom(); + tun->out_len = raw->wlen - raw->whead; + tun->out = malloc(tun->out_len); + if (!tun->out) scr_net_oom(); + memcpy(tun->out, raw->wbuf + raw->whead, tun->out_len); + tun->send_only = true; + t->tunnel = tun; + } + raw->whead = raw->wlen = 0; + raw->adopted_by = scr_net_sock_retain(t); + t->adopted_from = scr_net_sock_retain(raw); + scr_net_sock_register(t); + return t; +} + +/* Starts an adopted socket once its transport is set: the unsent bytes + * drain first, then the handshake runs (over any bytes raw had already + * read). */ +void scr_net_sock_adopt_start(ScrNetSocket *t) { + if (t->tunnel != NULL) { + scr_net_sock_update_write(t); + return; + } + /* the handshake starts from the poller (the socket is writable), never + * the constructing stack — Node's start is asynchronous too */ + scr_net_sock_transport_want_write(t); +} + int scr_net_sock_fd(ScrNetSocket *s) { return s->fd; } +/* The host a client socket was told to dial (Node's socket._host). +1; + * NULL on server sockets. */ +ScrStr *scr_net_sock_dial_name(ScrNetSocket *s) { return scr_str_retain(s->host_name); } + /* Drain up to n bytes of the receive buffer (peeked/unshifted bytes) — * consumers call this BEFORE the fd so re-queued bytes keep their * position in the stream. */ @@ -5050,6 +5184,32 @@ void scr_net_sock_replay(ScrNetSocket *s, const char *data, size_t len) { s->rcap = total; } +/* The peer closed before the handshake finished, on a socket whose + * stream the program already holds (new tls.TLSSocket): 'end', then + * 'close' without an error, as Node reports it. */ +void scr_net_sock_transport_eof(ScrNetSocket *s) { + scr_net_sock_eof(s); + if (s->fd >= 0) scr_net_sock_close_fd(s); +} + +/* A listener for the handshake's completion once TCP is up (a socket + * tls.connect({ socket }) took over is up from the start): it registers + * until the transport establishes. */ +void scr_net_sock_on_established(ScrNetSocket *s, ScrClosure *cb /*moves*/, bool once) { + if (s->close_emitted || s->fd < 0 || s->tops == NULL || s->t_est) { + scr_closure_release(cb); + return; + } + scr_net_ls_add(&s->conn_ls, cb, NULL, once); +} + +/* scr_net_sock_transport_error with the error's code given (static + * storage), for messages whose text does not name it. */ +void scr_net_sock_transport_error_code(ScrNetSocket *s, const char *msg, const char *code) { + if (!s->pending_err) s->pending_code = code; + scr_net_sock_transport_error(s, msg); +} + void scr_net_sock_transport_error(ScrNetSocket *s, const char *msg) { if (msg != NULL) { if (!s->pending_err) s->pending_err = scr_str_new(msg, strlen(msg)); @@ -5141,6 +5301,72 @@ static void scr_net_server_settle(ScrNetServer *srv) { scr_net_server_unregister(srv); } +/* Fires a closed socket's 'close' and settles it: its server's count + * drains, the protocol layer hears it, listeners drop and it leaves the + * registry. A socket that took over another's connection settles that one + * first, so the wrapped socket's 'close' comes just before its own. False + * with an exception pending. */ +static bool scr_net_sock_settle(ScrNetSocket *sock) { + ScrNetSocket *raw = sock->adopted_from; + if (raw != NULL) { + sock->adopted_from = NULL; + if (raw->adopted_by == sock) { + raw->adopted_by = NULL; + scr_net_sock_release(sock); + } + bool ok = raw->close_emitted || scr_net_sock_settle(raw); + scr_net_sock_release(raw); + if (!ok) return false; + } + sock->close_emitted = true; + sock->emit_close = false; + /* The owning server's count drains FIRST, and a now-drained closing + * server settles before this socket's own 'close' fires — Node's + * observed order (differential: the net-echo fixture). */ + if (sock->server) { + ScrNetServer *srv = sock->server; + sock->server = NULL; + srv->nconns--; + if (srv->closing && srv->nconns == 0 && !srv->close_emitted) { + scr_net_server_settle(srv); + } + scr_net_server_release(srv); + if (scr_exc_pending()) return false; + } + if (sock->native_closed) { + sock->native_closed(sock->native_ctx); + if (scr_exc_pending()) return false; + } + { + ScrDyn *had_error = scr_dyn_new_bool(sock->had_error); + scr_net_fire_arg_this(&sock->close_ls, had_error, sock, SCR_DYNH_NET_SOCKET); + scr_dyn_release(had_error); + } + /* settle: listeners drop (cycle story) */ + scr_net_ls_drop(&sock->data_ls); + scr_net_ls_drop(&sock->end_ls); + scr_net_ls_drop(&sock->close_ls); + scr_net_ls_drop(&sock->err_ls); + scr_net_ls_drop(&sock->conn_ls); + scr_net_ls_drop(&sock->timeout_ls); + scr_net_ls_drop(&sock->readable_ls); + scr_net_ls_drop(&sock->finish_ls); + scr_net_ls_drop(&sock->wcb_ls); + scr_net_ls_drop(&sock->ready_ls); + scr_net_ls_drop(&sock->lookup_ls); + if (sock->tops && sock->tops->settle) sock->tops->settle(sock->tctx); + if (sock->pipe_dst) { + scr_net_sock_release(sock->pipe_dst); + sock->pipe_dst = NULL; + } + if (sock->conn_pending) { + scr_net_server_release(sock->conn_pending); + sock->conn_pending = NULL; + } + scr_net_sock_unregister(sock); + return !scr_exc_pending(); +} + /* Sockets first (a dying connection may drain its server), servers after. * Every fire checks for a pending exception and bails — the loop surfaces * it as an uncaught throw. */ @@ -5200,7 +5426,19 @@ static void scr_net_sweep(void) { * listeners — and the unhandled-'error' exit */ bool consumed = false; if (sock->native_err) consumed = sock->native_err(sock->native_ctx, msg); - if (!consumed && !scr_exc_pending()) scr_net_fire_err_this(&sock->err_ls, msg, sock, SCR_DYNH_NET_SOCKET); + if (!consumed && !scr_exc_pending()) { + ScrError *coded = NULL; + ScrError *saved = scr_event_error_payload; + if (sock->pending_code != NULL) { + coded = scr_error_new(SCR_ERR_ERROR, msg); + coded->code = scr_str_new(sock->pending_code, strlen(sock->pending_code)); + scr_event_error_payload = coded; + } + scr_net_fire_err_this(&sock->err_ls, msg, sock, SCR_DYNH_NET_SOCKET); + scr_event_error_payload = saved; + if (coded != NULL) scr_error_release(coded); + } + sock->pending_code = NULL; scr_str_release(msg); if (scr_exc_pending()) { scr_net_sock_release(sock); @@ -5208,58 +5446,7 @@ static void scr_net_sweep(void) { } } if (sock->emit_close && !sock->close_emitted && sock->fd < 0) { - sock->close_emitted = true; - sock->emit_close = false; - /* The owning server's count drains FIRST, and a now-drained closing - * server settles before this socket's own 'close' fires — Node's - * observed order (differential: the net-echo fixture). */ - if (sock->server) { - ScrNetServer *srv = sock->server; - sock->server = NULL; - srv->nconns--; - if (srv->closing && srv->nconns == 0 && !srv->close_emitted) { - scr_net_server_settle(srv); - } - scr_net_server_release(srv); - if (scr_exc_pending()) { - scr_net_sock_release(sock); - return; - } - } - if (sock->native_closed) { - sock->native_closed(sock->native_ctx); - if (scr_exc_pending()) { - scr_net_sock_release(sock); - return; - } - } - { - ScrDyn *had_error = scr_dyn_new_bool(sock->had_error); - scr_net_fire_arg_this(&sock->close_ls, had_error, sock, SCR_DYNH_NET_SOCKET); - scr_dyn_release(had_error); - } - /* settle: listeners drop (cycle story) */ - scr_net_ls_drop(&sock->data_ls); - scr_net_ls_drop(&sock->end_ls); - scr_net_ls_drop(&sock->close_ls); - scr_net_ls_drop(&sock->err_ls); - scr_net_ls_drop(&sock->conn_ls); - scr_net_ls_drop(&sock->timeout_ls); - scr_net_ls_drop(&sock->readable_ls); - scr_net_ls_drop(&sock->finish_ls); - scr_net_ls_drop(&sock->wcb_ls); - scr_net_ls_drop(&sock->ready_ls); - scr_net_ls_drop(&sock->lookup_ls); - if (sock->pipe_dst) { - scr_net_sock_release(sock->pipe_dst); - sock->pipe_dst = NULL; - } - if (sock->conn_pending) { - scr_net_server_release(sock->conn_pending); - sock->conn_pending = NULL; - } - scr_net_sock_unregister(sock); - if (scr_exc_pending()) { + if (!scr_net_sock_settle(sock)) { scr_net_sock_release(sock); return; } @@ -5504,6 +5691,17 @@ static void scr_net_cleanup_atexit(void) { scr_net_server_release(s->server); s->server = NULL; } + /* a wrapped socket and the socket that took it over hold each other */ + if (s->adopted_by) { + ScrNetSocket *t = s->adopted_by; + s->adopted_by = NULL; + scr_net_sock_release(t); + } + if (s->adopted_from) { + ScrNetSocket *raw = s->adopted_from; + s->adopted_from = NULL; + scr_net_sock_release(raw); + } scr_net_sock_unregister(s); } while (scr_net_servers) { diff --git a/packages/runtime/src/scr_net.h b/packages/runtime/src/scr_net.h index 33638f699..ffa9b2f72 100644 --- a/packages/runtime/src/scr_net.h +++ b/packages/runtime/src/scr_net.h @@ -351,8 +351,22 @@ typedef struct ScrNetTransportOps { bool (*pending)(void *tctx); void (*shutdown_write)(void *tctx); void (*free)(void *tctx); + /* nullable: runs after the established socket's 'connect' listeners + * (the TLS 'secure' event, which Node emits after secureConnect) */ + void (*after_established)(void *tctx); + /* nullable: runs when the closed socket settles, after its own + * listeners drop; the transport drops the listeners it holds */ + void (*settle)(void *tctx); } ScrNetTransportOps; void scr_net_sock_set_transport(ScrNetSocket *s, const ScrNetTransportOps *ops, void *tctx); +/* new tls.TLSSocket(socket) and tls.connect({ socket }): a fresh socket + * takes over an open connection (fd, buffered bytes, peer identity); the + * old socket stays open without I/O, forwards end() and destroy(), and + * fires 'close' just before the new one. +1, or NULL when the socket has + * no open, idle connection to give. Set the transport on the result, then + * call scr_net_sock_adopt_start. */ +ScrNetSocket *scr_net_sock_adopt(ScrNetSocket *raw); +void scr_net_sock_adopt_start(ScrNetSocket *t); /* Routes a client socket through an HTTP CONNECT proxy. Call it right * after the dial (scr_net_connect to the proxy) and before any transport * is set: once TCP is up, `request` (the CONNECT head, copied) is sent @@ -366,6 +380,9 @@ void scr_net_sock_set_tunnel(ScrNetSocket *s, const char *request, size_t len); int scr_net_tunnel_status(const char *head, size_t len); void scr_net_tunnel_failure(int status, char *msg, size_t cap); int scr_net_sock_fd(ScrNetSocket *s); +/* The host a client socket was told to dial (Node's socket._host). +1; + * NULL on server sockets. */ +ScrStr *scr_net_sock_dial_name(ScrNetSocket *s); /* Drain up to n bytes of the socket's receive buffer (peeked/unshifted * bytes — the demux path); consumers call it before the fd. */ size_t scr_net_sock_take_buffered(ScrNetSocket *s, char *buf, size_t n); @@ -385,6 +402,16 @@ void scr_net_sock_replay(ScrNetSocket *s, const char *data, size_t len); * 'error' + teardown to the sweep; NULL tears down without an 'error' * event, Node's default for an unhandled server-side handshake failure. */ void scr_net_sock_transport_error(ScrNetSocket *s, const char *msg); +/* The same with the error's code given (static storage), for messages + * whose text does not name it. */ +void scr_net_sock_transport_error_code(ScrNetSocket *s, const char *msg, const char *code); +/* The peer closed before the handshake finished on a wrapped socket: + * 'end', then 'close' without an error. */ +void scr_net_sock_transport_eof(ScrNetSocket *s); +/* Registers a listener that fires when the transport establishes, once + * TCP is up (a socket that took over an open connection is up from the + * start). */ +void scr_net_sock_on_established(ScrNetSocket *s, ScrClosure *cb /*moves*/, bool once); /* Defer the server's 'connection' listeners to handshake completion — * tls.createServer's handler is the 'secureConnection' event, fired with * the socket only once the TLS layer stands (Node's timing). */ diff --git a/packages/runtime/src/scr_node_builtin.c b/packages/runtime/src/scr_node_builtin.c index 233617092..c0031e67b 100644 --- a/packages/runtime/src/scr_node_builtin.c +++ b/packages/runtime/src/scr_node_builtin.c @@ -90,6 +90,10 @@ static SCR_TL ScrDyn *scr_global_own; * live on the box (string-keyed ones in scr_global_own), so every spelling * of the global object answers this box. */ static SCR_TL ScrDyn *scr_global_box; +/* The compiler's immortal name table (one per program) whose names + * scr_global_known holds; cleared with the tables, so a library re-init + * registers the names again. */ +static SCR_TL const ScrArr *scr_global_registered; static SCR_TL bool scr_global_cleanup_registered; static SCR_TL ScrDyn *(*scr_global_console_get)(void); static SCR_TL ScrDyn *(*scr_global_fetch_get)(void); @@ -190,6 +194,7 @@ static void scr_global_cleanup(void) { scr_dyn_release(scr_global_own); scr_global_known = NULL; scr_global_own = NULL; + scr_global_registered = NULL; } static void *scr_global_retain(void *handle) { return handle; } @@ -246,8 +251,12 @@ ScrDyn *scr_global_object(void) { } ScrDyn *scr_global_native_init(ScrArr *known, ScrDyn *(*console_get)(void)) { + /* The compiler passes one immortal name table per program: once it is + * registered, later reads of the global object only take a reference. */ + if (known == scr_global_registered && scr_global_box) return scr_dyn_retain(scr_global_box); ScrDyn *global = scr_global_object(); scr_global_console_get = console_get; + if (known->rc == SIZE_MAX) scr_global_registered = known; for (size_t i = 0; i < known->len; i++) { ScrStr *key = (ScrStr *)scr_arr_get_ref(known, (double)i); if (!scr_dyn_obj_get(scr_global_known, key->data, key->len)) diff --git a/packages/runtime/src/scr_pki.c b/packages/runtime/src/scr_pki.c new file mode 100644 index 000000000..54aadc06b --- /dev/null +++ b/packages/runtime/src/scr_pki.c @@ -0,0 +1,2144 @@ +/* node:crypto asymmetric keys and signatures over the vendored mbedTLS + * public-key layer: createPrivateKey, createPublicKey, generateKeyPairSync + * and generateKeyPair for "rsa", "ec" and "ed25519" keys, the + * PrivateKeyObject and PublicKeyObject handles (type, asymmetricKeyType, + * asymmetricKeyDetails, export(), equals()), crypto.sign and crypto.verify, + * and the Sign and Verify objects of createSign and createVerify. Keys read + * and write PEM and DER as PKCS#1, SEC1, PKCS#8 and SubjectPublicKeyInfo, + * and JWK; the EC curves are prime256v1, secp384r1, secp521r1 and + * secp256k1, and the Ed25519 arithmetic is scr_ed25519.c. Argument checks + * and errors follow Node 24's lib/internal/crypto/keys.js, keygen.js and + * sig.js. Encrypted keys and other key types throw a coded SC2020 error. + * All arguments are borrowed. */ +#include "scr_runtime.h" + +#include +#include +#include +#include +#include + +#include "mbedtls/asn1.h" +#include "mbedtls/asn1write.h" +#include "mbedtls/base64.h" +#include "mbedtls/bignum.h" +#include "mbedtls/ecdsa.h" +#include "mbedtls/ecp.h" +#include "mbedtls/md.h" +#include "mbedtls/oid.h" +#include "mbedtls/pk.h" +#include "mbedtls/platform_util.h" +#include "mbedtls/rsa.h" +#include "mbedtls/x509_crt.h" + +#include "scr_pki.h" + +/* ── errors ───────────────────────────────────────────────────────────── */ + +static void sp_throw(int kind, const char *code, const char *message) { + scr_throw_error_msg_code(kind, message, strlen(message), code); +} + +void scr_pki_throw_fmt(int kind, const char *code, const char *fmt, ...) { + va_list ap, sized; + va_start(ap, fmt); + va_copy(sized, ap); + int n = vsnprintf(NULL, 0, fmt, sized); + va_end(sized); + if (n < 0) n = 0; + char *message = malloc((size_t)n + 1); + if (!message) scr_trap("scriptc: out of memory\n"); + vsnprintf(message, (size_t)n + 1, fmt, ap); + va_end(ap); + if (code) scr_throw_error_msg_code(kind, message, (size_t)n, code); + else scr_throw_error_msg(kind, message, (size_t)n); + free(message); +} + +/* The "Received" text of Node's ERR_INVALID_ARG_VALUE and ERR_OUT_OF_RANGE + * messages: a string as util.inspect quotes it (cut at 128 UTF-16 units + * plus "..."), a number as ERR_OUT_OF_RANGE prints it when `range`, any + * other value as its sketch. +1. */ +static ScrStr *sp_received(const ScrDyn *got, bool range) { + if (got->kind == SCR_DYN_STR) return scr_str_inspect_quoted(got->v.str, true); + char text[96]; + if (range && got->kind == SCR_DYN_NUM) return scr_str_new(text, scr_num_received(got->v.num, text)); + const char *lite = scr_dyn_inspect_lite(got, text, sizeof text); + return scr_str_new(lite, strlen(lite)); +} + +/* ERR_INVALID_ARG_VALUE for an option ("The property 'options.type' is + * invalid. Received 'spki'"). */ +static void sp_property_invalid(const char *name, const ScrDyn *got) { + ScrStr *received = sp_received(got, false); + scr_pki_throw_fmt(SCR_ERR_TYPE, "ERR_INVALID_ARG_VALUE", "The property '%s' is invalid. Received %.*s", name, + (int)received->len, received->data); + scr_str_release(received); +} + +static void sp_unsupported_input(void) { + sp_throw(SCR_ERR_ERROR, "ERR_OSSL_UNSUPPORTED", "error:1E08010C:DECODER routines::unsupported"); +} + +/* The coded refusal for a form this runtime does not implement. */ +static void sp_not_supported(const char *what) { + scr_pki_throw_fmt(SCR_ERR_ERROR, "SC2020", "'%s' is part of the standard library types but has no scriptc lowering yet", + what); +} + +static int sp_random(void *state, unsigned char *out, size_t len) { + (void)state; + arc4random_buf(out, len); + return 0; +} + +/* ── Ed25519 ────────────────────────────────────────────────────────── + * The arithmetic is scr_ed25519.c, which links only into programs that + * name Ed25519 and installs itself here at startup. Keys are the 32-byte + * seed and the 32-byte encoded public point. */ +const ScrPkiEd25519 *scr_pki_ed25519 = NULL; + +/* The Ed25519 arithmetic, or NULL with a coded SC2020 error pending. */ +static const ScrPkiEd25519 *sp_ed(void) { + if (!scr_pki_ed25519) + sp_throw(SCR_ERR_ERROR, "SC2020", + "Ed25519 keys are supported when a string literal in the program names 'ed25519'"); + return scr_pki_ed25519; +} + +bool scr_pki_ed25519_ready(void) { return sp_ed() != NULL; } + +static bool sp_ed_verify(const ScrPkiEd25519 *ed, const uint8_t pub[32], const uint8_t *m, size_t n, + const uint8_t *sig, size_t sig_len) { + return sig_len == 64 && ed->verify(pub, m, n, sig); +} + +/* ── option bags ──────────────────────────────────────────────────────── */ + +static bool sp_is_object(const ScrDyn *v) { return v != NULL && v->kind == SCR_DYN_OBJ; } + +/* A statically typed object argument (a record or class instance) as a + * plain object: +1, or NULL with the error pending. Other values are + * retained as they are. */ +static ScrDyn *sp_plain(const ScrDyn *v) { + if (v != NULL && v->kind == SCR_DYN_TYPED_REF) return scr_dyn_typed_ref_materialize(v); + return scr_dyn_retain((ScrDyn *)(v ? v : scr_dyn_undefined())); +} + +/* A borrowed option, or the undefined singleton. */ +static const ScrDyn *sp_opt(const ScrDyn *obj, const char *key) { + const ScrDyn *v = sp_is_object(obj) ? scr_dyn_obj_get(obj, key, strlen(key)) : NULL; + return v ? v : scr_dyn_undefined(); +} + +static bool sp_is_str(const ScrDyn *v, const char *text) { + size_t n = strlen(text); + return v->kind == SCR_DYN_STR && v->v.str->len == n && memcmp(v->v.str->data, text, n) == 0; +} + +static bool sp_absent(const ScrDyn *v) { return v->kind == SCR_DYN_UNDEF; } + +/* ── keys ─────────────────────────────────────────────────────────────── */ + +typedef struct SpKey { + size_t rc; + mbedtls_pk_context pk; /* RSA and EC keys */ + bool private_key; + bool ed25519; /* an Ed25519 key: ed_seed (private keys) and ed_pub */ + uint8_t ed_seed[32]; + uint8_t ed_pub[32]; +} SpKey; + +static void *sp_key_retain(void *h) { + SpKey *k = h; + if (k->rc != SIZE_MAX) k->rc++; + return h; +} + +static void sp_key_release(void *h) { + SpKey *k = h; + if (!k || k->rc == SIZE_MAX || --k->rc != 0) return; + mbedtls_pk_free(&k->pk); + mbedtls_platform_zeroize(k, sizeof *k); + free(k); +} + +static SpKey *sp_key_alloc(bool private_key) { + SpKey *k = calloc(1, sizeof *k); + if (!k) scr_trap("scriptc: out of memory\n"); + k->rc = 1; + k->private_key = private_key; + mbedtls_pk_init(&k->pk); + return k; +} + +static void sp_key_install(void); + +/* Boxes the key (consuming the caller's reference). */ +static ScrDyn *sp_key_box(SpKey *k) { + sp_key_install(); + ScrDyn *box = scr_dyn_new_handle(k, k->private_key ? SCR_DYNH_PRIVATE_KEY : SCR_DYNH_PUBLIC_KEY); + sp_key_release(k); + return box; +} + +static SpKey *sp_key_of(const ScrDyn *v) { + if (v == NULL || v->kind != SCR_DYN_HANDLE) return NULL; + if (v->v.handle.tag != SCR_DYNH_PRIVATE_KEY && v->v.handle.tag != SCR_DYNH_PUBLIC_KEY) return NULL; + return v->v.handle.ptr; +} + +bool scr_crypto_is_asymmetric_key(const ScrDyn *value) { return sp_key_of(value) != NULL; } + +/* The type getter of a KeyObject value: "private", "public", or NULL for + * anything else. */ +const char *scr_crypto_asymmetric_key_type(const ScrDyn *value) { + SpKey *k = sp_key_of(value); + return k ? (k->private_key ? "private" : "public") : NULL; +} + +static bool sp_is_rsa(const SpKey *k) { return mbedtls_pk_get_type(&k->pk) == MBEDTLS_PK_RSA; } + +static bool sp_is_ec(const SpKey *k) { return mbedtls_pk_get_type(&k->pk) == MBEDTLS_PK_ECKEY; } + +static bool sp_is_ed(const SpKey *k) { return k->ed25519; } + +typedef struct { + const char *name; /* OpenSSL short name (namedCurve) */ + const char *nist; /* EC_curve_nist2nid alias, or NULL */ + const char *jwk; /* JWK crv */ + mbedtls_ecp_group_id id; +} SpCurve; + +static const SpCurve sp_curves[] = { + {"prime256v1", "P-256", "P-256", MBEDTLS_ECP_DP_SECP256R1}, + {"secp384r1", "P-384", "P-384", MBEDTLS_ECP_DP_SECP384R1}, + {"secp521r1", "P-521", "P-521", MBEDTLS_ECP_DP_SECP521R1}, + {"secp256k1", NULL, "secp256k1", MBEDTLS_ECP_DP_SECP256K1}, +}; + +static const SpCurve *sp_curve_by_id(mbedtls_ecp_group_id id) { + for (size_t i = 0; i < sizeof sp_curves / sizeof sp_curves[0]; i++) + if (sp_curves[i].id == id) return &sp_curves[i]; + return NULL; +} + +static const SpCurve *sp_curve_of(const SpKey *k) { + return sp_is_ec(k) ? sp_curve_by_id(mbedtls_pk_ec(k->pk)->MBEDTLS_PRIVATE(grp).id) : NULL; +} + +/* A parsed key is usable when it is RSA or EC on a curve above. */ +static bool sp_key_supported(const SpKey *k) { + return sp_is_ed(k) || sp_is_rsa(k) || (sp_is_ec(k) && sp_curve_of(k) != NULL); +} + +/* ── DER writing ──────────────────────────────────────────────────────── */ + +/* mbedtls writes DER backwards into the end of a buffer; these helpers + * answer the written length or a negative error. */ +#define SP_DER_MAX 8192 + +static int sp_write_private_der(SpKey *k, unsigned char *buf, size_t size) { + return mbedtls_pk_write_key_der(&k->pk, buf, size); +} + +/* Ed25519's PKCS#8 and SubjectPublicKeyInfo prefixes (RFC 8410): the + * 32-byte seed or public key follows. */ +static const uint8_t sp_ed_pkcs8_prefix[16] = {0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, + 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20}; +static const uint8_t sp_ed_spki_prefix[12] = {0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, + 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00}; + +/* Writes prefix || 32 bytes at the end of buf, as the mbedtls writers do. */ +static int sp_write_ed_der(const uint8_t *prefix, size_t prefix_len, const uint8_t key[32], + unsigned char *buf, size_t size) { + size_t n = prefix_len + 32; + if (size < n) return MBEDTLS_ERR_ASN1_BUF_TOO_SMALL; + memcpy(buf + size - n, prefix, prefix_len); + memcpy(buf + size - 32, key, 32); + return (int)n; +} + +static int sp_write_spki_der(SpKey *k, unsigned char *buf, size_t size) { + if (sp_is_ed(k)) return sp_write_ed_der(sp_ed_spki_prefix, sizeof sp_ed_spki_prefix, k->ed_pub, buf, size); + return mbedtls_pk_write_pubkey_der(&k->pk, buf, size); +} + +/* RSAPublicKey (PKCS#1) DER. */ +static int sp_write_pkcs1_public_der(SpKey *k, unsigned char *buf, size_t size) { + unsigned char *p = buf + size; + return mbedtls_pk_write_pubkey(&p, buf, &k->pk); +} + +/* PKCS#8 PrivateKeyInfo around the PKCS#1 or SEC1 key, as OpenSSL writes + * it: version 0, the AlgorithmIdentifier (rsaEncryption with NULL + * parameters, or id-ecPublicKey with the curve OID), and the inner key, + * which for EC omits the parameters field. */ +static int sp_write_pkcs8_der(SpKey *k, unsigned char *buf, size_t size) { + if (sp_is_ed(k)) + return sp_write_ed_der(sp_ed_pkcs8_prefix, sizeof sp_ed_pkcs8_prefix, k->ed_seed, buf, size); + unsigned char inner[SP_DER_MAX]; + size_t inner_len; + if (sp_is_rsa(k)) { + int n = sp_write_private_der(k, inner, sizeof inner); + if (n < 0) return n; + inner_len = (size_t)n; + memmove(inner, inner + sizeof inner - inner_len, inner_len); + } else { + /* ECPrivateKey ::= SEQUENCE { version 1, privateKey OCTET STRING, + * [1] publicKey BIT STRING } */ + const mbedtls_ecp_keypair *ec = mbedtls_pk_ec(k->pk); + unsigned char *c = inner + sizeof inner; + size_t len = 0; + int r; + unsigned char point[160]; + size_t point_len; + if ((r = mbedtls_ecp_point_write_binary(&ec->MBEDTLS_PRIVATE(grp), &ec->MBEDTLS_PRIVATE(Q), + MBEDTLS_ECP_PF_UNCOMPRESSED, &point_len, point, + sizeof point)) != 0) + return r; + size_t pub_len = 0; + if ((r = mbedtls_asn1_write_bitstring(&c, inner, point, point_len * 8)) < 0) return r; + pub_len += (size_t)r; + if ((r = mbedtls_asn1_write_len(&c, inner, pub_len)) < 0) return r; + pub_len += (size_t)r; + if ((r = mbedtls_asn1_write_tag(&c, inner, MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 1)) < 0) + return r; + pub_len += (size_t)r; + len += pub_len; + size_t d_len = (ec->MBEDTLS_PRIVATE(grp).nbits + 7) / 8; + unsigned char d[72]; + if ((r = mbedtls_mpi_write_binary(&ec->MBEDTLS_PRIVATE(d), d, d_len)) != 0) return r; + if ((r = mbedtls_asn1_write_octet_string(&c, inner, d, d_len)) < 0) return r; + len += (size_t)r; + mbedtls_platform_zeroize(d, sizeof d); + if ((r = mbedtls_asn1_write_int(&c, inner, 1)) < 0) return r; + len += (size_t)r; + if ((r = mbedtls_asn1_write_len(&c, inner, len)) < 0) return r; + len += (size_t)r; + if ((r = mbedtls_asn1_write_tag(&c, inner, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) < 0) + return r; + len += (size_t)r; + inner_len = len; + memmove(inner, c, inner_len); + } + unsigned char *c = buf + size; + size_t len = 0; + int r; + if ((r = mbedtls_asn1_write_octet_string(&c, buf, inner, inner_len)) < 0) goto done; + len += (size_t)r; + { + const char *oid; + size_t oid_len; + size_t alg_len = 0; + if (sp_is_rsa(k)) { + if ((r = mbedtls_asn1_write_null(&c, buf)) < 0) goto done; + alg_len += (size_t)r; + oid = MBEDTLS_OID_PKCS1_RSA; + oid_len = MBEDTLS_OID_SIZE(MBEDTLS_OID_PKCS1_RSA); + } else { + const char *curve_oid; + size_t curve_oid_len; + if ((r = mbedtls_oid_get_oid_by_ec_grp(mbedtls_pk_ec(k->pk)->MBEDTLS_PRIVATE(grp).id, &curve_oid, + &curve_oid_len)) != 0) + goto done; + if ((r = mbedtls_asn1_write_oid(&c, buf, curve_oid, curve_oid_len)) < 0) goto done; + alg_len += (size_t)r; + oid = MBEDTLS_OID_EC_ALG_UNRESTRICTED; + oid_len = MBEDTLS_OID_SIZE(MBEDTLS_OID_EC_ALG_UNRESTRICTED); + } + if ((r = mbedtls_asn1_write_oid(&c, buf, oid, oid_len)) < 0) goto done; + alg_len += (size_t)r; + if ((r = mbedtls_asn1_write_len(&c, buf, alg_len)) < 0) goto done; + alg_len += (size_t)r; + if ((r = mbedtls_asn1_write_tag(&c, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) < 0) + goto done; + alg_len += (size_t)r; + len += alg_len; + } + if ((r = mbedtls_asn1_write_int(&c, buf, 0)) < 0) goto done; + len += (size_t)r; + if ((r = mbedtls_asn1_write_len(&c, buf, len)) < 0) goto done; + len += (size_t)r; + if ((r = mbedtls_asn1_write_tag(&c, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) < 0) + goto done; + len += (size_t)r; + r = (int)len; +done: + mbedtls_platform_zeroize(inner, sizeof inner); + return r; +} + +/* PEM armor with 64-character base64 lines and a final newline. */ +static ScrStr *sp_pem(const char *label, const unsigned char *der, size_t len) { + size_t b64_len = 0; + mbedtls_base64_encode(NULL, 0, &b64_len, der, len); + unsigned char *b64 = malloc(b64_len + 1); + char *out = malloc(b64_len + b64_len / 64 + 2 * strlen(label) + 64); + if (!b64 || !out) scr_trap("scriptc: out of memory\n"); + mbedtls_base64_encode(b64, b64_len + 1, &b64_len, der, len); + size_t o = (size_t)sprintf(out, "-----BEGIN %s-----\n", label); + for (size_t i = 0; i < b64_len; i += 64) { + size_t n = b64_len - i < 64 ? b64_len - i : 64; + memcpy(out + o, b64 + i, n); + o += n; + out[o++] = '\n'; + } + o += (size_t)sprintf(out + o, "-----END %s-----\n", label); + ScrStr *s = scr_str_new(out, o); + mbedtls_platform_zeroize(b64, b64_len); + mbedtls_platform_zeroize(out, o); + free(b64); + free(out); + return s; +} + +static ScrDyn *sp_dyn_buffer(const unsigned char *data, size_t len) { + ScrBytes *bytes = scr_bytes_new(SCR_BYTES_U8, (double)len); + bytes->is_buffer = true; + if (len) memcpy(bytes->data, data, len); + ScrDyn *d = scr_dyn_new_buffer(bytes); + scr_bytes_release(bytes); + return d; +} + +static ScrDyn *sp_dyn_str(ScrStr *s) { + ScrDyn *d = scr_dyn_new_str(s); + scr_str_release(s); + return d; +} + +/* ── JWK ──────────────────────────────────────────────────────────────── */ + +/* base64url without padding of the big-endian integer `x` in `len` bytes + * (0 = its minimal length). */ +static ScrDyn *sp_jwk_int(const mbedtls_mpi *x, size_t len) { + if (len == 0) len = mbedtls_mpi_size(x); + if (len == 0) len = 1; + unsigned char *raw = malloc(len); + size_t b64_len = 0; + if (!raw) scr_trap("scriptc: out of memory\n"); + mbedtls_mpi_write_binary(x, raw, len); + mbedtls_base64_encode(NULL, 0, &b64_len, raw, len); + unsigned char *b64 = malloc(b64_len + 1); + if (!b64) scr_trap("scriptc: out of memory\n"); + mbedtls_base64_encode(b64, b64_len + 1, &b64_len, raw, len); + size_t o = 0; + for (size_t i = 0; i < b64_len; i++) { + unsigned char c = b64[i]; + if (c == '=') break; + b64[o++] = c == '+' ? '-' : c == '/' ? '_' : c; + } + ScrDyn *d = sp_dyn_str(scr_str_new((const char *)b64, o)); + mbedtls_platform_zeroize(raw, len); + free(raw); + free(b64); + return d; +} + +static void sp_set(ScrDyn *obj, const char *key, ScrDyn *value) { + scr_dyn_obj_set(obj, key, strlen(key), value); +} + +/* base64url without padding of raw bytes. */ +static ScrDyn *sp_b64url(const uint8_t *raw, size_t len) { + size_t b64_len = 0; + mbedtls_base64_encode(NULL, 0, &b64_len, raw, len); + unsigned char *b64 = malloc(b64_len + 1); + if (!b64) scr_trap("scriptc: out of memory\n"); + mbedtls_base64_encode(b64, b64_len + 1, &b64_len, raw, len); + size_t o = 0; + for (size_t i = 0; i < b64_len; i++) { + unsigned char c = b64[i]; + if (c == '=') break; + b64[o++] = c == '+' ? '-' : c == '/' ? '_' : c; + } + ScrDyn *d = sp_dyn_str(scr_str_new((const char *)b64, o)); + mbedtls_platform_zeroize(b64, b64_len); + free(b64); + return d; +} + +static ScrDyn *sp_export_jwk(SpKey *k) { + ScrDyn *jwk = scr_dyn_new_obj(); + if (sp_is_ed(k)) { + sp_set(jwk, "kty", sp_dyn_str(scr_str_new("OKP", 3))); + sp_set(jwk, "crv", sp_dyn_str(scr_str_new("Ed25519", 7))); + sp_set(jwk, "x", sp_b64url(k->ed_pub, 32)); + if (k->private_key) sp_set(jwk, "d", sp_b64url(k->ed_seed, 32)); + return jwk; + } + if (sp_is_rsa(k)) { + mbedtls_rsa_context *rsa = mbedtls_pk_rsa(k->pk); + mbedtls_mpi n, e, d, p, q, dp, dq, qi; + mbedtls_mpi *all[] = {&n, &e, &d, &p, &q, &dp, &dq, &qi}; + for (size_t i = 0; i < 8; i++) mbedtls_mpi_init(all[i]); + mbedtls_rsa_export(rsa, &n, k->private_key ? &p : NULL, k->private_key ? &q : NULL, + k->private_key ? &d : NULL, &e); + sp_set(jwk, "kty", sp_dyn_str(scr_str_new("RSA", 3))); + sp_set(jwk, "n", sp_jwk_int(&n, 0)); + sp_set(jwk, "e", sp_jwk_int(&e, 0)); + if (k->private_key) { + mbedtls_rsa_export_crt(rsa, &dp, &dq, &qi); + sp_set(jwk, "d", sp_jwk_int(&d, 0)); + sp_set(jwk, "p", sp_jwk_int(&p, 0)); + sp_set(jwk, "q", sp_jwk_int(&q, 0)); + sp_set(jwk, "dp", sp_jwk_int(&dp, 0)); + sp_set(jwk, "dq", sp_jwk_int(&dq, 0)); + sp_set(jwk, "qi", sp_jwk_int(&qi, 0)); + } + for (size_t i = 0; i < 8; i++) mbedtls_mpi_free(all[i]); + } else { + const mbedtls_ecp_keypair *ec = mbedtls_pk_ec(k->pk); + const SpCurve *curve = sp_curve_of(k); + size_t size = (ec->MBEDTLS_PRIVATE(grp).nbits + 7) / 8; + sp_set(jwk, "kty", sp_dyn_str(scr_str_new("EC", 2))); + sp_set(jwk, "x", sp_jwk_int(&ec->MBEDTLS_PRIVATE(Q).MBEDTLS_PRIVATE(X), size)); + sp_set(jwk, "y", sp_jwk_int(&ec->MBEDTLS_PRIVATE(Q).MBEDTLS_PRIVATE(Y), size)); + sp_set(jwk, "crv", sp_dyn_str(scr_str_new(curve->jwk, strlen(curve->jwk)))); + if (k->private_key) sp_set(jwk, "d", sp_jwk_int(&ec->MBEDTLS_PRIVATE(d), size)); + } + return jwk; +} + +/* Decodes a JWK base64url member into `x`; false when it is missing or + * not a string. */ +static bool sp_jwk_read(const ScrDyn *jwk, const char *key, mbedtls_mpi *x) { + const ScrDyn *v = sp_opt(jwk, key); + if (v->kind != SCR_DYN_STR) return false; + size_t n = v->v.str->len; + unsigned char *b64 = malloc(n + 4); + unsigned char *raw = malloc(n + 4); + if (!b64 || !raw) scr_trap("scriptc: out of memory\n"); + for (size_t i = 0; i < n; i++) { + char c = v->v.str->data[i]; + b64[i] = (unsigned char)(c == '-' ? '+' : c == '_' ? '/' : c); + } + while (n % 4) b64[n++] = '='; + size_t raw_len = 0; + bool ok = mbedtls_base64_decode(raw, n, &raw_len, b64, n) == 0 && + mbedtls_mpi_read_binary(x, raw, raw_len) == 0; + mbedtls_platform_zeroize(raw, n); + free(b64); + free(raw); + return ok; +} + +/* Decodes a 32-byte JWK base64url member; false when it is missing, not a + * string, or another length. */ +static bool sp_jwk_bytes(const ScrDyn *jwk, const char *key, uint8_t out[32]) { + const ScrDyn *v = sp_opt(jwk, key); + if (v->kind != SCR_DYN_STR || v->v.str->len != 43) return false; + unsigned char b64[44]; + for (size_t i = 0; i < 43; i++) { + char c = v->v.str->data[i]; + b64[i] = (unsigned char)(c == '-' ? '+' : c == '_' ? '/' : c); + } + b64[43] = '='; + size_t n = 0; + return mbedtls_base64_decode(out, 32, &n, b64, 44) == 0 && n == 32; +} + +static void sp_invalid_jwk(void) { + sp_throw(SCR_ERR_TYPE, "ERR_CRYPTO_INVALID_JWK", "Invalid JWK data"); +} + +/* A key from a JWK object: RSA (n, e, and d, p, q for a private key) or EC + * (crv, x, y, and d). NULL with the error pending. */ +static SpKey *sp_key_from_jwk_plain(const ScrDyn *jwk, bool want_private); + +static SpKey *sp_key_from_jwk(const ScrDyn *jwk, bool want_private) { + ScrDyn *plain = sp_plain(jwk); + if (!plain) return NULL; + SpKey *k = sp_key_from_jwk_plain(plain, want_private); + scr_dyn_release(plain); + return k; +} + +static SpKey *sp_key_from_jwk_plain(const ScrDyn *jwk, bool want_private) { + if (!sp_is_object(jwk)) { + scr_dyn_prop_type_fail("key.key", "of type object", jwk); + return NULL; + } + const ScrDyn *kty = sp_opt(jwk, "kty"); + if (kty->kind != SCR_DYN_STR) { + scr_dyn_prop_type_fail("key.kty", "of type string", kty); + return NULL; + } + bool has_d = !sp_absent(sp_opt(jwk, "d")); + if (want_private && !has_d) { + sp_invalid_jwk(); + return NULL; + } + bool private_key = want_private; + SpKey *k = sp_key_alloc(private_key); + bool ok = false; + if (sp_is_str(kty, "OKP")) { + const ScrDyn *crv = sp_opt(jwk, "crv"); + if (!sp_is_str(crv, "Ed25519")) { + sp_key_release(k); + if (crv->kind != SCR_DYN_STR) { + scr_dyn_prop_type_fail("key.crv", "of type string", crv); + return NULL; + } + sp_not_supported("JWK keys of this crv"); + return NULL; + } + k->ed25519 = true; + if (private_key) { + ok = sp_jwk_bytes(jwk, "d", k->ed_seed); + if (ok) { + const ScrPkiEd25519 *ed = sp_ed(); + if (!ed) { + sp_key_release(k); + return NULL; + } + ed->public_key(k->ed_pub, k->ed_seed); + } + } else { + ok = sp_jwk_bytes(jwk, "x", k->ed_pub); + } + } else if (sp_is_str(kty, "RSA")) { + mbedtls_mpi n, e, d, p, q; + mbedtls_mpi_init(&n); + mbedtls_mpi_init(&e); + mbedtls_mpi_init(&d); + mbedtls_mpi_init(&p); + mbedtls_mpi_init(&q); + if (sp_jwk_read(jwk, "n", &n) && sp_jwk_read(jwk, "e", &e) && + mbedtls_pk_setup(&k->pk, mbedtls_pk_info_from_type(MBEDTLS_PK_RSA)) == 0) { + mbedtls_rsa_context *rsa = mbedtls_pk_rsa(k->pk); + if (private_key) { + ok = sp_jwk_read(jwk, "d", &d) && sp_jwk_read(jwk, "p", &p) && sp_jwk_read(jwk, "q", &q) && + mbedtls_rsa_import(rsa, &n, &p, &q, &d, &e) == 0 && mbedtls_rsa_complete(rsa) == 0 && + mbedtls_rsa_check_privkey(rsa) == 0; + } else { + ok = mbedtls_rsa_import(rsa, &n, NULL, NULL, NULL, &e) == 0 && + mbedtls_rsa_complete(rsa) == 0 && mbedtls_rsa_check_pubkey(rsa) == 0; + } + } + mbedtls_mpi_free(&n); + mbedtls_mpi_free(&e); + mbedtls_mpi_free(&d); + mbedtls_mpi_free(&p); + mbedtls_mpi_free(&q); + } else if (sp_is_str(kty, "EC")) { + const ScrDyn *crv = sp_opt(jwk, "crv"); + if (crv->kind != SCR_DYN_STR) { + sp_key_release(k); + scr_dyn_prop_type_fail("key.crv", "of type string", crv); + return NULL; + } + const SpCurve *curve = NULL; + for (size_t i = 0; i < sizeof sp_curves / sizeof sp_curves[0]; i++) + if (sp_is_str(crv, sp_curves[i].jwk)) curve = &sp_curves[i]; + if (!curve) { + sp_key_release(k); + sp_throw(SCR_ERR_TYPE, "ERR_CRYPTO_INVALID_CURVE", "Invalid EC curve name"); + return NULL; + } + if (mbedtls_pk_setup(&k->pk, mbedtls_pk_info_from_type(MBEDTLS_PK_ECKEY)) == 0) { + mbedtls_ecp_keypair *ec = mbedtls_pk_ec(k->pk); + mbedtls_ecp_point *Q = &ec->MBEDTLS_PRIVATE(Q); + ok = mbedtls_ecp_group_load(&ec->MBEDTLS_PRIVATE(grp), curve->id) == 0 && + sp_jwk_read(jwk, "x", &Q->MBEDTLS_PRIVATE(X)) && + sp_jwk_read(jwk, "y", &Q->MBEDTLS_PRIVATE(Y)) && + mbedtls_mpi_lset(&Q->MBEDTLS_PRIVATE(Z), 1) == 0 && + mbedtls_ecp_check_pubkey(&ec->MBEDTLS_PRIVATE(grp), Q) == 0; + if (ok && private_key) + ok = sp_jwk_read(jwk, "d", &ec->MBEDTLS_PRIVATE(d)) && + mbedtls_ecp_check_privkey(&ec->MBEDTLS_PRIVATE(grp), &ec->MBEDTLS_PRIVATE(d)) == 0; + } + } else { + sp_key_release(k); + sp_not_supported("JWK keys of this kty"); + return NULL; + } + if (!ok) { + sp_key_release(k); + sp_invalid_jwk(); + return NULL; + } + return k; +} + +/* ── parsing ──────────────────────────────────────────────────────────── */ + +/* The private key of a public SpKey derived from `k`. */ +static SpKey *sp_public_of(SpKey *k) { + if (sp_is_ed(k)) { + SpKey *pub = sp_key_alloc(false); + pub->ed25519 = true; + memcpy(pub->ed_pub, k->ed_pub, 32); + return pub; + } + unsigned char der[SP_DER_MAX]; + int n = sp_write_spki_der(k, der, sizeof der); + SpKey *pub = sp_key_alloc(false); + if (n < 0 || mbedtls_pk_parse_public_key(&pub->pk, der + sizeof der - n, (size_t)n) != 0) { + sp_key_release(pub); + return NULL; + } + return pub; +} + +/* Parses key material (PEM or DER bytes). `private_key` selects + * createPrivateKey's parse (PKCS#1, SEC1, PKCS#8) or createPublicKey's + * (SubjectPublicKeyInfo, PKCS#1 RSAPublicKey, then a private key or an + * X.509 certificate, whose public key it takes). NULL with Node's + * decoder error pending. */ +/* The DER of the first PEM block in data (+1 malloc'd in *out), or the + * data itself when it has no PEM armor (*out NULL). */ +static bool sp_der_of(const unsigned char *data, size_t len, unsigned char **out, const unsigned char **der, + size_t *der_len) { + *out = NULL; + const unsigned char *begin = NULL; + for (size_t i = 0; i + 11 <= len; i++) { + if (memcmp(data + i, "-----BEGIN ", 11) == 0) { + begin = data + i; + break; + } + } + if (!begin) { + *der = data; + *der_len = len; + return true; + } + const unsigned char *end = data + len; + const unsigned char *body = memchr(begin, '\n', (size_t)(end - begin)); + if (!body) return false; + body++; + unsigned char *b64 = malloc((size_t)(end - body) + 1); + unsigned char *raw = malloc((size_t)(end - body) + 1); + if (!b64 || !raw) scr_trap("scriptc: out of memory\n"); + size_t n = 0; + for (const unsigned char *p = body; p < end && *p != '-'; p++) + if (*p != '\n' && *p != '\r' && *p != ' ' && *p != '\t') b64[n++] = *p; + size_t raw_len = 0; + bool ok = mbedtls_base64_decode(raw, (size_t)(end - body) + 1, &raw_len, b64, n) == 0; + free(b64); + if (!ok) { + free(raw); + return false; + } + *out = raw; + *der = raw; + *der_len = raw_len; + return true; +} + +/* The SubjectPublicKeyInfo element of an X.509 certificate's DER. */ +static bool sp_cert_spki(const unsigned char *der, size_t len, const unsigned char **spki, size_t *spki_len) { + unsigned char *p = (unsigned char *)der; + const unsigned char *end = der + len; + size_t n; + if (mbedtls_asn1_get_tag(&p, end, &n, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE) != 0) return false; + if (mbedtls_asn1_get_tag(&p, end, &n, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE) != 0) return false; + const unsigned char *tbs_end = p + n; + /* [0] version, serialNumber, signature, issuer, validity, subject */ + if (mbedtls_asn1_get_tag(&p, tbs_end, &n, MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 0) == 0) + p += n; + int tags[] = {MBEDTLS_ASN1_INTEGER, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE, + MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE, + MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE}; + for (size_t i = 0; i < 5; i++) { + if (mbedtls_asn1_get_tag(&p, tbs_end, &n, tags[i]) != 0) return false; + p += n; + } + const unsigned char *start = p; + if (mbedtls_asn1_get_tag(&p, tbs_end, &n, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE) != 0) return false; + *spki = start; + *spki_len = (size_t)(p + n - start); + return true; +} + +/* An Ed25519 key from PKCS#8 or SubjectPublicKeyInfo DER, or (for a public + * key) the key of an X.509 certificate; NULL when the DER is none of + * these, or with *failed set and an error pending. A private key wanted + * as public answers its public key. */ +static SpKey *sp_ed_from_der(const unsigned char *der, size_t len, bool private_key, bool *failed) { + *failed = false; + if (len == 48 && memcmp(der, sp_ed_pkcs8_prefix, 16) == 0) { + const ScrPkiEd25519 *ed = sp_ed(); + if (!ed) { + *failed = true; + return NULL; + } + SpKey *k = sp_key_alloc(private_key); + k->ed25519 = true; + ed->public_key(k->ed_pub, der + 16); + if (private_key) memcpy(k->ed_seed, der + 16, 32); + return k; + } + if (private_key) return NULL; + const unsigned char *spki = der; + size_t spki_len = len; + if (!(len == 44 && memcmp(der, sp_ed_spki_prefix, 12) == 0) && !sp_cert_spki(der, len, &spki, &spki_len)) + return NULL; + if (spki_len != 44 || memcmp(spki, sp_ed_spki_prefix, 12) != 0) return NULL; + SpKey *k = sp_key_alloc(false); + k->ed25519 = true; + memcpy(k->ed_pub, spki + 12, 32); + return k; +} + +static SpKey *sp_parse(const unsigned char *data, size_t len, bool private_key) { + { + unsigned char *decoded; + const unsigned char *der; + size_t der_len; + if (sp_der_of(data, len, &decoded, &der, &der_len)) { + bool failed; + SpKey *ed = sp_ed_from_der(der, der_len, private_key, &failed); + if (decoded) { + mbedtls_platform_zeroize(decoded, der_len); + free(decoded); + } + if (ed || failed) return ed; + } + } + /* mbedtls reads PEM from a NUL-terminated buffer whose length counts the + * NUL. */ + bool pem = false; + for (size_t i = 0; i + 11 <= len; i++) { + if (memcmp(data + i, "-----BEGIN ", 11) == 0) { + pem = true; + break; + } + } + unsigned char *buf = malloc(len + 1); + if (!buf) scr_trap("scriptc: out of memory\n"); + memcpy(buf, data, len); + buf[len] = 0; + size_t n = pem ? len + 1 : len; + SpKey *k = sp_key_alloc(private_key); + bool ok; + if (private_key) { + ok = mbedtls_pk_parse_key(&k->pk, buf, n, NULL, 0, sp_random, NULL) == 0; + } else { + ok = mbedtls_pk_parse_public_key(&k->pk, buf, n) == 0; + if (!ok) { + SpKey *priv = sp_key_alloc(true); + mbedtls_pk_free(&k->pk); + mbedtls_pk_init(&k->pk); + if (mbedtls_pk_parse_key(&priv->pk, buf, n, NULL, 0, sp_random, NULL) == 0) { + sp_key_release(k); + k = sp_public_of(priv); + ok = k != NULL; + if (!k) k = sp_key_alloc(false); + } else { + mbedtls_x509_crt crt; + mbedtls_x509_crt_init(&crt); + if (mbedtls_x509_crt_parse(&crt, buf, n) == 0) { + unsigned char der[SP_DER_MAX]; + int w = mbedtls_pk_write_pubkey_der(&crt.pk, der, sizeof der); + ok = w > 0 && mbedtls_pk_parse_public_key(&k->pk, der + sizeof der - w, (size_t)w) == 0; + } + mbedtls_x509_crt_free(&crt); + } + sp_key_release(priv); + } + } + mbedtls_platform_zeroize(buf, len); + free(buf); + if (!ok) { + sp_key_release(k); + sp_unsupported_input(); + return NULL; + } + if (!sp_key_supported(k)) { + sp_key_release(k); + sp_not_supported("crypto keys of this type"); + return NULL; + } + return k; +} + +/* The bytes of a string or buffer source, +1; NULL when `v` is neither. */ +static ScrBytes *sp_source_bytes(const ScrDyn *v, const ScrDyn *encoding) { + if (v->kind == SCR_DYN_STR) { + bool named = encoding != NULL && encoding->kind == SCR_DYN_STR; + ScrStr *utf8 = named ? NULL : scr_str_new("utf8", 4); + ScrBytes *b = scr_bytes_from_str_checked(v->v.str, named ? encoding->v.str : utf8); + if (utf8) scr_str_release(utf8); + return b; + } + if (v->kind == SCR_DYN_BYTES || scr_buffer_storage_is(v)) return scr_bytes_buffer_source(v); + return NULL; +} + +static const char sp_key_input_types[] = + "of type string or an instance of ArrayBuffer, Buffer, TypedArray, DataView, or URL"; + +/* createPrivateKey / createPublicKey: a PEM string or buffer, or + * { key, format, type, encoding, passphrase }; createPublicKey also takes + * a private KeyObject. */ +static ScrDyn *sp_create_key(ScrDyn *input, bool private_key) { + if (input->kind == SCR_DYN_TYPED_REF) { + ScrDyn *value = scr_dyn_typed_ref_materialize(input); + if (!value) return NULL; + ScrDyn *result = sp_create_key(value, private_key); + scr_dyn_release(value); + return result; + } + SpKey *object = sp_key_of(input); + if (object) { + if (private_key) { + scr_dyn_arg_type_fail("key", sp_key_input_types, input); + return NULL; + } + if (!object->private_key) { + sp_throw(SCR_ERR_TYPE, "ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE", + "Invalid key object type public, expected private."); + return NULL; + } + SpKey *pub = sp_public_of(object); + if (!pub) { + sp_unsupported_input(); + return NULL; + } + return sp_key_box(pub); + } + const ScrDyn *data = input; + const ScrDyn *format = scr_dyn_undefined(); + const ScrDyn *type = scr_dyn_undefined(); + const ScrDyn *encoding = NULL; + if (sp_is_object(input) && !scr_buffer_storage_is(input)) { + data = sp_opt(input, "key"); + format = sp_opt(input, "format"); + type = sp_opt(input, "type"); + encoding = sp_opt(input, "encoding"); + if (!sp_absent(sp_opt(input, "passphrase"))) { + sp_not_supported("encrypted private keys"); + return NULL; + } + SpKey *inner = sp_key_of(data); + if (inner) return sp_create_key((ScrDyn *)data, private_key); + if (sp_is_str(format, "jwk")) { + SpKey *k = sp_key_from_jwk(data, private_key); + return k ? sp_key_box(k) : NULL; + } + if (!sp_absent(format) && !sp_is_str(format, "pem") && !sp_is_str(format, "der")) { + sp_property_invalid("key.format", format); + return NULL; + } + if (sp_is_str(format, "der")) { + bool valid = private_key ? sp_is_str(type, "pkcs1") || sp_is_str(type, "pkcs8") || + sp_is_str(type, "sec1") + : sp_is_str(type, "pkcs1") || sp_is_str(type, "spki"); + if (!valid) { + sp_property_invalid("key.type", type); + return NULL; + } + } + } + ScrBytes *bytes = sp_source_bytes(data, encoding); + if (!bytes) { + if (data->kind == SCR_DYN_STR || data->kind == SCR_DYN_BYTES || scr_buffer_storage_is(data)) + return NULL; /* the decoder threw */ + scr_dyn_arg_type_fail(data == input ? "key" : "key.key", sp_key_input_types, data); + return NULL; + } + SpKey *k = sp_parse(bytes->data, (size_t)scr_bytes_byte_len(bytes), private_key); + scr_bytes_release(bytes); + return k ? sp_key_box(k) : NULL; +} + +ScrDyn *scr_crypto_create_private_key(ScrDyn *key) { return sp_create_key(key, true); } + +ScrDyn *scr_crypto_create_public_key(ScrDyn *key) { return sp_create_key(key, false); } + +/* ── export ───────────────────────────────────────────────────────────── */ + +/* export({ format, type }) per Node's parseKeyEncoding: format "pem", + * "der" or "jwk"; type pkcs1/pkcs8/sec1 for private keys and pkcs1/spki + * for public keys, where pkcs1 needs an RSA key and sec1 an EC key. */ +static ScrDyn *sp_export_plain(SpKey *k, const ScrDyn *options); + +static ScrDyn *sp_export(SpKey *k, const ScrDyn *options) { + ScrDyn *plain = sp_plain(options); + if (!plain) return NULL; + ScrDyn *result = sp_export_plain(k, plain); + scr_dyn_release(plain); + return result; +} + +static ScrDyn *sp_export_plain(SpKey *k, const ScrDyn *options) { + if (options == NULL || !sp_is_object(options)) { + scr_dyn_arg_type_fail("options", "of type object", options ? options : scr_dyn_undefined()); + return NULL; + } + const ScrDyn *format = sp_opt(options, "format"); + if (sp_is_str(format, "jwk")) return sp_export_jwk(k); + bool pem = sp_is_str(format, "pem"); + if (!pem && !sp_is_str(format, "der")) { + sp_property_invalid("options.format", format); + return NULL; + } + const ScrDyn *type = sp_opt(options, "type"); + bool pkcs1 = sp_is_str(type, "pkcs1"); + bool pkcs8 = k->private_key && sp_is_str(type, "pkcs8"); + bool sec1 = k->private_key && sp_is_str(type, "sec1"); + bool spki = !k->private_key && sp_is_str(type, "spki"); + if (!pkcs1 && !pkcs8 && !sec1 && !spki) { + sp_property_invalid("options.type", type); + return NULL; + } + if (!sp_absent(sp_opt(options, "cipher")) || !sp_absent(sp_opt(options, "passphrase"))) { + sp_not_supported("encrypted private key export"); + return NULL; + } + if (pkcs1 && !sp_is_rsa(k)) { + sp_throw(SCR_ERR_ERROR, "ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS", + "The selected key encoding pkcs1 can only be used for RSA keys."); + return NULL; + } + if (sec1 && !sp_is_ec(k)) { + sp_throw(SCR_ERR_ERROR, "ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS", + "The selected key encoding sec1 can only be used for EC keys."); + return NULL; + } + unsigned char *der = malloc(SP_DER_MAX); + if (!der) scr_trap("scriptc: out of memory\n"); + int n; + const char *label; + if (pkcs8) { + n = sp_write_pkcs8_der(k, der, SP_DER_MAX); + label = "PRIVATE KEY"; + } else if (spki) { + n = sp_write_spki_der(k, der, SP_DER_MAX); + label = "PUBLIC KEY"; + } else if (k->private_key) { + n = sp_write_private_der(k, der, SP_DER_MAX); + label = pkcs1 ? "RSA PRIVATE KEY" : "EC PRIVATE KEY"; + } else { + n = sp_write_pkcs1_public_der(k, der, SP_DER_MAX); + label = "RSA PUBLIC KEY"; + } + ScrDyn *result = NULL; + if (n < 0) { + sp_unsupported_input(); + } else { + const unsigned char *start = der + SP_DER_MAX - n; + result = pem ? sp_dyn_str(sp_pem(label, start, (size_t)n)) : sp_dyn_buffer(start, (size_t)n); + } + mbedtls_platform_zeroize(der, SP_DER_MAX); + free(der); + return result; +} + +/* ── the KeyObject handles ────────────────────────────────────────────── */ + +static ScrDyn *sp_key_details(SpKey *k) { + ScrDyn *details = scr_dyn_new_obj(); + if (sp_is_ed(k)) return details; + if (sp_is_rsa(k)) { + mbedtls_rsa_context *rsa = mbedtls_pk_rsa(k->pk); + mbedtls_mpi e; + mbedtls_mpi_init(&e); + mbedtls_rsa_export(rsa, NULL, NULL, NULL, NULL, &e); + uint64_t exponent = 0; + size_t bytes = mbedtls_mpi_size(&e); + unsigned char raw[8] = {0}; + if (bytes <= 8) mbedtls_mpi_write_binary(&e, raw, 8); + for (size_t i = 0; i < 8; i++) exponent = (exponent << 8) | raw[i]; + mbedtls_mpi_free(&e); + sp_set(details, "modulusLength", scr_dyn_new_num((double)mbedtls_pk_get_bitlen(&k->pk))); + ScrBigInt *big = scr_bigint_from_u64(exponent); + sp_set(details, "publicExponent", scr_dyn_new_bigint(big)); + scr_bigint_release(big); + } else { + const SpCurve *curve = sp_curve_of(k); + sp_set(details, "namedCurve", sp_dyn_str(scr_str_new(curve->name, strlen(curve->name)))); + } + return details; +} + +/* The DER that identifies a key for equals(): its private encoding for a + * private key, its SubjectPublicKeyInfo otherwise. */ +static int sp_identity_der(SpKey *k, unsigned char *buf, size_t size) { + if (sp_is_ed(k)) return k->private_key ? sp_write_pkcs8_der(k, buf, size) : sp_write_spki_der(k, buf, size); + return k->private_key ? sp_write_private_der(k, buf, size) : sp_write_spki_der(k, buf, size); +} + +static ScrDyn *sp_key_invoke(void *h, ScrDyn *self, const char *method, ScrDyn *const *args, + size_t argc, const char *what) { + (void)self; + SpKey *k = h; + if (strcmp(method, "export") == 0) return sp_export(k, argc ? args[0] : NULL); + if (strcmp(method, "equals") == 0) { + const ScrDyn *other_value = argc ? args[0] : scr_dyn_undefined(); + SpKey *other = sp_key_of(other_value); + if (!other) { + size_t len; + if (scr_key_object_bytes(other_value, &len)) return scr_dyn_new_bool(false); + scr_dyn_arg_type_fail("otherKeyObject", "an instance of KeyObject", other_value); + return NULL; + } + if (other->private_key != k->private_key || + mbedtls_pk_get_type(&other->pk) != mbedtls_pk_get_type(&k->pk)) + return scr_dyn_new_bool(false); + unsigned char *a = malloc(SP_DER_MAX), *b = malloc(SP_DER_MAX); + if (!a || !b) scr_trap("scriptc: out of memory\n"); + int na = sp_identity_der(k, a, SP_DER_MAX); + int nb = sp_identity_der(other, b, SP_DER_MAX); + bool same = na > 0 && na == nb && memcmp(a + SP_DER_MAX - na, b + SP_DER_MAX - nb, (size_t)na) == 0; + mbedtls_platform_zeroize(a, SP_DER_MAX); + mbedtls_platform_zeroize(b, SP_DER_MAX); + free(a); + free(b); + return scr_dyn_new_bool(same); + } + if (strcmp(method, "toCryptoKey") == 0) { + sp_not_supported("KeyObject.toCryptoKey"); + return NULL; + } + scr_pki_throw_fmt(SCR_ERR_TYPE, NULL, "%s is not a function", what); + return NULL; +} + +static ScrDyn *sp_key_get(void *h, const char *name, size_t len) { + SpKey *k = h; + if (len == 4 && memcmp(name, "type", 4) == 0) + return k->private_key ? sp_dyn_str(scr_str_new("private", 7)) : sp_dyn_str(scr_str_new("public", 6)); + if (len == 17 && memcmp(name, "asymmetricKeyType", 17) == 0) + return sp_is_ed(k) ? sp_dyn_str(scr_str_new("ed25519", 7)) + : sp_is_rsa(k) ? sp_dyn_str(scr_str_new("rsa", 3)) + : sp_dyn_str(scr_str_new("ec", 2)); + if (len == 20 && memcmp(name, "asymmetricKeyDetails", 20) == 0) return sp_key_details(k); + return NULL; +} + +static bool sp_key_set(void *h, const char *name, size_t len, const ScrDyn *value) { + (void)h; + (void)value; + const char *holder = len == 4 && memcmp(name, "type", 4) == 0 ? "KeyObject" + : (len == 17 && memcmp(name, "asymmetricKeyType", 17) == 0) || + (len == 20 && memcmp(name, "asymmetricKeyDetails", 20) == 0) + ? "AsymmetricKeyObject" + : NULL; + if (!holder) return false; + scr_pki_throw_fmt(SCR_ERR_TYPE, NULL, "Cannot set property %.*s of #<%s> which has only a getter", (int)len, name, + holder); + return true; +} + +static ScrDyn *sp_key_inspect_view(void *h) { + (void)h; + return scr_dyn_new_obj(); +} + +static const ScrDynHandleOps sp_private_ops = { + .cls = "PrivateKeyObject", + .retain = sp_key_retain, + .release = sp_key_release, + .invoke = sp_key_invoke, + .get = sp_key_get, + .set = sp_key_set, + .inspect_view = sp_key_inspect_view, + .json_empty_object = true, + .to_string_tag = "KeyObject", + .inspect_view_empty = true, +}; + +static const ScrDynHandleOps sp_public_ops = { + .cls = "PublicKeyObject", + .retain = sp_key_retain, + .release = sp_key_release, + .invoke = sp_key_invoke, + .get = sp_key_get, + .set = sp_key_set, + .inspect_view = sp_key_inspect_view, + .json_empty_object = true, + .to_string_tag = "KeyObject", + .inspect_view_empty = true, +}; + +/* createHmac with a private or public key (scr_crypto_reject_asymmetric_secret). */ +static void sp_reject_as_secret(const ScrDyn *key) { + bool private_key = key->v.handle.tag == SCR_DYNH_PRIVATE_KEY; + scr_throw_error_msg_code(SCR_ERR_TYPE, + private_key ? "Invalid key object type private, expected secret." + : "Invalid key object type public, expected secret.", + private_key ? 49 : 48, "ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE"); +} + +static void sp_key_install(void) { + static SCR_TL bool installed; + if (installed) return; + installed = true; + scr_dyn_handle_install(SCR_DYNH_PRIVATE_KEY, &sp_private_ops); + scr_dyn_handle_install(SCR_DYNH_PUBLIC_KEY, &sp_public_ops); + scr_crypto_reject_asymmetric_secret = sp_reject_as_secret; +} + +/* ── generateKeyPairSync ──────────────────────────────────────────────── */ + +/* A key in the encoding an options.publicKeyEncoding/privateKeyEncoding + * object asks for, or the KeyObject when it is undefined. Consumes `k`. */ +static ScrDyn *sp_encoded(SpKey *k, const ScrDyn *encoding) { + if (sp_absent(encoding)) return sp_key_box(k); + ScrDyn *result = sp_export(k, encoding); + sp_key_release(k); + return result; +} + +static bool sp_check_encoding_plain(const ScrDyn *encoding, const char *name, bool private_key); + +static bool sp_check_encoding(const ScrDyn *options, const char *name, bool private_key) { + ScrDyn *encoding = sp_plain(sp_opt(options, name)); + if (!encoding) return false; + bool ok = sp_check_encoding_plain(encoding, name, private_key); + scr_dyn_release(encoding); + return ok; +} + +static bool sp_check_encoding_plain(const ScrDyn *encoding, const char *name, bool private_key) { + if (sp_absent(encoding)) return true; + char full[64]; + snprintf(full, sizeof full, "options.%s", name); + if (!sp_is_object(encoding)) { + sp_property_invalid(full, encoding); + return false; + } + const ScrDyn *format = sp_opt(encoding, "format"); + if (!sp_is_str(format, "pem") && !sp_is_str(format, "der") && !sp_is_str(format, "jwk")) { + snprintf(full, sizeof full, "options.%s.format", name); + sp_property_invalid(full, format); + return false; + } + if (sp_is_str(format, "jwk")) return true; + const ScrDyn *type = sp_opt(encoding, "type"); + bool valid = private_key ? sp_is_str(type, "pkcs1") || sp_is_str(type, "pkcs8") || sp_is_str(type, "sec1") + : sp_is_str(type, "pkcs1") || sp_is_str(type, "spki"); + if (!valid) { + snprintf(full, sizeof full, "options.%s.type", name); + sp_property_invalid(full, type); + return false; + } + return true; +} + +/* Generates the private key for (type, options), validated in Node's + * order; NULL with the error pending. */ +static SpKey *sp_generate(const ScrDyn *type, const ScrDyn *options) { + if (type->kind != SCR_DYN_STR) { + scr_dyn_arg_type_fail("type", "of type string", type); + return NULL; + } + bool rsa = sp_is_str(type, "rsa"); + bool ec = sp_is_str(type, "ec"); + bool ed = sp_is_str(type, "ed25519"); + static const char *const known[] = {"rsa-pss", "dsa", "ed448", "x25519", "x448", "dh"}; + bool other = false; + for (size_t i = 0; i < sizeof known / sizeof known[0]; i++) other = other || sp_is_str(type, known[i]); + if (!rsa && !ec && !ed && !other) { + ScrStr *received = sp_received(type, false); + scr_pki_throw_fmt(SCR_ERR_TYPE, "ERR_INVALID_ARG_VALUE", + "The argument 'type' must be a supported key type. Received %.*s", (int)received->len, + received->data); + scr_str_release(received); + return NULL; + } + /* The ed25519 options are optional. */ + if (!sp_is_object(options) && !(ed && sp_absent(options))) { + scr_dyn_arg_type_fail("options", "of type object", options); + return NULL; + } + if (other) { + sp_not_supported("generateKeyPairSync for this key type"); + return NULL; + } + SpKey *k = sp_key_alloc(true); + if (ed) { + if (!sp_check_encoding(options, "publicKeyEncoding", false) || + !sp_check_encoding(options, "privateKeyEncoding", true)) { + sp_key_release(k); + return NULL; + } + const ScrPkiEd25519 *ed = sp_ed(); + if (!ed) { + sp_key_release(k); + return NULL; + } + k->ed25519 = true; + sp_random(NULL, k->ed_seed, 32); + ed->public_key(k->ed_pub, k->ed_seed); + return k; + } + if (rsa) { + const ScrDyn *bits = sp_opt(options, "modulusLength"); + if (bits->kind != SCR_DYN_NUM) { + sp_key_release(k); + scr_dyn_prop_type_fail("options.modulusLength", "of type number", bits); + return NULL; + } + double b = bits->v.num; + /* validateUint32: an integer first, then the range. */ + bool integer = isfinite(b) && trunc(b) == b; + if (!integer || b < 0 || b > 4294967295.0) { + sp_key_release(k); + ScrStr *received = sp_received(bits, true); + scr_pki_throw_fmt(SCR_ERR_RANGE, "ERR_OUT_OF_RANGE", + "The value of \"options.modulusLength\" is out of range. It must be %s. Received %.*s", + integer ? ">= 0 && <= 4294967295" : "an integer", (int)received->len, received->data); + scr_str_release(received); + return NULL; + } + const ScrDyn *exp = sp_opt(options, "publicExponent"); + double e = 65537; + if (!sp_absent(exp)) { + if (exp->kind != SCR_DYN_NUM) { + sp_key_release(k); + scr_dyn_prop_type_fail("options.publicExponent", "of type number", exp); + return NULL; + } + e = exp->v.num; + } + if (!sp_check_encoding(options, "publicKeyEncoding", false) || + !sp_check_encoding(options, "privateKeyEncoding", true)) { + sp_key_release(k); + return NULL; + } + if (b < 512 || b > 16384 || e < 3 || e > 2147483647.0 || e != (double)(int64_t)e || ((int64_t)e & 1) == 0 || + mbedtls_pk_setup(&k->pk, mbedtls_pk_info_from_type(MBEDTLS_PK_RSA)) != 0 || + mbedtls_rsa_gen_key(mbedtls_pk_rsa(k->pk), sp_random, NULL, (unsigned)b, (int)e) != 0) { + sp_key_release(k); + sp_not_supported("generateKeyPairSync with this RSA modulus length or exponent"); + return NULL; + } + return k; + } + const ScrDyn *curve_name = sp_opt(options, "namedCurve"); + if (curve_name->kind != SCR_DYN_STR) { + sp_key_release(k); + scr_dyn_prop_type_fail("options.namedCurve", "of type string", curve_name); + return NULL; + } + if (!sp_check_encoding(options, "publicKeyEncoding", false) || + !sp_check_encoding(options, "privateKeyEncoding", true)) { + sp_key_release(k); + return NULL; + } + const SpCurve *curve = NULL; + for (size_t i = 0; i < sizeof sp_curves / sizeof sp_curves[0]; i++) + if (sp_is_str(curve_name, sp_curves[i].name) || + (sp_curves[i].nist && sp_is_str(curve_name, sp_curves[i].nist))) + curve = &sp_curves[i]; + if (!curve) { + sp_key_release(k); + sp_throw(SCR_ERR_TYPE, "ERR_CRYPTO_INVALID_CURVE", "Invalid EC curve name"); + return NULL; + } + if (mbedtls_pk_setup(&k->pk, mbedtls_pk_info_from_type(MBEDTLS_PK_ECKEY)) != 0 || + mbedtls_ecp_gen_key(curve->id, mbedtls_pk_ec(k->pk), sp_random, NULL) != 0) { + sp_key_release(k); + sp_unsupported_input(); + return NULL; + } + return k; +} + +/* generateKeyPairSync(type, options): { publicKey, privateKey }, each a + * KeyObject or the encoding the options ask for. */ +ScrDyn *scr_crypto_generate_key_pair_sync(ScrDyn *type, ScrDyn *options) { + if (options->kind == SCR_DYN_TYPED_REF) { + ScrDyn *value = scr_dyn_typed_ref_materialize(options); + if (!value) return NULL; + ScrDyn *result = scr_crypto_generate_key_pair_sync(type, value); + scr_dyn_release(value); + return result; + } + SpKey *k = sp_generate(type, options); + if (!k) return NULL; + SpKey *pub = sp_public_of(k); + if (!pub) { + sp_key_release(k); + sp_unsupported_input(); + return NULL; + } + ScrDyn *public_value = sp_encoded(pub, sp_opt(options, "publicKeyEncoding")); + if (!public_value) { + sp_key_release(k); + return NULL; + } + ScrDyn *private_value = sp_encoded(k, sp_opt(options, "privateKeyEncoding")); + if (!private_value) { + scr_dyn_release(public_value); + return NULL; + } + ScrDyn *pair = scr_dyn_new_obj(); + sp_set(pair, "publicKey", public_value); + sp_set(pair, "privateKey", private_value); + return pair; +} + +/* ── sign and verify ──────────────────────────────────────────────────── */ + +typedef struct { + const char *name; + mbedtls_md_type_t md; +} SpDigest; + +/* Digest names as OpenSSL's EVP_get_digestbyname takes them for + * signatures, matched without regard to case. */ +static const SpDigest sp_digests[] = { + {"sha1", MBEDTLS_MD_SHA1}, {"rsa-sha1", MBEDTLS_MD_SHA1}, + {"sha1withrsaencryption", MBEDTLS_MD_SHA1}, {"ecdsa-with-sha1", MBEDTLS_MD_SHA1}, + {"sha224", MBEDTLS_MD_SHA224}, {"rsa-sha224", MBEDTLS_MD_SHA224}, + {"sha224withrsaencryption", MBEDTLS_MD_SHA224}, + {"sha256", MBEDTLS_MD_SHA256}, {"rsa-sha256", MBEDTLS_MD_SHA256}, + {"sha256withrsaencryption", MBEDTLS_MD_SHA256}, + {"sha384", MBEDTLS_MD_SHA384}, {"rsa-sha384", MBEDTLS_MD_SHA384}, + {"sha384withrsaencryption", MBEDTLS_MD_SHA384}, + {"sha512", MBEDTLS_MD_SHA512}, {"rsa-sha512", MBEDTLS_MD_SHA512}, + {"sha512withrsaencryption", MBEDTLS_MD_SHA512}, + {"sha2-256", MBEDTLS_MD_SHA256}, {"sha2-384", MBEDTLS_MD_SHA384}, + {"sha2-512", MBEDTLS_MD_SHA512}, {"sha2-224", MBEDTLS_MD_SHA224}, +}; + +static bool sp_digest_of(const ScrStr *name, mbedtls_md_type_t *md) { + for (size_t i = 0; i < sizeof sp_digests / sizeof sp_digests[0]; i++) { + size_t n = strlen(sp_digests[i].name); + if (name->len != n) continue; + bool same = true; + for (size_t j = 0; j < n && same; j++) { + char c = name->data[j]; + if (c >= 'A' && c <= 'Z') c = (char)(c - 'A' + 'a'); + same = c == sp_digests[i].name[j]; + } + if (same) { + *md = sp_digests[i].md; + return true; + } + } + return false; +} + +/* The algorithm argument of crypto.sign/verify: a digest name, or + * null/undefined for the key type's default (SHA-256). */ +static bool sp_algorithm(const ScrDyn *alg, mbedtls_md_type_t *md) { + if (alg->kind == SCR_DYN_UNDEF || alg->kind == SCR_DYN_NULL) { + *md = MBEDTLS_MD_SHA256; + return true; + } + if (alg->kind != SCR_DYN_STR) { + scr_dyn_arg_type_fail("algorithm", "of type string", alg); + return false; + } + if (!sp_digest_of(alg->v.str, md)) { + /* The whole name, at any length and with any bytes, as in Node. */ + static const char prefix[] = "Invalid digest: "; + size_t len = sizeof prefix - 1 + alg->v.str->len; + char *message = malloc(len); + if (!message) scr_trap("scriptc: out of memory\n"); + memcpy(message, prefix, sizeof prefix - 1); + memcpy(message + sizeof prefix - 1, alg->v.str->data, alg->v.str->len); + scr_throw_error_msg_code(SCR_ERR_TYPE, message, len, "ERR_CRYPTO_INVALID_DIGEST"); + free(message); + return false; + } + return true; +} + +typedef struct { + SpKey *key; /* +1 */ + int padding; /* RSA_PKCS1_PADDING (1) or RSA_PKCS1_PSS_PADDING (6) */ + int salt; /* -1 digest length, -2 maximum (sign) or auto (verify) */ + bool p1363; /* dsaEncoding: "ieee-p1363" */ +} SpSigKey; + +/* The key argument of a signing operation: a KeyObject, key material, or + * { key, dsaEncoding, padding, saltLength, ...createKey options }. */ +static bool sp_sig_key_plain(const ScrDyn *value, bool sign, SpSigKey *out); + +static bool sp_sig_key(const ScrDyn *value, bool sign, SpSigKey *out) { + out->key = NULL; + ScrDyn *plain = sp_plain(value); + if (!plain) return false; + bool ok = sp_sig_key_plain(plain, sign, out); + scr_dyn_release(plain); + return ok; +} + +static bool sp_sig_key_plain(const ScrDyn *value, bool sign, SpSigKey *out) { + out->key = NULL; + out->padding = 1; + out->salt = sign ? -2 : -2; + out->p1363 = false; + const ScrDyn *options = NULL; + if (sp_is_object(value) && !sp_key_of(value) && !scr_buffer_storage_is(value)) { + options = value; + const ScrDyn *dsa = sp_opt(value, "dsaEncoding"); + if (sp_is_str(dsa, "ieee-p1363")) out->p1363 = true; + else if (!sp_absent(dsa) && !sp_is_str(dsa, "der")) { + sp_property_invalid("options.dsaEncoding", dsa); + return false; + } + const ScrDyn *padding = sp_opt(value, "padding"); + if (!sp_absent(padding)) { + if (padding->kind != SCR_DYN_NUM || (padding->v.num != 1 && padding->v.num != 6)) { + sp_not_supported("signatures with this padding"); + return false; + } + out->padding = (int)padding->v.num; + } + const ScrDyn *salt = sp_opt(value, "saltLength"); + if (!sp_absent(salt)) { + if (salt->kind != SCR_DYN_NUM || salt->v.num != (double)(int)salt->v.num || salt->v.num < -2) { + sp_not_supported("signatures with this saltLength"); + return false; + } + out->salt = (int)salt->v.num; + } + } + SpKey *direct = sp_key_of(options ? sp_opt(options, "key") : value); + if (direct) { + if (sign && !direct->private_key) { + sp_throw(SCR_ERR_TYPE, "ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE", + "Invalid key object type public, expected private."); + return false; + } + sp_key_retain(direct); + out->key = direct; + return true; + } + ScrDyn *created = sp_create_key((ScrDyn *)value, sign); + if (!created) return false; + out->key = sp_key_retain(sp_key_of(created)); + scr_dyn_release(created); + return true; +} + +/* DER ECDSA-Sig-Value ⇄ IEEE P1363 r || s. */ +static bool sp_der_to_p1363(const unsigned char *der, size_t len, size_t size, unsigned char *out) { + unsigned char *p = (unsigned char *)der; + const unsigned char *end = der + len; + size_t seq; + mbedtls_mpi r, s; + mbedtls_mpi_init(&r); + mbedtls_mpi_init(&s); + bool ok = mbedtls_asn1_get_tag(&p, end, &seq, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE) == 0 && + mbedtls_asn1_get_mpi(&p, end, &r) == 0 && mbedtls_asn1_get_mpi(&p, end, &s) == 0 && + mbedtls_mpi_write_binary(&r, out, size) == 0 && + mbedtls_mpi_write_binary(&s, out + size, size) == 0; + mbedtls_mpi_free(&r); + mbedtls_mpi_free(&s); + return ok; +} + +static int sp_p1363_to_der(const unsigned char *sig, size_t len, unsigned char *buf, size_t size) { + mbedtls_mpi r, s; + mbedtls_mpi_init(&r); + mbedtls_mpi_init(&s); + int out = -1; + if (len % 2 == 0 && mbedtls_mpi_read_binary(&r, sig, len / 2) == 0 && + mbedtls_mpi_read_binary(&s, sig + len / 2, len / 2) == 0) { + unsigned char *c = buf + size; + size_t n = 0; + int w; + if ((w = mbedtls_asn1_write_mpi(&c, buf, &s)) >= 0) { + n += (size_t)w; + if ((w = mbedtls_asn1_write_mpi(&c, buf, &r)) >= 0) { + n += (size_t)w; + if ((w = mbedtls_asn1_write_len(&c, buf, n)) >= 0) { + n += (size_t)w; + if ((w = mbedtls_asn1_write_tag(&c, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) >= 0) + out = (int)(n + (size_t)w); + } + } + } + } + mbedtls_mpi_free(&r); + mbedtls_mpi_free(&s); + return out; +} + +static size_t sp_ec_size(SpKey *k) { return (mbedtls_pk_ec(k->pk)->MBEDTLS_PRIVATE(grp).nbits + 7) / 8; } + +/* Applies the RSA padding of a signature operation. */ +static bool sp_rsa_padding(SpSigKey *key, mbedtls_md_type_t md) { + if (!sp_is_rsa(key->key)) return true; + mbedtls_rsa_context *rsa = mbedtls_pk_rsa(key->key->pk); + if (key->padding == 6) return mbedtls_rsa_set_padding(rsa, MBEDTLS_RSA_PKCS_V21, md) == 0; + return mbedtls_rsa_set_padding(rsa, MBEDTLS_RSA_PKCS_V15, MBEDTLS_MD_NONE) == 0; +} + +/* Signs a digest: +1 Buffer or NULL with the error pending. */ +static ScrDyn *sp_sign_hash(SpSigKey *key, mbedtls_md_type_t md, const unsigned char *hash, size_t hash_len) { + unsigned char sig[MBEDTLS_PK_SIGNATURE_MAX_SIZE]; + size_t sig_len = 0; + int r; + if (!sp_rsa_padding(key, md)) { + sp_unsupported_input(); + return NULL; + } + if (sp_is_rsa(key->key) && key->padding == 6) { + mbedtls_rsa_context *rsa = mbedtls_pk_rsa(key->key->pk); + int salt = key->salt; + size_t bytes = mbedtls_rsa_get_len(rsa); + size_t bits = mbedtls_pk_get_bitlen(&key->key->pk); + size_t max = bytes - hash_len - 2 - ((bits - 1) % 8 == 0 ? 1 : 0); + if (salt == -1) salt = (int)hash_len; + else if (salt == -2) salt = (int)max; + if (salt < 0 || (size_t)salt > max) { + sp_throw(SCR_ERR_ERROR, "ERR_OSSL_RSA_DATA_TOO_LARGE_FOR_KEY_SIZE", + "error:1C8000A5:Provider routines::data too large for key size"); + return NULL; + } + r = mbedtls_rsa_rsassa_pss_sign_ext(rsa, sp_random, NULL, md, (unsigned)hash_len, hash, salt, sig); + sig_len = bytes; + } else { + r = mbedtls_pk_sign(&key->key->pk, md, hash, hash_len, sig, sizeof sig, &sig_len, sp_random, NULL); + } + if (r != 0) { + sp_unsupported_input(); + return NULL; + } + if (sp_is_ec(key->key) && key->p1363) { + size_t size = sp_ec_size(key->key); + unsigned char raw[2 * 66]; + if (!sp_der_to_p1363(sig, sig_len, size, raw)) { + sp_unsupported_input(); + return NULL; + } + return sp_dyn_buffer(raw, 2 * size); + } + return sp_dyn_buffer(sig, sig_len); +} + +/* Verifies a digest against a signature; false for a signature that does + * not verify or does not parse. */ +static bool sp_verify_hash(SpSigKey *key, mbedtls_md_type_t md, const unsigned char *hash, size_t hash_len, + const unsigned char *sig, size_t sig_len) { + if (!sp_rsa_padding(key, md)) return false; + if (sp_is_rsa(key->key) && key->padding == 6) { + mbedtls_rsa_context *rsa = mbedtls_pk_rsa(key->key->pk); + if (sig_len != mbedtls_rsa_get_len(rsa)) return false; + int salt = key->salt; + if (salt == -1) salt = (int)hash_len; + else if (salt == -2) salt = MBEDTLS_RSA_SALT_LEN_ANY; + return mbedtls_rsa_rsassa_pss_verify_ext(rsa, md, (unsigned)hash_len, hash, md, salt, sig) == 0; + } + if (sp_is_ec(key->key) && key->p1363) { + unsigned char der[2 * 66 + 16]; + if (sig_len != 2 * sp_ec_size(key->key)) return false; + int n = sp_p1363_to_der(sig, sig_len, der, sizeof der); + if (n < 0) return false; + return mbedtls_pk_verify(&key->key->pk, md, hash, hash_len, der + sizeof der - n, (size_t)n) == 0; + } + return mbedtls_pk_verify(&key->key->pk, md, hash, hash_len, sig, sig_len) == 0; +} + +static const char sp_data_types[] = "an instance of Buffer, TypedArray, or DataView"; + +/* Ed25519 signs the message itself: an algorithm other than null or + * undefined is OpenSSL's invalid digest (false, error pending). */ +static bool sp_ed_digest_given(const ScrDyn *algorithm) { + if (algorithm->kind == SCR_DYN_UNDEF || algorithm->kind == SCR_DYN_NULL) return true; + sp_throw(SCR_ERR_ERROR, "ERR_OSSL_INVALID_DIGEST", "error:1C80007A:Provider routines::invalid digest"); + return false; +} + +/* crypto.sign(algorithm, data, key): the signature Buffer. */ +ScrDyn *scr_crypto_sign_oneshot(ScrDyn *algorithm, ScrDyn *data, ScrDyn *key) { + mbedtls_md_type_t md; + if (!sp_algorithm(algorithm, &md)) return NULL; + if (data->kind != SCR_DYN_BYTES) { + scr_dyn_arg_type_fail("data", sp_data_types, data); + return NULL; + } + SpSigKey k; + if (!sp_sig_key(key, true, &k)) return NULL; + ScrBytes *bytes = scr_bytes_buffer_source(data); + if (sp_is_ed(k.key)) { + ScrDyn *result = NULL; + const ScrPkiEd25519 *ed = sp_ed_digest_given(algorithm) ? sp_ed() : NULL; + if (ed) { + uint8_t sig[64]; + ed->sign(sig, k.key->ed_seed, k.key->ed_pub, bytes->data, (size_t)scr_bytes_byte_len(bytes)); + result = sp_dyn_buffer(sig, 64); + } + scr_bytes_release(bytes); + sp_key_release(k.key); + return result; + } + unsigned char hash[MBEDTLS_MD_MAX_SIZE]; + const mbedtls_md_info_t *info = mbedtls_md_info_from_type(md); + mbedtls_md(info, bytes->data, (size_t)scr_bytes_byte_len(bytes), hash); + scr_bytes_release(bytes); + ScrDyn *result = sp_sign_hash(&k, md, hash, mbedtls_md_get_size(info)); + sp_key_release(k.key); + return result; +} + +/* crypto.verify(algorithm, data, key, signature): a boolean. */ +ScrDyn *scr_crypto_verify_oneshot(ScrDyn *algorithm, ScrDyn *data, ScrDyn *key, ScrDyn *signature) { + mbedtls_md_type_t md; + if (!sp_algorithm(algorithm, &md)) return NULL; + if (data->kind != SCR_DYN_BYTES) { + scr_dyn_arg_type_fail("data", sp_data_types, data); + return NULL; + } + SpSigKey k; + if (!sp_sig_key(key, false, &k)) return NULL; + if (signature->kind != SCR_DYN_BYTES) { + sp_key_release(k.key); + scr_dyn_arg_type_fail("signature", sp_data_types, signature); + return NULL; + } + ScrBytes *bytes = scr_bytes_buffer_source(data); + ScrBytes *sig = scr_bytes_buffer_source(signature); + if (sp_is_ed(k.key)) { + ScrDyn *result = NULL; + const ScrPkiEd25519 *ed = sp_ed_digest_given(algorithm) ? sp_ed() : NULL; + if (ed) + result = scr_dyn_new_bool(sp_ed_verify(ed, k.key->ed_pub, bytes->data, + (size_t)scr_bytes_byte_len(bytes), sig->data, + (size_t)scr_bytes_byte_len(sig))); + scr_bytes_release(bytes); + scr_bytes_release(sig); + sp_key_release(k.key); + return result; + } + unsigned char hash[MBEDTLS_MD_MAX_SIZE]; + const mbedtls_md_info_t *info = mbedtls_md_info_from_type(md); + mbedtls_md(info, bytes->data, (size_t)scr_bytes_byte_len(bytes), hash); + bool ok = sp_verify_hash(&k, md, hash, mbedtls_md_get_size(info), sig->data, (size_t)scr_bytes_byte_len(sig)); + scr_bytes_release(bytes); + scr_bytes_release(sig); + sp_key_release(k.key); + return scr_dyn_new_bool(ok); +} + +/* ── Sign and Verify objects ──────────────────────────────────────────── */ + +typedef struct SpSigner { + size_t rc; + mbedtls_md_context_t md; + mbedtls_md_type_t type; + bool done; /* sign()/verify() ran: Node's "Not initialised" afterwards */ +} SpSigner; + +static void *sp_signer_retain(void *h) { + ((SpSigner *)h)->rc++; + return h; +} + +static void sp_signer_release(void *h) { + SpSigner *s = h; + if (--s->rc) return; + mbedtls_md_free(&s->md); + free(s); +} + +static void sp_not_initialised(void) { + sp_throw(SCR_ERR_ERROR, "ERR_CRYPTO_INVALID_STATE", "Not initialised"); +} + +/* update(data[, inputEncoding]): strings encode with the encoding (UTF-8 + * by default). */ +static bool sp_signer_update(SpSigner *s, ScrDyn *const *args, size_t argc) { + if (s->done) { + sp_not_initialised(); + return false; + } + const ScrDyn *data = argc ? args[0] : scr_dyn_undefined(); + if (data->kind != SCR_DYN_STR && data->kind != SCR_DYN_BYTES) { + scr_dyn_arg_type_fail("data", "of type string or an instance of Buffer, TypedArray, or DataView", data); + return false; + } + ScrBytes *bytes = sp_source_bytes(data, argc > 1 ? args[1] : NULL); + if (!bytes) return false; + mbedtls_md_update(&s->md, bytes->data, (size_t)scr_bytes_byte_len(bytes)); + scr_bytes_release(bytes); + return true; +} + +/* An output or signature encoding argument: a string encoding, or the + * Buffer form for undefined, null and "buffer". */ +static const ScrStr *sp_encoding_arg(const ScrDyn *v) { + if (v == NULL || v->kind != SCR_DYN_STR || sp_is_str(v, "buffer")) return NULL; + return v->v.str; +} + +static ScrDyn *sp_signer_invoke(void *h, ScrDyn *self, const char *method, ScrDyn *const *args, size_t argc, + const char *what, bool verifier) { + SpSigner *s = h; + if (strcmp(method, "update") == 0) return sp_signer_update(s, args, argc) ? scr_dyn_retain(self) : NULL; + if (!verifier && strcmp(method, "sign") == 0) { + if (s->done) { + sp_not_initialised(); + return NULL; + } + SpSigKey k; + if (!sp_sig_key(argc ? args[0] : scr_dyn_undefined(), true, &k)) return NULL; + if (sp_is_ed(k.key)) { + sp_key_release(k.key); + sp_throw(SCR_ERR_ERROR, "ERR_CRYPTO_UNSUPPORTED_OPERATION", "Unsupported crypto operation"); + return NULL; + } + unsigned char hash[MBEDTLS_MD_MAX_SIZE]; + mbedtls_md_finish(&s->md, hash); + s->done = true; + ScrDyn *sig = sp_sign_hash(&k, s->type, hash, mbedtls_md_get_size(mbedtls_md_info_from_type(s->type))); + sp_key_release(k.key); + const ScrStr *encoding = sp_encoding_arg(argc > 1 ? args[1] : NULL); + if (!sig || !encoding) return sig; + ScrBytes *bytes = scr_bytes_buffer_source(sig); + ScrStr *text = scr_bytes_to_str_checked(bytes, encoding); + scr_bytes_release(bytes); + scr_dyn_release(sig); + return text ? sp_dyn_str(text) : NULL; + } + if (verifier && strcmp(method, "verify") == 0) { + if (s->done) { + sp_not_initialised(); + return NULL; + } + SpSigKey k; + if (!sp_sig_key(argc ? args[0] : scr_dyn_undefined(), false, &k)) return NULL; + if (sp_is_ed(k.key)) { + sp_key_release(k.key); + sp_throw(SCR_ERR_ERROR, "ERR_CRYPTO_UNSUPPORTED_OPERATION", "Unsupported crypto operation"); + return NULL; + } + const ScrDyn *signature = argc > 1 ? args[1] : scr_dyn_undefined(); + if (signature->kind != SCR_DYN_STR && signature->kind != SCR_DYN_BYTES) { + sp_key_release(k.key); + scr_dyn_arg_type_fail("signature", "of type string or an instance of Buffer, TypedArray, or DataView", + signature); + return NULL; + } + const ScrStr *encoding = sp_encoding_arg(argc > 2 ? args[2] : NULL); + ScrDyn *encoding_value = encoding ? scr_dyn_new_str((ScrStr *)encoding) : NULL; + ScrBytes *sig = sp_source_bytes(signature, encoding_value); + if (encoding_value) scr_dyn_release(encoding_value); + if (!sig) { + sp_key_release(k.key); + return NULL; + } + unsigned char hash[MBEDTLS_MD_MAX_SIZE]; + mbedtls_md_finish(&s->md, hash); + s->done = true; + bool ok = sp_verify_hash(&k, s->type, hash, mbedtls_md_get_size(mbedtls_md_info_from_type(s->type)), + sig->data, (size_t)scr_bytes_byte_len(sig)); + scr_bytes_release(sig); + sp_key_release(k.key); + return scr_dyn_new_bool(ok); + } + scr_pki_throw_fmt(SCR_ERR_TYPE, NULL, "%s is not a function", what); + return NULL; +} + +static ScrDyn *sp_sign_invoke(void *h, ScrDyn *self, const char *method, ScrDyn *const *args, size_t argc, + const char *what) { + return sp_signer_invoke(h, self, method, args, argc, what, false); +} + +static ScrDyn *sp_verify_invoke(void *h, ScrDyn *self, const char *method, ScrDyn *const *args, size_t argc, + const char *what) { + return sp_signer_invoke(h, self, method, args, argc, what, true); +} + +/* Sign and Verify have no modeled properties. */ +static ScrDyn *sp_signer_get(void *h, const char *name, size_t len) { + (void)h; + (void)name; + (void)len; + return NULL; +} + +static bool sp_signer_set(void *h, const char *name, size_t len, const ScrDyn *value) { + (void)h; + (void)name; + (void)len; + (void)value; + return false; +} + +static ScrDyn *sp_signer_inspect_view(void *h) { + (void)h; + return scr_dyn_new_obj(); +} + +static const ScrDynHandleOps sp_sign_ops = { + .cls = "Sign", + .retain = sp_signer_retain, + .release = sp_signer_release, + .invoke = sp_sign_invoke, + .get = sp_signer_get, + .set = sp_signer_set, + .inspect_view = sp_signer_inspect_view, +}; + +static const ScrDynHandleOps sp_verify_ops = { + .cls = "Verify", + .retain = sp_signer_retain, + .release = sp_signer_release, + .invoke = sp_verify_invoke, + .get = sp_signer_get, + .set = sp_signer_set, + .inspect_view = sp_signer_inspect_view, +}; + +/* createSign(algorithm) / createVerify(algorithm). */ +static ScrDyn *sp_signer_new(ScrDyn *algorithm, bool verifier) { + if (algorithm->kind != SCR_DYN_STR) { + scr_dyn_arg_type_fail("algorithm", "of type string", algorithm); + return NULL; + } + mbedtls_md_type_t md; + if (!sp_digest_of(algorithm->v.str, &md)) { + sp_throw(SCR_ERR_TYPE, "ERR_CRYPTO_INVALID_DIGEST", "Invalid digest"); + return NULL; + } + static SCR_TL bool installed; + if (!installed) { + installed = true; + scr_dyn_handle_install(SCR_DYNH_SIGN, &sp_sign_ops); + scr_dyn_handle_install(SCR_DYNH_VERIFY, &sp_verify_ops); + } + SpSigner *s = calloc(1, sizeof *s); + if (!s) scr_trap("scriptc: out of memory\n"); + s->rc = 1; + s->type = md; + mbedtls_md_init(&s->md); + mbedtls_md_setup(&s->md, mbedtls_md_info_from_type(md), 0); + mbedtls_md_starts(&s->md); + ScrDyn *box = scr_dyn_new_handle(s, verifier ? SCR_DYNH_VERIFY : SCR_DYNH_SIGN); + sp_signer_release(s); + return box; +} + +ScrDyn *scr_crypto_create_sign(ScrDyn *algorithm) { return sp_signer_new(algorithm, false); } + +ScrDyn *scr_crypto_create_verify(ScrDyn *algorithm) { return sp_signer_new(algorithm, true); } + +/* ── generateKeyPair ──────────────────────────────────────────────────── */ + +static ScrDyn *sp_cap(ScrClosure *c, size_t i) { return scr_box_get_ref(c->caps[i]); } + +static void sp_key_pair_deliver(ScrClosure *self) { + ScrDyn *callback = sp_cap(self, 0); + ScrDyn *pair = sp_cap(self, 1); + ScrDyn *args[3] = {scr_dyn_new_null(), scr_dyn_retain(scr_dyn_obj_get(pair, "publicKey", 9)), + scr_dyn_retain(scr_dyn_obj_get(pair, "privateKey", 10))}; + ScrDyn *result = scr_dyn_call(callback, args, 3, "callback"); + if (result) scr_dyn_release(result); + for (size_t i = 0; i < 3; i++) scr_dyn_release(args[i]); + scr_dyn_release(pair); + scr_dyn_release(callback); +} + +/* generateKeyPair(type, options, callback): argument errors throw, and the + * callback receives (null, publicKey, privateKey) in a later macrotask. */ +void scr_crypto_generate_key_pair_async(ScrDyn *type, ScrDyn *options, ScrDyn *callback) { + ScrDyn *pair = scr_crypto_generate_key_pair_sync(type, options); + if (!pair) return; + ScrClosure *c = scr_closure_new((void *)sp_key_pair_deliver, 2); + c->caps[0] = scr_box_new_obj(scr_dyn_retain_v, scr_dyn_release_v, NULL); + scr_box_set_ref(c->caps[0], scr_dyn_retain(callback)); + c->caps[1] = scr_box_new_obj(scr_dyn_retain_v, scr_dyn_release_v, NULL); + scr_box_set_ref(c->caps[1], pair); + scr_loop_defer(c); +} + +/* ── the core for the WebCrypto layer (scr_pki.h) ─────────────────────── */ + +ScrPkiKey *scr_pki_key_retain(ScrPkiKey *key) { return sp_key_retain(key); } + +void scr_pki_key_release(ScrPkiKey *key) { sp_key_release(key); } + +bool scr_pki_key_is_private(const ScrPkiKey *key) { return key->private_key; } + +bool scr_pki_key_is_rsa(const ScrPkiKey *key) { return sp_is_rsa(key); } + +bool scr_pki_key_is_ed25519(const ScrPkiKey *key) { return sp_is_ed(key); } + +const char *scr_pki_key_curve(const ScrPkiKey *key) { + const SpCurve *curve = sp_curve_of(key); + return curve ? curve->jwk : NULL; +} + +size_t scr_pki_key_bits(const ScrPkiKey *key) { return mbedtls_pk_get_bitlen(&key->pk); } + +ScrBytes *scr_pki_key_exponent(const ScrPkiKey *key) { + mbedtls_mpi e; + mbedtls_mpi_init(&e); + mbedtls_rsa_export(mbedtls_pk_rsa(key->pk), NULL, NULL, NULL, NULL, &e); + size_t n = mbedtls_mpi_size(&e); + ScrBytes *out = scr_bytes_new(SCR_BYTES_U8, (double)n); + if (n) mbedtls_mpi_write_binary(&e, out->data, n); + mbedtls_mpi_free(&e); + return out; +} + +ScrPkiKey *scr_pki_key_parse_der(const uint8_t *der, size_t len, bool private_key) { + if ((private_key && len == 48 && memcmp(der, sp_ed_pkcs8_prefix, 16) == 0) || + (!private_key && len == 44 && memcmp(der, sp_ed_spki_prefix, 12) == 0)) + { + bool failed; + return sp_ed_from_der(der, len, private_key, &failed); + } + SpKey *k = sp_key_alloc(private_key); + int r = private_key ? mbedtls_pk_parse_key(&k->pk, der, len, NULL, 0, sp_random, NULL) + : mbedtls_pk_parse_public_key(&k->pk, der, len); + if (r != 0 || !sp_key_supported(k)) { + sp_key_release(k); + return NULL; + } + return k; +} + +ScrPkiKey *scr_pki_key_from_jwk(const ScrDyn *jwk, bool private_key) { + SpKey *k = sp_key_from_jwk(jwk, private_key); + if (!k) scr_exc_clear(); + return k; +} + +ScrPkiKey *scr_pki_key_from_point(const char *curve_name, const uint8_t *point, size_t len) { + const SpCurve *curve = NULL; + for (size_t i = 0; i < sizeof sp_curves / sizeof sp_curves[0]; i++) + if (strcmp(sp_curves[i].jwk, curve_name) == 0) curve = &sp_curves[i]; + if (!curve) return NULL; + SpKey *k = sp_key_alloc(false); + bool ok = false; + if (mbedtls_pk_setup(&k->pk, mbedtls_pk_info_from_type(MBEDTLS_PK_ECKEY)) == 0) { + mbedtls_ecp_keypair *ec = mbedtls_pk_ec(k->pk); + ok = mbedtls_ecp_group_load(&ec->MBEDTLS_PRIVATE(grp), curve->id) == 0 && + mbedtls_ecp_point_read_binary(&ec->MBEDTLS_PRIVATE(grp), &ec->MBEDTLS_PRIVATE(Q), point, len) == 0 && + mbedtls_ecp_check_pubkey(&ec->MBEDTLS_PRIVATE(grp), &ec->MBEDTLS_PRIVATE(Q)) == 0; + } + if (!ok) { + sp_key_release(k); + return NULL; + } + return k; +} + +ScrPkiKey *scr_pki_key_public_of(ScrPkiKey *key) { return sp_public_of(key); } + +ScrPkiKey *scr_pki_generate_rsa(unsigned bits, uint64_t exponent) { + SpKey *k = sp_key_alloc(true); + if (exponent > 2147483647 || mbedtls_pk_setup(&k->pk, mbedtls_pk_info_from_type(MBEDTLS_PK_RSA)) != 0 || + mbedtls_rsa_gen_key(mbedtls_pk_rsa(k->pk), sp_random, NULL, bits, (int)exponent) != 0) { + sp_key_release(k); + return NULL; + } + return k; +} + +ScrPkiKey *scr_pki_generate_ec(const char *curve_name) { + const SpCurve *curve = NULL; + for (size_t i = 0; i < sizeof sp_curves / sizeof sp_curves[0]; i++) + if (strcmp(sp_curves[i].jwk, curve_name) == 0) curve = &sp_curves[i]; + SpKey *k = sp_key_alloc(true); + if (!curve || mbedtls_pk_setup(&k->pk, mbedtls_pk_info_from_type(MBEDTLS_PK_ECKEY)) != 0 || + mbedtls_ecp_gen_key(curve->id, mbedtls_pk_ec(k->pk), sp_random, NULL) != 0) { + sp_key_release(k); + return NULL; + } + return k; +} + +ScrPkiKey *scr_pki_generate_ed25519(void) { + const ScrPkiEd25519 *ed = sp_ed(); + if (!ed) return NULL; + SpKey *k = sp_key_alloc(true); + k->ed25519 = true; + sp_random(NULL, k->ed_seed, 32); + ed->public_key(k->ed_pub, k->ed_seed); + return k; +} + +ScrPkiKey *scr_pki_key_from_ed25519_raw(const uint8_t *raw, size_t len) { + if (len != 32) return NULL; + SpKey *k = sp_key_alloc(false); + k->ed25519 = true; + memcpy(k->ed_pub, raw, 32); + return k; +} + +ScrBytes *scr_pki_export_ed25519_raw(ScrPkiKey *key) { + ScrBytes *out = scr_bytes_new(SCR_BYTES_U8, 32); + memcpy(out->data, key->ed_pub, 32); + return out; +} + +ScrBytes *scr_pki_export_der(ScrPkiKey *key) { + unsigned char *der = malloc(SP_DER_MAX); + if (!der) scr_trap("scriptc: out of memory\n"); + int n = key->private_key ? sp_write_pkcs8_der(key, der, SP_DER_MAX) : sp_write_spki_der(key, der, SP_DER_MAX); + ScrBytes *out = NULL; + if (n > 0) { + out = scr_bytes_new(SCR_BYTES_U8, (double)n); + memcpy(out->data, der + SP_DER_MAX - n, (size_t)n); + } + mbedtls_platform_zeroize(der, SP_DER_MAX); + free(der); + return out; +} + +ScrBytes *scr_pki_export_point(ScrPkiKey *key) { + const mbedtls_ecp_keypair *ec = mbedtls_pk_ec(key->pk); + unsigned char point[160]; + size_t n; + if (mbedtls_ecp_point_write_binary(&ec->MBEDTLS_PRIVATE(grp), &ec->MBEDTLS_PRIVATE(Q), + MBEDTLS_ECP_PF_UNCOMPRESSED, &n, point, sizeof point) != 0) + return NULL; + ScrBytes *out = scr_bytes_new(SCR_BYTES_U8, (double)n); + memcpy(out->data, point, n); + return out; +} + +ScrDyn *scr_pki_export_jwk(ScrPkiKey *key) { return sp_export_jwk(key); } + +static bool sp_webcrypto_md(const char *hash, mbedtls_md_type_t *md) { + if (strcmp(hash, "SHA-1") == 0) *md = MBEDTLS_MD_SHA1; + else if (strcmp(hash, "SHA-256") == 0) *md = MBEDTLS_MD_SHA256; + else if (strcmp(hash, "SHA-384") == 0) *md = MBEDTLS_MD_SHA384; + else if (strcmp(hash, "SHA-512") == 0) *md = MBEDTLS_MD_SHA512; + else return false; + return true; +} + +ScrBytes *scr_pki_sign(ScrPkiKey *key, const char *hash, bool pss, int salt, const uint8_t *data, + size_t len) { + if (sp_is_ed(key)) { + const ScrPkiEd25519 *ed = sp_ed(); + if (!ed) return NULL; + ScrBytes *out = scr_bytes_new(SCR_BYTES_U8, 64); + ed->sign(out->data, key->ed_seed, key->ed_pub, data, len); + return out; + } + mbedtls_md_type_t md; + if (!sp_webcrypto_md(hash, &md)) return NULL; + const mbedtls_md_info_t *info = mbedtls_md_info_from_type(md); + unsigned char digest[MBEDTLS_MD_MAX_SIZE]; + mbedtls_md(info, data, len, digest); + SpSigKey k = {.key = key, .padding = pss ? 6 : 1, .salt = salt, .p1363 = true}; + ScrDyn *sig = sp_sign_hash(&k, md, digest, mbedtls_md_get_size(info)); + if (!sig) { + scr_exc_clear(); + return NULL; + } + ScrBytes *out = scr_bytes_buffer_source(sig); + scr_dyn_release(sig); + return out; +} + +bool scr_pki_verify(ScrPkiKey *key, const char *hash, bool pss, int salt, const uint8_t *data, + size_t len, const uint8_t *signature, size_t signature_len) { + if (sp_is_ed(key)) { + const ScrPkiEd25519 *ed = sp_ed(); + return ed && sp_ed_verify(ed, key->ed_pub, data, len, signature, signature_len); + } + mbedtls_md_type_t md; + if (!sp_webcrypto_md(hash, &md)) return false; + const mbedtls_md_info_t *info = mbedtls_md_info_from_type(md); + unsigned char digest[MBEDTLS_MD_MAX_SIZE]; + mbedtls_md(info, data, len, digest); + SpSigKey k = {.key = key, .padding = pss ? 6 : 1, .salt = salt, .p1363 = true}; + return sp_verify_hash(&k, md, digest, mbedtls_md_get_size(info), signature, signature_len); +} diff --git a/packages/runtime/src/scr_pki.h b/packages/runtime/src/scr_pki.h new file mode 100644 index 000000000..71be3c1df --- /dev/null +++ b/packages/runtime/src/scr_pki.h @@ -0,0 +1,79 @@ +/* The key and signature core of scr_pki.c, for the WebCrypto layer + * (scr_webcrypto_pki.c) and the Ed25519 unit (scr_ed25519.c). Keys are + * reference-counted RSA keys, EC keys on P-256, P-384, P-521 or secp256k1, + * or Ed25519 keys. Functions answering NULL or false set no error unless + * they say so; byte results are +1. */ +#ifndef SCR_PKI_H +#define SCR_PKI_H + +#include +#include +#include + +typedef struct SpKey ScrPkiKey; + +/* Throws an error of `kind` (with `code`, or none for NULL) whose message + * is the printf format's whole output, at any length. */ +void scr_pki_throw_fmt(int kind, const char *code, const char *fmt, ...) __attribute__((format(printf, 3, 4))); + +/* The Ed25519 arithmetic (scr_ed25519.c), installed at startup in + * programs that name Ed25519; NULL otherwise. Keys are the 32-byte seed + * and the 32-byte encoded public point. */ +typedef struct { + void (*public_key)(uint8_t pub[32], const uint8_t seed[32]); + void (*sign)(uint8_t sig[64], const uint8_t seed[32], const uint8_t pub[32], const uint8_t *m, size_t n); + bool (*verify)(const uint8_t pub[32], const uint8_t *m, size_t n, const uint8_t sig[64]); +} ScrPkiEd25519; +extern const ScrPkiEd25519 *scr_pki_ed25519; + +/* Whether the Ed25519 arithmetic is linked; false with a coded SC2020 + * error pending otherwise. */ +bool scr_pki_ed25519_ready(void); + +ScrPkiKey *scr_pki_key_retain(ScrPkiKey *key); +void scr_pki_key_release(ScrPkiKey *key); +bool scr_pki_key_is_private(const ScrPkiKey *key); +bool scr_pki_key_is_rsa(const ScrPkiKey *key); +bool scr_pki_key_is_ed25519(const ScrPkiKey *key); +/* The EC key's JWK curve name ("P-256", ...), or NULL for RSA keys. */ +const char *scr_pki_key_curve(const ScrPkiKey *key); +/* The RSA modulus length in bits. */ +size_t scr_pki_key_bits(const ScrPkiKey *key); +/* The RSA public exponent's big-endian bytes, without leading zeros. */ +ScrBytes *scr_pki_key_exponent(const ScrPkiKey *key); + +/* A key from SubjectPublicKeyInfo (public) or PKCS#8 (private) DER. */ +ScrPkiKey *scr_pki_key_parse_der(const uint8_t *der, size_t len, bool private_key); +/* A key from a JWK object (borrowed; a plain object). */ +ScrPkiKey *scr_pki_key_from_jwk(const ScrDyn *jwk, bool private_key); +/* A public EC key from an uncompressed or compressed point. */ +ScrPkiKey *scr_pki_key_from_point(const char *curve, const uint8_t *point, size_t len); +ScrPkiKey *scr_pki_key_public_of(ScrPkiKey *key); +ScrPkiKey *scr_pki_generate_rsa(unsigned bits, uint64_t exponent); +ScrPkiKey *scr_pki_generate_ec(const char *curve); +/* NULL with a coded SC2020 error pending when the program does not link + * the Ed25519 unit. */ +ScrPkiKey *scr_pki_generate_ed25519(void); +/* A public Ed25519 key from its 32-byte encoding. */ +ScrPkiKey *scr_pki_key_from_ed25519_raw(const uint8_t *raw, size_t len); +/* The Ed25519 public key's 32-byte encoding. */ +ScrBytes *scr_pki_export_ed25519_raw(ScrPkiKey *key); + +/* SubjectPublicKeyInfo (public keys) or PKCS#8 (private keys) DER. */ +ScrBytes *scr_pki_export_der(ScrPkiKey *key); +/* The EC public key's uncompressed point. */ +ScrBytes *scr_pki_export_point(ScrPkiKey *key); +/* The JWK members in Node's order (kty, n, e, ... or kty, x, y, crv, d), + * +1. */ +ScrDyn *scr_pki_export_jwk(ScrPkiKey *key); + +/* Signs `data` with the digest named by its WebCrypto name ("SHA-256"): + * RSA PKCS#1 v1.5 (pss false), RSA-PSS with `salt` bytes, or ECDSA as + * IEEE P1363 r || s. Ed25519 keys sign the message itself (hash + * ignored). */ +ScrBytes *scr_pki_sign(ScrPkiKey *key, const char *hash, bool pss, int salt, const uint8_t *data, + size_t len); +bool scr_pki_verify(ScrPkiKey *key, const char *hash, bool pss, int salt, const uint8_t *data, + size_t len, const uint8_t *signature, size_t signature_len); + +#endif diff --git a/packages/runtime/src/scr_publish.c b/packages/runtime/src/scr_publish.c index 675a13ca9..4767122dd 100644 --- a/packages/runtime/src/scr_publish.c +++ b/packages/runtime/src/scr_publish.c @@ -199,6 +199,19 @@ static void scr_pub_slot(ScrPub *ctx, uint64_t slot, ScrPubFn fn) { if (fn) scr_pub_push(ctx, p, fn); } +/* The elements of a compact reference array (SCR_ELEM_CREF): 4-byte dense + * slots, 8-byte pointers in the sparse entries. */ +static __attribute__((noinline)) void scr_pub_cref_elems(ScrArr *a, ScrPub *ctx, ScrPubFn fn) { + size_t dense = a->len < a->cap ? a->len : a->cap; + const uint32_t *refs = (const uint32_t *)a->data; + const uint8_t *states = scr_arr_has_states(a) ? scr_arr_states_end_w(a, sizeof(uint32_t)) : NULL; + for (size_t i = 0; i < dense; i++) + if (!states || *scr_arr_state_in(states, i)) scr_pub_slot(ctx, scr_cref_decode(refs[i]), fn); + if (scr_arr_ext_of(a)) + for (size_t i = 0; i < scr_arr_ext_of(a)->sparse_len; i++) + if (scr_arr_ext_of(a)->sparse[i].state) scr_pub_slot(ctx, scr_arr_ext_of(a)->sparse[i].slot, fn); +} + void scr_pub_arr(void *v, ScrPub *ctx, ScrPubFn elem) { ScrArr *a = v; if (scr_arr_ext_of(a) && (scr_arr_ext_of(a)->props || scr_arr_ext_of(a)->metadata)) { @@ -206,10 +219,15 @@ void scr_pub_arr(void *v, ScrPub *ctx, ScrPubFn elem) { return; } if (!scr_pub_mark(ctx, a, a->cyc != 0, SCR_PUB_KIND_ARRAY)) return; + if (__builtin_expect(a->elem == SCR_ELEM_CREF, 0)) { + scr_pub_cref_elems(a, ctx, elem); + return; + } ScrPubFn fn = a->elem == SCR_ELEM_STR ? scr_pub_str_fn : a->elem == SCR_ELEM_REF ? elem : NULL; if (!fn) return; + /* String and reference elements have 8-byte slots. */ size_t dense = a->len < a->cap ? a->len : a->cap; - const uint8_t *states = scr_arr_states_end(a); + const uint8_t *states = scr_arr_scan_states(a); for (size_t i = 0; i < dense; i++) if (!states || *scr_arr_state_in(states, i)) scr_pub_slot(ctx, a->data[i], fn); if (scr_arr_ext_of(a)) @@ -231,12 +249,12 @@ void scr_pub_map(void *v, ScrPub *ctx, ScrPubFn key, ScrPubFn val) { m->key_kind == SCR_MAP_KEY_BIGINT || m->key_kind == SCR_MAP_KEY_UNION_VALUE ? key : NULL; - ScrPubFn vfn = m->val_kind == SCR_MAP_VAL_REF ? val : NULL; + ScrPubFn vfn = m->val_kind == SCR_MAP_VAL_REF || m->val_kind == SCR_MAP_VAL_CREF ? val : NULL; for (size_t i = 0; i < m->nentries; i++) { if (!scr_map_entry_live(m, i)) continue; /* tombstone */ const ScrMapEntry *e = scr_map_entry_at(m, i); if (kfn) scr_pub_slot(ctx, e->key, kfn); - if (vfn) scr_pub_slot(ctx, e->val, vfn); + if (vfn) scr_pub_slot(ctx, scr_map_entry_val(m, e), vfn); } } diff --git a/packages/runtime/src/scr_rc.h b/packages/runtime/src/scr_rc.h index 7a921b451..18df3a237 100644 --- a/packages/runtime/src/scr_rc.h +++ b/packages/runtime/src/scr_rc.h @@ -670,6 +670,10 @@ static inline void scr_cyc_dead(void *obj) { * live heap — do not put it on a per-turn path. */ void scr_collect_cycles(void); void scr_collect_cycles_phase(void); +/* Sets the growth cap SCR_CYCLE_GROWTH_CAP sets (scr_cycle.c), for a program + * that knows its own memory profile; the environment variable takes + * precedence. Call it before the program allocates much. */ +void scr_cyc_set_growth_cap(long cap); void scr_cyc_context_cleanup(void); /* One pass on the normal generational schedule, for callers that reach a diff --git a/packages/runtime/src/scr_regex.c b/packages/runtime/src/scr_regex.c index b62cba896..158697a14 100644 --- a/packages/runtime/src/scr_regex.c +++ b/packages/runtime/src/scr_regex.c @@ -692,7 +692,7 @@ static ScrDyn *scr_regex_groups_of(const ScrArr *a, uint8_t *bc) { for (int k = 1; k < capture_count; k++) { size_t length = strlen(name); bool matched = (size_t)k < a->len && (size_t)k < a->cap && - *scr_arr_state_ptr(a, (size_t)k) == SCR_ARR_VALUE; + scr_arr_dense_state(a, (size_t)k) == SCR_ARR_VALUE; /* ES2025 duplicates sit in distinct alternatives: at most one * participates, and it wins over an earlier undefined. */ if (length && (matched || !scr_dyn_obj_get(groups, name, length))) @@ -845,7 +845,7 @@ static ScrArr *scr_regex_exec_core(ScrStr *s, ScrRegex *re, uint64_t mask, bool if (rc == 1) { int count = lre_get_capture_count(bc); bool spans = lazy != 0 && !input.wide && (count >= 64 || ((mask | lazy) >> count) == 0); - out = scr_arr_new_inline(SCR_ELEM_STR, (size_t)count + spans); + out = scr_arr_new_inline(SCR_ELEM_STR, (size_t)count + spans, true); /* A fresh dense array: every slot is written directly, then the * hole-free prefix is the run of materialized captures from 0. Its * storage pointers are fixed (the inline block never moves here), so @@ -905,14 +905,15 @@ static bool scr_regex_group_bytes(const ScrArr *m, double k, const char **p, siz /* Array lengths stay below 2^53, so signed conversions are exact. */ if (!(k >= 0 && k < (double)(int64_t)m->len)) return false; size_t i = (size_t)(int64_t)k; - if (*scr_arr_state_ptr(m, i) == SCR_ARR_VALUE) { + uint8_t state = scr_arr_dense_state(m, i); + if (state == SCR_ARR_VALUE) { const ScrStr *str = (const ScrStr *)(uintptr_t)m->data[i]; *p = str->data; *n = str->len; return true; } uint64_t span = m->data[i]; - if (*scr_arr_state_ptr(m, i) != SCR_ARR_UNDEFINED || span == SCR_RE_NO_SPAN) return false; + if (state != SCR_ARR_UNDEFINED || span == SCR_RE_NO_SPAN) return false; const ScrStr *subject = (const ScrStr *)(uintptr_t)m->data[m->len - 1]; *p = subject->data + (span >> 32); *n = (size_t)((span & UINT32_MAX) - (span >> 32)); @@ -1043,10 +1044,13 @@ static ScrArr *scr_regex_match_all_core(ScrStr *s, ScrRegex *re, ScrArr *indices int start = scr_capture_index(&input, capture[0]); int end = scr_capture_index(&input, capture[1]); /* One allocation per row, like an exec result: every slot is written - * directly, then the hole-free prefix is the run of captures from 0. */ - ScrArr *row = scr_arr_new_inline(SCR_ELEM_STR, (size_t)capture_count); + * directly, then the hole-free prefix is the run of captures from 0. + * A row needs states only for a capture that did not participate. */ + bool all = true; + for (int k = 0; k < capture_count; k++) all &= capture[2 * k] != NULL && capture[2 * k + 1] != NULL; + ScrArr *row = scr_arr_new_inline(SCR_ELEM_STR, (size_t)capture_count, !all); uint64_t *data = row->data; - uint8_t *states = scr_arr_states_end_w(row, 8); + uint8_t *states = all ? NULL : scr_arr_states_end_w(row, 8); for (int k = 0; k < capture_count; k++) { const uint8_t *cs = capture[2 * k], *ce = capture[2 * k + 1]; if (cs == NULL || ce == NULL) { @@ -1056,11 +1060,11 @@ static ScrArr *scr_regex_match_all_core(ScrStr *s, ScrRegex *re, ScrArr *indices ScrStr *text = scr_regex_span(&input, scr_capture_index(&input, cs), scr_capture_index(&input, ce)); data[k] = (uint64_t)(uintptr_t)text; - *scr_arr_state_in(states, (size_t)k) = SCR_ARR_VALUE; + if (states) *scr_arr_state_in(states, (size_t)k) = SCR_ARR_VALUE; } } size_t filled = 0; - while (filled < (size_t)capture_count && *scr_arr_state_in(states, filled) == SCR_ARR_VALUE) + while (filled < (size_t)capture_count && (!states || *scr_arr_state_in(states, filled) == SCR_ARR_VALUE)) filled++; row->filled = (uint32_t)filled; row->len = (size_t)capture_count; @@ -2795,7 +2799,7 @@ static ScrDyn *scr_native_regex_invoke(void *ptr, ScrDyn *self, const char *meth if (!row) return scr_exc_pending() ? NULL : scr_dyn_new_null(); ScrDyn *match = scr_dyn_new_arr(); for (size_t k = 0; k < row->len; k++) - scr_dyn_arr_push(match, *scr_arr_state_ptr(row, k) == SCR_ARR_VALUE + scr_dyn_arr_push(match, scr_arr_dense_state(row, k) == SCR_ARR_VALUE ? scr_dyn_new_str((ScrStr *)(uintptr_t)row->data[k]) : scr_dyn_retain(scr_dyn_undefined())); scr_arr_copy_metadata(row, match); diff --git a/packages/runtime/src/scr_region.c b/packages/runtime/src/scr_region.c index dbd74f3ac..25bbcf7ae 100644 --- a/packages/runtime/src/scr_region.c +++ b/packages/runtime/src/scr_region.c @@ -805,7 +805,7 @@ static void scr_rgn_walk_arr(ScrRgnWalk *w, ScrArr *a) { ScrRgnSlotKind k = a->elem == SCR_ELEM_ARR ? (ScrRgnSlotKind){SCR_RGN_W_ARR, NULL} : scr_rgn_slot_kind(scr_arr_ops(a) ? scr_arr_ops(a)->release : NULL); size_t dense = a->len < a->cap ? a->len : a->cap; - const uint8_t *states = scr_arr_states_end(a); + const uint8_t *states = scr_arr_scan_states(a); for (size_t i = 0; i < dense; i++) if (!states || *scr_arr_state_in(states, i) == SCR_ARR_VALUE) scr_rgn_slot_as(w, scr_rgn_slot_ptr(a->data[i]), k); if (!scr_arr_ext_of(a)) return; diff --git a/packages/runtime/src/scr_shared.c b/packages/runtime/src/scr_shared.c index 2dac5a4d1..6505a71ab 100644 --- a/packages/runtime/src/scr_shared.c +++ b/packages/runtime/src/scr_shared.c @@ -7,7 +7,9 @@ #include "scr_numeric.h" #include #include +#include #include +#include #include #if defined(SCR_WORKERS) || (defined(SCR_LIB) && defined(SCR_THREAD_INSTANCES)) #ifdef _WIN32 @@ -360,3 +362,69 @@ double scr_atomics_notify(ScrBytes *bytes, double index, double count) { scr_wait_unlock(bucket); return notified; } + +/* V8's text for a value in the TypeErrors below: a typed array as + * [object Int8Array] and so on, an array as [object Array], an ArrayBuffer + * or other native object as #, an object as #, and + * other values as String() gives them (undefined and null by name). */ +static ScrStr *scr_atomics_value_text(const ScrDyn *value) { + char text[64]; + int n; + if (value->kind == SCR_DYN_BYTES) { + if (value->v.bytes->is_data_view) n = snprintf(text, sizeof text, "#"); + else n = snprintf(text, sizeof text, "[object %s]", scr_bytes_elem_name(value->v.bytes->elem)); + } else if (value->kind == SCR_DYN_ARR) { + n = snprintf(text, sizeof text, "[object Array]"); + } else if (value->kind == SCR_DYN_HANDLE) { + n = snprintf(text, sizeof text, "#<%s>", scr_dyn_handle_ops_of(value)->cls); + } else if (value->kind == SCR_DYN_OBJ) { + const char *name = scr_dyn_class_name(value); + n = snprintf(text, sizeof text, "#<%s>", name ? name : "Object"); + } else if (value->kind == SCR_DYN_TYPED_REF && scr_dyn_typed_ref_class_name(value)) { + const ScrStr *name = scr_dyn_typed_ref_class_name(value); + n = snprintf(text, sizeof text, "#<%.*s>", (int)name->len, (const char *)name->data); + } else if (value->kind == SCR_DYN_UNDEF) { + n = snprintf(text, sizeof text, "undefined"); + } else if (value->kind == SCR_DYN_NULL) { + n = snprintf(text, sizeof text, "null"); + } else { + return scr_dyn_to_string(value, NULL); + } + return scr_str_new(text, n < (int)sizeof text ? (size_t)n : sizeof text - 1); +} + +/* The integer typed array an untyped Atomics argument holds, or NULL with + * Node's TypeError pending. `waitable` requires an Int32Array, as wait and + * notify do. */ +static ScrBytes *scr_atomics_dyn_array(const ScrDyn *value, bool waitable) { + if (value->kind == SCR_DYN_BYTES && !value->v.bytes->is_data_view) { + ScrBytesElem elem = value->v.bytes->elem; + bool integer = elem == SCR_BYTES_I8 || elem == SCR_BYTES_U8 || elem == SCR_BYTES_I16 || + elem == SCR_BYTES_U16 || elem == SCR_BYTES_I32 || elem == SCR_BYTES_U32; + if (waitable ? elem == SCR_BYTES_I32 : integer) return value->v.bytes; + } + ScrStr *shown = scr_atomics_value_text(value); + if (!shown) return NULL; + const char *tail = waitable ? " is not an int32 or BigInt64 typed array." : " is not an integer typed array."; + ScrStr *parts[2] = {shown, scr_str_new(tail, strlen(tail))}; + ScrStr *message = scr_str_concat_parts(parts, 2); + scr_str_release(parts[0]); + scr_str_release(parts[1]); + scr_throw_error(SCR_ERR_TYPE, message); + return NULL; +} + +double scr_atomics_op_dyn(const ScrDyn *array, double index, double value, double replacement, double operation) { + ScrBytes *bytes = scr_atomics_dyn_array(array, false); + return bytes ? scr_atomics_op(bytes, index, value, replacement, operation) : 0; +} + +ScrStr *scr_atomics_wait_dyn(const ScrDyn *array, double index, double expected, double timeout) { + ScrBytes *bytes = scr_atomics_dyn_array(array, true); + return bytes ? scr_atomics_wait(bytes, index, expected, timeout) : NULL; +} + +double scr_atomics_notify_dyn(const ScrDyn *array, double index, double count) { + ScrBytes *bytes = scr_atomics_dyn_array(array, true); + return bytes ? scr_atomics_notify(bytes, index, count) : 0; +} diff --git a/packages/runtime/src/scr_stream.c b/packages/runtime/src/scr_stream.c index f7330b615..275c03039 100644 --- a/packages/runtime/src/scr_stream.c +++ b/packages/runtime/src/scr_stream.c @@ -80,8 +80,11 @@ static ScrBytes *scr_stream_buffer(ScrBytes *b) { /* ── state ────────────────────────────────────────────────────────────── */ typedef struct ScrWEntry { - ScrBytes *chunk; /* owned */ + ScrBytes *chunk; /* owned; a ScrDyn* value on an object-mode writable side */ ScrClosure *cb; /* owned or NULL (the user's write(chunk, cb) callback) */ + ScrDyn *enc; /* owned or NULL = undefined: the encoding argument an + * object-mode write passed (Node hands it to _write + * unchanged; null when the callback took its place) */ } ScrWEntry; struct ScrStreamState { @@ -132,11 +135,22 @@ struct ScrStreamState { bool object_entries; /* An operator output's entry kind is decided by its first push. */ bool object_kind_set; + /* An object-mode buffer that holds a value other than a string or a + * Buffer, or both kinds: every entry is an owned ScrDyn* + * (scr_stream_add_value). Takes precedence over `encoded`. */ + bool dyn_entries; + /* The objectMode or readableObjectMode option made the buffer hold + * object entries (a stream without _read is not a seeded + * Readable.from source). */ + bool object_mode_opt; /* The parked for-await next() promise (at most one — the loop awaits * each chunk before asking again). next_dyn picks the resolution - * shape: a dyn boxed by tag (the JS lane), or bytes. */ + * shape: a dyn boxed by tag (the JS lane), or bytes; next_result + * wraps the dyn in an iterator result ({ value, done }) for the + * checked-dynamic for-await protocol. */ ScrPromise *next_waiter; bool next_dyn; + bool next_result; /* The iterator's own read() is calling _read: synchronous pushes * buffer, and the waiter takes the whole buffer afterwards (Node's * read() returns everything _read pushed). */ @@ -146,6 +160,11 @@ struct ScrStreamState { * nextTick and then the resumed `await new Promise(next)` * (next_wake: that tick is queued). */ bool next_parked, next_wake; + /* Node's iterator ends through eos, which waits for 'close' when the + * stream will emit it (willEmitClose, fixed when the iterator starts: + * a readable-only stream with autoDestroy and emitClose, not yet + * closed). next_eof_close: the ended waiter is held for 'close'. */ + bool next_started, next_close_wait, next_eof_close; ScrClosure *read_cb; ScrStreamReadInv read_inv; } r; @@ -157,9 +176,36 @@ struct ScrStreamState { size_t n, cap, head; int corked; bool writing, wsync, need_drain, after_scheduled; + /* Deferred afterWrites Node also defers (a user callback, a 'drain' + * or a destroyed stream): its pendingcb, which holds the finish until + * they ran — afterWrite's finishMaybe then puts 'finish' on a tick + * of its own. */ + size_t after_holds; + /* clearBuffer is running its loop: a write completing inside it + * leaves the next buffered write to the loop (Node's + * kBufferProcessing), so completions keep their order */ + bool buffer_processing; + /* objectMode writable side: queued chunks, and the chunk the write + * and transform steps receive, are ScrDyn* values (in the ScrBytes* + * slots), each counting 1 toward length. */ + bool object_mode; + /* The queue holds ScrDyn* values: on an object-mode side, and with + * decodeStrings: false, where strings stay strings (their UTF-16 + * length counts) and Buffers are buffer values. Each entry's encoding + * argument rides in ScrWEntry.enc. */ + bool values, decode_strings_off; + /* The defaultEncoding option or setDefaultEncoding(), as given; NULL + * is utf8. What write(string) encodes with, and the encoding _write + * receives for a string when decodeStrings is false. */ + ScrStr *default_enc; + /* _writev: more than one buffered write reaches it as one batch, and a + * stream without _write sends each write through it. */ + ScrClosure *writev_cb; + ScrStreamWritevInv writev_inv; bool ending, finished, prefinished, final_called, finish_scheduled; bool final_pending; /* _final called, its callback not yet run */ ScrClosure *inflight_cb; /* owned or NULL */ + ScrDyn *cur_enc; /* borrowed: the running write's encoding argument */ ScrClosure *write_cb; ScrStreamChunkInv write_inv; ScrClosure *final_cb; @@ -175,6 +221,11 @@ struct ScrStreamState { ScrStreamPlainInv flush_inv; bool flush_called; bool flush_pending; /* _flush called, its callback not yet run */ + /* Transform._write's backpressure: the readable length when the + * transform started, and whether its completed write waits for the + * readable side to read (Node's kCallback). */ + size_t xf_length; + bool xf_held; /* A _final that completes at once (zlib's ZlibBase): 'prefinish' starts * the flush and 'finish' does not wait for it. */ bool flush_on_prefinish; @@ -217,6 +268,7 @@ struct ScrStreamState { * path and _destroy wait. A destroy() in that window marks the stream * destroyed and runs its _destroy once construction completes. */ bool constructing, destroy_deferred; + bool construct_finished; /* onConstruct ran: a second callback is ERR_MULTIPLE_CALLBACK */ ScrError *destroy_err; /* owned: the deferred destroy's error */ ScrClosure *construct_cb; ScrStreamPlainInv construct_inv; @@ -262,31 +314,86 @@ static bool scr_stream_is(const ScrEmitter *em) { scr_vt_within(vt, &scr_passthrough_vt); } -/* Readable-buffer entry accessors: bytes chunks, or strings once an +/* Readable-buffer entry accessors: bytes chunks, strings once an * encoding is set (lengths then count JS string units, Node's encoded - * accounting). */ + * accounting), or checked-dynamic values in an object-mode buffer that + * holds other values. */ +typedef enum { SCR_ENTRY_BYTES, SCR_ENTRY_STR, SCR_ENTRY_DYN } ScrEntryKind; + +static ScrEntryKind scr_stream_rkind(const ScrStreamState *st) { + return st->r.dyn_entries ? SCR_ENTRY_DYN : st->r.encoded ? SCR_ENTRY_STR : SCR_ENTRY_BYTES; +} + static size_t scr_stream_entry_len(const ScrStreamState *st, void *e) { if (st->r.object_entries) return 1; /* objectMode-style accounting */ return st->r.encoded ? (size_t)scr_str_utf16_len((ScrStr *)e) : ((ScrBytes *)e)->len; } -static void scr_stream_entry_release(const ScrStreamState *st, void *e) { - if (st->r.encoded) scr_str_release((ScrStr *)e); +/* Releases an entry by the kind it had when it left the buffer: a 'data' + * listener may call setEncoding() or push another kind of value while the + * entry is out. */ +static void scr_stream_entry_release_kind(void *e, ScrEntryKind kind) { + if (kind == SCR_ENTRY_DYN) scr_dyn_release((ScrDyn *)e); + else if (kind == SCR_ENTRY_STR) scr_str_release((ScrStr *)e); else scr_bytes_release((ScrBytes *)e); } -/* Releases an entry by the kind it had when it left the buffer: a 'data' - * listener may call setEncoding() while the entry is out. */ -static void scr_stream_entry_release_kind(void *e, bool is_str) { - if (is_str) scr_str_release((ScrStr *)e); - else scr_bytes_release((ScrBytes *)e); +static void scr_stream_entry_release(const ScrStreamState *st, void *e) { + scr_stream_entry_release_kind(e, scr_stream_rkind(st)); +} + +/* An entry of the given kind as a dyn value (+1; moves entry). */ +static ScrDyn *scr_stream_entry_box(void *entry, ScrEntryKind kind) { + if (kind == SCR_ENTRY_DYN) return entry; + ScrDyn *d; + if (kind == SCR_ENTRY_STR) { + d = scr_dyn_new_str((ScrStr *)entry); + scr_str_release((ScrStr *)entry); + } else { + ScrBytes *b = entry; + d = b->is_buffer ? scr_dyn_new_buffer(b) : scr_dyn_new_bytes(b); + scr_bytes_release(b); + } + return d; +} + +/* Writable-queue chunks: Buffers, or dyn values (w.values). A value + * counts 1 on an object-mode side, else its length (a string's UTF-16 + * length, as Node's chunk.length). */ +static size_t scr_stream_wchunk_len(const ScrStreamState *st, ScrBytes *chunk) { + if (st->w.object_mode) return 1; + if (!st->w.values) return chunk->len; + ScrDyn *v = (ScrDyn *)chunk; + if (v->kind == SCR_DYN_STR) return (size_t)scr_str_utf16_len(v->v.str); + if (v->kind == SCR_DYN_BYTES) return v->v.bytes->len; + return 1; +} + +static ScrBytes *scr_stream_wchunk_retain(const ScrStreamState *st, ScrBytes *chunk) { + if (st->w.values) return (ScrBytes *)scr_dyn_retain((ScrDyn *)chunk); + return scr_bytes_retain(chunk); +} + +static void scr_stream_wchunk_release(const ScrStreamState *st, ScrBytes *chunk) { + if (st->w.values) scr_dyn_release((ScrDyn *)chunk); + else scr_bytes_release(chunk); +} + +/* A dyn entry the collector traces, and so frees itself in a collection + * (the kinds that carry a collector header). */ +static bool scr_stream_dyn_entry_traced(const ScrDyn *d) { + return d->kind > SCR_DYN_STR && d->kind != SCR_DYN_UNDEF; } static void scr_stream_state_drop(ScrStreamState *st, bool gc) { if (!st) return; if (st->errored) scr_error_release(st->errored); if (st->native) st->native_release(st->native); - for (size_t i = 0; i < st->r.n; i++) scr_stream_entry_release(st, st->r.buf[i]); + for (size_t i = 0; i < st->r.n; i++) { + /* The collector frees the dyn entries it traced. */ + if (gc && st->r.dyn_entries && scr_stream_dyn_entry_traced(st->r.buf[i])) continue; + scr_stream_entry_release(st, st->r.buf[i]); + } free(st->r.buf); if (st->r.enc) scr_str_release(st->r.enc); if (st->r.push_enc) scr_str_release(st->r.push_enc); @@ -294,6 +401,7 @@ static void scr_stream_state_drop(ScrStreamState *st, bool gc) { if (st->destroy_err) scr_error_release(st->destroy_err); if (!gc) { if (st->construct_cb) scr_closure_release(st->construct_cb); + if (st->w.writev_cb) scr_closure_release(st->w.writev_cb); if (st->r.read_cb) scr_closure_release(st->r.read_cb); if (st->w.write_cb) scr_closure_release(st->w.write_cb); if (st->w.final_cb) scr_closure_release(st->w.final_cb); @@ -307,10 +415,14 @@ static void scr_stream_state_drop(ScrStreamState *st, bool gc) { for (size_t i = 0; i < st->drain_srcs.n; i++) scr_stream_release(st->drain_srcs.src[i]); } for (size_t i = st->w.head; i < st->w.n; i++) { - scr_bytes_release(st->w.q[i].chunk); + bool traced = st->w.values && scr_stream_dyn_entry_traced((ScrDyn *)st->w.q[i].chunk); + if (!gc || !traced) scr_stream_wchunk_release(st, st->w.q[i].chunk); if (!gc && st->w.q[i].cb) scr_closure_release(st->w.q[i].cb); + ScrDyn *enc = st->w.q[i].enc; + if (enc && (!gc || !scr_stream_dyn_entry_traced(enc))) scr_dyn_release(enc); } free(st->w.q); + if (st->w.default_enc) scr_str_release(st->w.default_enc); free(st->w.end_cbs); free(st->fin.cb); free(st->fin.inv); @@ -330,11 +442,17 @@ void scr_stream_st_gcfree(ScrStreamState *st) { scr_stream_state_drop(st, true); void scr_stream_st_trace(ScrStreamState *st, ScrTraceVisit visit, void *ctx) { if (!st) return; + if (st->r.dyn_entries) { + for (size_t i = 0; i < st->r.n; i++) { + if (scr_stream_dyn_entry_traced(st->r.buf[i])) visit(st->r.buf[i], ctx); + } + } if (st->r.next_waiter) visit(st->r.next_waiter, ctx); if (st->r.read_cb) visit(st->r.read_cb, ctx); if (st->construct_cb) visit(st->construct_cb, ctx); if (st->w.write_cb) visit(st->w.write_cb, ctx); if (st->w.final_cb) visit(st->w.final_cb, ctx); + if (st->w.writev_cb) visit(st->w.writev_cb, ctx); if (st->w.inflight_cb) visit(st->w.inflight_cb, ctx); if (st->transform_cb) visit(st->transform_cb, ctx); if (st->flush_cb) visit(st->flush_cb, ctx); @@ -343,6 +461,9 @@ void scr_stream_st_trace(ScrStreamState *st, ScrTraceVisit visit, void *ctx) { for (size_t i = 0; i < st->fin.n; i++) visit(st->fin.cb[i], ctx); for (size_t i = st->w.head; i < st->w.n; i++) { if (st->w.q[i].cb) visit(st->w.q[i].cb, ctx); + if (st->w.values && scr_stream_dyn_entry_traced((ScrDyn *)st->w.q[i].chunk)) + visit(st->w.q[i].chunk, ctx); + if (st->w.q[i].enc && scr_stream_dyn_entry_traced(st->w.q[i].enc)) visit(st->w.q[i].enc, ctx); } for (size_t i = 0; i < st->pipes.n; i++) visit(st->pipes.dst[i], ctx); for (size_t i = 0; i < st->drain_srcs.n; i++) visit(st->drain_srcs.src[i], ctx); @@ -412,6 +533,7 @@ typedef enum { SCR_ST_ERROR_BUFFER, /* errorBuffer: buffered write and end() callbacks */ SCR_ST_CONSTRUCT, /* constructNT: run the construct hook */ SCR_ST_CONSTRUCTED, /* onConstruct: resume reads/writes/destroy */ + SCR_ST_XF_DONE, /* a transform's write callback after push(null) */ } ScrStreamTickOp; typedef struct ScrStreamTick { @@ -419,6 +541,7 @@ typedef struct ScrStreamTick { ScrStreamTickOp op; ScrError *err; /* owned or NULL (SCR_ST_ERROR) */ ScrClosure *cb; /* owned or NULL (SCR_ST_AFTER_WRITE / SCR_ST_WCB_ERR / SCR_ST_WRITE_ERR) */ + bool hold; /* SCR_ST_AFTER_WRITE: counted in w.after_holds */ struct ScrStreamTick *next; } ScrStreamTick; @@ -480,10 +603,20 @@ static ScrError *scr_stream_mkerr(const char *code, const char *msg) { return e; } +/* The pending exception as a stream error (+1): Error values as + * themselves, any other thrown value as an internal assertion. */ +static ScrError *scr_stream_take_error(void) { + ScrCaught *caught = scr_exc_take(); + ScrDyn *value = scr_caught_to_dyn(caught); + scr_caught_release(caught); + ScrError *err = value ? scr_errdyn_err_of(value) : NULL; + if (value) scr_dyn_release(value); + return err ? err : scr_stream_mkerr("ERR_INTERNAL_ASSERTION", "a stream operation threw a value that is not an Error"); +} + /* ── forward decls ────────────────────────────────────────────────────── */ static void scr_stream_flow(ScrStream *s); -static int scr_stream_add_entry(ScrStream *s, void *entry /*moves*/, bool is_str); static void scr_stream_readable_listen(ScrStream *s); static void scr_stream_emit_readable_now(ScrStream *s); static void scr_stream_maybe_read_more(ScrStream *s); @@ -492,7 +625,7 @@ static void scr_stream_clear_buffer(ScrStream *s); static void scr_stream_do_destroy(ScrStream *s, ScrError *err /*borrowed*/); static void scr_stream_notify_finished(ScrStream *s); static void *scr_stream_read_n(ScrStream *s, double size); -static void *scr_stream_read_n_kind(ScrStream *s, double size, bool *is_str); +static void *scr_stream_read_n_kind(ScrStream *s, double size, ScrEntryKind *kind); static void scr_stream_settle_next(ScrStream *s); static ScrStream *scr_stream_alloc(const ScrVt *vt, const char *cls, bool has_r, bool has_w, double rhwm, double whwm, bool auto_destroy, @@ -517,10 +650,10 @@ static void scr_stream_error_or_destroy(ScrStream *s, ScrError *err) { /* ── readable internals ───────────────────────────────────────────────── */ -static void scr_stream_rbuf_push(ScrStreamState *st, void *chunk /*moves*/, bool is_str, +static void scr_stream_rbuf_push(ScrStreamState *st, void *chunk /*moves*/, ScrEntryKind kind, bool front) { - if (is_str != st->r.encoded) { - /* every entry has the buffer's representation (encoded: ScrStr) */ + if (kind != scr_stream_rkind(st)) { + /* every entry has the buffer's representation (scr_stream_rkind) */ fputs("scriptc: internal error: stream buffer entry of the wrong kind\n", stderr); abort(); } @@ -543,7 +676,8 @@ static void scr_stream_rbuf_push(ScrStreamState *st, void *chunk /*moves*/, bool } /* Takes n units (n <= length; bytes, or chars once encoded) off the - * buffer head as one +1 Buffer / string. */ + * buffer head as one +1 Buffer / string. An object-mode buffer always + * takes one whole entry (n is 1). */ static void *scr_stream_rbuf_take(ScrStreamState *st, size_t n) { void *first = st->r.n > 0 ? st->r.buf[0] : NULL; if (first && st->r.head_off == 0 && scr_stream_entry_len(st, first) == n) { @@ -604,17 +738,29 @@ static void *scr_stream_rbuf_take(ScrStreamState *st, size_t n) { return out; } -/* emit('data', chunk) + pipe delivery. Borrows chunk (a Buffer, or a - * string once encoded). The emit ABI carries BOTH payload slots — the - * bytes chunk and the string chunk, exactly one non-NULL — and the - * compiler's stream-data listener thunks dispatch on which (typed - * listeners unwrap their declared side; dyn listeners box by tag). */ -static void scr_stream_emit_data(ScrStream *s, void *chunk) { +/* emit('data', chunk) + pipe delivery. Borrows chunk (a Buffer, a string + * once encoded, or a dyn value, by kind). The emit ABI carries three + * payload slots: the bytes chunk, the string chunk, and the value of a + * dyn entry. A dyn entry that is a Buffer or a string also fills that + * slot, so at most one of the first two is non-NULL; the compiler's + * stream-data listener thunks dispatch on them (typed listeners unwrap + * their declared side; dyn listeners box by tag or take the value). */ +static void scr_stream_emit_data(ScrStream *s, void *chunk, ScrEntryKind kind) { ScrStreamState *st = s->st; - ScrBytes *b = st->r.encoded ? NULL : (ScrBytes *)chunk; - ScrStr *str = st->r.encoded ? (ScrStr *)chunk : NULL; + ScrBytes *b = NULL; + ScrStr *str = NULL; + ScrDyn *value = NULL; + if (kind == SCR_ENTRY_DYN) { + value = chunk; + if (value->kind == SCR_DYN_BYTES) b = value->v.bytes; + else if (value->kind == SCR_DYN_STR) str = value->v.str; + } else if (kind == SCR_ENTRY_STR) { + str = chunk; + } else { + b = chunk; + } ScrStr *n = scr_str_new("data", 4); - scr_emitter_emit((ScrEmitter *)s, n, b, str); + scr_emitter_emit((ScrEmitter *)s, n, b, str, value); scr_str_release(n); if (scr_exc_pending()) return; /* pipe delivery, with backpressure: a full destination pauses us until @@ -631,7 +777,9 @@ static void scr_stream_emit_data(ScrStream *s, void *chunk) { if (scr_exc_pending()) return; continue; /* the pipes array shifted down over i */ } - bool ok = b ? scr_stream_write(dst, b, NULL) : scr_stream_write_str(dst, str, NULL); + bool ok = value ? scr_stream_write_dyn(dst, value, NULL) + : b ? scr_stream_write(dst, b, NULL) + : scr_stream_write_str(dst, str, NULL); if (scr_exc_pending()) return; i++; if (!ok && !dst->st->destroyed) { @@ -675,7 +823,7 @@ static void scr_stream_end_readable(ScrStream *s) { * ERR_METHOD_NOT_IMPLEMENTED, Node's contract. */ static void scr_stream_call_read(ScrStream *s) { ScrStreamState *st = s->st; - if (st->r.read_cb == NULL && st->r.object_entries) { + if (st->r.read_cb == NULL && st->r.object_entries && !st->r.object_mode_opt) { /* Readable.from: fully seeded at construction — _read is a no-op */ st->r.in_read_sync = false; return; @@ -688,8 +836,13 @@ static void scr_stream_call_read(ScrStream *s) { } if (st->r.read_cb == NULL) { /* transform reads are push-driven; the attempt still clears the - * initial sync flag (Node's Transform._read ran) */ + * initial sync flag (Node's Transform._read ran) and runs a held + * write callback */ st->r.in_read_sync = false; + if (st->xf_held) { + st->xf_held = false; + scr_stream_write_done(s, NULL); + } return; } st->r.reading = true; @@ -705,8 +858,21 @@ static void scr_stream_call_read(ScrStream *s) { * StringDecoder first (Node decodes at push); an empty decode (a partial * multi-byte tail held pending) adds nothing but still clears the * reading flag. */ +static int scr_stream_add_entry(ScrStream *s, void *entry /*moves*/, ScrEntryKind kind); +static void *scr_stream_entry_convert(ScrStreamState *st, void *entry, ScrEntryKind *kind); + static bool scr_stream_add_chunk(ScrStream *s, ScrBytes *chunk, bool front) { ScrStreamState *st = s->st; + if (st->has_r && st->r.object_entries) { + /* object mode: the Buffer is one whole entry */ + if (!front) return scr_stream_add_entry(s, scr_bytes_retain(chunk), SCR_ENTRY_BYTES) > 0; + ScrEntryKind kind = SCR_ENTRY_BYTES; + void *entry = scr_stream_entry_convert(st, scr_bytes_retain(chunk), &kind); + scr_stream_rbuf_push(st, entry, kind, true); + if (st->r.need_readable) scr_stream_emit_readable_nt(s); + scr_stream_settle_next(s); + return !st->r.ended && (st->r.length < st->r.hwm || st->r.length == 0); + } if (!st->has_r) { ScrError *e = scr_stream_mkerr("ERR_STREAM_PUSH_AFTER_EOF", "push on a Writable (no readable side)"); scr_stream_error_or_destroy(s, e); @@ -742,12 +908,12 @@ static bool scr_stream_add_chunk(ScrStream *s, ScrBytes *chunk, bool front) { (scr_emitter_has((ScrEmitter *)s, "data") || st->pipes.n > 0)) { /* the direct-emit fast path: flowing, empty buffer, async push */ if (st->r.emitted_readable) st->r.emitted_readable = false; - bool is_str = st->r.encoded; - scr_stream_emit_data(s, entry); - scr_stream_entry_release_kind(entry, is_str); + ScrEntryKind kind = scr_stream_rkind(st); + scr_stream_emit_data(s, entry, kind); + scr_stream_entry_release_kind(entry, kind); if (scr_exc_pending()) return false; } else { - scr_stream_rbuf_push(st, entry, st->r.encoded, front); + scr_stream_rbuf_push(st, entry, scr_stream_rkind(st), front); if (st->r.need_readable) scr_stream_emit_readable_nt(s); } if (!front) scr_stream_maybe_read_more(s); @@ -770,8 +936,8 @@ static void scr_stream_maybe_read_more(ScrStream *s) { * Answers a +1 Buffer — or a +1 string once encoded (lengths and the * size argument then count JS string units, Node's encoded accounting). */ static void *scr_stream_read_n(ScrStream *s, double size) { - bool is_str; - return scr_stream_read_n_kind(s, size, &is_str); + ScrEntryKind kind; + return scr_stream_read_n_kind(s, size, &kind); } /* read_n, also answering the chunk's kind as it was taken from the buffer @@ -779,9 +945,9 @@ static void *scr_stream_read_n(ScrStream *s, double size) { * inside the read can change the representation, and a 'data' listener * can call setEncoding() before this returns, so callers that need the * kind read it here rather than from st->r.encoded afterwards. */ -static void *scr_stream_read_n_kind(ScrStream *s, double size, bool *is_str) { +static void *scr_stream_read_n_kind(ScrStream *s, double size, ScrEntryKind *kind) { ScrStreamState *st = s->st; - *is_str = false; + *kind = scr_stream_rkind(st); bool absent = size < 0; size_t n = 0; if (!absent) { @@ -841,7 +1007,7 @@ static void *scr_stream_read_n_kind(ScrStream *s, double size, bool *is_str) { } } } - *is_str = st->r.encoded; + *kind = scr_stream_rkind(st); void *ret = want > 0 && want <= st->r.length ? scr_stream_rbuf_take(st, want) : NULL; if (ret == NULL) { st->r.need_readable = st->r.length <= st->r.hwm; @@ -854,9 +1020,9 @@ static void *scr_stream_read_n_kind(ScrStream *s, double size, bool *is_str) { if (st->r.ended && absent) scr_stream_end_readable(s); } if (ret != NULL && !st->error_emitted && !st->close_emitted) { - scr_stream_emit_data(s, ret); + scr_stream_emit_data(s, ret, *kind); if (scr_exc_pending()) { - scr_stream_entry_release_kind(ret, *is_str); + scr_stream_entry_release_kind(ret, *kind); return NULL; } } @@ -866,10 +1032,10 @@ static void *scr_stream_read_n_kind(ScrStream *s, double size, bool *is_str) { static void scr_stream_flow(ScrStream *s) { ScrStreamState *st = s->st; while (st->r.flowing == 1 && !scr_exc_pending()) { - bool is_str; - void *b = scr_stream_read_n_kind(s, -1, &is_str); + ScrEntryKind kind; + void *b = scr_stream_read_n_kind(s, -1, &kind); if (b == NULL) break; - scr_stream_entry_release_kind(b, is_str); + scr_stream_entry_release_kind(b, kind); } } @@ -893,23 +1059,10 @@ static void scr_stream_resume_kick(ScrStream *s) { static ScrError *scr_stream_dyn_err(ScrDyn *const *args, size_t argc) { if (argc < 1) return NULL; const ScrDyn *a = args[0]; - if (a->kind == SCR_DYN_UNDEF || a->kind == SCR_DYN_NULL) return NULL; - if (a->kind == SCR_DYN_STR) { - ScrError *e = scr_error_new(SCR_ERR_ERROR, a->v.str); - return e; - } - if (a->kind == SCR_DYN_OBJ) { - ScrDyn *m = scr_dyn_obj_get((ScrDyn *)a, "message", 7); - ScrStr *msg = m && m->kind == SCR_DYN_STR ? scr_str_retain(m->v.str) : scr_str_new("", 0); - ScrError *e = scr_error_new(SCR_ERR_ERROR, msg); - scr_str_release(msg); - return e; - } - /* any other truthy value: Node would wrap it — approximate with "" */ - ScrStr *empty = scr_str_new("", 0); - ScrError *e = scr_error_new(SCR_ERR_ERROR, empty); - scr_str_release(empty); - return e; + if (!scr_dyn_truthy(a)) return NULL; + if (a->kind == SCR_DYN_STR) return scr_error_new(SCR_ERR_ERROR, a->v.str); + /* the error value itself (the same object reaches 'error') */ + return scr_error_from_dyn(a); } static ScrStream *scr_stream_dyn_recv(ScrClosure *clo) { @@ -932,6 +1085,13 @@ ScrDyn *scr_stream_done_dyn_f(ScrClosure *clo, ScrDyn *const *args, size_t argc) return scr_stream_done_dyn_ret(); } +ScrDyn *scr_stream_done_dyn_c(ScrClosure *clo, ScrDyn *const *args, size_t argc) { + ScrStream *s = scr_stream_dyn_recv(clo); + scr_stream_construct_done(s, scr_stream_dyn_err(args, argc)); + scr_stream_release(s); + return scr_stream_done_dyn_ret(); +} + ScrDyn *scr_stream_done_dyn_d(ScrClosure *clo, ScrDyn *const *args, size_t argc) { ScrStream *s = scr_stream_dyn_recv(clo); scr_stream_destroy_done(s, scr_stream_dyn_err(args, argc)); @@ -939,47 +1099,37 @@ ScrDyn *scr_stream_done_dyn_d(ScrClosure *clo, ScrDyn *const *args, size_t argc) return scr_stream_done_dyn_ret(); } -static void scr_stream_dyn_data(ScrDyn *const *args, size_t argc, - ScrBytes **data, ScrStr **data_str) { - *data = NULL; - *data_str = NULL; - if (argc < 2) return; - const ScrDyn *a = args[1]; - if (a->kind == SCR_DYN_BYTES) *data = scr_bytes_raw_view(a->v.bytes); - else if (a->kind == SCR_DYN_STR) *data_str = scr_str_retain(a->v.str); -} - +/* callback(err, data) of an untyped transform or flush: data is pushed + * as push(data) pushes it. */ ScrDyn *scr_stream_done_dyn_t(ScrClosure *clo, ScrDyn *const *args, size_t argc) { ScrStream *s = scr_stream_dyn_recv(clo); - ScrBytes *data; - ScrStr *data_str; - scr_stream_dyn_data(args, argc, &data, &data_str); - scr_stream_transform_done(s, scr_stream_dyn_err(args, argc), data, data_str); + scr_stream_transform_done_value(s, scr_stream_dyn_err(args, argc), argc > 1 ? args[1] : NULL); scr_stream_release(s); return scr_stream_done_dyn_ret(); } ScrDyn *scr_stream_done_dyn_l(ScrClosure *clo, ScrDyn *const *args, size_t argc) { ScrStream *s = scr_stream_dyn_recv(clo); - ScrBytes *data; - ScrStr *data_str; - scr_stream_dyn_data(args, argc, &data, &data_str); - scr_stream_flush_done(s, scr_stream_dyn_err(args, argc), data, data_str); + scr_stream_flush_done_value(s, scr_stream_dyn_err(args, argc), argc > 1 ? args[1] : NULL); scr_stream_release(s); return scr_stream_done_dyn_ret(); } /* Checked-dynamic chunks (the JS lane's push/write of any-typed values): * dispatch by dyn tag — bytes copy out, strings convert utf8, null takes - * the null path (EOF for push; ERR_STREAM_NULL_VALUES for write). Any - * other write throws Node's ERR_INVALID_ARG_TYPE; any other push throws - * the null-values TypeError (Node reports ERR_INVALID_ARG_TYPE through - * 'error'). Borrow d. */ + * the null path (EOF for push; ERR_STREAM_NULL_VALUES for write). On an + * object-mode side every other value is one entry. Otherwise any other + * write throws Node's ERR_INVALID_ARG_TYPE, push(undefined) adds nothing, + * and any other push reports ERR_INVALID_ARG_TYPE through 'error', as + * readableAddChunkPushByteMode does. Borrow d. */ bool scr_stream_push_dyn(ScrStream *s, const ScrDyn *d) { + ScrStreamState *st = s->st; + if (d->kind != SCR_DYN_NULL && st->has_r && st->r.object_entries) + return scr_stream_push_object(s, d) > 0; switch (d->kind) { case SCR_DYN_BYTES: { ScrBytes *b = scr_bytes_raw_view(d->v.bytes); - bool r = scr_stream_push(s, b); + bool r = scr_stream_push_view(s, b); scr_bytes_release(b); return r; } @@ -987,15 +1137,26 @@ bool scr_stream_push_dyn(ScrStream *s, const ScrDyn *d) { return scr_stream_push_str(s, d->v.str); case SCR_DYN_NULL: return scr_stream_push_null(s); + case SCR_DYN_UNDEF: + if (!st->has_r) return false; + st->r.reading = false; + scr_stream_maybe_read_more(s); + return !st->r.ended && (st->r.length < st->r.hwm || st->r.length == 0); default: { - static const char msg[] = "May not write null values to stream"; - scr_throw_error_msg_code(SCR_ERR_TYPE, msg, sizeof msg - 1, "ERR_STREAM_NULL_VALUES"); + scr_dyn_arg_type_fail("chunk", "of type string or an instance of Buffer, TypedArray, or DataView", d); + ScrError *e = scr_stream_take_error(); + scr_stream_error_or_destroy(s, e); + scr_error_release(e); return false; } } } +static bool scr_stream_write_value(ScrStream *s, ScrDyn *v, ScrClosure *cb); + bool scr_stream_write_dyn(ScrStream *s, const ScrDyn *d, ScrClosure *cb) { + if (d->kind != SCR_DYN_NULL && s->st->has_w && s->st->w.object_mode) + return scr_stream_write_value(s, (ScrDyn *)d, cb); switch (d->kind) { case SCR_DYN_BYTES: { ScrBytes *b = scr_bytes_raw_view(d->v.bytes); @@ -1040,32 +1201,44 @@ static void scr_stream_next_str_fence(void) { scr_throw_error_msg(SCR_ERR_ERROR, msg, sizeof msg - 1); } -/* Fulfills the parked iterator with a chunk taken from the buffer; is_str - * is its kind as taken. The typed lane's chunk is a Buffer, so a string - * chunk rejects with the encoding fence instead. */ +/* Fulfills the parked iterator with a chunk taken from the buffer; kind + * is its kind as taken. The typed lane's chunk is a Buffer, so another + * chunk rejects with the encoding fence instead. The dyn lane's end is + * the done marker (scr_stream_from_done): an object-mode stream can + * yield undefined. */ static void scr_stream_next_fulfill(ScrStreamState *st, ScrPromise *w /*moves*/, - void *chunk /*moves or NULL=EOF*/, bool is_str) { + void *chunk /*moves or NULL=EOF*/, ScrEntryKind kind) { void *payload; bool dyn = st->r.next_dyn; - if (!dyn && chunk != NULL && is_str) { + if (!dyn && chunk != NULL && kind == SCR_ENTRY_DYN) { + ScrDyn *d = chunk; + if (d->kind == SCR_DYN_BYTES) { + chunk = scr_bytes_raw_view(d->v.bytes); + kind = SCR_ENTRY_BYTES; + scr_dyn_release(d); + } else { + chunk = scr_dyn_string_coerce_js(d); + kind = SCR_ENTRY_STR; + scr_dyn_release(d); + } + } + if (!dyn && chunk != NULL && kind == SCR_ENTRY_STR) { scr_str_release((ScrStr *)chunk); scr_stream_next_str_fence(); scr_promise_reject_pending(w); scr_promise_release(w); return; } - if (dyn) { - ScrDyn *d; - if (chunk == NULL) { - d = scr_dyn_retain(scr_dyn_undefined()); /* the EOF sentinel */ - } else if (is_str) { - d = scr_dyn_new_str((ScrStr *)chunk); - scr_str_release((ScrStr *)chunk); - } else { - d = scr_dyn_new_buffer((ScrBytes *)chunk); - scr_bytes_release((ScrBytes *)chunk); - } - payload = d; + if (dyn && st->r.next_result) { + /* { value, done }: the value, or undefined at the end */ + ScrDyn *result = scr_dyn_new_obj(); + scr_dyn_obj_set(result, "value", 5, + chunk == NULL ? scr_dyn_retain(scr_dyn_undefined()) + : scr_stream_entry_box(chunk, kind)); + scr_dyn_obj_set(result, "done", 4, scr_dyn_new_bool(chunk == NULL)); + payload = result; + } else if (dyn) { + payload = chunk == NULL ? scr_stream_from_done() : scr_stream_entry_box(chunk, kind); } else { payload = chunk ? (ScrBytes *)chunk : scr_bytes_new(SCR_BYTES_U8, 0); } @@ -1097,11 +1270,11 @@ static void scr_stream_iter_step(ScrStream *s) { if (!st->r.next_waiter) return; if (!st->destroyed && !st->errored) { st->r.next_reading = true; - bool is_str; - void *chunk = scr_stream_read_n_kind(s, -1, &is_str); + ScrEntryKind kind; + void *chunk = scr_stream_read_n_kind(s, -1, &kind); st->r.next_reading = false; if (scr_exc_pending()) { - if (chunk) scr_stream_entry_release_kind(chunk, is_str); + if (chunk) scr_stream_entry_release_kind(chunk, kind); ScrPromise *w = st->r.next_waiter; st->r.next_waiter = NULL; if (w) { @@ -1113,7 +1286,7 @@ static void scr_stream_iter_step(ScrStream *s) { if (chunk) { ScrPromise *w = st->r.next_waiter; st->r.next_waiter = NULL; - scr_stream_next_fulfill(st, w, chunk, is_str); + scr_stream_next_fulfill(st, w, chunk, kind); return; } } @@ -1164,13 +1337,18 @@ static void scr_stream_settle_next(ScrStream *s) { } ScrPromise *w = st->r.next_waiter; st->r.next_waiter = NULL; - bool is_str = st->r.encoded; + ScrEntryKind kind = scr_stream_rkind(st); void *chunk = scr_stream_rbuf_take(st, st->r.object_entries ? 1 : st->r.length); - scr_stream_next_fulfill(st, w, chunk, is_str); + scr_stream_next_fulfill(st, w, chunk, kind); if (st->r.ended && st->r.length == 0) scr_stream_end_readable(s); return; } if (st->r.ended || st->destroyed) { + if (st->r.ended && st->r.next_close_wait && !st->close_emitted) { + if (!st->r.end_emitted) scr_stream_end_readable(s); + st->r.next_eof_close = true; + return; + } if (st->r.ended && !st->r.end_emitted) { /* Node's iterator completes AFTER 'end' (and its autoDestroy): * queue the sentinel BEHIND the pending 'end' tick, so code after @@ -1181,16 +1359,17 @@ static void scr_stream_settle_next(ScrStream *s) { } ScrPromise *w = st->r.next_waiter; st->r.next_waiter = NULL; - scr_stream_next_fulfill(st, w, NULL, false); + scr_stream_next_fulfill(st, w, NULL, SCR_ENTRY_BYTES); } } -static ScrPromise *scr_stream_next_chunk_impl(ScrStream *s, bool dyn) { +static ScrPromise *scr_stream_next_chunk_impl(ScrStream *s, bool dyn, bool result) { ScrStreamState *st = s->st; ScrPromise *p = scr_promise_new(); if (!st->has_r) { st->r.next_dyn = dyn; - scr_stream_next_fulfill(st, scr_promise_retain(p), NULL, false); + st->r.next_result = result; + scr_stream_next_fulfill(st, scr_promise_retain(p), NULL, SCR_ENTRY_BYTES); return p; } if (st->r.next_waiter) { @@ -1201,8 +1380,14 @@ static ScrPromise *scr_stream_next_chunk_impl(ScrStream *s, bool dyn) { return p; } st->r.next_dyn = dyn; + st->r.next_result = result; st->r.next_waiter = scr_promise_retain(p); st->r.next_parked = false; + if (!st->r.next_started) { + st->r.next_started = true; + st->r.next_close_wait = + !st->has_w && st->auto_destroy && st->emit_close && !st->close_scheduled && !st->close_emitted; + } /* createAsyncIterator starts with stream.on('readable', next) */ scr_stream_readable_listen(s); scr_stream_iter_step(s); @@ -1219,11 +1404,15 @@ ScrPromise *scr_stream_next_chunk(ScrStream *s) { scr_promise_reject_pending(p); return p; } - return scr_stream_next_chunk_impl(s, false); + return scr_stream_next_chunk_impl(s, false, false); } ScrPromise *scr_stream_next_chunk_dyn(ScrStream *s) { - return scr_stream_next_chunk_impl(s, true); + return scr_stream_next_chunk_impl(s, true, false); +} + +ScrPromise *scr_stream_next_result_dyn(ScrStream *s) { + return scr_stream_next_chunk_impl(s, true, true); } /* ── Readable.from (array, string and Buffer sources) ─────────────────── */ @@ -1257,25 +1446,11 @@ static void scr_from_src_release(ScrFromSrc *f) { static void *scr_from_src_retain_v(void *f) { return scr_from_src_retain(f); } static void scr_from_src_release_v(void *f) { scr_from_src_release(f); } -/* A Readable.from source whose values no longer fit the buffer's kind - * (strings beside Buffers): destroyed with the "not supported yet" Error. */ -static void scr_from_destroy_mixed(ScrStream *s) { - static const char m[] = "a Readable.from source that mixes strings and Buffers is not supported yet"; - ScrStr *msg = scr_str_new(m, sizeof m - 1); - ScrError *e = scr_error_new(SCR_ERR_ERROR, msg); - scr_str_release(msg); - scr_stream_release(scr_stream_destroy(s, e)); - scr_error_release(e); -} - /* One typed element into the stream: a whole entry in object mode, a * chunk in byte mode. Moves e. Returns push's answer. */ static bool scr_from_push_typed(ScrStream *s, void *e, bool strings) { - if (s->st->r.object_entries) { - int pushed = scr_stream_add_entry(s, e, strings); - if (pushed < 0) scr_from_destroy_mixed(s); - return pushed > 0; - } + if (s->st->r.object_entries) + return scr_stream_add_entry(s, e, strings ? SCR_ENTRY_STR : SCR_ENTRY_BYTES) > 0; bool more = strings ? scr_stream_push_str(s, e) : scr_stream_push(s, e); if (strings) scr_str_release(e); else scr_bytes_release(e); @@ -1376,8 +1551,21 @@ static bool scr_from_check_hwm(double hwm) { * highWaterMark 1 for iterables, the mode's default for the string / * Buffer case or a nullish option, or the option's value. +1, or NULL with the error * pending. Moves f. */ +/* from.js's `new Readable(...)`: a Readable, or for Duplex.from (duplexify.js's + * from(Duplexify, body, { objectMode: true, writable: false })) a Duplexify + * whose writable side is off. */ +static ScrStream *scr_from_new(bool duplex, double hwm, ScrClosure *read, ScrStreamReadInv read_inv, + ScrClosure *destroy, ScrStreamErrInv destroy_inv) { + if (!duplex) return scr_stream_new_readable(hwm, true, true, read, read_inv, destroy, destroy_inv); + ScrStream *d = scr_stream_new_duplex(hwm, hwm, true, true, true, true, false, read, read_inv, NULL, + NULL, NULL, NULL, destroy, destroy_inv); + scr_stream_set_object_mode(d, false, true); + d->cls = "Duplexify"; + return d; +} + static ScrStream *scr_from_stream(ScrFromSrc *f, ScrStreamReadInv read_inv, bool object_mode, - int hwm_kind, double hwm, bool strings) { + int hwm_kind, double hwm, bool strings, bool duplex) { if (hwm_kind == SCR_FROM_HWM_SET && !scr_from_check_hwm(hwm)) { scr_from_src_release(f); return NULL; @@ -1389,8 +1577,8 @@ static ScrStream *scr_from_stream(ScrFromSrc *f, ScrStreamReadInv read_inv, bool scr_box_set_ref(read->caps[0], f); /* moves */ ScrClosure *destroy = NULL; if (!f->single) destroy = scr_closure_new((void *)&scr_from_destroy_inv, 0); - ScrStream *s = scr_stream_new_readable(hwm, true, true, read, read_inv, destroy, - destroy ? &scr_from_destroy_inv : NULL); + ScrStream *s = scr_from_new(duplex, hwm, read, read_inv, destroy, + destroy ? &scr_from_destroy_inv : NULL); ScrStreamState *st = s->st; if (object_mode) { st->r.object_entries = true; @@ -1417,7 +1605,7 @@ ScrStream *scr_stream_new_from_readable(ScrClosure *read, ScrStreamReadInv read_ bool object_mode = (bits & SCR_FROM_BYTE_MODE) == 0; if (bits & SCR_FROM_DEFAULT_HWM) hwm = object_mode ? 16 : -1; else if (!(bits & SCR_FROM_HAS_HWM)) hwm = 1; - ScrStream *s = scr_stream_new_readable(hwm, true, true, read, read_inv, destroy, destroy_inv); + ScrStream *s = scr_from_new((bits & SCR_FROM_DUPLEX) != 0, hwm, read, read_inv, destroy, destroy_inv); if (object_mode) s->st->r.object_entries = true; return s; } @@ -1432,14 +1620,14 @@ ScrStream *scr_stream_from_arr(ScrArr *arr, double flags, double hwm) { f->single = (bits & SCR_FROM_SINGLE) != 0; return scr_from_stream(f, &scr_from_read_inv, (bits & SCR_FROM_BYTE_MODE) == 0, (bits & SCR_FROM_HAS_HWM) ? SCR_FROM_HWM_SET : SCR_FROM_HWM_FROM, hwm, - f->strings); + f->strings, (bits & SCR_FROM_DUPLEX) != 0); } /* The JS lane: one checked-dynamic value into the stream. null is - * ERR_STREAM_NULL_VALUES; in object mode, values other than strings and - * Buffers (or a mix of the two) are outside the stream model; byte mode - * rejects them with push()'s ERR_INVALID_ARG_TYPE. Each failure destroys - * the stream and answers -1. Borrows v. */ + * ERR_STREAM_NULL_VALUES; in object mode every other value is an entry; + * byte mode rejects values other than strings and Buffers with push()'s + * ERR_INVALID_ARG_TYPE. Each failure destroys the stream and answers -1. + * Borrows v. */ int scr_stream_from_push(ScrStream *s, const ScrDyn *v) { ScrError *e = NULL; if (v->kind == SCR_DYN_NULL) { @@ -1449,14 +1637,7 @@ int scr_stream_from_push(ScrStream *s, const ScrDyn *v) { scr_str_release(msg); scr_error_set_code(e, "ERR_STREAM_NULL_VALUES"); } else if (s->st->r.object_entries) { - int pushed = scr_stream_push_object(s, v); - if (pushed >= 0) return pushed; - static const char mixed[] = "a Readable.from source that mixes strings and Buffers is not supported yet"; - static const char other[] = "Readable.from over values other than strings and Buffers is not supported yet"; - const char *m = pushed == -2 ? mixed : other; - ScrStr *msg = scr_str_new(m, strlen(m)); - e = scr_error_new(SCR_ERR_ERROR, msg); - scr_str_release(msg); + return scr_stream_push_object(s, v); } else if (v->kind == SCR_DYN_STR || v->kind == SCR_DYN_BYTES) { return scr_stream_push_dyn(s, v) ? 1 : 0; } else { @@ -1503,7 +1684,7 @@ static void scr_from_read_dyn_inv(ScrClosure *cb, ScrStream *s, double size) { scr_from_src_release(f); } -ScrStream *scr_stream_from_dyn(ScrDyn *src, ScrDyn *opts) { +static ScrStream *scr_from_dyn_ex(ScrDyn *src, ScrDyn *opts, bool duplex) { bool single = src->kind == SCR_DYN_STR || src->kind == SCR_DYN_BYTES; ScrDyn *iter = NULL; /* from.js's iterator, for sources other than arrays */ int kind = 0; @@ -1515,7 +1696,14 @@ ScrStream *scr_stream_from_dyn(ScrDyn *src, ScrDyn *opts) { if (kind < 0) return NULL; } if (!single && kind == 0) { - scr_dyn_arg_type_fail("iterable", "an instance of Iterable", src); + if (duplex) { + scr_dyn_arg_type_fail("body", + "of type function or an instance of Blob, ReadableStream, WritableStream, " + "Stream, Iterable, AsyncIterable, or Promise or { readable, writable } pair", + src); + } else { + scr_dyn_arg_type_fail("iterable", "an instance of Iterable", src); + } return NULL; } bool object_mode = true; @@ -1562,7 +1750,7 @@ ScrStream *scr_stream_from_dyn(ScrDyn *src, ScrDyn *opts) { } } if (iter) { - double flags = (object_mode ? 0 : SCR_FROM_BYTE_MODE) | + double flags = (object_mode ? 0 : SCR_FROM_BYTE_MODE) | (duplex ? SCR_FROM_DUPLEX : 0) | (hwm_kind == SCR_FROM_HWM_SET ? SCR_FROM_HAS_HWM : hwm_kind == SCR_FROM_HWM_DEFAULT ? SCR_FROM_DEFAULT_HWM : 0); @@ -1573,7 +1761,47 @@ ScrStream *scr_stream_from_dyn(ScrDyn *src, ScrDyn *opts) { f->rc = 1; f->dyn = scr_dyn_retain(src); f->single = single; - return scr_from_stream(f, &scr_from_read_dyn_inv, object_mode, hwm_kind, hwm, false); + return scr_from_stream(f, &scr_from_read_dyn_inv, object_mode, hwm_kind, hwm, false, duplex); +} + +ScrStream *scr_stream_from_dyn(ScrDyn *src, ScrDyn *opts) { + return scr_from_dyn_ex(src, opts, false); +} + +/* Duplex.from(body) over a checked-dynamic body (duplexify.js): a native + * Duplex answers itself, a lone native Readable or Writable is wrapped, a + * promise reads as its value, an iterable reads as Duplex.from does, and + * the other bodies Node accepts (a function, a thenable, a { readable, + * writable } pair) are not supported yet. */ +static ScrStream *scr_stream_boxed(const ScrDyn *value); +static ScrStream *scr_dupx_from_boxed(ScrDyn *boxed); + +ScrStream *scr_stream_duplex_from_dyn(ScrDyn *body) { + ScrStream *native = scr_stream_of_handle(body); /* +1 */ + if (!native) native = scr_stream_boxed(body); /* +1 */ + if (native) { + if (native->st->has_r && native->st->has_w) return native; + /* _duplexify({ readable }) / _duplexify({ writable }) */ + ScrStream *d = native->st->has_r ? scr_stream_duplexify(native, NULL) + : scr_stream_duplexify(NULL, native); + scr_stream_release(native); + return d; + } + if (body->kind == SCR_DYN_PROMISE) return scr_dupx_from_boxed(scr_dyn_retain(body)); + bool unsupported = body->kind == SCR_DYN_FUNC; + if (!unsupported && body->kind == SCR_DYN_OBJ) { + static const char *const keys[] = {"then", "readable", "writable"}; + for (size_t i = 0; i < 3 && !unsupported; i++) { + ScrDyn *v = scr_dyn_obj_get(body, keys[i], strlen(keys[i])); + unsupported = v != NULL && v->kind != SCR_DYN_UNDEF; + } + } + if (unsupported) { + static const char msg[] = "Duplex.from over this body is not supported yet"; + scr_throw_error_msg_code(SCR_ERR_ERROR, msg, sizeof msg - 1, "SC2020"); + return NULL; + } + return scr_from_dyn_ex(body, NULL, true); } /* ── object-mode streams for the stream operators (scr_stream_ops.c) ──── */ @@ -1587,61 +1815,72 @@ ScrStream *scr_stream_new_object_readable(ScrClosure *read, ScrStreamReadInv rea return s; } -/* An object-mode entry in the buffer's representation: a Buffer on a - * stream with a decoder decodes through it (Node's decoder.write in - * readableAddChunkPushObjectMode); an entry of the other kind otherwise - * mixes strings and Buffers, which the buffer cannot hold. Moves entry; - * +1, or NULL (entry released). */ -static void *scr_stream_entry_convert(ScrStreamState *st, void *entry, bool is_str) { - if (is_str == st->r.encoded) return entry; - if (!is_str && st->r.decoding) { +/* The object-mode buffer starts holding dyn values: every buffered entry + * is boxed. */ +static void scr_stream_rbuf_to_dyn(ScrStreamState *st) { + ScrEntryKind kind = scr_stream_rkind(st); + for (size_t i = 0; i < st->r.n; i++) st->r.buf[i] = scr_stream_entry_box(st->r.buf[i], kind); + st->r.dyn_entries = true; + st->r.object_kind_set = true; +} + +/* An object-mode entry in the buffer's representation (moves entry; +1). + * A Buffer on a stream with a decoder decodes through it (Node's + * decoder.write in readableAddChunkPushObjectMode); an entry of another + * kind turns the buffer into dyn entries. */ +static void *scr_stream_entry_convert(ScrStreamState *st, void *entry, ScrEntryKind *kind) { + ScrEntryKind want = scr_stream_rkind(st); + if (*kind == want) return entry; + if (*kind == SCR_ENTRY_BYTES && want == SCR_ENTRY_STR && st->r.decoding) { ScrBytes *b = entry; ScrStr *dec = scr_strdec_write(st->r.enc, st->r.dec_pending, b); st->r.dec_pending = scr_strdec_next(st->r.enc, st->r.dec_pending, b); scr_bytes_release(b); + *kind = SCR_ENTRY_STR; return dec; } - if (is_str) scr_str_release(entry); - else scr_bytes_release(entry); - return NULL; + if (want != SCR_ENTRY_DYN) scr_stream_rbuf_to_dyn(st); + ScrDyn *d = scr_stream_entry_box(entry, *kind); + *kind = SCR_ENTRY_DYN; + return d; } /* readableAddChunk in object mode: every value is one whole entry, empty - * strings and Buffers included. is_str gives entry's kind. Answers push()'s - * result, or -2 (entry released) when the kinds cannot mix. */ -static int scr_stream_add_entry(ScrStream *s, void *entry /*moves*/, bool is_str) { + * strings and Buffers included. kind gives entry's kind. Answers push()'s + * result. */ +static int scr_stream_add_entry(ScrStream *s, void *entry /*moves*/, ScrEntryKind kind) { ScrStreamState *st = s->st; if (!st->r.object_kind_set && st->r.length == 0) { /* the first entry picks the representation */ st->r.object_kind_set = true; - if (is_str && !st->r.encoded) { + if (kind == SCR_ENTRY_STR && !st->r.encoded) { st->r.encoded = true; if (!st->r.enc) st->r.enc = scr_str_new("utf8", 4); + } else if (kind == SCR_ENTRY_DYN) { + st->r.dyn_entries = true; } } - entry = scr_stream_entry_convert(st, entry, is_str); - if (entry == NULL) return -2; + entry = scr_stream_entry_convert(st, entry, &kind); if (st->r.ended) { - scr_stream_entry_release(st, entry); + scr_stream_entry_release_kind(entry, kind); ScrError *e = scr_stream_mkerr("ERR_STREAM_PUSH_AFTER_EOF", "stream.push() after EOF"); scr_stream_error_or_destroy(s, e); scr_error_release(e); return 0; } if (st->destroyed || st->errored) { - scr_stream_entry_release(st, entry); + scr_stream_entry_release_kind(entry, kind); return 0; } st->r.reading = false; if (st->r.flowing == 1 && st->r.length == 0 && !st->r.in_read_sync && (scr_emitter_has((ScrEmitter *)s, "data") || st->pipes.n > 0)) { if (st->r.emitted_readable) st->r.emitted_readable = false; - bool is_str = st->r.encoded; - scr_stream_emit_data(s, entry); - scr_stream_entry_release_kind(entry, is_str); + scr_stream_emit_data(s, entry, kind); + scr_stream_entry_release_kind(entry, kind); if (scr_exc_pending()) return 0; } else { - scr_stream_rbuf_push(st, entry, st->r.encoded, false); + scr_stream_rbuf_push(st, entry, kind, false); if (st->r.need_readable) scr_stream_emit_readable_nt(s); } scr_stream_maybe_read_more(s); @@ -1649,12 +1888,22 @@ static int scr_stream_add_entry(ScrStream *s, void *entry /*moves*/, bool is_str return !st->r.ended && (st->r.length < st->r.hwm || st->r.length == 0); } +/* push(value) on an object-mode stream: a string or a Buffer keeps its + * kind, any other value is a dyn entry. Borrows v. */ int scr_stream_push_object(ScrStream *s, const ScrDyn *v) { - bool is_str = v->kind == SCR_DYN_STR; - if (!is_str && v->kind != SCR_DYN_BYTES) return -1; - void *entry = is_str ? (void *)scr_str_retain(v->v.str) : (void *)scr_bytes_raw_view(v->v.bytes); - int pushed = scr_stream_add_entry(s, entry, is_str); - return pushed < 0 ? pushed : pushed ? 1 : 0; + void *entry; + ScrEntryKind kind; + if (v->kind == SCR_DYN_STR) { + entry = scr_str_retain(v->v.str); + kind = SCR_ENTRY_STR; + } else if (v->kind == SCR_DYN_BYTES) { + entry = scr_bytes_raw_view(v->v.bytes); + kind = SCR_ENTRY_BYTES; + } else { + entry = scr_dyn_retain((ScrDyn *)v); + kind = SCR_ENTRY_DYN; + } + return scr_stream_add_entry(s, entry, kind) ? 1 : 0; } /* ── the registration hook ('data'/'readable' listeners kick flow) ────── */ @@ -1695,7 +1944,8 @@ static void scr_stream_on_listener(ScrEmitter *em, ScrStr *name) { /* ── writable internals ───────────────────────────────────────────────── */ -static void scr_stream_wq_push(ScrStreamState *st, ScrBytes *chunk /*moves*/, ScrClosure *cb /*moves*/) { +static void scr_stream_wq_push(ScrStreamState *st, ScrBytes *chunk /*moves*/, ScrClosure *cb /*moves*/, + ScrDyn *enc /*moves*/) { if (st->w.n == st->w.cap) { st->w.cap = st->w.cap ? st->w.cap * 2 : 4; st->w.q = realloc(st->w.q, st->w.cap * sizeof *st->w.q); @@ -1703,26 +1953,51 @@ static void scr_stream_wq_push(ScrStreamState *st, ScrBytes *chunk /*moves*/, Sc } st->w.q[st->w.n].chunk = chunk; st->w.q[st->w.n].cb = cb; + st->w.q[st->w.n].enc = enc; st->w.n++; } -static void scr_stream_do_write(ScrStream *s, ScrBytes *chunk /*moves*/, ScrClosure *cb /*moves*/) { +static void scr_stream_transform_callback(ScrStream *s); + +static void scr_stream_do_write_inner(ScrStream *s, ScrBytes *chunk /*moves*/, ScrClosure *cb /*moves*/); +static ScrDyn *scr_stream_wentry_value(const ScrStreamState *st, ScrBytes *chunk); +static ScrDyn *scr_stream_wentry_encoding(const ScrStreamState *st, ScrDyn *enc); + +/* One write reaching _write/_transform; the callback reads the write's + * encoding argument through w.cur_enc while it runs. */ +static void scr_stream_do_write(ScrStream *s, ScrBytes *chunk /*moves*/, ScrClosure *cb /*moves*/, + ScrDyn *enc /*moves*/) { + ScrStreamState *st = s->st; + if (enc == NULL) { + scr_stream_do_write_inner(s, chunk, cb); + return; + } + ScrDyn *outer = st->w.cur_enc; + st->w.cur_enc = enc; + scr_stream_do_write_inner(s, chunk, cb); + st->w.cur_enc = outer; + scr_dyn_release(enc); +} + +static void scr_stream_do_write_inner(ScrStream *s, ScrBytes *chunk /*moves*/, ScrClosure *cb /*moves*/) { ScrStreamState *st = s->st; st->w.writing = true; st->w.wsync = true; - st->w.inflight_len = chunk->len; + st->w.inflight_len = scr_stream_wchunk_len(st, chunk); st->w.inflight_cb = cb; + if (st->is_transform || st->passthrough) st->xf_length = st->r.length; if (st->passthrough && st->transform_cb == NULL) { /* identity: push through, complete synchronously */ - scr_stream_add_chunk(s, chunk, false); - scr_bytes_release(chunk); - if (!scr_exc_pending()) scr_stream_write_done(s, NULL); + if (st->w.values) scr_stream_push_dyn(s, (ScrDyn *)chunk); + else scr_stream_add_chunk(s, chunk, false); + scr_stream_wchunk_release(st, chunk); + if (!scr_exc_pending()) scr_stream_transform_callback(s); st->w.wsync = false; return; } if (st->is_transform || st->passthrough) { if (st->transform_cb == NULL) { - scr_bytes_release(chunk); + scr_stream_wchunk_release(st, chunk); ScrError *e = scr_stream_mkerr("ERR_METHOD_NOT_IMPLEMENTED", "The _transform() method is not implemented"); st->w.wsync = false; scr_stream_error_or_destroy(s, e); @@ -1730,12 +2005,25 @@ static void scr_stream_do_write(ScrStream *s, ScrBytes *chunk /*moves*/, ScrClos return; } st->transform_inv(st->transform_cb, s, chunk); - scr_bytes_release(chunk); + scr_stream_wchunk_release(st, chunk); + st->w.wsync = false; + return; + } + if (st->w.write_cb == NULL && st->w.writev_cb) { + /* Writable.prototype._write: this._writev([{ chunk, encoding }], cb) */ + ScrDyn *chunks = scr_dyn_new_arr(); + ScrDyn *entry = scr_dyn_new_obj(); + scr_dyn_obj_set(entry, "chunk", 5, scr_stream_wentry_value(st, chunk)); + scr_dyn_obj_set(entry, "encoding", 8, scr_stream_wentry_encoding(st, st->w.cur_enc)); + scr_dyn_arr_push(chunks, entry); + scr_stream_wchunk_release(st, chunk); + st->w.writev_inv(st->w.writev_cb, s, chunks); + scr_dyn_release(chunks); st->w.wsync = false; return; } if (st->w.write_cb == NULL) { - scr_bytes_release(chunk); + scr_stream_wchunk_release(st, chunk); ScrError *e = scr_stream_mkerr("ERR_METHOD_NOT_IMPLEMENTED", "The _write() method is not implemented"); st->w.wsync = false; scr_stream_error_or_destroy(s, e); @@ -1743,7 +2031,7 @@ static void scr_stream_do_write(ScrStream *s, ScrBytes *chunk /*moves*/, ScrClos return; } st->w.write_inv(st->w.write_cb, s, chunk); - scr_bytes_release(chunk); + scr_stream_wchunk_release(st, chunk); st->w.wsync = false; } @@ -1756,8 +2044,9 @@ static void scr_stream_error_buffer(ScrStream *s) { if (st->w.writing) return; while (st->w.head < st->w.n && !scr_exc_pending()) { ScrWEntry e = st->w.q[st->w.head++]; - st->w.length -= e.chunk->len; - scr_bytes_release(e.chunk); + st->w.length -= scr_stream_wchunk_len(st, e.chunk); + scr_stream_wchunk_release(st, e.chunk); + if (e.enc) scr_dyn_release(e.enc); if (e.cb) { ((void (*)(ScrClosure *))e.cb->fn)(e.cb); scr_closure_release(e.cb); @@ -1849,12 +2138,110 @@ static SCR_COLD void scr_stream_writev_buffer(ScrStream *s) { } st->w.head = 0; st->w.n = 0; - scr_stream_do_write(s, all, cbs); + scr_stream_do_write(s, all, cbs, NULL); +} + +/* A write's chunk and encoding as _writev receives them (+1 each). */ +static ScrDyn *scr_stream_wentry_value(const ScrStreamState *st, ScrBytes *chunk) { + if (st->w.values) return scr_dyn_retain((ScrDyn *)chunk); + return chunk->is_buffer ? scr_dyn_new_buffer(chunk) : scr_dyn_new_bytes(chunk); +} + +static ScrDyn *scr_stream_wentry_encoding(const ScrStreamState *st, ScrDyn *enc) { + if (!st->w.values) { + ScrStr *buffer = scr_str_new("buffer", 6); + ScrDyn *d = scr_dyn_new_str(buffer); + scr_str_release(buffer); + return d; + } + return scr_dyn_retain(enc ? enc : scr_dyn_undefined()); +} + +/* A batch entry's callback: the write's callback, or Node's nop. */ +static ScrDyn *scr_stream_writev_entry_cb_call(ScrClosure *clo, ScrDyn *const *args, size_t argc) { + (void)args; + (void)argc; + if (clo->ncaps > 0) { + ScrClosure *cb = scr_box_get_ref(clo->caps[0]); + ((void (*)(ScrClosure *))cb->fn)(cb); + scr_closure_release(cb); + } + return scr_dyn_retain(scr_dyn_undefined()); +} + +static ScrDyn *scr_stream_writev_entry_cb(ScrClosure *cb /*borrowed or NULL*/) { + ScrClosure *c = scr_closure_new((void *)&scr_stream_writev_entry_cb_call, cb ? 1 : 0); + if (cb) { + c->caps[0] = scr_box_new_obj(&scr_closure_retain_v, &scr_closure_release_v, &scr_closure_trace_v); + scr_box_set_ref(c->caps[0], scr_closure_retain(cb)); + } + return scr_dyn_new_func(c, &scr_stream_writev_entry_cb_call, 1, "(error)", cb ? "" : "nop"); +} + +/* Calls _writev with chunks as the in-flight write of len, whose + * completion runs cb (moves; NULL when every write had none). */ +static void scr_stream_writev_call(ScrStream *s, ScrDyn *chunks, size_t len, ScrClosure *cb) { + ScrStreamState *st = s->st; + st->w.writing = true; + st->w.wsync = true; + st->w.inflight_len = len; + st->w.inflight_cb = cb; + st->w.writev_inv(st->w.writev_cb, s, chunks); + st->w.wsync = false; +} + +/* Node's clearBuffer with _writev and more than one buffered write: the + * writes go out as one [{ chunk, encoding, callback }] batch (its + * allBuffers says whether every encoding is 'buffer'), and the batch's + * completion runs the writes' callbacks in order. */ +static void scr_stream_writev_batch(ScrStream *s) { + ScrStreamState *st = s->st; + size_t total = 0, ncbs = 0; + for (size_t i = st->w.head; i < st->w.n; i++) + if (st->w.q[i].cb) ncbs++; + ScrClosure *cbs = ncbs > 0 ? scr_closure_new((void *)&scr_stream_writev_cbs, ncbs) : NULL; + ScrDyn *chunks = scr_dyn_new_arr(); + bool all_buffers = true; + size_t k = 0; + for (size_t i = st->w.head; i < st->w.n; i++) { + ScrWEntry e = st->w.q[i]; + total += scr_stream_wchunk_len(st, e.chunk); + ScrDyn *entry = scr_dyn_new_obj(); + ScrDyn *encoding = scr_stream_wentry_encoding(st, e.enc); + if (!(encoding->kind == SCR_DYN_STR && encoding->v.str->len == 6 && + memcmp(encoding->v.str->data, "buffer", 6) == 0)) + all_buffers = false; + scr_dyn_obj_set(entry, "chunk", 5, scr_stream_wentry_value(st, e.chunk)); + scr_dyn_obj_set(entry, "encoding", 8, encoding); + scr_dyn_obj_set(entry, "callback", 8, scr_stream_writev_entry_cb(e.cb)); + scr_dyn_arr_push(chunks, entry); + scr_stream_wchunk_release(st, e.chunk); + if (e.enc) scr_dyn_release(e.enc); + if (e.cb) { + cbs->caps[k] = scr_box_new_obj(&scr_closure_retain_v, &scr_closure_release_v, + &scr_closure_trace_v); + scr_box_set_ref(cbs->caps[k], e.cb); /* moves */ + k++; + } + } + scr_dyn_arr_named_put(chunks, "allBuffers", 10, scr_dyn_new_bool(all_buffers)); + st->w.head = 0; + st->w.n = 0; + scr_stream_writev_call(s, chunks, total, cbs); + scr_dyn_release(chunks); } /* The buffered writes, one at a time (Node's clearBuffer without _writev). */ static void scr_stream_clear_buffer_each(ScrStream *s) { ScrStreamState *st = s->st; + if (st->w.buffer_processing) return; + st->w.buffer_processing = true; + if (st->w.writev_cb && !st->w.writing && st->w.n - st->w.head > 1 && st->w.corked == 0 && + !st->destroyed && !st->constructing && !scr_exc_pending()) { + scr_stream_writev_batch(s); + st->w.buffer_processing = false; + return; + } while (!st->w.writing && st->w.head < st->w.n && st->w.corked == 0 && !st->destroyed && !scr_exc_pending()) { ScrWEntry e = st->w.q[st->w.head++]; @@ -1862,8 +2249,9 @@ static void scr_stream_clear_buffer_each(ScrStream *s) { st->w.head = 0; st->w.n = 0; } - scr_stream_do_write(s, e.chunk, e.cb); + scr_stream_do_write(s, e.chunk, e.cb, e.enc); } + st->w.buffer_processing = false; } /* The fs streams' clearBuffer: nothing while constructing, and _writev @@ -1933,6 +2321,11 @@ static void scr_stream_finish_maybe(ScrStream *s) { scr_stream_emit0(s, "prefinish"); if (scr_exc_pending()) return; } + /* prefinish ran; without a _final the deferred afterWrites still hold + * 'finish' (Node's pendingcb), and the last of them comes back here. + * A _final's callback puts 'finish' on a tick at once (callFinal's + * onFinish), and a Transform's _final is its flush. */ + if (st->w.after_holds > 0 && !st->w.final_cb && !st->is_transform && !st->passthrough) return; st->w.finish_scheduled = true; scr_st_tick(s, SCR_ST_FINISH, NULL, NULL); } @@ -2313,10 +2706,10 @@ static void scr_stream_dynopt_read_inv(ScrClosure *cb, ScrStream *s, double size static void scr_stream_dynopt_chunk3(ScrClosure *cb, ScrStream *s, ScrBytes *chunk, ScrDynThunk glue, const char *what) { ScrDyn *args[3]; - args[0] = scr_dyn_new_buffer(chunk); - ScrStr *enc = scr_str_new("buffer", 6); - args[1] = scr_dyn_new_str(enc); - scr_str_release(enc); + /* (chunk, encoding, cb): an object-mode side passes the value and the + * write's encoding argument, as Node's Writable does */ + args[0] = scr_stream_chunk_value(s, chunk); + args[1] = scr_stream_chunk_encoding_value(s); args[2] = scr_stream_dynopt_done(s, glue, 1, "(error)"); ScrDyn *fn = scr_stream_dynopt_target(cb); ScrDyn *r = scr_dyn_call(fn, args, 3, what); @@ -2331,10 +2724,8 @@ static void scr_stream_dynopt_write_inv(ScrClosure *cb, ScrStream *s, ScrBytes * static void scr_stream_dynopt_transform_inv(ScrClosure *cb, ScrStream *s, ScrBytes *chunk) { ScrDyn *args[3]; - args[0] = scr_dyn_new_buffer(chunk); - ScrStr *enc = scr_str_new("buffer", 6); - args[1] = scr_dyn_new_str(enc); - scr_str_release(enc); + args[0] = scr_stream_chunk_value(s, chunk); + args[1] = scr_stream_chunk_encoding_value(s); args[2] = scr_stream_dynopt_done(s, &scr_stream_done_dyn_t, 2, "(error,data)"); ScrDyn *fn = scr_stream_dynopt_target(cb); ScrDyn *r = scr_dyn_call(fn, args, 3, "transform"); @@ -2343,6 +2734,27 @@ static void scr_stream_dynopt_transform_inv(ScrClosure *cb, ScrStream *s, ScrByt if (r != NULL) scr_dyn_release(r); } +static void scr_stream_dynopt_construct_inv(ScrClosure *cb, ScrStream *s) { + ScrDyn *fn = scr_stream_dynopt_target(cb); + ScrDyn *a = scr_stream_dynopt_done(s, &scr_stream_done_dyn_c, 1, "(error)"); + ScrDyn *r = scr_dyn_call(fn, &a, 1, "construct"); + scr_dyn_release(a); + scr_dyn_release(fn); + if (r != NULL) scr_dyn_release(r); +} + +static void scr_stream_dynopt_writev_inv(ScrClosure *cb, ScrStream *s, ScrDyn *chunks) { + ScrDyn *fn = scr_stream_dynopt_target(cb); + ScrDyn *args[2]; + args[0] = scr_dyn_retain(chunks); + args[1] = scr_stream_dynopt_done(s, &scr_stream_done_dyn_w, 1, "(error)"); + ScrDyn *r = scr_dyn_call(fn, args, 2, "writev"); + scr_dyn_release(args[0]); + scr_dyn_release(args[1]); + scr_dyn_release(fn); + if (r != NULL) scr_dyn_release(r); +} + static void scr_stream_dynopt_final_inv(ScrClosure *cb, ScrStream *s) { ScrDyn *fn = scr_stream_dynopt_target(cb); ScrDyn *a = scr_stream_dynopt_done(s, &scr_stream_done_dyn_f, 1, "(error)"); @@ -2384,9 +2796,14 @@ typedef struct { double rhwm, whwm; bool auto_destroy, emit_close, allow_half_open; bool readable_side, writable_side; + bool readable_object, writable_object; /* objectMode and the sided keys */ + bool decode_strings_off; /* decodeStrings: false */ ScrStr *enc; /* owned canonical name, or NULL */ + /* defaultEncoding other than utf8: as given (borrowed) and canonical + * (owned), or NULL */ + ScrStr *default_enc, *default_canonical; /* BORROWED callable fields (owned by the options record). */ - ScrDyn *read, *write, *final_fn, *destroy, *transform, *flush; + ScrDyn *read, *write, *final_fn, *destroy, *transform, *flush, *construct, *writev; } ScrStreamDynOpts; /* Node's `=== false` comparisons (autoDestroy/emitClose/allowHalfOpen and @@ -2460,22 +2877,24 @@ static bool scr_stream_parse_dyn_opts(const ScrDyn *opts, char base, ScrStreamDy out->readable_side = true; out->writable_side = true; out->enc = NULL; + out->readable_object = out->writable_object = false; + out->decode_strings_off = false; + out->default_enc = out->default_canonical = NULL; out->read = out->write = out->final_fn = out->destroy = out->transform = out->flush = NULL; + out->construct = out->writev = NULL; if (opts == NULL || opts->kind != SCR_DYN_OBJ) return true; /* Node's `if (options)` */ const bool duplexish = base == 'd' || base == 't' || base == 'p'; const bool transformish = base == 't' || base == 'p'; const bool r_sided = base != 'w'; - if (scr_stream_dynopt_truthy(opts, "objectMode", 10) || - scr_stream_dynopt_truthy(opts, "readableObjectMode", 18) || - scr_stream_dynopt_truthy(opts, "writableObjectMode", 18)) { - static const char m[] = "objectMode streams are not supported yet (chunks are Buffers or utf8 strings)"; - return scr_stream_dynopt_unsupported(m, sizeof m - 1); - } - if (scr_stream_dynopt_false(scr_dyn_obj_get((ScrDyn *)opts, "decodeStrings", 13))) { - static const char m[] = "decodeStrings: false is not supported yet (chunks always decode to Buffers)"; - return scr_stream_dynopt_unsupported(m, sizeof m - 1); + { + bool object = scr_stream_dynopt_truthy(opts, "objectMode", 10); + out->readable_object = object || (duplexish && scr_stream_dynopt_truthy(opts, "readableObjectMode", 18)); + out->writable_object = object || (duplexish && scr_stream_dynopt_truthy(opts, "writableObjectMode", 18)); } + /* WritableState: decodeStrings === false keeps string writes */ + out->decode_strings_off = + base != 'r' && scr_stream_dynopt_false(scr_dyn_obj_get((ScrDyn *)opts, "decodeStrings", 13)); { ScrDyn *v = scr_dyn_obj_get((ScrDyn *)opts, "signal", 6); if (v != NULL && v->kind != SCR_DYN_NULL && v->kind != SCR_DYN_UNDEF) { @@ -2483,21 +2902,22 @@ static bool scr_stream_parse_dyn_opts(const ScrDyn *opts, char base, ScrStreamDy return scr_stream_dynopt_unsupported(m, sizeof m - 1); } } - if (scr_stream_dynopt_fn(opts, "construct", 9) != NULL) { - static const char m[] = "the stream option 'construct' is not supported yet (deferred construction has no lowering)"; - return scr_stream_dynopt_unsupported(m, sizeof m - 1); - } - if (scr_stream_dynopt_fn(opts, "writev", 6) != NULL) { - static const char m[] = "the stream option 'writev' is not supported yet (writes deliver one chunk at a time)"; + out->construct = scr_stream_dynopt_fn(opts, "construct", 9); + if (base != 'r') out->writev = scr_stream_dynopt_fn(opts, "writev", 6); + if (transformish && out->writev != NULL) { + static const char m[] = "the stream option 'writev' on a Transform is not supported yet (batches would bypass the transform)"; return scr_stream_dynopt_unsupported(m, sizeof m - 1); } { + /* a known encoding or ERR_UNKNOWN_ENCODING (the states' constructors) */ ScrDyn *v = scr_dyn_obj_get((ScrDyn *)opts, "defaultEncoding", 15); if (v != NULL && v->kind == SCR_DYN_STR && !(v->v.str->len == 4 && memcmp(v->v.str->data, "utf8", 4) == 0) && !(v->v.str->len == 5 && memcmp(v->v.str->data, "utf-8", 5) == 0)) { - static const char m[] = "the stream option 'defaultEncoding' is not supported yet (utf8, the default, is the write-side string encoding)"; - return scr_stream_dynopt_unsupported(m, sizeof m - 1); + ScrStr *canonical = scr_bytes_normalize_encoding(v->v.str); + if (canonical == NULL) return false; + out->default_enc = v->v.str; + out->default_canonical = canonical; } } if (transformish) { @@ -2513,7 +2933,7 @@ static bool scr_stream_parse_dyn_opts(const ScrDyn *opts, char base, ScrStreamDy /* highWaterMark wins over the sided keys (Node's getHighWaterMark); * the readable side is checked first, as Duplex's Readable constructor - * runs first. */ + * runs first. An object-mode side defaults to 16 entries. */ if (duplexish) { out->rhwm = scr_stream_dynopt_hwm(opts, "readableHighWaterMark", "options.readableHighWaterMark"); if (out->rhwm == -2) return false; @@ -2524,6 +2944,8 @@ static bool scr_stream_parse_dyn_opts(const ScrDyn *opts, char base, ScrStreamDy if (hwm == -2) return false; out->rhwm = out->whwm = hwm; } + if (out->rhwm == -1 && out->readable_object) out->rhwm = 16; + if (out->whwm == -1 && out->writable_object) out->whwm = 16; out->auto_destroy = !scr_stream_dynopt_false(scr_dyn_obj_get((ScrDyn *)opts, "autoDestroy", 11)); out->emit_close = !scr_stream_dynopt_false(scr_dyn_obj_get((ScrDyn *)opts, "emitClose", 9)); if (duplexish) { @@ -2564,6 +2986,35 @@ static ScrClosure *scr_stream_dynopt_pick(ScrDyn *opt, void *dyn_inv, ScrClosure return fb; } +static void scr_stream_dynopt_construct_inv(ScrClosure *cb, ScrStream *s); +static void scr_stream_dynopt_writev_inv(ScrClosure *cb, ScrStream *s, ScrDyn *chunks); + +/* The options a dyn constructor applies over the fresh stream: the object + * modes, decodeStrings, defaultEncoding (the push decoding of a readable + * side and the writes of a writable side), writev, and construct, which + * Node's constructor schedules last. Releases the owned canonical name. */ +static void scr_stream_dynopt_apply_object(ScrStream *s, ScrStreamDynOpts *o) { + if (s != NULL && s->st != NULL) { + scr_stream_set_object_mode(s, o->readable_object, o->writable_object); + if (o->decode_strings_off) scr_stream_set_decode_strings(s, false); + if (o->default_enc) { + scr_stream_set_write_encoding(s, o->default_enc); + if (s->st->has_r && !s->st->r.object_entries) + scr_stream_release(scr_stream_set_push_encoding(s, o->default_canonical)); + } + if (o->writev && s->st->has_w) + scr_stream_set_writev(s, scr_stream_dynopt_clo(o->writev, (void *)&scr_stream_dynopt_writev_inv), + &scr_stream_dynopt_writev_inv); + if (o->construct) + scr_stream_set_construct(s, scr_stream_dynopt_clo(o->construct, (void *)&scr_stream_dynopt_construct_inv), + &scr_stream_dynopt_construct_inv); + } + if (o->default_canonical) { + scr_str_release(o->default_canonical); + o->default_canonical = NULL; + } +} + static void scr_stream_dynopt_apply_enc(ScrStream *s, ScrStr *enc) { if (enc == NULL) return; ScrStream *chain = scr_stream_set_encoding(s, enc); @@ -2579,6 +3030,7 @@ ScrStream *scr_stream_new_readable_dyn(ScrDyn *opts) { ScrClosure *destroy = scr_stream_dynopt_pick(o.destroy, (void *)&scr_stream_dynopt_destroy_inv, NULL, NULL, &dinv); ScrStream *s = scr_stream_new_readable(o.rhwm, o.auto_destroy, o.emit_close, read, (ScrStreamReadInv)rinv, destroy, (ScrStreamErrInv)dinv); + scr_stream_dynopt_apply_object(s, &o); scr_stream_dynopt_apply_enc(s, o.enc); return s; } @@ -2590,8 +3042,10 @@ ScrStream *scr_stream_new_writable_dyn(ScrDyn *opts) { ScrClosure *write = scr_stream_dynopt_pick(o.write, (void *)&scr_stream_dynopt_write_inv, NULL, NULL, &winv); ScrClosure *final_cb = scr_stream_dynopt_pick(o.final_fn, (void *)&scr_stream_dynopt_final_inv, NULL, NULL, &finv); ScrClosure *destroy = scr_stream_dynopt_pick(o.destroy, (void *)&scr_stream_dynopt_destroy_inv, NULL, NULL, &dinv); - return scr_stream_new_writable(o.whwm, o.auto_destroy, o.emit_close, + ScrStream *s = scr_stream_new_writable(o.whwm, o.auto_destroy, o.emit_close, write, (ScrStreamChunkInv)winv, final_cb, (ScrStreamPlainInv)finv, destroy, (ScrStreamErrInv)dinv); + scr_stream_dynopt_apply_object(s, &o); + return s; } ScrStream *scr_stream_new_duplex_dyn(ScrDyn *opts) { @@ -2606,6 +3060,7 @@ ScrStream *scr_stream_new_duplex_dyn(ScrDyn *opts) { o.allow_half_open, o.readable_side, o.writable_side, read, (ScrStreamReadInv)rinv, write, (ScrStreamChunkInv)winv, final_cb, (ScrStreamPlainInv)finv, destroy, (ScrStreamErrInv)dinv); + scr_stream_dynopt_apply_object(s, &o); scr_stream_dynopt_apply_enc(s, o.enc); return s; } @@ -2626,6 +3081,7 @@ static ScrStream *scr_stream_new_transformish_dyn(ScrDyn *opts, char base) { o.allow_half_open, o.readable_side, o.writable_side, transform, (ScrStreamChunkInv)tinv, flush, (ScrStreamPlainInv)linv, destroy, (ScrStreamErrInv)dinv); + scr_stream_dynopt_apply_object(s, &o); scr_stream_dynopt_apply_enc(s, o.enc); return s; } @@ -2652,6 +3108,7 @@ void scr_stream_init_readable_dyn(ScrStream *s, ScrDyn *opts, ScrClosure *destroy = scr_stream_dynopt_pick(o.destroy, (void *)&scr_stream_dynopt_destroy_inv, destroy_fb, (void *)destroy_fb_inv, &dinv); scr_stream_init_readable(s, o.rhwm, o.auto_destroy, o.emit_close, read, (ScrStreamReadInv)rinv, destroy, (ScrStreamErrInv)dinv); + scr_stream_dynopt_apply_object(s, &o); scr_stream_dynopt_apply_enc(s, o.enc); } @@ -2672,6 +3129,7 @@ void scr_stream_init_writable_dyn(ScrStream *s, ScrDyn *opts, ScrClosure *destroy = scr_stream_dynopt_pick(o.destroy, (void *)&scr_stream_dynopt_destroy_inv, destroy_fb, (void *)destroy_fb_inv, &dinv); scr_stream_init_writable(s, o.whwm, o.auto_destroy, o.emit_close, write, (ScrStreamChunkInv)winv, final_cb, (ScrStreamPlainInv)finv, destroy, (ScrStreamErrInv)dinv); + scr_stream_dynopt_apply_object(s, &o); } void scr_stream_init_duplex_dyn(ScrStream *s, ScrDyn *opts, @@ -2696,6 +3154,7 @@ void scr_stream_init_duplex_dyn(ScrStream *s, ScrDyn *opts, o.allow_half_open, o.readable_side, o.writable_side, read, (ScrStreamReadInv)rinv, write, (ScrStreamChunkInv)winv, final_cb, (ScrStreamPlainInv)finv, destroy, (ScrStreamErrInv)dinv); + scr_stream_dynopt_apply_object(s, &o); scr_stream_dynopt_apply_enc(s, o.enc); } @@ -2725,6 +3184,7 @@ static void scr_stream_init_transformish_dyn(ScrStream *s, ScrDyn *opts, char ba transform, (ScrStreamChunkInv)tinv, flush, (ScrStreamPlainInv)linv, destroy, (ScrStreamErrInv)dinv); } + scr_stream_dynopt_apply_object(s, &o); scr_stream_dynopt_apply_enc(s, o.enc); } @@ -3285,6 +3745,12 @@ static void scr_stream_done_marker_free(void) { scr_stream_done_marker = NULL; } +/* readable.chunkDone: whether a dyn for-await step answered the end (the + * done marker; an object-mode stream can yield undefined). */ +bool scr_stream_chunk_done(const ScrDyn *v) { + return v != NULL && v == scr_stream_done_marker; +} + ScrDyn *scr_stream_from_done(void) { if (!scr_stream_done_marker) { scr_stream_done_marker = scr_dyn_new_obj(); @@ -3294,35 +3760,43 @@ ScrDyn *scr_stream_from_done(void) { } /* ── pipeline function stages (pipeline.js: makeAsyncIterable, pumpToNode) ── - * A run of async generator functions between two node streams. Each - * stage is called while the pipeline is set up, in pipeline order: - * makeAsyncIterable hands the first one the previous stream itself (a - * Readable is async iterable) and each later one the previous stage's - * generator. The last generator is pumped into the stream after the run - * with pumpToNode. The stages and helpers use the closure ABI (the - * closure first; the callee owns its parameters). */ + * Runs of async generator functions between node streams. Each stage is + * called while the pipeline is set up, in pipeline order: + * makeAsyncIterable hands a stage that follows a stream the stream itself + * (a Readable is async iterable) and any other stage the previous stage's + * generator. The last generator of a run that a stream follows is pumped + * into that stream with pumpToNode. The stages and helpers use the closure + * ABI (the closure first; the callee owns its parameters). */ typedef ScrPromise *(*ScrPipeNextFn)(ScrClosure *, ScrGen *); typedef ScrDyn *(*ScrPipeReadFn)(ScrClosure *, void *); typedef ScrDyn *(*ScrPipeBoxFn)(ScrClosure *, ScrPromise *); -enum { SCR_PIPE_DEST_STREAM, SCR_PIPE_DEST_PROMISE = 2 }; +enum { SCR_PIPE_DEST_STREAM, SCR_PIPE_DEST_GEN, SCR_PIPE_DEST_PROMISE }; +/* flags bit 7: the callback is typed code's (stream.pipelineStagesDyn) */ +enum { SCR_PIPE_TYPED_CB = 128 }; typedef struct { - size_t at; /* streams[0..at-1] come before the stages */ size_t count; /* the function stages */ + uint64_t positions; /* bit j: the pipeline's j-th stage is a function */ /* stage(source[, { signal }]) answers an async generator, or a promise * for a promise destination; the source is absent for a source - * function, else the previous stream or async generator */ + * function (position 0), else the previous stream or async generator */ ScrClosure **stages; - bool source; /* stages[0] is the source (at == 0) */ int dest; /* the last stage: SCR_PIPE_DEST_* */ unsigned opts_mask; /* bit i: stages[i] takes the { signal } argument */ ScrDyn *signal; /* the pipeline's AbortSignal when opts_mask != 0 */ - ScrClosure *next, *read, *ret; /* the pumped generator's helpers, or NULL */ + /* (next, read, return) for each generator pumped into a stream (an + * async generator destination's PassThrough included), in pipeline + * order, or NULL */ + ScrClosure **helpers; ScrClosure *box; /* SCR_PIPE_DEST_PROMISE: boxes its promise as a dyn promise */ } ScrPipeStages; +static bool scr_pipe_is_stage(const ScrPipeStages *fs, size_t j) { + return fs && j < 64 && ((fs->positions >> j) & 1u); +} + /* stages[i](source[, { signal }]): the callee owns its parameters. */ static void *scr_pipe_call_stage(const ScrPipeStages *fs, size_t i, void *src /*moves*/) { ScrClosure *st = fs->stages[i]; @@ -3331,7 +3805,7 @@ static void *scr_pipe_call_stage(const ScrPipeStages *fs, size_t i, void *src /* opts = scr_dyn_new_obj(); scr_dyn_obj_set(opts, "signal", 6, scr_dyn_retain(fs->signal)); } - if (i == 0 && fs->source) { + if (i == 0 && (fs->positions & 1u)) { return opts ? ((void *(*)(ScrClosure *, ScrDyn *))st->fn)(st, opts) : ((void *(*)(ScrClosure *))st->fn)(st); } @@ -3580,17 +4054,17 @@ static void scr_pump_after_wait(ScrPump *pm, int stage, bool rejected) { } /* pumpToNode(gen, w, finish, { end }): starts at once, as the async - * function does. The helpers are borrowed. */ -static void scr_pump_start(ScrStreamPipeCtx *ctx, ScrGen *gen /*moves*/, const ScrPipeStages *fs, + * function does. The helpers (next, read, return) are borrowed. */ +static void scr_pump_start(ScrStreamPipeCtx *ctx, ScrGen *gen /*moves*/, ScrClosure *const *helpers, ScrStream *w, bool end) { ScrPump *pm = calloc(1, sizeof *pm); if (!pm) scr_stream_oom(); pm->rc = 1; pm->ctx = scr_stream_pipectx_retain_v(ctx); pm->gen = gen; - pm->next = scr_closure_retain(fs->next); - pm->read = scr_closure_retain(fs->read); - pm->ret = scr_closure_retain(fs->ret); + pm->next = scr_closure_retain(helpers[0]); + pm->read = scr_closure_retain(helpers[1]); + pm->ret = scr_closure_retain(helpers[2]); pm->w = scr_stream_retain(w); pm->end = end; pm->drain_l = scr_pump_closure((void *)&scr_pump_drain_l, pm); @@ -3649,7 +4123,7 @@ static void scr_pipe_dest_entry(ScrFiber *fiber, void *arg) { ctx->value = v; if (ctx->value_p) scr_promise_release(ctx->value_p); ctx->value_p = scr_promise_retain(d.typed); - if (pt && v && (v->kind == SCR_DYN_STR || v->kind == SCR_DYN_BYTES)) { + if (pt && v && v->kind != SCR_DYN_NULL && v->kind != SCR_DYN_UNDEF) { scr_stream_write_dyn(pt, v, NULL); if (scr_exc_pending()) scr_exc_clear(); } @@ -3721,27 +4195,27 @@ static ScrStream *scr_stream_pipeline_ex(size_t n, ScrStream **streams, ScrClosu ctx->dispose = add(signal, listener); scr_dyn_release(listener); } - /* pipelineImpl's loop over the stages: the n streams, with fs->count - * function stages before streams[fs->at] */ + /* pipelineImpl's loop over the stages: the n streams and fs->count + * function stages, at the positions fs->positions names */ size_t stages = n + (fs ? fs->count : 0); - size_t fn_first = fs ? fs->at : stages, fn_end = fs ? fs->at + fs->count : stages; ScrStream *ret = NULL; ScrGen *ret_gen = NULL; /* +1: ret when the previous stage was a function */ size_t i = 0; /* the next stream */ + size_t k = 0; /* the next function stage */ + size_t h = 0; /* the next pumped generator's helpers */ for (size_t j = 0; j < stages; j++) { bool reading = j + 1 < stages; bool end = reading || end_opt; bool last = j + 1 == stages; - if (j >= fn_first && j < fn_end) { + if (scr_pipe_is_stage(fs, j)) { /* ret = stage({ signal }) for the source, else * stage(makeAsyncIterable(ret), { signal }) */ - size_t k = j - fn_first; bool dest = last && fs->dest != SCR_PIPE_DEST_STREAM; - void *src = k == 0 && fs->source ? NULL - : ret_gen ? (void *)ret_gen - : (void *)scr_stream_retain(ret); + void *src = j == 0 ? NULL + : ret_gen ? (void *)ret_gen + : (void *)scr_stream_retain(ret); ret_gen = NULL; - void *out = scr_pipe_call_stage(fs, k, src); + void *out = scr_pipe_call_stage(fs, k++, src); if (scr_exc_pending()) { if (out && dest) scr_promise_release(out); else if (out) scr_gen_release(out); @@ -3753,17 +4227,22 @@ static ScrStream *scr_stream_pipeline_ex(size_t n, ScrStream **streams, ScrClosu ret_gen = out; continue; } - /* The destination function: pipeline() answers a PassThrough proxy - * that the promise's value feeds. Node's is in object mode; the - * frontend refuses programs that read it, so a byte-mode - * PassThrough plays its part in the pipeline's bookkeeping. */ + /* The destination function: pipeline() answers an object-mode + * PassThrough proxy that the promise's value or the generator's + * values feed. */ ScrDyn *pt_opts = scr_dyn_new_obj(); + scr_dyn_obj_set(pt_opts, "objectMode", 10, scr_dyn_new_bool(true)); ScrStream *pt = scr_stream_new_passthrough_dyn(pt_opts); scr_dyn_release(pt_opts); size_t pi = ctx->n++; ctx->streams[pi] = pt; ctx->finish_count++; - scr_pipe_dest_promise(ctx, out, fs->box, pi, end); + if (fs->dest == SCR_PIPE_DEST_GEN) { + /* pumpToNode(ret, pt, finish, { end }) */ + scr_pump_start(ctx, out, fs->helpers + 3 * h++, pt, end); + } else { + scr_pipe_dest_promise(ctx, out, fs->box, pi, end); + } /* destroyer(pt, false, true), with its cleanup as the last stream's */ ctx->destroyer[pi] = true; scr_pipe_on(pt, "close", scr_pipe_closure((void *)&scr_pipe_destroyer_close_l, ctx, pi), @@ -3776,7 +4255,7 @@ static ScrStream *scr_stream_pipeline_ex(size_t n, ScrStream **streams, ScrClosu } ScrStream *s = streams[i]; bool writing = j > 0; - if (reading && !(j + 1 >= fn_first && j + 1 < fn_end) && + if (reading && !scr_pipe_is_stage(fs, j + 1) && (streams[i + 1]->st->close_emitted || streams[i + 1]->st->destroyed)) { scr_pipe_throw("ERR_STREAM_UNABLE_TO_PIPE", "Cannot pipe to a closed or destroyed stream", SCR_ERR_ERROR); @@ -3803,7 +4282,7 @@ static ScrStream *scr_stream_pipeline_ex(size_t n, ScrStream **streams, ScrClosu ctx->finish_count++; ScrGen *g = ret_gen; ret_gen = NULL; - scr_pump_start(ctx, g, fs, s, end); + scr_pump_start(ctx, g, fs->helpers + 3 * h++, s, end); } else if (j > 0) { if (!ret->st->has_r) { static const char msg[] = @@ -3841,22 +4320,24 @@ static ScrStream *scr_stream_pipeline_ex(size_t n, ScrStream **streams, ScrClosu return scr_stream_retain(ret); } -static ScrPipeStages scr_pipe_stages_of(double at, double count, ScrClosure **stages, double flags, - double mask, ScrClosure *next, ScrClosure *read, - ScrClosure *ret, ScrClosure *box, ScrDyn *signal) { +static ScrPipeStages scr_pipe_stages_of(double count, ScrClosure **stages, double positions, + double flags, double mask, ScrClosure **helpers, + ScrClosure *box, ScrDyn *signal) { int bits = (int)flags; - ScrPipeStages fs = {(size_t)at, (size_t)count, stages, (bits & 1) != 0, (bits >> 1) & 3, - (unsigned)mask, signal, next, read, ret, box}; + ScrPipeStages fs = {(size_t)count, (uint64_t)positions, stages, (bits >> 1) & 3, (unsigned)mask, + signal, helpers, box}; return fs; } /* callback(error, value) through a checked-dynamic callback: Node passes - * both arguments. */ -static void scr_pipe_dyn_value_inv(ScrClosure *cb, ScrError *err, ScrDyn *value, ScrPromise *value_p) { - (void)value_p; + * both arguments. A typed callback (SCR_PIPE_TYPED_CB) takes null for no + * error, as the typed callback forms do. */ +static void scr_pipe_dyn_value_call(ScrClosure *cb, ScrError *err, ScrDyn *value, bool typed) { ScrDyn *fn = scr_stream_dynopt_target(cb); - ScrDyn *args[2] = {err ? scr_dyn_from_error(err) : scr_dyn_retain(scr_dyn_undefined()), + ScrDyn *none = typed ? scr_dyn_new_null() : scr_dyn_retain(scr_dyn_undefined()); + ScrDyn *args[2] = {err ? scr_dyn_from_error(err) : none, value && !err ? scr_dyn_retain(value) : scr_dyn_retain(scr_dyn_undefined())}; + if (err) scr_dyn_release(none); ScrDyn *r = scr_dyn_call(fn, args, 2, "callback"); scr_dyn_release(args[0]); scr_dyn_release(args[1]); @@ -3864,28 +4345,41 @@ static void scr_pipe_dyn_value_inv(ScrClosure *cb, ScrError *err, ScrDyn *value, if (r != NULL) scr_dyn_release(r); } -/* pipeline(...) with a run of function stages (see ScrPipeStages): flags - * bit 0 marks a source function and bits 1-2 the destination kind; mask - * names the stages taking { signal }. The helpers, box, signal and abort - * are borrowed (each NULL when unused); cb moves. */ -ScrStream *scr_stream_pipeline_stages(double n, ScrStream **streams, double at, double count, - ScrClosure **stages, double flags, double mask, - ScrClosure *next, ScrClosure *read, ScrClosure *ret, - ScrClosure *box, ScrDyn *signal, ScrClosure *abort, - ScrClosure *cb, ScrStreamErrInv inv) { - ScrPipeStages fs = scr_pipe_stages_of(at, count, stages, flags, mask, next, read, ret, box, signal); +static void scr_pipe_dyn_value_inv(ScrClosure *cb, ScrError *err, ScrDyn *value, ScrPromise *value_p) { + (void)value_p; + scr_pipe_dyn_value_call(cb, err, value, false); +} + +static void scr_pipe_dyn_value_typed_inv(ScrClosure *cb, ScrError *err, ScrDyn *value, + ScrPromise *value_p) { + (void)value_p; + scr_pipe_dyn_value_call(cb, err, value, true); +} + +/* pipeline(...) with function stages (see ScrPipeStages): positions + * marks the function stages among the n + count stages, flags bits 1-2 + * give the destination kind, and mask names the stages taking + * { signal }. The helpers, box, signal and abort are borrowed (each NULL + * when unused); cb moves. */ +ScrStream *scr_stream_pipeline_stages(double n, ScrStream **streams, double count, + ScrClosure **stages, double positions, double flags, + double mask, ScrClosure **helpers, ScrClosure *box, + ScrDyn *signal, ScrClosure *abort, ScrClosure *cb, + ScrStreamErrInv inv) { + ScrPipeStages fs = scr_pipe_stages_of(count, stages, positions, flags, mask, helpers, box, signal); return scr_stream_pipeline_ex((size_t)n, streams, cb, inv, true, NULL, NULL, &fs, abort, NULL); } -ScrStream *scr_stream_pipeline_stages_dyn(double n, ScrStream **streams, double at, double count, - ScrClosure **stages, double flags, double mask, - ScrClosure *next, ScrClosure *read, ScrClosure *ret, - ScrClosure *box, ScrDyn *signal, ScrClosure *abort, - ScrDyn *cb) { - ScrPipeStages fs = scr_pipe_stages_of(at, count, stages, flags, mask, next, read, ret, box, signal); +ScrStream *scr_stream_pipeline_stages_dyn(double n, ScrStream **streams, double count, + ScrClosure **stages, double positions, double flags, + double mask, ScrClosure **helpers, ScrClosure *box, + ScrDyn *signal, ScrClosure *abort, ScrDyn *cb) { + ScrPipeStages fs = scr_pipe_stages_of(count, stages, positions, flags, mask, helpers, box, signal); ScrClosure *c = scr_stream_dynopt_clo(cb, (void *)&scr_stream_finished_dyn_inv); /* a function destination's value reaches the callback */ - ScrPipeValInv vi = fs.dest != SCR_PIPE_DEST_STREAM ? &scr_pipe_dyn_value_inv : NULL; + ScrPipeValInv vi = fs.dest == SCR_PIPE_DEST_STREAM ? NULL + : ((int)flags & SCR_PIPE_TYPED_CB) ? &scr_pipe_dyn_value_typed_inv + : &scr_pipe_dyn_value_inv; return scr_stream_pipeline_ex((size_t)n, streams, c, &scr_stream_finished_dyn_inv, true, NULL, NULL, &fs, abort, vi); } @@ -3939,7 +4433,7 @@ static void *scr_compose_retain_v(void *p) { static void scr_compose_release_v(void *p) { ScrCompose *c = p; if (--c->rc > 0) return; - scr_stream_release(c->head); + if (c->head) scr_stream_release(c->head); scr_stream_release(c->tail); free(c); } @@ -3999,7 +4493,9 @@ static void scr_compose_destroyed(ScrCompose *c, ScrError *err) { /* d._write: head.write(chunk) ? callback() : (ondrain = callback) */ static void scr_compose_write_inv(ScrClosure *cb, ScrStream *s, ScrBytes *chunk) { ScrCompose *c = scr_box_get_ref(cb->caps[0]); - if (scr_stream_write(c->head, chunk, NULL)) { + bool ok = scr_stream_writes_values(s) ? scr_stream_write_dyn(c->head, (ScrDyn *)chunk, NULL) + : scr_stream_write(c->head, chunk, NULL); + if (ok) { if (!scr_exc_pending()) scr_stream_write_done(s, NULL); } else { c->ondrain = true; @@ -4048,25 +4544,20 @@ static void scr_compose_read_inv(ScrClosure *cb, ScrStream *s, double size) { } /* tail.on('data'): d.push(chunk), pausing the tail when d is full. The - * chunk is the tail's Buffer, or its string when the tail is encoded. */ -static void scr_compose_data_l(ScrClosure *cb, ScrBytes *bytes, ScrStr *str) { + * chunk is the tail's Buffer, its string when the tail is encoded, or an + * object-mode value. */ +static void scr_compose_data_l(ScrClosure *cb, ScrBytes *bytes, ScrStr *str, ScrDyn *value) { ScrCompose *c = scr_box_get_ref(cb->caps[0]); ScrStream *d = c->d; if (d) { ScrStreamState *dst = d->st; bool more; if (dst->r.object_entries) { - int pushed = scr_stream_add_entry( - d, str ? (void *)scr_str_retain(str) : (void *)scr_bytes_retain(bytes), str != NULL); - if (pushed < 0) { - static const char m[] = "a composed stream whose tail mixes strings and Buffers is not supported yet"; - ScrStr *msg = scr_str_new(m, sizeof m - 1); - ScrError *e = scr_error_new(SCR_ERR_ERROR, msg); - scr_str_release(msg); - scr_stream_release(scr_stream_destroy(d, e)); - scr_error_release(e); - } - more = pushed > 0; + more = value ? scr_stream_push_object(d, value) > 0 + : scr_stream_add_entry(d, str ? (void *)scr_str_retain(str) : (void *)scr_bytes_retain(bytes), + str ? SCR_ENTRY_STR : SCR_ENTRY_BYTES) > 0; + } else if (value && !str && !bytes) { + more = scr_stream_push_dyn(d, value); } else if (str) { more = scr_stream_push_str(d, str); } else { @@ -4135,43 +4626,54 @@ static void scr_compose_arg_value(size_t i, const char *what, ScrStream *s) { scr_throw_error_msg_code(SCR_ERR_TYPE, m, (size_t)n, "ERR_INVALID_ARG_VALUE"); } -ScrStream *scr_stream_compose(double n_d, ScrStream **streams) { - size_t n = (size_t)n_d; - if (n == 0) { +/* compose(...streams) over n streams and fs's function stages: the stream + * at pipeline position j must be readable unless it is last and writable + * unless it is first. A first stage that is not a stream (an iterable or + * source function) leaves the Duplex without a writable side. */ +static ScrStream *scr_stream_compose_impl(size_t n, ScrStream **streams, const ScrPipeStages *fs, + ScrClosure *abort) { + size_t total = n + (fs ? fs->count : 0); + if (total == 0) { static const char msg[] = "The \"streams\" argument must be specified"; scr_throw_error_msg_code(SCR_ERR_TYPE, msg, sizeof msg - 1, "ERR_MISSING_ARGS"); return NULL; } - if (n == 1) return scr_stream_retain(streams[0]); /* Duplex.from(duplex) */ - for (size_t i = 0; i < n; i++) { - if (i + 1 < n && !scr_stream_prop(streams[i], "readable")) { - scr_compose_arg_value(i, "readable", streams[i]); + if (total == 1 && n == 1) return scr_stream_retain(streams[0]); /* Duplex.from(duplex) */ + for (size_t j = 0, i = 0; j < total; j++) { + if (fs && j < 64 && ((fs->positions >> j) & 1u)) continue; + if (j + 1 < total && !scr_stream_prop(streams[i], "readable")) { + scr_compose_arg_value(j, "readable", streams[i]); return NULL; } - if (i > 0 && !scr_stream_prop(streams[i], "writable")) { - scr_compose_arg_value(i, "writable", streams[i]); + if (j > 0 && !scr_stream_prop(streams[i], "writable")) { + scr_compose_arg_value(j, "writable", streams[i]); return NULL; } + i++; } + bool stage_head = fs && (fs->positions & 1u); ScrCompose *c = calloc(1, sizeof *c); if (!c) scr_stream_oom(); c->rc = 1; - c->head = scr_stream_retain(streams[0]); + c->head = stage_head ? NULL : scr_stream_retain(streams[0]); c->tail = scr_stream_retain(streams[n - 1]); c->onclose = SCR_COMPOSE_RUNNING; ScrStream *tail = scr_stream_pipeline_ex(n, streams, scr_compose_closure((void *)&scr_compose_finished, c), - &scr_compose_finished, true, NULL, NULL, NULL, NULL, + &scr_compose_finished, true, NULL, NULL, fs, abort, NULL); if (!tail) { scr_compose_release_v(c); return NULL; } scr_stream_release(tail); - c->writable = scr_stream_prop(c->head, "writable") != 0; + c->writable = c->head && scr_stream_prop(c->head, "writable") != 0; c->readable = scr_stream_prop(c->tail, "readable") != 0; + /* readableObjectMode: !!tail?.readableObjectMode, writableObjectMode: + * !!head?.writableObjectMode */ bool object_mode = c->tail->st->has_r && c->tail->st->r.object_entries; + bool w_object = c->head && c->head->st->has_w && c->head->st->w.object_mode; ScrStream *d = scr_stream_new_duplex( - object_mode ? 16 : -1, -1, true, true, true, c->readable, c->writable, + object_mode ? 16 : -1, w_object ? 16 : -1, true, true, true, c->readable, c->writable, c->readable ? scr_compose_closure((void *)&scr_compose_read_inv, c) : NULL, c->readable ? &scr_compose_read_inv : NULL, c->writable ? scr_compose_closure((void *)&scr_compose_write_inv, c) : NULL, @@ -4180,6 +4682,7 @@ ScrStream *scr_stream_compose(double n_d, ScrStream **streams) { c->writable ? &scr_compose_final_inv : NULL, scr_compose_closure((void *)&scr_compose_destroy_inv, c), &scr_compose_destroy_inv); if (object_mode) d->st->r.object_entries = true; + if (w_object) scr_stream_set_object_mode(d, false, true); c->d = scr_stream_retain(d); if (c->writable) { scr_compose_on(c->head, "drain", &c->drain_l, (void *)&scr_compose_drain_l, c, scr_ee_inv_fixed0); @@ -4187,7 +4690,7 @@ ScrStream *scr_stream_compose(double n_d, ScrStream **streams) { c->tail, scr_compose_closure((void *)&scr_compose_tail_eos, c), &scr_compose_tail_eos)); } if (c->readable) { - scr_compose_on(c->tail, "data", &c->data_l, (void *)&scr_compose_data_l, c, scr_ee_inv_fixed2); + scr_compose_on(c->tail, "data", &c->data_l, (void *)&scr_compose_data_l, c, scr_ee_inv_fixed3); scr_compose_on(c->tail, "end", &c->end_l, (void *)&scr_compose_end_l, c, scr_ee_inv_fixed0); } static SCR_TL bool registered = false; @@ -4201,6 +4704,374 @@ ScrStream *scr_stream_compose(double n_d, ScrStream **streams) { return d; } +ScrStream *scr_stream_compose(double n_d, ScrStream **streams) { + return scr_stream_compose_impl((size_t)n_d, streams, NULL, NULL); +} + +/* compose(...stages) with function stages among the streams (the + * pipeline stage layout: scr_stream_pipeline_stages). */ +ScrStream *scr_stream_compose_stages(double n, ScrStream **streams, double count, ScrClosure **stages, + double positions, double flags, double mask, ScrClosure **helpers, + ScrClosure *box, ScrDyn *signal, ScrClosure *abort) { + ScrPipeStages fs = scr_pipe_stages_of(count, stages, positions, flags, mask, helpers, box, signal); + return scr_stream_compose_impl((size_t)n, streams, &fs, abort); +} + +/* ── Duplex.from over a stream or a { readable, writable } pair ───────── + * duplexify.js's _duplexify({ readable, writable }): a Duplexify that + * writes to w (write() answering false waits for 'drain'; final ends w and + * waits for its 'finish') and reads r through 'readable' and read(), with + * each side's end of stream (eos) finishing the Duplex. The readable and + * writable object modes follow r's and w's. */ + +enum { SCR_DUPX_UNSET, SCR_DUPX_NULL, SCR_DUPX_WAIT }; + +typedef struct ScrDuplexify { + size_t rc; + ScrStream *r, *w; /* +1 or NULL */ + ScrStream *d; /* +1 until teardown */ + ScrClosure *drain_l, *finish_l, *readable_l, *end_l; /* +1, the listeners, or NULL */ + ScrClosure *r_eos, *w_eos; /* +1: the eos listeners' cleanups, or NULL */ + bool readable, writable; + bool ondrain, onfinish, onreadable; + int onclose; /* _duplexify's onclose: undefined, null, or d's destroy callback */ + struct ScrDuplexify *live_prev, *live_next; +} ScrDuplexify; + +static SCR_TL ScrDuplexify *scr_dupx_live = NULL; + +static void *scr_dupx_retain_v(void *p) { + ((ScrDuplexify *)p)->rc++; + return p; +} + +static void scr_dupx_release_v(void *p) { + ScrDuplexify *x = p; + if (--x->rc > 0) return; + if (x->r_eos) scr_closure_release(x->r_eos); + if (x->w_eos) scr_closure_release(x->w_eos); + if (x->r) scr_stream_release(x->r); + if (x->w) scr_stream_release(x->w); + free(x); +} + +static ScrClosure *scr_dupx_closure(void *fn, ScrDuplexify *x) { + ScrClosure *cl = scr_closure_new(fn, 1); + cl->caps[0] = scr_box_new_obj(&scr_dupx_retain_v, &scr_dupx_release_v, NULL); + scr_box_set_ref(cl->caps[0], scr_dupx_retain_v(x)); + return cl; +} + +static void scr_dupx_on(ScrStream *s, const char *name, ScrClosure **slot, void *fn, ScrDuplexify *x) { + ScrStr *n = scr_str_new(name, strlen(name)); + *slot = scr_dupx_closure(fn, x); + scr_emitter_release( + scr_emitter_on((ScrEmitter *)s, n, scr_closure_retain(*slot), scr_ee_inv_fixed0, false, false)); + scr_str_release(n); +} + +/* Drop the Duplex and the listeners on r and w (the eos listeners stay + * registered; their cleanups, which hold the context, are dropped). */ +static void scr_dupx_teardown(ScrDuplexify *x) { + if (!x->d) return; + if (x->r_eos) scr_closure_release(x->r_eos); + if (x->w_eos) scr_closure_release(x->w_eos); + x->r_eos = x->w_eos = NULL; + if (x->w) { + scr_compose_off(x->w, "drain", &x->drain_l); + scr_compose_off(x->w, "finish", &x->finish_l); + } + if (x->r) { + scr_compose_off(x->r, "readable", &x->readable_l); + scr_compose_off(x->r, "end", &x->end_l); + } + if (x->live_prev) x->live_prev->live_next = x->live_next; + else scr_dupx_live = x->live_next; + if (x->live_next) x->live_next->live_prev = x->live_prev; + x->live_prev = x->live_next = NULL; + ScrStream *d = x->d; + x->d = NULL; + scr_stream_release(d); + scr_dupx_release_v(x); /* the live list's reference */ +} + +/* At exit, a Duplexify still open also drops its eos listeners on r and + * w: they hold the context, which holds r and w. */ +static void scr_dupx_atexit(void) { + while (scr_dupx_live) { + ScrDuplexify *x = scr_dupx_live; + ScrClosure *eos[2] = {x->r_eos, x->w_eos}; + x->r_eos = x->w_eos = NULL; + for (int i = 0; i < 2; i++) { + if (!eos[i]) continue; + ((void (*)(ScrClosure *))eos[i]->fn)(eos[i]); + scr_closure_release(eos[i]); + } + scr_dupx_teardown(x); + } +} + +/* d's destroy callback: callback(err), then the context lets go. */ +static void scr_dupx_destroyed(ScrDuplexify *x, ScrError *err) { + ScrStream *d = scr_stream_retain(x->d); + scr_dupx_teardown(x); + scr_stream_destroy_done(d, err ? scr_error_retain(err) : NULL); + scr_stream_release(d); +} + +/* onfinished(err): the pending destroy callback, else d.destroy(err) */ +static void scr_dupx_onfinished(ScrDuplexify *x, ScrError *err) { + int onclose = x->onclose; + x->onclose = SCR_DUPX_NULL; + if (!x->d) return; + if (onclose == SCR_DUPX_WAIT) { + scr_dupx_destroyed(x, err); + } else if (err) { + ScrStream *d = scr_stream_retain(x->d); + scr_stream_release(scr_stream_destroy(d, err)); + scr_stream_release(d); + } +} + +/* eos(w): writable = false; an error destroys r */ +static void scr_dupx_w_eos(ScrClosure *cb, ScrStream *s, ScrError *err) { + (void)s; + ScrDuplexify *x = scr_box_get_ref(cb->caps[0]); + x->writable = false; + if (err && x->r) scr_stream_release(scr_stream_destroy(x->r, err)); + scr_dupx_onfinished(x, err); + scr_dupx_release_v(x); +} + +/* eos(r): readable = false; an error destroys w */ +static void scr_dupx_r_eos(ScrClosure *cb, ScrStream *s, ScrError *err) { + (void)s; + ScrDuplexify *x = scr_box_get_ref(cb->caps[0]); + x->readable = false; + if (err && x->w) scr_stream_release(scr_stream_destroy(x->w, err)); + scr_dupx_onfinished(x, err); + scr_dupx_release_v(x); +} + +/* d._write: w.write(chunk) ? callback() : (ondrain = callback) */ +static void scr_dupx_write_inv(ScrClosure *cb, ScrStream *s, ScrBytes *chunk) { + ScrDuplexify *x = scr_box_get_ref(cb->caps[0]); + bool ok = scr_stream_writes_values(s) ? scr_stream_write_dyn(x->w, (ScrDyn *)chunk, NULL) + : scr_stream_write(x->w, chunk, NULL); + if (ok) { + if (!scr_exc_pending()) scr_stream_write_done(s, NULL); + } else { + x->ondrain = true; + } + scr_dupx_release_v(x); +} + +/* d._final: w.end(); onfinish = callback */ +static void scr_dupx_final_inv(ScrClosure *cb, ScrStream *s) { + (void)s; + ScrDuplexify *x = scr_box_get_ref(cb->caps[0]); + ScrStream *r = scr_stream_end(x->w, NULL, NULL, NULL); + if (r) scr_stream_release(r); + x->onfinish = true; + scr_dupx_release_v(x); +} + +static void scr_dupx_drain_l(ScrClosure *cb) { + ScrDuplexify *x = scr_box_get_ref(cb->caps[0]); + if (x->ondrain && x->d) { + x->ondrain = false; + scr_stream_write_done(x->d, NULL); + } + scr_dupx_release_v(x); +} + +static void scr_dupx_finish_l(ScrClosure *cb) { + ScrDuplexify *x = scr_box_get_ref(cb->caps[0]); + if (x->onfinish && x->d) { + x->onfinish = false; + scr_stream_final_done(x->d, NULL); + } + scr_dupx_release_v(x); +} + +/* d._read: push r.read() until it answers null (then wait for 'readable') + * or d is full */ +static void scr_dupx_pull(ScrDuplexify *x) { + ScrStream *d = x->d; + while (d && x->r) { + ScrEntryKind kind = SCR_ENTRY_BYTES; + void *chunk = scr_stream_read_n_kind(x->r, -1, &kind); + if (scr_exc_pending()) return; + if (!chunk) { + x->onreadable = true; + return; + } + bool more; + if (d->st->r.object_entries) { + more = scr_stream_add_entry(d, chunk, kind) > 0; + } else if (kind == SCR_ENTRY_STR) { + more = scr_stream_push_str(d, chunk); + scr_str_release(chunk); + } else if (kind == SCR_ENTRY_DYN) { + more = scr_stream_push_dyn(d, chunk); + scr_dyn_release(chunk); + } else { + more = scr_stream_push(d, chunk); + scr_bytes_release(chunk); + } + if (!more || scr_exc_pending()) return; + } +} + +static void scr_dupx_read_inv(ScrClosure *cb, ScrStream *s, double size) { + (void)s; + (void)size; + ScrDuplexify *x = scr_box_get_ref(cb->caps[0]); + x->onreadable = false; + scr_dupx_pull(x); + scr_dupx_release_v(x); +} + +static void scr_dupx_readable_l(ScrClosure *cb) { + ScrDuplexify *x = scr_box_get_ref(cb->caps[0]); + if (x->onreadable && x->d) { + x->onreadable = false; + scr_dupx_pull(x); + } + scr_dupx_release_v(x); +} + +static void scr_dupx_end_l(ScrClosure *cb) { + ScrDuplexify *x = scr_box_get_ref(cb->caps[0]); + if (x->d) scr_stream_push_null(x->d); + scr_dupx_release_v(x); +} + +/* d._destroy */ +static void scr_dupx_destroy_inv(ScrClosure *cb, ScrStream *s, ScrError *err) { + (void)s; + ScrDuplexify *x = scr_box_get_ref(cb->caps[0]); + ScrError *e = err ? scr_error_retain(err) : NULL; + if (!e && x->onclose != SCR_DUPX_NULL) e = scr_compose_abort_error(); + x->onreadable = x->ondrain = x->onfinish = false; + if (x->onclose == SCR_DUPX_NULL) { + if (x->d) scr_dupx_destroyed(x, e); + } else { + x->onclose = SCR_DUPX_WAIT; + if (x->w && !x->w->st->destroyed) scr_stream_release(scr_stream_destroy(x->w, e)); + if (x->r && !x->r->st->destroyed) scr_stream_release(scr_stream_destroy(x->r, e)); + } + if (e) scr_error_release(e); + scr_dupx_release_v(x); +} + +/* _duplexify({ readable: r, writable: w }): r and w borrowed, either NULL. + * +1. */ +ScrStream *scr_stream_duplexify(ScrStream *r, ScrStream *w) { + ScrDuplexify *x = calloc(1, sizeof *x); + if (!x) scr_stream_oom(); + x->rc = 1; + x->r = r ? scr_stream_retain(r) : NULL; + x->w = w ? scr_stream_retain(w) : NULL; + x->onclose = SCR_DUPX_UNSET; + x->readable = r && scr_stream_prop(r, "readable") != 0; + x->writable = w && scr_stream_prop(w, "writable") != 0; + /* new Duplexify({ readableObjectMode, writableObjectMode, readable, writable }) */ + bool r_object = r && r->st->has_r && r->st->r.object_entries; + bool w_object = w && w->st->has_w && w->st->w.object_mode; + ScrStream *d = scr_stream_new_duplex( + r_object ? 16 : -1, w_object ? 16 : -1, true, true, true, x->readable, x->writable, + x->readable ? scr_dupx_closure((void *)&scr_dupx_read_inv, x) : NULL, + x->readable ? &scr_dupx_read_inv : NULL, + x->writable ? scr_dupx_closure((void *)&scr_dupx_write_inv, x) : NULL, + x->writable ? &scr_dupx_write_inv : NULL, + x->writable ? scr_dupx_closure((void *)&scr_dupx_final_inv, x) : NULL, + x->writable ? &scr_dupx_final_inv : NULL, + scr_dupx_closure((void *)&scr_dupx_destroy_inv, x), &scr_dupx_destroy_inv); + if (r_object) d->st->r.object_entries = true; + if (w_object) scr_stream_set_object_mode(d, false, true); + d->cls = "Duplexify"; + x->d = scr_stream_retain(d); + if (x->writable) { + x->w_eos = scr_stream_finished(w, scr_dupx_closure((void *)&scr_dupx_w_eos, x), &scr_dupx_w_eos); + scr_dupx_on(w, "drain", &x->drain_l, (void *)&scr_dupx_drain_l, x); + scr_dupx_on(w, "finish", &x->finish_l, (void *)&scr_dupx_finish_l, x); + } + if (x->readable) { + x->r_eos = scr_stream_finished(r, scr_dupx_closure((void *)&scr_dupx_r_eos, x), &scr_dupx_r_eos); + scr_dupx_on(r, "readable", &x->readable_l, (void *)&scr_dupx_readable_l, x); + scr_dupx_on(r, "end", &x->end_l, (void *)&scr_dupx_end_l, x); + } + static SCR_TL bool registered = false; + if (!registered) { + registered = true; + scr_atexit(scr_dupx_atexit); + } + x->live_next = scr_dupx_live; + if (scr_dupx_live) scr_dupx_live->live_prev = x; + scr_dupx_live = x; /* the reference x was created with */ + return d; +} + +/* Duplex.from(promise) (duplexify.js): a Duplexify({ objectMode: true, + * writable: false, read() {} }) that pushes the promise's value unless it + * is nullish, then ends; a rejection destroys it with the reason. */ +typedef struct { + ScrStream *d; /* +1 */ + ScrDyn *boxed; /* +1, the promise boxed */ +} ScrDupxPromise; + +static void scr_dupx_noop_read(ScrClosure *cb, ScrStream *s, double size) { + (void)cb; + (void)s; + (void)size; +} + +static void scr_dupx_promise_entry(ScrFiber *fiber, void *arg) { + (void)fiber; + ScrDupxPromise p = *(ScrDupxPromise *)arg; + free(arg); + /* the boxed promise's payload is a dyn value (NULL: undefined) */ + ScrDyn *v = scr_await_ref(p.boxed->v.promise); + if (!scr_exc_pending()) { + if (v && v->kind != SCR_DYN_NULL && v->kind != SCR_DYN_UNDEF) scr_stream_push_object(p.d, v); + if (!scr_exc_pending()) scr_stream_push_null(p.d); + if (scr_exc_pending()) scr_exc_clear(); + if (v) scr_dyn_release(v); + } else { + ScrError *err = scr_pump_caught(); + scr_stream_release(scr_stream_destroy(p.d, err)); + if (scr_exc_pending()) scr_exc_clear(); + scr_error_release(err); + } + scr_stream_release(p.d); + scr_dyn_release(p.boxed); +} + +/* The readable Duplexify over a boxed promise (moves boxed). +1. */ +static ScrStream *scr_dupx_from_boxed(ScrDyn *boxed) { + ScrClosure *read = scr_closure_new((void *)&scr_dupx_noop_read, 0); + ScrStream *d = scr_stream_new_duplex(16, 16, true, true, true, true, false, read, + &scr_dupx_noop_read, NULL, NULL, NULL, NULL, NULL, NULL); + scr_stream_set_object_mode(d, true, true); + d->cls = "Duplexify"; + ScrDupxPromise *ctx = malloc(sizeof *ctx); + if (!ctx) scr_stream_oom(); + ctx->d = scr_stream_retain(d); + ctx->boxed = boxed; + scr_promise_release(scr_async_spawn_after(ctx->boxed->v.promise, &scr_dupx_promise_entry, ctx)); + return d; +} + +/* p and box borrowed (box: the compiler's promise → dyn promise helper). +1. */ +ScrStream *scr_stream_duplex_from_promise(ScrPromise *p, ScrClosure *box) { + return scr_dupx_from_boxed(((ScrPipeBoxFn)box->fn)(box, scr_promise_retain(p))); +} + +ScrStream *scr_stream_duplexify_readable(ScrStream *r) { return scr_stream_duplexify(r, NULL); } +ScrStream *scr_stream_duplexify_writable(ScrStream *w) { return scr_stream_duplexify(NULL, w); } +ScrStream *scr_stream_duplexify_pair(ScrStream *r, ScrStream *w) { return scr_stream_duplexify(r, w); } + /* ── node:stream/promises ───────────────────────────────────────────── * The promise forms ride the callback machinery above with a settling * watcher: caps[0] boxes the pending promise; the terminal status @@ -4263,12 +5134,12 @@ static void scr_sp_value_inv(ScrClosure *cb, ScrError *err, ScrDyn *value, ScrPr scr_promise_release(p); } -ScrPromise *scr_sp_pipeline_stages(double n, ScrStream **streams, double at, double count, - ScrClosure **stages, double flags, double mask, - ScrClosure *next, ScrClosure *read, ScrClosure *ret, - ScrClosure *box, ScrDyn *signal, ScrClosure *abort) { +ScrPromise *scr_sp_pipeline_stages(double n, ScrStream **streams, double count, + ScrClosure **stages, double positions, double flags, + double mask, ScrClosure **helpers, ScrClosure *box, + ScrDyn *signal, ScrClosure *abort) { ScrPromise *p = scr_promise_new(); - ScrPipeStages fs = scr_pipe_stages_of(at, count, stages, flags, mask, next, read, ret, box, signal); + ScrPipeStages fs = scr_pipe_stages_of(count, stages, positions, flags, mask, helpers, box, signal); ScrPipeValInv vi = fs.dest != SCR_PIPE_DEST_STREAM ? &scr_sp_value_inv : NULL; ScrStream *dst = scr_stream_pipeline_ex((size_t)n, streams, scr_sp_watcher(p), &scr_sp_settle_inv, true, NULL, NULL, &fs, abort, vi); @@ -4277,6 +5148,24 @@ ScrPromise *scr_sp_pipeline_stages(double n, ScrStream **streams, double at, dou return p; } +/* The options' signal: NULL for a nullish one; false (p rejected with + * ERR_INVALID_ARG_TYPE) for a value that is not an AbortSignal. */ +static bool scr_sp_opts_signal(ScrPromise *p, ScrDyn **signal) { + if (*signal && scr_dyn_is_nullish(*signal)) *signal = NULL; + if (!*signal) return true; + ScrDyn *aborted = NULL; + if ((*signal)->kind == SCR_DYN_OBJ || (*signal)->kind == SCR_DYN_HANDLE) { + aborted = scr_stream_signal_prop(*signal, "aborted"); + } + if (!aborted) { + scr_dyn_prop_type_fail("options.signal", "an instance of AbortSignal", *signal); + scr_promise_reject_pending(p); + return false; + } + scr_dyn_release(aborted); + return true; +} + /* pipeline(...streams, { signal, end }): end false leaves the destination * open (the promise settles once the stages before it finish); signal is * NULL or borrowed — a value that is not an AbortSignal rejects with @@ -4284,19 +5173,7 @@ ScrPromise *scr_sp_pipeline_stages(double n, ScrStream **streams, double at, dou ScrPromise *scr_sp_pipeline_opts(double n, ScrStream **streams, bool end, ScrDyn *signal, ScrAbortAddFn add) { ScrPromise *p = scr_promise_new(); - if (signal && scr_dyn_is_nullish(signal)) signal = NULL; - if (signal) { - ScrDyn *aborted = NULL; - if (signal->kind == SCR_DYN_OBJ || signal->kind == SCR_DYN_HANDLE) { - aborted = scr_stream_signal_prop(signal, "aborted"); - } - if (!aborted) { - scr_dyn_prop_type_fail("options.signal", "an instance of AbortSignal", signal); - scr_promise_reject_pending(p); - return p; - } - scr_dyn_release(aborted); - } + if (!scr_sp_opts_signal(p, &signal)) return p; ScrStream *dst = scr_stream_pipeline_ex((size_t)n, streams, scr_sp_watcher(p), &scr_sp_settle_inv, end, signal, add, NULL, NULL, NULL); if (dst) scr_stream_release(dst); @@ -4304,6 +5181,25 @@ ScrPromise *scr_sp_pipeline_opts(double n, ScrStream **streams, bool end, ScrDyn return p; } +/* scr_sp_pipeline_stages with the options argument: end and the + * options' signal (outer, NULL or borrowed) as scr_sp_pipeline_opts + * takes them. The stages' signal is the pipeline's own. */ +ScrPromise *scr_sp_pipeline_stages_opts(double n, ScrStream **streams, double count, + ScrClosure **stages, double positions, double flags, + double mask, ScrClosure **helpers, ScrClosure *box, + ScrDyn *signal, ScrClosure *abort, bool end, + ScrDyn *outer, ScrAbortAddFn add) { + ScrPromise *p = scr_promise_new(); + if (!scr_sp_opts_signal(p, &outer)) return p; + ScrPipeStages fs = scr_pipe_stages_of(count, stages, positions, flags, mask, helpers, box, signal); + ScrPipeValInv vi = fs.dest != SCR_PIPE_DEST_STREAM ? &scr_sp_value_inv : NULL; + ScrStream *dst = scr_stream_pipeline_ex((size_t)n, streams, scr_sp_watcher(p), &scr_sp_settle_inv, + end, outer, add, &fs, abort, vi); + if (dst) scr_stream_release(dst); + else scr_promise_reject_pending(p); + return p; +} + /* ── node:stream/consumers ──────────────────────────────────────────── * text/json/buffer/arrayBuffer over the readable machinery: a native 'data' listener * accumulates every chunk (Buffer chunks as-is; string chunks — an @@ -4360,7 +5256,21 @@ static void scr_sc_settle_ok(ScrClosure *cb, int kind) { /* The 'data' accumulation (the emit ABI's two payload slots — exactly * one non-NULL). */ -static void scr_sc_data(ScrClosure *cb, void *b, void *str) { +/* An object-mode value other than a string or a Buffer reaching a + * runtime consumer that reads text or bytes (stream/consumers, readline). */ +static void scr_stream_value_consumer_fence(const char *consumer) { + char msg[160]; + int n = snprintf(msg, sizeof msg, + "%s over an object-mode stream value that is not a string or Buffer is not supported yet", + consumer); + scr_throw_error_msg_code(SCR_ERR_ERROR, msg, (size_t)n, "SC2020"); +} + +static void scr_sc_data(ScrClosure *cb, void *b, void *str, void *value) { + if (b == NULL && str == NULL && value != NULL) { + scr_stream_value_consumer_fence("stream/consumers"); + return; + } ScrArr *chunks = scr_box_get_ref(cb->caps[1]); /* +1 */ if (b != NULL) { scr_arr_push_ref(chunks, scr_bytes_retain((ScrBytes *)b)); @@ -4433,7 +5343,7 @@ static ScrPromise *scr_sc_consume(ScrStream *s, int kind) { ScrStr *dn = scr_str_new("data", 4); scr_emitter_release(scr_emitter_on((ScrEmitter *)s, dn, scr_sc_closure((void *)&scr_sc_data, p, chunks), - scr_ee_inv_fixed2, false, false)); + scr_ee_inv_fixed3, false, false)); scr_str_release(dn); /* resume() rather than the 'data' hook alone: Node's consumer pulls * through the iterator, which drains a PAUSED stream too. */ @@ -4624,7 +5534,11 @@ static SCR_TL ScrRlHook *scr_rl_hooks = NULL; static double scr_stream_rl_id(ScrClosure *cb) { return scr_box_get_f64(cb->caps[0]); } -static void scr_stream_rl_data(ScrClosure *cb, void *b, void *str) { +static void scr_stream_rl_data(ScrClosure *cb, void *b, void *str, void *value) { + if (b == NULL && str == NULL && value != NULL) { + scr_stream_value_consumer_fence("readline"); + return; + } if (b != NULL) scr_rl_input_bytes(scr_stream_rl_id(cb), (ScrBytes *)b); else if (str != NULL) scr_rl_input_str(scr_stream_rl_id(cb), (ScrStr *)str); } @@ -4778,7 +5692,7 @@ double scr_stream_rl_open(ScrStream *in, ScrStream *out, bool out_stdout, double h->next = scr_rl_hooks; scr_rl_hooks = h; scr_stream_rl_on(in, "error", h->error, scr_ee_inv_fixed1); - scr_stream_rl_on(in, "data", h->data, scr_ee_inv_fixed2); + scr_stream_rl_on(in, "data", h->data, scr_ee_inv_fixed3); scr_stream_rl_on(in, "end", h->end, scr_ee_inv_fixed0); scr_stream_rl_resume(in); return id; @@ -5304,13 +6218,174 @@ void scr_console_bind(ScrDyn *console, double which, ScrStream *stream) { inst->stream_drop = &scr_console_stream_drop; } +/* ── object mode ──────────────────────────────────────────────────────── */ + +/* The objectMode option (both sides) or a Duplex's readableObjectMode and + * writableObjectMode, applied right after construction: the readable + * side's entries are whole values (each counts 1, and the first push picks + * the representation), and the writable side queues values. The caller + * passes the object-mode high-water marks (16 by default). */ +void scr_stream_set_object_mode(ScrStream *s, bool readable, bool writable) { + ScrStreamState *st = s->st; + if (readable && st->has_r) { + st->r.object_entries = true; + st->r.object_mode_opt = true; + } + if (writable && st->has_w) st->w.object_mode = st->w.values = true; +} + +/* decodeStrings: false — string writes stay strings (scr_stream_write_string). */ +void scr_stream_set_decode_strings(ScrStream *s, bool decode) { + ScrStreamState *st = s->st; + if (decode || !st->has_w) return; + st->w.decode_strings_off = true; + st->w.values = true; +} + +ScrStream *scr_stream_decode_strings(ScrStream *s, bool decode) { + scr_stream_set_decode_strings(s, decode); + return scr_stream_retain(s); +} + +static void scr_stream_store_default_enc(ScrStreamState *st, ScrStr *enc /*moves*/) { + if (st->w.default_enc) scr_str_release(st->w.default_enc); + st->w.default_enc = NULL; + if ((enc->len == 4 && memcmp(enc->data, "utf8", 4) == 0) || + (enc->len == 5 && memcmp(enc->data, "utf-8", 5) == 0)) { + scr_str_release(enc); /* Node's kDefaultUTF8Encoding */ + return; + } + st->w.default_enc = enc; +} + +/* The defaultEncoding option on the writable side, a known encoding as + * given (borrowed; validated by the caller). */ +void scr_stream_set_write_encoding(ScrStream *s, ScrStr *enc) { + if (s->st->has_w) scr_stream_store_default_enc(s->st, scr_str_retain(enc)); +} + +ScrStream *scr_stream_write_encoding(ScrStream *s, ScrStr *enc) { + scr_stream_set_write_encoding(s, enc); + return scr_stream_retain(s); +} + +/* setDefaultEncoding(encoding): the name lowercased, a known encoding or + * ERR_UNKNOWN_ENCODING (thrown); answers the stream (+1). */ +ScrStream *scr_stream_set_default_encoding(ScrStream *s, ScrDyn *enc) { + ScrStr *raw = enc->kind == SCR_DYN_STR ? scr_str_retain(enc->v.str) : scr_dyn_string_coerce_js(enc); + ScrStr *lower = raw; + if (enc->kind == SCR_DYN_STR) { + char *buf = malloc(raw->len ? raw->len : 1); + if (!buf) scr_stream_oom(); + for (size_t i = 0; i < raw->len; i++) { + char c = raw->data[i]; + buf[i] = c >= 'A' && c <= 'Z' ? (char)(c - 'A' + 'a') : c; + } + lower = scr_str_new(buf, raw->len); + free(buf); + scr_str_release(raw); + } + ScrStr *canonical = scr_bytes_normalize_encoding(lower); + if (canonical == NULL) { + scr_str_release(lower); + return scr_stream_retain(s); + } + scr_str_release(canonical); + if (s->st->has_w) scr_stream_store_default_enc(s->st, lower); + else scr_str_release(lower); + return scr_stream_retain(s); +} + +/* stream.objectMode: scr_stream_set_object_mode, answering the receiver + * (+1). */ +ScrStream *scr_stream_object_mode(ScrStream *s, bool readable, bool writable) { + scr_stream_set_object_mode(s, readable, writable); + return scr_stream_retain(s); +} + +/* Whether the write and transform steps receive dyn values (an + * object-mode writable side): the compiler's chunk thunks read the chunk + * by this. */ +bool scr_stream_writes_values(ScrStream *s) { + return s->st->has_w && s->st->w.values; +} + +/* emit('data', value) with a checked-dynamic chunk: the 'data' slots by + * the value's tag (scr_stream_emit_data's ABI). Borrows its arguments. */ +bool scr_stream_emit_value(ScrStream *s, ScrStr *name, ScrDyn *v) { + ScrBytes *b = v->kind == SCR_DYN_BYTES ? v->v.bytes : NULL; + ScrStr *str = v->kind == SCR_DYN_STR ? v->v.str : NULL; + return scr_emitter_emit((ScrEmitter *)s, name, b, str, v); +} + +/* The chunk a compiled write or transform callback receives, by its + * declared type: as a Buffer (+1; on an object-mode side the value must + * be a Buffer, else a TypeError is thrown and NULL answered), as a dyn + * value (+1), and the encoding argument: 'buffer' on a byte-mode side, + * else what the write passed (undefined, null or a name). A parameter + * typed string receives the name, or "" for undefined and null; one typed + * otherwise receives the value (+1 each). */ +ScrBytes *scr_stream_chunk_bytes(ScrStream *s, ScrBytes *chunk) { + if (!scr_stream_writes_values(s)) return scr_bytes_retain(chunk); + ScrDyn *v = (ScrDyn *)chunk; + if (v->kind == SCR_DYN_BYTES) return scr_bytes_raw_view(v->v.bytes); + static const char msg[] = + "a stream callback declaring a Buffer chunk received an object-mode value that is not a Buffer"; + scr_throw_error_msg(SCR_ERR_TYPE, msg, sizeof msg - 1); + return NULL; +} + +ScrDyn *scr_stream_chunk_value(ScrStream *s, ScrBytes *chunk) { + if (scr_stream_writes_values(s)) return scr_dyn_retain((ScrDyn *)chunk); + return scr_dyn_new_buffer(chunk); +} + +ScrStr *scr_stream_chunk_encoding(ScrStream *s) { + if (!scr_stream_writes_values(s)) return scr_str_new("buffer", 6); + ScrDyn *enc = s->st->w.cur_enc; + if (enc && enc->kind == SCR_DYN_STR) return scr_str_retain(enc->v.str); + if (enc == NULL || enc->kind == SCR_DYN_NULL) return scr_str_new("", 0); + return scr_dyn_string_coerce_js(enc); +} + +ScrDyn *scr_stream_chunk_encoding_value(ScrStream *s) { + if (!scr_stream_writes_values(s)) { + ScrStr *name = scr_str_new("buffer", 6); + ScrDyn *d = scr_dyn_new_str(name); + scr_str_release(name); + return d; + } + ScrDyn *enc = s->st->w.cur_enc; + return enc ? scr_dyn_retain(enc) : scr_dyn_undefined(); +} + /* ── the readable surface ─────────────────────────────────────────────── */ bool scr_stream_push(ScrStream *s, ScrBytes *chunk) { return scr_stream_add_chunk(s, chunk, false); } +/* readable.push(chunk) from a program: in byte mode another + * ArrayBufferView becomes a Buffer over the same bytes + * (Stream._uint8ArrayToBuffer); the runtime's own producers push Buffers + * through scr_stream_push. */ +bool scr_stream_push_view(ScrStream *s, ScrBytes *chunk) { + if (chunk && !chunk->is_buffer && !(s->st->has_r && s->st->r.object_entries)) { + ScrBytes *b = scr_bytes_buffer_view(chunk, SCR_BYTES_U8, scr_bytes_byte_offset(chunk), true, + scr_bytes_byte_len(chunk)); + if (!b) return false; + b->is_buffer = true; + bool r = scr_stream_add_chunk(s, b, false); + scr_bytes_release(b); + return r; + } + return scr_stream_add_chunk(s, chunk, false); +} + bool scr_stream_push_str(ScrStream *s, ScrStr *str) { + /* object mode: the string is one whole entry, not converted */ + if (s->st->has_r && s->st->r.object_entries) + return scr_stream_add_entry(s, scr_str_retain(str), SCR_ENTRY_STR) > 0; ScrStr *enc = s->st->has_r ? s->st->r.push_enc : NULL; ScrBytes *b; if (enc != NULL) { @@ -5330,6 +6405,8 @@ bool scr_stream_push_str(ScrStream *s, ScrStr *str) { /* push(chunk, encoding) with an explicit non-utf8 literal: the per-call * encoding overrides the stream's default. Borrows both strings. */ bool scr_stream_push_str_enc(ScrStream *s, ScrStr *str, ScrStr *enc) { + /* object mode: the string is the chunk and the encoding is not used */ + if (s->st->has_r && s->st->r.object_entries) return scr_stream_push_str(s, str); ScrBytes *b = scr_stream_buffer(scr_bytes_from_str(str, enc)); bool ret = scr_stream_add_chunk(s, b, false); scr_bytes_release(b); @@ -5355,11 +6432,11 @@ bool scr_stream_push_null(ScrStream *s) { if (!st->r.ended) { /* onEofChunk flushes the decoder's held partial first (utf8's * replacement chars et al — Node's decoder.end() push). */ - if (st->r.encoded) { + if (st->r.encoded && !st->r.dyn_entries) { ScrStr *tail = scr_strdec_end(st->r.enc, st->r.dec_pending); st->r.dec_pending = 0; if (scr_str_utf16_len(tail) > 0) { - scr_stream_rbuf_push(st, tail, true, false); + scr_stream_rbuf_push(st, tail, SCR_ENTRY_STR, false); if (st->r.need_readable) scr_stream_emit_readable_nt(s); } else { scr_str_release(tail); @@ -5389,12 +6466,19 @@ void scr_stream_unshift(ScrStream *s, ScrBytes *chunk) { if (st->r.head_off > 0) { /* materialize the part-read head so the front slot is whole */ void *rest = scr_stream_rbuf_take(st, scr_stream_entry_len(st, st->r.buf[0]) - st->r.head_off); - scr_stream_rbuf_push(st, rest, st->r.encoded, true); + scr_stream_rbuf_push(st, rest, scr_stream_rkind(st), true); } scr_stream_add_chunk(s, chunk, true); } void scr_stream_unshift_str(ScrStream *s, ScrStr *str) { + if (s->st->has_r && s->st->r.object_entries) { + /* object mode: the string itself goes to the front */ + ScrDyn *v = scr_dyn_new_str(str); + scr_stream_unshift_dyn(s, v); + scr_dyn_release(v); + return; + } ScrBytes *b = scr_bytes_new(SCR_BYTES_U8, (double)str->len); memcpy(b->data, str->data, str->len); if (!str->ascii) scr_wtf8_to_utf8((char *)b->data, str->len); @@ -5403,6 +6487,46 @@ void scr_stream_unshift_str(ScrStream *s, ScrStr *str) { scr_bytes_release(b); } +/* unshift(value): null is the end of the stream (Node's onEofChunk); an + * object-mode stream takes any other value as one entry at the front; a + * byte-mode stream takes Buffers and strings, ignores undefined and + * reports another value as push does. Borrows d. */ +void scr_stream_unshift_dyn(ScrStream *s, const ScrDyn *d) { + ScrStreamState *st = s->st; + if (d->kind == SCR_DYN_NULL) { + scr_stream_push_null(s); + return; + } + if (st->has_r && st->r.object_entries) { + void *entry; + ScrEntryKind kind; + if (d->kind == SCR_DYN_STR) { + entry = scr_str_retain(d->v.str); + kind = SCR_ENTRY_STR; + } else if (d->kind == SCR_DYN_BYTES) { + entry = scr_bytes_raw_view(d->v.bytes); + kind = SCR_ENTRY_BYTES; + } else { + entry = scr_dyn_retain((ScrDyn *)d); + kind = SCR_ENTRY_DYN; + } + entry = scr_stream_entry_convert(st, entry, &kind); + scr_stream_rbuf_push(st, entry, kind, true); + if (st->r.need_readable) scr_stream_emit_readable_nt(s); + scr_stream_settle_next(s); + return; + } + if (d->kind == SCR_DYN_BYTES) { + ScrBytes *b = scr_bytes_raw_view(d->v.bytes); + scr_stream_unshift(s, b); + scr_bytes_release(b); + } else if (d->kind == SCR_DYN_STR) { + scr_stream_unshift_str(s, d->v.str); + } else { + scr_stream_push_dyn(s, d); + } +} + static void scr_stream_listener_error(ScrClosure *adapter, ScrError *error) { ScrDyn *fn = scr_dyn_listener_fn(adapter); ScrDyn *arg = scr_dyn_from_error(error); @@ -5412,9 +6536,9 @@ static void scr_stream_listener_error(ScrClosure *adapter, ScrError *error) { scr_dyn_release(fn); } -static void scr_stream_listener_data(ScrClosure *adapter, ScrBytes *bytes, ScrStr *string) { +static void scr_stream_listener_data(ScrClosure *adapter, ScrBytes *bytes, ScrStr *string, ScrDyn *value) { ScrDyn *fn = scr_dyn_listener_fn(adapter); - ScrDyn *arg = string ? scr_dyn_new_str(string) : scr_dyn_new_bytes(bytes); + ScrDyn *arg = value ? scr_dyn_retain(value) : string ? scr_dyn_new_str(string) : scr_dyn_new_bytes(bytes); ScrDyn *answer = scr_dyn_call(fn, &arg, 1, "listener"); scr_dyn_release(answer); scr_dyn_release(arg); @@ -5425,7 +6549,7 @@ ScrStream *scr_stream_on_dyn(ScrStream *s, ScrStr *name, ScrDyn *cb, bool once, if (name->len == 4 && !memcmp(name->data, "data", 4)) { return (ScrStream *)scr_emitter_on_dyn((ScrEmitter *)s, name, cb, scr_dyn_listener_closure_fn(cb, (void *)scr_stream_listener_data), - scr_ee_inv_fixed2, once, prepend); + scr_ee_inv_fixed3, once, prepend); } bool error = name->len == 5 && memcmp(name->data, "error", 5) == 0; bool empty = (name->len == 8 && memcmp(name->data, "readable", 8) == 0) || @@ -5449,13 +6573,15 @@ ScrStream *scr_stream_on_dyn(ScrStream *s, ScrStr *name, ScrDyn *cb, bool once, ScrDyn *scr_stream_read_dyn(ScrStream *s, ScrDyn *size) { double n = size && size->kind != SCR_DYN_UNDEF ? scr_dyn_number_coerce(size) : -1; if (scr_exc_pending()) return scr_dyn_undefined(); - bool is_str = false; - void *chunk = s->st->has_r ? scr_stream_read_n_kind(s, n, &is_str) : NULL; + ScrEntryKind kind = SCR_ENTRY_BYTES; + void *chunk = s->st->has_r ? scr_stream_read_n_kind(s, n, &kind) : NULL; if (!chunk) return scr_dyn_new_null(); - ScrDyn *result = is_str ? scr_dyn_new_str(chunk) : scr_dyn_new_buffer(chunk); - if (is_str) scr_str_release(chunk); - else scr_bytes_release(chunk); - return result; + if (kind == SCR_ENTRY_BYTES) { + ScrDyn *result = scr_dyn_new_buffer(chunk); + scr_bytes_release(chunk); + return result; + } + return scr_stream_entry_box(chunk, kind); } /* read() answers STRINGS once encoded: the static result type here is @@ -5472,13 +6598,28 @@ ScrBytes *scr_stream_read(ScrStream *s, double size) { /* a destroyed readable still DRAINS its buffer (Node: destroy leaves * buffered chunks readable; only _read refills are blocked) */ if (!s->st->has_r) return NULL; - if (s->st->r.encoded) { + if (s->st->r.encoded && !s->st->r.dyn_entries) { scr_stream_read_str_fence(); return NULL; } - bool is_str; - void *chunk = scr_stream_read_n_kind(s, size, &is_str); - if (chunk && is_str) { + ScrEntryKind kind; + void *chunk = scr_stream_read_n_kind(s, size, &kind); + if (chunk && kind == SCR_ENTRY_DYN) { + /* an object-mode value: a Buffer is the result, anything else is not */ + ScrDyn *d = chunk; + if (d->kind == SCR_DYN_BYTES) { + ScrBytes *b = scr_bytes_raw_view(d->v.bytes); + scr_dyn_release(d); + return b; + } + scr_dyn_release(d); + static const char msg[] = + "read() of an object-mode stream value that is not a Buffer is not supported yet in typed " + "code (consume 'data' events or for await)"; + scr_throw_error_msg(SCR_ERR_ERROR, msg, sizeof msg - 1); + return NULL; + } + if (chunk && kind == SCR_ENTRY_STR) { /* the read itself made the stream hold strings (a lazy Readable.from * pull's first string, or setEncoding() inside _read): the same * fence, never a string in the Buffer result */ @@ -5496,11 +6637,19 @@ ScrBytes *scr_stream_read(ScrStream *s, double size) { ScrStream *scr_stream_set_encoding(ScrStream *s, ScrStr *enc) { ScrStreamState *st = s->st; if (!st->has_r) return scr_stream_retain(s); + if (st->r.dyn_entries) { + /* an object-mode buffer of values: Buffers pushed later decode */ + if (st->r.enc) scr_str_release(st->r.enc); + st->r.enc = scr_str_retain(enc); + st->r.dec_pending = 0; + st->r.decoding = true; + return scr_stream_retain(s); + } if (st->r.encoded) { /* switching encodings mid-stream: fold the old decoder's pending * tail into the buffer first (rare; Node re-creates the decoder) */ ScrStr *tail = scr_strdec_end(st->r.enc, st->r.dec_pending); - if (scr_str_utf16_len(tail) > 0) scr_stream_rbuf_push(st, tail, true, false); + if (scr_str_utf16_len(tail) > 0) scr_stream_rbuf_push(st, tail, SCR_ENTRY_STR, false); else scr_str_release(tail); scr_str_release(st->r.enc); st->r.enc = scr_str_retain(enc); @@ -5556,7 +6705,7 @@ ScrStream *scr_stream_set_encoding(ScrStream *s, ScrStr *enc) { st->r.decoding = true; st->r.object_kind_set = true; if (content != NULL) { - if (scr_str_utf16_len(content) > 0) scr_stream_rbuf_push(st, content, true, false); + if (scr_str_utf16_len(content) > 0) scr_stream_rbuf_push(st, content, SCR_ENTRY_STR, false); else scr_str_release(content); } return scr_stream_retain(s); @@ -5628,7 +6777,8 @@ ScrStream *scr_stream_unpipe(ScrStream *src, ScrStream *dst) { /* ── the writable surface ─────────────────────────────────────────────── */ -static bool scr_stream_write_chunk(ScrStream *s, ScrBytes *chunk /*borrowed*/, ScrClosure *cb /*moves*/) { +static bool scr_stream_write_chunk_enc(ScrStream *s, ScrBytes *chunk /*borrowed*/, + ScrClosure *cb /*moves*/, ScrDyn *enc /*borrowed*/) { ScrStreamState *st = s->st; if (!st->has_w || st->destroyed || st->w.ending) { ScrError *e = st->has_w && !st->destroyed @@ -5639,12 +6789,12 @@ static bool scr_stream_write_chunk(ScrStream *s, ScrBytes *chunk /*borrowed*/, S scr_error_release(e); return false; } - size_t len = chunk->len; - st->w.length += len; + st->w.length += scr_stream_wchunk_len(st, chunk); + if (enc) enc = scr_dyn_retain(enc); if (st->w.writing || st->w.corked > 0 || st->constructing) { - scr_stream_wq_push(st, scr_bytes_retain(chunk), cb); + scr_stream_wq_push(st, scr_stream_wchunk_retain(st, chunk), cb, enc); } else { - scr_stream_do_write(s, scr_bytes_retain(chunk), cb); + scr_stream_do_write(s, scr_stream_wchunk_retain(st, chunk), cb, enc); } /* Node computes the answer AFTER the (possibly synchronous) write: * a sync completion has already drained its bytes from length. */ @@ -5653,8 +6803,98 @@ static bool scr_stream_write_chunk(ScrStream *s, ScrBytes *chunk /*borrowed*/, S return ret; } +static bool scr_stream_write_chunk(ScrStream *s, ScrBytes *chunk /*borrowed*/, ScrClosure *cb /*moves*/) { + return scr_stream_write_chunk_enc(s, chunk, cb, NULL); +} + +/* The encoding argument of a compiled write(chunk[, cb]) on an object-mode + * side: undefined, or null when the callback took its place (Node's + * write and end shift it there). */ +static ScrDyn *scr_stream_cb_enc(ScrClosure *cb) { return cb ? scr_dyn_new_null() : NULL; } + +/* write(value) on an object-mode writable side: the value is the chunk. + * Borrows v. */ +static bool scr_stream_write_value(ScrStream *s, ScrDyn *v, ScrClosure *cb) { + return scr_stream_write_chunk_enc(s, (ScrBytes *)v, cb, scr_stream_cb_enc(cb)); +} + +/* A Buffer write on a byte-mode side: with decodeStrings: false the + * queue holds values, so the Buffer is boxed with its 'buffer' encoding. + * Borrows chunk. */ +static bool scr_stream_write_buffer(ScrStream *s, ScrBytes *chunk, ScrClosure *cb) { + ScrStreamState *st = s->st; + if (!st->has_w || !st->w.values) return scr_stream_write_chunk(s, chunk, cb); + ScrDyn *v = chunk->is_buffer ? scr_dyn_new_buffer(chunk) : scr_dyn_new_bytes(chunk); + ScrStr *buffer = scr_str_new("buffer", 6); + ScrDyn *enc = scr_dyn_new_str(buffer); + scr_str_release(buffer); + bool ret = scr_stream_write_chunk_enc(s, (ScrBytes *)v, cb, enc); + scr_dyn_release(enc); + scr_dyn_release(v); + return ret; +} + +/* A string write on a byte-mode side, with the encoding argument as + * given (borrowed; NULL takes the default encoding): decodeStrings + * encodes it (Buffer.from(chunk, encoding)), and with decodeStrings: + * false it stays a string that _write receives with that encoding. */ +static bool scr_stream_write_string(ScrStream *s, ScrStr *str, ScrStr *name, ScrClosure *cb) { + ScrStreamState *st = s->st; + ScrStr *given = name ? scr_str_retain(name) : st->has_w && st->w.default_enc ? scr_str_retain(st->w.default_enc) : NULL; + if (st->has_w && st->w.decode_strings_off) { + ScrStr *e = given ? given : scr_str_new("utf8", 4); + ScrDyn *v = scr_dyn_new_str(str); + ScrDyn *enc = scr_dyn_new_str(e); + scr_str_release(e); + bool ret = scr_stream_write_chunk_enc(s, (ScrBytes *)v, cb, enc); + scr_dyn_release(enc); + scr_dyn_release(v); + return ret; + } + ScrBytes *b; + if (given) { + ScrStr *canonical = scr_bytes_normalize_encoding(given); + scr_str_release(given); + if (canonical == NULL) { + if (cb) scr_closure_release(cb); + return false; + } + b = scr_bytes_from_str(str, canonical); + scr_str_release(canonical); + } else { + b = scr_bytes_new(SCR_BYTES_U8, (double)str->len); + memcpy(b->data, str->data, str->len); + if (!str->ascii) scr_wtf8_to_utf8((char *)b->data, str->len); + } + scr_stream_buffer(b); + bool ret = scr_stream_write_buffer(s, b, cb); + scr_bytes_release(b); + return ret; +} + bool scr_stream_write(ScrStream *s, ScrBytes *chunk, ScrClosure *cb) { - return scr_stream_write_chunk(s, chunk, cb); + if (s->st->has_w && s->st->w.object_mode) { + ScrDyn *v = chunk->is_buffer ? scr_dyn_new_buffer(chunk) : scr_dyn_new_bytes(chunk); + bool ret = scr_stream_write_value(s, v, cb); + scr_dyn_release(v); + return ret; + } + if (!chunk->is_buffer) { + /* Writable's _write: a typed array or DataView chunk becomes a Buffer + * over the same bytes (Stream._uint8ArrayToBuffer), which _write, + * _writev and a decodeStrings: false queue receive. */ + ScrBytes *b = scr_bytes_buffer_view(chunk, SCR_BYTES_U8, scr_bytes_byte_offset(chunk), true, + scr_bytes_byte_len(chunk)); + if (!b) { + if (cb) scr_closure_release(cb); + return false; + } + b->is_buffer = true; + bool ret = scr_stream_write_buffer(s, b, cb); + scr_bytes_release(b); + return ret; + } + return scr_stream_write_buffer(s, chunk, cb); } /* write(null) reached at runtime (a nullable-union chunk's null arm): @@ -5667,19 +6907,70 @@ bool scr_stream_write_null(ScrStream *s) { } bool scr_stream_write_str(ScrStream *s, ScrStr *str, ScrClosure *cb) { - ScrBytes *b = scr_bytes_new(SCR_BYTES_U8, (double)str->len); - memcpy(b->data, str->data, str->len); - if (!str->ascii) scr_wtf8_to_utf8((char *)b->data, str->len); - scr_stream_buffer(b); - bool ret = scr_stream_write_chunk(s, b, cb); - scr_bytes_release(b); - return ret; + if (s->st->has_w && s->st->w.object_mode) { + /* object mode: the string itself, not converted */ + ScrDyn *v = scr_dyn_new_str(str); + bool ret = scr_stream_write_value(s, v, cb); + scr_dyn_release(v); + return ret; + } + return scr_stream_write_string(s, str, NULL, cb); +} + +/* write(chunk, encoding, cb) with the encoding argument as passed (NULL + * or undefined when absent): an object-mode side hands it to _write + * unchanged; a byte-mode side encodes a string chunk with it. Borrows + * chunk and enc. */ +bool scr_stream_write_enc(ScrStream *s, const ScrDyn *chunk, ScrDyn *enc, ScrClosure *cb) { + if (enc && enc->kind == SCR_DYN_UNDEF) enc = NULL; + ScrStreamState *st = s->st; + if (chunk->kind != SCR_DYN_NULL && st->has_w && st->w.object_mode) + return scr_stream_write_chunk_enc(s, (ScrBytes *)chunk, cb, enc); + /* Node's _write: an encoding other than 'buffer' must be a known one + * (ERR_UNKNOWN_ENCODING, thrown), and a string chunk is encoded with + * it; an empty or nullish encoding is the default */ + ScrStr *name = NULL; + if (enc && enc->kind != SCR_DYN_NULL && !(enc->kind == SCR_DYN_STR && enc->v.str->len == 0)) + name = scr_dyn_string_coerce_js(enc); + if (name && !(name->len == 6 && memcmp(name->data, "buffer", 6) == 0)) { + ScrStr *canonical = scr_bytes_normalize_encoding(name); + if (canonical == NULL) { + scr_str_release(name); + if (cb) scr_closure_release(cb); + return false; + } + scr_str_release(canonical); + bool ret = chunk->kind == SCR_DYN_STR ? scr_stream_write_string(s, chunk->v.str, name, cb) + : scr_stream_write_dyn(s, chunk, cb); + scr_str_release(name); + return ret; + } + if (name && chunk->kind == SCR_DYN_STR) { + /* Buffer.from(string, 'buffer') */ + scr_str_release(name); + if (cb) scr_closure_release(cb); + static const char msg[] = "Unknown encoding: buffer"; + scr_throw_error_msg_code(SCR_ERR_TYPE, msg, sizeof msg - 1, "ERR_UNKNOWN_ENCODING"); + return false; + } + if (name) scr_str_release(name); + return scr_stream_write_dyn(s, chunk, cb); } ScrStream *scr_stream_end(ScrStream *s, ScrBytes *chunk_b, ScrStr *chunk_s, ScrClosure *cb) { ScrStreamState *st = s->st; - if (chunk_b) scr_stream_write(s, chunk_b, NULL); - else if (chunk_s) scr_stream_write_str(s, chunk_s, NULL); + if ((chunk_b || chunk_s) && st->has_w && st->w.object_mode) { + /* end(chunk[, cb]) writes with the encoding Node's end leaves: + * undefined, or null when the callback took its place */ + ScrDyn *v = chunk_s ? scr_dyn_new_str(chunk_s) + : chunk_b->is_buffer ? scr_dyn_new_buffer(chunk_b) : scr_dyn_new_bytes(chunk_b); + scr_stream_write_chunk_enc(s, (ScrBytes *)v, NULL, scr_stream_cb_enc(cb)); + scr_dyn_release(v); + } else if (chunk_b) { + scr_stream_write(s, chunk_b, NULL); + } else if (chunk_s) { + scr_stream_write_str(s, chunk_s, NULL); + } if (!st->has_w || st->destroyed) { if (cb) scr_closure_release(cb); return scr_stream_retain(s); @@ -5759,7 +7050,12 @@ void scr_stream_write_done(ScrStream *s, ScrError *err /*moves*/) { return; } if (was_sync) { + bool hold = ucb != NULL || (st->w.need_drain && st->w.length == 0) || st->destroyed; scr_st_tick(s, SCR_ST_AFTER_WRITE, NULL, ucb); + if (hold) { + scr_st_tail->hold = true; + st->w.after_holds++; + } } else { scr_stream_after_write(s, ucb); } @@ -5800,11 +7096,26 @@ void scr_stream_destroy_done(ScrStream *s, ScrError *err /*moves*/) { } } +/* Transform._write's callback after the transform pushed its output: + * on a tick once the readable side has ended, at once when the writable + * side has ended, the transform pushed nothing, or the readable buffer is + * below its high-water mark, and otherwise when the readable side next + * reads (Transform._read). */ +static void scr_stream_transform_callback(ScrStream *s) { + ScrStreamState *st = s->st; + if (st->r.ended) scr_st_tick(s, SCR_ST_XF_DONE, NULL, NULL); + else if (st->w.ending || st->xf_length == st->r.length || st->r.length < st->r.hwm) + scr_stream_write_done(s, NULL); + else st->xf_held = true; +} + void scr_stream_transform_done(ScrStream *s, ScrError *err /*moves*/, ScrBytes *data /*moves*/, ScrStr *data_str /*moves*/) { if (!err) { if (data) { scr_stream_add_chunk(s, data, false); + } else if (data_str && s->st->r.object_entries) { + scr_stream_push_str(s, data_str); /* object mode: the string itself */ } else if (data_str) { ScrBytes *b = scr_bytes_new(SCR_BYTES_U8, (double)data_str->len); memcpy(b->data, data_str->data, data_str->len); @@ -5820,7 +7131,8 @@ void scr_stream_transform_done(ScrStream *s, ScrError *err /*moves*/, ScrBytes * if (err) scr_error_release(err); return; } - scr_stream_write_done(s, err); + if (err) scr_stream_write_done(s, err); + else scr_stream_transform_callback(s); } void scr_stream_flush_done(ScrStream *s, ScrError *err /*moves*/, ScrBytes *data /*moves*/, @@ -5837,6 +7149,9 @@ void scr_stream_flush_done(ScrStream *s, ScrError *err /*moves*/, ScrBytes *data if (data) { scr_stream_add_chunk(s, data, false); scr_bytes_release(data); + } else if (data_str && st->r.object_entries) { + scr_stream_push_str(s, data_str); /* object mode: the string itself */ + scr_str_release(data_str); } else if (data_str) { ScrBytes *b = scr_bytes_new(SCR_BYTES_U8, (double)data_str->len); memcpy(b->data, data_str->data, data_str->len); @@ -5852,6 +7167,38 @@ void scr_stream_flush_done(ScrStream *s, ScrError *err /*moves*/, ScrBytes *data scr_stream_finish_maybe(s); } +/* The transform and flush completions with a checked-dynamic value (an + * object-mode Transform's data, or an untyped callback's): null and + * undefined push nothing (Transform's `val != null`), and any other value + * is pushed as push(value) pushes it. v borrowed (NULL: absent). */ +static bool scr_stream_done_pushes(const ScrDyn *v) { + return v && v->kind != SCR_DYN_NULL && v->kind != SCR_DYN_UNDEF; +} + +void scr_stream_transform_done_value(ScrStream *s, ScrError *err /*moves*/, ScrDyn *v) { + if (!err && scr_stream_done_pushes(v)) scr_stream_push_dyn(s, v); + if (scr_exc_pending()) { + if (err) scr_error_release(err); + return; + } + if (err) scr_stream_write_done(s, err); + else scr_stream_transform_callback(s); +} + +void scr_stream_flush_done_value(ScrStream *s, ScrError *err /*moves*/, ScrDyn *v) { + s->st->flush_pending = false; + if (err) { + scr_stream_error_or_destroy(s, err); + scr_error_release(err); + return; + } + if (scr_stream_done_pushes(v)) scr_stream_push_dyn(s, v); + if (scr_exc_pending()) return; + scr_stream_push_null(s); + if (scr_exc_pending()) return; + scr_stream_finish_maybe(s); +} + /* ── destroy ──────────────────────────────────────────────────────────── */ /* Node's _destroy step: the destroy hook, or 'error'/'close' on ticks. */ @@ -5937,6 +7284,7 @@ double scr_stream_prop(ScrStream *s, const char *name) { if (strcmp(name, "readableLength") == 0) return (double)st->r.length; if (strcmp(name, "readableHighWaterMark") == 0) return (double)st->r.hwm; if (strcmp(name, "readableObjectMode") == 0) return st->r.object_entries; + if (strcmp(name, "writableObjectMode") == 0) return st->w.object_mode; if (strcmp(name, "writable") == 0) { return st->has_w && !st->destroyed && !st->w.ending && !st->errored; } @@ -5978,7 +7326,7 @@ double scr_stream_prop(ScrStream *s, const char *name) { if (strcmp(p, "destroyed") == 0) return st->destroyed; if (strcmp(p, "errorEmitted") == 0) return st->error_emitted; if (strcmp(p, "needDrain") == 0) return st->w.need_drain; - if (strcmp(p, "objectMode") == 0) return 0; + if (strcmp(p, "objectMode") == 0) return st->w.object_mode; if (strcmp(p, "constructed") == 0) return 1; if (strcmp(p, "closed") == 0) return st->close_emitted; if (strcmp(p, "length") == 0) return (double)st->w.length; @@ -6013,8 +7361,41 @@ static void scr_stream_emit_readable_now(ScrStream *s) { /* ── tick dispatch ────────────────────────────────────────────────────── */ /* onConstruct + the readable/writable onConstructed hooks. err moves. */ +/* aggregateTwoErrors(inner, outer) for streams without native ops: both + * present and distinct make an AggregateError([outer, inner]) with + * outer's message and code. Borrows both; +1 or NULL. */ +static ScrError *scr_stream_aggregate_errors(ScrError *inner, ScrError *outer) { + if (inner && outer && inner != outer) { + ScrDyn *message = scr_dyn_new_str(outer->message); + ScrError *agg = scr_aggregate_new(message, scr_dyn_undefined()); + scr_dyn_release(message); + if (agg == NULL) return scr_error_retain(outer); + ScrDyn *outer_value = scr_dyn_from_error(outer); + ScrDyn *list = scr_dyn_new_arr(); + scr_dyn_arr_push(list, scr_dyn_retain(outer_value)); + scr_dyn_arr_push(list, scr_dyn_from_error(inner)); + scr_aggregate_set_errors(agg, list); + scr_dyn_release(list); + ScrDyn *code = scr_dyn_obj_read(outer_value, "code", 4); + if (code && code->kind == SCR_DYN_STR) scr_error_set_code(agg, code->v.str->data); + scr_dyn_release(code); + scr_dyn_release(outer_value); + return agg; + } + ScrError *one = outer ? outer : inner; + return one ? scr_error_retain(one) : NULL; +} + static void scr_stream_constructed(ScrStream *s, ScrError *err) { ScrStreamState *st = s->st; + if (st->construct_finished) { + /* onConstruct called again: errorOrDestroy(err ?? ERR_MULTIPLE_CALLBACK) */ + if (!err) err = scr_stream_mkerr("ERR_MULTIPLE_CALLBACK", "Callback called multiple times"); + scr_stream_error_or_destroy(s, err); + scr_error_release(err); + return; + } + st->construct_finished = true; st->constructing = false; if (st->construct_cb) { scr_closure_release(st->construct_cb); @@ -6027,8 +7408,9 @@ static void scr_stream_constructed(ScrStream *s, ScrError *err) { /* aggregateTwoErrors(constructError, destroyError): the owner builds * the AggregateError when both are present and distinct */ ScrError *use; - if (err && derr && err != derr && st->native_ops && st->native_ops->aggregate) { - use = st->native_ops->aggregate(err, derr); + if (err && derr && err != derr) { + use = st->native_ops && st->native_ops->aggregate ? st->native_ops->aggregate(err, derr) + : scr_stream_aggregate_errors(err, derr); } else { use = derr ? derr : err; if (use) scr_error_retain(use); @@ -6067,6 +7449,39 @@ void scr_stream_construct_done(ScrStream *s, ScrError *err /*moves*/) { void scr_stream_set_writev_concat(ScrStream *s) { s->st->writev_concat = true; } +/* A user construct option or _construct method: Node schedules it from the + * constructor (construct(stream, cb)), and the hook's callback reports + * through scr_stream_construct_done. */ +void scr_stream_set_construct(ScrStream *s, ScrClosure *cb /*moves*/, ScrStreamPlainInv inv) { + if (s->st->construct_cb || s->st->construct_finished) { + scr_closure_release(cb); + return; + } + scr_stream_construct(s, cb, inv); +} + +/* A class's _writev under options that may carry their own writev (the + * option, an instance property in Node, wins). */ +void scr_stream_set_writev_default(ScrStream *s, ScrClosure *cb /*moves*/, ScrStreamWritevInv inv) { + if (s->st->has_w && s->st->w.writev_cb == NULL) { + scr_stream_set_writev(s, cb, inv); + return; + } + scr_closure_release(cb); +} + +/* A user writev option or _writev method. */ +void scr_stream_set_writev(ScrStream *s, ScrClosure *cb /*moves*/, ScrStreamWritevInv inv) { + ScrStreamState *st = s->st; + if (!st->has_w) { + scr_closure_release(cb); + return; + } + if (st->w.writev_cb) scr_closure_release(st->w.writev_cb); + st->w.writev_cb = cb; + st->w.writev_inv = inv; +} + void scr_stream_fail(ScrStream *s, ScrError *err) { scr_stream_error_or_destroy(s, err); } static void scr_stream_plain_inv(ScrClosure *cb, va_list ap) { @@ -6171,8 +7586,12 @@ static void scr_stream_run_tick(ScrStreamTick *t) { } break; } + case SCR_ST_XF_DONE: + if (st->w.writing) scr_stream_write_done(s, NULL); + break; case SCR_ST_AFTER_WRITE: { st->w.after_scheduled = false; + if (t->hold) st->w.after_holds--; ScrClosure *cb = t->cb; t->cb = NULL; if (!st->destroyed) { @@ -6236,6 +7655,13 @@ static void scr_stream_run_tick(ScrStreamTick *t) { if (!st->close_emitted) { st->close_emitted = true; if (st->emit_close) scr_stream_emit0(s, "close"); + if (st->r.next_eof_close && !scr_exc_pending()) { + /* the iterator's eos 'close' listener completes the loop */ + st->r.next_eof_close = false; + ScrPromise *w = st->r.next_waiter; + st->r.next_waiter = NULL; + if (w) scr_stream_next_fulfill(st, w, NULL, SCR_ENTRY_BYTES); + } /* eos ordering: the finished()/pipeline watchers fire right after * 'close' (Node's willEmitClose stance). */ scr_stream_notify_finished(s); @@ -6247,6 +7673,7 @@ static void scr_stream_run_tick(ScrStreamTick *t) { if (st->r.read_cb) { scr_closure_release(st->r.read_cb); st->r.read_cb = NULL; } if (st->w.write_cb) { scr_closure_release(st->w.write_cb); st->w.write_cb = NULL; } if (st->w.final_cb) { scr_closure_release(st->w.final_cb); st->w.final_cb = NULL; } + if (st->w.writev_cb) { scr_closure_release(st->w.writev_cb); st->w.writev_cb = NULL; } if (st->transform_cb) { scr_closure_release(st->transform_cb); st->transform_cb = NULL; } if (st->flush_cb) { scr_closure_release(st->flush_cb); st->flush_cb = NULL; } if (st->destroy_cb) { scr_closure_release(st->destroy_cb); st->destroy_cb = NULL; } @@ -6282,9 +7709,9 @@ static void scr_stream_run_tick(ScrStreamTick *t) { } case SCR_ST_READ0: { if (st->has_r) { - bool is_str; - void *chunk = scr_stream_read_n_kind(s, 0, &is_str); - if (chunk) scr_stream_entry_release_kind(chunk, is_str); + ScrEntryKind kind; + void *chunk = scr_stream_read_n_kind(s, 0, &kind); + if (chunk) scr_stream_entry_release_kind(chunk, kind); } break; } @@ -6301,7 +7728,11 @@ static void scr_stream_run_tick(ScrStreamTick *t) { scr_stream_error_buffer(s); break; case SCR_ST_CONSTRUCT: { - if (st->construct_cb) st->construct_inv(st->construct_cb, s); + if (st->construct_cb) { + st->construct_inv(st->construct_cb, s); + /* a throw inside _construct reaches onConstruct on a tick */ + if (scr_exc_pending()) scr_stream_construct_done(s, scr_stream_take_error()); + } break; } case SCR_ST_CONSTRUCTED: { @@ -6311,10 +7742,13 @@ static void scr_stream_run_tick(ScrStreamTick *t) { break; } case SCR_ST_NEXT_EOF: { - if (st->r.next_waiter && st->r.length == 0 && (st->r.ended || st->destroyed)) { + if (st->r.next_waiter && st->r.length == 0 && st->r.ended && st->r.next_close_wait && + !st->close_emitted) { + st->r.next_eof_close = true; + } else if (st->r.next_waiter && st->r.length == 0 && (st->r.ended || st->destroyed)) { ScrPromise *w = st->r.next_waiter; st->r.next_waiter = NULL; - scr_stream_next_fulfill(st, w, NULL, false); + scr_stream_next_fulfill(st, w, NULL, SCR_ENTRY_BYTES); } else if (st->r.next_waiter) { scr_stream_settle_next(s); /* content raced in: deliver it */ } @@ -6369,8 +7803,11 @@ static void scr_stream_dispatch(void) { } } +static const ScrHandleStreamHooks scr_handle_stream_hooks_impl; + void scr_stream_install(void) { scr_emitter_on_hook = &scr_stream_on_listener; + scr_handle_stream_hooks = &scr_handle_stream_hooks_impl; scr_loop_set_stream(&scr_stream_ticks_pending, &scr_stream_dispatch); } @@ -6409,23 +7846,140 @@ void scr_stream_worker_stdio(void) { #endif } -static ScrStream *scr_stream_view_receiver(const ScrDyn *value) { - if (value->kind == SCR_DYN_TYPED_REF && value->v.typed_ref.type_key_len > 7 && - !memcmp(value->v.typed_ref.type_key, "object:", 7)) { - ScrStream *stream = scr_dyn_typed_ref_unbox(value); - const ScrVt *vt = scr_stream_vt_of(stream); - if (vt && ((vt->pre >= scr_readable_vt.pre && vt->pre <= scr_readable_vt.post) || - (vt->pre >= scr_writable_vt.pre && vt->pre <= scr_writable_vt.post))) return stream; - value->v.typed_ref.release(stream); +/* ── handles that are Transforms (Cipheriv, Decipheriv) ────────────────── + * A Transform handle (ScrDynHandleOps.transform) used as a stream gets one + * native Transform, built here on first use and kept in the handle's + * slot. Its steps share the handle (held, and traced: the handle and its + * stream form a cycle the collector reclaims) and the handle's static + * ops: each chunk goes through the handle's update(), and the flush pushes + * final() or reports its error. */ + +static void *scr_handle_ops_retain(void *p) { return p; } +static void scr_handle_ops_release(void *p) { (void)p; } + +static const ScrDynHandleOps *scr_handle_step_handle_ops(ScrClosure *cb) { + return scr_box_get_ref(cb->caps[1]); +} + +/* The step's handle, borrowed: scr_box_get_ref answers +1, and the box + * keeps the handle alive. */ +static void *scr_handle_step_handle(ScrClosure *cb) { + void *h = scr_box_get_ref(cb->caps[0]); + scr_handle_step_handle_ops(cb)->release(h); + return h; +} + +static const ScrDynHandleTransform *scr_handle_step_ops(ScrClosure *cb) { + return scr_handle_step_handle_ops(cb)->transform; +} + +static void scr_handle_step_transform(ScrClosure *cb, ScrStream *s, ScrBytes *chunk) { + /* A throwing update() leaves the exception pending: it throws out of + * the write, as Node's _transform does. */ + ScrBytes *out = scr_handle_step_ops(cb)->update(scr_handle_step_handle(cb), chunk); + if (out) scr_stream_transform_done(s, NULL, out, NULL); +} + +static void scr_handle_step_flush(ScrClosure *cb, ScrStream *s) { + ScrBytes *out = scr_handle_step_ops(cb)->final(scr_handle_step_handle(cb)); + scr_stream_flush_done(s, out ? NULL : scr_stream_take_error(), out, NULL); +} + +static void scr_handle_step_destroy(ScrClosure *cb, ScrStream *s, ScrError *err) { + (void)cb; + scr_stream_destroy_done(s, err ? scr_error_retain(err) : NULL); +} + +static ScrClosure *scr_handle_step(const ScrDynHandleOps *ops, void *h) { + ScrClosure *step = scr_closure_new(NULL, 2); + step->caps[0] = scr_box_new_obj(ops->retain, ops->release, ops->transform->trace); + scr_box_set_ref(step->caps[0], ops->retain(h)); + step->caps[1] = scr_box_new_obj(scr_handle_ops_retain, scr_handle_ops_release, NULL); + scr_box_set_ref(step->caps[1], (void *)ops); + return step; +} + +/* The Transform of handle h (+1), built on first use. */ +static ScrStream *scr_handle_transform(const ScrDynHandleOps *ops, void *h) { + const ScrDynHandleTransform *t = ops->transform; + ScrStream *s = t->stream(h); + if (!s) { + s = scr_stream_new_transform(-1, -1, true, true, true, true, true, + scr_handle_step(ops, h), scr_handle_step_transform, + scr_handle_step(ops, h), scr_handle_step_flush, + scr_handle_step(ops, h), scr_handle_step_destroy); + s->cls = ops->cls; + t->set_stream(h, s, scr_stream_release_v); } + return scr_stream_retain(s); +} + +/* The native stream of a checked-dynamic Transform handle (+1), or NULL + * when the value is not one. */ +ScrStream *scr_stream_of_handle(const ScrDyn *value) { + if (value->kind != SCR_DYN_HANDLE) return NULL; + const ScrDynHandleOps *ops = scr_dyn_handle_ops_of(value); + return ops->transform ? scr_handle_transform(ops, value->v.handle.ptr) : NULL; +} + +/* A boxed native stream (+1), or NULL for any other value. */ +static ScrStream *scr_stream_boxed(const ScrDyn *value) { + if (value->kind != SCR_DYN_TYPED_REF || value->v.typed_ref.type_key_len <= 7 || + memcmp(value->v.typed_ref.type_key, "object:", 7) != 0) + return NULL; + ScrStream *stream = scr_dyn_typed_ref_unbox(value); + const ScrVt *vt = scr_stream_vt_of(stream); + if (vt && ((vt->pre >= scr_readable_vt.pre && vt->pre <= scr_readable_vt.post) || + (vt->pre >= scr_writable_vt.pre && vt->pre <= scr_writable_vt.post))) + return stream; + value->v.typed_ref.release(stream); + return NULL; +} + +/* The native readable stream behind a checked-dynamic value (+1): a + * boxed stream or a Cipheriv/Decipheriv handle's Transform, or NULL. */ +ScrStream *scr_stream_native_readable_of_dyn(const ScrDyn *value) { + ScrStream *s = scr_stream_of_handle(value); + if (!s) s = scr_stream_boxed(value); + if (s && !s->st->has_r) { + scr_stream_release(s); + return NULL; + } + return s; +} + +/* stream.handleStream: the stream of a value typed as a stream handle + * class (a Cipheriv or Decipheriv), +1. A value of that type can also be + * the stream itself, boxed (the stream addAbortSignal answers). */ +ScrStream *scr_stream_handle(const ScrDyn *value) { + ScrStream *stream = scr_stream_of_handle(value); + if (!stream) stream = scr_stream_boxed(value); + if (stream) return stream; + static const char message[] = "Stream use of a value that is not a native stream has no lowering"; + scr_throw_error_msg_code(SCR_ERR_ERROR, message, sizeof message - 1, "SC2020"); + return NULL; +} + +static ScrStream *scr_stream_view_receiver(const ScrDyn *value) { + ScrStream *stream = scr_stream_of_handle(value); + if (!stream) stream = scr_stream_boxed(value); + if (stream) return stream; scr_dyn_arg_type_fail("destination", "an instance of Stream", value); return NULL; } -static ScrDyn *scr_stream_view_call(ScrClosure *cb, ScrDyn *const *args, size_t argc) { - ScrStream *stream = scr_box_get_ref(cb->caps[0]); - ScrStr *name = scr_box_get_ref(cb->caps[1]); - const char *method = name->data; +/* The members a native stream answers to checked-dynamic calls. */ +static const char *const scr_stream_dyn_methods[] = { + "on", "once", "addListener", "prependListener", "prependOnceListener", + "off", "removeListener", "pipe", "unpipe", "read", "pause", "resume", "isPaused", + "setEncoding", "write", "end", "destroy", "cork", "uncork", +}; + +/* A checked-dynamic call of one of a native stream's members (borrowed + * stream): the result, +1, with `this` results answering `self`, or the + * current `this` when self is NULL. */ +static ScrDyn *scr_stream_dyn_call(ScrStream *stream, ScrDyn *self, const char *method, + ScrDyn *const *args, size_t argc) { ScrDyn *result = NULL; ScrDyn *first = argc ? args[0] : scr_dyn_undefined(); if (!strcmp(method, "on") || !strcmp(method, "once") || !strcmp(method, "addListener") || @@ -6501,21 +8055,72 @@ static ScrDyn *scr_stream_view_call(ScrClosure *cb, ScrDyn *const *args, size_t scr_error_release(error); } else if (!strcmp(method, "cork")) scr_stream_cork(stream); else if (!strcmp(method, "uncork")) scr_stream_uncork(stream); - if (!result && !scr_exc_pending()) result = scr_dyn_this_get(); + if (!result && !scr_exc_pending()) result = self ? scr_dyn_retain(self) : scr_dyn_this_get(); + return result; +} + +static ScrDyn *scr_stream_view_call(ScrClosure *cb, ScrDyn *const *args, size_t argc) { + ScrStream *stream = scr_box_get_ref(cb->caps[0]); + ScrStr *name = scr_box_get_ref(cb->caps[1]); + ScrDyn *result = scr_stream_dyn_call(stream, NULL, name->data, args, argc); scr_str_release(name); scr_stream_release(stream); return result; } +/* ScrHandleStreamHooks.call: a member a native stream answers to + * checked-dynamic calls, on the handle's Transform. Members that answer + * the stream answer `self`. */ +static bool scr_handle_stream_call(const ScrDynHandleOps *ops, void *h, ScrDyn *self, + const char *method, ScrDyn *const *args, size_t argc, + ScrDyn **result) { + for (size_t i = 0; i < sizeof scr_stream_dyn_methods / sizeof *scr_stream_dyn_methods; i++) { + if (strcmp(method, scr_stream_dyn_methods[i]) != 0) continue; + ScrStream *stream = scr_handle_transform(ops, h); + *result = scr_stream_dyn_call(stream, self, method, args, argc); + scr_stream_release(stream); + return true; + } + return false; +} + +/* The stream properties a checked-dynamic read answers. */ +static const char *const scr_stream_dyn_properties[] = { + "readable", "readableEnded", "readableLength", "readableHighWaterMark", + "writable", "writableEnded", "writableFinished", "writableLength", "writableHighWaterMark", + "writableNeedDrain", "destroyed", "closed", +}; + +static ScrDyn *scr_stream_dyn_property(ScrStream *stream, const char *name) { + double value = scr_stream_prop(stream, name); + bool number = strstr(name, "Length") || strstr(name, "HighWaterMark"); + return number ? scr_dyn_new_num(value) : scr_dyn_new_bool(value != 0); +} + +/* ScrHandleStreamHooks.get: a stream property of the handle's Transform. */ +static ScrDyn *scr_handle_stream_get(const ScrDynHandleOps *ops, void *h, const char *key, + size_t key_len) { + for (size_t i = 0; i < sizeof scr_stream_dyn_properties / sizeof *scr_stream_dyn_properties; i++) { + const char *name = scr_stream_dyn_properties[i]; + if (strlen(name) != key_len || memcmp(name, key, key_len) != 0) continue; + ScrStream *stream = scr_handle_transform(ops, h); + ScrDyn *value = scr_stream_dyn_property(stream, name); + scr_stream_release(stream); + return value; + } + return NULL; +} + +static const ScrHandleStreamHooks scr_handle_stream_hooks_impl = { + scr_handle_stream_call, + scr_handle_stream_get, +}; + ScrDyn *scr_stream_dyn_view(ScrStream *stream) { ScrDyn *view = scr_dyn_new_obj(); ScrDyn *prototype = scr_dyn_new_obj(); - static const char *const methods[] = { - "on", "once", "addListener", "prependListener", "prependOnceListener", - "off", "removeListener", "pipe", "unpipe", "read", "pause", "resume", "isPaused", - "setEncoding", "write", "end", "destroy", "cork", "uncork", - }; - for (size_t i = 0; i < sizeof methods / sizeof *methods; i++) { + const char *const *methods = scr_stream_dyn_methods; + for (size_t i = 0; i < sizeof scr_stream_dyn_methods / sizeof *scr_stream_dyn_methods; i++) { ScrClosure *cb = scr_closure_new((void *)scr_stream_view_call, 2); cb->caps[0] = scr_box_new_obj(scr_stream_retain_v, scr_stream_release_v, scr_stream_trace); cb->caps[1] = scr_box_new(SCR_BOX_STR); @@ -6524,16 +8129,9 @@ ScrDyn *scr_stream_dyn_view(ScrStream *stream) { scr_dyn_obj_set(prototype, methods[i], strlen(methods[i]), scr_dyn_new_func(cb, scr_stream_view_call, 0, "native stream method", methods[i])); } - static const char *const properties[] = { - "readable", "readableEnded", "readableLength", "readableHighWaterMark", - "writable", "writableEnded", "writableFinished", "writableLength", "writableHighWaterMark", - "writableNeedDrain", "destroyed", "closed", - }; - for (size_t i = 0; i < sizeof properties / sizeof *properties; i++) { - double value = scr_stream_prop(stream, properties[i]); - bool number = strstr(properties[i], "Length") || strstr(properties[i], "HighWaterMark"); - scr_dyn_obj_set(view, properties[i], strlen(properties[i]), - number ? scr_dyn_new_num(value) : scr_dyn_new_bool(value != 0)); + for (size_t i = 0; i < sizeof scr_stream_dyn_properties / sizeof *scr_stream_dyn_properties; i++) { + const char *name = scr_stream_dyn_properties[i]; + scr_dyn_obj_set(view, name, strlen(name), scr_stream_dyn_property(stream, name)); } if (stream->st->native && stream->st->native_ops && stream->st->native_ops->view) { ScrClosure *cb = scr_closure_new((void *)scr_stream_view_call, 2); @@ -6712,17 +8310,13 @@ ScrStream *scr_stream_pipe_general(ScrStream *src, ScrStream *dst, bool end) { /* A pipeline() stage that arrives as a checked-dynamic value (the * stream.unboxDyn libCall): a boxed native stream unwraps by identity - * (+1); any other value throws the compiled program's not-supported - * message (Node also takes iterables and functions there). */ + * (+1), a stream handle (a Cipheriv or Decipheriv) answers its stream, and + * any other value throws the compiled program's not-supported message + * (Node also takes iterables and functions there). */ ScrStream *scr_stream_unbox_dyn(const ScrDyn *value, const ScrStr *message) { - if (value->kind == SCR_DYN_TYPED_REF && value->v.typed_ref.type_key_len > 7 && - !memcmp(value->v.typed_ref.type_key, "object:", 7)) { - ScrStream *stream = scr_dyn_typed_ref_unbox(value); - const ScrVt *vt = scr_stream_vt_of(stream); - if (vt && ((vt->pre >= scr_readable_vt.pre && vt->pre <= scr_readable_vt.post) || - (vt->pre >= scr_writable_vt.pre && vt->pre <= scr_writable_vt.post))) return stream; - value->v.typed_ref.release(stream); - } + ScrStream *stream = scr_stream_of_handle(value); + if (!stream) stream = scr_stream_boxed(value); + if (stream) return stream; scr_throw_error_msg_code(SCR_ERR_ERROR, message->data, message->len, "SC2020"); return NULL; } diff --git a/packages/runtime/src/scr_stream.h b/packages/runtime/src/scr_stream.h index 99f58331c..d26077b5c 100644 --- a/packages/runtime/src/scr_stream.h +++ b/packages/runtime/src/scr_stream.h @@ -65,6 +65,8 @@ typedef void (*ScrStreamReadInv)(ScrClosure *cb, ScrStream *s, double size); typedef void (*ScrStreamChunkInv)(ScrClosure *cb, ScrStream *s, ScrBytes *chunk); typedef void (*ScrStreamPlainInv)(ScrClosure *cb, ScrStream *s); typedef void (*ScrStreamErrInv)(ScrClosure *cb, ScrStream *s, ScrError *err); +/* writev(chunks, callback): chunks is the batch's dyn array (borrowed). */ +typedef void (*ScrStreamWritevInv)(ScrClosure *cb, ScrStream *s, struct ScrDyn *chunks); /* Constructors (+1 result; option callbacks MOVE; NULL = absent). hwm < 0 * means the byte default (65536 — Node 24's getDefaultHighWaterMark). */ @@ -143,6 +145,13 @@ ScrStream *scr_stream_pipe_general(ScrStream *src, ScrStream *dst, bool end); /* A boxed native stream out of a checked-dynamic pipeline stage (+1), or * NULL with `message` thrown as the not-supported Error. */ ScrStream *scr_stream_unbox_dyn(const struct ScrDyn *value, const ScrStr *message); +/* Handles that are Transforms (ScrDynHandleOps.transform: Cipheriv and + * Decipheriv). scr_stream_of_handle: the handle's Transform (+1), built on + * first use, or NULL when the value is not such a handle. + * stream.handleStream: the same, throwing the coded SC2020 error for any + * other value. */ +ScrStream *scr_stream_of_handle(const struct ScrDyn *value); +ScrStream *scr_stream_handle(const struct ScrDyn *value); /* Checked-dynamic stream slots (scr_stream_dyn.c): the native stream a * value boxes with the requested side (1 readable, 2 writable; +1, or * NULL), and readable.pipe()/unpipe() for a destination that is not a @@ -197,35 +206,37 @@ ScrStream *scr_stream_pipeline(double n, ScrStream **streams, ScrClosure *cb, Sc * mustCall wrappers; borrowed). */ ScrClosure *scr_stream_finished_dyn(ScrStream *s, struct ScrDyn *cb); ScrStream *scr_stream_pipeline_dyn(double n, ScrStream **streams, struct ScrDyn *cb); -/* pipeline(...[, cb]) with one run of function stages (pipeline.js): the - * run starts at streams[at] (count functions). flags bit 0: the first - * stage is a source function, called with only its options; bits 1-2: - * the last stage is a function destination (2: an async function whose - * promise, boxed through box, carries the value to the callback), and - * pipeline() answers a PassThrough. Other - * stages get the previous stream itself or the previous stage's async - * generator. mask bit i: stage i takes { signal } (the pipeline's own - * AbortSignal, aborted through abort when the pipeline finishes). The - * last generator before a stream or a PassThrough is pumped - * (pumpToNode) through its helpers: next/ret answer the resume's - * promise, read maps its IteratorResult to the value or - * scr_stream_from_done. Streams and closures borrowed (helpers, box, - * signal and abort NULL when unused); cb moves. */ -ScrStream *scr_stream_pipeline_stages(double n, ScrStream **streams, double at, double count, - ScrClosure **stages, double flags, double mask, - ScrClosure *next, ScrClosure *read, ScrClosure *ret, - ScrClosure *box, struct ScrDyn *signal, ScrClosure *abort, - ScrClosure *cb, ScrStreamErrInv inv); -ScrStream *scr_stream_pipeline_stages_dyn(double n, ScrStream **streams, double at, double count, - ScrClosure **stages, double flags, double mask, - ScrClosure *next, ScrClosure *read, ScrClosure *ret, - ScrClosure *box, struct ScrDyn *signal, - ScrClosure *abort, struct ScrDyn *cb); -struct ScrPromise *scr_sp_pipeline_stages(double n, ScrStream **streams, double at, double count, - ScrClosure **stages, double flags, double mask, - ScrClosure *next, ScrClosure *read, ScrClosure *ret, - ScrClosure *box, struct ScrDyn *signal, - ScrClosure *abort); +/* pipeline(...[, cb]) with function stages (pipeline.js): positions bit j + * marks the j-th of the n + count stages a function. A function at + * position 0 is a source function, called with only its options. flags + * bits 1-2: the last stage is a function destination (2: an async + * function whose promise, boxed through box, carries the value to the + * callback), and pipeline() answers a PassThrough. Other stages get the + * previous stream itself or the previous stage's async generator. mask + * bit i: function i takes { signal } (the pipeline's own AbortSignal, + * aborted through abort when the pipeline finishes). The last generator + * of each run that a stream follows is pumped (pumpToNode) through its + * three helpers in `helpers`: next/ret answer the resume's promise, read + * maps its IteratorResult to the value or scr_stream_from_done. Streams + * and closures borrowed (helpers, box, signal and abort NULL when + * unused); cb moves. */ +ScrStream *scr_stream_pipeline_stages(double n, ScrStream **streams, double count, + ScrClosure **stages, double positions, double flags, + double mask, ScrClosure **helpers, ScrClosure *box, + struct ScrDyn *signal, ScrClosure *abort, ScrClosure *cb, + ScrStreamErrInv inv); +ScrStream *scr_stream_compose_stages(double n, ScrStream **streams, double count, ScrClosure **stages, + double positions, double flags, double mask, ScrClosure **helpers, + ScrClosure *box, ScrDyn *signal, ScrClosure *abort); +ScrStream *scr_stream_pipeline_stages_dyn(double n, ScrStream **streams, double count, + ScrClosure **stages, double positions, double flags, + double mask, ScrClosure **helpers, ScrClosure *box, + struct ScrDyn *signal, ScrClosure *abort, + struct ScrDyn *cb); +struct ScrPromise *scr_sp_pipeline_stages(double n, ScrStream **streams, double count, + ScrClosure **stages, double positions, double flags, + double mask, ScrClosure **helpers, ScrClosure *box, + struct ScrDyn *signal, ScrClosure *abort); /* stream.compose(s1..sn): a pipeline over the streams and a Duplex that * writes to the first and reads from the last (compose.js). One stream * answers itself (Duplex.from of a duplex). +1, or NULL with @@ -255,6 +266,9 @@ ScrDyn *scr_stream_done_dyn_l(ScrClosure *clo, ScrDyn *const *args, size_t argc) /* The readable surface. push/unshift borrow their chunk (strings convert * utf8, Node's decodeStrings default); push answers the below-hwm bool. */ bool scr_stream_push(ScrStream *s, ScrBytes *chunk); +/* readable.push(chunk) from a program: a non-Buffer view becomes a Buffer + * over the same bytes in byte mode. */ +bool scr_stream_push_view(ScrStream *s, ScrBytes *chunk); bool scr_stream_push_str(ScrStream *s, ScrStr *str); /* push(chunk, enc): the per-call literal encoding (canonical); overrides * the stream's defaultEncoding. Borrows both. */ @@ -266,6 +280,7 @@ ScrStream *scr_stream_set_push_encoding(ScrStream *s, ScrStr *enc); bool scr_stream_push_null(ScrStream *s); void scr_stream_unshift(ScrStream *s, ScrBytes *chunk); void scr_stream_unshift_str(ScrStream *s, ScrStr *str); +void scr_stream_unshift_dyn(ScrStream *s, const ScrDyn *d); ScrBytes *scr_stream_read(ScrStream *s, double size); ScrStream *scr_stream_on_dyn(ScrStream *s, ScrStr *name, ScrDyn *cb, bool once, bool prepend); ScrDyn *scr_stream_read_dyn(ScrStream *s, ScrDyn *size); /* +1 or NULL; size < 0 = all/first; throws once encoded (the static type is Buffer|null) */ @@ -285,8 +300,18 @@ typedef struct ScrPromise ScrPromise; /* full declaration below (C11 repeat) */ * each chunk before asking again). */ bool scr_stream_push_dyn(ScrStream *s, const ScrDyn *d); /* borrows d; tag dispatch */ bool scr_stream_write_dyn(ScrStream *s, const ScrDyn *d, ScrClosure *cb); /* cb moves */ +/* write(chunk, encoding, cb): enc borrowed, NULL or undefined when absent */ +bool scr_stream_write_enc(ScrStream *s, const ScrDyn *chunk, ScrDyn *enc, ScrClosure *cb); ScrPromise *scr_stream_next_chunk(ScrStream *s); ScrPromise *scr_stream_next_chunk_dyn(ScrStream *s); +/* The same step resolving with an iterator result ({ value, done }). */ +ScrPromise *scr_stream_next_result_dyn(ScrStream *s); +/* The native readable stream behind a checked-dynamic value (+1), or NULL. */ +ScrStream *scr_stream_native_readable_of_dyn(const struct ScrDyn *value); +/* for await over a checked-dynamic value in a program with streams + * (scr_stream_ops.c): a native readable stream iterates as a typed loop + * does; any other value takes scr_dyn_async_iterator_open. */ +struct ScrDyn *scr_stream_dyn_async_iterator_open(struct ScrDyn *value, ScrStr *spell); /* node:stream/promises — the promise forms over the finished/pipeline * machinery above: a pending void promise the terminal watcher settles * (fulfilled on a clean finish, rejected with the finish status @@ -320,6 +345,7 @@ enum { SCR_FROM_BYTE_MODE = 4, SCR_FROM_HAS_HWM = 8, SCR_FROM_DEFAULT_HWM = 16, /* a nullish highWaterMark: the mode's default */ + SCR_FROM_DUPLEX = 32, /* Duplex.from: a Duplexify with its writable side off */ }; ScrStream *scr_stream_from_arr(ScrArr *arr, double flags, double hwm); /* Readable.from(iterable, options) over a checked-dynamic source: a @@ -405,18 +431,41 @@ int scr_stream_push_object(ScrStream *s, const ScrDyn *v); * dyn array, find and reduce a dyn value — reduce's `kind` picks the * payload instead: 0 dyn, 1 number, 2 boolean, 3 string — some and every * a boolean, forEach nothing. */ -ScrStream *scr_stream_op_map(ScrStream *s, ScrDyn *fn, ScrDyn *options); -ScrStream *scr_stream_op_filter(ScrStream *s, ScrDyn *fn, ScrDyn *options); -ScrStream *scr_stream_op_flat_map(ScrStream *s, ScrDyn *fn, ScrDyn *options); +ScrStream *scr_stream_op_map(ScrStream *s, ScrDyn *fn, ScrDyn *options, ScrDyn *cb_opts); +ScrStream *scr_stream_op_filter(ScrStream *s, ScrDyn *fn, ScrDyn *options, ScrDyn *cb_opts); +ScrStream *scr_stream_op_flat_map(ScrStream *s, ScrDyn *fn, ScrDyn *options, ScrDyn *cb_opts); +/* flatMap whose callback returns a compiled generator: the helpers over its + * type (async: next, read, return, throw; sync: next, return, throw; + * borrowed). */ +ScrStream *scr_stream_op_flat_map_async_gen(ScrStream *s, ScrDyn *fn, ScrDyn *options, + ScrDyn *cb_opts, ScrClosure *next, ScrClosure *read, + ScrClosure *ret, ScrClosure *thr); +ScrStream *scr_stream_op_flat_map_sync_gen(ScrStream *s, ScrDyn *fn, ScrDyn *options, + ScrDyn *cb_opts, ScrClosure *next, ScrClosure *ret, + ScrClosure *thr); ScrStream *scr_stream_op_drop(ScrStream *s, ScrDyn *number, ScrDyn *options); ScrStream *scr_stream_op_take(ScrStream *s, ScrDyn *number, ScrDyn *options); ScrPromise *scr_stream_op_to_array(ScrStream *s, ScrDyn *options); -ScrPromise *scr_stream_op_for_each(ScrStream *s, ScrDyn *fn, ScrDyn *options); -ScrPromise *scr_stream_op_some(ScrStream *s, ScrDyn *fn, ScrDyn *options); -ScrPromise *scr_stream_op_every(ScrStream *s, ScrDyn *fn, ScrDyn *options); -ScrPromise *scr_stream_op_find(ScrStream *s, ScrDyn *fn, ScrDyn *options); +ScrPromise *scr_stream_op_for_each(ScrStream *s, ScrDyn *fn, ScrDyn *options, ScrDyn *cb_opts); +ScrPromise *scr_stream_op_some(ScrStream *s, ScrDyn *fn, ScrDyn *options, ScrDyn *cb_opts); +ScrPromise *scr_stream_op_every(ScrStream *s, ScrDyn *fn, ScrDyn *options, ScrDyn *cb_opts); +ScrPromise *scr_stream_op_find(ScrStream *s, ScrDyn *fn, ScrDyn *options, ScrDyn *cb_opts); ScrPromise *scr_stream_op_reduce(ScrStream *s, ScrDyn *fn, ScrDyn *init, bool has_init, ScrDyn *options, double kind); +/* reduce whose reducer reads its { signal } (cb_opts): abort is ac.abort() + * (borrowed), run when the reduction ends. */ +ScrPromise *scr_stream_op_reduce_signal(ScrStream *s, ScrDyn *fn, ScrDyn *init, bool has_init, + ScrDyn *options, double kind, ScrClosure *abort, + ScrDyn *cb_opts); +/* `options?.signal` (+1, undefined when absent) and `{ once: true }` (+1), + * for the listener that makes options.signal abort reduce's controller. */ +ScrDyn *scr_stream_op_signal_of(ScrDyn *options); +ScrDyn *scr_stream_op_once_options(void); +/* The operator callbacks' { signal } (the options argument): the signals + * AbortSignal.any combines (`[options?.signal].filter(Boolean)`) and the + * object around the combined signal. +1 each. */ +ScrDyn *scr_stream_op_signal_list(ScrDyn *options); +ScrDyn *scr_stream_op_signal_opts(ScrDyn *signal); /* finished(s, options[, cb]) — Node's eos with its listeners and state * predicates: readable/writable are -1 (the default), 0 or 1; on_error is * options.error !== false; signal is NULL or borrowed (ERR_INVALID_ARG_TYPE @@ -436,6 +485,12 @@ ScrPromise *scr_sp_finished_opts(ScrStream *s, double readable, double writable, * ERR_INVALID_ARG_TYPE. Streams borrowed. */ ScrPromise *scr_sp_pipeline_opts(double n, ScrStream **streams, bool end, ScrDyn *signal, ScrAbortAddFn add); +/* scr_sp_pipeline_stages with the options' end and signal (outer). */ +ScrPromise *scr_sp_pipeline_stages_opts(double n, ScrStream **streams, double count, + ScrClosure **stages, double positions, double flags, + double mask, ScrClosure **helpers, ScrClosure *box, + ScrDyn *signal, ScrClosure *abort, bool end, + ScrDyn *outer, ScrAbortAddFn add); double scr_stream_prop(ScrStream *s, const char *name); ScrError *scr_stream_errored(ScrStream *s); /* +1 or NULL */ @@ -469,6 +524,28 @@ void scr_stream_final_done(ScrStream *s, ScrError *err); void scr_stream_destroy_done(ScrStream *s, ScrError *err); void scr_stream_transform_done(ScrStream *s, ScrError *err, ScrBytes *data, ScrStr *data_str); void scr_stream_flush_done(ScrStream *s, ScrError *err, ScrBytes *data, ScrStr *data_str); +/* The same completions with a checked-dynamic data value (borrowed; NULL, + * null and undefined push nothing): an object-mode Transform's data, or an + * untyped callback's. err moves. */ +/* objectMode: scr_stream_set_object_mode applies the option's sides right + * after construction; scr_stream_writes_values answers whether the write + * and transform steps receive dyn values instead of Buffers. */ +void scr_stream_set_object_mode(ScrStream *s, bool readable, bool writable); +ScrStream *scr_stream_object_mode(ScrStream *s, bool readable, bool writable); +bool scr_stream_writes_values(ScrStream *s); +/* A compiled write or transform callback's chunk by its declared type: a + * Buffer (+1, or NULL with a TypeError for another object-mode value), a + * dyn value (+1), and the encoding argument (+1). */ +ScrBytes *scr_stream_chunk_bytes(ScrStream *s, ScrBytes *chunk); +struct ScrDyn *scr_stream_chunk_value(ScrStream *s, ScrBytes *chunk); +ScrStr *scr_stream_chunk_encoding(ScrStream *s); +ScrDyn *scr_stream_chunk_encoding_value(ScrStream *s); +/* emit('data', value) with a checked-dynamic chunk (borrowed). */ +bool scr_stream_emit_value(ScrStream *s, ScrStr *name, struct ScrDyn *v); +/* Whether a dyn for-await step (readable.nextChunkDyn) answered the end. */ +bool scr_stream_chunk_done(const struct ScrDyn *v); +void scr_stream_transform_done_value(ScrStream *s, ScrError *err, struct ScrDyn *v); +void scr_stream_flush_done_value(ScrStream *s, ScrError *err, struct ScrDyn *v); /* Runtime-backed streams (the fs streams in scr_fs_stream.c). * - construct: Node's _construct. The hook runs on a tick after @@ -481,6 +558,57 @@ void scr_stream_flush_done(ScrStream *s, ScrError *err, ScrBytes *data, ScrStr * void scr_stream_construct(ScrStream *s, ScrClosure *cb, ScrStreamPlainInv inv); void scr_stream_construct_done(ScrStream *s, ScrError *err); void scr_stream_set_writev_concat(ScrStream *s); +/* The user construct option / _construct method (scheduled now; cb + * moves), and the writev option / _writev method (cb moves). */ +void scr_stream_set_construct(ScrStream *s, ScrClosure *cb, ScrStreamPlainInv inv); +void scr_stream_set_writev(ScrStream *s, ScrClosure *cb, ScrStreamWritevInv inv); +void scr_stream_set_writev_default(ScrStream *s, ScrClosure *cb, ScrStreamWritevInv inv); +/* Duplex.from (duplexify.js): over an async generator function (the + * compiled stage takes the source generator that the compiled source + * makes from next() and ack(); all borrowed, helpers too), and over a + * checked-dynamic body (borrowed). +1 each. The typed iterable bodies take + * the Readable.from builders with SCR_FROM_DUPLEX. */ +ScrStream *scr_stream_duplex_from_gen(ScrClosure *stage, ScrClosure *source, ScrClosure *next, + ScrClosure *read, ScrClosure *ret, ScrClosure *thr); +ScrStream *scr_stream_duplex_from_dyn(struct ScrDyn *body); +/* Readable.fromWeb(readableStream, { objectMode, highWaterMark, encoding }) + * (scr_stream_from_web.c): hwm < 0 is the mode's default, encoding NULL or + * a known name; web and encoding borrowed. +1, or NULL with the error. */ +ScrStream *scr_stream_readable_from_web(struct ScrDyn *web, bool object_mode, double hwm, ScrStr *encoding); +/* Duplex.from over an async function (the compiled stage takes the source + * generator and answers its promise; source and the promise's box helper + * borrowed): a writable Duplexify whose final waits for the promise. +1. */ +ScrStream *scr_stream_duplex_from_async_fn(ScrClosure *stage, ScrClosure *source, ScrClosure *box); +/* The same for a body that declares the options argument: it takes + * { signal } (signal borrowed), and destroy calls abort(err) (borrowed), + * the AbortController's abort, before it settles (fromAsyncGen's + * ac.abort(err)). */ +ScrStream *scr_stream_duplex_from_gen_signal(ScrClosure *stage, ScrClosure *source, ScrClosure *next, + ScrClosure *read, ScrClosure *ret, ScrClosure *thr, + ScrClosure *abort, struct ScrDyn *signal); +ScrStream *scr_stream_duplex_from_async_fn_signal(ScrClosure *stage, ScrClosure *source, + ScrClosure *box, ScrClosure *abort, + struct ScrDyn *signal); +/* Duplex.from over a Readable, a Writable, or a { readable, writable } + * pair (duplexify.js's _duplexify): a Duplexify that reads r and writes w + * (either NULL in scr_stream_duplexify; streams borrowed). +1. */ +ScrStream *scr_stream_duplexify(ScrStream *r, ScrStream *w); +ScrStream *scr_stream_duplexify_readable(ScrStream *r); +ScrStream *scr_stream_duplexify_writable(ScrStream *w); +ScrStream *scr_stream_duplexify_pair(ScrStream *r, ScrStream *w); +/* Duplex.from(promise): a readable Duplexify of the promise's value. p and + * box (the compiler's promise → dyn promise helper) borrowed. +1. */ +ScrStream *scr_stream_duplex_from_promise(struct ScrPromise *p, ScrClosure *box); +/* decodeStrings (false keeps string writes as strings), the writable + * defaultEncoding option (a known encoding, borrowed), and + * setDefaultEncoding (validated; answers the stream +1). The chaining + * forms answer the stream (+1). */ +void scr_stream_set_decode_strings(ScrStream *s, bool decode); +ScrStream *scr_stream_decode_strings(ScrStream *s, bool decode); +void scr_stream_set_write_encoding(ScrStream *s, ScrStr *enc); +ScrStream *scr_stream_write_encoding(ScrStream *s, ScrStr *enc); +ScrStream *scr_stream_set_default_encoding(ScrStream *s, struct ScrDyn *enc); +ScrDyn *scr_stream_done_dyn_c(ScrClosure *clo, ScrDyn *const *args, size_t argc); /* The native state's extra operations: view adds its members to the * stream's untyped view and close is the view's close() (both NULL when * absent); aggregate builds aggregateTwoErrors' +1 AggregateError from the diff --git a/packages/runtime/src/scr_stream_dyn.c b/packages/runtime/src/scr_stream_dyn.c index 11dcf6ee2..5cef9d536 100644 --- a/packages/runtime/src/scr_stream_dyn.c +++ b/packages/runtime/src/scr_stream_dyn.c @@ -17,8 +17,11 @@ static bool scr_stream_dyn_within(const ScrVt *vt, const ScrVt *cls) { /* The native stream a checked-dynamic value boxes (+1), when it has the * requested side (1 readable, 2 writable; Duplex, Transform and PassThrough - * have both), or NULL for any other value. Never throws. */ + * have both), or the stream of a stream handle, or NULL for any other + * value. Never throws. */ ScrStream *scr_stream_dyn_native(const ScrDyn *value, double side) { + /* A Cipheriv or Decipheriv is a Transform. */ + if (value->kind == SCR_DYN_HANDLE) return scr_stream_of_handle(value); if (value->kind != SCR_DYN_TYPED_REF || value->v.typed_ref.type_key_len <= 7 || memcmp(value->v.typed_ref.type_key, "object:", 7) != 0) return NULL; diff --git a/packages/runtime/src/scr_stream_from_web.c b/packages/runtime/src/scr_stream_from_web.c new file mode 100644 index 000000000..f88826335 --- /dev/null +++ b/packages/runtime/src/scr_stream_from_web.c @@ -0,0 +1,247 @@ +/* Readable.fromWeb (Node's newStreamReadableFromReadableStream in + * internal/webstreams/adapters.js): a Readable over a web ReadableStream's + * reader. read() queues one read request (scr_fetch_reader_read_into); a + * chunk is pushed in a microtask, the end pushes null and an error + * destroys the Readable. destroy() cancels the reader unless it has + * closed, then completes. reader.closed's settlement marks it closed (a + * rejection also destroys the Readable). Linked only by programs that + * use both streams and the native web streams. */ +#include "scr_runtime.h" +#include "scr_stream.h" + +#include +#include + +typedef struct SfwCtx SfwCtx; +struct SfwCtx { + size_t rc; + ScrStream *readable; /* +1 until teardown */ + ScrDyn *reader; /* +1 */ + ScrDyn *pending; /* +1: pendingChunk, or NULL */ + bool closed; + SfwCtx *live_prev, *live_next; +}; + +static SCR_TL SfwCtx *sfw_live = NULL; + +static SfwCtx *sfw_ref(SfwCtx *c) { + c->rc++; + return c; +} + +static void sfw_unref(SfwCtx *c) { + if (--c->rc > 0) return; + if (c->readable) scr_stream_release(c->readable); + if (c->reader) scr_dyn_release(c->reader); + if (c->pending) scr_dyn_release(c->pending); + free(c); +} + +static void *sfw_retain_v(void *p) { return sfw_ref(p); } +static void sfw_release_v(void *p) { sfw_unref(p); } + +/* Drop the Readable (the cycle through its callbacks). */ +static void sfw_teardown(SfwCtx *c) { + if (c->live_prev) c->live_prev->live_next = c->live_next; + else if (sfw_live == c) sfw_live = c->live_next; + else return; /* already torn down */ + if (c->live_next) c->live_next->live_prev = c->live_prev; + c->live_prev = c->live_next = NULL; + ScrStream *r = c->readable; + c->readable = NULL; + if (r) scr_stream_release(r); + sfw_unref(c); /* the live list's reference */ +} + +static void sfw_atexit(void) { + while (sfw_live) sfw_teardown(sfw_live); +} + +static ScrClosure *sfw_closure(void *fn, SfwCtx *c) { + ScrClosure *cl = scr_closure_new(fn, 1); + cl->caps[0] = scr_box_new_obj(&sfw_retain_v, &sfw_release_v, NULL); + scr_box_set_ref(cl->caps[0], sfw_ref(c)); + return cl; +} + +static SfwCtx *sfw_of(ScrClosure *cl) { return scr_box_get_ref(cl->caps[0]); /* +1 */ } + +/* destroyer(readable, error) */ +static void sfw_destroyer(SfwCtx *c, ScrDyn *reason) { + ScrStream *r = c->readable; + if (!r || scr_stream_prop(r, "destroyed")) return; + ScrError *err = reason ? scr_error_from_dyn(reason) : NULL; + if (scr_exc_pending()) scr_exc_clear(); + scr_stream_release(scr_stream_destroy(r, err)); + if (err) scr_error_release(err); +} + +/* forwardChunk: readable.push(pendingChunk) */ +static void sfw_forward(ScrClosure *job) { + SfwCtx *c = sfw_of(job); + ScrDyn *chunk = c->pending; + c->pending = NULL; + if (chunk && c->readable) { + scr_stream_push_dyn(c->readable, chunk); + if (scr_exc_pending()) scr_exc_clear(); + } + if (chunk) scr_dyn_release(chunk); + sfw_unref(c); +} + +static void sfw_sink_chunk(void *ctx, ScrDyn *value) { + SfwCtx *c = ctx; + if (c->pending) scr_dyn_release(c->pending); + c->pending = scr_dyn_retain(value); + scr_queue_microtask(sfw_closure((void *)&sfw_forward, c)); + sfw_unref(c); /* the request's reference */ +} + +static void sfw_sink_close(void *ctx) { + SfwCtx *c = ctx; + if (c->readable) scr_stream_push_null(c->readable); + if (scr_exc_pending()) scr_exc_clear(); + sfw_unref(c); +} + +static void sfw_sink_error(void *ctx, ScrDyn *reason) { + SfwCtx *c = ctx; + sfw_destroyer(c, reason); + sfw_unref(c); +} + +static const ScrFetchReadSink sfw_sink = {&sfw_sink_chunk, &sfw_sink_close, &sfw_sink_error}; + +/* read(): readableStreamDefaultReaderRead(reader, readRequest) */ +static void sfw_read_inv(ScrClosure *cb, ScrStream *s, double size) { + (void)s; + (void)size; + SfwCtx *c = sfw_of(cb); + if (c->reader) { + if (!scr_fetch_reader_read_into(c->reader, &sfw_sink, sfw_ref(c))) { + sfw_unref(c); + if (scr_exc_pending()) scr_exc_clear(); + } + } + sfw_unref(c); +} + +/* destroy's done(): callback(error) */ +typedef struct { + SfwCtx *c; /* +1 */ + ScrStream *s; /* +1 */ + ScrError *err; /* +1 or NULL */ + ScrDyn *cancel; /* +1: reader.cancel(error)'s promise */ +} SfwDestroy; + +static void sfw_destroy_done(SfwCtx *c, ScrStream *s, ScrError *err) { + scr_stream_destroy_done(s, err ? scr_error_retain(err) : NULL); + sfw_teardown(c); +} + +static void sfw_cancel_entry(ScrFiber *fiber, void *arg) { + (void)fiber; + SfwDestroy d = *(SfwDestroy *)arg; + free(arg); + ScrDyn *v = scr_await_ref(d.cancel->v.promise); /* then(done, done) */ + if (scr_exc_pending()) scr_exc_clear(); + if (v) scr_dyn_release(v); + sfw_destroy_done(d.c, d.s, d.err); + if (d.err) scr_error_release(d.err); + scr_stream_release(d.s); + scr_dyn_release(d.cancel); + sfw_unref(d.c); +} + +static void sfw_destroy_inv(ScrClosure *cb, ScrStream *s, ScrError *err) { + SfwCtx *c = sfw_of(cb); + if (!c->closed && c->reader) { + /* _destroy(err, cb) gets null for a destroy without an error */ + ScrDyn *reason = err ? scr_dyn_from_error(err) : scr_dyn_new_null(); + ScrDyn *cancel = scr_dyn_invoke(c->reader, "cancel", &reason, 1, "reader.cancel"); + scr_dyn_release(reason); + if (cancel && cancel->kind == SCR_DYN_PROMISE) { + SfwDestroy *d = malloc(sizeof *d); + if (!d) abort(); + d->c = sfw_ref(c); + d->s = scr_stream_retain(s); + d->err = err ? scr_error_retain(err) : NULL; + d->cancel = cancel; + scr_promise_release(scr_async_spawn_after(cancel->v.promise, &sfw_cancel_entry, d)); + sfw_unref(c); + return; + } + if (cancel) scr_dyn_release(cancel); + if (scr_exc_pending()) scr_exc_clear(); + } + sfw_destroy_done(c, s, err); + sfw_unref(c); +} + +/* reader.closed.then(() => closed = true, (e) => { closed = true; destroy(readable, e) }) */ +typedef struct { + SfwCtx *c; /* +1 */ + ScrDyn *closed; /* +1, the promise */ +} SfwClosed; + +static void sfw_closed_entry(ScrFiber *fiber, void *arg) { + (void)fiber; + SfwClosed w = *(SfwClosed *)arg; + free(arg); + ScrDyn *v = scr_await_ref(w.closed->v.promise); + w.c->closed = true; + if (scr_exc_pending()) { + ScrCaught *caught = scr_exc_take(); + ScrDyn *reason = scr_caught_to_dyn(caught); + scr_caught_release(caught); + sfw_destroyer(w.c, reason); + if (reason) scr_dyn_release(reason); + } + if (v) scr_dyn_release(v); + scr_dyn_release(w.closed); + sfw_unref(w.c); +} + +/* web: the ReadableStream (borrowed); hwm < 0 = the mode's default; + * encoding NULL or a known name (borrowed). +1, or NULL with the error + * pending. */ +ScrStream *scr_stream_readable_from_web(ScrDyn *web, bool object_mode, double hwm, ScrStr *encoding) { + if (encoding && encoding->len == 0) encoding = NULL; + if (!web || web->kind != SCR_DYN_HANDLE || web->v.handle.tag != SCR_DYNH_WEB_STREAM) { + scr_dyn_arg_type_fail("readableStream", "an instance of ReadableStream", web); + return NULL; + } + ScrDyn *reader = scr_dyn_invoke(web, "getReader", NULL, 0, "readableStream.getReader"); + if (!reader) return NULL; + SfwCtx *c = calloc(1, sizeof *c); + if (!c) abort(); + c->rc = 1; + c->reader = reader; + ScrStream *r = scr_stream_new_readable(hwm < 0 ? (object_mode ? 16 : -1) : hwm, true, true, + sfw_closure((void *)&sfw_read_inv, c), &sfw_read_inv, + sfw_closure((void *)&sfw_destroy_inv, c), &sfw_destroy_inv); + if (object_mode) scr_stream_set_object_mode(r, true, false); + if (encoding) scr_stream_release(scr_stream_set_encoding(r, encoding)); + c->readable = scr_stream_retain(r); + static SCR_TL bool registered = false; + if (!registered) { + registered = true; + scr_atexit(sfw_atexit); + } + c->live_next = sfw_live; + if (sfw_live) sfw_live->live_prev = c; + sfw_live = c; /* the reference c was created with */ + ScrStr *key = scr_str_new("closed", 6); + ScrDyn *closed = scr_dyn_handle_key_get(reader, key); + scr_str_release(key); + if (closed && closed->kind == SCR_DYN_PROMISE) { + SfwClosed *w = malloc(sizeof *w); + if (!w) abort(); + w->c = sfw_ref(c); + w->closed = closed; + scr_promise_release(scr_async_spawn_after(closed->v.promise, &sfw_closed_entry, w)); + } else if (closed) { + scr_dyn_release(closed); + } + return r; +} diff --git a/packages/runtime/src/scr_stream_ops.c b/packages/runtime/src/scr_stream_ops.c index d32dd5d67..a92b4a0e5 100644 --- a/packages/runtime/src/scr_stream_ops.c +++ b/packages/runtime/src/scr_stream_ops.c @@ -267,20 +267,15 @@ static bool op_aborted(const ScrDyn *signal) { return r; } -/* The callback argument: a function that does not read the options - * argument. `max` is how many parameters Node's call passes before the - * options. False with the error pending. */ +/* The callback argument: validateFunction. False with the error pending. + * (The options argument the callback may read is the operator's + * cb_opts.) */ static bool op_check_fn(const ScrDyn *fn, const char *name, uint32_t max) { + (void)max; if (!fn || !scr_dyn_is_callable(fn)) { scr_dyn_arg_type_fail(name, "of type function", fn ? fn : scr_dyn_undefined()); return false; } - if (fn->kind == SCR_DYN_FUNC && fn->v.fn.arity > max) { - static const char m[] = - "stream operator callbacks that read the options argument ({ signal }) are not supported yet"; - scr_throw_error_msg(SCR_ERR_ERROR, m, sizeof m - 1); - return false; - } return true; } @@ -305,7 +300,7 @@ static ScrPromise *src_next(OpSrc *src) { } static bool src_done(const OpSrc *src, const ScrDyn *v) { - return src->s ? v->kind == SCR_DYN_UNDEF : v == op_k_done; + return src->s ? scr_stream_chunk_done(v) : v == op_k_done; } /* The Readable iterator's return(): the iterator generator resumes at its @@ -610,8 +605,9 @@ enum { MODE_MAP, MODE_FILTER, MODE_FOREACH, MODE_EVERY }; typedef struct { OpGen g; OpSrc src; - ScrDyn *fn; /* +1 */ - ScrDyn *signal; /* +1 or NULL */ + ScrDyn *fn; /* +1 */ + ScrDyn *signal; /* +1 or NULL */ + ScrDyn *cb_opts; /* +1: the { signal } fn takes as its second argument, or NULL */ int mode; double concurrency, hwm; ScrDyn **queue; /* +1 entries: dyn promises or kEof */ @@ -628,6 +624,7 @@ static void op_map_body_drop(OpGen *g) { src_release(&m->src); scr_dyn_release(m->fn); if (m->signal) scr_dyn_release(m->signal); + if (m->cb_opts) scr_dyn_release(m->cb_opts); for (size_t i = m->qh; i < m->qn; i++) scr_dyn_release(m->queue[i]); free(m->queue); if (m->next_p) scr_promise_release(m->next_p); @@ -734,9 +731,11 @@ static void op_wrap_k(void *self, ScrDyn *v) { } /* Calls fn(chunk): +1 result, or NULL with the exception pending. */ -static ScrDyn *op_call(ScrDyn *fn, ScrDyn *chunk) { - ScrDyn *args[1] = {chunk}; - return scr_dyn_call(fn, args, 1, "fn"); +/* Calls fn(chunk, signalOpt) — the second argument when the callback + * declares it. +1 result, or NULL with the exception pending. */ +static ScrDyn *op_call(OpMap *m, ScrDyn *chunk) { + ScrDyn *args[2] = {chunk, m->cb_opts}; + return scr_dyn_call(m->fn, args, m->cb_opts ? 2 : 1, "fn"); } /* An async wrapper body: `await fn(chunk)` then its transform. The @@ -744,7 +743,7 @@ static ScrDyn *op_call(ScrDyn *fn, ScrDyn *chunk) { static ScrPromise *op_wrap_call(OpMap *m, ScrDyn *chunk, int mode, int stage) { OpWrap *w = op_wrap_new(mode, chunk, stage); ScrPromise *result = scr_promise_retain(w->p); - ScrDyn *r = op_call(m->fn, chunk); + ScrDyn *r = op_call(m, chunk); if (!r) { scr_promise_reject_pending(w->p); } else { @@ -772,7 +771,7 @@ static ScrPromise *op_every_call(OpMap *m, ScrDyn *chunk) { static ScrDyn *map_item(OpMap *m, ScrDyn *chunk) { ScrPromise *p; if (m->mode == MODE_MAP) { - ScrDyn *r = op_call(m->fn, chunk); + ScrDyn *r = op_call(m, chunk); if (!r) { ScrCaught *c = scr_exc_take(); ScrDyn *d = op_rejected_dyn(c); @@ -981,7 +980,7 @@ static void map_thr(OpGen *g, ScrCaught *c) { } static OpMap *map_new(ScrStream *s, ScrDyn *fn, int mode, double concurrency, double hwm, - ScrDyn *signal) { + ScrDyn *signal, ScrDyn *cb_opts) { OpMap *m = op_alloc(sizeof *m); gen_init(&m->g, &op_map_body_drop); m->g.resume = &map_resume; @@ -990,6 +989,7 @@ static OpMap *map_new(ScrStream *s, ScrDyn *fn, int mode, double concurrency, do m->src.s = scr_stream_retain(s); m->fn = scr_dyn_retain(fn); m->signal = signal ? scr_dyn_retain(signal) : NULL; + m->cb_opts = cb_opts && cb_opts->kind != SCR_DYN_UNDEF ? scr_dyn_retain(cb_opts) : NULL; m->mode = mode; m->concurrency = concurrency; m->hwm = hwm; @@ -1137,27 +1137,137 @@ static void slice_thr(OpGen *g, ScrCaught *c) { * goes through the async-from-sync iterator: each step resolves after the * element's PromiseResolve job, and yield* awaits that result before * yielding without a further await. */ +/* yield* over the delegate: an array or string (its elements, through + * the async-from-sync iterator), another iterable's iterator (FLAT_SYNC + * through the async-from-sync iterator, FLAT_ASYNC awaiting next()), or a + * native Readable (FLAT_STREAM, its async iterator). */ +enum { FLAT_NONE, FLAT_SYNC, FLAT_ASYNC, FLAT_STREAM, FLAT_GEN_SYNC, FLAT_GEN_ASYNC }; + +typedef ScrDyn *(*FromSyncFn)(ScrClosure *, ScrGen *); +typedef ScrDyn *(*FromSyncThrowFn)(ScrClosure *, ScrGen *, ScrDyn *); +typedef ScrPromise *(*FromAsyncFn)(ScrClosure *, ScrGen *); +typedef ScrPromise *(*FromAsyncThrowFn)(ScrClosure *, ScrGen *, ScrDyn *); +typedef ScrDyn *(*FromReadFn)(ScrClosure *, void *); +static void op_await_gen(ScrPromise *p, ScrClosure *read, OpCont k, void *self); + typedef struct { OpGen g; OpSrc values; /* the map generator */ ScrDyn *inner; /* +1: the array or string being delegated to, or NULL */ size_t idx; /* element index, or the string's byte offset */ ScrPromise *step; /* the async-from-sync iterator result being awaited */ + ScrDyn *iter; /* +1: the delegate's iterator (FLAT_SYNC / FLAT_ASYNC), or NULL */ + ScrStream *stream; /* +1: the delegate stream (FLAT_STREAM), or NULL */ + ScrGen *gen; /* +1: a compiled generator delegate (FLAT_GEN_*), or NULL */ + /* The compiler's helpers over the callback's generator type (+1 each, + * or NULL): next/return/throw, and read for an async generator. */ + ScrClosure *gnext, *gread, *gret, *gthr; + bool gen_async; + int iter_kind; bool started; } OpFlat; +/* A delegate's member (+1), read as the IR's keyed read does: a compiled + * value (a generator, its result record) through its typed ref, anything + * else through the iterator-result read. NULL with the error pending. */ +static ScrDyn *flat_get(const ScrDyn *v, const char *key) { + if (v->kind == SCR_DYN_TYPED_REF) { + ScrStr *k = scr_str_new(key, strlen(key)); + ScrDyn *r = scr_dyn_typed_ref_key_get(v, k); + scr_str_release(k); + return r; + } + return scr_dyn_iterator_result_get(v, key, strlen(key)); +} + +/* iterator[name](...args) with the iterator as this: +1, or NULL with the + * error pending. */ +static ScrDyn *flat_call(const ScrDyn *iter, const char *name, ScrDyn *const *args, size_t argc) { + ScrDyn *m = flat_get(iter, name); + if (!m) return NULL; + scr_dyn_this_push_dyn(iter); + ScrDyn *r = scr_dyn_call(m, args, argc, name); + scr_dyn_this_pop(); + scr_dyn_release(m); + return r; +} + +/* `const { value, done } = result`: +1 value with *done set, or NULL with + * the error pending. */ +static ScrDyn *flat_result(const ScrDyn *r, bool *done) { + if (r->kind == SCR_DYN_UNDEF || r->kind == SCR_DYN_NULL || r->kind == SCR_DYN_NUM || + r->kind == SCR_DYN_STR || r->kind == SCR_DYN_BOOL) { + ScrDyn *checked = scr_dyn_iterator_result((ScrDyn *)r); /* throws V8's TypeError */ + if (checked) scr_dyn_release(checked); + return NULL; + } + ScrDyn *d = flat_get(r, "done"); + if (!d) return NULL; + *done = scr_dyn_truthy(d); + scr_dyn_release(d); + return flat_get(r, "value"); +} + +static void flat_drop_delegate(OpFlat *f) { + if (f->inner) scr_dyn_release(f->inner); + if (f->iter) scr_dyn_release(f->iter); + if (f->stream) scr_stream_release(f->stream); + if (f->gen) scr_gen_release(f->gen); + f->inner = f->iter = NULL; + f->stream = NULL; + f->gen = NULL; + f->iter_kind = FLAT_NONE; +} + static void op_flat_body_drop(OpGen *g) { OpFlat *f = (OpFlat *)g; src_release(&f->values); - if (f->inner) scr_dyn_release(f->inner); + flat_drop_delegate(f); if (f->step) scr_promise_release(f->step); + if (f->gnext) scr_closure_release(f->gnext); + if (f->gread) scr_closure_release(f->gread); + if (f->gret) scr_closure_release(f->gret); + if (f->gthr) scr_closure_release(f->gthr); free(f); } static void flat_next_value(OpFlat *f); -/* The next element (+1), or NULL when the delegate is exhausted. */ -static ScrDyn *flat_take_element(OpFlat *f) { +/* The next element (+1), or NULL when the delegate is exhausted; for a + * sync iterator NULL with *failed set when next() threw (pending). */ +static ScrDyn *flat_take_element(OpFlat *f, bool *failed) { + *failed = false; + if (f->iter_kind == FLAT_GEN_SYNC) { + ScrDyn *v = ((FromSyncFn)f->gnext->fn)(f->gnext, scr_gen_retain(f->gen)); + if (!v) { + *failed = true; + return NULL; + } + if (v == op_k_done) { + scr_dyn_release(v); + return NULL; + } + return v; + } + if (f->iter_kind == FLAT_SYNC) { + ScrDyn *r = flat_call(f->iter, "next", NULL, 0); + if (!r) { + *failed = true; + return NULL; + } + bool done = false; + ScrDyn *v = flat_result(r, &done); + scr_dyn_release(r); + if (!v) { + *failed = true; + return NULL; + } + if (done) { + scr_dyn_release(v); + return NULL; + } + return v; + } ScrDyn *in = f->inner; if (in->kind == SCR_DYN_ARR) { if (f->idx >= in->v.arr.len) return NULL; @@ -1185,10 +1295,15 @@ static void flat_step_k(void *self, ScrDyn *v) { scr_promise_release(f->step); f->step = NULL; } - if (v == op_k_done || (v && v == op_k_eof)) { + if (!v) { + /* the delegate's next() threw: it leaves the for await */ + flat_drop_delegate(f); + gen_close_source(&f->g, &f->values, scr_exc_take()); + return; + } + if (v == op_k_done || v == op_k_eof) { scr_dyn_release(v); - scr_dyn_release(f->inner); - f->inner = NULL; + flat_drop_delegate(f); flat_next_value(f); return; } @@ -1196,6 +1311,33 @@ static void flat_step_k(void *self, ScrDyn *v) { scr_dyn_release(v); } +/* Await(innerResult) for an async delegate: done ends it, else its value + * is yielded as it is. */ +static void flat_iter_k(void *self, ScrDyn *v) { + OpFlat *f = self; + if (!v) { + flat_drop_delegate(f); + gen_close_source(&f->g, &f->values, scr_exc_take()); + return; + } + bool done = false; + ScrDyn *value = flat_result(v, &done); + scr_dyn_release(v); + if (!value) { + flat_drop_delegate(f); + gen_close_source(&f->g, &f->values, scr_exc_take()); + return; + } + if (done) { + scr_dyn_release(value); + flat_drop_delegate(f); + flat_next_value(f); + return; + } + gen_yield_now(&f->g, value); + scr_dyn_release(value); +} + /* The async-from-sync continuation: PromiseResolve(value) then the result * promise settles; yield* awaits that promise. */ typedef struct { @@ -1220,8 +1362,56 @@ static void op_flat_wrap_k(void *self, ScrDyn *v) { scr_dyn_release(v); } +/* The awaited resume of an async compiled generator delegate, read to its + * value or the done marker: done ends it, else the value is yielded. */ +static void flat_gen_k(void *self, ScrDyn *v) { + OpFlat *f = self; + if (!v) { + flat_drop_delegate(f); + gen_close_source(&f->g, &f->values, scr_exc_take()); + return; + } + if (v == op_k_done) { + scr_dyn_release(v); + flat_drop_delegate(f); + flat_next_value(f); + return; + } + gen_yield_now(&f->g, v); + scr_dyn_release(v); +} + static void flat_delegate_step(OpFlat *f) { - ScrDyn *e = flat_take_element(f); + if (f->iter_kind == FLAT_GEN_ASYNC) { + ScrPromise *p = ((FromAsyncFn)f->gnext->fn)(f->gnext, scr_gen_retain(f->gen)); + op_await_gen(p, f->gread, &flat_gen_k, f); + scr_promise_release(p); + return; + } + if (f->iter_kind == FLAT_ASYNC) { + ScrDyn *r = flat_call(f->iter, "next", NULL, 0); + if (!r) { + flat_drop_delegate(f); + gen_close_source(&f->g, &f->values, scr_exc_take()); + return; + } + op_await_value(r, &flat_iter_k, f); + scr_dyn_release(r); + return; + } + if (f->iter_kind == FLAT_STREAM) { + ScrPromise *p = scr_stream_next_result_dyn(f->stream); + op_await(p, &flat_iter_k, f); + scr_promise_release(p); + return; + } + bool failed = false; + ScrDyn *e = flat_take_element(f, &failed); + if (failed) { + flat_drop_delegate(f); + gen_close_source(&f->g, &f->values, scr_exc_take()); + return; + } OpFlatWrap *w = op_alloc(sizeof *w); w->base.rc = 1; w->base.drop = &op_flat_wrap_drop; @@ -1247,15 +1437,63 @@ static void flat_val_k(void *self, ScrDyn *v) { gen_complete(&f->g, NULL); return; } - if (v->kind != SCR_DYN_ARR && v->kind != SCR_DYN_STR) { - scr_dyn_release(v); - ScrCaught *c = op_take_error( - op_unsupported("flatMap callback results other than arrays or strings")); - gen_close_source(&f->g, &f->values, c); + if (v->kind == SCR_DYN_ARR || v->kind == SCR_DYN_STR) { + f->inner = v; + f->idx = 0; + flat_delegate_step(f); return; } - f->inner = v; - f->idx = 0; + ScrStream *stream = scr_stream_native_readable_of_dyn(v); + if (stream) { + scr_dyn_release(v); + f->stream = stream; + f->iter_kind = FLAT_STREAM; + flat_delegate_step(f); + return; + } + /* a compiled generator of the callback's declared type: stepped through + * the compiler's helpers */ + if (f->gnext && v->kind == SCR_DYN_TYPED_REF && v->v.typed_ref.type_key && + !strncmp(v->v.typed_ref.type_key, f->gen_async ? "async-generator<" : "generator<", + f->gen_async ? 16 : 10)) { + f->gen = scr_dyn_typed_ref_unbox(v); + scr_dyn_release(v); + f->iter_kind = f->gen_async ? FLAT_GEN_ASYNC : FLAT_GEN_SYNC; + flat_delegate_step(f); + return; + } + /* yield* val: GetIterator(val, async); a compiled generator is its own + * iterator */ + int kind = 0; + ScrDyn *iter = NULL; + if (v->kind == SCR_DYN_TYPED_REF && v->v.typed_ref.type_key && + (!strncmp(v->v.typed_ref.type_key, "async-generator<", 16) || + !strncmp(v->v.typed_ref.type_key, "generator<", 10))) { + kind = v->v.typed_ref.type_key[0] == 'a' ? 2 : 1; + iter = scr_dyn_retain(v); + } else { + iter = scr_dyn_open_iterator(v, &kind, true); + } + if (!iter && kind == 0 && !scr_exc_pending()) { + /* V8's GetIterator over a value without either method */ + if (v->kind == SCR_DYN_NULL || v->kind == SCR_DYN_UNDEF) { + char m[96]; + int n = snprintf(m, sizeof m, + "Cannot read properties of %s (reading 'Symbol(Symbol.asyncIterator)')", + v->kind == SCR_DYN_NULL ? "null" : "undefined"); + scr_throw_error_msg(SCR_ERR_TYPE, m, (size_t)n); + } else { + static const char m[] = "undefined is not a function"; + scr_throw_error_msg(SCR_ERR_TYPE, m, sizeof m - 1); + } + } + scr_dyn_release(v); + if (!iter) { + gen_close_source(&f->g, &f->values, scr_exc_take()); + return; + } + f->iter = iter; + f->iter_kind = kind == 2 ? FLAT_ASYNC : FLAT_SYNC; flat_delegate_step(f); } @@ -1300,19 +1538,85 @@ static void op_flat_ret_k(void *self, ScrDyn *v) { op_await_value(scr_dyn_undefined(), &op_flat_ret_k, r); return; } - if (r->f->inner) { - scr_dyn_release(r->f->inner); - r->f->inner = NULL; - } + flat_drop_delegate(r->f); gen_close_source(&r->f->g, &r->f->values, NULL); } +/* Whether the delegate's iterator has a callable `name` method. */ +static bool flat_iter_has(OpFlat *f, const char *name) { + if (!f->iter) return false; + ScrDyn *m = flat_get(f->iter, name); + if (!m) { + scr_exc_clear(); + return false; + } + bool callable = scr_dyn_is_callable(m); + scr_dyn_release(m); + return callable; +} + static void flat_ret(OpGen *g, ScrDyn *v) { (void)v; + OpFlat *f = (OpFlat *)g; OpFlatRet *r = op_alloc(sizeof *r); r->base.rc = 1; r->base.drop = &op_flat_ret_drop; - r->f = op_ref((OpFlat *)g); + r->f = op_ref(f); + if (f->iter_kind == FLAT_GEN_ASYNC) { + /* the generator's return(): awaited, then the value */ + ScrPromise *p = ((FromAsyncFn)f->gret->fn)(f->gret, scr_gen_retain(f->gen)); + op_await_gen(p, f->gread, &op_flat_ret_k, r); + scr_promise_release(p); + op_unref(r); + return; + } + if (f->iter_kind == FLAT_GEN_SYNC) { + ScrDyn *res = ((FromSyncFn)f->gret->fn)(f->gret, scr_gen_retain(f->gen)); + if (!res) { + flat_drop_delegate(f); + gen_close_source(g, &f->values, scr_exc_take()); + op_unref(r); + return; + } + scr_dyn_release(res); + op_await_value(scr_dyn_undefined(), &op_flat_ret_k, r); + op_unref(r); + return; + } + if (f->iter_kind == FLAT_ASYNC) { + /* yield*'s return: Await(iterator.return(value)), then the value */ + if (flat_iter_has(f, "return")) { + ScrDyn *arg = scr_dyn_undefined(); + ScrDyn *res = flat_call(f->iter, "return", &arg, 1); + if (!res) { + flat_drop_delegate(f); + gen_close_source(g, &f->values, scr_exc_take()); + op_unref(r); + return; + } + op_await_value(res, &op_flat_ret_k, r); + scr_dyn_release(res); + } else { + r->stage = 1; + op_await_value(scr_dyn_undefined(), &op_flat_ret_k, r); + } + op_unref(r); + return; + } + if (f->iter_kind == FLAT_SYNC && flat_iter_has(f, "return")) { + /* the async-from-sync iterator's return() calls the sync one */ + ScrDyn *arg = scr_dyn_undefined(); + ScrDyn *res = flat_call(f->iter, "return", &arg, 1); + if (!res) { + flat_drop_delegate(f); + gen_close_source(g, &f->values, scr_exc_take()); + op_unref(r); + return; + } + scr_dyn_release(res); + } else if (f->iter_kind == FLAT_STREAM) { + scr_stream_release(scr_stream_iterator_close(f->stream)); + } op_await_value(scr_dyn_undefined(), &op_flat_ret_k, r); op_unref(r); } @@ -1321,12 +1625,72 @@ static void flat_ret(OpGen *g, ScrDyn *v) { * yield* rejects with Node's TypeError, which leaves the for await and * closes map's generator. */ static void flat_thr(OpGen *g, ScrCaught *c) { - (void)c; OpFlat *f = (OpFlat *)g; - if (f->inner) { - scr_dyn_release(f->inner); - f->inner = NULL; + if (f->iter_kind == FLAT_GEN_ASYNC || f->iter_kind == FLAT_GEN_SYNC) { + /* the generator's throw(error) answers the next step */ + ScrDyn *err = scr_caught_to_dyn(c); + if (f->iter_kind == FLAT_GEN_ASYNC) { + ScrPromise *p = ((FromAsyncThrowFn)f->gthr->fn)(f->gthr, scr_gen_retain(f->gen), err); + op_await_gen(p, f->gread, &flat_gen_k, f); + scr_promise_release(p); + return; + } + ScrDyn *v = ((FromSyncThrowFn)f->gthr->fn)(f->gthr, scr_gen_retain(f->gen), err); + if (!v) { + flat_drop_delegate(f); + gen_close_source(g, &f->values, scr_exc_take()); + return; + } + if (v == op_k_done) { + scr_dyn_release(v); + flat_drop_delegate(f); + flat_next_value(f); + return; + } + op_await_value(v, &flat_step_k, f); + scr_dyn_release(v); + return; } + if ((f->iter_kind == FLAT_ASYNC || f->iter_kind == FLAT_SYNC) && flat_iter_has(f, "throw")) { + /* yield*'s throw: the delegate's throw(error) answers the next step */ + ScrDyn *err = scr_caught_to_dyn(c); + ScrDyn *res = flat_call(f->iter, "throw", &err, 1); + scr_dyn_release(err); + if (!res) { + flat_drop_delegate(f); + gen_close_source(g, &f->values, scr_exc_take()); + return; + } + if (f->iter_kind == FLAT_ASYNC) { + op_await_value(res, &flat_iter_k, f); + scr_dyn_release(res); + return; + } + ScrPromise *p = op_resolved(res); + scr_dyn_release(res); + op_await(p, &flat_iter_k, f); + scr_promise_release(p); + return; + } + if (f->iter_kind == FLAT_STREAM) { + /* the stream's iterator rethrows after destroying the stream */ + ScrDyn *err = scr_caught_to_dyn(c); + ScrError *e = err ? scr_error_from_dyn(err) : NULL; + if (scr_exc_pending()) scr_exc_clear(); + if (err) scr_dyn_release(err); + scr_stream_release(scr_stream_destroy(f->stream, e)); + if (e) scr_error_release(e); + flat_drop_delegate(f); + gen_close_source(g, &f->values, scr_caught_retain(c)); + return; + } + if (f->iter_kind != FLAT_NONE && flat_iter_has(f, "return")) { + /* no throw method: the iterator closes first */ + ScrDyn *res = flat_call(f->iter, "return", NULL, 0); + if (res) scr_dyn_release(res); + else scr_exc_clear(); + } + flat_drop_delegate(f); ScrError *e = op_coded_error(SCR_ERR_TYPE, NULL, "The iterator does not provide a 'throw' method."); gen_close_source(g, &f->values, op_take_error(e)); } @@ -1370,12 +1734,6 @@ static void op_from_drop(OpObj *o) { /* The helper ABIs: the closure first, then the declared parameters, which * the callee owns. */ -typedef ScrDyn *(*FromSyncFn)(ScrClosure *, ScrGen *); -typedef ScrDyn *(*FromSyncThrowFn)(ScrClosure *, ScrGen *, ScrDyn *); -typedef ScrPromise *(*FromAsyncFn)(ScrClosure *, ScrGen *); -typedef ScrPromise *(*FromAsyncThrowFn)(ScrClosure *, ScrGen *, ScrDyn *); -typedef ScrDyn *(*FromReadFn)(ScrClosure *, void *); - /* `await p` over an async generator's resume promise: the IteratorResult * record goes through `read` (the value, or the done marker) before k. * Awaiting the typed promise itself keeps from.js's single await. */ @@ -1492,16 +1850,6 @@ static void op_from_step_k(void *self, ScrDyn *v) { } int pushed = scr_stream_push_object(out, v); scr_dyn_release(v); - if (pushed == -2) { - op_from_destroy_with(out, op_unsupported( - "a stream operator output that mixes strings and Buffers")); - return; - } - if (pushed < 0) { - op_from_destroy_with(out, op_unsupported( - "a stream operator value that is not a string or Buffer (object-mode streams of other values)")); - return; - } if (pushed) { from_next(f, out); return; @@ -2039,6 +2387,466 @@ ScrStream *scr_stream_from_async_iter(ScrDyn *iter, double flags, double hwm) { return scr_stream_from_dyn_iter(scr_dyn_retain(iter), true, flags, hwm); } +/* ── Duplex.from (duplexify.js) ───────────────────────────────────── + * Duplex.from(asyncGeneratorFunction): fromAsyncGen hands the function a + * source generator that the writes and the final feed through a deferred + * promise, and from(Duplexify, value, { objectMode: true, write, final, + * destroy }) reads what the function yields. The source generator is + * compiled (the frontend's Duplex.from source helper): + * + * while (true) { const v = await next(); ack(); if (v is done) return; yield v; } + * + * next() answers the current deferred, a write or the final settles it + * (the chunk, or the done marker), and ack() is fromAsyncGen's + * `process.nextTick(cb)` followed by a fresh deferred. */ + +enum { CHAN_NONE, CHAN_WRITE, CHAN_FINAL, CHAN_ABORT, CHAN_FINAL_ASYNC }; + +typedef struct OpChan OpChan; +struct OpChan { + OpObj base; + ScrStream *d; /* +1, dropped at destroy (or exit) */ + ScrPromise *promise; /* +1: the deferred next() answers, NULL once taken */ + ScrPromise *resolve; /* +1: the deferred a write or the final settles, NULL once settled */ + int settled; /* CHAN_*: what settled the deferred, for ack() */ + bool aborted; /* destroy ran (fromAsyncGen's ac.abort()) */ + ScrClosure *abort; /* +1: the body's AbortController's abort(), or NULL */ + /* An async function body: its promise's then() (duplexify.js) settles + * `promise` there; the final waits for it. */ + bool finalized; /* final() has started */ + bool body_settled; /* the then() callbacks ran */ + bool final_waiting; /* the final's callback awaits the settlement */ + ScrError *body_err; /* +1: what awaiting the then() result throws, or NULL */ + OpChan *live_prev, *live_next; +}; + +static SCR_TL OpChan *op_chan_live = NULL; + +static void op_chan_drop(OpObj *o) { + OpChan *c = (OpChan *)o; + if (c->body_err) scr_error_release(c->body_err); + if (c->abort) scr_closure_release(c->abort); + if (c->d) scr_stream_release(c->d); + if (c->promise) scr_promise_release(c->promise); + if (c->resolve) scr_promise_release(c->resolve); + free(c); +} + +/* createDeferredPromise() */ +static void op_chan_defer(OpChan *c) { + ScrPromise *p = scr_promise_new(); + if (c->promise) scr_promise_release(c->promise); + if (c->resolve) scr_promise_release(c->resolve); + c->promise = p; + c->resolve = scr_promise_retain(p); +} + +/* Unlinks the channel from the live list and drops its stream and its + * deferred (a source still awaiting it stays pending, as in Node). */ +static void op_chan_retire(OpChan *c) { + if (c->live_prev) c->live_prev->live_next = c->live_next; + else if (op_chan_live == c) op_chan_live = c->live_next; + else return; /* already retired */ + if (c->live_next) c->live_next->live_prev = c->live_prev; + c->live_prev = c->live_next = NULL; + ScrStream *d = c->d; + c->d = NULL; + if (c->abort) scr_closure_release(c->abort); + c->abort = NULL; + if (c->promise) scr_promise_release(c->promise); + if (c->resolve) scr_promise_release(c->resolve); + c->promise = c->resolve = NULL; + if (d) scr_stream_release(d); + op_unref(c); /* the live list's reference */ +} + +static void op_chan_atexit(void) { + while (op_chan_live) op_chan_retire(op_chan_live); +} + +static ScrClosure *op_chan_closure(void *fn, OpChan *c) { + ScrClosure *cl = scr_closure_new(fn, 1); + cl->caps[0] = scr_box_new_obj(&op_ref, &op_unref, NULL); + scr_box_set_ref(cl->caps[0], op_ref(c)); + return cl; +} + +static OpChan *op_chan_of(ScrClosure *cb) { return scr_box_get_ref(cb->caps[0]); /* +1 */ } + +/* process.nextTick(cb): the write's or the final's completion. */ +static void op_chan_done_tick(ScrClosure *job) { + ScrStream *d = scr_box_get_ref(job->caps[0]); + bool final = scr_box_get_bool(job->caps[1]); + if (final) scr_stream_final_done(d, NULL); + else scr_stream_write_done(d, NULL); + scr_stream_release(d); +} + +/* The source's `await _promise`: the current deferred (+1). */ +static ScrPromise *op_chan_next_inv(ScrClosure *cb) { + OpChan *c = op_chan_of(cb); + ScrPromise *p = c->promise; + c->promise = NULL; + op_unref(c); + return p ? p : scr_promise_new(); +} + +static ScrError *op_chan_abort_error(void) { + ScrStr *message = scr_str_new("The operation was aborted", 25); + ScrError *e = scr_error_new(SCR_ERR_ERROR, message); + scr_str_release(message); + scr_str_release(e->name); + e->name = scr_str_new("AbortError", 10); + scr_error_set_code(e, "ABORT_ERR"); + e->name_present = true; + e->name_enumerable = true; + return e; +} + +/* After the source's await: process.nextTick(cb), then (unless done) the + * aborted check and a fresh deferred. */ +static void op_chan_final_async_wait(OpChan *c); + +/* The final's completion after `await promise`: process.nextTick(cb, err) */ +static void op_chan_final_async_done(ScrClosure *job) { + OpChan *c = op_chan_of(job); + if (c->d) { + ScrError *err = c->body_err ? scr_error_retain(c->body_err) : NULL; + ScrStream *d = scr_stream_retain(c->d); + scr_stream_final_done(d, err); + scr_stream_release(d); + } + op_unref(c); +} + +/* `await promise` resumed: the completion follows on the next tick */ +static void op_chan_final_async_resume(ScrClosure *job) { + OpChan *c = op_chan_of(job); + scr_next_tick(op_chan_closure((void *)&op_chan_final_async_done, c)); + op_unref(c); +} + +/* The final's async callback (run by the source's nextTick): it awaits + * the then() result, which may still be pending. */ +static void op_chan_final_async_tick(ScrClosure *job) { + OpChan *c = op_chan_of(job); + op_chan_final_async_wait(c); + op_unref(c); +} + +static void op_chan_final_async_wait(OpChan *c) { + if (c->body_settled) scr_queue_microtask(op_chan_closure((void *)&op_chan_final_async_resume, c)); + else c->final_waiting = true; +} + +static void op_chan_ack_inv(ScrClosure *cb) { + OpChan *c = op_chan_of(cb); + int settled = c->settled; + c->settled = CHAN_NONE; + if (settled == CHAN_FINAL_ASYNC) { + scr_next_tick(op_chan_closure((void *)&op_chan_final_async_tick, c)); + op_unref(c); + return; + } + if (c->d && (settled == CHAN_WRITE || settled == CHAN_FINAL)) { + ScrClosure *tick = scr_closure_new((void *)&op_chan_done_tick, 2); + tick->caps[0] = scr_box_new_obj(&scr_stream_retain_v, &scr_stream_release_v, &scr_stream_trace); + scr_box_set_ref(tick->caps[0], scr_stream_retain(c->d)); + tick->caps[1] = scr_box_new(SCR_BOX_BOOL); + scr_box_set_bool(tick->caps[1], settled == CHAN_FINAL); + scr_next_tick(tick); + } + if (settled != CHAN_FINAL && settled != CHAN_ABORT) { + if (c->aborted) { + ScrError *e = op_chan_abort_error(); + scr_throw_obj(e, &scr_error_retain_v, &scr_error_release_v, scr_error_trace_arg()); + } else if (c->d) { + op_chan_defer(c); + } + } + op_unref(c); +} + +/* `_resolve(value)`: the write's chunk or the final's done marker. */ +static void op_chan_settle(OpChan *c, ScrDyn *v /*moves*/, int kind) { + ScrPromise *p = c->resolve; + c->resolve = NULL; + if (!p) { + scr_dyn_release(v); + return; + } + c->settled = kind; + scr_promise_fulfill_ref(p, v, scr_dyn_retain_v, scr_dyn_release_v, NULL); + scr_promise_release(p); +} + +/* Duplexify's write(chunk, encoding, cb) */ +static void op_chan_write_inv(ScrClosure *cb, ScrStream *s, ScrBytes *chunk) { + OpChan *c = op_chan_of(cb); + op_chan_settle(c, scr_stream_chunk_value(s, chunk), CHAN_WRITE); + op_unref(c); +} + +/* Duplexify's final(cb) */ +static void op_chan_final_inv(ScrClosure *cb, ScrStream *s) { + (void)s; + OpChan *c = op_chan_of(cb); + op_chan_settle(c, scr_stream_from_done(), CHAN_FINAL); + op_unref(c); +} + +/* fromAsyncGen's ac.abort(err): the body's signal fires its abort + * listeners once (a body that declares the options argument); without an + * error the reason is null (destroy passes `err || null`). */ +static void op_chan_abort(OpChan *c, ScrError *err) { + c->aborted = true; + ScrClosure *abort = c->abort; + if (!abort) return; + c->abort = NULL; + ScrDyn *reason = err ? scr_dyn_from_error(err) : NULL; + if (!reason) reason = scr_dyn_new_null(); + ((void (*)(ScrClosure *, ScrDyn *))abort->fn)(abort, reason); /* reason moves in */ + if (scr_exc_pending()) scr_exc_clear(); + scr_closure_release(abort); +} + +/* destroy: fromAsyncGen's (ac.abort(); a source waiting for a write or + * the final is unblocked with the done marker and a no-op callback; + * cb(err)), then from()'s close of the function's iterator. caps: the + * channel and the from() destroy closure. */ +static void op_dup_destroy_inv(ScrClosure *cb, ScrStream *s, ScrError *err) { + OpChan *c = scr_box_get_ref(cb->caps[0]); + ScrClosure *from = scr_box_get_ref(cb->caps[1]); + op_chan_abort(c, err); + if (c->resolve) op_chan_settle(c, scr_stream_from_done(), CHAN_ABORT); + op_chan_retire(c); + op_unref(c); + op_from_destroy_inv(from, s, err); + scr_closure_release(from); +} + +typedef ScrGen *(*OpSourceFn)(ScrClosure *, ScrClosure *, ScrClosure *); +typedef ScrGen *(*OpStageFn)(ScrClosure *, ScrGen *); +typedef ScrGen *(*OpStageOptsFn)(ScrClosure *, ScrGen *, ScrDyn *); + +/* A new channel; with a signal (borrowed), the body's AbortController's + * abort() (borrowed) is kept for destroy and *opts is { signal } (+1). */ +static OpChan *op_chan_new(ScrClosure *abort, ScrDyn *signal, ScrDyn **opts) { + op_sentinels_init(); + static SCR_TL bool registered = false; + if (!registered) { + registered = true; + scr_atexit(op_chan_atexit); + } + OpChan *c = op_alloc(sizeof *c); + c->base.rc = 1; + c->base.drop = &op_chan_drop; + *opts = NULL; + if (signal) { + c->abort = scr_closure_retain(abort); + *opts = scr_dyn_new_obj(); + scr_dyn_obj_set(*opts, "signal", 6, scr_dyn_retain(signal)); + } + op_chan_defer(c); + return c; +} + +/* Duplex.from(fn) for an async generator function: the compiled stage + * (borrowed) takes the source generator and answers its own; source + * (borrowed) makes the source generator from next() and ack(); the + * compiler's helpers over the stage's generator are borrowed. With a + * signal, the stage also takes { signal }. +1, or NULL with the + * function's throw pending. */ +static ScrStream *op_duplex_from_gen(ScrClosure *stage, ScrClosure *source, ScrClosure *next, + ScrClosure *read, ScrClosure *ret, ScrClosure *thr, + ScrClosure *abort, ScrDyn *signal) { + ScrDyn *opts; + OpChan *c = op_chan_new(abort, signal, &opts); + ScrGen *src = ((OpSourceFn)source->fn)(source, op_chan_closure((void *)&op_chan_next_inv, c), + op_chan_closure((void *)&op_chan_ack_inv, c)); + ScrGen *g = NULL; /* src and opts move in */ + if (scr_exc_pending()) { + if (opts) scr_dyn_release(opts); + } else { + g = opts ? ((OpStageOptsFn)stage->fn)(stage, src, opts) : ((OpStageFn)stage->fn)(stage, src); + } + if (scr_exc_pending()) { + if (g) scr_gen_release(g); + op_unref(c); + return NULL; + } + OpFrom *f = op_alloc(sizeof *f); + f->base.rc = 1; + f->base.drop = &op_from_drop; + f->kind = FROM_ASYNC; + f->gen = g; + f->next = scr_closure_retain(next); + f->read = scr_closure_retain(read); + f->ret = scr_closure_retain(ret); + f->thr = scr_closure_retain(thr); + ScrClosure *destroy = scr_closure_new((void *)&op_dup_destroy_inv, 2); + destroy->caps[0] = scr_box_new_obj(&op_ref, &op_unref, NULL); + scr_box_set_ref(destroy->caps[0], op_ref(c)); + destroy->caps[1] = scr_box_new_obj(&scr_closure_retain_v, &scr_closure_release_v, &scr_closure_trace_v); + scr_box_set_ref(destroy->caps[1], op_from_closure((void *)&op_from_destroy_inv, f)); + /* Duplexify({ objectMode: true, highWaterMark: 1, write, final, destroy }) */ + ScrStream *d = scr_stream_new_duplex(1, 1, true, true, true, true, true, + op_from_closure((void *)&op_from_read_inv, f), &op_from_read_inv, + op_chan_closure((void *)&op_chan_write_inv, c), &op_chan_write_inv, + op_chan_closure((void *)&op_chan_final_inv, c), &op_chan_final_inv, + destroy, &op_dup_destroy_inv); + scr_stream_set_object_mode(d, true, true); + d->cls = "Duplexify"; + f->out = d; + op_unref(f); + c->d = scr_stream_retain(d); + c->live_next = op_chan_live; + if (op_chan_live) op_chan_live->live_prev = c; + op_chan_live = c; /* the reference c was created with */ + return d; +} + +ScrStream *scr_stream_duplex_from_gen(ScrClosure *stage, ScrClosure *source, ScrClosure *next, + ScrClosure *read, ScrClosure *ret, ScrClosure *thr) { + return op_duplex_from_gen(stage, source, next, read, ret, thr, NULL, NULL); +} + +ScrStream *scr_stream_duplex_from_gen_signal(ScrClosure *stage, ScrClosure *source, ScrClosure *next, + ScrClosure *read, ScrClosure *ret, ScrClosure *thr, + ScrClosure *abort, ScrDyn *signal) { + return op_duplex_from_gen(stage, source, next, read, ret, thr, abort, signal); +} + +/* ── Duplex.from(asyncFunction) ── duplexify.js: the function's promise + * must settle to a nullish value (else ERR_INVALID_RETURN_VALUE when the + * final awaits it), a return before the input was consumed destroys the + * Duplex, a rejection destroys it with the reason, and the Duplexify is + * writable only, its final waiting for the promise. */ + +typedef ScrPromise *(*OpAsyncStageFn)(ScrClosure *, ScrGen *); +typedef ScrPromise *(*OpAsyncStageOptsFn)(ScrClosure *, ScrGen *, ScrDyn *); +typedef ScrDyn *(*OpBoxFn)(ScrClosure *, ScrPromise *); + +typedef struct { + OpChan *c; /* +1 */ + ScrDyn *boxed; /* +1, the function's promise boxed */ +} OpAsyncBody; + +static void op_async_body_entry(ScrFiber *fiber, void *arg) { + (void)fiber; + OpAsyncBody b = *(OpAsyncBody *)arg; + free(arg); + OpChan *c = b.c; + ScrDyn *v = scr_await_ref(b.boxed->v.promise); /* NULL: undefined */ + ScrStream *d = c->d ? scr_stream_retain(c->d) : NULL; + if (!scr_exc_pending()) { + if (v && v->kind != SCR_DYN_NULL && v->kind != SCR_DYN_UNDEF) { + /* the then() callback throws: awaiting its result rejects */ + char detail[160]; + const char *got = scr_dyn_specific_type(v, detail, sizeof detail); + char msg[320]; + int n = snprintf(msg, sizeof msg, + "Expected nully to be returned from the \"body\" function but got %s.", got); + c->body_err = op_coded_error(SCR_ERR_TYPE, "ERR_INVALID_RETURN_VALUE", msg); + (void)n; + } else if (!c->finalized && d) { + /* returned without consuming the input: destroyer(d) */ + ScrError *e = op_chan_abort_error(); + scr_stream_release(scr_stream_destroy(d, e)); + scr_error_release(e); + } + if (v) scr_dyn_release(v); + } else { + ScrCaught *caught = scr_exc_take(); + ScrError *err = op_caught_error(caught); + scr_caught_release(caught); + if (d) scr_stream_release(scr_stream_destroy(d, err)); + scr_error_release(err); + } + if (scr_exc_pending()) scr_exc_clear(); + if (d) scr_stream_release(d); + c->body_settled = true; + if (c->final_waiting) { + c->final_waiting = false; + op_chan_final_async_wait(c); + } + op_unref(c); + scr_dyn_release(b.boxed); +} + +/* Duplexify's final(cb) for an async function body: finalized, then + * fromAsyncGen's final with the awaiting callback */ +static void op_chan_final_async_inv(ScrClosure *cb, ScrStream *s) { + (void)s; + OpChan *c = op_chan_of(cb); + c->finalized = true; + op_chan_settle(c, scr_stream_from_done(), CHAN_FINAL_ASYNC); + op_unref(c); +} + +/* fromAsyncGen's destroy alone (no from() iterator to close) */ +static void op_chan_destroy_inv(ScrClosure *cb, ScrStream *s, ScrError *err) { + OpChan *c = op_chan_of(cb); + op_chan_abort(c, err); + if (c->resolve) op_chan_settle(c, scr_stream_from_done(), CHAN_ABORT); + op_chan_retire(c); + op_unref(c); + scr_stream_destroy_done(s, err ? scr_error_retain(err) : NULL); +} + +/* Duplex.from(fn) for an async function: the compiled stage (borrowed) + * takes the source generator (and, with a signal, { signal }) and answers + * its promise; source and box (promise → dyn promise) borrowed. +1, or + * NULL with the function's throw pending. */ +static ScrStream *op_duplex_from_async_fn(ScrClosure *stage, ScrClosure *source, ScrClosure *box, + ScrClosure *abort, ScrDyn *signal) { + ScrDyn *opts; + OpChan *c = op_chan_new(abort, signal, &opts); + ScrGen *src = ((OpSourceFn)source->fn)(source, op_chan_closure((void *)&op_chan_next_inv, c), + op_chan_closure((void *)&op_chan_ack_inv, c)); + ScrPromise *p = NULL; /* src and opts move in */ + if (scr_exc_pending()) { + if (opts) scr_dyn_release(opts); + } else { + p = opts ? ((OpAsyncStageOptsFn)stage->fn)(stage, src, opts) + : ((OpAsyncStageFn)stage->fn)(stage, src); + } + if (scr_exc_pending()) { + if (p) scr_promise_release(p); + op_unref(c); + return NULL; + } + /* Duplexify({ objectMode: true, readable: false, write, final, destroy }) */ + ScrStream *d = scr_stream_new_duplex(16, 16, true, true, true, false, true, NULL, NULL, + op_chan_closure((void *)&op_chan_write_inv, c), &op_chan_write_inv, + op_chan_closure((void *)&op_chan_final_async_inv, c), + &op_chan_final_async_inv, + op_chan_closure((void *)&op_chan_destroy_inv, c), &op_chan_destroy_inv); + scr_stream_set_object_mode(d, true, true); + d->cls = "Duplexify"; + c->d = scr_stream_retain(d); + c->live_next = op_chan_live; + if (op_chan_live) op_chan_live->live_prev = c; + op_chan_live = c; /* the reference c was created with */ + /* value.then(onFulfilled, onRejected) */ + OpAsyncBody *b = malloc(sizeof *b); + if (!b) op_oom(); + b->c = op_ref(c); + b->boxed = ((OpBoxFn)box->fn)(box, p); /* p moves */ + scr_promise_release(scr_async_spawn_after(b->boxed->v.promise, &op_async_body_entry, b)); + return d; +} + +ScrStream *scr_stream_duplex_from_async_fn(ScrClosure *stage, ScrClosure *source, ScrClosure *box) { + return op_duplex_from_async_fn(stage, source, box, NULL, NULL); +} + +ScrStream *scr_stream_duplex_from_async_fn_signal(ScrClosure *stage, ScrClosure *source, + ScrClosure *box, ScrClosure *abort, + ScrDyn *signal) { + return op_duplex_from_async_fn(stage, source, box, abort, signal); +} + /* ── the promise operators ─────────────────────────────────────────── */ enum { PK_DYN, PK_F64, PK_BOOL, PK_STR, PK_VOID }; @@ -2051,6 +2859,8 @@ typedef struct { ScrDyn *fn; /* +1 or NULL */ ScrDyn *signal; /* +1 or NULL */ ScrDyn *acc; /* toArray's array / reduce's accumulator (+1) */ + ScrClosure *ctl; /* +1: reduce's ac.abort(), run when it ends, or NULL */ + ScrDyn *cb_opts; /* +1: the { signal } the reducer takes as its third argument, or NULL */ int op; int kind; /* the promise payload (PK_*) */ bool has_init, got_any, negate; @@ -2065,9 +2875,21 @@ static void op_fn_drop(OpObj *o) { if (a->fn) scr_dyn_release(a->fn); if (a->signal) scr_dyn_release(a->signal); if (a->acc) scr_dyn_release(a->acc); + if (a->ctl) scr_closure_release(a->ctl); + if (a->cb_opts) scr_dyn_release(a->cb_opts); free(a); } +/* reduce's `finally { ac.abort(); }`, before its promise settles. */ +static void op_fn_abort_ctl(OpFn *a) { + if (!a->ctl) return; + ScrClosure *ctl = a->ctl; + a->ctl = NULL; + ((void (*)(ScrClosure *))ctl->fn)(ctl); + if (scr_exc_pending()) scr_exc_clear(); + scr_closure_release(ctl); +} + static OpFn *op_fn_new(int op, int kind) { OpFn *a = op_alloc(sizeof *a); a->base.rc = 1; @@ -2081,6 +2903,7 @@ static OpFn *op_fn_new(int op, int kind) { /* Settles the operator's promise with v converted to its payload kind (a * value of the wrong kind rejects with the checked conversion's error). */ static void op_fn_resolve(OpFn *a, ScrDyn *v /*borrowed*/) { + op_fn_abort_ctl(a); switch (a->kind) { case PK_VOID: scr_promise_fulfill_void(a->p); @@ -2105,7 +2928,10 @@ static void op_fn_resolve(OpFn *a, ScrDyn *v /*borrowed*/) { scr_promise_reject_pending(a->p); } -static void op_fn_reject(OpFn *a, const ScrCaught *c) { op_reject(a->p, c); } +static void op_fn_reject(OpFn *a, const ScrCaught *c) { + op_fn_abort_ctl(a); + op_reject(a->p, c); +} static void op_fn_next(OpFn *a); @@ -2246,8 +3072,8 @@ static void op_fn_val_k(void *self, ScrDyn *v) { op_fn_next(a); return; } - ScrDyn *args[2] = {a->acc, v}; - ScrDyn *r = scr_dyn_call(a->fn, args, 2, "reducer"); + ScrDyn *args[3] = {a->acc, v, a->cb_opts}; + ScrDyn *r = scr_dyn_call(a->fn, args, a->cb_opts ? 3 : 2, "reducer"); scr_dyn_release(v); if (!r) { op_fn_close(a, scr_exc_take(), NULL); @@ -2329,7 +3155,7 @@ static bool op_map_options(const ScrDyn *options, double *concurrency, double *h /* map(fn, options) with fn already checked: +1 generator, or NULL with * the error pending. */ -static OpMap *op_map_make(ScrStream *s, ScrDyn *fn, ScrDyn *options, int mode) { +static OpMap *op_map_make(ScrStream *s, ScrDyn *fn, ScrDyn *options, int mode, ScrDyn *cb_opts) { op_sentinels_init(); if (!op_check_options(options)) return NULL; bool ok; @@ -2340,26 +3166,28 @@ static OpMap *op_map_make(ScrStream *s, ScrDyn *fn, ScrDyn *options, int mode) { if (signal) scr_dyn_release(signal); return NULL; } - OpMap *m = map_new(s, fn, mode, concurrency, hwm, signal); + OpMap *m = map_new(s, fn, mode, concurrency, hwm, signal, cb_opts); if (signal) scr_dyn_release(signal); return m; } -ScrStream *scr_stream_op_map(ScrStream *s, ScrDyn *fn, ScrDyn *options) { +ScrStream *scr_stream_op_map(ScrStream *s, ScrDyn *fn, ScrDyn *options, ScrDyn *cb_opts) { if (!op_check_fn(fn, "fn", 1)) return NULL; - OpMap *m = op_map_make(s, fn, options, MODE_MAP); + OpMap *m = op_map_make(s, fn, options, MODE_MAP, cb_opts); return m ? op_from_gen(&m->g) : NULL; } -ScrStream *scr_stream_op_filter(ScrStream *s, ScrDyn *fn, ScrDyn *options) { +ScrStream *scr_stream_op_filter(ScrStream *s, ScrDyn *fn, ScrDyn *options, ScrDyn *cb_opts) { if (!op_check_fn(fn, "fn", 1)) return NULL; - OpMap *m = op_map_make(s, fn, options, MODE_FILTER); + OpMap *m = op_map_make(s, fn, options, MODE_FILTER, cb_opts); return m ? op_from_gen(&m->g) : NULL; } -ScrStream *scr_stream_op_flat_map(ScrStream *s, ScrDyn *fn, ScrDyn *options) { +static ScrStream *op_flat_map(ScrStream *s, ScrDyn *fn, ScrDyn *options, ScrDyn *cb_opts, + ScrClosure *next, ScrClosure *read, ScrClosure *ret, + ScrClosure *thr, bool async_gen) { if (!op_check_fn(fn, "fn", 1)) return NULL; - OpMap *m = op_map_make(s, fn, options, MODE_MAP); + OpMap *m = op_map_make(s, fn, options, MODE_MAP, cb_opts); if (!m) return NULL; OpFlat *f = op_alloc(sizeof *f); gen_init(&f->g, &op_flat_body_drop); @@ -2367,9 +3195,34 @@ ScrStream *scr_stream_op_flat_map(ScrStream *s, ScrDyn *fn, ScrDyn *options) { f->g.ret = &flat_ret; f->g.thr = &flat_thr; f->values.g = &m->g; /* moves */ + if (next) { + f->gnext = scr_closure_retain(next); + f->gread = read ? scr_closure_retain(read) : NULL; + f->gret = scr_closure_retain(ret); + f->gthr = scr_closure_retain(thr); + f->gen_async = async_gen; + } return op_from_gen(&f->g); } +ScrStream *scr_stream_op_flat_map(ScrStream *s, ScrDyn *fn, ScrDyn *options, ScrDyn *cb_opts) { + return op_flat_map(s, fn, options, cb_opts, NULL, NULL, NULL, NULL, false); +} + +/* flatMap whose callback returns a compiled generator: the helpers over + * its type (borrowed) step the generators it yields from. */ +ScrStream *scr_stream_op_flat_map_async_gen(ScrStream *s, ScrDyn *fn, ScrDyn *options, + ScrDyn *cb_opts, ScrClosure *next, ScrClosure *read, + ScrClosure *ret, ScrClosure *thr) { + return op_flat_map(s, fn, options, cb_opts, next, read, ret, thr, true); +} + +ScrStream *scr_stream_op_flat_map_sync_gen(ScrStream *s, ScrDyn *fn, ScrDyn *options, + ScrDyn *cb_opts, ScrClosure *next, ScrClosure *ret, + ScrClosure *thr) { + return op_flat_map(s, fn, options, cb_opts, next, NULL, ret, thr, false); +} + /* drop(number, options) / take(number, options) */ static ScrStream *op_slice(ScrStream *s, ScrDyn *number, ScrDyn *options, bool take) { op_sentinels_init(); @@ -2454,8 +3307,8 @@ static void op_noop_listener(ScrClosure *cb, void *err) { (void)err; } -ScrPromise *scr_stream_op_reduce(ScrStream *s, ScrDyn *fn, ScrDyn *init, bool has_init, - ScrDyn *options, double kind) { +static ScrPromise *op_reduce(ScrStream *s, ScrDyn *fn, ScrDyn *init, bool has_init, + ScrDyn *options, double kind, ScrClosure *ctl, ScrDyn *cb_opts) { op_sentinels_init(); OpFn *a = op_fn_new(FN_REDUCE, (int)kind); if (!op_check_fn(fn, "reducer", 2)) return op_fn_reject_now(a); @@ -2471,6 +3324,7 @@ ScrPromise *scr_stream_op_reduce(ScrStream *s, ScrDyn *fn, ScrDyn *init, bool ha ScrDyn *reason = op_get(a->signal, "reason"); ScrError *e = op_abort_error(reason ? reason : scr_dyn_undefined()); if (reason) scr_dyn_release(reason); + /* (thrown before the controller exists) */ /* this.once('error', () => {}) */ ScrStr *name = scr_str_new("error", 5); scr_emitter_release(scr_emitter_on((ScrEmitter *)s, name, @@ -2486,40 +3340,97 @@ ScrPromise *scr_stream_op_reduce(ScrStream *s, ScrDyn *fn, ScrDyn *init, bool ha op_unref(a); return p; } + /* const ac = new AbortController() (options.signal's listener that + * aborts it too is registered by the caller) */ + if (ctl) { + a->ctl = scr_closure_retain(ctl); + a->cb_opts = cb_opts && cb_opts->kind != SCR_DYN_UNDEF ? scr_dyn_retain(cb_opts) : NULL; + } return op_fn_start(a); } +ScrPromise *scr_stream_op_reduce(ScrStream *s, ScrDyn *fn, ScrDyn *init, bool has_init, + ScrDyn *options, double kind) { + return op_reduce(s, fn, init, has_init, options, kind, NULL, NULL); +} + +/* reduce with a reducer that reads its { signal }: abort is ac.abort() + * (borrowed), cb_opts `{ signal: ac.signal }`. */ +ScrPromise *scr_stream_op_reduce_signal(ScrStream *s, ScrDyn *fn, ScrDyn *init, bool has_init, + ScrDyn *options, double kind, ScrClosure *abort, + ScrDyn *cb_opts) { + return op_reduce(s, fn, init, has_init, options, kind, abort, cb_opts); +} + +/* `options?.signal`: +1, undefined when absent. */ +ScrDyn *scr_stream_op_signal_of(ScrDyn *options) { + if (!options || options->kind == SCR_DYN_UNDEF || options->kind == SCR_DYN_NULL) + return scr_dyn_retain(scr_dyn_undefined()); + ScrDyn *sig = op_get(options, "signal"); + if (scr_exc_pending()) scr_exc_clear(); + return sig ? sig : scr_dyn_retain(scr_dyn_undefined()); +} + +/* `{ once: true }`: +1. */ +ScrDyn *scr_stream_op_once_options(void) { + ScrDyn *o = scr_dyn_new_obj(); + scr_dyn_obj_set(o, "once", 4, scr_dyn_new_bool(true)); + return o; +} + +/* `[options?.signal].filter(Boolean)` for AbortSignal.any: +1 array. */ +ScrDyn *scr_stream_op_signal_list(ScrDyn *options) { + ScrDyn *list = scr_dyn_new_arr(); + if (options && options->kind != SCR_DYN_UNDEF && options->kind != SCR_DYN_NULL) { + /* A signal that fails validateAbortSignal is left out: the operator + * itself throws Node's ERR_INVALID_ARG_TYPE for it. */ + bool ok; + ScrDyn *sig = op_signal(options, &ok); + if (sig) scr_dyn_arr_push(list, sig); /* moves */ + if (scr_exc_pending()) scr_exc_clear(); + } + return list; +} + +/* `{ signal }`, the callbacks' second argument: +1 object (borrows signal). */ +ScrDyn *scr_stream_op_signal_opts(ScrDyn *signal) { + ScrDyn *o = scr_dyn_new_obj(); + scr_dyn_obj_set(o, "signal", 6, scr_dyn_retain(signal)); + return o; +} + /* some/find/every/forEach: the loop over map's generator (filter's for * some, find and every). */ -static ScrPromise *op_gen_fn(ScrStream *s, ScrDyn *fn, ScrDyn *options, int op, int mode, int kind) { +static ScrPromise *op_gen_fn(ScrStream *s, ScrDyn *fn, ScrDyn *options, int op, int mode, int kind, + ScrDyn *cb_opts) { op_sentinels_init(); OpFn *a = op_fn_new(op, kind); if (!op_check_fn(fn, "fn", 1)) return op_fn_reject_now(a); - OpMap *m = op_map_make(s, fn, options, mode); + OpMap *m = op_map_make(s, fn, options, mode, cb_opts); if (!m) return op_fn_reject_now(a); a->src.g = &m->g; /* moves */ return op_fn_start(a); } -ScrPromise *scr_stream_op_some(ScrStream *s, ScrDyn *fn, ScrDyn *options) { - return op_gen_fn(s, fn, options, FN_SOME, MODE_FILTER, PK_BOOL); +ScrPromise *scr_stream_op_some(ScrStream *s, ScrDyn *fn, ScrDyn *options, ScrDyn *cb_opts) { + return op_gen_fn(s, fn, options, FN_SOME, MODE_FILTER, PK_BOOL, cb_opts); } -ScrPromise *scr_stream_op_find(ScrStream *s, ScrDyn *fn, ScrDyn *options) { - return op_gen_fn(s, fn, options, FN_FIND, MODE_FILTER, PK_DYN); +ScrPromise *scr_stream_op_find(ScrStream *s, ScrDyn *fn, ScrDyn *options, ScrDyn *cb_opts) { + return op_gen_fn(s, fn, options, FN_FIND, MODE_FILTER, PK_DYN, cb_opts); } -ScrPromise *scr_stream_op_for_each(ScrStream *s, ScrDyn *fn, ScrDyn *options) { - return op_gen_fn(s, fn, options, FN_FOR_EACH, MODE_FOREACH, PK_VOID); +ScrPromise *scr_stream_op_for_each(ScrStream *s, ScrDyn *fn, ScrDyn *options, ScrDyn *cb_opts) { + return op_gen_fn(s, fn, options, FN_FOR_EACH, MODE_FOREACH, PK_VOID, cb_opts); } /* every(fn, options) = !(await some.call(this, async (...args) => * !(await fn(...args)), options)) */ -ScrPromise *scr_stream_op_every(ScrStream *s, ScrDyn *fn, ScrDyn *options) { +ScrPromise *scr_stream_op_every(ScrStream *s, ScrDyn *fn, ScrDyn *options, ScrDyn *cb_opts) { op_sentinels_init(); OpFn *outer = op_fn_new(FN_EVERY, PK_BOOL); if (!op_check_fn(fn, "fn", 1)) return op_fn_reject_now(outer); - ScrPromise *some = op_gen_fn(s, fn, options, FN_EVERY, MODE_EVERY, PK_DYN); + ScrPromise *some = op_gen_fn(s, fn, options, FN_EVERY, MODE_EVERY, PK_DYN, cb_opts); ScrPromise *p = scr_promise_retain(outer->p); op_await(some, &op_every_k, outer); scr_promise_release(some); diff --git a/packages/runtime/src/scr_string.c b/packages/runtime/src/scr_string.c index 58272cf67..f94554642 100644 --- a/packages/runtime/src/scr_string.c +++ b/packages/runtime/src/scr_string.c @@ -2571,15 +2571,11 @@ ScrArr *scr_str_split_limit(ScrStr *s, ScrStr *sep, double limit_num) { while (count < 64 && (bytes = scr_str_split_span(s, sep, &cursor, false, &len))) slots[count++] = (uint64_t)(uintptr_t)(s->ascii ? scr_str_from_span_ascii(bytes, len) : scr_str_from_span(bytes, len)); - ScrArr *out = scr_arr_new_inline(SCR_ELEM_STR, count); + ScrArr *out = scr_arr_new_inline(SCR_ELEM_STR, count, false); if (count) { - /* A fresh inline array of exactly `count` slots: store the pieces and - * their states directly. */ - uint8_t *states = scr_arr_states_end(out); - for (size_t k = 0; k < count; k++) { - out->data[k] = slots[k]; - *scr_arr_state_in(states, k) = SCR_ARR_VALUE; - } + /* A fresh inline array of exactly `count` slots: store the pieces + * directly. */ + for (size_t k = 0; k < count; k++) out->data[k] = slots[k]; out->len = (uint32_t)count; out->filled = (uint32_t)count; } diff --git a/packages/runtime/src/scr_tls.c b/packages/runtime/src/scr_tls.c index b4d125cb2..e7436ab69 100644 --- a/packages/runtime/src/scr_tls.c +++ b/packages/runtime/src/scr_tls.c @@ -368,6 +368,10 @@ typedef struct ScrTlsSrv { /* maxVersion TLSv1.2: the ClientHello is pre-parsed so a hello that * offers only later versions gets OpenSSL's protocol_version alert. */ bool max_tls12; + /* new tls.TLSSocket(socket, { secureContext }): the context whose + * certificate and key this config serves (+1; NULL when cert/key are the + * config's own) */ + ScrSecureCtx *ctx; } ScrTlsSrv; /* The ALPN answers (static storage — mbedTLS keeps the pointers). Plain @@ -405,6 +409,28 @@ static ScrTlsSrv *scr_tls_srv_new(const char *cert, size_t cert_len, const char return s; } +/* A server config that serves a SecureContext's certificate and key. */ +static ScrTlsSrv *scr_tls_srv_from_ctx(ScrSecureCtx *ctx /*borrowed*/) { + scr_tls_rng_init(); + ScrTlsSrv *s = calloc(1, sizeof *s); + if (!s) scr_tls_oom(); + s->rc = 1; + mbedtls_x509_crt_init(&s->cert); + mbedtls_pk_init(&s->pk); + mbedtls_ssl_config_init(&s->conf); + if (mbedtls_ssl_config_defaults(&s->conf, MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_TRANSPORT_STREAM, + MBEDTLS_SSL_PRESET_DEFAULT) != 0) { + scr_tls_oom(); + } + mbedtls_ssl_conf_rng(&s->conf, mbedtls_ctr_drbg_random, &scr_tls_drbg); + mbedtls_ssl_conf_authmode(&s->conf, MBEDTLS_SSL_VERIFY_NONE); + s->ctx = scr_secure_ctx_retain(ctx); + if (mbedtls_ssl_conf_own_cert(&s->conf, &ctx->cert, &ctx->pk) != 0) { + scr_tls_bad_material("certificate/key pair", 0); + } + return s; +} + static ScrTlsSrv *scr_tls_srv_retain(ScrTlsSrv *s) { s->rc++; return s; @@ -419,6 +445,7 @@ static void scr_tls_srv_release(ScrTlsSrv *s) { mbedtls_x509_crt_free(&s->cert); mbedtls_pk_free(&s->pk); scr_tls_alpn_free(s->alpn); + scr_secure_ctx_release(s->ctx); free(s); } @@ -629,6 +656,15 @@ typedef struct ScrTlsSock { unsigned char *hello; /* the raw ClientHello flight, replayed at DONE */ size_t hello_len, hello_cap; ScrSecureCtx *sni_ctx; /* owned; the answer (NULL = default cert) */ + /* new tls.TLSSocket(socket, { isServer: true }): the program holds this + * socket before the handshake, so a failed handshake is its 'error' + * (tls.createServer's sockets fail without one) */ + bool wrapped; + unsigned char head[5]; /* the first bytes the peer sent (the error's wording) */ + size_t head_len; + /* the 'secure' event's listeners */ + ScrNetLs secure_ls; + bool settled; /* the socket closed: listeners added later never fire */ } ScrTlsSock; /* checkServerIdentity for an IP literal: the address must be one of the @@ -703,6 +739,16 @@ static int scr_tls_bio_send(void *ctx, const unsigned char *buf, size_t len) { return MBEDTLS_ERR_NET_SEND_FAILED; } +/* Keeps the first bytes a wrapped socket's peer sends: a handshake that + * fails on them reports what they looked like, as OpenSSL does. */ +static void scr_tls_note_head(ScrTlsSock *t, const unsigned char *buf, size_t n) { + if (!t->wrapped || t->head_len == sizeof t->head) return; + size_t take = sizeof t->head - t->head_len; + if (take > n) take = n; + memcpy(t->head + t->head_len, buf, take); + t->head_len += take; +} + static int scr_tls_bio_recv(void *ctx, unsigned char *buf, size_t len) { ScrTlsSock *t = (ScrTlsSock *)ctx; int fd = scr_net_sock_fd(t->sock); @@ -710,8 +756,12 @@ static int scr_tls_bio_recv(void *ctx, unsigned char *buf, size_t len) { /* bytes a consumer peeked and unshifted (the demux path) re-enter the * stream here, ahead of the kernel's */ size_t took = scr_net_sock_take_buffered(t->sock, (char *)buf, len); - if (took > 0) return (int)took; + if (took > 0) { + scr_tls_note_head(t, buf, took); + return (int)took; + } ssize_t n = read(fd, buf, len); + if (n > 0) scr_tls_note_head(t, buf, (size_t)n); if (n >= 0) return (int)n; /* 0 = EOF; mbedTLS maps it to CONN_EOF */ if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) { return MBEDTLS_ERR_SSL_WANT_READ; @@ -1026,6 +1076,43 @@ void scr_tls_sni_answer(ScrClosure *self, bool has_err, ScrSecureCtx *ctx /*move scr_net_sock_release(sock); } +/* A wrapped server socket's failed handshake, reported as Node reports it + * on the TLSSocket: a peer that closed first ends the stream, a reset is + * ECONNRESET, and bytes that are not a TLS record name what they were + * (OpenSSL's reasons without the per-process prefix and source location, + * SEMANTICS.md divergence 55). */ +static void scr_tls_wrapped_failure(ScrTlsSock *t, int r) { + if (r == MBEDTLS_ERR_SSL_CONN_EOF) { + scr_net_sock_transport_eof(t->sock); + return; + } + if (r == MBEDTLS_ERR_NET_CONN_RESET) { + scr_net_sock_transport_error(t->sock, "read ECONNRESET"); + return; + } + const unsigned char *h = t->head; + bool record = t->head_len >= 3 && h[0] >= 20 && h[0] <= 23 && h[1] == 3; + if (t->head_len >= 5 && !record) { + static const char *const http[] = { "GET ", "POST ", "HEAD ", "PATCH", "OPTIO", + "DELET", "TRACE", "PUT ", NULL }; + const char *reason = "error:0A00010B:SSL routines:tls_validate_record_header:wrong version number"; + const char *code = "ERR_SSL_WRONG_VERSION_NUMBER"; + for (size_t i = 0; http[i] != NULL; i++) { + if (memcmp(h, http[i], strlen(http[i])) == 0) { + reason = "error:0A00009C:SSL routines:tls_validate_record_header:http request"; + code = "ERR_SSL_HTTP_REQUEST"; + } + } + if (memcmp(h, "CONNE", 5) == 0) { + reason = "error:0A00009B:SSL routines:tls_validate_record_header:https proxy request"; + code = "ERR_SSL_HTTPS_PROXY_REQUEST"; + } + scr_net_sock_transport_error_code(t->sock, reason, code); + return; + } + scr_net_sock_transport_error(t->sock, "server TLS handshake failed"); +} + static int scr_tls_handshake(void *tctx) { ScrTlsSock *t = (ScrTlsSock *)tctx; if (t->cli != NULL && t->cli->no_protocols) { @@ -1046,6 +1133,10 @@ static int scr_tls_handshake(void *tctx) { scr_tls_current = NULL; if (r == 0) return 1; if (r == MBEDTLS_ERR_SSL_WANT_READ || r == MBEDTLS_ERR_SSL_WANT_WRITE) return 0; + if (t->srv != NULL && t->wrapped) { + scr_tls_wrapped_failure(t, r); + return -1; + } if (t->srv != NULL) { /* Node's server default: 'tlsClientError' with no listener destroys * the socket without an error event — exactly what portless (no @@ -1133,11 +1224,31 @@ static void scr_tls_free(void *tctx) { if (t->srv) scr_tls_srv_release(t->srv); if (t->cli) scr_tls_cli_free(t->cli); scr_net_ls_drop(&t->session_ls); + scr_net_ls_drop(&t->secure_ls); free(t->hello); scr_secure_ctx_release(t->sni_ctx); free(t); } +/* The 'secure' event: after a client's secureConnect listeners, as Node + * emits it. */ +static void scr_tls_after_established(void *tctx) { + ScrTlsSock *t = (ScrTlsSock *)tctx; + scr_net_fire0_this(&t->secure_ls, t->sock, SCR_DYNH_NET_SOCKET); + scr_net_ls_drop(&t->secure_ls); +} + +/* The closed socket settles: its 'secure' and 'session' listeners can no + * longer fire, and a listener that captures the socket would otherwise + * keep it, and this transport, alive (a handshake that fails never fires + * 'secure'). */ +static void scr_tls_settle(void *tctx) { + ScrTlsSock *t = (ScrTlsSock *)tctx; + t->settled = true; + scr_net_ls_drop(&t->secure_ls); + scr_net_ls_drop(&t->session_ls); +} + static const ScrNetTransportOps SCR_TLS_OPS = { .xread = scr_tls_xread, .xwrite = scr_tls_xwrite, @@ -1146,6 +1257,8 @@ static const ScrNetTransportOps SCR_TLS_OPS = { .pending = scr_tls_pending, .shutdown_write = scr_tls_shutdown_write, .free = scr_tls_free, + .settle = scr_tls_settle, + .after_established = scr_tls_after_established, }; /* ── the server surface ──────────────────────────────────────────────── */ @@ -2088,6 +2201,129 @@ ScrNetServer *scr_https_create_server_dyn(const ScrDyn *opts /*borrowed*/, return s; } +/* ── new tls.TLSSocket(socket, options) ───────────────────────────────── */ + +/* The server-mode wrap: a fresh TLS socket takes over raw's connection + * (scr_net_sock_adopt) and runs the server handshake over it. It serves + * `ctx` (options.secureContext, which the lowering passes apart from the + * record; borrowed, nullable) or the record's cert and key. The record + * reads at runtime like tls.createServer's: ALPNProtocols, minVersion and + * maxVersion apply, and options without a lowering throw the fence. Node + * never starts the handshake of a client-mode TLSSocket (no isServer), so + * that form throws the fence too. +1, or NULL with the exception pending. */ +static const char *const SCR_TLS_WRAP_FENCED_OPTIONS[] = { + "server", "session", "requestOCSP", "pskCallback", "enableTrace", NULL, +}; + +/* The socket-level options of a wrap that serves a secureContext, which + * the server-options walk would otherwise check: requestCert (client + * certificates are not modeled), SNICallback and ALPNCallback fence. + * False with the exception pending. */ +static bool scr_tls_wrap_socket_opts_check(const ScrDyn *record, const char *api) { + for (size_t i = 0; record != NULL && i < record->v.obj.len; i++) { + const ScrDynEntry *e = &record->v.obj.entries[i]; + if (e->value->kind == SCR_DYN_UNDEF) continue; + if (strcmp(e->key, "requestCert") == 0) { + if (!scr_tls_dyn_truthy(e->value)) continue; + scr_tls_opt_fence(api, "requestCert", + "client-certificate handshakes are not modeled (SEMANTICS.md divergence 55) — requestCert stays at Node's false default"); + return false; + } + if (strcmp(e->key, "SNICallback") == 0 || strcmp(e->key, "ALPNCallback") == 0) { + scr_tls_opt_fence(api, e->key, + "isServer, cert, key, secureContext, ALPNProtocols, minVersion and maxVersion are the implemented members"); + return false; + } + } + return true; +} + +ScrNetSocket *scr_tls_wrap_socket(ScrNetSocket *raw, const ScrDyn *opts /*borrowed*/, + ScrSecureCtx *ctx /*borrowed, nullable*/) { + static const char api[] = "new tls.TLSSocket"; + bool is_server = false; + const ScrDyn *record = opts != NULL && opts->kind == SCR_DYN_OBJ ? opts : NULL; + for (size_t i = 0; record != NULL && i < record->v.obj.len; i++) { + const ScrDynEntry *e = &record->v.obj.entries[i]; + if (e->value->kind == SCR_DYN_UNDEF) continue; + if (strcmp(e->key, "isServer") == 0) { + is_server = scr_tls_dyn_truthy(e->value); + continue; + } + if (strcmp(e->key, "secureContext") == 0) { + scr_tls_opt_fence(api, "secureContext", + "secureContext lowers as a member of an options object literal"); + return NULL; + } + for (size_t k = 0; SCR_TLS_WRAP_FENCED_OPTIONS[k] != NULL; k++) { + if (strcmp(e->key, SCR_TLS_WRAP_FENCED_OPTIONS[k]) == 0) { + scr_tls_opt_fence(api, e->key, + "isServer, cert, key, secureContext, ALPNProtocols, minVersion and maxVersion are the implemented members"); + return NULL; + } + } + } + if (!is_server) { + scr_tls_opt_fence(api, "isServer", + "Node starts no handshake for a client-mode TLSSocket; tls.connect({ socket }) runs the client handshake over an open socket"); + return NULL; + } + /* Node serves a secureContext as it is: the record's cert, key and + * other context options are not read then. The socket's own options + * still apply, so the ones without a lowering fence either way: + * requestCert asks for a client certificate this runtime cannot + * verify. */ + int min_version = 12, max_version = 13; + ScrBytes *cert = NULL, *key = NULL; + if (ctx == NULL) { + if (!scr_tls_versions_dyn(record, &min_version, &max_version)) return NULL; + if (!scr_tls_srv_opts_walk_ex(record, api, &cert, &key, true)) return NULL; + } else if (!scr_tls_wrap_socket_opts_check(record, api)) { + return NULL; + } + char **alpn = NULL; + const ScrDyn *protocols = record != NULL ? scr_dyn_obj_get(record, "ALPNProtocols", 13) : NULL; + if (protocols != NULL && protocols->kind != SCR_DYN_UNDEF && !scr_tls_alpn_dyn(protocols, &alpn)) { + scr_bytes_release(cert); + scr_bytes_release(key); + return NULL; + } + ScrTlsSrv *srv = ctx != NULL ? scr_tls_srv_from_ctx(ctx) + : scr_tls_srv_new((const char *)cert->data, cert->len, + (const char *)key->data, key->len, false); + scr_bytes_release(cert); + scr_bytes_release(key); + srv->alpn = alpn; /* moves */ + if (alpn != NULL) mbedtls_ssl_conf_alpn_protocols(&srv->conf, (const char **)srv->alpn); + if (!scr_tls_conf_versions(&srv->conf, min_version, max_version)) { + scr_tls_srv_release(srv); + scr_tls_opt_fence(api, "maxVersion", + "a version range with neither TLSv1.2 nor TLSv1.3 has no lowering"); + return NULL; + } + srv->max_tls12 = max_version == 12; + ScrNetSocket *t = scr_net_sock_adopt(raw); + if (t == NULL) { + scr_tls_srv_release(srv); + static const char msg[] = + "new tls.TLSSocket over a socket that is not connected, or is already wrapped, is not supported yet"; + scr_throw_error_msg(SCR_ERR_ERROR, msg, sizeof msg - 1); + return NULL; + } + ScrTlsSock *ts = calloc(1, sizeof *ts); + if (!ts) scr_tls_oom(); + mbedtls_ssl_init(&ts->ssl); + if (mbedtls_ssl_setup(&ts->ssl, &srv->conf) != 0) scr_tls_oom(); + ts->sock = t; + ts->srv = srv; /* moves */ + ts->wrapped = true; + if (srv->max_tls12) ts->sni_state = SCR_SNI_COLLECT; /* pre-parse the hello */ + mbedtls_ssl_set_bio(&ts->ssl, ts, scr_tls_bio_send, scr_tls_bio_recv, NULL); + scr_net_sock_set_transport(t, &SCR_TLS_OPS, ts); + scr_net_sock_adopt_start(t); + return t; +} + /* ── tls.connect (the TLS client socket) ──────────────────────────────── */ /* Node's inspect of a Buffer inside ERR_INVALID_ARG_VALUE's message: @@ -2239,7 +2475,7 @@ static const char *const SCR_TLS_CONNECT_FENCED_OPTIONS[] = { "localAddress", "localPort", "lookup", "minDHSize", "noDelay", "onread", "passphrase", "path", "pfx", "privateKeyEngine", "privateKeyIdentifier", "pskCallback", "readable", "secureContext", "secureOptions", "secureProtocol", "session", - "sessionIdContext", "sigalgs", "signal", "socket", "ticketKeys", + "sessionIdContext", "sigalgs", "signal", "ticketKeys", "writable", NULL, }; @@ -2255,6 +2491,7 @@ ScrNetSocket *scr_tls_connect_dyn(double port, ScrStr *host /*borrowed, nullable const ScrDyn *alpn_value = NULL; const ScrDyn *timeout_value = NULL; int min_version = 12, max_version = 13; + ScrNetSocket *wrap = NULL; /* options.socket: the open socket to take over */ bool ok = true; if (opts != NULL && opts->kind != SCR_DYN_UNDEF && opts->kind != SCR_DYN_NULL) { if (opts->kind != SCR_DYN_OBJ) { @@ -2322,6 +2559,15 @@ ScrNetSocket *scr_tls_connect_dyn(double port, ScrStr *host /*borrowed, nullable timeout_value = scr_tls_dyn_truthy(v) ? v : NULL; continue; } + if (strcmp(e->key, "socket") == 0) { + if (v->kind == SCR_DYN_HANDLE && v->v.handle.tag == SCR_DYNH_NET_SOCKET) { + wrap = (ScrNetSocket *)v->v.handle.ptr; + } else { + scr_tls_opt_fence("tls.connect", "socket", "a net.Socket is the implemented socket value"); + ok = false; + } + continue; + } if (strcmp(e->key, "servername") == 0) { if (v->kind == SCR_DYN_STR) servername = v->v.str; else { @@ -2333,7 +2579,7 @@ ScrNetSocket *scr_tls_connect_dyn(double port, ScrStr *host /*borrowed, nullable for (size_t k = 0; SCR_TLS_CONNECT_FENCED_OPTIONS[k] != NULL; k++) { if (strcmp(e->key, SCR_TLS_CONNECT_FENCED_OPTIONS[k]) == 0) { scr_tls_opt_fence("tls.connect", e->key, - "port/host/rejectUnauthorized/ca/servername/ALPNProtocols/minVersion/maxVersion/timeout are the implemented members of a runtime options record"); + "port/host/socket/rejectUnauthorized/ca/servername/ALPNProtocols/minVersion/maxVersion/timeout are the implemented members of a runtime options record"); ok = false; break; } @@ -2361,7 +2607,7 @@ ScrNetSocket *scr_tls_connect_dyn(double port, ScrStr *host /*borrowed, nullable timeout_ms = timeout_value->v.num; } } - if (ok && port < 0) { + if (ok && port < 0 && wrap == NULL) { scr_dyn_arg_type_fail("options.port", "of type number", scr_dyn_undefined()); ok = false; } @@ -2377,6 +2623,9 @@ ScrNetSocket *scr_tls_connect_dyn(double port, ScrStr *host /*borrowed, nullable * name otherwise (Node's servername default); "" sends no SNI. */ ScrStr *verify_host = dial_host; ScrStr *localhost_fallback = NULL; + /* over options.socket, the host that socket dialed (Node's socket._host) */ + ScrStr *socket_host = verify_host == NULL && wrap != NULL ? scr_net_sock_dial_name(wrap) : NULL; + if (socket_host != NULL) verify_host = socket_host; if (verify_host == NULL) { localhost_fallback = scr_str_new("localhost", 9); verify_host = localhost_fallback; @@ -2384,9 +2633,25 @@ ScrNetSocket *scr_tls_connect_dyn(double port, ScrStr *host /*borrowed, nullable /* Resolve for the dial only (the http client's rule): verify_host above * already holds the NAME, which is what SNI and certificate verification * must see. A null dial_host stays null — scr_net_connect's own arm. */ - ScrStr *dial_addr = dial_host != NULL ? scr_net_blocking_lookup(dial_host) : NULL; - ScrNetSocket *s = scr_net_connect(port, dial_addr, cb); /* cb fires post-handshake — secureConnect */ - if (dial_addr) scr_str_release(dial_addr); + ScrNetSocket *s; + if (wrap != NULL) { + s = scr_net_sock_adopt(wrap); + if (s == NULL) { + scr_tls_alpn_free(alpn); + scr_bytes_release(ca); + scr_closure_release(cb); + scr_str_release(localhost_fallback); + scr_str_release(socket_host); + static const char msg[] = + "tls.connect over a socket that is not connected, or is already wrapped, is not supported yet"; + scr_throw_error_msg(SCR_ERR_ERROR, msg, sizeof msg - 1); + return NULL; + } + } else { + ScrStr *dial_addr = dial_host != NULL ? scr_net_blocking_lookup(dial_host) : NULL; + s = scr_net_connect(port, dial_addr, cb); /* cb fires post-handshake — secureConnect */ + if (dial_addr) scr_str_release(dial_addr); + } ScrTlsCli *cli = scr_tls_cli_new2(verify_host, reject, ca != NULL ? (const char *)ca->data : NULL, ca != NULL ? ca->len : 0, !reject); @@ -2397,8 +2662,13 @@ ScrNetSocket *scr_tls_connect_dyn(double port, ScrStr *host /*borrowed, nullable } cli->no_protocols = !scr_tls_conf_versions(&cli->conf, min_version, max_version); scr_tls_cli_wrap(s, cli); + if (wrap != NULL) { + if (cb != NULL) scr_net_sock_on_established(s, cb, true); /* secureConnect */ + scr_net_sock_adopt_start(s); + } if (timeout_ms > 0) scr_net_sock_set_timeout(s, timeout_ms); scr_str_release(localhost_fallback); + scr_str_release(socket_host); scr_bytes_release(ca); return s; } @@ -2610,12 +2880,39 @@ ScrDyn *scr_tls_sock_alpn_protocol(ScrNetSocket *s) { return d; } +/* secureConnect: a client socket's 'connect' list fires at establishment + * (scr_net.c's transport pump), Node's secureConnect timing. Once TCP is up + * (a socket tls.connect({ socket }) took over is up from the start) the + * listener waits for the handshake instead. Server-side sockets never emit + * it. */ +static void scr_tls_add_secure_connect(ScrNetSocket *s, ScrTlsSock *t, ScrClosure *cb, bool once) { + if (t->srv != NULL) { + scr_closure_release(cb); + return; + } + if (scr_net_sock_connecting(s)) scr_net_sock_on_connect(s, cb, once); + else scr_net_sock_on_established(s, cb, once); +} + void scr_tls_sock_on_secure_connect(ScrNetSocket *s, ScrClosure *cb /*moves*/, bool once) { - if (scr_tls_sock_of(s) == NULL) { + ScrTlsSock *t = scr_tls_sock_of(s); + if (t == NULL) { scr_closure_release(cb); /* a plain socket never fires it, like Node */ return; } - scr_net_sock_on_connect(s, cb, once); /* fires at establishment — secureConnect timing */ + scr_tls_add_secure_connect(s, t, cb, once); +} + +/* The 'secure' event: the handshake completed (after secureConnect on a + * client). A plain socket never emits it, and a registration after the + * handshake comes too late, as in Node. */ +void scr_tls_sock_on_secure(ScrNetSocket *s, ScrClosure *cb /*moves*/, bool once) { + ScrTlsSock *t = scr_tls_sock_of(s); + if (t == NULL || t->established || t->settled) { + scr_closure_release(cb); + return; + } + scr_net_ls_add(&t->secure_ls, cb, NULL, once); } void scr_tls_sock_on_session(ScrNetSocket *s, ScrClosure *cb /*moves*/, void *fn, bool once) { @@ -2624,6 +2921,10 @@ void scr_tls_sock_on_session(ScrNetSocket *s, ScrClosure *cb /*moves*/, void *fn scr_closure_release(cb); /* a plain socket never fires it, like Node */ return; } + if (t->settled) { + scr_closure_release(cb); + return; + } scr_net_ls_add(&t->session_ls, cb, fn, once); if (t->established) scr_tls_fire_session(t); /* the ticket already arrived */ } @@ -2660,9 +2961,11 @@ static bool scr_tls_dynh_on(ScrNetSocket *s, const char *event, const ScrDyn *cb ScrTlsSock *t = scr_tls_sock_of(s); if (t == NULL) return false; if (strcmp(event, "secureConnect") == 0) { - /* a TLS socket's 'connect' list fires at establishment — exactly - * Node's secureConnect timing (scr_net.c's transport pump) */ - scr_net_sock_on_connect(s, scr_dyn_listener_closure0(cb), once); + scr_tls_add_secure_connect(s, t, scr_dyn_listener_closure0(cb), once); + return true; + } + if (strcmp(event, "secure") == 0) { + scr_tls_sock_on_secure(s, scr_dyn_listener_closure0(cb), once); return true; } if (strcmp(event, "session") == 0) { diff --git a/packages/runtime/src/scr_tls.h b/packages/runtime/src/scr_tls.h index fcb221b42..cc8e3336e 100644 --- a/packages/runtime/src/scr_tls.h +++ b/packages/runtime/src/scr_tls.h @@ -62,6 +62,10 @@ ScrDyn *scr_tls_sock_get_cipher(ScrNetSocket *s); /* +1: object, undefined or ScrDyn *scr_tls_sock_alpn_protocol(ScrNetSocket *s); /* +1: string, false or null */ void scr_tls_sock_on_secure_connect(ScrNetSocket *s, ScrClosure *cb /*moves*/, bool once); void scr_tls_sock_on_session(ScrNetSocket *s, ScrClosure *cb /*moves*/, void *fn, bool once); +/* The 'secure' event: fires when the handshake completes (after the + * secureConnect listeners on a client); released unread on a plain socket + * or after the handshake. */ +void scr_tls_sock_on_secure(ScrNetSocket *s, ScrClosure *cb /*moves*/, bool once); /* ── h2 over TLS (scr_tls.c ↔ scr_http2.c): the ALPN=h2 server wrap and * the https-authority client wrap. scr_http2.c calls both directly — @@ -93,6 +97,11 @@ ScrSecureCtx *scr_tls_create_secure_context(const char *cert, size_t cert_len, c * validations first, then the pem walk (+1, or NULL with the exception * pending). Borrowed. */ ScrSecureCtx *scr_tls_create_secure_context_dyn(const ScrDyn *opts); +/* new tls.TLSSocket(socket, options) in server mode: a fresh TLS socket + * takes over socket's connection and runs the server handshake, serving + * ctx (options.secureContext; borrowed, nullable) or the options record's + * cert and key. +1, or NULL with the exception pending. */ +ScrNetSocket *scr_tls_wrap_socket(ScrNetSocket *raw, const ScrDyn *opts /*borrowed*/, ScrSecureCtx *ctx /*borrowed, nullable*/); /* tls.getCACertificates(type): validateString + the documented name set, * then the compiler-rendered fence — always leaves an exception pending. */ void scr_tls_ca_certs_chk(const ScrDyn *type, const ScrStr *fence); diff --git a/packages/runtime/src/scr_webcrypto.c b/packages/runtime/src/scr_webcrypto.c index 546b24151..1b4207349 100644 --- a/packages/runtime/src/scr_webcrypto.c +++ b/packages/runtime/src/scr_webcrypto.c @@ -1,23 +1,29 @@ -/* WebCrypto's HMAC slice: crypto.subtle.importKey (raw HMAC keys), - * sign, verify and the SHA-1/SHA-2 digests, plus the CryptoKey values - * importKey answers. +/* WebCrypto's secret-key slice: crypto.subtle.importKey, generateKey and + * exportKey for HMAC and AES keys (importKey also for PBKDF2 and HKDF + * keys), HMAC sign and verify, the SHA-1/SHA-2 digests, PBKDF2 and HKDF + * deriveBits and deriveKey, the argument and key handling of AES encrypt + * and decrypt (whose cipher runs in scr_webcrypto_aes.c), and the + * CryptoKey values those methods answer. * * This unit is only the WebCrypto layer, modeled on Node 24's - * lib/internal/crypto/webcrypto.js and mac.js: Web IDL argument - * conversion, algorithm normalization, the CryptoKey handle, promise - * wrapping and Node's error shapes. The MACs and digests themselves come - * from node:crypto's digest core (scr_crypto_hmac_raw and - * scr_crypto_digest_raw in scr_lib.c), and results settle through the - * deferred crypto queue that node:crypto's callback forms use, so sign, - * verify and digest settle on a later loop turn like Node's thread-pool - * jobs while importKey settles at once. + * lib/internal/crypto/webcrypto.js, mac.js, aes.js and keys.js: Web IDL + * argument conversion, algorithm normalization, the CryptoKey handle, the + * JSON Web Key forms, promise wrapping and Node's error shapes. The MACs + * and digests themselves come from node:crypto's digest core + * (scr_crypto_hmac_raw and scr_crypto_digest_raw in scr_lib.c), and + * results settle through the deferred crypto queue that node:crypto's + * callback forms use, so sign, verify, digest and generateKey settle on a + * later loop turn like Node's thread-pool jobs while importKey and + * exportKey settle at once. * * Every argument and validation failure rejects the returned promise. * Algorithms Node recognizes but this slice does not implement (RSA, - * ECDSA, AES, SHA-3, ...) and the 'jwk' key format reject with a coded - * SC2020 Error instead of silently diverging. The compiler links the unit - * only into programs that call these methods (the webcrypto feature). */ + * ECDSA, AES-OCB, SHA-3, ...) and the key formats of asymmetric keys + * reject with a coded SC2020 Error instead of silently diverging. The + * compiler links the unit only into programs that call these methods + * (the webcrypto feature). */ #include "scr_runtime.h" +#include "scr_webcrypto.h" #include #include @@ -28,8 +34,9 @@ /* ── algorithm registry ─────────────────────────────────────────────── * The names Node 24 registers per operation (util.js's * kAlgorithmDefinitions with the conditional algorithms its OpenSSL - * build enables), matched case-insensitively. Only HMAC and the SHA-1/ - * SHA-2 digests are implemented. */ + * build enables), matched case-insensitively. HMAC, AES-CBC/CTR/GCM/KW + * keys, PBKDF2 and HKDF key imports and the SHA-1/SHA-2 digests are + * implemented. */ static const char *const scr_wc_import_names[] = { "AES-CBC", "AES-CTR", "AES-GCM", "AES-KW", "AES-OCB", "Argon2d", "Argon2i", "Argon2id", "ChaCha20-Poly1305", @@ -43,13 +50,21 @@ static const char *const scr_wc_sign_names[] = { "ECDSA", "Ed25519", "Ed448", "HMAC", "KMAC128", "KMAC256", "ML-DSA-44", "ML-DSA-65", "ML-DSA-87", "RSA-PSS", "RSASSA-PKCS1-v1_5", }; -static const char *const scr_wc_digest_names[] = { +/* generateKey and exportKey register the same algorithms. */ +static const char *const scr_wc_key_names[] = { + "AES-CBC", "AES-CTR", "AES-GCM", "AES-KW", "AES-OCB", + "ChaCha20-Poly1305", "ECDH", "ECDSA", "Ed25519", "Ed448", + "HMAC", "KMAC128", "KMAC256", "ML-DSA-44", "ML-DSA-65", + "ML-DSA-87", "ML-KEM-512", "ML-KEM-768", "ML-KEM-1024", "MLKEM768-P256", + "MLKEM768-X25519", "MLKEM1024-P384", "RSA-OAEP", "RSA-PSS", "RSASSA-PKCS1-v1_5", + "X25519", "X448", +}; +const char *const scr_wc_digest_names[] = { "SHA-1", "SHA-256", "SHA-384", "SHA-512", "SHA3-256", "SHA3-384", "SHA3-512", "cSHAKE128", "cSHAKE256", "KT128", "KT256", "TurboSHAKE128", "TurboSHAKE256", }; -#define SCR_WC_COUNT(names) (sizeof(names) / sizeof((names)[0])) /* The implemented hashes: WebCrypto name and node:crypto digest name. */ static const struct { @@ -75,7 +90,7 @@ static bool scr_wc_ascii_ieq(const ScrStr *s, const char *name) { } /* The canonical registered spelling of `name`, or NULL. */ -static const char *scr_wc_lookup(const char *const *names, size_t count, const ScrStr *name) { +const char *scr_wc_lookup(const char *const *names, size_t count, const ScrStr *name) { for (size_t i = 0; i < count; i++) if (scr_wc_ascii_ieq(name, names[i])) return names[i]; return NULL; @@ -89,11 +104,17 @@ static const char *scr_wc_native_hash(const char *name) { /* ── errors ────────────────────────────────────────────────────────── */ -static const char *const scr_wc_ordinals[] = {"1st", "2nd", "3rd", "4th", "5th"}; +const char *const scr_wc_ordinals[] = {"1st", "2nd", "3rd", "4th", "5th"}; -static void scr_wc_type_error(const char *code, const char *fmt, ...) - __attribute__((format(printf, 2, 3))); -static void scr_wc_type_error(const char *code, const char *fmt, ...) { +/* An argument's ordinal: unwrapKey's seven arguments run past the shared + * table. */ +static const char *scr_wc_ordinal(size_t index) { + static const char *const later[] = {"6th", "7th"}; + size_t shared = SCR_WC_COUNT(scr_wc_ordinals); + return index < shared ? scr_wc_ordinals[index] : later[index - shared]; +} + +void scr_wc_type_error(const char *code, const char *fmt, ...) { char message[512]; va_list ap; va_start(ap, fmt); @@ -105,7 +126,7 @@ static void scr_wc_type_error(const char *code, const char *fmt, ...) { } /* An operation or algorithm Node supports that this slice does not. */ -static void scr_wc_unsupported(const char *method, const char *what) { +void scr_wc_unsupported(const char *method, const char *what) { char message[256]; int n = snprintf(message, sizeof message, "crypto.subtle.%s with %s is not supported yet", method, what); @@ -113,7 +134,7 @@ static void scr_wc_unsupported(const char *method, const char *what) { scr_throw_error_msg_code(SCR_ERR_ERROR, message, (size_t)n, "SC2020"); } -static void scr_wc_unsupported_algorithm(const char *method, const char *name) { +void scr_wc_unsupported_algorithm(const char *method, const char *name) { char what[96]; snprintf(what, sizeof what, "the %s algorithm", name); scr_wc_unsupported(method, what); @@ -123,7 +144,7 @@ static void scr_wc_unsupported_algorithm(const char *method, const char *name) { * Each answers NULL/false with the TypeError pending. `prefix` is * "Failed to execute '' on 'SubtleCrypto'". */ -static bool scr_wc_is_object(const ScrDyn *v) { +bool scr_wc_is_object(const ScrDyn *v) { switch (v->kind) { case SCR_DYN_UNDEF: case SCR_DYN_NULL: @@ -139,14 +160,14 @@ static bool scr_wc_is_object(const ScrDyn *v) { } /* A typed reference capsule as its plain view; other values retained. */ -static ScrDyn *scr_wc_plain(ScrDyn *v) { +ScrDyn *scr_wc_plain(ScrDyn *v) { if (v->kind == SCR_DYN_TYPED_REF) return scr_dyn_typed_ref_materialize(v); return scr_dyn_retain(v); } /* BufferSource: the bytes of a TypedArray, DataView, Buffer or * ArrayBuffer as a u8 view (+1). */ -static ScrBytes *scr_wc_buffer_source(const char *prefix, size_t index, ScrDyn *value) { +ScrBytes *scr_wc_buffer_source(const char *prefix, size_t index, ScrDyn *value) { ScrDyn *plain = scr_wc_plain(value); if (!plain) return NULL; ScrBytes *view = NULL; @@ -156,21 +177,21 @@ static ScrBytes *scr_wc_buffer_source(const char *prefix, size_t index, ScrDyn * scr_wc_type_error("ERR_INVALID_ARG_TYPE", "%s: %s argument is not instance of ArrayBuffer, Buffer, TypedArray, or " "DataView.", - prefix, scr_wc_ordinals[index]); + prefix, scr_wc_ordinal(index)); } scr_dyn_release(plain); return view; } /* DOMString conversion (+1). */ -static ScrStr *scr_wc_dom_string(const ScrDyn *value) { return scr_dyn_string_coerce_js(value); } +ScrStr *scr_wc_dom_string(const ScrDyn *value) { return scr_dyn_string_coerce_js(value); } static const char *const scr_wc_key_formats[] = { "raw", "raw-public", "raw-seed", "raw-secret", "raw-private", "pkcs8", "spki", "jwk", }; /* KeyFormat: the canonical enum spelling, or NULL. */ -static const char *scr_wc_key_format(const char *prefix, ScrDyn *value) { +const char *scr_wc_key_format(const char *prefix, ScrDyn *value) { ScrStr *s = scr_wc_dom_string(value); if (!s) return NULL; for (size_t i = 0; i < SCR_WC_COUNT(scr_wc_key_formats); i++) { @@ -188,20 +209,26 @@ static const char *scr_wc_key_format(const char *prefix, ScrDyn *value) { } /* Node's canonical usage order; the bit is the index. */ -static const char *const scr_wc_usages[] = { +const char *const scr_wc_usages[] = { "encrypt", "decrypt", "sign", "verify", "deriveKey", "deriveBits", "wrapKey", "unwrapKey", "encapsulateKey", "encapsulateBits", "decapsulateKey", "decapsulateBits", }; -enum { SCR_WC_USAGE_SIGN = 1u << 2, SCR_WC_USAGE_VERIFY = 1u << 3 }; +/* The usage index of a KeyUsage string, or -1. */ +static int scr_wc_usage_index(const ScrStr *s) { + for (size_t k = 0; k < SCR_WC_COUNT(scr_wc_usages); k++) + if (s->len == strlen(scr_wc_usages[k]) && memcmp(s->data, scr_wc_usages[k], s->len) == 0) + return (int)k; + return -1; +} /* sequence over an array: the usage mask (-1 on failure). */ -static long scr_wc_key_usages(const char *prefix, size_t index, ScrDyn *value) { +long scr_wc_key_usages(const char *prefix, size_t index, ScrDyn *value) { ScrDyn *plain = scr_wc_plain(value); if (!plain) return -1; if (plain->kind != SCR_DYN_ARR) { scr_wc_type_error("ERR_INVALID_ARG_TYPE", "%s: %s argument cannot be converted to sequence.", - prefix, scr_wc_ordinals[index]); + prefix, scr_wc_ordinal(index)); scr_dyn_release(plain); return -1; } @@ -215,14 +242,11 @@ static long scr_wc_key_usages(const char *prefix, size_t index, ScrDyn *value) { scr_dyn_release(plain); return -1; } - size_t k = 0; - while (k < SCR_WC_COUNT(scr_wc_usages) && - !(s->len == strlen(scr_wc_usages[k]) && memcmp(s->data, scr_wc_usages[k], s->len) == 0)) - k++; - if (k == SCR_WC_COUNT(scr_wc_usages)) { + int k = scr_wc_usage_index(s); + if (k < 0) { scr_wc_type_error("ERR_INVALID_ARG_VALUE", "%s: %s argument[%.0f] '%.*s' is not a valid enum value of type KeyUsage.", - prefix, scr_wc_ordinals[index], i, (int)(s->len > 200 ? 200 : s->len), + prefix, scr_wc_ordinal(index), i, (int)(s->len > 200 ? 200 : s->len), s->data); scr_str_release(s); scr_dyn_release(plain); @@ -237,17 +261,17 @@ static long scr_wc_key_usages(const char *prefix, size_t index, ScrDyn *value) { /* ── algorithm normalization ────────────────────────────────────────── * normalizeAlgorithm(algorithm, op) for the members this slice reads: - * the canonical name, and for HMAC imports the hash and length. */ + * the canonical name, the HMAC hash and length, and AES key lengths. */ typedef struct { const char *name; /* canonical registered name */ - const char *hash; /* HMAC import: the normalized hash name */ + const char *hash; /* HMAC: the normalized hash name */ bool has_length; double length; } ScrWcAlgorithm; -static const char scr_wc_normalize_prefix[] = "Failed to normalize algorithm"; +const char scr_wc_normalize_prefix[] = "Failed to normalize algorithm"; -static void scr_wc_missing_member(const char *dict, const char *member) { +void scr_wc_missing_member(const char *dict, const char *member) { scr_wc_type_error("ERR_MISSING_OPTION", "%s: passed algorithm cannot be converted to '%s' because '%s' is required in " "'%s'.", @@ -255,16 +279,38 @@ static void scr_wc_missing_member(const char *dict, const char *member) { } /* Reads `key` off an algorithm dictionary (+1; undefined when absent). */ -static ScrDyn *scr_wc_member(const ScrDyn *dict, const char *key) { +ScrDyn *scr_wc_member(const ScrDyn *dict, const char *key) { if (dict->kind != SCR_DYN_OBJ) return scr_dyn_retain(scr_dyn_undefined()); ScrDyn *v = scr_dyn_obj_read(dict, key, strlen(key)); return v ? v : scr_dyn_retain(scr_dyn_undefined()); } +/* An [EnforceRange] integer conversion: the truncated value in [0, max], + * or false with Node's TypeError pending. `context` names the value + * ("length in passed algorithm", "3rd argument"). */ +static bool scr_wc_enforce_range(const char *prefix, const char *context, const ScrDyn *value, + double max, double *out) { + double x; + if (!scr_dyn_number_coerce_js(value, &x)) return false; + if (x != x || x == 1.0 / 0.0 || x == -1.0 / 0.0) { + scr_wc_type_error("ERR_INVALID_ARG_TYPE", "%s: %s is not a finite number.", prefix, context); + return false; + } + x = trunc(x); + if (x == 0) x = 0; + if (x < 0 || x > max) { + scr_wc_type_error("ERR_OUT_OF_RANGE", "%s: %s is outside the expected range of 0 to %.0f.", + prefix, context, max); + return false; + } + *out = x; + return true; +} + /* The name an AlgorithmIdentifier carries (+1), with the Algorithm * dictionary's missing-name TypeError. `dict` names the dictionary the * value converts to. */ -static ScrStr *scr_wc_algorithm_name(ScrDyn *identifier, const char *dict) { +ScrStr *scr_wc_algorithm_name(ScrDyn *identifier, const char *dict) { if (!scr_wc_is_object(identifier)) return scr_wc_dom_string(identifier); ScrDyn *plain = scr_wc_plain(identifier); if (!plain) return NULL; @@ -279,7 +325,7 @@ static ScrStr *scr_wc_algorithm_name(ScrDyn *identifier, const char *dict) { /* The digest a HashAlgorithmIdentifier names: canonical name, or NULL * with NotSupportedError / the SC2020 refusal pending. */ -static const char *scr_wc_digest_algorithm(ScrDyn *identifier, const char *method) { +const char *scr_wc_digest_algorithm(ScrDyn *identifier, const char *method) { ScrStr *name = scr_wc_algorithm_name(identifier, "Algorithm"); if (!name) return NULL; const char *canonical = scr_wc_lookup(scr_wc_digest_names, SCR_WC_COUNT(scr_wc_digest_names), name); @@ -295,11 +341,13 @@ static const char *scr_wc_digest_algorithm(ScrDyn *identifier, const char *metho return canonical; } -/* HmacImportParams over an object: hash (required, a SHA name), then the - * optional [EnforceRange] unsigned long length. */ -static bool scr_wc_hmac_import_params(ScrDyn *identifier, ScrWcAlgorithm *out) { +/* HmacImportParams / HmacKeyGenParams (`dict`) over an object: hash + * (required, a SHA name), then the optional [EnforceRange] unsigned long + * length, which cannot be 0 (`zero_error` names that DOMException). */ +static bool scr_wc_hmac_params(ScrDyn *identifier, const char *dict, const char *zero_error, + const char *method, ScrWcAlgorithm *out) { if (!scr_wc_is_object(identifier)) { - scr_wc_missing_member("HmacImportParams", "hash"); + scr_wc_missing_member(dict, "hash"); return false; } ScrDyn *plain = scr_wc_plain(identifier); @@ -307,7 +355,7 @@ static bool scr_wc_hmac_import_params(ScrDyn *identifier, ScrWcAlgorithm *out) { ScrDyn *hash = scr_wc_member(plain, "hash"); bool ok = true; if (hash->kind == SCR_DYN_UNDEF) { - scr_wc_missing_member("HmacImportParams", "hash"); + scr_wc_missing_member(dict, "hash"); ok = false; } ScrDyn *hash_value = NULL; @@ -335,7 +383,9 @@ static bool scr_wc_hmac_import_params(ScrDyn *identifier, ScrWcAlgorithm *out) { (hash_name->data[2] | 32) == 'a'; if (hash_name) scr_str_release(hash_name); if (ok && !sha) { - scr_throw_domex("NotSupportedError", "Only SHA hashes are supported in HmacImportParams"); + char message[96]; + snprintf(message, sizeof message, "Only SHA hashes are supported in %s", dict); + scr_throw_domex("NotSupportedError", message); ok = false; } } @@ -343,34 +393,23 @@ static bool scr_wc_hmac_import_params(ScrDyn *identifier, ScrWcAlgorithm *out) { ScrDyn *length = scr_wc_member(plain, "length"); if (length->kind != SCR_DYN_UNDEF) { double x; - if (!scr_dyn_number_coerce_js(length, &x)) ok = false; - else if (x != x || x == 1.0 / 0.0 || x == -1.0 / 0.0) { - scr_wc_type_error("ERR_INVALID_ARG_TYPE", - "%s: length in passed algorithm is not a finite number.", - scr_wc_normalize_prefix); + if (!scr_wc_enforce_range(scr_wc_normalize_prefix, "length in passed algorithm", length, + 4294967295.0, &x)) + ok = false; + else if (x == 0) { + char message[96]; + snprintf(message, sizeof message, "%s.length cannot be 0", dict); + scr_throw_domex(zero_error, message); ok = false; } else { - x = trunc(x); - if (x == 0) x = 0; - if (x < 0 || x > 4294967295.0) { - scr_wc_type_error("ERR_OUT_OF_RANGE", - "%s: length in passed algorithm is outside the expected range of 0 to " - "4294967295.", - scr_wc_normalize_prefix); - ok = false; - } else if (x == 0) { - scr_throw_domex("DataError", "HmacImportParams.length cannot be 0"); - ok = false; - } else { - out->has_length = true; - out->length = x; - } + out->has_length = true; + out->length = x; } } scr_dyn_release(length); } if (ok) { - out->hash = scr_wc_digest_algorithm(hash_value, "importKey"); + out->hash = scr_wc_digest_algorithm(hash_value, method); if (!out->hash) ok = false; } if (hash_value) scr_dyn_release(hash_value); @@ -379,11 +418,51 @@ static bool scr_wc_hmac_import_params(ScrDyn *identifier, ScrWcAlgorithm *out) { return ok; } -/* normalizeAlgorithm for importKey, sign/verify (`names`) — false with - * the error pending. Only HMAC parameters are read; any other recognized - * algorithm is refused by the caller. */ -static bool scr_wc_normalize(ScrDyn *identifier, const char *const *names, size_t count, - bool import, ScrWcAlgorithm *out) { +/* AesKeyGenParams / AesDerivedKeyParams (`dict`): the required + * [EnforceRange] unsigned short length, 128, 192 or 256. */ +static bool scr_wc_aes_length_params(ScrDyn *identifier, const char *dict, ScrWcAlgorithm *out) { + ScrDyn *plain = scr_wc_plain(identifier); + if (!plain) return false; + ScrDyn *length = scr_wc_member(plain, "length"); + bool ok = false; + double x; + if (length->kind == SCR_DYN_UNDEF) scr_wc_missing_member(dict, "length"); + else if (scr_wc_enforce_range(scr_wc_normalize_prefix, "length in passed algorithm", length, + 65535.0, &x)) { + if (x != 128 && x != 192 && x != 256) { + scr_throw_domex("OperationError", "AES key length must be 128, 192, or 256 bits"); + } else { + out->has_length = true; + out->length = x; + ok = true; + } + } + scr_dyn_release(length); + scr_dyn_release(plain); + return ok; +} + +static bool scr_wc_is_aes(const char *name) { + return strcmp(name, "AES-CBC") == 0 || strcmp(name, "AES-CTR") == 0 || + strcmp(name, "AES-GCM") == 0 || strcmp(name, "AES-KW") == 0; +} + +static bool scr_wc_is_kdf(const char *name) { + return strcmp(name, "PBKDF2") == 0 || strcmp(name, "HKDF") == 0; +} + +typedef enum { + SCR_WC_OP_IMPORT, + SCR_WC_OP_SIGN, + SCR_WC_OP_GENERATE, +} ScrWcOp; + +/* normalizeAlgorithm for importKey, sign/verify and generateKey (`names`) + * — false with the error pending. Only the dictionaries of the + * implemented algorithms are read; any other recognized algorithm is + * refused by the caller. */ +static bool scr_wc_normalize(ScrDyn *identifier, const char *const *names, size_t count, ScrWcOp op, + ScrWcAlgorithm *out) { memset(out, 0, sizeof *out); ScrStr *name = scr_wc_algorithm_name(identifier, "Algorithm"); if (!name) return false; @@ -393,19 +472,27 @@ static bool scr_wc_normalize(ScrDyn *identifier, const char *const *names, size_ scr_throw_domex("NotSupportedError", "Unrecognized algorithm name"); return false; } - if (import && strcmp(out->name, "HMAC") == 0) return scr_wc_hmac_import_params(identifier, out); + bool hmac = strcmp(out->name, "HMAC") == 0; + if (op == SCR_WC_OP_IMPORT && hmac) + return scr_wc_hmac_params(identifier, "HmacImportParams", "DataError", "importKey", out); + if (op == SCR_WC_OP_GENERATE && hmac) + return scr_wc_hmac_params(identifier, "HmacKeyGenParams", "OperationError", "generateKey", out); + if (op == SCR_WC_OP_GENERATE && scr_wc_is_aes(out->name)) + return scr_wc_aes_length_params(identifier, "AesKeyGenParams", out); return true; } /* ── CryptoKey ───────────────────────────────────────────────────────── - * A secret HMAC key: the bytes, the hash, the bit length, the usage mask - * and the extractable flag. The algorithm and usages getters answer the - * same object on every read (Node caches its clones), built on first - * read. The bytes are cleared when the last reference goes. */ + * A secret key: the algorithm name, the bytes, the HMAC hash, the bit + * length (HMAC and AES keys), the usage mask and the extractable flag. + * The algorithm and usages getters answer the same object on every read + * (Node caches its clones), built on first read. The bytes are cleared + * when the last reference goes. */ typedef struct ScrCryptoKey { size_t rc; - const char *hash; /* WebCrypto hash name */ - double length; /* bits */ + const char *name; /* canonical algorithm name */ + const char *hash; /* HMAC: WebCrypto hash name */ + double length; /* HMAC and AES: bits */ unsigned usages; bool extractable; ScrDyn *algorithm; /* cached getter results, or NULL */ @@ -436,36 +523,44 @@ static ScrCryptoKey *scr_crypto_key_of(const ScrDyn *value) { bool scr_webcrypto_is_crypto_key(const ScrDyn *value) { if (value->kind == SCR_DYN_TYPED_REF) return false; - return scr_crypto_key_of(value) != NULL; + return scr_crypto_key_of(value) != NULL || (scr_wc_asymmetric && scr_wc_asymmetric->is_key(value)); } -static ScrDyn *scr_wc_cstr(const char *s) { +ScrDyn *scr_wc_cstr(const char *s) { ScrStr *str = scr_str_new(s, strlen(s)); ScrDyn *out = scr_dyn_new_str(str); scr_str_release(str); return out; } +/* Node's algorithm objects: { name, length, hash } for HMAC keys, + * { name, length } for AES keys and { name } for PBKDF2 and HKDF keys. */ static ScrDyn *scr_crypto_key_algorithm(ScrCryptoKey *key) { if (!key->algorithm) { - ScrDyn *hash = scr_dyn_new_obj(); - scr_dyn_obj_set(hash, "name", 4, scr_wc_cstr(key->hash)); ScrDyn *algorithm = scr_dyn_new_obj(); - scr_dyn_obj_set(algorithm, "name", 4, scr_wc_cstr("HMAC")); - scr_dyn_obj_set(algorithm, "length", 6, scr_dyn_new_num(key->length)); - scr_dyn_obj_set(algorithm, "hash", 4, hash); + scr_dyn_obj_set(algorithm, "name", 4, scr_wc_cstr(key->name)); + if (!scr_wc_is_kdf(key->name)) + scr_dyn_obj_set(algorithm, "length", 6, scr_dyn_new_num(key->length)); + if (key->hash) { + ScrDyn *hash = scr_dyn_new_obj(); + scr_dyn_obj_set(hash, "name", 4, scr_wc_cstr(key->hash)); + scr_dyn_obj_set(algorithm, "hash", 4, hash); + } key->algorithm = algorithm; } return scr_dyn_retain(key->algorithm); } +/* The usages as a fresh array in Node's canonical order (+1). */ +static ScrDyn *scr_wc_usage_array(unsigned usages) { + ScrDyn *list = scr_dyn_new_arr(); + for (size_t i = 0; i < SCR_WC_COUNT(scr_wc_usages); i++) + if (usages & (1u << i)) scr_dyn_arr_push(list, scr_wc_cstr(scr_wc_usages[i])); + return list; +} + static ScrDyn *scr_crypto_key_usages(ScrCryptoKey *key) { - if (!key->usage_list) { - ScrDyn *list = scr_dyn_new_arr(); - for (size_t i = 0; i < SCR_WC_COUNT(scr_wc_usages); i++) - if (key->usages & (1u << i)) scr_dyn_arr_push(list, scr_wc_cstr(scr_wc_usages[i])); - key->usage_list = list; - } + if (!key->usage_list) key->usage_list = scr_wc_usage_array(key->usages); return scr_dyn_retain(key->usage_list); } @@ -540,8 +635,9 @@ static const ScrDynHandleOps scr_crypto_key_ops = { .symbol_get = scr_crypto_key_symbol_get, }; -static ScrDyn *scr_crypto_key_new(const unsigned char *data, size_t len, const char *hash, - double length, unsigned usages, bool extractable) { +static ScrDyn *scr_crypto_key_new(const unsigned char *data, size_t len, const char *name, + const char *hash, double length, unsigned usages, + bool extractable) { static SCR_TL bool installed; if (!installed) { installed = true; @@ -550,6 +646,7 @@ static ScrDyn *scr_crypto_key_new(const unsigned char *data, size_t len, const c ScrCryptoKey *key = malloc(sizeof *key + (len ? len : 1)); if (!key) scr_trap("scriptc: out of memory\n"); key->rc = 1; + key->name = name; key->hash = hash; key->length = length; key->usages = usages; @@ -563,19 +660,282 @@ static ScrDyn *scr_crypto_key_new(const unsigned char *data, size_t len, const c return box; } +/* numBitsToBytes: whole bytes for `bits`, rounding up. */ +static size_t scr_wc_bits_to_bytes(double bits) { + return (size_t)(floor(bits / 8) + floor((7 + fmod(bits, 8)) / 8)); +} + +/* Clears the unused low bits of the final byte of a `bits`-long key + * (truncateToBitLength). */ +static void scr_wc_truncate_bits(unsigned char *data, size_t len, double bits) { + int extra = (int)fmod(bits, 8); + if (extra && len) data[len - 1] = (unsigned char)(data[len - 1] & (0xff << (8 - extra))); +} + +/* The usages each key algorithm accepts. */ +static unsigned scr_wc_allowed_usages(const char *name) { + if (strcmp(name, "HMAC") == 0) return SCR_WC_USAGE_SIGN | SCR_WC_USAGE_VERIFY; + if (strcmp(name, "AES-KW") == 0) return SCR_WC_USAGE_WRAP_KEY | SCR_WC_USAGE_UNWRAP_KEY; + if (scr_wc_is_kdf(name)) return SCR_WC_USAGE_DERIVE_KEY | SCR_WC_USAGE_DERIVE_BITS; + return SCR_WC_USAGE_ENCRYPT | SCR_WC_USAGE_DECRYPT | SCR_WC_USAGE_WRAP_KEY | + SCR_WC_USAGE_UNWRAP_KEY; +} + +/* validateKeyUsages: SyntaxError for a usage outside the algorithm's. */ +static bool scr_wc_check_usages(const char *name, long usages) { + if (!(usages & ~(long)scr_wc_allowed_usages(name))) return true; + char message[96]; + snprintf(message, sizeof message, "Unsupported key usage for %s%s key", + scr_wc_is_kdf(name) ? "a " : "", name); + scr_throw_domex("SyntaxError", message); + return false; +} + +/* The JWK "alg" of an HMAC hash or an AES key, or NULL. */ +static const char *scr_wc_jwk_alg(const char *name, const char *hash, double length, char *buf, + size_t size) { + if (strcmp(name, "HMAC") == 0) { + if (strcmp(hash, "SHA-1") == 0) return "HS1"; + if (strcmp(hash, "SHA-256") == 0) return "HS256"; + if (strcmp(hash, "SHA-384") == 0) return "HS384"; + if (strcmp(hash, "SHA-512") == 0) return "HS512"; + return NULL; + } + if (!scr_wc_is_aes(name)) return NULL; + snprintf(buf, size, "A%.0f%s", length, name + 4); + return buf; +} + +/* ── JSON Web Keys ───────────────────────────────────────────────────── + * The JsonWebKey dictionary members a secret key reads, converted in Web + * IDL's member order (every DOMString member converts, so a Symbol or a + * throwing toString in any of them rejects like Node). */ +typedef struct { + ScrStr *alg, *k, *kty, *use; + bool has_ext, ext; + ScrDyn *key_ops; /* array of strings, or NULL */ +} ScrWcJwk; + +static void scr_wc_jwk_drop(ScrWcJwk *jwk) { + if (jwk->alg) scr_str_release(jwk->alg); + if (jwk->k) scr_str_release(jwk->k); + if (jwk->kty) scr_str_release(jwk->kty); + if (jwk->use) scr_str_release(jwk->use); + if (jwk->key_ops) scr_dyn_release(jwk->key_ops); + memset(jwk, 0, sizeof *jwk); +} + +/* A DOMString dictionary member: NULL with *ok when absent; NULL with + * !*ok and the TypeError pending on failure. */ +static ScrStr *scr_wc_jwk_string(const char *prefix, const ScrDyn *dict, const char *key, bool *ok) { + ScrDyn *value = scr_wc_member(dict, key); + ScrStr *out = NULL; + if (value->kind == SCR_DYN_SYMBOL) { + scr_wc_type_error("ERR_INVALID_ARG_TYPE", + "%s: %s in 2nd argument is a Symbol and cannot be converted to a string.", + prefix, key); + *ok = false; + } else if (value->kind != SCR_DYN_UNDEF) { + out = scr_wc_dom_string(value); + if (!out) *ok = false; + } + scr_dyn_release(value); + return out; +} + +static bool scr_wc_jwk_convert(const char *prefix, ScrDyn *value, ScrWcJwk *out) { + memset(out, 0, sizeof *out); + if (value->kind == SCR_DYN_UNDEF || value->kind == SCR_DYN_NULL) return true; + if (!scr_wc_is_object(value)) { + scr_wc_type_error("ERR_INVALID_ARG_TYPE", "%s: 2nd argument cannot be converted to a dictionary", + prefix); + return false; + } + ScrDyn *dict = scr_wc_plain(value); + if (!dict) return false; + static const char *const members[] = {"alg", "crv", "d", "dp", "dq", "e", "ext", + "k", "key_ops", "kty", "n", "p", "priv", "pub", + "q", "qi", "use", "x", "y"}; + bool ok = true; + for (size_t i = 0; ok && i < SCR_WC_COUNT(members); i++) { + const char *key = members[i]; + if (strcmp(key, "ext") == 0) { + ScrDyn *ext = scr_wc_member(dict, key); + if (ext->kind != SCR_DYN_UNDEF) { + out->has_ext = true; + out->ext = scr_dyn_truthy(ext); + } + scr_dyn_release(ext); + } else if (strcmp(key, "key_ops") == 0) { + ScrDyn *ops = scr_wc_member(dict, key); + if (ops->kind != SCR_DYN_UNDEF) { + ScrDyn *list = scr_wc_plain(ops); + if (!list) ok = false; + else if (list->kind != SCR_DYN_ARR) { + scr_wc_type_error("ERR_INVALID_ARG_TYPE", + "%s: key_ops in 2nd argument cannot be converted to sequence.", prefix); + scr_dyn_release(list); + ok = false; + } else { + ScrDyn *strings = scr_dyn_new_arr(); + double n = scr_dyn_arr_len(list); + for (double j = 0; ok && j < n; j++) { + ScrDyn *item = scr_dyn_arr_at(list, j); + ScrStr *s = scr_wc_dom_string(item); + scr_dyn_release(item); + if (!s) ok = false; + else { + scr_dyn_arr_push(strings, scr_dyn_new_str(s)); + scr_str_release(s); + } + } + scr_dyn_release(list); + if (ok) out->key_ops = strings; + else scr_dyn_release(strings); + } + } + scr_dyn_release(ops); + } else { + ScrStr *s = scr_wc_jwk_string(prefix, dict, key, &ok); + if (strcmp(key, "alg") == 0) out->alg = s; + else if (strcmp(key, "k") == 0) out->k = s; + else if (strcmp(key, "kty") == 0) out->kty = s; + else if (strcmp(key, "use") == 0) out->use = s; + else if (s) scr_str_release(s); + } + } + scr_dyn_release(dict); + if (!ok) scr_wc_jwk_drop(out); + return ok; +} + +static bool scr_wc_str_is(const ScrStr *s, const char *literal) { + return s && s->len == strlen(literal) && memcmp(s->data, literal, s->len) == 0; +} + +/* validateJwk for an oct key, then the key bytes (+1): k decodes with + * Node's lenient base64 decoder, so any string answers bytes. */ +static ScrBytes *scr_wc_jwk_secret(const ScrWcJwk *jwk, bool extractable, long usages, + const char *expected_use) { + if (!jwk->kty) { + scr_throw_domex("DataError", "Invalid keyData"); + return NULL; + } + if (!scr_wc_str_is(jwk->kty, "oct")) { + scr_throw_domex("DataError", "Invalid JWK \"kty\" Parameter"); + return NULL; + } + if (!jwk->k) { + scr_throw_domex("DataError", "Invalid keyData"); + return NULL; + } + if (usages != 0 && jwk->use && !scr_wc_str_is(jwk->use, expected_use)) { + scr_throw_domex("DataError", "Invalid JWK \"use\" Parameter"); + return NULL; + } + if (jwk->key_ops) { + long seen = 0; + double n = scr_dyn_arr_len(jwk->key_ops); + for (double i = 0; i < n; i++) { + ScrDyn *op = scr_dyn_arr_at(jwk->key_ops, i); + int k = scr_wc_usage_index(op->v.str); + scr_dyn_release(op); + if (k < 0) continue; + if (seen & (1L << k)) { + scr_throw_domex("DataError", "Duplicate key operation"); + return NULL; + } + seen |= 1L << k; + } + if ((seen & usages) != usages) { + scr_throw_domex("DataError", "Key operations and usage mismatch"); + return NULL; + } + } + if (jwk->has_ext && !jwk->ext && extractable) { + scr_throw_domex("DataError", "JWK \"ext\" Parameter and extractable mismatch"); + return NULL; + } + ScrStr *encoding = scr_str_new("base64url", 9); + ScrBytes *bytes = scr_bytes_from_str(jwk->k, encoding); + scr_str_release(encoding); + return bytes; +} + /* ── the operations ─────────────────────────────────────────────────── * Each takes its argument vector as one dyn array (borrowed) and answers * a +1 promise. */ -static ScrPromise *scr_wc_rejected(void) { +const ScrWcAsymmetric *scr_wc_asymmetric = NULL; + +static const char *const scr_wc_asymmetric_names[] = {"ECDSA", "Ed25519", "RSA-PSS", "RSASSA-PKCS1-v1_5"}; + +/* Whether the AlgorithmIdentifier at args[index] names ECDSA, + * RSASSA-PKCS1-v1_5, RSA-PSS or Ed25519, read without side effects or errors: a + * string, or the name member of an object (a statically typed one through + * its plain view). A value that does not read cleanly takes the HMAC path, + * which reports its errors. */ +static const char *scr_wc_asymmetric_name(const ScrDyn *args, size_t index) { + if ((size_t)scr_dyn_arr_len(args) <= index) return NULL; + ScrDyn *identifier = scr_dyn_arr_at(args, (double)index); + ScrDyn *plain = scr_wc_plain(identifier); + if (!plain) scr_exc_clear(); + const char *found = NULL; + if (plain) { + const ScrDyn *name = plain; + if (plain->kind == SCR_DYN_OBJ) name = scr_dyn_obj_get(plain, "name", 4); + if (name && name->kind == SCR_DYN_STR) + found = scr_wc_lookup(scr_wc_asymmetric_names, SCR_WC_COUNT(scr_wc_asymmetric_names), + name->v.str); + scr_dyn_release(plain); + } + scr_dyn_release(identifier); + return found; +} + +/* Whether `value` is an ECDSA, Ed25519 or RSA CryptoKey, which + * scr_webcrypto_pki.c holds; wrapKey and unwrapKey wrap secret keys only. */ +static bool scr_wc_is_asymmetric_key(const ScrDyn *value) { + return scr_wc_asymmetric && scr_wc_asymmetric->is_key(value); +} + +static bool scr_wc_is_asymmetric_algorithm(const char *name) { + for (size_t i = 0; i < SCR_WC_COUNT(scr_wc_asymmetric_names); i++) + if (strcmp(name, scr_wc_asymmetric_names[i]) == 0) return true; + return false; +} + +/* The asymmetric algorithms run in scr_webcrypto_pki.c, which the compiler + * links when a string literal in the program names one of them. */ +static ScrPromise *scr_wc_asymmetric_missing(const char *method, const char *name) { + char what[160]; + snprintf(what, sizeof what, "the %s algorithm named only by a computed string", name); + scr_wc_unsupported(method, what); + return scr_wc_rejected(); +} + +ScrPromise *scr_wc_rejected(void) { ScrPromise *p = scr_promise_new(); scr_promise_reject_pending(p); return p; } +/* A promise already fulfilled with `value` (moves). */ +static ScrPromise *scr_wc_resolved(ScrDyn *value) { + return scr_promise_settled_ref(value, &scr_dyn_retain_v, &scr_dyn_release_v, NULL); +} + +/* A promise that fulfills with `value` (moves) on a later loop turn, like + * Node's crypto jobs. */ +static ScrPromise *scr_wc_deferred(ScrDyn *value) { + ScrPromise *p = scr_promise_new(); + scr_crypto_defer_dyn(value, NULL, scr_crypto_promise_callback(p), scr_crypto_promise_settle_dyn); + return p; +} + /* The argument count check every method starts with (after the receiver * check the compiler's call shape already guarantees). */ -static bool scr_wc_required(const char *prefix, const ScrDyn *args, size_t required) { +bool scr_wc_required(const char *prefix, const ScrDyn *args, size_t required) { size_t argc = (size_t)scr_dyn_arr_len(args); if (argc >= required) return true; scr_wc_type_error("ERR_MISSING_ARGS", "%s: %zu arguments required, but only %zu present.", prefix, @@ -583,21 +943,167 @@ static bool scr_wc_required(const char *prefix, const ScrDyn *args, size_t requi return false; } -typedef struct { - ScrDyn *v[5]; -} ScrWcArgs; -static void scr_wc_args_take(ScrWcArgs *a, const ScrDyn *args, size_t n) { +void scr_wc_args_take(ScrWcArgs *a, const ScrDyn *args, size_t n) { for (size_t i = 0; i < n; i++) a->v[i] = scr_dyn_arr_at(args, (double)i); } -static void scr_wc_args_drop(ScrWcArgs *a, size_t n) { +void scr_wc_args_drop(ScrWcArgs *a, size_t n) { for (size_t i = 0; i < n; i++) scr_dyn_release(a->v[i]); } +/* AlgorithmIdentifier: an object, or a value converted to a DOMString. */ +static bool scr_wc_algorithm_identifier(ScrDyn *value) { + if (scr_wc_is_object(value)) return true; + ScrStr *s = scr_wc_dom_string(value); + if (!s) return false; + scr_str_release(s); + return true; +} + +/* macImportKey: the usage check, the format, then normalizeKeyLength. */ +static ScrDyn *scr_wc_import_hmac(const char *format, ScrBytes *data, const ScrWcJwk *jwk, + const ScrWcAlgorithm *algorithm, bool extractable, long usages, + bool *unsupported) { + if (!scr_wc_check_usages("HMAC", usages)) return NULL; + ScrBytes *bytes = NULL; + if (strcmp(format, "raw") == 0 || strcmp(format, "raw-secret") == 0) { + bytes = scr_bytes_retain(data); + } else if (strcmp(format, "jwk") == 0) { + bytes = scr_wc_jwk_secret(jwk, extractable, usages, "sig"); + if (!bytes) return NULL; + char buf[16]; + const char *expected = scr_wc_jwk_alg("HMAC", algorithm->hash, 0, buf, sizeof buf); + if (jwk->alg && expected && !scr_wc_str_is(jwk->alg, expected)) { + scr_bytes_release(bytes); + scr_throw_domex("DataError", "JWK \"alg\" does not match the requested algorithm"); + return NULL; + } + } else { + *unsupported = true; + return NULL; + } + ScrDyn *result = NULL; + { + ScrBytes *view = bytes; + SCR_BYTES_SNAPSHOT(view); + size_t len = (size_t)scr_bytes_byte_len(view); + double length = (double)len * 8; + if (len == 0) { + scr_throw_domex("DataError", "Zero-length key is not supported"); + goto done; + } + if (algorithm->has_length) { + if (scr_wc_bits_to_bytes(algorithm->length) != len) { + scr_throw_domex("DataError", "Invalid key length"); + goto done; + } + length = algorithm->length; + } + result = scr_crypto_key_new(view->data, len, "HMAC", algorithm->hash, length, + (unsigned)usages, extractable); + ScrCryptoKey *key = scr_crypto_key_of(result); + scr_wc_truncate_bits(key->data, key->len, length); + } +done: + scr_bytes_release(bytes); + return result; +} + +/* aesImportKey: the usage check, then the format and the key length. */ +static ScrDyn *scr_wc_import_aes(const char *format, ScrBytes *data, const ScrWcJwk *jwk, + const char *name, bool extractable, long usages, + bool *unsupported) { + if (!scr_wc_check_usages(name, usages)) return NULL; + ScrBytes *bytes = NULL; + bool from_jwk = strcmp(format, "jwk") == 0; + if (strcmp(format, "raw") == 0 || strcmp(format, "raw-secret") == 0) { + bytes = scr_bytes_retain(data); + } else if (from_jwk) { + bytes = scr_wc_jwk_secret(jwk, extractable, usages, "enc"); + if (!bytes) return NULL; + } else { + *unsupported = true; + return NULL; + } + ScrDyn *result = NULL; + { + ScrBytes *view = bytes; + SCR_BYTES_SNAPSHOT(view); + size_t len = (size_t)scr_bytes_byte_len(view); + double length = (double)len * 8; + if (length != 128 && length != 192 && length != 256) { + scr_throw_domex("DataError", "Invalid key length"); + goto done; + } + char buf[16]; + if (from_jwk && jwk->alg && + !scr_wc_str_is(jwk->alg, scr_wc_jwk_alg(name, NULL, length, buf, sizeof buf))) { + scr_throw_domex("DataError", "JWK \"alg\" does not match the requested algorithm"); + goto done; + } + result = scr_crypto_key_new(view->data, len, name, NULL, length, (unsigned)usages, extractable); + } +done: + scr_bytes_release(bytes); + return result; +} + +/* importGenericSecretKey (PBKDF2, HKDF): never extractable, derivation + * usages only, raw bytes of any length. */ +static ScrDyn *scr_wc_import_kdf(const char *format, ScrBytes *data, const char *name, + bool extractable, long usages, bool *unsupported) { + if (extractable) { + char message[64]; + snprintf(message, sizeof message, "%s keys are not extractable", name); + scr_throw_domex("SyntaxError", message); + return NULL; + } + if (!scr_wc_check_usages(name, usages)) return NULL; + if (strcmp(format, "raw") != 0 && strcmp(format, "raw-secret") != 0) { + *unsupported = true; + return NULL; + } + ScrBytes *view = data; + SCR_BYTES_SNAPSHOT(view); + return scr_crypto_key_new(view->data, (size_t)scr_bytes_byte_len(view), name, NULL, 0, + (unsigned)usages, false); +} + +/* importKeySync over converted arguments: the per-algorithm import, the + * unsupported-format NotSupportedError, then the empty-usages check. */ +static ScrDyn *scr_wc_import_key_sync(const char *format, ScrBytes *data, const ScrWcJwk *jwk, + const ScrWcAlgorithm *algorithm, bool extractable, + long usages) { + bool unsupported = false; + ScrDyn *key; + if (strcmp(algorithm->name, "HMAC") == 0) + key = scr_wc_import_hmac(format, data, jwk, algorithm, extractable, usages, &unsupported); + else if (scr_wc_is_aes(algorithm->name)) + key = scr_wc_import_aes(format, data, jwk, algorithm->name, extractable, usages, &unsupported); + else if (scr_wc_is_kdf(algorithm->name)) + key = scr_wc_import_kdf(format, data, algorithm->name, extractable, usages, &unsupported); + else { + scr_wc_unsupported_algorithm("importKey", algorithm->name); + return NULL; + } + if (unsupported) { + char message[96]; + snprintf(message, sizeof message, "Unable to import %s using %s format", algorithm->name, + format); + scr_throw_domex("NotSupportedError", message); + return NULL; + } + if (key && usages == 0) { + scr_dyn_release(key); + scr_throw_domex("SyntaxError", "Usages cannot be empty when importing a secret key."); + return NULL; + } + return key; +} + /* importKey(format, keyData, algorithm, extractable, keyUsages): Node's - * conversion order, then macImportKey's checks and importKeySync's empty - * usage check. */ + * conversion order, then normalization and importKeySync. */ static ScrDyn *scr_wc_import(const ScrDyn *args) { static const char prefix[] = "Failed to execute 'importKey' on 'SubtleCrypto'"; if (!scr_wc_required(prefix, args, 5)) return NULL; @@ -605,85 +1111,187 @@ static ScrDyn *scr_wc_import(const ScrDyn *args) { scr_wc_args_take(&a, args, 5); ScrDyn *result = NULL; ScrBytes *data = NULL; + ScrWcJwk jwk; + memset(&jwk, 0, sizeof jwk); const char *format = scr_wc_key_format(prefix, a.v[0]); if (!format) goto done; - bool jwk = strcmp(format, "jwk") == 0; - /* The JsonWebKey dictionary is not implemented; that format is refused - * after the remaining arguments convert. */ - if (!jwk) { + if (strcmp(format, "jwk") == 0) { + if (!scr_wc_jwk_convert(prefix, a.v[1], &jwk)) goto done; + } else { data = scr_wc_buffer_source(prefix, 1, a.v[1]); if (!data) goto done; } - if (!scr_wc_is_object(a.v[2])) { - ScrStr *s = scr_wc_dom_string(a.v[2]); - if (!s) goto done; - scr_str_release(s); - } + if (!scr_wc_algorithm_identifier(a.v[2])) goto done; bool extractable = scr_dyn_truthy(a.v[3]); long usages = scr_wc_key_usages(prefix, 4, a.v[4]); if (usages < 0) goto done; ScrWcAlgorithm algorithm; - if (!scr_wc_normalize(a.v[2], scr_wc_import_names, SCR_WC_COUNT(scr_wc_import_names), true, - &algorithm)) + if (!scr_wc_normalize(a.v[2], scr_wc_import_names, SCR_WC_COUNT(scr_wc_import_names), + SCR_WC_OP_IMPORT, &algorithm)) goto done; - if (strcmp(algorithm.name, "HMAC") != 0) { - scr_wc_unsupported_algorithm("importKey", algorithm.name); - goto done; - } - if (usages & ~(long)(SCR_WC_USAGE_SIGN | SCR_WC_USAGE_VERIFY)) { - scr_throw_domex("SyntaxError", "Unsupported key usage for HMAC key"); - goto done; - } - if (jwk) { - scr_wc_unsupported("importKey", "the 'jwk' key format"); - goto done; - } - if (strcmp(format, "raw") != 0 && strcmp(format, "raw-secret") != 0) { - char message[96]; - snprintf(message, sizeof message, "Unable to import HMAC using %s format", format); - scr_throw_domex("NotSupportedError", message); - goto done; - } - { - ScrBytes *view = data; - SCR_BYTES_SNAPSHOT(view); - size_t len = (size_t)scr_bytes_byte_len(view); - if (len == 0) { - scr_throw_domex("DataError", "Zero-length key is not supported"); - goto done; - } - double length = (double)len * 8; - unsigned char last = view->data[len - 1]; - if (algorithm.has_length) { - double bytes = floor(algorithm.length / 8) + floor((7 + fmod(algorithm.length, 8)) / 8); - if (bytes != (double)len) { - scr_throw_domex("DataError", "Invalid key length"); - goto done; - } - /* A length that is not a whole number of bytes clears the unused - * low bits of the final byte (truncateToBitLength). */ - int extra = (int)fmod(algorithm.length, 8); - if (extra) last = (unsigned char)(last & (0xff << (8 - extra))); - length = algorithm.length; - } - if (usages == 0) { - scr_throw_domex("SyntaxError", "Usages cannot be empty when importing a secret key."); - goto done; - } - result = scr_crypto_key_new(view->data, len, algorithm.hash, length, (unsigned)usages, - extractable); - scr_crypto_key_of(result)->data[len - 1] = last; - } + result = scr_wc_import_key_sync(format, data, &jwk, &algorithm, extractable, usages); done: if (data) scr_bytes_release(data); + scr_wc_jwk_drop(&jwk); scr_wc_args_drop(&a, 5); return result; } ScrPromise *scr_webcrypto_import_key(ScrDyn *args) { + const char *asymmetric = scr_wc_asymmetric_name(args, 2); + if (asymmetric) { + return scr_wc_asymmetric ? scr_wc_asymmetric->import_key(args) + : scr_wc_asymmetric_missing("importKey", asymmetric); + } ScrDyn *key = scr_wc_import(args); if (!key) return scr_wc_rejected(); - return scr_promise_settled_ref(key, &scr_dyn_retain_v, &scr_dyn_release_v, NULL); + return scr_wc_resolved(key); +} + +/* generateKey(algorithm, extractable, keyUsages) for HMAC and AES keys: + * random bytes of the requested length (an HMAC key defaults to its + * hash's block size; a length that is not a whole number of bytes clears + * the final byte's unused low bits). ECDSA, Ed25519, RSASSA-PKCS1-v1_5 and + * RSA-PSS key pairs generate in scr_webcrypto_pki.c. */ +ScrPromise *scr_webcrypto_generate_key(ScrDyn *args) { + const char *asymmetric = scr_wc_asymmetric_name(args, 0); + if (asymmetric) { + return scr_wc_asymmetric ? scr_wc_asymmetric->generate_key(args) + : scr_wc_asymmetric_missing("generateKey", asymmetric); + } + static const char prefix[] = "Failed to execute 'generateKey' on 'SubtleCrypto'"; + if (!scr_wc_required(prefix, args, 3)) return scr_wc_rejected(); + ScrWcArgs a; + scr_wc_args_take(&a, args, 3); + ScrDyn *key = NULL; + if (!scr_wc_algorithm_identifier(a.v[0])) goto done; + bool extractable = scr_dyn_truthy(a.v[1]); + long usages = scr_wc_key_usages(prefix, 2, a.v[2]); + if (usages < 0) goto done; + ScrWcAlgorithm algorithm; + if (!scr_wc_normalize(a.v[0], scr_wc_key_names, SCR_WC_COUNT(scr_wc_key_names), + SCR_WC_OP_GENERATE, &algorithm)) + goto done; + bool hmac = strcmp(algorithm.name, "HMAC") == 0; + if (!hmac && !scr_wc_is_aes(algorithm.name)) { + scr_wc_unsupported_algorithm("generateKey", algorithm.name); + goto done; + } + if (!scr_wc_check_usages(algorithm.name, usages)) goto done; + if (usages == 0) { + scr_throw_domex("SyntaxError", "Usages cannot be empty when creating a key."); + goto done; + } + double length = algorithm.has_length ? algorithm.length + : strcmp(algorithm.hash, "SHA-384") == 0 || strcmp(algorithm.hash, "SHA-512") == 0 + ? 1024 + : 512; + size_t len = scr_wc_bits_to_bytes(length); + unsigned char *bytes = malloc(len ? len : 1); + if (!bytes) scr_trap("scriptc: out of memory\n"); + arc4random_buf(bytes, len); + scr_wc_truncate_bits(bytes, len, length); + key = scr_crypto_key_new(bytes, len, algorithm.name, hmac ? algorithm.hash : NULL, length, + (unsigned)usages, extractable); + volatile unsigned char *wipe = bytes; + for (size_t i = 0; i < len; i++) wipe[i] = 0; + free(bytes); +done: + scr_wc_args_drop(&a, 3); + if (!key) return scr_wc_rejected(); + return scr_wc_deferred(key); +} + +/* exportKeySync's checks for a secret key: false with Node's error + * pending. raw, raw-secret and jwk are the formats a secret key exports. */ +static bool scr_wc_exportable(const char *format, const ScrCryptoKey *key) { + if (scr_wc_is_kdf(key->name)) { + char message[64]; + snprintf(message, sizeof message, "%s key export is not supported", key->name); + scr_throw_domex("NotSupportedError", message); + return false; + } + if (!key->extractable) { + scr_throw_domex("InvalidAccessError", "key is not extractable"); + return false; + } + if (strcmp(format, "raw") != 0 && strcmp(format, "raw-secret") != 0 && + strcmp(format, "jwk") != 0) { + char message[96]; + snprintf(message, sizeof message, "Unable to export %s secret key using %s format", key->name, + format); + scr_throw_domex("NotSupportedError", message); + return false; + } + return true; +} + +/* The key bytes as a fresh u8 view (+1). */ +static ScrBytes *scr_wc_key_bytes(const ScrCryptoKey *key) { + ScrBytes *bytes = scr_bytes_new(SCR_BYTES_U8, (double)key->len); + if (key->len) memcpy(bytes->data, key->data, key->len); + return bytes; +} + +/* A JWK's k: the key bytes in unpadded base64url (+1). */ +static ScrStr *scr_wc_jwk_k(const ScrCryptoKey *key) { + ScrBytes *bytes = scr_wc_key_bytes(key); + ScrStr *encoding = scr_str_new("base64url", 9); + ScrStr *k = scr_bytes_to_str(bytes, encoding); + scr_str_release(encoding); + scr_bytes_release(bytes); + return k; +} + +/* exportKeySync for secret keys: raw and raw-secret answer an ArrayBuffer + * of the key bytes, jwk an object { key_ops, ext, alg, kty, k }. An ECDSA, + * Ed25519 or RSA key sets *asymmetric after the format check instead + * (scr_webcrypto_pki.c exports it). */ +static ScrDyn *scr_wc_export(const ScrDyn *args, bool *asymmetric) { + static const char prefix[] = "Failed to execute 'exportKey' on 'SubtleCrypto'"; + if (!scr_wc_required(prefix, args, 2)) return NULL; + ScrWcArgs a; + scr_wc_args_take(&a, args, 2); + ScrDyn *result = NULL; + const char *format = scr_wc_key_format(prefix, a.v[0]); + if (!format) goto done; + ScrCryptoKey *key = scr_crypto_key_of(a.v[1]); + if (!key && scr_wc_asymmetric && scr_wc_asymmetric->is_key(a.v[1])) { + *asymmetric = true; + goto done; + } + if (!key) { + scr_wc_type_error("ERR_INVALID_ARG_TYPE", "%s: 2nd argument is not of type CryptoKey.", prefix); + goto done; + } + if (!scr_wc_exportable(format, key)) goto done; + if (strcmp(format, "jwk") == 0) { + char buf[16]; + const char *alg = scr_wc_jwk_alg(key->name, key->hash, key->length, buf, sizeof buf); + ScrStr *k = scr_wc_jwk_k(key); + result = scr_dyn_new_obj(); + scr_dyn_obj_set(result, "key_ops", 7, scr_wc_usage_array(key->usages)); + scr_dyn_obj_set(result, "ext", 3, scr_dyn_new_bool(key->extractable)); + if (alg) scr_dyn_obj_set(result, "alg", 3, scr_wc_cstr(alg)); + scr_dyn_obj_set(result, "kty", 3, scr_wc_cstr("oct")); + scr_dyn_obj_set(result, "k", 1, scr_dyn_new_str(k)); + scr_str_release(k); + } else { + ScrBytes *bytes = scr_wc_key_bytes(key); + result = scr_array_buffer_from_bytes(bytes); + scr_bytes_release(bytes); + } +done: + scr_wc_args_drop(&a, 2); + return result; +} + +ScrPromise *scr_webcrypto_export_key(ScrDyn *args) { + bool asymmetric = false; + ScrDyn *result = scr_wc_export(args, &asymmetric); + if (asymmetric) return scr_wc_asymmetric->export_key(args); + if (!result) return scr_wc_rejected(); + return scr_wc_resolved(result); } /* sign(algorithm, key, data) / verify(algorithm, key, signature, data): @@ -706,7 +1314,8 @@ static bool scr_wc_sign_verify(const ScrDyn *args, bool verify, unsigned char ma scr_str_release(s); } ScrCryptoKey *key = scr_crypto_key_of(a.v[1]); - if (!key) { + bool asymmetric_key = !key && scr_wc_asymmetric && scr_wc_asymmetric->is_key(a.v[1]); + if (!key && !asymmetric_key) { scr_wc_type_error("ERR_INVALID_ARG_TYPE", "%s: 2nd argument is not of type CryptoKey.", prefix); goto done; } @@ -717,13 +1326,17 @@ static bool scr_wc_sign_verify(const ScrDyn *args, bool verify, unsigned char ma data = scr_wc_buffer_source(prefix, verify ? 3 : 2, a.v[verify ? 3 : 2]); if (!data) goto done; ScrWcAlgorithm algorithm; - if (!scr_wc_normalize(a.v[0], scr_wc_sign_names, SCR_WC_COUNT(scr_wc_sign_names), false, - &algorithm)) + if (!scr_wc_normalize(a.v[0], scr_wc_sign_names, SCR_WC_COUNT(scr_wc_sign_names), + SCR_WC_OP_SIGN, &algorithm)) goto done; if (strcmp(algorithm.name, "HMAC") != 0) { scr_wc_unsupported_algorithm(method, algorithm.name); goto done; } + if (asymmetric_key || strcmp(key->name, algorithm.name) != 0) { + scr_throw_domex("InvalidAccessError", "Key algorithm mismatch"); + goto done; + } if (!(key->usages & (verify ? SCR_WC_USAGE_VERIFY : SCR_WC_USAGE_SIGN))) { char message[64]; snprintf(message, sizeof message, "Unable to use this key to %s", method); @@ -744,6 +1357,11 @@ done: } ScrPromise *scr_webcrypto_sign(ScrDyn *args) { + const char *asymmetric = scr_wc_asymmetric_name(args, 0); + if (asymmetric) { + return scr_wc_asymmetric ? scr_wc_asymmetric->sign(args) + : scr_wc_asymmetric_missing("sign", asymmetric); + } unsigned char mac[64]; size_t mac_len = 0; if (!scr_wc_sign_verify(args, false, mac, &mac_len, NULL)) return scr_wc_rejected(); @@ -766,6 +1384,11 @@ static void scr_wc_settle_verified(ScrClosure *cb, ScrError *error, ScrBytes *va } ScrPromise *scr_webcrypto_verify(ScrDyn *args) { + const char *asymmetric = scr_wc_asymmetric_name(args, 0); + if (asymmetric) { + return scr_wc_asymmetric ? scr_wc_asymmetric->verify(args) + : scr_wc_asymmetric_missing("verify", asymmetric); + } unsigned char mac[64]; size_t mac_len = 0; ScrBytes *signature = NULL; @@ -827,3 +1450,775 @@ done: scr_crypto_promise_settle_array_buffer); return p; } + +/* ── encrypt and decrypt ────────────────────────────────────────────── + * The WebCrypto half of encrypt and decrypt: argument conversion, the + * AesCbcParams, AesCtrParams and AeadParams dictionaries, and the key + * checks. The cipher itself runs in scr_webcrypto_aes.c, which links + * with the mbedTLS archive and passes it in. */ +static const char *const scr_wc_cipher_names[] = { + "AES-CBC", "AES-CTR", "AES-GCM", "AES-OCB", "ChaCha20-Poly1305", "RSA-OAEP", +}; + +/* Node's limit on the data, IV and additional data (kMaxBufferLength). */ +static const double scr_wc_max_buffer = 2147483647.0; + +/* A BufferSource member of an algorithm dictionary: false with the error + * pending; *out stays NULL when an optional member is absent. */ +static bool scr_wc_member_buffer(const ScrDyn *dict, const char *dict_name, const char *key, + bool required, ScrBytes **out) { + ScrDyn *value = scr_wc_member(dict, key); + bool ok = true; + if (value->kind == SCR_DYN_UNDEF) { + if (required) { + scr_wc_missing_member(dict_name, key); + ok = false; + } + } else { + ScrDyn *plain = scr_wc_plain(value); + if (!plain) ok = false; + else if (plain->kind == SCR_DYN_BYTES || scr_array_buffer_is(plain)) { + *out = scr_bytes_buffer_source(plain); + } else { + scr_wc_type_error("ERR_INVALID_ARG_TYPE", + "%s: %s in passed algorithm is not instance of ArrayBuffer, Buffer, " + "TypedArray, or DataView.", + scr_wc_normalize_prefix, key); + ok = false; + } + if (plain) scr_dyn_release(plain); + } + scr_dyn_release(value); + return ok; +} + +/* validateByteLength / validateMaxBufferLength over a converted member. */ +static bool scr_wc_exact_length(const ScrBytes *bytes, const char *name, double length) { + if (scr_bytes_byte_len(bytes) == length) return true; + char message[96]; + snprintf(message, sizeof message, "%s must contain exactly %.0f bytes", name, length); + scr_throw_domex("OperationError", message); + return false; +} + +static bool scr_wc_max_length(const ScrBytes *bytes, const char *name) { + if (scr_bytes_byte_len(bytes) <= scr_wc_max_buffer) return true; + char message[96]; + snprintf(message, sizeof message, "%s must be at most %.0f bytes", name, scr_wc_max_buffer); + scr_throw_domex("OperationError", message); + return false; +} + +typedef struct { + ScrBytes *iv; /* the IV or the CTR counter block */ + ScrBytes *aad; + double tag_bits; + double counter_bits; +} ScrWcCipherParams; + +static void scr_wc_cipher_params_drop(ScrWcCipherParams *params) { + if (params->iv) scr_bytes_release(params->iv); + if (params->aad) scr_bytes_release(params->aad); + params->iv = params->aad = NULL; +} + +/* An optional or required [EnforceRange] octet member: false with the + * error pending; *present says whether it was given. */ +static bool scr_wc_member_octet(const ScrDyn *dict, const char *dict_name, const char *key, + bool required, bool *present, double *out) { + ScrDyn *value = scr_wc_member(dict, key); + bool ok = true; + *present = value->kind != SCR_DYN_UNDEF; + if (!*present) { + if (required) { + scr_wc_missing_member(dict_name, key); + ok = false; + } + } else { + char context[48]; + snprintf(context, sizeof context, "%s in passed algorithm", key); + ok = scr_wc_enforce_range(scr_wc_normalize_prefix, context, value, 255, out); + } + scr_dyn_release(value); + return ok; +} + +/* normalizeAlgorithm(algorithm, 'encrypt' / 'decrypt'): the canonical + * name and the AES dictionaries' members, in Web IDL member order with + * each member's validator right after its conversion. */ +static const char *scr_wc_normalize_cipher(ScrDyn *identifier, const char *method, + ScrWcCipherParams *params) { + memset(params, 0, sizeof *params); + params->tag_bits = 128; + ScrStr *name = scr_wc_algorithm_name(identifier, "Algorithm"); + if (!name) return NULL; + const char *canonical = + scr_wc_lookup(scr_wc_cipher_names, SCR_WC_COUNT(scr_wc_cipher_names), name); + scr_str_release(name); + if (!canonical) { + scr_throw_domex("NotSupportedError", "Unrecognized algorithm name"); + return NULL; + } + if (!scr_wc_is_aes(canonical)) { + scr_wc_unsupported_algorithm(method, canonical); + return NULL; + } + ScrDyn *dict = scr_wc_is_object(identifier) ? scr_wc_plain(identifier) + : scr_dyn_retain(scr_dyn_undefined()); + if (!dict) return NULL; + bool ok = true; + bool present; + if (strcmp(canonical, "AES-CBC") == 0) { + ok = scr_wc_member_buffer(dict, "AesCbcParams", "iv", true, ¶ms->iv) && + scr_wc_exact_length(params->iv, "algorithm.iv", 16); + } else if (strcmp(canonical, "AES-CTR") == 0) { + ok = scr_wc_member_buffer(dict, "AesCtrParams", "counter", true, ¶ms->iv) && + scr_wc_exact_length(params->iv, "algorithm.counter", 16) && + scr_wc_member_octet(dict, "AesCtrParams", "length", true, &present, + ¶ms->counter_bits); + if (ok && (params->counter_bits == 0 || params->counter_bits > 128)) { + scr_throw_domex("OperationError", "AES-CTR algorithm.length must be between 1 and 128"); + ok = false; + } + } else { + ok = scr_wc_member_buffer(dict, "AeadParams", "additionalData", false, ¶ms->aad) && + (!params->aad || scr_wc_max_length(params->aad, "algorithm.additionalData")) && + scr_wc_member_buffer(dict, "AeadParams", "iv", true, ¶ms->iv) && + scr_wc_max_length(params->iv, "algorithm.iv") && + scr_wc_member_octet(dict, "AeadParams", "tagLength", false, &present, ¶ms->tag_bits); + if (ok && !present) params->tag_bits = 128; + double t = params->tag_bits; + if (ok && t != 32 && t != 64 && t != 96 && t != 104 && t != 112 && t != 120 && t != 128) { + char message[64]; + snprintf(message, sizeof message, "%.0f is not a valid AES-GCM tag length", t); + scr_throw_domex("OperationError", message); + ok = false; + } + } + scr_dyn_release(dict); + if (!ok) { + scr_wc_cipher_params_drop(params); + return NULL; + } + return canonical; +} + +static void *scr_wc_caught_retain(void *c) { return scr_caught_retain(c); } +static void scr_wc_caught_release(void *c) { scr_caught_release(c); } + +static void scr_wc_settle_rethrow(ScrClosure *cb, ScrError *error, ScrBytes *value) { + (void)error; + (void)value; + ScrPromise *p; + ScrCaught *caught; + memcpy(&p, &cb->caps[0]->slot, sizeof p); + memcpy(&caught, &cb->caps[1]->slot, sizeof caught); + scr_rethrow(caught); + scr_promise_reject_pending(p); +} + +/* A job failure: a fresh promise that rejects with the pending exception + * on a later loop turn, as Node's job promises do (+1). */ +static ScrPromise *scr_wc_deferred_rejection(void) { + ScrPromise *p = scr_promise_new(); + ScrClosure *cb = scr_closure_new(NULL, 2); + cb->caps[0] = scr_box_new_obj(scr_promise_retain_v, scr_promise_release_v, NULL); + scr_box_set_ref(cb->caps[0], scr_promise_retain(p)); + cb->caps[1] = scr_box_new_obj(scr_wc_caught_retain, scr_wc_caught_release, scr_caught_trace_v); + scr_box_set_ref(cb->caps[1], scr_exc_take()); + scr_crypto_defer_bytes(NULL, NULL, cb, scr_wc_settle_rethrow); + return p; +} + +/* A promise that fulfills with an ArrayBuffer of `bytes` (moves) on a + * later loop turn. */ +static ScrPromise *scr_wc_deferred_buffer(ScrBytes *bytes) { + ScrPromise *p = scr_promise_new(); + scr_crypto_defer_bytes(bytes, NULL, scr_crypto_promise_callback(p), + scr_crypto_promise_settle_array_buffer); + return p; +} + +/* The cipher over `data` (cipherOrWrap's job): +1 output bytes, or NULL + * with Node's OperationError pending. */ +static ScrBytes *scr_wc_cipher_bytes(ScrWebCryptoAesFn aes, const char *name, bool decrypt, + const ScrCryptoKey *key, ScrWcCipherParams *params, + ScrBytes *data) { + if (!params->iv) params->iv = scr_bytes_new(SCR_BYTES_U8, 0); + if (!params->aad) params->aad = scr_bytes_new(SCR_BYTES_U8, 0); + ScrBytes *view = data; + SCR_BYTES_SNAPSHOT(view); + ScrBytes *iv = params->iv; + SCR_BYTES_SNAPSHOT(iv); + ScrBytes *aad = params->aad; + SCR_BYTES_SNAPSHOT(aad); + ScrWebCryptoAesParams run = { + .iv = iv->data, + .iv_len = (size_t)scr_bytes_byte_len(iv), + .aad = aad->data, + .aad_len = (size_t)scr_bytes_byte_len(aad), + .tag_len = (size_t)(params->tag_bits / 8), + .counter_bits = (unsigned)params->counter_bits, + }; + ScrBytes *out = + aes(name, decrypt, key->data, key->len, &run, view->data, (size_t)scr_bytes_byte_len(view)); + if (!out) + scr_throw_domex("OperationError", "The operation failed for an operation-specific reason"); + return out; +} + +/* The cipher's promise: an ArrayBuffer of the output, or the job's + * OperationError, on a later loop turn. */ +static ScrPromise *scr_wc_run_cipher(ScrWebCryptoAesFn aes, const char *name, bool decrypt, + const ScrCryptoKey *key, ScrWcCipherParams *params, + ScrBytes *data) { + ScrBytes *out = scr_wc_cipher_bytes(aes, name, decrypt, key, params, data); + return out ? scr_wc_deferred_buffer(out) : scr_wc_deferred_rejection(); +} + +ScrPromise *scr_webcrypto_cipher(ScrDyn *args, bool decrypt, ScrWebCryptoAesFn aes) { + const char *method = decrypt ? "decrypt" : "encrypt"; + const char *prefix = decrypt ? "Failed to execute 'decrypt' on 'SubtleCrypto'" + : "Failed to execute 'encrypt' on 'SubtleCrypto'"; + if (!scr_wc_required(prefix, args, 3)) return scr_wc_rejected(); + ScrWcArgs a; + scr_wc_args_take(&a, args, 3); + ScrBytes *data = NULL; + ScrWcCipherParams params; + memset(¶ms, 0, sizeof params); + ScrPromise *result = NULL; + if (!scr_wc_algorithm_identifier(a.v[0])) goto done; + ScrCryptoKey *key = scr_crypto_key_of(a.v[1]); + /* an ECDSA, Ed25519 or RSA key (scr_webcrypto_pki.c) is no cipher key */ + bool asymmetric_key = !key && scr_wc_asymmetric && scr_wc_asymmetric->is_key(a.v[1]); + if (!key && !asymmetric_key) { + scr_wc_type_error("ERR_INVALID_ARG_TYPE", "%s: 2nd argument is not of type CryptoKey.", prefix); + goto done; + } + data = scr_wc_buffer_source(prefix, 2, a.v[2]); + if (!data) goto done; + const char *name = scr_wc_normalize_cipher(a.v[0], method, ¶ms); + if (!name) goto done; + if (asymmetric_key || strcmp(key->name, name) != 0) { + scr_throw_domex("InvalidAccessError", "Key algorithm mismatch"); + goto done; + } + if (!(key->usages & (decrypt ? SCR_WC_USAGE_DECRYPT : SCR_WC_USAGE_ENCRYPT))) { + char message[64]; + snprintf(message, sizeof message, "Unable to use this key to %s", method); + scr_throw_domex("InvalidAccessError", message); + goto done; + } + if (!scr_wc_max_length(data, "data")) goto done; + result = scr_wc_run_cipher(aes, name, decrypt, key, ¶ms, data); +done: + if (data) scr_bytes_release(data); + scr_wc_cipher_params_drop(¶ms); + scr_wc_args_drop(&a, 3); + return result ? result : scr_wc_rejected(); +} + +/* ── wrapKey and unwrapKey ──────────────────────────────────────────── + * wrapKey is exportKey followed by encrypt (or AES-KW's wrap), and + * unwrapKey is decrypt (or AES-KW's unwrap) followed by importKey, as in + * Node's webcrypto.js. The cipher runs in scr_webcrypto_aes.c. */ + +/* normalizeAlgorithm(algorithm, 'wrapKey' / 'unwrapKey'), falling back to + * the 'encrypt' / 'decrypt' registry as Node does: AES-KW (no + * parameters), or the AES ciphers with their dictionaries. */ +static const char *scr_wc_normalize_wrap(ScrDyn *identifier, const char *method, + ScrWcCipherParams *params) { + memset(params, 0, sizeof *params); + ScrStr *name = scr_wc_algorithm_name(identifier, "Algorithm"); + if (!name) return NULL; + bool kw = scr_wc_ascii_ieq(name, "AES-KW"); + scr_str_release(name); + if (kw) return "AES-KW"; + return scr_wc_normalize_cipher(identifier, method, params); +} + +/* The bytes wrapKey encrypts (+1): the raw key, or the JWK's JSON text, + * padded with spaces to a multiple of 8 bytes for AES-KW. */ +static ScrBytes *scr_wc_wrap_payload(const char *format, const ScrCryptoKey *key, bool kw) { + if (strcmp(format, "jwk") != 0) return scr_wc_key_bytes(key); + char buf[16]; + const char *alg = scr_wc_jwk_alg(key->name, key->hash, key->length, buf, sizeof buf); + ScrStr *k = scr_wc_jwk_k(key); + ScrJsonBuf b; + scr_jb_init(&b); + scr_jb_puts(&b, "{\"key_ops\":["); + bool first = true; + for (size_t i = 0; i < SCR_WC_COUNT(scr_wc_usages); i++) { + if (!(key->usages & (1u << i))) continue; + if (!first) scr_jb_puts(&b, ","); + first = false; + scr_jb_puts(&b, "\""); + scr_jb_puts(&b, scr_wc_usages[i]); + scr_jb_puts(&b, "\""); + } + scr_jb_puts(&b, key->extractable ? "],\"ext\":true" : "],\"ext\":false"); + if (alg) { + scr_jb_puts(&b, ",\"alg\":\""); + scr_jb_puts(&b, alg); + scr_jb_puts(&b, "\""); + } + scr_jb_puts(&b, ",\"kty\":\"oct\",\"k\":\""); + ScrStr *json_prefix = scr_jb_finish(&b); + size_t len = json_prefix->len + k->len + 2; + size_t padded = kw && len % 8 ? len + 8 - len % 8 : len; + ScrBytes *out = scr_bytes_new(SCR_BYTES_U8, (double)padded); + memcpy(out->data, json_prefix->data, json_prefix->len); + memcpy(out->data + json_prefix->len, k->data, k->len); + memcpy(out->data + json_prefix->len + k->len, "\"}", 2); + memset(out->data + len, ' ', padded - len); + scr_str_release(json_prefix); + scr_str_release(k); + return out; +} + +/* wrapKey(format, key, wrappingKey, wrapAlgorithm). */ +ScrPromise *scr_webcrypto_wrap(ScrDyn *args, ScrWebCryptoAesFn aes) { + static const char prefix[] = "Failed to execute 'wrapKey' on 'SubtleCrypto'"; + if (!scr_wc_required(prefix, args, 4)) return scr_wc_rejected(); + ScrWcArgs a; + scr_wc_args_take(&a, args, 4); + ScrWcCipherParams params; + memset(¶ms, 0, sizeof params); + ScrBytes *payload = NULL; + ScrPromise *result = NULL; + const char *format = scr_wc_key_format(prefix, a.v[0]); + if (!format) goto done; + ScrCryptoKey *key = scr_crypto_key_of(a.v[1]); + if (!key && !scr_wc_is_asymmetric_key(a.v[1])) { + scr_wc_type_error("ERR_INVALID_ARG_TYPE", "%s: 2nd argument is not of type CryptoKey.", prefix); + goto done; + } + ScrCryptoKey *wrapping = scr_crypto_key_of(a.v[2]); + if (!wrapping && !scr_wc_is_asymmetric_key(a.v[2])) { + scr_wc_type_error("ERR_INVALID_ARG_TYPE", "%s: 3rd argument is not of type CryptoKey.", prefix); + goto done; + } + if (!scr_wc_algorithm_identifier(a.v[3])) goto done; + const char *name = scr_wc_normalize_wrap(a.v[3], "wrapKey", ¶ms); + if (!name) goto done; + /* An ECDSA, Ed25519 or RSA key never has an AES algorithm. */ + if (!wrapping || strcmp(wrapping->name, name) != 0) { + scr_throw_domex("InvalidAccessError", "Key algorithm mismatch"); + goto done; + } + if (!(wrapping->usages & SCR_WC_USAGE_WRAP_KEY)) { + scr_throw_domex("InvalidAccessError", "Unable to use this key to wrapKey"); + goto done; + } + if (!key) { + scr_wc_unsupported("wrapKey", "an ECDSA, Ed25519 or RSA key"); + goto done; + } + if (!scr_wc_exportable(format, key)) goto done; + payload = scr_wc_wrap_payload(format, key, strcmp(name, "AES-KW") == 0); + result = scr_wc_run_cipher(aes, name, false, wrapping, ¶ms, payload); +done: + if (payload) scr_bytes_release(payload); + scr_wc_cipher_params_drop(¶ms); + scr_wc_args_drop(&a, 4); + return result ? result : scr_wc_rejected(); +} + +/* parseJwk: the unwrapped bytes as UTF-8 JSON converted to a JsonWebKey + * with a kty member, or DataError "Invalid wrapped JWK key". */ +static bool scr_wc_parse_wrapped_jwk(ScrBytes *bytes, ScrWcJwk *jwk) { + static const char prefix[] = "Failed to execute 'unwrapKey' on 'SubtleCrypto'"; + ScrStr *text = scr_text_decode_options(bytes, true, false); + ScrDyn *parsed = text ? scr_json_parse(text) : NULL; + if (text) scr_str_release(text); + bool ok = parsed && scr_wc_is_object(parsed) && scr_wc_jwk_convert(prefix, parsed, jwk) && jwk->kty; + if (parsed) scr_dyn_release(parsed); + if (!ok) { + if (scr_exc_pending()) scr_caught_release(scr_exc_take()); + scr_wc_jwk_drop(jwk); + scr_throw_domex("DataError", "Invalid wrapped JWK key"); + } + return ok; +} + +/* unwrapKey(format, wrappedKey, unwrappingKey, unwrapAlgorithm, + * unwrappedKeyAlgorithm, extractable, keyUsages): argument and key errors + * reject at once; the cipher's failure and the import's errors reject on + * a later loop turn, after Node's job. */ +ScrPromise *scr_webcrypto_unwrap(ScrDyn *args, ScrWebCryptoAesFn aes) { + static const char prefix[] = "Failed to execute 'unwrapKey' on 'SubtleCrypto'"; + if (!scr_wc_required(prefix, args, 7)) return scr_wc_rejected(); + ScrDyn *v[7]; + for (size_t i = 0; i < 7; i++) v[i] = scr_dyn_arr_at(args, (double)i); + ScrWcCipherParams params; + memset(¶ms, 0, sizeof params); + ScrBytes *wrapped = NULL; + ScrPromise *result = NULL; + const char *format = scr_wc_key_format(prefix, v[0]); + if (!format) goto done; + wrapped = scr_wc_buffer_source(prefix, 1, v[1]); + if (!wrapped) goto done; + ScrCryptoKey *unwrapping = scr_crypto_key_of(v[2]); + if (!unwrapping && !scr_wc_is_asymmetric_key(v[2])) { + scr_wc_type_error("ERR_INVALID_ARG_TYPE", "%s: 3rd argument is not of type CryptoKey.", prefix); + goto done; + } + if (!scr_wc_algorithm_identifier(v[3]) || !scr_wc_algorithm_identifier(v[4])) goto done; + bool extractable = scr_dyn_truthy(v[5]); + long usages = scr_wc_key_usages(prefix, 6, v[6]); + if (usages < 0) goto done; + const char *name = scr_wc_normalize_wrap(v[3], "unwrapKey", ¶ms); + if (!name) goto done; + ScrWcAlgorithm imported; + if (!scr_wc_normalize(v[4], scr_wc_import_names, SCR_WC_COUNT(scr_wc_import_names), + SCR_WC_OP_IMPORT, &imported)) + goto done; + if (!unwrapping || strcmp(unwrapping->name, name) != 0) { + scr_throw_domex("InvalidAccessError", "Key algorithm mismatch"); + goto done; + } + if (!(unwrapping->usages & SCR_WC_USAGE_UNWRAP_KEY)) { + scr_throw_domex("InvalidAccessError", "Unable to use this key to unwrapKey"); + goto done; + } + if (scr_wc_is_asymmetric_algorithm(imported.name)) { + scr_wc_unsupported_algorithm("unwrapKey", imported.name); + goto done; + } + if (!scr_wc_max_length(wrapped, "data")) goto done; + ScrBytes *bytes = scr_wc_cipher_bytes(aes, name, true, unwrapping, ¶ms, wrapped); + if (!bytes) { + result = scr_wc_deferred_rejection(); + goto done; + } + ScrWcJwk jwk; + memset(&jwk, 0, sizeof jwk); + ScrDyn *key = NULL; + if (strcmp(format, "jwk") != 0 || scr_wc_parse_wrapped_jwk(bytes, &jwk)) + key = scr_wc_import_key_sync(format, bytes, &jwk, &imported, extractable, usages); + scr_wc_jwk_drop(&jwk); + scr_bytes_release(bytes); + result = key ? scr_wc_deferred(key) : scr_wc_deferred_rejection(); +done: + if (wrapped) scr_bytes_release(wrapped); + scr_wc_cipher_params_drop(¶ms); + for (size_t i = 0; i < 7; i++) scr_dyn_release(v[i]); + return result ? result : scr_wc_rejected(); +} + +/* ── deriveBits and deriveKey ───────────────────────────────────────── + * PBKDF2 and HKDF over node:crypto's KDF core (scr_crypto_pbkdf2 and + * scr_crypto_hkdf_bytes in scr_lib.c), with Node's Pbkdf2Params and + * HkdfParams dictionaries, length rules and key checks. deriveKey derives + * the bits the derived key type needs and imports them as a raw-secret + * key of that type. */ +static const char *const scr_wc_derive_names[] = { + "Argon2d", "Argon2i", "Argon2id", "ECDH", "HKDF", "PBKDF2", "X25519", "X448", +}; +/* The algorithms 'get key length' registers. */ +static const char *const scr_wc_length_names[] = { + "AES-CBC", "AES-CTR", "AES-GCM", "AES-KW", "AES-OCB", "Argon2d", "Argon2i", + "Argon2id", "ChaCha20-Poly1305", "HKDF", "HMAC", "KMAC128", "KMAC256", "PBKDF2", +}; + +typedef struct { + const char *name; + const char *hash; + double iterations; + ScrBytes *salt; + ScrBytes *info; +} ScrWcKdfParams; + +static void scr_wc_kdf_params_drop(ScrWcKdfParams *params) { + if (params->salt) scr_bytes_release(params->salt); + if (params->info) scr_bytes_release(params->info); + params->salt = params->info = NULL; +} + +/* A HashAlgorithmIdentifier member with ensureSHA (`dict` names the + * dictionary); *hash is the member value for the later digest + * normalization (+1). */ +static bool scr_wc_member_hash(const ScrDyn *dict, const char *dict_name, ScrDyn **hash) { + ScrDyn *value = scr_wc_member(dict, "hash"); + if (value->kind == SCR_DYN_UNDEF) { + scr_dyn_release(value); + scr_wc_missing_member(dict_name, "hash"); + return false; + } + ScrStr *name = NULL; + bool ok = true; + if (scr_wc_is_object(value)) { + ScrDyn *plain = scr_wc_plain(value); + ScrDyn *member = plain ? scr_wc_member(plain, "name") : NULL; + if (plain) scr_dyn_release(plain); + if (!member) ok = false; + else { + if (member->kind == SCR_DYN_STR) name = scr_str_retain(member->v.str); + scr_dyn_release(member); + } + *hash = scr_dyn_retain(value); + } else { + name = scr_wc_dom_string(value); + if (!name) ok = false; + *hash = name ? scr_dyn_new_str(name) : NULL; + } + scr_dyn_release(value); + bool sha = name && name->len >= 3 && (name->data[0] | 32) == 's' && + (name->data[1] | 32) == 'h' && (name->data[2] | 32) == 'a'; + if (name) scr_str_release(name); + if (ok && !sha) { + char message[96]; + snprintf(message, sizeof message, "Only SHA hashes are supported in %s", dict_name); + scr_throw_domex("NotSupportedError", message); + ok = false; + } + if (!ok && *hash) { + scr_dyn_release(*hash); + *hash = NULL; + } + return ok; +} + +/* normalizeAlgorithm(algorithm, 'deriveBits') for PBKDF2 and HKDF. */ +static bool scr_wc_normalize_kdf(ScrDyn *identifier, const char *method, ScrWcKdfParams *params) { + memset(params, 0, sizeof *params); + ScrStr *name = scr_wc_algorithm_name(identifier, "Algorithm"); + if (!name) return false; + params->name = scr_wc_lookup(scr_wc_derive_names, SCR_WC_COUNT(scr_wc_derive_names), name); + scr_str_release(name); + if (!params->name) { + scr_throw_domex("NotSupportedError", "Unrecognized algorithm name"); + return false; + } + if (!scr_wc_is_kdf(params->name)) { + scr_wc_unsupported_algorithm(method, params->name); + return false; + } + bool pbkdf2 = strcmp(params->name, "PBKDF2") == 0; + const char *dict_name = pbkdf2 ? "Pbkdf2Params" : "HkdfParams"; + ScrDyn *dict = scr_wc_is_object(identifier) ? scr_wc_plain(identifier) + : scr_dyn_retain(scr_dyn_undefined()); + if (!dict) return false; + ScrDyn *hash = NULL; + bool ok = scr_wc_member_hash(dict, dict_name, &hash); + if (ok && pbkdf2) { + ScrDyn *iterations = scr_wc_member(dict, "iterations"); + if (iterations->kind == SCR_DYN_UNDEF) { + scr_wc_missing_member(dict_name, "iterations"); + ok = false; + } else if (!scr_wc_enforce_range(scr_wc_normalize_prefix, "iterations in passed algorithm", + iterations, 4294967295.0, ¶ms->iterations)) { + ok = false; + } else if (params->iterations == 0) { + scr_throw_domex("OperationError", "iterations cannot be zero"); + ok = false; + } else if (params->iterations > 2147483647.0) { + scr_throw_domex("NotSupportedError", "iterations exceeds the implementation limit"); + ok = false; + } + scr_dyn_release(iterations); + ok = ok && scr_wc_member_buffer(dict, dict_name, "salt", true, ¶ms->salt); + } else if (ok) { + ok = scr_wc_member_buffer(dict, dict_name, "info", true, ¶ms->info); + if (ok && scr_bytes_byte_len(params->info) > 1024) { + scr_throw_domex("OperationError", "algorithm.info must be at most 1024 bytes"); + ok = false; + } + ok = ok && scr_wc_member_buffer(dict, dict_name, "salt", true, ¶ms->salt); + } + scr_dyn_release(dict); + if (ok) { + params->hash = scr_wc_digest_algorithm(hash, method); + if (!params->hash) ok = false; + } + if (hash) scr_dyn_release(hash); + if (!ok) scr_wc_kdf_params_drop(params); + return ok; +} + +/* The length rules of pbkdf2DeriveBits and hkdfDeriveBits; `null_length` + * says the length was null. */ +static bool scr_wc_kdf_length(const ScrWcKdfParams *params, bool null_length, double length) { + if (null_length) { + scr_throw_domex("OperationError", "length cannot be null"); + return false; + } + if (fmod(length, 8) != 0) { + scr_throw_domex("OperationError", "length must be a multiple of 8"); + return false; + } + if (strcmp(params->name, "HKDF") == 0) { + double digest = strcmp(params->hash, "SHA-1") == 0 ? 20 + : strcmp(params->hash, "SHA-256") == 0 ? 32 + : strcmp(params->hash, "SHA-384") == 0 ? 48 + : 64; + if (length > 255 * digest * 8) { + scr_throw_domex("OperationError", "length exceeds the maximum derived bit length"); + return false; + } + } + return true; +} + +/* The derived bytes (+1); length is a nonzero multiple of 8. */ +static ScrBytes *scr_wc_kdf_derive(const ScrWcKdfParams *params, const ScrCryptoKey *key, + double length) { + ScrBytes *secret = scr_bytes_new(SCR_BYTES_U8, (double)key->len); + if (key->len) memcpy(secret->data, key->data, key->len); + const char *native = scr_wc_native_hash(params->hash); + ScrStr *digest = scr_str_new(native, strlen(native)); + ScrBytes *out; + if (strcmp(params->name, "PBKDF2") == 0) { + out = scr_crypto_pbkdf2(secret, params->salt, params->iterations, length / 8, digest); + } else { + out = scr_crypto_hkdf_bytes(digest, secret, params->salt, params->info, length / 8); + } + scr_str_release(digest); + volatile unsigned char *wipe = secret->data; + for (size_t i = 0; i < key->len; i++) wipe[i] = 0; + scr_bytes_release(secret); + return out; +} + +/* The base key checks deriveBits and deriveKey share. */ +static bool scr_wc_check_base_key(const ScrCryptoKey *key, const char *algorithm, unsigned usage, + const char *usage_name) { + /* NULL: an asymmetric key, which never has a derive usage */ + if (key == NULL || !(key->usages & usage)) { + char message[64]; + snprintf(message, sizeof message, "baseKey does not have %s usage", usage_name); + scr_throw_domex("InvalidAccessError", message); + return false; + } + if (strcmp(key->name, algorithm) != 0) { + scr_throw_domex("InvalidAccessError", "Key algorithm mismatch"); + return false; + } + return true; +} + +/* deriveBits(algorithm, baseKey[, length]). */ +ScrPromise *scr_webcrypto_derive_bits(ScrDyn *args) { + static const char prefix[] = "Failed to execute 'deriveBits' on 'SubtleCrypto'"; + if (!scr_wc_required(prefix, args, 2)) return scr_wc_rejected(); + size_t argc = (size_t)scr_dyn_arr_len(args); + ScrWcArgs a; + size_t n = argc > 3 ? 3 : argc; + scr_wc_args_take(&a, args, n); + ScrWcKdfParams params; + memset(¶ms, 0, sizeof params); + ScrPromise *result = NULL; + if (!scr_wc_algorithm_identifier(a.v[0])) goto done; + ScrCryptoKey *key = scr_crypto_key_of(a.v[1]); + /* an ECDSA, Ed25519 or RSA key (scr_webcrypto_pki.c) has no derive usage */ + bool asymmetric_key = !key && scr_wc_asymmetric && scr_wc_asymmetric->is_key(a.v[1]); + if (!key && !asymmetric_key) { + scr_wc_type_error("ERR_INVALID_ARG_TYPE", "%s: 2nd argument is not of type CryptoKey.", prefix); + goto done; + } + /* length defaults to null when absent or undefined. */ + bool null_length = n < 3 || a.v[2]->kind == SCR_DYN_UNDEF || a.v[2]->kind == SCR_DYN_NULL; + double length = 0; + if (!null_length && !scr_wc_enforce_range(prefix, "3rd argument", a.v[2], 4294967295.0, &length)) + goto done; + if (!scr_wc_normalize_kdf(a.v[0], "deriveBits", ¶ms)) goto done; + if (!scr_wc_check_base_key(asymmetric_key ? NULL : key, params.name, SCR_WC_USAGE_DERIVE_BITS, + "deriveBits")) + goto done; + if (!scr_wc_kdf_length(¶ms, null_length, length)) goto done; + if (length == 0) { + ScrBytes *empty = scr_bytes_new(SCR_BYTES_U8, 0); + result = scr_wc_resolved(scr_array_buffer_from_bytes(empty)); + scr_bytes_release(empty); + goto done; + } + ScrBytes *bits = scr_wc_kdf_derive(¶ms, key, length); + if (bits) result = scr_wc_deferred_buffer(bits); +done: + scr_wc_kdf_params_drop(¶ms); + scr_wc_args_drop(&a, n); + return result ? result : scr_wc_rejected(); +} + +/* getKeyLength for the derived key type: the bits to derive, or *null + * for the KDF types (whose derivation then rejects). */ +static bool scr_wc_derived_length(ScrDyn *identifier, const ScrWcAlgorithm *imported, + bool *null_length, double *length) { + ScrStr *name = scr_wc_algorithm_name(identifier, "Algorithm"); + if (!name) return false; + const char *canonical = + scr_wc_lookup(scr_wc_length_names, SCR_WC_COUNT(scr_wc_length_names), name); + scr_str_release(name); + if (!canonical) { + scr_throw_domex("NotSupportedError", "Unrecognized algorithm name"); + return false; + } + *null_length = false; + if (scr_wc_is_aes(canonical)) { + ScrWcAlgorithm aes; + memset(&aes, 0, sizeof aes); + if (!scr_wc_aes_length_params(identifier, "AesDerivedKeyParams", &aes)) return false; + *length = aes.length; + return true; + } + if (strcmp(canonical, "HMAC") == 0 && imported->hash) { + *length = imported->has_length ? imported->length + : strcmp(imported->hash, "SHA-384") == 0 || strcmp(imported->hash, "SHA-512") == 0 + ? 1024 + : 512; + return true; + } + *null_length = true; + return true; +} + +/* deriveKey(algorithm, baseKey, derivedKeyType, extractable, keyUsages): + * the derivation's errors reject at once; the import of the derived bits + * settles, or rejects, on a later loop turn. */ +ScrPromise *scr_webcrypto_derive_key(ScrDyn *args) { + static const char prefix[] = "Failed to execute 'deriveKey' on 'SubtleCrypto'"; + if (!scr_wc_required(prefix, args, 5)) return scr_wc_rejected(); + ScrWcArgs a; + scr_wc_args_take(&a, args, 5); + ScrWcKdfParams params; + memset(¶ms, 0, sizeof params); + ScrPromise *result = NULL; + if (!scr_wc_algorithm_identifier(a.v[0])) goto done; + ScrCryptoKey *key = scr_crypto_key_of(a.v[1]); + /* an ECDSA, Ed25519 or RSA key (scr_webcrypto_pki.c) has no derive usage */ + bool asymmetric_key = !key && scr_wc_asymmetric && scr_wc_asymmetric->is_key(a.v[1]); + if (!key && !asymmetric_key) { + scr_wc_type_error("ERR_INVALID_ARG_TYPE", "%s: 2nd argument is not of type CryptoKey.", prefix); + goto done; + } + if (!scr_wc_algorithm_identifier(a.v[2])) goto done; + bool extractable = scr_dyn_truthy(a.v[3]); + long usages = scr_wc_key_usages(prefix, 4, a.v[4]); + if (usages < 0) goto done; + if (!scr_wc_normalize_kdf(a.v[0], "deriveKey", ¶ms)) goto done; + ScrWcAlgorithm imported; + if (!scr_wc_normalize(a.v[2], scr_wc_import_names, SCR_WC_COUNT(scr_wc_import_names), + SCR_WC_OP_IMPORT, &imported)) + goto done; + bool null_length; + double length; + if (!scr_wc_derived_length(a.v[2], &imported, &null_length, &length)) goto done; + if (strcmp(imported.name, "HMAC") != 0 && !scr_wc_is_aes(imported.name) && + !scr_wc_is_kdf(imported.name)) { + scr_wc_unsupported_algorithm("deriveKey", imported.name); + goto done; + } + if (!scr_wc_check_base_key(asymmetric_key ? NULL : key, params.name, SCR_WC_USAGE_DERIVE_KEY, + "deriveKey")) + goto done; + if (!scr_wc_kdf_length(¶ms, null_length, length)) goto done; + ScrBytes *bits = scr_wc_kdf_derive(¶ms, key, length); + if (!bits) goto done; + ScrDyn *derived = scr_wc_import_key_sync("raw-secret", bits, NULL, &imported, extractable, usages); + scr_bytes_release(bits); + result = derived ? scr_wc_deferred(derived) : scr_wc_deferred_rejection(); +done: + scr_wc_kdf_params_drop(¶ms); + scr_wc_args_drop(&a, 5); + return result ? result : scr_wc_rejected(); +} diff --git a/packages/runtime/src/scr_webcrypto.h b/packages/runtime/src/scr_webcrypto.h new file mode 100644 index 000000000..1eb84af9b --- /dev/null +++ b/packages/runtime/src/scr_webcrypto.h @@ -0,0 +1,67 @@ +/* The Web IDL and error helpers of scr_webcrypto.c that the asymmetric + * algorithms (scr_webcrypto_pki.c) share, and the table through which + * scr_webcrypto.c reaches them when that unit is linked. */ +#ifndef SCR_WEBCRYPTO_H +#define SCR_WEBCRYPTO_H + +#include +#include + +#define SCR_WC_COUNT(names) (sizeof(names) / sizeof((names)[0])) + +enum { + SCR_WC_USAGE_ENCRYPT = 1u << 0, + SCR_WC_USAGE_DECRYPT = 1u << 1, + SCR_WC_USAGE_SIGN = 1u << 2, + SCR_WC_USAGE_VERIFY = 1u << 3, + SCR_WC_USAGE_DERIVE_KEY = 1u << 4, + SCR_WC_USAGE_DERIVE_BITS = 1u << 5, + SCR_WC_USAGE_WRAP_KEY = 1u << 6, + SCR_WC_USAGE_UNWRAP_KEY = 1u << 7, +}; + +/* Node's canonical usage order; the bit is the index. */ +extern const char *const scr_wc_usages[12]; +extern const char *const scr_wc_ordinals[5]; +extern const char scr_wc_normalize_prefix[]; +extern const char *const scr_wc_digest_names[13]; + +typedef struct { + ScrDyn *v[5]; +} ScrWcArgs; + +void scr_wc_type_error(const char *code, const char *fmt, ...) __attribute__((format(printf, 2, 3))); +void scr_wc_unsupported(const char *method, const char *what); +void scr_wc_unsupported_algorithm(const char *method, const char *name); +bool scr_wc_is_object(const ScrDyn *v); +ScrDyn *scr_wc_plain(ScrDyn *v); +ScrBytes *scr_wc_buffer_source(const char *prefix, size_t index, ScrDyn *value); +ScrStr *scr_wc_dom_string(const ScrDyn *value); +const char *scr_wc_key_format(const char *prefix, ScrDyn *value); +long scr_wc_key_usages(const char *prefix, size_t index, ScrDyn *value); +void scr_wc_missing_member(const char *dict, const char *member); +ScrDyn *scr_wc_member(const ScrDyn *dict, const char *key); +ScrStr *scr_wc_algorithm_name(ScrDyn *identifier, const char *dict); +const char *scr_wc_digest_algorithm(ScrDyn *identifier, const char *method); +const char *scr_wc_lookup(const char *const *names, size_t count, const ScrStr *name); +ScrDyn *scr_wc_cstr(const char *s); +ScrPromise *scr_wc_rejected(void); +bool scr_wc_required(const char *prefix, const ScrDyn *args, size_t required); +void scr_wc_args_take(ScrWcArgs *a, const ScrDyn *args, size_t n); +void scr_wc_args_drop(ScrWcArgs *a, size_t n); + +/* ECDSA, RSASSA-PKCS1-v1_5 and RSA-PSS (scr_webcrypto_pki.c, linked with + * the pki unit): each takes the method's argument vector (borrowed) and + * answers a +1 promise. NULL until that unit installs it. */ +typedef struct { + ScrPromise *(*generate_key)(const ScrDyn *args); + ScrPromise *(*import_key)(const ScrDyn *args); + ScrPromise *(*export_key)(const ScrDyn *args); + ScrPromise *(*sign)(const ScrDyn *args); + ScrPromise *(*verify)(const ScrDyn *args); + bool (*is_key)(const ScrDyn *value); +} ScrWcAsymmetric; + +extern const ScrWcAsymmetric *scr_wc_asymmetric; + +#endif diff --git a/packages/runtime/src/scr_webcrypto_aes.c b/packages/runtime/src/scr_webcrypto_aes.c new file mode 100644 index 000000000..016ac57af --- /dev/null +++ b/packages/runtime/src/scr_webcrypto_aes.c @@ -0,0 +1,204 @@ +/* WebCrypto's AES ciphers: crypto.subtle.encrypt and decrypt with AES-CBC, + * AES-CTR and AES-GCM keys, over the vendored mbedTLS block cipher. + * + * scr_webcrypto.c converts and validates the arguments, normalizes the + * algorithm and checks the key; this unit runs the cipher itself, the way + * Node 24's src/crypto/crypto_aes.cc does: CBC with PKCS#7 padding, CTR + * with a counter that wraps within its low `length` bits (and fails when + * the input needs more blocks than those bits can count), and GCM with a + * 12 to 128 byte IV and a 4 to 16 byte tag appended to the ciphertext. + * The unit links only into programs that call these methods, alongside + * the cipher feature's mbedTLS archive. */ +#include "scr_runtime.h" + +#include +#include + +#include "mbedtls/aes.h" +#include "mbedtls/gcm.h" +#include "mbedtls/platform_util.h" + +static ScrBytes *scr_wc_aes_gcm(bool decrypt, const unsigned char *key, size_t key_len, + const ScrWebCryptoAesParams *p, const unsigned char *in, + size_t len) { + if (p->iv_len < 12 || p->iv_len > 128) return NULL; + if (decrypt && len < p->tag_len) return NULL; + size_t out_len = decrypt ? len - p->tag_len : len + p->tag_len; + ScrBytes *out = scr_bytes_new(SCR_BYTES_U8, (double)out_len); + mbedtls_gcm_context gcm; + mbedtls_gcm_init(&gcm); + int rc = mbedtls_gcm_setkey(&gcm, MBEDTLS_CIPHER_ID_AES, key, (unsigned)(key_len * 8)); + if (rc == 0 && decrypt) { + rc = mbedtls_gcm_auth_decrypt(&gcm, out_len, p->iv, p->iv_len, p->aad, p->aad_len, + in + out_len, p->tag_len, in, out->data); + } else if (rc == 0) { + rc = mbedtls_gcm_crypt_and_tag(&gcm, MBEDTLS_GCM_ENCRYPT, len, p->iv, p->iv_len, p->aad, + p->aad_len, in, out->data, p->tag_len, out->data + len); + } + mbedtls_gcm_free(&gcm); + if (rc != 0) { + mbedtls_platform_zeroize(out->data, out_len); + scr_bytes_release(out); + return NULL; + } + return out; +} + +static ScrBytes *scr_wc_aes_cbc(bool decrypt, const unsigned char *key, size_t key_len, + const ScrWebCryptoAesParams *p, const unsigned char *in, + size_t len) { + if (decrypt && (len == 0 || len % 16 != 0)) return NULL; + size_t padded = decrypt ? len : (len / 16 + 1) * 16; + unsigned char *buf = malloc(padded); + if (!buf) scr_trap("scriptc: out of memory\n"); + memcpy(buf, in, len); + if (!decrypt) memset(buf + len, (int)(padded - len), padded - len); + unsigned char iv[16]; + memcpy(iv, p->iv, 16); + mbedtls_aes_context aes; + mbedtls_aes_init(&aes); + int rc = decrypt ? mbedtls_aes_setkey_dec(&aes, key, (unsigned)(key_len * 8)) + : mbedtls_aes_setkey_enc(&aes, key, (unsigned)(key_len * 8)); + if (rc == 0) + rc = mbedtls_aes_crypt_cbc(&aes, decrypt ? MBEDTLS_AES_DECRYPT : MBEDTLS_AES_ENCRYPT, padded, + iv, buf, buf); + mbedtls_aes_free(&aes); + size_t out_len = padded; + if (rc == 0 && decrypt) { + /* PKCS#7: the final byte names 1 to 16 bytes of padding, each of + * which holds that value. Checked without data-dependent branches. */ + unsigned char pad = buf[padded - 1]; + unsigned char diff = (unsigned char)-(pad == 0 || pad > 16); + for (unsigned i = 1; i <= 16; i++) + diff |= (unsigned char)((buf[padded - i] ^ pad) & (unsigned char)-(i <= pad)); + if (diff) rc = -1; + else out_len = padded - pad; + } + ScrBytes *out = NULL; + if (rc == 0) { + out = scr_bytes_new(SCR_BYTES_U8, (double)out_len); + memcpy(out->data, buf, out_len); + } + mbedtls_platform_zeroize(buf, padded); + free(buf); + return out; +} + +/* Adds one to the low `bits` bits of a big-endian counter block, leaving + * the bits above them unchanged. */ +static void scr_wc_ctr_increment(unsigned char block[16], unsigned bits) { + for (int i = 15; i >= 0 && bits > 0; i--) { + unsigned width = bits >= 8 ? 8 : bits; + unsigned mask = (1u << width) - 1; + unsigned low = ((unsigned)block[i] + 1) & mask; + block[i] = (unsigned char)((block[i] & ~mask) | low); + bits -= width; + if (low != 0) return; + } +} + +static ScrBytes *scr_wc_aes_ctr(const unsigned char *key, size_t key_len, + const ScrWebCryptoAesParams *p, const unsigned char *in, + size_t len) { + size_t blocks = (len + 15) / 16; + if (p->counter_bits < 64 && (double)blocks > (double)(1ull << p->counter_bits)) return NULL; + mbedtls_aes_context aes; + mbedtls_aes_init(&aes); + if (mbedtls_aes_setkey_enc(&aes, key, (unsigned)(key_len * 8)) != 0) { + mbedtls_aes_free(&aes); + return NULL; + } + ScrBytes *out = scr_bytes_new(SCR_BYTES_U8, (double)len); + unsigned char counter[16], stream[16]; + memcpy(counter, p->iv, 16); + for (size_t off = 0; off < len; off += 16) { + mbedtls_aes_crypt_ecb(&aes, MBEDTLS_AES_ENCRYPT, counter, stream); + size_t n = len - off < 16 ? len - off : 16; + for (size_t i = 0; i < n; i++) out->data[off + i] = (unsigned char)(in[off + i] ^ stream[i]); + scr_wc_ctr_increment(counter, p->counter_bits); + } + mbedtls_platform_zeroize(stream, sizeof stream); + mbedtls_aes_free(&aes); + return out; +} + +/* RFC 3394 AES key wrap with the default IV: wrapping takes a multiple of + * 8 bytes, at least 16; unwrapping a multiple of 8, at least 24, and fails + * when the integrity check value does not match (compared in constant + * time). */ +static ScrBytes *scr_wc_aes_kw(bool unwrap, const unsigned char *key, size_t key_len, + const unsigned char *in, size_t len) { + static const unsigned char iv[8] = {0xa6, 0xa6, 0xa6, 0xa6, 0xa6, 0xa6, 0xa6, 0xa6}; + if (len % 8 != 0 || len < (unwrap ? 24u : 16u)) return NULL; + size_t n = unwrap ? len / 8 - 1 : len / 8; + mbedtls_aes_context aes; + mbedtls_aes_init(&aes); + int rc = unwrap ? mbedtls_aes_setkey_dec(&aes, key, (unsigned)(key_len * 8)) + : mbedtls_aes_setkey_enc(&aes, key, (unsigned)(key_len * 8)); + if (rc != 0) { + mbedtls_aes_free(&aes); + return NULL; + } + ScrBytes *out = scr_bytes_new(SCR_BYTES_U8, (double)(unwrap ? len - 8 : len + 8)); + unsigned char a[8], block[16]; + unsigned char *r = unwrap ? out->data : out->data + 8; + if (unwrap) { + memcpy(a, in, 8); + memcpy(r, in + 8, len - 8); + for (int j = 5; j >= 0; j--) { + for (size_t i = n; i >= 1; i--) { + uint64_t t = (uint64_t)n * (uint64_t)j + i; + for (int k = 0; k < 8; k++) block[k] = (unsigned char)(a[k] ^ (t >> (56 - 8 * k))); + memcpy(block + 8, r + 8 * (i - 1), 8); + mbedtls_aes_crypt_ecb(&aes, MBEDTLS_AES_DECRYPT, block, block); + memcpy(a, block, 8); + memcpy(r + 8 * (i - 1), block + 8, 8); + } + } + } else { + memcpy(a, iv, 8); + memcpy(r, in, len); + for (int j = 0; j <= 5; j++) { + for (size_t i = 1; i <= n; i++) { + memcpy(block, a, 8); + memcpy(block + 8, r + 8 * (i - 1), 8); + mbedtls_aes_crypt_ecb(&aes, MBEDTLS_AES_ENCRYPT, block, block); + uint64_t t = (uint64_t)n * (uint64_t)j + i; + for (int k = 0; k < 8; k++) a[k] = (unsigned char)(block[k] ^ (t >> (56 - 8 * k))); + memcpy(r + 8 * (i - 1), block + 8, 8); + } + } + memcpy(out->data, a, 8); + } + mbedtls_platform_zeroize(block, sizeof block); + mbedtls_aes_free(&aes); + if (unwrap) { + unsigned char diff = 0; + for (int k = 0; k < 8; k++) diff |= (unsigned char)(a[k] ^ iv[k]); + if (diff) { + mbedtls_platform_zeroize(out->data, len - 8); + scr_bytes_release(out); + return NULL; + } + } + return out; +} + +/* The cipher scr_webcrypto_cipher runs: +1 output bytes, or NULL when the + * operation fails (Node's OperationError). */ +static ScrBytes *scr_wc_aes(const char *name, bool decrypt, const unsigned char *key, + size_t key_len, const ScrWebCryptoAesParams *p, + const unsigned char *in, size_t len) { + if (strcmp(name, "AES-KW") == 0) return scr_wc_aes_kw(decrypt, key, key_len, in, len); + if (strcmp(name, "AES-GCM") == 0) return scr_wc_aes_gcm(decrypt, key, key_len, p, in, len); + if (strcmp(name, "AES-CBC") == 0) return scr_wc_aes_cbc(decrypt, key, key_len, p, in, len); + return scr_wc_aes_ctr(key, key_len, p, in, len); +} + +ScrPromise *scr_webcrypto_encrypt(ScrDyn *args) { return scr_webcrypto_cipher(args, false, scr_wc_aes); } + +ScrPromise *scr_webcrypto_decrypt(ScrDyn *args) { return scr_webcrypto_cipher(args, true, scr_wc_aes); } + +ScrPromise *scr_webcrypto_wrap_key(ScrDyn *args) { return scr_webcrypto_wrap(args, scr_wc_aes); } + +ScrPromise *scr_webcrypto_unwrap_key(ScrDyn *args) { return scr_webcrypto_unwrap(args, scr_wc_aes); } diff --git a/packages/runtime/src/scr_webcrypto_object.c b/packages/runtime/src/scr_webcrypto_object.c new file mode 100644 index 000000000..c20ef13dc --- /dev/null +++ b/packages/runtime/src/scr_webcrypto_object.c @@ -0,0 +1,53 @@ +/* The crypto global as a value: node:crypto's dynamic Crypto object + * (scr_crypto_native in scr_async_dyn.c, which carries subtle.digest) with + * the Crypto object's own randomUUID and getRandomValues methods, for + * untyped reads such as uuid's `crypto.randomUUID && crypto.randomUUID()`. + * Node's receiver check (ERR_INVALID_THIS on a detached call) is not + * modeled. There is one object per thread, so every spelling of the + * global (crypto, globalThis.crypto, node:crypto's webcrypto) is the same + * value; it is released at exit. Linked only into programs that read the + * global as a value. */ +#include "scr_runtime.h" + +static ScrDyn *scr_webcrypto_random_uuid_call(ScrClosure *closure, ScrDyn *const *args, size_t argc) { + (void)closure; + (void)args; + (void)argc; + ScrStr *uuid = scr_crypto_random_uuid(); + ScrDyn *result = scr_dyn_new_str(uuid); + scr_str_release(uuid); + return result; +} + +static ScrDyn *scr_webcrypto_get_random_values_call(ScrClosure *closure, ScrDyn *const *args, + size_t argc) { + (void)closure; + if (argc == 0) { + static const char message[] = + "Failed to execute 'getRandomValues' on 'Crypto': 1 argument required, but only 0 present."; + scr_throw_error_msg_code(SCR_ERR_TYPE, message, sizeof message - 1, "ERR_MISSING_ARGS"); + return NULL; + } + return scr_crypto_get_random_values_dyn(args[0]); +} + +static SCR_TL ScrDyn *scr_webcrypto_object_value; + +static void scr_webcrypto_object_cleanup(void) { + if (scr_webcrypto_object_value) scr_dyn_release(scr_webcrypto_object_value); + scr_webcrypto_object_value = NULL; +} + +ScrDyn *scr_webcrypto_object(void) { + if (scr_webcrypto_object_value) return scr_dyn_retain(scr_webcrypto_object_value); + ScrDyn *result = scr_crypto_native(); + scr_dyn_obj_set(result, "randomUUID", 10, + scr_dyn_new_func(scr_closure_new(NULL, 0), scr_webcrypto_random_uuid_call, 0, + "crypto.randomUUID", "randomUUID")); + scr_dyn_obj_set(result, "getRandomValues", 15, + scr_dyn_new_func(scr_closure_new(NULL, 0), scr_webcrypto_get_random_values_call, 1, + "crypto.getRandomValues", "getRandomValues")); + scr_webcrypto_object_value = result; + scr_atexit(scr_webcrypto_object_cleanup); + return scr_dyn_retain(result); +} diff --git a/packages/runtime/src/scr_webcrypto_pki.c b/packages/runtime/src/scr_webcrypto_pki.c new file mode 100644 index 000000000..7439a12db --- /dev/null +++ b/packages/runtime/src/scr_webcrypto_pki.c @@ -0,0 +1,841 @@ +/* WebCrypto's ECDSA, RSASSA-PKCS1-v1_5, RSA-PSS and Ed25519 algorithms: + * crypto.subtle.generateKey, importKey (spki, pkcs8, jwk, and raw for ECDSA + * and Ed25519 public keys), exportKey, sign and verify, and the CryptoKey + * values of these keys. ECDSA keys are on P-256, P-384 and P-521; ECDSA + * signatures are IEEE P1363 r || s. + * + * Argument conversion, algorithm normalization and the DOMException + * shapes follow Node 24's lib/internal/crypto/webcrypto.js, ec.js and + * rsa.js, through the Web IDL helpers of scr_webcrypto.c. The keys and + * signatures come from the pki unit (scr_pki.c). This unit installs + * itself into scr_webcrypto.c's dispatch table at startup; the compiler + * links it when a program uses WebCrypto and names one of these + * algorithms. All arguments are borrowed. */ +#include "scr_runtime.h" + +#include +#include +#include +#include + +#include "scr_pki.h" +#include "scr_webcrypto.h" + +typedef enum { SW_ECDSA, SW_RSASSA, SW_PSS, SW_ED25519 } SwKind; + +static const char *const sw_names[] = {"ECDSA", "RSASSA-PKCS1-v1_5", "RSA-PSS", "Ed25519"}; + +static const char *const sw_curves[] = {"P-256", "P-384", "P-521"}; + +/* ── CryptoKey ────────────────────────────────────────────────────────── */ + +typedef struct SwKey { + size_t rc; + ScrPkiKey *key; + SwKind kind; + const char *hash; /* RSA keys: the WebCrypto hash name */ + unsigned usages; + bool extractable; + ScrDyn *algorithm; /* cached getter results, or NULL */ + ScrDyn *usage_list; +} SwKey; + +static void *sw_key_retain(void *p) { + ((SwKey *)p)->rc++; + return p; +} + +static void sw_key_release(void *p) { + SwKey *k = p; + if (!k || --k->rc != 0) return; + scr_pki_key_release(k->key); + if (k->algorithm) scr_dyn_release(k->algorithm); + if (k->usage_list) scr_dyn_release(k->usage_list); + free(k); +} + +static SwKey *sw_key_of(const ScrDyn *value) { + if (value->kind != SCR_DYN_HANDLE || value->v.handle.tag != SCR_DYNH_ASYMMETRIC_CRYPTO_KEY) return NULL; + return value->v.handle.ptr; +} + +static bool sw_is_key(const ScrDyn *value) { return sw_key_of(value) != NULL; } + +static ScrDyn *sw_key_algorithm(SwKey *k) { + if (!k->algorithm) { + ScrDyn *algorithm = scr_dyn_new_obj(); + scr_dyn_obj_set(algorithm, "name", 4, scr_wc_cstr(sw_names[k->kind])); + if (k->kind == SW_ED25519) { + /* { name } only */ + } else if (k->kind == SW_ECDSA) { + scr_dyn_obj_set(algorithm, "namedCurve", 10, scr_wc_cstr(scr_pki_key_curve(k->key))); + } else { + scr_dyn_obj_set(algorithm, "modulusLength", 13, scr_dyn_new_num((double)scr_pki_key_bits(k->key))); + ScrBytes *exponent = scr_pki_key_exponent(k->key); + scr_dyn_obj_set(algorithm, "publicExponent", 14, scr_dyn_new_bytes(exponent)); + scr_bytes_release(exponent); + ScrDyn *hash = scr_dyn_new_obj(); + scr_dyn_obj_set(hash, "name", 4, scr_wc_cstr(k->hash)); + scr_dyn_obj_set(algorithm, "hash", 4, hash); + } + k->algorithm = algorithm; + } + return scr_dyn_retain(k->algorithm); +} + +static ScrDyn *sw_usage_array(unsigned usages) { + ScrDyn *list = scr_dyn_new_arr(); + for (size_t i = 0; i < SCR_WC_COUNT(scr_wc_usages); i++) + if (usages & (1u << i)) scr_dyn_arr_push(list, scr_wc_cstr(scr_wc_usages[i])); + return list; +} + +static ScrDyn *sw_key_usages(SwKey *k) { + if (!k->usage_list) k->usage_list = sw_usage_array(k->usages); + return scr_dyn_retain(k->usage_list); +} + +static bool sw_name_is(const char *name, size_t len, const char *literal) { + return len == strlen(literal) && memcmp(name, literal, len) == 0; +} + +static ScrDyn *sw_key_get(void *h, const char *name, size_t len) { + SwKey *k = h; + if (sw_name_is(name, len, "type")) + return scr_wc_cstr(scr_pki_key_is_private(k->key) ? "private" : "public"); + if (sw_name_is(name, len, "extractable")) return scr_dyn_new_bool(k->extractable); + if (sw_name_is(name, len, "algorithm")) return sw_key_algorithm(k); + if (sw_name_is(name, len, "usages")) return sw_key_usages(k); + return NULL; +} + +static bool sw_key_set(void *h, const char *name, size_t len, const ScrDyn *value) { + (void)h; + (void)value; + if (!sw_name_is(name, len, "type") && !sw_name_is(name, len, "extractable") && + !sw_name_is(name, len, "algorithm") && !sw_name_is(name, len, "usages")) + return false; + scr_pki_throw_fmt(SCR_ERR_TYPE, NULL, "Cannot set property %.*s of # which has only a getter", (int)len, + name); + return true; +} + +static ScrDyn *sw_key_invoke(void *h, ScrDyn *self, const char *method, ScrDyn *const *args, size_t argc, + const char *what) { + (void)h; + (void)self; + (void)args; + (void)argc; + if (strcmp(method, "toString") == 0) return scr_wc_cstr("[object CryptoKey]"); + scr_pki_throw_fmt(SCR_ERR_TYPE, NULL, "%s is not a function", what); + return NULL; +} + +static ScrDyn *sw_key_symbol_get(void *h, const ScrDyn *key) { + (void)h; + if (key->kind != SCR_DYN_SYMBOL || !key->v.symbol.description) return NULL; + ScrStr *description = key->v.symbol.description(key->v.symbol.value); + bool tag = description && description->len == 18 && memcmp(description->data, "Symbol.toStringTag", 18) == 0; + if (description) scr_str_release(description); + return tag ? scr_wc_cstr("CryptoKey") : NULL; +} + +/* As for HMAC CryptoKeys, util.inspect refuses these keys rather than + * printing a different shape than Node's custom inspector. */ +static const ScrDynHandleOps sw_key_ops = { + .cls = "CryptoKey", + .retain = sw_key_retain, + .release = sw_key_release, + .invoke = sw_key_invoke, + .get = sw_key_get, + .set = sw_key_set, + .json_empty_object = true, + .to_string_tag = "CryptoKey", + .symbol_get = sw_key_symbol_get, +}; + +/* Boxes a CryptoKey over `key` (consumed). */ +static ScrDyn *sw_key_new(ScrPkiKey *key, SwKind kind, const char *hash, unsigned usages, bool extractable) { + static SCR_TL bool installed; + if (!installed) { + installed = true; + scr_dyn_handle_install(SCR_DYNH_ASYMMETRIC_CRYPTO_KEY, &sw_key_ops); + } + SwKey *k = calloc(1, sizeof *k); + if (!k) scr_trap("scriptc: out of memory\n"); + k->rc = 1; + k->key = key; + k->kind = kind; + k->hash = hash; + k->usages = usages; + k->extractable = extractable; + ScrDyn *box = scr_dyn_new_handle(k, SCR_DYNH_ASYMMETRIC_CRYPTO_KEY); + sw_key_release(k); + return box; +} + +/* ── algorithm parameters ─────────────────────────────────────────────── */ + +static SwKind sw_kind_of(const char *name) { + if (strcmp(name, "ECDSA") == 0) return SW_ECDSA; + if (strcmp(name, "Ed25519") == 0) return SW_ED25519; + return strcmp(name, "RSA-PSS") == 0 ? SW_PSS : SW_RSASSA; +} + +static bool sw_is_rsa_kind(SwKind kind) { return kind == SW_RSASSA || kind == SW_PSS; } + +/* The canonical algorithm name of an AlgorithmIdentifier the dispatcher + * already recognized as one of this unit's algorithms, or NULL with the + * error pending. */ +static const char *sw_algorithm_name(ScrDyn *identifier) { + ScrStr *name = scr_wc_algorithm_name(identifier, "Algorithm"); + if (!name) return NULL; + const char *found = scr_wc_lookup(sw_names, SCR_WC_COUNT(sw_names), name); + scr_str_release(name); + if (!found) scr_throw_domex("NotSupportedError", "Unrecognized algorithm name"); + return found; +} + +/* A required dictionary member (+1), or NULL with ERR_MISSING_OPTION. */ +static ScrDyn *sw_required(ScrDyn *plain, const char *dict, const char *member) { + ScrDyn *v = scr_wc_member(plain, member); + if (v->kind == SCR_DYN_UNDEF) { + scr_dyn_release(v); + scr_wc_missing_member(dict, member); + return NULL; + } + return v; +} + +/* namedCurve (DOMString, required): one of the implemented curves, or + * NULL with the error pending. */ +static const char *sw_named_curve(ScrDyn *plain, const char *dict) { + ScrDyn *value = sw_required(plain, dict, "namedCurve"); + if (!value) return NULL; + ScrStr *s = scr_wc_dom_string(value); + scr_dyn_release(value); + if (!s) return NULL; + const char *curve = NULL; + for (size_t i = 0; i < SCR_WC_COUNT(sw_curves); i++) + if (s->len == strlen(sw_curves[i]) && memcmp(s->data, sw_curves[i], s->len) == 0) curve = sw_curves[i]; + scr_str_release(s); + if (!curve) scr_throw_domex("NotSupportedError", "Unrecognized namedCurve"); + return curve; +} + +/* hash (HashAlgorithmIdentifier, required): with `sha_only`, Node's + * ensureSHA check first ("Only SHA hashes are supported in "). */ +static const char *sw_hash(ScrDyn *plain, const char *dict, bool sha_only, const char *method) { + ScrDyn *hash = sw_required(plain, dict, "hash"); + if (!hash) return NULL; + if (sha_only) { + ScrStr *name = NULL; + if (scr_wc_is_object(hash)) { + ScrDyn *hp = scr_wc_plain(hash); + ScrDyn *member = hp ? scr_wc_member(hp, "name") : NULL; + if (hp) scr_dyn_release(hp); + if (member && member->kind == SCR_DYN_STR) name = scr_str_retain(member->v.str); + if (member) scr_dyn_release(member); + } else { + name = scr_wc_dom_string(hash); + if (!name) { + scr_dyn_release(hash); + return NULL; + } + } + bool sha = name && name->len >= 3 && (name->data[0] | 32) == 's' && (name->data[1] | 32) == 'h' && + (name->data[2] | 32) == 'a'; + if (name) scr_str_release(name); + if (!sha) { + char message[96]; + snprintf(message, sizeof message, "Only SHA hashes are supported in %s", dict); + scr_throw_domex("NotSupportedError", message); + scr_dyn_release(hash); + return NULL; + } + } + const char *canonical = scr_wc_digest_algorithm(hash, method); + scr_dyn_release(hash); + return canonical; +} + +/* An [EnforceRange] unsigned long member; false with the TypeError + * pending. */ +static bool sw_unsigned_long(ScrDyn *value, const char *member, double *out) { + double x; + if (!scr_dyn_number_coerce_js(value, &x)) return false; + if (x != x || x == 1.0 / 0.0 || x == -1.0 / 0.0) { + scr_wc_type_error("ERR_INVALID_ARG_TYPE", "%s: %s in passed algorithm is not a finite number.", + scr_wc_normalize_prefix, member); + return false; + } + x = trunc(x); + if (x < 0 || x > 4294967295.0) { + scr_wc_type_error("ERR_OUT_OF_RANGE", + "%s: %s in passed algorithm is outside the expected range of 0 to 4294967295.", + scr_wc_normalize_prefix, member); + return false; + } + *out = x == 0 ? 0 : x; + return true; +} + +static void sw_unsupported_usage(SwKind kind) { + char message[96]; + snprintf(message, sizeof message, "Unsupported key usage for %s key", sw_names[kind]); + scr_throw_domex("SyntaxError", message); +} + +/* ── generateKey ──────────────────────────────────────────────────────── */ + +static ScrPromise *sw_generate_key(const ScrDyn *args) { + static const char prefix[] = "Failed to execute 'generateKey' on 'SubtleCrypto'"; + if (!scr_wc_required(prefix, args, 3)) return scr_wc_rejected(); + ScrWcArgs a; + scr_wc_args_take(&a, args, 3); + ScrDyn *pair = NULL; + ScrDyn *plain = NULL; + if (!scr_wc_is_object(a.v[0])) { + ScrStr *s = scr_wc_dom_string(a.v[0]); + if (!s) goto done; + scr_str_release(s); + } + bool extractable = scr_dyn_truthy(a.v[1]); + long usages = scr_wc_key_usages(prefix, 2, a.v[2]); + if (usages < 0) goto done; + const char *name = sw_algorithm_name(a.v[0]); + if (!name) goto done; + SwKind kind = sw_kind_of(name); + plain = scr_wc_plain(a.v[0]); + if (!plain) goto done; + const char *curve = NULL; + const char *hash = NULL; + double bits = 0; + ScrBytes *exponent = NULL; + if (kind == SW_ED25519) { + /* no parameters */ + } else if (kind == SW_ECDSA) { + if (!scr_wc_is_object(plain)) { + scr_wc_missing_member("EcKeyGenParams", "namedCurve"); + goto done; + } + curve = sw_named_curve(plain, "EcKeyGenParams"); + if (!curve) goto done; + } else { + static const char dict[] = "RsaHashedKeyGenParams"; + if (!scr_wc_is_object(plain)) { + scr_wc_missing_member(dict, "hash"); + goto done; + } + /* Dictionary members convert in name order: hash, modulusLength, + * publicExponent. */ + hash = sw_hash(plain, dict, true, "generateKey"); + if (!hash) goto done; + ScrDyn *length = sw_required(plain, dict, "modulusLength"); + if (!length) goto done; + bool ok = sw_unsigned_long(length, "modulusLength", &bits); + scr_dyn_release(length); + if (!ok) goto done; + ScrDyn *e = sw_required(plain, dict, "publicExponent"); + if (!e) goto done; + if (e->kind != SCR_DYN_BYTES || e->v.bytes->elem != SCR_BYTES_U8) { + scr_wc_type_error("ERR_INVALID_ARG_TYPE", "%s: publicExponent in passed algorithm is not instance of Uint8Array.", + scr_wc_normalize_prefix); + scr_dyn_release(e); + goto done; + } + exponent = scr_bytes_buffer_source(e); + scr_dyn_release(e); + } + if (usages & ~(long)(SCR_WC_USAGE_SIGN | SCR_WC_USAGE_VERIFY)) { + sw_unsupported_usage(kind); + if (exponent) scr_bytes_release(exponent); + goto done; + } + ScrPkiKey *key; + if (kind == SW_ED25519) { + key = scr_pki_generate_ed25519(); + if (!key) goto done; + } else if (kind == SW_ECDSA) { + key = scr_pki_generate_ec(curve); + } else { + /* publicExponent: big-endian, at most a 32-bit value. */ + size_t n = (size_t)scr_bytes_byte_len(exponent); + uint64_t value = 0; + bool fits = true; + for (size_t i = 0; i < n; i++) { + if (value > 0xffffffu && fits) fits = false; + value = (value << 8) | exponent->data[i]; + } + scr_bytes_release(exponent); + if (!fits || value > 0xffffffffu) { + scr_throw_domex("OperationError", "The publicExponent must be equivalent to an unsigned 32-bit value"); + goto done; + } + if (bits < 512) { + scr_throw_domex("OperationError", "algorithm.modulusLength must be at least 512"); + goto done; + } + if ((value & 1) == 0) { + scr_throw_domex("OperationError", "algorithm.publicExponent must be odd"); + goto done; + } + if (bits > 16384 || value < 3) { + scr_wc_unsupported("generateKey", "this RSA modulus length or public exponent"); + goto done; + } + key = scr_pki_generate_rsa((unsigned)bits, value); + } + if (!key) { + scr_throw_domex("OperationError", "Key generation failed"); + goto done; + } + unsigned private_usages = (unsigned)usages & SCR_WC_USAGE_SIGN; + unsigned public_usages = (unsigned)usages & SCR_WC_USAGE_VERIFY; + if (private_usages == 0) { + scr_pki_key_release(key); + scr_throw_domex("SyntaxError", "Usages cannot be empty when creating a key."); + goto done; + } + ScrPkiKey *public_key = scr_pki_key_public_of(key); + if (!public_key) { + scr_pki_key_release(key); + scr_throw_domex("OperationError", "Key generation failed"); + goto done; + } + pair = scr_dyn_new_obj(); + scr_dyn_obj_set(pair, "publicKey", 9, sw_key_new(public_key, kind, hash, public_usages, true)); + scr_dyn_obj_set(pair, "privateKey", 10, sw_key_new(key, kind, hash, private_usages, extractable)); +done: + if (plain) scr_dyn_release(plain); + scr_wc_args_drop(&a, 3); + if (!pair) return scr_wc_rejected(); + ScrPromise *p = scr_promise_new(); + scr_crypto_defer_dyn(pair, NULL, scr_crypto_promise_callback(p), scr_crypto_promise_settle_dyn); + return p; +} + +/* ── importKey ────────────────────────────────────────────────────────── */ + +/* A JWK string member, or NULL. */ +static const ScrDyn *sw_jwk_member(const ScrDyn *jwk, const char *key) { + const ScrDyn *v = scr_dyn_obj_get(jwk, key, strlen(key)); + return v && v->kind != SCR_DYN_UNDEF ? v : NULL; +} + +static bool sw_jwk_is(const ScrDyn *v, const char *text) { + return v && v->kind == SCR_DYN_STR && v->v.str->len == strlen(text) && + memcmp(v->v.str->data, text, v->v.str->len) == 0; +} + +/* The JWK checks Node runs before reading the key: use, key_ops and ext. */ +static bool sw_jwk_checks(const ScrDyn *jwk, unsigned usages, bool extractable) { + const ScrDyn *use = sw_jwk_member(jwk, "use"); + if (use && !sw_jwk_is(use, "sig")) { + scr_throw_domex("DataError", "Invalid JWK \"use\" Parameter"); + return false; + } + const ScrDyn *ops = sw_jwk_member(jwk, "key_ops"); + if (ops) { + if (ops->kind != SCR_DYN_ARR) { + scr_throw_domex("DataError", "Key operations and usage mismatch"); + return false; + } + for (size_t u = 0; u < SCR_WC_COUNT(scr_wc_usages); u++) { + if (!(usages & (1u << u))) continue; + bool listed = false; + double n = scr_dyn_arr_len(ops); + for (double i = 0; i < n && !listed; i++) { + ScrDyn *item = scr_dyn_arr_at(ops, i); + listed = sw_jwk_is(item, scr_wc_usages[u]); + scr_dyn_release(item); + } + if (!listed) { + scr_throw_domex("DataError", "Key operations and usage mismatch"); + return false; + } + } + } + const ScrDyn *ext = sw_jwk_member(jwk, "ext"); + if (ext && ext->kind == SCR_DYN_BOOL && !ext->v.b && extractable) { + scr_throw_domex("DataError", "JWK \"ext\" Parameter and extractable mismatch"); + return false; + } + return true; +} + +/* The JWK "alg" an RSA key with this hash carries ("RS256", "PS384"). */ +static void sw_rsa_jwk_alg(SwKind kind, const char *hash, char out[8]) { + const char *bits = strcmp(hash, "SHA-1") == 0 ? "1" : hash + 4; + snprintf(out, 8, "%s%s", kind == SW_PSS ? "PS" : "RS", bits); +} + +static ScrDyn *sw_import(const ScrDyn *args) { + static const char prefix[] = "Failed to execute 'importKey' on 'SubtleCrypto'"; + if (!scr_wc_required(prefix, args, 5)) return NULL; + ScrWcArgs a; + scr_wc_args_take(&a, args, 5); + ScrDyn *result = NULL; + ScrBytes *data = NULL; + ScrDyn *jwk = NULL; + ScrDyn *plain = NULL; + const char *format = scr_wc_key_format(prefix, a.v[0]); + if (!format) goto done; + bool is_jwk = strcmp(format, "jwk") == 0; + if (is_jwk) { + if (!scr_wc_is_object(a.v[1])) { + scr_wc_type_error("ERR_INVALID_ARG_TYPE", "%s: 2nd argument is not of type JsonWebKey.", prefix); + goto done; + } + jwk = scr_wc_plain(a.v[1]); + if (!jwk) goto done; + } else { + data = scr_wc_buffer_source(prefix, 1, a.v[1]); + if (!data) goto done; + } + if (!scr_wc_is_object(a.v[2])) { + ScrStr *s = scr_wc_dom_string(a.v[2]); + if (!s) goto done; + scr_str_release(s); + } + bool extractable = scr_dyn_truthy(a.v[3]); + long usages = scr_wc_key_usages(prefix, 4, a.v[4]); + if (usages < 0) goto done; + const char *name = sw_algorithm_name(a.v[2]); + if (!name) goto done; + SwKind kind = sw_kind_of(name); + plain = scr_wc_plain(a.v[2]); + if (!plain) goto done; + const char *curve = NULL; + const char *hash = NULL; + if (kind == SW_ED25519) { + /* no parameters */ + } else if (kind == SW_ECDSA) { + if (!scr_wc_is_object(plain)) { + scr_wc_missing_member("EcKeyImportParams", "namedCurve"); + goto done; + } + curve = sw_named_curve(plain, "EcKeyImportParams"); + if (!curve) goto done; + } else { + if (!scr_wc_is_object(plain)) { + scr_wc_missing_member("RsaHashedImportParams", "hash"); + goto done; + } + hash = sw_hash(plain, "RsaHashedImportParams", true, "importKey"); + if (!hash) goto done; + } + bool private_key; + if (is_jwk) { + private_key = sw_jwk_member(jwk, "d") != NULL; + } else if (strcmp(format, "pkcs8") == 0) { + private_key = true; + } else if (strcmp(format, "spki") == 0 || + ((kind == SW_ECDSA || kind == SW_ED25519) && strcmp(format, "raw") == 0)) { + private_key = false; + } else { + char message[96]; + snprintf(message, sizeof message, "Unable to import %s using %s format", sw_names[kind], format); + scr_throw_domex("NotSupportedError", message); + goto done; + } + unsigned allowed = private_key ? SCR_WC_USAGE_SIGN : SCR_WC_USAGE_VERIFY; + ScrPkiKey *key = NULL; + /* An Ed25519 private key derives its public key in the Ed25519 unit. */ + if (kind == SW_ED25519 && private_key && !scr_pki_ed25519_ready()) goto done; + if (is_jwk) { + const ScrDyn *kty = sw_jwk_member(jwk, "kty"); + if (!kty) { + scr_throw_domex("DataError", "Invalid keyData"); + goto done; + } + if (!sw_jwk_is(kty, kind == SW_ECDSA ? "EC" : kind == SW_ED25519 ? "OKP" : "RSA")) { + scr_throw_domex("DataError", "Invalid JWK \"kty\" Parameter"); + goto done; + } + if (kind == SW_ECDSA && !sw_jwk_is(sw_jwk_member(jwk, "crv"), curve)) { + scr_throw_domex("DataError", "JWK \"crv\" does not match the requested algorithm"); + goto done; + } + if (kind == SW_ED25519 && !sw_jwk_is(sw_jwk_member(jwk, "crv"), "Ed25519")) { + scr_throw_domex("DataError", "JWK \"crv\" Parameter and algorithm name mismatch"); + goto done; + } + if ((unsigned)usages & ~allowed) { + sw_unsupported_usage(kind); + goto done; + } + if (!sw_jwk_checks(jwk, (unsigned)usages, extractable)) goto done; + const ScrDyn *alg = sw_jwk_member(jwk, "alg"); + if (kind == SW_ED25519 && alg && !sw_jwk_is(alg, "Ed25519") && !sw_jwk_is(alg, "EdDSA")) { + scr_throw_domex("DataError", "JWK \"alg\" does not match the requested algorithm"); + goto done; + } + if (sw_is_rsa_kind(kind) && alg) { + char expected[8]; + sw_rsa_jwk_alg(kind, hash, expected); + if (!sw_jwk_is(alg, expected)) { + scr_throw_domex("DataError", "JWK \"alg\" does not match the requested algorithm"); + goto done; + } + } + key = scr_pki_key_from_jwk(jwk, private_key); + } else { + if ((unsigned)usages & ~allowed) { + sw_unsupported_usage(kind); + goto done; + } + ScrBytes *view = data; + SCR_BYTES_SNAPSHOT(view); + size_t len = (size_t)scr_bytes_byte_len(view); + if (strcmp(format, "raw") == 0) + key = kind == SW_ED25519 ? scr_pki_key_from_ed25519_raw(view->data, len) + : scr_pki_key_from_point(curve, view->data, len); + else key = scr_pki_key_parse_der(view->data, len, private_key); + } + if (!key) { + scr_throw_domex("DataError", "Invalid keyData"); + goto done; + } + bool key_matches = kind == SW_ED25519 ? scr_pki_key_is_ed25519(key) + : kind == SW_ECDSA ? !scr_pki_key_is_rsa(key) && !scr_pki_key_is_ed25519(key) + : scr_pki_key_is_rsa(key); + if (!key_matches) { + scr_pki_key_release(key); + scr_throw_domex("DataError", "Invalid key type"); + goto done; + } + if (kind == SW_ECDSA && strcmp(scr_pki_key_curve(key), curve) != 0) { + scr_pki_key_release(key); + scr_throw_domex("DataError", "Named curve mismatch"); + goto done; + } + if (private_key && usages == 0) { + scr_pki_key_release(key); + scr_throw_domex("SyntaxError", "Usages cannot be empty when importing a private key."); + goto done; + } + result = sw_key_new(key, kind, hash, (unsigned)usages, extractable); +done: + if (data) scr_bytes_release(data); + if (jwk) scr_dyn_release(jwk); + if (plain) scr_dyn_release(plain); + scr_wc_args_drop(&a, 5); + return result; +} + +static ScrPromise *sw_import_key(const ScrDyn *args) { + ScrDyn *key = sw_import(args); + if (!key) return scr_wc_rejected(); + return scr_promise_settled_ref(key, &scr_dyn_retain_v, &scr_dyn_release_v, NULL); +} + +/* ── exportKey ────────────────────────────────────────────────────────── */ + +static ScrDyn *sw_array_buffer(ScrBytes *bytes) { + ScrDyn *out = scr_array_buffer_from_bytes(bytes); + scr_bytes_release(bytes); + return out; +} + +static ScrDyn *sw_export(const ScrDyn *args) { + ScrWcArgs a; + scr_wc_args_take(&a, args, 2); + ScrDyn *result = NULL; + const char *format = scr_wc_key_format("Failed to execute 'exportKey' on 'SubtleCrypto'", a.v[0]); + SwKey *k = sw_key_of(a.v[1]); + bool private_key = scr_pki_key_is_private(k->key); + if (!format) goto done; + if (!k->extractable) { + scr_throw_domex("InvalidAccessError", "key is not extractable"); + goto done; + } + if (strcmp(format, "spki") == 0 || strcmp(format, "pkcs8") == 0) { + bool want_private = strcmp(format, "pkcs8") == 0; + if (want_private != private_key) { + scr_throw_domex("InvalidAccessError", want_private ? "Key must be a private key" : "Key must be a public key"); + goto done; + } + ScrBytes *der = scr_pki_export_der(k->key); + if (!der) { + scr_throw_domex("OperationError", "Failed to export key"); + goto done; + } + result = sw_array_buffer(der); + } else if (strcmp(format, "raw") == 0 && (k->kind == SW_ECDSA || k->kind == SW_ED25519) && + !private_key) { + ScrBytes *point = k->kind == SW_ED25519 ? scr_pki_export_ed25519_raw(k->key) : scr_pki_export_point(k->key); + if (!point) { + scr_throw_domex("OperationError", "Failed to export key"); + goto done; + } + result = sw_array_buffer(point); + } else if (strcmp(format, "jwk") == 0) { + ScrDyn *members = scr_pki_export_jwk(k->key); + ScrDyn *jwk = scr_dyn_new_obj(); + scr_dyn_obj_set(jwk, "key_ops", 7, sw_usage_array(k->usages)); + scr_dyn_obj_set(jwk, "ext", 3, scr_dyn_new_bool(k->extractable)); + if (sw_is_rsa_kind(k->kind)) { + char alg[8]; + sw_rsa_jwk_alg(k->kind, k->hash, alg); + scr_dyn_obj_set(jwk, "alg", 3, scr_wc_cstr(alg)); + } else if (k->kind == SW_ED25519) { + scr_dyn_obj_set(jwk, "alg", 3, scr_wc_cstr("Ed25519")); + } + /* The key members in Node's order for each key type. */ + static const char *const rsa_names[] = {"kty", "n", "e", "d", "p", "q", "dp", "dq", "qi"}; + static const char *const ec_names[] = {"kty", "x", "y", "crv", "d"}; + static const char *const okp_names[] = {"kty", "crv", "x", "d"}; + const char *const *names = sw_is_rsa_kind(k->kind) ? rsa_names : k->kind == SW_ED25519 ? okp_names : ec_names; + size_t count = sw_is_rsa_kind(k->kind) ? SCR_WC_COUNT(rsa_names) + : k->kind == SW_ED25519 ? SCR_WC_COUNT(okp_names) + : SCR_WC_COUNT(ec_names); + for (size_t i = 0; i < count; i++) { + const ScrDyn *v = scr_dyn_obj_get(members, names[i], strlen(names[i])); + if (v) scr_dyn_obj_set(jwk, names[i], strlen(names[i]), scr_dyn_retain((ScrDyn *)v)); + } + scr_dyn_release(members); + result = jwk; + } else { + char message[128]; + snprintf(message, sizeof message, "Unable to export %s %s key using %s format", sw_names[k->kind], + private_key ? "private" : "public", format); + scr_throw_domex("NotSupportedError", message); + } +done: + scr_wc_args_drop(&a, 2); + return result; +} + +static ScrPromise *sw_export_key(const ScrDyn *args) { + ScrDyn *value = sw_export(args); + if (!value) return scr_wc_rejected(); + return scr_promise_settled_ref(value, &scr_dyn_retain_v, &scr_dyn_release_v, NULL); +} + +/* ── sign and verify ──────────────────────────────────────────────────── */ + +/* The deferred verify result: a dyn boolean. */ +static void sw_settle_verified(ScrClosure *cb, ScrError *error, ScrBytes *value) { + (void)error; + ScrPromise *p; + memcpy(&p, &cb->caps[0]->slot, sizeof p); + ScrDyn *verified = (ScrDyn *)value; + scr_promise_fulfill_bool(p, scr_dyn_truthy(verified)); + scr_dyn_release(verified); +} + +static ScrPromise *sw_sign_verify(const ScrDyn *args, bool verify) { + const char *prefix = verify ? "Failed to execute 'verify' on 'SubtleCrypto'" + : "Failed to execute 'sign' on 'SubtleCrypto'"; + const char *method = verify ? "verify" : "sign"; + size_t n = verify ? 4 : 3; + if (!scr_wc_required(prefix, args, n)) return scr_wc_rejected(); + ScrWcArgs a; + scr_wc_args_take(&a, args, n); + ScrPromise *result = NULL; + ScrBytes *data = NULL; + ScrBytes *signature = NULL; + ScrDyn *plain = NULL; + if (!scr_wc_is_object(a.v[0])) { + ScrStr *s = scr_wc_dom_string(a.v[0]); + if (!s) goto done; + scr_str_release(s); + } + SwKey *k = sw_key_of(a.v[1]); + if (!k && !scr_webcrypto_is_crypto_key(a.v[1])) { + scr_wc_type_error("ERR_INVALID_ARG_TYPE", "%s: 2nd argument is not of type CryptoKey.", prefix); + goto done; + } + if (verify) { + signature = scr_wc_buffer_source(prefix, 2, a.v[2]); + if (!signature) goto done; + } + data = scr_wc_buffer_source(prefix, verify ? 3 : 2, a.v[verify ? 3 : 2]); + if (!data) goto done; + const char *name = sw_algorithm_name(a.v[0]); + if (!name) goto done; + SwKind kind = sw_kind_of(name); + plain = scr_wc_plain(a.v[0]); + if (!plain) goto done; + const char *hash = NULL; + int salt = 0; + if (kind == SW_ED25519) { + /* no parameters */ + } else if (kind == SW_ECDSA) { + if (!scr_wc_is_object(plain)) { + scr_wc_missing_member("EcdsaParams", "hash"); + goto done; + } + hash = sw_hash(plain, "EcdsaParams", false, method); + if (!hash) goto done; + } else if (kind == SW_PSS) { + if (!scr_wc_is_object(plain)) { + scr_wc_missing_member("RsaPssParams", "saltLength"); + goto done; + } + ScrDyn *value = sw_required(plain, "RsaPssParams", "saltLength"); + if (!value) goto done; + double x; + bool ok = sw_unsigned_long(value, "saltLength", &x); + scr_dyn_release(value); + if (!ok) goto done; + salt = x > 65536 ? 65536 : (int)x; + } + if (!k || k->kind != kind) { + scr_throw_domex("InvalidAccessError", "Key algorithm mismatch"); + goto done; + } + if (!(k->usages & (verify ? SCR_WC_USAGE_VERIFY : SCR_WC_USAGE_SIGN))) { + char message[64]; + snprintf(message, sizeof message, "Unable to use this key to %s", method); + scr_throw_domex("InvalidAccessError", message); + goto done; + } + if (sw_is_rsa_kind(kind)) hash = k->hash; + if (kind == SW_ED25519 && !scr_pki_ed25519_ready()) goto done; + { + ScrBytes *view = data; + SCR_BYTES_SNAPSHOT(view); + size_t len = (size_t)scr_bytes_byte_len(view); + if (verify) { + ScrBytes *sig = signature; + SCR_BYTES_SNAPSHOT(sig); + bool ok = scr_pki_verify(k->key, hash, kind == SW_PSS, salt, view->data, len, sig->data, + (size_t)scr_bytes_byte_len(sig)); + result = scr_promise_new(); + scr_crypto_defer_dyn(scr_dyn_new_bool(ok), NULL, scr_crypto_promise_callback(result), sw_settle_verified); + } else { + ScrBytes *out = scr_pki_sign(k->key, hash, kind == SW_PSS, salt, view->data, len); + if (!out) { + scr_throw_domex("OperationError", "Failed to sign"); + goto done; + } + result = scr_promise_new(); + scr_crypto_defer_bytes(out, NULL, scr_crypto_promise_callback(result), scr_crypto_promise_settle_array_buffer); + } + } +done: + if (data) scr_bytes_release(data); + if (signature) scr_bytes_release(signature); + if (plain) scr_dyn_release(plain); + scr_wc_args_drop(&a, n); + return result ? result : scr_wc_rejected(); +} + +static ScrPromise *sw_sign(const ScrDyn *args) { return sw_sign_verify(args, false); } + +static ScrPromise *sw_verify(const ScrDyn *args) { return sw_sign_verify(args, true); } + +static const ScrWcAsymmetric sw_table = { + .generate_key = sw_generate_key, + .import_key = sw_import_key, + .export_key = sw_export_key, + .sign = sw_sign, + .verify = sw_verify, + .is_key = sw_is_key, +}; + +/* Installed before main: scr_webcrypto.c dispatches these algorithms + * here. */ +__attribute__((constructor)) static void sw_install(void) { scr_wc_asymmetric = &sw_table; } diff --git a/packages/runtime/src/scr_worker.c b/packages/runtime/src/scr_worker.c index 67f4ec084..59e245ea0 100644 --- a/packages/runtime/src/scr_worker.c +++ b/packages/runtime/src/scr_worker.c @@ -99,9 +99,10 @@ static bool scr_worker_stats(void) { static ScrMailEvent *scr_worker_event(unsigned kind, uint64_t source, int code, ScrMessage *message) { - ScrMailEvent *event = calloc(1, sizeof(*event)); + ScrMailEvent *event = message ? scr_message_mail_event(message) : calloc(1, sizeof(*event)); if (!event) scr_trap("scriptc: out of memory\n"); - *event = (ScrMailEvent){.kind = kind, .source = source, .code = code, .message = message}; + *event = (ScrMailEvent){ + .kind = kind, .source = source, .code = code, .message = message, .in_message = message != NULL}; return event; } diff --git a/packages/runtime/src/scr_worker_events.c b/packages/runtime/src/scr_worker_events.c index 252230372..3d10183f4 100644 --- a/packages/runtime/src/scr_worker_events.c +++ b/packages/runtime/src/scr_worker_events.c @@ -665,6 +665,17 @@ static bool scr_channel_dispatch(void) { continue; } scr_worker_view_retain(view); + if (event->message && !view->broadcast && scr_message_readable(event->message)) { + /* Compiled listeners with a typed message entry read the message. */ + ScrStr *name = scr_str_new("message", 7); + scr_dyn_this_push(view, SCR_DYNH_MESSAGE_PORT); + scr_emitter_emit_message(view->events, name, event->message, scr_message_decode); + scr_dyn_this_pop(); + scr_str_release(name); + scr_mail_event_free(event); + scr_worker_view_release(view); + return true; + } ScrDyn *argument = event->message ? scr_message_decode(event->message) : NULL; if (argument && view->broadcast) { ScrDyn *self = scr_dyn_new_handle(view, SCR_DYNH_BROADCAST_CHANNEL); @@ -815,6 +826,19 @@ static void scr_worker_dispatch(void) { } } scr_worker_view_retain(view); + if (event->kind == SCR_WORKER_MESSAGE && event->message && scr_message_readable(event->message)) { + /* Compiled listeners with a typed message entry read the message. */ + if (!scr_exc_pending()) { + ScrStr *name = scr_str_new("message", 7); + scr_dyn_this_push(view, view->port ? SCR_DYNH_MESSAGE_PORT : SCR_DYNH_WORKER); + scr_emitter_emit_message(view->events, name, event->message, scr_message_decode); + scr_dyn_this_pop(); + scr_str_release(name); + } + scr_worker_view_release(view); + scr_mail_event_free(event); + return; + } const char *event_name = event->kind == SCR_WORKER_ONLINE ? "online" : event->kind == SCR_WORKER_EXIT ? "exit" : event->kind == SCR_WORKER_ERROR ? "error" : "message"; ScrDyn *argument = event->message ? scr_message_decode(event->message) : diff --git a/packages/runtime/src/scr_zlib_stream.c b/packages/runtime/src/scr_zlib_stream.c index 4ed717d53..54ffacf02 100644 --- a/packages/runtime/src/scr_zlib_stream.c +++ b/packages/runtime/src/scr_zlib_stream.c @@ -104,7 +104,8 @@ static void scr_zs_finish(ScrZlibStream *zs, ScrStream *s) { zs->flushing = false; scr_stream_flush_done(s, NULL, NULL, NULL); } else { - scr_stream_transform_done(s, NULL, NULL, NULL); + /* scr_zs_complete has applied Transform._write's callback rule. */ + scr_stream_write_done(s, NULL); } } diff --git a/packages/runtime/test/dh.test.ts b/packages/runtime/test/dh.test.ts new file mode 100644 index 000000000..d402d0465 --- /dev/null +++ b/packages/runtime/test/dh.test.ts @@ -0,0 +1,85 @@ +import { execFile } from "node:child_process"; +import { mkdir } from "node:fs/promises"; +import { join } from "node:path"; +import { promisify } from "node:util"; +import { beforeAll, expect, test } from "vitest"; + +const execFileAsync = promisify(execFile); +const testDir = import.meta.dirname; +const bin = join(testDir, "build", "test_dh"); +const mbedtls = join(testDir, "../vendor/mbedtls"); + +const runtimeSources = [ + "scr_shared.c", + "scr_bytes.c", + "scr_bytes.test.c", + "scr_bytes_io.c", + "scr_fs_cp.c", + "scr_zlib.c", + "scr_lib.c", + "scr_hash.c", + "scr_string.c", + "scr_array.c", + "scr_map.c", + "scr_exception.c", + "scr_error.c", + "scr_number.c", + "scr_console.c", + "scr_closure.c", + "scr_ffi.c", + "scr_object.c", + "scr_union.c", + "scr_cycle.c", + "scr_alloc.c", + "scr_json.c", + "scr_inspect.c", + "scr_bigint.c", + "scr_async.c", + "scr_async_dyn.c", + "scr_child.c", + "scr_path.c", + "scr_url.c", + "scr_url_params.c", +]; + +// The bignum modules scr_dh.c uses. +const mbedtlsSources = ["bignum.c", "bignum_core.c", "constant_time.c", "platform_util.c"]; + +// Compiled once with ASan, UBSan and the RC audit. test_dh.c includes +// scr_dh.c and checks the primality tests' Montgomery exponentiation +// against mbedTLS's, the primality test on primes, Carmichael numbers and +// strong pseudoprimes, exponents past mbedTLS's 8192-bit limit, DH_check +// results, and generated safe primes. +beforeAll(async () => { + await mkdir(join(testDir, "build"), { recursive: true }); + await execFileAsync("clang", [ + "-std=c11", + "-O1", + "-Wall", + "-Wextra", + "-Wno-missing-field-initializers", + "-fsanitize=address,undefined", + "-DSCR_RC_AUDIT", + "-I", + join(testDir, "../src"), + "-I", + join(mbedtls, "include"), + "-I", + join(mbedtls, "library"), + "-o", + bin, + join(testDir, "test_dh.c"), + ...runtimeSources.map((source) => join(testDir, "../src", source)), + ...mbedtlsSources.map((source) => join(mbedtls, "library", source)), + "-Wno-deprecated-declarations", + "-lz", + ...(process.platform === "linux" ? ["-D_GNU_SOURCE", "-lm"] : []), + ]); +}, 300_000); + +test("DiffieHellman runtime: exponentiation, primality and safe primes", async () => { + const { stderr } = await execFileAsync(bin, [], { + env: { ...process.env, UBSAN_OPTIONS: "halt_on_error=1" }, + }); + expect(stderr.trim().split("\n").pop()).toMatch(/^(\d+)\/\1 cases passed$/); +}, 300_000); diff --git a/packages/runtime/test/test_array.c b/packages/runtime/test/test_array.c index d943acfb2..769b8ef3a 100644 --- a/packages/runtime/test/test_array.c +++ b/packages/runtime/test/test_array.c @@ -446,6 +446,44 @@ static void test_ref_elements(void) { #endif } +/* Elements whose release does nothing (SCR_ARR_OPS_RELEASE_NOTHING): the + * last release of an array frees its storage without calling the element + * release. An array with out-of-line storage keeps the full teardown. */ +static int nothing_releases = 0; +static void *nothing_retain(void *p) { return p; } +static void nothing_release(void *p) { + (void)p; + nothing_releases++; +} +static ScrArrOps nothing_ops = { ¬hing_retain, ¬hing_release, NULL, 0, + SCR_ARR_OPS_RELEASE_NOTHING }; + +static void test_release_nothing_ops(void) { +#ifdef SCR_RC_AUDIT + long arrays0 = scr_arr_live_count(); +#endif + static MockRec kept[3]; + ScrArr *a = scr_arr_new_ops(¬hing_ops, 0); + for (int i = 0; i < 3; i++) scr_arr_push_ref(a, &kept[i]); + ScrArr *shared = scr_arr_retain(a); + scr_arr_release(shared); + check_f64(scr_arr_len(a), 3, "release-nothing: a shared release keeps the array"); + scr_arr_release(a); + check(nothing_releases == 0, "release-nothing: teardown calls no element release"); + ScrArr *sparse = scr_arr_new_ops(¬hing_ops, 0); + scr_arr_push_ref(sparse, &kept[0]); + scr_arr_set_ref(sparse, 4000000000.0, &kept[1]); /* out-of-line sparse slot */ + check(scr_arr_ext_of(sparse) != NULL, "release-nothing: a far index makes an ext"); + scr_arr_release(sparse); + check(nothing_releases == 2, "release-nothing: an array with an ext keeps the full teardown"); + ScrArr *nums = scr_arr_new(SCR_ELEM_F64, 0); + scr_arr_push_f64(nums, 1); + scr_arr_release(nums); +#ifdef SCR_RC_AUDIT + check(scr_arr_live_count() == arrays0, "release-nothing: no arrays leaked"); +#endif +} + /* Element ops past the registry's capacity: every descriptor still finds its * own retain and release, and the first ones keep their registry ids. */ static void test_ops_overflow(void) { @@ -1365,11 +1403,13 @@ static void test_exact_construction(void) { } /* The hole-free prefix bound never covers a non-value state, and the - * operations that keep an array hole-free keep the bound at its length. */ + * operations that keep an array hole-free keep the bound at its length. An + * array without states keeps its elements in dense storage. */ static bool filled_ok(const ScrArr *a) { if (a->filled > a->len || a->filled > a->cap) return false; + if (!scr_arr_has_states(a) && (a->len > a->cap || a->filled != a->len)) return false; for (size_t i = 0; i < a->filled; i++) - if (*scr_arr_state_ptr(a, i) != SCR_ARR_VALUE) return false; + if (scr_arr_dense_state(a, i) != SCR_ARR_VALUE) return false; return true; } @@ -1444,7 +1484,7 @@ static void test_filled_prefix(void) { scr_arr_release(scr_arr_sort_primitive(b, false)); check(filled_ok(b), "sorting moves holes past the bound"); for (size_t i = 0; i < b->len; i++) { - if (i < b->cap && *scr_arr_state_ptr(b, i) != SCR_ARR_VALUE) break; + if (i < b->cap && scr_arr_dense_state(b, i) != SCR_ARR_VALUE) break; check(i < b->filled, "sorted values form the bound"); } while (scr_arr_len(b) > 0) { @@ -1464,11 +1504,13 @@ static void test_filled_prefix(void) { } /* Boolean arrays store one byte per dense element, followed by the states in - * the same allocation. Growth moves the states to the end of the larger area, - * densifying absorbs sparse entries into bytes, and every moving and copying - * operation keeps values, holes and present undefined in place. */ + * the same allocation once they have states. Growth moves the states to the + * end of the larger area, densifying absorbs sparse entries into bytes, and + * every moving and copying operation keeps values, holes and present + * undefined in place. */ static bool bool_layout_ok(const ScrArr *a) { - return a->cap == 0 || scr_arr_states_end(a) == (const uint8_t *)a->data + 2 * (size_t)a->cap; + return a->cap == 0 || !scr_arr_has_states(a) || + scr_arr_states_end(a) == (const uint8_t *)a->data + 2 * (size_t)a->cap; } static bool bool_states(const ScrArr *a, const char *want) { @@ -1584,7 +1626,7 @@ static void test_inline_slots(void) { * block; growth past them moves them out like any inline array. */ ScrArr *known = scr_arr_new(SCR_ELEM_F64, 4); check(inline_slots(known) && known->cap >= 4 && known->len == 0 && !scr_arr_has(known, 0) && - scr_arr_states_end(known) == (uint8_t *)(known->data + known->cap) + known->cap, + !scr_arr_has_states(known), "a known-count construction places its slots in the array block"); size_t known_cap = known->cap; for (size_t i = 0; i <= known_cap; i++) scr_arr_push_f64(known, (double)i); @@ -1605,26 +1647,25 @@ static void test_inline_slots(void) { "known-count boolean constructions are inline too"); scr_arr_release(known_flags); ScrArr *a = scr_arr_new_small(SCR_ELEM_F64); - check(inline_slots(a) && a->cap >= 4 && a->len == 0 && - scr_arr_states_end(a) == (uint8_t *)(a->data + a->cap) + a->cap, - "small construction places slots and states in the array block"); + check(inline_slots(a) && a->cap >= 4 && a->len == 0 && !scr_arr_has_states(a), + "small construction places its slots in the array block, without states"); size_t inline_cap = a->cap; for (size_t i = 0; i < inline_cap; i++) scr_arr_push_f64(a, (double)i); check(inline_slots(a) && a->filled == inline_cap, "appends within the inline capacity stay inline"); scr_arr_push_f64(a, 100); check(!inline_slots(a) && a->cap > inline_cap && scr_arr_get_f64(a, 0) == 0 && scr_arr_get_f64(a, (double)inline_cap - 1) == (double)inline_cap - 1 && - scr_arr_get_f64(a, (double)inline_cap) == 100 && - scr_arr_states_end(a) == (uint8_t *)(a->data + a->cap) + a->cap, + scr_arr_get_f64(a, (double)inline_cap) == 100 && !scr_arr_has_states(a), "growth moves inline slots to their own allocation"); scr_arr_release(a); ScrArr *flags = scr_arr_new_small(SCR_ELEM_BOOL); - check(inline_slots(flags) && scr_arr_states_end(flags) == (uint8_t *)flags->data + 2 * (size_t)flags->cap, + check(inline_slots(flags) && flags->cap >= 4 && !scr_arr_has_states(flags), "boolean inline slots are one byte each"); scr_arr_push_bool(flags, true); scr_arr_set_bool(flags, 3, true); - check(scr_arr_get_bool(flags, 0) && !scr_arr_has(flags, 1) && scr_arr_get_bool(flags, 3), + check(scr_arr_get_bool(flags, 0) && !scr_arr_has(flags, 1) && scr_arr_get_bool(flags, 3) && + scr_arr_has_states(flags) && bool_layout_ok(flags), "boolean inline slots keep holes"); scr_arr_release(flags); @@ -2107,8 +2148,8 @@ static void test_head_room(void) { check_f64(scr_arr_shift_f64(q), 0, "shift answers the first element"); check(q->data == block + 1 && q->cap == cap - 1 && q->len == 63, "shift advances the storage instead of moving the tail"); - check(scr_arr_states_end(q) == (uint8_t *)(block + cap) + cap - 1 && head_room(q) && q->data[-1] == 1, - "the remaining states stay at the end of the allocation"); + check(!scr_arr_has_states(q) && head_room(q) && q->data[-1] == 1, + "shift records the vacated slot in front of the data"); check(q->filled == 63, "shift keeps the hole-free prefix"); for (int i = 1; i < 40; i++) scr_arr_shift_f64(q); check(q->data == block + 40 && q->len == 24 && scr_arr_get_f64(q, 0) == 40 && @@ -2223,6 +2264,159 @@ static void test_head_room(void) { #endif } +/* SCR_ARR_STATES (scr_array.h): an array starts without state bytes and + * keeps none while every index below its length is a present value. A + * hole, a present undefined or a length past the elements gives it states, + * with the elements in place. */ +static ScrStr *str_of(const char *text) { return scr_str_new(text, strlen(text)); } + +static bool strs_are(ScrArr *a, const char *want) { + /* want: one character per element, '_' a hole, 'u' undefined. */ + if (scr_arr_len(a) != (double)strlen(want)) return false; + for (size_t i = 0; want[i]; i++) { + double state = scr_arr_state(a, (double)i); + if (want[i] == '_') { + if (state != SCR_ARR_HOLE) return false; + } else if (want[i] == 'u') { + if (state != SCR_ARR_UNDEFINED) return false; + } else { + if (state != SCR_ARR_VALUE) return false; + ScrStr *got = scr_arr_get_ref(a, (double)i); + bool same = got->len == 1 && got->data[0] == want[i]; + scr_str_release(got); + if (!same) return false; + } + } + return filled_ok(a); +} + +static ScrArr *strs_of(const char *text, bool small) { + ScrArr *a = small ? scr_arr_new_small(SCR_ELEM_STR) : scr_arr_new(SCR_ELEM_STR, 0); + for (size_t i = 0; text[i]; i++) scr_arr_push_ref(a, scr_str_new(text + i, 1)); + return a; +} + +static void test_states_on_demand(void) { +#ifdef SCR_RC_AUDIT + long strings0 = scr_str_live_count(); + long arrays0 = scr_arr_live_count(); +#endif + ScrArr *a = strs_of("abcdef", false); + scr_arr_set_ref(a, 1, str_of("B")); + scr_arr_set_ref(a, 6, str_of("g")); + scr_str_release(scr_arr_pop_ref(a)); + scr_arr_set_len(a, 5); + check(!scr_arr_has_states(a) && a->filled == 5 && strs_are(a, "aBcde"), + "pushes, writes below the length, appends, pops and truncation keep no states"); + scr_arr_set_undefined(a, 2); + check(scr_arr_has_states(a) && strs_are(a, "aBude"), "a present undefined gives the array states"); + scr_arr_release(a); + + ScrArr *gap = strs_of("ab", true); + scr_arr_set_ref(gap, 3, str_of("d")); + check(scr_arr_has_states(gap) && strs_are(gap, "ab_d"), "a write past the length leaves holes"); + scr_arr_release(gap); + + ScrArr *longer = strs_of("abc", true); + scr_arr_set_len(longer, 5); + check(scr_arr_has_states(longer) && strs_are(longer, "abc__"), "a longer length adds holes"); + scr_arr_release(longer); + + /* `new Array(n)` and a length set on an empty small array: the inline + * slots give way to one allocation holding the slots and their states. */ + ScrArr *sized = scr_arr_new_small(SCR_ELEM_STR); + scr_arr_set_len(sized, 6); + scr_arr_set_ref(sized, 4, str_of("e")); + check(scr_arr_has_states(sized) && !(sized->spare & SCR_ARR_INLINE_SLOTS) && sized->cap == 6 && + strs_are(sized, "____e_") && filled_ok(sized), + "a length set on an empty inline array reserves that many slots with states"); + scr_arr_release(sized); + + ScrArr *deleted = strs_of("abcd", false); + scr_arr_delete(deleted, 1); + check(scr_arr_has_states(deleted) && strs_are(deleted, "a_cd"), "delete leaves a hole"); + scr_arr_release(deleted); + + /* Conversion keeps out-of-line storage and head room's elements. */ + ScrArr *props = strs_of("abc", true); + scr_arr_set_ref(props, -1, str_of("p")); + scr_arr_set_undefined(props, 3); + ScrStr *prop = scr_arr_get_ref(props, -1); + check(scr_arr_has_states(props) && strs_are(props, "abcu") && prop->data[0] == 'p', + "states keep a noncanonical property"); + scr_str_release(prop); + scr_arr_release(props); + ScrArr *q = strs_of("abcdefghijklmnopqrst", false); + for (int i = 0; i < 3; i++) scr_str_release(scr_arr_shift_ref(q)); + check(!scr_arr_has_states(q) && head_room(q), "shift keeps no states"); + scr_arr_set_undefined(q, 1); + check(scr_arr_has_states(q) && !head_room(q) && strs_are(q, "dufghijklmnopqrst"), + "states move the elements of head room to the front"); + scr_arr_release(q); + + /* Copies keep no states for values, and states for holes. */ + ScrArr *src = strs_of("abcde", false); + ScrArr *part = scr_arr_slice(src, 1, 4); + ScrArr *joined = scr_arr_slice(src, 0, INFINITY); + scr_arr_concat_copy(joined, src); + ScrArr *spliced = scr_arr_splice(joined, 2, 3); + ScrArr *reversed = scr_arr_to_reversed(src); + scr_arr_release(scr_arr_reverse(src)); + scr_arr_release(scr_arr_sort_primitive(src, false)); + check(!scr_arr_has_states(part) && strs_are(part, "bcd"), "a slice of values keeps no states"); + check(!scr_arr_has_states(joined) && strs_are(joined, "ababcde"), + "concat and splice of values keep no states"); + check(!scr_arr_has_states(spliced) && strs_are(spliced, "cde"), "removed values keep no states"); + check(!scr_arr_has_states(reversed) && strs_are(reversed, "edcba"), "toReversed of values keeps no states"); + check(!scr_arr_has_states(src) && strs_are(src, "abcde"), "reverse and sort of values keep no states"); + scr_arr_release(src); + scr_arr_release(part); + scr_arr_release(joined); + scr_arr_release(spliced); + scr_arr_release(reversed); + ScrArr *holey = strs_of("ab", false); + scr_arr_set_ref(holey, 3, str_of("d")); + ScrArr *spread = strs_of("x", true); + scr_arr_push_spread(spread, holey); + ScrArr *concat = strs_of("x", true); + scr_arr_concat_copy(concat, holey); + ScrArr *values = scr_arr_slice(holey, 0, 2); + ScrArr *front = strs_of("yz", false); + scr_arr_unshift_spread(front, holey); + check(scr_arr_has_states(spread) && strs_are(spread, "xabud") && scr_arr_has_states(concat) && + strs_are(concat, "xab_d") && !scr_arr_has_states(values) && strs_are(values, "ab") && + scr_arr_has_states(front) && strs_are(front, "abudyz"), + "copies of holes keep holes or present undefined"); + scr_arr_release(holey); + scr_arr_release(spread); + scr_arr_release(concat); + scr_arr_release(values); + scr_arr_release(front); + + /* Numbers and booleans take the same paths without references. */ + ScrArr *nums = scr_arr_new(SCR_ELEM_F64, 3); + for (int i = 0; i < 40; i++) scr_arr_push_f64(nums, i); + scr_arr_release(scr_arr_fill_f64(nums, 7, 30, INFINITY)); + check(!scr_arr_has_states(nums) && scr_arr_get_number(nums, 39) == 7 && scr_arr_get_number(nums, 40) != 0, + "number fills keep no states"); + scr_arr_release(scr_arr_fill_undefined(nums, 0, 1)); + check(scr_arr_has_states(nums) && scr_arr_state(nums, 0) == SCR_ARR_UNDEFINED && + scr_arr_get_number(nums, 1) == 1 && scr_arr_get_number(nums, 39) == 7 && filled_ok(nums), + "an undefined fill gives a number array states"); + scr_arr_release(nums); + ScrArr *bits = scr_arr_new_small(SCR_ELEM_BOOL); + for (int i = 0; i < 6; i++) scr_arr_push_bool(bits, i % 2 == 0); + scr_arr_set_undefined(bits, 6); + check(scr_arr_has_states(bits) && bool_layout_ok(bits) && scr_arr_get_bool(bits, 4) && + !scr_arr_get_bool(bits, 5) && scr_arr_state(bits, 6) == SCR_ARR_UNDEFINED, + "boolean arrays get one state byte per element"); + scr_arr_release(bits); +#ifdef SCR_RC_AUDIT + check(scr_str_live_count() == strings0, "states on demand: no strings leaked"); + check(scr_arr_live_count() == arrays0, "states on demand: no arrays leaked"); +#endif +} + int main(int argc, char **argv) { if (argc > 1) { ScrArr *a = scr_arr_new(SCR_ELEM_F64, 0); @@ -2263,6 +2457,7 @@ int main(int argc, char **argv) { test_nested_rc(); test_index_of_includes(); test_ref_elements(); + test_release_nothing_ops(); test_ref_known_count_cycle(&mock_cyc_ops); test_ops_overflow(); test_ref_known_count_cycle(&mock_cyc_ops_late); @@ -2279,6 +2474,7 @@ int main(int argc, char **argv) { test_bool_bytes(); test_inline_slots(); test_head_room(); + test_states_on_demand(); fprintf(stderr, "%ld/%ld cases passed\n", total - failed, total); return failed == 0 ? 0 : 1; diff --git a/packages/runtime/test/test_cycle.c b/packages/runtime/test/test_cycle.c index 4e00b852e..160083d6b 100644 --- a/packages/runtime/test/test_cycle.c +++ b/packages/runtime/test/test_cycle.c @@ -536,6 +536,27 @@ static void check_mixed_dead_structure_narrows(void) { check(live <= narrowed, "a pass that freed a dead mature and old structure did not narrow the growth fraction"); } +/* scr_cyc_set_growth_cap sets the cap SCR_CYCLE_GROWTH_CAP sets, and a + * fraction already widened past it starts at it: after passes that found + * nothing widened the old level's fraction to the configured cap, a cap of + * 1 has the next dead cycle go once the heap has doubled past the floor. + * Restores the configured cap. */ +static void check_program_growth_cap(void) { + enum { FLOOR = 4096 }; + if (getenv("SCR_CYCLE_GROWTH_CAP") != NULL) return; /* it takes precedence */ + size_t slack = 2 * configured_nursery_threshold() + 2; + size_t live = 0; + for (int i = 0; i < 4; i++) live = grow_dead_cycle_until_full_pass(0, false); + check(live > FLOOR + FLOOR * configured_growth_cap(), + "passes that found nothing did not widen the growth fraction to the cap"); + scr_cyc_set_growth_cap(1); + for (int i = 0; i < 4; i++) { + live = grow_dead_cycle_until_full_pass(0, false); + check(live <= FLOOR + FLOOR + slack, "a program's growth cap of 1 did not bound the heap"); + } + scr_cyc_set_growth_cap(0); +} + /* The phase sweep (scr_collect_cycles_phase) is for a caller that knows a * phase's data has just died: it sweeps, and the growth schedule starts * over. After passes that find nothing have widened the old level's @@ -1500,6 +1521,7 @@ int main(void) { check_large_old_buffer_with_nursery_candidates(); check_unjudged_backlog_follows_growth(); check_acyclic_objects(); + check_program_growth_cap(); printf("cycle collection checks passed: threshold=%zu growth_cap=%zu\n", configured_nursery_threshold(), configured_growth_cap()); return 0; diff --git a/packages/runtime/test/test_dh.c b/packages/runtime/test/test_dh.c new file mode 100644 index 000000000..f459f1047 --- /dev/null +++ b/packages/runtime/test/test_dh.c @@ -0,0 +1,280 @@ +/* Unit tests for the DiffieHellman runtime's arithmetic (scr_dh.c), built + * with ASan and UBSan by dh.test.ts. The unit is included directly so the + * tests can compare the Montgomery exponentiation the primality tests use + * with mbedTLS's, run the primality test on primes, Carmichael numbers and + * strong pseudoprimes to small bases, split exponents past mbedTLS's limit, + * and check generated safe primes and DH_check results. */ +#include "../src/scr_dh.c" + +#include +#include + +static long total = 0, failed = 0; + +static void check(bool ok, const char *what) { + total++; + if (!ok) { + failed++; + fprintf(stderr, "FAIL: %s\n", what); + } +} + +static void from_hex(mbedtls_mpi *x, const char *hex) { + if (mbedtls_mpi_read_string(x, 16, hex) != 0) scr_trap("bad hex\n"); +} + +/* The Montgomery exponentiation, with the base 2 and with general bases, + * against mbedtls_mpi_exp_mod for moduli of one to 64 limbs. */ +static void test_mont_pow(void) { +#if SD_MONT + static const size_t sizes[] = {3, 64, 65, 127, 128, 129, 512, 1000, 2048, 4096}; + mbedtls_mpi n, base, e, two, got, want; + mbedtls_mpi_init(&n); + mbedtls_mpi_init(&base); + mbedtls_mpi_init(&e); + mbedtls_mpi_init(&two); + mbedtls_mpi_init(&got); + mbedtls_mpi_init(&want); + mbedtls_mpi_lset(&two, 2); + for (size_t s = 0; s < sizeof sizes / sizeof sizes[0]; s++) { + for (int trial = 0; trial < 6; trial++) { + size_t bits = sizes[s]; + sd_random_bits(&n, bits, true); + if (mbedtls_mpi_cmp_int(&n, 3) <= 0) mbedtls_mpi_lset(&n, 7); + sd_random_bits(&base, bits > 2 ? bits - 1 : 1, false); + size_t ebits = trial == 0 ? 1 : trial == 1 ? bits + 70 : (bits * (size_t)trial) / 5 + 1; + sd_random_bits(&e, ebits, false); + if (trial == 0) mbedtls_mpi_lset(&e, 0); + ScDhMont m; + bool ready = sd_mont_init(&m, &n); + check(ready, "sd_mont_init"); + char what[96]; + snprintf(what, sizeof what, "base^e mod n for %zu bits, trial %d", bits, trial); + bool ok = ready && sd_mont_pow(&m, &got, &base, &e) && mbedtls_mpi_exp_mod(&want, &base, &e, &n, NULL) == 0; + check(ok && mbedtls_mpi_cmp_mpi(&got, &want) == 0, what); + snprintf(what, sizeof what, "2^e mod n for %zu bits, trial %d", bits, trial); + ok = ready && sd_mont_pow(&m, &got, NULL, &e) && mbedtls_mpi_exp_mod(&want, &two, &e, &n, NULL) == 0; + check(ok && mbedtls_mpi_cmp_mpi(&got, &want) == 0, what); + sd_mont_free(&m); + } + } + mbedtls_mpi_free(&n); + mbedtls_mpi_free(&base); + mbedtls_mpi_free(&e); + mbedtls_mpi_free(&two); + mbedtls_mpi_free(&got); + mbedtls_mpi_free(&want); +#endif +} + +/* BN_check_prime's answers for small values, Mersenne numbers, Carmichael + * numbers and strong pseudoprimes to small prime bases. */ +static void test_is_prime(void) { + static const struct { + const char *hex; + bool prime; + } cases[] = { + {"0", false}, + {"1", false}, + {"2", true}, + {"3", true}, + {"4", false}, + {"5", true}, + {"9", false}, + {"231", false}, /* 561, a Carmichael number */ + {"451", false}, /* 1105, a Carmichael number */ + {"7ff", false}, /* 2047, a strong pseudoprime to the base 2 */ + {"45c5", false}, /* 17861 = 53 · 337 */ + {"45c7", true}, /* 17863, the largest trial-division prime */ + {"bfa17dc7", false}, /* 3215031751, to the bases 2, 3, 5 and 7 */ + {"351591274f9af9fb", false}, /* 3825123056546413051, to the bases up to 23 */ + {"437ae92817f9fc85b7e5", false}, /* to the prime bases up to 37 */ + {"2be6951adc5b22410a5fd", false}, /* to the prime bases up to 41 */ + {"1fffffffffffffff", true}, /* 2^61 - 1 */ + {"1ffffffffffffffffffffff", true}, /* 2^89 - 1 */ + {"7fffffffffffffffffffffffffffffff", true}, /* 2^127 - 1 */ + {"100000000000000000000000000000001", false}, /* 2^128 + 1 */ + }; + ScDhSmallPrimes *small = sd_small_primes(); + mbedtls_mpi x; + mbedtls_mpi_init(&x); + for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) { + from_hex(&x, cases[i].hex); + char what[96]; + snprintf(what, sizeof what, "is_prime(0x%s) == %d", cases[i].hex, cases[i].prime); + check(sd_is_prime(small, &x) == cases[i].prime, what); + } + /* The modp groups' primes are safe primes. */ + for (size_t i = 0; i < 4; i++) { + mbedtls_mpi_read_binary(&x, sd_groups[i].p, sd_groups[i].p_len); + check(sd_is_prime(small, &x), "a modp prime is prime"); + mbedtls_mpi_shift_r(&x, 1); + check(sd_is_prime(small, &x), "half a modp prime is prime"); + mbedtls_mpi_add_int(&x, &x, 2); + check(!sd_is_prime(small, &x), "half a modp prime plus 2 is composite"); + } + mbedtls_mpi_free(&x); + free(small); +} + +/* DH_check bits for small and composite primes, the Pocklington path for + * safe primes, and a generator at p - 1. */ +static void test_check_params(void) { + static const struct { + const char *p; + int g; + int codes; + } cases[] = { + {"0", 2, 137}, {"1", 2, 137}, {"2", 2, 139}, {"3", 2, 138}, {"5", 2, 128}, {"5", 5, 136}, + {"7", 2, 128}, {"9", 2, 129}, {"f", 2, 129}, {"11", 2, 130}, {"17", 2, 128}, {"17", 22, 136}, + {"18", 2, 129}, {"231", 2, 129}, {"7ff", 2, 129}, + }; + mbedtls_mpi p, g; + mbedtls_mpi_init(&p); + mbedtls_mpi_init(&g); + for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) { + from_hex(&p, cases[i].p); + mbedtls_mpi_lset(&g, cases[i].g); + char what[96]; + int codes = sd_check_params(&p, &g); + snprintf(what, sizeof what, "check(0x%s, %d) == %d (got %d)", cases[i].p, cases[i].g, cases[i].codes, codes); + check(codes == cases[i].codes, what); + } + mbedtls_mpi_read_binary(&p, sd_groups[1].p, sd_groups[1].p_len); + mbedtls_mpi_lset(&g, 2); + check(sd_check_params(&p, &g) == 0, "check(modp2, 2) == 0"); + mbedtls_mpi_sub_int(&g, &p, 1); + check(sd_check_params(&p, &g) == SD_NOT_SUITABLE_GENERATOR, "check(modp2, p - 1) == 8"); + mbedtls_mpi_lset(&g, 2); + mbedtls_mpi_add_int(&p, &p, 2); + check(sd_check_params(&p, &g) == SD_P_NOT_PRIME, "check(modp2 + 2, 2) == 1"); + mbedtls_mpi_free(&p); + mbedtls_mpi_free(&g); +} + +/* Exponents past 8192 bits, split into digits, against the exponent + * reduced modulo p - 1 (Fermat) for a prime p. */ +static void test_long_exponent(void) { + mbedtls_mpi p, p1, base, e, reduced, got, want; + mbedtls_mpi_init(&p); + mbedtls_mpi_init(&p1); + mbedtls_mpi_init(&base); + mbedtls_mpi_init(&e); + mbedtls_mpi_init(&reduced); + mbedtls_mpi_init(&got); + mbedtls_mpi_init(&want); + mbedtls_mpi_read_binary(&p, sd_groups[0].p, sd_groups[0].p_len); + mbedtls_mpi_sub_int(&p1, &p, 1); + mbedtls_mpi_lset(&base, 5); + static const size_t sizes[] = {8192, 8193, 16382, 16383, 20000}; + for (size_t i = 0; i < sizeof sizes / sizeof sizes[0]; i++) { + sd_random_bits(&e, sizes[i], false); + mbedtls_mpi_mod_mpi(&reduced, &e, &p1); + bool ok = sd_exp(&got, &base, &e, &p) && mbedtls_mpi_exp_mod(&want, &base, &reduced, &p, NULL) == 0; + char what[64]; + snprintf(what, sizeof what, "5^e mod p for a %zu-bit e", sizes[i]); + check(ok && mbedtls_mpi_cmp_mpi(&got, &want) == 0, what); + } + mbedtls_mpi_lset(&p, 24); + check(!sd_exp(&got, &base, &e, &p), "an even modulus fails"); + mbedtls_mpi_lset(&p, 1); + check(!sd_exp(&got, &base, &e, &p), "the modulus 1 fails"); + mbedtls_mpi_free(&p); + mbedtls_mpi_free(&p1); + mbedtls_mpi_free(&base); + mbedtls_mpi_free(&e); + mbedtls_mpi_free(&reduced); + mbedtls_mpi_free(&got); + mbedtls_mpi_free(&want); +} + +/* Generated safe primes have the requested length and congruence, and + * mbedTLS's own primality test accepts p and (p - 1) / 2. */ +static void test_generate(void) { + static const unsigned adds[] = {24, 60, 12}; + mbedtls_mpi p, q, g; + mbedtls_mpi_init(&p); + mbedtls_mpi_init(&q); + mbedtls_mpi_init(&g); + mbedtls_mpi_lset(&g, 2); + for (size_t i = 0; i < sizeof adds / sizeof adds[0]; i++) { + for (int trial = 0; trial < 2; trial++) { + bool ok = sd_generate_safe_prime(&p, 512, adds[i], adds[i] - 1, false); + mbedtls_mpi_uint r = 0; + ok = ok && mbedtls_mpi_bitlen(&p) == 512 && mbedtls_mpi_mod_int(&r, &p, adds[i]) == 0 && r == adds[i] - 1; + mbedtls_mpi_copy(&q, &p); + mbedtls_mpi_shift_r(&q, 1); + ok = ok && mbedtls_mpi_is_prime_ext(&p, 40, sd_random, NULL) == 0 && + mbedtls_mpi_is_prime_ext(&q, 40, sd_random, NULL) == 0; + char what[64]; + snprintf(what, sizeof what, "a 512-bit safe prime ≡ %u (mod %u)", adds[i] - 1, adds[i]); + check(ok, what); + check(sd_check_params(&p, &g) == 0, "a generated prime has no DH_check findings"); + } + } + mbedtls_mpi_free(&p); + mbedtls_mpi_free(&q); + mbedtls_mpi_free(&g); +} + +/* generatePrime's search: the sizes and add forms with one possible + * result, top-two-bit safe-prime starts, and checks above OpenSSL's + * round count. */ +static void test_generate_prime(void) { + static const struct { + size_t bits; + bool safe; + int add, rem; + int want; + } cases[] = { + {2, false, 0, 0, 3}, {3, false, 0, 0, 7}, {4, false, 0, 0, 13}, {3, true, 0, 0, 7}, + {6, true, 0, 0, 59}, {7, true, 0, 0, 107}, {8, false, 200, 1, 401}, {8, false, 128, 0, 257}, + {5, false, 16, 3, 19}, + }; + mbedtls_mpi p, add, rem, q; + mbedtls_mpi_init(&p); + mbedtls_mpi_init(&add); + mbedtls_mpi_init(&rem); + mbedtls_mpi_init(&q); + for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) { + mbedtls_mpi_lset(&add, cases[i].add); + mbedtls_mpi_lset(&rem, cases[i].rem); + bool ok = sd_generate_prime(&p, cases[i].bits, cases[i].safe, cases[i].add ? &add : NULL, + cases[i].rem ? &rem : NULL) && + mbedtls_mpi_cmp_int(&p, cases[i].want) == 0; + char what[96]; + snprintf(what, sizeof what, "generatePrime(%zu, safe %d, add %d, rem %d) is %d", cases[i].bits, cases[i].safe, + cases[i].add, cases[i].rem, cases[i].want); + check(ok, what); + } + for (int trial = 0; trial < 2; trial++) { + bool ok = sd_generate_safe_prime(&p, 128, 12, 11, true) && mbedtls_mpi_bitlen(&p) == 128 && + mbedtls_mpi_get_bit(&p, 126) == 1; + mbedtls_mpi_copy(&q, &p); + mbedtls_mpi_shift_r(&q, 1); + ok = ok && mbedtls_mpi_is_prime_ext(&p, 40, sd_random, NULL) == 0 && + mbedtls_mpi_is_prime_ext(&q, 40, sd_random, NULL) == 0; + check(ok, "a 128-bit safe prime with its top two bits set"); + } + ScDhSmallPrimes *small = sd_small_primes(); + mbedtls_mpi_read_string(&q, 10, "3215031751"); + check(!sd_is_prime_checks(small, &q, 200), "200 rounds reject a strong pseudoprime to 2, 3, 5 and 7"); + mbedtls_mpi_read_string(&q, 10, "2305843009213693951"); + check(sd_is_prime_checks(small, &q, 200), "200 rounds accept 2^61 - 1"); + free(small); + mbedtls_mpi_free(&p); + mbedtls_mpi_free(&add); + mbedtls_mpi_free(&rem); + mbedtls_mpi_free(&q); +} + +int main(void) { + test_mont_pow(); + test_is_prime(); + test_check_params(); + test_long_exponent(); + test_generate(); + test_generate_prime(); + fprintf(stderr, "%ld/%ld cases passed\n", total - failed, total); + return failed ? 1 : 0; +} diff --git a/packages/runtime/test/test_map.c b/packages/runtime/test/test_map.c index 32bdb7be1..46805da1e 100644 --- a/packages/runtime/test/test_map.c +++ b/packages/runtime/test/test_map.c @@ -826,11 +826,96 @@ static void test_absent_key_filter(void) { for (int i = 0; i < UNIVERSE; i++) scr_str_release(names[i]); } +/* SCR_MAP_VAL_CREF: string keys with compact class values in 16-byte + * entries (a 32-bit hash, the value as an address over 8). The values here + * are stand-in addresses, never dereferenced. */ +static uint64_t cref_val(size_t i) { return (uint64_t)(i + 1) * 8; } + +static void test_compact_values(void) { + ScrMap *m = scr_map_new(SCR_MAP_KEY_STR, SCR_MAP_VAL_CREF, NULL); + enum { N = 2000 }; + char buf[32]; + ScrStr *keys[N]; + for (size_t i = 0; i < N; i++) { + snprintf(buf, sizeof buf, "k%zu", i); + keys[i] = S(buf); + scr_map_set_str_ref(m, keys[i], (void *)(uintptr_t)cref_val(i)); + } + check(scr_map_size(m) == N, "cref: size after inserts"); + bool all = true; + for (size_t i = 0; i < N; i++) { + all &= scr_map_get_str_ref(m, keys[i]) == (void *)(uintptr_t)cref_val(i); + const ScrMapCEntry *e = scr_map_entry_str_c(m, keys[i]); + all &= e && ((uint64_t)e->val << 3) == cref_val(i) && e->key == (uint64_t)(uintptr_t)keys[i]; + } + check(all, "cref: get and entry_str_c find every value"); + ScrStr *missing = S("absent"); + check(!scr_map_get_str_ref(m, missing) && !scr_map_entry_str_c(m, missing), "cref: absent key"); + check(scr_map_get_span_ref(m, "k7", 2) == (void *)(uintptr_t)cref_val(7), "cref: span lookup"); + /* A key object other than the stored one, equal bytes. */ + ScrStr *again = S("k42"); + check(scr_map_entry_str_c(m, again) && scr_map_get_str_ref(m, again) == (void *)(uintptr_t)cref_val(42), + "cref: equal key bytes, other object"); + scr_str_release(again); + for (size_t i = 0; i < N; i += 2) scr_map_set_str_ref(m, keys[i], (void *)(uintptr_t)cref_val(i + N)); + all = true; + for (size_t i = 0; i < N; i++) + all &= scr_map_get_str_ref(m, keys[i]) == (void *)(uintptr_t)cref_val(i % 2 ? i : i + N); + check(all && scr_map_size(m) == N, "cref: overwrite keeps the entry"); + for (size_t i = 0; i < N; i++) + if (i % 4) scr_map_delete_str(m, keys[i]); + check(scr_map_size(m) == N / 4, "cref: deletes"); + all = true; + for (size_t i = 0; i < N; i++) { + bool want = i % 4 == 0; + all &= scr_map_has_str(m, keys[i]) == want; + if (want) all &= scr_map_get_str_ref(m, keys[i]) == (void *)(uintptr_t)cref_val(i + N); + } + check(all, "cref: lookups after compaction"); + /* Iteration order and values. */ + size_t seen = 0; + all = true; + scr_map_iter_enter(m); + for (double i = scr_map_iter_start(m); i < scr_map_iter_count(m); i = scr_map_iter_skip(m, i + 1)) { + ScrStr *k = scr_map_iter_key_str(m, i); + void *v = scr_map_iter_val_ref(m, i); + size_t want = seen * 4; + all &= k->len == keys[want]->len && memcmp(k->data, keys[want]->data, k->len) == 0; + all &= v == (void *)(uintptr_t)cref_val(want + N); + scr_str_release(k); + seen++; + } + scr_map_iter_exit(m); + check(all && seen == N / 4, "cref: iteration order and values"); + /* Copies keep the layout; a key-only copy takes the 24-byte one. */ + ScrMap *copy = scr_map_clone(m, false, NULL); + ScrMap *set = scr_map_clone(m, true, NULL); + all = scr_map_size(copy) == N / 4 && scr_map_size(set) == N / 4; + for (size_t i = 0; i < N; i += 4) { + all &= scr_map_get_str_ref(copy, keys[i]) == (void *)(uintptr_t)cref_val(i + N); + all &= scr_map_has_str(set, keys[i]); + } + all &= !scr_map_has_str(set, keys[1]); + check(all, "cref: clone and key-only clone"); + scr_map_set_str_ref(copy, keys[1], (void *)(uintptr_t)cref_val(1)); + check(!scr_map_has_str(m, keys[1]) && scr_map_size(copy) == N / 4 + 1, "cref: copies are independent"); + scr_map_clear(m); + check(scr_map_size(m) == 0 && !scr_map_has_str(m, keys[0]), "cref: clear"); + scr_map_set_str_ref(m, keys[3], (void *)(uintptr_t)cref_val(3)); + check(scr_map_get_str_ref(m, keys[3]) == (void *)(uintptr_t)cref_val(3), "cref: reuse after clear"); + scr_map_release(copy); + scr_map_release(set); + scr_map_release(m); + scr_str_release(missing); + for (size_t i = 0; i < N; i++) scr_str_release(keys[i]); +} + int main(void) { test_key_bytes(); test_string_bucket_collisions(); test_string_keys(); test_string_entries(); + test_compact_values(); test_same_value_zero(); test_span_keys(); test_scratch_keys(); diff --git a/packages/runtime/vendor/README.md b/packages/runtime/vendor/README.md index 977179609..7ab8cf6b0 100644 --- a/packages/runtime/vendor/README.md +++ b/packages/runtime/vendor/README.md @@ -48,3 +48,15 @@ The objects build lazily on the first zlib-using cross compile into the per-user The TLS provider behind node:tls/node:https (see the design note atop packages/runtime/src/scr_tls.c for why mbedTLS over SecureTransport/BoringSSL/libtls). Only `include/` and `library/` are vendored (LICENSE beside them) — tests, docs, programs, scripts, and CMake machinery are not. No vendored file is modified and no custom config is applied (the stock `mbedtls_config.h` builds every `library/*.c` standalone with clang); to update, re-fetch the release tarball, copy the same two directories, and bump `MBEDTLS_VERSION` in packages/compiler/src/backend/vendor-archives.ts. The archive (libmbedtls.a) is prebuilt best-effort during npm installation (or explicitly by `scriptc cache warm`) and otherwise built lazily on the first TLS-using compile. It lives under the per-user build cache's `vendor/mbedtls----/` directory — one flavor per lane (plain, asan), native platform/architecture or explicit cross target, and compiler environment/identity, the libqjs.a pattern. TLS-free binaries never compile or link any of this. + +## libsodium/ + +- Project: https://github.com/jedisct1/libsodium +- Version: 1.0.20 (release tarball libsodium-1.0.20.tar.gz, sha256 ebb65ef6ca439333c2bb41a0c1990587288da07f6c7fd07cb3a18cc18d30ce19) +- License: ISC (see libsodium/LICENSE) + +The Ed25519 arithmetic behind node:crypto and WebCrypto Ed25519 keys (see packages/runtime/src/scr_ed25519.c). Its verification matches Node 24: it rejects a non-canonical S and the small-order R and public-key encodings, then checks the cofactorless equation. Only the ref10 Ed25519 subset is vendored, flat in one directory: `crypto_core/ed25519/ref10/ed25519_ref10.c` with its `fe_25_5/` headers, `crypto_sign/ed25519/ref10/{sign,open,keypair}.c` and `sign_ed25519_ref10.h`, `crypto_hash/sha512/cp/hash_sha512_cp.c`, `crypto_verify/verify.c`, and the public and private headers they include. The 64-bit `fe_51` field code (used only with `HAVE_TI_MODE`) and the rest of the library are not vendored. + +The only modification to upstream files: `#include "private/x.h"` flattened to `#include "x.h"` in ed25519_ref10.c, sign.c, open.c, keypair.c, hash_sha512_cp.c and ed25519_ref10_fe_25_5.h, so the directory is self-contained. scr_ed25519.c textually includes the .c files and supplies `sodium_memzero`, `sodium_memcmp`, `sodium_is_zero` and `randombytes_buf` (from `arc4random_buf`) in place of libsodium's utils.c and randombytes.c. To update, re-fetch the release tarball, copy the same files, and re-apply that include flattening. + +The unit compiles only into programs that use asymmetric keys and name Ed25519 in a string literal (the `ed25519` runtime feature); other binaries never compile or link any of this. diff --git a/packages/runtime/vendor/libsodium/LICENSE b/packages/runtime/vendor/libsodium/LICENSE new file mode 100644 index 000000000..6bce7f058 --- /dev/null +++ b/packages/runtime/vendor/libsodium/LICENSE @@ -0,0 +1,18 @@ +/* + * ISC License + * + * Copyright (c) 2013-2024 + * Frank Denis + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/packages/runtime/vendor/libsodium/README.md b/packages/runtime/vendor/libsodium/README.md new file mode 100644 index 000000000..5207d8ad6 --- /dev/null +++ b/packages/runtime/vendor/libsodium/README.md @@ -0,0 +1,7 @@ +# libsodium 1.0.20 (Ed25519 subset) + +- Source: https://download.libsodium.org/libsodium/releases/libsodium-1.0.20.tar.gz (the same tarball as the GitHub release 1.0.20-RELEASE) +- sha256: ebb65ef6ca439333c2bb41a0c1990587288da07f6c7fd07cb3a18cc18d30ce19 +- License: ISC, see LICENSE + +See ../README.md for the files vendored, the one modification, and how to update. diff --git a/packages/runtime/vendor/libsodium/common.h b/packages/runtime/vendor/libsodium/common.h new file mode 100644 index 000000000..63f0d2b2d --- /dev/null +++ b/packages/runtime/vendor/libsodium/common.h @@ -0,0 +1,285 @@ +#ifndef common_H +#define common_H 1 + +#if !defined(_MSC_VER) && !defined(DEV_MODE) && 0 +# warning *** This is unstable, untested, development code. +# warning It might not compile. It might not work as expected. +# warning It might be totally insecure. +# warning Do not use this except if you are planning to contribute code. +# warning Use releases available at https://download.libsodium.org/libsodium/releases/ instead. +# warning Alternatively, use the "stable" branch in the git repository. +#endif + +#if !defined(_MSC_VER) && (!defined(CONFIGURED) || CONFIGURED != 1) +# warning *** The library is being compiled using an undocumented method. +# warning This is not supported. It has not been tested, it might not +# warning work as expected, and performance is likely to be suboptimal. +#endif + +#include +#include +#include + +#define COMPILER_ASSERT(X) (void) sizeof(char[(X) ? 1 : -1]) + +#ifdef HAVE_TI_MODE +# if defined(__SIZEOF_INT128__) +typedef unsigned __int128 uint128_t; +# else +typedef unsigned uint128_t __attribute__((mode(TI))); +# endif +#endif + +#define ROTL32(X, B) rotl32((X), (B)) +static inline uint32_t +rotl32(const uint32_t x, const int b) +{ + return (x << b) | (x >> (32 - b)); +} + +#define ROTL64(X, B) rotl64((X), (B)) +static inline uint64_t +rotl64(const uint64_t x, const int b) +{ + return (x << b) | (x >> (64 - b)); +} + +#define ROTR32(X, B) rotr32((X), (B)) +static inline uint32_t +rotr32(const uint32_t x, const int b) +{ + return (x >> b) | (x << (32 - b)); +} + +#define ROTR64(X, B) rotr64((X), (B)) +static inline uint64_t +rotr64(const uint64_t x, const int b) +{ + return (x >> b) | (x << (64 - b)); +} + +#define LOAD64_LE(SRC) load64_le(SRC) +static inline uint64_t +load64_le(const uint8_t src[8]) +{ +#ifdef NATIVE_LITTLE_ENDIAN + uint64_t w; + memcpy(&w, src, sizeof w); + return w; +#else + uint64_t w = (uint64_t) src[0]; + w |= (uint64_t) src[1] << 8; + w |= (uint64_t) src[2] << 16; + w |= (uint64_t) src[3] << 24; + w |= (uint64_t) src[4] << 32; + w |= (uint64_t) src[5] << 40; + w |= (uint64_t) src[6] << 48; + w |= (uint64_t) src[7] << 56; + return w; +#endif +} + +#define STORE64_LE(DST, W) store64_le((DST), (W)) +static inline void +store64_le(uint8_t dst[8], uint64_t w) +{ +#ifdef NATIVE_LITTLE_ENDIAN + memcpy(dst, &w, sizeof w); +#else + dst[0] = (uint8_t) w; w >>= 8; + dst[1] = (uint8_t) w; w >>= 8; + dst[2] = (uint8_t) w; w >>= 8; + dst[3] = (uint8_t) w; w >>= 8; + dst[4] = (uint8_t) w; w >>= 8; + dst[5] = (uint8_t) w; w >>= 8; + dst[6] = (uint8_t) w; w >>= 8; + dst[7] = (uint8_t) w; +#endif +} + +#define LOAD32_LE(SRC) load32_le(SRC) +static inline uint32_t +load32_le(const uint8_t src[4]) +{ +#ifdef NATIVE_LITTLE_ENDIAN + uint32_t w; + memcpy(&w, src, sizeof w); + return w; +#else + uint32_t w = (uint32_t) src[0]; + w |= (uint32_t) src[1] << 8; + w |= (uint32_t) src[2] << 16; + w |= (uint32_t) src[3] << 24; + return w; +#endif +} + +#define STORE32_LE(DST, W) store32_le((DST), (W)) +static inline void +store32_le(uint8_t dst[4], uint32_t w) +{ +#ifdef NATIVE_LITTLE_ENDIAN + memcpy(dst, &w, sizeof w); +#else + dst[0] = (uint8_t) w; w >>= 8; + dst[1] = (uint8_t) w; w >>= 8; + dst[2] = (uint8_t) w; w >>= 8; + dst[3] = (uint8_t) w; +#endif +} + +/* ----- */ + +#define LOAD64_BE(SRC) load64_be(SRC) +static inline uint64_t +load64_be(const uint8_t src[8]) +{ +#ifdef NATIVE_BIG_ENDIAN + uint64_t w; + memcpy(&w, src, sizeof w); + return w; +#else + uint64_t w = (uint64_t) src[7]; + w |= (uint64_t) src[6] << 8; + w |= (uint64_t) src[5] << 16; + w |= (uint64_t) src[4] << 24; + w |= (uint64_t) src[3] << 32; + w |= (uint64_t) src[2] << 40; + w |= (uint64_t) src[1] << 48; + w |= (uint64_t) src[0] << 56; + return w; +#endif +} + +#define STORE64_BE(DST, W) store64_be((DST), (W)) +static inline void +store64_be(uint8_t dst[8], uint64_t w) +{ +#ifdef NATIVE_BIG_ENDIAN + memcpy(dst, &w, sizeof w); +#else + dst[7] = (uint8_t) w; w >>= 8; + dst[6] = (uint8_t) w; w >>= 8; + dst[5] = (uint8_t) w; w >>= 8; + dst[4] = (uint8_t) w; w >>= 8; + dst[3] = (uint8_t) w; w >>= 8; + dst[2] = (uint8_t) w; w >>= 8; + dst[1] = (uint8_t) w; w >>= 8; + dst[0] = (uint8_t) w; +#endif +} + +#define LOAD32_BE(SRC) load32_be(SRC) +static inline uint32_t +load32_be(const uint8_t src[4]) +{ +#ifdef NATIVE_BIG_ENDIAN + uint32_t w; + memcpy(&w, src, sizeof w); + return w; +#else + uint32_t w = (uint32_t) src[3]; + w |= (uint32_t) src[2] << 8; + w |= (uint32_t) src[1] << 16; + w |= (uint32_t) src[0] << 24; + return w; +#endif +} + +#define STORE32_BE(DST, W) store32_be((DST), (W)) +static inline void +store32_be(uint8_t dst[4], uint32_t w) +{ +#ifdef NATIVE_BIG_ENDIAN + memcpy(dst, &w, sizeof w); +#else + dst[3] = (uint8_t) w; w >>= 8; + dst[2] = (uint8_t) w; w >>= 8; + dst[1] = (uint8_t) w; w >>= 8; + dst[0] = (uint8_t) w; +#endif +} + +#define XOR_BUF(OUT, IN, N) xor_buf((OUT), (IN), (N)) +static inline void +xor_buf(unsigned char *out, const unsigned char *in, size_t n) +{ + size_t i; + + for (i = 0; i < n; i++) { + out[i] ^= in[i]; + } +} + +#if !defined(__clang__) && !defined(__GNUC__) +# ifdef __attribute__ +# undef __attribute__ +# endif +# define __attribute__(a) +#endif + +#ifndef CRYPTO_ALIGN +# if defined(__INTEL_COMPILER) || defined(_MSC_VER) +# define CRYPTO_ALIGN(x) __declspec(align(x)) +# else +# define CRYPTO_ALIGN(x) __attribute__ ((aligned(x))) +# endif +#endif + +#ifdef _MSC_VER + +# if defined(_M_X64) || defined(_M_IX86) +# include + +# define HAVE_INTRIN_H 1 +# define HAVE_MMINTRIN_H 1 +# define HAVE_EMMINTRIN_H 1 +# define HAVE_PMMINTRIN_H 1 +# define HAVE_TMMINTRIN_H 1 +# define HAVE_SMMINTRIN_H 1 +# define HAVE_AVXINTRIN_H 1 +# if _MSC_VER >= 1600 +# define HAVE_WMMINTRIN_H 1 +# endif +# if _MSC_VER >= 1700 && defined(_M_X64) +# define HAVE_AVX2INTRIN_H 1 +# endif +# if _MSC_VER >= 1910 && defined(_M_X64) +# define HAVE_AVX512FINTRIN_H 1 +# endif + +# elif defined(_M_ARM64) + +# ifndef __ARM_ARCH +# define __ARM_ARCH 1 +# endif +# ifndef __ARM_NEON +# define __ARM_NEON 1 +# endif +# define HAVE_ARMCRYPTO 1 + +# endif /* _MSC_VER */ + +#elif defined(HAVE_INTRIN_H) +# include +#endif + +#ifdef HAVE_LIBCTGRIND +extern void ct_poison (const void *, size_t); +extern void ct_unpoison(const void *, size_t); +# define POISON(X, L) ct_poison((X), (L)) +# define UNPOISON(X, L) ct_unpoison((X), (L)) +#else +# define POISON(X, L) (void) 0 +# define UNPOISON(X, L) (void) 0 +#endif + +#ifdef HAVE_GCC_MEMORY_FENCES +# define ACQUIRE_FENCE __atomic_thread_fence(__ATOMIC_ACQUIRE) +#elif defined(HAVE_C11_MEMORY_FENCES) +# define ACQUIRE_FENCE atomic_thread_fence(memory_order_acquire) +#else +# define ACQUIRE_FENCE (void) 0 +#endif + +#endif diff --git a/packages/runtime/vendor/libsodium/crypto_hash_sha512.h b/packages/runtime/vendor/libsodium/crypto_hash_sha512.h new file mode 100644 index 000000000..5b690fb25 --- /dev/null +++ b/packages/runtime/vendor/libsodium/crypto_hash_sha512.h @@ -0,0 +1,60 @@ +#ifndef crypto_hash_sha512_H +#define crypto_hash_sha512_H + +/* + * WARNING: Unless you absolutely need to use SHA512 for interoperability, + * purposes, you might want to consider crypto_generichash() instead. + * Unlike SHA512, crypto_generichash() is not vulnerable to length + * extension attacks. + */ + +#include +#include +#include + +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +typedef struct crypto_hash_sha512_state { + uint64_t state[8]; + uint64_t count[2]; + uint8_t buf[128]; +} crypto_hash_sha512_state; + +SODIUM_EXPORT +size_t crypto_hash_sha512_statebytes(void); + +#define crypto_hash_sha512_BYTES 64U +SODIUM_EXPORT +size_t crypto_hash_sha512_bytes(void); + +SODIUM_EXPORT +int crypto_hash_sha512(unsigned char *out, const unsigned char *in, + unsigned long long inlen) __attribute__ ((nonnull(1))); + +SODIUM_EXPORT +int crypto_hash_sha512_init(crypto_hash_sha512_state *state) + __attribute__ ((nonnull)); + +SODIUM_EXPORT +int crypto_hash_sha512_update(crypto_hash_sha512_state *state, + const unsigned char *in, + unsigned long long inlen) + __attribute__ ((nonnull(1))); + +SODIUM_EXPORT +int crypto_hash_sha512_final(crypto_hash_sha512_state *state, + unsigned char *out) + __attribute__ ((nonnull)); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/packages/runtime/vendor/libsodium/crypto_scalarmult_curve25519.h b/packages/runtime/vendor/libsodium/crypto_scalarmult_curve25519.h new file mode 100644 index 000000000..60e9d0c5a --- /dev/null +++ b/packages/runtime/vendor/libsodium/crypto_scalarmult_curve25519.h @@ -0,0 +1,42 @@ +#ifndef crypto_scalarmult_curve25519_H +#define crypto_scalarmult_curve25519_H + +#include + +#include "export.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define crypto_scalarmult_curve25519_BYTES 32U +SODIUM_EXPORT +size_t crypto_scalarmult_curve25519_bytes(void); + +#define crypto_scalarmult_curve25519_SCALARBYTES 32U +SODIUM_EXPORT +size_t crypto_scalarmult_curve25519_scalarbytes(void); + +/* + * NOTE: Do not use the result of this function directly for key exchange. + * + * Hash the result with the public keys in order to compute a shared + * secret key: H(q || client_pk || server_pk) + * + * Or unless this is not an option, use the crypto_kx() API instead. + */ +SODIUM_EXPORT +int crypto_scalarmult_curve25519(unsigned char *q, const unsigned char *n, + const unsigned char *p) + __attribute__ ((warn_unused_result)) __attribute__ ((nonnull)); + +SODIUM_EXPORT +int crypto_scalarmult_curve25519_base(unsigned char *q, + const unsigned char *n) + __attribute__ ((nonnull)); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/packages/runtime/vendor/libsodium/crypto_sign_ed25519.h b/packages/runtime/vendor/libsodium/crypto_sign_ed25519.h new file mode 100644 index 000000000..0fdac42d3 --- /dev/null +++ b/packages/runtime/vendor/libsodium/crypto_sign_ed25519.h @@ -0,0 +1,124 @@ +#ifndef crypto_sign_ed25519_H +#define crypto_sign_ed25519_H + +#include +#include "crypto_hash_sha512.h" +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +typedef struct crypto_sign_ed25519ph_state { + crypto_hash_sha512_state hs; +} crypto_sign_ed25519ph_state; + +SODIUM_EXPORT +size_t crypto_sign_ed25519ph_statebytes(void); + +#define crypto_sign_ed25519_BYTES 64U +SODIUM_EXPORT +size_t crypto_sign_ed25519_bytes(void); + +#define crypto_sign_ed25519_SEEDBYTES 32U +SODIUM_EXPORT +size_t crypto_sign_ed25519_seedbytes(void); + +#define crypto_sign_ed25519_PUBLICKEYBYTES 32U +SODIUM_EXPORT +size_t crypto_sign_ed25519_publickeybytes(void); + +#define crypto_sign_ed25519_SECRETKEYBYTES (32U + 32U) +SODIUM_EXPORT +size_t crypto_sign_ed25519_secretkeybytes(void); + +#define crypto_sign_ed25519_MESSAGEBYTES_MAX (SODIUM_SIZE_MAX - crypto_sign_ed25519_BYTES) +SODIUM_EXPORT +size_t crypto_sign_ed25519_messagebytes_max(void); + +SODIUM_EXPORT +int crypto_sign_ed25519(unsigned char *sm, unsigned long long *smlen_p, + const unsigned char *m, unsigned long long mlen, + const unsigned char *sk) + __attribute__ ((nonnull(1, 5))); + +SODIUM_EXPORT +int crypto_sign_ed25519_open(unsigned char *m, unsigned long long *mlen_p, + const unsigned char *sm, unsigned long long smlen, + const unsigned char *pk) + __attribute__ ((warn_unused_result)) __attribute__ ((nonnull(3, 5))); + +SODIUM_EXPORT +int crypto_sign_ed25519_detached(unsigned char *sig, + unsigned long long *siglen_p, + const unsigned char *m, + unsigned long long mlen, + const unsigned char *sk) + __attribute__ ((nonnull(1, 5))); + +SODIUM_EXPORT +int crypto_sign_ed25519_verify_detached(const unsigned char *sig, + const unsigned char *m, + unsigned long long mlen, + const unsigned char *pk) + __attribute__ ((warn_unused_result)) __attribute__ ((nonnull(1, 4))); + +SODIUM_EXPORT +int crypto_sign_ed25519_keypair(unsigned char *pk, unsigned char *sk) + __attribute__ ((nonnull)); + +SODIUM_EXPORT +int crypto_sign_ed25519_seed_keypair(unsigned char *pk, unsigned char *sk, + const unsigned char *seed) + __attribute__ ((nonnull)); + +SODIUM_EXPORT +int crypto_sign_ed25519_pk_to_curve25519(unsigned char *curve25519_pk, + const unsigned char *ed25519_pk) + __attribute__ ((warn_unused_result)) __attribute__ ((nonnull)); + +SODIUM_EXPORT +int crypto_sign_ed25519_sk_to_curve25519(unsigned char *curve25519_sk, + const unsigned char *ed25519_sk) + __attribute__ ((nonnull)); + +SODIUM_EXPORT +int crypto_sign_ed25519_sk_to_seed(unsigned char *seed, + const unsigned char *sk) + __attribute__ ((nonnull)); + +SODIUM_EXPORT +int crypto_sign_ed25519_sk_to_pk(unsigned char *pk, const unsigned char *sk) + __attribute__ ((nonnull)); + +SODIUM_EXPORT +int crypto_sign_ed25519ph_init(crypto_sign_ed25519ph_state *state) + __attribute__ ((nonnull)); + +SODIUM_EXPORT +int crypto_sign_ed25519ph_update(crypto_sign_ed25519ph_state *state, + const unsigned char *m, + unsigned long long mlen) + __attribute__ ((nonnull(1))); + +SODIUM_EXPORT +int crypto_sign_ed25519ph_final_create(crypto_sign_ed25519ph_state *state, + unsigned char *sig, + unsigned long long *siglen_p, + const unsigned char *sk) + __attribute__ ((nonnull(1, 2, 4))); + +SODIUM_EXPORT +int crypto_sign_ed25519ph_final_verify(crypto_sign_ed25519ph_state *state, + const unsigned char *sig, + const unsigned char *pk) + __attribute__ ((warn_unused_result)) __attribute__ ((nonnull)); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/packages/runtime/vendor/libsodium/crypto_verify_16.h b/packages/runtime/vendor/libsodium/crypto_verify_16.h new file mode 100644 index 000000000..7b9c8077a --- /dev/null +++ b/packages/runtime/vendor/libsodium/crypto_verify_16.h @@ -0,0 +1,23 @@ +#ifndef crypto_verify_16_H +#define crypto_verify_16_H + +#include +#include "export.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define crypto_verify_16_BYTES 16U +SODIUM_EXPORT +size_t crypto_verify_16_bytes(void); + +SODIUM_EXPORT +int crypto_verify_16(const unsigned char *x, const unsigned char *y) + __attribute__ ((warn_unused_result)) __attribute__ ((nonnull)); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/packages/runtime/vendor/libsodium/crypto_verify_32.h b/packages/runtime/vendor/libsodium/crypto_verify_32.h new file mode 100644 index 000000000..9b0f4529f --- /dev/null +++ b/packages/runtime/vendor/libsodium/crypto_verify_32.h @@ -0,0 +1,23 @@ +#ifndef crypto_verify_32_H +#define crypto_verify_32_H + +#include +#include "export.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define crypto_verify_32_BYTES 32U +SODIUM_EXPORT +size_t crypto_verify_32_bytes(void); + +SODIUM_EXPORT +int crypto_verify_32(const unsigned char *x, const unsigned char *y) + __attribute__ ((warn_unused_result)) __attribute__ ((nonnull)); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/packages/runtime/vendor/libsodium/crypto_verify_64.h b/packages/runtime/vendor/libsodium/crypto_verify_64.h new file mode 100644 index 000000000..c83b73025 --- /dev/null +++ b/packages/runtime/vendor/libsodium/crypto_verify_64.h @@ -0,0 +1,23 @@ +#ifndef crypto_verify_64_H +#define crypto_verify_64_H + +#include +#include "export.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define crypto_verify_64_BYTES 64U +SODIUM_EXPORT +size_t crypto_verify_64_bytes(void); + +SODIUM_EXPORT +int crypto_verify_64(const unsigned char *x, const unsigned char *y) + __attribute__ ((warn_unused_result)) __attribute__ ((nonnull)); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/packages/runtime/vendor/libsodium/ed25519_ref10.c b/packages/runtime/vendor/libsodium/ed25519_ref10.c new file mode 100644 index 000000000..ac7a41492 --- /dev/null +++ b/packages/runtime/vendor/libsodium/ed25519_ref10.c @@ -0,0 +1,2858 @@ +#include +#include +#include +#include + +#include "crypto_verify_32.h" +#include "common.h" +#include "ed25519_ref10.h" +#include "utils.h" + +static inline uint64_t +load_3(const unsigned char *in) +{ + uint64_t result; + + result = (uint64_t) in[0]; + result |= ((uint64_t) in[1]) << 8; + result |= ((uint64_t) in[2]) << 16; + + return result; +} + +static inline uint64_t +load_4(const unsigned char *in) +{ + uint64_t result; + + result = (uint64_t) in[0]; + result |= ((uint64_t) in[1]) << 8; + result |= ((uint64_t) in[2]) << 16; + result |= ((uint64_t) in[3]) << 24; + + return result; +} + +/* + * Field arithmetic: + * Use 5*51 bit limbs on 64-bit systems with support for 128 bit arithmetic, + * and 10*25.5 bit limbs elsewhere. + * + * Functions used elsewhere that are candidates for inlining are defined + * via "private/curve25519_ref10.h". + */ + +#ifdef HAVE_TI_MODE +# include "fe_51/constants.h" +# include "fe_51/fe.h" +#else +# include "fe_25_5/constants.h" +# include "fe_25_5/fe.h" +#endif + +void +fe25519_invert(fe25519 out, const fe25519 z) +{ + fe25519 t0; + fe25519 t1; + fe25519 t2; + fe25519 t3; + int i; + + fe25519_sq(t0, z); + fe25519_sq(t1, t0); + fe25519_sq(t1, t1); + fe25519_mul(t1, z, t1); + fe25519_mul(t0, t0, t1); + fe25519_sq(t2, t0); + fe25519_mul(t1, t1, t2); + fe25519_sq(t2, t1); + for (i = 1; i < 5; ++i) { + fe25519_sq(t2, t2); + } + fe25519_mul(t1, t2, t1); + fe25519_sq(t2, t1); + for (i = 1; i < 10; ++i) { + fe25519_sq(t2, t2); + } + fe25519_mul(t2, t2, t1); + fe25519_sq(t3, t2); + for (i = 1; i < 20; ++i) { + fe25519_sq(t3, t3); + } + fe25519_mul(t2, t3, t2); + for (i = 1; i < 11; ++i) { + fe25519_sq(t2, t2); + } + fe25519_mul(t1, t2, t1); + fe25519_sq(t2, t1); + for (i = 1; i < 50; ++i) { + fe25519_sq(t2, t2); + } + fe25519_mul(t2, t2, t1); + fe25519_sq(t3, t2); + for (i = 1; i < 100; ++i) { + fe25519_sq(t3, t3); + } + fe25519_mul(t2, t3, t2); + for (i = 1; i < 51; ++i) { + fe25519_sq(t2, t2); + } + fe25519_mul(t1, t2, t1); + for (i = 1; i < 6; ++i) { + fe25519_sq(t1, t1); + } + fe25519_mul(out, t1, t0); +} + +static void +fe25519_pow22523(fe25519 out, const fe25519 z) +{ + fe25519 t0; + fe25519 t1; + fe25519 t2; + int i; + + fe25519_sq(t0, z); + fe25519_sq(t1, t0); + fe25519_sq(t1, t1); + fe25519_mul(t1, z, t1); + fe25519_mul(t0, t0, t1); + fe25519_sq(t0, t0); + fe25519_mul(t0, t1, t0); + fe25519_sq(t1, t0); + for (i = 1; i < 5; ++i) { + fe25519_sq(t1, t1); + } + fe25519_mul(t0, t1, t0); + fe25519_sq(t1, t0); + for (i = 1; i < 10; ++i) { + fe25519_sq(t1, t1); + } + fe25519_mul(t1, t1, t0); + fe25519_sq(t2, t1); + for (i = 1; i < 20; ++i) { + fe25519_sq(t2, t2); + } + fe25519_mul(t1, t2, t1); + for (i = 1; i < 11; ++i) { + fe25519_sq(t1, t1); + } + fe25519_mul(t0, t1, t0); + fe25519_sq(t1, t0); + for (i = 1; i < 50; ++i) { + fe25519_sq(t1, t1); + } + fe25519_mul(t1, t1, t0); + fe25519_sq(t2, t1); + for (i = 1; i < 100; ++i) { + fe25519_sq(t2, t2); + } + fe25519_mul(t1, t2, t1); + for (i = 1; i < 51; ++i) { + fe25519_sq(t1, t1); + } + fe25519_mul(t0, t1, t0); + fe25519_sq(t0, t0); + fe25519_sq(t0, t0); + fe25519_mul(out, t0, z); +} + +static inline void +fe25519_cneg(fe25519 h, const fe25519 f, unsigned int b) +{ + fe25519 negf; + + fe25519_neg(negf, f); + fe25519_copy(h, f); + fe25519_cmov(h, negf, b); +} + +static inline void +fe25519_abs(fe25519 h, const fe25519 f) +{ + fe25519_cneg(h, f, fe25519_isnegative(f)); +} + +static inline void +fe25519_sqmul(fe25519 s, const int n, const fe25519 a) +{ + int i; + + for (i = 0; i < n; i++) { + fe25519_sq(s, s); + } + fe25519_mul(s, s, a); +} + +static unsigned int +fe25519_notsquare(const fe25519 x) +{ + fe25519 _10, _11, _1100, _1111, _11110000, _11111111; + fe25519 t, u, v; + unsigned char s[32]; + + /* Jacobi symbol - x^((p-1)/2) */ + fe25519_mul(_10, x, x); + fe25519_mul(_11, x, _10); + fe25519_sq(_1100, _11); + fe25519_sq(_1100, _1100); + fe25519_mul(_1111, _11, _1100); + fe25519_sq(_11110000, _1111); + fe25519_sq(_11110000, _11110000); + fe25519_sq(_11110000, _11110000); + fe25519_sq(_11110000, _11110000); + fe25519_mul(_11111111, _1111, _11110000); + fe25519_copy(t, _11111111); + fe25519_sqmul(t, 2, _11); + fe25519_copy(u, t); + fe25519_sqmul(t, 10, u); + fe25519_sqmul(t, 10, u); + fe25519_copy(v, t); + fe25519_sqmul(t, 30, v); + fe25519_copy(v, t); + fe25519_sqmul(t, 60, v); + fe25519_copy(v, t); + fe25519_sqmul(t, 120, v); + fe25519_sqmul(t, 10, u); + fe25519_sqmul(t, 3, _11); + fe25519_sq(t, t); + + fe25519_tobytes(s, t); + + return s[1] & 1; +} + +/* + r = p + q + */ + +void +ge25519_add(ge25519_p1p1 *r, const ge25519_p3 *p, const ge25519_cached *q) +{ + fe25519 t0; + + fe25519_add(r->X, p->Y, p->X); + fe25519_sub(r->Y, p->Y, p->X); + fe25519_mul(r->Z, r->X, q->YplusX); + fe25519_mul(r->Y, r->Y, q->YminusX); + fe25519_mul(r->T, q->T2d, p->T); + fe25519_mul(r->X, p->Z, q->Z); + fe25519_add(t0, r->X, r->X); + fe25519_sub(r->X, r->Z, r->Y); + fe25519_add(r->Y, r->Z, r->Y); + fe25519_add(r->Z, t0, r->T); + fe25519_sub(r->T, t0, r->T); +} + +static void +slide_vartime(signed char *r, const unsigned char *a) +{ + int i; + int b; + int k; + int ribs; + int cmp; + + for (i = 0; i < 256; ++i) { + r[i] = 1 & (a[i >> 3] >> (i & 7)); + } + for (i = 0; i < 256; ++i) { + if (! r[i]) { + continue; + } + for (b = 1; b <= 6 && i + b < 256; ++b) { + if (! r[i + b]) { + continue; + } + ribs = r[i + b] << b; + cmp = r[i] + ribs; + if (cmp <= 15) { + r[i] = cmp; + r[i + b] = 0; + } else { + cmp = r[i] - ribs; + if (cmp < -15) { + break; + } + r[i] = cmp; + for (k = i + b; k < 256; ++k) { + if (! r[k]) { + r[k] = 1; + break; + } + r[k] = 0; + } + } + } + } +} + +int +ge25519_frombytes(ge25519_p3 *h, const unsigned char *s) +{ + fe25519 u; + fe25519 v; + fe25519 vxx; + fe25519 m_root_check, p_root_check; + fe25519 negx; + fe25519 x_sqrtm1; + int has_m_root, has_p_root; + + fe25519_frombytes(h->Y, s); + fe25519_1(h->Z); + fe25519_sq(u, h->Y); + fe25519_mul(v, u, d); + fe25519_sub(u, u, h->Z); /* u = y^2-1 */ + fe25519_add(v, v, h->Z); /* v = dy^2+1 */ + + fe25519_mul(h->X, u, v); + fe25519_pow22523(h->X, h->X); + fe25519_mul(h->X, u, h->X); /* u((uv)^((q-5)/8)) */ + + fe25519_sq(vxx, h->X); + fe25519_mul(vxx, vxx, v); + fe25519_sub(m_root_check, vxx, u); /* vx^2-u */ + fe25519_add(p_root_check, vxx, u); /* vx^2+u */ + has_m_root = fe25519_iszero(m_root_check); + has_p_root = fe25519_iszero(p_root_check); + fe25519_mul(x_sqrtm1, h->X, sqrtm1); /* x*sqrt(-1) */ + fe25519_cmov(h->X, x_sqrtm1, 1 - has_m_root); + + fe25519_neg(negx, h->X); + fe25519_cmov(h->X, negx, fe25519_isnegative(h->X) ^ (s[31] >> 7)); + fe25519_mul(h->T, h->X, h->Y); + + return (has_m_root | has_p_root) - 1; +} + +int +ge25519_frombytes_negate_vartime(ge25519_p3 *h, const unsigned char *s) +{ + fe25519 u; + fe25519 v; + fe25519 v3; + fe25519 vxx; + fe25519 m_root_check, p_root_check; + + fe25519_frombytes(h->Y, s); + fe25519_1(h->Z); + fe25519_sq(u, h->Y); + fe25519_mul(v, u, d); + fe25519_sub(u, u, h->Z); /* u = y^2-1 */ + fe25519_add(v, v, h->Z); /* v = dy^2+1 */ + + fe25519_sq(v3, v); + fe25519_mul(v3, v3, v); /* v3 = v^3 */ + fe25519_sq(h->X, v3); + fe25519_mul(h->X, h->X, v); + fe25519_mul(h->X, h->X, u); /* x = uv^7 */ + + fe25519_pow22523(h->X, h->X); /* x = (uv^7)^((q-5)/8) */ + fe25519_mul(h->X, h->X, v3); + fe25519_mul(h->X, h->X, u); /* x = uv^3(uv^7)^((q-5)/8) */ + + fe25519_sq(vxx, h->X); + fe25519_mul(vxx, vxx, v); + fe25519_sub(m_root_check, vxx, u); /* vx^2-u */ + if (fe25519_iszero(m_root_check) == 0) { + fe25519_add(p_root_check, vxx, u); /* vx^2+u */ + if (fe25519_iszero(p_root_check) == 0) { + return -1; + } + fe25519_mul(h->X, h->X, sqrtm1); + } + + if (fe25519_isnegative(h->X) == (s[31] >> 7)) { + fe25519_neg(h->X, h->X); + } + fe25519_mul(h->T, h->X, h->Y); + + return 0; +} + +/* + r = p + q + */ + +static void +ge25519_madd(ge25519_p1p1 *r, const ge25519_p3 *p, const ge25519_precomp *q) +{ + fe25519 t0; + + fe25519_add(r->X, p->Y, p->X); + fe25519_sub(r->Y, p->Y, p->X); + fe25519_mul(r->Z, r->X, q->yplusx); + fe25519_mul(r->Y, r->Y, q->yminusx); + fe25519_mul(r->T, q->xy2d, p->T); + fe25519_add(t0, p->Z, p->Z); + fe25519_sub(r->X, r->Z, r->Y); + fe25519_add(r->Y, r->Z, r->Y); + fe25519_add(r->Z, t0, r->T); + fe25519_sub(r->T, t0, r->T); +} + +/* + r = p - q + */ + +static void +ge25519_msub(ge25519_p1p1 *r, const ge25519_p3 *p, const ge25519_precomp *q) +{ + fe25519 t0; + + fe25519_add(r->X, p->Y, p->X); + fe25519_sub(r->Y, p->Y, p->X); + fe25519_mul(r->Z, r->X, q->yminusx); + fe25519_mul(r->Y, r->Y, q->yplusx); + fe25519_mul(r->T, q->xy2d, p->T); + fe25519_add(t0, p->Z, p->Z); + fe25519_sub(r->X, r->Z, r->Y); + fe25519_add(r->Y, r->Z, r->Y); + fe25519_sub(r->Z, t0, r->T); + fe25519_add(r->T, t0, r->T); +} + +/* + r = p + */ + +void +ge25519_p1p1_to_p2(ge25519_p2 *r, const ge25519_p1p1 *p) +{ + fe25519_mul(r->X, p->X, p->T); + fe25519_mul(r->Y, p->Y, p->Z); + fe25519_mul(r->Z, p->Z, p->T); +} + +/* + r = p + */ + +void +ge25519_p1p1_to_p3(ge25519_p3 *r, const ge25519_p1p1 *p) +{ + fe25519_mul(r->X, p->X, p->T); + fe25519_mul(r->Y, p->Y, p->Z); + fe25519_mul(r->Z, p->Z, p->T); + fe25519_mul(r->T, p->X, p->Y); +} + +static void +ge25519_p2_0(ge25519_p2 *h) +{ + fe25519_0(h->X); + fe25519_1(h->Y); + fe25519_1(h->Z); +} + +/* + r = 2 * p + */ + +static void +ge25519_p2_dbl(ge25519_p1p1 *r, const ge25519_p2 *p) +{ + fe25519 t0; + + fe25519_sq(r->X, p->X); + fe25519_sq(r->Z, p->Y); + fe25519_sq2(r->T, p->Z); + fe25519_add(r->Y, p->X, p->Y); + fe25519_sq(t0, r->Y); + fe25519_add(r->Y, r->Z, r->X); + fe25519_sub(r->Z, r->Z, r->X); + fe25519_sub(r->X, t0, r->Y); + fe25519_sub(r->T, r->T, r->Z); +} + +static void +ge25519_p3_0(ge25519_p3 *h) +{ + fe25519_0(h->X); + fe25519_1(h->Y); + fe25519_1(h->Z); + fe25519_0(h->T); +} + +static void +ge25519_cached_0(ge25519_cached *h) +{ + fe25519_1(h->YplusX); + fe25519_1(h->YminusX); + fe25519_1(h->Z); + fe25519_0(h->T2d); +} + +/* + r = p + */ + +void +ge25519_p3_to_cached(ge25519_cached *r, const ge25519_p3 *p) +{ + fe25519_add(r->YplusX, p->Y, p->X); + fe25519_sub(r->YminusX, p->Y, p->X); + fe25519_copy(r->Z, p->Z); + fe25519_mul(r->T2d, p->T, d2); +} + +static void +ge25519_p3_to_precomp(ge25519_precomp *pi, const ge25519_p3 *p) +{ + fe25519 recip; + fe25519 x; + fe25519 y; + fe25519 xy; + + fe25519_invert(recip, p->Z); + fe25519_mul(x, p->X, recip); + fe25519_mul(y, p->Y, recip); + fe25519_add(pi->yplusx, y, x); + fe25519_sub(pi->yminusx, y, x); + fe25519_mul(xy, x, y); + fe25519_mul(pi->xy2d, xy, d2); +} + +/* + r = p + */ + +static void +ge25519_p3_to_p2(ge25519_p2 *r, const ge25519_p3 *p) +{ + fe25519_copy(r->X, p->X); + fe25519_copy(r->Y, p->Y); + fe25519_copy(r->Z, p->Z); +} + +void +ge25519_p3_tobytes(unsigned char *s, const ge25519_p3 *h) +{ + fe25519 recip; + fe25519 x; + fe25519 y; + + fe25519_invert(recip, h->Z); + fe25519_mul(x, h->X, recip); + fe25519_mul(y, h->Y, recip); + fe25519_tobytes(s, y); + s[31] ^= fe25519_isnegative(x) << 7; +} + +/* + r = 2 * p + */ + +static void +ge25519_p3_dbl(ge25519_p1p1 *r, const ge25519_p3 *p) +{ + ge25519_p2 q; + ge25519_p3_to_p2(&q, p); + ge25519_p2_dbl(r, &q); +} + +static void +ge25519_precomp_0(ge25519_precomp *h) +{ + fe25519_1(h->yplusx); + fe25519_1(h->yminusx); + fe25519_0(h->xy2d); +} + +static unsigned char +equal(signed char b, signed char c) +{ + unsigned char ub = b; + unsigned char uc = c; + unsigned char x = ub ^ uc; /* 0: yes; 1..255: no */ + uint32_t y = (uint32_t) x; /* 0: yes; 1..255: no */ + + y -= 1; /* 4294967295: yes; 0..254: no */ + y >>= 31; /* 1: yes; 0: no */ + + return y; +} + +static unsigned char +negative(signed char b) +{ + /* 18446744073709551361..18446744073709551615: yes; 0..255: no */ + uint64_t x = b; + + x >>= 63; /* 1: yes; 0: no */ + + return x; +} + +static void +ge25519_cmov(ge25519_precomp *t, const ge25519_precomp *u, unsigned char b) +{ + fe25519_cmov(t->yplusx, u->yplusx, b); + fe25519_cmov(t->yminusx, u->yminusx, b); + fe25519_cmov(t->xy2d, u->xy2d, b); +} + +static void +ge25519_cmov_cached(ge25519_cached *t, const ge25519_cached *u, unsigned char b) +{ + fe25519_cmov(t->YplusX, u->YplusX, b); + fe25519_cmov(t->YminusX, u->YminusX, b); + fe25519_cmov(t->Z, u->Z, b); + fe25519_cmov(t->T2d, u->T2d, b); +} + +static void +ge25519_cmov8(ge25519_precomp *t, const ge25519_precomp precomp[8], const signed char b) +{ + ge25519_precomp minust; + const unsigned char bnegative = negative(b); + const unsigned char babs = b - (((-bnegative) & b) * ((signed char) 1 << 1)); + + ge25519_precomp_0(t); + ge25519_cmov(t, &precomp[0], equal(babs, 1)); + ge25519_cmov(t, &precomp[1], equal(babs, 2)); + ge25519_cmov(t, &precomp[2], equal(babs, 3)); + ge25519_cmov(t, &precomp[3], equal(babs, 4)); + ge25519_cmov(t, &precomp[4], equal(babs, 5)); + ge25519_cmov(t, &precomp[5], equal(babs, 6)); + ge25519_cmov(t, &precomp[6], equal(babs, 7)); + ge25519_cmov(t, &precomp[7], equal(babs, 8)); + fe25519_copy(minust.yplusx, t->yminusx); + fe25519_copy(minust.yminusx, t->yplusx); + fe25519_neg(minust.xy2d, t->xy2d); + ge25519_cmov(t, &minust, bnegative); +} + +static void +ge25519_cmov8_base(ge25519_precomp *t, const int pos, const signed char b) +{ + static const ge25519_precomp base[32][8] = { /* base[i][j] = (j+1)*256^i*B */ +#ifdef HAVE_TI_MODE +# include "fe_51/base.h" +#else +# include "fe_25_5/base.h" +#endif + }; + ge25519_cmov8(t, base[pos], b); +} + +static void +ge25519_cmov8_cached(ge25519_cached *t, const ge25519_cached cached[8], const signed char b) +{ + ge25519_cached minust; + const unsigned char bnegative = negative(b); + const unsigned char babs = b - (((-bnegative) & b) * ((signed char) 1 << 1)); + + ge25519_cached_0(t); + ge25519_cmov_cached(t, &cached[0], equal(babs, 1)); + ge25519_cmov_cached(t, &cached[1], equal(babs, 2)); + ge25519_cmov_cached(t, &cached[2], equal(babs, 3)); + ge25519_cmov_cached(t, &cached[3], equal(babs, 4)); + ge25519_cmov_cached(t, &cached[4], equal(babs, 5)); + ge25519_cmov_cached(t, &cached[5], equal(babs, 6)); + ge25519_cmov_cached(t, &cached[6], equal(babs, 7)); + ge25519_cmov_cached(t, &cached[7], equal(babs, 8)); + fe25519_copy(minust.YplusX, t->YminusX); + fe25519_copy(minust.YminusX, t->YplusX); + fe25519_copy(minust.Z, t->Z); + fe25519_neg(minust.T2d, t->T2d); + ge25519_cmov_cached(t, &minust, bnegative); +} + +/* + r = p - q + */ + +void +ge25519_sub(ge25519_p1p1 *r, const ge25519_p3 *p, const ge25519_cached *q) +{ + fe25519 t0; + + fe25519_add(r->X, p->Y, p->X); + fe25519_sub(r->Y, p->Y, p->X); + fe25519_mul(r->Z, r->X, q->YminusX); + fe25519_mul(r->Y, r->Y, q->YplusX); + fe25519_mul(r->T, q->T2d, p->T); + fe25519_mul(r->X, p->Z, q->Z); + fe25519_add(t0, r->X, r->X); + fe25519_sub(r->X, r->Z, r->Y); + fe25519_add(r->Y, r->Z, r->Y); + fe25519_sub(r->Z, t0, r->T); + fe25519_add(r->T, t0, r->T); +} + +void +ge25519_tobytes(unsigned char *s, const ge25519_p2 *h) +{ + fe25519 recip; + fe25519 x; + fe25519 y; + + fe25519_invert(recip, h->Z); + fe25519_mul(x, h->X, recip); + fe25519_mul(y, h->Y, recip); + fe25519_tobytes(s, y); + s[31] ^= fe25519_isnegative(x) << 7; +} + +/* + r = a * A + b * B + where a = a[0]+256*a[1]+...+256^31 a[31]. + and b = b[0]+256*b[1]+...+256^31 b[31]. + B is the Ed25519 base point (x,4/5) with x positive. + + Only used for signatures verification. + */ + +void +ge25519_double_scalarmult_vartime(ge25519_p2 *r, const unsigned char *a, + const ge25519_p3 *A, const unsigned char *b) +{ + static const ge25519_precomp Bi[8] = { +#ifdef HAVE_TI_MODE +# include "fe_51/base2.h" +#else +# include "fe_25_5/base2.h" +#endif + }; + signed char aslide[256]; + signed char bslide[256]; + ge25519_cached Ai[8]; /* A,3A,5A,7A,9A,11A,13A,15A */ + ge25519_p1p1 t; + ge25519_p3 u; + ge25519_p3 A2; + int i; + + slide_vartime(aslide, a); + slide_vartime(bslide, b); + + ge25519_p3_to_cached(&Ai[0], A); + + ge25519_p3_dbl(&t, A); + ge25519_p1p1_to_p3(&A2, &t); + + ge25519_add(&t, &A2, &Ai[0]); + ge25519_p1p1_to_p3(&u, &t); + ge25519_p3_to_cached(&Ai[1], &u); + + ge25519_add(&t, &A2, &Ai[1]); + ge25519_p1p1_to_p3(&u, &t); + ge25519_p3_to_cached(&Ai[2], &u); + + ge25519_add(&t, &A2, &Ai[2]); + ge25519_p1p1_to_p3(&u, &t); + ge25519_p3_to_cached(&Ai[3], &u); + + ge25519_add(&t, &A2, &Ai[3]); + ge25519_p1p1_to_p3(&u, &t); + ge25519_p3_to_cached(&Ai[4], &u); + + ge25519_add(&t, &A2, &Ai[4]); + ge25519_p1p1_to_p3(&u, &t); + ge25519_p3_to_cached(&Ai[5], &u); + + ge25519_add(&t, &A2, &Ai[5]); + ge25519_p1p1_to_p3(&u, &t); + ge25519_p3_to_cached(&Ai[6], &u); + + ge25519_add(&t, &A2, &Ai[6]); + ge25519_p1p1_to_p3(&u, &t); + ge25519_p3_to_cached(&Ai[7], &u); + + ge25519_p2_0(r); + + for (i = 255; i >= 0; --i) { + if (aslide[i] || bslide[i]) { + break; + } + } + + for (; i >= 0; --i) { + ge25519_p2_dbl(&t, r); + + if (aslide[i] > 0) { + ge25519_p1p1_to_p3(&u, &t); + ge25519_add(&t, &u, &Ai[aslide[i] / 2]); + } else if (aslide[i] < 0) { + ge25519_p1p1_to_p3(&u, &t); + ge25519_sub(&t, &u, &Ai[(-aslide[i]) / 2]); + } + + if (bslide[i] > 0) { + ge25519_p1p1_to_p3(&u, &t); + ge25519_madd(&t, &u, &Bi[bslide[i] / 2]); + } else if (bslide[i] < 0) { + ge25519_p1p1_to_p3(&u, &t); + ge25519_msub(&t, &u, &Bi[(-bslide[i]) / 2]); + } + + ge25519_p1p1_to_p2(r, &t); + } +} + +/* + h = a * p + where a = a[0]+256*a[1]+...+256^31 a[31] + + Preconditions: + a[31] <= 127 + + p is public + */ + +void +ge25519_scalarmult(ge25519_p3 *h, const unsigned char *a, const ge25519_p3 *p) +{ + signed char e[64]; + signed char carry; + ge25519_p1p1 r; + ge25519_p2 s; + ge25519_p1p1 t2, t3, t4, t5, t6, t7, t8; + ge25519_p3 p2, p3, p4, p5, p6, p7, p8; + ge25519_cached pi[8]; + ge25519_cached t; + int i; + + ge25519_p3_to_cached(&pi[1 - 1], p); /* p */ + + ge25519_p3_dbl(&t2, p); + ge25519_p1p1_to_p3(&p2, &t2); + ge25519_p3_to_cached(&pi[2 - 1], &p2); /* 2p = 2*p */ + + ge25519_add(&t3, p, &pi[2 - 1]); + ge25519_p1p1_to_p3(&p3, &t3); + ge25519_p3_to_cached(&pi[3 - 1], &p3); /* 3p = 2p+p */ + + ge25519_p3_dbl(&t4, &p2); + ge25519_p1p1_to_p3(&p4, &t4); + ge25519_p3_to_cached(&pi[4 - 1], &p4); /* 4p = 2*2p */ + + ge25519_add(&t5, p, &pi[4 - 1]); + ge25519_p1p1_to_p3(&p5, &t5); + ge25519_p3_to_cached(&pi[5 - 1], &p5); /* 5p = 4p+p */ + + ge25519_p3_dbl(&t6, &p3); + ge25519_p1p1_to_p3(&p6, &t6); + ge25519_p3_to_cached(&pi[6 - 1], &p6); /* 6p = 2*3p */ + + ge25519_add(&t7, p, &pi[6 - 1]); + ge25519_p1p1_to_p3(&p7, &t7); + ge25519_p3_to_cached(&pi[7 - 1], &p7); /* 7p = 6p+p */ + + ge25519_p3_dbl(&t8, &p4); + ge25519_p1p1_to_p3(&p8, &t8); + ge25519_p3_to_cached(&pi[8 - 1], &p8); /* 8p = 2*4p */ + + for (i = 0; i < 32; ++i) { + e[2 * i + 0] = (a[i] >> 0) & 15; + e[2 * i + 1] = (a[i] >> 4) & 15; + } + /* each e[i] is between 0 and 15 */ + /* e[63] is between 0 and 7 */ + + carry = 0; + for (i = 0; i < 63; ++i) { + e[i] += carry; + carry = e[i] + 8; + carry >>= 4; + e[i] -= carry * ((signed char) 1 << 4); + } + e[63] += carry; + /* each e[i] is between -8 and 8 */ + + ge25519_p3_0(h); + + for (i = 63; i != 0; i--) { + ge25519_cmov8_cached(&t, pi, e[i]); + ge25519_add(&r, h, &t); + + ge25519_p1p1_to_p2(&s, &r); + ge25519_p2_dbl(&r, &s); + ge25519_p1p1_to_p2(&s, &r); + ge25519_p2_dbl(&r, &s); + ge25519_p1p1_to_p2(&s, &r); + ge25519_p2_dbl(&r, &s); + ge25519_p1p1_to_p2(&s, &r); + ge25519_p2_dbl(&r, &s); + + ge25519_p1p1_to_p3(h, &r); /* *16 */ + } + ge25519_cmov8_cached(&t, pi, e[i]); + ge25519_add(&r, h, &t); + + ge25519_p1p1_to_p3(h, &r); +} + +/* + h = a * B (with precomputation) + where a = a[0]+256*a[1]+...+256^31 a[31] + B is the Ed25519 base point (x,4/5) with x positive + (as bytes: 0x5866666666666666666666666666666666666666666666666666666666666666) + + Preconditions: + a[31] <= 127 + */ + +void +ge25519_scalarmult_base(ge25519_p3 *h, const unsigned char *a) +{ + signed char e[64]; + signed char carry; + ge25519_p1p1 r; + ge25519_p2 s; + ge25519_precomp t; + int i; + + for (i = 0; i < 32; ++i) { + e[2 * i + 0] = (a[i] >> 0) & 15; + e[2 * i + 1] = (a[i] >> 4) & 15; + } + /* each e[i] is between 0 and 15 */ + /* e[63] is between 0 and 7 */ + + carry = 0; + for (i = 0; i < 63; ++i) { + e[i] += carry; + carry = e[i] + 8; + carry >>= 4; + e[i] -= carry * ((signed char) 1 << 4); + } + e[63] += carry; + /* each e[i] is between -8 and 8 */ + + ge25519_p3_0(h); + + for (i = 1; i < 64; i += 2) { + ge25519_cmov8_base(&t, i / 2, e[i]); + ge25519_madd(&r, h, &t); + ge25519_p1p1_to_p3(h, &r); + } + + ge25519_p3_dbl(&r, h); + ge25519_p1p1_to_p2(&s, &r); + ge25519_p2_dbl(&r, &s); + ge25519_p1p1_to_p2(&s, &r); + ge25519_p2_dbl(&r, &s); + ge25519_p1p1_to_p2(&s, &r); + ge25519_p2_dbl(&r, &s); + ge25519_p1p1_to_p3(h, &r); + + for (i = 0; i < 64; i += 2) { + ge25519_cmov8_base(&t, i / 2, e[i]); + ge25519_madd(&r, h, &t); + ge25519_p1p1_to_p3(h, &r); + } +} + +/* multiply by the order of the main subgroup l = 2^252+27742317777372353535851937790883648493 */ +static void +ge25519_mul_l(ge25519_p3 *r, const ge25519_p3 *A) +{ + static const signed char aslide[253] = { + 13, 0, 0, 0, 0, -1, 0, 0, 0, 0, -11, 0, 0, 0, 0, 0, 0, -5, 0, 0, 0, 0, 0, 0, -3, 0, 0, 0, 0, -13, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, -13, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 11, 0, 0, 0, 0, 0, 11, 0, 0, 0, 0, -13, 0, 0, 0, 0, 0, 0, -3, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 3, 0, 0, 0, 0, -11, 0, 0, 0, 0, 0, 0, 0, 15, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 7, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 + }; + ge25519_cached Ai[8]; + ge25519_p1p1 t; + ge25519_p3 u; + ge25519_p3 A2; + int i; + + ge25519_p3_to_cached(&Ai[0], A); + ge25519_p3_dbl(&t, A); + ge25519_p1p1_to_p3(&A2, &t); + ge25519_add(&t, &A2, &Ai[0]); + ge25519_p1p1_to_p3(&u, &t); + ge25519_p3_to_cached(&Ai[1], &u); + ge25519_add(&t, &A2, &Ai[1]); + ge25519_p1p1_to_p3(&u, &t); + ge25519_p3_to_cached(&Ai[2], &u); + ge25519_add(&t, &A2, &Ai[2]); + ge25519_p1p1_to_p3(&u, &t); + ge25519_p3_to_cached(&Ai[3], &u); + ge25519_add(&t, &A2, &Ai[3]); + ge25519_p1p1_to_p3(&u, &t); + ge25519_p3_to_cached(&Ai[4], &u); + ge25519_add(&t, &A2, &Ai[4]); + ge25519_p1p1_to_p3(&u, &t); + ge25519_p3_to_cached(&Ai[5], &u); + ge25519_add(&t, &A2, &Ai[5]); + ge25519_p1p1_to_p3(&u, &t); + ge25519_p3_to_cached(&Ai[6], &u); + ge25519_add(&t, &A2, &Ai[6]); + ge25519_p1p1_to_p3(&u, &t); + ge25519_p3_to_cached(&Ai[7], &u); + + ge25519_p3_0(r); + + for (i = 252; i >= 0; --i) { + ge25519_p3_dbl(&t, r); + + if (aslide[i] > 0) { + ge25519_p1p1_to_p3(&u, &t); + ge25519_add(&t, &u, &Ai[aslide[i] / 2]); + } else if (aslide[i] < 0) { + ge25519_p1p1_to_p3(&u, &t); + ge25519_sub(&t, &u, &Ai[(-aslide[i]) / 2]); + } + + ge25519_p1p1_to_p3(r, &t); + } +} + +int +ge25519_is_on_curve(const ge25519_p3 *p) +{ + fe25519 x2; + fe25519 y2; + fe25519 z2; + fe25519 z4; + fe25519 t0; + fe25519 t1; + + fe25519_sq(x2, p->X); + fe25519_sq(y2, p->Y); + fe25519_sq(z2, p->Z); + fe25519_sub(t0, y2, x2); + fe25519_mul(t0, t0, z2); + + fe25519_mul(t1, x2, y2); + fe25519_mul(t1, t1, d); + fe25519_sq(z4, z2); + fe25519_add(t1, t1, z4); + fe25519_sub(t0, t0, t1); + + return fe25519_iszero(t0); +} + +int +ge25519_is_on_main_subgroup(const ge25519_p3 *p) +{ + ge25519_p3 pl; + + ge25519_mul_l(&pl, p); + + return fe25519_iszero(pl.X); +} + +int +ge25519_is_canonical(const unsigned char *s) +{ + unsigned char c; + unsigned char d; + unsigned int i; + + c = (s[31] & 0x7f) ^ 0x7f; + for (i = 30; i > 0; i--) { + c |= s[i] ^ 0xff; + } + c = (((unsigned int) c) - 1U) >> 8; + d = (0xed - 1U - (unsigned int) s[0]) >> 8; + + return 1 - (c & d & 1); +} + +int +ge25519_has_small_order(const unsigned char s[32]) +{ + CRYPTO_ALIGN(16) + static const unsigned char blacklist[][32] = { + /* 0 (order 4) */ + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, + /* 1 (order 1) */ + { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, + /* 2707385501144840649318225287225658788936804267575313519463743609750303402022 + (order 8) */ + { 0x26, 0xe8, 0x95, 0x8f, 0xc2, 0xb2, 0x27, 0xb0, 0x45, 0xc3, 0xf4, + 0x89, 0xf2, 0xef, 0x98, 0xf0, 0xd5, 0xdf, 0xac, 0x05, 0xd3, 0xc6, + 0x33, 0x39, 0xb1, 0x38, 0x02, 0x88, 0x6d, 0x53, 0xfc, 0x05 }, + /* 55188659117513257062467267217118295137698188065244968500265048394206261417927 + (order 8) */ + { 0xc7, 0x17, 0x6a, 0x70, 0x3d, 0x4d, 0xd8, 0x4f, 0xba, 0x3c, 0x0b, + 0x76, 0x0d, 0x10, 0x67, 0x0f, 0x2a, 0x20, 0x53, 0xfa, 0x2c, 0x39, + 0xcc, 0xc6, 0x4e, 0xc7, 0xfd, 0x77, 0x92, 0xac, 0x03, 0x7a }, + /* p-1 (order 2) */ + { 0xec, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f }, + /* p (=0, order 4) */ + { 0xed, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f }, + /* p+1 (=1, order 1) */ + { 0xee, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f } + }; + unsigned char c[7] = { 0 }; + unsigned int k; + size_t i, j; + + COMPILER_ASSERT(7 == sizeof blacklist / sizeof blacklist[0]); + for (j = 0; j < 31; j++) { + for (i = 0; i < sizeof blacklist / sizeof blacklist[0]; i++) { + c[i] |= s[j] ^ blacklist[i][j]; + } + } + for (i = 0; i < sizeof blacklist / sizeof blacklist[0]; i++) { + c[i] |= (s[j] & 0x7f) ^ blacklist[i][j]; + } + k = 0; + for (i = 0; i < sizeof blacklist / sizeof blacklist[0]; i++) { + k |= (c[i] - 1); + } + return (int) ((k >> 8) & 1); +} + +/* + Input: + a[0]+256*a[1]+...+256^31*a[31] = a + b[0]+256*b[1]+...+256^31*b[31] = b + * + Output: + s[0]+256*s[1]+...+256^31*s[31] = (ab) mod l + where l = 2^252 + 27742317777372353535851937790883648493. + */ + +void +sc25519_mul(unsigned char s[32], const unsigned char a[32], const unsigned char b[32]) +{ + int64_t a0 = 2097151 & load_3(a); + int64_t a1 = 2097151 & (load_4(a + 2) >> 5); + int64_t a2 = 2097151 & (load_3(a + 5) >> 2); + int64_t a3 = 2097151 & (load_4(a + 7) >> 7); + int64_t a4 = 2097151 & (load_4(a + 10) >> 4); + int64_t a5 = 2097151 & (load_3(a + 13) >> 1); + int64_t a6 = 2097151 & (load_4(a + 15) >> 6); + int64_t a7 = 2097151 & (load_3(a + 18) >> 3); + int64_t a8 = 2097151 & load_3(a + 21); + int64_t a9 = 2097151 & (load_4(a + 23) >> 5); + int64_t a10 = 2097151 & (load_3(a + 26) >> 2); + int64_t a11 = (load_4(a + 28) >> 7); + + int64_t b0 = 2097151 & load_3(b); + int64_t b1 = 2097151 & (load_4(b + 2) >> 5); + int64_t b2 = 2097151 & (load_3(b + 5) >> 2); + int64_t b3 = 2097151 & (load_4(b + 7) >> 7); + int64_t b4 = 2097151 & (load_4(b + 10) >> 4); + int64_t b5 = 2097151 & (load_3(b + 13) >> 1); + int64_t b6 = 2097151 & (load_4(b + 15) >> 6); + int64_t b7 = 2097151 & (load_3(b + 18) >> 3); + int64_t b8 = 2097151 & load_3(b + 21); + int64_t b9 = 2097151 & (load_4(b + 23) >> 5); + int64_t b10 = 2097151 & (load_3(b + 26) >> 2); + int64_t b11 = (load_4(b + 28) >> 7); + + int64_t s0; + int64_t s1; + int64_t s2; + int64_t s3; + int64_t s4; + int64_t s5; + int64_t s6; + int64_t s7; + int64_t s8; + int64_t s9; + int64_t s10; + int64_t s11; + int64_t s12; + int64_t s13; + int64_t s14; + int64_t s15; + int64_t s16; + int64_t s17; + int64_t s18; + int64_t s19; + int64_t s20; + int64_t s21; + int64_t s22; + int64_t s23; + + int64_t carry0; + int64_t carry1; + int64_t carry2; + int64_t carry3; + int64_t carry4; + int64_t carry5; + int64_t carry6; + int64_t carry7; + int64_t carry8; + int64_t carry9; + int64_t carry10; + int64_t carry11; + int64_t carry12; + int64_t carry13; + int64_t carry14; + int64_t carry15; + int64_t carry16; + int64_t carry17; + int64_t carry18; + int64_t carry19; + int64_t carry20; + int64_t carry21; + int64_t carry22; + + s0 = a0 * b0; + s1 = a0 * b1 + a1 * b0; + s2 = a0 * b2 + a1 * b1 + a2 * b0; + s3 = a0 * b3 + a1 * b2 + a2 * b1 + a3 * b0; + s4 = a0 * b4 + a1 * b3 + a2 * b2 + a3 * b1 + a4 * b0; + s5 = a0 * b5 + a1 * b4 + a2 * b3 + a3 * b2 + a4 * b1 + a5 * b0; + s6 = a0 * b6 + a1 * b5 + a2 * b4 + a3 * b3 + a4 * b2 + a5 * b1 + a6 * b0; + s7 = a0 * b7 + a1 * b6 + a2 * b5 + a3 * b4 + a4 * b3 + a5 * b2 + + a6 * b1 + a7 * b0; + s8 = a0 * b8 + a1 * b7 + a2 * b6 + a3 * b5 + a4 * b4 + a5 * b3 + + a6 * b2 + a7 * b1 + a8 * b0; + s9 = a0 * b9 + a1 * b8 + a2 * b7 + a3 * b6 + a4 * b5 + a5 * b4 + + a6 * b3 + a7 * b2 + a8 * b1 + a9 * b0; + s10 = a0 * b10 + a1 * b9 + a2 * b8 + a3 * b7 + a4 * b6 + a5 * b5 + + a6 * b4 + a7 * b3 + a8 * b2 + a9 * b1 + a10 * b0; + s11 = a0 * b11 + a1 * b10 + a2 * b9 + a3 * b8 + a4 * b7 + a5 * b6 + + a6 * b5 + a7 * b4 + a8 * b3 + a9 * b2 + a10 * b1 + a11 * b0; + s12 = a1 * b11 + a2 * b10 + a3 * b9 + a4 * b8 + a5 * b7 + a6 * b6 + + a7 * b5 + a8 * b4 + a9 * b3 + a10 * b2 + a11 * b1; + s13 = a2 * b11 + a3 * b10 + a4 * b9 + a5 * b8 + a6 * b7 + a7 * b6 + + a8 * b5 + a9 * b4 + a10 * b3 + a11 * b2; + s14 = a3 * b11 + a4 * b10 + a5 * b9 + a6 * b8 + a7 * b7 + a8 * b6 + + a9 * b5 + a10 * b4 + a11 * b3; + s15 = a4 * b11 + a5 * b10 + a6 * b9 + a7 * b8 + a8 * b7 + a9 * b6 + + a10 * b5 + a11 * b4; + s16 = + a5 * b11 + a6 * b10 + a7 * b9 + a8 * b8 + a9 * b7 + a10 * b6 + a11 * b5; + s17 = a6 * b11 + a7 * b10 + a8 * b9 + a9 * b8 + a10 * b7 + a11 * b6; + s18 = a7 * b11 + a8 * b10 + a9 * b9 + a10 * b8 + a11 * b7; + s19 = a8 * b11 + a9 * b10 + a10 * b9 + a11 * b8; + s20 = a9 * b11 + a10 * b10 + a11 * b9; + s21 = a10 * b11 + a11 * b10; + s22 = a11 * b11; + s23 = 0; + + carry0 = (s0 + (int64_t) (1L << 20)) >> 21; + s1 += carry0; + s0 -= carry0 * ((uint64_t) 1L << 21); + carry2 = (s2 + (int64_t) (1L << 20)) >> 21; + s3 += carry2; + s2 -= carry2 * ((uint64_t) 1L << 21); + carry4 = (s4 + (int64_t) (1L << 20)) >> 21; + s5 += carry4; + s4 -= carry4 * ((uint64_t) 1L << 21); + carry6 = (s6 + (int64_t) (1L << 20)) >> 21; + s7 += carry6; + s6 -= carry6 * ((uint64_t) 1L << 21); + carry8 = (s8 + (int64_t) (1L << 20)) >> 21; + s9 += carry8; + s8 -= carry8 * ((uint64_t) 1L << 21); + carry10 = (s10 + (int64_t) (1L << 20)) >> 21; + s11 += carry10; + s10 -= carry10 * ((uint64_t) 1L << 21); + carry12 = (s12 + (int64_t) (1L << 20)) >> 21; + s13 += carry12; + s12 -= carry12 * ((uint64_t) 1L << 21); + carry14 = (s14 + (int64_t) (1L << 20)) >> 21; + s15 += carry14; + s14 -= carry14 * ((uint64_t) 1L << 21); + carry16 = (s16 + (int64_t) (1L << 20)) >> 21; + s17 += carry16; + s16 -= carry16 * ((uint64_t) 1L << 21); + carry18 = (s18 + (int64_t) (1L << 20)) >> 21; + s19 += carry18; + s18 -= carry18 * ((uint64_t) 1L << 21); + carry20 = (s20 + (int64_t) (1L << 20)) >> 21; + s21 += carry20; + s20 -= carry20 * ((uint64_t) 1L << 21); + carry22 = (s22 + (int64_t) (1L << 20)) >> 21; + s23 += carry22; + s22 -= carry22 * ((uint64_t) 1L << 21); + + carry1 = (s1 + (int64_t) (1L << 20)) >> 21; + s2 += carry1; + s1 -= carry1 * ((uint64_t) 1L << 21); + carry3 = (s3 + (int64_t) (1L << 20)) >> 21; + s4 += carry3; + s3 -= carry3 * ((uint64_t) 1L << 21); + carry5 = (s5 + (int64_t) (1L << 20)) >> 21; + s6 += carry5; + s5 -= carry5 * ((uint64_t) 1L << 21); + carry7 = (s7 + (int64_t) (1L << 20)) >> 21; + s8 += carry7; + s7 -= carry7 * ((uint64_t) 1L << 21); + carry9 = (s9 + (int64_t) (1L << 20)) >> 21; + s10 += carry9; + s9 -= carry9 * ((uint64_t) 1L << 21); + carry11 = (s11 + (int64_t) (1L << 20)) >> 21; + s12 += carry11; + s11 -= carry11 * ((uint64_t) 1L << 21); + carry13 = (s13 + (int64_t) (1L << 20)) >> 21; + s14 += carry13; + s13 -= carry13 * ((uint64_t) 1L << 21); + carry15 = (s15 + (int64_t) (1L << 20)) >> 21; + s16 += carry15; + s15 -= carry15 * ((uint64_t) 1L << 21); + carry17 = (s17 + (int64_t) (1L << 20)) >> 21; + s18 += carry17; + s17 -= carry17 * ((uint64_t) 1L << 21); + carry19 = (s19 + (int64_t) (1L << 20)) >> 21; + s20 += carry19; + s19 -= carry19 * ((uint64_t) 1L << 21); + carry21 = (s21 + (int64_t) (1L << 20)) >> 21; + s22 += carry21; + s21 -= carry21 * ((uint64_t) 1L << 21); + + s11 += s23 * 666643; + s12 += s23 * 470296; + s13 += s23 * 654183; + s14 -= s23 * 997805; + s15 += s23 * 136657; + s16 -= s23 * 683901; + + s10 += s22 * 666643; + s11 += s22 * 470296; + s12 += s22 * 654183; + s13 -= s22 * 997805; + s14 += s22 * 136657; + s15 -= s22 * 683901; + + s9 += s21 * 666643; + s10 += s21 * 470296; + s11 += s21 * 654183; + s12 -= s21 * 997805; + s13 += s21 * 136657; + s14 -= s21 * 683901; + + s8 += s20 * 666643; + s9 += s20 * 470296; + s10 += s20 * 654183; + s11 -= s20 * 997805; + s12 += s20 * 136657; + s13 -= s20 * 683901; + + s7 += s19 * 666643; + s8 += s19 * 470296; + s9 += s19 * 654183; + s10 -= s19 * 997805; + s11 += s19 * 136657; + s12 -= s19 * 683901; + + s6 += s18 * 666643; + s7 += s18 * 470296; + s8 += s18 * 654183; + s9 -= s18 * 997805; + s10 += s18 * 136657; + s11 -= s18 * 683901; + + carry6 = (s6 + (int64_t) (1L << 20)) >> 21; + s7 += carry6; + s6 -= carry6 * ((uint64_t) 1L << 21); + carry8 = (s8 + (int64_t) (1L << 20)) >> 21; + s9 += carry8; + s8 -= carry8 * ((uint64_t) 1L << 21); + carry10 = (s10 + (int64_t) (1L << 20)) >> 21; + s11 += carry10; + s10 -= carry10 * ((uint64_t) 1L << 21); + carry12 = (s12 + (int64_t) (1L << 20)) >> 21; + s13 += carry12; + s12 -= carry12 * ((uint64_t) 1L << 21); + carry14 = (s14 + (int64_t) (1L << 20)) >> 21; + s15 += carry14; + s14 -= carry14 * ((uint64_t) 1L << 21); + carry16 = (s16 + (int64_t) (1L << 20)) >> 21; + s17 += carry16; + s16 -= carry16 * ((uint64_t) 1L << 21); + + carry7 = (s7 + (int64_t) (1L << 20)) >> 21; + s8 += carry7; + s7 -= carry7 * ((uint64_t) 1L << 21); + carry9 = (s9 + (int64_t) (1L << 20)) >> 21; + s10 += carry9; + s9 -= carry9 * ((uint64_t) 1L << 21); + carry11 = (s11 + (int64_t) (1L << 20)) >> 21; + s12 += carry11; + s11 -= carry11 * ((uint64_t) 1L << 21); + carry13 = (s13 + (int64_t) (1L << 20)) >> 21; + s14 += carry13; + s13 -= carry13 * ((uint64_t) 1L << 21); + carry15 = (s15 + (int64_t) (1L << 20)) >> 21; + s16 += carry15; + s15 -= carry15 * ((uint64_t) 1L << 21); + + s5 += s17 * 666643; + s6 += s17 * 470296; + s7 += s17 * 654183; + s8 -= s17 * 997805; + s9 += s17 * 136657; + s10 -= s17 * 683901; + + s4 += s16 * 666643; + s5 += s16 * 470296; + s6 += s16 * 654183; + s7 -= s16 * 997805; + s8 += s16 * 136657; + s9 -= s16 * 683901; + + s3 += s15 * 666643; + s4 += s15 * 470296; + s5 += s15 * 654183; + s6 -= s15 * 997805; + s7 += s15 * 136657; + s8 -= s15 * 683901; + + s2 += s14 * 666643; + s3 += s14 * 470296; + s4 += s14 * 654183; + s5 -= s14 * 997805; + s6 += s14 * 136657; + s7 -= s14 * 683901; + + s1 += s13 * 666643; + s2 += s13 * 470296; + s3 += s13 * 654183; + s4 -= s13 * 997805; + s5 += s13 * 136657; + s6 -= s13 * 683901; + + s0 += s12 * 666643; + s1 += s12 * 470296; + s2 += s12 * 654183; + s3 -= s12 * 997805; + s4 += s12 * 136657; + s5 -= s12 * 683901; + s12 = 0; + + carry0 = (s0 + (int64_t) (1L << 20)) >> 21; + s1 += carry0; + s0 -= carry0 * ((uint64_t) 1L << 21); + carry2 = (s2 + (int64_t) (1L << 20)) >> 21; + s3 += carry2; + s2 -= carry2 * ((uint64_t) 1L << 21); + carry4 = (s4 + (int64_t) (1L << 20)) >> 21; + s5 += carry4; + s4 -= carry4 * ((uint64_t) 1L << 21); + carry6 = (s6 + (int64_t) (1L << 20)) >> 21; + s7 += carry6; + s6 -= carry6 * ((uint64_t) 1L << 21); + carry8 = (s8 + (int64_t) (1L << 20)) >> 21; + s9 += carry8; + s8 -= carry8 * ((uint64_t) 1L << 21); + carry10 = (s10 + (int64_t) (1L << 20)) >> 21; + s11 += carry10; + s10 -= carry10 * ((uint64_t) 1L << 21); + + carry1 = (s1 + (int64_t) (1L << 20)) >> 21; + s2 += carry1; + s1 -= carry1 * ((uint64_t) 1L << 21); + carry3 = (s3 + (int64_t) (1L << 20)) >> 21; + s4 += carry3; + s3 -= carry3 * ((uint64_t) 1L << 21); + carry5 = (s5 + (int64_t) (1L << 20)) >> 21; + s6 += carry5; + s5 -= carry5 * ((uint64_t) 1L << 21); + carry7 = (s7 + (int64_t) (1L << 20)) >> 21; + s8 += carry7; + s7 -= carry7 * ((uint64_t) 1L << 21); + carry9 = (s9 + (int64_t) (1L << 20)) >> 21; + s10 += carry9; + s9 -= carry9 * ((uint64_t) 1L << 21); + carry11 = (s11 + (int64_t) (1L << 20)) >> 21; + s12 += carry11; + s11 -= carry11 * ((uint64_t) 1L << 21); + + s0 += s12 * 666643; + s1 += s12 * 470296; + s2 += s12 * 654183; + s3 -= s12 * 997805; + s4 += s12 * 136657; + s5 -= s12 * 683901; + s12 = 0; + + carry0 = s0 >> 21; + s1 += carry0; + s0 -= carry0 * ((uint64_t) 1L << 21); + carry1 = s1 >> 21; + s2 += carry1; + s1 -= carry1 * ((uint64_t) 1L << 21); + carry2 = s2 >> 21; + s3 += carry2; + s2 -= carry2 * ((uint64_t) 1L << 21); + carry3 = s3 >> 21; + s4 += carry3; + s3 -= carry3 * ((uint64_t) 1L << 21); + carry4 = s4 >> 21; + s5 += carry4; + s4 -= carry4 * ((uint64_t) 1L << 21); + carry5 = s5 >> 21; + s6 += carry5; + s5 -= carry5 * ((uint64_t) 1L << 21); + carry6 = s6 >> 21; + s7 += carry6; + s6 -= carry6 * ((uint64_t) 1L << 21); + carry7 = s7 >> 21; + s8 += carry7; + s7 -= carry7 * ((uint64_t) 1L << 21); + carry8 = s8 >> 21; + s9 += carry8; + s8 -= carry8 * ((uint64_t) 1L << 21); + carry9 = s9 >> 21; + s10 += carry9; + s9 -= carry9 * ((uint64_t) 1L << 21); + carry10 = s10 >> 21; + s11 += carry10; + s10 -= carry10 * ((uint64_t) 1L << 21); + carry11 = s11 >> 21; + s12 += carry11; + s11 -= carry11 * ((uint64_t) 1L << 21); + + s0 += s12 * 666643; + s1 += s12 * 470296; + s2 += s12 * 654183; + s3 -= s12 * 997805; + s4 += s12 * 136657; + s5 -= s12 * 683901; + + carry0 = s0 >> 21; + s1 += carry0; + s0 -= carry0 * ((uint64_t) 1L << 21); + carry1 = s1 >> 21; + s2 += carry1; + s1 -= carry1 * ((uint64_t) 1L << 21); + carry2 = s2 >> 21; + s3 += carry2; + s2 -= carry2 * ((uint64_t) 1L << 21); + carry3 = s3 >> 21; + s4 += carry3; + s3 -= carry3 * ((uint64_t) 1L << 21); + carry4 = s4 >> 21; + s5 += carry4; + s4 -= carry4 * ((uint64_t) 1L << 21); + carry5 = s5 >> 21; + s6 += carry5; + s5 -= carry5 * ((uint64_t) 1L << 21); + carry6 = s6 >> 21; + s7 += carry6; + s6 -= carry6 * ((uint64_t) 1L << 21); + carry7 = s7 >> 21; + s8 += carry7; + s7 -= carry7 * ((uint64_t) 1L << 21); + carry8 = s8 >> 21; + s9 += carry8; + s8 -= carry8 * ((uint64_t) 1L << 21); + carry9 = s9 >> 21; + s10 += carry9; + s9 -= carry9 * ((uint64_t) 1L << 21); + carry10 = s10 >> 21; + s11 += carry10; + s10 -= carry10 * ((uint64_t) 1L << 21); + + s[0] = s0 >> 0; + s[1] = s0 >> 8; + s[2] = (s0 >> 16) | (s1 * ((uint64_t) 1 << 5)); + s[3] = s1 >> 3; + s[4] = s1 >> 11; + s[5] = (s1 >> 19) | (s2 * ((uint64_t) 1 << 2)); + s[6] = s2 >> 6; + s[7] = (s2 >> 14) | (s3 * ((uint64_t) 1 << 7)); + s[8] = s3 >> 1; + s[9] = s3 >> 9; + s[10] = (s3 >> 17) | (s4 * ((uint64_t) 1 << 4)); + s[11] = s4 >> 4; + s[12] = s4 >> 12; + s[13] = (s4 >> 20) | (s5 * ((uint64_t) 1 << 1)); + s[14] = s5 >> 7; + s[15] = (s5 >> 15) | (s6 * ((uint64_t) 1 << 6)); + s[16] = s6 >> 2; + s[17] = s6 >> 10; + s[18] = (s6 >> 18) | (s7 * ((uint64_t) 1 << 3)); + s[19] = s7 >> 5; + s[20] = s7 >> 13; + s[21] = s8 >> 0; + s[22] = s8 >> 8; + s[23] = (s8 >> 16) | (s9 * ((uint64_t) 1 << 5)); + s[24] = s9 >> 3; + s[25] = s9 >> 11; + s[26] = (s9 >> 19) | (s10 * ((uint64_t) 1 << 2)); + s[27] = s10 >> 6; + s[28] = (s10 >> 14) | (s11 * ((uint64_t) 1 << 7)); + s[29] = s11 >> 1; + s[30] = s11 >> 9; + s[31] = s11 >> 17; +} + +/* + Input: + a[0]+256*a[1]+...+256^31*a[31] = a + b[0]+256*b[1]+...+256^31*b[31] = b + c[0]+256*c[1]+...+256^31*c[31] = c + * + Output: + s[0]+256*s[1]+...+256^31*s[31] = (ab+c) mod l + where l = 2^252 + 27742317777372353535851937790883648493. + */ + +void +sc25519_muladd(unsigned char s[32], const unsigned char a[32], + const unsigned char b[32], const unsigned char c[32]) +{ + int64_t a0 = 2097151 & load_3(a); + int64_t a1 = 2097151 & (load_4(a + 2) >> 5); + int64_t a2 = 2097151 & (load_3(a + 5) >> 2); + int64_t a3 = 2097151 & (load_4(a + 7) >> 7); + int64_t a4 = 2097151 & (load_4(a + 10) >> 4); + int64_t a5 = 2097151 & (load_3(a + 13) >> 1); + int64_t a6 = 2097151 & (load_4(a + 15) >> 6); + int64_t a7 = 2097151 & (load_3(a + 18) >> 3); + int64_t a8 = 2097151 & load_3(a + 21); + int64_t a9 = 2097151 & (load_4(a + 23) >> 5); + int64_t a10 = 2097151 & (load_3(a + 26) >> 2); + int64_t a11 = (load_4(a + 28) >> 7); + + int64_t b0 = 2097151 & load_3(b); + int64_t b1 = 2097151 & (load_4(b + 2) >> 5); + int64_t b2 = 2097151 & (load_3(b + 5) >> 2); + int64_t b3 = 2097151 & (load_4(b + 7) >> 7); + int64_t b4 = 2097151 & (load_4(b + 10) >> 4); + int64_t b5 = 2097151 & (load_3(b + 13) >> 1); + int64_t b6 = 2097151 & (load_4(b + 15) >> 6); + int64_t b7 = 2097151 & (load_3(b + 18) >> 3); + int64_t b8 = 2097151 & load_3(b + 21); + int64_t b9 = 2097151 & (load_4(b + 23) >> 5); + int64_t b10 = 2097151 & (load_3(b + 26) >> 2); + int64_t b11 = (load_4(b + 28) >> 7); + + int64_t c0 = 2097151 & load_3(c); + int64_t c1 = 2097151 & (load_4(c + 2) >> 5); + int64_t c2 = 2097151 & (load_3(c + 5) >> 2); + int64_t c3 = 2097151 & (load_4(c + 7) >> 7); + int64_t c4 = 2097151 & (load_4(c + 10) >> 4); + int64_t c5 = 2097151 & (load_3(c + 13) >> 1); + int64_t c6 = 2097151 & (load_4(c + 15) >> 6); + int64_t c7 = 2097151 & (load_3(c + 18) >> 3); + int64_t c8 = 2097151 & load_3(c + 21); + int64_t c9 = 2097151 & (load_4(c + 23) >> 5); + int64_t c10 = 2097151 & (load_3(c + 26) >> 2); + int64_t c11 = (load_4(c + 28) >> 7); + + int64_t s0; + int64_t s1; + int64_t s2; + int64_t s3; + int64_t s4; + int64_t s5; + int64_t s6; + int64_t s7; + int64_t s8; + int64_t s9; + int64_t s10; + int64_t s11; + int64_t s12; + int64_t s13; + int64_t s14; + int64_t s15; + int64_t s16; + int64_t s17; + int64_t s18; + int64_t s19; + int64_t s20; + int64_t s21; + int64_t s22; + int64_t s23; + + int64_t carry0; + int64_t carry1; + int64_t carry2; + int64_t carry3; + int64_t carry4; + int64_t carry5; + int64_t carry6; + int64_t carry7; + int64_t carry8; + int64_t carry9; + int64_t carry10; + int64_t carry11; + int64_t carry12; + int64_t carry13; + int64_t carry14; + int64_t carry15; + int64_t carry16; + int64_t carry17; + int64_t carry18; + int64_t carry19; + int64_t carry20; + int64_t carry21; + int64_t carry22; + + s0 = c0 + a0 * b0; + s1 = c1 + a0 * b1 + a1 * b0; + s2 = c2 + a0 * b2 + a1 * b1 + a2 * b0; + s3 = c3 + a0 * b3 + a1 * b2 + a2 * b1 + a3 * b0; + s4 = c4 + a0 * b4 + a1 * b3 + a2 * b2 + a3 * b1 + a4 * b0; + s5 = c5 + a0 * b5 + a1 * b4 + a2 * b3 + a3 * b2 + a4 * b1 + a5 * b0; + s6 = c6 + a0 * b6 + a1 * b5 + a2 * b4 + a3 * b3 + a4 * b2 + a5 * b1 + + a6 * b0; + s7 = c7 + a0 * b7 + a1 * b6 + a2 * b5 + a3 * b4 + a4 * b3 + a5 * b2 + + a6 * b1 + a7 * b0; + s8 = c8 + a0 * b8 + a1 * b7 + a2 * b6 + a3 * b5 + a4 * b4 + a5 * b3 + + a6 * b2 + a7 * b1 + a8 * b0; + s9 = c9 + a0 * b9 + a1 * b8 + a2 * b7 + a3 * b6 + a4 * b5 + a5 * b4 + + a6 * b3 + a7 * b2 + a8 * b1 + a9 * b0; + s10 = c10 + a0 * b10 + a1 * b9 + a2 * b8 + a3 * b7 + a4 * b6 + a5 * b5 + + a6 * b4 + a7 * b3 + a8 * b2 + a9 * b1 + a10 * b0; + s11 = c11 + a0 * b11 + a1 * b10 + a2 * b9 + a3 * b8 + a4 * b7 + a5 * b6 + + a6 * b5 + a7 * b4 + a8 * b3 + a9 * b2 + a10 * b1 + a11 * b0; + s12 = a1 * b11 + a2 * b10 + a3 * b9 + a4 * b8 + a5 * b7 + a6 * b6 + + a7 * b5 + a8 * b4 + a9 * b3 + a10 * b2 + a11 * b1; + s13 = a2 * b11 + a3 * b10 + a4 * b9 + a5 * b8 + a6 * b7 + a7 * b6 + + a8 * b5 + a9 * b4 + a10 * b3 + a11 * b2; + s14 = a3 * b11 + a4 * b10 + a5 * b9 + a6 * b8 + a7 * b7 + a8 * b6 + + a9 * b5 + a10 * b4 + a11 * b3; + s15 = a4 * b11 + a5 * b10 + a6 * b9 + a7 * b8 + a8 * b7 + a9 * b6 + + a10 * b5 + a11 * b4; + s16 = + a5 * b11 + a6 * b10 + a7 * b9 + a8 * b8 + a9 * b7 + a10 * b6 + a11 * b5; + s17 = a6 * b11 + a7 * b10 + a8 * b9 + a9 * b8 + a10 * b7 + a11 * b6; + s18 = a7 * b11 + a8 * b10 + a9 * b9 + a10 * b8 + a11 * b7; + s19 = a8 * b11 + a9 * b10 + a10 * b9 + a11 * b8; + s20 = a9 * b11 + a10 * b10 + a11 * b9; + s21 = a10 * b11 + a11 * b10; + s22 = a11 * b11; + s23 = 0; + + carry0 = (s0 + (int64_t) (1L << 20)) >> 21; + s1 += carry0; + s0 -= carry0 * ((uint64_t) 1L << 21); + carry2 = (s2 + (int64_t) (1L << 20)) >> 21; + s3 += carry2; + s2 -= carry2 * ((uint64_t) 1L << 21); + carry4 = (s4 + (int64_t) (1L << 20)) >> 21; + s5 += carry4; + s4 -= carry4 * ((uint64_t) 1L << 21); + carry6 = (s6 + (int64_t) (1L << 20)) >> 21; + s7 += carry6; + s6 -= carry6 * ((uint64_t) 1L << 21); + carry8 = (s8 + (int64_t) (1L << 20)) >> 21; + s9 += carry8; + s8 -= carry8 * ((uint64_t) 1L << 21); + carry10 = (s10 + (int64_t) (1L << 20)) >> 21; + s11 += carry10; + s10 -= carry10 * ((uint64_t) 1L << 21); + carry12 = (s12 + (int64_t) (1L << 20)) >> 21; + s13 += carry12; + s12 -= carry12 * ((uint64_t) 1L << 21); + carry14 = (s14 + (int64_t) (1L << 20)) >> 21; + s15 += carry14; + s14 -= carry14 * ((uint64_t) 1L << 21); + carry16 = (s16 + (int64_t) (1L << 20)) >> 21; + s17 += carry16; + s16 -= carry16 * ((uint64_t) 1L << 21); + carry18 = (s18 + (int64_t) (1L << 20)) >> 21; + s19 += carry18; + s18 -= carry18 * ((uint64_t) 1L << 21); + carry20 = (s20 + (int64_t) (1L << 20)) >> 21; + s21 += carry20; + s20 -= carry20 * ((uint64_t) 1L << 21); + carry22 = (s22 + (int64_t) (1L << 20)) >> 21; + s23 += carry22; + s22 -= carry22 * ((uint64_t) 1L << 21); + + carry1 = (s1 + (int64_t) (1L << 20)) >> 21; + s2 += carry1; + s1 -= carry1 * ((uint64_t) 1L << 21); + carry3 = (s3 + (int64_t) (1L << 20)) >> 21; + s4 += carry3; + s3 -= carry3 * ((uint64_t) 1L << 21); + carry5 = (s5 + (int64_t) (1L << 20)) >> 21; + s6 += carry5; + s5 -= carry5 * ((uint64_t) 1L << 21); + carry7 = (s7 + (int64_t) (1L << 20)) >> 21; + s8 += carry7; + s7 -= carry7 * ((uint64_t) 1L << 21); + carry9 = (s9 + (int64_t) (1L << 20)) >> 21; + s10 += carry9; + s9 -= carry9 * ((uint64_t) 1L << 21); + carry11 = (s11 + (int64_t) (1L << 20)) >> 21; + s12 += carry11; + s11 -= carry11 * ((uint64_t) 1L << 21); + carry13 = (s13 + (int64_t) (1L << 20)) >> 21; + s14 += carry13; + s13 -= carry13 * ((uint64_t) 1L << 21); + carry15 = (s15 + (int64_t) (1L << 20)) >> 21; + s16 += carry15; + s15 -= carry15 * ((uint64_t) 1L << 21); + carry17 = (s17 + (int64_t) (1L << 20)) >> 21; + s18 += carry17; + s17 -= carry17 * ((uint64_t) 1L << 21); + carry19 = (s19 + (int64_t) (1L << 20)) >> 21; + s20 += carry19; + s19 -= carry19 * ((uint64_t) 1L << 21); + carry21 = (s21 + (int64_t) (1L << 20)) >> 21; + s22 += carry21; + s21 -= carry21 * ((uint64_t) 1L << 21); + + s11 += s23 * 666643; + s12 += s23 * 470296; + s13 += s23 * 654183; + s14 -= s23 * 997805; + s15 += s23 * 136657; + s16 -= s23 * 683901; + + s10 += s22 * 666643; + s11 += s22 * 470296; + s12 += s22 * 654183; + s13 -= s22 * 997805; + s14 += s22 * 136657; + s15 -= s22 * 683901; + + s9 += s21 * 666643; + s10 += s21 * 470296; + s11 += s21 * 654183; + s12 -= s21 * 997805; + s13 += s21 * 136657; + s14 -= s21 * 683901; + + s8 += s20 * 666643; + s9 += s20 * 470296; + s10 += s20 * 654183; + s11 -= s20 * 997805; + s12 += s20 * 136657; + s13 -= s20 * 683901; + + s7 += s19 * 666643; + s8 += s19 * 470296; + s9 += s19 * 654183; + s10 -= s19 * 997805; + s11 += s19 * 136657; + s12 -= s19 * 683901; + + s6 += s18 * 666643; + s7 += s18 * 470296; + s8 += s18 * 654183; + s9 -= s18 * 997805; + s10 += s18 * 136657; + s11 -= s18 * 683901; + + carry6 = (s6 + (int64_t) (1L << 20)) >> 21; + s7 += carry6; + s6 -= carry6 * ((uint64_t) 1L << 21); + carry8 = (s8 + (int64_t) (1L << 20)) >> 21; + s9 += carry8; + s8 -= carry8 * ((uint64_t) 1L << 21); + carry10 = (s10 + (int64_t) (1L << 20)) >> 21; + s11 += carry10; + s10 -= carry10 * ((uint64_t) 1L << 21); + carry12 = (s12 + (int64_t) (1L << 20)) >> 21; + s13 += carry12; + s12 -= carry12 * ((uint64_t) 1L << 21); + carry14 = (s14 + (int64_t) (1L << 20)) >> 21; + s15 += carry14; + s14 -= carry14 * ((uint64_t) 1L << 21); + carry16 = (s16 + (int64_t) (1L << 20)) >> 21; + s17 += carry16; + s16 -= carry16 * ((uint64_t) 1L << 21); + + carry7 = (s7 + (int64_t) (1L << 20)) >> 21; + s8 += carry7; + s7 -= carry7 * ((uint64_t) 1L << 21); + carry9 = (s9 + (int64_t) (1L << 20)) >> 21; + s10 += carry9; + s9 -= carry9 * ((uint64_t) 1L << 21); + carry11 = (s11 + (int64_t) (1L << 20)) >> 21; + s12 += carry11; + s11 -= carry11 * ((uint64_t) 1L << 21); + carry13 = (s13 + (int64_t) (1L << 20)) >> 21; + s14 += carry13; + s13 -= carry13 * ((uint64_t) 1L << 21); + carry15 = (s15 + (int64_t) (1L << 20)) >> 21; + s16 += carry15; + s15 -= carry15 * ((uint64_t) 1L << 21); + + s5 += s17 * 666643; + s6 += s17 * 470296; + s7 += s17 * 654183; + s8 -= s17 * 997805; + s9 += s17 * 136657; + s10 -= s17 * 683901; + + s4 += s16 * 666643; + s5 += s16 * 470296; + s6 += s16 * 654183; + s7 -= s16 * 997805; + s8 += s16 * 136657; + s9 -= s16 * 683901; + + s3 += s15 * 666643; + s4 += s15 * 470296; + s5 += s15 * 654183; + s6 -= s15 * 997805; + s7 += s15 * 136657; + s8 -= s15 * 683901; + + s2 += s14 * 666643; + s3 += s14 * 470296; + s4 += s14 * 654183; + s5 -= s14 * 997805; + s6 += s14 * 136657; + s7 -= s14 * 683901; + + s1 += s13 * 666643; + s2 += s13 * 470296; + s3 += s13 * 654183; + s4 -= s13 * 997805; + s5 += s13 * 136657; + s6 -= s13 * 683901; + + s0 += s12 * 666643; + s1 += s12 * 470296; + s2 += s12 * 654183; + s3 -= s12 * 997805; + s4 += s12 * 136657; + s5 -= s12 * 683901; + s12 = 0; + + carry0 = (s0 + (int64_t) (1L << 20)) >> 21; + s1 += carry0; + s0 -= carry0 * ((uint64_t) 1L << 21); + carry2 = (s2 + (int64_t) (1L << 20)) >> 21; + s3 += carry2; + s2 -= carry2 * ((uint64_t) 1L << 21); + carry4 = (s4 + (int64_t) (1L << 20)) >> 21; + s5 += carry4; + s4 -= carry4 * ((uint64_t) 1L << 21); + carry6 = (s6 + (int64_t) (1L << 20)) >> 21; + s7 += carry6; + s6 -= carry6 * ((uint64_t) 1L << 21); + carry8 = (s8 + (int64_t) (1L << 20)) >> 21; + s9 += carry8; + s8 -= carry8 * ((uint64_t) 1L << 21); + carry10 = (s10 + (int64_t) (1L << 20)) >> 21; + s11 += carry10; + s10 -= carry10 * ((uint64_t) 1L << 21); + + carry1 = (s1 + (int64_t) (1L << 20)) >> 21; + s2 += carry1; + s1 -= carry1 * ((uint64_t) 1L << 21); + carry3 = (s3 + (int64_t) (1L << 20)) >> 21; + s4 += carry3; + s3 -= carry3 * ((uint64_t) 1L << 21); + carry5 = (s5 + (int64_t) (1L << 20)) >> 21; + s6 += carry5; + s5 -= carry5 * ((uint64_t) 1L << 21); + carry7 = (s7 + (int64_t) (1L << 20)) >> 21; + s8 += carry7; + s7 -= carry7 * ((uint64_t) 1L << 21); + carry9 = (s9 + (int64_t) (1L << 20)) >> 21; + s10 += carry9; + s9 -= carry9 * ((uint64_t) 1L << 21); + carry11 = (s11 + (int64_t) (1L << 20)) >> 21; + s12 += carry11; + s11 -= carry11 * ((uint64_t) 1L << 21); + + s0 += s12 * 666643; + s1 += s12 * 470296; + s2 += s12 * 654183; + s3 -= s12 * 997805; + s4 += s12 * 136657; + s5 -= s12 * 683901; + s12 = 0; + + carry0 = s0 >> 21; + s1 += carry0; + s0 -= carry0 * ((uint64_t) 1L << 21); + carry1 = s1 >> 21; + s2 += carry1; + s1 -= carry1 * ((uint64_t) 1L << 21); + carry2 = s2 >> 21; + s3 += carry2; + s2 -= carry2 * ((uint64_t) 1L << 21); + carry3 = s3 >> 21; + s4 += carry3; + s3 -= carry3 * ((uint64_t) 1L << 21); + carry4 = s4 >> 21; + s5 += carry4; + s4 -= carry4 * ((uint64_t) 1L << 21); + carry5 = s5 >> 21; + s6 += carry5; + s5 -= carry5 * ((uint64_t) 1L << 21); + carry6 = s6 >> 21; + s7 += carry6; + s6 -= carry6 * ((uint64_t) 1L << 21); + carry7 = s7 >> 21; + s8 += carry7; + s7 -= carry7 * ((uint64_t) 1L << 21); + carry8 = s8 >> 21; + s9 += carry8; + s8 -= carry8 * ((uint64_t) 1L << 21); + carry9 = s9 >> 21; + s10 += carry9; + s9 -= carry9 * ((uint64_t) 1L << 21); + carry10 = s10 >> 21; + s11 += carry10; + s10 -= carry10 * ((uint64_t) 1L << 21); + carry11 = s11 >> 21; + s12 += carry11; + s11 -= carry11 * ((uint64_t) 1L << 21); + + s0 += s12 * 666643; + s1 += s12 * 470296; + s2 += s12 * 654183; + s3 -= s12 * 997805; + s4 += s12 * 136657; + s5 -= s12 * 683901; + + carry0 = s0 >> 21; + s1 += carry0; + s0 -= carry0 * ((uint64_t) 1L << 21); + carry1 = s1 >> 21; + s2 += carry1; + s1 -= carry1 * ((uint64_t) 1L << 21); + carry2 = s2 >> 21; + s3 += carry2; + s2 -= carry2 * ((uint64_t) 1L << 21); + carry3 = s3 >> 21; + s4 += carry3; + s3 -= carry3 * ((uint64_t) 1L << 21); + carry4 = s4 >> 21; + s5 += carry4; + s4 -= carry4 * ((uint64_t) 1L << 21); + carry5 = s5 >> 21; + s6 += carry5; + s5 -= carry5 * ((uint64_t) 1L << 21); + carry6 = s6 >> 21; + s7 += carry6; + s6 -= carry6 * ((uint64_t) 1L << 21); + carry7 = s7 >> 21; + s8 += carry7; + s7 -= carry7 * ((uint64_t) 1L << 21); + carry8 = s8 >> 21; + s9 += carry8; + s8 -= carry8 * ((uint64_t) 1L << 21); + carry9 = s9 >> 21; + s10 += carry9; + s9 -= carry9 * ((uint64_t) 1L << 21); + carry10 = s10 >> 21; + s11 += carry10; + s10 -= carry10 * ((uint64_t) 1L << 21); + + s[0] = s0 >> 0; + s[1] = s0 >> 8; + s[2] = (s0 >> 16) | (s1 * ((uint64_t) 1 << 5)); + s[3] = s1 >> 3; + s[4] = s1 >> 11; + s[5] = (s1 >> 19) | (s2 * ((uint64_t) 1 << 2)); + s[6] = s2 >> 6; + s[7] = (s2 >> 14) | (s3 * ((uint64_t) 1 << 7)); + s[8] = s3 >> 1; + s[9] = s3 >> 9; + s[10] = (s3 >> 17) | (s4 * ((uint64_t) 1 << 4)); + s[11] = s4 >> 4; + s[12] = s4 >> 12; + s[13] = (s4 >> 20) | (s5 * ((uint64_t) 1 << 1)); + s[14] = s5 >> 7; + s[15] = (s5 >> 15) | (s6 * ((uint64_t) 1 << 6)); + s[16] = s6 >> 2; + s[17] = s6 >> 10; + s[18] = (s6 >> 18) | (s7 * ((uint64_t) 1 << 3)); + s[19] = s7 >> 5; + s[20] = s7 >> 13; + s[21] = s8 >> 0; + s[22] = s8 >> 8; + s[23] = (s8 >> 16) | (s9 * ((uint64_t) 1 << 5)); + s[24] = s9 >> 3; + s[25] = s9 >> 11; + s[26] = (s9 >> 19) | (s10 * ((uint64_t) 1 << 2)); + s[27] = s10 >> 6; + s[28] = (s10 >> 14) | (s11 * ((uint64_t) 1 << 7)); + s[29] = s11 >> 1; + s[30] = s11 >> 9; + s[31] = s11 >> 17; +} + +/* + Input: + a[0]+256*a[1]+...+256^31*a[31] = a + * + Output: + s[0]+256*s[1]+...+256^31*s[31] = a^2 mod l + where l = 2^252 + 27742317777372353535851937790883648493. + */ + +static inline void +sc25519_sq(unsigned char *s, const unsigned char *a) +{ + sc25519_mul(s, a, a); +} + +/* + Input: + s[0]+256*a[1]+...+256^31*a[31] = a + n + * + Output: + s[0]+256*s[1]+...+256^31*s[31] = x * s^(s^n) mod l + where l = 2^252 + 27742317777372353535851937790883648493. + Overwrites s in place. + */ + +static inline void +sc25519_sqmul(unsigned char s[32], const int n, const unsigned char a[32]) +{ + int i; + + for (i = 0; i < n; i++) { + sc25519_sq(s, s); + } + sc25519_mul(s, s, a); +} + +void +sc25519_invert(unsigned char recip[32], const unsigned char s[32]) +{ + unsigned char _10[32], _100[32], _1000[32], _10000[32], _100000[32], + _1000000[32], _10010011[32], _10010111[32], _100110[32], _1010[32], + _1010000[32], _1010011[32], _1011[32], _10110[32], _10111101[32], + _11[32], _1100011[32], _1100111[32], _11010011[32], _1101011[32], + _11100111[32], _11101011[32], _11110101[32]; + + sc25519_sq(_10, s); + sc25519_mul(_11, s, _10); + sc25519_mul(_100, s, _11); + sc25519_sq(_1000, _100); + sc25519_mul(_1010, _10, _1000); + sc25519_mul(_1011, s, _1010); + sc25519_sq(_10000, _1000); + sc25519_sq(_10110, _1011); + sc25519_mul(_100000, _1010, _10110); + sc25519_mul(_100110, _10000, _10110); + sc25519_sq(_1000000, _100000); + sc25519_mul(_1010000, _10000, _1000000); + sc25519_mul(_1010011, _11, _1010000); + sc25519_mul(_1100011, _10000, _1010011); + sc25519_mul(_1100111, _100, _1100011); + sc25519_mul(_1101011, _100, _1100111); + sc25519_mul(_10010011, _1000000, _1010011); + sc25519_mul(_10010111, _100, _10010011); + sc25519_mul(_10111101, _100110, _10010111); + sc25519_mul(_11010011, _10110, _10111101); + sc25519_mul(_11100111, _1010000, _10010111); + sc25519_mul(_11101011, _100, _11100111); + sc25519_mul(_11110101, _1010, _11101011); + + sc25519_mul(recip, _1011, _11110101); + sc25519_sqmul(recip, 126, _1010011); + sc25519_sqmul(recip, 9, _10); + sc25519_mul(recip, recip, _11110101); + sc25519_sqmul(recip, 7, _1100111); + sc25519_sqmul(recip, 9, _11110101); + sc25519_sqmul(recip, 11, _10111101); + sc25519_sqmul(recip, 8, _11100111); + sc25519_sqmul(recip, 9, _1101011); + sc25519_sqmul(recip, 6, _1011); + sc25519_sqmul(recip, 14, _10010011); + sc25519_sqmul(recip, 10, _1100011); + sc25519_sqmul(recip, 9, _10010111); + sc25519_sqmul(recip, 10, _11110101); + sc25519_sqmul(recip, 8, _11010011); + sc25519_sqmul(recip, 8, _11101011); +} + +/* + Input: + s[0]+256*s[1]+...+256^63*s[63] = s + * + Output: + s[0]+256*s[1]+...+256^31*s[31] = s mod l + where l = 2^252 + 27742317777372353535851937790883648493. + Overwrites s in place. + */ + +void +sc25519_reduce(unsigned char s[64]) +{ + int64_t s0 = 2097151 & load_3(s); + int64_t s1 = 2097151 & (load_4(s + 2) >> 5); + int64_t s2 = 2097151 & (load_3(s + 5) >> 2); + int64_t s3 = 2097151 & (load_4(s + 7) >> 7); + int64_t s4 = 2097151 & (load_4(s + 10) >> 4); + int64_t s5 = 2097151 & (load_3(s + 13) >> 1); + int64_t s6 = 2097151 & (load_4(s + 15) >> 6); + int64_t s7 = 2097151 & (load_3(s + 18) >> 3); + int64_t s8 = 2097151 & load_3(s + 21); + int64_t s9 = 2097151 & (load_4(s + 23) >> 5); + int64_t s10 = 2097151 & (load_3(s + 26) >> 2); + int64_t s11 = 2097151 & (load_4(s + 28) >> 7); + int64_t s12 = 2097151 & (load_4(s + 31) >> 4); + int64_t s13 = 2097151 & (load_3(s + 34) >> 1); + int64_t s14 = 2097151 & (load_4(s + 36) >> 6); + int64_t s15 = 2097151 & (load_3(s + 39) >> 3); + int64_t s16 = 2097151 & load_3(s + 42); + int64_t s17 = 2097151 & (load_4(s + 44) >> 5); + int64_t s18 = 2097151 & (load_3(s + 47) >> 2); + int64_t s19 = 2097151 & (load_4(s + 49) >> 7); + int64_t s20 = 2097151 & (load_4(s + 52) >> 4); + int64_t s21 = 2097151 & (load_3(s + 55) >> 1); + int64_t s22 = 2097151 & (load_4(s + 57) >> 6); + int64_t s23 = (load_4(s + 60) >> 3); + + int64_t carry0; + int64_t carry1; + int64_t carry2; + int64_t carry3; + int64_t carry4; + int64_t carry5; + int64_t carry6; + int64_t carry7; + int64_t carry8; + int64_t carry9; + int64_t carry10; + int64_t carry11; + int64_t carry12; + int64_t carry13; + int64_t carry14; + int64_t carry15; + int64_t carry16; + + s11 += s23 * 666643; + s12 += s23 * 470296; + s13 += s23 * 654183; + s14 -= s23 * 997805; + s15 += s23 * 136657; + s16 -= s23 * 683901; + + s10 += s22 * 666643; + s11 += s22 * 470296; + s12 += s22 * 654183; + s13 -= s22 * 997805; + s14 += s22 * 136657; + s15 -= s22 * 683901; + + s9 += s21 * 666643; + s10 += s21 * 470296; + s11 += s21 * 654183; + s12 -= s21 * 997805; + s13 += s21 * 136657; + s14 -= s21 * 683901; + + s8 += s20 * 666643; + s9 += s20 * 470296; + s10 += s20 * 654183; + s11 -= s20 * 997805; + s12 += s20 * 136657; + s13 -= s20 * 683901; + + s7 += s19 * 666643; + s8 += s19 * 470296; + s9 += s19 * 654183; + s10 -= s19 * 997805; + s11 += s19 * 136657; + s12 -= s19 * 683901; + + s6 += s18 * 666643; + s7 += s18 * 470296; + s8 += s18 * 654183; + s9 -= s18 * 997805; + s10 += s18 * 136657; + s11 -= s18 * 683901; + + carry6 = (s6 + (int64_t) (1L << 20)) >> 21; + s7 += carry6; + s6 -= carry6 * ((uint64_t) 1L << 21); + carry8 = (s8 + (int64_t) (1L << 20)) >> 21; + s9 += carry8; + s8 -= carry8 * ((uint64_t) 1L << 21); + carry10 = (s10 + (int64_t) (1L << 20)) >> 21; + s11 += carry10; + s10 -= carry10 * ((uint64_t) 1L << 21); + carry12 = (s12 + (int64_t) (1L << 20)) >> 21; + s13 += carry12; + s12 -= carry12 * ((uint64_t) 1L << 21); + carry14 = (s14 + (int64_t) (1L << 20)) >> 21; + s15 += carry14; + s14 -= carry14 * ((uint64_t) 1L << 21); + carry16 = (s16 + (int64_t) (1L << 20)) >> 21; + s17 += carry16; + s16 -= carry16 * ((uint64_t) 1L << 21); + + carry7 = (s7 + (int64_t) (1L << 20)) >> 21; + s8 += carry7; + s7 -= carry7 * ((uint64_t) 1L << 21); + carry9 = (s9 + (int64_t) (1L << 20)) >> 21; + s10 += carry9; + s9 -= carry9 * ((uint64_t) 1L << 21); + carry11 = (s11 + (int64_t) (1L << 20)) >> 21; + s12 += carry11; + s11 -= carry11 * ((uint64_t) 1L << 21); + carry13 = (s13 + (int64_t) (1L << 20)) >> 21; + s14 += carry13; + s13 -= carry13 * ((uint64_t) 1L << 21); + carry15 = (s15 + (int64_t) (1L << 20)) >> 21; + s16 += carry15; + s15 -= carry15 * ((uint64_t) 1L << 21); + + s5 += s17 * 666643; + s6 += s17 * 470296; + s7 += s17 * 654183; + s8 -= s17 * 997805; + s9 += s17 * 136657; + s10 -= s17 * 683901; + + s4 += s16 * 666643; + s5 += s16 * 470296; + s6 += s16 * 654183; + s7 -= s16 * 997805; + s8 += s16 * 136657; + s9 -= s16 * 683901; + + s3 += s15 * 666643; + s4 += s15 * 470296; + s5 += s15 * 654183; + s6 -= s15 * 997805; + s7 += s15 * 136657; + s8 -= s15 * 683901; + + s2 += s14 * 666643; + s3 += s14 * 470296; + s4 += s14 * 654183; + s5 -= s14 * 997805; + s6 += s14 * 136657; + s7 -= s14 * 683901; + + s1 += s13 * 666643; + s2 += s13 * 470296; + s3 += s13 * 654183; + s4 -= s13 * 997805; + s5 += s13 * 136657; + s6 -= s13 * 683901; + + s0 += s12 * 666643; + s1 += s12 * 470296; + s2 += s12 * 654183; + s3 -= s12 * 997805; + s4 += s12 * 136657; + s5 -= s12 * 683901; + s12 = 0; + + carry0 = (s0 + (int64_t) (1L << 20)) >> 21; + s1 += carry0; + s0 -= carry0 * ((uint64_t) 1L << 21); + carry2 = (s2 + (int64_t) (1L << 20)) >> 21; + s3 += carry2; + s2 -= carry2 * ((uint64_t) 1L << 21); + carry4 = (s4 + (int64_t) (1L << 20)) >> 21; + s5 += carry4; + s4 -= carry4 * ((uint64_t) 1L << 21); + carry6 = (s6 + (int64_t) (1L << 20)) >> 21; + s7 += carry6; + s6 -= carry6 * ((uint64_t) 1L << 21); + carry8 = (s8 + (int64_t) (1L << 20)) >> 21; + s9 += carry8; + s8 -= carry8 * ((uint64_t) 1L << 21); + carry10 = (s10 + (int64_t) (1L << 20)) >> 21; + s11 += carry10; + s10 -= carry10 * ((uint64_t) 1L << 21); + + carry1 = (s1 + (int64_t) (1L << 20)) >> 21; + s2 += carry1; + s1 -= carry1 * ((uint64_t) 1L << 21); + carry3 = (s3 + (int64_t) (1L << 20)) >> 21; + s4 += carry3; + s3 -= carry3 * ((uint64_t) 1L << 21); + carry5 = (s5 + (int64_t) (1L << 20)) >> 21; + s6 += carry5; + s5 -= carry5 * ((uint64_t) 1L << 21); + carry7 = (s7 + (int64_t) (1L << 20)) >> 21; + s8 += carry7; + s7 -= carry7 * ((uint64_t) 1L << 21); + carry9 = (s9 + (int64_t) (1L << 20)) >> 21; + s10 += carry9; + s9 -= carry9 * ((uint64_t) 1L << 21); + carry11 = (s11 + (int64_t) (1L << 20)) >> 21; + s12 += carry11; + s11 -= carry11 * ((uint64_t) 1L << 21); + + s0 += s12 * 666643; + s1 += s12 * 470296; + s2 += s12 * 654183; + s3 -= s12 * 997805; + s4 += s12 * 136657; + s5 -= s12 * 683901; + s12 = 0; + + carry0 = s0 >> 21; + s1 += carry0; + s0 -= carry0 * ((uint64_t) 1L << 21); + carry1 = s1 >> 21; + s2 += carry1; + s1 -= carry1 * ((uint64_t) 1L << 21); + carry2 = s2 >> 21; + s3 += carry2; + s2 -= carry2 * ((uint64_t) 1L << 21); + carry3 = s3 >> 21; + s4 += carry3; + s3 -= carry3 * ((uint64_t) 1L << 21); + carry4 = s4 >> 21; + s5 += carry4; + s4 -= carry4 * ((uint64_t) 1L << 21); + carry5 = s5 >> 21; + s6 += carry5; + s5 -= carry5 * ((uint64_t) 1L << 21); + carry6 = s6 >> 21; + s7 += carry6; + s6 -= carry6 * ((uint64_t) 1L << 21); + carry7 = s7 >> 21; + s8 += carry7; + s7 -= carry7 * ((uint64_t) 1L << 21); + carry8 = s8 >> 21; + s9 += carry8; + s8 -= carry8 * ((uint64_t) 1L << 21); + carry9 = s9 >> 21; + s10 += carry9; + s9 -= carry9 * ((uint64_t) 1L << 21); + carry10 = s10 >> 21; + s11 += carry10; + s10 -= carry10 * ((uint64_t) 1L << 21); + carry11 = s11 >> 21; + s12 += carry11; + s11 -= carry11 * ((uint64_t) 1L << 21); + + s0 += s12 * 666643; + s1 += s12 * 470296; + s2 += s12 * 654183; + s3 -= s12 * 997805; + s4 += s12 * 136657; + s5 -= s12 * 683901; + + carry0 = s0 >> 21; + s1 += carry0; + s0 -= carry0 * ((uint64_t) 1L << 21); + carry1 = s1 >> 21; + s2 += carry1; + s1 -= carry1 * ((uint64_t) 1L << 21); + carry2 = s2 >> 21; + s3 += carry2; + s2 -= carry2 * ((uint64_t) 1L << 21); + carry3 = s3 >> 21; + s4 += carry3; + s3 -= carry3 * ((uint64_t) 1L << 21); + carry4 = s4 >> 21; + s5 += carry4; + s4 -= carry4 * ((uint64_t) 1L << 21); + carry5 = s5 >> 21; + s6 += carry5; + s5 -= carry5 * ((uint64_t) 1L << 21); + carry6 = s6 >> 21; + s7 += carry6; + s6 -= carry6 * ((uint64_t) 1L << 21); + carry7 = s7 >> 21; + s8 += carry7; + s7 -= carry7 * ((uint64_t) 1L << 21); + carry8 = s8 >> 21; + s9 += carry8; + s8 -= carry8 * ((uint64_t) 1L << 21); + carry9 = s9 >> 21; + s10 += carry9; + s9 -= carry9 * ((uint64_t) 1L << 21); + carry10 = s10 >> 21; + s11 += carry10; + s10 -= carry10 * ((uint64_t) 1L << 21); + + s[0] = s0 >> 0; + s[1] = s0 >> 8; + s[2] = (s0 >> 16) | (s1 * ((uint64_t) 1 << 5)); + s[3] = s1 >> 3; + s[4] = s1 >> 11; + s[5] = (s1 >> 19) | (s2 * ((uint64_t) 1 << 2)); + s[6] = s2 >> 6; + s[7] = (s2 >> 14) | (s3 * ((uint64_t) 1 << 7)); + s[8] = s3 >> 1; + s[9] = s3 >> 9; + s[10] = (s3 >> 17) | (s4 * ((uint64_t) 1 << 4)); + s[11] = s4 >> 4; + s[12] = s4 >> 12; + s[13] = (s4 >> 20) | (s5 * ((uint64_t) 1 << 1)); + s[14] = s5 >> 7; + s[15] = (s5 >> 15) | (s6 * ((uint64_t) 1 << 6)); + s[16] = s6 >> 2; + s[17] = s6 >> 10; + s[18] = (s6 >> 18) | (s7 * ((uint64_t) 1 << 3)); + s[19] = s7 >> 5; + s[20] = s7 >> 13; + s[21] = s8 >> 0; + s[22] = s8 >> 8; + s[23] = (s8 >> 16) | (s9 * ((uint64_t) 1 << 5)); + s[24] = s9 >> 3; + s[25] = s9 >> 11; + s[26] = (s9 >> 19) | (s10 * ((uint64_t) 1 << 2)); + s[27] = s10 >> 6; + s[28] = (s10 >> 14) | (s11 * ((uint64_t) 1 << 7)); + s[29] = s11 >> 1; + s[30] = s11 >> 9; + s[31] = s11 >> 17; +} + +int +sc25519_is_canonical(const unsigned char s[32]) +{ + /* 2^252+27742317777372353535851937790883648493 */ + static const unsigned char L[32] = { + 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, + 0xa2, 0xde, 0xf9, 0xde, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10 + }; + unsigned char c = 0; + unsigned char n = 1; + unsigned int i = 32; + + do { + i--; + c |= ((s[i] - L[i]) >> 8) & n; + n &= ((s[i] ^ L[i]) - 1) >> 8; + } while (i != 0); + + return (c != 0); +} + +/* multiply by the cofactor */ +static void +ge25519_clear_cofactor(ge25519_p3 *p3) +{ + ge25519_p1p1 p1; + ge25519_p2 p2; + + ge25519_p3_dbl(&p1, p3); + ge25519_p1p1_to_p2(&p2, &p1); + ge25519_p2_dbl(&p1, &p2); + ge25519_p1p1_to_p2(&p2, &p1); + ge25519_p2_dbl(&p1, &p2); + ge25519_p1p1_to_p3(p3, &p1); +} + +static void +ge25519_elligator2(unsigned char s[32], const fe25519 r, const unsigned char x_sign) +{ + fe25519 gx; + fe25519 negx; + fe25519 rr2; + fe25519 x, x2, x3; + ge25519_p3 p3; + unsigned int notsquare; + + fe25519_sq2(rr2, r); + rr2[0]++; + fe25519_invert(rr2, rr2); + fe25519_mul32(x, rr2, curve25519_A[0]); + fe25519_neg(x, x); + + fe25519_sq(x2, x); + fe25519_mul(x3, x, x2); + fe25519_add(gx, x3, x); + fe25519_mul32(x2, x2, curve25519_A[0]); + fe25519_add(gx, x2, gx); + + notsquare = fe25519_notsquare(gx); + fe25519_neg(negx, x); + fe25519_cmov(x, negx, notsquare); + fe25519_0(x2); + fe25519_cmov(x2, curve25519_A, notsquare); + fe25519_sub(x, x, x2); + + /* yed = (x-1)/(x+1) */ + { + fe25519 one; + fe25519 x_plus_one; + fe25519 x_plus_one_inv; + fe25519 x_minus_one; + fe25519 yed; + + fe25519_1(one); + fe25519_add(x_plus_one, x, one); + fe25519_sub(x_minus_one, x, one); + fe25519_invert(x_plus_one_inv, x_plus_one); + fe25519_mul(yed, x_minus_one, x_plus_one_inv); + fe25519_tobytes(s, yed); + } + + /* recover x */ + s[31] |= x_sign; + if (ge25519_frombytes(&p3, s) != 0) { + abort(); /* LCOV_EXCL_LINE */ + } + + ge25519_clear_cofactor(&p3); + ge25519_p3_tobytes(s, &p3); +} + +void +ge25519_from_uniform(unsigned char s[32], const unsigned char r[32]) +{ + fe25519 r_fe; + unsigned char x_sign; + + memcpy(s, r, 32); + x_sign = s[31] & 0x80; + s[31] &= 0x7f; + fe25519_frombytes(r_fe, s); + ge25519_elligator2(s, r_fe, x_sign); +} + +void +ge25519_from_hash(unsigned char s[32], const unsigned char h[64]) +{ + unsigned char fl[32]; + unsigned char gl[32]; + fe25519 fe_f; + fe25519 fe_g; + size_t i; + unsigned char x_sign; + + x_sign = h[0] & 0x80; + for (i = 0; i < 32; i++) { + fl[i] = h[63 - i]; + gl[i] = h[31 - i]; + } + fl[31] &= 0x7f; + gl[31] &= 0x7f; + fe25519_frombytes(fe_f, fl); + fe25519_frombytes(fe_g, gl); + fe_f[0] += (h[32] >> 7) * 19; + for (i = 0; i < sizeof (fe25519) / sizeof fe_f[0]; i++) { + fe_f[i] += 38 * fe_g[i]; + } + fe25519_reduce(fe_f, fe_f); + ge25519_elligator2(s, fe_f, x_sign); +} + +/* Ristretto group */ + +static int +ristretto255_sqrt_ratio_m1(fe25519 x, const fe25519 u, const fe25519 v) +{ + fe25519 v3; + fe25519 vxx; + fe25519 m_root_check, p_root_check, f_root_check; + fe25519 x_sqrtm1; + int has_m_root, has_p_root, has_f_root; + + fe25519_sq(v3, v); + fe25519_mul(v3, v3, v); /* v3 = v^3 */ + fe25519_sq(x, v3); + fe25519_mul(x, x, v); + fe25519_mul(x, x, u); /* x = uv^7 */ + + fe25519_pow22523(x, x); /* x = (uv^7)^((q-5)/8) */ + fe25519_mul(x, x, v3); + fe25519_mul(x, x, u); /* x = uv^3(uv^7)^((q-5)/8) */ + + fe25519_sq(vxx, x); + fe25519_mul(vxx, vxx, v); /* vx^2 */ + fe25519_sub(m_root_check, vxx, u); /* vx^2-u */ + fe25519_add(p_root_check, vxx, u); /* vx^2+u */ + fe25519_mul(f_root_check, u, sqrtm1); /* u*sqrt(-1) */ + fe25519_add(f_root_check, vxx, f_root_check); /* vx^2+u*sqrt(-1) */ + has_m_root = fe25519_iszero(m_root_check); + has_p_root = fe25519_iszero(p_root_check); + has_f_root = fe25519_iszero(f_root_check); + fe25519_mul(x_sqrtm1, x, sqrtm1); /* x*sqrt(-1) */ + + fe25519_cmov(x, x_sqrtm1, has_p_root | has_f_root); + fe25519_abs(x, x); + + return has_m_root | has_p_root; +} + +static int +ristretto255_is_canonical(const unsigned char *s) +{ + unsigned char c; + unsigned char d; + unsigned char e; + unsigned int i; + + c = (s[31] & 0x7f) ^ 0x7f; + for (i = 30; i > 0; i--) { + c |= s[i] ^ 0xff; + } + c = (((unsigned int) c) - 1U) >> 8; + d = (0xed - 1U - (unsigned int) s[0]) >> 8; + e = s[31] >> 7; + + return 1 - (((c & d) | e | s[0]) & 1); +} + +int +ristretto255_frombytes(ge25519_p3 *h, const unsigned char *s) +{ + fe25519 inv_sqrt; + fe25519 one; + fe25519 s_; + fe25519 ss; + fe25519 u1, u2; + fe25519 u1u1, u2u2; + fe25519 v; + fe25519 v_u2u2; + int was_square; + + if (ristretto255_is_canonical(s) == 0) { + return -1; + } + fe25519_frombytes(s_, s); + fe25519_sq(ss, s_); /* ss = s^2 */ + + fe25519_1(u1); + fe25519_sub(u1, u1, ss); /* u1 = 1-ss */ + fe25519_sq(u1u1, u1); /* u1u1 = u1^2 */ + + fe25519_1(u2); + fe25519_add(u2, u2, ss); /* u2 = 1+ss */ + fe25519_sq(u2u2, u2); /* u2u2 = u2^2 */ + + fe25519_mul(v, d, u1u1); /* v = d*u1^2 */ + fe25519_neg(v, v); /* v = -d*u1^2 */ + fe25519_sub(v, v, u2u2); /* v = -(d*u1^2)-u2^2 */ + + fe25519_mul(v_u2u2, v, u2u2); /* v_u2u2 = v*u2^2 */ + + fe25519_1(one); + was_square = ristretto255_sqrt_ratio_m1(inv_sqrt, one, v_u2u2); + fe25519_mul(h->X, inv_sqrt, u2); + fe25519_mul(h->Y, inv_sqrt, h->X); + fe25519_mul(h->Y, h->Y, v); + + fe25519_mul(h->X, h->X, s_); + fe25519_add(h->X, h->X, h->X); + fe25519_abs(h->X, h->X); + fe25519_mul(h->Y, u1, h->Y); + fe25519_1(h->Z); + fe25519_mul(h->T, h->X, h->Y); + + return - ((1 - was_square) | + fe25519_isnegative(h->T) | fe25519_iszero(h->Y)); +} + +void +ristretto255_p3_tobytes(unsigned char *s, const ge25519_p3 *h) +{ + fe25519 den1, den2; + fe25519 den_inv; + fe25519 eden; + fe25519 inv_sqrt; + fe25519 ix, iy; + fe25519 one; + fe25519 s_; + fe25519 t_z_inv; + fe25519 u1, u2; + fe25519 u1_u2u2; + fe25519 x_, y_; + fe25519 x_z_inv; + fe25519 z_inv; + fe25519 zmy; + int rotate; + + fe25519_add(u1, h->Z, h->Y); /* u1 = Z+Y */ + fe25519_sub(zmy, h->Z, h->Y); /* zmy = Z-Y */ + fe25519_mul(u1, u1, zmy); /* u1 = (Z+Y)*(Z-Y) */ + fe25519_mul(u2, h->X, h->Y); /* u2 = X*Y */ + + fe25519_sq(u1_u2u2, u2); /* u1_u2u2 = u2^2 */ + fe25519_mul(u1_u2u2, u1, u1_u2u2); /* u1_u2u2 = u1*u2^2 */ + + fe25519_1(one); + (void) ristretto255_sqrt_ratio_m1(inv_sqrt, one, u1_u2u2); + fe25519_mul(den1, inv_sqrt, u1); /* den1 = inv_sqrt*u1 */ + fe25519_mul(den2, inv_sqrt, u2); /* den2 = inv_sqrt*u2 */ + fe25519_mul(z_inv, den1, den2); /* z_inv = den1*den2 */ + fe25519_mul(z_inv, z_inv, h->T); /* z_inv = den1*den2*T */ + + fe25519_mul(ix, h->X, sqrtm1); /* ix = X*sqrt(-1) */ + fe25519_mul(iy, h->Y, sqrtm1); /* iy = Y*sqrt(-1) */ + fe25519_mul(eden, den1, invsqrtamd); /* eden = den1/sqrt(a-d) */ + + fe25519_mul(t_z_inv, h->T, z_inv); /* t_z_inv = T*z_inv */ + rotate = fe25519_isnegative(t_z_inv); + + fe25519_copy(x_, h->X); + fe25519_copy(y_, h->Y); + fe25519_copy(den_inv, den2); + + fe25519_cmov(x_, iy, rotate); + fe25519_cmov(y_, ix, rotate); + fe25519_cmov(den_inv, eden, rotate); + + fe25519_mul(x_z_inv, x_, z_inv); + fe25519_cneg(y_, y_, fe25519_isnegative(x_z_inv)); + + fe25519_sub(s_, h->Z, y_); + fe25519_mul(s_, den_inv, s_); + fe25519_abs(s_, s_); + fe25519_tobytes(s, s_); +} + +static void +ristretto255_elligator(ge25519_p3 *p, const fe25519 t) +{ + fe25519 c; + fe25519 n; + fe25519 one; + fe25519 r; + fe25519 rpd; + fe25519 s, s_prime; + fe25519 ss; + fe25519 u, v; + fe25519 w0, w1, w2, w3; + int wasnt_square; + + fe25519_1(one); + fe25519_sq(r, t); /* r = t^2 */ + fe25519_mul(r, sqrtm1, r); /* r = sqrt(-1)*t^2 */ + fe25519_add(u, r, one); /* u = r+1 */ + fe25519_mul(u, u, onemsqd); /* u = (r+1)*(1-d^2) */ + fe25519_1(c); + fe25519_neg(c, c); /* c = -1 */ + fe25519_add(rpd, r, d); /* rpd = r+d */ + fe25519_mul(v, r, d); /* v = r*d */ + fe25519_sub(v, c, v); /* v = c-r*d */ + fe25519_mul(v, v, rpd); /* v = (c-r*d)*(r+d) */ + + wasnt_square = 1 - ristretto255_sqrt_ratio_m1(s, u, v); + fe25519_mul(s_prime, s, t); + fe25519_abs(s_prime, s_prime); + fe25519_neg(s_prime, s_prime); /* s_prime = -|s*t| */ + fe25519_cmov(s, s_prime, wasnt_square); + fe25519_cmov(c, r, wasnt_square); + + fe25519_sub(n, r, one); /* n = r-1 */ + fe25519_mul(n, n, c); /* n = c*(r-1) */ + fe25519_mul(n, n, sqdmone); /* n = c*(r-1)*(d-1)^2 */ + fe25519_sub(n, n, v); /* n = c*(r-1)*(d-1)^2-v */ + + fe25519_add(w0, s, s); /* w0 = 2s */ + fe25519_mul(w0, w0, v); /* w0 = 2s*v */ + fe25519_mul(w1, n, sqrtadm1); /* w1 = n*sqrt(ad-1) */ + fe25519_sq(ss, s); /* ss = s^2 */ + fe25519_sub(w2, one, ss); /* w2 = 1-s^2 */ + fe25519_add(w3, one, ss); /* w3 = 1+s^2 */ + + fe25519_mul(p->X, w0, w3); + fe25519_mul(p->Y, w2, w1); + fe25519_mul(p->Z, w1, w3); + fe25519_mul(p->T, w0, w2); +} + +void +ristretto255_from_hash(unsigned char s[32], const unsigned char h[64]) +{ + fe25519 r0, r1; + ge25519_cached p1_cached; + ge25519_p1p1 p_p1p1; + ge25519_p3 p0, p1; + ge25519_p3 p; + + fe25519_frombytes(r0, h); + fe25519_frombytes(r1, h + 32); + ristretto255_elligator(&p0, r0); + ristretto255_elligator(&p1, r1); + ge25519_p3_to_cached(&p1_cached, &p1); + ge25519_add(&p_p1p1, &p0, &p1_cached); + ge25519_p1p1_to_p3(&p, &p_p1p1); + ristretto255_p3_tobytes(s, &p); +} diff --git a/packages/runtime/vendor/libsodium/ed25519_ref10.h b/packages/runtime/vendor/libsodium/ed25519_ref10.h new file mode 100644 index 000000000..3f4c45caf --- /dev/null +++ b/packages/runtime/vendor/libsodium/ed25519_ref10.h @@ -0,0 +1,142 @@ +#ifndef ed25519_ref10_H +#define ed25519_ref10_H + +#include +#include + +/* + fe means field element. + Here the field is \Z/(2^255-19). + */ + +#ifdef HAVE_TI_MODE +typedef uint64_t fe25519[5]; +#else +typedef int32_t fe25519[10]; +#endif + +void fe25519_invert(fe25519 out, const fe25519 z); +void fe25519_frombytes(fe25519 h, const unsigned char *s); +void fe25519_tobytes(unsigned char *s, const fe25519 h); + +#ifdef HAVE_TI_MODE +# include "ed25519_ref10_fe_51.h" +#else +# include "ed25519_ref10_fe_25_5.h" +#endif + + +/* + ge means group element. + + Here the group is the set of pairs (x,y) of field elements + satisfying -x^2 + y^2 = 1 + d x^2y^2 + where d = -121665/121666. + + Representations: + ge25519_p2 (projective): (X:Y:Z) satisfying x=X/Z, y=Y/Z + ge25519_p3 (extended): (X:Y:Z:T) satisfying x=X/Z, y=Y/Z, XY=ZT + ge25519_p1p1 (completed): ((X:Z),(Y:T)) satisfying x=X/Z, y=Y/T + ge25519_precomp (Duif): (y+x,y-x,2dxy) + */ + +typedef struct { + fe25519 X; + fe25519 Y; + fe25519 Z; +} ge25519_p2; + +typedef struct { + fe25519 X; + fe25519 Y; + fe25519 Z; + fe25519 T; +} ge25519_p3; + +typedef struct { + fe25519 X; + fe25519 Y; + fe25519 Z; + fe25519 T; +} ge25519_p1p1; + +typedef struct { + fe25519 yplusx; + fe25519 yminusx; + fe25519 xy2d; +} ge25519_precomp; + +typedef struct { + fe25519 YplusX; + fe25519 YminusX; + fe25519 Z; + fe25519 T2d; +} ge25519_cached; + +void ge25519_tobytes(unsigned char *s, const ge25519_p2 *h); + +void ge25519_p3_tobytes(unsigned char *s, const ge25519_p3 *h); + +int ge25519_frombytes(ge25519_p3 *h, const unsigned char *s); + +int ge25519_frombytes_negate_vartime(ge25519_p3 *h, const unsigned char *s); + +void ge25519_p3_to_cached(ge25519_cached *r, const ge25519_p3 *p); + +void ge25519_p1p1_to_p2(ge25519_p2 *r, const ge25519_p1p1 *p); + +void ge25519_p1p1_to_p3(ge25519_p3 *r, const ge25519_p1p1 *p); + +void ge25519_add(ge25519_p1p1 *r, const ge25519_p3 *p, const ge25519_cached *q); + +void ge25519_sub(ge25519_p1p1 *r, const ge25519_p3 *p, const ge25519_cached *q); + +void ge25519_scalarmult_base(ge25519_p3 *h, const unsigned char *a); + +void ge25519_double_scalarmult_vartime(ge25519_p2 *r, const unsigned char *a, + const ge25519_p3 *A, + const unsigned char *b); + +void ge25519_scalarmult(ge25519_p3 *h, const unsigned char *a, + const ge25519_p3 *p); + +int ge25519_is_canonical(const unsigned char *s); + +int ge25519_is_on_curve(const ge25519_p3 *p); + +int ge25519_is_on_main_subgroup(const ge25519_p3 *p); + +int ge25519_has_small_order(const unsigned char s[32]); + +void ge25519_from_uniform(unsigned char s[32], const unsigned char r[32]); + +void ge25519_from_hash(unsigned char s[32], const unsigned char h[64]); + +/* + Ristretto group + */ + +int ristretto255_frombytes(ge25519_p3 *h, const unsigned char *s); + +void ristretto255_p3_tobytes(unsigned char *s, const ge25519_p3 *h); + +void ristretto255_from_hash(unsigned char s[32], const unsigned char h[64]); + +/* + The set of scalars is \Z/l + where l = 2^252 + 27742317777372353535851937790883648493. + */ + +void sc25519_invert(unsigned char recip[32], const unsigned char s[32]); + +void sc25519_reduce(unsigned char s[64]); + +void sc25519_mul(unsigned char s[32], const unsigned char a[32], + const unsigned char b[32]); + +void sc25519_muladd(unsigned char s[32], const unsigned char a[32], + const unsigned char b[32], const unsigned char c[32]); + +int sc25519_is_canonical(const unsigned char s[32]); + +#endif diff --git a/packages/runtime/vendor/libsodium/ed25519_ref10_fe_25_5.h b/packages/runtime/vendor/libsodium/ed25519_ref10_fe_25_5.h new file mode 100644 index 000000000..a0816b219 --- /dev/null +++ b/packages/runtime/vendor/libsodium/ed25519_ref10_fe_25_5.h @@ -0,0 +1,1030 @@ +#include + +#include "common.h" +#include "utils.h" + +/* + h = 0 + */ + +static inline void +fe25519_0(fe25519 h) +{ + memset(&h[0], 0, 10 * sizeof h[0]); +} + +/* + h = 1 + */ + +static inline void +fe25519_1(fe25519 h) +{ + h[0] = 1; + h[1] = 0; + memset(&h[2], 0, 8 * sizeof h[0]); +} + +/* + h = f + g + Can overlap h with f or g. + * + Preconditions: + |f| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. + |g| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. + * + Postconditions: + |h| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. + */ + +static inline void +fe25519_add(fe25519 h, const fe25519 f, const fe25519 g) +{ + int32_t h0 = f[0] + g[0]; + int32_t h1 = f[1] + g[1]; + int32_t h2 = f[2] + g[2]; + int32_t h3 = f[3] + g[3]; + int32_t h4 = f[4] + g[4]; + int32_t h5 = f[5] + g[5]; + int32_t h6 = f[6] + g[6]; + int32_t h7 = f[7] + g[7]; + int32_t h8 = f[8] + g[8]; + int32_t h9 = f[9] + g[9]; + + h[0] = h0; + h[1] = h1; + h[2] = h2; + h[3] = h3; + h[4] = h4; + h[5] = h5; + h[6] = h6; + h[7] = h7; + h[8] = h8; + h[9] = h9; +} + +/* + h = f - g + Can overlap h with f or g. + * + Preconditions: + |f| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. + |g| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. + * + Postconditions: + |h| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. + */ + +static void +fe25519_sub(fe25519 h, const fe25519 f, const fe25519 g) +{ + int32_t h0 = f[0] - g[0]; + int32_t h1 = f[1] - g[1]; + int32_t h2 = f[2] - g[2]; + int32_t h3 = f[3] - g[3]; + int32_t h4 = f[4] - g[4]; + int32_t h5 = f[5] - g[5]; + int32_t h6 = f[6] - g[6]; + int32_t h7 = f[7] - g[7]; + int32_t h8 = f[8] - g[8]; + int32_t h9 = f[9] - g[9]; + + h[0] = h0; + h[1] = h1; + h[2] = h2; + h[3] = h3; + h[4] = h4; + h[5] = h5; + h[6] = h6; + h[7] = h7; + h[8] = h8; + h[9] = h9; +} + +/* + h = -f + * + Preconditions: + |f| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. + * + Postconditions: + |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. + */ + +static inline void +fe25519_neg(fe25519 h, const fe25519 f) +{ + int32_t h0 = -f[0]; + int32_t h1 = -f[1]; + int32_t h2 = -f[2]; + int32_t h3 = -f[3]; + int32_t h4 = -f[4]; + int32_t h5 = -f[5]; + int32_t h6 = -f[6]; + int32_t h7 = -f[7]; + int32_t h8 = -f[8]; + int32_t h9 = -f[9]; + + h[0] = h0; + h[1] = h1; + h[2] = h2; + h[3] = h3; + h[4] = h4; + h[5] = h5; + h[6] = h6; + h[7] = h7; + h[8] = h8; + h[9] = h9; +} + +/* + Replace (f,g) with (g,g) if b == 1; + replace (f,g) with (f,g) if b == 0. + * + Preconditions: b in {0,1}. + */ + +static void +fe25519_cmov(fe25519 f, const fe25519 g, unsigned int b) +{ + const uint32_t mask = (uint32_t) (-(int32_t) b); + + int32_t f0 = f[0]; + int32_t f1 = f[1]; + int32_t f2 = f[2]; + int32_t f3 = f[3]; + int32_t f4 = f[4]; + int32_t f5 = f[5]; + int32_t f6 = f[6]; + int32_t f7 = f[7]; + int32_t f8 = f[8]; + int32_t f9 = f[9]; + + int32_t x0 = f0 ^ g[0]; + int32_t x1 = f1 ^ g[1]; + int32_t x2 = f2 ^ g[2]; + int32_t x3 = f3 ^ g[3]; + int32_t x4 = f4 ^ g[4]; + int32_t x5 = f5 ^ g[5]; + int32_t x6 = f6 ^ g[6]; + int32_t x7 = f7 ^ g[7]; + int32_t x8 = f8 ^ g[8]; + int32_t x9 = f9 ^ g[9]; + + x0 &= mask; + x1 &= mask; + x2 &= mask; + x3 &= mask; + x4 &= mask; + x5 &= mask; + x6 &= mask; + x7 &= mask; + x8 &= mask; + x9 &= mask; + + f[0] = f0 ^ x0; + f[1] = f1 ^ x1; + f[2] = f2 ^ x2; + f[3] = f3 ^ x3; + f[4] = f4 ^ x4; + f[5] = f5 ^ x5; + f[6] = f6 ^ x6; + f[7] = f7 ^ x7; + f[8] = f8 ^ x8; + f[9] = f9 ^ x9; +} + +static void +fe25519_cswap(fe25519 f, fe25519 g, unsigned int b) +{ + const uint32_t mask = (uint32_t) (-(int64_t) b); + + int32_t f0 = f[0]; + int32_t f1 = f[1]; + int32_t f2 = f[2]; + int32_t f3 = f[3]; + int32_t f4 = f[4]; + int32_t f5 = f[5]; + int32_t f6 = f[6]; + int32_t f7 = f[7]; + int32_t f8 = f[8]; + int32_t f9 = f[9]; + + int32_t g0 = g[0]; + int32_t g1 = g[1]; + int32_t g2 = g[2]; + int32_t g3 = g[3]; + int32_t g4 = g[4]; + int32_t g5 = g[5]; + int32_t g6 = g[6]; + int32_t g7 = g[7]; + int32_t g8 = g[8]; + int32_t g9 = g[9]; + + int32_t x0 = f0 ^ g0; + int32_t x1 = f1 ^ g1; + int32_t x2 = f2 ^ g2; + int32_t x3 = f3 ^ g3; + int32_t x4 = f4 ^ g4; + int32_t x5 = f5 ^ g5; + int32_t x6 = f6 ^ g6; + int32_t x7 = f7 ^ g7; + int32_t x8 = f8 ^ g8; + int32_t x9 = f9 ^ g9; + + x0 &= mask; + x1 &= mask; + x2 &= mask; + x3 &= mask; + x4 &= mask; + x5 &= mask; + x6 &= mask; + x7 &= mask; + x8 &= mask; + x9 &= mask; + + f[0] = f0 ^ x0; + f[1] = f1 ^ x1; + f[2] = f2 ^ x2; + f[3] = f3 ^ x3; + f[4] = f4 ^ x4; + f[5] = f5 ^ x5; + f[6] = f6 ^ x6; + f[7] = f7 ^ x7; + f[8] = f8 ^ x8; + f[9] = f9 ^ x9; + + g[0] = g0 ^ x0; + g[1] = g1 ^ x1; + g[2] = g2 ^ x2; + g[3] = g3 ^ x3; + g[4] = g4 ^ x4; + g[5] = g5 ^ x5; + g[6] = g6 ^ x6; + g[7] = g7 ^ x7; + g[8] = g8 ^ x8; + g[9] = g9 ^ x9; +} + +/* + h = f + */ + +static inline void +fe25519_copy(fe25519 h, const fe25519 f) +{ + memcpy(h, f, 10 * sizeof h[0]); +} + +/* + return 1 if f is in {1,3,5,...,q-2} + return 0 if f is in {0,2,4,...,q-1} + + Preconditions: + |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. + */ + +static inline int +fe25519_isnegative(const fe25519 f) +{ + unsigned char s[32]; + + fe25519_tobytes(s, f); + + return s[0] & 1; +} + +/* + return 1 if f == 0 + return 0 if f != 0 + + Preconditions: + |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. + */ + +static inline int +fe25519_iszero(const fe25519 f) +{ + unsigned char s[32]; + + fe25519_tobytes(s, f); + + return sodium_is_zero(s, 32); +} + +/* + h = f * g + Can overlap h with f or g. + * + Preconditions: + |f| bounded by 1.65*2^26,1.65*2^25,1.65*2^26,1.65*2^25,etc. + |g| bounded by 1.65*2^26,1.65*2^25,1.65*2^26,1.65*2^25,etc. + * + Postconditions: + |h| bounded by 1.01*2^25,1.01*2^24,1.01*2^25,1.01*2^24,etc. + */ + +/* + Notes on implementation strategy: + * + Using schoolbook multiplication. + Karatsuba would save a little in some cost models. + * + Most multiplications by 2 and 19 are 32-bit precomputations; + cheaper than 64-bit postcomputations. + * + There is one remaining multiplication by 19 in the carry chain; + one *19 precomputation can be merged into this, + but the resulting data flow is considerably less clean. + * + There are 12 carries below. + 10 of them are 2-way parallelizable and vectorizable. + Can get away with 11 carries, but then data flow is much deeper. + * + With tighter constraints on inputs can squeeze carries into int32. + */ + +static void +fe25519_mul(fe25519 h, const fe25519 f, const fe25519 g) +{ + int32_t f0 = f[0]; + int32_t f1 = f[1]; + int32_t f2 = f[2]; + int32_t f3 = f[3]; + int32_t f4 = f[4]; + int32_t f5 = f[5]; + int32_t f6 = f[6]; + int32_t f7 = f[7]; + int32_t f8 = f[8]; + int32_t f9 = f[9]; + + int32_t g0 = g[0]; + int32_t g1 = g[1]; + int32_t g2 = g[2]; + int32_t g3 = g[3]; + int32_t g4 = g[4]; + int32_t g5 = g[5]; + int32_t g6 = g[6]; + int32_t g7 = g[7]; + int32_t g8 = g[8]; + int32_t g9 = g[9]; + + int32_t g1_19 = 19 * g1; /* 1.959375*2^29 */ + int32_t g2_19 = 19 * g2; /* 1.959375*2^30; still ok */ + int32_t g3_19 = 19 * g3; + int32_t g4_19 = 19 * g4; + int32_t g5_19 = 19 * g5; + int32_t g6_19 = 19 * g6; + int32_t g7_19 = 19 * g7; + int32_t g8_19 = 19 * g8; + int32_t g9_19 = 19 * g9; + int32_t f1_2 = 2 * f1; + int32_t f3_2 = 2 * f3; + int32_t f5_2 = 2 * f5; + int32_t f7_2 = 2 * f7; + int32_t f9_2 = 2 * f9; + + int64_t f0g0 = f0 * (int64_t) g0; + int64_t f0g1 = f0 * (int64_t) g1; + int64_t f0g2 = f0 * (int64_t) g2; + int64_t f0g3 = f0 * (int64_t) g3; + int64_t f0g4 = f0 * (int64_t) g4; + int64_t f0g5 = f0 * (int64_t) g5; + int64_t f0g6 = f0 * (int64_t) g6; + int64_t f0g7 = f0 * (int64_t) g7; + int64_t f0g8 = f0 * (int64_t) g8; + int64_t f0g9 = f0 * (int64_t) g9; + int64_t f1g0 = f1 * (int64_t) g0; + int64_t f1g1_2 = f1_2 * (int64_t) g1; + int64_t f1g2 = f1 * (int64_t) g2; + int64_t f1g3_2 = f1_2 * (int64_t) g3; + int64_t f1g4 = f1 * (int64_t) g4; + int64_t f1g5_2 = f1_2 * (int64_t) g5; + int64_t f1g6 = f1 * (int64_t) g6; + int64_t f1g7_2 = f1_2 * (int64_t) g7; + int64_t f1g8 = f1 * (int64_t) g8; + int64_t f1g9_38 = f1_2 * (int64_t) g9_19; + int64_t f2g0 = f2 * (int64_t) g0; + int64_t f2g1 = f2 * (int64_t) g1; + int64_t f2g2 = f2 * (int64_t) g2; + int64_t f2g3 = f2 * (int64_t) g3; + int64_t f2g4 = f2 * (int64_t) g4; + int64_t f2g5 = f2 * (int64_t) g5; + int64_t f2g6 = f2 * (int64_t) g6; + int64_t f2g7 = f2 * (int64_t) g7; + int64_t f2g8_19 = f2 * (int64_t) g8_19; + int64_t f2g9_19 = f2 * (int64_t) g9_19; + int64_t f3g0 = f3 * (int64_t) g0; + int64_t f3g1_2 = f3_2 * (int64_t) g1; + int64_t f3g2 = f3 * (int64_t) g2; + int64_t f3g3_2 = f3_2 * (int64_t) g3; + int64_t f3g4 = f3 * (int64_t) g4; + int64_t f3g5_2 = f3_2 * (int64_t) g5; + int64_t f3g6 = f3 * (int64_t) g6; + int64_t f3g7_38 = f3_2 * (int64_t) g7_19; + int64_t f3g8_19 = f3 * (int64_t) g8_19; + int64_t f3g9_38 = f3_2 * (int64_t) g9_19; + int64_t f4g0 = f4 * (int64_t) g0; + int64_t f4g1 = f4 * (int64_t) g1; + int64_t f4g2 = f4 * (int64_t) g2; + int64_t f4g3 = f4 * (int64_t) g3; + int64_t f4g4 = f4 * (int64_t) g4; + int64_t f4g5 = f4 * (int64_t) g5; + int64_t f4g6_19 = f4 * (int64_t) g6_19; + int64_t f4g7_19 = f4 * (int64_t) g7_19; + int64_t f4g8_19 = f4 * (int64_t) g8_19; + int64_t f4g9_19 = f4 * (int64_t) g9_19; + int64_t f5g0 = f5 * (int64_t) g0; + int64_t f5g1_2 = f5_2 * (int64_t) g1; + int64_t f5g2 = f5 * (int64_t) g2; + int64_t f5g3_2 = f5_2 * (int64_t) g3; + int64_t f5g4 = f5 * (int64_t) g4; + int64_t f5g5_38 = f5_2 * (int64_t) g5_19; + int64_t f5g6_19 = f5 * (int64_t) g6_19; + int64_t f5g7_38 = f5_2 * (int64_t) g7_19; + int64_t f5g8_19 = f5 * (int64_t) g8_19; + int64_t f5g9_38 = f5_2 * (int64_t) g9_19; + int64_t f6g0 = f6 * (int64_t) g0; + int64_t f6g1 = f6 * (int64_t) g1; + int64_t f6g2 = f6 * (int64_t) g2; + int64_t f6g3 = f6 * (int64_t) g3; + int64_t f6g4_19 = f6 * (int64_t) g4_19; + int64_t f6g5_19 = f6 * (int64_t) g5_19; + int64_t f6g6_19 = f6 * (int64_t) g6_19; + int64_t f6g7_19 = f6 * (int64_t) g7_19; + int64_t f6g8_19 = f6 * (int64_t) g8_19; + int64_t f6g9_19 = f6 * (int64_t) g9_19; + int64_t f7g0 = f7 * (int64_t) g0; + int64_t f7g1_2 = f7_2 * (int64_t) g1; + int64_t f7g2 = f7 * (int64_t) g2; + int64_t f7g3_38 = f7_2 * (int64_t) g3_19; + int64_t f7g4_19 = f7 * (int64_t) g4_19; + int64_t f7g5_38 = f7_2 * (int64_t) g5_19; + int64_t f7g6_19 = f7 * (int64_t) g6_19; + int64_t f7g7_38 = f7_2 * (int64_t) g7_19; + int64_t f7g8_19 = f7 * (int64_t) g8_19; + int64_t f7g9_38 = f7_2 * (int64_t) g9_19; + int64_t f8g0 = f8 * (int64_t) g0; + int64_t f8g1 = f8 * (int64_t) g1; + int64_t f8g2_19 = f8 * (int64_t) g2_19; + int64_t f8g3_19 = f8 * (int64_t) g3_19; + int64_t f8g4_19 = f8 * (int64_t) g4_19; + int64_t f8g5_19 = f8 * (int64_t) g5_19; + int64_t f8g6_19 = f8 * (int64_t) g6_19; + int64_t f8g7_19 = f8 * (int64_t) g7_19; + int64_t f8g8_19 = f8 * (int64_t) g8_19; + int64_t f8g9_19 = f8 * (int64_t) g9_19; + int64_t f9g0 = f9 * (int64_t) g0; + int64_t f9g1_38 = f9_2 * (int64_t) g1_19; + int64_t f9g2_19 = f9 * (int64_t) g2_19; + int64_t f9g3_38 = f9_2 * (int64_t) g3_19; + int64_t f9g4_19 = f9 * (int64_t) g4_19; + int64_t f9g5_38 = f9_2 * (int64_t) g5_19; + int64_t f9g6_19 = f9 * (int64_t) g6_19; + int64_t f9g7_38 = f9_2 * (int64_t) g7_19; + int64_t f9g8_19 = f9 * (int64_t) g8_19; + int64_t f9g9_38 = f9_2 * (int64_t) g9_19; + + int64_t h0 = f0g0 + f1g9_38 + f2g8_19 + f3g7_38 + f4g6_19 + f5g5_38 + + f6g4_19 + f7g3_38 + f8g2_19 + f9g1_38; + int64_t h1 = f0g1 + f1g0 + f2g9_19 + f3g8_19 + f4g7_19 + f5g6_19 + f6g5_19 + + f7g4_19 + f8g3_19 + f9g2_19; + int64_t h2 = f0g2 + f1g1_2 + f2g0 + f3g9_38 + f4g8_19 + f5g7_38 + f6g6_19 + + f7g5_38 + f8g4_19 + f9g3_38; + int64_t h3 = f0g3 + f1g2 + f2g1 + f3g0 + f4g9_19 + f5g8_19 + f6g7_19 + + f7g6_19 + f8g5_19 + f9g4_19; + int64_t h4 = f0g4 + f1g3_2 + f2g2 + f3g1_2 + f4g0 + f5g9_38 + f6g8_19 + + f7g7_38 + f8g6_19 + f9g5_38; + int64_t h5 = f0g5 + f1g4 + f2g3 + f3g2 + f4g1 + f5g0 + f6g9_19 + f7g8_19 + + f8g7_19 + f9g6_19; + int64_t h6 = f0g6 + f1g5_2 + f2g4 + f3g3_2 + f4g2 + f5g1_2 + f6g0 + + f7g9_38 + f8g8_19 + f9g7_38; + int64_t h7 = f0g7 + f1g6 + f2g5 + f3g4 + f4g3 + f5g2 + f6g1 + f7g0 + + f8g9_19 + f9g8_19; + int64_t h8 = f0g8 + f1g7_2 + f2g6 + f3g5_2 + f4g4 + f5g3_2 + f6g2 + f7g1_2 + + f8g0 + f9g9_38; + int64_t h9 = + f0g9 + f1g8 + f2g7 + f3g6 + f4g5 + f5g4 + f6g3 + f7g2 + f8g1 + f9g0; + + int64_t carry0; + int64_t carry1; + int64_t carry2; + int64_t carry3; + int64_t carry4; + int64_t carry5; + int64_t carry6; + int64_t carry7; + int64_t carry8; + int64_t carry9; + + /* + |h0| <= (1.65*1.65*2^52*(1+19+19+19+19)+1.65*1.65*2^50*(38+38+38+38+38)) + i.e. |h0| <= 1.4*2^60; narrower ranges for h2, h4, h6, h8 + |h1| <= (1.65*1.65*2^51*(1+1+19+19+19+19+19+19+19+19)) + i.e. |h1| <= 1.7*2^59; narrower ranges for h3, h5, h7, h9 + */ + + carry0 = (h0 + (int64_t)(1L << 25)) >> 26; + h1 += carry0; + h0 -= carry0 * ((uint64_t) 1L << 26); + carry4 = (h4 + (int64_t)(1L << 25)) >> 26; + h5 += carry4; + h4 -= carry4 * ((uint64_t) 1L << 26); + /* |h0| <= 2^25 */ + /* |h4| <= 2^25 */ + /* |h1| <= 1.71*2^59 */ + /* |h5| <= 1.71*2^59 */ + + carry1 = (h1 + (int64_t)(1L << 24)) >> 25; + h2 += carry1; + h1 -= carry1 * ((uint64_t) 1L << 25); + carry5 = (h5 + (int64_t)(1L << 24)) >> 25; + h6 += carry5; + h5 -= carry5 * ((uint64_t) 1L << 25); + /* |h1| <= 2^24; from now on fits into int32 */ + /* |h5| <= 2^24; from now on fits into int32 */ + /* |h2| <= 1.41*2^60 */ + /* |h6| <= 1.41*2^60 */ + + carry2 = (h2 + (int64_t)(1L << 25)) >> 26; + h3 += carry2; + h2 -= carry2 * ((uint64_t) 1L << 26); + carry6 = (h6 + (int64_t)(1L << 25)) >> 26; + h7 += carry6; + h6 -= carry6 * ((uint64_t) 1L << 26); + /* |h2| <= 2^25; from now on fits into int32 unchanged */ + /* |h6| <= 2^25; from now on fits into int32 unchanged */ + /* |h3| <= 1.71*2^59 */ + /* |h7| <= 1.71*2^59 */ + + carry3 = (h3 + (int64_t)(1L << 24)) >> 25; + h4 += carry3; + h3 -= carry3 * ((uint64_t) 1L << 25); + carry7 = (h7 + (int64_t)(1L << 24)) >> 25; + h8 += carry7; + h7 -= carry7 * ((uint64_t) 1L << 25); + /* |h3| <= 2^24; from now on fits into int32 unchanged */ + /* |h7| <= 2^24; from now on fits into int32 unchanged */ + /* |h4| <= 1.72*2^34 */ + /* |h8| <= 1.41*2^60 */ + + carry4 = (h4 + (int64_t)(1L << 25)) >> 26; + h5 += carry4; + h4 -= carry4 * ((uint64_t) 1L << 26); + carry8 = (h8 + (int64_t)(1L << 25)) >> 26; + h9 += carry8; + h8 -= carry8 * ((uint64_t) 1L << 26); + /* |h4| <= 2^25; from now on fits into int32 unchanged */ + /* |h8| <= 2^25; from now on fits into int32 unchanged */ + /* |h5| <= 1.01*2^24 */ + /* |h9| <= 1.71*2^59 */ + + carry9 = (h9 + (int64_t)(1L << 24)) >> 25; + h0 += carry9 * 19; + h9 -= carry9 * ((uint64_t) 1L << 25); + /* |h9| <= 2^24; from now on fits into int32 unchanged */ + /* |h0| <= 1.1*2^39 */ + + carry0 = (h0 + (int64_t)(1L << 25)) >> 26; + h1 += carry0; + h0 -= carry0 * ((uint64_t) 1L << 26); + /* |h0| <= 2^25; from now on fits into int32 unchanged */ + /* |h1| <= 1.01*2^24 */ + + h[0] = (int32_t) h0; + h[1] = (int32_t) h1; + h[2] = (int32_t) h2; + h[3] = (int32_t) h3; + h[4] = (int32_t) h4; + h[5] = (int32_t) h5; + h[6] = (int32_t) h6; + h[7] = (int32_t) h7; + h[8] = (int32_t) h8; + h[9] = (int32_t) h9; +} + +/* + h = f * f + Can overlap h with f. + * + Preconditions: + |f| bounded by 1.65*2^26,1.65*2^25,1.65*2^26,1.65*2^25,etc. + * + Postconditions: + |h| bounded by 1.01*2^25,1.01*2^24,1.01*2^25,1.01*2^24,etc. + */ + +static void +fe25519_sq(fe25519 h, const fe25519 f) +{ + int32_t f0 = f[0]; + int32_t f1 = f[1]; + int32_t f2 = f[2]; + int32_t f3 = f[3]; + int32_t f4 = f[4]; + int32_t f5 = f[5]; + int32_t f6 = f[6]; + int32_t f7 = f[7]; + int32_t f8 = f[8]; + int32_t f9 = f[9]; + + int32_t f0_2 = 2 * f0; + int32_t f1_2 = 2 * f1; + int32_t f2_2 = 2 * f2; + int32_t f3_2 = 2 * f3; + int32_t f4_2 = 2 * f4; + int32_t f5_2 = 2 * f5; + int32_t f6_2 = 2 * f6; + int32_t f7_2 = 2 * f7; + int32_t f5_38 = 38 * f5; /* 1.959375*2^30 */ + int32_t f6_19 = 19 * f6; /* 1.959375*2^30 */ + int32_t f7_38 = 38 * f7; /* 1.959375*2^30 */ + int32_t f8_19 = 19 * f8; /* 1.959375*2^30 */ + int32_t f9_38 = 38 * f9; /* 1.959375*2^30 */ + + int64_t f0f0 = f0 * (int64_t) f0; + int64_t f0f1_2 = f0_2 * (int64_t) f1; + int64_t f0f2_2 = f0_2 * (int64_t) f2; + int64_t f0f3_2 = f0_2 * (int64_t) f3; + int64_t f0f4_2 = f0_2 * (int64_t) f4; + int64_t f0f5_2 = f0_2 * (int64_t) f5; + int64_t f0f6_2 = f0_2 * (int64_t) f6; + int64_t f0f7_2 = f0_2 * (int64_t) f7; + int64_t f0f8_2 = f0_2 * (int64_t) f8; + int64_t f0f9_2 = f0_2 * (int64_t) f9; + int64_t f1f1_2 = f1_2 * (int64_t) f1; + int64_t f1f2_2 = f1_2 * (int64_t) f2; + int64_t f1f3_4 = f1_2 * (int64_t) f3_2; + int64_t f1f4_2 = f1_2 * (int64_t) f4; + int64_t f1f5_4 = f1_2 * (int64_t) f5_2; + int64_t f1f6_2 = f1_2 * (int64_t) f6; + int64_t f1f7_4 = f1_2 * (int64_t) f7_2; + int64_t f1f8_2 = f1_2 * (int64_t) f8; + int64_t f1f9_76 = f1_2 * (int64_t) f9_38; + int64_t f2f2 = f2 * (int64_t) f2; + int64_t f2f3_2 = f2_2 * (int64_t) f3; + int64_t f2f4_2 = f2_2 * (int64_t) f4; + int64_t f2f5_2 = f2_2 * (int64_t) f5; + int64_t f2f6_2 = f2_2 * (int64_t) f6; + int64_t f2f7_2 = f2_2 * (int64_t) f7; + int64_t f2f8_38 = f2_2 * (int64_t) f8_19; + int64_t f2f9_38 = f2 * (int64_t) f9_38; + int64_t f3f3_2 = f3_2 * (int64_t) f3; + int64_t f3f4_2 = f3_2 * (int64_t) f4; + int64_t f3f5_4 = f3_2 * (int64_t) f5_2; + int64_t f3f6_2 = f3_2 * (int64_t) f6; + int64_t f3f7_76 = f3_2 * (int64_t) f7_38; + int64_t f3f8_38 = f3_2 * (int64_t) f8_19; + int64_t f3f9_76 = f3_2 * (int64_t) f9_38; + int64_t f4f4 = f4 * (int64_t) f4; + int64_t f4f5_2 = f4_2 * (int64_t) f5; + int64_t f4f6_38 = f4_2 * (int64_t) f6_19; + int64_t f4f7_38 = f4 * (int64_t) f7_38; + int64_t f4f8_38 = f4_2 * (int64_t) f8_19; + int64_t f4f9_38 = f4 * (int64_t) f9_38; + int64_t f5f5_38 = f5 * (int64_t) f5_38; + int64_t f5f6_38 = f5_2 * (int64_t) f6_19; + int64_t f5f7_76 = f5_2 * (int64_t) f7_38; + int64_t f5f8_38 = f5_2 * (int64_t) f8_19; + int64_t f5f9_76 = f5_2 * (int64_t) f9_38; + int64_t f6f6_19 = f6 * (int64_t) f6_19; + int64_t f6f7_38 = f6 * (int64_t) f7_38; + int64_t f6f8_38 = f6_2 * (int64_t) f8_19; + int64_t f6f9_38 = f6 * (int64_t) f9_38; + int64_t f7f7_38 = f7 * (int64_t) f7_38; + int64_t f7f8_38 = f7_2 * (int64_t) f8_19; + int64_t f7f9_76 = f7_2 * (int64_t) f9_38; + int64_t f8f8_19 = f8 * (int64_t) f8_19; + int64_t f8f9_38 = f8 * (int64_t) f9_38; + int64_t f9f9_38 = f9 * (int64_t) f9_38; + + int64_t h0 = f0f0 + f1f9_76 + f2f8_38 + f3f7_76 + f4f6_38 + f5f5_38; + int64_t h1 = f0f1_2 + f2f9_38 + f3f8_38 + f4f7_38 + f5f6_38; + int64_t h2 = f0f2_2 + f1f1_2 + f3f9_76 + f4f8_38 + f5f7_76 + f6f6_19; + int64_t h3 = f0f3_2 + f1f2_2 + f4f9_38 + f5f8_38 + f6f7_38; + int64_t h4 = f0f4_2 + f1f3_4 + f2f2 + f5f9_76 + f6f8_38 + f7f7_38; + int64_t h5 = f0f5_2 + f1f4_2 + f2f3_2 + f6f9_38 + f7f8_38; + int64_t h6 = f0f6_2 + f1f5_4 + f2f4_2 + f3f3_2 + f7f9_76 + f8f8_19; + int64_t h7 = f0f7_2 + f1f6_2 + f2f5_2 + f3f4_2 + f8f9_38; + int64_t h8 = f0f8_2 + f1f7_4 + f2f6_2 + f3f5_4 + f4f4 + f9f9_38; + int64_t h9 = f0f9_2 + f1f8_2 + f2f7_2 + f3f6_2 + f4f5_2; + + int64_t carry0; + int64_t carry1; + int64_t carry2; + int64_t carry3; + int64_t carry4; + int64_t carry5; + int64_t carry6; + int64_t carry7; + int64_t carry8; + int64_t carry9; + + carry0 = (h0 + (int64_t)(1L << 25)) >> 26; + h1 += carry0; + h0 -= carry0 * ((uint64_t) 1L << 26); + carry4 = (h4 + (int64_t)(1L << 25)) >> 26; + h5 += carry4; + h4 -= carry4 * ((uint64_t) 1L << 26); + + carry1 = (h1 + (int64_t)(1L << 24)) >> 25; + h2 += carry1; + h1 -= carry1 * ((uint64_t) 1L << 25); + carry5 = (h5 + (int64_t)(1L << 24)) >> 25; + h6 += carry5; + h5 -= carry5 * ((uint64_t) 1L << 25); + + carry2 = (h2 + (int64_t)(1L << 25)) >> 26; + h3 += carry2; + h2 -= carry2 * ((uint64_t) 1L << 26); + carry6 = (h6 + (int64_t)(1L << 25)) >> 26; + h7 += carry6; + h6 -= carry6 * ((uint64_t) 1L << 26); + + carry3 = (h3 + (int64_t)(1L << 24)) >> 25; + h4 += carry3; + h3 -= carry3 * ((uint64_t) 1L << 25); + carry7 = (h7 + (int64_t)(1L << 24)) >> 25; + h8 += carry7; + h7 -= carry7 * ((uint64_t) 1L << 25); + + carry4 = (h4 + (int64_t)(1L << 25)) >> 26; + h5 += carry4; + h4 -= carry4 * ((uint64_t) 1L << 26); + carry8 = (h8 + (int64_t)(1L << 25)) >> 26; + h9 += carry8; + h8 -= carry8 * ((uint64_t) 1L << 26); + + carry9 = (h9 + (int64_t)(1L << 24)) >> 25; + h0 += carry9 * 19; + h9 -= carry9 * ((uint64_t) 1L << 25); + + carry0 = (h0 + (int64_t)(1L << 25)) >> 26; + h1 += carry0; + h0 -= carry0 * ((uint64_t) 1L << 26); + + h[0] = (int32_t) h0; + h[1] = (int32_t) h1; + h[2] = (int32_t) h2; + h[3] = (int32_t) h3; + h[4] = (int32_t) h4; + h[5] = (int32_t) h5; + h[6] = (int32_t) h6; + h[7] = (int32_t) h7; + h[8] = (int32_t) h8; + h[9] = (int32_t) h9; +} + +/* + h = 2 * f * f + Can overlap h with f. + * + Preconditions: + |f| bounded by 1.65*2^26,1.65*2^25,1.65*2^26,1.65*2^25,etc. + * + Postconditions: + |h| bounded by 1.01*2^25,1.01*2^24,1.01*2^25,1.01*2^24,etc. + */ + +static void +fe25519_sq2(fe25519 h, const fe25519 f) +{ + int32_t f0 = f[0]; + int32_t f1 = f[1]; + int32_t f2 = f[2]; + int32_t f3 = f[3]; + int32_t f4 = f[4]; + int32_t f5 = f[5]; + int32_t f6 = f[6]; + int32_t f7 = f[7]; + int32_t f8 = f[8]; + int32_t f9 = f[9]; + + int32_t f0_2 = 2 * f0; + int32_t f1_2 = 2 * f1; + int32_t f2_2 = 2 * f2; + int32_t f3_2 = 2 * f3; + int32_t f4_2 = 2 * f4; + int32_t f5_2 = 2 * f5; + int32_t f6_2 = 2 * f6; + int32_t f7_2 = 2 * f7; + int32_t f5_38 = 38 * f5; /* 1.959375*2^30 */ + int32_t f6_19 = 19 * f6; /* 1.959375*2^30 */ + int32_t f7_38 = 38 * f7; /* 1.959375*2^30 */ + int32_t f8_19 = 19 * f8; /* 1.959375*2^30 */ + int32_t f9_38 = 38 * f9; /* 1.959375*2^30 */ + + int64_t f0f0 = f0 * (int64_t) f0; + int64_t f0f1_2 = f0_2 * (int64_t) f1; + int64_t f0f2_2 = f0_2 * (int64_t) f2; + int64_t f0f3_2 = f0_2 * (int64_t) f3; + int64_t f0f4_2 = f0_2 * (int64_t) f4; + int64_t f0f5_2 = f0_2 * (int64_t) f5; + int64_t f0f6_2 = f0_2 * (int64_t) f6; + int64_t f0f7_2 = f0_2 * (int64_t) f7; + int64_t f0f8_2 = f0_2 * (int64_t) f8; + int64_t f0f9_2 = f0_2 * (int64_t) f9; + int64_t f1f1_2 = f1_2 * (int64_t) f1; + int64_t f1f2_2 = f1_2 * (int64_t) f2; + int64_t f1f3_4 = f1_2 * (int64_t) f3_2; + int64_t f1f4_2 = f1_2 * (int64_t) f4; + int64_t f1f5_4 = f1_2 * (int64_t) f5_2; + int64_t f1f6_2 = f1_2 * (int64_t) f6; + int64_t f1f7_4 = f1_2 * (int64_t) f7_2; + int64_t f1f8_2 = f1_2 * (int64_t) f8; + int64_t f1f9_76 = f1_2 * (int64_t) f9_38; + int64_t f2f2 = f2 * (int64_t) f2; + int64_t f2f3_2 = f2_2 * (int64_t) f3; + int64_t f2f4_2 = f2_2 * (int64_t) f4; + int64_t f2f5_2 = f2_2 * (int64_t) f5; + int64_t f2f6_2 = f2_2 * (int64_t) f6; + int64_t f2f7_2 = f2_2 * (int64_t) f7; + int64_t f2f8_38 = f2_2 * (int64_t) f8_19; + int64_t f2f9_38 = f2 * (int64_t) f9_38; + int64_t f3f3_2 = f3_2 * (int64_t) f3; + int64_t f3f4_2 = f3_2 * (int64_t) f4; + int64_t f3f5_4 = f3_2 * (int64_t) f5_2; + int64_t f3f6_2 = f3_2 * (int64_t) f6; + int64_t f3f7_76 = f3_2 * (int64_t) f7_38; + int64_t f3f8_38 = f3_2 * (int64_t) f8_19; + int64_t f3f9_76 = f3_2 * (int64_t) f9_38; + int64_t f4f4 = f4 * (int64_t) f4; + int64_t f4f5_2 = f4_2 * (int64_t) f5; + int64_t f4f6_38 = f4_2 * (int64_t) f6_19; + int64_t f4f7_38 = f4 * (int64_t) f7_38; + int64_t f4f8_38 = f4_2 * (int64_t) f8_19; + int64_t f4f9_38 = f4 * (int64_t) f9_38; + int64_t f5f5_38 = f5 * (int64_t) f5_38; + int64_t f5f6_38 = f5_2 * (int64_t) f6_19; + int64_t f5f7_76 = f5_2 * (int64_t) f7_38; + int64_t f5f8_38 = f5_2 * (int64_t) f8_19; + int64_t f5f9_76 = f5_2 * (int64_t) f9_38; + int64_t f6f6_19 = f6 * (int64_t) f6_19; + int64_t f6f7_38 = f6 * (int64_t) f7_38; + int64_t f6f8_38 = f6_2 * (int64_t) f8_19; + int64_t f6f9_38 = f6 * (int64_t) f9_38; + int64_t f7f7_38 = f7 * (int64_t) f7_38; + int64_t f7f8_38 = f7_2 * (int64_t) f8_19; + int64_t f7f9_76 = f7_2 * (int64_t) f9_38; + int64_t f8f8_19 = f8 * (int64_t) f8_19; + int64_t f8f9_38 = f8 * (int64_t) f9_38; + int64_t f9f9_38 = f9 * (int64_t) f9_38; + + int64_t h0 = f0f0 + f1f9_76 + f2f8_38 + f3f7_76 + f4f6_38 + f5f5_38; + int64_t h1 = f0f1_2 + f2f9_38 + f3f8_38 + f4f7_38 + f5f6_38; + int64_t h2 = f0f2_2 + f1f1_2 + f3f9_76 + f4f8_38 + f5f7_76 + f6f6_19; + int64_t h3 = f0f3_2 + f1f2_2 + f4f9_38 + f5f8_38 + f6f7_38; + int64_t h4 = f0f4_2 + f1f3_4 + f2f2 + f5f9_76 + f6f8_38 + f7f7_38; + int64_t h5 = f0f5_2 + f1f4_2 + f2f3_2 + f6f9_38 + f7f8_38; + int64_t h6 = f0f6_2 + f1f5_4 + f2f4_2 + f3f3_2 + f7f9_76 + f8f8_19; + int64_t h7 = f0f7_2 + f1f6_2 + f2f5_2 + f3f4_2 + f8f9_38; + int64_t h8 = f0f8_2 + f1f7_4 + f2f6_2 + f3f5_4 + f4f4 + f9f9_38; + int64_t h9 = f0f9_2 + f1f8_2 + f2f7_2 + f3f6_2 + f4f5_2; + + int64_t carry0; + int64_t carry1; + int64_t carry2; + int64_t carry3; + int64_t carry4; + int64_t carry5; + int64_t carry6; + int64_t carry7; + int64_t carry8; + int64_t carry9; + + h0 += h0; + h1 += h1; + h2 += h2; + h3 += h3; + h4 += h4; + h5 += h5; + h6 += h6; + h7 += h7; + h8 += h8; + h9 += h9; + + carry0 = (h0 + (int64_t)(1L << 25)) >> 26; + h1 += carry0; + h0 -= carry0 * ((uint64_t) 1L << 26); + carry4 = (h4 + (int64_t)(1L << 25)) >> 26; + h5 += carry4; + h4 -= carry4 * ((uint64_t) 1L << 26); + + carry1 = (h1 + (int64_t)(1L << 24)) >> 25; + h2 += carry1; + h1 -= carry1 * ((uint64_t) 1L << 25); + carry5 = (h5 + (int64_t)(1L << 24)) >> 25; + h6 += carry5; + h5 -= carry5 * ((uint64_t) 1L << 25); + + carry2 = (h2 + (int64_t)(1L << 25)) >> 26; + h3 += carry2; + h2 -= carry2 * ((uint64_t) 1L << 26); + carry6 = (h6 + (int64_t)(1L << 25)) >> 26; + h7 += carry6; + h6 -= carry6 * ((uint64_t) 1L << 26); + + carry3 = (h3 + (int64_t)(1L << 24)) >> 25; + h4 += carry3; + h3 -= carry3 * ((uint64_t) 1L << 25); + carry7 = (h7 + (int64_t)(1L << 24)) >> 25; + h8 += carry7; + h7 -= carry7 * ((uint64_t) 1L << 25); + + carry4 = (h4 + (int64_t)(1L << 25)) >> 26; + h5 += carry4; + h4 -= carry4 * ((uint64_t) 1L << 26); + carry8 = (h8 + (int64_t)(1L << 25)) >> 26; + h9 += carry8; + h8 -= carry8 * ((uint64_t) 1L << 26); + + carry9 = (h9 + (int64_t)(1L << 24)) >> 25; + h0 += carry9 * 19; + h9 -= carry9 * ((uint64_t) 1L << 25); + + carry0 = (h0 + (int64_t)(1L << 25)) >> 26; + h1 += carry0; + h0 -= carry0 * ((uint64_t) 1L << 26); + + h[0] = (int32_t) h0; + h[1] = (int32_t) h1; + h[2] = (int32_t) h2; + h[3] = (int32_t) h3; + h[4] = (int32_t) h4; + h[5] = (int32_t) h5; + h[6] = (int32_t) h6; + h[7] = (int32_t) h7; + h[8] = (int32_t) h8; + h[9] = (int32_t) h9; +} + +static inline void +fe25519_mul32(fe25519 h, const fe25519 f, uint32_t n) +{ + int64_t sn = (int64_t) n; + int32_t f0 = f[0]; + int32_t f1 = f[1]; + int32_t f2 = f[2]; + int32_t f3 = f[3]; + int32_t f4 = f[4]; + int32_t f5 = f[5]; + int32_t f6 = f[6]; + int32_t f7 = f[7]; + int32_t f8 = f[8]; + int32_t f9 = f[9]; + int64_t h0 = f0 * sn; + int64_t h1 = f1 * sn; + int64_t h2 = f2 * sn; + int64_t h3 = f3 * sn; + int64_t h4 = f4 * sn; + int64_t h5 = f5 * sn; + int64_t h6 = f6 * sn; + int64_t h7 = f7 * sn; + int64_t h8 = f8 * sn; + int64_t h9 = f9 * sn; + int64_t carry0, carry1, carry2, carry3, carry4, carry5, carry6, carry7, + carry8, carry9; + + carry9 = (h9 + ((int64_t) 1 << 24)) >> 25; + h0 += carry9 * 19; + h9 -= carry9 * ((int64_t) 1 << 25); + carry1 = (h1 + ((int64_t) 1 << 24)) >> 25; + h2 += carry1; + h1 -= carry1 * ((int64_t) 1 << 25); + carry3 = (h3 + ((int64_t) 1 << 24)) >> 25; + h4 += carry3; + h3 -= carry3 * ((int64_t) 1 << 25); + carry5 = (h5 + ((int64_t) 1 << 24)) >> 25; + h6 += carry5; + h5 -= carry5 * ((int64_t) 1 << 25); + carry7 = (h7 + ((int64_t) 1 << 24)) >> 25; + h8 += carry7; + h7 -= carry7 * ((int64_t) 1 << 25); + + carry0 = (h0 + ((int64_t) 1 << 25)) >> 26; + h1 += carry0; + h0 -= carry0 * ((int64_t) 1 << 26); + carry2 = (h2 + ((int64_t) 1 << 25)) >> 26; + h3 += carry2; + h2 -= carry2 * ((int64_t) 1 << 26); + carry4 = (h4 + ((int64_t) 1 << 25)) >> 26; + h5 += carry4; + h4 -= carry4 * ((int64_t) 1 << 26); + carry6 = (h6 + ((int64_t) 1 << 25)) >> 26; + h7 += carry6; + h6 -= carry6 * ((int64_t) 1 << 26); + carry8 = (h8 + ((int64_t) 1 << 25)) >> 26; + h9 += carry8; + h8 -= carry8 * ((int64_t) 1 << 26); + + h[0] = (int32_t) h0; + h[1] = (int32_t) h1; + h[2] = (int32_t) h2; + h[3] = (int32_t) h3; + h[4] = (int32_t) h4; + h[5] = (int32_t) h5; + h[6] = (int32_t) h6; + h[7] = (int32_t) h7; + h[8] = (int32_t) h8; + h[9] = (int32_t) h9; +} diff --git a/packages/runtime/vendor/libsodium/export.h b/packages/runtime/vendor/libsodium/export.h new file mode 100644 index 000000000..a0074fc9c --- /dev/null +++ b/packages/runtime/vendor/libsodium/export.h @@ -0,0 +1,57 @@ + +#ifndef sodium_export_H +#define sodium_export_H + +#include +#include +#include + +#if !defined(__clang__) && !defined(__GNUC__) +# ifdef __attribute__ +# undef __attribute__ +# endif +# define __attribute__(a) +#endif + +#ifdef SODIUM_STATIC +# define SODIUM_EXPORT +# define SODIUM_EXPORT_WEAK +#else +# if defined(_MSC_VER) +# ifdef SODIUM_DLL_EXPORT +# define SODIUM_EXPORT __declspec(dllexport) +# else +# define SODIUM_EXPORT __declspec(dllimport) +# endif +# else +# if defined(__SUNPRO_C) +# ifndef __GNU_C__ +# define SODIUM_EXPORT __attribute__ (visibility(__global)) +# else +# define SODIUM_EXPORT __attribute__ __global +# endif +# elif defined(_MSG_VER) +# define SODIUM_EXPORT extern __declspec(dllexport) +# else +# define SODIUM_EXPORT __attribute__ ((visibility ("default"))) +# endif +# endif +# if defined(__ELF__) && !defined(SODIUM_DISABLE_WEAK_FUNCTIONS) +# define SODIUM_EXPORT_WEAK SODIUM_EXPORT __attribute__((weak)) +# else +# define SODIUM_EXPORT_WEAK SODIUM_EXPORT +# endif +#endif + +#ifndef CRYPTO_ALIGN +# if defined(__INTEL_COMPILER) || defined(_MSC_VER) +# define CRYPTO_ALIGN(x) __declspec(align(x)) +# else +# define CRYPTO_ALIGN(x) __attribute__ ((aligned(x))) +# endif +#endif + +#define SODIUM_MIN(A, B) ((A) < (B) ? (A) : (B)) +#define SODIUM_SIZE_MAX SODIUM_MIN(UINT64_MAX, SIZE_MAX) + +#endif diff --git a/packages/runtime/vendor/libsodium/fe_25_5/base.h b/packages/runtime/vendor/libsodium/fe_25_5/base.h new file mode 100644 index 000000000..e18530bbb --- /dev/null +++ b/packages/runtime/vendor/libsodium/fe_25_5/base.h @@ -0,0 +1,1344 @@ +{ /* 0/31 */ + { + { 25967493, -14356035, 29566456, 3660896, -12694345, 4014787, 27544626, -11754271, -6079156, 2047605 }, + { -12545711, 934262, -2722910, 3049990, -727428, 9406986, 12720692, 5043384, 19500929, -15469378 }, + { -8738181, 4489570, 9688441, -14785194, 10184609, -12363380, 29287919, 11864899, -24514362, -4438546 } + }, + { + { -12815894, -12976347, -21581243, 11784320, -25355658, -2750717, -11717903, -3814571, -358445, -10211303 }, + { -21703237, 6903825, 27185491, 6451973, -29577724, -9554005, -15616551, 11189268, -26829678, -5319081 }, + { 26966642, 11152617, 32442495, 15396054, 14353839, -12752335, -3128826, -9541118, -15472047, -4166697 } + }, + { + { 15636291, -9688557, 24204773, -7912398, 616977, -16685262, 27787600, -14772189, 28944400, -1550024 }, + { 16568933, 4717097, -11556148, -1102322, 15682896, -11807043, 16354577, -11775962, 7689662, 11199574 }, + { 30464156, -5976125, -11779434, -15670865, 23220365, 15915852, 7512774, 10017326, -17749093, -9920357 } + }, + { + { -17036878, 13921892, 10945806, -6033431, 27105052, -16084379, -28926210, 15006023, 3284568, -6276540 }, + { 23599295, -8306047, -11193664, -7687416, 13236774, 10506355, 7464579, 9656445, 13059162, 10374397 }, + { 7798556, 16710257, 3033922, 2874086, 28997861, 2835604, 32406664, -3839045, -641708, -101325 } + }, + { + { 10861363, 11473154, 27284546, 1981175, -30064349, 12577861, 32867885, 14515107, -15438304, 10819380 }, + { 4708026, 6336745, 20377586, 9066809, -11272109, 6594696, -25653668, 12483688, -12668491, 5581306 }, + { 19563160, 16186464, -29386857, 4097519, 10237984, -4348115, 28542350, 13850243, -23678021, -15815942 } + }, + { + { -15371964, -12862754, 32573250, 4720197, -26436522, 5875511, -19188627, -15224819, -9818940, -12085777 }, + { -8549212, 109983, 15149363, 2178705, 22900618, 4543417, 3044240, -15689887, 1762328, 14866737 }, + { -18199695, -15951423, -10473290, 1707278, -17185920, 3916101, -28236412, 3959421, 27914454, 4383652 } + }, + { + { 5153746, 9909285, 1723747, -2777874, 30523605, 5516873, 19480852, 5230134, -23952439, -15175766 }, + { -30269007, -3463509, 7665486, 10083793, 28475525, 1649722, 20654025, 16520125, 30598449, 7715701 }, + { 28881845, 14381568, 9657904, 3680757, -20181635, 7843316, -31400660, 1370708, 29794553, -1409300 } + }, + { + { 14499471, -2729599, -33191113, -4254652, 28494862, 14271267, 30290735, 10876454, -33154098, 2381726 }, + { -7195431, -2655363, -14730155, 462251, -27724326, 3941372, -6236617, 3696005, -32300832, 15351955 }, + { 27431194, 8222322, 16448760, -3907995, -18707002, 11938355, -32961401, -2970515, 29551813, 10109425 } + } +}, +{ /* 1/31 */ + { + { -13657040, -13155431, -31283750, 11777098, 21447386, 6519384, -2378284, -1627556, 10092783, -4764171 }, + { 27939166, 14210322, 4677035, 16277044, -22964462, -12398139, -32508754, 12005538, -17810127, 12803510 }, + { 17228999, -15661624, -1233527, 300140, -1224870, -11714777, 30364213, -9038194, 18016357, 4397660 } + }, + { + { -10958843, -7690207, 4776341, -14954238, 27850028, -15602212, -26619106, 14544525, -17477504, 982639 }, + { 29253598, 15796703, -2863982, -9908884, 10057023, 3163536, 7332899, -4120128, -21047696, 9934963 }, + { 5793303, 16271923, -24131614, -10116404, 29188560, 1206517, -14747930, 4559895, -30123922, -10897950 } + }, + { + { -27643952, -11493006, 16282657, -11036493, 28414021, -15012264, 24191034, 4541697, -13338309, 5500568 }, + { 12650548, -1497113, 9052871, 11355358, -17680037, -8400164, -17430592, 12264343, 10874051, 13524335 }, + { 25556948, -3045990, 714651, 2510400, 23394682, -10415330, 33119038, 5080568, -22528059, 5376628 } + }, + { + { -26088264, -4011052, -17013699, -3537628, -6726793, 1920897, -22321305, -9447443, 4535768, 1569007 }, + { -2255422, 14606630, -21692440, -8039818, 28430649, 8775819, -30494562, 3044290, 31848280, 12543772 }, + { -22028579, 2943893, -31857513, 6777306, 13784462, -4292203, -27377195, -2062731, 7718482, 14474653 } + }, + { + { 2385315, 2454213, -22631320, 46603, -4437935, -15680415, 656965, -7236665, 24316168, -5253567 }, + { 13741529, 10911568, -33233417, -8603737, -20177830, -1033297, 33040651, -13424532, -20729456, 8321686 }, + { 21060490, -2212744, 15712757, -4336099, 1639040, 10656336, 23845965, -11874838, -9984458, 608372 } + }, + { + { -13672732, -15087586, -10889693, -7557059, -6036909, 11305547, 1123968, -6780577, 27229399, 23887 }, + { -23244140, -294205, -11744728, 14712571, -29465699, -2029617, 12797024, -6440308, -1633405, 16678954 }, + { -29500620, 4770662, -16054387, 14001338, 7830047, 9564805, -1508144, -4795045, -17169265, 4904953 } + }, + { + { 24059557, 14617003, 19037157, -15039908, 19766093, -14906429, 5169211, 16191880, 2128236, -4326833 }, + { -16981152, 4124966, -8540610, -10653797, 30336522, -14105247, -29806336, 916033, -6882542, -2986532 }, + { -22630907, 12419372, -7134229, -7473371, -16478904, 16739175, 285431, 2763829, 15736322, 4143876 } + }, + { + { 2379352, 11839345, -4110402, -5988665, 11274298, 794957, 212801, -14594663, 23527084, -16458268 }, + { 33431127, -11130478, -17838966, -15626900, 8909499, 8376530, -32625340, 4087881, -15188911, -14416214 }, + { 1767683, 7197987, -13205226, -2022635, -13091350, 448826, 5799055, 4357868, -4774191, -16323038 } + } +}, +{ /* 2/31 */ + { + { 6721966, 13833823, -23523388, -1551314, 26354293, -11863321, 23365147, -3949732, 7390890, 2759800 }, + { 4409041, 2052381, 23373853, 10530217, 7676779, -12885954, 21302353, -4264057, 1244380, -12919645 }, + { -4421239, 7169619, 4982368, -2957590, 30256825, -2777540, 14086413, 9208236, 15886429, 16489664 } + }, + { + { 1996075, 10375649, 14346367, 13311202, -6874135, -16438411, -13693198, 398369, -30606455, -712933 }, + { -25307465, 9795880, -2777414, 14878809, -33531835, 14780363, 13348553, 12076947, -30836462, 5113182 }, + { -17770784, 11797796, 31950843, 13929123, -25888302, 12288344, -30341101, -7336386, 13847711, 5387222 } + }, + { + { -18582163, -3416217, 17824843, -2340966, 22744343, -10442611, 8763061, 3617786, -19600662, 10370991 }, + { 20246567, -14369378, 22358229, -543712, 18507283, -10413996, 14554437, -8746092, 32232924, 16763880 }, + { 9648505, 10094563, 26416693, 14745928, -30374318, -6472621, 11094161, 15689506, 3140038, -16510092 } + }, + { + { -16160072, 5472695, 31895588, 4744994, 8823515, 10365685, -27224800, 9448613, -28774454, 366295 }, + { 19153450, 11523972, -11096490, -6503142, -24647631, 5420647, 28344573, 8041113, 719605, 11671788 }, + { 8678025, 2694440, -6808014, 2517372, 4964326, 11152271, -15432916, -15266516, 27000813, -10195553 } + }, + { + { -15157904, 7134312, 8639287, -2814877, -7235688, 10421742, 564065, 5336097, 6750977, -14521026 }, + { 11836410, -3979488, 26297894, 16080799, 23455045, 15735944, 1695823, -8819122, 8169720, 16220347 }, + { -18115838, 8653647, 17578566, -6092619, -8025777, -16012763, -11144307, -2627664, -5990708, -14166033 } + }, + { + { -23308498, -10968312, 15213228, -10081214, -30853605, -11050004, 27884329, 2847284, 2655861, 1738395 }, + { -27537433, -14253021, -25336301, -8002780, -9370762, 8129821, 21651608, -3239336, -19087449, -11005278 }, + { 1533110, 3437855, 23735889, 459276, 29970501, 11335377, 26030092, 5821408, 10478196, 8544890 } + }, + { + { 32173121, -16129311, 24896207, 3921497, 22579056, -3410854, 19270449, 12217473, 17789017, -3395995 }, + { -30552961, -2228401, -15578829, -10147201, 13243889, 517024, 15479401, -3853233, 30460520, 1052596 }, + { -11614875, 13323618, 32618793, 8175907, -15230173, 12596687, 27491595, -4612359, 3179268, -9478891 } + }, + { + { 31947069, -14366651, -4640583, -15339921, -15125977, -6039709, -14756777, -16411740, 19072640, -9511060 }, + { 11685058, 11822410, 3158003, -13952594, 33402194, -4165066, 5977896, -5215017, 473099, 5040608 }, + { -20290863, 8198642, -27410132, 11602123, 1290375, -2799760, 28326862, 1721092, -19558642, -3131606 } + } +}, +{ /* 3/31 */ + { + { 7881532, 10687937, 7578723, 7738378, -18951012, -2553952, 21820786, 8076149, -27868496, 11538389 }, + { -19935666, 3899861, 18283497, -6801568, -15728660, -11249211, 8754525, 7446702, -5676054, 5797016 }, + { -11295600, -3793569, -15782110, -7964573, 12708869, -8456199, 2014099, -9050574, -2369172, -5877341 } + }, + { + { -22472376, -11568741, -27682020, 1146375, 18956691, 16640559, 1192730, -3714199, 15123619, 10811505 }, + { 14352098, -3419715, -18942044, 10822655, 32750596, 4699007, -70363, 15776356, -28886779, -11974553 }, + { -28241164, -8072475, -4978962, -5315317, 29416931, 1847569, -20654173, -16484855, 4714547, -9600655 } + }, + { + { 15200332, 8368572, 19679101, 15970074, -31872674, 1959451, 24611599, -4543832, -11745876, 12340220 }, + { 12876937, -10480056, 33134381, 6590940, -6307776, 14872440, 9613953, 8241152, 15370987, 9608631 }, + { -4143277, -12014408, 8446281, -391603, 4407738, 13629032, -7724868, 15866074, -28210621, -8814099 } + }, + { + { 26660628, -15677655, 8393734, 358047, -7401291, 992988, -23904233, 858697, 20571223, 8420556 }, + { 14620715, 13067227, -15447274, 8264467, 14106269, 15080814, 33531827, 12516406, -21574435, -12476749 }, + { 236881, 10476226, 57258, -14677024, 6472998, 2466984, 17258519, 7256740, 8791136, 15069930 } + }, + { + { 1276410, -9371918, 22949635, -16322807, -23493039, -5702186, 14711875, 4874229, -30663140, -2331391 }, + { 5855666, 4990204, -13711848, 7294284, -7804282, 1924647, -1423175, -7912378, -33069337, 9234253 }, + { 20590503, -9018988, 31529744, -7352666, -2706834, 10650548, 31559055, -11609587, 18979186, 13396066 } + }, + { + { 24474287, 4968103, 22267082, 4407354, 24063882, -8325180, -18816887, 13594782, 33514650, 7021958 }, + { -11566906, -6565505, -21365085, 15928892, -26158305, 4315421, -25948728, -3916677, -21480480, 12868082 }, + { -28635013, 13504661, 19988037, -2132761, 21078225, 6443208, -21446107, 2244500, -12455797, -8089383 } + }, + { + { -30595528, 13793479, -5852820, 319136, -25723172, -6263899, 33086546, 8957937, -15233648, 5540521 }, + { -11630176, -11503902, -8119500, -7643073, 2620056, 1022908, -23710744, -1568984, -16128528, -14962807 }, + { 23152971, 775386, 27395463, 14006635, -9701118, 4649512, 1689819, 892185, -11513277, -15205948 } + }, + { + { 9770129, 9586738, 26496094, 4324120, 1556511, -3550024, 27453819, 4763127, -19179614, 5867134 }, + { -32765025, 1927590, 31726409, -4753295, 23962434, -16019500, 27846559, 5931263, -29749703, -16108455 }, + { 27461885, -2977536, 22380810, 1815854, -23033753, -3031938, 7283490, -15148073, -19526700, 7734629 } + } +}, +{ /* 4/31 */ + { + { -8010264, -9590817, -11120403, 6196038, 29344158, -13430885, 7585295, -3176626, 18549497, 15302069 }, + { -32658337, -6171222, -7672793, -11051681, 6258878, 13504381, 10458790, -6418461, -8872242, 8424746 }, + { 24687205, 8613276, -30667046, -3233545, 1863892, -1830544, 19206234, 7134917, -11284482, -828919 } + }, + { + { 11334899, -9218022, 8025293, 12707519, 17523892, -10476071, 10243738, -14685461, -5066034, 16498837 }, + { 8911542, 6887158, -9584260, -6958590, 11145641, -9543680, 17303925, -14124238, 6536641, 10543906 }, + { -28946384, 15479763, -17466835, 568876, -1497683, 11223454, -2669190, -16625574, -27235709, 8876771 } + }, + { + { -25742899, -12566864, -15649966, -846607, -33026686, -796288, -33481822, 15824474, -604426, -9039817 }, + { 10330056, 70051, 7957388, -9002667, 9764902, 15609756, 27698697, -4890037, 1657394, 3084098 }, + { 10477963, -7470260, 12119566, -13250805, 29016247, -5365589, 31280319, 14396151, -30233575, 15272409 } + }, + { + { -12288309, 3169463, 28813183, 16658753, 25116432, -5630466, -25173957, -12636138, -25014757, 1950504 }, + { -26180358, 9489187, 11053416, -14746161, -31053720, 5825630, -8384306, -8767532, 15341279, 8373727 }, + { 28685821, 7759505, -14378516, -12002860, -31971820, 4079242, 298136, -10232602, -2878207, 15190420 } + }, + { + { -32932876, 13806336, -14337485, -15794431, -24004620, 10940928, 8669718, 2742393, -26033313, -6875003 }, + { -1580388, -11729417, -25979658, -11445023, -17411874, -10912854, 9291594, -16247779, -12154742, 6048605 }, + { -30305315, 14843444, 1539301, 11864366, 20201677, 1900163, 13934231, 5128323, 11213262, 9168384 } + }, + { + { -26280513, 11007847, 19408960, -940758, -18592965, -4328580, -5088060, -11105150, 20470157, -16398701 }, + { -23136053, 9282192, 14855179, -15390078, -7362815, -14408560, -22783952, 14461608, 14042978, 5230683 }, + { 29969567, -2741594, -16711867, -8552442, 9175486, -2468974, 21556951, 3506042, -5933891, -12449708 } + }, + { + { -3144746, 8744661, 19704003, 4581278, -20430686, 6830683, -21284170, 8971513, -28539189, 15326563 }, + { -19464629, 10110288, -17262528, -3503892, -23500387, 1355669, -15523050, 15300988, -20514118, 9168260 }, + { -5353335, 4488613, -23803248, 16314347, 7780487, -15638939, -28948358, 9601605, 33087103, -9011387 } + }, + { + { -19443170, -15512900, -20797467, -12445323, -29824447, 10229461, -27444329, -15000531, -5996870, 15664672 }, + { 23294591, -16632613, -22650781, -8470978, 27844204, 11461195, 13099750, -2460356, 18151676, 13417686 }, + { -24722913, -4176517, -31150679, 5988919, -26858785, 6685065, 1661597, -12551441, 15271676, -15452665 } + } +}, +{ /* 5/31 */ + { + { 11433042, -13228665, 8239631, -5279517, -1985436, -725718, -18698764, 2167544, -6921301, -13440182 }, + { -31436171, 15575146, 30436815, 12192228, -22463353, 9395379, -9917708, -8638997, 12215110, 12028277 }, + { 14098400, 6555944, 23007258, 5757252, -15427832, -12950502, 30123440, 4617780, -16900089, -655628 } + }, + { + { -4026201, -15240835, 11893168, 13718664, -14809462, 1847385, -15819999, 10154009, 23973261, -12684474 }, + { -26531820, -3695990, -1908898, 2534301, -31870557, -16550355, 18341390, -11419951, 32013174, -10103539 }, + { -25479301, 10876443, -11771086, -14625140, -12369567, 1838104, 21911214, 6354752, 4425632, -837822 } + }, + { + { -10433389, -14612966, 22229858, -3091047, -13191166, 776729, -17415375, -12020462, 4725005, 14044970 }, + { 19268650, -7304421, 1555349, 8692754, -21474059, -9910664, 6347390, -1411784, -19522291, -16109756 }, + { -24864089, 12986008, -10898878, -5558584, -11312371, -148526, 19541418, 8180106, 9282262, 10282508 } + }, + { + { -26205082, 4428547, -8661196, -13194263, 4098402, -14165257, 15522535, 8372215, 5542595, -10702683 }, + { -10562541, 14895633, 26814552, -16673850, -17480754, -2489360, -2781891, 6993761, -18093885, 10114655 }, + { -20107055, -929418, 31422704, 10427861, -7110749, 6150669, -29091755, -11529146, 25953725, -106158 } + }, + { + { -4234397, -8039292, -9119125, 3046000, 2101609, -12607294, 19390020, 6094296, -3315279, 12831125 }, + { -15998678, 7578152, 5310217, 14408357, -33548620, -224739, 31575954, 6326196, 7381791, -2421839 }, + { -20902779, 3296811, 24736065, -16328389, 18374254, 7318640, 6295303, 8082724, -15362489, 12339664 } + }, + { + { 27724736, 2291157, 6088201, -14184798, 1792727, 5857634, 13848414, 15768922, 25091167, 14856294 }, + { -18866652, 8331043, 24373479, 8541013, -701998, -9269457, 12927300, -12695493, -22182473, -9012899 }, + { -11423429, -5421590, 11632845, 3405020, 30536730, -11674039, -27260765, 13866390, 30146206, 9142070 } + }, + { + { 3924129, -15307516, -13817122, -10054960, 12291820, -668366, -27702774, 9326384, -8237858, 4171294 }, + { -15921940, 16037937, 6713787, 16606682, -21612135, 2790944, 26396185, 3731949, 345228, -5462949 }, + { -21327538, 13448259, 25284571, 1143661, 20614966, -8849387, 2031539, -12391231, -16253183, -13582083 } + }, + { + { 31016211, -16722429, 26371392, -14451233, -5027349, 14854137, 17477601, 3842657, 28012650, -16405420 }, + { -5075835, 9368966, -8562079, -4600902, -15249953, 6970560, -9189873, 16292057, -8867157, 3507940 }, + { 29439664, 3537914, 23333589, 6997794, -17555561, -11018068, -15209202, -15051267, -9164929, 6580396 } + } +}, +{ /* 6/31 */ + { + { -12185861, -7679788, 16438269, 10826160, -8696817, -6235611, 17860444, -9273846, -2095802, 9304567 }, + { 20714564, -4336911, 29088195, 7406487, 11426967, -5095705, 14792667, -14608617, 5289421, -477127 }, + { -16665533, -10650790, -6160345, -13305760, 9192020, -1802462, 17271490, 12349094, 26939669, -3752294 } + }, + { + { -12889898, 9373458, 31595848, 16374215, 21471720, 13221525, -27283495, -12348559, -3698806, 117887 }, + { 22263325, -6560050, 3984570, -11174646, -15114008, -566785, 28311253, 5358056, -23319780, 541964 }, + { 16259219, 3261970, 2309254, -15534474, -16885711, -4581916, 24134070, -16705829, -13337066, -13552195 } + }, + { + { 9378160, -13140186, -22845982, -12745264, 28198281, -7244098, -2399684, -717351, 690426, 14876244 }, + { 24977353, -314384, -8223969, -13465086, 28432343, -1176353, -13068804, -12297348, -22380984, 6618999 }, + { -1538174, 11685646, 12944378, 13682314, -24389511, -14413193, 8044829, -13817328, 32239829, -5652762 } + }, + { + { -18603066, 4762990, -926250, 8885304, -28412480, -3187315, 9781647, -10350059, 32779359, 5095274 }, + { -33008130, -5214506, -32264887, -3685216, 9460461, -9327423, -24601656, 14506724, 21639561, -2630236 }, + { -16400943, -13112215, 25239338, 15531969, 3987758, -4499318, -1289502, -6863535, 17874574, 558605 } + }, + { + { -13600129, 10240081, 9171883, 16131053, -20869254, 9599700, 33499487, 5080151, 2085892, 5119761 }, + { -22205145, -2519528, -16381601, 414691, -25019550, 2170430, 30634760, -8363614, -31999993, -5759884 }, + { -6845704, 15791202, 8550074, -1312654, 29928809, -12092256, 27534430, -7192145, -22351378, 12961482 } + }, + { + { -24492060, -9570771, 10368194, 11582341, -23397293, -2245287, 16533930, 8206996, -30194652, -5159638 }, + { -11121496, -3382234, 2307366, 6362031, -135455, 8868177, -16835630, 7031275, 7589640, 8945490 }, + { -32152748, 8917967, 6661220, -11677616, -1192060, -15793393, 7251489, -11182180, 24099109, -14456170 } + }, + { + { 5019558, -7907470, 4244127, -14714356, -26933272, 6453165, -19118182, -13289025, -6231896, -10280736 }, + { 10853594, 10721687, 26480089, 5861829, -22995819, 1972175, -1866647, -10557898, -3363451, -6441124 }, + { -17002408, 5906790, 221599, -6563147, 7828208, -13248918, 24362661, -2008168, -13866408, 7421392 } + }, + { + { 8139927, -6546497, 32257646, -5890546, 30375719, 1886181, -21175108, 15441252, 28826358, -4123029 }, + { 6267086, 9695052, 7709135, -16603597, -32869068, -1886135, 14795160, -7840124, 13746021, -1742048 }, + { 28584902, 7787108, -6732942, -15050729, 22846041, -7571236, -3181936, -363524, 4771362, -8419958 } + } +}, +{ /* 7/31 */ + { + { 24949256, 6376279, -27466481, -8174608, -18646154, -9930606, 33543569, -12141695, 3569627, 11342593 }, + { 26514989, 4740088, 27912651, 3697550, 19331575, -11472339, 6809886, 4608608, 7325975, -14801071 }, + { -11618399, -14554430, -24321212, 7655128, -1369274, 5214312, -27400540, 10258390, -17646694, -8186692 } + }, + { + { 11431204, 15823007, 26570245, 14329124, 18029990, 4796082, -31446179, 15580664, 9280358, -3973687 }, + { -160783, -10326257, -22855316, -4304997, -20861367, -13621002, -32810901, -11181622, -15545091, 4387441 }, + { -20799378, 12194512, 3937617, -5805892, -27154820, 9340370, -24513992, 8548137, 20617071, -7482001 } + }, + { + { -938825, -3930586, -8714311, 16124718, 24603125, -6225393, -13775352, -11875822, 24345683, 10325460 }, + { -19855277, -1568885, -22202708, 8714034, 14007766, 6928528, 16318175, -1010689, 4766743, 3552007 }, + { -21751364, -16730916, 1351763, -803421, -4009670, 3950935, 3217514, 14481909, 10988822, -3994762 } + }, + { + { 15564307, -14311570, 3101243, 5684148, 30446780, -8051356, 12677127, -6505343, -8295852, 13296005 }, + { -9442290, 6624296, -30298964, -11913677, -4670981, -2057379, 31521204, 9614054, -30000824, 12074674 }, + { 4771191, -135239, 14290749, -13089852, 27992298, 14998318, -1413936, -1556716, 29832613, -16391035 } + }, + { + { 7064884, -7541174, -19161962, -5067537, -18891269, -2912736, 25825242, 5293297, -27122660, 13101590 }, + { -2298563, 2439670, -7466610, 1719965, -27267541, -16328445, 32512469, -5317593, -30356070, -4190957 }, + { -30006540, 10162316, -33180176, 3981723, -16482138, -13070044, 14413974, 9515896, 19568978, 9628812 } + }, + { + { 33053803, 199357, 15894591, 1583059, 27380243, -4580435, -17838894, -6106839, -6291786, 3437740 }, + { -18978877, 3884493, 19469877, 12726490, 15913552, 13614290, -22961733, 70104, 7463304, 4176122 }, + { -27124001, 10659917, 11482427, -16070381, 12771467, -6635117, -32719404, -5322751, 24216882, 5944158 } + }, + { + { 8894125, 7450974, -2664149, -9765752, -28080517, -12389115, 19345746, 14680796, 11632993, 5847885 }, + { 26942781, -2315317, 9129564, -4906607, 26024105, 11769399, -11518837, 6367194, -9727230, 4782140 }, + { 19916461, -4828410, -22910704, -11414391, 25606324, -5972441, 33253853, 8220911, 6358847, -1873857 } + }, + { + { 801428, -2081702, 16569428, 11065167, 29875704, 96627, 7908388, -4480480, -13538503, 1387155 }, + { 19646058, 5720633, -11416706, 12814209, 11607948, 12749789, 14147075, 15156355, -21866831, 11835260 }, + { 19299512, 1155910, 28703737, 14890794, 2925026, 7269399, 26121523, 15467869, -26560550, 5052483 } + } +}, +{ /* 8/31 */ + { + { -3017432, 10058206, 1980837, 3964243, 22160966, 12322533, -6431123, -12618185, 12228557, -7003677 }, + { 32944382, 14922211, -22844894, 5188528, 21913450, -8719943, 4001465, 13238564, -6114803, 8653815 }, + { 22865569, -4652735, 27603668, -12545395, 14348958, 8234005, 24808405, 5719875, 28483275, 2841751 } + }, + { + { -16420968, -1113305, -327719, -12107856, 21886282, -15552774, -1887966, -315658, 19932058, -12739203 }, + { -11656086, 10087521, -8864888, -5536143, -19278573, -3055912, 3999228, 13239134, -4777469, -13910208 }, + { 1382174, -11694719, 17266790, 9194690, -13324356, 9720081, 20403944, 11284705, -14013818, 3093230 } + }, + { + { 16650921, -11037932, -1064178, 1570629, -8329746, 7352753, -302424, 16271225, -24049421, -6691850 }, + { -21911077, -5927941, -4611316, -5560156, -31744103, -10785293, 24123614, 15193618, -21652117, -16739389 }, + { -9935934, -4289447, -25279823, 4372842, 2087473, 10399484, 31870908, 14690798, 17361620, 11864968 } + }, + { + { -11307610, 6210372, 13206574, 5806320, -29017692, -13967200, -12331205, -7486601, -25578460, -16240689 }, + { 14668462, -12270235, 26039039, 15305210, 25515617, 4542480, 10453892, 6577524, 9145645, -6443880 }, + { 5974874, 3053895, -9433049, -10385191, -31865124, 3225009, -7972642, 3936128, -5652273, -3050304 } + }, + { + { 30625386, -4729400, -25555961, -12792866, -20484575, 7695099, 17097188, -16303496, -27999779, 1803632 }, + { -3553091, 9865099, -5228566, 4272701, -5673832, -16689700, 14911344, 12196514, -21405489, 7047412 }, + { 20093277, 9920966, -11138194, -5343857, 13161587, 12044805, -32856851, 4124601, -32343828, -10257566 } + }, + { + { -20788824, 14084654, -13531713, 7842147, 19119038, -13822605, 4752377, -8714640, -21679658, 2288038 }, + { -26819236, -3283715, 29965059, 3039786, -14473765, 2540457, 29457502, 14625692, -24819617, 12570232 }, + { -1063558, -11551823, 16920318, 12494842, 1278292, -5869109, -21159943, -3498680, -11974704, 4724943 } + }, + { + { 17960970, -11775534, -4140968, -9702530, -8876562, -1410617, -12907383, -8659932, -29576300, 1903856 }, + { 23134274, -14279132, -10681997, -1611936, 20684485, 15770816, -12989750, 3190296, 26955097, 14109738 }, + { 15308788, 5320727, -30113809, -14318877, 22902008, 7767164, 29425325, -11277562, 31960942, 11934971 } + }, + { + { -27395711, 8435796, 4109644, 12222639, -24627868, 14818669, 20638173, 4875028, 10491392, 1379718 }, + { -13159415, 9197841, 3875503, -8936108, -1383712, -5879801, 33518459, 16176658, 21432314, 12180697 }, + { -11787308, 11500838, 13787581, -13832590, -22430679, 10140205, 1465425, 12689540, -10301319, -13872883 } + } +}, +{ /* 9/31 */ + { + { 5414091, -15386041, -21007664, 9643570, 12834970, 1186149, -2622916, -1342231, 26128231, 6032912 }, + { -26337395, -13766162, 32496025, -13653919, 17847801, -12669156, 3604025, 8316894, -25875034, -10437358 }, + { 3296484, 6223048, 24680646, -12246460, -23052020, 5903205, -8862297, -4639164, 12376617, 3188849 } + }, + { + { 29190488, -14659046, 27549113, -1183516, 3520066, -10697301, 32049515, -7309113, -16109234, -9852307 }, + { -14744486, -9309156, 735818, -598978, -20407687, -5057904, 25246078, -15795669, 18640741, -960977 }, + { -6928835, -16430795, 10361374, 5642961, 4910474, 12345252, -31638386, -494430, 10530747, 1053335 } + }, + { + { -29265967, -14186805, -13538216, -12117373, -19457059, -10655384, -31462369, -2948985, 24018831, 15026644 }, + { -22592535, -3145277, -2289276, 5953843, -13440189, 9425631, 25310643, 13003497, -2314791, -15145616 }, + { -27419985, -603321, -8043984, -1669117, -26092265, 13987819, -27297622, 187899, -23166419, -2531735 } + }, + { + { -21744398, -13810475, 1844840, 5021428, -10434399, -15911473, 9716667, 16266922, -5070217, 726099 }, + { 29370922, -6053998, 7334071, -15342259, 9385287, 2247707, -13661962, -4839461, 30007388, -15823341 }, + { -936379, 16086691, 23751945, -543318, -1167538, -5189036, 9137109, 730663, 9835848, 4555336 } + }, + { + { -23376435, 1410446, -22253753, -12899614, 30867635, 15826977, 17693930, 544696, -11985298, 12422646 }, + { 31117226, -12215734, -13502838, 6561947, -9876867, -12757670, -5118685, -4096706, 29120153, 13924425 }, + { -17400879, -14233209, 19675799, -2734756, -11006962, -5858820, -9383939, -11317700, 7240931, -237388 } + }, + { + { -31361739, -11346780, -15007447, -5856218, -22453340, -12152771, 1222336, 4389483, 3293637, -15551743 }, + { -16684801, -14444245, 11038544, 11054958, -13801175, -3338533, -24319580, 7733547, 12796905, -6335822 }, + { -8759414, -10817836, -25418864, 10783769, -30615557, -9746811, -28253339, 3647836, 3222231, -11160462 } + }, + { + { 18606113, 1693100, -25448386, -15170272, 4112353, 10045021, 23603893, -2048234, -7550776, 2484985 }, + { 9255317, -3131197, -12156162, -1004256, 13098013, -9214866, 16377220, -2102812, -19802075, -3034702 }, + { -22729289, 7496160, -5742199, 11329249, 19991973, -3347502, -31718148, 9936966, -30097688, -10618797 } + }, + { + { 21878590, -5001297, 4338336, 13643897, -3036865, 13160960, 19708896, 5415497, -7360503, -4109293 }, + { 27736861, 10103576, 12500508, 8502413, -3413016, -9633558, 10436918, -1550276, -23659143, -8132100 }, + { 19492550, -12104365, -29681976, -852630, -3208171, 12403437, 30066266, 8367329, 13243957, 8709688 } + } +}, +{ /* 10/31 */ + { + { 12015105, 2801261, 28198131, 10151021, 24818120, -4743133, -11194191, -5645734, 5150968, 7274186 }, + { 2831366, -12492146, 1478975, 6122054, 23825128, -12733586, 31097299, 6083058, 31021603, -9793610 }, + { -2529932, -2229646, 445613, 10720828, -13849527, -11505937, -23507731, 16354465, 15067285, -14147707 } + }, + { + { 7840942, 14037873, -33364863, 15934016, -728213, -3642706, 21403988, 1057586, -19379462, -12403220 }, + { 915865, -16469274, 15608285, -8789130, -24357026, 6060030, -17371319, 8410997, -7220461, 16527025 }, + { 32922597, -556987, 20336074, -16184568, 10903705, -5384487, 16957574, 52992, 23834301, 6588044 } + }, + { + { 32752030, 11232950, 3381995, -8714866, 22652988, -10744103, 17159699, 16689107, -20314580, -1305992 }, + { -4689649, 9166776, -25710296, -10847306, 11576752, 12733943, 7924251, -2752281, 1976123, -7249027 }, + { 21251222, 16309901, -2983015, -6783122, 30810597, 12967303, 156041, -3371252, 12331345, -8237197 } + }, + { + { 8651614, -4477032, -16085636, -4996994, 13002507, 2950805, 29054427, -5106970, 10008136, -4667901 }, + { 31486080, 15114593, -14261250, 12951354, 14369431, -7387845, 16347321, -13662089, 8684155, -10532952 }, + { 19443825, 11385320, 24468943, -9659068, -23919258, 2187569, -26263207, -6086921, 31316348, 14219878 } + }, + { + { -28594490, 1193785, 32245219, 11392485, 31092169, 15722801, 27146014, 6992409, 29126555, 9207390 }, + { 32382935, 1110093, 18477781, 11028262, -27411763, -7548111, -4980517, 10843782, -7957600, -14435730 }, + { 2814918, 7836403, 27519878, -7868156, -20894015, -11553689, -21494559, 8550130, 28346258, 1994730 } + }, + { + { -19578299, 8085545, -14000519, -3948622, 2785838, -16231307, -19516951, 7174894, 22628102, 8115180 }, + { -30405132, 955511, -11133838, -15078069, -32447087, -13278079, -25651578, 3317160, -9943017, 930272 }, + { -15303681, -6833769, 28856490, 1357446, 23421993, 1057177, 24091212, -1388970, -22765376, -10650715 } + }, + { + { -22751231, -5303997, -12907607, -12768866, -15811511, -7797053, -14839018, -16554220, -1867018, 8398970 }, + { -31969310, 2106403, -4736360, 1362501, 12813763, 16200670, 22981545, -6291273, 18009408, -15772772 }, + { -17220923, -9545221, -27784654, 14166835, 29815394, 7444469, 29551787, -3727419, 19288549, 1325865 } + }, + { + { 15100157, -15835752, -23923978, -1005098, -26450192, 15509408, 12376730, -3479146, 33166107, -8042750 }, + { 20909231, 13023121, -9209752, 16251778, -5778415, -8094914, 12412151, 10018715, 2213263, -13878373 }, + { 32529814, -11074689, 30361439, -16689753, -9135940, 1513226, 22922121, 6382134, -5766928, 8371348 } + } +}, +{ /* 11/31 */ + { + { 9923462, 11271500, 12616794, 3544722, -29998368, -1721626, 12891687, -8193132, -26442943, 10486144 }, + { -22597207, -7012665, 8587003, -8257861, 4084309, -12970062, 361726, 2610596, -23921530, -11455195 }, + { 5408411, -1136691, -4969122, 10561668, 24145918, 14240566, 31319731, -4235541, 19985175, -3436086 } + }, + { + { -13994457, 16616821, 14549246, 3341099, 32155958, 13648976, -17577068, 8849297, 65030, 8370684 }, + { -8320926, -12049626, 31204563, 5839400, -20627288, -1057277, -19442942, 6922164, 12743482, -9800518 }, + { -2361371, 12678785, 28815050, 4759974, -23893047, 4884717, 23783145, 11038569, 18800704, 255233 } + }, + { + { -5269658, -1773886, 13957886, 7990715, 23132995, 728773, 13393847, 9066957, 19258688, -14753793 }, + { -2936654, -10827535, -10432089, 14516793, -3640786, 4372541, -31934921, 2209390, -1524053, 2055794 }, + { 580882, 16705327, 5468415, -2683018, -30926419, -14696000, -7203346, -8994389, -30021019, 7394435 } + }, + { + { 23838809, 1822728, -15738443, 15242727, 8318092, -3733104, -21672180, -3492205, -4821741, 14799921 }, + { 13345610, 9759151, 3371034, -16137791, 16353039, 8577942, 31129804, 13496856, -9056018, 7402518 }, + { 2286874, -4435931, -20042458, -2008336, -13696227, 5038122, 11006906, -15760352, 8205061, 1607563 } + }, + { + { 14414086, -8002132, 3331830, -3208217, 22249151, -5594188, 18364661, -2906958, 30019587, -9029278 }, + { -27688051, 1585953, -10775053, 931069, -29120221, -11002319, -14410829, 12029093, 9944378, 8024 }, + { 4368715, -3709630, 29874200, -15022983, -20230386, -11410704, -16114594, -999085, -8142388, 5640030 } + }, + { + { 10299610, 13746483, 11661824, 16234854, 7630238, 5998374, 9809887, -16694564, 15219798, -14327783 }, + { 27425505, -5719081, 3055006, 10660664, 23458024, 595578, -15398605, -1173195, -18342183, 9742717 }, + { 6744077, 2427284, 26042789, 2720740, -847906, 1118974, 32324614, 7406442, 12420155, 1994844 } + }, + { + { 14012521, -5024720, -18384453, -9578469, -26485342, -3936439, -13033478, -10909803, 24319929, -6446333 }, + { 16412690, -4507367, 10772641, 15929391, -17068788, -4658621, 10555945, -10484049, -30102368, -4739048 }, + { 22397382, -7767684, -9293161, -12792868, 17166287, -9755136, -27333065, 6199366, 21880021, -12250760 } + }, + { + { -4283307, 5368523, -31117018, 8163389, -30323063, 3209128, 16557151, 8890729, 8840445, 4957760 }, + { -15447727, 709327, -6919446, -10870178, -29777922, 6522332, -21720181, 12130072, -14796503, 5005757 }, + { -2114751, -14308128, 23019042, 15765735, -25269683, 6002752, 10183197, -13239326, -16395286, -2176112 } + } +}, +{ /* 12/31 */ + { + { -19025756, 1632005, 13466291, -7995100, -23640451, 16573537, -32013908, -3057104, 22208662, 2000468 }, + { 3065073, -1412761, -25598674, -361432, -17683065, -5703415, -8164212, 11248527, -3691214, -7414184 }, + { 10379208, -6045554, 8877319, 1473647, -29291284, -12507580, 16690915, 2553332, -3132688, 16400289 } + }, + { + { 15716668, 1254266, -18472690, 7446274, -8448918, 6344164, -22097271, -7285580, 26894937, 9132066 }, + { 24158887, 12938817, 11085297, -8177598, -28063478, -4457083, -30576463, 64452, -6817084, -2692882 }, + { 13488534, 7794716, 22236231, 5989356, 25426474, -12578208, 2350710, -3418511, -4688006, 2364226 } + }, + { + { 16335052, 9132434, 25640582, 6678888, 1725628, 8517937, -11807024, -11697457, 15445875, -7798101 }, + { 29004207, -7867081, 28661402, -640412, -12794003, -7943086, 31863255, -4135540, -278050, -15759279 }, + { -6122061, -14866665, -28614905, 14569919, -10857999, -3591829, 10343412, -6976290, -29828287, -10815811 } + }, + { + { 27081650, 3463984, 14099042, -4517604, 1616303, -6205604, 29542636, 15372179, 17293797, 960709 }, + { 20263915, 11434237, -5765435, 11236810, 13505955, -10857102, -16111345, 6493122, -19384511, 7639714 }, + { -2830798, -14839232, 25403038, -8215196, -8317012, -16173699, 18006287, -16043750, 29994677, -15808121 } + }, + { + { 9769828, 5202651, -24157398, -13631392, -28051003, -11561624, -24613141, -13860782, -31184575, 709464 }, + { 12286395, 13076066, -21775189, -1176622, -25003198, 4057652, -32018128, -8890874, 16102007, 13205847 }, + { 13733362, 5599946, 10557076, 3195751, -5557991, 8536970, -25540170, 8525972, 10151379, 10394400 } + }, + { + { 4024660, -16137551, 22436262, 12276534, -9099015, -2686099, 19698229, 11743039, -33302334, 8934414 }, + { -15879800, -4525240, -8580747, -2934061, 14634845, -698278, -9449077, 3137094, -11536886, 11721158 }, + { 17555939, -5013938, 8268606, 2331751, -22738815, 9761013, 9319229, 8835153, -9205489, -1280045 } + }, + { + { -461409, -7830014, 20614118, 16688288, -7514766, -4807119, 22300304, 505429, 6108462, -6183415 }, + { -5070281, 12367917, -30663534, 3234473, 32617080, -8422642, 29880583, -13483331, -26898490, -7867459 }, + { -31975283, 5726539, 26934134, 10237677, -3173717, -605053, 24199304, 3795095, 7592688, -14992079 } + }, + { + { 21594432, -14964228, 17466408, -4077222, 32537084, 2739898, 6407723, 12018833, -28256052, 4298412 }, + { -20650503, -11961496, -27236275, 570498, 3767144, -1717540, 13891942, -1569194, 13717174, 10805743 }, + { -14676630, -15644296, 15287174, 11927123, 24177847, -8175568, -796431, 14860609, -26938930, -5863836 } + } +}, +{ /* 13/31 */ + { + { 12962541, 5311799, -10060768, 11658280, 18855286, -7954201, 13286263, -12808704, -4381056, 9882022 }, + { 18512079, 11319350, -20123124, 15090309, 18818594, 5271736, -22727904, 3666879, -23967430, -3299429 }, + { -6789020, -3146043, 16192429, 13241070, 15898607, -14206114, -10084880, -6661110, -2403099, 5276065 } + }, + { + { 30169808, -5317648, 26306206, -11750859, 27814964, 7069267, 7152851, 3684982, 1449224, 13082861 }, + { 10342826, 3098505, 2119311, 193222, 25702612, 12233820, 23697382, 15056736, -21016438, -8202000 }, + { -33150110, 3261608, 22745853, 7948688, 19370557, -15177665, -26171976, 6482814, -10300080, -11060101 } + }, + { + { 32869458, -5408545, 25609743, 15678670, -10687769, -15471071, 26112421, 2521008, -22664288, 6904815 }, + { 29506923, 4457497, 3377935, -9796444, -30510046, 12935080, 1561737, 3841096, -29003639, -6657642 }, + { 10340844, -6630377, -18656632, -2278430, 12621151, -13339055, 30878497, -11824370, -25584551, 5181966 } + }, + { + { 25940115, -12658025, 17324188, -10307374, -8671468, 15029094, 24396252, -16450922, -2322852, -12388574 }, + { -21765684, 9916823, -1300409, 4079498, -1028346, 11909559, 1782390, 12641087, 20603771, -6561742 }, + { -18882287, -11673380, 24849422, 11501709, 13161720, -4768874, 1925523, 11914390, 4662781, 7820689 } + }, + { + { 12241050, -425982, 8132691, 9393934, 32846760, -1599620, 29749456, 12172924, 16136752, 15264020 }, + { -10349955, -14680563, -8211979, 2330220, -17662549, -14545780, 10658213, 6671822, 19012087, 3772772 }, + { 3753511, -3421066, 10617074, 2028709, 14841030, -6721664, 28718732, -15762884, 20527771, 12988982 } + }, + { + { -14822485, -5797269, -3707987, 12689773, -898983, -10914866, -24183046, -10564943, 3299665, -12424953 }, + { -16777703, -15253301, -9642417, 4978983, 3308785, 8755439, 6943197, 6461331, -25583147, 8991218 }, + { -17226263, 1816362, -1673288, -6086439, 31783888, -8175991, -32948145, 7417950, -30242287, 1507265 } + }, + { + { 29692663, 6829891, -10498800, 4334896, 20945975, -11906496, -28887608, 8209391, 14606362, -10647073 }, + { -3481570, 8707081, 32188102, 5672294, 22096700, 1711240, -33020695, 9761487, 4170404, -2085325 }, + { -11587470, 14855945, -4127778, -1531857, -26649089, 15084046, 22186522, 16002000, -14276837, -8400798 } + }, + { + { -4811456, 13761029, -31703877, -2483919, -3312471, 7869047, -7113572, -9620092, 13240845, 10965870 }, + { -7742563, -8256762, -14768334, -13656260, -23232383, 12387166, 4498947, 14147411, 29514390, 4302863 }, + { -13413405, -12407859, 20757302, -13801832, 14785143, 8976368, -5061276, -2144373, 17846988, -13971927 } + } +}, +{ /* 14/31 */ + { + { -2244452, -754728, -4597030, -1066309, -6247172, 1455299, -21647728, -9214789, -5222701, 12650267 }, + { -9906797, -16070310, 21134160, 12198166, -27064575, 708126, 387813, 13770293, -19134326, 10958663 }, + { 22470984, 12369526, 23446014, -5441109, -21520802, -9698723, -11772496, -11574455, -25083830, 4271862 } + }, + { + { -25169565, -10053642, -19909332, 15361595, -5984358, 2159192, 75375, -4278529, -32526221, 8469673 }, + { 15854970, 4148314, -8893890, 7259002, 11666551, 13824734, -30531198, 2697372, 24154791, -9460943 }, + { 15446137, -15806644, 29759747, 14019369, 30811221, -9610191, -31582008, 12840104, 24913809, 9815020 } + }, + { + { -4709286, -5614269, -31841498, -12288893, -14443537, 10799414, -9103676, 13438769, 18735128, 9466238 }, + { 11933045, 9281483, 5081055, -5183824, -2628162, -4905629, -7727821, -10896103, -22728655, 16199064 }, + { 14576810, 379472, -26786533, -8317236, -29426508, -10812974, -102766, 1876699, 30801119, 2164795 } + }, + { + { 15995086, 3199873, 13672555, 13712240, -19378835, -4647646, -13081610, -15496269, -13492807, 1268052 }, + { -10290614, -3659039, -3286592, 10948818, 23037027, 3794475, -3470338, -12600221, -17055369, 3565904 }, + { 29210088, -9419337, -5919792, -4952785, 10834811, -13327726, -16512102, -10820713, -27162222, -14030531 } + }, + { + { -13161890, 15508588, 16663704, -8156150, -28349942, 9019123, -29183421, -3769423, 2244111, -14001979 }, + { -5152875, -3800936, -9306475, -6071583, 16243069, 14684434, -25673088, -16180800, 13491506, 4641841 }, + { 10813417, 643330, -19188515, -728916, 30292062, -16600078, 27548447, -7721242, 14476989, -12767431 } + }, + { + { 10292079, 9984945, 6481436, 8279905, -7251514, 7032743, 27282937, -1644259, -27912810, 12651324 }, + { -31185513, -813383, 22271204, 11835308, 10201545, 15351028, 17099662, 3988035, 21721536, -3148940 }, + { 10202177, -6545839, -31373232, -9574638, -32150642, -8119683, -12906320, 3852694, 13216206, 14842320 } + }, + { + { -15815640, -10601066, -6538952, -7258995, -6984659, -6581778, -31500847, 13765824, -27434397, 9900184 }, + { 14465505, -13833331, -32133984, -14738873, -27443187, 12990492, 33046193, 15796406, -7051866, -8040114 }, + { 30924417, -8279620, 6359016, -12816335, 16508377, 9071735, -25488601, 15413635, 9524356, -7018878 } + }, + { + { 12274201, -13175547, 32627641, -1785326, 6736625, 13267305, 5237659, -5109483, 15663516, 4035784 }, + { -2951309, 8903985, 17349946, 601635, -16432815, -4612556, -13732739, -15889334, -22258478, 4659091 }, + { -16916263, -4952973, -30393711, -15158821, 20774812, 15897498, 5736189, 15026997, -2178256, -13455585 } + } +}, +{ /* 15/31 */ + { + { -8858980, -2219056, 28571666, -10155518, -474467, -10105698, -3801496, 278095, 23440562, -290208 }, + { 10226241, -5928702, 15139956, 120818, -14867693, 5218603, 32937275, 11551483, -16571960, -7442864 }, + { 17932739, -12437276, -24039557, 10749060, 11316803, 7535897, 22503767, 5561594, -3646624, 3898661 } + }, + { + { 7749907, -969567, -16339731, -16464, -25018111, 15122143, -1573531, 7152530, 21831162, 1245233 }, + { 26958459, -14658026, 4314586, 8346991, -5677764, 11960072, -32589295, -620035, -30402091, -16716212 }, + { -12165896, 9166947, 33491384, 13673479, 29787085, 13096535, 6280834, 14587357, -22338025, 13987525 } + }, + { + { -24349909, 7778775, 21116000, 15572597, -4833266, -5357778, -4300898, -5124639, -7469781, -2858068 }, + { 9681908, -6737123, -31951644, 13591838, -6883821, 386950, 31622781, 6439245, -14581012, 4091397 }, + { -8426427, 1470727, -28109679, -1596990, 3978627, -5123623, -19622683, 12092163, 29077877, -14741988 } + }, + { + { 5269168, -6859726, -13230211, -8020715, 25932563, 1763552, -5606110, -5505881, -20017847, 2357889 }, + { 32264008, -15407652, -5387735, -1160093, -2091322, -3946900, 23104804, -12869908, 5727338, 189038 }, + { 14609123, -8954470, -6000566, -16622781, -14577387, -7743898, -26745169, 10942115, -25888931, -14884697 } + }, + { + { 20513500, 5557931, -15604613, 7829531, 26413943, -2019404, -21378968, 7471781, 13913677, -5137875 }, + { -25574376, 11967826, 29233242, 12948236, -6754465, 4713227, -8940970, 14059180, 12878652, 8511905 }, + { -25656801, 3393631, -2955415, -7075526, -2250709, 9366908, -30223418, 6812974, 5568676, -3127656 } + }, + { + { 11630004, 12144454, 2116339, 13606037, 27378885, 15676917, -17408753, -13504373, -14395196, 8070818 }, + { 27117696, -10007378, -31282771, -5570088, 1127282, 12772488, -29845906, 10483306, -11552749, -1028714 }, + { 10637467, -5688064, 5674781, 1072708, -26343588, -6982302, -1683975, 9177853, -27493162, 15431203 } + }, + { + { 20525145, 10892566, -12742472, 12779443, -29493034, 16150075, -28240519, 14943142, -15056790, -7935931 }, + { -30024462, 5626926, -551567, -9981087, 753598, 11981191, 25244767, -3239766, -3356550, 9594024 }, + { -23752644, 2636870, -5163910, -10103818, 585134, 7877383, 11345683, -6492290, 13352335, -10977084 } + }, + { + { -1931799, -5407458, 3304649, -12884869, 17015806, -4877091, -29783850, -7752482, -13215537, -319204 }, + { 20239939, 6607058, 6203985, 3483793, -18386976, -779229, -20723742, 15077870, -22750759, 14523817 }, + { 27406042, -6041657, 27423596, -4497394, 4996214, 10002360, -28842031, -4545494, -30172742, -4805667 } + } +}, +{ /* 16/31 */ + { + { 11374242, 12660715, 17861383, -12540833, 10935568, 1099227, -13886076, -9091740, -27727044, 11358504 }, + { -12730809, 10311867, 1510375, 10778093, -2119455, -9145702, 32676003, 11149336, -26123651, 4985768 }, + { -19096303, 341147, -6197485, -239033, 15756973, -8796662, -983043, 13794114, -19414307, -15621255 } + }, + { + { 6490081, 11940286, 25495923, -7726360, 8668373, -8751316, 3367603, 6970005, -1691065, -9004790 }, + { 1656497, 13457317, 15370807, 6364910, 13605745, 8362338, -19174622, -5475723, -16796596, -5031438 }, + { -22273315, -13524424, -64685, -4334223, -18605636, -10921968, -20571065, -7007978, -99853, -10237333 } + }, + { + { 17747465, 10039260, 19368299, -4050591, -20630635, -16041286, 31992683, -15857976, -29260363, -5511971 }, + { 31932027, -4986141, -19612382, 16366580, 22023614, 88450, 11371999, -3744247, 4882242, -10626905 }, + { 29796507, 37186, 19818052, 10115756, -11829032, 3352736, 18551198, 3272828, -5190932, -4162409 } + }, + { + { 12501286, 4044383, -8612957, -13392385, -32430052, 5136599, -19230378, -3529697, 330070, -3659409 }, + { 6384877, 2899513, 17807477, 7663917, -2358888, 12363165, 25366522, -8573892, -271295, 12071499 }, + { -8365515, -4042521, 25133448, -4517355, -6211027, 2265927, -32769618, 1936675, -5159697, 3829363 } + }, + { + { 28425966, -5835433, -577090, -4697198, -14217555, 6870930, 7921550, -6567787, 26333140, 14267664 }, + { -11067219, 11871231, 27385719, -10559544, -4585914, -11189312, 10004786, -8709488, -21761224, 8930324 }, + { -21197785, -16396035, 25654216, -1725397, 12282012, 11008919, 1541940, 4757911, -26491501, -16408940 } + }, + { + { 13537262, -7759490, -20604840, 10961927, -5922820, -13218065, -13156584, 6217254, -15943699, 13814990 }, + { -17422573, 15157790, 18705543, 29619, 24409717, -260476, 27361681, 9257833, -1956526, -1776914 }, + { -25045300, -10191966, 15366585, 15166509, -13105086, 8423556, -29171540, 12361135, -18685978, 4578290 } + }, + { + { 24579768, 3711570, 1342322, -11180126, -27005135, 14124956, -22544529, 14074919, 21964432, 8235257 }, + { -6528613, -2411497, 9442966, -5925588, 12025640, -1487420, -2981514, -1669206, 13006806, 2355433 }, + { -16304899, -13605259, -6632427, -5142349, 16974359, -10911083, 27202044, 1719366, 1141648, -12796236 } + }, + { + { -12863944, -13219986, -8318266, -11018091, -6810145, -4843894, 13475066, -3133972, 32674895, 13715045 }, + { 11423335, -5468059, 32344216, 8962751, 24989809, 9241752, -13265253, 16086212, -28740881, -15642093 }, + { -1409668, 12530728, -6368726, 10847387, 19531186, -14132160, -11709148, 7791794, -27245943, 4383347 } + } +}, +{ /* 17/31 */ + { + { -28970898, 5271447, -1266009, -9736989, -12455236, 16732599, -4862407, -4906449, 27193557, 6245191 }, + { -15193956, 5362278, -1783893, 2695834, 4960227, 12840725, 23061898, 3260492, 22510453, 8577507 }, + { -12632451, 11257346, -32692994, 13548177, -721004, 10879011, 31168030, 13952092, -29571492, -3635906 } + }, + { + { 3877321, -9572739, 32416692, 5405324, -11004407, -13656635, 3759769, 11935320, 5611860, 8164018 }, + { -16275802, 14667797, 15906460, 12155291, -22111149, -9039718, 32003002, -8832289, 5773085, -8422109 }, + { -23788118, -8254300, 1950875, 8937633, 18686727, 16459170, -905725, 12376320, 31632953, 190926 } + }, + { + { -24593607, -16138885, -8423991, 13378746, 14162407, 6901328, -8288749, 4508564, -25341555, -3627528 }, + { 8884438, -5884009, 6023974, 10104341, -6881569, -4941533, 18722941, -14786005, -1672488, 827625 }, + { -32720583, -16289296, -32503547, 7101210, 13354605, 2659080, -1800575, -14108036, -24878478, 1541286 } + }, + { + { 2901347, -1117687, 3880376, -10059388, -17620940, -3612781, -21802117, -3567481, 20456845, -1885033 }, + { 27019610, 12299467, -13658288, -1603234, -12861660, -4861471, -19540150, -5016058, 29439641, 15138866 }, + { 21536104, -6626420, -32447818, -10690208, -22408077, 5175814, -5420040, -16361163, 7779328, 109896 } + }, + { + { 30279744, 14648750, -8044871, 6425558, 13639621, -743509, 28698390, 12180118, 23177719, -554075 }, + { 26572847, 3405927, -31701700, 12890905, -19265668, 5335866, -6493768, 2378492, 4439158, -13279347 }, + { -22716706, 3489070, -9225266, -332753, 18875722, -1140095, 14819434, -12731527, -17717757, -5461437 } + }, + { + { -5056483, 16566551, 15953661, 3767752, -10436499, 15627060, -820954, 2177225, 8550082, -15114165 }, + { -18473302, 16596775, -381660, 15663611, 22860960, 15585581, -27844109, -3582739, -23260460, -8428588 }, + { -32480551, 15707275, -8205912, -5652081, 29464558, 2713815, -22725137, 15860482, -21902570, 1494193 } + }, + { + { -19562091, -14087393, -25583872, -9299552, 13127842, 759709, 21923482, 16529112, 8742704, 12967017 }, + { -28464899, 1553205, 32536856, -10473729, -24691605, -406174, -8914625, -2933896, -29903758, 15553883 }, + { 21877909, 3230008, 9881174, 10539357, -4797115, 2841332, 11543572, 14513274, 19375923, -12647961 } + }, + { + { 8832269, -14495485, 13253511, 5137575, 5037871, 4078777, 24880818, -6222716, 2862653, 9455043 }, + { 29306751, 5123106, 20245049, -14149889, 9592566, 8447059, -2077124, -2990080, 15511449, 4789663 }, + { -20679756, 7004547, 8824831, -9434977, -4045704, -3750736, -5754762, 108893, 23513200, 16652362 } + } +}, +{ /* 18/31 */ + { + { -33256173, 4144782, -4476029, -6579123, 10770039, -7155542, -6650416, -12936300, -18319198, 10212860 }, + { 2756081, 8598110, 7383731, -6859892, 22312759, -1105012, 21179801, 2600940, -9988298, -12506466 }, + { -24645692, 13317462, -30449259, -15653928, 21365574, -10869657, 11344424, 864440, -2499677, -16710063 } + }, + { + { -26432803, 6148329, -17184412, -14474154, 18782929, -275997, -22561534, 211300, 2719757, 4940997 }, + { -1323882, 3911313, -6948744, 14759765, -30027150, 7851207, 21690126, 8518463, 26699843, 5276295 }, + { -13149873, -6429067, 9396249, 365013, 24703301, -10488939, 1321586, 149635, -15452774, 7159369 } + }, + { + { 9987780, -3404759, 17507962, 9505530, 9731535, -2165514, 22356009, 8312176, 22477218, -8403385 }, + { 18155857, -16504990, 19744716, 9006923, 15154154, -10538976, 24256460, -4864995, -22548173, 9334109 }, + { 2986088, -4911893, 10776628, -3473844, 10620590, -7083203, -21413845, 14253545, -22587149, 536906 } + }, + { + { 4377756, 8115836, 24567078, 15495314, 11625074, 13064599, 7390551, 10589625, 10838060, -15420424 }, + { -19342404, 867880, 9277171, -3218459, -14431572, -1986443, 19295826, -15796950, 6378260, 699185 }, + { 7895026, 4057113, -7081772, -13077756, -17886831, -323126, -716039, 15693155, -5045064, -13373962 } + }, + { + { -7737563, -5869402, -14566319, -7406919, 11385654, 13201616, 31730678, -10962840, -3918636, -9669325 }, + { 10188286, -15770834, -7336361, 13427543, 22223443, 14896287, 30743455, 7116568, -21786507, 5427593 }, + { 696102, 13206899, 27047647, -10632082, 15285305, -9853179, 10798490, -4578720, 19236243, 12477404 } + }, + { + { -11229439, 11243796, -17054270, -8040865, -788228, -8167967, -3897669, 11180504, -23169516, 7733644 }, + { 17800790, -14036179, -27000429, -11766671, 23887827, 3149671, 23466177, -10538171, 10322027, 15313801 }, + { 26246234, 11968874, 32263343, -5468728, 6830755, -13323031, -15794704, -101982, -24449242, 10890804 } + }, + { + { -31365647, 10271363, -12660625, -6267268, 16690207, -13062544, -14982212, 16484931, 25180797, -5334884 }, + { -586574, 10376444, -32586414, -11286356, 19801893, 10997610, 2276632, 9482883, 316878, 13820577 }, + { -9882808, -4510367, -2115506, 16457136, -11100081, 11674996, 30756178, -7515054, 30696930, -3712849 } + }, + { + { 32988917, -9603412, 12499366, 7910787, -10617257, -11931514, -7342816, -9985397, -32349517, 7392473 }, + { -8855661, 15927861, 9866406, -3649411, -2396914, -16655781, -30409476, -9134995, 25112947, -2926644 }, + { -2504044, -436966, 25621774, -5678772, 15085042, -5479877, -24884878, -13526194, 5537438, -13914319 } + } +}, +{ /* 19/31 */ + { + { -11225584, 2320285, -9584280, 10149187, -33444663, 5808648, -14876251, -1729667, 31234590, 6090599 }, + { -9633316, 116426, 26083934, 2897444, -6364437, -2688086, 609721, 15878753, -6970405, -9034768 }, + { -27757857, 247744, -15194774, -9002551, 23288161, -10011936, -23869595, 6503646, 20650474, 1804084 } + }, + { + { -27589786, 15456424, 8972517, 8469608, 15640622, 4439847, 3121995, -10329713, 27842616, -202328 }, + { -15306973, 2839644, 22530074, 10026331, 4602058, 5048462, 28248656, 5031932, -11375082, 12714369 }, + { 20807691, -7270825, 29286141, 11421711, -27876523, -13868230, -21227475, 1035546, -19733229, 12796920 } + }, + { + { 12076899, -14301286, -8785001, -11848922, -25012791, 16400684, -17591495, -12899438, 3480665, -15182815 }, + { -32361549, 5457597, 28548107, 7833186, 7303070, -11953545, -24363064, -15921875, -33374054, 2771025 }, + { -21389266, 421932, 26597266, 6860826, 22486084, -6737172, -17137485, -4210226, -24552282, 15673397 } + }, + { + { -20184622, 2338216, 19788685, -9620956, -4001265, -8740893, -20271184, 4733254, 3727144, -12934448 }, + { 6120119, 814863, -11794402, -622716, 6812205, -15747771, 2019594, 7975683, 31123697, -10958981 }, + { 30069250, -11435332, 30434654, 2958439, 18399564, -976289, 12296869, 9204260, -16432438, 9648165 } + }, + { + { 32705432, -1550977, 30705658, 7451065, -11805606, 9631813, 3305266, 5248604, -26008332, -11377501 }, + { 17219865, 2375039, -31570947, -5575615, -19459679, 9219903, 294711, 15298639, 2662509, -16297073 }, + { -1172927, -7558695, -4366770, -4287744, -21346413, -8434326, 32087529, -1222777, 32247248, -14389861 } + }, + { + { 14312628, 1221556, 17395390, -8700143, -4945741, -8684635, -28197744, -9637817, -16027623, -13378845 }, + { -1428825, -9678990, -9235681, 6549687, -7383069, -468664, 23046502, 9803137, 17597934, 2346211 }, + { 18510800, 15337574, 26171504, 981392, -22241552, 7827556, -23491134, -11323352, 3059833, -11782870 } + }, + { + { 10141598, 6082907, 17829293, -1947643, 9830092, 13613136, -25556636, -5544586, -33502212, 3592096 }, + { 33114168, -15889352, -26525686, -13343397, 33076705, 8716171, 1151462, 1521897, -982665, -6837803 }, + { -32939165, -4255815, 23947181, -324178, -33072974, -12305637, -16637686, 3891704, 26353178, 693168 } + }, + { + { 30374239, 1595580, -16884039, 13186931, 4600344, 406904, 9585294, -400668, 31375464, 14369965 }, + { -14370654, -7772529, 1510301, 6434173, -18784789, -6262728, 32732230, -13108839, 17901441, 16011505 }, + { 18171223, -11934626, -12500402, 15197122, -11038147, -15230035, -19172240, -16046376, 8764035, 12309598 } + } +}, +{ /* 20/31 */ + { + { 5975908, -5243188, -19459362, -9681747, -11541277, 14015782, -23665757, 1228319, 17544096, -10593782 }, + { 5811932, -1715293, 3442887, -2269310, -18367348, -8359541, -18044043, -15410127, -5565381, 12348900 }, + { -31399660, 11407555, 25755363, 6891399, -3256938, 14872274, -24849353, 8141295, -10632534, -585479 } + }, + { + { -12675304, 694026, -5076145, 13300344, 14015258, -14451394, -9698672, -11329050, 30944593, 1130208 }, + { 8247766, -6710942, -26562381, -7709309, -14401939, -14648910, 4652152, 2488540, 23550156, -271232 }, + { 17294316, -3788438, 7026748, 15626851, 22990044, 113481, 2267737, -5908146, -408818, -137719 } + }, + { + { 16091085, -16253926, 18599252, 7340678, 2137637, -1221657, -3364161, 14550936, 3260525, -7166271 }, + { -4910104, -13332887, 18550887, 10864893, -16459325, -7291596, -23028869, -13204905, -12748722, 2701326 }, + { -8574695, 16099415, 4629974, -16340524, -20786213, -6005432, -10018363, 9276971, 11329923, 1862132 } + }, + { + { 14763076, -15903608, -30918270, 3689867, 3511892, 10313526, -21951088, 12219231, -9037963, -940300 }, + { 8894987, -3446094, 6150753, 3013931, 301220, 15693451, -31981216, -2909717, -15438168, 11595570 }, + { 15214962, 3537601, -26238722, -14058872, 4418657, -15230761, 13947276, 10730794, -13489462, -4363670 } + }, + { + { -2538306, 7682793, 32759013, 263109, -29984731, -7955452, -22332124, -10188635, 977108, 699994 }, + { -12466472, 4195084, -9211532, 550904, -15565337, 12917920, 19118110, -439841, -30534533, -14337913 }, + { 31788461, -14507657, 4799989, 7372237, 8808585, -14747943, 9408237, -10051775, 12493932, -5409317 } + }, + { + { -25680606, 5260744, -19235809, -6284470, -3695942, 16566087, 27218280, 2607121, 29375955, 6024730 }, + { 842132, -2794693, -4763381, -8722815, 26332018, -12405641, 11831880, 6985184, -9940361, 2854096 }, + { -4847262, -7969331, 2516242, -5847713, 9695691, -7221186, 16512645, 960770, 12121869, 16648078 } + }, + { + { -15218652, 14667096, -13336229, 2013717, 30598287, -464137, -31504922, -7882064, 20237806, 2838411 }, + { -19288047, 4453152, 15298546, -16178388, 22115043, -15972604, 12544294, -13470457, 1068881, -12499905 }, + { -9558883, -16518835, 33238498, 13506958, 30505848, -1114596, -8486907, -2630053, 12521378, 4845654 } + }, + { + { -28198521, 10744108, -2958380, 10199664, 7759311, -13088600, 3409348, -873400, -6482306, -12885870 }, + { -23561822, 6230156, -20382013, 10655314, -24040585, -11621172, 10477734, -1240216, -3113227, 13974498 }, + { 12966261, 15550616, -32038948, -1615346, 21025980, -629444, 5642325, 7188737, 18895762, 12629579 } + } +}, +{ /* 21/31 */ + { + { 14741879, -14946887, 22177208, -11721237, 1279741, 8058600, 11758140, 789443, 32195181, 3895677 }, + { 10758205, 15755439, -4509950, 9243698, -4879422, 6879879, -2204575, -3566119, -8982069, 4429647 }, + { -2453894, 15725973, -20436342, -10410672, -5803908, -11040220, -7135870, -11642895, 18047436, -15281743 } + }, + { + { -25173001, -11307165, 29759956, 11776784, -22262383, -15820455, 10993114, -12850837, -17620701, -9408468 }, + { 21987233, 700364, -24505048, 14972008, -7774265, -5718395, 32155026, 2581431, -29958985, 8773375 }, + { -25568350, 454463, -13211935, 16126715, 25240068, 8594567, 20656846, 12017935, -7874389, -13920155 } + }, + { + { 6028182, 6263078, -31011806, -11301710, -818919, 2461772, -31841174, -5468042, -1721788, -2776725 }, + { -12278994, 16624277, 987579, -5922598, 32908203, 1248608, 7719845, -4166698, 28408820, 6816612 }, + { -10358094, -8237829, 19549651, -12169222, 22082623, 16147817, 20613181, 13982702, -10339570, 5067943 } + }, + { + { -30505967, -3821767, 12074681, 13582412, -19877972, 2443951, -19719286, 12746132, 5331210, -10105944 }, + { 30528811, 3601899, -1957090, 4619785, -27361822, -15436388, 24180793, -12570394, 27679908, -1648928 }, + { 9402404, -13957065, 32834043, 10838634, -26580150, -13237195, 26653274, -8685565, 22611444, -12715406 } + }, + { + { 22190590, 1118029, 22736441, 15130463, -30460692, -5991321, 19189625, -4648942, 4854859, 6622139 }, + { -8310738, -2953450, -8262579, -3388049, -10401731, -271929, 13424426, -3567227, 26404409, 13001963 }, + { -31241838, -15415700, -2994250, 8939346, 11562230, -12840670, -26064365, -11621720, -15405155, 11020693 } + }, + { + { 1866042, -7949489, -7898649, -10301010, 12483315, 13477547, 3175636, -12424163, 28761762, 1406734 }, + { -448555, -1777666, 13018551, 3194501, -9580420, -11161737, 24760585, -4347088, 25577411, -13378680 }, + { -24290378, 4759345, -690653, -1852816, 2066747, 10693769, -29595790, 9884936, -9368926, 4745410 } + }, + { + { -9141284, 6049714, -19531061, -4341411, -31260798, 9944276, -15462008, -11311852, 10931924, -11931931 }, + { -16561513, 14112680, -8012645, 4817318, -8040464, -11414606, -22853429, 10856641, -20470770, 13434654 }, + { 22759489, -10073434, -16766264, -1871422, 13637442, -10168091, 1765144, -12654326, 28445307, -5364710 } + }, + { + { 29875063, 12493613, 2795536, -3786330, 1710620, 15181182, -10195717, -8788675, 9074234, 1167180 }, + { -26205683, 11014233, -9842651, -2635485, -26908120, 7532294, -18716888, -9535498, 3843903, 9367684 }, + { -10969595, -6403711, 9591134, 9582310, 11349256, 108879, 16235123, 8601684, -139197, 4242895 } + } +}, +{ /* 22/31 */ + { + { 22092954, -13191123, -2042793, -11968512, 32186753, -11517388, -6574341, 2470660, -27417366, 16625501 }, + { -11057722, 3042016, 13770083, -9257922, 584236, -544855, -7770857, 2602725, -27351616, 14247413 }, + { 6314175, -10264892, -32772502, 15957557, -10157730, 168750, -8618807, 14290061, 27108877, -1180880 } + }, + { + { -8586597, -7170966, 13241782, 10960156, -32991015, -13794596, 33547976, -11058889, -27148451, 981874 }, + { 22833440, 9293594, -32649448, -13618667, -9136966, 14756819, -22928859, -13970780, -10479804, -16197962 }, + { -7768587, 3326786, -28111797, 10783824, 19178761, 14905060, 22680049, 13906969, -15933690, 3797899 } + }, + { + { 21721356, -4212746, -12206123, 9310182, -3882239, -13653110, 23740224, -2709232, 20491983, -8042152 }, + { 9209270, -15135055, -13256557, -6167798, -731016, 15289673, 25947805, 15286587, 30997318, -6703063 }, + { 7392032, 16618386, 23946583, -8039892, -13265164, -1533858, -14197445, -2321576, 17649998, -250080 } + }, + { + { -9301088, -14193827, 30609526, -3049543, -25175069, -1283752, -15241566, -9525724, -2233253, 7662146 }, + { -17558673, 1763594, -33114336, 15908610, -30040870, -12174295, 7335080, -8472199, -3174674, 3440183 }, + { -19889700, -5977008, -24111293, -9688870, 10799743, -16571957, 40450, -4431835, 4862400, 1133 } + }, + { + { -32856209, -7873957, -5422389, 14860950, -16319031, 7956142, 7258061, 311861, -30594991, -7379421 }, + { -3773428, -1565936, 28985340, 7499440, 24445838, 9325937, 29727763, 16527196, 18278453, 15405622 }, + { -4381906, 8508652, -19898366, -3674424, -5984453, 15149970, -13313598, 843523, -21875062, 13626197 } + }, + { + { 2281448, -13487055, -10915418, -2609910, 1879358, 16164207, -10783882, 3953792, 13340839, 15928663 }, + { 31727126, -7179855, -18437503, -8283652, 2875793, -16390330, -25269894, -7014826, -23452306, 5964753 }, + { 4100420, -5959452, -17179337, 6017714, -18705837, 12227141, -26684835, 11344144, 2538215, -7570755 } + }, + { + { -9433605, 6123113, 11159803, -2156608, 30016280, 14966241, -20474983, 1485421, -629256, -15958862 }, + { -26804558, 4260919, 11851389, 9658551, -32017107, 16367492, -20205425, -13191288, 11659922, -11115118 }, + { 26180396, 10015009, -30844224, -8581293, 5418197, 9480663, 2231568, -10170080, 33100372, -1306171 } + }, + { + { 15121113, -5201871, -10389905, 15427821, -27509937, -15992507, 21670947, 4486675, -5931810, -14466380 }, + { 16166486, -9483733, -11104130, 6023908, -31926798, -1364923, 2340060, -16254968, -10735770, -10039824 }, + { 28042865, -3557089, -12126526, 12259706, -3717498, -6945899, 6766453, -8689599, 18036436, 5803270 } + } +}, +{ /* 23/31 */ + { + { -817581, 6763912, 11803561, 1585585, 10958447, -2671165, 23855391, 4598332, -6159431, -14117438 }, + { -31031306, -14256194, 17332029, -2383520, 31312682, -5967183, 696309, 50292, -20095739, 11763584 }, + { -594563, -2514283, -32234153, 12643980, 12650761, 14811489, 665117, -12613632, -19773211, -10713562 } + }, + { + { 30464590, -11262872, -4127476, -12734478, 19835327, -7105613, -24396175, 2075773, -17020157, 992471 }, + { 18357185, -6994433, 7766382, 16342475, -29324918, 411174, 14578841, 8080033, -11574335, -10601610 }, + { 19598397, 10334610, 12555054, 2555664, 18821899, -10339780, 21873263, 16014234, 26224780, 16452269 } + }, + { + { -30223925, 5145196, 5944548, 16385966, 3976735, 2009897, -11377804, -7618186, -20533829, 3698650 }, + { 14187449, 3448569, -10636236, -10810935, -22663880, -3433596, 7268410, -10890444, 27394301, 12015369 }, + { 19695761, 16087646, 28032085, 12999827, 6817792, 11427614, 20244189, -1312777, -13259127, -3402461 } + }, + { + { 30860103, 12735208, -1888245, -4699734, -16974906, 2256940, -8166013, 12298312, -8550524, -10393462 }, + { -5719826, -11245325, -1910649, 15569035, 26642876, -7587760, -5789354, -15118654, -4976164, 12651793 }, + { -2848395, 9953421, 11531313, -5282879, 26895123, -12697089, -13118820, -16517902, 9768698, -2533218 } + }, + { + { -24719459, 1894651, -287698, -4704085, 15348719, -8156530, 32767513, 12765450, 4940095, 10678226 }, + { 18860224, 15980149, -18987240, -1562570, -26233012, -11071856, -7843882, 13944024, -24372348, 16582019 }, + { -15504260, 4970268, -29893044, 4175593, -20993212, -2199756, -11704054, 15444560, -11003761, 7989037 } + }, + { + { 31490452, 5568061, -2412803, 2182383, -32336847, 4531686, -32078269, 6200206, -19686113, -14800171 }, + { -17308668, -15879940, -31522777, -2831, -32887382, 16375549, 8680158, -16371713, 28550068, -6857132 }, + { -28126887, -5688091, 16837845, -1820458, -6850681, 12700016, -30039981, 4364038, 1155602, 5988841 } + }, + { + { 21890435, -13272907, -12624011, 12154349, -7831873, 15300496, 23148983, -4470481, 24618407, 8283181 }, + { -33136107, -10512751, 9975416, 6841041, -31559793, 16356536, 3070187, -7025928, 1466169, 10740210 }, + { -1509399, -15488185, -13503385, -10655916, 32799044, 909394, -13938903, -5779719, -32164649, -15327040 } + }, + { + { 3960823, -14267803, -28026090, -15918051, -19404858, 13146868, 15567327, 951507, -3260321, -573935 }, + { 24740841, 5052253, -30094131, 8961361, 25877428, 6165135, -24368180, 14397372, -7380369, -6144105 }, + { -28888365, 3510803, -28103278, -1158478, -11238128, -10631454, -15441463, -14453128, -1625486, -6494814 } + } +}, +{ /* 24/31 */ + { + { 793299, -9230478, 8836302, -6235707, -27360908, -2369593, 33152843, -4885251, -9906200, -621852 }, + { 5666233, 525582, 20782575, -8038419, -24538499, 14657740, 16099374, 1468826, -6171428, -15186581 }, + { -4859255, -3779343, -2917758, -6748019, 7778750, 11688288, -30404353, -9871238, -1558923, -9863646 } + }, + { + { 10896332, -7719704, 824275, 472601, -19460308, 3009587, 25248958, 14783338, -30581476, -15757844 }, + { 10566929, 12612572, -31944212, 11118703, -12633376, 12362879, 21752402, 8822496, 24003793, 14264025 }, + { 27713862, -7355973, -11008240, 9227530, 27050101, 2504721, 23886875, -13117525, 13958495, -5732453 } + }, + { + { -23481610, 4867226, -27247128, 3900521, 29838369, -8212291, -31889399, -10041781, 7340521, -15410068 }, + { 4646514, -8011124, -22766023, -11532654, 23184553, 8566613, 31366726, -1381061, -15066784, -10375192 }, + { -17270517, 12723032, -16993061, 14878794, 21619651, -6197576, 27584817, 3093888, -8843694, 3849921 } + }, + { + { -9064912, 2103172, 25561640, -15125738, -5239824, 9582958, 32477045, -9017955, 5002294, -15550259 }, + { -12057553, -11177906, 21115585, -13365155, 8808712, -12030708, 16489530, 13378448, -25845716, 12741426 }, + { -5946367, 10645103, -30911586, 15390284, -3286982, -7118677, 24306472, 15852464, 28834118, -7646072 } + }, + { + { -17335748, -9107057, -24531279, 9434953, -8472084, -583362, -13090771, 455841, 20461858, 5491305 }, + { 13669248, -16095482, -12481974, -10203039, -14569770, -11893198, -24995986, 11293807, -28588204, -9421832 }, + { 28497928, 6272777, -33022994, 14470570, 8906179, -1225630, 18504674, -14165166, 29867745, -8795943 } + }, + { + { -16207023, 13517196, -27799630, -13697798, 24009064, -6373891, -6367600, -13175392, 22853429, -4012011 }, + { 24191378, 16712145, -13931797, 15217831, 14542237, 1646131, 18603514, -11037887, 12876623, -2112447 }, + { 17902668, 4518229, -411702, -2829247, 26878217, 5258055, -12860753, 608397, 16031844, 3723494 } + }, + { + { -28632773, 12763728, -20446446, 7577504, 33001348, -13017745, 17558842, -7872890, 23896954, -4314245 }, + { -20005381, -12011952, 31520464, 605201, 2543521, 5991821, -2945064, 7229064, -9919646, -8826859 }, + { 28816045, 298879, -28165016, -15920938, 19000928, -1665890, -12680833, -2949325, -18051778, -2082915 } + }, + { + { 16000882, -344896, 3493092, -11447198, -29504595, -13159789, 12577740, 16041268, -19715240, 7847707 }, + { 10151868, 10572098, 27312476, 7922682, 14825339, 4723128, -32855931, -6519018, -10020567, 3852848 }, + { -11430470, 15697596, -21121557, -4420647, 5386314, 15063598, 16514493, -15932110, 29330899, -15076224 } + } +}, +{ /* 25/31 */ + { + { -25499735, -4378794, -15222908, -6901211, 16615731, 2051784, 3303702, 15490, -27548796, 12314391 }, + { 15683520, -6003043, 18109120, -9980648, 15337968, -5997823, -16717435, 15921866, 16103996, -3731215 }, + { -23169824, -10781249, 13588192, -1628807, -3798557, -1074929, -19273607, 5402699, -29815713, -9841101 } + }, + { + { 23190676, 2384583, -32714340, 3462154, -29903655, -1529132, -11266856, 8911517, -25205859, 2739713 }, + { 21374101, -3554250, -33524649, 9874411, 15377179, 11831242, -33529904, 6134907, 4931255, 11987849 }, + { -7732, -2978858, -16223486, 7277597, 105524, -322051, -31480539, 13861388, -30076310, 10117930 } + }, + { + { -29501170, -10744872, -26163768, 13051539, -25625564, 5089643, -6325503, 6704079, 12890019, 15728940 }, + { -21972360, -11771379, -951059, -4418840, 14704840, 2695116, 903376, -10428139, 12885167, 8311031 }, + { -17516482, 5352194, 10384213, -13811658, 7506451, 13453191, 26423267, 4384730, 1888765, -5435404 } + }, + { + { -25817338, -3107312, -13494599, -3182506, 30896459, -13921729, -32251644, -12707869, -19464434, -3340243 }, + { -23607977, -2665774, -526091, 4651136, 5765089, 4618330, 6092245, 14845197, 17151279, -9854116 }, + { -24830458, -12733720, -15165978, 10367250, -29530908, -265356, 22825805, -7087279, -16866484, 16176525 } + }, + { + { -23583256, 6564961, 20063689, 3798228, -4740178, 7359225, 2006182, -10363426, -28746253, -10197509 }, + { -10626600, -4486402, -13320562, -5125317, 3432136, -6393229, 23632037, -1940610, 32808310, 1099883 }, + { 15030977, 5768825, -27451236, -2887299, -6427378, -15361371, -15277896, -6809350, 2051441, -15225865 } + }, + { + { -3362323, -7239372, 7517890, 9824992, 23555850, 295369, 5148398, -14154188, -22686354, 16633660 }, + { 4577086, -16752288, 13249841, -15304328, 19958763, -14537274, 18559670, -10759549, 8402478, -9864273 }, + { -28406330, -1051581, -26790155, -907698, -17212414, -11030789, 9453451, -14980072, 17983010, 9967138 } + }, + { + { -25762494, 6524722, 26585488, 9969270, 24709298, 1220360, -1677990, 7806337, 17507396, 3651560 }, + { -10420457, -4118111, 14584639, 15971087, -15768321, 8861010, 26556809, -5574557, -18553322, -11357135 }, + { 2839101, 14284142, 4029895, 3472686, 14402957, 12689363, -26642121, 8459447, -5605463, -7621941 } + }, + { + { -4839289, -3535444, 9744961, 2871048, 25113978, 3187018, -25110813, -849066, 17258084, -7977739 }, + { 18164541, -10595176, -17154882, -1542417, 19237078, -9745295, 23357533, -15217008, 26908270, 12150756 }, + { -30264870, -7647865, 5112249, -7036672, -1499807, -6974257, 43168, -5537701, -32302074, 16215819 } + } +}, +{ /* 26/31 */ + { + { -6898905, 9824394, -12304779, -4401089, -31397141, -6276835, 32574489, 12532905, -7503072, -8675347 }, + { -27343522, -16515468, -27151524, -10722951, 946346, 16291093, 254968, 7168080, 21676107, -1943028 }, + { 21260961, -8424752, -16831886, -11920822, -23677961, 3968121, -3651949, -6215466, -3556191, -7913075 } + }, + { + { 16544754, 13250366, -16804428, 15546242, -4583003, 12757258, -2462308, -8680336, -18907032, -9662799 }, + { -2415239, -15577728, 18312303, 4964443, -15272530, -12653564, 26820651, 16690659, 25459437, -4564609 }, + { -25144690, 11425020, 28423002, -11020557, -6144921, -15826224, 9142795, -2391602, -6432418, -1644817 } + }, + { + { -23104652, 6253476, 16964147, -3768872, -25113972, -12296437, -27457225, -16344658, 6335692, 7249989 }, + { -30333227, 13979675, 7503222, -12368314, -11956721, -4621693, -30272269, 2682242, 25993170, -12478523 }, + { 4364628, 5930691, 32304656, -10044554, -8054781, 15091131, 22857016, -10598955, 31820368, 15075278 } + }, + { + { 31879134, -8918693, 17258761, 90626, -8041836, -4917709, 24162788, -9650886, -17970238, 12833045 }, + { 19073683, 14851414, -24403169, -11860168, 7625278, 11091125, -19619190, 2074449, -9413939, 14905377 }, + { 24483667, -11935567, -2518866, -11547418, -1553130, 15355506, -25282080, 9253129, 27628530, -7555480 } + }, + { + { 17597607, 8340603, 19355617, 552187, 26198470, -3176583, 4593324, -9157582, -14110875, 15297016 }, + { 510886, 14337390, -31785257, 16638632, 6328095, 2713355, -20217417, -11864220, 8683221, 2921426 }, + { 18606791, 11874196, 27155355, -5281482, -24031742, 6265446, -25178240, -1278924, 4674690, 13890525 } + }, + { + { 13609624, 13069022, -27372361, -13055908, 24360586, 9592974, 14977157, 9835105, 4389687, 288396 }, + { 9922506, -519394, 13613107, 5883594, -18758345, -434263, -12304062, 8317628, 23388070, 16052080 }, + { 12720016, 11937594, -31970060, -5028689, 26900120, 8561328, -20155687, -11632979, -14754271, -10812892 } + }, + { + { 15961858, 14150409, 26716931, -665832, -22794328, 13603569, 11829573, 7467844, -28822128, 929275 }, + { 11038231, -11582396, -27310482, -7316562, -10498527, -16307831, -23479533, -9371869, -21393143, 2465074 }, + { 20017163, -4323226, 27915242, 1529148, 12396362, 15675764, 13817261, -9658066, 2463391, -4622140 } + }, + { + { -16358878, -12663911, -12065183, 4996454, -1256422, 1073572, 9583558, 12851107, 4003896, 12673717 }, + { -1731589, -15155870, -3262930, 16143082, 19294135, 13385325, 14741514, -9103726, 7903886, 2348101 }, + { 24536016, -16515207, 12715592, -3862155, 1511293, 10047386, -3842346, -7129159, -28377538, 10048127 } + } +}, +{ /* 27/31 */ + { + { -12622226, -6204820, 30718825, 2591312, -10617028, 12192840, 18873298, -7297090, -32297756, 15221632 }, + { -26478122, -11103864, 11546244, -1852483, 9180880, 7656409, -21343950, 2095755, 29769758, 6593415 }, + { -31994208, -2907461, 4176912, 3264766, 12538965, -868111, 26312345, -6118678, 30958054, 8292160 } + }, + { + { 31429822, -13959116, 29173532, 15632448, 12174511, -2760094, 32808831, 3977186, 26143136, -3148876 }, + { 22648901, 1402143, -22799984, 13746059, 7936347, 365344, -8668633, -1674433, -3758243, -2304625 }, + { -15491917, 8012313, -2514730, -12702462, -23965846, -10254029, -1612713, -1535569, -16664475, 8194478 } + }, + { + { 27338066, -7507420, -7414224, 10140405, -19026427, -6589889, 27277191, 8855376, 28572286, 3005164 }, + { 26287124, 4821776, 25476601, -4145903, -3764513, -15788984, -18008582, 1182479, -26094821, -13079595 }, + { -7171154, 3178080, 23970071, 6201893, -17195577, -4489192, -21876275, -13982627, 32208683, -1198248 } + }, + { + { -16657702, 2817643, -10286362, 14811298, 6024667, 13349505, -27315504, -10497842, -27672585, -11539858 }, + { 15941029, -9405932, -21367050, 8062055, 31876073, -238629, -15278393, -1444429, 15397331, -4130193 }, + { 8934485, -13485467, -23286397, -13423241, -32446090, 14047986, 31170398, -1441021, -27505566, 15087184 } + }, + { + { -18357243, -2156491, 24524913, -16677868, 15520427, -6360776, -15502406, 11461896, 16788528, -5868942 }, + { -1947386, 16013773, 21750665, 3714552, -17401782, -16055433, -3770287, -10323320, 31322514, -11615635 }, + { 21426655, -5650218, -13648287, -5347537, -28812189, -4920970, -18275391, -14621414, 13040862, -12112948 } + }, + { + { 11293895, 12478086, -27136401, 15083750, -29307421, 14748872, 14555558, -13417103, 1613711, 4896935 }, + { -25894883, 15323294, -8489791, -8057900, 25967126, -13425460, 2825960, -4897045, -23971776, -11267415 }, + { -15924766, -5229880, -17443532, 6410664, 3622847, 10243618, 20615400, 12405433, -23753030, -8436416 } + }, + { + { -7091295, 12556208, -20191352, 9025187, -17072479, 4333801, 4378436, 2432030, 23097949, -566018 }, + { 4565804, -16025654, 20084412, -7842817, 1724999, 189254, 24767264, 10103221, -18512313, 2424778 }, + { 366633, -11976806, 8173090, -6890119, 30788634, 5745705, -7168678, 1344109, -3642553, 12412659 } + }, + { + { -24001791, 7690286, 14929416, -168257, -32210835, -13412986, 24162697, -15326504, -3141501, 11179385 }, + { 18289522, -14724954, 8056945, 16430056, -21729724, 7842514, -6001441, -1486897, -18684645, -11443503 }, + { 476239, 6601091, -6152790, -9723375, 17503545, -4863900, 27672959, 13403813, 11052904, 5219329 } + } +}, +{ /* 28/31 */ + { + { 20678546, -8375738, -32671898, 8849123, -5009758, 14574752, 31186971, -3973730, 9014762, -8579056 }, + { -13644050, -10350239, -15962508, 5075808, -1514661, -11534600, -33102500, 9160280, 8473550, -3256838 }, + { 24900749, 14435722, 17209120, -15292541, -22592275, 9878983, -7689309, -16335821, -24568481, 11788948 } + }, + { + { -3118155, -11395194, -13802089, 14797441, 9652448, -6845904, -20037437, 10410733, -24568470, -1458691 }, + { -15659161, 16736706, -22467150, 10215878, -9097177, 7563911, 11871841, -12505194, -18513325, 8464118 }, + { -23400612, 8348507, -14585951, -861714, -3950205, -6373419, 14325289, 8628612, 33313881, -8370517 } + }, + { + { -20186973, -4967935, 22367356, 5271547, -1097117, -4788838, -24805667, -10236854, -8940735, -5818269 }, + { -6948785, -1795212, -32625683, -16021179, 32635414, -7374245, 15989197, -12838188, 28358192, -4253904 }, + { -23561781, -2799059, -32351682, -1661963, -9147719, 10429267, -16637684, 4072016, -5351664, 5596589 } + }, + { + { -28236598, -3390048, 12312896, 6213178, 3117142, 16078565, 29266239, 2557221, 1768301, 15373193 }, + { -7243358, -3246960, -4593467, -7553353, -127927, -912245, -1090902, -4504991, -24660491, 3442910 }, + { -30210571, 5124043, 14181784, 8197961, 18964734, -11939093, 22597931, 7176455, -18585478, 13365930 } + }, + { + { -7877390, -1499958, 8324673, 4690079, 6261860, 890446, 24538107, -8570186, -9689599, -3031667 }, + { 25008904, -10771599, -4305031, -9638010, 16265036, 15721635, 683793, -11823784, 15723479, -15163481 }, + { -9660625, 12374379, -27006999, -7026148, -7724114, -12314514, 11879682, 5400171, 519526, -1235876 } + }, + { + { 22258397, -16332233, -7869817, 14613016, -22520255, -2950923, -20353881, 7315967, 16648397, 7605640 }, + { -8081308, -8464597, -8223311, 9719710, 19259459, -15348212, 23994942, -5281555, -9468848, 4763278 }, + { -21699244, 9220969, -15730624, 1084137, -25476107, -2852390, 31088447, -7764523, -11356529, 728112 } + }, + { + { 26047220, -11751471, -6900323, -16521798, 24092068, 9158119, -4273545, -12555558, -29365436, -5498272 }, + { 17510331, -322857, 5854289, 8403524, 17133918, -3112612, -28111007, 12327945, 10750447, 10014012 }, + { -10312768, 3936952, 9156313, -8897683, 16498692, -994647, -27481051, -666732, 3424691, 7540221 } + }, + { + { 30322361, -6964110, 11361005, -4143317, 7433304, 4989748, -7071422, -16317219, -9244265, 15258046 }, + { 13054562, -2779497, 19155474, 469045, -12482797, 4566042, 5631406, 2711395, 1062915, -5136345 }, + { -19240248, -11254599, -29509029, -7499965, -5835763, 13005411, -6066489, 12194497, 32960380, 1459310 } + } +}, +{ /* 29/31 */ + { + { 19852034, 7027924, 23669353, 10020366, 8586503, -6657907, 394197, -6101885, 18638003, -11174937 }, + { 31395534, 15098109, 26581030, 8030562, -16527914, -5007134, 9012486, -7584354, -6643087, -5442636 }, + { -9192165, -2347377, -1997099, 4529534, 25766844, 607986, -13222, 9677543, -32294889, -6456008 } + }, + { + { -2444496, -149937, 29348902, 8186665, 1873760, 12489863, -30934579, -7839692, -7852844, -8138429 }, + { -15236356, -15433509, 7766470, 746860, 26346930, -10221762, -27333451, 10754588, -9431476, 5203576 }, + { 31834314, 14135496, -770007, 5159118, 20917671, -16768096, -7467973, -7337524, 31809243, 7347066 } + }, + { + { -9606723, -11874240, 20414459, 13033986, 13716524, -11691881, 19797970, -12211255, 15192876, -2087490 }, + { -12663563, -2181719, 1168162, -3804809, 26747877, -14138091, 10609330, 12694420, 33473243, -13382104 }, + { 33184999, 11180355, 15832085, -11385430, -1633671, 225884, 15089336, -11023903, -6135662, 14480053 } + }, + { + { 31308717, -5619998, 31030840, -1897099, 15674547, -6582883, 5496208, 13685227, 27595050, 8737275 }, + { -20318852, -15150239, 10933843, -16178022, 8335352, -7546022, -31008351, -12610604, 26498114, 66511 }, + { 22644454, -8761729, -16671776, 4884562, -3105614, -13559366, 30540766, -4286747, -13327787, -7515095 } + }, + { + { -28017847, 9834845, 18617207, -2681312, -3401956, -13307506, 8205540, 13585437, -17127465, 15115439 }, + { 23711543, -672915, 31206561, -8362711, 6164647, -9709987, -33535882, -1426096, 8236921, 16492939 }, + { -23910559, -13515526, -26299483, -4503841, 25005590, -7687270, 19574902, 10071562, 6708380, -6222424 } + }, + { + { 2101391, -4930054, 19702731, 2367575, -15427167, 1047675, 5301017, 9328700, 29955601, -11678310 }, + { 3096359, 9271816, -21620864, -15521844, -14847996, -7592937, -25892142, -12635595, -9917575, 6216608 }, + { -32615849, 338663, -25195611, 2510422, -29213566, -13820213, 24822830, -6146567, -26767480, 7525079 } + }, + { + { -23066649, -13985623, 16133487, -7896178, -3389565, 778788, -910336, -2782495, -19386633, 11994101 }, + { 21691500, -13624626, -641331, -14367021, 3285881, -3483596, -25064666, 9718258, -7477437, 13381418 }, + { 18445390, -4202236, 14979846, 11622458, -1727110, -3582980, 23111648, -6375247, 28535282, 15779576 } + }, + { + { 30098053, 3089662, -9234387, 16662135, -21306940, 11308411, -14068454, 12021730, 9955285, -16303356 }, + { 9734894, -14576830, -7473633, -9138735, 2060392, 11313496, -18426029, 9924399, 20194861, 13380996 }, + { -26378102, -7965207, -22167821, 15789297, -18055342, -6168792, -1984914, 15707771, 26342023, 10146099 } + } +}, +{ /* 30/31 */ + { + { -26016874, -219943, 21339191, -41388, 19745256, -2878700, -29637280, 2227040, 21612326, -545728 }, + { -13077387, 1184228, 23562814, -5970442, -20351244, -6348714, 25764461, 12243797, -20856566, 11649658 }, + { -10031494, 11262626, 27384172, 2271902, 26947504, -15997771, 39944, 6114064, 33514190, 2333242 } + }, + { + { -21433588, -12421821, 8119782, 7219913, -21830522, -9016134, -6679750, -12670638, 24350578, -13450001 }, + { -4116307, -11271533, -23886186, 4843615, -30088339, 690623, -31536088, -10406836, 8317860, 12352766 }, + { 18200138, -14475911, -33087759, -2696619, -23702521, -9102511, -23552096, -2287550, 20712163, 6719373 } + }, + { + { 26656208, 6075253, -7858556, 1886072, -28344043, 4262326, 11117530, -3763210, 26224235, -3297458 }, + { -17168938, -14854097, -3395676, -16369877, -19954045, 14050420, 21728352, 9493610, 18620611, -16428628 }, + { -13323321, 13325349, 11432106, 5964811, 18609221, 6062965, -5269471, -9725556, -30701573, -16479657 } + }, + { + { -23860538, -11233159, 26961357, 1640861, -32413112, -16737940, 12248509, -5240639, 13735342, 1934062 }, + { 25089769, 6742589, 17081145, -13406266, 21909293, -16067981, -15136294, -3765346, -21277997, 5473616 }, + { 31883677, -7961101, 1083432, -11572403, 22828471, 13290673, -7125085, 12469656, 29111212, -5451014 } + }, + { + { 24244947, -15050407, -26262976, 2791540, -14997599, 16666678, 24367466, 6388839, -10295587, 452383 }, + { -25640782, -3417841, 5217916, 16224624, 19987036, -4082269, -24236251, -5915248, 15766062, 8407814 }, + { -20406999, 13990231, 15495425, 16395525, 5377168, 15166495, -8917023, -4388953, -8067909, 2276718 } + }, + { + { 30157918, 12924066, -17712050, 9245753, 19895028, 3368142, -23827587, 5096219, 22740376, -7303417 }, + { 2041139, -14256350, 7783687, 13876377, -25946985, -13352459, 24051124, 13742383, -15637599, 13295222 }, + { 33338237, -8505733, 12532113, 7977527, 9106186, -1715251, -17720195, -4612972, -4451357, -14669444 } + }, + { + { -20045281, 5454097, -14346548, 6447146, 28862071, 1883651, -2469266, -4141880, 7770569, 9620597 }, + { 23208068, 7979712, 33071466, 8149229, 1758231, -10834995, 30945528, -1694323, -33502340, -14767970 }, + { 1439958, -16270480, -1079989, -793782, 4625402, 10647766, -5043801, 1220118, 30494170, -11440799 } + }, + { + { -5037580, -13028295, -2970559, -3061767, 15640974, -6701666, -26739026, 926050, -1684339, -13333647 }, + { 13908495, -3549272, 30919928, -6273825, -21521863, 7989039, 9021034, 9078865, 3353509, 4033511 }, + { -29663431, -15113610, 32259991, -344482, 24295849, -12912123, 23161163, 8839127, 27485041, 7356032 } + } +}, +{ /* 31/31 */ + { + { 9661027, 705443, 11980065, -5370154, -1628543, 14661173, -6346142, 2625015, 28431036, -16771834 }, + { -23839233, -8311415, -25945511, 7480958, -17681669, -8354183, -22545972, 14150565, 15970762, 4099461 }, + { 29262576, 16756590, 26350592, -8793563, 8529671, -11208050, 13617293, -9937143, 11465739, 8317062 } + }, + { + { -25493081, -6962928, 32500200, -9419051, -23038724, -2302222, 14898637, 3848455, 20969334, -5157516 }, + { -20384450, -14347713, -18336405, 13884722, -33039454, 2842114, -21610826, -3649888, 11177095, 14989547 }, + { -24496721, -11716016, 16959896, 2278463, 12066309, 10137771, 13515641, 2581286, -28487508, 9930240 } + }, + { + { -17751622, -2097826, 16544300, -13009300, -15914807, -14949081, 18345767, -13403753, 16291481, -5314038 }, + { -33229194, 2553288, 32678213, 9875984, 8534129, 6889387, -9676774, 6957617, 4368891, 9788741 }, + { 16660756, 7281060, -10830758, 12911820, 20108584, -8101676, -21722536, -8613148, 16250552, -11111103 } + }, + { + { -19765507, 2390526, -16551031, 14161980, 1905286, 6414907, 4689584, 10604807, -30190403, 4782747 }, + { -1354539, 14736941, -7367442, -13292886, 7710542, -14155590, -9981571, 4383045, 22546403, 437323 }, + { 31665577, -12180464, -16186830, 1491339, -18368625, 3294682, 27343084, 2786261, -30633590, -14097016 } + }, + { + { -14467279, -683715, -33374107, 7448552, 19294360, 14334329, -19690631, 2355319, -19284671, -6114373 }, + { 15121312, -15796162, 6377020, -6031361, -10798111, -12957845, 18952177, 15496498, -29380133, 11754228 }, + { -2637277, -13483075, 8488727, -14303896, 12728761, -1622493, 7141596, 11724556, 22761615, -10134141 } + }, + { + { 16918416, 11729663, -18083579, 3022987, -31015732, -13339659, -28741185, -12227393, 32851222, 11717399 }, + { 11166634, 7338049, -6722523, 4531520, -29468672, -7302055, 31474879, 3483633, -1193175, -4030831 }, + { -185635, 9921305, 31456609, -13536438, -12013818, 13348923, 33142652, 6546660, -19985279, -3948376 } + }, + { + { -32460596, 11266712, -11197107, -7899103, 31703694, 3855903, -8537131, -12833048, -30772034, -15486313 }, + { -18006477, 12709068, 3991746, -6479188, -21491523, -10550425, -31135347, -16049879, 10928917, 3011958 }, + { -6957757, -15594337, 31696059, 334240, 29576716, 14796075, -30831056, -12805180, 18008031, 10258577 } + }, + { + { -22448644, 15655569, 7018479, -4410003, -30314266, -1201591, -1853465, 1367120, 25127874, 6671743 }, + { 29701166, -14373934, -10878120, 9279288, -17568, 13127210, 21382910, 11042292, 25838796, 4642684 }, + { -20430234, 14955537, -24126347, 8124619, -5369288, -5990470, 30468147, -13900640, 18423289, 4177476 } + } +} diff --git a/packages/runtime/vendor/libsodium/fe_25_5/base2.h b/packages/runtime/vendor/libsodium/fe_25_5/base2.h new file mode 100644 index 000000000..90a1457ea --- /dev/null +++ b/packages/runtime/vendor/libsodium/fe_25_5/base2.h @@ -0,0 +1,40 @@ +{ + { 25967493, -14356035, 29566456, 3660896, -12694345, 4014787, 27544626, -11754271, -6079156, 2047605 }, + { -12545711, 934262, -2722910, 3049990, -727428, 9406986, 12720692, 5043384, 19500929, -15469378 }, + { -8738181, 4489570, 9688441, -14785194, 10184609, -12363380, 29287919, 11864899, -24514362, -4438546 } +}, +{ + { 15636291, -9688557, 24204773, -7912398, 616977, -16685262, 27787600, -14772189, 28944400, -1550024 }, + { 16568933, 4717097, -11556148, -1102322, 15682896, -11807043, 16354577, -11775962, 7689662, 11199574 }, + { 30464156, -5976125, -11779434, -15670865, 23220365, 15915852, 7512774, 10017326, -17749093, -9920357 } +}, +{ + { 10861363, 11473154, 27284546, 1981175, -30064349, 12577861, 32867885, 14515107, -15438304, 10819380 }, + { 4708026, 6336745, 20377586, 9066809, -11272109, 6594696, -25653668, 12483688, -12668491, 5581306 }, + { 19563160, 16186464, -29386857, 4097519, 10237984, -4348115, 28542350, 13850243, -23678021, -15815942 } +}, +{ + { 5153746, 9909285, 1723747, -2777874, 30523605, 5516873, 19480852, 5230134, -23952439, -15175766 }, + { -30269007, -3463509, 7665486, 10083793, 28475525, 1649722, 20654025, 16520125, 30598449, 7715701 }, + { 28881845, 14381568, 9657904, 3680757, -20181635, 7843316, -31400660, 1370708, 29794553, -1409300 } +}, +{ + { -22518993, -6692182, 14201702, -8745502, -23510406, 8844726, 18474211, -1361450, -13062696, 13821877 }, + { -6455177, -7839871, 3374702, -4740862, -27098617, -10571707, 31655028, -7212327, 18853322, -14220951 }, + { 4566830, -12963868, -28974889, -12240689, -7602672, -2830569, -8514358, -10431137, 2207753, -3209784 } +}, +{ + { -25154831, -4185821, 29681144, 7868801, -6854661, -9423865, -12437364, -663000, -31111463, -16132436 }, + { 25576264, -2703214, 7349804, -11814844, 16472782, 9300885, 3844789, 15725684, 171356, 6466918 }, + { 23103977, 13316479, 9739013, -16149481, 817875, -15038942, 8965339, -14088058, -30714912, 16193877 } +}, +{ + { -33521811, 3180713, -2394130, 14003687, -16903474, -16270840, 17238398, 4729455, -18074513, 9256800 }, + { -25182317, -4174131, 32336398, 5036987, -21236817, 11360617, 22616405, 9761698, -19827198, 630305 }, + { -13720693, 2639453, -24237460, -7406481, 9494427, -5774029, -6554551, -15960994, -2449256, -14291300 } +}, +{ + { -3151181, -5046075, 9282714, 6866145, -31907062, -863023, -18940575, 15033784, 25105118, -7894876 }, + { -24326370, 15950226, -31801215, -14592823, -11662737, -5090925, 1573892, -2625887, 2198790, -15804619 }, + { -3099351, 10324967, -2241613, 7453183, -5446979, -2735503, -13812022, -16236442, -32461234, -12290683 } +} diff --git a/packages/runtime/vendor/libsodium/fe_25_5/constants.h b/packages/runtime/vendor/libsodium/fe_25_5/constants.h new file mode 100644 index 000000000..dd6da1b87 --- /dev/null +++ b/packages/runtime/vendor/libsodium/fe_25_5/constants.h @@ -0,0 +1,40 @@ +/* 37095705934669439343138083508754565189542113879843219016388785533085940283555 */ +static const fe25519 d = { + -10913610, 13857413, -15372611, 6949391, 114729, -8787816, -6275908, -3247719, -18696448, -12055116 +}; + +/* 2 * d = + * 16295367250680780974490674513165176452449235426866156013048779062215315747161 + */ +static const fe25519 d2 = { + -21827239, -5839606, -30745221, 13898782, 229458, 15978800, -12551817, -6495438, 29715968, 9444199 }; + +/* sqrt(-1) */ +static const fe25519 sqrtm1 = { + -32595792, -7943725, 9377950, 3500415, 12389472, -272473, -25146209, -2005654, 326686, 11406482 +}; + +/* A = 486662 */ +static const fe25519 curve25519_A = { + 486662, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +/* sqrt(ad - 1) with a = -1 (mod p) */ +static const fe25519 sqrtadm1 = { + 24849947, -153582, -23613485, 6347715, -21072328, -667138, -25271143, -15367704, -870347, 14525639 +}; + +/* 1 / sqrt(a - d) */ +static const fe25519 invsqrtamd = { + 6111485, 4156064, -27798727, 12243468, -25904040, 120897, 20826367, -7060776, 6093568, -1986012 +}; + +/* 1 - d ^ 2 */ +static const fe25519 onemsqd = { + 6275446, -16617371, -22938544, -3773710, 11667077, 7397348, -27922721, 1766195, -24433858, 672203 +}; + +/* (d - 1) ^ 2 */ +static const fe25519 sqdmone = { + 15551795, -11097455, -13425098, -10125071, -11896535, 10178284, -26634327, 4729244, -5282110, -10116402 +}; diff --git a/packages/runtime/vendor/libsodium/fe_25_5/fe.h b/packages/runtime/vendor/libsodium/fe_25_5/fe.h new file mode 100644 index 000000000..9e11afd11 --- /dev/null +++ b/packages/runtime/vendor/libsodium/fe_25_5/fe.h @@ -0,0 +1,220 @@ +/* + Ignores top bit of s. + */ + +void +fe25519_frombytes(fe25519 h, const unsigned char *s) +{ + int64_t h0 = load_4(s); + int64_t h1 = load_3(s + 4) << 6; + int64_t h2 = load_3(s + 7) << 5; + int64_t h3 = load_3(s + 10) << 3; + int64_t h4 = load_3(s + 13) << 2; + int64_t h5 = load_4(s + 16); + int64_t h6 = load_3(s + 20) << 7; + int64_t h7 = load_3(s + 23) << 5; + int64_t h8 = load_3(s + 26) << 4; + int64_t h9 = (load_3(s + 29) & 8388607) << 2; + + int64_t carry0; + int64_t carry1; + int64_t carry2; + int64_t carry3; + int64_t carry4; + int64_t carry5; + int64_t carry6; + int64_t carry7; + int64_t carry8; + int64_t carry9; + + carry9 = (h9 + (int64_t)(1L << 24)) >> 25; + h0 += carry9 * 19; + h9 -= carry9 * ((uint64_t) 1L << 25); + carry1 = (h1 + (int64_t)(1L << 24)) >> 25; + h2 += carry1; + h1 -= carry1 * ((uint64_t) 1L << 25); + carry3 = (h3 + (int64_t)(1L << 24)) >> 25; + h4 += carry3; + h3 -= carry3 * ((uint64_t) 1L << 25); + carry5 = (h5 + (int64_t)(1L << 24)) >> 25; + h6 += carry5; + h5 -= carry5 * ((uint64_t) 1L << 25); + carry7 = (h7 + (int64_t)(1L << 24)) >> 25; + h8 += carry7; + h7 -= carry7 * ((uint64_t) 1L << 25); + + carry0 = (h0 + (int64_t)(1L << 25)) >> 26; + h1 += carry0; + h0 -= carry0 * ((uint64_t) 1L << 26); + carry2 = (h2 + (int64_t)(1L << 25)) >> 26; + h3 += carry2; + h2 -= carry2 * ((uint64_t) 1L << 26); + carry4 = (h4 + (int64_t)(1L << 25)) >> 26; + h5 += carry4; + h4 -= carry4 * ((uint64_t) 1L << 26); + carry6 = (h6 + (int64_t)(1L << 25)) >> 26; + h7 += carry6; + h6 -= carry6 * ((uint64_t) 1L << 26); + carry8 = (h8 + (int64_t)(1L << 25)) >> 26; + h9 += carry8; + h8 -= carry8 * ((uint64_t) 1L << 26); + + h[0] = (int32_t) h0; + h[1] = (int32_t) h1; + h[2] = (int32_t) h2; + h[3] = (int32_t) h3; + h[4] = (int32_t) h4; + h[5] = (int32_t) h5; + h[6] = (int32_t) h6; + h[7] = (int32_t) h7; + h[8] = (int32_t) h8; + h[9] = (int32_t) h9; +} + +/* + Preconditions: + |h| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. + + Write p=2^255-19; q=floor(h/p). + Basic claim: q = floor(2^(-255)(h + 19 2^(-25)h9 + 2^(-1))). + + Proof: + Have |h|<=p so |q|<=1 so |19^2 2^(-255) q|<1/4. + Also have |h-2^230 h9|<2^231 so |19 2^(-255)(h-2^230 h9)|<1/4. + + Write y=2^(-1)-19^2 2^(-255)q-19 2^(-255)(h-2^230 h9). + Then 0> 25; + q = (h0 + q) >> 26; + q = (h1 + q) >> 25; + q = (h2 + q) >> 26; + q = (h3 + q) >> 25; + q = (h4 + q) >> 26; + q = (h5 + q) >> 25; + q = (h6 + q) >> 26; + q = (h7 + q) >> 25; + q = (h8 + q) >> 26; + q = (h9 + q) >> 25; + + /* Goal: Output h-(2^255-19)q, which is between 0 and 2^255-20. */ + h0 += 19 * q; + /* Goal: Output h-2^255 q, which is between 0 and 2^255-20. */ + + carry0 = h0 >> 26; + h1 += carry0; + h0 -= carry0 * ((uint32_t) 1L << 26); + carry1 = h1 >> 25; + h2 += carry1; + h1 -= carry1 * ((uint32_t) 1L << 25); + carry2 = h2 >> 26; + h3 += carry2; + h2 -= carry2 * ((uint32_t) 1L << 26); + carry3 = h3 >> 25; + h4 += carry3; + h3 -= carry3 * ((uint32_t) 1L << 25); + carry4 = h4 >> 26; + h5 += carry4; + h4 -= carry4 * ((uint32_t) 1L << 26); + carry5 = h5 >> 25; + h6 += carry5; + h5 -= carry5 * ((uint32_t) 1L << 25); + carry6 = h6 >> 26; + h7 += carry6; + h6 -= carry6 * ((uint32_t) 1L << 26); + carry7 = h7 >> 25; + h8 += carry7; + h7 -= carry7 * ((uint32_t) 1L << 25); + carry8 = h8 >> 26; + h9 += carry8; + h8 -= carry8 * ((uint32_t) 1L << 26); + carry9 = h9 >> 25; + h9 -= carry9 * ((uint32_t) 1L << 25); + + h[0] = h0; + h[1] = h1; + h[2] = h2; + h[3] = h3; + h[4] = h4; + h[5] = h5; + h[6] = h6; + h[7] = h7; + h[8] = h8; + h[9] = h9; +} + +/* + Goal: Output h0+...+2^255 h10-2^255 q, which is between 0 and 2^255-20. + Have h0+...+2^230 h9 between 0 and 2^255-1; + evidently 2^255 h10-2^255 q = 0. + + Goal: Output h0+...+2^230 h9. + */ + +void +fe25519_tobytes(unsigned char *s, const fe25519 h) +{ + fe25519 t; + + fe25519_reduce(t, h); + s[0] = t[0] >> 0; + s[1] = t[0] >> 8; + s[2] = t[0] >> 16; + s[3] = (t[0] >> 24) | (t[1] * ((uint32_t) 1 << 2)); + s[4] = t[1] >> 6; + s[5] = t[1] >> 14; + s[6] = (t[1] >> 22) | (t[2] * ((uint32_t) 1 << 3)); + s[7] = t[2] >> 5; + s[8] = t[2] >> 13; + s[9] = (t[2] >> 21) | (t[3] * ((uint32_t) 1 << 5)); + s[10] = t[3] >> 3; + s[11] = t[3] >> 11; + s[12] = (t[3] >> 19) | (t[4] * ((uint32_t) 1 << 6)); + s[13] = t[4] >> 2; + s[14] = t[4] >> 10; + s[15] = t[4] >> 18; + s[16] = t[5] >> 0; + s[17] = t[5] >> 8; + s[18] = t[5] >> 16; + s[19] = (t[5] >> 24) | (t[6] * ((uint32_t) 1 << 1)); + s[20] = t[6] >> 7; + s[21] = t[6] >> 15; + s[22] = (t[6] >> 23) | (t[7] * ((uint32_t) 1 << 3)); + s[23] = t[7] >> 5; + s[24] = t[7] >> 13; + s[25] = (t[7] >> 21) | (t[8] * ((uint32_t) 1 << 4)); + s[26] = t[8] >> 4; + s[27] = t[8] >> 12; + s[28] = (t[8] >> 20) | (t[9] * ((uint32_t) 1 << 6)); + s[29] = t[9] >> 2; + s[30] = t[9] >> 10; + s[31] = t[9] >> 18; +} diff --git a/packages/runtime/vendor/libsodium/hash_sha512_cp.c b/packages/runtime/vendor/libsodium/hash_sha512_cp.c new file mode 100644 index 000000000..59a8b9368 --- /dev/null +++ b/packages/runtime/vendor/libsodium/hash_sha512_cp.c @@ -0,0 +1,284 @@ + +/*- + * Copyright 2005,2007,2009 Colin Percival + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + */ + +#include +#include +#include +#include + +#include + +#include "crypto_hash_sha512.h" +#include "common.h" +#include "utils.h" + +static void +be64enc_vect(unsigned char *dst, const uint64_t *src, size_t len) +{ + size_t i; + + for (i = 0; i < len / 8; i++) { + STORE64_BE(dst + i * 8, src[i]); + } +} + +static void +be64dec_vect(uint64_t *dst, const unsigned char *src, size_t len) +{ + size_t i; + + for (i = 0; i < len / 8; i++) { + dst[i] = LOAD64_BE(src + i * 8); + } +} + +static const uint64_t Krnd[80] = { + 0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL, 0xb5c0fbcfec4d3b2fULL, + 0xe9b5dba58189dbbcULL, 0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL, + 0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL, 0xd807aa98a3030242ULL, + 0x12835b0145706fbeULL, 0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL, + 0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL, 0x9bdc06a725c71235ULL, + 0xc19bf174cf692694ULL, 0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL, + 0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL, 0x2de92c6f592b0275ULL, + 0x4a7484aa6ea6e483ULL, 0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL, + 0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL, 0xb00327c898fb213fULL, + 0xbf597fc7beef0ee4ULL, 0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL, + 0x06ca6351e003826fULL, 0x142929670a0e6e70ULL, 0x27b70a8546d22ffcULL, + 0x2e1b21385c26c926ULL, 0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL, + 0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL, 0x81c2c92e47edaee6ULL, + 0x92722c851482353bULL, 0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL, + 0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL, 0xd192e819d6ef5218ULL, + 0xd69906245565a910ULL, 0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL, + 0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL, 0x2748774cdf8eeb99ULL, + 0x34b0bcb5e19b48a8ULL, 0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL, + 0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL, 0x748f82ee5defb2fcULL, + 0x78a5636f43172f60ULL, 0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL, + 0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL, 0xbef9a3f7b2c67915ULL, + 0xc67178f2e372532bULL, 0xca273eceea26619cULL, 0xd186b8c721c0c207ULL, + 0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL, 0x06f067aa72176fbaULL, + 0x0a637dc5a2c898a6ULL, 0x113f9804bef90daeULL, 0x1b710b35131c471bULL, + 0x28db77f523047d84ULL, 0x32caab7b40c72493ULL, 0x3c9ebe0a15c9bebcULL, + 0x431d67c49c100d4cULL, 0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL, + 0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL +}; + +#define Ch(x, y, z) ((x & (y ^ z)) ^ z) +#define Maj(x, y, z) ((x & (y | z)) | (y & z)) +#define SHR(x, n) (x >> n) +#define ROTR(x, n) ROTR64(x, n) +#define S0(x) (ROTR(x, 28) ^ ROTR(x, 34) ^ ROTR(x, 39)) +#define S1(x) (ROTR(x, 14) ^ ROTR(x, 18) ^ ROTR(x, 41)) +#define s0(x) (ROTR(x, 1) ^ ROTR(x, 8) ^ SHR(x, 7)) +#define s1(x) (ROTR(x, 19) ^ ROTR(x, 61) ^ SHR(x, 6)) + +#define RND(a, b, c, d, e, f, g, h, k) \ + h += S1(e) + Ch(e, f, g) + k; \ + d += h; \ + h += S0(a) + Maj(a, b, c); + +#define RNDr(S, W, i, ii) \ + RND(S[(80 - i) % 8], S[(81 - i) % 8], S[(82 - i) % 8], S[(83 - i) % 8], \ + S[(84 - i) % 8], S[(85 - i) % 8], S[(86 - i) % 8], S[(87 - i) % 8], \ + W[i + ii] + Krnd[i + ii]) + +#define MSCH(W, ii, i) \ + W[i + ii + 16] = \ + s1(W[i + ii + 14]) + W[i + ii + 9] + s0(W[i + ii + 1]) + W[i + ii] + +static void +SHA512_Transform(uint64_t *state, const uint8_t block[128], uint64_t W[80], + uint64_t S[8]) +{ + int i; + + be64dec_vect(W, block, 128); + memcpy(S, state, 64); + for (i = 0; i < 80; i += 16) { + RNDr(S, W, 0, i); + RNDr(S, W, 1, i); + RNDr(S, W, 2, i); + RNDr(S, W, 3, i); + RNDr(S, W, 4, i); + RNDr(S, W, 5, i); + RNDr(S, W, 6, i); + RNDr(S, W, 7, i); + RNDr(S, W, 8, i); + RNDr(S, W, 9, i); + RNDr(S, W, 10, i); + RNDr(S, W, 11, i); + RNDr(S, W, 12, i); + RNDr(S, W, 13, i); + RNDr(S, W, 14, i); + RNDr(S, W, 15, i); + if (i == 64) { + break; + } + MSCH(W, 0, i); + MSCH(W, 1, i); + MSCH(W, 2, i); + MSCH(W, 3, i); + MSCH(W, 4, i); + MSCH(W, 5, i); + MSCH(W, 6, i); + MSCH(W, 7, i); + MSCH(W, 8, i); + MSCH(W, 9, i); + MSCH(W, 10, i); + MSCH(W, 11, i); + MSCH(W, 12, i); + MSCH(W, 13, i); + MSCH(W, 14, i); + MSCH(W, 15, i); + } + for (i = 0; i < 8; i++) { + state[i] += S[i]; + } +} + +static const uint8_t PAD[128] = { + 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +static void +SHA512_Pad(crypto_hash_sha512_state *state, uint64_t tmp64[80 + 8]) +{ + unsigned int r; + unsigned int i; + + ACQUIRE_FENCE; + r = (unsigned int) ((state->count[1] >> 3) & 0x7f); + if (r < 112) { + for (i = 0; i < 112 - r; i++) { + state->buf[r + i] = PAD[i]; + } + } else { + for (i = 0; i < 128 - r; i++) { + state->buf[r + i] = PAD[i]; + } + SHA512_Transform(state->state, state->buf, &tmp64[0], &tmp64[80]); + memset(&state->buf[0], 0, 112); + } + be64enc_vect(&state->buf[112], state->count, 16); + SHA512_Transform(state->state, state->buf, &tmp64[0], &tmp64[80]); +} + +int +crypto_hash_sha512_init(crypto_hash_sha512_state *state) +{ + static const uint64_t sha512_initial_state[8] = { + 0x6a09e667f3bcc908ULL, 0xbb67ae8584caa73bULL, 0x3c6ef372fe94f82bULL, + 0xa54ff53a5f1d36f1ULL, 0x510e527fade682d1ULL, 0x9b05688c2b3e6c1fULL, + 0x1f83d9abfb41bd6bULL, 0x5be0cd19137e2179ULL + }; + + state->count[0] = state->count[1] = (uint64_t) 0U; + memcpy(state->state, sha512_initial_state, sizeof sha512_initial_state); + + return 0; +} + +int +crypto_hash_sha512_update(crypto_hash_sha512_state *state, + const unsigned char *in, unsigned long long inlen) +{ + uint64_t tmp64[80 + 8]; + uint64_t bitlen[2]; + unsigned long long i; + unsigned long long r; + + if (inlen <= 0U) { + return 0; + } + ACQUIRE_FENCE; + r = (unsigned long long) ((state->count[1] >> 3) & 0x7f); + + bitlen[1] = ((uint64_t) inlen) << 3; + bitlen[0] = ((uint64_t) inlen) >> 61; + /* LCOV_EXCL_START */ + if ((state->count[1] += bitlen[1]) < bitlen[1]) { + state->count[0]++; + } + /* LCOV_EXCL_STOP */ + state->count[0] += bitlen[0]; + if (inlen < 128 - r) { + for (i = 0; i < inlen; i++) { + state->buf[r + i] = in[i]; + } + return 0; + } + for (i = 0; i < 128 - r; i++) { + state->buf[r + i] = in[i]; + } + SHA512_Transform(state->state, state->buf, &tmp64[0], &tmp64[80]); + in += 128 - r; + inlen -= 128 - r; + + while (inlen >= 128) { + SHA512_Transform(state->state, in, &tmp64[0], &tmp64[80]); + in += 128; + inlen -= 128; + } + inlen &= 127; + for (i = 0; i < inlen; i++) { + state->buf[i] = in[i]; + } + sodium_memzero((void *) tmp64, sizeof tmp64); + + return 0; +} + +int +crypto_hash_sha512_final(crypto_hash_sha512_state *state, unsigned char *out) +{ + uint64_t tmp64[80 + 8]; + + SHA512_Pad(state, tmp64); + be64enc_vect(out, state->state, 64); + sodium_memzero((void *) tmp64, sizeof tmp64); + sodium_memzero((void *) state, sizeof *state); + + return 0; +} + +int +crypto_hash_sha512(unsigned char *out, const unsigned char *in, + unsigned long long inlen) +{ + crypto_hash_sha512_state state; + + crypto_hash_sha512_init(&state); + crypto_hash_sha512_update(&state, in, inlen); + crypto_hash_sha512_final(&state, out); + + return 0; +} diff --git a/packages/runtime/vendor/libsodium/keypair.c b/packages/runtime/vendor/libsodium/keypair.c new file mode 100644 index 000000000..18059adfe --- /dev/null +++ b/packages/runtime/vendor/libsodium/keypair.c @@ -0,0 +1,84 @@ + +#include + +#include "crypto_hash_sha512.h" +#include "crypto_scalarmult_curve25519.h" +#include "crypto_sign_ed25519.h" +#include "sign_ed25519_ref10.h" +#include "ed25519_ref10.h" +#include "randombytes.h" +#include "utils.h" + +int +crypto_sign_ed25519_seed_keypair(unsigned char *pk, unsigned char *sk, + const unsigned char *seed) +{ + ge25519_p3 A; + + crypto_hash_sha512(sk, seed, 32); + sk[0] &= 248; + sk[31] &= 127; + sk[31] |= 64; + + ge25519_scalarmult_base(&A, sk); + ge25519_p3_tobytes(pk, &A); + + memmove(sk, seed, 32); + memmove(sk + 32, pk, 32); + + return 0; +} + +int +crypto_sign_ed25519_keypair(unsigned char *pk, unsigned char *sk) +{ + unsigned char seed[32]; + int ret; + + randombytes_buf(seed, sizeof seed); + ret = crypto_sign_ed25519_seed_keypair(pk, sk, seed); + sodium_memzero(seed, sizeof seed); + + return ret; +} + +int +crypto_sign_ed25519_pk_to_curve25519(unsigned char *curve25519_pk, + const unsigned char *ed25519_pk) +{ + ge25519_p3 A; + fe25519 x; + fe25519 one_minus_y; + + if (ge25519_has_small_order(ed25519_pk) != 0 || + ge25519_frombytes_negate_vartime(&A, ed25519_pk) != 0 || + ge25519_is_on_main_subgroup(&A) == 0) { + return -1; + } + fe25519_1(one_minus_y); + /* assumes A.Z=1 */ + fe25519_sub(one_minus_y, one_minus_y, A.Y); + fe25519_1(x); + fe25519_add(x, x, A.Y); + fe25519_invert(one_minus_y, one_minus_y); + fe25519_mul(x, x, one_minus_y); + fe25519_tobytes(curve25519_pk, x); + + return 0; +} + +int +crypto_sign_ed25519_sk_to_curve25519(unsigned char *curve25519_sk, + const unsigned char *ed25519_sk) +{ + unsigned char h[crypto_hash_sha512_BYTES]; + + crypto_hash_sha512(h, ed25519_sk, 32); + h[0] &= 248; + h[31] &= 127; + h[31] |= 64; + memcpy(curve25519_sk, h, crypto_scalarmult_curve25519_BYTES); + sodium_memzero(h, sizeof h); + + return 0; +} diff --git a/packages/runtime/vendor/libsodium/open.c b/packages/runtime/vendor/libsodium/open.c new file mode 100644 index 000000000..0670866d6 --- /dev/null +++ b/packages/runtime/vendor/libsodium/open.c @@ -0,0 +1,98 @@ + +#include +#include +#include + +#include "crypto_hash_sha512.h" +#include "crypto_sign_ed25519.h" +#include "crypto_verify_32.h" +#include "sign_ed25519_ref10.h" +#include "common.h" +#include "ed25519_ref10.h" +#include "utils.h" + +int +_crypto_sign_ed25519_verify_detached(const unsigned char *sig, + const unsigned char *m, + unsigned long long mlen, + const unsigned char *pk, + int prehashed) +{ + crypto_hash_sha512_state hs; + unsigned char h[64]; + unsigned char rcheck[32]; + ge25519_p3 A; + ge25519_p2 R; + + ACQUIRE_FENCE; +#ifdef ED25519_COMPAT + if (sig[63] & 224) { + return -1; + } +#else + if (sc25519_is_canonical(sig + 32) == 0 || + ge25519_has_small_order(sig) != 0) { + return -1; + } + if (ge25519_is_canonical(pk) == 0 || + ge25519_has_small_order(pk) != 0) { + return -1; + } +#endif + if (ge25519_frombytes_negate_vartime(&A, pk) != 0) { + return -1; + } + _crypto_sign_ed25519_ref10_hinit(&hs, prehashed); + crypto_hash_sha512_update(&hs, sig, 32); + crypto_hash_sha512_update(&hs, pk, 32); + crypto_hash_sha512_update(&hs, m, mlen); + crypto_hash_sha512_final(&hs, h); + sc25519_reduce(h); + + ge25519_double_scalarmult_vartime(&R, h, &A, sig + 32); + ge25519_tobytes(rcheck, &R); + + return crypto_verify_32(rcheck, sig) | (-(rcheck == sig)) | + sodium_memcmp(sig, rcheck, 32); +} + +int +crypto_sign_ed25519_verify_detached(const unsigned char *sig, + const unsigned char *m, + unsigned long long mlen, + const unsigned char *pk) +{ + return _crypto_sign_ed25519_verify_detached(sig, m, mlen, pk, 0); +} + +int +crypto_sign_ed25519_open(unsigned char *m, unsigned long long *mlen_p, + const unsigned char *sm, unsigned long long smlen, + const unsigned char *pk) +{ + unsigned long long mlen; + + if (smlen < 64 || smlen - 64 > crypto_sign_ed25519_MESSAGEBYTES_MAX) { + goto badsig; + } + mlen = smlen - 64; + if (crypto_sign_ed25519_verify_detached(sm, sm + 64, mlen, pk) != 0) { + if (m != NULL) { + memset(m, 0, mlen); + } + goto badsig; + } + if (mlen_p != NULL) { + *mlen_p = mlen; + } + if (m != NULL) { + memmove(m, sm + 64, mlen); + } + return 0; + +badsig: + if (mlen_p != NULL) { + *mlen_p = 0; + } + return -1; +} diff --git a/packages/runtime/vendor/libsodium/randombytes.h b/packages/runtime/vendor/libsodium/randombytes.h new file mode 100644 index 000000000..c83a4df50 --- /dev/null +++ b/packages/runtime/vendor/libsodium/randombytes.h @@ -0,0 +1,72 @@ + +#ifndef randombytes_H +#define randombytes_H + +#include +#include + +#include + +#include "export.h" + +#ifdef __cplusplus +# ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# endif +extern "C" { +#endif + +typedef struct randombytes_implementation { + const char *(*implementation_name)(void); /* required */ + uint32_t (*random)(void); /* required */ + void (*stir)(void); /* optional */ + uint32_t (*uniform)(const uint32_t upper_bound); /* optional, a default implementation will be used if NULL */ + void (*buf)(void * const buf, const size_t size); /* required */ + int (*close)(void); /* optional */ +} randombytes_implementation; + +#define randombytes_BYTES_MAX SODIUM_MIN(SODIUM_SIZE_MAX, 0xffffffffUL) + +#define randombytes_SEEDBYTES 32U +SODIUM_EXPORT +size_t randombytes_seedbytes(void); + +SODIUM_EXPORT +void randombytes_buf(void * const buf, const size_t size) + __attribute__ ((nonnull)); + +SODIUM_EXPORT +void randombytes_buf_deterministic(void * const buf, const size_t size, + const unsigned char seed[randombytes_SEEDBYTES]) + __attribute__ ((nonnull)); + +SODIUM_EXPORT +uint32_t randombytes_random(void); + +SODIUM_EXPORT +uint32_t randombytes_uniform(const uint32_t upper_bound); + +SODIUM_EXPORT +void randombytes_stir(void); + +SODIUM_EXPORT +int randombytes_close(void); + +SODIUM_EXPORT +int randombytes_set_implementation(const randombytes_implementation *impl) + __attribute__ ((nonnull)); + +SODIUM_EXPORT +const char *randombytes_implementation_name(void); + +/* -- NaCl compatibility interface -- */ + +SODIUM_EXPORT +void randombytes(unsigned char * const buf, const unsigned long long buf_len) + __attribute__ ((nonnull)); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/packages/runtime/vendor/libsodium/sign.c b/packages/runtime/vendor/libsodium/sign.c new file mode 100644 index 000000000..1b4a2923c --- /dev/null +++ b/packages/runtime/vendor/libsodium/sign.c @@ -0,0 +1,128 @@ + +#include + +#include "crypto_hash_sha512.h" +#include "crypto_sign_ed25519.h" +#include "sign_ed25519_ref10.h" +#include "ed25519_ref10.h" +#include "randombytes.h" +#include "utils.h" + +void +_crypto_sign_ed25519_ref10_hinit(crypto_hash_sha512_state *hs, int prehashed) +{ + static const unsigned char DOM2PREFIX[32 + 2] = { + 'S', 'i', 'g', 'E', 'd', '2', '5', '5', '1', '9', ' ', + 'n', 'o', ' ', + 'E', 'd', '2', '5', '5', '1', '9', ' ', + 'c', 'o', 'l', 'l', 'i', 's', 'i', 'o', 'n', 's', 1, 0 + }; + + crypto_hash_sha512_init(hs); + if (prehashed) { + crypto_hash_sha512_update(hs, DOM2PREFIX, sizeof DOM2PREFIX); + } +} + +static inline void +_crypto_sign_ed25519_clamp(unsigned char k[32]) +{ + k[0] &= 248; + k[31] &= 127; + k[31] |= 64; +} + +#ifdef ED25519_NONDETERMINISTIC +/* r = hash(k || K || noise || pad || M) (mod q) */ +static void +_crypto_sign_ed25519_synthetic_r_hv(crypto_hash_sha512_state *hs, + unsigned char tmp[64], + const unsigned char az[64]) +{ + crypto_hash_sha512_update(hs, az, 64); + randombytes_buf(tmp, 32); + memset(tmp + 32, 0, 32); + crypto_hash_sha512_update(hs, tmp, 64); +} +#endif + +int +_crypto_sign_ed25519_detached(unsigned char *sig, unsigned long long *siglen_p, + const unsigned char *m, unsigned long long mlen, + const unsigned char *sk, int prehashed) +{ + crypto_hash_sha512_state hs; + unsigned char az[64]; + unsigned char nonce[64]; + unsigned char hram[64]; + ge25519_p3 R; + + _crypto_sign_ed25519_ref10_hinit(&hs, prehashed); + + crypto_hash_sha512(az, sk, 32); +#ifdef ED25519_NONDETERMINISTIC + _crypto_sign_ed25519_synthetic_r_hv(&hs, nonce /* tmp */, az); +#else + crypto_hash_sha512_update(&hs, az + 32, 32); +#endif + + crypto_hash_sha512_update(&hs, m, mlen); + crypto_hash_sha512_final(&hs, nonce); + + memmove(sig + 32, sk + 32, 32); + + sc25519_reduce(nonce); + ge25519_scalarmult_base(&R, nonce); + ge25519_p3_tobytes(sig, &R); + + _crypto_sign_ed25519_ref10_hinit(&hs, prehashed); + crypto_hash_sha512_update(&hs, sig, 64); + crypto_hash_sha512_update(&hs, m, mlen); + crypto_hash_sha512_final(&hs, hram); + + sc25519_reduce(hram); + _crypto_sign_ed25519_clamp(az); + sc25519_muladd(sig + 32, hram, az, nonce); + + sodium_memzero(az, sizeof az); + sodium_memzero(nonce, sizeof nonce); + + if (siglen_p != NULL) { + *siglen_p = 64U; + } + return 0; +} + +int +crypto_sign_ed25519_detached(unsigned char *sig, unsigned long long *siglen_p, + const unsigned char *m, unsigned long long mlen, + const unsigned char *sk) +{ + return _crypto_sign_ed25519_detached(sig, siglen_p, m, mlen, sk, 0); +} + +int +crypto_sign_ed25519(unsigned char *sm, unsigned long long *smlen_p, + const unsigned char *m, unsigned long long mlen, + const unsigned char *sk) +{ + unsigned long long siglen; + + memmove(sm + crypto_sign_ed25519_BYTES, m, mlen); + /* LCOV_EXCL_START */ + if (crypto_sign_ed25519_detached( + sm, &siglen, sm + crypto_sign_ed25519_BYTES, mlen, sk) != 0 || + siglen != crypto_sign_ed25519_BYTES) { + if (smlen_p != NULL) { + *smlen_p = 0; + } + memset(sm, 0, mlen + crypto_sign_ed25519_BYTES); + return -1; + } + /* LCOV_EXCL_STOP */ + + if (smlen_p != NULL) { + *smlen_p = mlen + siglen; + } + return 0; +} diff --git a/packages/runtime/vendor/libsodium/sign_ed25519_ref10.h b/packages/runtime/vendor/libsodium/sign_ed25519_ref10.h new file mode 100644 index 000000000..29f45a854 --- /dev/null +++ b/packages/runtime/vendor/libsodium/sign_ed25519_ref10.h @@ -0,0 +1,18 @@ +#ifndef sign_ed25519_ref10_H +#define sign_ed25519_ref10_H + +void _crypto_sign_ed25519_ref10_hinit(crypto_hash_sha512_state *hs, + int prehashed); + +int _crypto_sign_ed25519_detached(unsigned char *sig, + unsigned long long *siglen_p, + const unsigned char *m, + unsigned long long mlen, + const unsigned char *sk, int prehashed); + +int _crypto_sign_ed25519_verify_detached(const unsigned char *sig, + const unsigned char *m, + unsigned long long mlen, + const unsigned char *pk, + int prehashed); +#endif diff --git a/packages/runtime/vendor/libsodium/utils.h b/packages/runtime/vendor/libsodium/utils.h new file mode 100644 index 000000000..f9b369796 --- /dev/null +++ b/packages/runtime/vendor/libsodium/utils.h @@ -0,0 +1,179 @@ + +#ifndef sodium_utils_H +#define sodium_utils_H + +#include + +#include "export.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef SODIUM_C99 +# if defined(__cplusplus) || !defined(__STDC_VERSION__) || __STDC_VERSION__ < 199901L +# define SODIUM_C99(X) +# else +# define SODIUM_C99(X) X +# endif +#endif + +SODIUM_EXPORT +void sodium_memzero(void * const pnt, const size_t len); + +SODIUM_EXPORT +void sodium_stackzero(const size_t len); + +/* + * WARNING: sodium_memcmp() must be used to verify if two secret keys + * are equal, in constant time. + * It returns 0 if the keys are equal, and -1 if they differ. + * This function is not designed for lexicographical comparisons. + */ +SODIUM_EXPORT +int sodium_memcmp(const void * const b1_, const void * const b2_, size_t len) + __attribute__ ((warn_unused_result)); + +/* + * sodium_compare() returns -1 if b1_ < b2_, 1 if b1_ > b2_ and 0 if b1_ == b2_ + * It is suitable for lexicographical comparisons, or to compare nonces + * and counters stored in little-endian format. + * However, it is slower than sodium_memcmp(). + */ +SODIUM_EXPORT +int sodium_compare(const unsigned char *b1_, const unsigned char *b2_, + size_t len) __attribute__ ((warn_unused_result)); + +SODIUM_EXPORT +int sodium_is_zero(const unsigned char *n, const size_t nlen); + +SODIUM_EXPORT +void sodium_increment(unsigned char *n, const size_t nlen); + +SODIUM_EXPORT +void sodium_add(unsigned char *a, const unsigned char *b, const size_t len); + +SODIUM_EXPORT +void sodium_sub(unsigned char *a, const unsigned char *b, const size_t len); + +SODIUM_EXPORT +char *sodium_bin2hex(char * const hex, const size_t hex_maxlen, + const unsigned char * const bin, const size_t bin_len) + __attribute__ ((nonnull(1))); + +SODIUM_EXPORT +int sodium_hex2bin(unsigned char * const bin, const size_t bin_maxlen, + const char * const hex, const size_t hex_len, + const char * const ignore, size_t * const bin_len, + const char ** const hex_end) + __attribute__ ((nonnull(1))); + +#define sodium_base64_VARIANT_ORIGINAL 1 +#define sodium_base64_VARIANT_ORIGINAL_NO_PADDING 3 +#define sodium_base64_VARIANT_URLSAFE 5 +#define sodium_base64_VARIANT_URLSAFE_NO_PADDING 7 + +/* + * Computes the required length to encode BIN_LEN bytes as a base64 string + * using the given variant. The computed length includes a trailing \0. + */ +#define sodium_base64_ENCODED_LEN(BIN_LEN, VARIANT) \ + (((BIN_LEN) / 3U) * 4U + \ + ((((BIN_LEN) - ((BIN_LEN) / 3U) * 3U) | (((BIN_LEN) - ((BIN_LEN) / 3U) * 3U) >> 1)) & 1U) * \ + (4U - (~((((VARIANT) & 2U) >> 1) - 1U) & (3U - ((BIN_LEN) - ((BIN_LEN) / 3U) * 3U)))) + 1U) + +SODIUM_EXPORT +size_t sodium_base64_encoded_len(const size_t bin_len, const int variant); + +SODIUM_EXPORT +char *sodium_bin2base64(char * const b64, const size_t b64_maxlen, + const unsigned char * const bin, const size_t bin_len, + const int variant) __attribute__ ((nonnull(1))); + +SODIUM_EXPORT +int sodium_base642bin(unsigned char * const bin, const size_t bin_maxlen, + const char * const b64, const size_t b64_len, + const char * const ignore, size_t * const bin_len, + const char ** const b64_end, const int variant) + __attribute__ ((nonnull(1))); + +SODIUM_EXPORT +int sodium_mlock(void * const addr, const size_t len) + __attribute__ ((nonnull)); + +SODIUM_EXPORT +int sodium_munlock(void * const addr, const size_t len) + __attribute__ ((nonnull)); + +/* WARNING: sodium_malloc() and sodium_allocarray() are not general-purpose + * allocation functions. + * + * They return a pointer to a region filled with 0xd0 bytes, immediately + * followed by a guard page. + * As a result, accessing a single byte after the requested allocation size + * will intentionally trigger a segmentation fault. + * + * A canary and an additional guard page placed before the beginning of the + * region may also kill the process if a buffer underflow is detected. + * + * The memory layout is: + * [unprotected region size (read only)][guard page (no access)][unprotected pages (read/write)][guard page (no access)] + * With the layout of the unprotected pages being: + * [optional padding][16-bytes canary][user region] + * + * However: + * - These functions are significantly slower than standard functions + * - Each allocation requires 3 or 4 additional pages + * - The returned address will not be aligned if the allocation size is not + * a multiple of the required alignment. For this reason, these functions + * are designed to store data, such as secret keys and messages. + * + * sodium_malloc() can be used to allocate any libsodium data structure. + * + * The crypto_generichash_state structure is packed and its length is + * either 357 or 361 bytes. For this reason, when using sodium_malloc() to + * allocate a crypto_generichash_state structure, padding must be added in + * order to ensure proper alignment. crypto_generichash_statebytes() + * returns the rounded up structure size, and should be preferred to sizeof(): + * state = sodium_malloc(crypto_generichash_statebytes()); + */ + +SODIUM_EXPORT +void *sodium_malloc(const size_t size) + __attribute__ ((malloc)); + +SODIUM_EXPORT +void *sodium_allocarray(size_t count, size_t size) + __attribute__ ((malloc)); + +SODIUM_EXPORT +void sodium_free(void *ptr); + +SODIUM_EXPORT +int sodium_mprotect_noaccess(void *ptr) __attribute__ ((nonnull)); + +SODIUM_EXPORT +int sodium_mprotect_readonly(void *ptr) __attribute__ ((nonnull)); + +SODIUM_EXPORT +int sodium_mprotect_readwrite(void *ptr) __attribute__ ((nonnull)); + +SODIUM_EXPORT +int sodium_pad(size_t *padded_buflen_p, unsigned char *buf, + size_t unpadded_buflen, size_t blocksize, size_t max_buflen) + __attribute__ ((nonnull(2))); + +SODIUM_EXPORT +int sodium_unpad(size_t *unpadded_buflen_p, const unsigned char *buf, + size_t padded_buflen, size_t blocksize) + __attribute__ ((nonnull(2))); + +/* -------- */ + +int _sodium_alloc_init(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/packages/runtime/vendor/libsodium/verify.c b/packages/runtime/vendor/libsodium/verify.c new file mode 100644 index 000000000..0c3323a50 --- /dev/null +++ b/packages/runtime/vendor/libsodium/verify.c @@ -0,0 +1,95 @@ + +#include +#include + +#include "crypto_verify_16.h" +#include "crypto_verify_32.h" +#include "crypto_verify_64.h" + +size_t +crypto_verify_16_bytes(void) +{ + return crypto_verify_16_BYTES; +} + +size_t +crypto_verify_32_bytes(void) +{ + return crypto_verify_32_BYTES; +} + +size_t +crypto_verify_64_bytes(void) +{ + return crypto_verify_64_BYTES; +} + +#if defined(HAVE_EMMINTRIN_H) && defined(__SSE2__) + +# include + +static inline int +crypto_verify_n(const unsigned char *x_, const unsigned char *y_, + const int n) +{ + const __m128i zero = _mm_setzero_si128(); + volatile __m128i v1, v2, z; + volatile int m; + int i; + + const volatile __m128i *volatile x = + (const volatile __m128i *volatile) (const void *) x_; + const volatile __m128i *volatile y = + (const volatile __m128i *volatile) (const void *) y_; + v1 = _mm_loadu_si128((const __m128i *) &x[0]); + v2 = _mm_loadu_si128((const __m128i *) &y[0]); + z = _mm_xor_si128(v1, v2); + for (i = 1; i < n / 16; i++) { + v1 = _mm_loadu_si128((const __m128i *) &x[i]); + v2 = _mm_loadu_si128((const __m128i *) &y[i]); + z = _mm_or_si128(z, _mm_xor_si128(v1, v2)); + } + m = _mm_movemask_epi8(_mm_cmpeq_epi32(z, zero)); + v1 = zero; v2 = zero; z = zero; + + return (int) (((uint32_t) m + 1U) >> 16) - 1; +} + +#else + +static inline int +crypto_verify_n(const unsigned char *x_, const unsigned char *y_, + const int n) +{ + const volatile unsigned char *volatile x = + (const volatile unsigned char *volatile) x_; + const volatile unsigned char *volatile y = + (const volatile unsigned char *volatile) y_; + volatile uint_fast16_t d = 0U; + int i; + + for (i = 0; i < n; i++) { + d |= x[i] ^ y[i]; + } + return (1 & ((d - 1) >> 8)) - 1; +} + +#endif + +int +crypto_verify_16(const unsigned char *x, const unsigned char *y) +{ + return crypto_verify_n(x, y, crypto_verify_16_BYTES); +} + +int +crypto_verify_32(const unsigned char *x, const unsigned char *y) +{ + return crypto_verify_n(x, y, crypto_verify_32_BYTES); +} + +int +crypto_verify_64(const unsigned char *x, const unsigned char *y) +{ + return crypto_verify_n(x, y, crypto_verify_64_BYTES); +} diff --git a/packages/threads/package.json b/packages/threads/package.json index 2aeeb7cbb..11b8ef624 100644 --- a/packages/threads/package.json +++ b/packages/threads/package.json @@ -1,6 +1,6 @@ { "name": "@scriptc/threads", - "version": "0.4.1", + "version": "0.4.2", "description": "Zero-copy publication of immutable object graphs to worker threads (scriptc), with a deep-freezing Node.js implementation", "license": "Apache-2.0", "homepage": "https://scriptc.dev", diff --git a/packages/types/package.json b/packages/types/package.json index ffbbdf4a4..689c7b72f 100644 --- a/packages/types/package.json +++ b/packages/types/package.json @@ -1,6 +1,6 @@ { "name": "@scriptc/types", - "version": "0.4.1", + "version": "0.4.2", "description": "Contract types for scriptc: type-only annotations (Int32, NoThrow, Immutable) that scriptc checks and optimizes, with no runtime semantics", "license": "Apache-2.0", "homepage": "https://scriptc.dev", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 3974f346e..589de2a51 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -30,8 +30,8 @@ importers: specifier: 3.22.2 version: 3.22.2 js-yaml: - specifier: 4.3.0 - version: 4.3.0 + specifier: 4.3.2 + version: 4.3.2 oxfmt: specifier: 0.71.0 version: 0.71.0 @@ -41,6 +41,9 @@ importers: rollup: specifier: 4.62.2 version: 4.62.2 + smol-toml: + specifier: 1.7.1 + version: 1.7.1 three: specifier: 0.186.1 version: 0.186.1 @@ -52,7 +55,7 @@ importers: version: 5.9.3 vercel: specifier: 58.1.0 - version: 58.1.0(@emnapi/core@2.0.0-alpha.3)(@emnapi/runtime@2.0.0-alpha.3)(rollup@4.62.2) + version: 58.1.0(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3)(rollup@4.62.2) vitest: specifier: ^3.0.0 version: 3.2.7(patch_hash=03a418fae669c2cd9846dc3c49e6c1b8ee7047bbdcda9d4f5d5ee09eb525a1be)(@edge-runtime/vm@3.2.0)(@types/node@24.13.3)(tsx@4.23.0) @@ -107,8 +110,8 @@ importers: specifier: workspace:* version: link:../runtime tsc-ts: - specifier: 0.0.5 - version: 0.0.5 + specifier: 0.0.7 + version: 0.0.7 typescript: specifier: 7.0.2 version: 7.0.2 @@ -268,14 +271,14 @@ packages: effect: ^4.0.0 redis: '>=5.0.0 <7.0.0' - '@emnapi/core@2.0.0-alpha.3': - resolution: {integrity: sha512-AZypUeJ/yByuxyS7BlSNRDOMLMlROYtjYdIAuBmJssVz1UJDSeYxLrdizhXCFYhedC5bqd/ASy8EuNXbVVXp9g==} + '@emnapi/core@1.11.3': + resolution: {integrity: sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg==} - '@emnapi/runtime@2.0.0-alpha.3': - resolution: {integrity: sha512-hFPAhMUjJD9BSyCANEISPOogeXC9Zo9ZQl7L6vKnaVsMkCtzznaW/naYypeyl0Gv5rYfWYsZbpixTMpjDJzQeA==} + '@emnapi/runtime@1.11.3': + resolution: {integrity: sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==} - '@emnapi/wasi-threads@2.0.1': - resolution: {integrity: sha512-9DsSk+o5NBX0CCJT8s0EROGSGxjR/tKu6aBTaVyq+SjAEQH4XcdcRxPBRzsBLizTTJ49MJjF+jgu3qnO9GLQcQ==} + '@emnapi/wasi-threads@1.2.3': + resolution: {integrity: sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g==} '@esbuild/aix-ppc64@0.27.0': resolution: {integrity: sha512-KuZrd2hRjz01y5JK9mEBSD3Vj3mbCvemhT466rSuJYeE/hjuBrHfjjcjMdTm/sz7au+++sdbJZJmuBwQLuw68A==} @@ -1357,8 +1360,8 @@ packages: cpu: [x64] os: [win32] - '@scriptc/threads@0.3.6': - resolution: {integrity: sha512-XZb4JhXM/ivhx4MMLxqLLF2mCI28nUK+VVKlCnELO83tacUuGlq7YCe/8LwvzO7fZwy/rCH4+genAYYEc6BF6Q==} + '@scriptc/threads@0.4.1': + resolution: {integrity: sha512-wKgEBiVc07ZIGNFGwJpV5JbTXJN1N42qG6/g7ipnwt3klsU0nuWH2ToKV9vYH+RQstF7+twq6zMCf2qhUloTHQ==} engines: {node: '>=24.0.0'} '@sinclair/typebox@0.25.24': @@ -1374,42 +1377,42 @@ packages: '@ts-morph/common@0.11.1': resolution: {integrity: sha512-7hWZS0NRpEsNV8vWJzg7FEz6V8MaLNeJOmwmghqUXTpzk16V1LLZhdo+4QvE/+zv4cVci0OviuJFnqhEfoV3+g==} - '@tsc-ts/darwin-arm64@0.0.5': - resolution: {integrity: sha512-yP64b2VpAKWG92KepBqxs1P89wpwiheYwNMk4EmmhSl6aw/ImIBrdHYNjvao3sg6FHZCXTc+PB6Vukh6hyQiJQ==} + '@tsc-ts/darwin-arm64@0.0.7': + resolution: {integrity: sha512-nIaTJKBpG6n60xxRYfBlh02G6aSO2punIvj4qPy8/CXZu0Kw4ra/J3PYJtrtYMIh/eIGo4+f1Q01v5dFPPwZbw==} cpu: [arm64] os: [darwin] - '@tsc-ts/darwin-x64@0.0.5': - resolution: {integrity: sha512-CEeHOFfpx5H9V3WSq+V7XGU8tfc06nRN818auiRVwuwPHvpti9gHq0HYkvf/43PH1pIGcgf68sQYdIxJhrQDKQ==} + '@tsc-ts/darwin-x64@0.0.7': + resolution: {integrity: sha512-8ITDyF3FG4SYeS1cV4+oRpbbk0jVsfd23Ww138wbQymbOLYjWPafzj4bymxnIE5kEWjZPVqTFDbaYqgWwNStag==} cpu: [x64] os: [darwin] - '@tsc-ts/linux-arm64-gnu@0.0.5': - resolution: {integrity: sha512-qwybOqGDEa35eV9x/3WO81ExAUbUMY8288ATC83kUfYGmOAVStaO+JM2IdrsiI8hLWVC7/f0RFgZ+7dyWh9/nA==} + '@tsc-ts/linux-arm64-gnu@0.0.7': + resolution: {integrity: sha512-nXGjtbM3YrARWOb+nkDaFdhKGSzPf3ofl/gV4x8JnVQ8SgK4IWJ5J0u93sk3mTYgdLj/Gcobp/D3lZ6WIzjKvA==} cpu: [arm64] os: [linux] libc: [glibc] - '@tsc-ts/linux-arm64-musl@0.0.5': - resolution: {integrity: sha512-6oSw3NbQIrnxxCRuEe190MbMFoOrM+P+u1usascQMgSjsMcVRnJ/ztvTnRrCDtfPEHJ5EC8drgWIpcdrhGsB0w==} + '@tsc-ts/linux-arm64-musl@0.0.7': + resolution: {integrity: sha512-hSjpQsOhrLaDsbvEO5EH9nC3Vy0WAt3aB+GejytEh9fl4F3kT0BasbBP4wJqu6S5SG9upLW7ZClXiNVnGYDGlQ==} cpu: [arm64] os: [linux] libc: [musl] - '@tsc-ts/linux-x64-gnu@0.0.5': - resolution: {integrity: sha512-KrlBLUcG7M6p7lN+ke+kHVLqy7IiY/H0FxFZzq5slXanhrps/BfjdkUahsyREg7KVprr08xFuXqJTBtLEI4eow==} + '@tsc-ts/linux-x64-gnu@0.0.7': + resolution: {integrity: sha512-MCU2MFefQGG/++nepg09BtYnsN2mVzeYfIS6GW30ChxUt2nJUMkEvzbDim9czDevW4LRqHgfnwEt+hs2ud1SDQ==} cpu: [x64] os: [linux] libc: [glibc] - '@tsc-ts/linux-x64-musl@0.0.5': - resolution: {integrity: sha512-fr8yGzkocCcTYoE+NwC+/WGPNteQ2GmOPJTy/z9NcsLchnpSIZ1fzFll15UYPKQlwQdNRJXxKK3npVBtLRdHTg==} + '@tsc-ts/linux-x64-musl@0.0.7': + resolution: {integrity: sha512-abTZZkn74772MPABStuXWJ1GHI07nbEf4a3Nwl7NYI5mLFYxeLSbq6+cGh0BUJeBeMhFNsjtQ5/j5sGmsrJ2tg==} cpu: [x64] os: [linux] libc: [musl] - '@tsc-ts/win32-x64-msvc@0.0.5': - resolution: {integrity: sha512-SQwufJafzsiOBYncHOxYkyELWjLlBijcKB+xOs6hr6Lxxp5MMLoPtvDFNG88c7G5xv2TDb1XbvyxnjQltr6SHw==} + '@tsc-ts/win32-x64-msvc@0.0.7': + resolution: {integrity: sha512-EOhLTkuWYytJYklR5BI1jRtTpEIPh1FQJKD8R37qqlcnPrELlRO6Nc2ncDpdCoYbpN+KrewIVPB3xD4o3VGUaw==} cpu: [x64] os: [win32] @@ -2089,8 +2092,8 @@ packages: resolution: {integrity: sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==} hasBin: true - js-yaml@4.3.0: - resolution: {integrity: sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q==} + js-yaml@4.3.2: + resolution: {integrity: sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==} hasBin: true json-schema-to-ts@1.6.4: @@ -2458,6 +2461,10 @@ packages: resolution: {integrity: sha512-QlaZEqcAH3/RtNyet1IPIYPsEWAaYyXXv1Krsi+1L/QHppjX4Ifm8MQsBISz9vE8cHicIq3clogsheili5vhaQ==} engines: {node: '>= 18'} + smol-toml@1.7.1: + resolution: {integrity: sha512-PPlsspAZ4jbMBu5DMFhfUGDQLu/vrL4SyBROVS37x8ynnVmFIs1VPBz1Co8Xks3TvpIaZXmU85y4DrQ+UyVFoQ==} + engines: {node: '>= 18'} + source-map-js@1.2.1: resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} engines: {node: '>=0.10.0'} @@ -2570,8 +2577,8 @@ packages: ts-toolbelt@6.15.5: resolution: {integrity: sha512-FZIXf1ksVyLcfr7M317jbB67XFJhOO1YqdTcuGaq9q5jLUoTikukZ+98TPjKiP2jC5CgmYdWWYs0s2nLSU0/1A==} - tsc-ts@0.0.5: - resolution: {integrity: sha512-Eea+zNv7y696pqNZtXBd0AX7/6PXIhR7aaEb0EhgpHadbk7VEiURD94/NngeLpYWts2tPjetkpwFLJY0+6yOnQ==} + tsc-ts@0.0.7: + resolution: {integrity: sha512-KRWTXRUvwMXi4At6xOWPDa/0BreY3MR2tPHooEMNWLZUA2eLphNe7PJiHclPLLn9RCnHY4ffDTTeF5hqgyBvtA==} engines: {node: '>=20'} hasBin: true @@ -2833,18 +2840,18 @@ snapshots: - bufferutil - utf-8-validate - '@emnapi/core@2.0.0-alpha.3': + '@emnapi/core@1.11.3': dependencies: - '@emnapi/wasi-threads': 2.0.1 + '@emnapi/wasi-threads': 1.2.3 tslib: 2.8.1 optional: true - '@emnapi/runtime@2.0.0-alpha.3': + '@emnapi/runtime@1.11.3': dependencies: tslib: 2.8.1 optional: true - '@emnapi/wasi-threads@2.0.1': + '@emnapi/wasi-threads@1.2.3': dependencies: tslib: 2.8.1 optional: true @@ -3083,10 +3090,10 @@ snapshots: '@napi-rs/keyring-win32-ia32-msvc': 1.2.0 '@napi-rs/keyring-win32-x64-msvc': 1.2.0 - '@napi-rs/wasm-runtime@1.1.6(@emnapi/core@2.0.0-alpha.3)(@emnapi/runtime@2.0.0-alpha.3)': + '@napi-rs/wasm-runtime@1.1.6(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3)': dependencies: - '@emnapi/core': 2.0.0-alpha.3 - '@emnapi/runtime': 2.0.0-alpha.3 + '@emnapi/core': 1.11.3 + '@emnapi/runtime': 1.11.3 '@tybys/wasm-util': 0.10.3 optional: true @@ -3152,9 +3159,9 @@ snapshots: '@oxc-transform/binding-openharmony-arm64@0.111.0': optional: true - '@oxc-transform/binding-wasm32-wasi@0.111.0(@emnapi/core@2.0.0-alpha.3)(@emnapi/runtime@2.0.0-alpha.3)': + '@oxc-transform/binding-wasm32-wasi@0.111.0(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3)': dependencies: - '@napi-rs/wasm-runtime': 1.1.6(@emnapi/core@2.0.0-alpha.3)(@emnapi/runtime@2.0.0-alpha.3) + '@napi-rs/wasm-runtime': 1.1.6(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3) transitivePeerDependencies: - '@emnapi/core' - '@emnapi/runtime' @@ -3333,9 +3340,9 @@ snapshots: '@rolldown/binding-openharmony-arm64@1.0.0-rc.1': optional: true - '@rolldown/binding-wasm32-wasi@1.0.0-rc.1(@emnapi/core@2.0.0-alpha.3)(@emnapi/runtime@2.0.0-alpha.3)': + '@rolldown/binding-wasm32-wasi@1.0.0-rc.1(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3)': dependencies: - '@napi-rs/wasm-runtime': 1.1.6(@emnapi/core@2.0.0-alpha.3)(@emnapi/runtime@2.0.0-alpha.3) + '@napi-rs/wasm-runtime': 1.1.6(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3) transitivePeerDependencies: - '@emnapi/core' - '@emnapi/runtime' @@ -3432,7 +3439,7 @@ snapshots: '@rollup/rollup-win32-x64-msvc@4.62.2': optional: true - '@scriptc/threads@0.3.6': {} + '@scriptc/threads@0.4.1': {} '@sinclair/typebox@0.25.24': {} @@ -3447,25 +3454,25 @@ snapshots: mkdirp: 1.0.4 path-browserify: 1.0.1 - '@tsc-ts/darwin-arm64@0.0.5': + '@tsc-ts/darwin-arm64@0.0.7': optional: true - '@tsc-ts/darwin-x64@0.0.5': + '@tsc-ts/darwin-x64@0.0.7': optional: true - '@tsc-ts/linux-arm64-gnu@0.0.5': + '@tsc-ts/linux-arm64-gnu@0.0.7': optional: true - '@tsc-ts/linux-arm64-musl@0.0.5': + '@tsc-ts/linux-arm64-musl@0.0.7': optional: true - '@tsc-ts/linux-x64-gnu@0.0.5': + '@tsc-ts/linux-x64-gnu@0.0.7': optional: true - '@tsc-ts/linux-x64-musl@0.0.5': + '@tsc-ts/linux-x64-musl@0.0.7': optional: true - '@tsc-ts/win32-x64-msvc@0.0.5': + '@tsc-ts/win32-x64-msvc@0.0.7': optional: true '@tybys/wasm-util@0.10.3': @@ -3556,7 +3563,7 @@ snapshots: '@typescript/typescript-win32-x64@7.0.2': optional: true - '@vercel/backends@0.8.27(@emnapi/core@2.0.0-alpha.3)(@emnapi/runtime@2.0.0-alpha.3)(rollup@4.62.2)': + '@vercel/backends@0.8.27(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3)(rollup@4.62.2)': dependencies: '@vercel/build-utils': 13.36.0 '@vercel/nft': 1.10.0(rollup@4.62.2) @@ -3564,10 +3571,10 @@ snapshots: execa: 3.2.0 fs-extra: 11.1.0 get-port: 5.1.1 - oxc-transform: 0.111.0(@emnapi/core@2.0.0-alpha.3)(@emnapi/runtime@2.0.0-alpha.3) + oxc-transform: 0.111.0(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3) path-to-regexp: 8.3.0 resolve.exports: 2.0.3 - rolldown: 1.0.0-rc.1(@emnapi/core@2.0.0-alpha.3)(@emnapi/runtime@2.0.0-alpha.3) + rolldown: 1.0.0-rc.1(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3) srvx: 0.11.16 ts-morph: 12.0.0 tsx: 4.21.0 @@ -3593,9 +3600,9 @@ snapshots: cjs-module-lexer: 1.2.3 es-module-lexer: 1.5.0 - '@vercel/cervel@0.1.35(@emnapi/core@2.0.0-alpha.3)(@emnapi/runtime@2.0.0-alpha.3)(rollup@4.62.2)': + '@vercel/cervel@0.1.35(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3)(rollup@4.62.2)': dependencies: - '@vercel/backends': 0.8.27(@emnapi/core@2.0.0-alpha.3)(@emnapi/runtime@2.0.0-alpha.3)(rollup@4.62.2) + '@vercel/backends': 0.8.27(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3)(rollup@4.62.2) transitivePeerDependencies: - '@emnapi/core' - '@emnapi/runtime' @@ -3631,9 +3638,9 @@ snapshots: '@vercel/error-utils@2.2.0': {} - '@vercel/express@0.1.118(@emnapi/core@2.0.0-alpha.3)(@emnapi/runtime@2.0.0-alpha.3)(rollup@4.62.2)': + '@vercel/express@0.1.118(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3)(rollup@4.62.2)': dependencies: - '@vercel/cervel': 0.1.35(@emnapi/core@2.0.0-alpha.3)(@emnapi/runtime@2.0.0-alpha.3)(rollup@4.62.2) + '@vercel/cervel': 0.1.35(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3)(rollup@4.62.2) '@vercel/nft': 1.10.0(rollup@4.62.2) '@vercel/node': 5.9.0(rollup@4.62.2) '@vercel/static-config': 3.4.0 @@ -4305,7 +4312,7 @@ snapshots: dependencies: argparse: 2.0.1 - js-yaml@4.3.0: + js-yaml@4.3.2: dependencies: argparse: 2.0.1 @@ -4435,7 +4442,7 @@ snapshots: os-paths@4.4.0: {} - oxc-transform@0.111.0(@emnapi/core@2.0.0-alpha.3)(@emnapi/runtime@2.0.0-alpha.3): + oxc-transform@0.111.0(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3): optionalDependencies: '@oxc-transform/binding-android-arm-eabi': 0.111.0 '@oxc-transform/binding-android-arm64': 0.111.0 @@ -4453,7 +4460,7 @@ snapshots: '@oxc-transform/binding-linux-x64-gnu': 0.111.0 '@oxc-transform/binding-linux-x64-musl': 0.111.0 '@oxc-transform/binding-openharmony-arm64': 0.111.0 - '@oxc-transform/binding-wasm32-wasi': 0.111.0(@emnapi/core@2.0.0-alpha.3)(@emnapi/runtime@2.0.0-alpha.3) + '@oxc-transform/binding-wasm32-wasi': 0.111.0(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3) '@oxc-transform/binding-win32-arm64-msvc': 0.111.0 '@oxc-transform/binding-win32-ia32-msvc': 0.111.0 '@oxc-transform/binding-win32-x64-msvc': 0.111.0 @@ -4597,7 +4604,7 @@ snapshots: reusify@1.1.0: {} - rolldown@1.0.0-rc.1(@emnapi/core@2.0.0-alpha.3)(@emnapi/runtime@2.0.0-alpha.3): + rolldown@1.0.0-rc.1(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3): dependencies: '@oxc-project/types': 0.110.0 '@rolldown/pluginutils': 1.0.0-rc.1 @@ -4612,7 +4619,7 @@ snapshots: '@rolldown/binding-linux-x64-gnu': 1.0.0-rc.1 '@rolldown/binding-linux-x64-musl': 1.0.0-rc.1 '@rolldown/binding-openharmony-arm64': 1.0.0-rc.1 - '@rolldown/binding-wasm32-wasi': 1.0.0-rc.1(@emnapi/core@2.0.0-alpha.3)(@emnapi/runtime@2.0.0-alpha.3) + '@rolldown/binding-wasm32-wasi': 1.0.0-rc.1(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3) '@rolldown/binding-win32-arm64-msvc': 1.0.0-rc.1 '@rolldown/binding-win32-x64-msvc': 1.0.0-rc.1 transitivePeerDependencies: @@ -4694,6 +4701,8 @@ snapshots: smol-toml@1.5.2: {} + smol-toml@1.7.1: {} + source-map-js@1.2.1: {} srvx@0.11.16: {} @@ -4804,17 +4813,17 @@ snapshots: ts-toolbelt@6.15.5: {} - tsc-ts@0.0.5: + tsc-ts@0.0.7: dependencies: - '@scriptc/threads': 0.3.6 + '@scriptc/threads': 0.4.1 optionalDependencies: - '@tsc-ts/darwin-arm64': 0.0.5 - '@tsc-ts/darwin-x64': 0.0.5 - '@tsc-ts/linux-arm64-gnu': 0.0.5 - '@tsc-ts/linux-arm64-musl': 0.0.5 - '@tsc-ts/linux-x64-gnu': 0.0.5 - '@tsc-ts/linux-x64-musl': 0.0.5 - '@tsc-ts/win32-x64-msvc': 0.0.5 + '@tsc-ts/darwin-arm64': 0.0.7 + '@tsc-ts/darwin-x64': 0.0.7 + '@tsc-ts/linux-arm64-gnu': 0.0.7 + '@tsc-ts/linux-arm64-musl': 0.0.7 + '@tsc-ts/linux-x64-gnu': 0.0.7 + '@tsc-ts/linux-x64-musl': 0.0.7 + '@tsc-ts/win32-x64-msvc': 0.0.7 tslib@2.8.1: optional: true @@ -4885,9 +4894,9 @@ snapshots: dependencies: punycode: 2.3.1 - vercel@58.1.0(@emnapi/core@2.0.0-alpha.3)(@emnapi/runtime@2.0.0-alpha.3)(rollup@4.62.2): + vercel@58.1.0(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3)(rollup@4.62.2): dependencies: - '@vercel/backends': 0.8.27(@emnapi/core@2.0.0-alpha.3)(@emnapi/runtime@2.0.0-alpha.3)(rollup@4.62.2) + '@vercel/backends': 0.8.27(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3)(rollup@4.62.2) '@vercel/blob': 2.4.0 '@vercel/build-utils': 13.36.0 '@vercel/cli-auth': 0.3.1 @@ -4895,7 +4904,7 @@ snapshots: '@vercel/container': 0.1.0 '@vercel/detect-agent': 1.2.3 '@vercel/elysia': 0.1.104(rollup@4.62.2) - '@vercel/express': 0.1.118(@emnapi/core@2.0.0-alpha.3)(@emnapi/runtime@2.0.0-alpha.3)(rollup@4.62.2) + '@vercel/express': 0.1.118(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3)(rollup@4.62.2) '@vercel/fastify': 0.1.107(rollup@4.62.2) '@vercel/fun': 1.3.0 '@vercel/go': 3.10.2 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index a3e992b0a..ceb1506e9 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -7,14 +7,15 @@ minimumReleaseAgeExclude: - "effect@4.0.0" - "@effect/platform-node@4.0.0" - "@effect/platform-node-shared@4.0.0" - - "@tsc-ts/darwin-arm64@0.0.5" - - "@tsc-ts/darwin-x64@0.0.5" - - "@tsc-ts/linux-arm64-gnu@0.0.5" - - "@tsc-ts/linux-arm64-musl@0.0.5" - - "@tsc-ts/linux-x64-gnu@0.0.5" - - "@tsc-ts/linux-x64-musl@0.0.5" - - "@tsc-ts/win32-x64-msvc@0.0.5" - - "tsc-ts@0.0.5" + - "@tsc-ts/darwin-arm64@0.0.7" + - "@tsc-ts/darwin-x64@0.0.7" + - "@tsc-ts/linux-arm64-gnu@0.0.7" + - "@tsc-ts/linux-arm64-musl@0.0.7" + - "@tsc-ts/linux-x64-gnu@0.0.7" + - "@tsc-ts/linux-x64-musl@0.0.7" + - "@tsc-ts/win32-x64-msvc@0.0.7" + - "tsc-ts@0.0.7" + - "@scriptc/threads@0.4.1" allowBuilds: esbuild: true overrides: diff --git a/scripts/generate-ts7-ast-schema.mjs b/scripts/generate-ts7-ast-schema.mjs index a1bc80117..3218c8962 100644 --- a/scripts/generate-ts7-ast-schema.mjs +++ b/scripts/generate-ts7-ast-schema.mjs @@ -44,6 +44,7 @@ const enumNames = [ "ModuleDetectionKind", "OuterExpressionKinds", "LanguageVariant", + "JsxEmit", ]; const enumLines = [ "/* eslint-disable @typescript-eslint/no-duplicate-enum-values -- TypeScript aliases are part of the protocol. */", @@ -67,6 +68,7 @@ for (const name of enumNames) { "ModuleKind", "ModuleResolutionKind", "ModuleDetectionKind", + "JsxEmit", ].includes(name) ) { const values = require(join(packageRoot, "dist/enums", `${basename}.js`))[name]; @@ -280,6 +282,26 @@ const adaptedGetters = new Set([ "operand", "questionToken", ]); +// A getter selects its child's wire slot by kind directly: an integer +// switch, without astChildOrder's switch on the child's name. `answer` +// maps a slot to the returned expression; `missing` is returned for kinds +// without the child. +const slotCases = (name, answer, missing) => { + const kindsBySlot = new Map(); + for (const [kind, childNames] of Object.entries(protocol.childProperties)) { + const slot = childNames.indexOf(name); + if (slot < 0) continue; + if (!kindsBySlot.has(slot)) kindsBySlot.set(slot, []); + kindsBySlot.get(slot).push(kind); + } + const lines = [" switch (this.kind) {"]; + for (const [slot, kinds] of [...kindsBySlot].sort((a, b) => a[0] - b[0])) { + for (const kind of kinds) lines.push(` case ${kind}:`); + lines.push(` return ${answer(slot)};`); + } + lines.push(" default:", ` return ${missing};`, " }"); + return lines.join("\n"); +}; const getters = names .filter((name) => !adaptedGetters.has(name)) .map((name) => { @@ -290,12 +312,19 @@ const getters = names .replaceAll("RemoteNode", "AstNode"); const method = type.includes("AstNode |") && type.includes("AstNodeList") - ? "child" + ? "childAt" : type.includes("AstNodeList") - ? "childList" - : "childNode"; - return ` get ${name}(): ${type} {\n return this.${method}(${JSON.stringify(name)});\n }`; + ? "childListAt" + : "childNodeAt"; + return ` get ${name}(): ${type} {\n${slotCases(name, (slot) => `this.${method}(${slot})`, "undefined")}\n }`; }); +// The adapted getters read their raw child through the same slot switch. +const adaptedSlots = [...adaptedGetters] + .sort() + .map( + (name) => + ` private ${name}Slot(): number {\n${slotCases(name, (slot) => String(slot), "-1")}\n }`, + ); const nodeTarget = join(root, "packages/compiler/src/frontend/ts7/ast-node.ts"); const before = readFileSync(nodeTarget, "utf8"); if ( @@ -309,6 +338,7 @@ const after = before.replace( " // BEGIN GENERATED CHILD GETTERS", ` // Generated from typescript@${version}; run scripts/generate-ts7-ast-schema.mjs.`, ...getters, + ...adaptedSlots, " // END GENERATED CHILD GETTERS", ].join("\n"), ); diff --git a/scripts/split/README.md b/scripts/split/README.md new file mode 100644 index 000000000..be8c948ac --- /dev/null +++ b/scripts/split/README.md @@ -0,0 +1,24 @@ +# Split tools + +These scripts split a large source file into smaller files without changing behavior, and carry open branches across the split. Each transform is deterministic: the same config gives the same result on any version of the tree, and rehoming depends on that. + +Run them from a checkout with `node_modules` installed. That checkout is the tools directory (`--tools`) and supplies `typescript` and `oxfmt`. + +## Transforms + +- `split-module.mjs plan|apply ` moves top-level declarations into new files. `plan` computes a manifest from seed declarations, and `apply` does the move. +- `split-methods.mjs apply ` moves class methods into exported functions that take the instance as a parameter (`emitter`). The class keeps a one-line stub with the same signature, so callers don't change. +- `move-state.mjs apply ` moves a group of class fields into a feature's state object, defined in the feature's file with `defineModuleState` (`packages/compiler/src/backend/llvm/emitter-state.ts`). It rewrites `this.` and `emitter.` to `KEY.of(this).` and creates files from templates. It also applies the change's other edits as literal replacements, in order. A replacement whose text isn't found the expected number of times is reported and skipped. + +Each transform takes `--repo ` (the tree to rewrite) and `--tools `, and formats what it writes with the tools checkout's oxfmt and its `.oxfmtrc.jsonc` (`format.mjs`). The formatter reads no configuration from `--repo`, so an `oxfmt.config.ts` a branch commits is never run. The tools read and write the tree's files only at real paths inside `--repo`, and a config's templates and manifest only inside the config's directory. A path that resolves elsewhere, through a symlink or `..`, stops the tool with an error (`confine.mjs`). `configs/` holds the configs of splits that have landed. For example, `configs/loop-state/` moves the loop optimizations' state out of `LlEmitter`. + +## Rehoming an open branch + +```sh +git fetch origin pull//head:pr- +node scripts/split/rehome-split.mjs --branch pr- --onto origin/main --config scripts/split/configs//.json +``` + +The result is the branch `pr--rehomed`, a merge of `origin/main` into the branch. + +The script applies the split's transform to the branch's merge base and to its tip, then cherry-picks the difference onto `--onto`. It records the result as a merge commit with parents (branch tip, `--onto`), so it can be pushed without rewriting the branch; `--squash` makes one ordinary commit instead. Conflicts made only of import lines in the split's files resolve to both sides' imports. Any other conflict stops the script, which lists the files and leaves its scratch worktree for you to resolve. diff --git a/scripts/split/configs/loop-state/emitter-state.template b/scripts/split/configs/loop-state/emitter-state.template new file mode 100644 index 000000000..62dc47b4e --- /dev/null +++ b/scripts/split/configs/loop-state/emitter-state.template @@ -0,0 +1,24 @@ +/* Per-feature emitter state. A feature defines its state in its own file + * with defineModuleState and reads it through the returned key, so adding + * or extending a feature does not edit LlEmitter's field list or + * constructor. */ +import type { LlEmitter } from "./emitter.js"; + +/** A feature's state on an emitter, read with `key.of(emitter)`. */ +export interface EmitterStateKey { + of(emitter: LlEmitter): T; +} + +let moduleSlots = 0; + +/** State that lives for the whole module, created on first read. */ +export function defineModuleState(create: (emitter: LlEmitter) => T): EmitterStateKey { + const slot = moduleSlots++; + return { + of(emitter) { + const states = emitter.moduleStates; + if (slot >= states.length || states[slot] === undefined) states[slot] = create(emitter); + return states[slot] as T; + }, + }; +} diff --git a/scripts/split/configs/loop-state/loop-state.config.json b/scripts/split/configs/loop-state/loop-state.config.json new file mode 100644 index 000000000..e749a4b39 --- /dev/null +++ b/scripts/split/configs/loop-state/loop-state.config.json @@ -0,0 +1,29 @@ +{ + "module": "packages/compiler/src/backend/llvm/emitter.ts", + "class": "LlEmitter", + "dir": "packages/compiler/src/backend/llvm", + "create": { + "emitter-state.ts": "emitter-state.template", + "loop-state.ts": "loop-state.template" + }, + "groups": [ + { + "file": "loop-state.ts", + "key": "LOOPS", + "interfaceName": "LoopState", + "fields": ["unaliasedArrays", "denseLoopsEnabled", "denseLoopEntries", "denseLoop", "countedLoopsEnabled", "byteWindowsEnabled", "byteWindowEntries", "bytesLoopVersionsEnabled", "bytesLoopVersioning", "bytesLoopEntries", "bytesLoopFunction", "provenCountedGuards"] + } + ], + "replacements": [ + { "file": "emitter.ts", "find": "export class LlEmitter {\n", "replace": "export class LlEmitter {\n /** Per-feature state (emitter-state.ts), indexed by each key's slot. */\n readonly moduleStates: unknown[] = [];\n" }, + { "file": "emitter.ts", "find": "import { type DenseArrayLoop } from \"./dense-array-loops.js\";\n", "replace": "" }, + { "file": "emitter.ts", "find": " const initialized = LOOPS.of(this).bytesLoopEntries.get(s);\n", "replace": " const initialized = LOOPS.of(this).bytesLoopEntries!.get(s);\n" }, + { "file": "emit-statements.ts", "find": " ? LOOPS.of(emitter).denseLoop.range\n", "replace": " ? LOOPS.of(emitter).denseLoop!.range\n", "count": 2 }, + { "file": "emit-function.ts", "find": " LOOPS.of(emitter).unaliasedArrays = findUnaliasedLocalArrays(fn);\n", "replace": "" }, + { "file": "emit-function.ts", "find": " LOOPS.of(emitter).countedLoopsEnabled = emitter.debug === null && !fn.async && !fn.generator;\n", "replace": " beginFunctionLoops(emitter, fn, numericFn);\n" }, + { "file": "emit-function.ts", "find": " LOOPS.of(emitter).byteWindowsEnabled = LOOPS.of(emitter).countedLoopsEnabled;\n LOOPS.of(emitter).bytesLoopVersionsEnabled = LOOPS.of(emitter).countedLoopsEnabled;\n LOOPS.of(emitter).bytesLoopEntries = null;\n LOOPS.of(emitter).bytesLoopFunction = fn;\n LOOPS.of(emitter).denseLoopsEnabled = LOOPS.of(emitter).countedLoopsEnabled;\n LOOPS.of(emitter).denseLoop = null;\n LOOPS.of(emitter).denseLoopEntries =\n LOOPS.of(emitter).denseLoopsEnabled && numericFn.locals.some((l) => l.type.kind === \"array\")\n ? findInitializedByteLoopBindings(fn)\n : new Map();\n LOOPS.of(emitter).byteWindowEntries =\n LOOPS.of(emitter).byteWindowsEnabled && numericFn.locals.some((l) => l.type.kind === \"bytes\")\n ? findInitializedByteLoopBindings(fn)\n : new Map();\n", "replace": "" }, + { "file": "emit-function.ts", "find": "import { LOOPS } from \"./loop-state.js\";\n", "replace": "import { beginFunctionLoops, LOOPS } from \"./loop-state.js\";\n" }, + { "file": "emit-function.ts", "find": "import { findUnaliasedLocalArrays } from \"../../ir/array-length-stability.js\";\n", "replace": "" }, + { "file": "emit-function.ts", "find": "import { findInitializedByteLoopBindings } from \"./byte-windows.js\";\n", "replace": "" } + ] +} diff --git a/scripts/split/configs/loop-state/loop-state.template b/scripts/split/configs/loop-state/loop-state.template new file mode 100644 index 000000000..ae9673267 --- /dev/null +++ b/scripts/split/configs/loop-state/loop-state.template @@ -0,0 +1,34 @@ +/* The loop optimizations' per-function state: counted loops, dense array + * loops, byte windows and typed-array loop versioning, and the unaliased + * local arrays they rely on. */ +import { findUnaliasedLocalArrays } from "../../ir/array-length-stability.js"; +import type { IrFunction, IrStmt } from "../../ir/ir.js"; +import { findInitializedByteLoopBindings } from "./byte-windows.js"; +import type { DenseArrayLoop } from "./dense-array-loops.js"; +import type { LlEmitter } from "./emitter.js"; + +/** Sets the loop state for `fn` at the start of its emission; `numericFn` + * is `fn` with its initializer bindings (emitFunction). */ +export function beginFunctionLoops( + emitter: LlEmitter, + fn: IrFunction, + numericFn: IrFunction, +): void { + const loops = LOOPS.of(emitter); + loops.unaliasedArrays = findUnaliasedLocalArrays(fn); + loops.countedLoopsEnabled = emitter.debug === null && !fn.async && !fn.generator; + loops.byteWindowsEnabled = loops.countedLoopsEnabled; + loops.bytesLoopVersionsEnabled = loops.countedLoopsEnabled; + loops.bytesLoopEntries = null; + loops.bytesLoopFunction = fn; + loops.denseLoopsEnabled = loops.countedLoopsEnabled; + loops.denseLoop = null; + loops.denseLoopEntries = + loops.denseLoopsEnabled && numericFn.locals.some((l) => l.type.kind === "array") + ? findInitializedByteLoopBindings(fn) + : new Map(); + loops.byteWindowEntries = + loops.byteWindowsEnabled && numericFn.locals.some((l) => l.type.kind === "bytes") + ? findInitializedByteLoopBindings(fn) + : new Map(); +} diff --git a/scripts/split/confine.mjs b/scripts/split/confine.mjs new file mode 100644 index 000000000..14af8b85a --- /dev/null +++ b/scripts/split/confine.mjs @@ -0,0 +1,89 @@ +/* Path confinement for the split tools. A branch they rewrite can commit + * symlinks, so every file a tool reads or writes goes through a guard for + * the directory it belongs to (the checkout being rewritten, or the + * config's directory). The guard resolves the path's real location, through + * every symlink on the way, and throws when that location is outside the + * directory's real path. A path that doesn't exist yet resolves through its + * nearest existing parent, so a write can't create a file through a + * symlinked directory or a dangling symlink either. */ +import { + existsSync, + lstatSync, + mkdirSync, + readdirSync, + readFileSync, + readlinkSync, + realpathSync, + writeFileSync, +} from "node:fs"; +import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; + +const isInside = (root, path) => { + const rel = relative(root, path); + return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)); +}; + +/** The real location of `path`, which need not exist: the real path of its + * nearest existing entry joined with the rest. A dangling symlink resolves + * to where its target would be. */ +function realLocation(path, hops = 0) { + const rest = []; + for (let at = resolve(path); ; at = dirname(at)) { + let stat = null; + try { + stat = lstatSync(at); + } catch (e) { + if (e.code !== "ENOENT" && e.code !== "ENOTDIR") throw e; + } + if (stat) { + try { + return join(realpathSync(at), ...rest); + } catch (e) { + if (e.code !== "ENOENT" || !stat.isSymbolicLink() || hops > 40) throw e; + return realLocation(join(resolve(dirname(at), readlinkSync(at)), ...rest), hops + 1); + } + } + if (dirname(at) === at) return resolve(path); + rest.unshift(basename(at)); + } +} + +/** A guard for the files under `root`. */ +export function confine(root) { + const lexical = resolve(root); + const real = realpathSync(lexical); + const check = (path) => { + const location = realLocation(path); + if (!isInside(real, location)) + throw new Error(`refusing ${path}: it resolves to ${location}, outside ${real}`); + return location; + }; + return { + /** The path's real location; throws when it is outside the root. */ + check, + /** True when `path` names a file under the root (before symlinks). */ + contains: (path) => isInside(lexical, resolve(path)) || isInside(real, resolve(path)), + read: (path) => readFileSync(check(path), "utf8"), + write: (path, text) => writeFileSync(check(path), text), + exists: (path) => existsSync(check(path)), + mkdir: (path) => mkdirSync(check(path), { recursive: true }), + list: (path) => readdirSync(check(path)), + }; +} + +/** Routes a TypeScript host's (or `ts.sys`-like object's) file reads under + * the guard's root through the guard; other files (the TypeScript libraries) + * read as before. */ +export function confineHost(host, guard) { + const checked = + (read) => + (fileName, ...rest) => { + if (guard.contains(fileName)) guard.check(fileName); + return read.call(host, fileName, ...rest); + }; + return { + ...host, + ...(host.getSourceFile ? { getSourceFile: checked(host.getSourceFile) } : {}), + readFile: checked(host.readFile), + }; +} diff --git a/scripts/split/format.mjs b/scripts/split/format.mjs new file mode 100644 index 000000000..10c1fbc8a --- /dev/null +++ b/scripts/split/format.mjs @@ -0,0 +1,20 @@ +/* Formatting for the split tools. oxfmt reads its configuration from the + * directory it runs in, its parents and the formatted files' directories, + * and an oxfmt.config.ts there is code it runs. The tools format files in + * a checkout they rewrite, which can be a pull request's, so they pass the + * tools checkout's own configuration and turn the nested lookup off: no + * configuration file of the rewritten checkout is read or run. */ +import { execFileSync } from "node:child_process"; +import { join } from "node:path"; + +/** Formats `files` (paths relative to `cwd`) with the tools checkout's + * oxfmt and configuration. */ +export function formatFiles(toolsDir, files, { cwd, stdio }) { + // With no file arguments oxfmt would format the whole directory. + if (files.length === 0) return; + execFileSync( + join(toolsDir, "node_modules/.bin/oxfmt"), + ["--config", join(toolsDir, ".oxfmtrc.jsonc"), "--disable-nested-config", ...files], + { cwd, stdio }, + ); +} diff --git a/scripts/split/move-state.mjs b/scripts/split/move-state.mjs new file mode 100644 index 000000000..71306f5d1 --- /dev/null +++ b/scripts/split/move-state.mjs @@ -0,0 +1,206 @@ +#!/usr/bin/env node +/* Move a group of LlEmitter fields into a feature's state object, as a + * deterministic rewrite (the same config gives the same result on any + * version of the tree, which the rehoming tool relies on). + * + * node move-state.mjs apply [--repo ] [--tools ] + * + * : + * { "module": "packages/compiler/src/backend/llvm/emitter.ts", + * "class": "LlEmitter", + * "dir": "packages/compiler/src/backend/llvm", + * "groups": [{ "file": "loop-state.ts", "key": "LOOPS", + * "fields": ["denseLoop", ...] }], + * "create": { "loop-state.ts": "loop-state.template.ts" }, + * "replacements": [{ "file": "emit-function.ts", "find": "...", "replace": "...", "count": 1 }], + * "receivers": ["this", "emitter"] } + * + * For each group: the fields' declarations leave the class (their doc + * comments and initializers move into the state object's interface and + * factory in the group's file), every `this.` and `emitter.` + * (or the config's receivers) in the directory's sources becomes + * `.of(this).` / `.of(emitter).`, and each + * rewritten file imports the key. + * The group's file must already exist and hold everything else (header, + * setup function); the tool appends the interface and key to it. */ +import { readFileSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import { createRequire } from "node:module"; +import { confine } from "./confine.mjs"; +import { formatFiles } from "./format.mjs"; + +const [command, configPath, ...flags] = process.argv.slice(2); +if (command !== "apply") throw new Error("usage: move-state.mjs apply "); +const config = JSON.parse(readFileSync(configPath, "utf8")); +const flag = (name) => { + const i = flags.indexOf(name); + return i >= 0 ? flags[i + 1] : undefined; +}; +const repo = resolve(flag("--repo") ?? process.cwd()); +const toolsDir = resolve(flag("--tools") ?? process.cwd()); +const require = createRequire(join(toolsDir, "package.json")); +const ts = require("typescript"); +const modulePath = join(repo, config.module); +const dir = join(repo, config.dir); +// Every read and write stays inside the checkout, or for the templates, the +// config's directory (confine.mjs). +const checkout = confine(repo); + +// Adds an import line after the file's first block of imports (up to a +// blank line or other code). +const addImport = (text, line) => { + const sf = ts.createSourceFile("x.ts", text, ts.ScriptTarget.Latest, true); + let last; + for (const s of sf.statements) { + if (!ts.isImportDeclaration(s)) break; + if (last && /\n[ \t]*\n/.test(text.slice(last.getEnd(), s.getStart()))) break; + last = s; + } + const at = last ? last.getEnd() + 1 : 0; + return text.slice(0, at) + line + "\n" + text.slice(at); +}; +const configDir = dirname(resolve(configPath)); +const configFiles = confine(configDir); +// The names the class's instance goes by in the directory's sources. +const receivers = config.receivers ?? ["this", "emitter"]; +const touched = new Set(); +// Files the change creates, from templates next to the config (kept when a +// branch already has the file). +for (const [file, template] of Object.entries(config.create ?? {})) { + const path = join(dir, file); + if (checkout.exists(path)) continue; + checkout.write(path, configFiles.read(join(configDir, template))); + touched.add(path); +} +let moduleText = checkout.read(modulePath); +for (const group of config.groups) { + const sf = ts.createSourceFile(modulePath, moduleText, ts.ScriptTarget.Latest, true); + const cls = sf.statements.find((s) => ts.isClassDeclaration(s) && s.name?.text === config.class); + if (!cls) throw new Error(`no class ${config.class}`); + const wanted = new Set(group.fields); + const members = []; + for (const m of cls.members) { + if (ts.isPropertyDeclaration(m) && ts.isIdentifier(m.name) && wanted.has(m.name.text)) + members.push(m); + } + // A field the tree does not have yet (an older merge base) is left out, so + // the move still applies there. + const missing = group.fields.filter((f) => !members.some((m) => m.name.text === f)); + if (missing.length) + console.warn(`${group.file}: fields not in ${config.class}: ${missing.join(", ")}; skipped`); + group.present = members.map((m) => m.name.text); + // Interface members and factory entries, in the class's order. + const iface = []; + const factory = []; + for (const m of members) { + const lead = moduleText.slice(m.getFullStart(), m.getStart()).replace(/^\s*\n/, ""); + const readonly = m.modifiers?.some((x) => x.kind === ts.SyntaxKind.ReadonlyKeyword) + ? "readonly " + : ""; + const name = m.name.text; + if (!m.initializer) + throw new Error( + `${name}: a field without an initializer needs its constructor line moved by hand`, + ); + // An unannotated field takes its initializer's type: a boolean, + // number or string literal, or `new C(...)`. + const init = m.initializer; + const type = m.type + ? m.type.getText(sf) + : init.kind === ts.SyntaxKind.TrueKeyword || init.kind === ts.SyntaxKind.FalseKeyword + ? "boolean" + : ts.isNumericLiteral(init) + ? "number" + : ts.isStringLiteral(init) + ? "string" + : ts.isNewExpression(init) && init.typeArguments?.length + ? `${init.expression.getText(sf)}<${init.typeArguments.map((t) => t.getText(sf)).join(", ")}>` + : null; + if (type === null) throw new Error(`${name}: give the field a type annotation first`); + iface.push(`${lead} ${readonly}${name}: ${type};`); + factory.push(` ${name}: ${m.initializer.getText(sf)},`); + } + // Remove the declarations (with their leading comments) from the class. + const cuts = members.map((m) => [m.getFullStart(), m.getEnd()]).sort((a, b) => b[0] - a[0]); + for (const [s, e] of cuts) moduleText = moduleText.slice(0, s) + moduleText.slice(e); + const iName = group.interface ?? `${group.key[0]}${group.key.slice(1).toLowerCase()}State`; + const stateText = + `\n/** The state ${group.key} holds on each emitter. */\n` + + `export interface ${group.interfaceName ?? iName} {\n${iface.join("\n")}\n}\n\n` + + `export const ${group.key} = defineModuleState<${group.interfaceName ?? iName}>(() => ({\n${factory.join("\n")}\n}));\n`; + const groupPath = join(dir, group.file); + let groupText = checkout.read(groupPath); + if (!groupText.includes('from "./emitter-state.js"')) + groupText = addImport(groupText, `import { defineModuleState } from "./emitter-state.js";`); + groupText = groupText.trimEnd() + "\n" + stateText; + checkout.write(groupPath, groupText); + touched.add(groupPath); + group.rename = group.present.length + ? new RegExp(`(? f.endsWith(".ts"))) { + const path = join(dir, file); + let text = path === modulePath ? moduleText : checkout.read(path); + let changed = false; + for (const group of config.groups) { + if (!group.rename) continue; + const next = text.replace( + group.rename, + (_, recv, field) => `${group.key}.of(${recv}).${field}`, + ); + if (next === text) continue; + text = next; + changed = true; + if (file === group.file) continue; + const spec = `./${group.file.replace(/\.ts$/, ".js")}`; + const existing = new RegExp( + `^import \\{([^}]*)\\} from "${spec.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}";$`, + "m", + ); + const m = existing.exec(text); + if (m) { + const names = new Set( + m[1] + .split(",") + .map((s) => s.trim()) + .filter(Boolean), + ); + names.add(group.key); + text = text.replace(existing, `import { ${[...names].sort().join(", ")} } from "${spec}";`); + } else { + text = addImport(text, `import { ${group.key} } from "${spec}";`); + } + } + if (changed) { + checkout.write(path, text); + touched.add(path); + } +} +// The change's remaining edits, as literal replacements in order (the +// setup function call, imports, narrowing the rename loses). One whose text +// is not found as often as expected is reported and skipped: the branch +// changed that code, and the rehome's cherry-pick shows the difference. +let skipped = 0; +for (const r of config.replacements ?? []) { + const path = join(dir, r.file); + const text = checkout.exists(path) ? checkout.read(path) : ""; + const count = text.split(r.find).length - 1; + if (count !== (r.count ?? 1)) { + console.warn( + `${r.file}: expected ${r.count ?? 1} of ${JSON.stringify(r.find.slice(0, 60))}, found ${count}; skipped`, + ); + skipped++; + continue; + } + checkout.write(path, text.split(r.find).join(r.replace)); + touched.add(path); +} +formatFiles(toolsDir, [...touched], { cwd: repo, stdio: "inherit" }); +if (skipped) console.warn(`${skipped} replacement(s) skipped`); +console.log( + `moved ${config.groups.map((g) => g.present.length).reduce((a, b) => a + b, 0)} fields; rewrote ${touched.size} files`, +); diff --git a/scripts/split/rehome-split.mjs b/scripts/split/rehome-split.mjs new file mode 100644 index 000000000..6533301f8 --- /dev/null +++ b/scripts/split/rehome-split.mjs @@ -0,0 +1,316 @@ +#!/usr/bin/env node +/* Rehome a branch's changes across a module split. + * + * A split moves whole declarations out of one module into new files, so git + * cannot follow a branch's edits into them: merging the split reports every + * edit to a moved declaration as a conflict. This script carries the branch + * across instead. It applies the same split (split-module.mjs, + * split-methods.mjs or move-state.mjs with the split's config; each also + * formats with oxfmt) to the branch's merge base and to the branch tip, and + * cherry-picks the difference onto the target. That is a three-way merge + * whose base and branch side already use the new layout, so each hunk lands + * in the file its declaration moved to. Hunks in declarations that stay, and + * declarations the branch adds, stay in the module. + * + * node rehome-split.mjs --branch --onto --config + * [--out ] [--squash] [--scratch ] + * + * Run it from a checkout with node_modules installed (it supplies typescript + * and oxfmt). --onto is a commit that contains the split, usually main. + * The result is a new branch (default -rehomed). By default its tip + * is a merge commit with parents and : the branch's history + * is kept and the result reads as "merge main into the branch", so it can be + * pushed without rewriting the branch. --squash makes one ordinary commit on + * instead. When the cherry-pick conflicts, the script stops and + * leaves the work tree with the conflicts to resolve; see the message. */ +import { execFileSync, spawnSync } from "node:child_process"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { createRequire } from "node:module"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { confine } from "./confine.mjs"; +import { formatFiles } from "./format.mjs"; + +const args = process.argv.slice(2); +const opt = (name, fallback) => { + const i = args.indexOf(`--${name}`); + return i >= 0 ? args[i + 1] : fallback; +}; +const has = (name) => args.includes(`--${name}`); +const branch = opt("branch"); +const onto = opt("onto"); +const configPath = opt("config"); +if (!branch || !onto || !configPath) { + console.error( + "usage: rehome-split.mjs --branch --onto --config [--out ] [--squash]", + ); + process.exit(2); +} +const out = opt("out", `${branch.replace(/^.*\//, "")}-rehomed`); +const tools = process.cwd(); +const here = dirname(fileURLToPath(import.meta.url)); +const config = JSON.parse(readFileSync(configPath, "utf8")); +// A config with "groups" moves fields into feature state (move-state.mjs), +// one with "methods" moves methods (split-methods.mjs), and any other moves +// top-level declarations (split-module.mjs). +const splitTool = join( + here, + config.groups ? "move-state.mjs" : config.class ? "split-methods.mjs" : "split-module.mjs", +); + +const git = (...a) => + execFileSync("git", a, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim(); +const gitIn = (cwd, ...a) => + execFileSync("git", a, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim(); +// Every commit the script makes is authored and committed as the branch's +// last author. +const author = (format) => git("log", "-1", `--format=${format}`, branch); +const ident = { + GIT_AUTHOR_NAME: author("%an"), + GIT_AUTHOR_EMAIL: author("%ae"), +}; +ident.GIT_COMMITTER_NAME = ident.GIT_AUTHOR_NAME; +ident.GIT_COMMITTER_EMAIL = ident.GIT_AUTHOR_EMAIL; +Object.assign(process.env, ident); + +const tip = git("rev-parse", `${branch}^{commit}`); +const target = git("rev-parse", `${onto}^{commit}`); +// The split must not be in the branch already, or there is nothing to rehome. +const moduleFile = config.module; +// With several merge bases (criss-cross history, such as a branch that +// carries another branch's commits that main merged), merge them into one +// virtual base, as git's merge does, so the cherry-pick sees the same base. +let base = git("merge-base", tip, target); +{ + const bases = git("merge-base", "--all", tip, target).split("\n").filter(Boolean); + for (const next of bases.slice(1)) { + const merged = spawnSync("git", ["merge-tree", "--write-tree", base, next], { + encoding: "utf8", + }); + const tree = merged.stdout.split("\n")[0]; + base = git("commit-tree", tree, "-p", base, "-p", next, "-m", "virtual merge base"); + } +} + +// Scratch worktrees go next to the checkout: not inside it (they would show +// as untracked files) and not under node_modules (oxfmt skips those paths). +const scratch = mkdtempSync(opt("scratch", join(dirname(tools), ".rehome-"))); +const worktree = (name, commit) => { + const dir = join(scratch, name); + git("worktree", "add", "--detach", "-q", dir, commit); + return dir; +}; +const split = (dir) => { + execFileSync( + process.execPath, + [splitTool, "apply", configPath, "--repo", dir, "--tools", tools], + { + stdio: ["ignore", "pipe", "inherit"], + }, + ); + gitIn(dir, "add", "-A"); + return gitIn(dir, "write-tree"); +}; +const commitTree = (tree, parents, message) => + execFileSync("git", ["commit-tree", tree, ...parents.flatMap((p) => ["-p", p]), "-m", message], { + encoding: "utf8", + env: { + ...process.env, + ...ident, + }, + }).trim(); + +let baseDir, tipDir; +try { + baseDir = worktree("base", base); + tipDir = worktree("tip", tip); + const splitBase = commitTree(split(baseDir), [base], "split of the merge base"); + const splitTip = commitTree(split(tipDir), [splitBase], "split of the branch tip"); + if (git("rev-parse", `${splitBase}^{tree}`) === git("rev-parse", `${splitTip}^{tree}`)) { + console.log(`${branch} has no changes relative to ${base.slice(0, 9)}`); + process.exit(0); + } + const touched = git("diff", "--name-only", splitBase, splitTip).split("\n").filter(Boolean); + console.log(`${branch}: ${touched.length} files changed in the split layout`); + // Apply the branch's changes onto the target in a worktree of its own. + const resultDir = worktree("result", target); + const pick = spawnSync( + "git", + ["-c", "merge.conflictStyle=merge", "cherry-pick", "--no-commit", splitTip], + { + cwd: resultDir, + encoding: "utf8", + }, + ); + // Moved declarations bring short import blocks, where an import main added + // and one the branch added can sit on adjacent lines. Resolve conflicts + // made only of import declarations to the union of both sides. + if (pick.status !== 0) { + // Only the files the split writes: other conflicts are the branch's own. + // A method split names its files in the config; a module split, in its manifest. + const files = config.groups + ? [ + ...config.groups.map((g) => g.file), + ...Object.keys(config.create ?? {}), + ...(config.replacements ?? []).map((r) => r.file), + ] + : config.class + ? Object.keys(config.methods) + : Object.keys( + (({ files, ...rest }) => files ?? rest)( + JSON.parse( + confine(dirname(resolve(configPath))).read( + resolve(dirname(resolve(configPath)), config.manifest), + ), + ), + ), + ); + const moduleDir = config.dir ?? dirname(moduleFile); + const splitFiles = new Set([moduleFile, ...files.map((f) => join(moduleDir, f))]); + for (const file of gitIn(resultDir, "diff", "--name-only", "--diff-filter=U") + .split("\n") + .filter(Boolean)) { + if ( + splitFiles.has(file) && + resolveImportConflicts(confine(resultDir), join(resultDir, file)) + ) { + formatFiles(tools, [file], { cwd: resultDir, stdio: ["ignore", "ignore", "inherit"] }); + gitIn(resultDir, "add", file); + console.log(`${file}: import conflicts resolved to both sides' imports`); + } + } + } + if (pick.status !== 0 && gitIn(resultDir, "diff", "--name-only", "--diff-filter=U") !== "") { + const conflicts = gitIn(resultDir, "diff", "--name-only", "--diff-filter=U"); + console.error( + `conflicts in:\n${conflicts}\n\nResolve them in ${resultDir}, then run:\n git -C ${resultDir} add -A && git -C ${resultDir} commit -m "Merge ${onto} into ${branch}" # or rerun with the resolution\nThe scratch worktrees stay until you remove ${scratch}.`, + ); + process.exit(1); + } + const tree = gitIn(resultDir, "write-tree"); + const subjects = git("log", "--format=%s", `${base}..${tip}`).split("\n").filter(Boolean); + const result = has("squash") + ? commitTree( + tree, + [target], + subjects.length === 1 + ? subjects[0] + : `${subjects.at(-1)}\n\n${subjects.map((s) => `- ${s}`).join("\n")}`, + ) + : commitTree( + tree, + [tip, target], + `Merge ${onto} into ${branch.replace(/^.*\//, "")}\n\nCarries the branch's changes to ${moduleFile} into the files its declarations moved to.`, + ); + git("branch", "-f", out, result); + console.log( + `${out} -> ${result.slice(0, 9)} (${has("squash") ? "one commit on" : "merge of"} ${onto})`, + ); + for (const dir of [baseDir, tipDir, resultDir]) git("worktree", "remove", "--force", dir); + rmSync(scratch, { recursive: true, force: true }); +} catch (error) { + console.error(error.stderr?.toString() || error.message); + console.error(`scratch worktrees left in ${scratch}`); + process.exit(1); +} + +/* Rewrites every conflict in `path` whose two sides hold only import + * declarations as the union of both: one declaration per module and kind, + * with the named imports of both sides in first-seen order, read and + * written through the result checkout's guard. Returns false, + * leaving the file unchanged, when any conflict holds other code. */ +function resolveImportConflicts(checkout, path) { + const ts = createRequire(join(tools, "package.json"))("typescript"); + const text = checkout.read(path); + const region = /^<<<<<<< [^\n]*\n([\s\S]*?)^=======\n([\s\S]*?)^>>>>>>> [^\n]*\n/gm; + const imports = (side) => { + const sf = ts.createSourceFile("side.ts", side, ts.ScriptTarget.Latest, true); + return sf.statements.every(ts.isImportDeclaration) ? sf.statements : null; + }; + let ok = true; + const imported = new Set(); + const resolved = text.replace(region, (whole, ours, theirs) => { + const a = imports(ours), + b = imports(theirs); + if (!a || !b) { + ok = false; + return whole; + } + const merged = new Map(); + for (const decl of [...a, ...b]) { + const clause = decl.importClause; + const named = + clause?.namedBindings && ts.isNamedImports(clause.namedBindings) + ? clause.namedBindings + : null; + if (!clause || !named || clause.name) { + // Side-effect, default and namespace imports are kept as written, once. + merged.set(decl.getText(), null); + continue; + } + const key = `${clause.isTypeOnly ? "type " : ""}${decl.moduleSpecifier.getText()}`; + const entry = merged.get(key) ?? { + typeOnly: clause.isTypeOnly, + from: decl.moduleSpecifier.getText(), + names: [], + }; + for (const element of named.elements) { + imported.add(element.name.text); + if (!entry.names.includes(element.getText())) entry.names.push(element.getText()); + } + merged.set(key, entry); + } + return ( + [...merged] + .map(([key, entry]) => + entry === null + ? key + : `import ${entry.typeOnly ? "type " : ""}{ ${entry.names.join(", ")} } from ${entry.from};`, + ) + .join("\n") + "\n" + ); + }); + if (!ok || resolved === text) return false; + checkout.write(path, pruneUnusedImports(ts, resolved, imported)); + return true; +} + +/* Drops the named imports among `names` that nothing outside import + * declarations references: a side's import whose use the other side's code + * replaced. The split computes each file's imports from its references, so + * this keeps a rehomed file's imports the ones the split would write. */ +function pruneUnusedImports(ts, text, names) { + const sf = ts.createSourceFile("file.ts", text, ts.ScriptTarget.Latest, true); + const used = new Set(); + const visit = (node) => { + if (ts.isImportDeclaration(node)) return; + if (ts.isIdentifier(node)) used.add(node.text); + ts.forEachChild(node, visit); + }; + visit(sf); + const edits = []; + for (const decl of sf.statements) { + const named = decl.importClause?.namedBindings; + if ( + !ts.isImportDeclaration(decl) || + !named || + !ts.isNamedImports(named) || + decl.importClause.name + ) + continue; + const kept = named.elements.filter((e) => !names.has(e.name.text) || used.has(e.name.text)); + if (kept.length === named.elements.length) continue; + const from = decl.moduleSpecifier.getText(); + const prefix = decl.importClause.isTypeOnly ? "import type" : "import"; + // A dropped declaration takes its line break with it. + const end = kept.length || text[decl.getEnd()] !== "\n" ? decl.getEnd() : decl.getEnd() + 1; + edits.push([ + decl.getStart(), + end, + kept.length ? `${prefix} { ${kept.map((e) => e.getText()).join(", ")} } from ${from};` : "", + ]); + } + for (const [start, end, replacement] of edits.reverse()) + text = text.slice(0, start) + replacement + text.slice(end); + return text; +} diff --git a/scripts/split/split-methods.mjs b/scripts/split/split-methods.mjs new file mode 100644 index 000000000..4d57644af --- /dev/null +++ b/scripts/split/split-methods.mjs @@ -0,0 +1,417 @@ +#!/usr/bin/env node +/* Move methods of one class into other files as functions of a host, as a + * pure move. + * + * node split-methods.mjs apply [--repo ] [--tools ] + * + * : + * { "tsconfig": "packages/compiler/tsconfig.json", + * "module": "packages/compiler/src/backend/llvm/emitter.ts", + * "class": "LlEmitter", + * "methods": { "emit-statements.ts": ["emitStmtBody", ...], ... }, + * "headers": { "emit-statements.ts": "/* ... *\/" } } + * + * Each listed method becomes `export function (host: , ...)` + * in its file (relative to the module's directory), with its doc comment + * and `this` replaced by the host parameter (`emitter`, or "hostName"). The class keeps a stub with the method's + * signature that calls the function, so every caller is unchanged. Members + * the moved bodies reach through `host` lose a `private` modifier (a + * compile-time check only). Each new file imports what its functions + * reference from the module's scope, with paths rebased; the module imports + * the functions and drops imports nothing uses anymore. Names the config + * lists but the class lacks are skipped. */ +import { readFileSync } from "node:fs"; +import { dirname, join, relative, resolve, posix } from "node:path"; +import { createRequire } from "node:module"; +import { confine, confineHost } from "./confine.mjs"; +import { formatFiles } from "./format.mjs"; + +const [command, configPath, ...flags] = process.argv.slice(2); +if (command !== "apply") throw new Error("usage: split-methods.mjs apply "); +const config = JSON.parse(readFileSync(configPath, "utf8")); +const flag = (name) => { + const i = flags.indexOf(name); + return i >= 0 ? flags[i + 1] : undefined; +}; +const repo = resolve(flag("--repo") ?? process.cwd()); +// Every read and write in the checkout stays inside it (confine.mjs). +const checkout = confine(repo); +const toolsDir = resolve(flag("--tools") ?? process.cwd()); +const require = createRequire(join(toolsDir, "package.json")); +const ts = require("typescript"); +const modulePath = join(repo, config.module); +const moduleDir = dirname(modulePath); +const className = config.class; +// The host parameter's name; a moved body that already uses it is refused. +const hostName = config.hostName ?? "emitter"; + +const text = checkout.read(modulePath); +const host = confineHost(ts.createCompilerHost({ noEmit: true }), checkout); +const sf = ts.createSourceFile(modulePath, text, ts.ScriptTarget.Latest, true); +const realGet = host.getSourceFile; +host.getSourceFile = (f, l, ...r) => + resolve(f) === modulePath ? sf : realGet.call(host, f, l, ...r); +const program = ts.createProgram([modulePath], { noEmit: true, noResolve: true }, host); +const checker = program.getTypeChecker(); +const source = program.getSourceFile(modulePath); + +const cls = source.statements.find((s) => ts.isClassDeclaration(s) && s.name?.text === className); +if (!cls) throw new Error(`no class ${className}`); +const memberByName = new Map(); +for (const m of cls.members) + if (m.name && ts.isIdentifier(m.name)) { + if (!memberByName.has(m.name.text)) memberByName.set(m.name.text, []); + memberByName.get(m.name.text).push(m); + } + +// Module scope: import bindings and top-level declarations. +const imports = new Map(); +const topLevel = new Map(); +for (const st of source.statements) { + if (ts.isImportDeclaration(st)) { + const c = st.importClause; + if (!c) continue; + if (c.name) imports.set(c.name.text, { st, kind: "default", typeOnly: c.isTypeOnly }); + const nb = c.namedBindings; + if (nb && ts.isNamespaceImport(nb)) + imports.set(nb.name.text, { st, kind: "namespace", typeOnly: c.isTypeOnly }); + if (nb && ts.isNamedImports(nb)) + for (const el of nb.elements) + imports.set(el.name.text, { + st, + kind: "named", + typeOnly: c.isTypeOnly || el.isTypeOnly, + imported: (el.propertyName ?? el.name).text, + }); + continue; + } + const names = []; + if ( + (ts.isFunctionDeclaration(st) || + ts.isClassDeclaration(st) || + ts.isInterfaceDeclaration(st) || + ts.isTypeAliasDeclaration(st) || + ts.isEnumDeclaration(st)) && + st.name + ) + names.push(st.name.text); + if (ts.isVariableStatement(st)) + for (const d of st.declarationList.declarations) + if (ts.isIdentifier(d.name)) names.push(d.name.text); + for (const n of names) topLevel.set(n, st); +} +const isExported = (st) => + st.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword) ?? false; +const isTypeDecl = (st) => ts.isInterfaceDeclaration(st) || ts.isTypeAliasDeclaration(st); + +/** Module-scope references in `node`: name -> { kind: "import"|"local" }, and `this.` names. */ +function references(node) { + const refs = new Map(); + const members = new Set(); + const visit = (n) => { + if ( + n.kind === ts.SyntaxKind.ThisKeyword && + n.parent && + ts.isPropertyAccessExpression(n.parent) && + n.parent.expression === n + ) + members.add(n.parent.name.text); + if (ts.isIdentifier(n)) { + const p = n.parent; + const propName = + p && + ((ts.isPropertyAccessExpression(p) && p.name === n) || + (ts.isQualifiedName(p) && p.right === n) || + (ts.isPropertyAssignment(p) && p.name === n)); + if (!propName) { + let sym = checker.getSymbolAtLocation(n); + if (p && ts.isShorthandPropertyAssignment(p)) + sym = checker.getShorthandAssignmentValueSymbol(p); + const decl = sym?.declarations?.[0]; + if (decl && decl.getSourceFile() === source) { + if (ts.isImportSpecifier(decl) || ts.isNamespaceImport(decl) || ts.isImportClause(decl)) + refs.set(decl.name.text, { kind: "import" }); + else if ( + topLevel.get(n.text) && + (decl === topLevel.get(n.text) || + decl.parent?.parent === topLevel.get(n.text) || + decl.parent === topLevel.get(n.text)) + ) + refs.set(n.text, { kind: "local" }); + } + } + } + ts.forEachChild(n, visit); + }; + visit(node); + return { refs, members }; +} + +const rebase = (spec, toDir) => { + if (!spec.startsWith(".")) return spec; + let rel = posix.normalize(relative(toDir, resolve(moduleDir, spec)).split("\\").join("/")); + return rel.startsWith(".") ? rel : "./" + rel; +}; +const specTo = (fromDir, file) => { + let rel = relative(fromDir, file).split("\\").join("/").replace(/\.ts$/, ".js"); + return rel.startsWith(".") ? rel : "./" + rel; +}; + +const edits = []; // [start, end, replacement] in the module +const stubs = []; +const files = new Map(); +const publicize = new Set(); +const moduleNeeds = new Map(); // spec -> names (functions the stubs call) +const exportLocals = new Set(); +let moved = 0; + +for (const [file, names] of Object.entries(config.methods)) { + const path = join(moduleDir, file); + const dir = dirname(path); + const entry = { decls: [], named: new Map(), other: [] }; + const addNamed = (spec, name, imported, typeOnly) => { + if (!entry.named.has(spec)) entry.named.set(spec, new Map()); + const m = entry.named.get(spec); + const prev = m.get(name); + m.set(name, { imported, typeOnly: prev ? prev.typeOnly && typeOnly : typeOnly }); + }; + addNamed(specTo(dir, modulePath), className, className, true); + for (const name of names) { + const decls = memberByName.get(name); + if (!decls) { + console.error(`skip: ${className}.${name} not found`); + continue; + } + if (decls.length !== 1 || !ts.isMethodDeclaration(decls[0]) || !decls[0].body) + throw new Error(`${name}: expected one method with a body`); + const m = decls[0]; + if (m.typeParameters?.length || m.asteriskToken) + throw new Error(`${name}: generic and generator methods are not handled`); + const isAsync = m.modifiers?.some((x) => x.kind === ts.SyntaxKind.AsyncKeyword) ?? false; + // The function: doc comment, signature (initializers kept, so a + // defaulted parameter after an optional one stays valid; the stub + // passes every argument), and the body with this -> host. + const lead = text.slice(m.getFullStart(), m.getStart()).replace(/^\s*\n/, ""); + const params = m.parameters.map((p) => { + const nameText = p.name.getText(); + // A parameter typed only by its default takes the default's widened type. + const type = p.type + ? `: ${p.type.getText()}` + : p.initializer + ? `: ${checker.typeToString(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(p.initializer)))}` + : ""; + const optional = p.questionToken ? "?" : ""; + let init = ""; + if (p.initializer) { + const initText = p.initializer.getText(); + if (/\bthis\b/.test(initText)) + throw new Error(`${name}: a parameter default that reads this is not handled`); + init = ` = ${initText}`; + } + return `${p.dotDotDotToken ? "..." : ""}${nameText}${optional}${type}${init}`; + }); + const ret = m.type ? `: ${m.type.getText()}` : ""; + const body = m.body; + const thisEdits = []; + const findThis = (n) => { + // `this` in an expression, or in a type query (`typeof this.x`). + // (In a type query `this` parses as an identifier.) + if ( + n.kind === ts.SyntaxKind.ThisKeyword || + (ts.isIdentifier(n) && n.text === "this" && ts.findAncestor(n, ts.isTypeQueryNode)) + ) + thisEdits.push(n.getStart()); + if (ts.isFunctionExpression(n) || ts.isFunctionDeclaration(n) || ts.isClassLike(n)) + throw new Error(`${name}: a nested function or class rebinds this`); + ts.forEachChild(n, findThis); + }; + ts.forEachChild(body, findThis); + const clash = (n) => { + if (ts.isIdentifier(n) && n.text === hostName) + throw new Error(`${name}: already uses the name ${hostName}`); + ts.forEachChild(n, clash); + }; + clash(m); + let bodyText = ""; + let cursor = body.getStart(); + for (const at of thisEdits.sort((a, b) => a - b)) { + bodyText += text.slice(cursor, at) + hostName; + cursor = at + 4; + } + bodyText += text.slice(cursor, body.end); + const leadOut = lead + .split("\n") + .map((l) => (l.startsWith(" ") ? l.slice(2) : l)) + .join("\n"); + const fn = `${leadOut}export ${isAsync ? "async " : ""}function ${name}(${hostName}: ${className}${params.length ? ", " + params.join(", ") : ""})${ret} ${bodyText}`; + entry.decls.push(fn); + stubs.push(m); + if (!moduleNeeds.has(specTo(moduleDir, path))) + moduleNeeds.set(specTo(moduleDir, path), new Set()); + moduleNeeds.get(specTo(moduleDir, path)).add(name); + // What the function needs. + const { refs, members } = references(m); + for (const member of members) publicize.add(member); + for (const [ref, { kind }] of refs) { + if (kind === "import") { + const imp = imports.get(ref); + const spec = rebase(imp.st.moduleSpecifier.text, dir); + if (imp.kind === "named") addNamed(spec, ref, imp.imported, imp.typeOnly); + else entry.other.push({ spec, kind: imp.kind, name: ref, typeOnly: imp.typeOnly }); + } else { + const st = topLevel.get(ref); + if (!isExported(st)) exportLocals.add(st); + addNamed(specTo(dir, modulePath), ref, ref, isTypeDecl(st)); + } + } + moved++; + } + files.set(file, entry); +} + +const renderImports = (entry) => { + const lines = []; + const seen = new Set(); + for (const o of entry.other) { + const key = `${o.kind}:${o.name}:${o.spec}`; + if (seen.has(key)) continue; + seen.add(key); + lines.push( + o.kind === "namespace" + ? `import ${o.typeOnly ? "type " : ""}* as ${o.name} from "${o.spec}";` + : `import ${o.typeOnly ? "type " : ""}${o.name} from "${o.spec}";`, + ); + } + for (const [spec, names] of entry.named) { + const all = [...names.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)); + const allType = all.every(([, v]) => v.typeOnly); + const parts = all.map( + ([n, v]) => + `${!allType && v.typeOnly ? "type " : ""}${v.imported === n ? n : `${v.imported} as ${n}`}`, + ); + lines.push(`import ${allType ? "type " : ""}{ ${parts.join(", ")} } from "${spec}";`); + } + return lines; +}; + +for (const [file, entry] of files) { + if (!entry.decls.length) continue; + const path = join(moduleDir, file); + if (checkout.exists(path)) throw new Error(`${file} exists`); + const header = config.headers?.[file]; + checkout.write( + path, + [...(header ? [header] : []), ...renderImports(entry), "", entry.decls.join("\n\n"), ""].join( + "\n", + ), + ); +} + +// Each moved method leaves a stub with its signature (defaults included) +// that calls the function; one the moved bodies call loses `private`. +const stubSet = new Set(stubs); +for (const m of stubs) { + let signature = m.modifiers + ? text.slice(m.getStart(), m.body.getStart()).trimEnd() + : text.slice(m.getStart(), m.body.getStart()).trimEnd(); + if (publicize.has(m.name.text)) signature = signature.replace(/^private /, ""); + const args = m.parameters.map((p) => `${p.dotDotDotToken ? "..." : ""}${p.name.getText()}`); + const call = `${m.name.text}(this${args.length ? ", " + args.join(", ") : ""})`; + edits.push([m.getFullStart(), m.end, `\n ${signature} {\n return ${call};\n }`]); +} +// Other members the moved bodies reach through the host lose `private`. +for (const name of publicize) + for (const m of memberByName.get(name) ?? []) + if (!stubSet.has(m)) + for (const mod of m.modifiers ?? []) + if (mod.kind === ts.SyntaxKind.PrivateKeyword) + edits.push([mod.getStart(), mod.end + 1, ""]); +// Top-level declarations the new files import get `export`. +for (const st of exportLocals) edits.push([st.getStart(), st.getStart(), "export "]); + +let out = ""; +let cursor = 0; +for (const [a, b, r] of edits.sort((x, y) => x[0] - y[0])) { + out += text.slice(cursor, a) + r; + cursor = b; +} +out += text.slice(cursor); + +// Re-analyze the rewritten module for unused imports, then add the new ones. +const sf2 = ts.createSourceFile(modulePath, out, ts.ScriptTarget.Latest, true); +const host2 = confineHost(ts.createCompilerHost({ noEmit: true }), checkout); +const get2 = host2.getSourceFile; +host2.getSourceFile = (f, l, ...r) => + resolve(f) === modulePath ? sf2 : get2.call(host2, f, l, ...r); +const program2 = ts.createProgram([modulePath], { noEmit: true, noResolve: true }, host2); +const checker2 = program2.getTypeChecker(); +const src2 = program2.getSourceFile(modulePath); +const used = new Set(); +const walk = (n) => { + if ( + ts.isIdentifier(n) && + !(n.parent && ts.isImportSpecifier(n.parent)) && + !(n.parent && ts.isImportClause(n.parent)) && + !(n.parent && ts.isNamespaceImport(n.parent)) + ) { + const sym = + n.parent && ts.isShorthandPropertyAssignment(n.parent) + ? checker2.getShorthandAssignmentValueSymbol(n.parent) + : checker2.getSymbolAtLocation(n); + const d = sym?.declarations?.[0]; + if (d && (ts.isImportSpecifier(d) || ts.isImportClause(d) || ts.isNamespaceImport(d))) + used.add(d.name.text); + } + ts.forEachChild(n, walk); +}; +for (const st of src2.statements) if (!ts.isImportDeclaration(st)) walk(st); +const importEdits = []; +for (const st of src2.statements) { + if (!ts.isImportDeclaration(st) || !st.importClause) continue; + const c = st.importClause; + const def = c.name && used.has(c.name.text) ? c.name.text : null; + const nb = c.namedBindings; + const ns = nb && ts.isNamespaceImport(nb) && used.has(nb.name.text) ? nb.name.text : null; + const named = + nb && ts.isNamedImports(nb) ? nb.elements.filter((el) => used.has(el.name.text)) : []; + const all = + (c.name ? def !== null : true) && + (!nb || (ts.isNamespaceImport(nb) ? ns !== null : named.length === nb.elements.length)); + if (all) continue; + let r = ""; + if (def || ns || named.length) { + const bits = []; + if (def) bits.push(def); + if (ns) bits.push(`* as ${ns}`); + if (named.length) bits.push(`{ ${named.map((el) => el.getText()).join(", ")} }`); + r = `import ${c.isTypeOnly ? "type " : ""}${bits.join(", ")} from ${st.moduleSpecifier.getText()};`; + } + const end = r === "" && out[st.end] === "\n" ? st.end + 1 : st.end; + importEdits.push([st.getStart(), end, r]); +} +let final = ""; +cursor = 0; +for (const [a, b, r] of importEdits.sort((x, y) => x[0] - y[0])) { + final += out.slice(cursor, a) + r; + cursor = b; +} +final += out.slice(cursor); +const lastImport = [ + ...ts.createSourceFile(modulePath, final, ts.ScriptTarget.Latest, true).statements, +] + .filter(ts.isImportDeclaration) + .at(-1); +const add = [...moduleNeeds].map( + ([spec, names]) => `import { ${[...names].sort().join(", ")} } from "${spec}";`, +); +const at = lastImport ? lastImport.end : 0; +final = final.slice(0, at) + (add.length ? "\n" + add.join("\n") : "") + final.slice(at); +checkout.write(modulePath, final); +// Format what changed with the tools checkout's oxfmt, so the split and +// every rehome of it are formatted the same way. +const touched = [ + modulePath, + ...[...files].filter(([, e]) => e.decls.length).map(([f]) => join(moduleDir, f)), +]; +formatFiles(toolsDir, touched, { cwd: repo, stdio: ["ignore", "ignore", "inherit"] }); +console.log(`${moved} methods moved; ${publicize.size} members reached through host`); diff --git a/scripts/split/split-module.mjs b/scripts/split/split-module.mjs new file mode 100644 index 000000000..4b8764d80 --- /dev/null +++ b/scripts/split/split-module.mjs @@ -0,0 +1,545 @@ +#!/usr/bin/env node +/* Split a large TypeScript module into files by a manifest of top-level + * declaration names, as a pure move. + * + * node split-module.mjs plan compute the manifest from seeds + * node split-module.mjs apply extract branches, move declarations + * + * : + * { "tsconfig": "packages/compiler/tsconfig.json", + * "module": "packages/compiler/src/frontend/lowering/lower-exprs.ts", + * "extract": [{ "function": "lowerExprInner", "condition": "ts.isIdentifier(expr)", + * "name": "lowerIdentifierExpr", "exprType": "ts.Identifier" }, ...], + * "seeds": { "expressions/binary.ts": ["lowerBinary", ...], ... }, + * "manifest": "" } + * + * It runs on the checkout in the current directory, or --repo , and + * loads typescript from that checkout or --tools . + * + * extract turns `if () { ...block... }` at the top level of the + * named function into `if () return (lowerer, expr, loc);` + * and adds `function (lowerer: Lowerer, expr: , loc: SrcLoc): + * IrExpr { ...block... }` after it. The block must end in a call that never + * returns, so no path falls through. + * + * plan assigns each seed to its file, then moves every other top-level + * declaration whose referrers all sit in one file (other than the module) + * into that file, to a fixpoint. Module-level `let` bindings stay put (an + * importer cannot assign them). The manifest lists file → names. + * + * apply moves the manifest's declarations with their leading comments, + * in source order, into the new files. Each new file imports what its + * declarations reference: names from the module or another new file, and + * the module's own imports with their paths rebased. The module imports the + * moved names it still uses, re-exports the moved names that were exported, + * and drops imports nothing uses anymore. Moved declarations that something + * outside their file references get `export`. Names a manifest lists but + * the module lacks are skipped, and new declarations stay in the module, + * so the same manifest applies to an edited copy of the module. */ +import { readFileSync } from "node:fs"; +import { dirname, join, relative, resolve, posix } from "node:path"; +import { createRequire } from "node:module"; +import { confine, confineHost } from "./confine.mjs"; +import { formatFiles } from "./format.mjs"; + +const [command, configPath, ...flags] = process.argv.slice(2); +const config = JSON.parse(readFileSync(configPath, "utf8")); +const flag = (name) => { + const i = flags.indexOf(name); + return i >= 0 ? flags[i + 1] : undefined; +}; +// --repo runs on another checkout (a temporary worktree); --tools names the +// checkout whose node_modules supply typescript. +const repo = resolve(flag("--repo") ?? config.repo ?? process.cwd()); +// Every read and write stays inside the checkout, or for the manifest, the +// config's directory (confine.mjs). +const checkout = confine(repo); +const configFiles = confine(dirname(resolve(configPath))); +// The manifest path is relative to the config file. +config.manifest = resolve(dirname(resolve(configPath)), flag("--manifest") ?? config.manifest); +const toolsDir = resolve(flag("--tools") ?? config.repo ?? process.cwd()); +const require = createRequire(join(toolsDir, "package.json")); +const ts = require("typescript"); +const modulePath = join(repo, config.module); +const moduleDir = dirname(modulePath); + +function parse(text, path = modulePath) { + return ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true); +} + +/* ── extract ─────────────────────────────────────────────────────────── */ + +function extractBranches(text) { + for (const spec of config.extract ?? []) { + const sf = parse(text); + const fn = sf.statements.find( + (s) => ts.isFunctionDeclaration(s) && s.name?.text === spec.function, + ); + if (!fn) throw new Error(`no function ${spec.function}`); + const branch = fn.body.statements.find( + (s) => + ts.isIfStatement(s) && + s.expression.getText() === spec.condition && + ts.isBlock(s.thenStatement) && + !s.elseStatement, + ); + if (!branch) { + console.error(`skip: no \`if (${spec.condition}) { ... }\` in ${spec.function}`); + continue; + } + const block = branch.thenStatement; + const last = block.statements.at(-1); + if ( + !last || + !(ts.isExpressionStatement(last) || ts.isReturnStatement(last) || ts.isThrowStatement(last)) + ) + throw new Error( + `${spec.condition}: the block must end in a never-returning call, return or throw`, + ); + // The block's inner text, dedented one level (two spaces). + const inner = text.slice(block.statements[0].getFullStart(), block.statements.at(-1).end); + const body = inner + .split("\n") + .map((line) => (line.startsWith(" ") ? line.slice(2) : line)) + .join("\n") + .replace(/^\n+/, ""); + const call = `if (${spec.condition}) return ${spec.name}(lowerer, expr, loc);`; + const fnText = `\n\nfunction ${spec.name}(lowerer: Lowerer, expr: ${spec.exprType}, loc: SrcLoc): IrExpr {\n ${body.trimStart()}\n}`; + text = + text.slice(0, branch.getStart()) + + call + + text.slice(branch.end, fn.end) + + fnText + + text.slice(fn.end); + } + return text; +} + +/* ── analysis ────────────────────────────────────────────────────────── */ + +function declNames(st) { + if ( + ts.isFunctionDeclaration(st) || + ts.isClassDeclaration(st) || + ts.isInterfaceDeclaration(st) || + ts.isTypeAliasDeclaration(st) || + ts.isEnumDeclaration(st) + ) + return st.name ? [st.name.text] : []; + if (ts.isVariableStatement(st)) + return st.declarationList.declarations.flatMap((d) => + ts.isIdentifier(d.name) ? [d.name.text] : [], + ); + return []; +} +const isExported = (st) => + st.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword) ?? false; +const isTypeDecl = (st) => ts.isInterfaceDeclaration(st) || ts.isTypeAliasDeclaration(st); +const isMutable = (st) => + ts.isVariableStatement(st) && !(st.declarationList.flags & ts.NodeFlags.Const); + +function inTypePosition(node) { + for (let n = node; n.parent; n = n.parent) { + // A class's `extends` names a value; `implements` and an interface's + // `extends` name types. + if (ts.isExpressionWithTypeArguments(n) && ts.isHeritageClause(n.parent)) + return !(n.parent.token === ts.SyntaxKind.ExtendsKeyword && ts.isClassLike(n.parent.parent)); + if (ts.isTypeNode(n) || ts.isTypeQueryNode?.(n)) return true; + if (ts.isStatement(n) || (ts.isExpression(n) && !ts.isIdentifier(n))) break; + } + return false; +} + +/** For the module text: its statements with names, its import bindings, and + * each declaration's references (local names and import bindings), each + * marked type-only when every reference sits in a type position. */ +function analyze(text) { + const sf = parse(text); + const host = confineHost(ts.createCompilerHost({}), checkout); + const tsconfigPath = join(repo, config.tsconfig); + checkout.check(tsconfigPath); + const tsconfig = ts.getParsedCommandLineOfConfigFile( + tsconfigPath, + {}, + { ...confineHost(ts.sys, checkout), onUnRecoverableConfigFileDiagnostic: () => {} }, + ); + const options = { ...tsconfig.options, noEmit: true }; + const realGet = host.getSourceFile; + host.getSourceFile = (fileName, lang, ...rest) => + resolve(fileName) === modulePath ? sf : realGet.call(host, fileName, lang, ...rest); + const program = ts.createProgram([modulePath], options, host); + const checker = program.getTypeChecker(); + const source = program.getSourceFile(modulePath); + + const imports = new Map(); // binding name -> { decl, spec, kind, typeOnly } + const statements = []; + for (const st of source.statements) { + if (ts.isImportDeclaration(st)) { + const clause = st.importClause; + const typeOnlyDecl = clause?.isTypeOnly ?? false; + if (clause?.name) + imports.set(clause.name.text, { + decl: st, + kind: "default", + typeOnly: typeOnlyDecl, + node: clause, + }); + const nb = clause?.namedBindings; + if (nb && ts.isNamespaceImport(nb)) + imports.set(nb.name.text, { + decl: st, + kind: "namespace", + typeOnly: typeOnlyDecl, + node: nb, + }); + if (nb && ts.isNamedImports(nb)) + for (const el of nb.elements) + imports.set(el.name.text, { + decl: st, + kind: "named", + typeOnly: typeOnlyDecl || el.isTypeOnly, + node: el, + imported: (el.propertyName ?? el.name).text, + }); + continue; + } + statements.push({ node: st, names: declNames(st) }); + } + const byNode = new Map(); + for (const s of statements) byNode.set(s.node, s); + const ownerOf = (decl) => { + for (let n = decl; n; n = n.parent) if (byNode.has(n)) return byNode.get(n); + return undefined; + }; + for (const s of statements) { + const refs = new Map(); // name -> { kind: "local"|"import", typeOnly } + const visit = (node) => { + if (ts.isIdentifier(node)) { + const parent = node.parent; + const isDeclName = + parent && + parent.name === node && + (ts.isFunctionDeclaration(parent) || + ts.isVariableDeclaration(parent) || + ts.isInterfaceDeclaration(parent) || + ts.isTypeAliasDeclaration(parent) || + ts.isParameter(parent) || + ts.isPropertyAssignment(parent) || + ts.isPropertySignature(parent) || + ts.isPropertyDeclaration(parent) || + ts.isMethodDeclaration(parent) || + ts.isBindingElement(parent)); + const isPropertyName = + parent && + ((ts.isPropertyAccessExpression(parent) && parent.name === node) || + (ts.isQualifiedName(parent) && parent.right === node)); + if (!isPropertyName) { + let sym = checker.getSymbolAtLocation(node); + if (ts.isShorthandPropertyAssignment(parent)) + sym = checker.getShorthandAssignmentValueSymbol(parent); + const decl = sym?.declarations?.[0]; + if (decl && decl.getSourceFile() === source) { + const typePos = inTypePosition(node); + let target; + if ( + ts.isImportSpecifier(decl) || + ts.isNamespaceImport(decl) || + ts.isImportClause(decl) + ) { + const name = (ts.isImportClause(decl) ? decl.name : decl.name).text; + target = { name, kind: "import" }; + } else { + const owner = ownerOf(decl); + if (owner && owner !== s && !isDeclName) { + const name = owner.names.find((n) => n === node.text) ?? node.text; + if (owner.names.includes(name)) target = { name, kind: "local" }; + } + } + if (target) { + const prev = refs.get(target.name); + refs.set(target.name, { + kind: target.kind, + typeOnly: (prev ? prev.typeOnly : true) && typePos, + }); + } + } + } + } + ts.forEachChild(node, visit); + }; + visit(s.node); + s.refs = refs; + } + return { source, statements, imports }; +} + +/* ── plan ────────────────────────────────────────────────────────────── */ + +function plan() { + const text = extractBranches(checkout.read(modulePath)); + const { statements } = analyze(text); + const fileOf = new Map(); + for (const [file, names] of Object.entries(config.seeds)) + for (const name of names) { + if (!statements.some((s) => s.names.includes(name))) + throw new Error(`seed ${name} not found`); + fileOf.set(name, file); + } + const keep = new Set(config.keep ?? []); + const referrers = new Map(); + for (const s of statements) + for (const [name, ref] of s.refs) + if (ref.kind === "local") { + if (!referrers.has(name)) referrers.set(name, new Set()); + for (const n of s.names) referrers.get(name).add(n); + } + for (let changed = true; changed;) { + changed = false; + for (const s of statements) { + if ( + s.names.length === 0 || + s.names.some((n) => fileOf.has(n) || keep.has(n)) || + isMutable(s.node) + ) + continue; + const users = new Set(); + for (const n of s.names) + for (const u of referrers.get(n) ?? []) if (!s.names.includes(u)) users.add(u); + const files = new Set([...users].map((u) => fileOf.get(u) ?? null)); + if (users.size > 0 && files.size === 1 && !files.has(null)) { + const [file] = files; + for (const n of s.names) fileOf.set(n, file); + changed = true; + } + } + } + const manifest = {}; + for (const s of statements) { + const file = s.names.map((n) => fileOf.get(n)).find(Boolean); + if (file) (manifest[file] ??= []).push(...s.names); + } + configFiles.write(config.manifest, JSON.stringify(manifest, null, 2) + "\n"); + for (const [file, names] of Object.entries(manifest)) console.log(`${file}: ${names.length}`); +} + +/* ── apply ───────────────────────────────────────────────────────────── */ + +function rebase(spec, fromDir, toDir) { + if (!spec.startsWith(".")) return spec; + let rel = posix.normalize(relative(toDir, resolve(fromDir, spec)).split("\\").join("/")); + if (!rel.startsWith(".")) rel = "./" + rel; + return rel; +} +const moduleSpecifierTo = (fromDir, file) => { + let rel = relative(fromDir, file).split("\\").join("/").replace(/\.ts$/, ".js"); + return rel.startsWith(".") ? rel : "./" + rel; +}; + +/** The statement's text with its leading comments, without leading blank lines. */ +function fullText(text, st) { + return text.slice(st.getFullStart(), st.end).replace(/^\s*\n/, ""); +} + +function apply() { + const manifest = JSON.parse(configFiles.read(config.manifest)); + let text = extractBranches(checkout.read(modulePath)); + const { source, statements, imports } = analyze(text); + const fileOf = new Map(); + for (const [file, names] of Object.entries(manifest)) for (const n of names) fileOf.set(n, file); + const stFile = (s) => s.names.map((n) => fileOf.get(n)).find(Boolean) ?? null; + const nameFile = new Map(); + const nameStmt = new Map(); + for (const s of statements) + for (const n of s.names) { + nameFile.set(n, stFile(s)); + nameStmt.set(n, s); + } + + // Which names need `export`: referenced from another file, or exported already. + const needsExport = new Set(); + for (const s of statements) + for (const [name, ref] of s.refs) + if (ref.kind === "local" && nameFile.get(name) !== stFile(s)) needsExport.add(name); + + const files = new Map(); // file -> { decls: [], imports: Map } + const fileImports = (file) => { + if (!files.has(file)) files.set(file, { decls: [], named: new Map(), other: [] }); + return files.get(file); + }; + const addNamed = (entry, spec, name, imported, typeOnly) => { + if (!entry.named.has(spec)) entry.named.set(spec, new Map()); + const m = entry.named.get(spec); + const prev = m.get(name); + m.set(name, { imported, typeOnly: prev ? prev.typeOnly && typeOnly : typeOnly }); + }; + const moduleEntry = { decls: [], named: new Map(), other: [] }; + for (const s of statements) { + const file = stFile(s); + const entry = file ? fileImports(file) : moduleEntry; + const dir = file ? dirname(join(moduleDir, file)) : moduleDir; + if (file) { + let t = fullText(text, s.node); + if (!isExported(s.node) && s.names.some((n) => needsExport.has(n))) { + const start = s.node.getStart() - s.node.getFullStart(); + const lead = text.slice(s.node.getFullStart(), s.node.getStart()).replace(/^\s*\n/, ""); + t = lead + "export " + text.slice(s.node.getStart(), s.node.end); + void start; + } + entry.decls.push(t); + } + for (const [name, ref] of s.refs) { + if (ref.kind === "local") { + const target = nameFile.get(name) ?? null; + if (target === file) continue; + const targetPath = target ? join(moduleDir, target) : modulePath; + const typeOnly = ref.typeOnly || isTypeDecl(nameStmt.get(name).node); + addNamed(entry, moduleSpecifierTo(dir, targetPath), name, name, typeOnly); + } else if (file) { + const imp = imports.get(name); + const spec = rebase(imp.decl.moduleSpecifier.text, moduleDir, dir); + if (imp.kind === "named") addNamed(entry, spec, name, imp.imported, imp.typeOnly); + else entry.other.push({ spec, kind: imp.kind, name, typeOnly: imp.typeOnly }); + } + } + } + + const renderImports = (entry) => { + const lines = []; + const seen = new Set(); + for (const o of entry.other) { + const key = `${o.kind}:${o.name}:${o.spec}`; + if (seen.has(key)) continue; + seen.add(key); + lines.push( + o.kind === "namespace" + ? `import ${o.typeOnly ? "type " : ""}* as ${o.name} from "${o.spec}";` + : `import ${o.typeOnly ? "type " : ""}${o.name} from "${o.spec}";`, + ); + } + for (const [spec, names] of entry.named) { + const all = [...names.entries()]; + const allType = all.every(([, v]) => v.typeOnly); + const parts = all + .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) + .map( + ([name, v]) => + `${!allType && v.typeOnly ? "type " : ""}${v.imported === name ? name : `${v.imported} as ${name}`}`, + ); + lines.push(`import ${allType ? "type " : ""}{ ${parts.join(", ")} } from "${spec}";`); + } + return lines; + }; + + // New files. + for (const [file, entry] of files) { + const header = config.headers?.[file]; + const out = [ + ...(header ? [header] : []), + ...renderImports(entry), + "", + entry.decls.join("\n\n"), + "", + ].join("\n"); + const path = join(moduleDir, file); + checkout.mkdir(dirname(path)); + if (checkout.exists(path)) throw new Error(`${file} exists`); + checkout.write(path, out); + } + + // The module: drop moved declarations, rewrite its import block. + const keptRefs = new Set(); + for (const s of statements) + if (!stFile(s)) for (const [name, ref] of s.refs) if (ref.kind === "import") keptRefs.add(name); + const pieces = []; + let cursor = 0; + const removals = []; + for (const s of statements) if (stFile(s)) removals.push([s.node.getFullStart(), s.node.end]); + // Import declarations: rebuild each without bindings nothing uses. + const importEdits = []; + for (const st of source.statements) { + if (!ts.isImportDeclaration(st)) continue; + const clause = st.importClause; + if (!clause) continue; // side-effect import + const used = (n) => keptRefs.has(n); + const def = clause.name && used(clause.name.text) ? clause.name.text : null; + const nb = clause.namedBindings; + let ns = null; + let named = []; + if (nb && ts.isNamespaceImport(nb) && used(nb.name.text)) ns = nb.name.text; + if (nb && ts.isNamedImports(nb)) named = nb.elements.filter((el) => used(el.name.text)); + const keepAll = + def === (clause.name?.text ?? null) && + (!nb || (ts.isNamespaceImport(nb) ? ns !== null : named.length === nb.elements.length)); + if (keepAll) continue; + let replacement = ""; + if (def || ns || named.length) { + const bits = []; + if (def) bits.push(def); + if (ns) bits.push(`* as ${ns}`); + if (named.length) bits.push(`{ ${named.map((el) => el.getText()).join(", ")} }`); + replacement = `import ${clause.isTypeOnly ? "type " : ""}${bits.join(", ")} from ${st.moduleSpecifier.getText()};`; + } + // A removed declaration takes its line break with it. + const end = replacement === "" && text[st.end] === "\n" ? st.end + 1 : st.end; + importEdits.push([st.getStart(), end, replacement]); + } + // Declarations that stay but that a moved one references get `export`. + const exportEdits = []; + for (const s of statements) + if (!stFile(s) && !isExported(s.node) && s.names.some((n) => needsExport.has(n))) + exportEdits.push([s.node.getStart(), s.node.getStart(), "export "]); + const edits = [...removals.map(([a, b]) => [a, b, ""]), ...importEdits, ...exportEdits].sort( + (x, y) => x[0] - y[0], + ); + for (const [a, b, r] of edits) { + pieces.push(text.slice(cursor, a), r); + cursor = b; + } + pieces.push(text.slice(cursor)); + let moduleText = pieces.join(""); + // Imports of moved names the module still uses, and re-exports of moved + // names that were exported (other modules import them from here). + const addLines = renderImports(moduleEntry); + const reexports = new Map(); + for (const s of statements) { + const file = stFile(s); + if (!file || !isExported(s.node)) continue; + const spec = moduleSpecifierTo(moduleDir, join(moduleDir, file)); + if (!reexports.has(spec)) reexports.set(spec, []); + for (const n of s.names) reexports.get(spec).push({ name: n, type: isTypeDecl(s.node) }); + } + for (const [spec, names] of reexports) { + const values = names + .filter((n) => !n.type) + .map((n) => n.name) + .sort(); + const types = names + .filter((n) => n.type) + .map((n) => n.name) + .sort(); + if (values.length) addLines.push(`export { ${values.join(", ")} } from "${spec}";`); + if (types.length) addLines.push(`export type { ${types.join(", ")} } from "${spec}";`); + } + // Insert after the last import declaration. + const reparsed = parse(moduleText); + const lastImport = [...reparsed.statements].filter(ts.isImportDeclaration).at(-1); + const at = lastImport ? lastImport.end : 0; + moduleText = + moduleText.slice(0, at) + + (addLines.length ? "\n" + addLines.join("\n") : "") + + moduleText.slice(at); + moduleText = moduleText.replace(/\n{3,}/g, "\n\n"); + checkout.write(modulePath, moduleText); + // Format what changed with the tools checkout's oxfmt, so the split and + // every rehome of it are formatted the same way. + const touched = [modulePath, ...[...files.keys()].map((f) => join(moduleDir, f))]; + formatFiles(toolsDir, touched, { cwd: repo, stdio: ["ignore", "ignore", "inherit"] }); + for (const [file, entry] of files) console.log(`${file}: ${entry.decls.length} declarations`); +} + +if (command === "plan") plan(); +else if (command === "apply") apply(); +else { + console.error("usage: split-module.mjs plan|apply "); + process.exit(2); +} diff --git a/scripts/test-ts7.mjs b/scripts/test-ts7.mjs index e022c1ff5..b776bea3e 100644 --- a/scripts/test-ts7.mjs +++ b/scripts/test-ts7.mjs @@ -25,6 +25,7 @@ if (process.argv.includes("--baselines-only")) { const ALLOWED_TYPESCRIPT5_IMPORTS = new Set([ "packages/compiler/src/frontend/comptime-node.ts", + "packages/compiler/src/frontend/jsx-source.test.ts", "packages/compiler/src/frontend/ts7/world-check.ts", "packages/compiler/src/frontend/ts7/source-parser.test.ts", "packages/compiler/src/library/semantic-source.ts", diff --git a/tests/corpus/4638-contract-program-lifetime-arrays.ts b/tests/corpus/4638-contract-program-lifetime-arrays.ts new file mode 100644 index 000000000..a50094f8b --- /dev/null +++ b/tests/corpus/4638-contract-program-lifetime-arrays.ts @@ -0,0 +1,117 @@ +import type { ProgramLifetime } from "@scriptc/types"; + +// Arrays of ProgramLifetime class instances: literals, growth, removal +// from both ends, splicing, slicing, concatenation, searching, sorting, +// filling, copying methods, holes, length changes, Sets and Maps built +// from them, arrays held in class fields, optional elements, inspection +// and JSON. Each operation sees the same instances, in the same order. + +class Sym implements ProgramLifetime { + readonly name: string; + readonly rank: number; + readonly decls: Sym[] = []; + parent: Sym | undefined = undefined; + constructor(name: string, rank: number) { + this.name = name; + this.rank = rank; + } +} + +class Scope implements ProgramLifetime { + readonly symbols: Sym[] = []; + readonly optional: (Sym | undefined)[] = []; + readonly nullable: (Sym | null)[] = []; +} + +const names = (xs: readonly (Sym | undefined | null)[]): string => + xs.map((s) => (s === undefined ? "u" : s === null ? "n" : s.name)).join(","); + +const a = new Sym("a", 3); +const b = new Sym("b", 1); +const c = new Sym("c", 2); +const d = new Sym("d", 5); +const e = new Sym("e", 4); + +// Literals, push, pop, shift and unshift. +const xs: Sym[] = [a, b, c]; +xs.push(d); +xs.push(e, a); +console.log(names(xs), xs.length); +console.log(xs.pop()?.name, xs.shift()?.name, names(xs)); +xs.unshift(e, d); +console.log(names(xs), xs[0] === e, xs.at(-1) === e); + +// Growth well past the inline slots, then reads by index. +const many: Sym[] = []; +for (let i = 0; i < 1000; i++) many.push(i % 2 === 0 ? a : new Sym(`s${i}`, i)); +let ranks = 0; +for (let i = 0; i < many.length; i++) ranks += many[i]!.rank; +console.log(many.length, ranks, many[999]!.name, many[998] === a); + +// Splice, slice, concat, spread and copying methods. +const ys = xs.slice(1, 4); +const removed = xs.splice(1, 2, a, b, c); +console.log(names(ys), names(removed), names(xs)); +const zs = [...ys, ...removed].concat(xs); +console.log(names(zs), zs.length); +console.log(names(zs.toReversed()), names(zs.with(0, c)), names(zs.toSpliced(1, 3))); + +// Searching by identity. +console.log(zs.indexOf(c), zs.lastIndexOf(c), zs.includes(d), zs.indexOf(new Sym("c", 2))); +console.log(zs.find((s) => s.rank > 3)?.name, zs.findIndex((s) => s === b), zs.some((s) => s === e)); +console.log(zs.every((s) => s.rank > 0), zs.filter((s) => s.rank % 2 === 1).length); + +// Sorting with comparators, reversing and filling. +const sorted = [...zs].sort((p, q) => p.rank - q.rank || p.name.localeCompare(q.name)); +console.log(names(sorted)); +console.log(names(zs.toSorted((p, q) => q.name.localeCompare(p.name)))); +sorted.reverse(); +console.log(names(sorted)); +const filled: Sym[] = new Array(5).fill(b); +filled.fill(c, 2, 4); +console.log(names(filled), filled.copyWithin(0, 3).map((s) => s.name).join("")); + +// Holes, length changes and iteration. +const holey: Sym[] = [a, b]; +holey[5] = c; +console.log(holey.length, 2 in holey, holey[5]?.name, holey.findIndex((s) => s === c)); +holey.length = 3; +console.log(holey.length, holey[5]); +let visited = ""; +for (const s of xs) visited += s.name; +xs.forEach((s, i) => { + visited += i; +}); +console.log(visited, names(xs.map((s) => s.parent ?? s))); + +// Arrays inside class instances, optional and nullable elements. +const scope = new Scope(); +for (const s of [a, b, c, d, e]) { + scope.symbols.push(s); + s.decls.push(s, a); + s.parent = scope.symbols[0]; +} +scope.optional.push(a, undefined, c); +scope.nullable.push(null, b, null); +scope.optional[3] = e; +console.log(names(scope.symbols), names(scope.optional), names(scope.nullable)); +console.log(scope.optional.indexOf(undefined), scope.nullable.indexOf(null), scope.optional.length); +console.log(c.decls.length, c.decls[1] === a, e.parent === a, names(e.decls)); + +// Sets and Maps built from arrays, and arrays built from them. +const set = new Set(zs); +console.log(set.size, set.has(d), names([...set])); +const byName = new Map(zs.map((s) => [s.name, s] as const)); +console.log(names([...byName.values()]), byName.get("b") === b); +const grouped = new Map(); +for (const s of many.slice(0, 10)) { + const list = grouped.get(s.rank % 3) ?? []; + list.push(s); + grouped.set(s.rank % 3, list); +} +console.log([...grouped.entries()].map(([k, v]) => `${k}:${v.length}`).join(" ")); + +// Inspection and JSON. +console.log(xs.slice(0, 2).map((s) => s.name)); +console.log(JSON.stringify(scope.nullable.map((s) => s?.rank ?? null))); +console.log(JSON.stringify([a, b].map((s) => ({ name: s.name, rank: s.rank })))); diff --git a/tests/corpus/4639-contract-program-lifetime-maps.ts b/tests/corpus/4639-contract-program-lifetime-maps.ts new file mode 100644 index 000000000..21f7da33c --- /dev/null +++ b/tests/corpus/4639-contract-program-lifetime-maps.ts @@ -0,0 +1,120 @@ +import type { ProgramLifetime } from "@scriptc/types"; + +// Maps from strings to ProgramLifetime class instances: get, set, has and +// delete, growth past the linear scan into bucket tables, deletion with +// compaction, clear, every iteration form, copies, Sets of keys and +// values, maps held in class fields, optional and nullable values, +// inspection, and a cast through unknown. Each read sees the same +// instance that was stored. + +class Sym implements ProgramLifetime { + readonly name: string; + readonly rank: number; + readonly members = new Map(); + constructor(name: string, rank: number) { + this.name = name; + this.rank = rank; + } +} + +class Scope implements ProgramLifetime { + readonly locals = new Map(); + readonly maybe = new Map(); + readonly nullable = new Map(); +} + +function show(m: ReadonlyMap): string { + return [...m].map(([k, v]) => `${k}=${v === undefined ? "u" : v === null ? "n" : v.name}`).join(","); +} + +const a = new Sym("a", 3); +const b = new Sym("b", 1); +const c = new Sym("c", 2); + +// get, set, has, delete, overwrite and size. +const m = new Map(); +m.set("x", a).set("y", b); +m.set("z", c); +console.log(show(m), m.size, m.get("y") === b, m.has("z"), m.has("w"), m.get("w")); +m.set("x", c); +console.log(show(m), m.get("x") === c, m.delete("y"), m.delete("y"), show(m)); +const seeded = new Map([ + ["p", a], + ["q", b], +]); +console.log(show(seeded), seeded.get("q")?.rank); + +// Growth into bucket tables, then deletes that compact the entries. +const big = new Map(); +const all: Sym[] = []; +for (let i = 0; i < 3000; i++) { + const s = new Sym(`s${i}`, i); + all.push(s); + big.set(s.name, s); +} +let same = 0; +for (let i = 0; i < 3000; i++) if (big.get(`s${i}`) === all[i]) same++; +console.log(big.size, same, big.get("s1234")?.rank, big.has("s3000")); +for (let i = 0; i < 3000; i++) if (i % 3 !== 0) big.delete(`s${i}`); +same = 0; +for (const [k, v] of big) if (v === all[Number(k.slice(1))] && v.rank % 3 === 0) same++; +console.log(big.size, same, big.get("s2997")?.name, big.get("s2998")); +for (let i = 0; i < 3000; i += 3) big.set(`s${i}`, all[(i + 1) % 3000]!); +console.log(big.get("s0")?.name, big.get("s2997")?.name, big.size); + +// Iteration forms. +const order: string[] = []; +m.forEach((v, k) => { + order.push(`${k}:${v.name}`); +}); +console.log(order.join(" ")); +console.log([...m.keys()].join(), [...m.values()].map((s) => s.name).join(), [...m.entries()].length); +console.log(Array.from(m.values(), (s) => s.rank).join(), Array.from(m).length); +for (const v of m.values()) v.members.set("owner", a); +console.log(c.members.get("owner") === a, a.members.size); + +// Mutation during iteration: entries added by the callback are visited. +const grow = new Map([["g0", a]]); +let visits = 0; +for (const [k] of grow) { + visits++; + if (visits < 4) grow.set(`${k}+`, b); +} +console.log(visits, show(grow)); + +// Copies, Sets of keys and values, clear. +const copy = new Map(m); +copy.set("extra", b); +console.log(show(m), show(copy), copy.get("x") === m.get("x")); +const keySet = new Set(m.keys()); +const valueSet = new Set(m.values()); +console.log([...keySet].join(), valueSet.has(c), valueSet.has(b), valueSet.size); +copy.clear(); +console.log(copy.size, copy.get("x"), show(m)); +copy.set("again", a); +console.log(show(copy)); + +// Maps in class fields, optional and nullable values. +const scope = new Scope(); +scope.locals.set("a", a); +scope.maybe.set("a", a).set("gone", undefined); +scope.nullable.set("b", b).set("none", null); +console.log(show(scope.locals), show(scope.maybe), show(scope.nullable)); +console.log(scope.maybe.has("gone"), scope.maybe.get("gone"), scope.nullable.get("none"), scope.nullable.get("b")?.name); +const v = scope.maybe.get("a"); +console.log(v === a, v?.rank); + +// Objects from entries, inspection and JSON. +const obj = Object.fromEntries(m); +console.log(Object.keys(obj).join(), obj["z"] === c); +console.log(new Map([["only", b]])); +console.log(JSON.stringify([...m.keys()]), JSON.stringify(Object.fromEntries([...m].map(([k, s]) => [k, s.rank])))); + +// Through unknown and back. +const u: unknown = m; +if (u instanceof Map) { + const back = u as Map; + const seen: string[] = []; + for (const [k, s] of back) seen.push(`${String(k)}:${(s as Sym).name}`); + console.log(back.size, seen.join(), back.get("x") === c); +} diff --git a/tests/corpus/4814-integer-or-nan-indexes.ts b/tests/corpus/4814-integer-or-nan-indexes.ts new file mode 100644 index 000000000..1bcfa3e02 --- /dev/null +++ b/tests/corpus/4814-integer-or-nan-indexes.ts @@ -0,0 +1,127 @@ +// Typed-array and array indexes that are exact integers or NaN: element +// reads that may miss, bound to locals or used inline, `charCodeAt` past +// either end, and sums of those. A NaN index reads undefined and a write +// to it is ignored; negative and too-large integers miss the same way. +function show(label: string, value: number | undefined): void { + console.log(label, value); +} + +const bytes = new Uint8Array([65, 67, 71, 84, 0, 255, 3]); +const signed = new Int8Array([-1, 2, -128, 127, 5]); +const wide = new Uint32Array([1, 4294967295, 2, 7]); +const halves = new Int16Array([-300, 4, 6]); +const table = new Int32Array(256); +for (let i = 0; i < 256; i++) table[i] = i * 3 - 100; +const list: number[] = []; +for (let i = 0; i < 300; i++) list.push(i * 0.5); + +function lookups(n: number): number { + let acc = 0; + for (let i = 0; i < n; i++) { + const c = bytes[i]!; + const t = table[c]; + acc = (acc * 7 + (t === undefined ? -1 : t)) % 1000003; + } + return acc; +} + +function listLookups(n: number): number { + let acc = 0; + for (let i = 0; i < n; i++) { + const c = bytes[i]!; + const v = list[c]; + acc = acc * 3 + (v === undefined ? -2 : v); + } + return acc; +} + +function signedIndexes(): string { + const out: string[] = []; + for (let i = -1; i <= signed.length; i++) { + const s = signed[i]!; + out.push(String(table[s]), String(list[s + 2]), String(bytes[s - 1])); + } + return out.join(","); +} + +function wideIndexes(): string { + const out: string[] = []; + for (let i = 0; i <= wide.length; i++) { + const w = wide[i]!; + out.push(String(bytes[w]), String(list[w]), String(table[w - 1])); + } + for (let i = 0; i <= halves.length; i++) { + const h = halves[i]!; + out.push(String(table[h + 301]), String(list[h])); + } + return out.join(","); +} + +function codeUnits(s: string): number { + let acc = 0; + for (let i = -2; i < s.length + 2; i++) { + const u = s.charCodeAt(i); + const t = table[u]; + acc = acc * 5 + (t === undefined ? 1 : t); + acc %= 1000003; + } + return acc; +} + +function writes(n: number): string { + const counts = new Uint16Array(8); + const tally: number[] = [0, 0, 0, 0]; + for (let i = 0; i < n; i++) { + const c = bytes[i]!; + counts[c & 7]++; + counts[c - 60] = 9; + tally[c - 65] = (tally[c - 65] ?? 0) + 1; + } + return `${Array.from(counts).join(" ")} | ${tally.join(" ")} | ${tally.length}`; +} + +function reassigned(n: number): string { + const out: number[] = []; + for (let i = 0; i < n; i++) { + let c = bytes[i]!; + if (c > 200) c = signed[i - 5]!; + out.push(table[c] ?? -7); + // A fraction makes `f` an ordinary number index. + let f = bytes[i]!; + if (i === 2) f = f / 2; + out.push(list[f] ?? -8); + } + return out.join(" "); +} + +function growing(n: number): number { + let x = bytes[0]!; + let acc = 0; + for (let i = 0; i < n; i++) { + x = x + bytes[i]!; + acc = acc + (table[x] ?? -3); + } + return acc; +} + +function hashes(n: number): string { + let h = 0; + let k = 0; + for (let i = 0; i < n; i++) { + const c = bytes[i]!; + h = (h * 31 + c) | 0; + k = ((k << 2) | (c >> 1)) & 0xffff; + } + return `${h} ${k}`; +} + +show("lookups", lookups(bytes.length)); +show("lookups past the end", lookups(bytes.length + 3)); +show("list lookups", listLookups(bytes.length + 2)); +console.log("signed", signedIndexes()); +console.log("wide", wideIndexes()); +show("code units", codeUnits("ACGTÿĀ")); +console.log("writes", writes(bytes.length + 2)); +console.log("reassigned", reassigned(bytes.length + 1)); +show("growing", growing(bytes.length + 1)); +console.log("hashes", hashes(bytes.length + 2)); diff --git a/tests/corpus/4815-touint32-wide-magnitudes.ts b/tests/corpus/4815-touint32-wide-magnitudes.ts new file mode 100644 index 000000000..ab60b8c0f --- /dev/null +++ b/tests/corpus/4815-touint32-wide-magnitudes.ts @@ -0,0 +1,79 @@ +// ToInt32 and ToUint32 (`| 0`, `>>> 0`, `^`, `<<`, `>>`) of doubles around +// 2^53 and 2^63, of multiplicative hash products that pass 2^53, and of +// NaN, the infinities and -0. +const values: number[] = [ + 2 ** 53 - 1, + 2 ** 53, + 2 ** 53 + 2, + -(2 ** 53) - 2, + 2 ** 53 * 3 + 4, + 2 ** 62, + 2 ** 62 + 2 ** 40 + 5 * 2 ** 10, + 2 ** 63 - 1024, + -(2 ** 63) + 1024, + 2 ** 63, + -(2 ** 63), + 2 ** 63 + 2048, + 2 ** 64, + 2 ** 64 - 2048, + -(2 ** 64) + 4096, + 2 ** 80 + 2 ** 33, + 1.5e300, + Infinity, + -Infinity, + NaN, + -0, + 0.75, + -2.5, + 4294967295.5, +]; + +function opaque(i: number): number { + return values[i % values.length]!; +} + +for (let i = 0; i < values.length; i++) { + const v = opaque(i); + console.log( + String(v), + v | 0, + v >>> 0, + v ^ 0x5a5a5a5a, + (v << 3) | 0, + v >> 7, + v >>> 9, + ); +} + +function fnv(bytes: Uint8Array): number { + let h = 2166136261; + for (let i = 0; i < bytes.length; i++) h = ((h ^ bytes[i]!) * 16777619) >>> 0; + return h; +} + +function mix(bytes: Uint8Array): number { + let h = 0; + for (let i = 0; i < bytes.length; i++) h = ((h ^ (bytes[i]! - 64)) * 16777619) | 0; + return h; +} + +function poly(bytes: Uint8Array): number { + let h = 7; + for (let i = 0; i < bytes.length; i++) h = (h * 1000003 + bytes[i]!) | 0; + return h; +} + +function wide(bytes: Uint8Array): number { + // Products near 2^63 and past it: the conversion of each must match. + let h = 3; + for (let i = 0; i < bytes.length; i++) h = ((h ^ bytes[i]!) * 2147483647 * (bytes[i]! * 17 + 1)) | 0; + return h; +} + +const bytes = new Uint8Array(4096); +let seed = 12345; +for (let i = 0; i < bytes.length; i++) { + seed = (seed * 1103515245 + 12345) % 2147483648; + bytes[i] = seed >>> 23; +} +console.log("fnv", fnv(bytes), "mix", mix(bytes), "poly", poly(bytes), "wide", wide(bytes)); diff --git a/tests/corpus/6706-dh-groups.ts b/tests/corpus/6706-dh-groups.ts new file mode 100644 index 000000000..24c8b5773 --- /dev/null +++ b/tests/corpus/6706-dh-groups.ts @@ -0,0 +1,52 @@ +// crypto.getDiffieHellman and createDiffieHellmanGroup on every modp +// group: the RFC primes and generator, verifyError, case-insensitive names, +// private keys of the group's width, and key pairs that agree on one +// secret of the prime's length. +import { createDiffieHellmanGroup, getDiffieHellman, type DiffieHellmanGroup } from "node:crypto"; + +const groups = ["modp1", "modp2", "modp5", "modp14", "modp15", "modp16", "modp17", "modp18"]; + +function bitLength(bytes: Buffer): number { + if (bytes.length === 0) return 0; + return (bytes.length - 1) * 8 + bytes[0]!.toString(2).length; +} + +for (const name of groups) { + const group: DiffieHellmanGroup = getDiffieHellman(name); + const prime: Buffer = group.getPrime(); + console.log( + name, + group.verifyError, + bitLength(prime), + prime.toString("hex").slice(0, 24), + prime.toString("hex").slice(-16), + group.getGenerator("hex"), + ); +} + +// Key exchange on the groups whose exponentiations stay quick. +for (const name of ["modp1", "modp2", "modp5", "modp14"]) { + const alice = getDiffieHellman(name); + const bob = createDiffieHellmanGroup(name.toUpperCase()); + const alicePublic: Buffer = alice.generateKeys(); + const bobPublic: string = bob.generateKeys("base64"); + const fromAlice: Buffer = alice.computeSecret(bobPublic, "base64"); + const fromBob: string = bob.computeSecret(alicePublic, null, "hex"); + const width = bitLength(alice.getPrivateKey()); + console.log( + name, + fromAlice.length, + fromAlice.toString("hex") === fromBob, + alicePublic.length <= fromAlice.length, + name === "modp1" || name === "modp2" ? width <= bitLength(alice.getPrime()) : width, + ); + // generateKeys keeps the key pair it has. + console.log(alice.generateKeys("hex") === alicePublic.toString("hex"), alice.getPublicKey().equals(alicePublic)); +} + +// The prime and generator in every encoding. +const modp5 = getDiffieHellman("Modp5"); +for (const encoding of ["hex", "base64", "base64url", "latin1", "binary"] as const) { + const prime: string = modp5.getPrime(encoding as "hex"); + console.log(encoding, prime.length, JSON.stringify(modp5.getGenerator(encoding as "hex"))); +} diff --git a/tests/corpus/6707-dh-explicit-params.ts b/tests/corpus/6707-dh-explicit-params.ts new file mode 100644 index 000000000..57e239d73 --- /dev/null +++ b/tests/corpus/6707-dh-explicit-params.ts @@ -0,0 +1,169 @@ +// crypto.createDiffieHellman over explicit parameters: fixed private keys +// give Node's public keys and secrets, verifyError reports DH_check's +// findings, and parameters that equal an OpenSSL named group draw private +// keys of the group's length. +import { createDiffieHellman, getDiffieHellman, type DiffieHellman } from "node:crypto"; + +// A 512-bit safe prime with p ≡ 23 (mod 24). +const P512 = + "f29864297728009aab9d4220c05ca2d80a5e4ac2f016cd098543a2486bde8bcb" + + "deed9eab7029c8d2b7a681f9495bfc7b1c39c6db64457bb79beeb74a4b78f5ff"; + +function bitLength(bytes: Buffer): number { + if (bytes.length === 0) return 0; + return (bytes.length - 1) * 8 + bytes[0]!.toString(2).length; +} + +function fixed(prime: Buffer, generator: number | Buffer, key: string): DiffieHellman { + const dh = createDiffieHellman(prime, generator); + dh.setPrivateKey(key, "hex"); + return dh; +} + +const prime512 = Buffer.from(P512, "hex"); +for (const generator of [2, 3, 5, Buffer.from([0x0b])]) { + const alice = fixed(prime512, generator, "0123456789abcdef0123456789abcdef"); + const bob = fixed(prime512, generator, "fedcba9876543210fedcba9876543210ff"); + const alicePublic: string = alice.generateKeys("hex"); + const bobPublic: Buffer = bob.generateKeys(); + const secret: string = alice.computeSecret(bobPublic, null, "hex"); + console.log(alice.getGenerator("hex"), alice.verifyError, alicePublic.slice(0, 32), bobPublic.length); + console.log(secret, secret === bob.computeSecret(alicePublic, "hex", "hex")); +} + +// Secrets pad to the prime's length; public keys are minimal. +const modp1 = getDiffieHellman("modp1").getPrime(); +const small = fixed(modp1, 2, "01"); +console.log(small.generateKeys("hex"), small.getPrivateKey("hex")); +const big = fixed(modp1, 2, "ff".repeat(100)); +console.log(big.generateKeys().length, big.getPrivateKey().length); +const padded: Buffer = small.computeSecret(Buffer.from([4])); +console.log(padded.length, padded.subarray(0, 4).toString("hex"), padded.subarray(-2).toString("hex")); +console.log(big.computeSecret(Buffer.from([2]), null, "base64url")); + +// A private key of 0 still yields a public key; reading it back and +// deriving a secret from it fail. A private key of 1 answers the peer's +// key. +function report(run: () => unknown): void { + try { + const result = run(); + console.log(Buffer.isBuffer(result) ? result.toString("hex") : result); + } catch (error) { + const e = error as Error & { code?: string }; + console.log(e.name, e.code, e.message); + } +} +const zero = fixed(prime512, 2, "00"); +console.log(zero.generateKeys("hex")); +report(() => zero.getPrivateKey()); +report(() => zero.computeSecret(Buffer.from([5]))); +report(() => fixed(prime512, 2, "01").computeSecret(Buffer.from([5]))); + +// A private key longer than the prime: 8800 bits. +const long = fixed(modp1, 2, "ff".repeat(1100)); +console.log(long.generateKeys("hex").slice(0, 32), long.computeSecret(Buffer.from([7]), null, "hex").slice(-32)); + +// setPublicKey and setPrivateKey answer the object and replace the keys. +const keys = createDiffieHellman(prime512); +keys.setPublicKey(Buffer.from([0, 0, 7])); +keys.setPrivateKey("0005", "hex"); +console.log(keys.getPublicKey("hex"), keys.getPrivateKey("hex")); +console.log(keys.generateKeys("hex").length, keys.getPublicKey("hex") !== "07"); + +// verifyError for small, even, composite and non-safe primes and for +// unsuitable generators. +const cases: [string, number | string][] = [ + ["01", 2], + ["02", 2], + ["03", 2], + ["0d", 2], + ["15", 2], + ["17", 2], + ["17", 5], + ["17", "16"], + ["17", "1e"], + ["18", 2], + ["000017", 2], + ["05", 2], + ["05", 5], + ["07", 2], + ["09", 2], + ["0b", 5], + ["0f", 2], + ["11", 2], + ["2f", 2], + ["3b", 5], + ["0231", 2], + ["0451", 2], + ["07ff", 2], +]; +for (const [prime, generator] of cases) { + const g = typeof generator === "number" ? generator : Buffer.from(generator, "hex"); + console.log(prime, generator, createDiffieHellman(Buffer.from(prime, "hex"), g).verifyError); +} +const almost = Buffer.from(P512, "hex"); +almost[almost.length - 1] = 0xfe; +console.log(createDiffieHellman(almost).verifyError); +const composite = Buffer.from(P512, "hex"); +composite[composite.length - 1] = 0xfd; +console.log(createDiffieHellman(composite).verifyError); +const generatorPMinus1 = Buffer.from(P512, "hex"); +generatorPMinus1[generatorPMinus1.length - 1] = 0xfe; +console.log(createDiffieHellman(prime512, generatorPMinus1).verifyError); + +// Generated keys: bits(p) - 2 bits for other primes, at most the named +// group's key length for RFC 3526 and RFC 5114 parameters. +const generated = createDiffieHellman(prime512); +generated.generateKeys(); +console.log(bitLength(generated.getPrivateKey())); +const modp14 = getDiffieHellman("modp14").getPrime(); +const named = createDiffieHellman(modp14, Buffer.from([0, 2])); +named.generateKeys(); +console.log(named.verifyError, bitLength(named.getPrivateKey()) <= 225); +const notNamed = createDiffieHellman(modp1); +notNamed.generateKeys(); +console.log(bitLength(notNamed.getPrivateKey())); +const rfc5114 = createDiffieHellman( + Buffer.from( + "b10b8f96a080e01dde92de5eae5d54ec52c99fbcfb06a3c69a6a9dca52d23b616073e28675a23d189838ef1e2ee652c0" + + "13ecb4aea906112324975c3cd49b83bfaccbdd7d90c4bd7098488e9c219a73724effd6fae5644738faa31a4ff55bccc0" + + "a151af5f0dc8b4bd45bf37df365c1a65e68cfda76d4da708df1fb2bc2e4a4371", + "hex", + ), + Buffer.from( + "a4d1cbd5c3fd34126765a442efb99905f8104dd258ac507fd6406cff14266d31266fea1e5c41564b777e690f5504f213" + + "160217b4b01b886a5e91547f9e2749f4d7fbd7d3b9a92ee1909d0d2263f80a76a6a24c087a091f531dbf0a0169b6a28a" + + "d662a4d18e73afa32d779d5918d08bc8858f4dcef97c2a24855e6eeb22b3b2e5", + "hex", + ), +); +rfc5114.generateKeys(); +console.log(rfc5114.verifyError, bitLength(rfc5114.getPrivateKey()) <= 160); +// RFC 5114's 2048-bit group with a 256-bit subgroup draws 224-bit keys. +const rfc5114q256 = createDiffieHellman( + Buffer.from( + "87a8e61db4b6663cffbbd19c651959998ceef608660dd0f25d2ceed4435e3b00e00df8f1d61957d4faf7df4561b2aa30" + + "16c3d91134096faa3bf4296d830e9a7c209e0c6497517abd5a8a9d306bcf67ed91f9e6725b4758c022e0b1ef4275bf7b" + + "6c5bfc11d45f9088b941f54eb1e59bb8bc39a0bf12307f5c4fdb70c581b23f76b63acae1caa6b7902d52526735488a0e" + + "f13c6d9a51bfa4ab3ad8347796524d8ef6a167b5a41825d967e144e5140564251ccacb83e6b486f6b3ca3f7971506026" + + "c0b857f689962856ded4010abd0be621c3a3960a54e710c375f26375d7014103a4b54330c198af126116d2276e11715f" + + "693877fad7ef09cadb094ae91e1a1597", + "hex", + ), + Buffer.from( + "3fb32c9b73134d0b2e77506660edbd484ca7b18f21ef205407f4793a1a0ba12510dbc15077be463fff4fed4aac0bb555" + + "be3a6c1b0c6b47b1bc3773bf7e8c6f62901228f8c28cbb18a55ae31341000a650196f931c77a57f2ddf463e5e9ec144b" + + "777de62aaab8a8628ac376d282d6ed3864e67982428ebc831d14348f6f2f9193b5045af2767164e1dfc967c1fb3f2e55" + + "a4bd1bffe83b9c80d052b985d182ea0adb2a3b7313d3fe14c8484b1e052588b9b7d2bbd2df016199ecd06e1557cd0915" + + "b3353bbb64e0ec377fd028370df92b52c7891428cdc67eb6184b523d1db246c32f63078490f00ef8d647d148d4795451" + + "5e2327cfef98c582664b4c0f6cc41659", + "hex", + ), +); +let widest = 0; +for (let i = 0; i < 8; i++) { + const keys = createDiffieHellman(rfc5114q256.getPrime(), rfc5114q256.getGenerator()); + keys.generateKeys(); + widest = Math.max(widest, bitLength(keys.getPrivateKey())); +} +console.log(rfc5114q256.verifyError, widest <= 224, widest > 200); diff --git a/tests/corpus/6708-dh-errors.js b/tests/corpus/6708-dh-errors.js new file mode 100644 index 000000000..0c711c96d --- /dev/null +++ b/tests/corpus/6708-dh-errors.js @@ -0,0 +1,175 @@ +// createDiffieHellman, getDiffieHellman and DiffieHellman errors from +// JavaScript: argument types and ranges, the keyEncoding and generator +// forms, OpenSSL's generator and modulus errors with their library and +// reason properties, parameter sizes, group names, encodings, keys read +// before they exist, public keys outside (1, p - 1), key generation and +// secrets on primes outside 512 to 10000 bits, and members a +// DiffieHellmanGroup does not have. +import crypto from "node:crypto"; + +// Values the declared overloads reject reach the calls through an +// untyped function, as they would from other untyped code. +const loose = (value) => value; + +function attempt(label, run) { + try { + const result = run(); + if (Buffer.isBuffer(result)) console.log(label, "ok", result.toString("hex")); + else if (typeof result === "object" && result !== null) + console.log(label, "ok", result.getGenerator("hex"), result.getPrime().length); + else console.log(label, "ok", JSON.stringify(result)); + } catch (e) { + const extra = e.library === undefined ? "" : ` [${Object.keys(e).join(",")}] ${e.library} / ${e.reason}`; + console.log(label, e.name, e.code, e.message + extra); + } +} + +const prime = crypto.getDiffieHellman("modp1").getPrime(); + +attempt("size missing", () => crypto.createDiffieHellman(loose(undefined))); +attempt("size null", () => crypto.createDiffieHellman(loose(null))); +attempt("size boolean", () => crypto.createDiffieHellman(loose(true))); +attempt("size object", () => crypto.createDiffieHellman(loose({}))); +attempt("size bigint", () => crypto.createDiffieHellman(loose(5n))); +attempt("size fraction", () => crypto.createDiffieHellman(1.5)); +attempt("size NaN", () => crypto.createDiffieHellman(NaN)); +attempt("size 2^31", () => crypto.createDiffieHellman(2 ** 31)); +attempt("size 2^40", () => crypto.createDiffieHellman(2 ** 40)); +attempt("size -1", () => crypto.createDiffieHellman(-1)); +attempt("size -0", () => crypto.createDiffieHellman(-0)); +attempt("size 1", () => crypto.createDiffieHellman(1)); +attempt("size 1 bad generator", () => crypto.createDiffieHellman(1, 1)); +attempt("size 2 generator 1", () => crypto.createDiffieHellman(2, 1)); +attempt("size 2", () => crypto.createDiffieHellman(2)); +attempt("size 511", () => crypto.createDiffieHellman(511)); +attempt("size 10001", () => crypto.createDiffieHellman(10001)); +attempt("size generator string", () => crypto.createDiffieHellman(64, loose("02"))); +attempt("size generator view", () => crypto.createDiffieHellman(64, loose(Buffer.from([2])))); + +attempt("generator 0", () => crypto.createDiffieHellman(prime, 0)); +attempt("generator 1", () => crypto.createDiffieHellman(prime, 1)); +attempt("generator -1", () => crypto.createDiffieHellman(prime, -1)); +attempt("generator fraction", () => crypto.createDiffieHellman(prime, 2.5)); +attempt("generator 2^31", () => crypto.createDiffieHellman(prime, 2 ** 31)); +attempt("generator NaN", () => crypto.createDiffieHellman(prime, NaN)); +attempt("generator null", () => crypto.createDiffieHellman(prime, loose(null))); +attempt("generator empty string", () => crypto.createDiffieHellman(prime, loose(""))); +attempt("generator true", () => crypto.createDiffieHellman(prime, loose(true))); +attempt("generator object", () => crypto.createDiffieHellman(prime, loose({}))); +attempt("generator view 1", () => crypto.createDiffieHellman(prime, Buffer.from([1]))); +attempt("generator view 0", () => crypto.createDiffieHellman(prime, Buffer.from([0]))); +attempt("generator view empty", () => crypto.createDiffieHellman(prime, Buffer.alloc(0))); +attempt("generator view 0002", () => crypto.createDiffieHellman(prime, Buffer.from([0, 2]))); +attempt("generator = p", () => crypto.createDiffieHellman(prime, prime)); +attempt("generator > p", () => crypto.createDiffieHellman(prime, Buffer.concat([Buffer.from([1]), prime]))); +attempt("generator string", () => crypto.createDiffieHellman(prime, loose("abc"))); +attempt("generator string hex", () => crypto.createDiffieHellman(prime, loose("05"), loose("hex"))); +attempt("generator bad encoding", () => crypto.createDiffieHellman(prime, loose("05"), loose("nope"))); +attempt("generator uint16", () => crypto.createDiffieHellman(prime, new Uint16Array([0x0300]))); + +attempt("prime hex", () => crypto.createDiffieHellman(prime.toString("hex"), "hex")); +attempt("prime base64 generator", () => crypto.createDiffieHellman(prime.toString("base64"), "base64", 5)); +attempt("prime utf8", () => crypto.createDiffieHellman("abc").verifyError); +attempt("prime buffer encoding", () => crypto.createDiffieHellman("abc", "buffer")); +attempt("keyEncoding as generator", () => crypto.createDiffieHellman("abc", loose("nope")).verifyError); +attempt("keyEncoding as generator with encoding", () => crypto.createDiffieHellman("abc", loose("nope"), loose("hex"))); +attempt("keyEncoding number", () => crypto.createDiffieHellman(prime, loose(5))); +attempt("keyEncoding on a view", () => crypto.createDiffieHellman(prime, loose("hex"), 5)); +attempt("prime ArrayBuffer", () => crypto.createDiffieHellman(new Uint8Array(prime).buffer)); +attempt("prime DataView", () => crypto.createDiffieHellman(new DataView(new ArrayBuffer(3))).verifyError); +attempt("prime zero", () => crypto.createDiffieHellman(Buffer.alloc(4)).getPrime()); + +attempt("group unknown", () => crypto.getDiffieHellman("modp3")); +attempt("group empty", () => crypto.getDiffieHellman("")); +attempt("group ffdhe", () => crypto.createDiffieHellmanGroup("ffdhe2048")); +attempt("group case", () => crypto.getDiffieHellman("MoDp2")); +attempt("group missing", () => crypto.getDiffieHellman(loose(undefined))); +attempt("group number", () => crypto.getDiffieHellman(loose(14))); + +const group = crypto.getDiffieHellman("modp2"); +attempt("group public before keys", () => group.getPublicKey()); +attempt("group private before keys", () => group.getPrivateKey()); +attempt("group secret before keys", () => group.computeSecret(Buffer.from([5]))); +const untypedGroup = loose(group); +attempt("group setPublicKey", () => untypedGroup.setPublicKey(Buffer.from([5]))); +attempt("group setPrivateKey", () => untypedGroup.setPrivateKey(Buffer.from([5]))); +group.generateKeys(); +attempt("secret 0", () => group.computeSecret(Buffer.from([0]))); +attempt("secret empty", () => group.computeSecret(Buffer.alloc(0))); +attempt("secret 1", () => group.computeSecret(Buffer.from([0, 1]))); +attempt("secret p - 1", () => { + const key = Buffer.from(group.getPrime()); + key[key.length - 1]--; + return group.computeSecret(key); +}); +attempt("secret p", () => group.computeSecret(group.getPrime())); +attempt("secret 2", () => group.computeSecret(Buffer.from([2])).length); +attempt("secret number", () => group.computeSecret(loose(5))); +attempt("secret bad input encoding", () => group.computeSecret("ab", loose("nope"))); +attempt("secret bad output encoding", () => untypedGroup.computeSecret(Buffer.from([2]), null, "nope")); +attempt("getPrime bad encoding", () => untypedGroup.getPrime("nope")); +attempt("getPrime HEX", () => untypedGroup.getPrime("HEX").slice(0, 8)); +attempt("getGenerator utf16le", () => untypedGroup.getGenerator("utf16le")); +attempt("verifyError call", () => untypedGroup.verifyError()); +attempt("unknown member", () => untypedGroup.bogus()); + +const fresh = crypto.createDiffieHellman(prime); +attempt("public before keys", () => fresh.getPublicKey()); +attempt("private before keys", () => fresh.getPrivateKey()); +attempt("secret before keys", () => fresh.computeSecret(Buffer.from([5]))); +attempt("setPublicKey number", () => fresh.setPublicKey(loose(5))); +attempt("setPrivateKey bad encoding", () => fresh.setPrivateKey("ab", loose("nope"))); +attempt("setPublicKey 0", () => loose(fresh.setPublicKey(Buffer.from([0]))).getPublicKey()); +attempt("setPrivateKey utf8", () => loose(fresh.setPrivateKey("ab")).getPrivateKey("hex")); + +// Primes outside 512 to 10000 bits: key generation and secrets fail, but a +// private key the program sets still yields a public key. +for (const value of [23, 1, 0, 24]) { + const label = `p ${value}`; + const dh = crypto.createDiffieHellman(Buffer.from([value])); + attempt(`${label} generateKeys`, () => dh.generateKeys()); + attempt(`${label} secret 2`, () => dh.computeSecret(Buffer.from([2]))); + attempt(`${label} secret 5`, () => dh.computeSecret(Buffer.from([5]))); + dh.setPrivateKey(Buffer.from([3])); + attempt(`${label} generateKeys with key`, () => dh.generateKeys()); + attempt(`${label} public with key`, () => dh.getPublicKey()); + attempt(`${label} secret with key`, () => dh.computeSecret(Buffer.from([5]))); +} +const even = Buffer.from(prime); +even[even.length - 1] = 0xfe; +const evenDh = crypto.createDiffieHellman(even); +attempt("even generateKeys", () => evenDh.generateKeys()); +evenDh.setPrivateKey(Buffer.from([3])); +attempt("even generateKeys with key", () => evenDh.generateKeys()); +attempt("p 23 generator 30", () => + loose(crypto.createDiffieHellman(Buffer.from([23]), 30).setPrivateKey(Buffer.from([2]))).generateKeys(), +); +attempt("p 9", () => loose(crypto.createDiffieHellman(Buffer.from([9])).setPrivateKey(Buffer.from([3]))).generateKeys()); + +// Secrets of 0, 1 and p - 1 fail like any other derivation failure: a peer +// key of order 3 or 6 modulo a prime with p ≡ 1 (mod 6), and a peer key +// sharing the factor of a square modulus. +const smooth = Buffer.from( + "ce306415e770bb1cde0380e3c5cf4e8110b5c8e82ca36b1d9074fa1e9d1ed41b0ae295f19288302647d2da0003fcac6fa21d8953afce2c30171844815ec7d6df", + "hex", +); +const orderThree = Buffer.from( + "6be4b47bb9f8143334dab6349ac191ef7208ae3d5e684a2c318d43acc45ebd2a27d79b075c6e14a4e6a75899d98ce05af71ef05e1869b1add76d1622ab5e7b1d", + "hex", +); +const orderSix = Buffer.from( + "624baf9a2d78a6e9a928caaf2b0dbc919ead1aaace3b20f15ee7b671d8c016f0e30afaea361a1b81612b81662a6fcc14aafe98f597647a823fab2e5eb3695bc2", + "hex", +); +function withPrivateKey(modulus, key) { + const dh = crypto.createDiffieHellman(modulus); + dh.setPrivateKey(Buffer.from([key])); + return dh; +} +attempt("secret 1", () => withPrivateKey(smooth, 3).computeSecret(orderThree).toString("hex")); +attempt("secret p - 1", () => withPrivateKey(smooth, 3).computeSecret(orderSix).toString("hex")); +attempt("secret of order 3, key 4", () => withPrivateKey(smooth, 4).computeSecret(orderThree).toString("hex").slice(0, 16)); +const factor = BigInt("0xdf22630cec2362c510f444af6784da7a3a714ed787eb3d6bf9158d18c087cc5d"); +const square = Buffer.from((factor * factor).toString(16).padStart(128, "0"), "hex"); +const factorKey = Buffer.from(factor.toString(16).padStart(128, "0"), "hex"); +attempt("secret 0", () => withPrivateKey(square, 2).computeSecret(factorKey).toString("hex")); diff --git a/tests/corpus/6709-dh-generate.ts b/tests/corpus/6709-dh-generate.ts new file mode 100644 index 000000000..b041605c2 --- /dev/null +++ b/tests/corpus/6709-dh-generate.ts @@ -0,0 +1,47 @@ +// crypto.createDiffieHellman(primeLength, generator) generates a safe +// prime of the requested length: p ≡ 23 (mod 24) for the generator 2, +// p ≡ 59 (mod 60) for 5 and p ≡ 11 (mod 12) otherwise. A second party built +// from the first one's prime and generator agrees on the secret. +import { createDiffieHellman } from "node:crypto"; + +function bitLength(bytes: Buffer): number { + if (bytes.length === 0) return 0; + return (bytes.length - 1) * 8 + bytes[0]!.toString(2).length; +} + +function mod(bytes: Buffer, m: number): number { + let r = 0; + for (const byte of bytes) r = (r * 256 + byte) % m; + return r; +} + +for (const generator of [undefined, 2, 5, 3, 7]) { + const alice = generator === undefined ? createDiffieHellman(512) : createDiffieHellman(512, generator); + const prime = alice.getPrime(); + console.log( + generator, + bitLength(prime), + alice.getGenerator("hex"), + alice.verifyError, + generator === undefined || generator === 2 + ? mod(prime, 24) + : generator === 5 + ? mod(prime, 60) + : mod(prime, 12), + ); + const bob = createDiffieHellman(alice.getPrime(), alice.getGenerator()); + const alicePublic = alice.generateKeys(); + const bobPublic = bob.generateKeys("hex"); + const secret = alice.computeSecret(bobPublic, "hex"); + console.log( + bob.verifyError, + bitLength(alice.getPrivateKey()), + secret.length, + secret.equals(bob.computeSecret(alicePublic)), + ); +} + +// A string prime with its encoding, and the generator as a string. +const shared = createDiffieHellman(512); +const copy = createDiffieHellman(shared.getPrime("base64"), "base64", shared.getGenerator("hex"), "hex"); +console.log(copy.getPrime().equals(shared.getPrime()), copy.getGenerator("hex"), copy.verifyError); diff --git a/tests/corpus/6710-dh-encodings.cjs b/tests/corpus/6710-dh-encodings.cjs new file mode 100644 index 000000000..100ee95e2 --- /dev/null +++ b/tests/corpus/6710-dh-encodings.cjs @@ -0,0 +1,73 @@ +// DiffieHellman string inputs and outputs from CommonJS: primes and +// generators as strings in every binary encoding, the keyEncoding slot +// read as the generator, keys set in every Buffer encoding and read in the +// declared ones, and computeSecret's input and output encodings. +const crypto = require("node:crypto"); + +// Values the declared overloads do not cover reach the calls through an +// untyped function, as they would from other untyped code. +const loose = (value) => value; + +const prime = crypto.getDiffieHellman("modp2").getPrime(); +const encodings = ["hex", "base64", "base64url", "latin1", "binary", "HEX", "Base64"]; + +for (const encoding of encodings) { + const text = prime.toString(encoding.toLowerCase()); + const dh = crypto.createDiffieHellman(text, encoding, "05", "hex"); + console.log(encoding, dh.getPrime().equals(prime), dh.getGenerator("hex")); +} +console.log(crypto.createDiffieHellman(prime.toString("hex"), "hex", "05", "hex").verifyError); + +// A truthy keyEncoding that names no encoding is the generator, and the +// generator slot its encoding. +console.log(crypto.createDiffieHellman(prime, 7).getGenerator("hex")); +console.log(crypto.createDiffieHellman(prime, "\x05").getGenerator("hex")); +console.log(crypto.createDiffieHellman(prime, Buffer.from([3])).getGenerator("hex")); +console.log(crypto.createDiffieHellman(prime, "buffer", 11).getGenerator("hex")); +console.log(crypto.createDiffieHellman(prime, "0d", "hex").getGenerator("hex")); +console.log(crypto.createDiffieHellman(prime, "base64", "Ew==", "base64").getGenerator("hex")); +console.log(crypto.createDiffieHellman(prime, "", 0, "").getGenerator("hex")); + +// Keys in and out of every encoding. +const alice = crypto.createDiffieHellman(prime); +const bob = crypto.createDiffieHellman(prime); +alice.setPrivateKey("q83vEjRWeJA=", "base64"); +bob.setPrivateKey(Buffer.from("10325476", "hex")); +alice.generateKeys(); +bob.generateKeys(); +function report(encoding, key, secret) { + const bytes = Buffer.isBuffer(secret) ? secret : Buffer.from(secret, encoding); + console.log(encoding, typeof key, key.length, bytes.toString("hex").slice(0, 24)); +} +const hex = alice.getPublicKey("hex"); +report("hex", hex, bob.computeSecret(hex, "hex", "hex")); +const base64 = alice.getPublicKey("base64"); +report("base64", base64, bob.computeSecret(base64, "base64", "base64")); +const base64url = alice.getPublicKey("base64url"); +report("base64url", base64url, bob.computeSecret(base64url, "base64url", "base64url")); +const binary = alice.getPublicKey("binary"); +report("binary", binary, bob.computeSecret(binary, "binary", "binary")); +const view = alice.getPublicKey(); +report("undefined", view, bob.computeSecret(view, undefined, undefined)); +report("null", view, bob.computeSecret(view, null, null)); +// Encodings @types/node does not declare for these methods reach them +// through an untyped receiver. +const untypedBob = loose(bob); +console.log(alice.getPrivateKey("hex"), alice.getPrivateKey("base64url"), untypedBob.getPrivateKey("latin1").length); +console.log(untypedBob.getPublicKey("utf16le").length, untypedBob.getPrime("ucs2").length, untypedBob.getGenerator("buffer")); +console.log(untypedBob.computeSecret(loose(alice).getPublicKey("latin1"), "latin1", "base64").slice(0, 16)); + +// setPublicKey and setPrivateKey read strings through their encoding; +// 'buffer' and a missing encoding read utf8. +const keys = crypto.createDiffieHellman(prime); +keys.setPublicKey("ffee", "hex"); +loose(keys).setPrivateKey("zz", "buffer"); +console.log(keys.getPublicKey("hex"), keys.getPrivateKey("hex")); +keys.setPublicKey("é"); +console.log(keys.getPublicKey("hex")); +keys.setPublicKey("é", "latin1"); +console.log(keys.getPublicKey("hex")); +keys.setPrivateKey(new Uint16Array([0x0102, 0x0304])); +console.log(keys.getPrivateKey("hex")); +keys.setPrivateKey(new DataView(new Uint8Array([9, 8, 7]).buffer)); +console.log(keys.getPrivateKey("hex")); diff --git a/tests/corpus/6711-dh-handles.ts b/tests/corpus/6711-dh-handles.ts new file mode 100644 index 000000000..c0c5522be --- /dev/null +++ b/tests/corpus/6711-dh-handles.ts @@ -0,0 +1,56 @@ +// DiffieHellman and DiffieHellmanGroup values as ordinary values: class +// fields, optional fields, arrays, Map values, parameters and return +// values, with verifyError read through each. +import * as crypto from "node:crypto"; +import { type DiffieHellman, type DiffieHellmanGroup } from "node:crypto"; + +const prime = crypto.getDiffieHellman("modp1").getPrime(); + +class Party { + readonly dh: DiffieHellman; + peer: DiffieHellman | null = null; + group?: DiffieHellmanGroup; + + constructor(seed: number) { + this.dh = crypto.createDiffieHellman(prime, 2); + this.dh.setPrivateKey(Buffer.from([seed, seed + 1, seed + 2])); + this.dh.generateKeys(); + } + + secretWith(other: Party): string { + return this.dh.computeSecret(other.dh.getPublicKey(), null, "hex"); + } +} + +const alice = new Party(1); +const bob = new Party(7); +alice.peer = bob.dh; +console.log(alice.secretWith(bob) === bob.secretWith(alice), alice.secretWith(bob).slice(0, 32)); +console.log(alice.peer !== null && alice.peer.getPublicKey().equals(bob.dh.getPublicKey())); +console.log(alice.group === undefined); +alice.group = crypto.getDiffieHellman("modp2"); +console.log(alice.group.verifyError, alice.group.getPrime().length); + +function verify(dh: DiffieHellman | DiffieHellmanGroup): number { + return dh.verifyError; +} + +function make(bytes: number[]): DiffieHellman { + return crypto.createDiffieHellman(Buffer.from(bytes)); +} + +const all: (DiffieHellman | DiffieHellmanGroup)[] = [alice.dh, make([23]), make([24]), crypto.getDiffieHellman("modp5")]; +console.log(all.map(verify).join(",")); +for (const dh of all) console.log(dh.getGenerator("hex"), dh.getPrime().length); + +const byName = new Map(); +for (const name of ["modp1", "modp2"]) byName.set(name, crypto.createDiffieHellmanGroup(name)); +for (const [name, group] of byName) { + group.generateKeys(); + console.log(name, group.getGenerator("hex"), group.computeSecret(alice.dh.getPublicKey()).length); +} + +let maybe: DiffieHellman | undefined; +console.log(maybe?.verifyError); +maybe = make([0x0d]); +console.log(maybe?.verifyError, maybe.getPrime("hex")); diff --git a/tests/corpus/6712-dh-peer-keys.js b/tests/corpus/6712-dh-peer-keys.js new file mode 100644 index 000000000..819fcf960 --- /dev/null +++ b/tests/corpus/6712-dh-peer-keys.js @@ -0,0 +1,117 @@ +// DiffieHellman computeSecret's peer key checks, and keys, primes and +// generators with leading zero bytes: under the RFC 5114 groups a peer key +// outside the order-q subgroup is invalid, while other parameters only +// check the range; a key longer than the prime is too large, and leading +// zeros of any length are ignored. +import crypto from "node:crypto"; + +function attempt(label, run) { + try { + console.log(label, "ok", JSON.stringify(run())); + } catch (e) { + console.log(label, e.name, e.code, e.message); + } +} + +const zeros = Buffer.alloc(100000); +const padded = (bytes) => Buffer.concat([zeros, bytes]); + +// Each group's parameters, and a peer key of small order: h^((p - 1) / r) +// for a small prime r dividing (p - 1) / q. +const groups = [ + { + label: "RFC 5114 1024-bit", + order: 7, + p: "B10B8F96A080E01DDE92DE5EAE5D54EC52C99FBCFB06A3C69A6A9DCA52D23B616073E28675A23D189838EF1E2EE652C013ECB4AEA906112324975C3CD49B83BFACCBDD7D90C4BD7098488E9C219A73724EFFD6FAE5644738FAA31A4FF55BCCC0A151AF5F0DC8B4BD45BF37DF365C1A65E68CFDA76D4DA708DF1FB2BC2E4A4371", + g: "A4D1CBD5C3FD34126765A442EFB99905F8104DD258AC507FD6406CFF14266D31266FEA1E5C41564B777E690F5504F213160217B4B01B886A5E91547F9E2749F4D7FBD7D3B9A92EE1909D0D2263F80A76A6A24C087A091F531DBF0A0169B6A28AD662A4D18E73AFA32D779D5918D08BC8858F4DCEF97C2A24855E6EEB22B3B2E5", + small: "24986e0c35fbae0d16a21b2aab7eac0dc32e9ca8c24c1eb9387366ee8a6df2bee49b6f46ea2525d208c1bc3d87e3749586616e0161a305f670830ba1fa9e4c5a1bd5ae9f4dc2032f1fd99bbcf3f4444a09d4da3ccbde680580ee8d78feced92d1efb235fc9f25c8525a4e5a453ccf7375119cee48b05421c093d10c8b6e90ab8", + }, + { + label: "RFC 5114 2048-bit, 224-bit q", + order: 3, + p: "AD107E1E9123A9D0D660FAA79559C51FA20D64E5683B9FD1B54B1597B61D0A75E6FA141DF95A56DBAF9A3C407BA1DF15EB3D688A309C180E1DE6B85A1274A0A66D3F8152AD6AC2129037C9EDEFDA4DF8D91E8FEF55B7394B7AD5B7D0B6C12207C9F98D11ED34DBF6C6BA0B2C8BBC27BE6A00E0A0B9C49708B3BF8A317091883681286130BC8985DB1602E714415D9330278273C7DE31EFDC7310F7121FD5A07415987D9ADC0A486DCDF93ACC44328387315D75E198C641A480CD86A1B9E587E8BE60E69CC928B2B9C52172E413042E9B23F10B0E16E79763C9B53DCF4BA80A29E3FB73C16B8E75B97EF363E2FFA31F71CF9DE5384E71B81C0AC4DFFE0C10E64F", + g: "AC4032EF4F2D9AE39DF30B5C8FFDAC506CDEBE7B89998CAF74866A08CFE4FFE3A6824A4E10B9A6F0DD921F01A70C4AFAAB739D7700C29F52C57DB17C620A8652BE5E9001A8D66AD7C17669101999024AF4D027275AC1348BB8A762D0521BC98AE247150422EA1ED409939D54DA7460CDB5F6C6B250717CBEF180EB34118E98D119529A45D6F834566E3025E316A330EFBB77A86F0C1AB15B051AE3D428C8F8ACB70A8137150B8EEB10E183EDD19963DDD9E263E4770589EF6AA21E7F5F2FF381B539CCE3409D13CD566AFBB48D6C019181E1BCFE94B30269EDFE72FE9B6AA4BD7B5A0F1C71CFFF4C19C418E1F6EC017981BC087F2A7065B384B890D3191F2BFA", + small: "73ef184cd50bd427992f4bbeaf1d7712f8cb8264929f533ded004618b29064e3583963fc634df866ef9aa5f158077765219401ad4bf0a2c42204241c8a728af1012cfd399a76f13a0e2cb153c0888a9eb0e05312610923777d185f46bf865bbfe86a0e79a6761d7e153cb46e2221dc3415a7e78c22d33c3d1e2363c041bb57badd344969ee2a1c4917d26ab51a20bc343b4db9964871b0918b2b8e97ff7d297e8b8ca2329426755fdf302a6401030c0f0206a0da004cac53d4408d2ff47cff332435d1f01cbeee301b8dda896be231fd38264f1a5c2b51365a8e74e608a2510c26c92c8d091e18577e854c43d5dc3b2779552f6723878deb5ec58bce2da61abe", + }, + { + label: "RFC 5114 2048-bit, 256-bit q", + order: 7, + p: "87A8E61DB4B6663CFFBBD19C651959998CEEF608660DD0F25D2CEED4435E3B00E00DF8F1D61957D4FAF7DF4561B2AA3016C3D91134096FAA3BF4296D830E9A7C209E0C6497517ABD5A8A9D306BCF67ED91F9E6725B4758C022E0B1EF4275BF7B6C5BFC11D45F9088B941F54EB1E59BB8BC39A0BF12307F5C4FDB70C581B23F76B63ACAE1CAA6B7902D52526735488A0EF13C6D9A51BFA4AB3AD8347796524D8EF6A167B5A41825D967E144E5140564251CCACB83E6B486F6B3CA3F7971506026C0B857F689962856DED4010ABD0BE621C3A3960A54E710C375F26375D7014103A4B54330C198AF126116D2276E11715F693877FAD7EF09CADB094AE91E1A1597", + g: "3FB32C9B73134D0B2E77506660EDBD484CA7B18F21EF205407F4793A1A0BA12510DBC15077BE463FFF4FED4AAC0BB555BE3A6C1B0C6B47B1BC3773BF7E8C6F62901228F8C28CBB18A55AE31341000A650196F931C77A57F2DDF463E5E9EC144B777DE62AAAB8A8628AC376D282D6ED3864E67982428EBC831D14348F6F2F9193B5045AF2767164E1DFC967C1FB3F2E55A4BD1BFFE83B9C80D052B985D182EA0ADB2A3B7313D3FE14C8484B1E052588B9B7D2BBD2DF016199ECD06E1557CD0915B3353BBB64E0EC377FD028370DF92B52C7891428CDC67EB6184B523D1DB246C32F63078490F00EF8D647D148D47954515E2327CFEF98C582664B4C0F6CC41659", + small: "7e22fad9cc23b5949616a26b060dcec3557a81d98dc45f51943f4e29b06dd73e6fbf201c01c4c2620b81698048fcb21655d1276bfb402a41c3af50528f2df02b3440a3b7a1855dfe31a549ddce9563ed18fe1530a3a649f87fa4d427d6d2e1b73cf3848177651080f2ca96628fed411c331d9e28d28da5f0c65f2516f9bb4c72e4c9050f5d654bcc0139e66fbc582ae32d345ad84a249d9cea131c6a9af59ecaefbc190ca265394eb8190ff91a6af58327060ca4900829eaa3a1c26f86737d7510bfd55c430bcc1f2db6a62c3bfe1717e5236945c475bb7b36dc2fa5ab06b089325dfd864a6b044622e62a5638ce23f319cf564826ce1e5c1bc1166896c5f205", + }, +]; + +for (const group of groups) { + const p = Buffer.from(group.p, "hex"); + const g = Buffer.from(group.g, "hex"); + const alice = crypto.createDiffieHellman(p, g); + const bob = crypto.createDiffieHellman(p, g); + alice.generateKeys(); + bob.generateKeys(); + const name = group.label; + attempt(`${name}: verifyError`, () => alice.verifyError); + attempt(`${name}: agreed`, () => alice.computeSecret(bob.getPublicKey()).equals(bob.computeSecret(alice.getPublicKey()))); + attempt(`${name}: order ${group.order}`, () => alice.computeSecret(Buffer.from(group.small, "hex")).length); + attempt(`${name}: 2`, () => alice.computeSecret(Buffer.from([2])).length); + attempt(`${name}: p - 2`, () => { + const key = Buffer.from(p); + key[key.length - 1] -= 2; + return alice.computeSecret(key).length; + }); + attempt(`${name}: p - 1`, () => { + const key = Buffer.from(p); + key[key.length - 1] -= 1; + return alice.computeSecret(key).length; + }); + attempt(`${name}: without keys`, () => crypto.createDiffieHellman(p, g).computeSecret(Buffer.from([2])).length); + // The same prime with another generator is not the named group. The + // private key is a multiple of neither 3 nor 7, so the small-order key + // gives a secret other than 1. + const other = crypto.createDiffieHellman(p, 2); + other.setPrivateKey(Buffer.from("0123456789abcdee", "hex")); + attempt(`${name}, generator 2: order ${group.order}`, () => other.computeSecret(Buffer.from(group.small, "hex")).length); + attempt(`${name}, generator 2: 2`, () => other.computeSecret(Buffer.from([2])).length); +} + +// The safe prime groups check only the range: 11 is a quadratic +// non-residue modulo the 2048-bit MODP prime. +const modp14 = crypto.getDiffieHellman("modp14"); +modp14.generateKeys(); +attempt("modp14: non-residue", () => modp14.computeSecret(Buffer.from([11])).length); +const explicit = crypto.createDiffieHellman(modp14.getPrime(), modp14.getGenerator()); +explicit.generateKeys(); +attempt("modp14 explicit: non-residue", () => explicit.computeSecret(Buffer.from([11])).length); + +// Keys longer than the prime, and leading zeros. +const peer = crypto.createDiffieHellman(modp14.getPrime(), 2); +peer.generateKeys(); +const secret = modp14.computeSecret(peer.getPublicKey()); +attempt("100000 bytes of 0xff", () => modp14.computeSecret(Buffer.alloc(100000, 0xff)).length); +attempt("prime and one byte", () => modp14.computeSecret(Buffer.concat([Buffer.from([1]), modp14.getPrime()])).length); +attempt("hex of 100000 bytes", () => modp14.computeSecret(Buffer.alloc(100000, 0x7f).toString("hex"), "hex").length); +attempt("zero-padded key", () => modp14.computeSecret(padded(peer.getPublicKey())).equals(secret)); +attempt("zero-padded hex key", () => modp14.computeSecret(padded(peer.getPublicKey()).toString("hex"), "hex").equals(secret)); +attempt("zeros", () => modp14.computeSecret(zeros).length); +attempt("zero-padded 1", () => modp14.computeSecret(padded(Buffer.from([1]))).length); +attempt("zero-padded p - 1", () => { + const key = Buffer.from(modp14.getPrime()); + key[key.length - 1] -= 1; + return modp14.computeSecret(padded(key)).length; +}); +attempt("zero-padded public key", () => { + const dh = crypto.createDiffieHellman(modp14.getPrime(), 2); + dh.setPublicKey(padded(peer.getPublicKey())); + return dh.getPublicKey().equals(peer.getPublicKey()); +}); +attempt("zero-padded private key", () => { + const dh = crypto.createDiffieHellman(modp14.getPrime(), 2); + dh.setPrivateKey(padded(peer.getPrivateKey())); + return [dh.getPrivateKey().equals(peer.getPrivateKey()), dh.generateKeys().equals(peer.getPublicKey())]; +}); +attempt("zero-padded prime and generator", () => { + const dh = crypto.createDiffieHellman(padded(modp14.getPrime()), padded(Buffer.from([2]))); + return [dh.verifyError, dh.getPrime().equals(modp14.getPrime()), dh.getGenerator("hex")]; +}); +attempt("generator of 100000 bytes", () => crypto.createDiffieHellman(modp14.getPrime(), Buffer.alloc(100000, 0xff)).verifyError); +attempt("zero-padded generator 1", () => crypto.createDiffieHellman(modp14.getPrime(), padded(Buffer.from([1]))).verifyError); diff --git a/tests/corpus/6822-jsx-classic-runtime/factory.ts b/tests/corpus/6822-jsx-classic-runtime/factory.ts new file mode 100644 index 000000000..df09c6dde --- /dev/null +++ b/tests/corpus/6822-jsx-classic-runtime/factory.ts @@ -0,0 +1,7 @@ +// A React-shaped factory for the pragma file: createElement and Fragment. +export const Fragment = "frag"; + +export function createElement(tag: string, props: object | null, ...children: unknown[]): string { + const inner = children.map((child) => String(child)).join(","); + return `${tag}${props === null ? "" : JSON.stringify(props)}(${inner})`; +} diff --git a/tests/corpus/6822-jsx-classic-runtime/html.ts b/tests/corpus/6822-jsx-classic-runtime/html.ts new file mode 100644 index 000000000..2e4beb5cc --- /dev/null +++ b/tests/corpus/6822-jsx-classic-runtime/html.ts @@ -0,0 +1,45 @@ +// A small server-side JSX runtime: h builds elements, render writes HTML. +export type Leaf = string | number | boolean | null | undefined | Element; +export type Child = Leaf | Leaf[]; +export type Props = { [name: string]: unknown }; +export type Component = (props: Props, children: Child[]) => Element; +export interface Element { + tag: string; + props: Props | null; + children: Child[]; +} + +export const Fragment = "#fragment"; + +export function h(tag: string | Component, props: Props | null, ...children: Child[]): Element { + if (typeof tag === "function") return tag(props ?? {}, children); + return { tag, props, children }; +} + +function escape(text: string): string { + return text.replace(/&/g, "&").replace(/${inner}`; +} + +declare global { + namespace JSX { + type Element = import("./html.js").Element; + interface IntrinsicElements { + [name: string]: object; + } + } +} diff --git a/tests/corpus/6822-jsx-classic-runtime/list.jsx b/tests/corpus/6822-jsx-classic-runtime/list.jsx new file mode 100644 index 000000000..d5aa3aee1 --- /dev/null +++ b/tests/corpus/6822-jsx-classic-runtime/list.jsx @@ -0,0 +1,22 @@ +/** @jsx tag */ +// JSX in a JavaScript module, with a JavaScript factory that builds strings. +function tag(name, props, ...children) { + const attributes = Object.entries(props ?? {}) + .map(([key, value]) => ` ${key}=${JSON.stringify(value)}`) + .join(""); + return `<${name}${attributes}>${children.flat().join("")}`; +} + +const names = ["a", "b"]; + +export function List() { + return ( +
      + {names.map((name, index) => ( +
    1. + {name.toUpperCase()} +
    2. + ))} +
    + ); +} diff --git a/tests/corpus/6822-jsx-classic-runtime/main.ts b/tests/corpus/6822-jsx-classic-runtime/main.ts new file mode 100644 index 000000000..4378557a0 --- /dev/null +++ b/tests/corpus/6822-jsx-classic-runtime/main.ts @@ -0,0 +1,15 @@ +// @tsc-jsx +// JSX in .tsx modules with the classic runtime: jsxFactory, jsxFragmentFactory and per-file pragmas. +import { render } from "./html.js"; +import { List } from "./list.js"; +import { Page } from "./page.js"; +import { viaPragma } from "./pragma.js"; + +const items = [ + { id: 1, name: "write ", done: true }, + { id: 2, name: "ship", done: false }, +]; +console.log(render(Page("Today", items))); +console.log(render(Page("Empty", []))); +console.log(viaPragma); +console.log(List()); diff --git a/tests/corpus/6822-jsx-classic-runtime/page.tsx b/tests/corpus/6822-jsx-classic-runtime/page.tsx new file mode 100644 index 000000000..c3fa6a03c --- /dev/null +++ b/tests/corpus/6822-jsx-classic-runtime/page.tsx @@ -0,0 +1,40 @@ +import { Fragment, h, type Child, type Props } from "./html.js"; + +const Ui = { + Badge(props: Props, children: Child[]) { + return {...children}; + }, +}; + +function Row(props: Props) { + const name = typeof props.name === "string" ? props.name : "?"; + const done = props.done === true; + return ( + + ); +} + +export function Page(title: string, items: { id: number; name: string; done: boolean }[]) { + const extra = { lang: "en", dir: "ltr" }; + return ( + <> +

    {title}

    +
      + {items.map((item) => ( + + ))} +
    +

    + {items.filter((item) => item.done).length} of {items.length} done + multi word + badge +

    + + + <>nested {"fragment"} + + ); +} diff --git a/tests/corpus/6822-jsx-classic-runtime/pragma.tsx b/tests/corpus/6822-jsx-classic-runtime/pragma.tsx new file mode 100644 index 000000000..3aea8c330 --- /dev/null +++ b/tests/corpus/6822-jsx-classic-runtime/pragma.tsx @@ -0,0 +1,11 @@ +/** @jsx React.createElement */ +/** @jsxFrag React.Fragment */ +// The per-file pragmas select another factory than the tsconfig's. +import * as React from "./factory.js"; + +export const viaPragma = ( +
    + <>{1} + text +
    +); diff --git a/tests/corpus/6822-jsx-classic-runtime/tsconfig.json b/tests/corpus/6822-jsx-classic-runtime/tsconfig.json new file mode 100644 index 000000000..6ca523cf2 --- /dev/null +++ b/tests/corpus/6822-jsx-classic-runtime/tsconfig.json @@ -0,0 +1,9 @@ +{ + "compilerOptions": { + "strict": true, + "allowJs": true, + "jsx": "react", + "jsxFactory": "h", + "jsxFragmentFactory": "Fragment" + } +} diff --git a/tests/corpus/6824-jsx-automatic-runtime/alt.tsx b/tests/corpus/6824-jsx-automatic-runtime/alt.tsx new file mode 100644 index 000000000..a76d0ca72 --- /dev/null +++ b/tests/corpus/6824-jsx-automatic-runtime/alt.tsx @@ -0,0 +1,3 @@ +/** @jsxImportSource #alt */ +// This file's JSX uses the runtime the pragma names. +export const viaPragma = [one, {1}{2}, <>frag]; diff --git a/tests/corpus/6824-jsx-automatic-runtime/alt/jsx-runtime.ts b/tests/corpus/6824-jsx-automatic-runtime/alt/jsx-runtime.ts new file mode 100644 index 000000000..89b942ed2 --- /dev/null +++ b/tests/corpus/6824-jsx-automatic-runtime/alt/jsx-runtime.ts @@ -0,0 +1,17 @@ +// A second runtime, selected per file with @jsxImportSource. +export const Fragment = "alt-fragment"; + +export function jsx(type: string, props: { children?: unknown }): string { + return `${type}(${JSON.stringify(props.children ?? null)})`; +} + +export function jsxs(type: string, props: { children: unknown[] }): string { + return `${type}[${props.children.map((child) => JSON.stringify(child)).join(",")}]`; +} + +export namespace JSX { + export type Element = string; + export interface IntrinsicElements { + [name: string]: object; + } +} diff --git a/tests/corpus/6824-jsx-automatic-runtime/main.ts b/tests/corpus/6824-jsx-automatic-runtime/main.ts new file mode 100644 index 000000000..b25a4bc09 --- /dev/null +++ b/tests/corpus/6824-jsx-automatic-runtime/main.ts @@ -0,0 +1,10 @@ +// @tsc-jsx +// JSX with the automatic runtime: jsx/jsxs imports from jsxImportSource, keys, and per-file @jsxImportSource. +import { calls } from "#jsx/jsx-runtime"; +import { viaPragma } from "./alt.js"; +import { page } from "./page.js"; +import { render } from "./render.js"; + +console.log(render(page(["ada", "lin"]))); +console.log(calls.join(" ")); +console.log(viaPragma.join(" | ")); diff --git a/tests/corpus/6824-jsx-automatic-runtime/package.json b/tests/corpus/6824-jsx-automatic-runtime/package.json new file mode 100644 index 000000000..53f44dc61 --- /dev/null +++ b/tests/corpus/6824-jsx-automatic-runtime/package.json @@ -0,0 +1,8 @@ +{ + "type": "module", + "imports": { + "#jsx": "./runtime/index.ts", + "#jsx/jsx-runtime": "./runtime/jsx-runtime.ts", + "#alt/jsx-runtime": "./alt/jsx-runtime.ts" + } +} diff --git a/tests/corpus/6824-jsx-automatic-runtime/page.tsx b/tests/corpus/6824-jsx-automatic-runtime/page.tsx new file mode 100644 index 000000000..fe7fd8c0c --- /dev/null +++ b/tests/corpus/6824-jsx-automatic-runtime/page.tsx @@ -0,0 +1,33 @@ +import type { Props } from "#jsx/jsx-runtime"; + +function Card(props: Props) { + return ( +
    +

    {typeof props.title === "string" ? props.title : "?"}

    + {props.children} +
    + ); +} + +export function page(names: string[]) { + const extra = { id: "list", role: "list" }; + return ( + <> + +
      + {names.map((name, index) => ( +
    • + {name} +
    • + ))} +
    +
    +

    fallback

    +

    + two {"children"} +

    +
    {...names}
    +
    + + ); +} diff --git a/tests/corpus/6824-jsx-automatic-runtime/render.ts b/tests/corpus/6824-jsx-automatic-runtime/render.ts new file mode 100644 index 000000000..6f5f1e3c9 --- /dev/null +++ b/tests/corpus/6824-jsx-automatic-runtime/render.ts @@ -0,0 +1,15 @@ +// Renders elements to HTML-like text. +import type { Element } from "#jsx/jsx-runtime"; + +export function render(value: unknown): string { + if (value === null || value === undefined || typeof value === "boolean") return ""; + if (typeof value === "string" || typeof value === "number") return String(value); + if (Array.isArray(value)) return value.map(render).join(""); + const element = value as Element; + const { children, ...rest } = element.props; + const inner = render(children); + if (element.type === "#fragment") return inner; + let attributes = element.key === undefined ? "" : ` key="${element.key}"`; + for (const [name, item] of Object.entries(rest)) attributes += ` ${name}=${JSON.stringify(item)}`; + return `<${element.type}${attributes}>${inner}`; +} diff --git a/tests/corpus/6824-jsx-automatic-runtime/runtime/index.ts b/tests/corpus/6824-jsx-automatic-runtime/runtime/index.ts new file mode 100644 index 000000000..c7809cdc0 --- /dev/null +++ b/tests/corpus/6824-jsx-automatic-runtime/runtime/index.ts @@ -0,0 +1,12 @@ +// The import source's createElement: TypeScript calls it for an element +// whose key follows a spread of props. +import { calls, type Element, type Props } from "./jsx-runtime.js"; + +export function createElement(type: string, props: Props | null, ...children: unknown[]): Element { + calls.push(`createElement:${type}`); + const all: Props = { ...props }; + if (children.length > 0) all["children"] = children.length === 1 ? children[0] : children; + const key = all["key"]; + delete all["key"]; + return { type, props: all, key: key === undefined ? undefined : String(key) }; +} diff --git a/tests/corpus/6824-jsx-automatic-runtime/runtime/jsx-runtime.ts b/tests/corpus/6824-jsx-automatic-runtime/runtime/jsx-runtime.ts new file mode 100644 index 000000000..185aafbd7 --- /dev/null +++ b/tests/corpus/6824-jsx-automatic-runtime/runtime/jsx-runtime.ts @@ -0,0 +1,33 @@ +// The automatic runtime: jsx, jsxs and Fragment, with children in props. +export type Props = { [name: string]: unknown }; +export interface Element { + type: string; + props: Props; + key: string | undefined; +} +export type Component = (props: Props) => Element; + +export const Fragment = "#fragment"; +export const calls: string[] = []; + +function element(kind: string, type: string | Component, props: Props, key?: unknown): Element { + const name = typeof type === "function" ? "component" : type; + calls.push(`${kind}:${name}${key === undefined ? "" : `#${String(key)}`}`); + if (typeof type === "function") return type(props); + return { type, props, key: key === undefined ? undefined : String(key) }; +} + +export function jsx(type: string | Component, props: Props, key?: unknown): Element { + return element("jsx", type, props, key); +} + +export function jsxs(type: string | Component, props: Props, key?: unknown): Element { + return element("jsxs", type, props, key); +} + +export namespace JSX { + export type Element = import("./jsx-runtime.js").Element; + export interface IntrinsicElements { + [name: string]: object; + } +} diff --git a/tests/corpus/6824-jsx-automatic-runtime/tsconfig.json b/tests/corpus/6824-jsx-automatic-runtime/tsconfig.json new file mode 100644 index 000000000..2e5b6aee7 --- /dev/null +++ b/tests/corpus/6824-jsx-automatic-runtime/tsconfig.json @@ -0,0 +1,8 @@ +{ + "compilerOptions": { + "strict": true, + "module": "nodenext", + "jsx": "react-jsx", + "jsxImportSource": "#jsx" + } +} diff --git a/tests/corpus/6825-jsx-automatic-development/main.ts b/tests/corpus/6825-jsx-automatic-development/main.ts new file mode 100644 index 000000000..9ff046128 --- /dev/null +++ b/tests/corpus/6825-jsx-automatic-development/main.ts @@ -0,0 +1,5 @@ +// @tsc-jsx +// JSX with react-jsxdev: jsxDEV gets the key, static children, the source position and `this`. +import { views } from "./view.js"; + +for (const view of views()) console.log(view); diff --git a/tests/corpus/6825-jsx-automatic-development/package.json b/tests/corpus/6825-jsx-automatic-development/package.json new file mode 100644 index 000000000..cbd76bd4f --- /dev/null +++ b/tests/corpus/6825-jsx-automatic-development/package.json @@ -0,0 +1,6 @@ +{ + "type": "module", + "imports": { + "#dev/jsx-dev-runtime": "./runtime/jsx-dev-runtime.ts" + } +} diff --git a/tests/corpus/6825-jsx-automatic-development/runtime/jsx-dev-runtime.ts b/tests/corpus/6825-jsx-automatic-development/runtime/jsx-dev-runtime.ts new file mode 100644 index 000000000..f4e3aea4b --- /dev/null +++ b/tests/corpus/6825-jsx-automatic-development/runtime/jsx-dev-runtime.ts @@ -0,0 +1,31 @@ +// The development runtime: jsxDEV receives the key, whether the children +// are static, the element's source position and the calling `this`. +export const Fragment = "#fragment"; + +interface Source { + fileName: string; + lineNumber: number; + columnNumber: number; +} + +export function jsxDEV( + type: string | ((props: { [name: string]: unknown }) => string), + props: { [name: string]: unknown }, + key: unknown, + isStatic: boolean, + source: Source, + self: unknown, +): string { + const file = source.fileName.slice(source.fileName.lastIndexOf("/") + 1); + const where = `${file}:${source.lineNumber}:${source.columnNumber}`; + const owner = self === undefined ? "none" : typeof self; + const name = typeof type === "function" ? type(props) : type; + return `${name}{key=${String(key)} static=${isStatic} at=${where} self=${owner}}`; +} + +export namespace JSX { + export type Element = string; + export interface IntrinsicElements { + [name: string]: object; + } +} diff --git a/tests/corpus/6825-jsx-automatic-development/tsconfig.json b/tests/corpus/6825-jsx-automatic-development/tsconfig.json new file mode 100644 index 000000000..e1e88d270 --- /dev/null +++ b/tests/corpus/6825-jsx-automatic-development/tsconfig.json @@ -0,0 +1,8 @@ +{ + "compilerOptions": { + "strict": true, + "module": "nodenext", + "jsx": "react-jsxdev", + "jsxImportSource": "#dev" + } +} diff --git a/tests/corpus/6825-jsx-automatic-development/view.tsx b/tests/corpus/6825-jsx-automatic-development/view.tsx new file mode 100644 index 000000000..05fdc7b32 --- /dev/null +++ b/tests/corpus/6825-jsx-automatic-development/view.tsx @@ -0,0 +1,21 @@ +function Leaf() { + return "leaf"; +} + +export class Panel { + title = "panel"; + render() { + return
    {1}{2}
    ; + } +} + +export function views(): string[] { + return [ +

    one

    , + , + <> + + , + new Panel().render(), + ]; +} diff --git a/tests/corpus/6826-map-primitive-constructors.ts b/tests/corpus/6826-map-primitive-constructors.ts new file mode 100644 index 000000000..f6d61bd48 --- /dev/null +++ b/tests/corpus/6826-map-primitive-constructors.ts @@ -0,0 +1,25 @@ +// The String, Number and Boolean constructors passed as callbacks: over +// unknown arrays they convert any element, over typed arrays String converts +// each element as String(value) does, and the boxed values keep identity. +const values: unknown[] = [1, "b", true, null, undefined, Symbol("s"), [1, 2], { a: 1 }, 2n]; +console.log(values.map(String).join("|")); +console.log(values.slice(0, 5).map(Number), values.map(Boolean)); + +function joinAll(...parts: unknown[]): string { + return parts.map(String).join(","); +} +console.log(joinAll(1, "a", false, null)); + +const numbers = [1, 2.5, -0, NaN, Infinity]; +console.log(numbers.map(String)); +const mixed: (number | string | boolean)[] = [1, "x", false]; +console.log(mixed.map(String)); +const symbols: (symbol | string)[] = [Symbol("q"), "r", Symbol()]; +console.log(symbols.map(String)); +console.log([10n, -3n].map(String)); +console.log(["1", " 2 ", "x", ""].map(Number), ["", "0", "a"].map(Boolean)); + +const boxed: unknown = String; +const table: { [name: string]: unknown } = { s: String, n: Number, b: Boolean }; +console.log(boxed === String, table.n === Number, table.b === String, typeof boxed); +console.log(values.filter(Boolean).length, values.some(Boolean), numbers.every(Boolean)); diff --git a/tests/corpus/6827-recursive-union-nested-literals.ts b/tests/corpus/6827-recursive-union-nested-literals.ts new file mode 100644 index 000000000..900bbf977 --- /dev/null +++ b/tests/corpus/6827-recursive-union-nested-literals.ts @@ -0,0 +1,29 @@ +// A recursive JSON-like union with an array arm and an index-signature +// record arm: nested literals mix records into arrays and arrays into +// records at every depth. +type Json = null | boolean | number | string | Json[] | { [key: string]: Json }; + +function show(value: Json): string { + return JSON.stringify(value); +} + +const config: Json = { list: [1, "two", null, { nested: [true, { deeper: [] }] }], flag: false }; +console.log(show(config)); +console.log(show({ list: [{ n: true }] })); +console.log(show([1, { k: null }, [{ a: [2] }]])); +console.log(show({ a: { b: [{ c: "x" }, 3] } })); + +const rows: Json[] = [{ id: 1, tags: ["a", { t: 2 }] }, [null, { x: [] }]]; +console.log(rows.map(show).join(" | ")); + +let value: Json = []; +value = { replaced: [1, { again: [true] }] }; +console.log(show(value)); + +const doc: { [key: string]: Json } = { items: [{ name: "x", parts: [1, { p: "q" }] }] }; +console.log(show(doc)); +const items = doc["items"]; +if (Array.isArray(items)) { + items.push({ added: [9] }); + console.log(items.length, show(items)); +} diff --git a/tests/corpus/6828-recursive-union-object-walkers.ts b/tests/corpus/6828-recursive-union-object-walkers.ts new file mode 100644 index 000000000..5c854eb94 --- /dev/null +++ b/tests/corpus/6828-recursive-union-object-walkers.ts @@ -0,0 +1,83 @@ +// Recursive walkers over a JSON-like union: the array branch calls the +// walker for each element, and the record branch reads the narrowed record +// with Object.values, Object.keys and Object.entries. +type Json = null | boolean | number | string | Json[] | { [key: string]: Json }; + +function depth(value: Json): number { + if (Array.isArray(value)) return 1 + Math.max(0, ...value.map(depth)); + if (value !== null && typeof value === "object") return 1 + Math.max(0, ...Object.values(value).map(depth)); + return 0; +} + +function count(value: Json): number { + let total = 1; + if (Array.isArray(value)) { + for (const item of value) total += count(item); + } else if (value !== null && typeof value === "object") { + for (const item of Object.values(value)) total += count(item); + } + return total; +} + +function paths(value: Json, prefix: string): string[] { + if (Array.isArray(value)) return value.flatMap((item, index) => paths(item, `${prefix}[${index}]`)); + if (value !== null && typeof value === "object") { + const out: string[] = []; + for (const key of Object.keys(value)) out.push(...paths(value[key]!, `${prefix}.${key}`)); + for (const [key, item] of Object.entries(value)) if (item === null) out.push(`${prefix}.${key}=null`); + return out; + } + return [`${prefix}=${String(value)}`]; +} + +const doc: Json = JSON.parse('{"a":[1,{"b":[true,null]}],"c":{"d":"x"},"e":[]}'); +console.log(depth(doc), count(doc)); +console.log(paths(doc, "$").join(" ")); +console.log(depth(3), count([[[]]]), paths([], "$")); + +// A computed-key read or write in a branch that an array hole reaches throws +// Node's TypeError after the key (and, for a write, the value) evaluates. +type Bag = number | string | number[] | { [key: string]: number }; +const keys: string[] = []; +function keyOf(k: string): string { + keys.push(k); + return k; +} +function isBag(value: Bag): value is { [key: string]: number } { + return !Array.isArray(value) && typeof value !== "string" && typeof value !== "number"; +} +function bump(value: Bag, k: string): string { + if (isBag(value)) { + value[keyOf(k)] = (value[keyOf(k)] ?? 0) + 1; + return String(value[keyOf(k)]); + } + return "-"; +} +function put(value: Bag, k: string): string { + if (isBag(value)) { + value[keyOf(k)] = keys.length; + return "put"; + } + return "-"; +} +function peek(value: Bag, k: string): string { + if (isBag(value)) return typeof value[keyOf(k)]; + return "-"; +} +const bags: Bag[] = [{ a: 1 }, "s", [1]]; +bags.length = 4; +for (const which of ["bump", "put", "peek"]) { + const out: string[] = []; + for (let i = 0; i < bags.length; i++) { + try { + const k = "a" + which.length; + if (which === "bump") out.push(bump(bags[i], k)); + else if (which === "put") out.push(put(bags[i], k)); + else out.push(peek(bags[i], k)); + } catch (e) { + out.push(e instanceof TypeError ? e.message : "other"); + } + } + console.log(out.join(" | ")); +} +console.log(keys.join(","), JSON.stringify(bags)); diff --git a/tests/corpus/6862-readline-chained-listeners.cjs b/tests/corpus/6862-readline-chained-listeners.cjs new file mode 100644 index 000000000..78c05063f --- /dev/null +++ b/tests/corpus/6862-readline-chained-listeners.cjs @@ -0,0 +1,29 @@ +// Chained readline listener registration: on(), once() and addListener() +// return the interface, so `createInterface(...).on('line', f).on('close', g)` +// registers both listeners, in order, on the same interface; a chain's value +// is the interface itself. +'use strict'; +const readline = require('node:readline'); +const { Readable } = require('node:stream'); + +const lines = []; +readline + .createInterface({ input: Readable.from(['alpha\nbeta\n', 'gamma\n']), terminal: false }) + .on('line', (line) => lines.push(line)) + .once('line', (line) => console.log('first line', line)) + .on('close', () => console.log('lines', lines.length, lines.join(','))); + +const rl = readline.createInterface({ input: Readable.from(['one\ntwo']) }); +const same = rl.on('line', (line) => console.log('rl line', line)).addListener('close', () => { + console.log('rl close'); +}); +console.log('chain returns the interface', same === rl); + +let count = 0; +readline + .createInterface({ input: Readable.from(['x\ny\nz\n']) }) + .on('line', () => { + count++; + }) + .on('pause', () => console.log('pause after', count)) + .on('close', () => console.log('count', count)); diff --git a/tests/corpus/6865-number-parseint-default-radix.ts b/tests/corpus/6865-number-parseint-default-radix.ts new file mode 100644 index 000000000..dc6d2a4ad --- /dev/null +++ b/tests/corpus/6865-number-parseint-default-radix.ts @@ -0,0 +1,16 @@ +// Number.parseInt without a radix parses as the global parseInt does: radix +// 10, or 16 after a 0x prefix, after leading whitespace and a sign, stopping +// at the first character that is not a digit. +const inputs = ["42", " 17px", "0x1F", "-0x10", "0X0a", "08", "010", "1e3", "", " ", "abc", " -0", "+12", "9007199254740993", "0b11", "0o17", "\t\n 99 bottles", "١٢", "-", "0x"]; +for (const text of inputs) { + const parsed = Number.parseInt(text); + console.log(JSON.stringify(text), Object.is(parsed, -0) ? "-0" : String(parsed), parsed === parseInt(text)); +} + +function depth(arg: string | undefined): number { + return Math.max(6, Number.parseInt(arg ?? "10")); +} +console.log("depth", depth(process.argv[2]), depth("21"), depth("3")); + +const sizes = "640x480".split("x").map((part) => Number.parseInt(part)); +console.log("sizes", sizes[0]! * sizes[1]!); diff --git a/tests/corpus/6866-number-parseint-untyped.js b/tests/corpus/6866-number-parseint-untyped.js new file mode 100644 index 000000000..48223bd9b --- /dev/null +++ b/tests/corpus/6866-number-parseint-untyped.js @@ -0,0 +1,9 @@ +// Number.parseInt over untyped values in JavaScript, with and without a +// radix: the argument converts with ToString first ("undefined", "null", +// "1,2" for an array), then parses as the global parseInt does. +const config = JSON.parse('{"port":"8080","hex":"0xff","list":[3,4],"flag":true,"none":null}'); +for (const key of ["port", "hex", "list", "flag", "none", "missing"]) { + const value = config[key]; + console.log(key, Number.parseInt(value), Number.parseInt(value, 16), Number.parseInt(value, 36)); +} +console.log("argv", Number.parseInt(process.argv[2])); diff --git a/tests/corpus/6867-string-match-optional-regexp.js b/tests/corpus/6867-string-match-optional-regexp.js new file mode 100644 index 000000000..e847bda36 --- /dev/null +++ b/tests/corpus/6867-string-match-optional-regexp.js @@ -0,0 +1,20 @@ +// String match and search in JavaScript with a pattern that may be undefined +// (a Map lookup or an array read): a RegExp matches as usual, and an +// undefined pattern is `new RegExp(undefined)`, the empty pattern. +const text = 'agggtaaa tttaccct agggtaaa'; +const patterns = new Map([ + ['forward', /agggtaaa/g], + ['either', /agggtaaa|tttaccct/gi], + ['first', /t+a/], +]); +for (const name of ['forward', 'either', 'first', 'missing']) { + const re = patterns.get(name); + const m = text.match(re); + console.log(name, m === null ? null : m.length, m === null ? '' : JSON.stringify([...m]), text.search(re)); +} + +const list = [/a(g+)/, /x/]; +for (let i = 0; i < 3; i++) { + const m = text.match(list[i]); + console.log(i, m === null ? 'null' : `${m[0]} at ${m.index} ${m[1] ?? ''}`, text.search(list[i])); +} diff --git a/tests/corpus/6868-buffer-from-untyped-array-buffer.cjs b/tests/corpus/6868-buffer-from-untyped-array-buffer.cjs new file mode 100644 index 000000000..ff2c59a46 --- /dev/null +++ b/tests/corpus/6868-buffer-from-untyped-array-buffer.cjs @@ -0,0 +1,56 @@ +// Buffer.from over an untyped ArrayBuffer or SharedArrayBuffer (read from a +// Map, an untyped object field or a worker message): the Buffer covers the +// buffer from its byte offset (the second argument) and shares its memory, in +// both directions, as in Node. An encoding name or NaN in the second argument +// is offset 0; an offset past the end throws ERR_BUFFER_OUT_OF_BOUNDS. +'use strict'; +const { Worker, isMainThread, parentPort, workerData } = require('node:worker_threads'); + +if (isMainThread) { + const store = new Map(); + store.set('plain', new ArrayBuffer(6)); + store.set('shared', new SharedArrayBuffer(6)); + for (const key of ['plain', 'shared']) { + const storage = store.get(key); + const buf = Buffer.from(storage); + buf[1] = 0x41; + new Uint8Array(storage)[2] = 0x42; + console.log(key, buf.length, Buffer.isBuffer(buf), buf.toString('hex'), new Uint8Array(storage).join(',')); + const encoded = Buffer.from(storage, 'utf8'); + console.log(key, 'with encoding', encoded.length, encoded.toString('hex')); + } + + const offsets = new Map(); + offsets.set('storage', new ArrayBuffer(8)); + const storage = offsets.get('storage'); + for (const offset of [2, 1.5, '3', NaN, null, undefined, true, 8, 9, -1, -0.5, -1.5, -1e21, -Number.MAX_VALUE, -Infinity]) { + try { + const view = Buffer.from(storage, offset); + view.fill(offset === 2 ? 0x11 : 0); + console.log('offset', String(offset), view.byteOffset, view.length, new Uint8Array(storage).join(',')); + } catch (error) { + console.log('offset', String(offset), error.name, error.code, error.message); + } + } + const sharedOffsets = new Map([['s', new SharedArrayBuffer(6)]]); + const tail = Buffer.from(sharedOffsets.get('s'), 4); + tail[0] = 0x7f; + console.log('shared offset', tail.length, new Uint8Array(sharedOffsets.get('s')).join(',')); + + const holder = JSON.parse('{}'); + holder.data = new ArrayBuffer(3); + const view = Buffer.from(holder.data); + view.write('xyz'); + console.log('field', Buffer.from(holder.data).toString()); + + const sab = new SharedArrayBuffer(8); + const worker = new Worker(__filename, { workerData: sab }); + worker.on('message', (message) => { + const seen = Buffer.from(message.storage); + console.log('worker wrote', seen.toString('latin1'), new Uint8Array(sab).join(',')); + }); +} else { + const out = Buffer.from(workerData); + out.write('shared!'); + parentPort.postMessage({ storage: workerData }); +} diff --git a/tests/corpus/6869-atomics-untyped-arrays.cjs b/tests/corpus/6869-atomics-untyped-arrays.cjs new file mode 100644 index 000000000..18fe07319 --- /dev/null +++ b/tests/corpus/6869-atomics-untyped-arrays.cjs @@ -0,0 +1,65 @@ +// Atomics over untyped arrays in JavaScript: a worker's workerData carries +// Int32Array and Uint8Array views of a SharedArrayBuffer, and load, store, +// add, sub, and, or, xor, exchange, compareExchange, wait and notify run on +// them as on typed bindings. Other values throw Node's +// TypeError, and an index outside the array Node's RangeError. The results +// go to an untyped array. +'use strict'; +const { Worker, isMainThread, parentPort, workerData } = require('node:worker_threads'); + +const lines = []; +function attempt(label, run) { + try { + run(); + lines.push(`${label} ok`); + } catch (error) { + lines.push(`${label} ${error.name} ${error.message}`); + } +} + +if (isMainThread) { + const sab = new SharedArrayBuffer(16); + const counters = new Int32Array(sab); + const worker = new Worker(__filename, { workerData: { counters, bytes: new Uint8Array(sab, 8, 8) } }); + worker.on('message', (message) => { + if (message === 'ready') { + Atomics.store(counters, 1, 42); + console.log('notified', Atomics.notify(counters, 1, 1) >= 0); + return; + } + for (const line of message.lines) console.log(line); + console.log('worker results', JSON.stringify(message.out)); + console.log('counters', Array.from(counters).join(',')); + }); +} else { + const counters = workerData.counters; + const bytes = workerData.bytes; + const out = []; + out.push(Atomics.add(counters, 0, 5), Atomics.sub(counters, 0, 2), Atomics.load(counters, 0)); + out.push(Atomics.or(counters, 2, 6), Atomics.and(counters, 2, 3), Atomics.xor(counters, 2, 1), Atomics.load(counters, 2)); + out.push(Atomics.exchange(counters, 3, 9), Atomics.compareExchange(counters, 3, 9, 11), Atomics.compareExchange(counters, 3, 0, 1)); + out.push(Atomics.add(bytes, 0, 300), Atomics.load(bytes, 0), Atomics.sub(bytes, 1, 1), Atomics.load(bytes, 1)); + out.push(Atomics.load(counters, 1.9), Atomics.load(counters, NaN)); + attempt('index past the end', () => { + Atomics.load(counters, 4); + }); + attempt('negative index', () => { + Atomics.add(bytes, -1, 1); + }); + const values = [[], {}, undefined, null, 5, 'text', new Float64Array(2), new Map(), new ArrayBuffer(4), new DataView(new ArrayBuffer(4))]; + for (const value of values) { + attempt('load', () => { + Atomics.load(value, 0); + }); + attempt('notify', () => { + Atomics.notify(value, 0); + }); + } + attempt('wait on Uint8Array', () => { + Atomics.wait(bytes, 0, 0, 0); + }); + out.push(Atomics.wait(counters, 1, 0, 0)); + parentPort.postMessage('ready'); + out.push(Atomics.wait(counters, 1, 0, 5000) === 'ok' || Atomics.load(counters, 1) === 42); + parentPort.postMessage({ out, lines }); +} diff --git a/tests/corpus/6870-error-constructor-values.js b/tests/corpus/6870-error-constructor-values.js new file mode 100644 index 000000000..79c970914 --- /dev/null +++ b/tests/corpus/6870-error-constructor-values.js @@ -0,0 +1,65 @@ +// The error constructors as values in JavaScript: an error's `constructor` +// is the same function the global names, whose name, length, typeof and +// String() are Node's, for errors the program throws, errors the runtime +// throws, and errors read back from catch bindings and containers. +function describe(label, error) { + const ctor = error.constructor; + console.log(label, error.name, error.constructor.name, typeof ctor, ctor.length, String(ctor)); +} + +describe('Error', new Error('e')); +describe('TypeError', new TypeError('t')); +describe('RangeError', new RangeError('r')); +describe('SyntaxError', new SyntaxError('s')); +describe('ReferenceError', new ReferenceError('f')); +describe('EvalError', new EvalError('v')); +describe('URIError', new URIError('u')); +describe('AggregateError', new AggregateError([], 'a')); + +const thrown = [ + () => JSON.parse('{'), + () => { + const holder = JSON.parse('{"value":null}'); + return holder.value.missing; + }, + () => new Array(-1), + () => decodeURIComponent('%'), + () => { + throw new TypeError('own'); + }, +]; +const constructors = { SyntaxError, TypeError, RangeError, URIError }; +const caught = []; +for (const run of thrown) { + try { + run(); + } catch (error) { + caught.push(error); + console.log('caught', error.constructor.name, error.constructor === constructors[error.name]); + } +} + +const byName = new Map(); +for (const error of caught) byName.set(error.constructor.name, (byName.get(error.constructor.name) ?? 0) + 1); +console.log('kinds', JSON.stringify([...byName])); + +console.log('identity', new TypeError('x').constructor === TypeError, new RangeError('x').constructor === TypeError); +console.log('globals', Error.name, TypeError.length, AggregateError.length, typeof RangeError, String(SyntaxError)); + +const renamed = new TypeError('x'); +renamed.name = 'Custom'; +console.log('renamed', renamed.name, renamed.constructor.name); + +class ParseFailure extends SyntaxError {} +const failure = new ParseFailure('p'); +console.log('subclass', failure.name, failure.constructor.name, failure instanceof SyntaxError); + +// Effect's isStackTraceLimitWritable reflects on Error as a value. +const limit = Object.getOwnPropertyDescriptor(Error, 'stackTraceLimit'); +console.log('stackTraceLimit', JSON.stringify(limit), Object.hasOwn(limit, 'writable') ? limit.writable === true : limit.set !== undefined); +Error.stackTraceLimit = 4; +console.log('stackTraceLimit now', Object.getOwnPropertyDescriptor(Error, 'stackTraceLimit').value); +Error.stackTraceLimit = 10; +for (const ctor of [Error, TypeError, AggregateError, Object, Map]) { + console.log('extensible', ctor.name, Object.isExtensible(ctor), Object.isFrozen(ctor), Object.isSealed(ctor)); +} diff --git a/tests/corpus/6871-worker-data-destructuring.cjs b/tests/corpus/6871-worker-data-destructuring.cjs new file mode 100644 index 000000000..63ae789bd --- /dev/null +++ b/tests/corpus/6871-worker-data-destructuring.cjs @@ -0,0 +1,30 @@ +// Destructuring the members of a worker's workerData in JavaScript: plain, +// renamed, defaulted, nested and rest bindings read the data the worker was +// started with, as reading `workerData.` does. +'use strict'; +const { Worker, isMainThread, parentPort, workerData } = require('node:worker_threads'); + +if (isMainThread) { + const sab = new SharedArrayBuffer(8); + const data = { name: 'job-7', size: 3, options: { verbose: true, tags: ['a', 'b'] }, counters: new Int32Array(sab), extra: 1, more: 'x' }; + const worker = new Worker(__filename, { workerData: data }); + worker.on('message', (lines) => { + for (const line of lines) console.log(line); + console.log('main sees', new Int32Array(sab)[0]); + }); +} else { + const lines = []; + const { name, size } = workerData; + lines.push(`plain ${name} ${size}`); + const { name: jobName, missing = 'fallback', size: count = 10 } = workerData; + lines.push(`renamed ${jobName} ${missing} ${count}`); + const { + options: { verbose, tags: [firstTag, ...otherTags] }, + } = workerData; + lines.push(`nested ${verbose} ${firstTag} ${JSON.stringify(otherTags)}`); + const { name: ignored, size: alsoIgnored, options, counters, ...rest } = workerData; + lines.push(`rest ${JSON.stringify(rest)} ${typeof options} ${ignored === name && alsoIgnored === size}`); + counters[0] = 41; + counters[0] += 1; + parentPort.postMessage(lines); +} diff --git a/tests/corpus/6872-regex-start-filter.ts b/tests/corpus/6872-regex-start-filter.ts new file mode 100644 index 000000000..872342e93 --- /dev/null +++ b/tests/corpus/6872-regex-start-filter.ts @@ -0,0 +1,79 @@ +// Searches whose patterns begin with fixed sequences of characters and +// classes (literal alternations, classes, fixed repetitions), over subjects +// of every length from 0 to 80 and with matches at every offset: match, +// matchAll, search, exec with captures, global and sticky lastIndex, +// replace, case-insensitive letters, multiline anchors and word boundaries. +// Results must not depend on where a match falls relative to 16-character +// blocks or the end of the subject. +const patterns: RegExp[] = [ + /agggtaaa|tttaccct/gi, + /[cgt]gggtaaa|tttaccc[acg]/gi, + /ab|abc|b/g, + /(ab)(c|d)x/g, + /x[0-9]{3}y/g, + /(?:no|yes)(!+)/gi, + /^ab/gm, + /\bcat\b/g, + /a{2}(b+)c/g, + /[A-Z][a-z]{2}-[0-9]/g, +]; + +function describe(re: RegExp, subject: string): string { + const parts: string[] = []; + const all = subject.match(re); + parts.push(`match=${all === null ? "null" : JSON.stringify(all)}`); + parts.push(`search=${subject.search(re)}`); + const rows: string[] = []; + for (const m of subject.matchAll(re)) rows.push(`${m.index}:${JSON.stringify(m.slice(0))}`); + parts.push(`all=[${rows.join(" ")}]`); + parts.push(`replace=${JSON.stringify(subject.replace(re, "<$&>"))}`); + return parts.join(" "); +} + +const filler = "qwertyuiopasdfghjklzxcvbnm"; +const needles = ["agggtaaa", "TTTACCCT", "tttacccg", "abcx", "abdx", "x123y", "NO!!", "yes!", "cat", "aabbbc", "Abc-1", "ab"]; +let checksum = 0; +let lines = 0; +for (let length = 0; length <= 80; length += 7) { + for (const needle of needles) { + for (const offset of [0, 1, 14, 15, 16, 17, 31, 32, 33]) { + if (offset + needle.length > length) continue; + let subject = ""; + while (subject.length < length) subject += filler; + subject = subject.slice(0, offset) + needle + subject.slice(offset + needle.length, length); + for (const re of patterns) { + const text = describe(re, subject); + for (let i = 0; i < text.length; i++) checksum = (checksum * 31 + text.charCodeAt(i)) >>> 0; + lines++; + if (length === 35 && (offset === 15 || offset === 16)) console.log(re.source, offset, needle, text); + } + } + } +} +console.log("lines", lines, "checksum", checksum); + +// Overlapping candidates: every start position looks like a match for the +// first characters, and only some complete. +const dense = "agggtaa".repeat(9) + "agggtaaa" + "tttaccc".repeat(5) + "tttaccct"; +console.log(describe(/agggtaaa|tttaccct/g, dense)); + +// exec with lastIndex, global and sticky. +const re = /x[0-9]{3}y/g; +const text = "zzx111yzzzzzzzzzzzzzzzzzzx222yx333y" + "z".repeat(20) + "x444y"; +let m: RegExpExecArray | null; +const found: string[] = []; +while ((m = re.exec(text)) !== null) found.push(`${m[0]}@${m.index}->${re.lastIndex}`); +console.log("exec", found.join(" ")); +const sticky = /x[0-9]{3}y/y; +sticky.lastIndex = 2; +console.log("sticky", sticky.test(text), sticky.lastIndex, sticky.test(text), sticky.lastIndex); + +// Short subjects and the tail. +for (const subject of ["", "a", "agggtaa", "agggtaaa", "zagggtaaa", "z".repeat(16) + "agggtaaa", "z".repeat(23) + "tttaccct"]) { + console.log(JSON.stringify(subject.slice(-12)), subject.length, describe(/agggtaaa|tttaccct/gi, subject)); +} + +// A long subject with matches spread through it. +let long = ""; +for (let i = 0; i < 2000; i++) long += i % 97 === 0 ? "aGgGtAaA" : i % 89 === 0 ? "tttACCCt" : filler[i % filler.length]; +console.log("long", (long.match(/agggtaaa|tttaccct/gi) ?? []).length, long.search(/tttaccct/i)); diff --git a/tests/corpus/6912-extend-factory-local-class.ts b/tests/corpus/6912-extend-factory-local-class.ts new file mode 100644 index 000000000..e33a59c77 --- /dev/null +++ b/tests/corpus/6912-extend-factory-local-class.ts @@ -0,0 +1,99 @@ +// A generic factory returns its own local class through a declared +// constructor type, and a class extends the factory's result. The local +// class's static methods read the factory's parameter, inherit into the +// subclass, and call each other through `this`. +type Struct = (abstract new () => S) & { readonly decode: (value: unknown) => S }; +function struct(value: S): Struct { + abstract class Base { + static decode(_input: unknown): S { + return value; + } + } + return Base as Struct; +} +class Counter extends struct({ value: 42 }) {} +console.log(Counter.decode(null).value); + +type Named = (new (label: string) => { label: string; payload: T }) & { + readonly describe: () => string; + readonly make: (label: string) => { label: string; payload: T }; +}; +function named(kind: string, payload: T): Named { + class Entry { + label: string; + payload: T; + constructor(label: string) { + this.label = label; + this.payload = payload; + } + static describe(): string { + return `entry of ${kind}`; + } + static make(label: string): Entry { + return new this(label); + } + } + return Entry; +} +class Tag extends named("tag", [1, 2, 3]) { + shout(): string { + return this.label.toUpperCase(); + } +} +const tag = new Tag("hello"); +console.log(tag.shout(), tag.payload.join("+"), Tag.describe()); +const made = Tag.make("made"); +console.log(made.label, made.payload.length); + +const Flags = named("flag", { on: true }); +const flag = new Flags("first"); +console.log(flag.label, flag.payload.on, Flags.describe()); +const Other = named("other", 5); +console.log(Other.describe(), new Other("x").payload, Flags.describe()); + +// A function-local class's static methods read the function's parameter and +// call each other through `this`. +function twice(n: number): number { + class K { + static double(): number { + return n * 2; + } + static quad(): number { + return this.double() * 2; + } + } + return K.double() + K.quad(); +} +console.log(twice(3), twice(5)); + +// The factory returns an anonymous class expression, directly or through a +// `const` binding. +function anonymous(value: S): Struct { + return class { + static decode(_input: unknown): S { + return value; + } + } as unknown as Struct; +} +class Anonymous extends anonymous({ tag: "anon" }) {} +console.log(Anonymous.decode(null).tag); + +type Holder = (new (held: T) => { held: T }) & { readonly seed: () => T }; +function holder(initial: T): Holder { + const Hold = class { + held: T; + constructor(held: T) { + this.held = held; + } + static seed(): T { + return initial; + } + }; + return Hold; +} +class Boxed extends holder(7) { + twice(): number { + return this.held * 2; + } +} +console.log(new Boxed(4).twice(), Boxed.seed()); diff --git a/tests/corpus/6913-builtin-constructor-shorthand.ts b/tests/corpus/6913-builtin-constructor-shorthand.ts new file mode 100644 index 000000000..7fb5066ed --- /dev/null +++ b/tests/corpus/6913-builtin-constructor-shorthand.ts @@ -0,0 +1,10 @@ +// Builtin constructors in shorthand properties are the constructors themselves. +const direct: Record = { Date: Date, Map: Map, Set: Set }; +const shorthand: Record = { Date, Map, Set, Object, Promise, WeakMap }; +console.log(shorthand.Date === Date, shorthand.Map === direct.Map, shorthand.Set === direct.Set); +console.log(shorthand.Object === Object, shorthand.Promise === Promise, shorthand.WeakMap === WeakMap); +console.log(typeof shorthand.Date, typeof shorthand.Map); +function pick(table: Record, name: string): unknown { + return table[name]; +} +console.log(pick({ Map, Set }, "Set") === Set, pick({ Date }, "Date") === pick(direct, "Date")); diff --git a/tests/corpus/6914-dynamic-builtin-construct.ts b/tests/corpus/6914-dynamic-builtin-construct.ts new file mode 100644 index 000000000..c026a6691 --- /dev/null +++ b/tests/corpus/6914-dynamic-builtin-construct.ts @@ -0,0 +1,54 @@ +// `new` through values that hold builtin constructors. +const ctors: Record = { Date, Map, Set, Object, WeakMap, WeakSet }; +function construct(name: string, ...args: unknown[]): unknown { + const C = ctors[name] as any; + return new C(...args); +} +function make(C: any, ...args: unknown[]): unknown { + return new C(...args); +} +const tag = (value: unknown) => Object.prototype.toString.call(value); + +const d = construct("Date", 0) as Date; +console.log(tag(d), d.getTime(), d.toISOString()); +const d2 = make(Date, 2020, 1, 3, 4, 5, 6, 7) as Date; +console.log(d2.getFullYear(), d2.getMonth(), d2.getDate(), d2.getHours(), d2.getMilliseconds()); +const d3 = make(Date, "2001-02-03T04:05:06Z") as Date; +const d4 = make(Date, d3) as Date; +console.log(d3.getTime(), d4.getTime()); +console.log(typeof make(Date), Number.isNaN((make(Date, "nope") as Date).getTime())); + +const m = construct("Map", [["a", 1], ["b", 2]]) as Map; +console.log(tag(m), m.size, m.get("b"), [...m.keys()].join()); +const m2 = make(Map, m) as Map; +m2.set("c", 3); +console.log(m.size, m2.size, (make(Map) as Map).size, (make(Map, null) as Map).size); + +const s = construct("Set", [1, 2, 2, 3]) as Set; +console.log(tag(s), s.size, s.has(3), (make(Set, "abca") as Set).size); + +const o = construct("Object") as Record; +o.x = 1; +const same = { y: 2 }; +console.log(tag(o), JSON.stringify(o), make(Object, same) === same, tag(make(Object, null))); + +const key = {}; +const w = construct("WeakMap", [[key, "v"]]) as WeakMap; +console.log(tag(w), w.get(key), w.has({})); +const ws = make(WeakSet, [key]) as WeakSet; +console.log(tag(ws), ws.has(key)); + +try { + make(Map, [1]); +} catch (e) { + console.log((e as Error).name, (e as Error).message); +} +try { + make(WeakMap, [[1, 2]]); +} catch (e) { + console.log((e as Error).name, (e as Error).message); +} + +const DateSlot: new () => unknown = Date; +const MapSlot: new (entries: [string, number][]) => unknown = Map; +console.log(tag(new DateSlot()), (new MapSlot([["k", 1]]) as Map).get("k")); diff --git a/tests/corpus/6915-dynamic-builtin-construct.mjs b/tests/corpus/6915-dynamic-builtin-construct.mjs new file mode 100644 index 000000000..dd13aa325 --- /dev/null +++ b/tests/corpus/6915-dynamic-builtin-construct.mjs @@ -0,0 +1,16 @@ +// `new` through stored builtin constructors in JavaScript. +const table = [Date, Map, Set, Object, WeakMap, WeakSet]; +for (const C of table) { + const value = new C(); + console.log(C.name, typeof value, Object.prototype.toString.call(value), value.constructor === C); +} +const Ctor = table[0]; +console.log(new Ctor(86400000).toISOString(), new Ctor(2024, 0, 31).getDate()); +const MapCtor = table[1]; +const map = new MapCtor(Object.entries({ a: 1, b: 2 })); +map.set("c", 3); +console.log(map.size, map.get("a"), [...map.entries()].length); +const SetCtor = table[2]; +console.log(new SetCtor([...map.keys()]).size, new SetCtor([NaN, NaN, 0, -0]).size); +const named = { Date, Map, Set }; +console.log(named.Date === Date, named.Map === table[1], named.Set === table[2]); diff --git a/tests/corpus/6915-key-order-narrowed-throw.ts b/tests/corpus/6915-key-order-narrowed-throw.ts new file mode 100644 index 000000000..d4bc693f2 --- /dev/null +++ b/tests/corpus/6915-key-order-narrowed-throw.ts @@ -0,0 +1,72 @@ +// A record whose reads narrow a possibly-undefined binding (the narrowing +// ternary's throw arm stands in for a value of the record's type) still +// takes its literal's key order: a module-level accumulator typed by an +// interface declared in another order, as an event batcher builds it. +interface Entry { + id: string; + at: number; + text?: string; + stream: "out" | "err"; +} +interface Batch { + team: string; + project: string; + job: string; + origin: "task" | "worker"; + host: string; + entries: Entry[]; + sizes?: number[]; + stage?: "live" | "staging"; + branch?: string; + run?: string; + entry?: string; + path?: string; +} +interface Job { + id: string; + run?: string; + project: string; + team: string; + host: string; + stage: string | null; +} +let acc: Batch | undefined; + +function append(j: Job, text: string): void { + if (!acc) { + acc = { + run: j.run, + job: j.id, + stage: j.stage === null ? "staging" : "live", + project: j.project, + team: j.team, + origin: "task", + host: j.host, + entry: ".", + entries: [], + }; + } + acc.entries.push({ id: String(acc.entries.length), at: 1, text, stream: "out" }); + setTimeout(() => { + const batch = acc; + if (!batch) return; + acc = undefined; + for (const line of split(batch)) console.log(line); + }, 1); +} + +function split(batch: Batch): string[] { + const json = JSON.stringify(batch); + if (json.length < 200 || batch.entries.length < 2) return [json]; + const index = Math.floor(batch.entries.length / 2); + const first = { ...batch, entries: batch.entries.slice(0, index) }; + const second = { ...batch, entries: batch.entries.slice(index) }; + return [...split(first), ...split(second)]; +} + +const j: Job = { id: "job", run: "r1", project: "prj", team: "core", host: "h", stage: "live" }; +append(j, "one"); +append(j, "two"); +setTimeout(() => { + for (let i = 0; i < 6; i++) append(j, "line " + i); +}, 5); diff --git a/tests/corpus/6916-index-record-spread-overrides.ts b/tests/corpus/6916-index-record-spread-overrides.ts new file mode 100644 index 000000000..0a33b0e1b --- /dev/null +++ b/tests/corpus/6916-index-record-spread-overrides.ts @@ -0,0 +1,60 @@ +// Spreading a fixed-shape record into an index-signature record: the +// spread's keys enter in declaration order, and a field whose type does +// not fit the index slot is valid when a later property overrides it +// (its key keeps the spread's position, the override supplies the value). +interface FailureTags { + phase: string; + httpStatus: number; + retried: boolean; + region: string; +} +interface Counts { + zeta: number; + alpha: number; + mid: number; +} + +function emit(name: string, tags: { [key: string]: string }): void { + const parts: string[] = []; + for (const key of Object.keys(tags)) parts.push(key + ":" + tags[key]); + console.log(name, parts.join(","), JSON.stringify(tags)); +} + +const tags: FailureTags = { phase: "fetch", httpStatus: 503, retried: true, region: "iad1" }; +for (let attempt = 1; attempt <= 2; attempt++) { + emit("attempt_failed", { + ...tags, + attempt: String(attempt), + httpStatus: String(tags.httpStatus), + retried: tags.retried ? "yes" : "no", + }); +} + +const base: Record = { team: "core", owner: "infra" }; +emit("queue", { ...base, owner: "builds", shard: "7" }); +emit("size", { ...base }); + +const counts: Counts = { zeta: 3, alpha: 1, mid: 2 }; +const scores: Record = { ...counts, alpha: 10 }; +console.log(Object.keys(scores).join(","), JSON.stringify(scores)); +const labels: Record = { first: "a", ...{ zeta: "z", alpha: "a" }, last: "l" }; +console.log(Object.entries(labels).map(([k, v]) => k + "=" + v).join(" ")); +const flags: { [key: string]: boolean } = { ...counts, mid: true, zeta: false, alpha: true }; +console.log(JSON.stringify(flags)); + +// A source whose values are built in another order than its interface +// declares: the spread follows the order the values are built in. +interface Span { + start: number; + end: number; + label?: string; +} +function span(start: number, size: number, label?: string): Span { + return label === undefined ? { end: start + size, start } : { label, end: start + size, start }; +} +const spans: Record = { ...span(1, 4), step: 2 }; +console.log(Object.keys(spans).join(","), JSON.stringify(spans)); +const named: Record = { first: 0, ...span(5, 2, "w"), last: 9 }; +console.log(Object.keys(named).join(","), JSON.stringify(named)); +const both: Record = { ...counts, ...{ end: 3, start: 1 }, mid: 7 }; +console.log(Object.keys(both).join(","), JSON.stringify(both)); diff --git a/tests/corpus/6916-local-class-static-self-reference.mjs b/tests/corpus/6916-local-class-static-self-reference.mjs new file mode 100644 index 000000000..bc19cd0e9 --- /dev/null +++ b/tests/corpus/6916-local-class-static-self-reference.mjs @@ -0,0 +1,52 @@ +// Static fields, static blocks and static methods of function-local classes +// that read the class by its name while the class is being defined. +function registry(prefix) { + class Registry { + static label = Registry.name + ":" + prefix; + static instances = []; + static { + Registry.ready = Registry.instances.length === 0; + } + constructor(id) { + this.id = id; + Registry.instances.push(this); + } + static create(id) { + return new Registry(id); + } + } + return Registry; +} +const R = registry("main"); +R.create(1); +R.create(2); +console.log(R.label, R.ready, R.instances.map((r) => r.id)); +const R2 = registry("other"); +console.log(R2.label, R2.instances.length, R2 === R, R.instances.length); + +function counter(step) { + class Counter { + static zero = new Counter(0); + static one = Counter.zero.next(); + constructor(value) { + this.value = value; + } + next() { + return new Counter(this.value + step); + } + } + return Counter; +} +const C = counter(5); +console.log(C.zero.value, C.one.value, C.one.next().value, C.one instanceof C); + +function described() { + class Shape { + static kinds = ["circle", "square"]; + static describe() { + return Shape.kinds.map((kind) => kind + "@" + Shape.name).join(","); + } + } + return Shape.describe(); +} +console.log(described()); diff --git a/tests/corpus/6917-local-class-expression-self-reference.ts b/tests/corpus/6917-local-class-expression-self-reference.ts new file mode 100644 index 000000000..cff612d29 --- /dev/null +++ b/tests/corpus/6917-local-class-expression-self-reference.ts @@ -0,0 +1,53 @@ +// Function-local class expressions that refer to themselves by their own name. +function counter(start: number) { + const C = class Counter { + value: number; + constructor(value: number) { this.value = value; } + next(): Counter { return new Counter(this.value + 1); } + static first(): Counter { return new Counter(start); } + static isSelf(value: unknown): boolean { return value === Counter; } + }; + return C; +} +const Counter1 = counter(10); +console.log(Counter1.first().next().next().value); +console.log(Counter1.isSelf(Counter1), Counter1.isSelf(counter(1)), Counter1.name); + +function box(seed: T) { + return class Box { + value: T; + constructor(value: T) { this.value = value; } + again(): Box { return new Box(this.value); } + static of(): Box { return new Box(seed); } + }; +} +const StringBox = box("seed"); +console.log(new StringBox("x").again().value, StringBox.of().value); +const NumberBox = box(7); +console.log(NumberBox.of().again().value + 1); + +function nested(n: number) { + const Outer = class Tree { + children: Tree[] = []; + static build(depth: number): Tree { + const tree = new Tree(); + if (depth > 0) tree.children.push(Tree.build(depth - 1), Tree.build(depth - 1)); + return tree; + } + size(): number { return 1 + this.children.reduce((total, child) => total + child.size(), 0); } + }; + return Outer.build(n).size(); +} +console.log(nested(3)); + +// The only reference to the name is a shorthand property. +function registry(tag: string) { + return class Entry { + readonly tag = tag; + static table(): Record { + return { Entry }; + } + }; +} +const Entry1 = registry("e"); +console.log(Entry1.table().Entry === Entry1, new Entry1().tag); diff --git a/tests/corpus/6918-local-class-expression-self-reference.mjs b/tests/corpus/6918-local-class-expression-self-reference.mjs new file mode 100644 index 000000000..4b2440674 --- /dev/null +++ b/tests/corpus/6918-local-class-expression-self-reference.mjs @@ -0,0 +1,61 @@ +// Function-local class expressions in JavaScript whose static members and +// methods read the class by its own name. +function point(scale) { + const P = class Point { + static origin = new Point(0, 0); + static unit = Point.scaled(1); + constructor(x, y) { + this.x = x; + this.y = y; + } + static scaled(n) { + return new Point(n * scale, n * scale); + } + plus(other) { + return new Point(this.x + other.x, this.y + other.y); + } + }; + return P; +} +const P = point(3); +const sum = P.origin.plus(P.unit).plus(P.unit); +console.log(sum.x, sum.y, P.unit instanceof P, P.name); + +function selfName() { + const K = class Named { + static who() { + return Named === this; + } + }; + return [K.who(), K.name, typeof K]; +} +console.log(selfName()); + +function factory(tag) { + return class Tagged { + static count = 0; + constructor() { + Tagged.count++; + } + static make() { + return new Tagged(); + } + get tag() { + return tag + Tagged.count; + } + }; +} +const T = factory("t"); +T.make(); +console.log(T.make().tag, T.count, factory("u").count); + +// The only reference to the name is a shorthand property. +function packed() { + const K = class Packed { + static wrap() { + return { Packed }; + } + }; + return [K.wrap().Packed === K, K.wrap().Packed.name]; +} +console.log(packed()); diff --git a/tests/corpus/6919-local-class-inspect-name.mjs b/tests/corpus/6919-local-class-inspect-name.mjs new file mode 100644 index 000000000..022895591 --- /dev/null +++ b/tests/corpus/6919-local-class-inspect-name.mjs @@ -0,0 +1,51 @@ +// console.log prints instances of function-local classes with prototype +// methods under their class names. +function point() { + class Point { + constructor(x, y) { + this.x = x; + this.y = y; + } + plus(other) { + return new Point(this.x + other.x, this.y + other.y); + } + } + return Point; +} +const Point = point(); +const a = new Point(1, 2); +console.log(a, a.plus(a)); +console.log([new Point(0, 0)], { p: new Point(5, 6) }); + +function animals() { + class Animal { + constructor(name) { + this.name = name; + } + speak() { + return this.name + " makes a sound"; + } + } + class Dog extends Animal { + speak() { + return this.name + " barks"; + } + } + return [new Animal("cat"), new Dog("rex")]; +} +const [cat, dog] = animals(); +console.log(cat, dog); + +function anonymous() { + const Named = class { + value() { + return 1; + } + }; + return [new Named(), new (class { + value() { + return 2; + } + })()]; +} +console.log(anonymous()); diff --git a/tests/corpus/6921-local-subclass-override-dispatch.ts b/tests/corpus/6921-local-subclass-override-dispatch.ts new file mode 100644 index 000000000..0476e56c7 --- /dev/null +++ b/tests/corpus/6921-local-subclass-override-dispatch.ts @@ -0,0 +1,51 @@ +// Overrides declared by function-local subclasses dispatch on the receiver +// when the call site lowers before the function that declares them. +class Shape { + area(): number { return 0; } + get label(): string { return "shape"; } + describe(): string { return this.label + ":" + this.area(); } +} + +function square(side: number): Shape { + class Square extends Shape { + area(): number { return side * side; } + get label(): string { return "square"; } + } + return new Square(); +} + +function scaled(factor: number): Shape { + class Scaled extends Shape { + area(): number { return factor; } + } + class Doubled extends Scaled { + area(): number { return super.area() * 2; } + } + return new Doubled(); +} + +const shapes: Shape[] = [new Shape(), square(3), scaled(5)]; +for (const shape of shapes) console.log(shape.area(), shape.label, shape.describe()); + +function pair() { + class Base { + name(): string { return "base"; } + } + class Derived extends Base { + name(): string { return "derived"; } + } + return [new Base(), new Derived()]; +} +const [first, second] = pair(); +console.log(first.name(), second.name()); + +function counter() { + const Tally = class { + count(): number { return 1; } + }; + const Double = class extends Tally { + count(): number { return 2; } + }; + return new Double(); +} +console.log(counter().count()); diff --git a/tests/corpus/6922-local-subclass-override-dispatch.mjs b/tests/corpus/6922-local-subclass-override-dispatch.mjs new file mode 100644 index 000000000..8439c563d --- /dev/null +++ b/tests/corpus/6922-local-subclass-override-dispatch.mjs @@ -0,0 +1,51 @@ +// Overrides declared by function-local subclasses in JavaScript dispatch on +// the receiver when the call site lowers before the declaring function. +class Animal { + constructor(name) { + this.name = name; + } + speak() { + return this.name + " makes a sound"; + } +} + +function dog(name) { + class Dog extends Animal { + speak() { + return this.name + " barks"; + } + } + return new Dog(name); +} + +function animals() { + class Bird extends Animal { + speak() { + return this.name + " sings"; + } + } + return [new Animal("cat"), new Bird("robin"), dog("rex")]; +} + +for (const animal of animals()) console.log(animal.speak()); +const speak = (animal) => animal.speak(); +console.log(speak(dog("fido"))); + +function pets() { + class Pet { + constructor(name) { + this.name = name; + } + greet() { + return this.name + " waves"; + } + } + class Cat extends Pet { + greet() { + return this.name + " purrs"; + } + } + return [new Pet("ann"), new Cat("tom")]; +} +const [pet, cat] = pets(); +console.log(pet.greet(), cat.greet()); diff --git a/tests/corpus/6926-dynamic-collection-seeds.mjs b/tests/corpus/6926-dynamic-collection-seeds.mjs new file mode 100644 index 000000000..a48fab894 --- /dev/null +++ b/tests/corpus/6926-dynamic-collection-seeds.mjs @@ -0,0 +1,28 @@ +// Set, Map, WeakSet and Object.fromEntries over checked-dynamic iterables: +// native iterators, generators, objects with a Symbol.iterator method and +// collections, as seeds that reach the runtime untyped. +function* pairs() { yield ["g", 1]; yield ["h", 2]; } +function* values() { yield 1; yield 2; yield 2; } +const iterable = { *[Symbol.iterator]() { yield ["i", 3]; } }; +const valueIterable = { *[Symbol.iterator]() { yield "a"; yield "b"; } }; +function attempt(label, make) { + try { console.log(label, make()); } catch (e) { console.log(label, "threw", e.name, e.message); } +} +function viaSet(x) { return new Set(x).size; } +function viaMap(x) { return [...new Map(x).keys()].join(); } +function viaWeakSet(x) { return new WeakSet(x).has(key); } +const key = {}; +const m = new Map([["a", 1], ["b", 2]]); +attempt("set keys()", () => viaSet(m.keys())); +attempt("set values()", () => viaSet(new Set([1, 2]).values())); +attempt("set generator", () => viaSet(values())); +attempt("set iterable", () => viaSet(valueIterable)); +attempt("set string", () => viaSet("abca")); +attempt("set number", () => viaSet(5)); +attempt("map generator", () => viaMap(pairs())); +attempt("map iterable", () => viaMap(iterable)); +attempt("map set", () => viaMap(new Set([["s", 1]]))); +attempt("map entries()", () => viaMap(m.entries())); +attempt("map bad entry", () => viaMap([1])); +attempt("weakset generator", () => viaWeakSet((function* () { yield key; })())); +attempt("fromEntries generator", () => JSON.stringify(Object.fromEntries(pairs()))); diff --git a/tests/corpus/6927-dynamic-collection-seeds.ts b/tests/corpus/6927-dynamic-collection-seeds.ts new file mode 100644 index 000000000..c57433d57 --- /dev/null +++ b/tests/corpus/6927-dynamic-collection-seeds.ts @@ -0,0 +1,9 @@ +// Set and Map seeds held as any: native iterators and generators. +function* values(): Generator { yield 1; yield 2; yield 2; } +function* pairs(): Generator<[string, number]> { yield ["a", 1]; yield ["b", 2]; } +const m = new Map([["x", 1], ["y", 2]]); +const anyKeys: any = m.keys(); +const anyGen: any = values(); +const anyPairs: any = pairs(); +console.log(new Set(anyKeys).size, new Set(anyGen).size, new Map(anyPairs).size); +console.log(new Set(values()).size, new Map(pairs()).get("b"), new Set(m.values()).size); diff --git a/tests/corpus/6996-typed-array-index-temps.ts b/tests/corpus/6996-typed-array-index-temps.ts new file mode 100644 index 000000000..a19561ef0 --- /dev/null +++ b/tests/corpus/6996-typed-array-index-temps.ts @@ -0,0 +1,134 @@ +// Constant index temps derived from a loop counter (`const j = i * 4`) in +// typed-array loops: as indices and as numbers, in loops whose bounds guard +// passes or fails, nested, captured by closures, read after an await or a +// yield, and in loops whose counter reaches large values. + +function gray(px: Uint8Array, out: Uint8Array): void { + for (let i = 0; i < out.length; i++) { + const j = i * 4; + out[i] = (px[j]! * 77 + px[j + 1]! * 150 + px[j + 2]! * 29) >> 8; + } +} + +function interleave(a: Float32Array, b: Float32Array, out: Float32Array): void { + for (let i = 0; i < a.length; i++) { + const at = 2 * i; + out[at] = a[i]!; + out[at + 1] = b[i]!; + } +} + +function strided(src: Int16Array, out: Int32Array): string { + const seen: number[] = []; + for (let i = 0; i < out.length; i++) { + const at = i * 3 + 2; + out[i] = src[at]! - src[at - 2]!; + if (i % 5 === 0) seen.push(at, at / 2, -at, at % 4); + } + return seen.join(","); +} + +function previous(src: Float64Array, out: Float64Array): string { + const edges: string[] = []; + for (let i = 0; i < out.length; i++) { + const before = i - 1; + out[i] = src[before]! + 1; + if (before < 1) edges.push(`${before}:${Object.is(before * 0, -0)}:${1 / (before * 0)}`); + } + return edges.join(" "); +} + +function rows(cells: Uint32Array, width: number, sums: Float64Array): void { + for (let r = 0; r < sums.length; r++) { + const base = r * width; + let total = 0; + for (let c = 0; c < width; c++) { + const at = base + c; + total += cells[at]!; + } + sums[r] = total; + } +} + +function captured(values: Uint8Array): number { + const readers: (() => number)[] = []; + for (let i = 0; i < values.length; i++) { + const at = i * 2; + readers.push(() => at + values[i]!); + } + let sum = 0; + for (const read of readers) sum += read(); + return sum; +} + +function wide(start: number, count: number): string { + const out: number[] = []; + for (let i = start; i < start + count; i++) { + const next = i + 1; + const twice = i * 2; + out.push(next, twice, next - i); + } + return out.join(","); +} + +async function afterAwait(values: Float64Array): Promise { + const out: number[] = []; + for (let i = 0; i < values.length; i++) { + const at = i * 2; + await null; + out.push(at, values[at] ?? -1); + } + return out.join(","); +} + +function* acrossYield(values: Int8Array): Generator { + for (let i = 0; i < values.length; i++) { + const at = i + 1; + yield values[i]!; + yield at * 10 + (values[at] ?? 0); + } +} + +const px = new Uint8Array(64); +for (let i = 0; i < px.length; i++) px[i] = (i * 41 + 7) & 255; +const g = new Uint8Array(16); +gray(px, g); +console.log("gray", g.join(",")); +const tall = new Uint8Array(20); +gray(px, tall); +console.log("gray past input", tall.join(",")); + +const fa = new Float32Array([1.5, -2.25, 3.125, 0.1]); +const fb = new Float32Array([10, 20, 30, 40]); +const pairs = new Float32Array(8); +interleave(fa, fb, pairs); +console.log("interleave", pairs.join(",")); +const short = new Float32Array(5); +interleave(fa, fb, short); +console.log("interleave short", short.join(",")); + +const src16 = new Int16Array(40); +for (let i = 0; i < src16.length; i++) src16[i] = (i * 9973) % 32768 - 16384; +const diff = new Int32Array(12); +console.log("strided", strided(src16, diff), diff.join(",")); +const far = new Int32Array(20); +console.log("strided past input", strided(src16, far), far.join(",")); + +const src64 = new Float64Array([0.5, 1.5, 2.5]); +const shifted = new Float64Array(4); +console.log("previous", previous(src64, shifted), shifted.join(",")); + +const cells = new Uint32Array(30); +for (let i = 0; i < cells.length; i++) cells[i] = (i * 2654435761) >>> 0; +const sums = new Float64Array(5); +rows(cells, 6, sums); +console.log("rows", sums.join(",")); +const partial = new Float64Array(6); +rows(cells, 6, partial); +console.log("rows past input", partial.join(",")); + +console.log("captured", captured(new Uint8Array([5, 6, 7]))); +console.log("wide", wide(2 ** 53 - 4, 3)); +console.log("wide negative", wide(-3, 4)); +console.log("across yield", [...acrossYield(new Int8Array([3, -4, 5]))].join(",")); +afterAwait(new Float64Array([0.25, 1.25, 2.25, 3.25, 4.25])).then((line) => console.log("after await", line)); diff --git a/tests/corpus/6997-typed-array-invariant-index-terms.ts b/tests/corpus/6997-typed-array-invariant-index-terms.ts new file mode 100644 index 000000000..53d9f10c0 --- /dev/null +++ b/tests/corpus/6997-typed-array-invariant-index-terms.ts @@ -0,0 +1,78 @@ +// Typed-array loops whose index adds a loop-invariant number with no known +// integer range, such as the row base of a matrix-vector product. Rows +// with integer, fractional, negative, -0 and NaN bases, windows at 2^32 and +// beyond, and matrices too short for their last rows, read and write as +// Node does. + +function matvec(w: Float32Array, v: Float32Array, out: Float32Array, cols: number): void { + for (let r = 0; r < out.length; r++) { + const base = r * cols; + let s0 = 0, s1 = 0, s2 = 0, s3 = 0; + for (let j = 0; j < cols; j += 4) { + s0 += w[base + j]! * v[j]!; + s1 += w[base + j + 1]! * v[j + 1]!; + s2 += w[base + j + 2]! * v[j + 2]!; + s3 += w[base + j + 3]! * v[j + 3]!; + } + out[r] = s0 + s1 + s2 + s3; + } +} + +function rowSums(m: Float64Array, rows: number, cols: number, first: number): number[] { + const sums: number[] = []; + for (let r = first; r < first + rows; r++) { + let s = 0; + for (let c = 0; c < cols; c++) s += m[r * cols + c]!; + sums.push(s); + } + return sums; +} + +function shiftedCopy(src: Int16Array, out: Int16Array, offset: number): void { + for (let i = 0; i < out.length; i++) out[i] = src[i - offset]! + 1; +} + +function window(src: Uint8Array, start: number, k: number): number { + let s = 0; + for (let i = 0; i < k; i++) s += src[start + i]! * (i + 1); + return s; +} + +const rows = 6, cols = 8; +const w = new Float32Array(rows * cols); +for (let i = 0; i < w.length; i++) w[i] = ((i * 37) % 23) / 4 - 2; +const v = new Float32Array(cols); +for (let i = 0; i < cols; i++) v[i] = (i % 5) - 1.5; +const out = new Float32Array(rows); +matvec(w, v, out, cols); +console.log("matvec", out.join(",")); +const tall = new Float32Array(rows + 2); +matvec(w, v, tall, cols); +console.log("matvec past rows", tall.join(",")); +const odd = new Float32Array(3); +matvec(w, v, odd, 6.5); +console.log("matvec fractional cols", odd.join(",")); +matvec(w, v, odd, NaN); +console.log("matvec NaN cols", odd.join(",")); + +const m = new Float64Array(30); +for (let i = 0; i < m.length; i++) m[i] = i * 1.5 - 7; +console.log("rows", rowSums(m, 5, 6, 0).join(",")); +console.log("rows from -1", rowSums(m, 3, 6, -1).join(",")); +console.log("rows fractional", rowSums(m, 2, 2.5, 1).join(",")); +console.log("rows past end", rowSums(m, 3, 6, 4).join(",")); +console.log("rows -0 base", rowSums(m, 1, 6, -0).join(",")); + +const src16 = new Int16Array([10, 20, 30, 40, 50, 60]); +const shifted = new Int16Array(6); +shiftedCopy(src16, shifted, 2); +console.log("shifted", shifted.join(",")); +shiftedCopy(src16, shifted, -3); +console.log("shifted back", shifted.join(",")); +shiftedCopy(src16, shifted, 0.5); +console.log("shifted half", shifted.join(",")); + +const bytes = new Uint8Array(40); +for (let i = 0; i < bytes.length; i++) bytes[i] = (i * 29) & 255; +console.log("window", window(bytes, 3, 8), window(bytes, 36, 8), window(bytes, -2, 4)); +console.log("window far", window(bytes, 2 ** 32, 3), window(bytes, 2 ** 32 + 1, 3), window(bytes, 2 ** 40, 2), window(bytes, -(2 ** 32), 2)); diff --git a/tests/corpus/6998-typed-array-while-loop-versions.ts b/tests/corpus/6998-typed-array-while-loop-versions.ts new file mode 100644 index 000000000..383a2437f --- /dev/null +++ b/tests/corpus/6998-typed-array-while-loop-versions.ts @@ -0,0 +1,149 @@ +// While loops that scan typed arrays with a counter below a bound: scanners +// with nested loops and `&&` conditions, `| 0` increments, look-behind and +// look-ahead reads, writes, DataView reads, string-length bounds, and +// bounds or starts past the array, fractional, negative, -0 or NaN. + +function words(bytes: Uint8Array, end: number): number { + let pos = 0; + let count = 0; + while (pos < end) { + while (pos < end && (bytes[pos] === 32 || bytes[pos] === 10)) pos++; + if (pos < end) count++; + while (pos < end && bytes[pos] !== 32 && bytes[pos] !== 10) pos++; + } + return count; +} + +function identifiers(chars: Uint16Array, start: number, end: number): string { + let pos = start; + let count = 0; + let mix = 0; + while (pos < end) { + let hash = 0x811c9dc5 | 0; + while (pos < end) { + const c = chars[pos]!; + if (!((c >= 97 && c <= 122) || c === 95)) break; + hash = Math.imul(hash ^ c, 0x01000193); + pos = (pos + 1) | 0; + } + mix = (mix + hash) | 0; + count++; + pos = (pos + 1) | 0; + } + return `${count} ${mix >>> 0} ${pos}`; +} + +function around(values: Int16Array, start: number, end: number): number[] { + const out: number[] = []; + let i = start; + while (i <= end) { + out.push(values[i - 1]! + values[i + 2]! * 2); + i += 1; + } + return out; +} + +function fill(out: Float32Array, end: number, value: number): number { + let i = 0; + while (i < end) { + out[i] = value + i; + if (i < end - 1 && out[i] > 2) { + i += 2; + continue; + } + i++; + } + return i; +} + +function afterInner(bytes: Uint8Array): number { + let pos = 0; + let sum = 0; + while (pos < bytes.length) { + while (pos < bytes.length && bytes[pos] !== 0) pos++; + // The inner loop may stop at the length: this read stays checked. + sum += bytes[pos] ?? -1; + pos++; + } + return sum; +} + +function firstAbove(samples: Float64Array, limit: number): number { + let i = 0; + while (i < samples.length) { + if (samples[i]! > limit) return i; + i = i + 1; + } + return -1; +} + +function halves(view: DataView, end: number): number { + let at = 0; + let total = 0; + while (at < end) { + total += view.getUint16(at, true); + at += 2; + } + return total; +} + +function letters(text: string, codes: Uint8Array): number { + let i = 0; + let sum = 0; + while (i < text.length) { + sum += codes[i]! * (text.charCodeAt(i) & 7); + i++; + } + return sum; +} + +function notCounters(bytes: Uint8Array): string { + let i = 1; + let doubled = 0; + while (i < bytes.length) { + doubled += bytes[i]!; + i = i * 2; + } + let j = bytes.length - 1; + let down = 0; + while (j < bytes.length && j >= 0) { + down += bytes[j]!; + j--; + } + return `${doubled} ${down}`; +} + +const text = "let alpha = beta_gamma\nreturn delta "; +const bytes = new Uint8Array(text.length); +const chars = new Uint16Array(text.length); +for (let i = 0; i < text.length; i++) { + bytes[i] = text.charCodeAt(i); + chars[i] = text.charCodeAt(i); +} +console.log("words", words(bytes, bytes.length), words(bytes, 10), words(bytes, bytes.length + 5), words(bytes, 7.5), words(bytes, NaN)); +console.log("identifiers", identifiers(chars, 0, chars.length)); +console.log("identifiers past end", identifiers(chars, 4, chars.length + 3)); +console.log("identifiers starts", identifiers(chars, -2, 9), identifiers(chars, 2.5, 12), identifiers(chars, -0, 6)); + +const values = new Int16Array([5, -6, 7, -8, 9, -10, 11]); +console.log("around", around(values, 1, 4).join(","), around(values, 0, 6).join(","), around(values, -1, 1).join(",")); + +const floats = new Float32Array(6); +console.log("fill", fill(floats, 6, 0.5), floats.join(",")); +const short = new Float32Array(3); +console.log("fill past end", fill(short, 5, 1), short.join(",")); + +console.log("after inner", afterInner(new Uint8Array([1, 2, 0, 3, 0, 4, 5]))); +console.log("first above", firstAbove(new Float64Array([0.5, 1.5, 2.5]), 1), firstAbove(new Float64Array([0.5]), 1)); + +const buffer = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); +const view = new DataView(buffer.buffer); +console.log("halves", halves(view, 8)); +try { + console.log("halves past end", halves(view, 10)); +} catch (error) { + console.log((error as Error).name, (error as Error).message); +} + +console.log("letters", letters("abcdef", new Uint8Array([1, 2, 3, 4, 5, 6])), letters("abcdefgh", new Uint8Array([1, 2, 3]))); +console.log("not counters", notCounters(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))); diff --git a/tests/corpus/6999-typed-array-callback-loops.ts b/tests/corpus/6999-typed-array-callback-loops.ts new file mode 100644 index 000000000..84adfd995 --- /dev/null +++ b/tests/corpus/6999-typed-array-callback-loops.ts @@ -0,0 +1,93 @@ +// Typed-array callback methods with literal callbacks, function values shared +// by several calls, and callbacks chosen at run time: visit order and +// arguments, writes during the visit, early exits, reduce seeds and the +// empty-array TypeError, map conversions, Buffer results, throwing +// callbacks, empty arrays and subarray receivers. + +const ints = new Int32Array([5, -3, 8, 0, 12, -7, 4]); +const floats = new Float32Array([0.1, 2.5, -1.25, 3.75, 9.5]); + +const visits: string[] = []; +ints.forEach((v, i, a) => { + visits.push(`${i}:${v}:${a === ints}`); +}); +console.log("forEach", visits.join(" ")); + +const writes = new Uint8Array([1, 2, 3, 4, 5, 6]); +writes.forEach((v, i, a) => { + if (i + 1 < a.length) a[i + 1] = a[i + 1]! + v; +}); +console.log("forEach writes ahead", writes.join(",")); + +let calls = 0; +const counted = (v: number): boolean => { + calls++; + return v > 7; +}; +console.log("some", ints.some(counted), calls); +calls = 0; +console.log("every", ints.every((v) => (calls++, v < 10)), calls); +calls = 0; +console.log("find", ints.find(counted), calls, ints.find((v) => v > 100)); +calls = 0; +console.log("findIndex", ints.findIndex(counted), calls, ints.findIndex((v) => v > 100)); + +const order: number[] = []; +console.log( + "findLast", + ints.findLast((v, i) => (order.push(i), v < 0)), + ints.findLastIndex((v) => v > 100), + order.join(","), +); + +console.log("reduce", ints.reduce((acc, v) => acc + v), ints.reduce((acc, v, i) => acc + v * i, 100)); +const right: number[] = []; +console.log( + "reduceRight", + floats.reduceRight((acc, v, i) => (right.push(i), acc - v)), + right.join(","), + floats.reduceRight((acc, v) => acc + v, -1), +); +console.log("single", new Int8Array([42]).reduce(() => -1), new Int8Array([42]).reduceRight(() => -1)); +function tryReduce(label: string, run: () => number): void { + try { + console.log(label, run()); + } catch (error) { + console.log(label, (error as Error).name, (error as Error).message); + } +} +const emptyU16 = new Uint16Array(0); +const emptyF64 = new Float64Array(0); +tryReduce("empty u16 reduce", () => emptyU16.reduce((a, b) => a + b)); +tryReduce("empty f64 reduceRight", () => emptyF64.reduceRight((a, b) => a + b)); +tryReduce("empty with init", () => emptyU16.reduce((a, b) => a + b, 7) + emptyF64.reduceRight((a, b) => a + b, 1)); +console.log("empty", emptyU16.some(() => true), emptyF64.every(() => false), emptyU16.map((v) => v).length); + +console.log("map u8", new Uint8Array([250, 3, 128]).map((v) => v * 3).join(",")); +console.log("map clamped", new Uint8ClampedArray([250, 3, 128]).map((v) => v * 1.5 - 10).join(",")); +console.log("map i16", new Int16Array([30000, -30000, 7]).map((v, i) => v + i * 10000).join(",")); +console.log("map f32", floats.map((v) => v / 3).join(",")); +console.log("filter", ints.filter((v, i) => v > 0 && i % 2 === 0).join(","), floats.filter((v) => v > 1).join(",")); + +const buf = Buffer.from("scriptc"); +const upper = buf.map((c) => c - 32); +console.log("buffer map", Buffer.isBuffer(upper), upper.join(","), Buffer.isBuffer(buf.filter((c) => c > 112))); + +// One function value at several calls, and callbacks chosen at run time. +const double = (v: number): number => v * 2; +console.log("shared", new Int32Array([1, 2, 3]).map(double).join(","), new Int32Array([4, 5]).map(double).join(",")); +const pick = (k: number): ((v: number) => boolean) => (k > 0 ? (v) => v > k : (v) => v < k); +console.log("chosen", ints.filter(pick(4)).join(","), ints.filter(pick(-4)).join(",")); + +try { + let seen = 0; + floats.forEach((v) => { + seen++; + if (v < 0) throw new RangeError(`negative ${v} after ${seen}`); + }); +} catch (error) { + console.log("throw", (error as Error).name, (error as Error).message); +} + +const view = ints.subarray(2, 5); +console.log("subarray", view.map((v) => v + 1).join(","), view.reduce((a, v) => a * 10 + v, 0), view.findLastIndex((v) => v === 8)); diff --git a/tests/corpus/7002-empty-array-contextual-slots/main.ts b/tests/corpus/7002-empty-array-contextual-slots/main.ts new file mode 100644 index 000000000..ec08a297a --- /dev/null +++ b/tests/corpus/7002-empty-array-contextual-slots/main.ts @@ -0,0 +1,58 @@ +// Empty array literals whose own type is `never[]`: `return []` in an async +// function (its contextual type is `string[] | PromiseLike`) and +// an object literal's `files: []` field returned or passed where typed +// arrays are declared. Each value holds the declared element type. +interface Listing { + files: string[]; + sizes: number[]; +} + +async function readNames(text: string): Promise { + try { + return JSON.parse(text) as string[]; + } catch { + return []; + } +} + +const loadIds = async (fail: boolean): Promise => { + if (fail) return []; + return [1, 2]; +}; + +function emptyListing(): Listing { + const listing = { files: [], sizes: [] }; + return listing; +} + +function index(): Record<"files" | "dirs", string[]> { + const out = { files: [], dirs: [] }; + return out; +} + +function total(listing: Listing): number { + return listing.sizes.reduce((sum, size) => sum + size, 0); +} + +async function main(): Promise { + const names = await readNames("not json"); + names.push("fallback"); + console.log(names, (await readNames('["a","b"]')).join("+")); + const ids = await loadIds(true); + ids.push(7); + console.log(ids, await loadIds(false)); + + const listing = emptyListing(); + listing.files.push("a.txt"); + listing.sizes.push(3, 4); + console.log(listing, total(listing)); + + const dirs = index(); + dirs.dirs.push("src"); + console.log(JSON.stringify(dirs), dirs.files.length); + + const blank = { files: [], sizes: [] }; + console.log(total(blank), JSON.stringify(blank)); +} + +main(); diff --git a/tests/corpus/7005-dyn-constructor-instanceof/main.ts b/tests/corpus/7005-dyn-constructor-instanceof/main.ts new file mode 100644 index 000000000..21fcbbd26 --- /dev/null +++ b/tests/corpus/7005-dyn-constructor-instanceof/main.ts @@ -0,0 +1,12 @@ +// A package's own functions, read off an object the checker cannot type, +// on the right of `instanceof`: Node walks the value's prototype chain for +// an ES5 constructor's prototype, at module load and in calls, and throws a +// TypeError for an arrow function, which has no prototype, when the value +// is an object. +import { arrowCheck, arrowObjects, describe, rejects, tags } from "tag-types"; + +console.log(tags()); +console.log(describe("{}"), describe("[1]"), describe("null"), describe('"s"')); +console.log(rejects('{"tag":"!x"}')); +console.log(arrowCheck("{}"), arrowCheck("1")); +console.log(arrowObjects()); diff --git a/tests/corpus/7005-dyn-constructor-instanceof/node_modules/tag-types/index.d.ts b/tests/corpus/7005-dyn-constructor-instanceof/node_modules/tag-types/index.d.ts new file mode 100644 index 000000000..5b451adfa --- /dev/null +++ b/tests/corpus/7005-dyn-constructor-instanceof/node_modules/tag-types/index.d.ts @@ -0,0 +1,5 @@ +export declare function describe(json: string): string; +export declare function tags(): string; +export declare function rejects(json: string): string; +export declare function arrowCheck(json: string): string; +export declare function arrowObjects(): string; diff --git a/tests/corpus/7005-dyn-constructor-instanceof/node_modules/tag-types/index.js b/tests/corpus/7005-dyn-constructor-instanceof/node_modules/tag-types/index.js new file mode 100644 index 000000000..81165bd58 --- /dev/null +++ b/tests/corpus/7005-dyn-constructor-instanceof/node_modules/tag-types/index.js @@ -0,0 +1,71 @@ +"use strict"; +// A bundler's lazy module object holding an ES5 constructor: the checker +// cannot type the object, so the constructor is an untyped value where +// `instanceof` tests it. +var types = {}; +var hasTypes; +function requireTypes() { + if (hasTypes) return types; + hasTypes = 1; + function Type(tag, options) { + this.tag = tag; + this.kind = (options && options.kind) || "scalar"; + } + function Schema(list) { + this.list = list; + } + types.Type = Type; + types.Schema = Schema; + types.make = (tag) => new Type(tag); + return types; +} +var loaded = requireTypes(); +var Type = loaded.Type; +var Schema = loaded.Schema; +var make = loaded.make; + +function compileList(list) { + var tags = []; + list.forEach(function (item) { + if (!(item instanceof Type)) throw new Error("not a Type: " + JSON.stringify(item)); + tags.push(item.tag + ":" + item.kind); + }); + return tags; +} +// Runs when the module loads, as js-yaml's default schema does. +var defaults = new Schema(compileList([new Type("!str"), new Type("!seq", { kind: "sequence" })])); + +module.exports.describe = function (json) { + var value = JSON.parse(json); + return [value instanceof Type, value instanceof Schema, defaults instanceof Schema, defaults instanceof Type].join(","); +}; +module.exports.tags = function () { + return defaults.list.join(" "); +}; +function rejects(json) { + try { + compileList([JSON.parse(json)]); + return "accepted"; + } catch (error) { + return error.message; + } +} +module.exports.rejects = rejects; +// An arrow function has no prototype: Node throws a TypeError for an object. +module.exports.arrowCheck = function (json) { + try { + return String(JSON.parse(json) instanceof make); + } catch (error) { + return error.name + ": " + error.message; + } +}; +// Every object reaches the TypeError, typed arrays, promises and Maps too. +module.exports.arrowObjects = function () { + return [new Uint8Array(2), Promise.resolve(1), new Map(), [1]].map(function (value) { + try { + return String(value instanceof make); + } catch (error) { + return error.name; + } + }).join(","); +}; diff --git a/tests/corpus/7005-dyn-constructor-instanceof/node_modules/tag-types/package.json b/tests/corpus/7005-dyn-constructor-instanceof/node_modules/tag-types/package.json new file mode 100644 index 000000000..a469a45f3 --- /dev/null +++ b/tests/corpus/7005-dyn-constructor-instanceof/node_modules/tag-types/package.json @@ -0,0 +1 @@ +{ "name": "tag-types", "version": "1.0.0", "main": "./index.js", "types": "./index.d.ts" } diff --git a/tests/corpus/7006-evolving-array-aliases.ts b/tests/corpus/7006-evolving-array-aliases.ts new file mode 100644 index 000000000..215b3f3c5 --- /dev/null +++ b/tests/corpus/7006-evolving-array-aliases.ts @@ -0,0 +1,79 @@ +// An unannotated `const xs = []` inside a function whose writes store values +// of more than one element type: an alias taken between the writes +// (`const alias = xs`) and an alias of that alias name the same array, so +// they see every later write, as in Node. A write of another element type +// after reads that agree on one type also keeps the array untyped. +function chain(): string { + const xs = []; + xs.push(1); + const a = xs; + const b = a; + xs.push("two"); + b.push(3); + return `${xs.join(",")} ${a.length} ${b.length} ${a === xs} ${b === xs}`; +} +function viaAlias(): string { + const xs = []; + xs.push("a"); + const alias = xs; + alias.push("b"); + xs.push(2); + return `${xs.join(",")} ${alias.join(",")}`; +} +function letAlias(): string { + const xs = []; + xs.push(true); + let alias = xs; + xs.push("t"); + const seen = alias.length; + alias = []; + return `${seen} ${alias.length} ${xs.length}`; +} +function nested(flag: boolean): string { + const xs = []; + xs.push(1); + if (flag) { + const inner = xs; + xs.push("n"); + return `${inner.length} ${inner.join(":")}`; + } + return `${xs.length}`; +} +function elementWrite(): string { + const xs = []; + xs.push(1); + const alias = xs; + xs[1] = "one"; + return `${alias.length} ${alias.join("+")}`; +} +function agreeing(): string { + const xs = []; + xs.push(1); + const alias = xs; + xs.push(2); + return `${alias.length} ${alias === xs} ${alias.reduce((sum, v) => sum + v, 0)}`; +} +function total(values: number[]): number { + return values.length; +} +function passed(): string { + const xs = []; + xs.push(1); + const alias = xs; + const n = total(alias); + xs.push("z"); + return `${n} ${alias.length}`; +} +console.log(chain()); +console.log(viaAlias(), "|", letAlias()); +console.log(nested(true), "|", nested(false), "|", elementWrite()); +console.log(agreeing(), "|", passed()); + +function spreadSame(): number { + const xs = []; + xs.push(1); + const more = [2, 3]; + xs.push(...more); + return xs.reduce((sum, v) => sum + v, 0); +} +console.log(spreadSame()); diff --git a/tests/corpus/7007-filter-written-type-predicates.ts b/tests/corpus/7007-filter-written-type-predicates.ts new file mode 100644 index 000000000..b75b5727d --- /dev/null +++ b/tests/corpus/7007-filter-written-type-predicates.ts @@ -0,0 +1,108 @@ +// `.filter` with a written type predicate: an annotated callback +// (`(p): p is Cat => ...`) or a guard function passed as a value. The +// result holds the predicate's type: a union arm, a union of arms, a +// number out of `unknown`, a record or tuple with a narrower field, or a +// subclass. An inferred predicate that keeps several arms narrows too. +interface Cat { + kind: "cat"; + meow: string; +} +interface Dog { + kind: "dog"; + bark: number; +} +interface Fish { + kind: "fish"; + fins: number; +} +type Pet = Cat | Dog | Fish; +const pets: Pet[] = [ + { kind: "cat", meow: "m" }, + { kind: "dog", bark: 2 }, + { kind: "fish", fins: 3 }, + { kind: "dog", bark: 5 }, +]; + +const cats = pets.filter((p): p is Cat => p.kind === "cat"); +console.log(cats.length, cats[0]!.meow); +const furry = pets.filter((p): p is Cat | Dog => p.kind !== "fish"); +console.log(furry.map((p) => (p.kind === "cat" ? p.meow : p.bark)).join(",")); +const notFish = pets.filter((p) => p.kind !== "fish"); +console.log(notFish.length); + +function isDog(p: Pet): p is Dog { + return p.kind === "dog"; +} +console.log(pets.filter(isDog).map((d) => d.bark * 10).join(",")); + +const isNumber = (v: unknown): v is number => typeof v === "number"; +const values: unknown[] = JSON.parse('[1, "a", 2, null, 4]'); +console.log(values.filter(isNumber).reduce((sum, n) => sum + n, 0)); + +const rows: unknown[] = JSON.parse('[{"id":1},{"id":"x"},{"id":3}]'); +const withIds = rows.filter( + (r): r is { id: number } => typeof (r as { id: unknown }).id === "number", +); +console.log(withIds.map((r) => r.id + 1).join(",")); + +const entries: [string, unknown][] = [ + ["a", 1], + ["b", "x"], + ["c", 3], +]; +const numeric = entries.filter((e): e is [string, number] => typeof e[1] === "number"); +console.log(numeric.map(([key, value]) => `${key}${value * 2}`).join(" ")); + +class Shape { + name: string; + constructor(name: string) { + this.name = name; + } +} +class Circle extends Shape { + r: number; + constructor(r: number) { + super("circle"); + this.r = r; + } +} +const shapes: Shape[] = [new Shape("square"), new Circle(2), new Circle(3)]; +const circles = shapes.filter((s): s is Circle => s instanceof Circle); +console.log(circles.length, circles.map((c) => c.r).join("+")); + +const mixed: (string | number | boolean)[] = ["a", 1, true, "b"]; +console.log(mixed.filter((v): v is string => typeof v === "string").join("")); +console.log(mixed.filter((v): v is string | number => typeof v !== "boolean").length); + +const pair: [string | number, string | number] = ["x", 4]; +console.log(pair.filter((v): v is number => typeof v === "number").map((n) => n + 1).join()); + +const optional: (string | number | undefined)[] = ["a", 1, undefined, 2]; +const defined = optional.filter((v) => v !== undefined); +console.log(defined.length, defined.map((v) => typeof v).join(",")); +function isText(v: string | undefined): v is string { + return typeof v === "string"; +} +const maybe: (string | undefined)[] = ["a", undefined, "b"]; +console.log(maybe.filter(isText).join("-")); + +// Narrowing a record field keeps each object's own keys, in its own order, +// and an optional field the object lacks stays absent. +interface Row { + id: unknown; + note?: string; + label: string; +} +interface NumericRow { + id: number; + note?: string; + label: string; +} +const tableRows: Row[] = [ + { label: "a", id: 1 }, + { label: "b", id: "s" }, + { label: "c", id: 3, note: "n" }, +]; +for (const row of tableRows.filter((r): r is NumericRow => typeof r.id === "number")) { + console.log(Object.keys(row).join(","), JSON.stringify(row), "note" in row, row.id + 1); +} diff --git a/tests/corpus/7008-js-unit-initialized-properties/main.ts b/tests/corpus/7008-js-unit-initialized-properties/main.ts new file mode 100644 index 000000000..3ac113d6a --- /dev/null +++ b/tests/corpus/7008-js-unit-initialized-properties/main.ts @@ -0,0 +1,8 @@ +// A JavaScript package whose object literals start a property as +// `undefined` or `null` and later store records, numbers and arrays in it, +// as the diff package's path list does (`{ oldPos: -1, lastComponent: +// undefined }`). Node runs the later writes; each property holds them. +import { describe, session } from "edit-paths"; + +console.log(describe()); +console.log(session()); diff --git a/tests/corpus/7008-js-unit-initialized-properties/node_modules/edit-paths/index.d.ts b/tests/corpus/7008-js-unit-initialized-properties/node_modules/edit-paths/index.d.ts new file mode 100644 index 000000000..68e2b409b --- /dev/null +++ b/tests/corpus/7008-js-unit-initialized-properties/node_modules/edit-paths/index.d.ts @@ -0,0 +1,2 @@ +export declare function describe(): string; +export declare function session(): string; diff --git a/tests/corpus/7008-js-unit-initialized-properties/node_modules/edit-paths/index.js b/tests/corpus/7008-js-unit-initialized-properties/node_modules/edit-paths/index.js new file mode 100644 index 000000000..ec3e7c4d0 --- /dev/null +++ b/tests/corpus/7008-js-unit-initialized-properties/node_modules/edit-paths/index.js @@ -0,0 +1,43 @@ +"use strict"; +// A Myers-style path list, as the diff package keeps it: each path starts +// with `lastComponent: undefined` and later holds a linked list of records, +// and a state object starts with `null` fields that later hold other values. +function addToPath(path, added, removed, oldPosInc) { + var last = path.lastComponent; + if (last && last.added === added && last.removed === removed) { + return { oldPos: path.oldPos + oldPosInc, lastComponent: { count: last.count + 1, added: added, removed: removed, previousComponent: last.previousComponent } }; + } + return { oldPos: path.oldPos + oldPosInc, lastComponent: { count: 1, added: added, removed: removed, previousComponent: last } }; +} +function extractCommon(basePath, common) { + if (common) basePath.lastComponent = { count: common, previousComponent: basePath.lastComponent, added: false, removed: false }; + basePath.oldPos += common; +} +function components(lastComponent) { + var list = []; + while (lastComponent) { + list.push(lastComponent); + var next = lastComponent.previousComponent; + delete lastComponent.previousComponent; + lastComponent = next; + } + return list.reverse(); +} +function describe() { + var bestPath = [{ oldPos: -1, lastComponent: undefined }]; + extractCommon(bestPath[0], 1); + var path = addToPath(bestPath[0], false, true, 1); + path = addToPath(path, true, false, 0); + path = addToPath(path, true, false, 0); + return components(path.lastComponent).map(function (c) { + return (c.added ? "+" : c.removed ? "-" : "=") + c.count + ("previousComponent" in c ? "!" : ""); + }).join(" "); +} +function session() { + var state = { user: null, retries: null, tags: undefined }; + state.user = { name: "ada" }; + state.retries = 3; + state.tags = ["a", "b"]; + return state.user.name + " " + state.retries + " " + state.tags.join("+") + " " + JSON.stringify(state); +} +module.exports = { describe: describe, session: session }; diff --git a/tests/corpus/7008-js-unit-initialized-properties/node_modules/edit-paths/package.json b/tests/corpus/7008-js-unit-initialized-properties/node_modules/edit-paths/package.json new file mode 100644 index 000000000..98648c289 --- /dev/null +++ b/tests/corpus/7008-js-unit-initialized-properties/node_modules/edit-paths/package.json @@ -0,0 +1 @@ +{ "name": "edit-paths", "version": "1.0.0", "main": "./index.js", "types": "./index.d.ts" } diff --git a/tests/corpus/7009-finalization-registry-wasm-loader/main.ts b/tests/corpus/7009-finalization-registry-wasm-loader/main.ts new file mode 100644 index 000000000..f844b0183 --- /dev/null +++ b/tests/corpus/7009-finalization-registry-wasm-loader/main.ts @@ -0,0 +1,39 @@ +// A package loaded the way wasm-bindgen's web target loads: FinalizationRegistry +// guards and registrations run at load and in constructors, and free() +// unregisters. Registrations keep their bookkeeping; cleanup +// callbacks run at times only the garbage collector decides, so this program +// prints nothing from them, as under Node. +import { Counter, initSync, released_total } from "counter-wasm"; + +// (module (func (export "add") (param i32 i32) (result i32) local.get 0 local.get 1 i32.add)) +const bytes = new Uint8Array([ + 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x07, 0x01, 0x60, 0x02, 0x7f, 0x7f, 0x01, + 0x7f, 0x03, 0x02, 0x01, 0x00, 0x07, 0x07, 0x01, 0x03, 0x61, 0x64, 0x64, 0x00, 0x00, 0x0a, 0x09, + 0x01, 0x07, 0x00, 0x20, 0x00, 0x20, 0x01, 0x6a, 0x0b, +]); +initSync(bytes); + +const a = new Counter(10); +a.increment(5); +const b = new Counter(2); +b.increment(1); +console.log(a.value, b.value); +b.free(); +a.free(); +console.log(a.value, released_total()); + +const registry = new FinalizationRegistry((held) => console.log("cleanup", held)); +const token = {}; +registry.register({}, "first", token); +registry.register({ id: 2 }, "second", token); +registry.register({ id: 3 }, "third"); +console.log(registry.unregister(token), registry.unregister(token), registry.unregister({})); +try { + new FinalizationRegistry(() => {}).register(token, token); +} catch (error) { + console.log((error as Error).name, (error as Error).message); +} +console.log(typeof FinalizationRegistry, registry instanceof FinalizationRegistry); +// A name the registry does not have reads as undefined. +console.log((registry as any).label); +console.log(Object.prototype.toString.call(registry), registry); diff --git a/tests/corpus/7009-finalization-registry-wasm-loader/node_modules/counter-wasm/counter_wasm.d.ts b/tests/corpus/7009-finalization-registry-wasm-loader/node_modules/counter-wasm/counter_wasm.d.ts new file mode 100644 index 000000000..525dec86f --- /dev/null +++ b/tests/corpus/7009-finalization-registry-wasm-loader/node_modules/counter-wasm/counter_wasm.d.ts @@ -0,0 +1,9 @@ +export declare class Counter { + constructor(start: number); + free(): void; + increment(by: number): number; + readonly value: number; + [Symbol.dispose](): void; +} +export declare function released_total(): number; +export declare function initSync(bytes: Uint8Array): unknown; diff --git a/tests/corpus/7009-finalization-registry-wasm-loader/node_modules/counter-wasm/counter_wasm.js b/tests/corpus/7009-finalization-registry-wasm-loader/node_modules/counter-wasm/counter_wasm.js new file mode 100644 index 000000000..92715f743 --- /dev/null +++ b/tests/corpus/7009-finalization-registry-wasm-loader/node_modules/counter-wasm/counter_wasm.js @@ -0,0 +1,61 @@ +// A loader in the shape wasm-bindgen's web target generates: the module's +// wrapper classes register with a FinalizationRegistry when they are +// created and unregister when free() releases them, and a TextEncoder +// polyfill guard runs at load. +let wasm; +const cachedTextEncoder = new TextEncoder(); +if (!("encodeInto" in cachedTextEncoder)) { + cachedTextEncoder.encodeInto = function (arg, view) { + const buf = cachedTextEncoder.encode(arg); + view.set(buf); + return { read: arg.length, written: buf.length }; + }; +} +let released = 0; +const CounterFinalization = + typeof FinalizationRegistry === "undefined" + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry((ptr) => wasm.add(ptr >>> 0, 1)); + +export class Counter { + static __wrap(ptr) { + const obj = Object.create(Counter.prototype); + obj.__wbg_ptr = ptr; + CounterFinalization.register(obj, obj.__wbg_ptr, obj); + return obj; + } + constructor(start) { + this.__wbg_ptr = wasm.add(start, 0); + CounterFinalization.register(this, this.__wbg_ptr, this); + } + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + CounterFinalization.unregister(this); + return ptr; + } + free() { + const ptr = this.__destroy_into_raw(); + released += wasm.add(ptr, 0); + } + increment(by) { + this.__wbg_ptr = wasm.add(this.__wbg_ptr, by); + return this.__wbg_ptr; + } + get value() { + return this.__wbg_ptr; + } +} +if (Symbol.dispose) Counter.prototype[Symbol.dispose] = Counter.prototype.free; + +export function released_total() { + return released; +} + +export function initSync(bytes) { + if (wasm !== undefined) return wasm; + const module = new WebAssembly.Module(bytes); + const instance = new WebAssembly.Instance(module, {}); + wasm = instance.exports; + return wasm; +} diff --git a/tests/corpus/7009-finalization-registry-wasm-loader/node_modules/counter-wasm/package.json b/tests/corpus/7009-finalization-registry-wasm-loader/node_modules/counter-wasm/package.json new file mode 100644 index 000000000..d86e34137 --- /dev/null +++ b/tests/corpus/7009-finalization-registry-wasm-loader/node_modules/counter-wasm/package.json @@ -0,0 +1 @@ +{ "name": "counter-wasm", "version": "1.0.0", "type": "module", "main": "./counter_wasm.js", "types": "./counter_wasm.d.ts" } diff --git a/tests/corpus/7011-for-in-dictionary-deletes.ts b/tests/corpus/7011-for-in-dictionary-deletes.ts new file mode 100644 index 000000000..91dac573b --- /dev/null +++ b/tests/corpus/7011-for-in-dictionary-deletes.ts @@ -0,0 +1,42 @@ +// for-in over a string-keyed dictionary visits the keys present when the +// walk starts, in insertion order, and skips a key deleted before its +// turn; keys added during the walk are not visited. A key deleted and +// added again before its turn is visited. +const d: Record = {}; +for (let i = 0; i < 8; i++) d["k" + i] = i; +const seen: string[] = []; +for (const key in d) { + seen.push(key); + if (key === "k1") { + delete d["k3"]; + delete d["k0"]; + d["k8"] = 8; + } + if (key === "k2") { + delete d["k5"]; + d["k5"] = 50; + } + if (key === "k4") delete d["k4"]; +} +console.log(seen.join(",")); +console.log(Object.keys(d).join(","), JSON.stringify(d)); + +// A numeric-looking key is walked in integer order before string keys. +const n: Record = {}; +n["b"] = "x"; +n["2"] = "y"; +n["10"] = "z"; +n["a"] = "w"; +const order: string[] = []; +for (const key in n) { + order.push(key); + if (key === "2") delete n["a"]; +} +console.log(order.join(",")); + +// A larger dictionary walked many times. +const big: Record = {}; +for (let i = 0; i < 3000; i++) big["e" + i] = i; +let total = 0; +for (let pass = 0; pass < 20; pass++) for (const key in big) total += big[key]!; +console.log(total); diff --git a/tests/corpus/7014-js-never-array-literal-fields/main.ts b/tests/corpus/7014-js-never-array-literal-fields/main.ts new file mode 100644 index 000000000..cf6d235c0 --- /dev/null +++ b/tests/corpus/7014-js-never-array-literal-fields/main.ts @@ -0,0 +1,10 @@ +// A JavaScript package whose object literals start an array property as +// `[]` inside a literal that maps to a record, as zod 3's parse context does +// (`{ common: { issues: [] }, path: params?.path || [] }`), and later push +// records onto it. Node runs the pushes; each array holds them. +import { Schema, rows } from "mini"; + +const s = new Schema(); +console.log(JSON.stringify(s.safeParse(1)), JSON.stringify(s.safeParse("a"))); +console.log(JSON.stringify(s.safeParse(2, { path: ["root"] }))); +console.log(rows()); diff --git a/tests/corpus/7014-js-never-array-literal-fields/node_modules/mini/index.d.ts b/tests/corpus/7014-js-never-array-literal-fields/node_modules/mini/index.d.ts new file mode 100644 index 000000000..5925684c0 --- /dev/null +++ b/tests/corpus/7014-js-never-array-literal-fields/node_modules/mini/index.d.ts @@ -0,0 +1,5 @@ +export interface Issue { code: string; path: (string | number)[]; message: string } +export declare class Schema { + safeParse(data: unknown, params?: { async?: boolean; path?: (string | number)[] }): { success: true; data: string } | { success: false; issues: Issue[] }; +} +export declare function rows(): string; diff --git a/tests/corpus/7014-js-never-array-literal-fields/node_modules/mini/index.js b/tests/corpus/7014-js-never-array-literal-fields/node_modules/mini/index.js new file mode 100644 index 000000000..47d24c8ad --- /dev/null +++ b/tests/corpus/7014-js-never-array-literal-fields/node_modules/mini/index.js @@ -0,0 +1,31 @@ +// A parse context as zod 3 keeps it: the issue list starts as `[]` in a +// nested literal, and the path is the caller's array or `[]`. +export function makeIssue(params) { + const { path, issueData } = params; + const fullPath = [...path, ...(issueData.path || [])]; + return { ...issueData, path: fullPath, message: "m" }; +} +export function addIssue(ctx, issueData) { + const issue = makeIssue({ issueData, path: ctx.path }); + ctx.common.issues.push(issue); +} +export class Schema { + safeParse(data, params) { + const ctx = { + common: { issues: [], async: params?.async ?? false }, + path: params?.path || [], + data, + }; + if (typeof data !== "string") addIssue(ctx, { code: "invalid_type" }); + return ctx.common.issues.length === 0 ? { success: true, data } : { success: false, issues: ctx.common.issues }; + } +} +// Array properties of records in an array literal and in a deeper literal, +// filled after construction. +export function rows() { + const table = { rows: [{ cells: [] }, { cells: [] }], meta: { tags: { list: [] } }, size: 2 }; + table.rows[0].cells.push({ v: 1 }); + table.rows[1].cells.push("text", 3); + table.meta.tags.list.push({ name: "t" }, null); + return JSON.stringify(table); +} diff --git a/tests/corpus/7014-js-never-array-literal-fields/node_modules/mini/package.json b/tests/corpus/7014-js-never-array-literal-fields/node_modules/mini/package.json new file mode 100644 index 000000000..be8bc49a2 --- /dev/null +++ b/tests/corpus/7014-js-never-array-literal-fields/node_modules/mini/package.json @@ -0,0 +1 @@ +{ "name": "mini", "version": "1.0.0", "type": "module", "main": "./index.js", "types": "./index.d.ts" } diff --git a/tests/corpus/7020-conditional-spread-fields.ts b/tests/corpus/7020-conditional-spread-fields.ts new file mode 100644 index 000000000..61c250174 --- /dev/null +++ b/tests/corpus/7020-conditional-spread-fields.ts @@ -0,0 +1,137 @@ +// Conditional spreads that carry several properties, and conditional +// spreads of a record value against an empty arm. The condition runs +// once, the carried values run only when their arm is taken and in +// property order, and the keys appear at the spread's position. +const log: string[] = []; +function note(label: string, value: T): T { + log.push(label); + return value; +} + +interface Extra { + region: string; + zone: number; +} + +function build(flag: boolean, model: string | undefined, extra: Extra | undefined) { + return { + name: note("name", "tool"), + ...(note("cond", flag) ? { verbose: note("verbose", true), depth: note("depth", 2) } : {}), + ...(model ? { model } : {}), + ...(extra ? extra : {}), + last: note("last", 0), + }; +} + +for (const [flag, model, extra] of [ + [true, "m1", { region: "eu", zone: 3 }], + [false, undefined, undefined], + [true, undefined, { region: "us", zone: 1 }], +] as const) { + log.length = 0; + const out = build(flag, model, extra); + console.log(JSON.stringify(out), Object.keys(out).join(","), log.join(" ")); + console.log("verbose" in out, out.depth ?? "no depth", out.region ?? "no region"); +} + +// The carrying arm can be the false arm, and `c && { ... }` carries +// several properties too. +function flags(quiet: boolean, color: boolean) { + return { + ...(quiet ? {} : { level: "info", prefix: "[app]" }), + ...(color && { fg: "green", bg: "black", bold: true }), + }; +} +console.log(JSON.stringify(flags(false, true)), JSON.stringify(flags(true, false))); + +// A record arm in either position, against `{}`, `undefined` or `null`. +interface Auth { + user: string; + token?: string; +} +const auth: Auth = { user: "u", token: "t" }; +const bare: Auth = { user: "v" }; +function request(useAuth: boolean, source: Auth) { + return { + url: "/x", + ...(useAuth ? source : {}), + ...(useAuth ? undefined : { anonymous: true }), + }; +} +console.log(JSON.stringify(request(true, auth)), JSON.stringify(request(false, auth))); +console.log(JSON.stringify(request(true, bare)), Object.keys(request(true, bare)).join(",")); +function fallback(primary: Auth | null, secondary: Auth) { + return { ...(primary === null ? secondary : null), id: 1 }; +} +console.log(JSON.stringify(fallback(null, auth)), JSON.stringify(fallback(bare, auth))); + +// A record arm read through a call runs only when its arm is taken. +let reads = 0; +function current(): Extra { + reads++; + return { region: "ap", zone: reads }; +} +const a = { ...(reads > 0 ? current() : {}), tag: "a" }; +const b = { ...(reads === 0 ? current() : {}), tag: "b" }; +console.log(JSON.stringify(a), JSON.stringify(b), reads); + +// Into a declared shape with optional fields. +interface Options { + cwd: string; + shell?: boolean; + timeout?: number; + env?: string; +} +function options(detached: boolean, env: string | undefined): Options { + return { cwd: "/", ...(detached ? { shell: false, timeout: 5 } : {}), ...(env ? { env } : {}) }; +} +console.log(JSON.stringify(options(true, "prod")), JSON.stringify(options(false, undefined))); + +// Inside 'any'-typed object literals, where the key is absent when the +// empty arm is taken. +function anyLiterals(): void { + function opts(aspect: string | undefined): any { + const o: any = { + mode: "M", + ...(aspect ? { cfg: { aspect } } : {}), + }; + return o; + } + const a = opts("1:1"); + console.log(`${a.mode} ${a.cfg.aspect} ${typeof a.cfg}`); + const b = opts(undefined); + console.log(`${b.mode} ${typeof b.cfg}`); + + // Several carried properties. + function multi(on: boolean): any { + return { base: 1, ...(on ? { x: "X", y: "Y" } : {}) }; + } + const m1 = multi(true); + const m2 = multi(false); + console.log(`${m1.base} ${m1.x} ${m1.y}`); + console.log(`${m2.base} ${typeof m2.x} ${typeof m2.y}`); + + // Reversed orientation and string-literal keys. + function rev(quiet: boolean): any { + return { kind: "r", ...(quiet ? {} : { "log-level": "loud" }) }; + } + console.log(`${rev(false)["log-level"]}`); + console.log(`${typeof rev(true)["log-level"]}`); + + // The spread mid-literal: properties around it evaluate exactly once and + // land in engine key order. + let sides = 0; + function side(v: number): number { + sides++; + return v; + } + function ordered(flag: boolean): any { + const o: any = { first: side(1), ...(flag ? { mid: 2 } : {}), last: side(3) }; + return o; + } + const o1 = ordered(true); + const o2 = ordered(false); + console.log(`${o1.first} ${o1.mid} ${o1.last}`); + console.log(`${o2.first} ${typeof o2.mid} ${o2.last} ${sides}`); +} +anyLiterals(); diff --git a/tests/corpus/7021-promise-all-uniform-tuple.ts b/tests/corpus/7021-promise-all-uniform-tuple.ts new file mode 100644 index 000000000..461351992 --- /dev/null +++ b/tests/corpus/7021-promise-all-uniform-tuple.ts @@ -0,0 +1,46 @@ +// `const pair = await Promise.all([p, q])` over entries of one promise +// type: the checker types the binding as a tuple, and the values arrive +// on the same microtask turn as Node's, in entry order whatever the +// settlement order. +const order: string[] = []; +function later(label: string, turns: number): Promise { + return new Promise((resolve) => { + let left = turns; + const step = (): void => { + if (left-- === 0) { + order.push(`settle ${label}`); + resolve(`${label}!`); + } else queueMicrotask(step); + }; + step(); + }); +} +async function count(n: number): Promise { + return n * 10; +} + +async function main(): Promise { + let ticking = true; + void (async () => { + for (let i = 0; i < 20 && ticking; i++) { + order.push(`t${i}`); + await null; + } + })(); + const bodies = await Promise.all([later("a", 3), later("b", 1)]); + order.push(`bodies ${bodies[0]} ${bodies[1]} ${bodies.length}`); + const numbers = await Promise.all([count(1), count(2), count(3)]); + const [x, y, z] = numbers; + order.push(`numbers ${x + y + z} ${numbers.length}`); + const annotated: [string, string] = await Promise.all([later("c", 0), later("d", 0)]); + order.push(`annotated ${annotated.join("+")}`); + ticking = false; + console.log(order.join("\n")); + try { + const failed = await Promise.all([later("e", 2), Promise.reject(new Error("no"))]); + console.log("unreachable", failed[0]); + } catch (e) { + console.log("caught", (e as Error).message); + } +} +void main(); diff --git a/tests/corpus/7022-promise-all-dynamic-arrays.ts b/tests/corpus/7022-promise-all-dynamic-arrays.ts new file mode 100644 index 000000000..dca5cdcde --- /dev/null +++ b/tests/corpus/7022-promise-all-dynamic-arrays.ts @@ -0,0 +1,41 @@ +// Promise.all over arrays built from 'any' values: the argument is a +// runtime value, so the combinator reads it with Node's iteration and +// resolves each entry (promises, thenables and plain values). +interface Check { + name: string; + ok: boolean; +} +async function check(name: string): Promise { + await null; + return { name, ok: name.length > 2 }; +} + +async function main(): Promise { + const raw: any = JSON.parse('{"items":[{"name":"abc"},{"name":"x"}],"ids":[1,2,3]}'); + const results = await Promise.all(raw.items.map((item: any) => check(item.name))); + for (const r of results) console.log(r.name, r.ok); + const doubled = await Promise.all(raw.ids.map(async (id: number) => id * 2)); + console.log(doubled.join(","), doubled.length); + const mixed = await Promise.all(raw.ids.map((id: number) => (id % 2 ? id : Promise.resolve(-id)))); + console.log(JSON.stringify(mixed)); + const parsed: unknown = JSON.parse('["a","bb","ccc"]'); + const list = Array.isArray(parsed) ? parsed : []; + const lengths = await Promise.all(list.map(async (s) => String(s).length)); + console.log(lengths, lengths.reduce((a, b) => a + b, 0)); + const empty: any = []; + console.log(JSON.stringify(await Promise.all(empty))); + try { + await Promise.all(raw.items.map(async (item: any) => { + if (item.name === "x") throw new Error(`bad ${item.name}`); + return item.name; + })); + } catch (e) { + console.log("rejected", (e as Error).message); + } + try { + await Promise.all(raw.missing); + } catch (e) { + console.log("not iterable", e instanceof TypeError); + } +} +void main(); diff --git a/tests/corpus/7023-union-object-patterns.ts b/tests/corpus/7023-union-object-patterns.ts new file mode 100644 index 000000000..8717e892a --- /dev/null +++ b/tests/corpus/7023-union-object-patterns.ts @@ -0,0 +1,63 @@ +// Object patterns over unions of records and classes read the fields +// every arm declares, in parameters, declarations and loops. +interface Add { + kind: "add"; + path: string; + content: string; + mode?: number; +} +interface Remove { + kind: "remove"; + path: string; + mode?: number; +} +type Change = Add | Remove; + +function describe({ kind, path: file, mode = 0o644 }: Change): string { + return `${kind}:${file}:${mode.toString(8)}`; +} +const changes: Change[] = [ + { kind: "add", path: "a.txt", content: "x" }, + { kind: "remove", path: "b.txt", mode: 0o600 }, +]; +for (const change of changes) console.log(describe(change)); +for (const { kind, path } of changes) console.log(kind, path.length); +function applyChange(change: Change): number { + const { path } = change; + let { kind } = change; + if (kind === "add") kind = "remove"; + return path.length + kind.length; +} +console.log(applyChange(changes[0]!), applyChange(changes[1]!)); + +// The source runs once, and the fields read in pattern order. +let reads = 0; +function next(): Change { + reads++; + return reads % 2 ? changes[0]! : changes[1]!; +} +const { path: p1, kind: k1 } = next(); +const { kind: k2 } = next(); +console.log(p1, k1, k2, reads); + +class Circle { + name: string; + size: number; + constructor(name: string, size: number) { + this.name = name; + this.size = size; + } +} +class Square { + name: string; + size: number; + corners = 4; + constructor(name: string, size: number) { + this.name = name; + this.size = size; + } +} +function label({ name, size }: Circle | Square): string { + return `${name}/${size}`; +} +console.log(label(new Circle("c", 2)), label(new Square("s", 3))); diff --git a/tests/corpus/7024-async-return-fresh-collections.ts b/tests/corpus/7024-async-return-fresh-collections.ts new file mode 100644 index 000000000..8343e028b --- /dev/null +++ b/tests/corpus/7024-async-return-fresh-collections.ts @@ -0,0 +1,48 @@ +// Async functions can return an empty array literal (where the result is +// inferred) or a new Map or Set: the value takes the result's element +// types, as a synchronous return does. +import { existsSync, readdirSync } from "node:fs"; + +async function listJson(dir: string) { + if (!existsSync(dir)) return []; + return readdirSync(dir).filter((name) => name.endsWith(".json")); +} + +async function childPaths(root: string) { + if (root === "") { + return []; + } + const found = [root, `${root}/b`]; + return found; +} + +async function index(names: string[]): Promise> { + if (names.length === 0) return new Map(); + const byName = new Map(); + for (const name of names) byName.set(name, name.length); + return byName; +} + +async function unique(words: string[]): Promise> { + if (words.length === 0) return new Set(); + return new Set(words); +} + +const pick = async (flag: boolean) => (flag ? [] : ["a", "b"]); + +async function main(): Promise { + const missing = await listJson("/nonexistent-dir-for-test"); + missing.push("pushed"); + console.log(missing, missing.length); + console.log(await childPaths(""), await childPaths("/root")); + const empty = await index([]); + empty.set("late", 4); + console.log(empty.size, empty.get("late"), (await index(["ab", "c"])).get("ab")); + const none = await unique([]); + none.add("z"); + console.log([...none], [...(await unique(["x", "x", "y"]))]); + const first = await pick(true); + first.push("c"); + console.log(first, await pick(false)); +} +void main(); diff --git a/tests/corpus/7025-child-listener-chaining.ts b/tests/corpus/7025-child-listener-chaining.ts new file mode 100644 index 000000000..317c87db1 --- /dev/null +++ b/tests/corpus/7025-child-listener-chaining.ts @@ -0,0 +1,42 @@ +// child.on() and child.once() return the child, so registrations chain +// and the result can be stored or passed on. The receiver evaluates once, +// before the listener. Each child starts after the previous one closed. +import { spawn } from "node:child_process"; + +const events: string[] = []; +let lookups = 0; +const children = [spawn("sh", ["-c", "exit 3"], { stdio: "ignore" })]; +function first() { + lookups++; + return children[0]!; +} + +const returned = first() + .on("exit", (code) => events.push(`exit ${code}`)) + .once("close", (code, signal) => { + events.push(`close ${code} ${signal}`); + console.log(events.join(", "), lookups); + second(); + }) + .on("error", (err) => events.push(`error ${err.message}`)); +console.log(returned === children[0], lookups); + +function second(): void { + spawn("sh", ["-c", "exit 0"], { stdio: "ignore" }) + .on("spawn", () => console.log("spawned")) + .on("exit", (code) => console.log("second exit", code)) + .on("close", () => third()); +} + +function third(): void { + const missing = spawn("/nonexistent/command-for-test", [], { stdio: "ignore" }).on( + "error", + (e) => console.log("missing", (e as NodeJS.ErrnoException).code), + ); + console.log(typeof missing.pid); + const detached = spawn("sh", ["-c", "exit 0"], { detached: true, stdio: "ignore" }).once( + "error", + (e) => console.log("spawn failed", e.message), + ); + detached.unref(); +} diff --git a/tests/corpus/7026-url-object-patterns.ts b/tests/corpus/7026-url-object-patterns.ts new file mode 100644 index 000000000..c2bc59958 --- /dev/null +++ b/tests/corpus/7026-url-object-patterns.ts @@ -0,0 +1,27 @@ +// Object patterns over URLs read the URL's getters in pattern order, +// with renames and defaults, in declarations and parameters. +let built = 0; +function parse(text: string): URL { + built++; + return new URL(text); +} +const { protocol, hostname, port } = parse("http://localhost:8080/path?q=1#top"); +console.log(protocol, hostname, port, built); +const { host: where, pathname: path = "/", search, hash, href } = parse("https://example.com/a/b?x=1&y=2#h"); +console.log(where, path, search, hash, href, built); + +function origin({ protocol: scheme, host, username, password }: URL): string { + return `${scheme}//${username}:${password}@${host}`; +} +console.log(origin(new URL("ftp://user:secret@files.example.org:2121/dir"))); + +const { searchParams } = new URL("http://h/?a=1&b=2"); +searchParams.append("c", "3"); +console.log(searchParams.toString(), [...searchParams.keys()].join(",")); + +const { origin: o, port: p } = new URL("https://[::1]:8443/"); +console.log(o, p); +for (const text of ["http://a.test:1", "http://b.test"]) { + const { hostname: name, port: listen } = new URL(text); + console.log(name, listen === "" ? "(default)" : listen); +} diff --git a/tests/corpus/7027-search-params-conditional-init.ts b/tests/corpus/7027-search-params-conditional-init.ts new file mode 100644 index 000000000..580d6c039 --- /dev/null +++ b/tests/corpus/7027-search-params-conditional-init.ts @@ -0,0 +1,21 @@ +// new URLSearchParams(c ? a : b) builds from the arm the condition +// selects; each arm may be a record literal, a string, pairs or another +// URLSearchParams. +let checks = 0; +function flag(value: boolean): boolean { + checks++; + return value; +} +for (const on of [true, false]) { + const params = new URLSearchParams(flag(on) ? { code: "x y", state: "s&t" } : {}); + console.log(params.toString(), params.size); + const query = new URLSearchParams(on ? "a=1&b=2" : [["c", "3"]]); + console.log(query.toString()); + const base = new URLSearchParams("keep=1"); + const copy = new URLSearchParams(on ? base : undefined); + copy.append("more", "2"); + console.log(copy.toString(), base.toString()); + const nested = new URLSearchParams(on ? (checks > 1 ? { n: "2" } : { n: "1" }) : "?empty="); + console.log(nested.toString()); +} +console.log(checks); diff --git a/tests/corpus/7028-non-empty-rest-tuples.ts b/tests/corpus/7028-non-empty-rest-tuples.ts new file mode 100644 index 000000000..5d00952ab --- /dev/null +++ b/tests/corpus/7028-non-empty-rest-tuples.ts @@ -0,0 +1,38 @@ +// Tuples of required positions followed by a rest element of the same +// type (`[string, ...string[]]`, the non-empty list) behave as arrays of +// that type. +type Hosts = [string, ...string[]]; +const LOCAL_HOSTS: Hosts = ["127.0.0.1", "::1", "localhost"]; +const single: [string, ...string[]] = ["only"]; +const pair: readonly [number, number, ...number[]] = [1, 2]; + +function first(hosts: Hosts): string { + return hosts[0]; +} +function isLocalHost(host: string): boolean { + return LOCAL_HOSTS.includes(host); +} +console.log(first(LOCAL_HOSTS), first(single), LOCAL_HOSTS.length, single.length); +console.log(isLocalHost("::1"), isLocalHost("10.0.0.1"), LOCAL_HOSTS.indexOf("localhost")); +console.log(LOCAL_HOSTS.slice(1).join(","), LOCAL_HOSTS.map((h) => h.length)); +for (const host of LOCAL_HOSTS) console.log(host); +const [head, ...rest] = LOCAL_HOSTS; +console.log(head, rest, JSON.stringify(LOCAL_HOSTS)); +single.push("more"); +console.log(single, single[1], pair[0] + pair[1], pair.length); + +function hostsFrom(text: string): Hosts { + const parts = text.split(","); + const out: Hosts = [parts[0]!]; + for (const part of parts.slice(1)) out.push(part); + return out; +} +const parsed = hostsFrom("a,b,c"); +console.log(parsed, parsed.length, `${parsed}`); + +function join(...names: [string, ...string[]]): string { + return names.join("+"); +} +console.log(join("x"), join("x", "y", "z"), join(...LOCAL_HOSTS)); +const lists: Hosts[] = [LOCAL_HOSTS, single]; +console.log(lists.map((l) => l[0]).join(" ")); diff --git a/tests/corpus/7029-flatmap-union-results.ts b/tests/corpus/7029-flatmap-union-results.ts new file mode 100644 index 000000000..efeae4d8f --- /dev/null +++ b/tests/corpus/7029-flatmap-union-results.ts @@ -0,0 +1,44 @@ +// flatMap callbacks that return a value or an array: an array result +// appends its elements (holes skipped), any other result appends itself, +// and an empty `[]` arm appends nothing. +const words = ["a", "", "c", "", "e"]; +console.log(words.flatMap((s) => (s ? s : []))); +console.log(words.flatMap((s, i) => (s ? [s, String(i)] : []))); + +function expand(line: string): string | string[] { + return line.includes(",") ? line.split(",") : line; +} +console.log(["x", "y,z", "w"].flatMap(expand), ["x", "y,z"].flatMap((l) => expand(l)).length); + +const numbers = [1, 2, 3, 4]; +console.log(numbers.flatMap((n) => (n % 2 ? n : [n, n * 10]))); +const sparse: number[] = []; +sparse[0] = 1; +sparse[2] = 3; +console.log(numbers.flatMap((n) => (n === 2 ? sparse : n))); + +interface Entry { + name: string; + tags?: string[]; +} +const entries: Entry[] = [{ name: "a", tags: ["t1", "t2"] }, { name: "b" }]; +console.log(entries.flatMap((e) => e.tags ?? []), entries.flatMap((e) => e.tags ?? e.name)); +let calls = 0; +const out = words.flatMap((s) => { + calls++; + return s.length > 0 ? s.toUpperCase() : []; +}); +console.log(out, calls); + +// One union result type with an empty arm in one callback and a populated +// array arm in another. +const counts = [1, 2, 3]; +console.log(counts.flatMap((n) => (n % 2 ? n : [])), counts.flatMap((n) => (n % 2 ? n : [n, n]))); + +// Array results keep present undefined elements, and an undefined result +// appends itself. +const withGaps: (number | undefined)[] = [4, undefined, 6]; +const maybe: (number | undefined)[] = [1, 2, undefined]; +console.log(maybe.flatMap((n) => (n === 2 ? withGaps : n))); +const gaps: (string | undefined)[] = ["x", undefined]; +console.log(["a", "b"].flatMap((s) => (s === "b" ? gaps : s))); diff --git a/tests/corpus/7030-spawn-sync-env.ts b/tests/corpus/7030-spawn-sync-env.ts new file mode 100644 index 000000000..0ab001b8f --- /dev/null +++ b/tests/corpus/7030-spawn-sync-env.ts @@ -0,0 +1,47 @@ +// spawnSync's env option replaces the child's environment, alone or with +// the other options. +import { spawnSync } from "node:child_process"; +import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +const merged = spawnSync("sh", ["-c", 'echo "$GREETING $HOME_SET"'], { + env: { ...process.env, GREETING: "hello", HOME_SET: process.env.HOME ? "yes" : "no" }, + encoding: "utf8", +}); +console.log(merged.stdout.trim(), merged.status); + +const only = spawnSync("/bin/sh", ["-c", 'echo "${GREETING:-unset} ${HOME:-nohome}"'], { + env: { GREETING: "only" }, + encoding: "utf8", +}); +console.log(only.stdout.trim()); + +const empty = spawnSync("/bin/sh", ["-c", "env | grep -c ."], { env: {}, encoding: "utf8" }); +console.log(Number(empty.stdout.trim()) <= 3, empty.status); + +const quiet = spawnSync("sh", ["-c", 'echo "$MODE" >&2; exit 4'], { + env: { PATH: process.env.PATH ?? "/usr/bin:/bin", MODE: "loud" }, + stdio: ["ignore", "pipe", "pipe"], + timeout: 5000, +}); +console.log(quiet.status, quiet.stderr.toString().trim(), quiet.stdout.toString() === ""); + +const missing = spawnSync("/nonexistent/tool", [], { env: { A: "1" } }); +console.log(missing.status, missing.error?.message); + +// The command is found on the replacement environment's PATH, or on the +// default path when the replacement has none, not on the parent's PATH. +const dir = mkdtempSync(join(tmpdir(), "scr-spawn-path-")); +writeFileSync(join(dir, "child-only-tool"), "#!/bin/sh\necho child-only\n"); +chmodSync(join(dir, "child-only-tool"), 0o755); +writeFileSync(join(dir, "not-executable"), "#!/bin/sh\necho never\n"); +const viaPath = spawnSync("child-only-tool", [], { env: { PATH: `/nonexistent:${dir}` }, encoding: "utf8" }); +console.log(viaPath.status, viaPath.stdout.trim()); +const defaultPath = spawnSync("sh", ["-c", "echo default"], { env: { A: "1" }, encoding: "utf8" }); +console.log(defaultPath.status, defaultPath.stdout.trim()); +const notOnPath = spawnSync("sh", ["-c", "echo never"], { env: { PATH: dir }, encoding: "utf8" }); +console.log(notOnPath.status, notOnPath.error?.message); +const denied = spawnSync("not-executable", [], { env: { PATH: dir }, encoding: "utf8" }); +console.log(denied.status, denied.error?.message); +rmSync(dir, { recursive: true }); diff --git a/tests/corpus/7033-any-fields-into-declared-records.ts b/tests/corpus/7033-any-fields-into-declared-records.ts new file mode 100644 index 000000000..89c0f69e8 --- /dev/null +++ b/tests/corpus/7033-any-fields-into-declared-records.ts @@ -0,0 +1,28 @@ +// Records whose fields TypeScript types `any` convert into declared +// record types: each such field is checked against the declared type, +// as a typed binding initialized from the value is. +interface Transfer { + source: string; + targetId: string; + bytes: number; + tags: string[]; +} +const meta: any = JSON.parse('{"id":"x-1","size":4,"tags":["a","b"]}'); + +const mapped: Transfer[] = ["a", "b"].map((s, i) => ({ + source: s, + targetId: meta.id, + bytes: meta.size + i, + tags: meta.tags, +})); +console.log(JSON.stringify(mapped)); + +function build(): Transfer { + const record = { source: "c", targetId: meta.id, bytes: meta.size, tags: [] as string[] }; + return record; +} +console.log(JSON.stringify(build())); + +const list: Transfer[] = []; +for (const entry of [{ source: "d", targetId: meta.id, bytes: 1, tags: meta.tags }]) list.push(entry); +console.log(list.length, list[0]!.targetId.toUpperCase(), list[0]!.tags.length); diff --git a/tests/corpus/7034-optional-field-union-routes.ts b/tests/corpus/7034-optional-field-union-routes.ts new file mode 100644 index 000000000..0fb93ff8d --- /dev/null +++ b/tests/corpus/7034-optional-field-union-routes.ts @@ -0,0 +1,26 @@ +// A record whose `T | undefined` field is the one field that tells two +// arms of a union apart converts into that union: a value picks the arm +// that declares the field, and undefined picks the arm without it. +type Summary = + | { written: number; errors: string[]; ignored: number } + | { written: number; ignored: number }; + +function summarize(written: number, ignored: number, errors: string[]): Summary { + return { written, errors: errors.length > 0 ? errors : undefined, ignored }; +} +function errorCount(summary: Summary): number { + return "errors" in summary && summary.errors !== undefined ? summary.errors.length : 0; +} +for (const errors of [[], ["e1", "e2"]]) { + const summary = summarize(3, 1, errors); + console.log(JSON.stringify(summary), errorCount(summary), summary.written + summary.ignored); +} + +type Lookup = { name: string; value: number; source: string } | { name: string; source: string }; +const values = new Map([["a", 1]]); +const lookups: Lookup[] = ["a", "b"].map((name) => ({ + name, + value: values.get(name), + source: "map", +})); +console.log(JSON.stringify(lookups)); diff --git a/tests/corpus/7036-child-env-path-lookup.ts b/tests/corpus/7036-child-env-path-lookup.ts new file mode 100644 index 000000000..97c93d835 --- /dev/null +++ b/tests/corpus/7036-child-env-path-lookup.ts @@ -0,0 +1,53 @@ +// spawn and execFileSync with an env option find the command on the +// replacement environment's PATH, or on the default path when it has +// none, as Node does; a relative PATH entry is read from the cwd option. +import { execFileSync, spawn } from "node:child_process"; +import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +const dir = mkdtempSync(join(tmpdir(), "scr-child-path-")); +mkdirSync(join(dir, "tools")); +writeFileSync(join(dir, "tools", "child-tool"), "#!/bin/sh\necho child-tool $1\n"); +chmodSync(join(dir, "tools", "child-tool"), 0o755); + +// An earlier PATH entry holding a script whose interpreter is missing +// moves the lookup on to the next entry, as execvp does. +mkdirSync(join(dir, "broken")); +writeFileSync(join(dir, "broken", "child-tool"), "#!/nonexistent/interpreter\n"); +chmodSync(join(dir, "broken", "child-tool"), 0o755); + +const show = (e: unknown): string => { + const err = e as NodeJS.ErrnoException; + return `${err.code} ${err.message.replace(dir, "")}`; +}; + +console.log(execFileSync("child-tool", ["sync"], { env: { PATH: join(dir, "tools") }, encoding: "utf8" }).trim()); +console.log(execFileSync("sh", ["-c", "echo default"], { env: { A: "1" }, encoding: "utf8" }).trim()); +try { + execFileSync("sh", ["-c", "echo never"], { env: { PATH: "/nonexistent" }, encoding: "utf8" }); +} catch (e) { + console.log(show(e)); +} +const twoEntries = `${join(dir, "broken")}:${join(dir, "tools")}`; +console.log(execFileSync("child-tool", ["fallthrough"], { env: { PATH: twoEntries }, encoding: "utf8" }).trim()); +try { + execFileSync("child-tool", [], { env: { PATH: join(dir, "broken") }, encoding: "utf8" }); +} catch (e) { + console.log(show(e)); +} +console.log( + execFileSync("child-tool", ["relative"], { env: { PATH: "tools" }, cwd: dir, encoding: "utf8" }).trim(), +); + +const child = spawn("child-tool", ["async"], { env: { PATH: twoEntries }, stdio: ["ignore", "pipe", "ignore"] }); +let out = ""; +child.stdout!.on("data", (chunk: Buffer) => (out += chunk.toString())); +child.on("close", (code) => { + console.log(out.trim(), code); + const missing = spawn("sh", ["-c", "true"], { env: { PATH: "/nonexistent" }, stdio: "ignore" }); + missing.on("error", (e) => { + console.log("error", show(e)); + rmSync(dir, { recursive: true }); + }); +}); diff --git a/tests/corpus/7040-es5-error-constructor.mjs b/tests/corpus/7040-es5-error-constructor.mjs new file mode 100644 index 000000000..977567125 --- /dev/null +++ b/tests/corpus/7040-es5-error-constructor.mjs @@ -0,0 +1,79 @@ +// A constructor function that inherits from Error.prototype, the pre-class +// way of declaring an error type. +function ParseFailure(reason, position) { + Error.call(this); + this.name = "ParseFailure"; + this.reason = reason; + this.position = position; + this.message = reason + (position === undefined ? "" : " at " + position); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } else { + this.stack = new Error().stack || ""; + } +} +ParseFailure.prototype = Object.create(Error.prototype); +ParseFailure.prototype.constructor = ParseFailure; +ParseFailure.prototype.toString = function toString(compact) { + return this.name + ": " + this.reason + (compact ? "" : " (position " + this.position + ")"); +}; + +const failure = new ParseFailure("unexpected token", 7); +console.log(failure instanceof ParseFailure, failure instanceof Error, failure.constructor === ParseFailure); +console.log(failure.name, "|", failure.message, "|", failure.reason, failure.position); +console.log(failure.toString(), "|", failure.toString(true), "|", String(failure), "|", `${failure}`); +console.log(Object.keys(failure), JSON.stringify(failure)); +console.log(typeof failure.stack, failure.stack.split("\n")[0], Object.keys(failure).includes("stack")); +console.log(Object.prototype.toString.call(failure), Error.isError(failure)); + +try { + throw new ParseFailure("thrown"); +} catch (caught) { + console.log(caught instanceof Error, caught instanceof ParseFailure, caught.reason, caught.message); +} +const values = [new ParseFailure("in a list"), new Error("plain"), { name: "Fake", message: "x" }, "text"]; +console.log(values.map((value) => value instanceof Error)); + +// The inherited members of Error.prototype. +const bare = Object.create(Error.prototype); +console.log(bare instanceof Error, bare.name, JSON.stringify(bare.message), String(bare), Object.keys(bare)); +console.log(Error.prototype.name, JSON.stringify(Error.prototype.message), Error.prototype instanceof Error); +const record = Object.create(Error.prototype); +record.name = "N"; +record.message = "M"; +console.log(String(record), `${Object.create(record)}`); + +// captureStackTrace on other objects: the header follows name and message. +const target = { name: "Custom", message: "details", toString() { return "ignored"; } }; +Error.captureStackTrace(target); +console.log(target.stack.split("\n")[0], Object.keys(target)); +const empty = {}; +Error.captureStackTrace(empty); +console.log(empty.stack.split("\n")[0], typeof Error.captureStackTrace); + +// A subtype of the subtype. +function StrictFailure(reason) { + ParseFailure.call(this, reason, 0); + this.name = "StrictFailure"; +} +StrictFailure.prototype = Object.create(ParseFailure.prototype); +StrictFailure.prototype.constructor = StrictFailure; +const strict = new StrictFailure("strict mode"); +console.log(strict instanceof StrictFailure, strict instanceof ParseFailure, strict instanceof Error, strict.toString(true)); + +// A class that extends Error calls it too, directly or through `?.`. +class TokenError extends Error { + constructor(message) { + super(message); + this.name = "TokenError"; + Error.captureStackTrace(this, TokenError); + } +} +class LexError extends TokenError { + constructor(message) { + super(message), (this.name = "LexError"), Error.captureStackTrace?.(this, this.constructor); + } +} +for (const error of [new TokenError("bad token"), new LexError("bad char")]) { + console.log(error.name, error.message, error.stack.split("\n")[0], error instanceof TokenError, Object.keys(error)); +} diff --git a/tests/corpus/7041-error-called-without-new.mjs b/tests/corpus/7041-error-called-without-new.mjs new file mode 100644 index 000000000..bf1df8e99 --- /dev/null +++ b/tests/corpus/7041-error-called-without-new.mjs @@ -0,0 +1,40 @@ +// The standard error constructors called as functions construct errors too, +// and Function.prototype.call ignores the receiver it is given. +const plain = Error("plain"); +const typed = TypeError("typed"); +const range = RangeError(); +const withCause = Error("wrapped", { cause: plain }); +console.log(plain instanceof Error, plain.message, String(plain)); +console.log(typed instanceof TypeError, typed instanceof Error, typed.name, typed.message); +console.log(range instanceof RangeError, JSON.stringify(range.message), String(range)); +console.log(withCause.cause === plain, withCause.message); +console.log(SyntaxError("s").name, ReferenceError("r").name, EvalError("e").name, URIError("u").name); + +const receiver = { marker: true }; +const called = Error.call(receiver, "via call"); +console.log(called instanceof Error, called.message, Object.keys(receiver), called === receiver); +const typedCall = TypeError.call(null, "typed via call"); +console.log(typedCall instanceof TypeError, typedCall.message); +const noArguments = Error.call(); +console.log(noArguments instanceof Error, JSON.stringify(noArguments.message)); + +let evaluated = 0; +function effect(value) { + evaluated++; + return value; +} +const ordered = Error.call(effect({}), effect("ordered")); +console.log(evaluated, ordered.message); + +function Wrapper(message) { + const base = Error.call(this, message); + this.message = base.message; + this.kind = "wrapper"; +} +const wrapped = new Wrapper("kept"); +console.log(wrapped.message, wrapped.kind, wrapped instanceof Wrapper, wrapped instanceof Error); +try { + throw Error("thrown without new"); +} catch (error) { + console.log(error instanceof Error, error.message); +} diff --git a/tests/corpus/7042-string-method-names-on-objects.mjs b/tests/corpus/7042-string-method-names-on-objects.mjs new file mode 100644 index 000000000..c623f5417 --- /dev/null +++ b/tests/corpus/7042-string-method-names-on-objects.mjs @@ -0,0 +1,70 @@ +// Objects whose members share names with String.prototype methods, filled +// in after their declaration. A call dispatches on the receiver's runtime +// kind: a string runs the String method, any other value its own member. +var helpers = {}; +var initialized; +function setup() { + if (initialized) return helpers; + initialized = true; + function repeat(text, count) { + let out = ""; + for (let i = 0; i < count; i += 1) out += text; + return out; + } + function padStart(text, width, fill) { + let out = String(text); + while (out.length < width) out = fill + out; + return out; + } + helpers.repeat = repeat; + helpers.padStart = padStart; + helpers.trim = function (value) { + return "<" + value + ">"; + }; + helpers.split = (value, separator) => [value, separator, "own"]; + helpers.toUpperCase = () => "own upper"; + return helpers; +} + +const h = setup(); +console.log("[" + h.repeat("ab", 3) + "]", "[" + h.repeat("-", 0) + "]"); +console.log(h.padStart(7, 3, "0"), h.padStart("long", 2, "*")); +console.log(h.trim(" x "), h.split("a,b", ","), h.toUpperCase()); + +const indent = h.repeat(" ", 2); +console.log("[" + indent + "]", indent.length); +const lines = ["one", "two"].map((line, index) => h.padStart(index + 1, 3, " ") + " | " + line); +console.log(lines.join("\n")); + +// The same names on a missing member throw Node's TypeError. +var partial = {}; +function fillPartial() { + partial.present = true; +} +fillPartial(); +try { + partial.repeat("x", 2); +} catch (error) { + console.log(error instanceof TypeError, error.message); +} +try { + partial.trim(); +} catch (error) { + console.log(error instanceof TypeError, error.message); +} + +// Arguments are evaluated once, in order, after the member is read. +const order = []; +var traced = {}; +function fillTraced() { + traced.replace = (a, b) => { + order.push("call"); + return a + b; + }; +} +fillTraced(); +function arg(value) { + order.push("arg " + value); + return value; +} +console.log(traced.replace(arg(1), arg(2)), order.join(", ")); diff --git a/tests/corpus/7043-date-set-time.mjs b/tests/corpus/7043-date-set-time.mjs new file mode 100644 index 000000000..a673c58dc --- /dev/null +++ b/tests/corpus/7043-date-set-time.mjs @@ -0,0 +1,28 @@ +// Date.prototype.setTime on Dates a JavaScript file constructs: the Date +// is one mutable object, so every reference sees the new time value. +function shifted(year, month, day, minutes) { + const date = new Date(Date.UTC(year, month, day, 12, 30, 15, 250)); + if (minutes) date.setTime(date.getTime() - minutes * 60000); + return date; +} +const unchanged = shifted(2001, 1, 3, 0); +const moved = shifted(2001, 1, 3, 90); +console.log(unchanged.toISOString(), moved.toISOString()); + +const alias = moved; +const record = { when: moved }; +console.log(moved.setTime(1000), alias.getTime(), record.when.toISOString()); +console.log(moved.setTime("2500"), moved.getTime(), moved.setTime(1.9), moved.setTime(-1.9)); +console.log(moved.setTime(NaN), moved.getTime(), String(moved), moved.toJSON()); +console.log(moved.setTime(8.64e15), moved.setTime(8.64e15 + 1), moved.setTime(-8.64e15 - 1)); +console.log(Object.is(moved.setTime(-0), 0), moved.setTime(), moved.setTime(true), moved.setTime(null)); +console.log(moved.setTime({ valueOf: () => 86400000 }), moved.toISOString()); +try { + moved.setTime({ valueOf: () => { throw new Error("no time"); } }); +} catch (error) { + console.log(error.message, moved.toISOString()); +} +console.log(JSON.stringify({ at: shifted(1999, 11, 31, 1) })); +const dates = [shifted(2020, 0, 1, 0), shifted(2020, 0, 1, 0)]; +dates.forEach((date, index) => date.setTime(date.getTime() + index * 1000)); +console.log(dates.map((date) => date.getUTCSeconds())); diff --git a/tests/corpus/7044-nested-empty-object-maps.mjs b/tests/corpus/7044-nested-empty-object-maps.mjs new file mode 100644 index 000000000..e8d330f20 --- /dev/null +++ b/tests/corpus/7044-nested-empty-object-maps.mjs @@ -0,0 +1,46 @@ +// Object literals whose fields start as empty objects, used as maps the +// program adds keys to, including chained assignment into two of them. +function index(entries) { + const table = { + first: {}, + second: {}, + all: {}, + lists: { first: [], second: [], all: [] }, + }; + function add(entry) { + if (entry.many) { + table.lists[entry.group].push(entry.name); + table.lists["all"].push(entry.name); + } else { + table[entry.group][entry.name] = table["all"][entry.name] = entry; + } + } + entries.forEach(add); + return table; +} +const table = index([ + { group: "first", name: "a" }, + { group: "second", name: "b" }, + { group: "first", name: "c", many: true }, + { group: "second", name: "a" }, +]); +console.log(Object.keys(table.first), Object.keys(table.second), Object.keys(table.all), table.lists); +console.log(table.all.a === table.second.a, table.first.a.group, table.all.b.name, "c" in table.first); +console.log(JSON.stringify(table)); + +function counters(words) { + const result = { seen: {}, firstAt: {} }; + words.forEach((word, position) => { + result.seen[word] = (result.seen[word] || 0) + 1; + if (!(word in result.firstAt)) result.firstAt[word] = position; + }); + return result; +} +console.log(JSON.stringify(counters(["x", "y", "x", "z", "y", "x"]))); + +const settings = { values: {}, names: {} }; +const key = String(Math.round(1.6)); +settings.values[key] = 2; +settings["names"][key + "!"] = settings.values[key] * 10; +delete settings.values[key]; +console.log(JSON.stringify(settings), Object.keys(settings.values).length); diff --git a/tests/corpus/7045-instanceof-constructor-values.mjs b/tests/corpus/7045-instanceof-constructor-values.mjs new file mode 100644 index 000000000..6b41cfdca --- /dev/null +++ b/tests/corpus/7045-instanceof-constructor-values.mjs @@ -0,0 +1,43 @@ +// `instanceof` against constructors held as values: a property holding a +// global constructor, and constructor functions with prototype chains. +const kinds = [ + { name: "Date", type: Date }, + { name: "RegExp", type: RegExp }, + { name: "Map", type: Map }, + { name: "Set", type: Set }, + { name: "WeakMap", type: WeakMap }, + { name: "Promise", type: Promise }, + { name: "Array", type: Array }, +]; +function classify(value) { + return kinds + .filter((kind) => typeof value === "object" && value !== null && value instanceof kind.type) + .map((kind) => kind.name) + .join("+") || "none"; +} +const samples = [new Date(0), /x/g, new Map([[1, 2]]), new Set([1]), new WeakMap(), Promise.resolve(1), [1, 2], { a: 1 }, null, "text", 4]; +console.log(samples.map(classify).join(" ")); + +function Shape(sides) { + this.sides = sides; +} +Shape.prototype.describe = function () { + return this.sides + " sides"; +}; +function Square() { + Shape.call(this, 4); +} +Square.prototype = Object.create(Shape.prototype); +Square.prototype.constructor = Square; +const square = new Square(); +const shape = new Shape(3); +const types = { Shape, Square }; +console.log(square instanceof types.Shape, square instanceof types.Square, shape instanceof types.Square); +console.log(square.describe(), shape.describe(), Object.create(Square.prototype) instanceof types.Shape); +console.log([square, shape, {}, []].map((value) => value instanceof types.Shape)); +const notCallable = JSON.parse("{}"); +try { + console.log(square instanceof notCallable); +} catch (error) { + console.log(error instanceof TypeError, error.message); +} diff --git a/tests/corpus/7046-parse-float-extra-arguments.mjs b/tests/corpus/7046-parse-float-extra-arguments.mjs new file mode 100644 index 000000000..9046a9145 --- /dev/null +++ b/tests/corpus/7046-parse-float-extra-arguments.mjs @@ -0,0 +1,9 @@ +// parseFloat reads one argument; Node ignores any others. +const radix = 10; +const inputs = ["3.25", " -0.5e2xyz", "0x10", "Infinityx", ".5", "-.e1", "", "1_000"]; +console.log(inputs.map((text) => parseFloat(text, 10))); +console.log(inputs.map((text) => parseFloat(text, radix, "ignored"))); +const fromJson = JSON.parse('{"value":"12.5kg","n":7}'); +console.log(parseFloat(fromJson.value, 10), parseFloat(fromJson.n, radix), Object.is(parseFloat("-0", 10), -0)); +const values = ["1.5", "2.25"].map((text) => parseFloat(text.replace(/_/g, ""), 10)); +console.log(values, values[0] + values[1]); diff --git a/tests/corpus/7047-dynamic-string-index.mjs b/tests/corpus/7047-dynamic-string-index.mjs new file mode 100644 index 000000000..fc81db3ce --- /dev/null +++ b/tests/corpus/7047-dynamic-string-index.mjs @@ -0,0 +1,21 @@ +// Indexing a string with a key whose type is only known at run time reads +// the property the key names: a code unit, the length, or undefined. +function skipSpaces(text, at) { + let c; + while ((c = text[at]) === " " || c === "\t") at++; + return [at, c]; +} +const where = JSON.parse('{"at":2,"name":"length","past":9,"text":"1","neg":-1,"frac":1.5}'); +console.log(skipSpaces("ab \tcd", where.at), skipSpaces("ab", where.past)); +const s = "hello"; +console.log(s[where.at], s[where.name], s[where.past], s[where.text], s[where.neg], s[where.frac]); +console.log(typeof s[where.past], typeof s[where.name], s[where.at] === "l"); +function scan(text, start) { + let out = ""; + for (let i = start; text[i] !== undefined && text[i] !== ";"; i++) out += text[i]; + return out; +} +console.log(scan("key=value;rest", JSON.parse("4")), scan("abc", JSON.parse("1"))); +const codes = []; +for (let i = JSON.parse("0"); i < s.length; i++) codes.push(s[i].charCodeAt(0)); +console.log(codes); diff --git a/tests/corpus/7048-unary-number-coercions.mjs b/tests/corpus/7048-unary-number-coercions.mjs new file mode 100644 index 000000000..4154ae79e --- /dev/null +++ b/tests/corpus/7048-unary-number-coercions.mjs @@ -0,0 +1,34 @@ +// Unary plus and minus on booleans and on values that may be strings or +// undefined, and += on a binding that holds a number or a string. +function step(text, at) { + const open = text[at] === "["; + at += +open; + return [at, +open + +true + +false, -open]; +} +const at = JSON.parse("1"); +console.log(step("a[b", at), step("ab", at)); +let total = 0; +for (const flag of [true, false, true]) total += +flag; +console.log(total, +true, -true, +(1 > 2), -(2 > 1)); + +const match = "2024-01-02".match(/^(\d+)-(\d+)-(\d+)(?:T(\d+))?$/); +console.log(+match[1], +match[4], -match[2], +match[3] + 1, typeof +match[4], -match[4]); +const optional = [undefined, "7", " 8 ", "", "x"]; +console.log(optional.map((value) => +value), optional.map((value) => -value)); + +let fraction = 0; +const digits = "5"; +if (digits) { + fraction = digits.slice(0, 3); + while (fraction.length < 3) fraction += "0"; + fraction = +fraction; +} +console.log(fraction, typeof fraction); +let width = 0; +width = digits.repeat(2); +width += 1; +console.log(width, typeof width); +let label = "x"; +label += 5; +label += true; +console.log(label); diff --git a/tests/corpus/7049-member-assignment-values.mjs b/tests/corpus/7049-member-assignment-values.mjs new file mode 100644 index 000000000..b614ba308 --- /dev/null +++ b/tests/corpus/7049-member-assignment-values.mjs @@ -0,0 +1,20 @@ +// Member assignments used as values: the receiver, the key and the value are +// evaluated in order, and the expression yields the assigned value. +const log = []; +const holder = { get inner() { log.push("receiver"); return this._inner; }, _inner: {} }; +function value(v) { log.push("value"); return v; } +function key(k) { log.push("key"); return k; } +const r = holder.inner[key("k")] = value(5); +console.log(r, log.join(","), holder._inner.k); +const store = JSON.parse('{"a":{},"b":{}}'); +const t = { id: "x" }; +const out = store["a"][t.id] = store.b[t.id] = t; +console.log(out === t, JSON.stringify(store)); +let n; +const arr = [0, 0, 0]; +n = arr[1] = arr[2] = 7; +console.log(n, arr); +function Counter() { this.count = 0; } +Counter.prototype.bump = function () { return (this.count = this.count + 1); }; +const c = new Counter(); +console.log(c.bump(), c.bump(), c.count); diff --git a/tests/corpus/7050-date-subclass.mjs b/tests/corpus/7050-date-subclass.mjs new file mode 100644 index 000000000..b5edb38e4 --- /dev/null +++ b/tests/corpus/7050-date-subclass.mjs @@ -0,0 +1,78 @@ +// A class that extends Date: private fields beside the time value, super() +// with each Date constructor form, an overriding toISOString that +// JSON.stringify reaches through Date.prototype.toJSON, and the inherited +// Date methods. +class Moment extends Date { + #zone = "Z"; + #precise = true; + constructor(value, zone) { + if (value === undefined) super(0); + else super(value); + if (zone !== undefined) this.#zone = zone; + } + get zone() { + return this.#zone; + } + coarse() { + this.#precise = false; + return this; + } + toISOString() { + const iso = super.toISOString(); + const base = this.#precise ? iso : iso.slice(0, 19) + "Z"; + return this.#zone === "Z" ? base : base.slice(0, -1) + this.#zone; + } +} + +const fromString = new Moment("2001-02-03T04:05:06.789Z"); +const fromNumber = new Moment(86400000, "+01:00"); +const fromDate = new Moment(new Date(Date.UTC(1999, 11, 31, 23, 59, 59))); +const fromMoment = new Moment(fromString); +const none = new Moment(); +console.log(fromString.toISOString(), fromNumber.toISOString(), fromDate.toISOString()); +console.log(fromMoment.getTime() === fromString.getTime(), none.getTime(), fromNumber.zone); +console.log(fromString.getUTCFullYear(), fromString.getUTCMonth(), fromString.getUTCDate(), fromString.getUTCHours(), fromString.getUTCMilliseconds()); +console.log(fromString instanceof Date, fromString instanceof Moment, new Date(0) instanceof Moment); +console.log(JSON.stringify({ fromString, fromNumber, list: [fromDate.coarse()] })); +console.log(fromNumber.toJSON(), JSON.stringify(fromNumber)); +console.log(String(fromDate).slice(0, 15), `${fromDate}`.slice(0, 15), fromDate.toUTCString()); +console.log(+fromNumber, +fromNumber - 1000, fromNumber.valueOf(), fromNumber + "" === String(fromNumber)); +console.log(fromString > fromNumber, fromString < fromNumber, fromString >= fromMoment); +console.log(fromNumber.setTime(1000), fromNumber.getTime(), fromNumber.toISOString()); +console.log(new Date(fromString).toISOString(), new Date(fromNumber).getTime()); +console.log(fromString, [fromNumber], { d: fromDate }); + +const invalid = new Moment("not a date"); +console.log(Number.isNaN(invalid.getTime()), JSON.stringify({ invalid }), invalid.toJSON(), String(invalid)); +console.log(invalid); +try { + invalid.toISOString(); +} catch (error) { + console.log(error instanceof RangeError, error.message); +} + +class LocalMoment extends Moment { + constructor(value) { + super(value, "local"); + } + toISOString() { + return super.toISOString().replace("local", ""); + } +} +const local = new LocalMoment(0); +console.log(local.toISOString(), JSON.stringify([local]), local instanceof Moment, local.zone); + +// The field constructor and Date's statics, which the subclass inherits. +class Plain extends Date {} +const fields = new Plain(2020, 0, 15, 10, 30); +console.log(fields.getFullYear(), fields.getMonth(), fields.getDate(), fields.getHours(), fields.getMinutes()); +console.log(Plain.UTC(2000, 0, 1), Plain.parse("2000-01-01T00:00:00Z"), typeof Plain.now(), Object.keys(fields)); + +// Date held as a value answers instanceof for subclass instances. +const constructors = { date: Date }; +console.log(fields instanceof constructors.date, local instanceof constructors.date, {} instanceof constructors.date); + +// setTime evaluates every argument before it converts the first one. +let base = 1000; +const delayed = { valueOf: () => base }; +console.log(fields.setTime(delayed, (base = 2000)), fields.getTime()); diff --git a/tests/corpus/7051-date-subclass-typed.ts b/tests/corpus/7051-date-subclass-typed.ts new file mode 100644 index 000000000..e39b5f534 --- /dev/null +++ b/tests/corpus/7051-date-subclass-typed.ts @@ -0,0 +1,47 @@ +// A TypeScript class that extends Date, and a subclass of it: typed calls +// of the inherited Date methods, conversions, comparisons, JSON and +// console output, with the toISOString override visible to toJSON. +class Stamp extends Date { + #precise: boolean; + label = "stamp"; + constructor(value: number | string, precise = false) { + super(value); + this.#precise = precise; + } + override toISOString(): string { + const iso = super.toISOString(); + return this.#precise ? iso : iso.slice(0, 19) + "Z"; + } + shifted(ms: number): Stamp { + return new Stamp(this.getTime() + ms, this.#precise); + } +} + +class Tick extends Stamp { + constructor(value: number) { + super(value, true); + } + seconds(): number { + return this.getUTCSeconds() + this.getUTCMilliseconds() / 1000; + } +} + +const a = new Stamp("2001-02-03T04:05:06.789Z"); +const b = new Tick(1500); +console.log(a.toISOString(), b.toISOString(), a.getTime(), b.seconds()); +console.log(a instanceof Date, b instanceof Stamp, b instanceof Date, a.shifted(1000).toISOString()); +console.log(JSON.stringify({ a, b, list: [a] }), JSON.stringify(a), a.toJSON(), b.toJSON()); +console.log(String(a).slice(0, 15), `${b}`.slice(0, 15), +a, b.valueOf(), a.getTime() - b.getTime()); +console.log(a < b, a > b, a >= b, a == a, a + "!" === String(a) + "!"); +console.log(a); +console.log([b], { b }); +console.log(a.setTime(5000), a.getTime(), a.toISOString(), a.label); + +const items: Stamp[] = [a, b, new Tick(0)]; +items.sort((x, y) => x.getTime() - y.getTime()); +console.log(items.map((s) => s.toISOString()).join(",")); +console.log(items.filter((s) => s instanceof Tick).length); +function describe(value: Stamp | string): string { + return typeof value === "string" ? value : value.toISOString(); +} +console.log(describe(b), describe("text")); diff --git a/tests/corpus/7052-date-subclass-dynamic.mjs b/tests/corpus/7052-date-subclass-dynamic.mjs new file mode 100644 index 000000000..267c01ded --- /dev/null +++ b/tests/corpus/7052-date-subclass-dynamic.mjs @@ -0,0 +1,43 @@ +// Instances of a class that extends Date held in values typed only at run +// time: method calls, method values, conversions and instanceof through +// those values, and JSON and console output of the containers. +class Day extends Date { + #label; + constructor(value, label) { + super(value); + this.#label = label; + } + get label() { + return this.#label; + } + toISOString() { + return super.toISOString().slice(0, 10); + } +} +class Plain extends Date {} + +const box = JSON.parse('{"items":[],"byName":{}}'); +box.items.push(new Day(Date.UTC(2020, 1, 29), "leap"), new Plain(0), new Date(1000), "text"); +box.byName.first = box.items[0]; + +function inspect(value) { + if (!(value instanceof Date)) return "not a date: " + value; + return [value.toISOString(), value.getTime(), value.getUTCDate(), value instanceof Day, value.toJSON()].join(" | "); +} +for (const item of box.items) console.log(inspect(item)); +console.log(JSON.stringify(box)); +console.log(box.byName.first.label, box.byName.first.getUTCFullYear(), String(box.items[1]).slice(0, 15)); +console.log(+box.items[0], box.items[0] - box.items[1], box.items[0] > box.items[2], `${box.items[1]}`.slice(0, 3)); + +const getTime = box.items[0].getTime; +console.log(getTime.call(box.items[1]), getTime.call(box.items[0]), typeof getTime); +const toISO = box.items[0].toISOString; +console.log(toISO.call(box.items[0])); +console.log(box.items[1].setTime(5000), box.items[1].getTime(), box.items[1].toISOString()); +try { + getTime.call({}); +} catch (error) { + console.log(error instanceof TypeError); +} +console.log(box.items); +console.log(new Date(box.items[0]).toISOString(), new Date(box.items[1]).getTime()); diff --git a/tests/corpus/7053-private-fields-untyped-receivers.mjs b/tests/corpus/7053-private-fields-untyped-receivers.mjs new file mode 100644 index 000000000..815f612b0 --- /dev/null +++ b/tests/corpus/7053-private-fields-untyped-receivers.mjs @@ -0,0 +1,72 @@ +// Private fields read and written through receivers whose type is known only +// at run time: static factories and helpers that take the instance as an +// argument, compound assignments and updates, `#x in value`, subclasses, and +// Node's TypeErrors for values that do not carry the field. +class Counter { + #count = 0; + #label = null; + constructor(label) { + this.#label = label; + } + static labeled(label, start) { + let counter = new Counter("pending"); + counter.#label = label; + counter.#count = start; + return counter; + } + static read(counter) { + return [counter.#label, counter.#count]; + } + static bump(counter, by) { + counter.#count += by; + counter.#count++; + ++counter.#count; + return counter.#count; + } + static clear(counter) { + counter.#label = null; + return counter; + } + static owns(value) { + return #count in value; + } + describe() { + return `${this.#label}:${this.#count}`; + } +} +class LimitedCounter extends Counter { + #limit = 3; + static limit(value) { + return value.#limit; + } +} + +const made = Counter.labeled("made", 5); +console.log(made.describe(), Counter.read(made), Counter.bump(made, 10), made.describe()); +const held = JSON.parse('{"list":[]}'); +held.list.push(new Counter("held"), new LimitedCounter("limited")); +for (const item of held.list) console.log(Counter.read(item), Counter.bump(item, 1), item.describe(), Counter.owns(item)); +console.log(LimitedCounter.limit(held.list[1]), Counter.clear(held.list[0]).describe()); +for (const value of [{}, [], null, undefined, 1, "text", held.list[0]]) { + try { + console.log(Counter.read(value)); + } catch (error) { + console.log("read", error instanceof TypeError, error.message); + } + try { + Counter.bump(value, 1); + console.log("bumped"); + } catch (error) { + console.log("bump", error instanceof TypeError, error.message); + } + try { + console.log(LimitedCounter.limit(value)); + } catch (error) { + console.log("limit", error instanceof TypeError, error.message); + } + try { + console.log("owns", Counter.owns(value)); + } catch (error) { + console.log("owns", error instanceof TypeError, error.message); + } +} diff --git a/tests/corpus/7054-let-bindings-with-null-writes.mjs b/tests/corpus/7054-let-bindings-with-null-writes.mjs new file mode 100644 index 000000000..c8ca26a9d --- /dev/null +++ b/tests/corpus/7054-let-bindings-with-null-writes.mjs @@ -0,0 +1,37 @@ +// `let` bindings initialized with a string, number or boolean and later +// assigned values that can be null or undefined. JavaScript files are +// checked without strict null checks, so the declared type of each binding +// is the primitive alone. +const PATTERN = /^(\d+)(?:\.(\d+))?([+-]\d\d:\d\d)?$/; +function parts(text) { + let offset = "Z"; + let fraction = 0; + let signed = false; + const match = text.match(PATTERN); + if (match) { + offset = match[3] || null; + fraction = match[2] ? +match[2] : undefined; + signed = match[3] ? match[3][0] === "-" : null; + } + return [offset, fraction, signed]; +} +console.log(parts("12"), parts("12.5"), parts("12.25-01:00"), parts("x")); + +function pick(flag) { + let name = "default"; + name = flag ? name.toUpperCase() : void 0; + let count = 1; + count = flag && count + 1; + let ready = true; + ready = flag === undefined ? undefined : !flag; + return [name, count, ready, typeof name, typeof count]; +} +console.log(pick(true), pick(false), pick(undefined)); + +let last = "start"; +const seen = []; +for (const value of ["a", null, "b", undefined]) { + last = value ?? null; + seen.push(last === null ? "null" : last.length); +} +console.log(seen, last); diff --git a/tests/corpus/7055-cipher-streams.ts b/tests/corpus/7055-cipher-streams.ts new file mode 100644 index 000000000..8f9e0d1ea --- /dev/null +++ b/tests/corpus/7055-cipher-streams.ts @@ -0,0 +1,222 @@ +// Cipheriv and Decipheriv as Transforms: pipeline() and stream/promises +// pipeline stages, pipe() chains, for await, write()/end() with 'data' +// events, setEncoding(), finished(), compose(), addAbortSignal(), +// stream/consumers, the stream properties, and the cipher's state after +// its stream flushed. A Hash reads through stream/consumers and for await +// the same way. +import * as crypto from "node:crypto"; +import { + PassThrough, + Readable, + Transform, + Writable, + addAbortSignal, + compose, + finished, + pipeline, +} from "node:stream"; +import { text } from "node:stream/consumers"; +import { pipeline as pipelinePromise } from "node:stream/promises"; + +const key = Buffer.alloc(32, 7); +const iv = Buffer.alloc(16, 3); + +function collector(into: Buffer[]): Writable { + return new Writable({ + write(chunk: Buffer, _enc: string, cb: () => void) { + into.push(chunk); + cb(); + }, + }); +} + +async function viaCallbackPipeline(): Promise { + const out: Buffer[] = []; + await new Promise((resolve) => { + pipeline( + Readable.from(["hello ", "cipher ", "streams"]), + crypto.createCipheriv("aes-256-cbc", key, iv), + crypto.createDecipheriv("aes-256-cbc", key, iv), + collector(out), + (err: Error | null) => { + console.log("callback pipeline:", err ?? null, Buffer.concat(out).toString()); + resolve(); + }, + ); + }); +} + +async function viaPromisePipeline(): Promise { + const hash = crypto.createHash("sha256"); + await pipelinePromise( + Readable.from([Buffer.from("abc"), Buffer.from("def")]), + crypto.createCipheriv("aes-256-ctr", key, iv), + new PassThrough(), + hash, + ); + console.log("promise pipeline digest:", hash.digest("hex")); +} + +async function viaPipeAndForAwait(): Promise { + const cipher = crypto.createCipheriv("aes-256-cbc", key, iv); + const decipher = crypto.createDecipheriv("aes-256-cbc", key, iv); + const chain = Readable.from(["piped ", "through ", "two ciphers"]).pipe(cipher).pipe(decipher); + let text = ""; + for await (const chunk of chain) text += chunk; + console.log("pipe + for await:", text); +} + +async function viaPipeIntoTransform(): Promise { + const cipher = crypto.createCipheriv("aes-256-cbc", key, iv); + const upper = new Transform({ + transform(chunk: Buffer, _enc: string, cb: (err: Error | null, data?: Buffer) => void) { + cb(null, Buffer.from(chunk.toString("hex").toUpperCase())); + }, + }); + const out = cipher.pipe(upper); + console.log("pipe answers its destination:", out === upper); + cipher.end("into a transform"); + let hex = ""; + for await (const chunk of out) hex += chunk; + console.log("pipe into transform:", hex); +} + +async function viaPipelineArgumentOrder(): Promise { + const order: string[] = []; + const source = (): string[] => { + order.push("source"); + return ["x", "y"]; + }; + const cipherStage = (): crypto.Cipheriv => { + order.push("cipher"); + return crypto.createCipheriv("aes-256-ctr", key, iv); + }; + const hash = crypto.createHash("sha256"); + await pipelinePromise( + source(), + async function* (src: AsyncIterable) { + for await (const chunk of src) yield chunk.toUpperCase(); + }, + cipherStage(), + hash, + ); + console.log("pipeline argument order:", order.join(" "), hash.digest("hex")); +} + +async function viaEvents(): Promise { + const cipher = crypto.createCipheriv("aes-128-cbc", Buffer.alloc(16, 1), Buffer.alloc(16, 2)); + cipher.setEncoding("hex"); + let hex = ""; + cipher.on("data", (chunk: string) => { + hex += chunk; + }); + await new Promise((resolve) => { + cipher.on("end", () => { + console.log("events:", typeof hex, hex); + resolve(); + }); + console.log("write returns:", cipher.write("first block of text")); + cipher.end("and the rest"); + }); + // The stream's flush ran final(): the cipher is finished. + try { + cipher.update("more"); + } catch (e) { + console.log("update after the stream:", (e as Error).message); + } + try { + cipher.final(); + } catch (e) { + console.log("final after the stream:", (e as NodeJS.ErrnoException).code, (e as Error).message); + } +} + +async function gcm(): Promise { + const gcmKey = Buffer.alloc(32, 9); + const nonce = Buffer.alloc(12, 4); + const enc = crypto.createCipheriv("aes-256-gcm", gcmKey, nonce); + const parts: Buffer[] = []; + enc.on("data", (chunk: Buffer) => parts.push(chunk)); + await new Promise((resolve) => { + enc.on("end", () => resolve()); + enc.end("authenticated message"); + }); + const tag = enc.getAuthTag(); + console.log("gcm tag length:", tag.length); + const dec = crypto.createDecipheriv("aes-256-gcm", gcmKey, nonce); + dec.setAuthTag(tag); + let plain = ""; + for await (const chunk of Readable.from([Buffer.concat(parts)]).pipe(dec)) plain += chunk; + console.log("gcm round trip:", plain); +} + +async function viaFinishedAndProperties(): Promise { + const c = crypto.createDecipheriv("aes-256-ctr", key, iv); + console.log("before:", c.readable, c.writable, c.writableEnded, c.destroyed, c.writableLength); + const done = new Promise((resolve) => { + finished(c, (err?: NodeJS.ErrnoException | null) => { + console.log("finished:", err ?? null, c.readableEnded, c.writableFinished); + resolve(); + }); + }); + const parts: string[] = []; + const reading = (async () => { + for await (const chunk of c) parts.push(chunk.toString("hex")); + })(); + c.write(Buffer.from("00112233", "hex")); + c.end(Buffer.from("44556677", "hex")); + console.log("ended:", c.writableEnded, c.writable); + await reading; + await done; + console.log("for await over the cipher:", parts.join("")); + await new Promise((resolve) => setImmediate(resolve)); + console.log("after close:", c.destroyed, c.closed); +} + +async function viaCompositions(): Promise { + const both = compose( + crypto.createCipheriv("aes-256-cbc", key, iv), + crypto.createDecipheriv("aes-256-cbc", key, iv), + ); + let composed = ""; + both.on("data", (chunk: Buffer) => { + composed += chunk.toString(); + }); + await new Promise((resolve) => { + both.on("end", () => resolve()); + both.end("composed"); + }); + console.log("compose:", composed); + + const ac = new AbortController(); + const aborted = addAbortSignal(ac.signal, crypto.createCipheriv("aes-256-ctr", key, iv)); + aborted.on("error", (e: Error) => console.log("addAbortSignal:", e.name)); + const closed = new Promise((resolve) => aborted.on("close", () => resolve())); + ac.abort(); + await closed; + console.log("aborted cipher destroyed:", aborted.destroyed); + + const sealed = crypto.createCipheriv("aes-256-ctr", key, iv).update("through consumers"); + const plain = await text(Readable.from([sealed]).pipe(crypto.createDecipheriv("aes-256-ctr", key, iv))); + console.log("consumers text:", plain); + + const hash = crypto.createHash("sha1"); + hash.setEncoding("hex"); + console.log("hash text:", await text(Readable.from(["abc"]).pipe(hash))); + const md5 = crypto.createHash("md5"); + md5.end("xyz"); + for await (const digest of md5) console.log("hash for await:", (digest as Buffer).toString("hex")); +} + +async function main(): Promise { + await viaFinishedAndProperties(); + await viaCompositions(); + await viaCallbackPipeline(); + await viaPromisePipeline(); + await viaPipeAndForAwait(); + await viaPipeIntoTransform(); + await viaPipelineArgumentOrder(); + await viaEvents(); + await gcm(); +} +main(); diff --git a/tests/corpus/7056-cipher-stream-errors.ts b/tests/corpus/7056-cipher-stream-errors.ts new file mode 100644 index 000000000..e3e653091 --- /dev/null +++ b/tests/corpus/7056-cipher-stream-errors.ts @@ -0,0 +1,111 @@ +// Cipher stream errors, close ordering and backpressure: a bad decrypt +// through pipeline() destroys every stage with the same error, a failed +// GCM authentication reaches 'error' after the data, destroy() closes the +// cipher's stream, and write() reports the high-water mark with 'drain'. +import * as crypto from "node:crypto"; +import { Readable, Writable, pipeline } from "node:stream"; + +const key = Buffer.alloc(32, 5); +const iv = Buffer.alloc(16, 6); + +function sealed(text: string): Buffer { + const c = crypto.createCipheriv("aes-256-cbc", key, iv); + return Buffer.concat([c.update(text), c.final()]); +} + +async function badDecrypt(): Promise { + const log: string[] = []; + const source = Readable.from([sealed("secret message")]); + const decipher = crypto.createDecipheriv("aes-256-cbc", Buffer.alloc(32, 8), iv); + const sink = new Writable({ + write(_chunk: Buffer, _enc: string, cb: () => void) { + cb(); + }, + }); + source.on("close", () => log.push("source close")); + decipher.on("error", (e: NodeJS.ErrnoException) => log.push(`decipher error ${e.code}`)); + decipher.on("close", () => log.push("decipher close")); + sink.on("error", (e: NodeJS.ErrnoException) => log.push(`sink error ${e.code}`)); + sink.on("close", () => log.push("sink close")); + await new Promise((resolve) => { + pipeline(source, decipher, sink, (err: NodeJS.ErrnoException | null) => { + log.push(`callback ${err?.code} ${err?.message}`); + setImmediate(() => { + console.log(log.join("\n")); + console.log("destroyed:", source.destroyed, decipher.destroyed, sink.destroyed); + resolve(); + }); + }); + }); +} + +async function gcmWithoutTag(): Promise { + const d = crypto.createDecipheriv("aes-256-gcm", key, Buffer.alloc(12)); + await new Promise((resolve) => { + d.on("data", (chunk: Buffer) => console.log("gcm data", chunk.length)); + d.on("error", (e: Error) => console.log("gcm error:", e.message)); + d.on("close", () => { + console.log("gcm close"); + resolve(); + }); + d.end(Buffer.alloc(5)); + }); +} + +async function destroyMidway(): Promise { + const c = crypto.createCipheriv("aes-256-ctr", key, iv); + await new Promise((resolve) => { + c.on("data", (chunk: Buffer) => { + console.log("ctr data", chunk.length); + c.destroy(new Error("stop")); + }); + c.on("error", (e: Error) => console.log("ctr error:", e.message)); + c.on("close", () => { + console.log("ctr close, destroyed:", c.destroyed); + resolve(); + }); + c.write("0123456789"); + c.write("abcdef"); + }); +} + +async function backpressure(): Promise { + const c = crypto.createCipheriv("aes-256-ctr", key, iv); + let received = 0; + const slow = new Writable({ + highWaterMark: 1024, + write(chunk: Buffer, _enc: string, cb: () => void) { + received += chunk.length; + setImmediate(cb); + }, + }); + c.pipe(slow); + const block = Buffer.alloc(4096, 1); + let writes = 0; + let fullAt = -1; + while (writes < 64) { + writes++; + if (!c.write(block)) { + fullAt = writes; + break; + } + } + console.log("write returned false at", fullAt); + await new Promise((resolve) => c.once("drain", () => resolve())); + console.log("drained"); + await new Promise((resolve) => { + slow.on("finish", () => { + console.log("received", received); + resolve(); + }); + c.end(); + }); +} + +async function main(): Promise { + await badDecrypt(); + await gcmWithoutTag(); + await destroyMidway(); + await backpressure(); +} +main(); diff --git a/tests/corpus/7057-cipher-streams.mjs b/tests/corpus/7057-cipher-streams.mjs new file mode 100644 index 000000000..2173d29aa --- /dev/null +++ b/tests/corpus/7057-cipher-streams.mjs @@ -0,0 +1,85 @@ +// Cipheriv and Decipheriv streams from JavaScript: pipeline() and pipe() +// with cipher stages, a cipher passed through untyped helpers that call +// its stream members dynamically, and cipher stages that reach pipeline() +// through an untyped parameter. +import crypto from "node:crypto"; +import { pipeline, Readable, Writable } from "node:stream"; + +const key = Buffer.alloc(24, 1); +const iv = Buffer.alloc(16, 2); + +function attach(stream, label, log) { + stream.on("data", (chunk) => log.push(`${label} data ${chunk.length}`)); + stream.on("end", () => log.push(`${label} end`)); + stream.on("close", () => log.push(`${label} close`)); + return stream; +} + +function feed(stream, parts) { + for (const part of parts) stream.write(part); + stream.end(); +} + +function state(stream) { + return [stream.readable, stream.writable, stream.writableEnded, stream.destroyed, stream.readableLength].join(","); +} + +const log = []; +const cipher = attach(crypto.createCipheriv("aes-192-cbc", key, iv), "cipher", log); +const collected = []; +cipher.on("data", (chunk) => collected.push(chunk)); +cipher.on("end", () => { + console.log("state at end:", state(cipher)); + const sealed = Buffer.concat(collected); + const out = []; + pipeline( + Readable.from([sealed.subarray(0, 7), sealed.subarray(7)]), + crypto.createDecipheriv("aes-192-cbc", key, iv), + new Writable({ + write(chunk, enc, cb) { + out.push(chunk); + cb(); + }, + }), + (err) => { + console.log(log.join("\n")); + console.log("pipeline:", err ?? null, Buffer.concat(out).toString()); + const piped = Readable.from([sealed]).pipe(crypto.createDecipheriv("aes-192-cbc", key, iv)); + piped.setEncoding("utf8"); + let text = ""; + piped.on("data", (s) => (text += s)); + piped.on("end", () => { + console.log("pipe:", text); + throughHelper(sealed); + }); + }, + ); +}); + +// The stages arrive as untyped values. +function run(stages, done) { + const out = []; + pipeline( + stages[0], + stages[1], + new Writable({ + write(chunk, enc, cb) { + out.push(chunk); + cb(); + }, + }), + (err) => done(err, Buffer.concat(out)), + ); +} + +function throughHelper(sealed) { + run([Readable.from([sealed]), crypto.createDecipheriv("aes-192-cbc", key, iv)], (err, plain) => { + console.log("untyped stage:", err ?? null, plain.toString()); + run([Readable.from([sealed]), crypto.createDecipheriv("aes-192-cbc", Buffer.alloc(24, 9), iv)], (err2) => { + console.log("untyped stage, wrong key:", err2.code, err2.message); + }); + }); +} +console.log("state before:", state(cipher)); +feed(cipher, ["one ", "two ", "three"]); +console.log("state after end():", state(cipher)); diff --git a/tests/corpus/7058-pipeline-function-stages.mjs b/tests/corpus/7058-pipeline-function-stages.mjs new file mode 100644 index 000000000..f75abac39 --- /dev/null +++ b/tests/corpus/7058-pipeline-function-stages.mjs @@ -0,0 +1,180 @@ +// pipeline() function stages from JavaScript: runs of async generator +// stages between streams, stages named by a function declaration and a +// const, sources that are arrays, strings, synchronous generators and +// generator functions (with the ticks Node's async-from-sync iteration +// takes), the string and Buffer methods of generator-fed chunks, and an +// error thrown in a stage after two streams. +import { pipeline, PassThrough, Transform, Writable } from "node:stream"; +import { pipeline as pipelinePromise } from "node:stream/promises"; +import zlib from "node:zlib"; + +function sink(into) { + return new Writable({ + write(chunk, enc, cb) { + into.push(chunk.toString()); + cb(); + }, + }); +} + +async function* upper(source) { + for await (const chunk of source) yield chunk.toString().toUpperCase(); +} + +const bracket = async function* (source) { + for await (const chunk of source) yield `[${chunk.trim().replaceAll("\n", "|")}]`; +}; + +function* letters() { + yield "a"; + yield "b"; + yield "c"; +} + +// Stages on both sides of two zlib streams, and a named stage. +{ + const out = []; + await pipelinePromise( + async function* () { + for (let i = 0; i < 3; i++) yield `line ${i}\n`; + }, + zlib.createGzip(), + zlib.createGunzip(), + upper, + bracket, + sink(out), + ); + console.log("split runs:", out.join("")); +} + +// Iterable sources, and the destination value that reaches the callback. +await new Promise((resolve) => { + pipeline( + ["x", "y", "z"], + zlib.createDeflate(), + zlib.createInflate(), + async function (source) { + let text = ""; + for await (const chunk of source) text += chunk; + return text; + }, + (err, value) => { + console.log("array source:", err ?? null, value); + resolve(undefined); + }, + ); +}); +{ + const out = []; + await pipelinePromise("str", upper, sink(out)); + console.log("string source:", out.join(",")); + out.length = 0; + await pipelinePromise(letters, upper, sink(out)); + console.log("generator function source:", out.join(",")); + out.length = 0; + await pipelinePromise(letters(), new PassThrough(), sink(out)); + console.log("generator source:", out.join(",")); +} + +// Generator-fed chunks keep their string and Buffer methods. +{ + const out = []; + await pipelinePromise( + async function* () { + yield Buffer.from("buf"); + yield Buffer.from("fers"); + }, + async function* (source) { + for await (const chunk of source) yield chunk.toString("hex"); + }, + async function* (source) { + for await (const chunk of source) yield chunk.padStart(10, "-"); + }, + sink(out), + ); + console.log("chunk methods:", out.join(" ")); +} + +// The ticks of iterable sources match Node's for-await over them. +function ticker(log) { + let on = true; + (async () => { + for (let i = 0; on && i < 12; i++) { + log.push(`t${i}`); + await null; + } + })(); + return () => { + on = false; + }; +} +{ + const log = []; + const stop = ticker(log); + await new Promise((resolve) => + pipeline(["a", "b"], new PassThrough(), sink(log), () => { + stop(); + resolve(undefined); + }), + ); + console.log("array ticks:", log.join(" ")); +} +{ + const log = []; + const stop = ticker(log); + await new Promise((resolve) => + pipeline( + letters, + async function* (source) { + for await (const chunk of source) { + log.push(`stage ${chunk}`); + yield chunk; + } + }, + sink(log), + () => { + stop(); + resolve(undefined); + }, + ), + ); + console.log("generator function ticks:", log.join(" ")); +} + +// An error thrown in a stage after two streams destroys both with it. +{ + const log = []; + const first = new PassThrough(); + const second = new Transform({ + transform(chunk, enc, cb) { + cb(null, chunk.toString().toUpperCase()); + }, + }); + first.on("close", () => log.push("first close")); + second.on("close", () => log.push("second close")); + second.on("error", (e) => log.push(`second error ${e.name}`)); + await new Promise((resolve) => { + pipeline( + async function* () { + yield "one\n"; + yield "two\n"; + }, + first, + second, + async function* (source) { + for await (const chunk of source) { + log.push(`stage got ${JSON.stringify(chunk)}`); + if (chunk.length > 100) yield chunk; + throw new Error("stage failed"); + } + }, + sink([]), + (err) => { + log.push(`callback ${err.message}`); + setImmediate(resolve); + }, + ); + }); + console.log(log.join("\n")); + console.log("destroyed:", first.destroyed, second.destroyed); +} diff --git a/tests/corpus/7059-transform-backpressure.ts b/tests/corpus/7059-transform-backpressure.ts new file mode 100644 index 000000000..d19a41eb8 --- /dev/null +++ b/tests/corpus/7059-transform-backpressure.ts @@ -0,0 +1,90 @@ +// Transform write backpressure and typed pipeline stages. A Transform +// holds a write's callback while its readable side is at the high-water +// mark, so write() returns false once both buffers fill and 'drain' comes +// after the reader catches up. Typed stages: named async generator +// functions on both sides of zlib streams, an array source, and an async +// function destination whose value resolves the promise pipeline. +import { PassThrough, Transform, Writable } from "node:stream"; +import { pipeline } from "node:stream/promises"; +import * as zlib from "node:zlib"; + +class Copy extends Transform { + override _transform(chunk: Buffer, _enc: BufferEncoding, cb: (err?: Error | null) => void): void { + this.push(chunk); + cb(); + } +} + +async function measure(label: string, t: Transform): Promise { + let received = 0; + const slow = new Writable({ + highWaterMark: 1024, + write(chunk: Buffer, _enc: string, cb: () => void) { + received += chunk.length; + setImmediate(cb); + }, + }); + t.pipe(slow); + const block = Buffer.alloc(4096, 120); + let falseAt = -1; + for (let i = 1; i <= 64; i++) { + if (!t.write(block)) { + falseAt = i; + break; + } + } + console.log(label, "write() false at", falseAt, t.writableLength, t.readableLength); + await new Promise((resolve) => t.once("drain", () => resolve())); + console.log(label, "drained", t.writableLength); + await new Promise((resolve) => { + slow.on("finish", () => resolve()); + t.end(); + }); + console.log(label, "received", received); +} + +async function* numbered(): AsyncGenerator { + for (let i = 0; i < 4; i++) yield `row ${i}\n`; +} + +async function* shout(source: AsyncIterable): AsyncGenerator { + for await (const chunk of source) yield chunk.toString().toUpperCase(); +} + +async function count(source: AsyncIterable): Promise { + let n = 0; + for await (const chunk of source) n += chunk.split("\n").length - 1; + return n; +} + +async function main(): Promise { + await measure("passthrough", new PassThrough()); + await measure("subclass", new Copy()); + await measure( + "options", + new Transform({ + transform(chunk: Buffer, _enc: string, cb: (err?: Error | null, data?: Buffer) => void) { + cb(null, chunk); + }, + }), + ); + + const out: string[] = []; + await pipeline( + numbered, + zlib.createGzip(), + zlib.createGunzip(), + shout, + new Writable({ + write(chunk: Buffer, _enc: string, cb: () => void) { + out.push(chunk.toString()); + cb(); + }, + }), + ); + console.log("named stages:", JSON.stringify(out.join(""))); + + const rows = await pipeline(["a\n", "b\n", "c\n"], zlib.createGzip(), zlib.createGunzip(), shout, count); + console.log("array source, rows:", rows); +} +main(); diff --git a/tests/corpus/7080-crypto-ed25519.mjs b/tests/corpus/7080-crypto-ed25519.mjs new file mode 100644 index 000000000..355d98225 --- /dev/null +++ b/tests/corpus/7080-crypto-ed25519.mjs @@ -0,0 +1,34 @@ +// Ed25519 KeyObjects in node:crypto: the RFC 8032 test 1 key through +// PKCS#8, SubjectPublicKeyInfo and JWK export and import, its deterministic +// signatures from crypto.sign and crypto.verify, generateKeyPairSync, the +// two-argument generateKeyPair callback, and Node's errors for digests, +// Sign objects and the RSA and EC key encodings. +import * as c from "node:crypto"; +const t = (l, f) => { try { const v = f(); console.log(l, "=>", typeof v === "object" && v !== null && !Buffer.isBuffer(v) ? JSON.stringify(v) : Buffer.isBuffer(v) ? v.toString("hex") : String(v).slice(0, 200)); } catch (e) { console.log(l, "!!", e.name, e.code, e.message); } }; +const seed = Buffer.from("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", "hex"); +const der = Buffer.concat([Buffer.from("302e020100300506032b657004220420", "hex"), seed]); +const k = c.createPrivateKey({ key: der, format: "der", type: "pkcs8" }); +const p = c.createPublicKey(k); +t("type", () => [k.type, k.asymmetricKeyType, JSON.stringify(k.asymmetricKeyDetails), p.type].join()); +t("pkcs8 pem", () => k.export({ type: "pkcs8", format: "pem" })); +t("spki pem", () => p.export({ type: "spki", format: "pem" })); +t("spki der", () => p.export({ type: "spki", format: "der" })); +t("jwk priv", () => k.export({ format: "jwk" })); +t("jwk pub", () => p.export({ format: "jwk" })); +t("sig empty", () => c.sign(null, Buffer.alloc(0), k)); +t("sig abc", () => c.sign(undefined, Buffer.from("abc"), k)); +t("verify", () => c.verify(null, Buffer.from("abc"), p, c.sign(null, Buffer.from("abc"), k))); +t("verify bad", () => c.verify(null, Buffer.from("abd"), p, c.sign(null, Buffer.from("abc"), k))); +t("sign sha256", () => c.sign("sha256", Buffer.from("abc"), k)); +t("createSign", () => c.createSign("sha256").update("x").sign(k)); +t("pkcs1 export", () => k.export({ type: "pkcs1", format: "pem" })); +t("sec1 export", () => k.export({ type: "sec1", format: "pem" })); +t("gen cb form", () => { c.generateKeyPair("ed25519", (e, pub, priv) => console.log("cb", e, pub.asymmetricKeyType, priv.type)); return "scheduled"; }); +t("gen", () => { const g = c.generateKeyPairSync("ed25519"); return [g.publicKey.asymmetricKeyType, Object.keys(g).join()].join(); }); +t("gen opts", () => { const g = c.generateKeyPairSync("ed25519", { publicKeyEncoding: { type: "spki", format: "der" } }); return g.publicKey.length; }); +t("jwk import", () => c.createPrivateKey({ key: k.export({ format: "jwk" }), format: "jwk" }).equals(k)); +t("jwk pub import", () => c.createPublicKey({ key: p.export({ format: "jwk" }), format: "jwk" }).equals(p)); +t("dsaEncoding", () => c.sign(null, Buffer.from("x"), { key: k, dsaEncoding: "ieee-p1363" }).length); +t("verify short sig", () => c.verify(null, Buffer.from("x"), p, Buffer.alloc(10))); +t("pem parse", () => c.createPrivateKey(k.export({ type: "pkcs8", format: "pem" })).equals(k)); +t("equals ec", () => k.equals(c.generateKeyPairSync("ec", { namedCurve: "P-256" }).privateKey)); diff --git a/tests/corpus/7081-webcrypto-ed25519.mjs b/tests/corpus/7081-webcrypto-ed25519.mjs new file mode 100644 index 000000000..5cf7728f1 --- /dev/null +++ b/tests/corpus/7081-webcrypto-ed25519.mjs @@ -0,0 +1,39 @@ +// WebCrypto Ed25519: the RFC 8032 test 1 key imported from pkcs8, jwk and +// raw, its deterministic signatures, verify, generateKey, every export +// format, and Node's DOMExceptions for usages, raw private export, short +// raw keys and mismatched JWK members. + +const t = async (label, fn) => { try { const v = await fn(); console.log(label, "=>", v instanceof ArrayBuffer ? Buffer.from(v).toString("hex") : typeof v === "object" && v !== null ? JSON.stringify(v) : v); } catch (e) { console.log(label, "!!", e.name, e.code, e.message); } }; +const seed = Buffer.from("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", "hex"); +const pkcs8 = Buffer.concat([Buffer.from("302e020100300506032b657004220420", "hex"), seed]); +const priv = await crypto.subtle.importKey("pkcs8", pkcs8, { name: "Ed25519" }, true, ["sign"]); +await t("algorithm", () => [JSON.stringify(priv.algorithm), priv.type, priv.usages.join(), priv.extractable].join(" ")); +await t("sign empty", () => crypto.subtle.sign("Ed25519", priv, new Uint8Array(0))); +await t("sign abc", () => crypto.subtle.sign({ name: "Ed25519" }, priv, new TextEncoder().encode("abc"))); +await t("jwk priv", () => crypto.subtle.exportKey("jwk", priv)); +await t("pkcs8 back", async () => Buffer.from(await crypto.subtle.exportKey("pkcs8", priv)).equals(pkcs8)); +const jwk = await crypto.subtle.exportKey("jwk", priv); +const pubJwk = { kty: jwk.kty, crv: jwk.crv, x: jwk.x }; +const pub = await crypto.subtle.importKey("jwk", pubJwk, "Ed25519", true, ["verify"]); +await t("raw pub", () => crypto.subtle.exportKey("raw", pub)); +await t("spki pub", () => crypto.subtle.exportKey("spki", pub)); +await t("jwk pub", () => crypto.subtle.exportKey("jwk", pub)); +const sig = await crypto.subtle.sign("Ed25519", priv, new TextEncoder().encode("abc")); +await t("verify", () => crypto.subtle.verify("Ed25519", pub, sig, new TextEncoder().encode("abc"))); +await t("verify bad", () => crypto.subtle.verify("Ed25519", pub, sig, new TextEncoder().encode("abd"))); +await t("verify short", () => crypto.subtle.verify("Ed25519", pub, new Uint8Array(10), new TextEncoder().encode("abc"))); +const rawImported = await crypto.subtle.importKey("raw", await crypto.subtle.exportKey("raw", pub), { name: "Ed25519" }, false, ["verify"]); +await t("raw import verify", () => crypto.subtle.verify("Ed25519", rawImported, sig, new TextEncoder().encode("abc"))); +const pair = await crypto.subtle.generateKey({ name: "Ed25519" }, true, ["sign", "verify"]); +await t("generated", async () => [pair.privateKey.usages.join(), pair.publicKey.usages.join(), pair.publicKey.extractable, (await crypto.subtle.exportKey("raw", pair.publicKey)).byteLength, await crypto.subtle.verify("Ed25519", pair.publicKey, await crypto.subtle.sign("Ed25519", pair.privateKey, new Uint8Array([1])), new Uint8Array([1]))].join(" ")); +await t("raw private", () => crypto.subtle.exportKey("raw", pair.privateKey)); +await t("bad usage", () => crypto.subtle.generateKey({ name: "Ed25519" }, true, ["encrypt"])); +await t("verify only", () => crypto.subtle.generateKey("Ed25519", true, ["verify"])); +await t("raw short", () => crypto.subtle.importKey("raw", new Uint8Array(31), { name: "Ed25519" }, true, ["verify"])); +await t("raw sign usage", () => crypto.subtle.importKey("raw", new Uint8Array(32), "Ed25519", true, ["sign"])); +await t("jwk alg EdDSA", async () => (await crypto.subtle.importKey("jwk", { ...pubJwk, alg: "EdDSA" }, "Ed25519", true, ["verify"])).type); +await t("jwk alg bad", () => crypto.subtle.importKey("jwk", { ...pubJwk, alg: "RS256" }, "Ed25519", true, ["verify"])); +await t("jwk crv bad", () => crypto.subtle.importKey("jwk", { ...pubJwk, crv: "Ed448" }, "Ed25519", true, ["verify"])); +await t("jwk kty bad", () => crypto.subtle.importKey("jwk", { ...pubJwk, kty: "EC" }, "Ed25519", true, ["verify"])); +await t("ecdsa key as ed", async () => { const e = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign", "verify"]); return crypto.subtle.importKey("spki", await crypto.subtle.exportKey("spki", e.publicKey), "Ed25519", true, ["verify"]); }); +await t("sign wrong alg", () => crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, priv, new Uint8Array(1))); diff --git a/tests/corpus/7082-crypto-key-objects.ts b/tests/corpus/7082-crypto-key-objects.ts new file mode 100644 index 000000000..816dd6be0 --- /dev/null +++ b/tests/corpus/7082-crypto-key-objects.ts @@ -0,0 +1,132 @@ +// Private and public KeyObjects: createPrivateKey and createPublicKey from +// PEM, DER, JWK, a private KeyObject and a certificate; the type, +// asymmetricKeyType and asymmetricKeyDetails getters; export() as PKCS#1, +// SEC1, PKCS#8, SubjectPublicKeyInfo, DER and JWK; equals(); instanceof; +// and Node's errors for invalid options and inputs, including a private or +// public key passed to createHmac. +import * as crypto from "node:crypto"; + +const RSA = `-----BEGIN RSA PRIVATE KEY----- +MIICWwIBAAKBgQDWei4BREJm+4C6u/+F4NI7kTOQ9gf/a+Ecd2SZxfpXRtXT0QVN +MAI1uQNmB4abYzvd1G2V2XKsTJFJcJWibjAz56UxtxxggTpSAalFZYoPm6HfabwJ +b/YWh0K0OrNFvdkeXLLMiHQsxmIQ2lrFoycQEpZ4/yxjLe6LQF+L79k2ywIDAQAB +AoGAMWS/9ZC3zim7ssWbCkUFhaxh+M+AdgVtOXYRmAxtI+5vTjHEC8uzppWuP7Aa +Au0um17RwgHrE90qVIR2IYtI1C9K9RLUNlKKVPqnSSmr0qkXR246R/Zd8eho1XSS +MX6KmnbmRijUx9Rw1AbD2ZmYCrXsPf2HsCdH+SGQ1ZTunnECQQD090dTA21Jyu/b +ADglqgixJCPIoc6qpxst+W1LreIo4UvkSmgnRYvsKDlM7FNI+6f7igI625KXIAnl +xVlmGLXDAkEA4CNVeP07fmQUBs1aPQ9LCOvN42SV6S8Fjbf4XHIYG5Kp48/98oJj +1pFsXNa8nn8fmN9zFw8yM/yd22iZdueCWQJAWMja//po/OrhniVpNDV5awKnOYtz +xSRF1JbnhxthseFeSUKylzE8sn4trnSlBvm2+5MclcqJSd7h13Z8nWVtUwJAZ0SA +Ve0+ov4TKAsnH2jTZnnWc4VdeIFcqq3vdRBwQQvy0G59D2W6ABsidSfO4auqcDHL +gf1TYRZr2LI5usnxiQJAGt3e0QC0q0WN4p49YhyXXVuHccx79RFgfN7V1lkAyYuL +2bPV41mEtD/AbSrObtqqvOaWZjwSr8JCyPdPZZAIMw== +-----END RSA PRIVATE KEY----- +`; +const EC = `-----BEGIN EC PRIVATE KEY----- +MHcCAQEEILpVcXOEZQXpH/q3ec3AsLg4x4Bld6uZLqDC56OYKQK4oAoGCCqGSM49 +AwEHoUQDQgAE0gwi0a/4kuVxjsO3vw79rT3QSxnPY7sooVlI+ENq35D7meWZv/dp +FTGFte7Bd8lFxaZ10dMo0tl++AOtt7umPg== +-----END EC PRIVATE KEY----- +`; +const EC384 = `-----BEGIN EC PRIVATE KEY----- +MIGkAgEBBDDer7W8pQD96zdS8UWxg34nMTxqREszwP6niYYOdw75LHPmHFKWeMKW +dmG6d3n4bRugBwYFK4EEACKhZANiAATIQKDRVJ501CTQtbK2IslxdO8Oma2ZU4ee +GRuQFg6ajhKXa0iCU5o9rpdObfCecyiYApdtVpahD2SwPua5CZyq/0jUn9frwKtB +uEeB/3T/yYRCD4zGUc7TtUDh8c7Gt5c= +-----END EC PRIVATE KEY----- +`; +const CERT = `-----BEGIN CERTIFICATE----- +MIIDuzCCAqOgAwIBAgIPAPAN+s4AESIzRFVmd4iZMA0GCSqGSIb3DQEBDAUAMIGc +MQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNU2Fu +IEZyYW5jaXNjbzEUMBIGA1UECgwLRXhhbXBsZSBPcmcxETAPBgNVBAsMCERldiBU +ZWFtMRgwFgYDVQQDDA9FeGFtcGxlIFJvb3QgQ0ExHTAbBgkqhkiG9w0BCQEWDmNh +QGV4YW1wbGUuY29tMB4XDTI2MTAyMTE2MzM1MloXDTM2MTAxODE2MzM1MlowJzER +MA8GA1UECgwITGVhZiBPcmcxEjAQBgNVBAMMCWxvY2FsaG9zdDBZMBMGByqGSM49 +AgEGCCqGSM49AwEHA0IABJVfVy9EH/VHQuRqpFFnXk0F00ncDht6APgVPDoybK8H +PlcM4T5H1yAOMHnlH29LK1jtMqU1aAOiiQRzPdCvqoujggE3MIIBMzAJBgNVHRME +AjAAMGgGA1UdEQRhMF+CCWxvY2FsaG9zdIINKi5leGFtcGxlLmNvbYcEfwAAAYcQ +AAAAAAAAAAAAAAAAAAAAAYERYWRtaW5AZXhhbXBsZS5jb22GGGh0dHBzOi8vZXhh +bXBsZS5jb20vcGF0aDBdBggrBgEFBQcBAQRRME8wIwYIKwYBBQUHMAGGF2h0dHA6 +Ly9vY3NwLmV4YW1wbGUuY29tMCgGCCsGAQUFBzAChhxodHRwOi8vY2EuZXhhbXBs +ZS5jb20vY2EuY3J0MB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAdBgNV +HQ4EFgQUdKIx6ULFLPNP/kzwUFjSa5D19RswHwYDVR0jBBgwFoAUP+yQyItpNYEl +s26Jfv+NnciGaK8wDQYJKoZIhvcNAQEMBQADggEBABmQ8f2VsXNaMM9X1MEhi27D +LjwcOaaGEINNZq7xu/HL6UljMb1Odsuz66DkiH3Exd3MrWy6OlOpJJF0VzsqMsoD +0CRBxXF28o6Jil3vOGVwlYNmRidpkAkj4VyWDvv8FCS9VbsBtXaSHwu9wcCwePE0 +cGJRfTKoZ6KJ8vQ57DBEZ/ZszuhehOZYqrTmoUdjZ123kXdxQvK+ALn4SlIXHBhN +9unhd+8i00EmkXO/REw8paMcMVVGR+ioOEjyNHqZo6vkRqgpKggn1Yq8cTTDOMnS +P1o42EQZLlbuvx0kqInBqwqjDx4nZiPaifoDc9BF6iZPBvm8dhrEfghfB1tkNk0= +-----END CERTIFICATE----- +`; + +function attempt(label: string, run: () => unknown): void { + try { + const value = run(); + console.log(label, typeof value === "string" ? JSON.stringify(value) : value); + } catch (e) { + const err = e as NodeJS.ErrnoException; + console.log(label, "throws", err.name, err.code, err.message); + } +} + +const rsa = crypto.createPrivateKey(RSA); +const ec = crypto.createPrivateKey(Buffer.from(EC)); +const ec384 = crypto.createPrivateKey({ key: EC384, format: "pem" }); +const rsaPublic = crypto.createPublicKey(rsa); +const ecPublic = crypto.createPublicKey(EC); +const certPublic = crypto.createPublicKey(CERT); +const keys: [string, crypto.KeyObject][] = [ + ["rsa", rsa], + ["ec", ec], + ["ec384", ec384], + ["rsaPublic", rsaPublic], + ["ecPublic", ecPublic], + ["certPublic", certPublic], +]; +for (const [label, key] of keys) { + console.log(label, key.type, key.asymmetricKeyType, key.asymmetricKeyDetails, key instanceof crypto.KeyObject); +} + +attempt("pkcs1", () => rsa.export({ type: "pkcs1", format: "pem" }) === RSA + "\n"); +attempt("sec1", () => ec.export({ type: "sec1", format: "pem" }) === EC + "\n"); +attempt("rsa pkcs8", () => rsa.export({ type: "pkcs8", format: "pem" })); +attempt("ec pkcs8", () => ec.export({ type: "pkcs8", format: "pem" })); +attempt("rsa spki", () => rsaPublic.export({ type: "spki", format: "pem" })); +attempt("rsa public pkcs1", () => rsaPublic.export({ type: "pkcs1", format: "pem" })); +attempt("ec spki", () => ecPublic.export({ type: "spki", format: "pem" })); +attempt("cert spki", () => certPublic.export({ type: "spki", format: "pem" })); +attempt("der", () => (rsa.export({ type: "pkcs8", format: "der" }) as Buffer).toString("base64")); +attempt("ec jwk", () => JSON.stringify(ec.export({ format: "jwk" }))); +attempt("ec384 public jwk", () => JSON.stringify(crypto.createPublicKey(ec384).export({ format: "jwk" }))); +attempt("rsa jwk", () => JSON.stringify(rsa.export({ format: "jwk" }))); +attempt("rsa public jwk", () => JSON.stringify(rsaPublic.export({ format: "jwk" }))); + +// Round trips through DER and JWK. +const der = rsa.export({ type: "pkcs1", format: "der" }) as Buffer; +attempt("from der", () => crypto.createPrivateKey({ key: der, format: "der", type: "pkcs1" }).equals(rsa)); +const spki = ecPublic.export({ type: "spki", format: "der" }) as Buffer; +attempt("public from der", () => crypto.createPublicKey({ key: spki, format: "der", type: "spki" }).equals(ecPublic)); +attempt("from jwk", () => crypto.createPrivateKey({ key: ec.export({ format: "jwk" }), format: "jwk" }).equals(ec)); +attempt("rsa from jwk", () => crypto.createPrivateKey({ key: rsa.export({ format: "jwk" }), format: "jwk" }).equals(rsa)); +attempt("public from jwk", () => crypto.createPublicKey({ key: rsaPublic.export({ format: "jwk" }), format: "jwk" }).equals(rsaPublic)); +attempt("pkcs8 parse", () => crypto.createPrivateKey(ec.export({ type: "pkcs8", format: "pem" })).equals(ec)); +attempt("equals", () => [rsaPublic.equals(crypto.createPublicKey(RSA)), ec.equals(ecPublic), ec.equals(ec384)].join()); +attempt("tag", () => Object.prototype.toString.call(rsa)); + +// Errors. +attempt("export no options", () => rsa.export()); +attempt("export no format", () => rsa.export({} as crypto.AsymmetricKeyExportOptions<"pem">)); +attempt("export no type", () => rsa.export({ format: "pem" } as crypto.AsymmetricKeyExportOptions<"pem">)); +attempt("export spki private", () => rsa.export({ type: "spki", format: "pem" })); +attempt("export sec1 rsa", () => rsa.export({ type: "sec1", format: "pem" })); +attempt("export pkcs1 ec", () => ec.export({ type: "pkcs1", format: "der" })); +attempt("export pkcs8 public", () => ecPublic.export({ type: "pkcs8", format: "pem" })); +attempt("private from public pem", () => crypto.createPrivateKey(ecPublic.export({ type: "spki", format: "pem" }) as string)); +attempt("private from garbage", () => crypto.createPrivateKey("not a key")); +attempt("public from public", () => crypto.createPublicKey(ecPublic)); +attempt("der without type", () => crypto.createPrivateKey({ key: der, format: "der" } as crypto.PrivateKeyInput)); +attempt("hmac private key", () => crypto.createHmac("sha256", rsa)); +attempt("hmac public key", () => crypto.createHmac("sha256", ecPublic)); +// Last: OpenSSL keeps an error queued after comparing keys of different +// types, which a later call in Node can report. +attempt("equals other type", () => rsa.equals(ec)); diff --git a/tests/corpus/7083-crypto-sign-verify.ts b/tests/corpus/7083-crypto-sign-verify.ts new file mode 100644 index 000000000..4f6b86e72 --- /dev/null +++ b/tests/corpus/7083-crypto-sign-verify.ts @@ -0,0 +1,88 @@ +// crypto.sign and crypto.verify, and the Sign and Verify objects: RSA +// PKCS#1 v1.5 signatures (deterministic, so they compare with Node), RSA-PSS, +// ECDSA in DER and IEEE P1363 encodings, keys given as KeyObjects, PEM and +// option objects, output and signature encodings, and Node's errors. +import * as crypto from "node:crypto"; + +const RSA = `-----BEGIN RSA PRIVATE KEY----- +MIICWwIBAAKBgQDWei4BREJm+4C6u/+F4NI7kTOQ9gf/a+Ecd2SZxfpXRtXT0QVN +MAI1uQNmB4abYzvd1G2V2XKsTJFJcJWibjAz56UxtxxggTpSAalFZYoPm6HfabwJ +b/YWh0K0OrNFvdkeXLLMiHQsxmIQ2lrFoycQEpZ4/yxjLe6LQF+L79k2ywIDAQAB +AoGAMWS/9ZC3zim7ssWbCkUFhaxh+M+AdgVtOXYRmAxtI+5vTjHEC8uzppWuP7Aa +Au0um17RwgHrE90qVIR2IYtI1C9K9RLUNlKKVPqnSSmr0qkXR246R/Zd8eho1XSS +MX6KmnbmRijUx9Rw1AbD2ZmYCrXsPf2HsCdH+SGQ1ZTunnECQQD090dTA21Jyu/b +ADglqgixJCPIoc6qpxst+W1LreIo4UvkSmgnRYvsKDlM7FNI+6f7igI625KXIAnl +xVlmGLXDAkEA4CNVeP07fmQUBs1aPQ9LCOvN42SV6S8Fjbf4XHIYG5Kp48/98oJj +1pFsXNa8nn8fmN9zFw8yM/yd22iZdueCWQJAWMja//po/OrhniVpNDV5awKnOYtz +xSRF1JbnhxthseFeSUKylzE8sn4trnSlBvm2+5MclcqJSd7h13Z8nWVtUwJAZ0SA +Ve0+ov4TKAsnH2jTZnnWc4VdeIFcqq3vdRBwQQvy0G59D2W6ABsidSfO4auqcDHL +gf1TYRZr2LI5usnxiQJAGt3e0QC0q0WN4p49YhyXXVuHccx79RFgfN7V1lkAyYuL +2bPV41mEtD/AbSrObtqqvOaWZjwSr8JCyPdPZZAIMw== +-----END RSA PRIVATE KEY----- +`; +const EC = `-----BEGIN EC PRIVATE KEY----- +MHcCAQEEILpVcXOEZQXpH/q3ec3AsLg4x4Bld6uZLqDC56OYKQK4oAoGCCqGSM49 +AwEHoUQDQgAE0gwi0a/4kuVxjsO3vw79rT3QSxnPY7sooVlI+ENq35D7meWZv/dp +FTGFte7Bd8lFxaZ10dMo0tl++AOtt7umPg== +-----END EC PRIVATE KEY----- +`; + +function attempt(label: string, run: () => unknown): void { + try { + console.log(label, run()); + } catch (e) { + const err = e as NodeJS.ErrnoException; + console.log(label, "throws", err.name, err.code, err.message); + } +} + +const rsa = crypto.createPrivateKey(RSA); +const rsaPublic = crypto.createPublicKey(rsa); +const ec = crypto.createPrivateKey(EC); +const ecPublic = crypto.createPublicKey(ec); +const data = Buffer.from("signed message"); + +for (const digest of ["sha1", "sha224", "sha256", "SHA384", "RSA-SHA512", "sha256WithRSAEncryption"]) { + const signature = crypto.sign(digest, data, rsa); + console.log(digest, signature.toString("base64"), crypto.verify(digest, data, rsaPublic, signature)); +} +attempt("null digest", () => crypto.sign(null, data, RSA).equals(crypto.sign("sha256", data, rsa))); +attempt("private key verifies", () => crypto.verify("sha256", data, RSA, crypto.sign("sha256", data, rsa))); +attempt("wrong data", () => crypto.verify("sha256", Buffer.from("other"), rsaPublic, crypto.sign("sha256", data, rsa))); + +const pss = crypto.sign("sha256", data, { key: rsa, padding: crypto.constants.RSA_PKCS1_PSS_PADDING, saltLength: 32 }); +attempt("pss", () => [pss.length, crypto.verify("sha256", data, { key: rsaPublic, padding: crypto.constants.RSA_PKCS1_PSS_PADDING }, pss)].join()); +attempt("pss as pkcs1", () => crypto.verify("sha256", data, rsaPublic, pss)); +attempt("pss digest salt", () => + crypto.verify("sha256", data, { key: rsaPublic, padding: crypto.constants.RSA_PKCS1_PSS_PADDING, saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST }, pss), +); + +const der = crypto.sign("sha256", data, ec); +attempt("ecdsa der", () => [der[0], crypto.verify("sha256", data, ecPublic, der)].join()); +const p1363 = crypto.sign("sha384", data, { key: EC, dsaEncoding: "ieee-p1363" }); +attempt("ecdsa p1363", () => [p1363.length, crypto.verify("sha384", data, { key: ecPublic, dsaEncoding: "ieee-p1363" }, p1363)].join()); +attempt("p1363 as der", () => crypto.verify("sha384", data, ecPublic, p1363)); +attempt("truncated", () => crypto.verify("sha256", data, ecPublic, der.subarray(0, 10))); + +const signer = crypto.createSign("SHA256"); +signer.update("signed "); +signer.update(Buffer.from("message")); +const hex = signer.sign(rsa, "hex"); +attempt("sign object", () => hex === crypto.sign("sha256", data, rsa).toString("hex")); +attempt("sign again", () => signer.sign(rsa)); +attempt("update after sign", () => signer.update("more")); +const verifier = crypto.createVerify("RSA-SHA256"); +verifier.update("signed message", "utf8"); +attempt("verify object", () => verifier.verify(RSA, Buffer.from(hex, "hex").toString("base64"), "base64")); +attempt("verify again", () => verifier.verify(rsaPublic, hex, "hex")); +const ecSigner = crypto.createSign("sha512").update("chained"); +const ecSignature = ecSigner.sign({ key: ec, dsaEncoding: "ieee-p1363" }); +attempt("chained", () => crypto.createVerify("sha512").update("chained").verify({ key: ecPublic, dsaEncoding: "ieee-p1363" }, ecSignature)); + +attempt("invalid digest", () => crypto.sign("nope", data, rsa)); +const longDigest = "unknown-digest-".repeat(40); +attempt("long digest", () => crypto.sign(longDigest, data, rsa)); +attempt("long verify digest", () => crypto.verify(longDigest, data, rsaPublic, Buffer.alloc(64))); +attempt("public key signs", () => crypto.sign("sha256", data, rsaPublic)); +attempt("invalid createSign", () => crypto.createSign("nope")); +attempt("invalid dsaEncoding", () => crypto.sign("sha256", data, { key: ec, dsaEncoding: "x" as "der" })); diff --git a/tests/corpus/7084-crypto-key-pairs.cjs b/tests/corpus/7084-crypto-key-pairs.cjs new file mode 100644 index 000000000..ca267d89f --- /dev/null +++ b/tests/corpus/7084-crypto-key-pairs.cjs @@ -0,0 +1,78 @@ +// generateKeyPairSync and generateKeyPair for RSA and EC keys: KeyObject +// results, PEM and DER encodings, curve names and NIST aliases, the +// callback's later macrotask, and Node's errors for invalid types and +// options. +const crypto = require("node:crypto"); + +function attempt(label, run) { + try { + console.log(label, run()); + } catch (e) { + console.log(label, "throws", e.name, e.code, e.message); + } +} + +const data = Buffer.from("key pair"); +for (const curve of ["prime256v1", "P-256", "secp384r1", "P-384", "secp521r1", "P-521", "secp256k1"]) { + const { publicKey, privateKey } = crypto.generateKeyPairSync("ec", { namedCurve: curve }); + const signature = crypto.sign("sha256", data, privateKey); + console.log(curve, privateKey.type, publicKey.type, privateKey.asymmetricKeyDetails, crypto.verify("sha256", data, publicKey, signature)); +} +const rsa = crypto.generateKeyPairSync("rsa", { modulusLength: 1024 }); +console.log("rsa", rsa.privateKey.asymmetricKeyDetails, Object.keys(rsa)); +const exponent = crypto.generateKeyPairSync("rsa", { modulusLength: 1024, publicExponent: 3 }); +console.log("exponent", exponent.publicKey.asymmetricKeyDetails); +const encoded = crypto.generateKeyPairSync("ec", { + namedCurve: "P-256", + publicKeyEncoding: { type: "spki", format: "pem" }, + privateKeyEncoding: { type: "sec1", format: "der" }, +}); +console.log("encoded", typeof encoded.publicKey, encoded.publicKey.split("\n")[0], Buffer.isBuffer(encoded.privateKey)); +const reparsed = crypto.createPrivateKey({ key: encoded.privateKey, format: "der", type: "sec1" }); +console.log("reparsed", crypto.createPublicKey(reparsed).export({ type: "spki", format: "pem" }) === encoded.publicKey); +const rsaPem = crypto.generateKeyPairSync("rsa", { + modulusLength: 1024, + publicKeyEncoding: { type: "pkcs1", format: "pem" }, + privateKeyEncoding: { type: "pkcs8", format: "pem" }, +}); +console.log("rsa pem", rsaPem.publicKey.split("\n")[0], rsaPem.privateKey.split("\n")[0]); +const jwk = crypto.generateKeyPairSync("ec", { namedCurve: "secp256k1", publicKeyEncoding: { format: "jwk" } }); +console.log("jwk", Object.keys(jwk.publicKey), jwk.publicKey.crv); + +attempt("no options", () => crypto.generateKeyPairSync("rsa")); +attempt("no modulusLength", () => crypto.generateKeyPairSync("rsa", {})); +attempt("string modulusLength", () => crypto.generateKeyPairSync("rsa", { modulusLength: "2048" })); +attempt("negative modulusLength", () => crypto.generateKeyPairSync("rsa", { modulusLength: -1 })); +attempt("unknown type", () => crypto.generateKeyPairSync("foo", {})); +attempt("number type", () => crypto.generateKeyPairSync(5, {})); +attempt("no curve", () => crypto.generateKeyPairSync("ec", {})); +attempt("unknown curve", () => crypto.generateKeyPairSync("ec", { namedCurve: "nope" })); +attempt("bad encoding format", () => crypto.generateKeyPairSync("ec", { namedCurve: "P-256", publicKeyEncoding: { type: "spki", format: "xml" } })); +attempt("bad encoding type", () => crypto.generateKeyPairSync("ec", { namedCurve: "P-256", privateKeyEncoding: { type: "spki", format: "pem" } })); +attempt("encoding not object", () => crypto.generateKeyPairSync("ec", { namedCurve: "P-256", publicKeyEncoding: "pem" })); +// Error messages hold the whole text at any length, and received values +// render as Node's validators print them. +attempt("long type", () => crypto.generateKeyPairSync("unknown-type-".repeat(20), {})); +attempt("long encoding type", () => crypto.generateKeyPairSync("ec", { namedCurve: "P-256", publicKeyEncoding: { type: "z".repeat(300), format: "pem" } })); +attempt("quoted encoding type", () => crypto.generateKeyPairSync("ec", { namedCurve: "P-256", publicKeyEncoding: { type: "it's\n", format: "pem" } })); +attempt("huge modulusLength", () => crypto.generateKeyPairSync("rsa", { modulusLength: 2 ** 40 })); +attempt("fractional modulusLength", () => crypto.generateKeyPairSync("rsa", { modulusLength: 1.5 })); +attempt("NaN modulusLength", () => crypto.generateKeyPairSync("rsa", { modulusLength: NaN })); +const key = rsa.privateKey; +attempt("long method", () => key.aMethodNameLongEnoughThatTheWholeMessageRunsPastOneHundredAndSixtyBytesOnceTheReceiverTextAndTheSuffixAreIncluded()); +attempt("getter", () => { + "use strict"; + key.asymmetricKeyType = "ec"; +}); + +let returned = false; +crypto.generateKeyPair("ec", { namedCurve: "P-384" }, (err, publicKey, privateKey) => { + console.log("callback", returned, err, publicKey.type, privateKey.asymmetricKeyDetails); + crypto.generateKeyPair("rsa", { modulusLength: 1024 }, (err2, publicKey2) => { + console.log("rsa callback", err2, publicKey2.asymmetricKeyDetails.modulusLength); + }); +}); +process.nextTick(() => console.log("tick")); +attempt("callback errors throw", () => crypto.generateKeyPair("ec", {}, () => console.log("never"))); +returned = true; +console.log("returned"); diff --git a/tests/corpus/7085-webcrypto-ecdsa-rsa.ts b/tests/corpus/7085-webcrypto-ecdsa-rsa.ts new file mode 100644 index 000000000..446ed7c63 --- /dev/null +++ b/tests/corpus/7085-webcrypto-ecdsa-rsa.ts @@ -0,0 +1,66 @@ +// WebCrypto ECDSA, RSASSA-PKCS1-v1_5 and RSA-PSS: importKey from spki, +// pkcs8, jwk and raw, exportKey to each format, sign and verify (RSA +// PKCS#1 v1.5 signatures are deterministic, so they compare with Node), +// generateKey for every curve and both RSA algorithms, and the CryptoKey +// members of these keys. +const RSA_PKCS8 = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBANZ6LgFEQmb7gLq7/4Xg0juRM5D2B/9r4Rx3ZJnF+ldG1dPRBU0wAjW5A2YHhptjO93UbZXZcqxMkUlwlaJuMDPnpTG3HGCBOlIBqUVlig+bod9pvAlv9haHQrQ6s0W92R5cssyIdCzGYhDaWsWjJxASlnj/LGMt7otAX4vv2TbLAgMBAAECgYAxZL/1kLfOKbuyxZsKRQWFrGH4z4B2BW05dhGYDG0j7m9OMcQLy7Omla4/sBoC7S6bXtHCAesT3SpUhHYhi0jUL0r1EtQ2UopU+qdJKavSqRdHbjpH9l3x6GjVdJIxfoqaduZGKNTH1HDUBsPZmZgKtew9/YewJ0f5IZDVlO6ecQJBAPT3R1MDbUnK79sAOCWqCLEkI8ihzqqnGy35bUut4ijhS+RKaCdFi+woOUzsU0j7p/uKAjrbkpcgCeXFWWYYtcMCQQDgI1V4/Tt+ZBQGzVo9D0sI683jZJXpLwWNt/hcchgbkqnjz/3ygmPWkWxc1ryefx+Y33MXDzIz/J3baJl254JZAkBYyNr/+mj86uGeJWk0NXlrAqc5i3PFJEXUlueHG2Gx4V5JQrKXMTyyfi2udKUG+bb7kxyVyolJ3uHXdnydZW1TAkBnRIBV7T6i/hMoCycfaNNmedZzhV14gVyqre91EHBBC/LQbn0PZboAGyJ1J87hq6pwMcuB/VNhFmvYsjm6yfGJAkAa3d7RALSrRY3inj1iHJddW4dxzHv1EWB83tXWWQDJi4vZs9XjWYS0P8BtKs5u2qq85pZmPBKvwkLI909lkAgz"; +const RSA_SPKI = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDWei4BREJm+4C6u/+F4NI7kTOQ9gf/a+Ecd2SZxfpXRtXT0QVNMAI1uQNmB4abYzvd1G2V2XKsTJFJcJWibjAz56UxtxxggTpSAalFZYoPm6HfabwJb/YWh0K0OrNFvdkeXLLMiHQsxmIQ2lrFoycQEpZ4/yxjLe6LQF+L79k2ywIDAQAB"; +const EC_PKCS8 = "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgulVxc4RlBekf+rd5zcCwuDjHgGV3q5kuoMLno5gpArihRANCAATSDCLRr/iS5XGOw7e/Dv2tPdBLGc9juyihWUj4Q2rfkPuZ5Zm/92kVMYW17sF3yUXFpnXR0yjS2X74A623u6Y+"; +const EC_SPKI = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE0gwi0a/4kuVxjsO3vw79rT3QSxnPY7sooVlI+ENq35D7meWZv/dpFTGFte7Bd8lFxaZ10dMo0tl++AOtt7umPg=="; + +const bytes = (text: string): Uint8Array => new Uint8Array(Buffer.from(text, "base64")); +const hex = (buffer: ArrayBuffer): string => Buffer.from(buffer).toString("hex"); +const data = new TextEncoder().encode("webcrypto message"); + +const rsaPrivate = await crypto.subtle.importKey("pkcs8", bytes(RSA_PKCS8), { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, true, ["sign"]); +const rsaPublic = await crypto.subtle.importKey("spki", bytes(RSA_SPKI), { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, true, ["verify"]); +console.log(rsaPrivate.type, rsaPublic.type, rsaPrivate.extractable, rsaPublic.usages); +const rsaAlgorithm = rsaPrivate.algorithm as RsaHashedKeyAlgorithm; +console.log(rsaAlgorithm.name, rsaAlgorithm.modulusLength, Array.from(rsaAlgorithm.publicExponent), rsaAlgorithm.hash.name); +const rsaSignature = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", rsaPrivate, data); +console.log("rsa signature", hex(rsaSignature)); +console.log("rsa verify", await crypto.subtle.verify({ name: "RSASSA-PKCS1-v1_5" }, rsaPublic, rsaSignature, data)); +console.log("rsa spki", Buffer.from(await crypto.subtle.exportKey("spki", rsaPublic)).toString("base64") === RSA_SPKI); +console.log("rsa pkcs8", Buffer.from(await crypto.subtle.exportKey("pkcs8", rsaPrivate)).toString("base64") === RSA_PKCS8); +const rsaJwk = await crypto.subtle.exportKey("jwk", rsaPublic); +console.log("rsa jwk", JSON.stringify(rsaJwk)); +const fromJwk = await crypto.subtle.importKey("jwk", rsaJwk, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["verify"]); +console.log("rsa jwk verify", await crypto.subtle.verify("RSASSA-PKCS1-v1_5", fromJwk, rsaSignature, data), fromJwk.extractable); + +const ecPrivate = await crypto.subtle.importKey("pkcs8", bytes(EC_PKCS8), { name: "ECDSA", namedCurve: "P-256" }, true, ["sign"]); +const ecPublic = await crypto.subtle.importKey("spki", bytes(EC_SPKI), { name: "ECDSA", namedCurve: "P-256" }, true, ["verify"]); +console.log(JSON.stringify(ecPrivate.algorithm), ecPrivate.usages, ecPublic.usages); +console.log("ec jwk", JSON.stringify(await crypto.subtle.exportKey("jwk", ecPrivate))); +const point = await crypto.subtle.exportKey("raw", ecPublic); +console.log("ec raw", hex(point)); +const fromPoint = await crypto.subtle.importKey("raw", point, { name: "ECDSA", namedCurve: "P-256" }, true, ["verify"]); +for (const hash of ["SHA-1", "SHA-256", "SHA-384", "SHA-512"]) { + const signature = await crypto.subtle.sign({ name: "ECDSA", hash }, ecPrivate, data); + console.log("ecdsa", hash, signature.byteLength, await crypto.subtle.verify({ name: "ECDSA", hash: { name: hash } }, fromPoint, signature, data)); +} +const ecSignature = await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, ecPrivate, data); +const tampered = new Uint8Array(ecSignature); +tampered[5] ^= 1; +console.log("tampered", await crypto.subtle.verify({ name: "ECDSA", hash: "SHA-256" }, ecPublic, tampered, data)); +console.log("other data", await crypto.subtle.verify({ name: "ECDSA", hash: "SHA-256" }, ecPublic, ecSignature, new Uint8Array([1]))); + +for (const namedCurve of ["P-256", "P-384", "P-521"]) { + const pair = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve }, false, ["sign", "verify"]); + const signature = await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-384" }, pair.privateKey, data); + console.log(namedCurve, Object.keys(pair).join(), pair.privateKey.extractable, pair.publicKey.extractable, signature.byteLength, + await crypto.subtle.verify({ name: "ECDSA", hash: "SHA-384" }, pair.publicKey, signature, data), + (await crypto.subtle.exportKey("raw", pair.publicKey)).byteLength); +} +for (const name of ["RSASSA-PKCS1-v1_5", "RSA-PSS"]) { + const pair = await crypto.subtle.generateKey({ name, modulusLength: 1024, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-512" }, true, ["sign", "verify"]); + const params = { name, saltLength: 20 }; + const signature = await crypto.subtle.sign(params, pair.privateKey, data); + const jwk = await crypto.subtle.exportKey("jwk", pair.privateKey); + console.log(name, signature.byteLength, await crypto.subtle.verify(params, pair.publicKey, signature, data), jwk.alg, Object.keys(jwk).join()); +} +const pss = await crypto.subtle.importKey("pkcs8", bytes(RSA_PKCS8), { name: "RSA-PSS", hash: "SHA-256" }, false, ["sign"]); +const pssPublic = await crypto.subtle.importKey("spki", bytes(RSA_SPKI), { name: "RSA-PSS", hash: "SHA-256" }, false, ["verify"]); +const pssSignature = await crypto.subtle.sign({ name: "RSA-PSS", saltLength: 32 }, pss, data); +console.log("pss", await crypto.subtle.verify({ name: "RSA-PSS", saltLength: 32 }, pssPublic, pssSignature, data), + await crypto.subtle.verify({ name: "RSA-PSS", saltLength: 0 }, pssPublic, pssSignature, data)); +console.log(ecPrivate instanceof CryptoKey, String(ecPublic), Object.prototype.toString.call(rsaPublic)); diff --git a/tests/corpus/7086-webcrypto-ecdsa-rsa-errors.mjs b/tests/corpus/7086-webcrypto-ecdsa-rsa-errors.mjs new file mode 100644 index 000000000..62292fbdd --- /dev/null +++ b/tests/corpus/7086-webcrypto-ecdsa-rsa-errors.mjs @@ -0,0 +1,58 @@ +// WebCrypto ECDSA and RSA errors: Node's TypeErrors for missing algorithm +// members, and its DOMExceptions for curves, usages, key types, formats, +// extractability and JWK members, from generateKey, importKey, exportKey, +// sign and verify. + +const t = async (label, fn) => { try { const v = await fn(); console.log(label, "=>", v instanceof ArrayBuffer ? "AB" + v.byteLength : typeof v === "object" && v !== null ? JSON.stringify(v) : v); } catch (e) { console.log(label, "!!", e.name, e.code, e.message); } }; +const e3 = new Uint8Array([1, 0, 1]); +await t("rsa no hash", () => crypto.subtle.generateKey({ name: "RSASSA-PKCS1-v1_5", modulusLength: 1024, publicExponent: e3 }, true, ["sign"])); +await t("rsa no len", () => crypto.subtle.generateKey({ name: "RSASSA-PKCS1-v1_5", publicExponent: e3, hash: "SHA-256" }, true, ["sign"])); +await t("rsa no exp", () => crypto.subtle.generateKey({ name: "RSASSA-PKCS1-v1_5", modulusLength: 1024, hash: "SHA-256" }, true, ["sign"])); +await t("rsa bad usage", () => crypto.subtle.generateKey({ name: "RSASSA-PKCS1-v1_5", modulusLength: 1024, publicExponent: e3, hash: "SHA-256" }, true, ["encrypt"])); +await t("pss bad usage", () => crypto.subtle.generateKey({ name: "RSA-PSS", modulusLength: 1024, publicExponent: e3, hash: "SHA-256" }, true, ["encrypt"])); +await t("rsa bad hash", () => crypto.subtle.generateKey({ name: "RSASSA-PKCS1-v1_5", modulusLength: 1024, publicExponent: e3, hash: "MD5" }, true, ["sign"])); +await t("rsa exp 3", async () => (await crypto.subtle.generateKey({ name: "RSASSA-PKCS1-v1_5", modulusLength: 1024, publicExponent: new Uint8Array([3]), hash: "SHA-256" }, true, ["sign"])).publicKey.algorithm.publicExponent.length); +await t("rsa exp 4", () => crypto.subtle.generateKey({ name: "RSASSA-PKCS1-v1_5", modulusLength: 1024, publicExponent: new Uint8Array([4]), hash: "SHA-256" }, true, ["sign"])); +await t("rsa small", () => crypto.subtle.generateKey({ name: "RSASSA-PKCS1-v1_5", modulusLength: 256, publicExponent: e3, hash: "SHA-256" }, true, ["sign"])); +await t("ecdsa no curve", () => crypto.subtle.generateKey({ name: "ECDSA" }, true, ["sign"])); +await t("unknown alg", () => crypto.subtle.generateKey({ name: "FOO" }, true, ["sign"])); +const ec = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign", "verify"]); +await t("export bad format", () => crypto.subtle.exportKey("foo", ec.publicKey)); +await t("export not key", () => crypto.subtle.exportKey("spki", {})); +await t("export spki private", () => crypto.subtle.exportKey("spki", ec.privateKey)); +await t("export pkcs8 public", () => crypto.subtle.exportKey("pkcs8", ec.publicKey)); +await t("import raw private", () => crypto.subtle.importKey("raw", new Uint8Array(32), { name: "ECDSA", namedCurve: "P-256" }, true, ["sign"])); +await t("import pkcs8 verify", async () => crypto.subtle.importKey("pkcs8", await crypto.subtle.exportKey("pkcs8", ec.privateKey), { name: "ECDSA", namedCurve: "P-256" }, true, ["verify"])); +await t("import pkcs8 empty", async () => crypto.subtle.importKey("pkcs8", await crypto.subtle.exportKey("pkcs8", ec.privateKey), { name: "ECDSA", namedCurve: "P-256" }, true, [])); +await t("import spki empty", async () => (await crypto.subtle.importKey("spki", await crypto.subtle.exportKey("spki", ec.publicKey), { name: "ECDSA", namedCurve: "P-256" }, true, [])).usages); +await t("import no curve", async () => crypto.subtle.importKey("spki", await crypto.subtle.exportKey("spki", ec.publicKey), { name: "ECDSA" }, true, ["verify"])); +await t("import rsa no hash", async () => crypto.subtle.importKey("spki", await crypto.subtle.exportKey("spki", ec.publicKey), { name: "RSASSA-PKCS1-v1_5" }, true, ["verify"])); +await t("import ec as rsa", async () => crypto.subtle.importKey("spki", await crypto.subtle.exportKey("spki", ec.publicKey), { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, true, ["verify"])); +await t("import jwk bad", () => crypto.subtle.importKey("jwk", { kty: "EC", crv: "P-256", x: "AA", y: "AA" }, { name: "ECDSA", namedCurve: "P-256" }, true, ["verify"])); +await t("import jwk crv mismatch", async () => crypto.subtle.importKey("jwk", await crypto.subtle.exportKey("jwk", ec.publicKey), { name: "ECDSA", namedCurve: "P-384" }, true, ["verify"])); +await t("import jwk kty", async () => crypto.subtle.importKey("jwk", { ...(await crypto.subtle.exportKey("jwk", ec.publicKey)), kty: "RSA" }, { name: "ECDSA", namedCurve: "P-256" }, true, ["verify"])); +await t("jwk ext false", async () => crypto.subtle.importKey("jwk", { ...(await crypto.subtle.exportKey("jwk", ec.publicKey)), ext: false }, { name: "ECDSA", namedCurve: "P-256" }, true, ["verify"])); +await t("jwk key_ops", async () => crypto.subtle.importKey("jwk", { ...(await crypto.subtle.exportKey("jwk", ec.publicKey)), key_ops: ["sign"] }, { name: "ECDSA", namedCurve: "P-256" }, true, ["verify"])); +const data = new Uint8Array([1, 2, 3]); +const spki = await crypto.subtle.exportKey("spki", ec.publicKey); +const rsa = await crypto.subtle.generateKey({ name: "RSASSA-PKCS1-v1_5", modulusLength: 1024, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" }, false, ["sign", "verify"]); +const pss = await crypto.subtle.generateKey({ name: "RSA-PSS", modulusLength: 1024, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-384" }, true, ["sign", "verify"]); +await t("export nonextractable", () => crypto.subtle.exportKey("pkcs8", rsa.privateKey)); +await t("export raw private", () => crypto.subtle.exportKey("raw", ec.privateKey)); +await t("sign with public", () => crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, ec.publicKey, data)); +await t("sign wrong alg", () => crypto.subtle.sign("RSASSA-PKCS1-v1_5", ec.privateKey, data)); +await t("ecdsa no hash", () => crypto.subtle.sign({ name: "ECDSA" }, ec.privateKey, data)); +await t("bad curve", () => crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-999" }, true, ["sign"])); +await t("bad usage", () => crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["encrypt"])); +await t("empty usages", () => crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, [])); +await t("verify usage only", async () => { const k = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-384" }, true, ["verify"]); return k.privateKey.usages + "|" + k.publicKey.usages; }); +await t("import wrong curve", () => crypto.subtle.importKey("spki", spki, { name: "ECDSA", namedCurve: "P-384" }, true, ["verify"])); +await t("import sign usage public", () => crypto.subtle.importKey("spki", spki, { name: "ECDSA", namedCurve: "P-256" }, true, ["sign"])); +await t("import garbage", () => crypto.subtle.importKey("spki", new Uint8Array([1, 2, 3]), { name: "ECDSA", namedCurve: "P-256" }, true, ["verify"])); +await t("pss no salt", () => crypto.subtle.sign({ name: "RSA-PSS" }, pss.privateKey, data)); +await t("verify bad sig len", () => crypto.subtle.verify({ name: "ECDSA", hash: "SHA-256" }, ec.publicKey, new Uint8Array(10), data)); +await t("verify with private", () => crypto.subtle.verify({ name: "ECDSA", hash: "SHA-256" }, ec.privateKey, new Uint8Array(64), data)); +await t("sign hmac with ec", () => crypto.subtle.sign("HMAC", ec.privateKey, data)); +await t("sign ec hash obj", async () => (await crypto.subtle.sign({ name: "ECDSA", hash: { name: "SHA-512" } }, ec.privateKey, data)).byteLength); +await t("p521", async () => (await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, (await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-521" }, false, ["sign"])).privateKey, data)).byteLength); +await t("raw export p384", async () => (await crypto.subtle.exportKey("raw", (await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-384" }, true, ["sign","verify"])).publicKey)).byteLength); diff --git a/tests/corpus/7087-tls-socket-wrap.ts b/tests/corpus/7087-tls-socket-wrap.ts new file mode 100644 index 000000000..d1357a98e --- /dev/null +++ b/tests/corpus/7087-tls-socket-wrap.ts @@ -0,0 +1,104 @@ +// new tls.TLSSocket(socket, { isServer: true, ... }) over a net server's +// connection: the wrap is a new socket that runs the server handshake, with +// cert/key or a secureContext and ALPNProtocols. The wrapped socket stays +// open without I/O, destroy() on it closes both, and its 'close' fires just +// before the TLS socket's. A peer that closes, resets or sends bytes that +// are not TLS fails the handshake with Node's events and codes. +import { readFileSync } from "node:fs"; +import * as net from "node:net"; +import * as tls from "node:tls"; + +const certs = "tests/fixtures/server/certs"; +const ca = readFileSync(`${certs}/ca.pem`); +const cert = readFileSync(`${certs}/localhost.pem`); +const key = readFileSync(`${certs}/localhost-key.pem`); +const context = tls.createSecureContext({ cert, key }); + +// cert/key and ALPN: the events, the state of both sockets, and the data. +function certKey(next: () => void): void { + const server = net.createServer((raw) => { + raw.on("close", (hadError: boolean) => console.log("raw close", hadError, raw.destroyed)); + const s = new tls.TLSSocket(raw, { isServer: true, cert, key, ALPNProtocols: ["h2", "http/1.1"] }); + console.log("after wrap", raw.destroyed, raw.readyState, raw.writable, s === raw); + console.log("before handshake", s.destroyed, s.encrypted, s.alpnProtocol); + console.log("same peer", s.remoteAddress === raw.remoteAddress, s.remotePort === raw.remotePort); + s.on("connect", () => console.log("never: connect")); + s.on("secureConnect", () => console.log("never: secureConnect")); + s.on("secure", () => { + console.log("secure", s.getProtocol(), s.alpnProtocol, s.authorized, s.authorizationError); + }); + s.on("data", (chunk: Buffer) => { + console.log("server data", chunk.toString()); + s.end("pong"); + }); + s.on("end", () => console.log("server end")); + s.on("close", (hadError: boolean) => { + console.log("tls close", hadError, raw.destroyed, s.destroyed); + server.close(next); + }); + }); + server.listen(0, () => { + const port = (server.address() as net.AddressInfo).port; + const c = tls.connect({ port, host: "localhost", ca, ALPNProtocols: ["http/1.1"] }, () => { + console.log("client secureConnect", c.authorized, c.alpnProtocol); + c.write("ping"); + }); + c.on("secure", () => console.log("client secure")); + c.on("data", (chunk: Buffer) => console.log("client data", chunk.toString())); + c.on("close", () => console.log("client close")); + }); +} + +// secureContext, and destroy() on the wrapped socket. +function secureContext(next: () => void): void { + const server = net.createServer((raw) => { + raw.on("close", (hadError: boolean) => console.log("raw close", hadError)); + const s = new tls.TLSSocket(raw, { isServer: true, secureContext: context }); + s.on("secure", () => { + console.log("context secure", s.alpnProtocol); + raw.destroy(); + }); + s.on("close", (hadError: boolean) => { + console.log("tls close", hadError, s.destroyed); + server.close(next); + }); + }); + server.listen(0, () => { + const port = (server.address() as net.AddressInfo).port; + const c = tls.connect({ port, host: "localhost", ca }, () => console.log("client secureConnect")); + c.on("error", (err: Error & { code?: string }) => console.log("client error", err.code)); + c.on("close", () => console.log("client close")); + }); +} + +// Handshakes the peer fails. +function failure(mode: string, next: () => void): void { + const server = net.createServer((raw) => { + const s = new tls.TLSSocket(raw, { isServer: true, cert, key }); + s.on("secure", () => console.log("never: secure")); + s.on("error", (err: Error & { code?: string }) => console.log(mode, "error", err.code)); + s.on("end", () => console.log(mode, "end")); + s.on("close", (hadError: boolean) => { + console.log(mode, "close", hadError); + server.close(next); + }); + }); + server.listen(0, () => { + const port = (server.address() as net.AddressInfo).port; + const c = net.connect(port, "localhost", () => { + if (mode === "close") c.end(); + else if (mode === "garbage") c.end("hello there, this is not tls\r\n"); + else if (mode === "http") c.end("GET / HTTP/1.1\r\nHost: localhost\r\n\r\n"); + else c.resetAndDestroy(); + }); + c.on("error", () => {}); + }); +} + +certKey(() => + secureContext(() => + failure("close", () => + failure("garbage", () => failure("http", () => failure("reset", () => console.log("done")))), + ), + ), +); diff --git a/tests/corpus/7088-tls-socket-connect-tunnel.ts b/tests/corpus/7088-tls-socket-connect-tunnel.ts new file mode 100644 index 000000000..806575ddb --- /dev/null +++ b/tests/corpus/7088-tls-socket-connect-tunnel.ts @@ -0,0 +1,64 @@ +// An HTTPS-intercepting proxy: the http server answers CONNECT, then runs +// the TLS server side on the tunnel socket with new tls.TLSSocket and a +// secureContext; the client runs its handshake inside the tunnel with +// tls.connect({ socket }). Without a servername the client verifies against +// the host the tunnel socket dialed. +import { readFileSync } from "node:fs"; +import * as http from "node:http"; +import * as net from "node:net"; +import * as tls from "node:tls"; + +const certs = "tests/fixtures/server/certs"; +const ca = readFileSync(`${certs}/ca.pem`); +const context = tls.createSecureContext({ + cert: readFileSync(`${certs}/localhost.pem`), + key: readFileSync(`${certs}/localhost-key.pem`), +}); + +let tunnels = 0; +const proxy = http.createServer((_req, res) => { + res.end("plain"); +}); +proxy.on("connect", (req: http.IncomingMessage, socket: net.Socket, head: Buffer) => { + const id = ++tunnels; + console.log(id, "proxy connect", req.method, req.url, head.length); + socket.write("HTTP/1.1 200 Connection Established\r\n\r\n"); + const secure = new tls.TLSSocket(socket, { isServer: true, secureContext: context }); + secure.on("secure", () => console.log(id, "proxy secure", secure.getProtocol())); + secure.on("data", (chunk: Buffer) => { + console.log(id, "proxy got", chunk.toString()); + secure.end(`intercepted ${chunk.toString()}`); + }); + secure.on("close", () => { + console.log(id, "proxy tls close"); + if (id === 2) proxy.close(); + }); + socket.on("close", () => console.log(id, "tunnel close")); +}); + +function tunnel(port: number, servername: string | undefined, next: () => void): void { + const raw = net.connect(port, "localhost", () => { + raw.write("CONNECT example.test:443 HTTP/1.1\r\nHost: example.test:443\r\n\r\n"); + }); + raw.once("data", (chunk: Buffer) => { + console.log("client got", chunk.toString().split("\r\n")[0]); + const onSecure = (): void => { + console.log("client secureConnect", client.authorized); + client.write(servername ?? "no servername"); + }; + const client = + servername === undefined + ? tls.connect({ socket: raw, ca }, onSecure) + : tls.connect({ socket: raw, ca, servername }, onSecure); + client.on("data", (data: Buffer) => console.log("client data", data.toString())); + client.on("close", () => { + console.log("client close"); + next(); + }); + }); +} + +proxy.listen(0, () => { + const port = (proxy.address() as net.AddressInfo).port; + tunnel(port, "localhost", () => tunnel(port, undefined, () => console.log("done"))); +}); diff --git a/tests/corpus/7089-http-host-header-tunnels.ts b/tests/corpus/7089-http-host-header-tunnels.ts new file mode 100644 index 000000000..bc982b2d1 --- /dev/null +++ b/tests/corpus/7089-http-host-header-tunnels.ts @@ -0,0 +1,31 @@ +// An HTTP/1.1 request without a Host header gets 400 Bad Request, except +// the requests that leave the parser first: an upgrade an 'upgrade' +// listener takes, and a CONNECT (destroyed here, with no 'connect' +// listener). +import * as http from "node:http"; +import * as net from "node:net"; + +const server = http.createServer((_req, res) => res.end("request")); +server.on("upgrade", (req: http.IncomingMessage, socket: net.Socket) => { + console.log("upgrade", req.url, req.headers.host); + socket.end("HTTP/1.1 101 Switching Protocols\r\n\r\n"); +}); +function probe(head: string, next: () => void): void { + const port = (server.address() as net.AddressInfo).port; + const raw = net.connect(port, "127.0.0.1", () => raw.write(head)); + let got = ""; + raw.on("data", (d: Buffer) => { + got += d.toString(); + }); + raw.on("close", () => { + console.log("got", JSON.stringify(got.split("\r\n")[0])); + next(); + }); +} +server.listen(0, "127.0.0.1", () => { + probe("GET /ws HTTP/1.1\r\nConnection: upgrade\r\nUpgrade: websocket\r\n\r\n", () => + probe("CONNECT a:1 HTTP/1.1\r\n\r\n", () => + probe("GET / HTTP/1.1\r\nConnection: close\r\n\r\n", () => server.close()), + ), + ); +}); diff --git a/tests/corpus/7094-tls-socket-failed-handshakes.ts b/tests/corpus/7094-tls-socket-failed-handshakes.ts new file mode 100644 index 000000000..daad49a4e --- /dev/null +++ b/tests/corpus/7094-tls-socket-failed-handshakes.ts @@ -0,0 +1,49 @@ +// A TLSSocket whose handshake never completes still closes and releases +// its listeners, including a 'secure' listener that holds the socket: one +// peer closes before sending anything and the next sends a plain HTTP +// request. +import { readFileSync } from "node:fs"; +import * as net from "node:net"; +import * as tls from "node:tls"; + +const certs = "tests/fixtures/server/certs"; +const cert = readFileSync(`${certs}/localhost.pem`); +const key = readFileSync(`${certs}/localhost-key.pem`); +const context = tls.createSecureContext({ cert, key }); + +const peers: ((port: number) => void)[] = [ + (port) => { + const quiet = net.connect(port, "127.0.0.1", () => quiet.end()); + }, + (port) => { + const plain = net.connect(port, "127.0.0.1", () => plain.write("GET / HTTP/1.1\r\nHost: x\r\n\r\n")); + plain.on("error", () => {}); + plain.resume(); + }, + (port) => { + const quiet = net.connect(port, "127.0.0.1", () => quiet.destroy()); + }, +]; +let served = 0; +const server = net.createServer((raw) => { + served++; + const secure = + served === 3 + ? new tls.TLSSocket(raw, { isServer: true, secureContext: context }) + : new tls.TLSSocket(raw, { isServer: true, cert, key }); + secure.on("secure", () => console.log("secure", served, secure.alpnProtocol)); + secure.on("error", (err: NodeJS.ErrnoException) => console.log("error", served, err.code)); + secure.on("close", (hadError: boolean) => { + console.log("close", served, hadError); + next(); + }); +}); +function next(): void { + const peer = peers.shift(); + if (peer === undefined) { + server.close(() => console.log("server closed")); + return; + } + peer((server.address() as net.AddressInfo).port); +} +server.listen(0, "127.0.0.1", next); diff --git a/tests/corpus/7106-async-prefix-enter-with.ts b/tests/corpus/7106-async-prefix-enter-with.ts new file mode 100644 index 000000000..d70822171 --- /dev/null +++ b/tests/corpus/7106-async-prefix-enter-with.ts @@ -0,0 +1,119 @@ +// AsyncLocalStorage.enterWith in an async callee: before the callee's first +// await it runs in the caller's execution, so the caller sees the store +// after the call (Node's semantics), and the callee keeps it after its own +// await; after the first await it stays inside the callee. Covers callees +// that never suspend, stackless and fiber-backed callees, nested callees, +// run() scopes inside the prefix, and calls without an await. A store that +// an event-loop callback enters this way, or through a generator step, ends +// with that callback and does not reach the next one. +import { AsyncLocalStorage } from "node:async_hooks"; + +const store = new AsyncLocalStorage(); +const log: string[] = []; +const current = (): string => store.getStore() ?? "none"; + +async function neverSuspends(tag: string): Promise { + store.enterWith(`never-${tag}`); + return 1; +} +async function prefixThenAwait(tag: string): Promise { + store.enterWith(`prefix-${tag}`); + await null; + log.push(`callee ${tag} after its await: ${current()}`); + return 2; +} +async function afterAwait(tag: string): Promise { + await null; + store.enterWith(`after-${tag}`); + return 3; +} +async function nested(tag: string): Promise { + await neverSuspends(`inner-${tag}`); + log.push(`nested ${tag} after its callee: ${current()}`); + return 4; +} +async function runInPrefix(tag: string): Promise { + store.run(`run-${tag}`, () => store.enterWith("inside-run")); + return 5; +} +async function* ticks(): AsyncGenerator { + yield 1; +} +async function fibered(tag: string): Promise { + store.enterWith(`fibered-${tag}`); + let n = 0; + for await (const t of ticks()) n += t; + log.push(`fibered ${tag} after its loop: ${current()}`); + return n; +} + +function* steps(): Generator { + store.enterWith("generator-step"); + yield 1; +} +function callbacks(): Promise { + return new Promise((resolve) => { + setTimeout(() => { + void prefixThenAwait("9"); + log.push(`timer after the call: ${current()}`); + }, 0); + setTimeout(() => { + log.push(`second timer: ${current()}`); + steps().next(); + log.push(`second timer after a generator step: ${current()}`); + }, 0); + setTimeout(() => { + log.push(`third timer: ${current()}`); + void neverSuspends("10"); + log.push(`third timer after the call: ${current()}`); + }, 0); + setTimeout(() => { + log.push(`last timer: ${current()}`); + resolve(); + }, 0); + }); +} + +async function main(): Promise { + await store.run("A", async () => { + await neverSuspends("1"); + log.push(`A after neverSuspends: ${current()}`); + }); + await store.run("B", async () => { + const pending = prefixThenAwait("2"); + log.push(`B after the call: ${current()}`); + store.enterWith("B-later"); + await pending; + log.push(`B after its await: ${current()}`); + }); + await store.run("C", async () => { + await afterAwait("3"); + log.push(`C after afterAwait: ${current()}`); + }); + await store.run("D", async () => { + await nested("4"); + log.push(`D after nested: ${current()}`); + }); + await store.run("E", async () => { + await runInPrefix("5"); + log.push(`E after runInPrefix: ${current()}`); + }); + await store.run("F", async () => { + void neverSuspends("6"); + log.push(`F after an unawaited call: ${current()}`); + await null; + log.push(`F later: ${current()}`); + }); + store.run("G", () => { + void neverSuspends("7"); + log.push(`G synchronous caller: ${current()}`); + }); + await store.run("H", async () => { + await fibered("8"); + log.push(`H after fibered: ${current()}`); + }); + await callbacks(); + log.push(`main after the callbacks: ${current()}`); + for (const line of log) console.log(line); +} +void main(); diff --git a/tests/corpus/7107-for-await-context.ts b/tests/corpus/7107-for-await-context.ts new file mode 100644 index 000000000..8e21933b9 --- /dev/null +++ b/tests/corpus/7107-for-await-context.ts @@ -0,0 +1,37 @@ +// An async function's AsyncLocalStorage store across `for await` over an +// async generator: the consumer keeps its store after each resumption of +// the generator, whether it came from run(), from enterWith before the +// loop, or from enterWith after an earlier await. +import { AsyncLocalStorage } from "node:async_hooks"; + +const store = new AsyncLocalStorage(); +const current = (): string => store.getStore() ?? "none"; + +async function* numbers(n: number): AsyncGenerator { + for (let i = 0; i < n; i++) { + await null; + yield i; + } +} + +async function consume(label: string): Promise { + let sum = 0; + for await (const v of numbers(3)) { + sum += v; + console.log(`${label} step ${v}: ${current()}`); + } + console.log(`${label} after the loop (${sum}): ${current()}`); +} + +async function entered(): Promise { + await null; + store.enterWith("entered"); + await consume("entered"); +} + +async function main(): Promise { + await store.run("run", () => consume("run")); + await entered(); + console.log(`main: ${current()}`); +} +void main(); diff --git a/tests/corpus/7108-generator-step-context.ts b/tests/corpus/7108-generator-step-context.ts new file mode 100644 index 000000000..3e9a01a5f --- /dev/null +++ b/tests/corpus/7108-generator-step-context.ts @@ -0,0 +1,49 @@ +// A synchronous generator has no AsyncLocalStorage context of its own: each +// step runs in its resumer's execution, so it sees the store current at +// that next() call, and a store it enters is the resumer's after the step. +// Covers steps inside and outside run(), for-of, spread and early return. +import { AsyncLocalStorage } from "node:async_hooks"; + +const store = new AsyncLocalStorage(); +const current = (): string => store.getStore() ?? "none"; + +function* steps(): Generator { + console.log(`start sees ${current()}`); + yield "a"; + console.log(`step 2 sees ${current()}`); + store.enterWith("entered-in-step-2"); + yield "b"; + console.log(`step 3 sees ${current()}`); +} + +function* labels(): Generator { + yield current(); + yield current(); +} + +store.run("S1", () => { + const g = steps(); + g.next(); + store.run("S2", () => g.next()); + console.log(`caller after the S2 step: ${current()}`); + store.enterWith("S3"); + g.next(); + console.log(`caller after step 3: ${current()}`); +}); + +store.run("forof", () => { + const seen: string[] = []; + for (const label of labels()) seen.push(label); + console.log(`for-of: ${seen.join(",")}`); + console.log(`spread: ${[...labels()].join(",")}`); +}); + +store.run("outer", () => { + const g = steps(); + g.next(); + g.next(); + console.log(`caller after entering step: ${current()}`); + g.return(); + console.log(`caller after return: ${current()}`); +}); +console.log(`top level: ${current()}`); diff --git a/tests/corpus/7109-uninitialized-let-assignment-expressions.ts b/tests/corpus/7109-uninitialized-let-assignment-expressions.ts new file mode 100644 index 000000000..1354ab100 --- /dev/null +++ b/tests/corpus/7109-uninitialized-let-assignment-expressions.ts @@ -0,0 +1,63 @@ +// A module `let` declared without an initializer is initialized (to +// undefined) when its declaration runs. Assignments in expression +// position store into it like assignment statements do. + +// The deferred-resolver pattern: an expression-bodied executor. +let resolve!: (value: number) => void; +const pending = new Promise((r) => (resolve = r)); +resolve(1); +console.log("resolved", await pending); + +// An expression-bodied setter, and the assignment's value. +let handler!: (n: number) => string; +const setHandler = (h: (n: number) => string) => (handler = h); +const returned = setHandler((n) => `handled ${n}`); +console.log(returned(2), handler(3)); + +// The value held in a binding first. +let next!: () => string; +const install = (f: () => string) => { + const r = (next = f); + return r; +}; +console.log(install(() => "installed")(), next()); + +// Chained, conditional and argument positions. +let first!: (n: number) => number; +let second!: (n: number) => number; +first = second = (n) => n + 1; +console.log("chained", first(1), second(2)); +let picked!: () => string; +const choose = (flag: boolean) => (flag ? (picked = () => "yes") : (picked = () => "no")); +choose(false); +console.log("conditional", picked()); +const call = (f: () => string) => f(); +let passed!: () => string; +console.log("argument", call((passed = () => "passed")), passed()); + +// Reassignment releases the earlier function and keeps the new one. +let counter!: () => number; +const make = (start: number) => { + let n = start; + return (counter = () => ++n); +}; +make(10); +make(20); +console.log("reassigned", counter(), counter()); + +// An optional binding behaves the same way. +let maybe: ((s: string) => string) | undefined; +const setMaybe = (f: (s: string) => string) => (maybe = f); +console.log("optional", setMaybe((s) => s.toUpperCase())("a"), maybe?.("b")); + +// A write that runs before the declaration still throws. +function early(): () => number { + return (late = () => 1); +} +try { + early(); +} catch (e) { + console.log((e as Error).name, (e as Error).message); +} +let late!: () => number; +console.log("after declaration", early()(), late()); diff --git a/tests/corpus/7120-webcrypto-random-uuid.ts b/tests/corpus/7120-webcrypto-random-uuid.ts new file mode 100644 index 000000000..d35df97cc --- /dev/null +++ b/tests/corpus/7120-webcrypto-random-uuid.ts @@ -0,0 +1,22 @@ +// crypto.randomUUID() on the WebCrypto global, directly and through +// globalThis: version-4 UUIDs, distinct on every call, and inside +// closures and default parameters the way request-id middleware uses it. +const shape = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; + +const direct: string = crypto.randomUUID(); +console.log(direct.length, shape.test(direct)); +const viaGlobalThis = globalThis.crypto.randomUUID(); +console.log(viaGlobalThis.length, shape.test(viaGlobalThis), viaGlobalThis !== direct); + +const seen = new Set(); +for (let i = 0; i < 100; i++) seen.add(crypto.randomUUID()); +console.log("distinct", seen.size); + +function requestId(generator: () => string = () => crypto.randomUUID()): string { + return generator(); +} +console.log(shape.test(requestId()), requestId(() => "fixed")); + +const ids = ["a", "b", "c"].map((name) => ({ name, id: crypto.randomUUID() })); +console.log(ids.every((entry) => shape.test(entry.id)), ids[0]!.id !== ids[1]!.id); +console.log(typeof crypto.randomUUID()); diff --git a/tests/corpus/7121-webcrypto-crypto-object.mjs b/tests/corpus/7121-webcrypto-crypto-object.mjs new file mode 100644 index 000000000..058e72153 --- /dev/null +++ b/tests/corpus/7121-webcrypto-crypto-object.mjs @@ -0,0 +1,35 @@ +// The crypto global from JavaScript: uuid's feature test +// (`crypto.randomUUID && crypto.randomUUID()`), the methods read as values, +// and getRandomValues through the dynamic object, including its +// missing-argument and non-integer-view errors. +const shape = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; + +function v4(options) { + if (!options && crypto.randomUUID) { + return crypto.randomUUID(); + } + return "fallback"; +} +console.log(shape.test(v4()), v4({})); +console.log(shape.test(globalThis.crypto.randomUUID())); +console.log(typeof crypto.randomUUID, typeof crypto.getRandomValues, typeof crypto.subtle); +console.log(crypto.randomUUID.name, crypto.getRandomValues.name, crypto.getRandomValues.length); + +const native = typeof crypto !== "undefined" && crypto.randomUUID ? { randomUUID: crypto.randomUUID.bind(crypto) } : {}; +console.log(shape.test(native.randomUUID())); + +const rng = (n) => crypto.getRandomValues(new Uint8Array(n)); +console.log(rng(16).length, rng(16) instanceof Uint8Array); +const words = new Uint32Array(4); +console.log(crypto.getRandomValues(words) === words); + +function attempt(label, run) { + try { + console.log(label, run()); + } catch (e) { + console.log(label, e.name, e.code, e.message); + } +} +attempt("no argument", () => crypto.getRandomValues()); +attempt("float view", () => crypto.getRandomValues(new Float64Array(2))); +attempt("too long", () => crypto.getRandomValues(new Uint8Array(65537))); diff --git a/tests/corpus/7122-webcrypto-node-crypto.ts b/tests/corpus/7122-webcrypto-node-crypto.ts new file mode 100644 index 000000000..c0ada7939 --- /dev/null +++ b/tests/corpus/7122-webcrypto-node-crypto.ts @@ -0,0 +1,38 @@ +// WebCrypto reached through node:crypto: the webcrypto export (named and +// through the namespace), the module's own subtle export, and their +// identity with the crypto global. Each form runs the same HMAC and +// digest calls as the global. +import * as nodeCrypto from "node:crypto"; +import { subtle, webcrypto } from "node:crypto"; + +const encoder = new TextEncoder(); +const message = encoder.encode("node:crypto webcrypto"); + +function hex(buffer: ArrayBuffer): string { + return Buffer.from(buffer).toString("hex"); +} + +console.log(webcrypto === crypto, webcrypto === globalThis.crypto, nodeCrypto.webcrypto === crypto); +console.log(hex(await webcrypto.subtle.digest("SHA-256", message))); +console.log(hex(await subtle.digest("SHA-1", message))); +console.log(hex(await nodeCrypto.subtle.digest({ name: "SHA-384" }, message))); +console.log(hex(await nodeCrypto.webcrypto.subtle.digest("SHA-512", message))); + +const secret = encoder.encode("shared secret"); +const params = { name: "HMAC", hash: "SHA-256" }; +const signer = await webcrypto.subtle.importKey("raw", secret, params, false, ["sign"]); +const verifier = await subtle.importKey("raw", secret, params, false, ["verify"]); +const signature = await nodeCrypto.subtle.sign("HMAC", signer, message); +console.log(hex(signature)); +console.log(await nodeCrypto.webcrypto.subtle.verify("HMAC", verifier, signature, message)); +console.log(await subtle.verify("HMAC", verifier, signature, encoder.encode("other"))); +console.log(signer instanceof CryptoKey, signer.algorithm.name, verifier.usages.join(",")); + +const shape = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; +console.log(shape.test(webcrypto.randomUUID()), shape.test(nodeCrypto.webcrypto.randomUUID())); +console.log(webcrypto.getRandomValues(new Uint32Array(4)).length); +try { + await subtle.digest("MD5", message); +} catch (e) { + console.log((e as Error).name, (e as Error).message); +} diff --git a/tests/corpus/7123-webcrypto-node-crypto.cjs b/tests/corpus/7123-webcrypto-node-crypto.cjs new file mode 100644 index 000000000..b11131d4b --- /dev/null +++ b/tests/corpus/7123-webcrypto-node-crypto.cjs @@ -0,0 +1,31 @@ +// node:crypto's WebCrypto from CommonJS: destructured webcrypto and +// subtle, the module object's members, the +// `globalThis.crypto ?? require("crypto").webcrypto` fallback libraries +// use to find a Crypto object, and crypto destructured from globalThis, +// all the same object. +const nodeCrypto = require("node:crypto"); +const { webcrypto, subtle } = require("crypto"); + +const encoder = new TextEncoder(); +const hex = (buffer) => Buffer.from(new Uint8Array(buffer)).toString("hex"); + +function cryptoObject() { + return globalThis.crypto ?? nodeCrypto.webcrypto; +} + +async function main() { + console.log(webcrypto === globalThis.crypto, cryptoObject() === crypto, typeof subtle); + console.log(hex(await webcrypto.subtle.digest("SHA-256", encoder.encode("abc")))); + console.log(hex(await subtle.digest("SHA-1", encoder.encode("abc")))); + console.log(hex(await nodeCrypto.subtle.digest("SHA-256", encoder.encode("abc")))); + const key = await nodeCrypto.webcrypto.subtle.importKey("raw", encoder.encode("k"), { name: "HMAC", hash: "SHA-1" }, true, ["sign"]); + console.log(hex(await subtle.sign("HMAC", key, encoder.encode("abc")))); + const wc = cryptoObject(); + console.log(wc.randomUUID().length, wc.getRandomValues(new Uint8Array(8)).length); + console.log(typeof webcrypto.randomUUID, typeof nodeCrypto.webcrypto.getRandomValues); + const { crypto: destructured } = globalThis; + console.log(destructured === webcrypto, destructured.randomUUID().length); + console.log(hex(await destructured.subtle.digest("SHA-1", encoder.encode("abc")))); +} + +main(); diff --git a/tests/corpus/7124-webcrypto-secret-keys.ts b/tests/corpus/7124-webcrypto-secret-keys.ts new file mode 100644 index 000000000..8f1f5d601 --- /dev/null +++ b/tests/corpus/7124-webcrypto-secret-keys.ts @@ -0,0 +1,91 @@ +// crypto.crypto.subtle.generateKey, exportKey and importKey for secret keys: +// HMAC and AES keys generated at every length, exported as raw bytes and +// as JSON Web Keys, imported back from both forms, and PBKDF2 and HKDF +// base keys imported from raw bytes. Random key bytes are checked by +// length and round trip, not by value. +const encoder = new TextEncoder(); + +type Key = Awaited>; + +function describe(key: Key): string { + return JSON.stringify({ + type: key.type, + extractable: key.extractable, + algorithm: key.algorithm, + usages: key.usages, + }); +} + +function hex(buffer: ArrayBuffer): string { + return Buffer.from(buffer).toString("hex"); +} + +async function show(label: string, run: () => Promise): Promise { + try { + console.log(label, await run()); + } catch (e) { + const error = e as Error & { code?: string }; + console.log(label, "rejects", error.name, error.code, error.message); + } +} + +for (const hash of ["SHA-1", "SHA-256", "SHA-384", "SHA-512"]) { + await show(`hmac ${hash}`, async () => { + const key = await crypto.subtle.generateKey({ name: "HMAC", hash }, true, ["sign", "verify"]); + const raw = await crypto.subtle.exportKey("raw", key); + return `${describe(key)} ${raw.byteLength}`; + }); +} +await show("hmac length 100", async () => { + const key = await crypto.subtle.generateKey({ name: "HMAC", hash: { name: "SHA-512" }, length: 100 }, true, ["sign"]); + const raw = new Uint8Array(await crypto.subtle.exportKey("raw", key)); + return `${describe(key)} ${raw.length} ${raw[12]! & 0x0f}`; +}); +for (const name of ["AES-GCM", "AES-CBC", "AES-CTR", "AES-KW"]) { + for (const length of [128, 192, 256]) { + await show(`${name} ${length}`, async () => { + const usages: ("wrapKey" | "unwrapKey" | "encrypt" | "decrypt")[] = + name === "AES-KW" ? ["wrapKey", "unwrapKey"] : ["encrypt", "decrypt"]; + const key = await crypto.subtle.generateKey({ name, length }, true, usages); + const jwk = await crypto.subtle.exportKey("jwk", key); + return `${describe(key)} ${jwk.alg} ${jwk.kty} ${jwk.k!.length} ${JSON.stringify(jwk.key_ops)} ${jwk.ext}`; + }); + } +} + +// Fixed key bytes: the exported forms are deterministic. +const bytes = new Uint8Array(32); +for (let i = 0; i < bytes.length; i++) bytes[i] = i * 7 + 1; +const hmac = await crypto.subtle.importKey("raw", bytes, { name: "HMAC", hash: "SHA-384" }, true, ["verify", "sign"]); +const hmacJwk = await crypto.subtle.exportKey("jwk", hmac); +console.log(JSON.stringify(hmacJwk), Object.keys(hmacJwk).join(",")); +console.log(hex(await crypto.subtle.exportKey("raw", hmac)) === Buffer.from(bytes).toString("hex")); +const reimported = await crypto.subtle.importKey("jwk", hmacJwk, { name: "HMAC", hash: "SHA-384" }, true, ["sign"]); +console.log(describe(reimported)); +const signature = await crypto.subtle.sign("HMAC", reimported, encoder.encode("payload")); +console.log(await crypto.subtle.verify("HMAC", hmac, signature, encoder.encode("payload"))); + +const short = await crypto.subtle.importKey("raw", bytes.subarray(0, 20), { name: "HMAC", hash: "SHA-1", length: 156 }, true, ["sign"]); +console.log(describe(short), JSON.stringify(await crypto.subtle.exportKey("jwk", short))); +console.log(hex(await crypto.subtle.exportKey("raw-secret", short))); + +for (const length of [16, 24, 32]) { + const key = await crypto.subtle.importKey("raw", bytes.subarray(0, length), "AES-GCM", true, ["encrypt"]); + const jwk = await crypto.subtle.exportKey("jwk", key); + console.log(describe(key), JSON.stringify(jwk)); + const back = await crypto.subtle.importKey("jwk", jwk, { name: "AES-GCM" }, false, ["encrypt"]); + console.log(describe(back)); +} +const cbc = await crypto.subtle.importKey("raw-secret", bytes.subarray(0, 16), "aes-cbc", true, ["decrypt", "unwrapKey"]); +console.log(describe(cbc), hex(await crypto.subtle.exportKey("raw", cbc))); +const wrap = await crypto.subtle.importKey("raw", bytes.subarray(0, 24), "AES-KW", true, ["unwrapKey", "wrapKey"]); +console.log(describe(wrap), JSON.stringify(await crypto.subtle.exportKey("jwk", wrap))); + +const password = encoder.encode("correct horse battery staple"); +const pbkdf2 = await crypto.subtle.importKey("raw", password, "PBKDF2", false, ["deriveBits", "deriveKey"]); +console.log(describe(pbkdf2)); +const hkdf = await crypto.subtle.importKey("raw-secret", bytes, { name: "hkdf" }, false, ["deriveKey"]); +console.log(describe(hkdf)); +const empty = await crypto.subtle.importKey("raw", new Uint8Array(0), "PBKDF2", false, ["deriveBits"]); +console.log(describe(empty)); +console.log(hmac instanceof CryptoKey, pbkdf2 instanceof CryptoKey); diff --git a/tests/corpus/7125-webcrypto-key-errors.mjs b/tests/corpus/7125-webcrypto-key-errors.mjs new file mode 100644 index 000000000..7f14ae0d7 --- /dev/null +++ b/tests/corpus/7125-webcrypto-key-errors.mjs @@ -0,0 +1,95 @@ +// Rejections of crypto.crypto.subtle.generateKey, exportKey and importKey for +// secret keys, in Node's order: argument conversion, algorithm +// normalization, usages, then the per-algorithm checks, and the JSON Web +// Key validation of oct keys. + +async function attempt(label, run) { + try { + const value = await run(); + const shown = value instanceof ArrayBuffer ? `ArrayBuffer(${value.byteLength})` : value instanceof CryptoKey ? JSON.stringify(value.algorithm) : JSON.stringify(value); + console.log(label, "resolves", shown); + } catch (e) { + console.log(label, e.name, e.code, e.message); + } +} + +await attempt("generate too few", () => crypto.subtle.generateKey({ name: "HMAC", hash: "SHA-1" }, true)); +await attempt("generate unknown", () => crypto.subtle.generateKey({ name: "FOO" }, true, ["sign"])); +await attempt("generate PBKDF2", () => crypto.subtle.generateKey({ name: "PBKDF2" }, false, ["deriveBits"])); +await attempt("generate no name", () => crypto.subtle.generateKey({ hash: "SHA-1" }, true, ["sign"])); +await attempt("generate hmac string", () => crypto.subtle.generateKey("HMAC", true, ["sign"])); +await attempt("generate hmac no hash", () => crypto.subtle.generateKey({ name: "HMAC" }, true, ["sign"])); +await attempt("generate hmac md5", () => crypto.subtle.generateKey({ name: "HMAC", hash: "MD5" }, true, ["sign"])); +await attempt("generate hmac bogus hash", () => crypto.subtle.generateKey({ name: "HMAC", hash: "SHA-999" }, true, ["sign"])); +await attempt("generate hmac length 0", () => crypto.subtle.generateKey({ name: "HMAC", hash: "SHA-1", length: 0 }, true, ["sign"])); +await attempt("generate hmac length NaN", () => crypto.subtle.generateKey({ name: "HMAC", hash: "SHA-1", length: NaN }, true, ["sign"])); +await attempt("generate hmac length -1", () => crypto.subtle.generateKey({ name: "HMAC", hash: "SHA-1", length: -1 }, true, ["sign"])); +await attempt("generate hmac encrypt", () => crypto.subtle.generateKey({ name: "HMAC", hash: "SHA-1" }, true, ["encrypt"])); +await attempt("generate hmac no usages", () => crypto.subtle.generateKey({ name: "HMAC", hash: "SHA-1" }, true, [])); +await attempt("generate bad usage", () => crypto.subtle.generateKey({ name: "HMAC", hash: "SHA-1" }, true, ["fly"])); +await attempt("generate usages string", () => crypto.subtle.generateKey({ name: "HMAC", hash: "SHA-1" }, true, "sign")); +await attempt("generate aes no length", () => crypto.subtle.generateKey({ name: "AES-GCM" }, true, ["encrypt"])); +await attempt("generate aes length 100", () => crypto.subtle.generateKey({ name: "AES-GCM", length: 100 }, true, ["encrypt"])); +await attempt("generate aes length 70000", () => crypto.subtle.generateKey({ name: "AES-CBC", length: 70000 }, true, ["encrypt"])); +await attempt("generate aes sign", () => crypto.subtle.generateKey({ name: "AES-CTR", length: 128 }, true, ["sign"])); +await attempt("generate aes-kw encrypt", () => crypto.subtle.generateKey({ name: "AES-KW", length: 128 }, true, ["encrypt"])); +await attempt("generate aes no usages", () => crypto.subtle.generateKey({ name: "AES-GCM", length: 128 }, true, [])); +await attempt("generate aes string length", async () => (await crypto.subtle.generateKey({ name: "aes-gcm", length: "256" }, true, ["encrypt"])).algorithm); + +const hmac = await crypto.subtle.importKey("raw", new Uint8Array(20), { name: "HMAC", hash: "SHA-256" }, true, ["sign"]); +const locked = await crypto.subtle.importKey("raw", new Uint8Array(16), "AES-GCM", false, ["encrypt"]); +const pbkdf2 = await crypto.subtle.importKey("raw", new Uint8Array(4), "PBKDF2", false, ["deriveBits"]); +await attempt("export too few", () => crypto.subtle.exportKey("raw")); +await attempt("export bad format", () => crypto.subtle.exportKey("pem", hmac)); +await attempt("export not a key", () => crypto.subtle.exportKey("raw", { type: "secret" })); +await attempt("export spki", () => crypto.subtle.exportKey("spki", hmac)); +await attempt("export pkcs8", () => crypto.subtle.exportKey("pkcs8", hmac)); +await attempt("export raw-public", () => crypto.subtle.exportKey("raw-public", hmac)); +await attempt("export non-extractable", () => crypto.subtle.exportKey("raw", locked)); +await attempt("export pbkdf2", () => crypto.subtle.exportKey("raw", pbkdf2)); +await attempt("export pbkdf2 jwk", () => crypto.subtle.exportKey("jwk", pbkdf2)); + +const sixteen = new Uint8Array(16); +await attempt("import aes 15 bytes", () => crypto.subtle.importKey("raw", new Uint8Array(15), "AES-GCM", true, ["encrypt"])); +await attempt("import aes sign", () => crypto.subtle.importKey("raw", sixteen, "AES-GCM", true, ["sign"])); +await attempt("import aes-kw encrypt", () => crypto.subtle.importKey("raw", sixteen, "AES-KW", true, ["encrypt"])); +await attempt("import aes no usages", () => crypto.subtle.importKey("raw", sixteen, "AES-CBC", true, [])); +await attempt("import aes spki", () => crypto.subtle.importKey("spki", sixteen, "AES-CBC", true, ["encrypt"])); +await attempt("import aes length ignored", () => crypto.subtle.importKey("raw", sixteen, { name: "AES-CTR", length: 256 }, true, ["encrypt"])); +await attempt("import pbkdf2 extractable", () => crypto.subtle.importKey("raw", sixteen, "PBKDF2", true, ["deriveBits"])); +await attempt("import pbkdf2 sign", () => crypto.subtle.importKey("raw", sixteen, "PBKDF2", false, ["sign"])); +await attempt("import pbkdf2 no usages", () => crypto.subtle.importKey("raw", sixteen, "PBKDF2", false, [])); +await attempt("import hkdf jwk", () => crypto.subtle.importKey("jwk", { kty: "oct", k: "AAAA" }, "HKDF", false, ["deriveKey"])); +await attempt("import hkdf pkcs8", () => crypto.subtle.importKey("pkcs8", sixteen, "HKDF", false, ["deriveKey"])); +await attempt("sign with aes key", () => crypto.subtle.sign("HMAC", locked, sixteen)); + +const hs256 = { name: "HMAC", hash: "SHA-256" }; +const jwk = (data, alg = hs256, extractable = true, usages = ["sign"]) => crypto.subtle.importKey("jwk", data, alg, extractable, usages); +await attempt("jwk ok", () => jwk({ kty: "oct", k: "AAECAwQFBgc" })); +await attempt("jwk alg match", () => jwk({ kty: "oct", k: "AAECAwQFBgc", alg: "HS256" })); +await attempt("jwk alg mismatch", () => jwk({ kty: "oct", k: "AAECAwQFBgc", alg: "HS512" })); +await attempt("jwk no kty", () => jwk({ k: "AAECAwQFBgc" })); +await attempt("jwk kty RSA", () => jwk({ kty: "RSA", k: "AAECAwQFBgc" })); +await attempt("jwk no k", () => jwk({ kty: "oct" })); +await attempt("jwk k number", () => jwk({ kty: "oct", k: 5 })); +await attempt("jwk k empty", () => jwk({ kty: "oct", k: "" })); +await attempt("jwk k standard alphabet", () => jwk({ kty: "oct", k: "AA+/AA==" })); +await attempt("jwk k junk", () => jwk({ kty: "oct", k: "!!!!" })); +await attempt("jwk use enc", () => jwk({ kty: "oct", k: "AAECAwQFBgc", use: "enc" })); +await attempt("jwk use sig", () => jwk({ kty: "oct", k: "AAECAwQFBgc", use: "sig" })); +await attempt("jwk key_ops superset", () => jwk({ kty: "oct", k: "AAECAwQFBgc", key_ops: ["sign", "verify", "fly"] })); +await attempt("jwk key_ops missing", () => jwk({ kty: "oct", k: "AAECAwQFBgc", key_ops: ["verify"] })); +await attempt("jwk key_ops duplicate", () => jwk({ kty: "oct", k: "AAECAwQFBgc", key_ops: ["sign", "sign"] })); +await attempt("jwk key_ops string", () => jwk({ kty: "oct", k: "AAECAwQFBgc", key_ops: "sign" })); +await attempt("jwk ext false", () => jwk({ kty: "oct", k: "AAECAwQFBgc", ext: false })); +await attempt("jwk ext false locked", () => jwk({ kty: "oct", k: "AAECAwQFBgc", ext: false }, hs256, false)); +await attempt("jwk not an object", () => jwk("key")); +await attempt("jwk null", () => jwk(null)); +await attempt("jwk kty symbol", () => jwk({ kty: Symbol("oct"), k: "AA" })); +await attempt("jwk hmac length", () => jwk({ kty: "oct", k: "AAECAwQFBgc" }, { name: "HMAC", hash: "SHA-1", length: 60 })); +await attempt("jwk hmac length mismatch", () => jwk({ kty: "oct", k: "AAECAwQFBgc" }, { name: "HMAC", hash: "SHA-1", length: 128 })); +await attempt("jwk no usages", () => jwk({ kty: "oct", k: "AAECAwQFBgc" }, hs256, true, [])); +await attempt("jwk aes", () => jwk({ kty: "oct", k: "AAECAwQFBgcICQoLDA0ODw", alg: "A128GCM" }, "AES-GCM", true, ["encrypt"])); +await attempt("jwk aes alg mismatch", () => jwk({ kty: "oct", k: "AAECAwQFBgcICQoLDA0ODw", alg: "A256GCM" }, "AES-GCM", true, ["encrypt"])); +await attempt("jwk aes use sig", () => jwk({ kty: "oct", k: "AAECAwQFBgcICQoLDA0ODw", use: "sig" }, "AES-GCM", true, ["encrypt"])); +await attempt("jwk aes length", () => jwk({ kty: "oct", k: "AAECAwQFBgc" }, "AES-CBC", true, ["encrypt"])); diff --git a/tests/corpus/7126-webcrypto-aes.ts b/tests/corpus/7126-webcrypto-aes.ts new file mode 100644 index 000000000..0e7be7548 --- /dev/null +++ b/tests/corpus/7126-webcrypto-aes.ts @@ -0,0 +1,77 @@ +// crypto.crypto.subtle.encrypt and decrypt with AES-GCM, AES-CBC and AES-CTR: +// fixed keys, IVs and inputs give Node's exact ciphertexts, every key +// length and GCM tag length round-trips, and CTR counters wrap within +// their low `length` bits. +const encoder = new TextEncoder(); +const decoder = new TextDecoder(); + +function hex(buffer: ArrayBuffer): string { + return Buffer.from(buffer).toString("hex"); +} + +function bytes(length: number, seed: number): Uint8Array { + const out = new Uint8Array(length); + for (let i = 0; i < length; i++) out[i] = (i * 31 + seed) & 0xff; + return out; +} + +const plaintext = encoder.encode("The quick brown fox jumps over the lazy dog"); +for (const length of [16, 24, 32]) { + const raw = bytes(length, length); + const gcm = await crypto.subtle.importKey("raw", raw, "AES-GCM", false, ["encrypt", "decrypt"]); + const cbc = await crypto.subtle.importKey("raw", raw, "AES-CBC", false, ["encrypt", "decrypt"]); + const ctr = await crypto.subtle.importKey("raw", raw, "AES-CTR", false, ["encrypt", "decrypt"]); + const iv = bytes(12, 7); + const sealed = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, gcm, plaintext); + console.log("gcm", length, sealed.byteLength, hex(sealed)); + console.log(decoder.decode(await crypto.subtle.decrypt({ name: "AES-GCM", iv }, gcm, sealed))); + const aad = encoder.encode("header"); + const tagged = await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: aad, tagLength: 96 }, gcm, plaintext); + console.log("gcm aad", length, hex(tagged)); + console.log(decoder.decode(await crypto.subtle.decrypt({ name: "AES-GCM", iv, additionalData: aad, tagLength: 96 }, gcm, tagged))); + const cbcIv = bytes(16, 3); + const padded = await crypto.subtle.encrypt({ name: "AES-CBC", iv: cbcIv }, cbc, plaintext); + console.log("cbc", length, padded.byteLength, hex(padded)); + console.log(decoder.decode(await crypto.subtle.decrypt({ name: "AES-CBC", iv: cbcIv }, cbc, padded))); + const counter = bytes(16, 9); + const streamed = await crypto.subtle.encrypt({ name: "AES-CTR", counter, length: 64 }, ctr, plaintext); + console.log("ctr", length, hex(streamed)); + console.log(decoder.decode(await crypto.subtle.decrypt({ name: "AES-CTR", counter, length: 64 }, ctr, streamed))); +} + +const key = await crypto.subtle.importKey("raw", bytes(16, 1), "AES-GCM", true, ["encrypt", "decrypt"]); +for (const tagLength of [32, 64, 96, 104, 112, 120, 128]) { + const iv = bytes(16, tagLength); + const sealed = await crypto.subtle.encrypt({ name: "AES-GCM", iv, tagLength }, key, plaintext.subarray(0, 5)); + const opened = await crypto.subtle.decrypt({ name: "AES-GCM", iv, tagLength }, key, sealed); + console.log("tag", tagLength, sealed.byteLength, hex(sealed), decoder.decode(opened)); +} +console.log("gcm empty", hex(await crypto.subtle.encrypt({ name: "AES-GCM", iv: new Uint8Array(12) }, key, new Uint8Array(0)))); +console.log("gcm long iv", hex(await crypto.subtle.encrypt({ name: "AES-GCM", iv: bytes(128, 5) }, key, plaintext.subarray(0, 3)))); + +const cbcKey = await crypto.subtle.importKey("raw", bytes(16, 2), "AES-CBC", false, ["encrypt", "decrypt"]); +for (const length of [0, 1, 15, 16, 17, 32]) { + const sealed = await crypto.subtle.encrypt({ name: "AES-CBC", iv: new Uint8Array(16) }, cbcKey, bytes(length, 4)); + const opened = await crypto.subtle.decrypt({ name: "AES-CBC", iv: new Uint8Array(16) }, cbcKey, sealed); + console.log("cbc length", length, sealed.byteLength, opened.byteLength, hex(opened) === hex(bytes(length, 4).buffer as ArrayBuffer)); +} + +const ctrKey = await crypto.subtle.importKey("raw", new Uint8Array(16), "AES-CTR", false, ["encrypt"]); +const allOnes = new Uint8Array(16).fill(0xff); +const zeros = new Uint8Array(64); +console.log("ctr wrap 4", hex(await crypto.subtle.encrypt({ name: "AES-CTR", counter: allOnes, length: 4 }, ctrKey, zeros))); +console.log("ctr wrap 128", hex(await crypto.subtle.encrypt({ name: "AES-CTR", counter: allOnes, length: 128 }, ctrKey, zeros))); +console.log("ctr wrap 2", hex(await crypto.subtle.encrypt({ name: "AES-CTR", counter: allOnes, length: 2 }, ctrKey, zeros))); +console.log("ctr 1 bit, 2 blocks", hex(await crypto.subtle.encrypt({ name: "AES-CTR", counter: new Uint8Array(16), length: 1 }, ctrKey, zeros.subarray(0, 32)))); +console.log("ctr partial", hex(await crypto.subtle.encrypt({ name: "AES-CTR", counter: bytes(16, 6), length: 128 }, ctrKey, zeros.subarray(0, 21)))); + +const generated = await crypto.subtle.generateKey({ name: "AES-GCM", length: 256 }, true, ["encrypt", "decrypt"]); +const iv = crypto.getRandomValues(new Uint8Array(12)); +const message = encoder.encode("generated key round trip"); +const sealed = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, generated, message); +console.log(sealed.byteLength, decoder.decode(await crypto.subtle.decrypt({ name: "AES-GCM", iv }, generated, sealed))); +const exported = await crypto.subtle.exportKey("jwk", generated); +const reimported = await crypto.subtle.importKey("jwk", exported, "AES-GCM", false, ["decrypt"]); +console.log(decoder.decode(await crypto.subtle.decrypt({ name: "AES-GCM", iv }, reimported, sealed))); +console.log(decoder.decode(await crypto.subtle.decrypt({ name: "AES-GCM", iv }, generated, new DataView(sealed)))); +console.log(decoder.decode(await crypto.subtle.decrypt({ name: "AES-GCM", iv: iv.buffer as ArrayBuffer }, generated, Buffer.from(sealed)))); diff --git a/tests/corpus/7127-webcrypto-aes-errors.mjs b/tests/corpus/7127-webcrypto-aes-errors.mjs new file mode 100644 index 000000000..7ce51230a --- /dev/null +++ b/tests/corpus/7127-webcrypto-aes-errors.mjs @@ -0,0 +1,71 @@ +// Rejections of crypto.crypto.subtle.encrypt and decrypt in Node's order: +// argument conversion, the AesCbcParams, AesCtrParams and AeadParams +// dictionaries, the key checks, then the cipher's own OperationErrors +// (bad tags, bad padding, IV and counter limits). + +async function attempt(label, run) { + try { + const value = await run(); + console.log(label, "resolves", value instanceof ArrayBuffer ? `ArrayBuffer(${value.byteLength})` : value); + } catch (e) { + console.log(label, e.name, e.code, e.message); + } +} + +const raw = new Uint8Array(16).map((_, i) => i); +const gcm = await crypto.subtle.importKey("raw", raw, "AES-GCM", true, ["encrypt", "decrypt"]); +const cbc = await crypto.subtle.importKey("raw", raw, "AES-CBC", true, ["encrypt", "decrypt"]); +const ctr = await crypto.subtle.importKey("raw", raw, "AES-CTR", true, ["encrypt", "decrypt"]); +const encryptOnly = await crypto.subtle.importKey("raw", raw, "AES-GCM", true, ["encrypt"]); +const hmac = await crypto.subtle.importKey("raw", raw, { name: "HMAC", hash: "SHA-1" }, true, ["sign"]); +const iv12 = new Uint8Array(12); +const iv16 = new Uint8Array(16); +const data = new TextEncoder().encode("hello world"); + +await attempt("too few", () => crypto.subtle.encrypt({ name: "AES-GCM", iv: iv12 }, gcm)); +await attempt("decrypt too few", () => crypto.subtle.decrypt({ name: "AES-GCM", iv: iv12 })); +await attempt("not a key", () => crypto.subtle.encrypt({ name: "AES-GCM", iv: iv12 }, JSON.parse("{}"), data)); +await attempt("data string", () => crypto.subtle.encrypt({ name: "AES-GCM", iv: iv12 }, gcm, "hello")); +await attempt("unknown algorithm", () => crypto.subtle.encrypt({ name: "AES-XTS" }, gcm, data)); +await attempt("AES-KW", () => crypto.subtle.encrypt({ name: "AES-KW" }, gcm, data)); +await attempt("no name", () => crypto.subtle.encrypt({ iv: iv12 }, gcm, data)); +await attempt("string algorithm", () => crypto.subtle.encrypt("AES-GCM", gcm, data)); +await attempt("gcm no iv", () => crypto.subtle.encrypt({ name: "AES-GCM" }, gcm, data)); +await attempt("gcm iv string", () => crypto.subtle.encrypt({ name: "AES-GCM", iv: "abc" }, gcm, data)); +await attempt("gcm aad string", () => crypto.subtle.encrypt({ name: "AES-GCM", iv: iv12, additionalData: "x" }, gcm, data)); +await attempt("gcm aad null", () => crypto.subtle.encrypt({ name: "AES-GCM", iv: iv12, additionalData: null }, gcm, data)); +await attempt("gcm tag 100", () => crypto.subtle.encrypt({ name: "AES-GCM", iv: iv12, tagLength: 100 }, gcm, data)); +await attempt("gcm tag 300", () => crypto.subtle.encrypt({ name: "AES-GCM", iv: iv12, tagLength: 300 }, gcm, data)); +await attempt("gcm tag NaN", () => crypto.subtle.encrypt({ name: "AES-GCM", iv: iv12, tagLength: NaN }, gcm, data)); +await attempt("gcm tag string", () => crypto.subtle.encrypt({ name: "aes-gcm", iv: iv12, tagLength: "96" }, gcm, data)); +await attempt("gcm iv 11 bytes", () => crypto.subtle.encrypt({ name: "AES-GCM", iv: new Uint8Array(11) }, gcm, data)); +await attempt("gcm iv 129 bytes", () => crypto.subtle.encrypt({ name: "AES-GCM", iv: new Uint8Array(129) }, gcm, data)); +await attempt("gcm iv empty", () => crypto.subtle.encrypt({ name: "AES-GCM", iv: new Uint8Array(0) }, gcm, data)); +const sealed = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv: iv12 }, gcm, data)); +const tampered = sealed.slice(); +tampered[0] ^= 1; +await attempt("gcm tampered", () => crypto.subtle.decrypt({ name: "AES-GCM", iv: iv12 }, gcm, tampered)); +await attempt("gcm wrong aad", () => crypto.subtle.decrypt({ name: "AES-GCM", iv: iv12, additionalData: data }, gcm, sealed)); +await attempt("gcm wrong tag length", () => crypto.subtle.decrypt({ name: "AES-GCM", iv: iv12, tagLength: 96 }, gcm, sealed)); +await attempt("gcm shorter than tag", () => crypto.subtle.decrypt({ name: "AES-GCM", iv: iv12 }, gcm, new Uint8Array(15))); +await attempt("gcm tag only", () => crypto.subtle.decrypt({ name: "AES-GCM", iv: iv12 }, gcm, new Uint8Array(16))); +await attempt("cbc no iv", () => crypto.subtle.encrypt({ name: "AES-CBC" }, cbc, data)); +await attempt("cbc iv 12 bytes", () => crypto.subtle.encrypt({ name: "AES-CBC", iv: iv12 }, cbc, data)); +await attempt("cbc decrypt 15 bytes", () => crypto.subtle.decrypt({ name: "AES-CBC", iv: iv16 }, cbc, new Uint8Array(15))); +await attempt("cbc decrypt empty", () => crypto.subtle.decrypt({ name: "AES-CBC", iv: iv16 }, cbc, new Uint8Array(0))); +const block = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-CBC", iv: iv16 }, cbc, data)); +const badPad = block.slice(); +badPad[15] ^= 0x55; +await attempt("cbc bad padding", () => crypto.subtle.decrypt({ name: "AES-CBC", iv: iv16 }, cbc, badPad)); +await attempt("cbc other iv", () => crypto.subtle.decrypt({ name: "AES-CBC", iv: new Uint8Array(16).fill(1) }, cbc, block)); +await attempt("ctr no counter", () => crypto.subtle.encrypt({ name: "AES-CTR", length: 64 }, ctr, data)); +await attempt("ctr no length", () => crypto.subtle.encrypt({ name: "AES-CTR", counter: iv16 }, ctr, data)); +await attempt("ctr length 0", () => crypto.subtle.encrypt({ name: "AES-CTR", counter: iv16, length: 0 }, ctr, data)); +await attempt("ctr length 129", () => crypto.subtle.encrypt({ name: "AES-CTR", counter: iv16, length: 129 }, ctr, data)); +await attempt("ctr length 300", () => crypto.subtle.encrypt({ name: "AES-CTR", counter: iv16, length: 300 }, ctr, data)); +await attempt("ctr counter 8 bytes", () => crypto.subtle.encrypt({ name: "AES-CTR", counter: new Uint8Array(8), length: 64 }, ctr, data)); +await attempt("ctr 1 bit, 3 blocks", () => crypto.subtle.encrypt({ name: "AES-CTR", counter: iv16, length: 1 }, ctr, new Uint8Array(48))); +await attempt("ctr empty", () => crypto.subtle.encrypt({ name: "AES-CTR", counter: iv16, length: 1 }, ctr, new Uint8Array(0))); +await attempt("algorithm mismatch", () => crypto.subtle.encrypt({ name: "AES-CBC", iv: iv16 }, gcm, data)); +await attempt("hmac key", () => crypto.subtle.encrypt({ name: "AES-GCM", iv: iv12 }, hmac, data)); +await attempt("missing usage", () => crypto.subtle.decrypt({ name: "AES-GCM", iv: iv12 }, encryptOnly, sealed)); diff --git a/tests/corpus/7128-webcrypto-derive.ts b/tests/corpus/7128-webcrypto-derive.ts new file mode 100644 index 000000000..4badedb66 --- /dev/null +++ b/tests/corpus/7128-webcrypto-derive.ts @@ -0,0 +1,45 @@ +// crypto.crypto.subtle.deriveBits and deriveKey with PBKDF2 and HKDF: Node's +// exact derived bytes for every SHA digest, zero-length derivations, the +// SCRAM-style PBKDF2-then-HMAC chain, and derived AES and HMAC keys that +// encrypt and sign. +const encoder = new TextEncoder(); + +function hex(buffer: ArrayBuffer): string { + return Buffer.from(buffer).toString("hex"); +} + +const password = await crypto.subtle.importKey("raw", encoder.encode("pencil"), "PBKDF2", false, ["deriveBits", "deriveKey"]); +const ikm = await crypto.subtle.importKey("raw", encoder.encode("input keying material"), { name: "HKDF" }, false, ["deriveBits", "deriveKey"]); +const salt = encoder.encode("QSXCR+Q6sek8bf92"); +const info = encoder.encode("context"); + +for (const hash of ["SHA-1", "SHA-256", "SHA-384", "SHA-512"]) { + console.log("pbkdf2", hash, hex(await crypto.subtle.deriveBits({ name: "PBKDF2", hash, salt, iterations: 4096 }, password, 256))); + console.log("hkdf", hash, hex(await crypto.subtle.deriveBits({ name: "HKDF", hash: { name: hash }, salt, info }, ikm, 256))); +} +console.log("pbkdf2 0", (await crypto.subtle.deriveBits({ name: "PBKDF2", hash: "SHA-256", salt, iterations: 1 }, password, 0)).byteLength); +console.log("hkdf 0", (await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt, info }, ikm, 0)).byteLength); +console.log("hkdf empty salt and info", hex(await crypto.subtle.deriveBits({ name: "hkdf", hash: "SHA-256", salt: new Uint8Array(0), info: new Uint8Array(0) }, ikm, 128))); +console.log("hkdf max", (await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-1", salt, info }, ikm, 255 * 20 * 8)).byteLength); + +// SCRAM-SHA-256's client proof inputs, the way database drivers compute them. +const saltedPassword = await crypto.subtle.deriveBits({ name: "PBKDF2", hash: "SHA-256", salt, iterations: 4096 }, password, 256); +const salted = await crypto.subtle.importKey("raw", saltedPassword, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]); +const clientKey = await crypto.subtle.sign("HMAC", salted, encoder.encode("Client Key")); +console.log("client key", hex(clientKey)); +console.log("stored key", hex(await crypto.subtle.digest("SHA-256", clientKey))); + +const aes = await crypto.subtle.deriveKey({ name: "PBKDF2", hash: "SHA-256", salt, iterations: 1000 }, password, { name: "AES-GCM", length: 256 }, true, ["encrypt", "decrypt"]); +console.log(JSON.stringify(aes.algorithm), aes.usages.join(","), aes.extractable); +console.log("aes key", hex(await crypto.subtle.exportKey("raw", aes))); +const iv = new Uint8Array(12); +const sealed = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, aes, encoder.encode("derived")); +console.log(hex(sealed), new TextDecoder().decode(await crypto.subtle.decrypt({ name: "AES-GCM", iv }, aes, sealed))); + +const mac = await crypto.subtle.deriveKey({ name: "HKDF", hash: "SHA-256", salt, info }, ikm, { name: "HMAC", hash: "SHA-384" }, false, ["sign", "verify"]); +console.log(JSON.stringify(mac.algorithm), mac.extractable); +console.log("mac", hex(await crypto.subtle.sign("HMAC", mac, encoder.encode("message")))); +const shortMac = await crypto.subtle.deriveKey({ name: "HKDF", hash: "SHA-1", salt, info }, ikm, { name: "HMAC", hash: "SHA-1", length: 128 }, true, ["sign"]); +console.log(JSON.stringify(shortMac.algorithm), hex(await crypto.subtle.exportKey("raw", shortMac))); +const wrap = await crypto.subtle.deriveKey({ name: "HKDF", hash: "SHA-512", salt, info }, ikm, { name: "AES-KW", length: 128 }, true, ["wrapKey"]); +console.log(JSON.stringify(wrap.algorithm), JSON.stringify(await crypto.subtle.exportKey("jwk", wrap))); diff --git a/tests/corpus/7129-webcrypto-derive-errors.mjs b/tests/corpus/7129-webcrypto-derive-errors.mjs new file mode 100644 index 000000000..83149b61b --- /dev/null +++ b/tests/corpus/7129-webcrypto-derive-errors.mjs @@ -0,0 +1,72 @@ +// Rejections of crypto.crypto.subtle.deriveBits and deriveKey in Node's order: +// argument conversion, the Pbkdf2Params and HkdfParams dictionaries, the +// base key's usages and algorithm, the length rules, and for deriveKey +// the derived key type's normalization and import. +const encoder = new TextEncoder(); + +async function attempt(label, run) { + try { + const value = await run(); + const shown = value instanceof ArrayBuffer ? `ArrayBuffer(${value.byteLength})` : value instanceof CryptoKey ? JSON.stringify(value.algorithm) : value; + console.log(label, "resolves", shown); + } catch (e) { + console.log(label, e.name, e.code, e.message); + } +} + +const password = await crypto.subtle.importKey("raw", encoder.encode("password"), "PBKDF2", false, ["deriveBits", "deriveKey"]); +const ikm = await crypto.subtle.importKey("raw", encoder.encode("input key"), "HKDF", false, ["deriveBits", "deriveKey"]); +const bitsOnly = await crypto.subtle.importKey("raw", encoder.encode("x"), "PBKDF2", false, ["deriveBits"]); +const keyOnly = await crypto.subtle.importKey("raw", encoder.encode("x"), "PBKDF2", false, ["deriveKey"]); +const hmac = await crypto.subtle.importKey("raw", encoder.encode("x"), { name: "HMAC", hash: "SHA-1" }, false, ["sign"]); +const salt = encoder.encode("salt"); +const pbkdf2 = (extra = {}) => ({ name: "PBKDF2", hash: "SHA-256", salt, iterations: 1000, ...extra }); +const hkdf = (extra = {}) => ({ name: "HKDF", hash: "SHA-256", salt, info: encoder.encode("info"), ...extra }); + +await attempt("bits too few", () => crypto.subtle.deriveBits(pbkdf2())); +await attempt("bits not a key", () => crypto.subtle.deriveBits(pbkdf2(), JSON.parse("{}"), 64)); +await attempt("bits length null", () => crypto.subtle.deriveBits(pbkdf2(), password, null)); +await attempt("bits length undefined", () => crypto.subtle.deriveBits(pbkdf2(), password, undefined)); +await attempt("bits length absent", () => crypto.subtle.deriveBits(pbkdf2(), password)); +await attempt("bits length 12", () => crypto.subtle.deriveBits(pbkdf2(), password, 12)); +await attempt("bits length -1", () => crypto.subtle.deriveBits(pbkdf2(), password, -1)); +await attempt("bits length NaN", () => crypto.subtle.deriveBits(pbkdf2(), password, NaN)); +await attempt("bits length string", () => crypto.subtle.deriveBits(pbkdf2(), password, "64")); +await attempt("bits unknown", () => crypto.subtle.deriveBits({ name: "SCRYPT" }, password, 64)); +await attempt("bits no name", () => crypto.subtle.deriveBits({ hash: "SHA-1" }, password, 64)); +await attempt("pbkdf2 iterations 0", () => crypto.subtle.deriveBits(pbkdf2({ iterations: 0 }), password, 64)); +await attempt("pbkdf2 iterations 2^31", () => crypto.subtle.deriveBits(pbkdf2({ iterations: 2 ** 31 }), password, 64)); +await attempt("pbkdf2 iterations -1", () => crypto.subtle.deriveBits(pbkdf2({ iterations: -1 }), password, 64)); +await attempt("pbkdf2 no iterations", () => crypto.subtle.deriveBits({ name: "PBKDF2", hash: "SHA-256", salt }, password, 64)); +await attempt("pbkdf2 no salt", () => crypto.subtle.deriveBits({ name: "PBKDF2", hash: "SHA-256", iterations: 1 }, password, 64)); +await attempt("pbkdf2 no hash", () => crypto.subtle.deriveBits({ name: "PBKDF2", salt, iterations: 1 }, password, 64)); +await attempt("pbkdf2 string", () => crypto.subtle.deriveBits("PBKDF2", password, 64)); +await attempt("pbkdf2 md5", () => crypto.subtle.deriveBits(pbkdf2({ hash: "MD5" }), password, 64)); +await attempt("pbkdf2 bogus sha", () => crypto.subtle.deriveBits(pbkdf2({ hash: "SHA-999" }), password, 64)); +await attempt("pbkdf2 salt string", () => crypto.subtle.deriveBits(pbkdf2({ salt: "salt" }), password, 64)); +await attempt("pbkdf2 hkdf key", () => crypto.subtle.deriveBits(pbkdf2(), ikm, 64)); +await attempt("pbkdf2 hmac key", () => crypto.subtle.deriveBits(pbkdf2(), hmac, 64)); +await attempt("pbkdf2 no deriveBits usage", () => crypto.subtle.deriveBits(pbkdf2(), keyOnly, 64)); +await attempt("hkdf no info", () => crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt }, ikm, 64)); +await attempt("hkdf no salt", () => crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", info: salt }, ikm, 64)); +await attempt("hkdf info 1025 bytes", () => crypto.subtle.deriveBits(hkdf({ info: new Uint8Array(1025) }), ikm, 64)); +await attempt("hkdf over maximum", () => crypto.subtle.deriveBits(hkdf({ hash: "SHA-1" }), ikm, 255 * 20 * 8 + 8)); +await attempt("hkdf length 4", () => crypto.subtle.deriveBits(hkdf(), ikm, 4)); +await attempt("hkdf null", () => crypto.subtle.deriveBits(hkdf(), ikm, null)); + +const aes = { name: "AES-GCM", length: 128 }; +await attempt("key too few", () => crypto.subtle.deriveKey(pbkdf2(), password, aes, true)); +await attempt("key not a key", () => crypto.subtle.deriveKey(pbkdf2(), "key", aes, true, ["encrypt"])); +await attempt("key no deriveKey usage", () => crypto.subtle.deriveKey(pbkdf2(), bitsOnly, aes, true, ["encrypt"])); +await attempt("key mismatch", () => crypto.subtle.deriveKey(hkdf(), password, aes, true, ["encrypt"])); +await attempt("key aes no length", () => crypto.subtle.deriveKey(pbkdf2(), password, { name: "AES-GCM" }, true, ["encrypt"])); +await attempt("key aes length 100", () => crypto.subtle.deriveKey(pbkdf2(), password, { name: "AES-CBC", length: 100 }, true, ["encrypt"])); +await attempt("key aes sign usage", () => crypto.subtle.deriveKey(pbkdf2(), password, aes, true, ["sign"])); +await attempt("key aes no usages", () => crypto.subtle.deriveKey(pbkdf2(), password, aes, true, [])); +await attempt("key hmac no hash", () => crypto.subtle.deriveKey(pbkdf2(), password, { name: "HMAC" }, true, ["sign"])); +await attempt("key hmac length 0", () => crypto.subtle.deriveKey(pbkdf2(), password, { name: "HMAC", hash: "SHA-1", length: 0 }, true, ["sign"])); +await attempt("key hmac length 100", () => crypto.subtle.deriveKey(pbkdf2(), password, { name: "HMAC", hash: "SHA-1", length: 100 }, true, ["sign"])); +await attempt("key hkdf type", () => crypto.subtle.deriveKey(pbkdf2(), password, "HKDF", false, ["deriveBits"])); +await attempt("key unknown type", () => crypto.subtle.deriveKey(pbkdf2(), password, { name: "TWOFISH" }, true, ["encrypt"])); +await attempt("key pbkdf2 type", () => crypto.subtle.deriveKey(hkdf(), ikm, { name: "PBKDF2" }, false, ["deriveKey"])); +await attempt("key ok", () => crypto.subtle.deriveKey(pbkdf2(), password, aes, false, ["encrypt"])); diff --git a/tests/corpus/7130-typed-message-listeners.ts b/tests/corpus/7130-typed-message-listeners.ts new file mode 100644 index 000000000..b98983824 --- /dev/null +++ b/tests/corpus/7130-typed-message-listeners.ts @@ -0,0 +1,80 @@ +import { MessageChannel } from "node:worker_threads"; + +// 'message' listeners with typed parameters on MessageChannel ports. A +// message with the parameter's exact layout, and one with other keys, +// shared values or other kinds, reach the listener with the same values as +// in Node. +type Item = { id: number; name: string; done: boolean }; +type Nested = { label: string; item: Item }; + +const { port1, port2 } = new MessageChannel(); +// Each port's lines print in delivery order once every message arrived. +const lines: string[] = []; +const nestedLines: string[] = []; +const otherLines: string[] = []; +let pending = 0; +function finish(): void { + if (--pending === 0) { + for (const line of [...lines, ...nestedLines, ...otherLines]) console.log(line); + port1.close(); + channel.port1.close(); + other.port1.close(); + } +} + +port1.on("message", (value: number | string | Item | null | undefined) => { + if (value === null || value === undefined) lines.push(`unit ${String(value)}`); + else if (typeof value === "number") lines.push(`number ${value.toFixed(2)}`); + else if (typeof value === "string") lines.push(`string ${value.length} ${value}`); + else lines.push(`item ${value.id} ${value.name} ${value.done} ${JSON.stringify(value)}`); + finish(); +}); + +const sent: unknown[] = [ + 1.5, + -0, + "", + "héllo wörld", + null, + undefined, + { id: 1, name: "first", done: false }, + { id: 2, name: "", done: true }, + // An extra key stays beside the record. + { id: 4, name: "extra", done: false, note: "kept" }, +]; +pending += sent.length; +for (const value of sent) port2.postMessage(value); + +// Nested records, a value shared by two fields, and a second listener +// that reads the message untyped. +const channel = new MessageChannel(); +channel.port1.on("message", (value: Nested) => { + nestedLines.push(`nested ${value.label} ${value.item.id} ${value.item.name} ${JSON.stringify(value)}`); + finish(); +}); +channel.port1.on("message", (value: unknown) => { + nestedLines.push(`untyped ${JSON.stringify(value)}`); + finish(); +}); +const shared = { id: 5, name: "shared", done: true }; +const nested: unknown[] = [ + { label: "plain", item: { id: 6, name: "six", done: false } }, + { label: "shared", item: shared, again: shared }, +]; +pending += 2 * nested.length; +for (const value of nested) channel.port2.postMessage(value); + +// once listeners, and a listener added while the port delivers. +const other = new MessageChannel(); +other.port1.once("message", (value: Item) => { + otherLines.push(`once ${value.id} ${value.name}`); + other.port1.on("message", (later: number) => { + otherLines.push(`later ${later}`); + finish(); + }); + finish(); +}); +pending += 3; +other.port2.postMessage({ id: 7, name: "seven", done: true }); +other.port2.postMessage(8); +other.port2.postMessage(9); diff --git a/tests/corpus/7130-webcrypto-wrap-key.ts b/tests/corpus/7130-webcrypto-wrap-key.ts new file mode 100644 index 000000000..8cf51fab4 --- /dev/null +++ b/tests/corpus/7130-webcrypto-wrap-key.ts @@ -0,0 +1,69 @@ +// crypto.subtle.wrapKey and unwrapKey: AES-KW wrapping matches RFC 3394's +// test vectors, raw and JSON Web Key payloads round-trip (AES-KW pads the +// JWK's JSON with spaces to a multiple of 8 bytes), and AES-GCM, AES-CBC +// and AES-CTR wrap keys the way encrypt does. jose's A128KW and +// PBES2-HS256+A128KW content-key wrapping is the shape used here. +const encoder = new TextEncoder(); + +function hex(buffer: ArrayBuffer): string { + return Buffer.from(buffer).toString("hex"); +} + +type Key = Awaited>; + +function describe(key: Key): string { + return JSON.stringify({ algorithm: key.algorithm, usages: key.usages, extractable: key.extractable }); +} + +// RFC 3394 section 4: 128-, 192- and 256-bit key data under each KEK size. +const vectors: [string, string, string][] = [ + ["000102030405060708090A0B0C0D0E0F", "00112233445566778899AABBCCDDEEFF", "1fa68b0a8112b447aef34bd8fb5a7b829d3e862371d2cfe5"], + ["000102030405060708090A0B0C0D0E0F1011121314151617", "00112233445566778899AABBCCDDEEFF", "96778b25ae6ca435f92b5b97c050aed2468ab8a17ad84e5d"], + ["000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F", "00112233445566778899AABBCCDDEEFF", "64e8c3f9ce0f5ba263e9777905818a2a93c8191e7d6e8ae7"], + ["000102030405060708090A0B0C0D0E0F1011121314151617", "00112233445566778899AABBCCDDEEFF0001020304050607", "031d33264e15d33268f24ec260743edce1c6c7ddee725a936ba814915c6762d2"], + ["000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F", "00112233445566778899AABBCCDDEEFF000102030405060708090A0B0C0D0E0F", "28c9f404c4b810f4cbccb35cfb87f8263f5786e2d80ed326cbc7f0e71a99f43bfb988b9b7a02dd21"], +]; +for (const [kekHex, dataHex, expected] of vectors) { + const kek = await crypto.subtle.importKey("raw", Buffer.from(kekHex, "hex"), "AES-KW", false, ["wrapKey", "unwrapKey"]); + const data = await crypto.subtle.importKey("raw", Buffer.from(dataHex, "hex"), "AES-CBC", true, ["encrypt"]); + const wrapped = await crypto.subtle.wrapKey("raw", data, kek, "AES-KW"); + console.log(hex(wrapped) === expected, hex(wrapped)); + const unwrapped = await crypto.subtle.unwrapKey("raw", wrapped, kek, { name: "aes-kw" }, "AES-CBC", true, ["decrypt"]); + console.log(describe(unwrapped), hex(await crypto.subtle.exportKey("raw", unwrapped))); +} + +// jose's content-key wrap: an HMAC key wrapped raw, then unwrapped and exported. +const kek = await crypto.subtle.importKey("raw", new Uint8Array(16).fill(7), "AES-KW", true, ["wrapKey", "unwrapKey"]); +const cek = await crypto.subtle.importKey("raw", new Uint8Array(32).fill(9), { name: "HMAC", hash: "SHA-256" }, true, ["sign"]); +const wrappedCek = await crypto.subtle.wrapKey("raw", cek, kek, "AES-KW"); +console.log(hex(wrappedCek)); +const back = await crypto.subtle.unwrapKey("raw", wrappedCek, kek, "AES-KW", { hash: "SHA-256", name: "HMAC" }, true, ["sign"]); +console.log(describe(back), hex(await crypto.subtle.exportKey("raw", back))); + +// JSON Web Key payloads, padded for AES-KW. +const wrappedJwk = await crypto.subtle.wrapKey("jwk", cek, kek, "AES-KW"); +console.log(wrappedJwk.byteLength, hex(wrappedJwk)); +const fromJwk = await crypto.subtle.unwrapKey("jwk", wrappedJwk, kek, "AES-KW", { name: "HMAC", hash: "SHA-256" }, false, ["sign"]); +console.log(describe(fromJwk)); +const asRaw = await crypto.subtle.unwrapKey("raw", wrappedJwk, kek, "AES-KW", { name: "HMAC", hash: "SHA-256" }, true, ["sign"]); +const padded = new TextDecoder().decode(await crypto.subtle.exportKey("raw", asRaw)); +console.log(JSON.stringify(padded), padded.length); + +// The AES ciphers as wrapping algorithms. +const gcmKey = await crypto.subtle.importKey("raw", new Uint8Array(16).fill(3), "AES-GCM", false, ["wrapKey", "unwrapKey"]); +const iv = new Uint8Array(12).fill(1); +const gcmWrapped = await crypto.subtle.wrapKey("jwk", cek, gcmKey, { name: "AES-GCM", iv }); +console.log(gcmWrapped.byteLength, hex(gcmWrapped).slice(0, 64)); +console.log(describe(await crypto.subtle.unwrapKey("jwk", gcmWrapped, gcmKey, { name: "AES-GCM", iv }, { name: "HMAC", hash: "SHA-256" }, true, ["sign"]))); +const cbcKey = await crypto.subtle.importKey("raw", new Uint8Array(32).fill(4), "AES-CBC", false, ["wrapKey", "unwrapKey"]); +const cbcWrapped = await crypto.subtle.wrapKey("raw", cek, cbcKey, { name: "AES-CBC", iv: new Uint8Array(16) }); +console.log(hex(cbcWrapped)); +console.log(describe(await crypto.subtle.unwrapKey("raw", cbcWrapped, cbcKey, { name: "AES-CBC", iv: new Uint8Array(16) }, "AES-GCM", false, ["encrypt"]))); +const ctrKey = await crypto.subtle.importKey("raw", new Uint8Array(24).fill(5), "AES-CTR", false, ["wrapKey", "unwrapKey"]); +const ctr = { name: "AES-CTR", counter: new Uint8Array(16), length: 64 }; +const ctrWrapped = await crypto.subtle.wrapKey("raw", cek, ctrKey, ctr); +console.log(hex(ctrWrapped)); +const fromCtr = await crypto.subtle.unwrapKey("raw", ctrWrapped, ctrKey, ctr, { name: "HMAC", hash: "SHA-1" }, true, ["verify"]); +console.log(describe(fromCtr)); +const signature = await crypto.subtle.sign("HMAC", back, encoder.encode("message")); +console.log(hex(signature).slice(0, 32)); diff --git a/tests/corpus/7131-typed-worker-messages.ts b/tests/corpus/7131-typed-worker-messages.ts new file mode 100644 index 000000000..86197b4de --- /dev/null +++ b/tests/corpus/7131-typed-worker-messages.ts @@ -0,0 +1,54 @@ +import { MessageChannel, MessagePort, Worker, isMainThread, parentPort } from "node:worker_threads"; + +// 'message' listeners with typed parameters on a worker and its +// parentPort: records and numbers in both directions, and a message that +// carries a transferred MessagePort. +type Job = { id: number; text: string; urgent: boolean }; +type Reply = { id: number; length: number; upper: string }; + +if (isMainThread) { + const worker = new Worker(new URL(import.meta.url)); + // The worker's replies, then the port's, each in delivery order. + const replies: string[] = []; + const portLines: string[] = []; + let expected = 5; + const done = (): void => { + if (--expected > 0) return; + for (const line of [...replies, ...portLines]) console.log(line); + void worker.terminate(); + }; + worker.on("message", (reply: Reply | number) => { + if (typeof reply === "number") replies.push(`count ${reply}`); + else replies.push(`reply ${reply.id} ${reply.length} ${reply.upper}`); + done(); + }); + const jobs: Job[] = [ + { id: 1, text: "alpha", urgent: false }, + { id: 2, text: "βeta", urgent: true }, + { id: 3, text: "", urgent: false }, + ]; + for (const job of jobs) worker.postMessage(job); + worker.postMessage(jobs.length); + // A port in the message: the worker answers through it. + const { port1, port2 } = new MessageChannel(); + port1.on("message", (text: string) => { + portLines.push(`port ${text}`); + port1.close(); + done(); + }); + worker.postMessage({ port: port2 }, [port2]); +} else { + let count = 0; + parentPort!.on("message", (message: Job | number | { port: MessagePort }) => { + if (typeof message === "number") { + parentPort!.postMessage(count + message); + } else if ("port" in message) { + message.port.postMessage("through the port"); + message.port.close(); + } else { + count++; + const text = message.urgent ? message.text.toUpperCase() : message.text; + parentPort!.postMessage({ id: message.id, length: message.text.length, upper: text }); + } + }); +} diff --git a/tests/corpus/7131-webcrypto-wrap-key-errors.mjs b/tests/corpus/7131-webcrypto-wrap-key-errors.mjs new file mode 100644 index 000000000..23cb3e10d --- /dev/null +++ b/tests/corpus/7131-webcrypto-wrap-key-errors.mjs @@ -0,0 +1,65 @@ +// Rejections of crypto.crypto.subtle.wrapKey and unwrapKey in Node's order: +// argument conversion, wrap algorithm normalization (AES-KW, then the +// encrypt registry), the wrapping key's algorithm and usages, the export +// or import of the wrapped key, and the cipher's OperationErrors (AES-KW's +// length rules and integrity check), which reject on a later turn. + +async function attempt(label, run) { + try { + const value = await run(); + const shown = value instanceof ArrayBuffer ? `ArrayBuffer(${value.byteLength})` : value instanceof CryptoKey ? JSON.stringify([value.algorithm, value.usages]) : value; + console.log(label, "resolves", shown); + } catch (e) { + console.log(label, e.name, e.code, e.message); + } +} + +const kek = await crypto.subtle.importKey("raw", new Uint8Array(16).fill(1), "AES-KW", true, ["wrapKey", "unwrapKey"]); +const unwrapOnly = await crypto.subtle.importKey("raw", new Uint8Array(16).fill(1), "AES-KW", true, ["unwrapKey"]); +const gcm = await crypto.subtle.importKey("raw", new Uint8Array(16), "AES-GCM", true, ["wrapKey", "unwrapKey"]); +const hmac20 = await crypto.subtle.importKey("raw", new Uint8Array(20).fill(2), { name: "HMAC", hash: "SHA-256" }, true, ["sign"]); +const hmac32 = await crypto.subtle.importKey("raw", new Uint8Array(32).fill(2), { name: "HMAC", hash: "SHA-256" }, true, ["sign"]); +const locked = await crypto.subtle.importKey("raw", new Uint8Array(16), "AES-CBC", false, ["encrypt"]); +const password = await crypto.subtle.importKey("raw", new Uint8Array(4), "PBKDF2", false, ["deriveBits"]); +const hs256 = { name: "HMAC", hash: "SHA-256" }; + +await attempt("wrap too few", () => crypto.subtle.wrapKey("raw", hmac32, kek)); +await attempt("wrap bad format", () => crypto.subtle.wrapKey("pem", hmac32, kek, "AES-KW")); +await attempt("wrap key not a key", () => crypto.subtle.wrapKey("raw", JSON.parse("{}"), kek, "AES-KW")); +await attempt("wrap wrapping key not a key", () => crypto.subtle.wrapKey("raw", hmac32, JSON.parse("{}"), "AES-KW")); +await attempt("wrap unknown algorithm", () => crypto.subtle.wrapKey("raw", hmac32, kek, "AES-XTS")); +await attempt("wrap no name", () => crypto.subtle.wrapKey("raw", hmac32, kek, {})); +await attempt("wrap gcm without iv", () => crypto.subtle.wrapKey("raw", hmac32, gcm, "AES-GCM")); +await attempt("wrap mismatch", () => crypto.subtle.wrapKey("raw", hmac32, gcm, "AES-KW")); +await attempt("wrap ctr on gcm key", () => crypto.subtle.wrapKey("raw", hmac32, gcm, { name: "AES-CTR", counter: new Uint8Array(16), length: 64 })); +await attempt("wrap missing usage", () => crypto.subtle.wrapKey("raw", hmac32, unwrapOnly, "AES-KW")); +await attempt("wrap pbkdf2 key", () => crypto.subtle.wrapKey("raw", password, kek, "AES-KW")); +await attempt("wrap non-extractable", () => crypto.subtle.wrapKey("raw", locked, kek, "AES-KW")); +await attempt("wrap spki", () => crypto.subtle.wrapKey("spki", hmac32, kek, "AES-KW")); +await attempt("wrap 20 bytes with AES-KW", () => crypto.subtle.wrapKey("raw", hmac20, kek, "AES-KW")); +await attempt("wrap 20 bytes with AES-GCM", () => crypto.subtle.wrapKey("raw", hmac20, gcm, { name: "AES-GCM", iv: new Uint8Array(12) })); + +const wrapped = new Uint8Array(await crypto.subtle.wrapKey("raw", hmac32, kek, "AES-KW")); +const tampered = wrapped.slice(); +tampered[3] ^= 1; +const notJson = await crypto.subtle.wrapKey("raw", hmac32, kek, "AES-KW"); +await attempt("unwrap too few", () => crypto.subtle.unwrapKey("raw", wrapped, kek, "AES-KW", hs256, true)); +await attempt("unwrap data string", () => crypto.subtle.unwrapKey("raw", "x", kek, "AES-KW", hs256, true, ["sign"])); +await attempt("unwrap not a key", () => crypto.subtle.unwrapKey("raw", wrapped, JSON.parse("{}"), "AES-KW", hs256, true, ["sign"])); +await attempt("unwrap bad usage name", () => crypto.subtle.unwrapKey("raw", wrapped, kek, "AES-KW", hs256, true, ["fly"])); +await attempt("unwrap hmac without hash", () => crypto.subtle.unwrapKey("raw", wrapped, kek, "AES-KW", { name: "HMAC" }, true, ["sign"])); +await attempt("unwrap unknown key algorithm", () => crypto.subtle.unwrapKey("raw", wrapped, kek, "AES-KW", "TWOFISH", true, ["sign"])); +await attempt("unwrap mismatch", () => crypto.subtle.unwrapKey("raw", wrapped, gcm, "AES-KW", hs256, true, ["sign"])); +await attempt("unwrap missing usage", async () => crypto.subtle.unwrapKey("raw", wrapped, await crypto.subtle.importKey("raw", new Uint8Array(16).fill(1), "AES-KW", true, ["wrapKey"]), "AES-KW", hs256, true, ["sign"])); +await attempt("unwrap tampered", () => crypto.subtle.unwrapKey("raw", tampered, kek, "AES-KW", hs256, true, ["sign"])); +await attempt("unwrap 16 bytes", () => crypto.subtle.unwrapKey("raw", new Uint8Array(16), kek, "AES-KW", hs256, true, ["sign"])); +await attempt("unwrap 28 bytes", () => crypto.subtle.unwrapKey("raw", new Uint8Array(28), kek, "AES-KW", hs256, true, ["sign"])); +await attempt("unwrap bad key usage", () => crypto.subtle.unwrapKey("raw", wrapped, kek, "AES-KW", hs256, true, ["encrypt"])); +await attempt("unwrap empty usages", () => crypto.subtle.unwrapKey("raw", wrapped, kek, "AES-KW", hs256, true, [])); +await attempt("unwrap as pbkdf2", () => crypto.subtle.unwrapKey("raw", wrapped, kek, "AES-KW", "PBKDF2", false, ["deriveBits"])); +await attempt("unwrap as extractable pbkdf2", () => crypto.subtle.unwrapKey("raw", wrapped, kek, "AES-KW", "PBKDF2", true, ["deriveBits"])); +await attempt("unwrap raw bytes as jwk", () => crypto.subtle.unwrapKey("jwk", notJson, kek, "AES-KW", hs256, true, ["sign"])); +const jwkWrapped = await crypto.subtle.wrapKey("jwk", hmac32, kek, "AES-KW"); +await attempt("unwrap jwk with other usages", () => crypto.subtle.unwrapKey("jwk", jwkWrapped, kek, "AES-KW", hs256, true, ["sign", "verify"])); +await attempt("unwrap jwk as AES", () => crypto.subtle.unwrapKey("jwk", jwkWrapped, kek, "AES-KW", "AES-GCM", true, ["encrypt"])); +await attempt("unwrap jwk ok", () => crypto.subtle.unwrapKey("jwk", jwkWrapped, kek, "AES-KW", hs256, false, ["sign"])); diff --git a/tests/corpus/7132-jose-pbes2/main.mjs b/tests/corpus/7132-jose-pbes2/main.mjs new file mode 100644 index 000000000..1c0f1df13 --- /dev/null +++ b/tests/corpus/7132-jose-pbes2/main.mjs @@ -0,0 +1,50 @@ +// The real jose@6.2.12 PBES2 and AES key-wrap paths: EncryptJWT and +// jwtDecrypt from jose's public jose/jwt/encrypt, jose/jwt/decrypt and +// jose/errors entry points, over crypto.subtle importKey, deriveBits, +// wrapKey, unwrapKey, exportKey, encrypt and decrypt. node_modules/jose +// vendors the dist/webapi files those entry points load and their +// declarations, unmodified (MIT, LICENSE.md), with a package.json that +// exports only those entry points. Content keys and IVs are random, so +// tokens are checked by shape and by what they decrypt to. +import { EncryptJWT } from "jose/jwt/encrypt"; +import { jwtDecrypt } from "jose/jwt/decrypt"; +import * as errors from "jose/errors"; + +const encoder = new TextEncoder(); +const password = encoder.encode("correct horse battery staple"); +const kek = new Uint8Array(32); +for (let i = 0; i < kek.length; i++) kek[i] = i * 13 + 5; + +async function roundTrip(label, alg, enc, key, header = {}) { + const token = await new EncryptJWT({ sub: "alice", scope: "read", n: 1 }) + .setProtectedHeader({ alg, enc, ...header }) + .setIssuedAt(1_799_999_000) + .encrypt(key); + const parts = token.split("."); + const { payload, protectedHeader } = await jwtDecrypt(token, key, { + keyManagementAlgorithms: [alg], + currentDate: new Date(1_800_000_000_000), + }); + console.log(label, parts.length, parts[1].length > 0, payload.sub, payload.scope, payload.iat); + console.log(label, protectedHeader.alg, protectedHeader.enc, protectedHeader.p2c ?? "-"); + return token; +} + +const pbes = await roundTrip("pbes2 256", "PBES2-HS256+A128KW", "A256GCM", password); +await roundTrip("pbes2 384", "PBES2-HS384+A192KW", "A128CBC-HS256", password); +await roundTrip("pbes2 512", "PBES2-HS512+A256KW", "A256CBC-HS512", password); +await roundTrip("a128kw", "A128KW", "A128GCM", kek.subarray(0, 16)); +await roundTrip("a256kw", "A256KW", "A256CBC-HS512", kek); + +try { + await jwtDecrypt(pbes, encoder.encode("wrong password"), { keyManagementAlgorithms: ["PBES2-HS256+A128KW"] }); + console.log("wrong password accepted"); +} catch (e) { + console.log("wrong password", e instanceof errors.JWEDecryptionFailed, e.code); +} +try { + await jwtDecrypt(pbes, password); + console.log("unlisted algorithm accepted"); +} catch (e) { + console.log("unlisted algorithm", e instanceof errors.JOSEAlgNotAllowed, e.code); +} diff --git a/tests/corpus/7132-jose-pbes2/node_modules/jose/LICENSE.md b/tests/corpus/7132-jose-pbes2/node_modules/jose/LICENSE.md new file mode 100644 index 000000000..d0ec038a8 --- /dev/null +++ b/tests/corpus/7132-jose-pbes2/node_modules/jose/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2018 Filip Skokan + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/types/jwt/decrypt.d.ts b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/types/jwt/decrypt.d.ts new file mode 100644 index 000000000..cdf6a372a --- /dev/null +++ b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/types/jwt/decrypt.d.ts @@ -0,0 +1,34 @@ +import type * as t from '../types.d.ts'; +/** JWE decryption and JWT Claims Set validation options. */ +export interface JWTDecryptOptions extends t.DecryptOptions, t.JWTClaimVerificationOptions { +} +/** + * Resolves a JWT decryption key. No token components have been authenticated when this function is + * called. + */ +export interface JWTDecryptGetKey extends t.GetKeyFunction { +} +/** + * Decrypts a Compact JWE-formatted JWT and validates its Claims Set. + * + * @param key Private key or shared secret to decrypt and verify the JWT with. See + * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. + */ +export declare function jwtDecrypt(jwt: string | Uint8Array, key: t.KeyInput, options?: JWTDecryptOptions): Promise>; +/** + * Decrypts a JWT and validates its claims, returning the dynamically + * {@link t.ResolvedKey.key resolved key}. + * + * @param getKey Function resolving a private key or shared secret to decrypt and verify the JWT + * with. See {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. + */ +export declare function jwtDecrypt(jwt: string | Uint8Array, getKey: JWTDecryptGetKey, options?: JWTDecryptOptions): Promise & t.ResolvedKey>; +/** + * Accepts a key or key resolver. Use this overload when forwarding either form; the result includes + * `key` only when a resolver was used. + * + * @param key Private key or shared secret, or a function resolving one, to decrypt and verify the + * JWT with. See + * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. + */ +export declare function jwtDecrypt(jwt: string | Uint8Array, key: t.KeyInput | JWTDecryptGetKey, options?: JWTDecryptOptions): Promise & Partial>; diff --git a/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/types/jwt/encrypt.d.ts b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/types/jwt/encrypt.d.ts new file mode 100644 index 000000000..c39e4c994 --- /dev/null +++ b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/types/jwt/encrypt.d.ts @@ -0,0 +1,57 @@ +import type * as t from '../types.d.ts'; +/** @param payload Initial JWT Claims Set. Defaults to an empty object. */ +declare const EncryptJWT_base: new (payload?: t.JWTPayload) => t.ProduceJWT; +/** Builds and encrypts Compact JWE-formatted JSON Web Tokens. */ +export declare class EncryptJWT extends EncryptJWT_base { + #private; + /** + * Sets the JWE Protected Header. May only be called once. + * + * @param protectedHeader JWE Protected Header. Must contain an "alg" (JWE Algorithm) and "enc" + * (JWE Encryption Algorithm) properties. + */ + setProtectedHeader(protectedHeader: t.CompactJWEHeaderParameters): this; + /** + * Sets JWE Key Management parameters, such as ECDH-ES "apu" and "apv" or PBES2 "p2c", and adds + * them to the appropriate JOSE Header. Use this instead of the header setters for algorithm + * inputs. May only be called once. + */ + setKeyManagementParameters(parameters: t.JWEKeyManagementHeaderParameters): this; + /** + * Sets the content encryption key. By default, a suitable random key is generated for the JWE + * "enc" (Encryption Algorithm). May only be called once. + * + * @deprecated For testing and vector validation only; allow random generation in production. + */ + setContentEncryptionKey(cek: Uint8Array): this; + /** + * Sets the Initialization Vector for content encryption. By default, a suitable random IV is + * generated for the JWE "enc" (Encryption Algorithm). May only be called once. + * + * @deprecated For testing and vector validation only; allow random generation in production. + */ + setInitializationVector(iv: Uint8Array): this; + /** + * Replicates the "iss" (Issuer) Claim in the JWE Protected Header, exposing it without + * decryption. + */ + replicateIssuerAsHeader(): this; + /** + * Replicates the "sub" (Subject) Claim in the JWE Protected Header, exposing it without + * decryption. + */ + replicateSubjectAsHeader(): this; + /** + * Replicates the "aud" (Audience) Claim in the JWE Protected Header, exposing it without + * decryption. + */ + replicateAudienceAsHeader(): this; + /** + * Encrypts and returns the JWT. + * + * @param key Public key or shared secret to encrypt the JWT with. See + * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}. + */ + encrypt(key: t.KeyInput, options?: t.EncryptOptions): Promise; +} +export {}; diff --git a/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/types/types.d.ts b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/types/types.d.ts new file mode 100644 index 000000000..9815c018d --- /dev/null +++ b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/types/types.d.ts @@ -0,0 +1,736 @@ +/** Supported JWS "alg" (Algorithm) Header Parameter values. Availability depends on the runtime. */ +export type JWSAlgorithm = + | 'HS256' + | 'HS384' + | 'HS512' + | 'RS256' + | 'RS384' + | 'RS512' + | 'PS256' + | 'PS384' + | 'PS512' + | 'ES256' + | 'ES384' + | 'ES512' + | 'EdDSA' + | 'Ed25519' + | 'ML-DSA-44' + | 'ML-DSA-65' + | 'ML-DSA-87' + | (string & {}) + +/** Supported JWE "alg" (Algorithm) Header Parameter values. Availability depends on the runtime. */ +export type JWEKeyManagementAlgorithm = + | 'dir' + | 'A128KW' + | 'A192KW' + | 'A256KW' + | 'A128GCMKW' + | 'A192GCMKW' + | 'A256GCMKW' + | 'ECDH-ES' + | 'ECDH-ES+A128KW' + | 'ECDH-ES+A192KW' + | 'ECDH-ES+A256KW' + | 'RSA-OAEP' + | 'RSA-OAEP-256' + | 'RSA-OAEP-384' + | 'RSA-OAEP-512' + | 'PBES2-HS256+A128KW' + | 'PBES2-HS384+A192KW' + | 'PBES2-HS512+A256KW' + | (string & {}) + +/** + * Supported JWE "enc" (Encryption Algorithm) Header Parameter values. Availability depends on the + * runtime. + */ +export type JWEContentEncryptionAlgorithm = + | 'A128CBC-HS256' + | 'A192CBC-HS384' + | 'A256CBC-HS512' + | 'A128GCM' + | 'A192GCM' + | 'A256GCM' + | (string & {}) + +/** JWK "kty" (Key Type) Parameter values supported by this module. */ +export type JWKKeyType = 'EC' | 'RSA' | 'OKP' | 'AKP' | 'oct' | (string & {}) + +/** + * Generic JSON Web Key Parameters. + * + * > Note: This is declared as a type alias rather than an interface so that it satisfies the implicit index + * > signature of the `JsonWebKey` types shipped by `@types/node` and `lib.dom`. + */ +export type JWKParameters = { + /** JWK "kty" (Key Type) Parameter */ + kty?: JWKKeyType + /** JWK "alg" (Algorithm) Parameter */ + alg?: JWSAlgorithm | JWEKeyManagementAlgorithm | JWEContentEncryptionAlgorithm + /** Permitted key operations. */ + key_ops?: string[] + /** Whether the key may be exported. */ + ext?: boolean + + /** JWK "use" (Public Key Use) Parameter */ + use?: 'sig' | 'enc' | (string & {}) + /** X.509 certificate chain. */ + x5c?: string[] + /** X.509 certificate SHA-1 thumbprint. */ + x5t?: string + /** X.509 certificate SHA-256 thumbprint. */ + 'x5t#S256'?: string + /** X.509 certificate URL. */ + x5u?: string + + /** JWK "kid" (Key ID) Parameter */ + kid?: string +} + +/** Convenience interface for public OKP JSON Web Keys. */ +export interface JWK_OKP_Public extends JWKParameters { + /** Key pair subtype. */ + crv: string + /** Public key. */ + x: string +} + +/** Convenience interface for private OKP JSON Web Keys. */ +export interface JWK_OKP_Private extends JWK_OKP_Public { + /** Private key. */ + d: string +} + +/** Convenience interface for public AKP JSON Web Keys. */ +export interface JWK_AKP_Public extends JWKParameters { + /** JWK "alg" (Algorithm) Parameter */ + alg: string + + /** AKP JWK "pub" (The Public key) Parameter */ + pub: string +} + +/** Convenience interface for private AKP JSON Web Keys. */ +export interface JWK_AKP_Private extends JWK_AKP_Public { + /** AKP JWK "priv" (The Private Key) Parameter */ + priv: string +} + +/** Convenience interface for public EC JSON Web Keys. */ +export interface JWK_EC_Public extends JWKParameters { + /** Curve. */ + crv: string + /** Public key X coordinate. */ + x: string + /** Public key Y coordinate. */ + y: string +} + +/** Convenience interface for private EC JSON Web Keys. */ +export interface JWK_EC_Private extends JWK_EC_Public { + /** Private key. */ + d: string +} + +/** Convenience interface for public RSA JSON Web Keys. */ +export interface JWK_RSA_Public extends JWKParameters { + /** Public exponent. */ + e: string + /** Modulus. */ + n: string +} + +/** Convenience interface for private RSA JSON Web Keys. */ +export interface JWK_RSA_Private extends JWK_RSA_Public { + /** Private exponent. */ + d: string + /** First factor CRT exponent. */ + dp: string + /** Second factor CRT exponent. */ + dq: string + /** First prime factor. */ + p: string + /** Second prime factor. */ + q: string + /** First CRT coefficient. */ + qi: string +} + +/** Convenience interface for "oct" JSON Web Keys. */ +export interface JWK_oct extends JWKParameters { + /** Symmetric key value. */ + k: string +} + +/** + * JSON Web Key ({@link https://www.rfc-editor.org/info/rfc7517/ JWK}). "RSA", "EC", "OKP", "AKP", + * and "oct" key types are supported. + * + * > Note: This is declared as a type alias rather than an interface so that it satisfies the implicit index + * > signature of the `JsonWebKey` types shipped by `@types/node` and `lib.dom`. It spells out the + * > {@link JWKParameters} members rather than intersecting them so that every JWK member is documented + * > in one place. + */ +export type JWK = { + /** JWK "kty" (Key Type) Parameter */ + kty?: JWKKeyType + /** JWK "alg" (Algorithm) Parameter */ + alg?: JWSAlgorithm | JWEKeyManagementAlgorithm | JWEContentEncryptionAlgorithm + /** Permitted key operations. */ + key_ops?: string[] + /** Whether the key may be exported. */ + ext?: boolean + + /** JWK "use" (Public Key Use) Parameter */ + use?: 'sig' | 'enc' | (string & {}) + /** X.509 certificate chain. */ + x5c?: string[] + /** X.509 certificate SHA-1 thumbprint. */ + x5t?: string + /** X.509 certificate SHA-256 thumbprint. */ + 'x5t#S256'?: string + /** X.509 certificate URL. */ + x5u?: string + + /** JWK "kid" (Key ID) Parameter */ + kid?: string + /** EC curve or OKP key pair subtype. */ + crv?: string + /** Private RSA exponent, EC key, or OKP key. */ + d?: string + /** RSA first factor CRT exponent. */ + dp?: string + /** RSA second factor CRT exponent. */ + dq?: string + /** RSA public exponent. */ + e?: string + /** Symmetric key value. */ + k?: string + /** RSA modulus. */ + n?: string + /** RSA first prime factor. */ + p?: string + /** RSA second prime factor. */ + q?: string + /** RSA first CRT coefficient. */ + qi?: string + /** EC public key X coordinate or OKP public key. */ + x?: string + /** EC public key Y coordinate. */ + y?: string + + /** AKP JWK "pub" (Public Key) Parameter */ + pub?: string + + /** AKP JWK "priv" (Private key) Parameter */ + priv?: string + /** Additional RSA prime factors. */ + oth?: Array<{ + /** Factor CRT exponent. */ + d?: string + /** Prime factor. */ + r?: string + /** Factor CRT coefficient. */ + t?: string + }> +} + +/** Discriminated union of supported JSON Web Key shapes, narrowed by the "kty" (Key Type) Parameter. */ +// Intersect "kty" into each member separately: typedoc omits the parentheses in `X & (A | B)`. +export type AnyJWK = + | (JWK_EC_Private & { kty: 'EC' }) + | (JWK_EC_Public & { kty: 'EC' }) + | (JWK_RSA_Private & { kty: 'RSA' }) + | (JWK_RSA_Public & { kty: 'RSA' }) + | (JWK_OKP_Private & { kty: 'OKP' }) + | (JWK_OKP_Public & { kty: 'OKP' }) + | (JWK_AKP_Private & { kty: 'AKP' }) + | (JWK_AKP_Public & { kty: 'AKP' }) + | (JWK_oct & { kty: 'oct' }) + +/** Key or secret input accepted by all sign, verify, encrypt, and decrypt operations. */ +export type KeyInput = CryptoKey | KeyObject | JWK | Uint8Array + +/** Dynamic key resolver for consuming operations. */ +export interface GetKeyFunction { + /** + * Resolves a key for an unverified token. Throw if no suitable key can be resolved. + * + * @param token The consumed JWE or JWS token; none of its components have been verified. + */ + (protectedHeader: IProtectedHeader, token: IToken): Promise | KeyTypes +} + +/** Flattened JWS verification input. */ +export interface FlattenedJWSInput { + /** JWS Unprotected Header as a JSON object. Not integrity protected; omit when empty. */ + header?: JWSHeaderParameters + + /** Base64url-encoded payload; with `b64: false`, supply an unencoded string or Uint8Array. */ + payload: string | Uint8Array + + /** Base64url-encoded UTF-8 JWS Protected Header. Integrity protected; omit when empty. */ + protected?: string + + /** Base64url-encoded signature or MAC. */ + signature: string +} + +/** General JWS verification input. */ +export interface GeneralJWSInput { + /** Base64url-encoded payload; with `b64: false`, supply an unencoded string or Uint8Array. */ + payload: string | Uint8Array + + /** + * The "signatures" member value MUST be an array of JSON objects. Each object represents a + * signature or MAC over the JWS Payload and the JWS Protected Header. + */ + signatures: Omit[] +} + +/** + * Flattened JWS JSON Serialization token. The payload is an empty string when the + * {@link https://www.rfc-editor.org/info/rfc7797/ unencoded payload option} is used. + */ +export interface FlattenedJWS extends Partial { + payload: string + signature: string +} + +/** + * General JWS JSON Serialization token. The payload is an empty string when the + * {@link https://www.rfc-editor.org/info/rfc7797/ unencoded payload option} is used. + */ +export interface GeneralJWS { + payload: string + signatures: Omit[] +} + +/** Header Parameters common to JWE and JWS. */ +export interface JoseHeaderParameters { + /** "kid" (Key ID) Header Parameter */ + kid?: string + + /** X.509 certificate SHA-1 thumbprint. */ + x5t?: string + + /** X.509 certificate chain. */ + x5c?: string[] + + /** X.509 certificate URL. */ + x5u?: string + + /** JWK Set URL. */ + jku?: string + + /** Public JWK only; private and symmetric key parameters are not permitted. */ + jwk?: Omit + + /** "typ" (Type) Header Parameter */ + typ?: string + + /** Content type. */ + cty?: string +} + +/** Recognized JWS Header Parameters; additional members may also be present. */ +export interface JWSHeaderParameters extends JoseHeaderParameters { + /** JWS "alg" (Algorithm) Header Parameter */ + alg?: JWSAlgorithm + + /** + * Controls payload encoding and the JWS signing input as defined by + * {@link https://www.rfc-editor.org/info/rfc7797/ RFC7797}. Set to `false` and list `b64` in + * `crit` to use an unencoded payload. + */ + b64?: boolean + + /** Extension parameters that must be recognized. */ + crit?: string[] + + /** Any other JWS Header member. */ + [propName: string]: unknown +} + +/** Recognized JWE Key Management-related Header Parameters. */ +export interface JWEKeyManagementHeaderParameters { + /** ECDH-ES Agreement PartyUInfo bytes, used in ConcatKDF and added to the JOSE header. */ + apu?: Uint8Array + + /** ECDH-ES Agreement PartyVInfo bytes, used in ConcatKDF and added to the JOSE header. */ + apv?: Uint8Array + + /** PBES2 PBKDF2 iteration count, added to the JOSE header. */ + p2c?: number + + /** @deprecated For testing and vector validation only. */ + p2s?: Uint8Array + /** @deprecated For testing and vector validation only. */ + iv?: Uint8Array + /** @deprecated For testing and vector validation only. */ + epk?: CryptoKey | KeyObject +} + +/** Flattened JWE JSON Serialization token. */ +export interface FlattenedJWE { + /** + * Base64url-encoded additional authenticated data; integrity protected but not encrypted. Omit + * when empty. + */ + aad?: string + + /** Base64url-encoded ciphertext. */ + ciphertext: string + + /** Base64url-encoded encrypted key. Omit when empty. */ + encrypted_key?: string + + /** + * JWE Per-Recipient Unprotected Header as a JSON object. Not integrity protected; omit when + * empty. + */ + header?: JWEHeaderParameters + + /** Base64url-encoded initialization vector. Omit when empty. */ + iv?: string + + /** Base64url-encoded UTF-8 JWE Protected Header. Integrity protected; omit when empty. */ + protected?: string + + /** Base64url-encoded authentication tag. Omit when empty. */ + tag?: string + + /** JWE Shared Unprotected Header as a JSON object. Not integrity protected; omit when empty. */ + unprotected?: JWEHeaderParameters +} + +/** General JWE JSON Serialization token. */ +export interface GeneralJWE extends Omit { + recipients: Pick[] +} + +/** Recognized JWE Header Parameters; additional members may also be present. */ +export interface JWEHeaderParameters extends JoseHeaderParameters { + /** JWE "alg" (Algorithm) Header Parameter */ + alg?: JWEKeyManagementAlgorithm + + /** JWE "enc" (Encryption Algorithm) Header Parameter */ + enc?: JWEContentEncryptionAlgorithm + + /** Extension parameters that must be recognized. */ + crit?: string[] + + /** + * JWE compression algorithm. Only `"DEF"` (DEFLATE) is supported, requiring the runtime's + * `CompressionStream` / `DecompressionStream` APIs. + */ + zip?: 'DEF' | (string & {}) + + /** Any other JWE Header member. */ + [propName: string]: unknown +} + +/** Shared "crit" option for signing, verification, encryption, and decryption. */ +export interface CritOption { + /** + * Recognized "crit" (Critical) Header Parameter names. Set each value to `true` to require + * integrity protection, or `false` when protection is optional. The JWS `b64` extension is always + * recognized and processed. + * + * > Warning: Other extensions are only checked for syntax and optional integrity protection. Their presence + * > is not required by this option. You must check their presence and process them according to the + * > profile's validation steps after the operation succeeds. + */ + crit?: { + [propName: string]: boolean + } +} + +/** JWE Decryption options. */ +export interface DecryptOptions extends CritOption { + /** + * Accepted JWE "alg" (Algorithm) Header Parameter values. Defaults to all algorithms applicable + * to the key or secret except PBES2, which must be explicitly allowed. + */ + keyManagementAlgorithms?: JWEKeyManagementAlgorithm[] + + /** + * Accepted JWE "enc" (Encryption Algorithm) Header Parameter values. Defaults to all algorithms + * applicable to the key or secret. + */ + contentEncryptionAlgorithms?: JWEContentEncryptionAlgorithm[] + + /** + * Maximum "p2c" (PBES2 Count) Header Parameter value, limiting PBKDF2 iterations and their + * computational expense. Defaults to 10000; must be a positive safe integer or `Infinity` to + * disable the limit. + */ + maxPBES2Count?: number + + /** + * Maximum decompressed plaintext size in bytes. Defaults to 250000; `0` rejects compressed JWEs, + * and `Infinity` disables the limit. Other values must be positive safe integers. + */ + maxDecompressedLength?: number +} + +/** JWE Encryption options. */ +export interface EncryptOptions extends CritOption {} + +/** JWT Claims Set verification options. */ +export interface JWTClaimVerificationOptions { + /** Expected JWT "aud" (Audience) Claim value(s). Requires the claim to be present. */ + audience?: string | string[] + + /** + * Clock skew tolerance in seconds or a duration string (e.g. "5 seconds"). Applies to the "nbf" + * (Not Before) and "exp" (Expiration Time) claims, and to "iat" (Issued At) when + * {@link maxTokenAge} is set. + */ + clockTolerance?: string | number + + /** Expected JWT "iss" (Issuer) Claim value(s). Requires the claim to be present. */ + issuer?: string | string[] + + /** + * Maximum time since the JWT "iat" (Issued At) Claim, in seconds or a duration string (e.g. "2 + * hours"). Requires the claim to be present. + */ + maxTokenAge?: string | number + + /** Expected JWT "sub" (Subject) Claim value. Requires the claim to be present. */ + subject?: string + + /** Expected JWT "typ" (Type) Header Parameter value. Requires the parameter to be present. */ + typ?: string + + /** Date for NumericDate comparisons. Defaults to `new Date()`. */ + currentDate?: Date + + /** + * Additional claim names required in the JWT Claims Set. The {@link issuer}, {@link audience}, + * {@link subject}, and {@link maxTokenAge} options independently require "iss", "aud", "sub", and + * "iat", respectively. + */ + requiredClaims?: string[] +} + +/** JWS Verification options. */ +export interface VerifyOptions extends CritOption { + /** + * Accepted JWS "alg" (Algorithm) Header Parameter values. Defaults to all algorithms applicable + * to the key or secret. Unsecured JWTs (`alg: "none"`) are never accepted. + */ + algorithms?: JWSAlgorithm[] +} + +/** JWS Signing options. */ +export interface SignOptions extends CritOption {} + +/** Recognized JWT Claims Set members; additional members may also be present. */ +export interface JWTPayload { + /** JWT Issuer */ + iss?: string + + /** JWT Subject */ + sub?: string + + /** JWT Audience */ + aud?: string | string[] + + /** JWT ID */ + jti?: string + + /** Not valid before this Unix timestamp in seconds. */ + nbf?: number + + /** Expiration Unix timestamp in seconds. */ + exp?: number + + /** Issued-at Unix timestamp in seconds. */ + iat?: number + + /** Any other JWT Claim Set member. */ + [propName: string]: unknown +} + +/** Flattened JWE JSON Serialization decryption result. */ +export interface FlattenedDecryptResult { + /** JWE Additional Authenticated Data, integrity protected but not encrypted. */ + additionalAuthenticatedData?: Uint8Array + + /** Plaintext. */ + plaintext: Uint8Array + + /** JWE Protected Header. */ + protectedHeader?: JWEHeaderParameters + + /** JWE Shared Unprotected Header. Not integrity protected. */ + sharedUnprotectedHeader?: JWEHeaderParameters + + /** JWE Per-Recipient Unprotected Header. Not integrity protected. */ + unprotectedHeader?: JWEHeaderParameters +} + +/** General JWE JSON Serialization decryption result. */ +export interface GeneralDecryptResult extends FlattenedDecryptResult {} + +/** Compact JWE decryption result. */ +export interface CompactDecryptResult { + /** Plaintext. */ + plaintext: Uint8Array + + /** JWE Protected Header. */ + protectedHeader: CompactJWEHeaderParameters +} + +/** Flattened JWS JSON Serialization verification result. */ +export interface FlattenedVerifyResult { + /** JWS Payload. */ + payload: Uint8Array + + /** JWS Protected Header. */ + protectedHeader?: JWSHeaderParameters + + /** JWS Unprotected Header. Not integrity protected. */ + unprotectedHeader?: JWSHeaderParameters +} + +/** General JWS JSON Serialization verification result. */ +export interface GeneralVerifyResult extends FlattenedVerifyResult {} + +/** Compact JWS verification result. */ +export interface CompactVerifyResult { + /** JWS Payload. */ + payload: Uint8Array + + /** JWS Protected Header. */ + protectedHeader: CompactJWSHeaderParameters +} + +/** Signed JSON Web Token (JWT) verification result. */ +export interface JWTVerifyResult { + /** JWT Claims Set. */ + payload: PayloadType & + JWTPayload & + ([PayloadType] extends [object] ? unknown : unknown extends PayloadType ? unknown : never) + + /** JWS Protected Header. */ + protectedHeader: JWTHeaderParameters +} + +/** Encrypted JSON Web Token (JWT) decryption result. */ +export interface JWTDecryptResult { + /** JWT Claims Set. */ + payload: PayloadType & + JWTPayload & + ([PayloadType] extends [object] ? unknown : unknown extends PayloadType ? unknown : never) + + /** JWE Protected Header. */ + protectedHeader: CompactJWEHeaderParameters +} + +/** Key resolver result metadata. */ +export interface ResolvedKey { + /** The resolved key, present only when a key resolver is used. */ + key: KeyType +} + +/** Recognized Compact JWS Header Parameters; additional members may also be present. */ +export interface CompactJWSHeaderParameters extends JWSHeaderParameters { + alg: JWSAlgorithm +} + +/** Recognized signed JWT Header Parameters; additional members may also be present. */ +export interface JWTHeaderParameters extends CompactJWSHeaderParameters { + b64?: boolean +} + +/** Recognized Compact JWE Header Parameters; additional members may also be present. */ +export interface CompactJWEHeaderParameters extends JWEHeaderParameters { + alg: JWEKeyManagementAlgorithm + enc: JWEContentEncryptionAlgorithm +} + +/** JSON Web Key Set. */ +export interface JSONWebKeySet { + keys: JWK[] +} + +/** Node.js {@link !KeyObject} representation accepted as key input. */ +export interface KeyObject { + type: string +} + +/** The runtime's Web Crypto {@link !CryptoKey} representation accepted as key input. */ +export type CryptoKey = typeof globalThis extends { + crypto: { subtle: { generateKey(...args: any[]): Promise } } +} + ? Extract + : CryptoKeyStructuralFallback + +/** Structural fallback used when the host {@link !CryptoKey} type cannot be inferred. */ +export interface CryptoKeyStructuralFallback { + readonly algorithm: { name: string } + readonly extractable: boolean + readonly type: string + readonly usages: string[] +} + +/** Shared fluent API for JWT-producing classes. */ +export interface ProduceJWT { + /** + * Set the "iss" (Issuer) Claim. + * + * @param issuer "Issuer" Claim value to set on the JWT Claims Set. + */ + setIssuer(issuer: string): this + + /** + * Set the "sub" (Subject) Claim. + * + * @param subject "sub" (Subject) Claim value to set on the JWT Claims Set. + */ + setSubject(subject: string): this + + /** + * Set the "aud" (Audience) Claim. + * + * @param audience "aud" (Audience) Claim value to set on the JWT Claims Set. + */ + setAudience(audience: string | string[]): this + + /** + * Set the "jti" (JWT ID) Claim. + * + * @param jwtId "jti" (JWT ID) Claim value to set on the JWT Claims Set. + */ + setJti(jwtId: string): this + + /** + * Set the "nbf" (Not Before) Claim. Numbers are Unix timestamps in seconds; Dates are converted + * to seconds. Strings are relative to now, using seconds, minutes, hours, days, weeks, or years + * (365.25 days; no months). Prefix `-` or suffix `ago` subtracts the duration. + * + * @param input "nbf" (Not Before) Claim value as a timestamp, Date, or relative duration. + */ + setNotBefore(input: number | string | Date): this + + /** + * Set the "exp" (Expiration Time) Claim. Accepts a Unix timestamp in seconds, a Date, or a + * duration relative to now using the same formats as {@link setNotBefore}. + * + * @param input "exp" (Expiration Time) Claim value as a timestamp, Date, or relative duration. + */ + setExpirationTime(input: number | string | Date): this + + /** + * Set the "iat" (Issued At) Claim. Defaults to the current Unix timestamp in seconds. Accepts a + * Unix timestamp in seconds, a Date, or a duration relative to now using the same formats as + * {@link setNotBefore}. + * + * @param input "iat" (Issued At) Claim value as a timestamp, Date, or relative duration. + */ + setIssuedAt(input?: number | string | Date): this +} diff --git a/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/types/util/errors.d.ts b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/types/util/errors.d.ts new file mode 100644 index 000000000..930a29b9f --- /dev/null +++ b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/types/util/errors.d.ts @@ -0,0 +1,182 @@ +import type * as t from '../types.d.ts'; +/** Stable error codes used by this module. */ +export type JOSEErrorCode = 'ERR_JOSE_ALG_NOT_ALLOWED' | 'ERR_JOSE_GENERIC' | 'ERR_JOSE_NOT_SUPPORTED' | 'ERR_JWE_DECRYPTION_FAILED' | 'ERR_JWE_INVALID' | 'ERR_JWK_INVALID' | 'ERR_JWKS_INVALID' | 'ERR_JWKS_MULTIPLE_MATCHING_KEYS' | 'ERR_JWKS_NO_MATCHING_KEY' | 'ERR_JWKS_TIMEOUT' | 'ERR_JWS_INVALID' | 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED' | 'ERR_JWT_CLAIM_VALIDATION_FAILED' | 'ERR_JWT_EXPIRED' | 'ERR_JWT_INVALID'; +/** Shared details of JWT claim or header validation failures. */ +export interface JWTClaimValidationFailure { + /** Claim or header that failed validation. */ + claim: string; + /** Reason code for the validation failure. */ + reason: JWTClaimValidationReason; + /** The parsed JWT Claims Set; validation of other claims may be incomplete. */ + payload: t.JWTPayload; +} +/** Reason codes produced by JWT Claims Set validation. */ +export type JWTClaimValidationReason = 'check_failed' | 'invalid' | 'mismatch' | 'missing' | 'unspecified' | (string & {}); +/** Base class for JOSE errors. */ +export declare class JOSEError extends Error { + /** Stable code identifying the error class. */ + static code: JOSEErrorCode | (string & {}); + /** Stable code identifying the error class. Use {@link AnyJOSEError} to narrow subclasses by code. */ + code: JOSEErrorCode | (string & {}); + constructor(message?: string, options?: { + cause?: unknown; + }); +} +/** + * Thrown when JWT claim or header validation fails. Expiration is reported separately as + * {@link JWTExpired}. + */ +export declare class JWTClaimValidationFailed extends JOSEError implements JWTClaimValidationFailure { + static code: JOSEErrorCode | (string & {}); + code: JOSEErrorCode | (string & {}); + /** The {@link JWTClaimValidationFailure} details carried by this error. */ + cause: JWTClaimValidationFailure; + /** Claim or header that failed validation. */ + claim: string; + /** Reason code for the validation failure. */ + reason: JWTClaimValidationReason; + /** + * The parsed JWT Claims Set; validation of other claims may be incomplete. With + * {@link jwt/verify.jwtVerify jwtVerify} and {@link jwt/decrypt.jwtDecrypt jwtDecrypt}, token + * authentication precedes claim validation. {@link jwt/unsecured.UnsecuredJWT.decode} does not + * authenticate tokens. + */ + payload: t.JWTPayload; + constructor(message: string, payload: t.JWTPayload, claim?: string, reason?: JWTClaimValidationReason); +} +/** Thrown when a JWT has expired or exceeds the configured maximum token age. */ +export declare class JWTExpired extends JOSEError implements JWTClaimValidationFailure { + static code: JOSEErrorCode | (string & {}); + code: JOSEErrorCode | (string & {}); + /** The {@link JWTClaimValidationFailure} details carried by this error. */ + cause: JWTClaimValidationFailure; + /** Claim or header that failed validation. */ + claim: string; + /** Reason code for the validation failure. */ + reason: JWTClaimValidationReason; + /** + * The parsed JWT Claims Set; validation of other claims may be incomplete. With + * {@link jwt/verify.jwtVerify jwtVerify} and {@link jwt/decrypt.jwtDecrypt jwtDecrypt}, token + * authentication precedes claim validation. {@link jwt/unsecured.UnsecuredJWT.decode} does not + * authenticate tokens. + */ + payload: t.JWTPayload; + constructor(message: string, payload: t.JWTPayload, claim?: string, reason?: JWTClaimValidationReason); +} +/** Thrown when an algorithm is disallowed by configuration. */ +export declare class JOSEAlgNotAllowed extends JOSEError { + static code: JOSEErrorCode | (string & {}); + code: JOSEErrorCode | (string & {}); +} +/** Thrown when a feature or algorithm is unsupported. */ +export declare class JOSENotSupported extends JOSEError { + static code: JOSEErrorCode | (string & {}); + code: JOSEErrorCode | (string & {}); +} +/** Thrown when JWE ciphertext decryption or authentication fails. */ +export declare class JWEDecryptionFailed extends JOSEError { + static code: JOSEErrorCode | (string & {}); + code: JOSEErrorCode | (string & {}); + constructor(message?: string, options?: { + cause?: unknown; + }); +} +/** Thrown when a JWE is invalid. */ +export declare class JWEInvalid extends JOSEError { + static code: JOSEErrorCode | (string & {}); + code: JOSEErrorCode | (string & {}); +} +/** Thrown when a JWS is invalid. */ +export declare class JWSInvalid extends JOSEError { + static code: JOSEErrorCode | (string & {}); + code: JOSEErrorCode | (string & {}); +} +/** Thrown when a JWT is invalid. */ +export declare class JWTInvalid extends JOSEError { + static code: JOSEErrorCode | (string & {}); + code: JOSEErrorCode | (string & {}); +} +/** Thrown when a JWK is invalid. */ +export declare class JWKInvalid extends JOSEError { + static code: JOSEErrorCode | (string & {}); + code: JOSEErrorCode | (string & {}); +} +/** Thrown when a JWKS is invalid. */ +export declare class JWKSInvalid extends JOSEError { + static code: JOSEErrorCode | (string & {}); + code: JOSEErrorCode | (string & {}); +} +/** Thrown when no keys match in a JWKS. */ +export declare class JWKSNoMatchingKey extends JOSEError { + static code: JOSEErrorCode | (string & {}); + code: JOSEErrorCode | (string & {}); + constructor(message?: string, options?: { + cause?: unknown; + }); +} +/** Thrown when multiple keys match in a JWKS. */ +export declare class JWKSMultipleMatchingKeys extends JOSEError { + /** + * Yields public keys matching the JWS Header so verification can be attempted with each. See the + * {@link jwks/remote.createRemoteJWKSet createRemoteJWKSet} and + * {@link jwks/local.createLocalJWKSet createLocalJWKSet} examples. Empty on manually constructed + * errors. + */ + [Symbol.asyncIterator]: () => AsyncIterableIterator; + static code: JOSEErrorCode | (string & {}); + code: JOSEErrorCode | (string & {}); + constructor(message?: string, options?: { + cause?: unknown; + }); +} +/** Thrown when fetching a remote JWKS times out. */ +export declare class JWKSTimeout extends JOSEError { + static code: JOSEErrorCode | (string & {}); + code: JOSEErrorCode | (string & {}); + constructor(message?: string, options?: { + cause?: unknown; + }); +} +/** Thrown when JWS signature verification fails. */ +export declare class JWSSignatureVerificationFailed extends JOSEError { + static code: JOSEErrorCode | (string & {}); + code: JOSEErrorCode | (string & {}); + constructor(message?: string, options?: { + cause?: unknown; + }); +} +/** Errors thrown during JWT Claims Set validation. */ +export type JWTClaimValidationError = JWTClaimValidationFailed | JWTExpired; +/** + * Discriminated union of specific {@link JOSEError} subclasses, narrowed by `code`. Excludes base + * {@link JOSEError} instances; use `instanceof JOSEError` to catch all module errors. + */ +export type AnyJOSEError = (JOSEAlgNotAllowed & { + code: 'ERR_JOSE_ALG_NOT_ALLOWED'; +}) | (JOSENotSupported & { + code: 'ERR_JOSE_NOT_SUPPORTED'; +}) | (JWEDecryptionFailed & { + code: 'ERR_JWE_DECRYPTION_FAILED'; +}) | (JWEInvalid & { + code: 'ERR_JWE_INVALID'; +}) | (JWKInvalid & { + code: 'ERR_JWK_INVALID'; +}) | (JWKSInvalid & { + code: 'ERR_JWKS_INVALID'; +}) | (JWKSMultipleMatchingKeys & { + code: 'ERR_JWKS_MULTIPLE_MATCHING_KEYS'; +}) | (JWKSNoMatchingKey & { + code: 'ERR_JWKS_NO_MATCHING_KEY'; +}) | (JWKSTimeout & { + code: 'ERR_JWKS_TIMEOUT'; +}) | (JWSInvalid & { + code: 'ERR_JWS_INVALID'; +}) | (JWSSignatureVerificationFailed & { + code: 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED'; +}) | (JWTClaimValidationFailed & { + code: 'ERR_JWT_CLAIM_VALIDATION_FAILED'; +}) | (JWTExpired & { + code: 'ERR_JWT_EXPIRED'; +}) | (JWTInvalid & { + code: 'ERR_JWT_INVALID'; +}); diff --git a/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/jwt/decrypt.js b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/jwt/decrypt.js new file mode 100644 index 000000000..cfbe4730c --- /dev/null +++ b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/jwt/decrypt.js @@ -0,0 +1,13 @@ +import { prepareDecrypt, decryptCompact } from "../lib/jwe_decrypt.js"; +import { validateClaimsSet } from "../lib/jwt_claims_set.js"; +import { JWTClaimValidationFailed } from "../util/errors.js"; +async function jwtDecrypt(jwt, key, options) { + const { plaintext, ...result } = await decryptCompact(jwt, prepareDecrypt(options), key), { protectedHeader } = result, payload = validateClaimsSet(protectedHeader, plaintext, options); + for (const claim of ["iss", "sub", "aud"]) + if (protectedHeader[claim] !== void 0 && (claim === "aud" ? JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud) : protectedHeader[claim] !== payload[claim])) + throw new JWTClaimValidationFailed(`replicated "${claim}" claim header parameter mismatch`, payload, claim, "mismatch"); + return { payload, ...result }; +} +export { + jwtDecrypt +}; diff --git a/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/jwt/encrypt.js b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/jwt/encrypt.js new file mode 100644 index 000000000..c26908857 --- /dev/null +++ b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/jwt/encrypt.js @@ -0,0 +1,45 @@ +import { compactJWE, createJWE } from "../lib/jwe_encrypt.js"; +import { JWTClaimsBuilder, jwtClaim, jwtData } from "../lib/jwt_claims_set.js"; +import { assertNotSet } from "../lib/validate.js"; +const EncryptJWT_base = JWTClaimsBuilder; +class EncryptJWT extends EncryptJWT_base { + #input = [void 0]; + #replicateIssuerAsHeader; + #replicateSubjectAsHeader; + #replicateAudienceAsHeader; + setProtectedHeader(protectedHeader) { + return assertNotSet(this.#input[1], "setProtectedHeader"), this.#input[1] = protectedHeader, this; + } + setKeyManagementParameters(parameters) { + return assertNotSet(this.#input[7], "setKeyManagementParameters"), this.#input[7] = parameters, this; + } + setContentEncryptionKey(cek) { + return assertNotSet(this.#input[5], "setContentEncryptionKey"), this.#input[5] = cek, this; + } + setInitializationVector(iv) { + return assertNotSet(this.#input[6], "setInitializationVector"), this.#input[6] = iv, this; + } + replicateIssuerAsHeader() { + return this.#replicateIssuerAsHeader = !0, this; + } + replicateSubjectAsHeader() { + return this.#replicateSubjectAsHeader = !0, this; + } + replicateAudienceAsHeader() { + return this.#replicateAudienceAsHeader = !0, this; + } + async encrypt(key, options) { + const plaintext = jwtData(this); + this.#input[1] && (this.#replicateIssuerAsHeader || this.#replicateSubjectAsHeader || this.#replicateAudienceAsHeader) && (this.#input[1] = { + ...this.#input[1], + iss: this.#replicateIssuerAsHeader ? jwtClaim(this, "iss") : void 0, + sub: this.#replicateSubjectAsHeader ? jwtClaim(this, "sub") : void 0, + aud: this.#replicateAudienceAsHeader ? jwtClaim(this, "aud") : void 0 + }); + const input = [...this.#input]; + return input[0] = plaintext, compactJWE(await createJWE(input, key, options)); + } +} +export { + EncryptJWT +}; diff --git a/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/buffer_utils.js b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/buffer_utils.js new file mode 100644 index 000000000..b3cad85a9 --- /dev/null +++ b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/buffer_utils.js @@ -0,0 +1,75 @@ +const encoder = new TextEncoder(), decoder = new TextDecoder(), strictDecoder = new TextDecoder("utf-8", { fatal: !0 }), MAX_INT32 = 2 ** 32; +function concat(...buffers) { + const size = buffers.reduce((acc, { length }) => acc + length, 0), buf = new Uint8Array(size); + let i = 0; + for (const buffer of buffers) + buf.set(buffer, i), i += buffer.length; + return buf; +} +function writeUInt32BE(buf, value, offset) { + if (value < 0 || value >= MAX_INT32) + throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`); + buf.set([value >>> 24, value >>> 16, value >>> 8, value & 255], offset); +} +function uint64be(value) { + const high = Math.floor(value / MAX_INT32), low = value % MAX_INT32, buf = new Uint8Array(8); + return writeUInt32BE(buf, high, 0), writeUInt32BE(buf, low, 4), buf; +} +function uint32be(value) { + const buf = new Uint8Array(4); + return writeUInt32BE(buf, value), buf; +} +const NON_ASCII = /[^\x00-\x7f]/; +function encode(string) { + if (typeof string == "string" && string.length >= 128) { + if (NON_ASCII.test(string)) + throw new TypeError("non-ASCII string encountered in encode()"); + return encoder.encode(string); + } + const bytes = new Uint8Array(string.length); + for (let i = 0; i < string.length; i++) { + const code = string.charCodeAt(i); + if (code > 127) + throw new TypeError("non-ASCII string encountered in encode()"); + bytes[i] = code; + } + return bytes; +} +function encodeBase64(input, url = !1) { + if (Uint8Array.prototype.toBase64) + return input.toBase64({ alphabet: url ? "base64url" : "base64", omitPadding: url }); + const CHUNK_SIZE = 32768, arr = []; + for (let i = 0; i < input.length; i += CHUNK_SIZE) + arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE))); + const encoded = btoa(arr.join("")); + return url ? encoded.replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_") : encoded; +} +function decodeBase64(encoded, url = !1) { + if (Uint8Array.fromBase64) + return Uint8Array.fromBase64(encoded, { alphabet: url ? "base64url" : "base64" }); + if (url) { + if (encoded.includes("+") || encoded.includes("/")) + throw new TypeError("Invalid base64url"); + encoded = encoded.replace(/-/g, "+").replace(/_/g, "/"); + } + const binary = atob(encoded), bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) + bytes[i] = binary.charCodeAt(i); + return bytes; +} +async function digest(algorithm, data) { + const subtleDigest = `SHA-${algorithm.slice(-3)}`; + return new Uint8Array(await crypto.subtle.digest(subtleDigest, data)); +} +export { + concat, + decodeBase64, + decoder, + digest, + encode, + encodeBase64, + encoder, + strictDecoder, + uint32be, + uint64be +}; diff --git a/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/content_encryption.js b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/content_encryption.js new file mode 100644 index 000000000..1ea355e91 --- /dev/null +++ b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/content_encryption.js @@ -0,0 +1,90 @@ +import { concat, uint64be } from "./buffer_utils.js"; +import { rawKey, invalidKeyInput, isCryptoKey } from "./key.js"; +import { JWEDecryptionFailed, JWEInvalid } from "../util/errors.js"; +const generateCek = (enc) => crypto.getRandomValues(new Uint8Array(enc.cekBits >> 3)); +function checkCekLength(cek, expected) { + const actual = cek.byteLength << 3; + if (actual !== expected) + throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`); +} +const generateIv = (enc) => crypto.getRandomValues(new Uint8Array(enc.ivBits >> 3)); +function checkIvLength(enc, iv) { + if (iv.length << 3 !== enc.ivBits) + throw new JWEInvalid("Invalid Initialization Vector length"); +} +async function cbcKeySetup(enc, cek, usage) { + if (!(cek instanceof Uint8Array)) + throw new TypeError(invalidKeyInput(cek, "Uint8Array")); + const keySize = enc.cekBits >> 1, encKey = await crypto.subtle.importKey("raw", cek.subarray(keySize >> 3), "AES-CBC", !1, [usage]), macKey = await crypto.subtle.importKey("raw", cek.subarray(0, keySize >> 3), { + hash: `SHA-${keySize << 1}`, + name: "HMAC" + }, !1, ["sign"]); + return [encKey, macKey, keySize]; +} +async function cbcHmacTag(macKey, macData, keySize) { + return new Uint8Array((await crypto.subtle.sign("HMAC", macKey, macData)).slice(0, keySize >> 3)); +} +async function cbcEncrypt(enc, plaintext, cek, iv, aad) { + const [encKey, macKey, keySize] = await cbcKeySetup(enc, cek, "encrypt"), ciphertext = new Uint8Array(await crypto.subtle.encrypt({ + iv, + name: "AES-CBC" + }, encKey, plaintext)), macData = concat(aad, iv, ciphertext, uint64be(aad.length * 8)), tag = await cbcHmacTag(macKey, macData, keySize); + return { ciphertext, tag, iv }; +} +async function timingSafeEqual(a, b) { + const algorithm = { name: "HMAC", hash: "SHA-256" }, key = await crypto.subtle.generateKey(algorithm, !1, ["sign", "verify"]), aHmac = await crypto.subtle.sign(algorithm, key, a); + return crypto.subtle.verify(algorithm, key, aHmac, b); +} +async function cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) { + const [encKey, macKey, keySize] = await cbcKeySetup(enc, cek, "decrypt"), macData = concat(aad, iv, ciphertext, uint64be(aad.length * 8)), expectedTag = await cbcHmacTag(macKey, macData, keySize); + try { + if (await timingSafeEqual(tag, expectedTag)) + return new Uint8Array(await crypto.subtle.decrypt({ iv, name: "AES-CBC" }, encKey, ciphertext)); + } catch { + } + throw new JWEDecryptionFailed(); +} +async function encrypt(enc, plaintext, cek, iv, aad) { + if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) + throw new TypeError(invalidKeyInput(cek, "CryptoKey", "KeyObject", "Uint8Array", "JSON Web Key")); + if (iv ? checkIvLength(enc, iv) : iv = generateIv(enc), cek instanceof Uint8Array && checkCekLength(cek, enc.cekBits), enc.cbc) + return cbcEncrypt(enc, plaintext, cek, iv, aad); + const encKey = await rawKey(cek, enc.subtle, "encrypt"), encrypted = new Uint8Array(await crypto.subtle.encrypt({ + additionalData: aad, + iv, + name: "AES-GCM", + tagLength: 128 + }, encKey, plaintext)); + return { ciphertext: encrypted.subarray(0, -16), tag: encrypted.subarray(-16), iv }; +} +async function decrypt(enc, cek, ciphertext, iv, tag, aad) { + if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) + throw new TypeError(invalidKeyInput(cek, "CryptoKey", "KeyObject", "Uint8Array", "JSON Web Key")); + if (!iv) + throw new JWEInvalid("JWE Initialization Vector missing"); + if (!tag) + throw new JWEInvalid("JWE Authentication Tag missing"); + if (!enc.cbc && tag.length !== 16) + throw new JWEInvalid("Invalid Authentication Tag length"); + if (checkIvLength(enc, iv), cek instanceof Uint8Array && checkCekLength(cek, enc.cekBits), enc.cbc) + return cbcDecrypt(enc, cek, ciphertext, iv, tag, aad); + const encKey = await rawKey(cek, enc.subtle, "decrypt"); + try { + return new Uint8Array(await crypto.subtle.decrypt({ + additionalData: aad, + iv, + name: "AES-GCM", + tagLength: 128 + }, encKey, concat(ciphertext, tag))); + } catch { + throw new JWEDecryptionFailed(); + } +} +export { + checkCekLength, + checkIvLength, + decrypt, + encrypt, + generateCek, + generateIv +}; diff --git a/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/deflate.js b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/deflate.js new file mode 100644 index 000000000..27ffba278 --- /dev/null +++ b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/deflate.js @@ -0,0 +1,40 @@ +import { JOSENotSupported, JWEInvalid } from "../util/errors.js"; +import { concat } from "./buffer_utils.js"; +function validateZip(joseHeader, protectedHeader) { + if (joseHeader.zip !== void 0 && joseHeader.zip !== "DEF") + throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.'); + if (joseHeader.zip !== void 0 && !protectedHeader?.zip) + throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.'); +} +function supported(name) { + if (typeof globalThis[name] > "u") + throw new JOSENotSupported(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${name} API.`); +} +async function transform(stream, input, maxLength = 1 / 0) { + const writer = stream.writable.getWriter(); + writer.write(input).catch(() => { + }), writer.close().catch(() => { + }); + const chunks = []; + let length = 0; + const reader = stream.readable.getReader(); + for (; ; ) { + const { value, done } = await reader.read(); + if (done) + break; + if (chunks.push(value), length += value.byteLength, maxLength !== 1 / 0 && length > maxLength) + throw new JWEInvalid("Decompressed plaintext exceeded the configured limit"); + } + return concat(...chunks); +} +async function compress(input) { + return supported("CompressionStream"), transform(new CompressionStream("deflate-raw"), input); +} +async function decompress(input, maxLength) { + return supported("DecompressionStream"), transform(new DecompressionStream("deflate-raw"), input, maxLength); +} +export { + compress, + decompress, + validateZip +}; diff --git a/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/jwe_algorithms.js b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/jwe_algorithms.js new file mode 100644 index 000000000..a87af4eb5 --- /dev/null +++ b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/jwe_algorithms.js @@ -0,0 +1,116 @@ +import { JOSENotSupported } from "../util/errors.js"; +import { table } from "./key_descriptor.js"; +const wrap = [ + ["encrypt", "wrapKey"], + ["decrypt", "unwrapKey"] +], derive = [[], ["deriveBits"]], none = [[], []]; +function rsaes(bits) { + return { + kty: ["RSA"], + mode: "key-encryption", + subtle: { name: "RSA-OAEP", hash: `SHA-${bits}` }, + usages: wrap, + ops: ["wrapKey", "unwrapKey"] + }; +} +function ecdh(mode) { + return { + kty: ["EC", "OKP"], + mode, + subtle: { name: "ECDH" }, + resolve: ({ kty, crv, asymmetricKeyType }) => { + if (crv === "X25519" || asymmetricKeyType === "x25519") + return { name: "X25519" }; + if (kty === "OKP") + throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); + return { name: "ECDH", namedCurve: crv }; + }, + usages: derive, + ops: [void 0, "deriveBits"] + }; +} +function aeskw(bits, gcm = !1) { + return { + kty: ["oct"], + mode: "key-wrapping", + secret: !0, + subtle: { name: gcm ? "AES-GCM" : "AES-KW", length: bits }, + usages: none, + ops: gcm ? ["encrypt", "decrypt"] : ["wrapKey", "unwrapKey"] + }; +} +function pbes2() { + return { + kty: ["oct"], + mode: "key-wrapping", + secret: !0, + subtle: { name: "PBKDF2" }, + usages: none, + ops: ["deriveBits", "deriveBits"] + }; +} +const JWE = table({ + dir: { + kty: ["oct"], + mode: "direct-encryption", + secret: !0, + subtle: { name: "AES-GCM" }, + usages: none, + ops: ["encrypt", "decrypt"] + }, + "RSA-OAEP": rsaes(1), + "RSA-OAEP-256": rsaes(256), + "RSA-OAEP-384": rsaes(384), + "RSA-OAEP-512": rsaes(512), + "ECDH-ES": ecdh("direct-key-agreement"), + "ECDH-ES+A128KW": ecdh("key-agreement-with-key-wrapping"), + "ECDH-ES+A192KW": ecdh("key-agreement-with-key-wrapping"), + "ECDH-ES+A256KW": ecdh("key-agreement-with-key-wrapping"), + A128KW: aeskw(128), + A192KW: aeskw(192), + A256KW: aeskw(256), + A128GCMKW: aeskw(128, !0), + A192GCMKW: aeskw(192, !0), + A256GCMKW: aeskw(256, !0), + "PBES2-HS256+A128KW": pbes2(), + "PBES2-HS384+A192KW": pbes2(), + "PBES2-HS512+A256KW": pbes2() +}), contentOps = ["encrypt", "decrypt"]; +function contentEncryption(bits, cbc = !1) { + return { + kty: ["oct"], + secret: !0, + subtle: { name: cbc ? "AES-CBC" : "AES-GCM", length: bits }, + usages: none, + ops: contentOps, + cekBits: bits, + ivBits: cbc ? 128 : 96, + cbc + }; +} +const ENC = table({ + A128GCM: contentEncryption(128), + A192GCM: contentEncryption(192), + A256GCM: contentEncryption(256), + "A128CBC-HS256": contentEncryption(256, !0), + "A192CBC-HS384": contentEncryption(384, !0), + "A256CBC-HS512": contentEncryption(512, !0) +}); +function unsupported(parameter, name) { + throw new JOSENotSupported(`Invalid or unsupported "${parameter}" (JWE ${name}) header value`); +} +function jweAlgorithm(alg) { + return (typeof alg == "string" ? JWE[alg] : void 0) ?? unsupported("alg", "Algorithm"); +} +function isJWECEKTransport(algorithm) { + return algorithm.mode === "key-wrapping" || algorithm.mode === "key-encryption" || algorithm.mode === "key-agreement-with-key-wrapping"; +} +function jweEncryption(enc) { + return (typeof enc == "string" ? ENC[enc] : void 0) ?? unsupported("enc", "Encryption Algorithm"); +} +export { + JWE, + isJWECEKTransport, + jweAlgorithm, + jweEncryption +}; diff --git a/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/jwe_decrypt.js b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/jwe_decrypt.js new file mode 100644 index 000000000..e5453b9ba --- /dev/null +++ b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/jwe_decrypt.js @@ -0,0 +1,187 @@ +import { decrypt, generateCek } from "./content_encryption.js"; +import { decodeBase64url, encodeBase64url, parseJoseHeader, isDisjoint, isObject, validateCrit, validateAlgorithms, JWE_RECOGNIZED } from "./validate.js"; +import { JOSEAlgNotAllowed, JOSENotSupported, JWEInvalid } from "../util/errors.js"; +import { decryptKeyManagement } from "./key_management.js"; +import { decoder } from "./buffer_utils.js"; +import { prepareKey } from "./key.js"; +import { JWE, isJWECEKTransport, jweAlgorithm, jweEncryption } from "./jwe_algorithms.js"; +import { decompress, validateZip } from "./deflate.js"; +function snapshotSharedJWE(jwe) { + const { aad, ciphertext, iv, protected: encodedProtected, tag, unprotected } = jwe; + if (iv !== void 0 && (typeof iv != "string" || !iv)) + throw new JWEInvalid("JWE Initialization Vector incorrect type"); + if (typeof ciphertext != "string") + throw new JWEInvalid("JWE Ciphertext missing or incorrect type"); + if (tag !== void 0 && (typeof tag != "string" || !tag)) + throw new JWEInvalid("JWE Authentication Tag incorrect type"); + if (encodedProtected !== void 0 && typeof encodedProtected != "string") + throw new JWEInvalid("JWE Protected Header incorrect type"); + if (aad !== void 0 && (typeof aad != "string" || !aad)) + throw new JWEInvalid("JWE AAD incorrect type"); + if (unprotected !== void 0 && !isObject(unprotected)) + throw new JWEInvalid("JWE Shared Unprotected Header incorrect type"); + return { + aad, + ciphertext, + iv, + protected: encodedProtected, + tag, + unprotected: unprotected === void 0 ? void 0 : { ...unprotected } + }; +} +function snapshotRecipientJWE(recipient) { + let header, headerAlg; + try { + const { header: inputHeader } = recipient; + if (isObject(inputHeader)) { + headerAlg = inputHeader.alg; + const parameters = Object.keys(inputHeader); + parameters.includes("alg") || (headerAlg = void 0), header = Object.fromEntries(parameters.map((parameter) => [ + parameter, + parameter === "alg" ? headerAlg : inputHeader[parameter] + ])); + } else + header = inputHeader; + const { encrypted_key: encryptedKey } = recipient; + return [{ encrypted_key: encryptedKey, header }, headerAlg]; + } catch (error) { + return [void 0, headerAlg, error]; + } +} +function checkRecipient(jwe) { + const { encrypted_key: encryptedKey, header } = jwe; + if (encryptedKey !== void 0 && typeof encryptedKey != "string") + throw new JWEInvalid("JWE Encrypted Key incorrect type"); + if (header !== void 0 && !isObject(header)) + throw new JWEInvalid("JWE Per-Recipient Unprotected Header incorrect type"); + if (jwe.protected === void 0 && header === void 0 && jwe.unprotected === void 0) + throw new JWEInvalid("JOSE Header missing"); +} +function shareJWE(jwe) { + const { protected: encodedProtected, ciphertext, iv, tag, aad } = jwe; + let parsedProt; + return encodedProtected !== void 0 && (parsedProt = parseJoseHeader(encodedProtected, JWEInvalid, "JWE Protected Header is invalid")), [ + parsedProt, + decodeBase64url(ciphertext, "ciphertext", JWEInvalid), + iv !== void 0 ? decodeBase64url(iv, "iv", JWEInvalid) : void 0, + tag !== void 0 ? decodeBase64url(tag, "tag", JWEInvalid) : void 0, + encodeBase64url((encodedProtected ?? "") + (aad !== void 0 ? `.${aad}` : ""), "aad", JWEInvalid) + ]; +} +function prepareDecrypt(options) { + return [ + options && validateAlgorithms("keyManagementAlgorithms", options.keyManagementAlgorithms), + options && validateAlgorithms("contentEncryptionAlgorithms", options.contentEncryptionAlgorithms), + options?.crit, + options?.maxPBES2Count, + options?.maxDecompressedLength + ]; +} +async function decryptJWE(jwe, shared, key, token = shareJWE(jwe)) { + const [parsedProt, ciphertext, iv, tag, additionalData] = token, { header, unprotected, aad } = jwe; + let joseHeader; + if (header !== void 0 || unprotected !== void 0) { + if (!isDisjoint(parsedProt, header, unprotected)) + throw new JWEInvalid("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint"); + joseHeader = { ...parsedProt, ...header, ...unprotected }; + } else + joseHeader = parsedProt ?? {}; + const [keyManagementAlgorithms, contentEncryptionAlgorithms, crit, maxPBES2Count, maxDecompressedLength] = shared, { encrypted_key: encodedKey } = jwe; + validateCrit(JWEInvalid, JWE_RECOGNIZED, crit, parsedProt, joseHeader), validateZip(joseHeader, parsedProt); + const { alg, enc } = joseHeader; + if (typeof alg != "string" || !alg) + throw new JWEInvalid("missing JWE Algorithm (alg) in JWE Header"); + const selected = JWE[alg]; + if (encodedKey === "" && (!selected || !isJWECEKTransport(selected))) + throw new JWEInvalid("JWE Encrypted Key incorrect type"); + const integrated = selected?.mode === "integrated-encryption"; + if (!integrated && (typeof enc != "string" || !enc)) + throw new JWEInvalid("missing JWE Encryption Algorithm (enc) in JWE Header"); + if (keyManagementAlgorithms && !keyManagementAlgorithms.has(alg) || !keyManagementAlgorithms && alg.startsWith("PBES2")) + throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed'); + let encEntry; + if (integrated) { + if (enc !== void 0) + throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption'); + if (iv?.byteLength) + throw new JWEInvalid("JWE Initialization Vector must be empty for integrated encryption"); + if (tag?.byteLength) + throw new JWEInvalid("JWE Authentication Tag must be empty for integrated encryption"); + } else { + if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) + throw new JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter value not allowed'); + encEntry = jweEncryption(enc); + } + let encryptedKey; + if (encodedKey !== void 0) + try { + encryptedKey = decodeBase64url(encodedKey, "encrypted_key", JWEInvalid); + } catch (error) { + if (!selected || !isJWECEKTransport(selected)) + throw error; + encryptedKey = new Uint8Array(); + } + let resolvedKey = !1; + typeof key == "function" && (key = await key(parsedProt, jwe), resolvedKey = !0); + const algEntry = selected ?? jweAlgorithm(alg); + isJWECEKTransport(algEntry) && encryptedKey === void 0 && (encryptedKey = new Uint8Array()); + const k = await prepareKey(algEntry.mode === "direct-encryption" ? encEntry : algEntry, key, "decrypt"); + let plaintext; + if (algEntry.mode === "integrated-encryption") + plaintext = await algEntry.decrypt(k, encryptedKey, ciphertext, additionalData, parsedProt, joseHeader); + else { + const encryption = encEntry; + let cek; + try { + cek = await decryptKeyManagement(algEntry, encryption, k, encryptedKey, joseHeader, maxPBES2Count), isJWECEKTransport(algEntry) && cek instanceof Uint8Array && cek.byteLength << 3 !== encryption.cekBits && (cek = generateCek(encryption)); + } catch (err) { + if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) + throw err; + cek = generateCek(encryption); + } + plaintext = await decrypt(encryption, cek, ciphertext, iv, tag, additionalData); + } + if (joseHeader.zip === "DEF") { + const decompressionLimit = maxDecompressedLength ?? 25e4; + if (decompressionLimit === 0) + throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.'); + if (decompressionLimit !== 1 / 0 && (!Number.isSafeInteger(decompressionLimit) || decompressionLimit < 1)) + throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity"); + plaintext = await decompress(plaintext, decompressionLimit).catch((cause) => { + throw cause instanceof JWEInvalid ? cause : new JWEInvalid("Failed to decompress plaintext", { cause }); + }); + } + return { + plaintext, + ...parsedProt && { protectedHeader: parsedProt }, + ...aad !== void 0 && { + additionalAuthenticatedData: decodeBase64url(aad, "aad", JWEInvalid) + }, + ...unprotected && { sharedUnprotectedHeader: unprotected }, + ...header && { unprotectedHeader: header }, + ...resolvedKey && { key: k } + }; +} +async function decryptCompact(jwe, shared, key) { + if (jwe instanceof Uint8Array && (jwe = decoder.decode(jwe)), typeof jwe != "string") + throw new JWEInvalid("Compact JWE must be a string or Uint8Array"); + const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag, length } = jwe.split("."); + if (length !== 5) + throw new JWEInvalid("Invalid Compact JWE"); + return decryptJWE({ + ciphertext, + iv: iv || void 0, + protected: protectedHeader, + tag: tag || void 0, + encrypted_key: encryptedKey || void 0 + }, shared, key); +} +export { + checkRecipient, + decryptCompact, + decryptJWE, + prepareDecrypt, + shareJWE, + snapshotRecipientJWE, + snapshotSharedJWE +}; diff --git a/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/jwe_encrypt.js b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/jwe_encrypt.js new file mode 100644 index 000000000..5ab33766b --- /dev/null +++ b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/jwe_encrypt.js @@ -0,0 +1,75 @@ +import { encode as b64u } from "../util/base64url.js"; +import { encrypt } from "./content_encryption.js"; +import { encryptKeyManagement } from "./key_management.js"; +import { JWEInvalid } from "../util/errors.js"; +import { assertUint8Array, isDisjoint, isObject, serializeJoseHeader, validateCrit, validateCritDuplicates, JWE_RECOGNIZED } from "./validate.js"; +import { encode } from "./buffer_utils.js"; +import { prepareKey } from "./key.js"; +import { JWE, jweAlgorithm, jweEncryption } from "./jwe_algorithms.js"; +import { compress, validateZip } from "./deflate.js"; +function checkDisjoint(protectedHeader, unprotectedHeader, sharedUnprotectedHeader) { + if (!isDisjoint(protectedHeader, unprotectedHeader, sharedUnprotectedHeader)) + throw new JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint"); +} +function checkEncryptHeaders(input, options, sharedHeadersNormalized = !1) { + if (!input[1] && !input[2] && !input[3]) + throw new JWEInvalid("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()"); + options !== void 0 && (input[8] = options?.crit); + let [, protectedHeader, unprotectedHeader, sharedUnprotectedHeader, aad, cek, iv, keyManagementParameters, crit] = input; + if (aad !== void 0 && assertUint8Array(aad, "JWE Additional Authenticated Data"), cek !== void 0 && assertUint8Array(cek, "JWE Content Encryption Key"), iv !== void 0 && assertUint8Array(iv, "JWE Initialization Vector"), !sharedHeadersNormalized && protectedHeader !== void 0 && (protectedHeader = serializeJoseHeader(JWEInvalid, protectedHeader)[0], input[1] = protectedHeader), unprotectedHeader !== void 0 && (unprotectedHeader = serializeJoseHeader(JWEInvalid, unprotectedHeader)[0], input[2] = unprotectedHeader), !sharedHeadersNormalized && sharedUnprotectedHeader !== void 0 && (sharedUnprotectedHeader = serializeJoseHeader(JWEInvalid, sharedUnprotectedHeader)[0], input[3] = sharedUnprotectedHeader), keyManagementParameters !== void 0 && !isObject(keyManagementParameters)) + throw new TypeError("JWE Key Management Parameters must be an object"); + checkDisjoint(protectedHeader, unprotectedHeader, sharedUnprotectedHeader); + const joseHeader = { + ...protectedHeader, + ...unprotectedHeader, + ...sharedUnprotectedHeader + }; + validateCritDuplicates(JWEInvalid, protectedHeader), validateCrit(JWEInvalid, JWE_RECOGNIZED, crit, protectedHeader, joseHeader), validateZip(joseHeader, protectedHeader); + const { alg, enc } = joseHeader; + if (typeof alg != "string" || !alg) + throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); + const algEntry = JWE[alg]; + if (algEntry?.mode === "integrated-encryption") { + if (enc !== void 0) + throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption'); + if (cek !== void 0) + throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${alg}`); + if (iv !== void 0) + throw new TypeError(`setInitializationVector cannot be called with JWE "alg" (Algorithm) Header ${alg}`); + return [joseHeader, void 0, algEntry]; + } + if (typeof enc != "string" || !enc) + throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); + return [joseHeader, jweEncryption(enc), algEntry]; +} +async function encryptJWE(input, checked, key) { + const [joseHeader, encEntry, selected] = checked, [inputPlaintext, inputProtectedHeader, inputUnprotectedHeader, sharedUnprotectedHeader, aad, providedCek, inputIv, keyManagementParameters, , unprotectedParameters] = input; + let protectedHeader = inputProtectedHeader, unprotectedHeader = inputUnprotectedHeader; + const algEntry = selected ?? jweAlgorithm(joseHeader.alg); + let encryptedKey, parameters, cek; + algEntry.mode === "integrated-encryption" ? cek = await prepareKey(algEntry, key, "encrypt") : [cek, encryptedKey, parameters] = await encryptKeyManagement(algEntry, encEntry, key, joseHeader, providedCek, keyManagementParameters), parameters && (unprotectedParameters ? unprotectedHeader = unprotectedHeader ? { ...unprotectedHeader, ...parameters } : parameters : protectedHeader = protectedHeader ? { ...protectedHeader, ...parameters } : parameters, checkDisjoint(protectedHeader, unprotectedHeader, sharedUnprotectedHeader)); + const protectedHeaderS = protectedHeader ? b64u(JSON.stringify(protectedHeader)) : "", aadMember = aad?.byteLength ? b64u(aad) : void 0, additionalData = encode(aadMember ? `${protectedHeaderS}.${aadMember}` : protectedHeaderS); + let plaintext = inputPlaintext; + joseHeader.zip === "DEF" && (plaintext = await compress(plaintext).catch((cause) => { + throw new JWEInvalid("Failed to compress plaintext", { cause }); + })); + let ciphertext, tag, iv; + algEntry.mode === "integrated-encryption" ? [encryptedKey, ciphertext] = await algEntry.encrypt(cek, plaintext, additionalData, protectedHeader, joseHeader, keyManagementParameters) : { ciphertext, tag, iv } = await encrypt(encEntry, plaintext, cek, inputIv, additionalData); + const jwe = { + ciphertext: b64u(ciphertext) + }; + return iv && (jwe.iv = b64u(iv)), tag && (jwe.tag = b64u(tag)), encryptedKey?.byteLength && (jwe.encrypted_key = b64u(encryptedKey)), aadMember && (jwe.aad = aadMember), protectedHeader && (jwe.protected = protectedHeaderS), sharedUnprotectedHeader && (jwe.unprotected = sharedUnprotectedHeader), unprotectedHeader && (jwe.header = unprotectedHeader), jwe; +} +async function createJWE(input, key, options) { + return encryptJWE(input, checkEncryptHeaders(input, options), key); +} +function compactJWE(jwe) { + return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join("."); +} +export { + checkDisjoint, + checkEncryptHeaders, + compactJWE, + createJWE, + encryptJWE +}; diff --git a/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/jwt_claims_set.js b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/jwt_claims_set.js new file mode 100644 index 000000000..b99943f9c --- /dev/null +++ b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/jwt_claims_set.js @@ -0,0 +1,146 @@ +import { JWTClaimValidationFailed, JWTExpired, JWTInvalid } from "../util/errors.js"; +import { encoder, strictDecoder } from "./buffer_utils.js"; +import { isObject } from "./validate.js"; +const epoch = (date) => Math.floor(date.getTime() / 1e3), multipliers = { + s: 1, + m: 60, + h: 3600, + d: 86400, + w: 604800, + y: 31557600 +}, REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i, checkFailed = "check_failed"; +function invalidDuration() { + throw new TypeError("Invalid time period format"); +} +function secs(str) { + typeof str != "string" && invalidDuration(); + const matched = REGEX.exec(str); + (!matched || matched[4] && matched[1]) && invalidDuration(); + const value = parseFloat(matched[2]), numericDate2 = Math.round(value * multipliers[matched[3][0].toLowerCase()]); + return Number.isFinite(numericDate2) || invalidDuration(), matched[1] === "-" || matched[4] === "ago" ? -numericDate2 : numericDate2; +} +function validateInput(label, input) { + if (!Number.isFinite(input)) + throw new TypeError(`Invalid ${label} input`); + return input; +} +function validateStringClaim(claim, value) { + if (typeof value != "string") + throw new TypeError(`"${claim}" claim must be a string`); +} +function validateAudienceClaim(value) { + if (typeof value != "string" && (!Array.isArray(value) || Array.from(value).some((member) => typeof member != "string"))) + throw new TypeError('"aud" claim must be a string or an array of strings'); +} +function numericDate(value, label) { + return typeof value == "number" ? validateInput(label, value) : value instanceof Date ? validateInput(label, epoch(value)) : epoch(/* @__PURE__ */ new Date()) + secs(value); +} +const normalizeTyp = (value) => { + const normalized = value.toLowerCase(); + return value.includes("/") ? normalized : `application/${normalized}`; +}, checkAudiencePresence = (audPayload, audOption) => typeof audPayload == "string" ? audOption.includes(audPayload) : Array.isArray(audPayload) ? audOption.some((aud) => audPayload.includes(aud)) : !1; +function validateNumericDate(payload, claim, required = !1) { + const value = payload[claim]; + if (!(value === void 0 && !required)) { + if (typeof value != "number") + throw new JWTClaimValidationFailed(`"${claim}" claim must be a number`, payload, claim, "invalid"); + return value; + } +} +function unexpectedClaim(payload, claim) { + throw new JWTClaimValidationFailed(`unexpected "${claim}" claim value`, payload, claim, checkFailed); +} +function validateClaimsSet(protectedHeader, encodedPayload, options = {}) { + let payload; + try { + payload = JSON.parse(strictDecoder.decode(encodedPayload)); + } catch { + } + if (!isObject(payload)) + throw new JWTInvalid("JWT Claims Set must be a top-level JSON object"); + const { typ } = options; + if (typ !== void 0 && (typeof protectedHeader.typ != "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) + throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, "typ", checkFailed); + const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options, presenceCheck = [...requiredClaims]; + maxTokenAge !== void 0 && presenceCheck.push("iat"), audience !== void 0 && presenceCheck.push("aud"), subject !== void 0 && presenceCheck.push("sub"), issuer !== void 0 && presenceCheck.push("iss"); + for (const claim of new Set(presenceCheck.reverse())) + if (!Object.hasOwn(payload, claim)) + throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing"); + issuer !== void 0 && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss) && unexpectedClaim(payload, "iss"), subject !== void 0 && payload.sub !== subject && unexpectedClaim(payload, "sub"), audience !== void 0 && !checkAudiencePresence(payload.aud, typeof audience == "string" ? [audience] : audience) && unexpectedClaim(payload, "aud"); + const { clockTolerance } = options; + let tolerance = 0; + if (typeof clockTolerance == "string") + tolerance = secs(clockTolerance); + else if (clockTolerance !== void 0) { + if (typeof clockTolerance != "number") + throw new TypeError("Invalid clockTolerance option type"); + tolerance = clockTolerance; + } + validateInput("clockTolerance option", tolerance); + const { currentDate } = options, now = validateInput("currentDate option", epoch(currentDate === void 0 ? /* @__PURE__ */ new Date() : currentDate)), iat = validateNumericDate(payload, "iat", maxTokenAge !== void 0), nbf = validateNumericDate(payload, "nbf"); + if (nbf !== void 0 && nbf > now + tolerance) + throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, "nbf", checkFailed); + const exp = validateNumericDate(payload, "exp"); + if (exp !== void 0 && exp <= now - tolerance) + throw new JWTExpired('"exp" claim timestamp check failed', payload, "exp", checkFailed); + if (maxTokenAge !== void 0) { + const age = now - iat, max = validateInput("maxTokenAge option", typeof maxTokenAge == "number" ? maxTokenAge : secs(maxTokenAge)); + if (age - tolerance > max) + throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, "iat", checkFailed); + if (age < -tolerance) + throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, "iat", checkFailed); + } + return payload; +} +let producerPayloads; +function producerPayload(producer) { + return producerPayloads.get(producer); +} +function jwtData(producer) { + const payload = producerPayload(producer); + for (const claim of ["iat", "nbf", "exp"]) { + const value = payload[claim]; + if (typeof value == "number" && !Number.isFinite(value)) + throw new TypeError(`"${claim}" claim must be a finite number`); + } + return encoder.encode(JSON.stringify(payload)); +} +function jwtClaim(producer, claim) { + return producerPayload(producer)[claim]; +} +class JWTClaimsBuilder { + constructor(payload = {}) { + if (!isObject(payload)) + throw new TypeError("JWT Claims Set MUST be an object"); + (producerPayloads ||= /* @__PURE__ */ new WeakMap()).set(this, structuredClone(payload)); + } + setIssuer(value) { + return validateStringClaim("iss", value), producerPayload(this).iss = value, this; + } + setSubject(value) { + return validateStringClaim("sub", value), producerPayload(this).sub = value, this; + } + setAudience(value) { + return validateAudienceClaim(value), producerPayload(this).aud = value, this; + } + setJti(value) { + return validateStringClaim("jti", value), producerPayload(this).jti = value, this; + } + setNotBefore(value) { + return producerPayload(this).nbf = numericDate(value, "setNotBefore"), this; + } + setExpirationTime(value) { + return producerPayload(this).exp = numericDate(value, "setExpirationTime"), this; + } + setIssuedAt(value) { + const payload = producerPayload(this); + return value === void 0 ? payload.iat = epoch(/* @__PURE__ */ new Date()) : typeof value == "string" ? payload.iat = validateInput("setIssuedAt", epoch(/* @__PURE__ */ new Date()) + secs(value)) : payload.iat = numericDate(value, "setIssuedAt"), this; + } +} +export { + JWTClaimsBuilder, + jwtClaim, + jwtData, + secs, + validateClaimsSet +}; diff --git a/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/key.js b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/key.js new file mode 100644 index 000000000..7dc5602f1 --- /dev/null +++ b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/key.js @@ -0,0 +1,155 @@ +import { isObject } from "./validate.js"; +import { decode } from "../util/base64url.js"; +import { JOSENotSupported } from "../util/errors.js"; +const tag = (key) => key[Symbol.toStringTag], jwkMatchesOp = (entry, key, usage) => { + const { alg } = entry; + if (key.use !== void 0) { + const expected = usage === "sign" || usage === "verify" ? "sig" : "enc"; + if (key.use !== expected) + throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`); + } + if (key.alg !== void 0 && key.alg !== alg) + throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`); + if (Array.isArray(key.key_ops)) { + const expectedKeyOp = usage === "encrypt" || usage === "decrypt" ? entry.ops?.[usage === "encrypt" ? 0 : 1] : usage; + if (expectedKeyOp && !key.key_ops.includes(expectedKeyOp)) + throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`); + } +}; +async function prepareKey(entry, key, usage) { + const { alg, secret } = entry, privateKey = usage === "decrypt" || usage === "sign"; + if (secret && key instanceof Uint8Array) + return key; + let normalized, keyObject; + if (isObject(key)) { + if (normalized = normalizeJwk(key), typeof normalized.kty != "string") + throw invalidKeyType(alg, key, secret); + if (!(secret ? normalized.kty === "oct" && typeof normalized.k == "string" : normalized.kty !== "oct" && (privateKey ? normalized.kty === "AKP" && typeof normalized.priv == "string" || typeof normalized.d == "string" : normalized.d === void 0 && normalized.priv === void 0))) + throw new TypeError(secret ? 'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present' : `JSON Web Key for this operation must be a ${privateKey ? "private" : "public"} JWK`); + if (jwkMatchesOp(entry, normalized, usage), normalized.kty === "oct") + return decode(normalized.k); + if (!Object.isFrozen(key)) { + const { key_ops } = key; + Array.isArray(key_ops) && Object.freeze(key_ops), Object.freeze(key); + } + } else { + if (!isKeyLike(key)) + throw invalidKeyType(alg, key, secret); + const expectedType = secret ? "secret" : privateKey ? "private" : "public"; + if (key.type !== expectedType && (secret || ["secret", "public", "private"].includes(key.type))) + throw new TypeError(`${tag(key)} instances must be of type "${expectedType}" for the ${alg} algorithm`); + if (isCryptoKey(key)) + return key; + if (keyObject = key, keyObject.type === "secret") + return keyObject.export(); + } + cache ||= /* @__PURE__ */ new WeakMap(); + const cacheKey = key; + let cached = cache.get(cacheKey); + if (cached?.[alg]) + return cached[alg]; + if (cached || cache.set(cacheKey, cached = {}), keyObject && typeof keyObject.toCryptoKey == "function") { + const isPublic = keyObject.type === "public", crv = nist[keyObject.asymmetricKeyDetails?.namedCurve], params = entry.resolve?.({ crv, asymmetricKeyType: keyObject.asymmetricKeyType }) ?? entry.subtle; + return cached[alg] = keyObject.toCryptoKey(params, isPublic, entry.usages[isPublic ? 0 : 1]); + } + return normalized ??= keyObject.export({ format: "jwk" }), normalized.alg = alg, cached[alg] = await jwkToKey(entry, normalized); +} +let cache; +const nist = { + __proto__: null, + prime256v1: "P-256", + secp384r1: "P-384", + secp521r1: "P-521" +}; +function assertCryptoKey(key) { + if (!isCryptoKey(key)) + throw new Error("CryptoKey instance expected"); +} +const isCryptoKey = (key) => { + if (key?.[Symbol.toStringTag] === "CryptoKey") + return !0; + try { + return key instanceof CryptoKey; + } catch { + return !1; + } +}, isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject", isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key); +function message(msg, actual, ...types) { + if (types.length > 2) { + const last = types.pop(); + msg += `one of type ${types.join(", ")}, or ${last}.`; + } else types.length === 2 ? msg += `one of type ${types[0]} or ${types[1]}.` : msg += `of type ${types[0]}.`; + return actual == null ? msg += ` Received ${actual}` : typeof actual == "function" && actual.name ? msg += ` Received function ${actual.name}` : typeof actual == "object" && actual != null && actual.constructor?.name && (msg += ` Received an instance of ${actual.constructor.name}`), msg; +} +const invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types); +function invalidKeyType(alg, actual, secret) { + const types = ["CryptoKey", "KeyObject", "JSON Web Key"]; + return secret && types.push("Uint8Array"), new TypeError(message(`Key for the ${alg} algorithm must be `, actual, ...types)); +} +const unusable = (name, prop = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`); +function checkUsage(key, usage) { + if (usage && !key.usages.includes(usage)) + throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`); +} +function checkModulusLength(alg, key) { + const { modulusLength } = key.algorithm; + if (typeof modulusLength != "number" || modulusLength < 2048) + throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`); +} +function checkCryptoKey(key, expected, usage) { + const algorithm = key.algorithm; + if (algorithm.name !== expected.name) + throw unusable(expected.name); + if (expected.hash && algorithm.hash?.name !== expected.hash) + throw unusable(expected.hash, "algorithm.hash"); + if (expected.namedCurve && algorithm.namedCurve !== expected.namedCurve) + throw unusable(expected.namedCurve, "algorithm.namedCurve"); + if (expected.length !== void 0 && algorithm.length !== expected.length) + throw unusable(expected.length, "algorithm.length"); + checkUsage(key, usage); +} +function snapshotJwk(jwk) { + return { __proto__: null, ...jwk }; +} +function normalizeJwk(jwk) { + const normalized = snapshotJwk(jwk); + if (normalized.ext !== void 0 && typeof normalized.ext != "boolean") + throw new TypeError('"ext" (Extractable) Parameter must be a boolean'); + if (normalized.key_ops !== void 0) { + const value = normalized.key_ops, keyOps = Array.isArray(value) ? [...value] : void 0; + if (!keyOps || keyOps.some((operation) => typeof operation != "string") || new Set(keyOps).size !== keyOps.length) + throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings'); + normalized.key_ops = keyOps; + } + return normalized; +} +function validateExtractableOption(extractable) { + if (extractable !== void 0 && typeof extractable != "boolean") + throw new TypeError('"extractable" option must be a boolean'); + return extractable; +} +async function jwkToKey(entry, jwk, extractable) { + if (!entry.kty.includes(jwk.kty)) + throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); + const algorithm = entry.resolve?.({ kty: jwk.kty, crv: jwk.crv }) ?? entry.subtle, isPrivate = !!(jwk.d || jwk.priv), keyData = { ...jwk, ext: extractable ?? jwk.ext }; + return keyData.kty !== "AKP" && delete keyData.alg, delete keyData.use, crypto.subtle.importKey("jwk", keyData, algorithm, keyData.ext ?? !isPrivate, jwk.key_ops ?? entry.usages[isPrivate ? 1 : 0]); +} +async function rawKey(key, expected, usage, extractable = !1) { + return key instanceof Uint8Array && (key = await crypto.subtle.importKey("raw", key, expected, extractable, [usage])), checkCryptoKey(key, expected, usage), key; +} +export { + assertCryptoKey, + checkCryptoKey, + checkModulusLength, + checkUsage, + invalidKeyInput, + isCryptoKey, + isKeyLike, + isKeyObject, + jwkToKey, + normalizeJwk, + prepareKey, + rawKey, + snapshotJwk, + validateExtractableOption +}; diff --git a/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/key_descriptor.js b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/key_descriptor.js new file mode 100644 index 000000000..cf0afbd90 --- /dev/null +++ b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/key_descriptor.js @@ -0,0 +1,9 @@ +function table(entries) { + const out = { __proto__: null }; + for (const alg in entries) + out[alg] = { ...entries[alg], alg }; + return out; +} +export { + table +}; diff --git a/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/key_management.js b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/key_management.js new file mode 100644 index 000000000..7b7533b70 --- /dev/null +++ b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/key_management.js @@ -0,0 +1,196 @@ +import { encode as b64u } from "../util/base64url.js"; +import { prepareKey, rawKey, jwkToKey, checkCryptoKey, checkModulusLength, checkUsage, assertCryptoKey } from "./key.js"; +import { jweAlgorithm, jweEncryption, isJWECEKTransport } from "./jwe_algorithms.js"; +import { JOSENotSupported, JWEInvalid } from "../util/errors.js"; +import { decodeBase64url, assertUint8Array, isObject } from "./validate.js"; +import { digest, concat, encode, uint32be } from "./buffer_utils.js"; +import { checkCekLength, generateCek, encrypt, decrypt } from "./content_encryption.js"; +function checkEcdhCryptoKey(key, usage) { + if (key.algorithm.name !== "ECDH" && key.algorithm.name !== "X25519") + throw new TypeError("CryptoKey does not support this operation, its algorithm.name must be ECDH or X25519"); + checkUsage(key, usage); +} +async function aeskwWrap(alg, key, cek) { + const cryptoKey = await rawKey(key, jweAlgorithm(alg).subtle, "wrapKey", !0), cryptoKeyCek = await crypto.subtle.importKey("raw", cek, { hash: "SHA-256", name: "HMAC" }, !0, ["sign"]); + return new Uint8Array(await crypto.subtle.wrapKey("raw", cryptoKeyCek, cryptoKey, "AES-KW")); +} +async function aeskwUnwrap(alg, key, encryptedKey) { + const cryptoKey = await rawKey(key, jweAlgorithm(alg).subtle, "unwrapKey", !0), cryptoKeyCek = await crypto.subtle.unwrapKey("raw", encryptedKey, cryptoKey, "AES-KW", { hash: "SHA-256", name: "HMAC" }, !0, ["sign"]); + return new Uint8Array(await crypto.subtle.exportKey("raw", cryptoKeyCek)); +} +function checkRsaKey(alg, key, usage) { + checkCryptoKey(key, jweAlgorithm(alg).subtle, usage), checkModulusLength(alg, key); +} +async function deriveKey(p2s, alg, p2c, key) { + if (!(p2s instanceof Uint8Array) || p2s.length < 8) + throw new JWEInvalid("PBES2 Salt Input must be 8 or more octets"); + if (!Number.isSafeInteger(p2c) || Math.sign(p2c) !== 1) + throw new JWEInvalid("PBES2 Count Input must be a positive integer"); + const salt = concat(encode(alg), Uint8Array.of(0), p2s), keylen = parseInt(alg.slice(13, 16), 10), subtleAlg = { + hash: `SHA-${alg.slice(8, 11)}`, + iterations: p2c, + name: "PBKDF2", + salt + }, cryptoKey = await rawKey(key, jweAlgorithm(alg).subtle, "deriveBits"); + return new Uint8Array(await crypto.subtle.deriveBits(subtleAlg, cryptoKey, keylen)); +} +function lengthAndInput(input) { + return concat(uint32be(input.length), input); +} +async function concatKdf(Z, L, OtherInfo) { + const dkLen = L >> 3, hashLen = 32, reps = Math.ceil(dkLen / hashLen), dk = new Uint8Array(reps * hashLen); + for (let i = 1; i <= reps; i++) { + const hashResult = await digest("sha256", concat(uint32be(i), Z, OtherInfo)); + dk.set(hashResult, (i - 1) * hashLen); + } + return dk.slice(0, dkLen); +} +async function ecdhesDeriveKey(publicKey, privateKey, algorithm, keyLength, apu = new Uint8Array(), apv = new Uint8Array()) { + checkEcdhCryptoKey(publicKey), checkEcdhCryptoKey(privateKey, "deriveBits"); + const otherInfo = concat(lengthAndInput(encode(algorithm)), lengthAndInput(apu), lengthAndInput(apv), uint32be(keyLength)), Z = new Uint8Array(await crypto.subtle.deriveBits({ + name: publicKey.algorithm.name, + public: publicKey + }, privateKey, publicKey.algorithm.name === "X25519" ? 256 : Math.ceil(parseInt(publicKey.algorithm.namedCurve.slice(-3), 10) / 8) << 3)); + return concatKdf(Z, keyLength, otherInfo); +} +function assertEcdhKey(key) { + assertCryptoKey(key); + const curve = key.algorithm.namedCurve; + if (curve !== "P-256" && curve !== "P-384" && curve !== "P-521" && key.algorithm.name !== "X25519") + throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime"); +} +function partyInfo(joseHeader, name) { + const value = joseHeader[name]; + if (value !== void 0) { + if (typeof value != "string") + throw new JWEInvalid(`JOSE Header "${name}" (Agreement Party${name === "apu" ? "U" : "V"}Info) invalid`); + return decodeBase64url(value, name, JWEInvalid); + } +} +function checkPartyInfo(apu, apv) { + if (!(apu === void 0 || apv === void 0 || apu.byteLength !== apv.byteLength)) { + for (let i = 0; i < apu.byteLength; i++) + if (apu[i] !== apv[i]) + return; + throw new JWEInvalid('JOSE Header "apu" and "apv" values must be distinct'); + } +} +function assertEncryptedKey(encryptedKey) { + if (encryptedKey === void 0) + throw new JWEInvalid("JWE Encrypted Key missing"); +} +function assertNoEncryptedKey(encryptedKey) { + if (encryptedKey !== void 0) + throw new JWEInvalid("Encountered unexpected JWE Encrypted Key"); +} +function validateMaxPBES2Count(value) { + if (value !== void 0 && value !== 1 / 0 && (!Number.isSafeInteger(value) || value < 1)) + throw new TypeError("maxPBES2Count must be a positive safe integer or Infinity"); +} +async function decryptKeyManagement(entry, enc, key, encryptedKey, joseHeader, maxPBES2Count) { + const { alg } = entry, mode = entry.mode; + if (mode === "direct-encryption") + return assertNoEncryptedKey(encryptedKey), key; + const direct = mode === "direct-key-agreement"; + switch (direct ? assertNoEncryptedKey(encryptedKey) : assertEncryptedKey(encryptedKey), entry.subtle.name) { + case "ECDH": { + const { epk } = joseHeader; + if (!isObject(epk) || ["d", "k", "p", "q", "dp", "dq", "qi", "oth", "priv"].some((parameter) => Object.hasOwn(epk, parameter))) + throw new JWEInvalid('JOSE Header "epk" (Ephemeral Public Key) missing or invalid'); + assertEcdhKey(key); + const ephemeralPublicKey = await jwkToKey(entry, epk), partyUInfo = partyInfo(joseHeader, "apu"), partyVInfo = partyInfo(joseHeader, "apv"); + checkPartyInfo(partyUInfo, partyVInfo); + const sharedSecret = await ecdhesDeriveKey(ephemeralPublicKey, key, direct ? enc.alg : alg, direct ? enc.cekBits : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo); + if (direct) + return sharedSecret; + key = sharedSecret; + break; + } + case "RSA-OAEP": + return assertCryptoKey(key), checkRsaKey(alg, key, "decrypt"), new Uint8Array(await crypto.subtle.decrypt("RSA-OAEP", key, encryptedKey)); + case "PBKDF2": { + if (typeof joseHeader.p2c != "number") + throw new JWEInvalid('JOSE Header "p2c" (PBES2 Count) missing or invalid'); + validateMaxPBES2Count(maxPBES2Count); + const p2cLimit = maxPBES2Count ?? 1e4; + if (joseHeader.p2c > p2cLimit) + throw new JWEInvalid('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds'); + if (typeof joseHeader.p2s != "string") + throw new JWEInvalid('JOSE Header "p2s" (PBES2 Salt) missing or invalid'); + const p2s = decodeBase64url(joseHeader.p2s, "p2s", JWEInvalid); + key = await deriveKey(p2s, alg, joseHeader.p2c, key); + break; + } + case "AES-GCM": { + if (typeof joseHeader.iv != "string") + throw new JWEInvalid('JOSE Header "iv" (Initialization Vector) missing or invalid'); + if (typeof joseHeader.tag != "string") + throw new JWEInvalid('JOSE Header "tag" (Authentication Tag) missing or invalid'); + const iv = decodeBase64url(joseHeader.iv, "iv", JWEInvalid), tag = decodeBase64url(joseHeader.tag, "tag", JWEInvalid); + if (iv.byteLength !== 12) + throw new JWEInvalid("Invalid Initialization Vector length"); + if (tag.byteLength !== 16) + throw new JWEInvalid("Invalid Authentication Tag length"); + return decrypt(jweEncryption(alg.slice(0, -2)), key, encryptedKey, iv, tag, new Uint8Array()); + } + } + return aeskwUnwrap(alg.slice(-6), key, encryptedKey); +} +async function encryptKeyManagement(entry, enc, inputKey, joseHeader, providedCek, providedParameters = {}) { + const { alg, mode } = entry, transport = isJWECEKTransport(entry); + if (providedCek !== void 0 && !transport) + throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${alg}`); + let key = await prepareKey(mode === "direct-encryption" ? enc : entry, inputKey, "encrypt"); + if (mode === "direct-encryption") + return [key, void 0, void 0]; + const cek = transport ? providedCek ?? generateCek(enc) : void 0; + cek && checkCekLength(cek, enc.cekBits); + let encryptedKey, parameters; + switch (entry.subtle.name) { + case "ECDH": { + assertEcdhKey(key); + const { apu: providedApu, apv: providedApv } = providedParameters; + providedApu !== void 0 && assertUint8Array(providedApu, '"apu"'), providedApv !== void 0 && assertUint8Array(providedApv, '"apv"'); + const apu = providedApu ?? partyInfo(joseHeader, "apu"), apv = providedApv ?? partyInfo(joseHeader, "apv"); + checkPartyInfo(apu, apv); + let ephemeralKey; + providedParameters.epk !== void 0 ? ephemeralKey = await prepareKey(entry, providedParameters.epk, "decrypt") : ephemeralKey = (await crypto.subtle.generateKey(key.algorithm, !0, ["deriveBits"])).privateKey; + const subtle = crypto.subtle; + let exportableEpk = ephemeralKey; + if (!exportableEpk.extractable) { + if (typeof subtle.getPublicKey != "function") + throw new TypeError('CryptoKey for "epk" must be extractable'); + exportableEpk = await subtle.getPublicKey(ephemeralKey, []); + } + const { x, y, crv, kty } = await subtle.exportKey("jwk", exportableEpk), direct = mode === "direct-key-agreement", sharedSecret = await ecdhesDeriveKey(key, ephemeralKey, direct ? enc.alg : alg, direct ? enc.cekBits : parseInt(alg.slice(-5, -2), 10), apu, apv), epk = { x, crv, kty }; + if (kty === "EC" && (epk.y = y), parameters = { epk }, providedApu !== void 0 && (parameters.apu = b64u(providedApu)), providedApv !== void 0 && (parameters.apv = b64u(providedApv)), direct) + return [sharedSecret, void 0, parameters]; + key = sharedSecret; + break; + } + case "RSA-OAEP": { + assertCryptoKey(key), checkRsaKey(alg, key, "encrypt"), encryptedKey = new Uint8Array(await crypto.subtle.encrypt("RSA-OAEP", key, cek)); + break; + } + case "PBKDF2": { + const { p2c = 2048, p2s = crypto.getRandomValues(new Uint8Array(16)) } = providedParameters; + key = await deriveKey(p2s, alg, p2c, key), parameters = { p2c, p2s: b64u(p2s) }; + break; + } + case "AES-GCM": { + const iv = providedParameters.iv === void 0 ? crypto.getRandomValues(new Uint8Array(12)) : providedParameters.iv; + if (!(iv instanceof Uint8Array)) + throw new TypeError('"iv" must be an instance of Uint8Array'); + const wrapped = await encrypt(jweEncryption(alg.slice(0, -2)), cek, key, iv, new Uint8Array()); + encryptedKey = wrapped.ciphertext, parameters = { iv: b64u(wrapped.iv), tag: b64u(wrapped.tag) }; + } + } + if (encryptedKey ??= await aeskwWrap(alg.slice(-6), key, cek), !(encryptedKey instanceof Uint8Array) || !encryptedKey.byteLength) + throw new TypeError("JWE key management algorithm did not produce an Encrypted Key"); + return [cek, encryptedKey, parameters]; +} +export { + decryptKeyManagement, + encryptKeyManagement, + validateMaxPBES2Count +}; diff --git a/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/validate.js b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/validate.js new file mode 100644 index 000000000..51b7dfe89 --- /dev/null +++ b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/lib/validate.js @@ -0,0 +1,122 @@ +import { JOSENotSupported, JWSInvalid } from "../util/errors.js"; +import { decode } from "../util/base64url.js"; +import { encode, strictDecoder } from "./buffer_utils.js"; +function assertUint8Array(input, label) { + if (!(input instanceof Uint8Array)) + throw new TypeError(`${label} must be an instance of Uint8Array`); +} +function isObject(input) { + if (typeof input != "object" || input === null || Object.prototype.toString.call(input) !== "[object Object]") + return !1; + const prototype = Object.getPrototypeOf(input); + return prototype === null || Object.getPrototypeOf(prototype) === null; +} +function isJwkSet(input) { + return isObject(input) && Array.isArray(input.keys) && Array.from(input.keys).every(isObject); +} +function isDisjoint(...headers) { + const parameters = /* @__PURE__ */ new Set(); + for (const header of headers) + if (header) + for (const parameter of Object.keys(header)) { + if (parameters.has(parameter)) + return !1; + parameters.add(parameter); + } + return !0; +} +function assertNotSet(value, name) { + if (value !== void 0) + throw new TypeError(`${name} can only be called once`); +} +function decodeBase64url(value, label, ErrorClass) { + try { + return decode(value); + } catch { + throw new ErrorClass(`Failed to base64url decode the ${label}`); + } +} +function encodeBase64url(value, label, ErrorClass) { + try { + return encode(value); + } catch { + throw new ErrorClass(`The ${label} is not a valid base64url string`); + } +} +function parseJoseHeader(b64, ErrorClass, message) { + let parsed; + try { + parsed = JSON.parse(strictDecoder.decode(decode(b64))); + } catch { + throw new ErrorClass(message); + } + if (!isObject(parsed)) + throw new ErrorClass(message); + return parsed; +} +const JWS_RECOGNIZED = { __proto__: null, b64: !0 }, JWE_RECOGNIZED = { __proto__: null }; +function validateAlgorithms(option, algorithms) { + if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s != "string"))) + throw new TypeError(`"${option}" option must be an array of strings`); + return algorithms === void 0 ? void 0 : new Set(algorithms); +} +function validateCritDuplicates(Err, protectedHeader) { + const { crit } = protectedHeader ?? {}; + if (Array.isArray(crit) && new Set(crit).size !== crit.length) + throw new Err('"crit" (Critical) Header Parameter MUST NOT contain duplicate values'); +} +function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) { + if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) + throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected'); + if (!protectedHeader || protectedHeader.crit === void 0) + return []; + if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input != "string" || input.length === 0)) + throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present'); + const recognized = recognizedOption === void 0 ? recognizedDefault : { __proto__: null, ...recognizedOption, ...recognizedDefault }; + for (const parameter of protectedHeader.crit) { + if (!(parameter in recognized)) + throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`); + if (!Object.hasOwn(joseHeader, parameter) || joseHeader[parameter] === void 0) + throw new Err(`Extension Header Parameter "${parameter}" is missing`); + if (recognized[parameter] && (!Object.hasOwn(protectedHeader, parameter) || protectedHeader[parameter] === void 0)) + throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`); + } + return protectedHeader.crit; +} +function validateB64(protectedHeader, extensions) { + if (extensions.includes("b64")) { + const b64 = protectedHeader.b64; + if (typeof b64 != "boolean") + throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); + return b64; + } + return !0; +} +function serializeJoseHeader(Err, header) { + let serialized, parsed; + try { + serialized = JSON.stringify(header), parsed = JSON.parse(serialized); + } catch (cause) { + throw new Err("JOSE Header is not valid JSON", { cause }); + } + if (!isObject(parsed)) + throw new Err("JOSE Header is not a JSON object"); + return [parsed, serialized]; +} +export { + JWE_RECOGNIZED, + JWS_RECOGNIZED, + assertNotSet, + assertUint8Array, + decodeBase64url, + encodeBase64url, + isDisjoint, + isJwkSet, + isObject, + parseJoseHeader, + serializeJoseHeader, + validateAlgorithms, + validateB64, + validateCrit, + validateCritDuplicates +}; diff --git a/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/util/base64url.js b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/util/base64url.js new file mode 100644 index 000000000..4447baa6d --- /dev/null +++ b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/util/base64url.js @@ -0,0 +1,16 @@ +import { encoder, decoder, encodeBase64, decodeBase64 } from "../lib/buffer_utils.js"; +const invalid = "The input to be decoded is not correctly encoded."; +function decode(input) { + try { + return decodeBase64(typeof input == "string" ? input : decoder.decode(input), !0); + } catch (cause) { + throw new TypeError(invalid, { cause }); + } +} +function encode(input) { + return encodeBase64(typeof input == "string" ? encoder.encode(input) : input, !0); +} +export { + decode, + encode +}; diff --git a/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/util/errors.js b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/util/errors.js new file mode 100644 index 000000000..b7d579f51 --- /dev/null +++ b/tests/corpus/7132-jose-pbes2/node_modules/jose/dist/webapi/util/errors.js @@ -0,0 +1,109 @@ +class JOSEError extends Error { + static code = "ERR_JOSE_GENERIC"; + code = "ERR_JOSE_GENERIC"; + constructor(message, options) { + super(message, options), this.name = this.constructor.name, Error.captureStackTrace?.(this, this.constructor); + } +} +class JWTClaimValidationFailed extends JOSEError { + static code = "ERR_JWT_CLAIM_VALIDATION_FAILED"; + code = "ERR_JWT_CLAIM_VALIDATION_FAILED"; + claim; + reason; + payload; + constructor(message, payload, claim = "unspecified", reason = "unspecified") { + super(message, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload; + } +} +class JWTExpired extends JOSEError { + static code = "ERR_JWT_EXPIRED"; + code = "ERR_JWT_EXPIRED"; + claim; + reason; + payload; + constructor(message, payload, claim = "unspecified", reason = "unspecified") { + super(message, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload; + } +} +class JOSEAlgNotAllowed extends JOSEError { + static code = "ERR_JOSE_ALG_NOT_ALLOWED"; + code = "ERR_JOSE_ALG_NOT_ALLOWED"; +} +class JOSENotSupported extends JOSEError { + static code = "ERR_JOSE_NOT_SUPPORTED"; + code = "ERR_JOSE_NOT_SUPPORTED"; +} +class JWEDecryptionFailed extends JOSEError { + static code = "ERR_JWE_DECRYPTION_FAILED"; + code = "ERR_JWE_DECRYPTION_FAILED"; + constructor(message = "decryption operation failed", options) { + super(message, options); + } +} +class JWEInvalid extends JOSEError { + static code = "ERR_JWE_INVALID"; + code = "ERR_JWE_INVALID"; +} +class JWSInvalid extends JOSEError { + static code = "ERR_JWS_INVALID"; + code = "ERR_JWS_INVALID"; +} +class JWTInvalid extends JOSEError { + static code = "ERR_JWT_INVALID"; + code = "ERR_JWT_INVALID"; +} +class JWKInvalid extends JOSEError { + static code = "ERR_JWK_INVALID"; + code = "ERR_JWK_INVALID"; +} +class JWKSInvalid extends JOSEError { + static code = "ERR_JWKS_INVALID"; + code = "ERR_JWKS_INVALID"; +} +class JWKSNoMatchingKey extends JOSEError { + static code = "ERR_JWKS_NO_MATCHING_KEY"; + code = "ERR_JWKS_NO_MATCHING_KEY"; + constructor(message = "no applicable key found in the JSON Web Key Set", options) { + super(message, options); + } +} +class JWKSMultipleMatchingKeys extends JOSEError { + [Symbol.asyncIterator] = async function* () { + }; + static code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS"; + code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS"; + constructor(message = "multiple matching keys found in the JSON Web Key Set", options) { + super(message, options); + } +} +class JWKSTimeout extends JOSEError { + static code = "ERR_JWKS_TIMEOUT"; + code = "ERR_JWKS_TIMEOUT"; + constructor(message = "request timed out", options) { + super(message, options); + } +} +class JWSSignatureVerificationFailed extends JOSEError { + static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"; + code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"; + constructor(message = "signature verification failed", options) { + super(message, options); + } +} +export { + JOSEAlgNotAllowed, + JOSEError, + JOSENotSupported, + JWEDecryptionFailed, + JWEInvalid, + JWKInvalid, + JWKSInvalid, + JWKSMultipleMatchingKeys, + JWKSNoMatchingKey, + JWKSTimeout, + JWSInvalid, + JWSSignatureVerificationFailed, + JWTClaimValidationFailed, + JWTExpired, + JWTInvalid +}; diff --git a/tests/corpus/7132-jose-pbes2/node_modules/jose/package.json b/tests/corpus/7132-jose-pbes2/node_modules/jose/package.json new file mode 100644 index 000000000..bcb353430 --- /dev/null +++ b/tests/corpus/7132-jose-pbes2/node_modules/jose/package.json @@ -0,0 +1,17 @@ +{ + "name": "jose", + "version": "6.2.12", + "license": "MIT", + "type": "module", + "sideEffects": false, + "exports": { + "./jwt/*": { + "types": "./dist/types/jwt/*.d.ts", + "default": "./dist/webapi/jwt/*.js" + }, + "./errors": { + "types": "./dist/types/util/errors.d.ts", + "default": "./dist/webapi/util/errors.js" + } + } +} diff --git a/tests/corpus/7139-message-typed-records.ts b/tests/corpus/7139-message-typed-records.ts new file mode 100644 index 000000000..35d0d1588 --- /dev/null +++ b/tests/corpus/7139-message-typed-records.ts @@ -0,0 +1,85 @@ +import { MessageChannel } from "node:worker_threads"; + +// Typed records posted on a MessageChannel arrive as plain objects with +// the same keys, order and values as in Node: optional fields present and +// absent, nested records, a record reached twice, a record nested deeper +// than the encoder recurses, a record parsed with undeclared keys, and a +// function-valued field, which postMessage rejects. +type Point = { x: number; y: number }; +type Item = { id: number; name: string; done: boolean; pos: Point; note?: string }; +type Pair = { left: Point; right: Point }; +type Link = { value: number; next?: Link }; + +const { port1, port2 } = new MessageChannel(); +const lines: string[] = []; +const expected = 7; +port1.on("message", (value: unknown) => { + let checks = ""; + if (!Array.isArray(value)) { + const object = value as Record; + if ("left" in object) checks += ` same ${object["left"] === object["right"]}`; + const pos = object["pos"] as Record | undefined; + if (pos !== undefined) checks += ` negative zero ${Object.is(pos["x"], -0)}`; + } + lines.push(JSON.stringify(value) + checks); + if (lines.length === expected) { + for (const line of lines) console.log(line); + port1.close(); + } +}); + +const item: Item = { id: 1, name: "first", done: false, pos: { x: 1, y: 2 } }; +port2.postMessage(item); +const noted: Item = { id: 2, name: "", done: true, pos: { x: -0, y: 0.5 }, note: "n" }; +port2.postMessage(noted); + +const shared: Point = { x: 3, y: 4 }; +const pair: Pair = { left: shared, right: shared }; +port2.postMessage(pair); + +let chain: Link = { value: 0 }; +for (let i = 1; i < 40; i++) chain = { value: i, next: chain }; +port2.postMessage(chain); + +const parsed = JSON.parse('{"y":6,"extra":true,"x":5}') as Point; +port2.postMessage(parsed); +port2.postMessage({ x: 7, y: 8 } as Point); +port2.postMessage([item.pos, noted.pos]); + +type WithFunction = { id: number; run: () => number }; +const bad: WithFunction = { id: 9, run: () => 1 }; +try { + port2.postMessage(bad); +} catch (error) { + console.log("rejected", (error as Error).name); +} + +// Fields that hold objects with getters: each field's value is read +// completely, its getters included, before the next field's, as in Node. +type Holder = { id: number; first: unknown; second: unknown }; +const reads: string[] = []; +const getters: Holder = { + id: 1, + first: { + get a() { + reads.push("first.a"); + return 1; + }, + nested: { + get b() { + reads.push("first.nested.b"); + return 2; + }, + }, + }, + second: { + get c() { + reads.push("second.c"); + return 3; + }, + }, +}; +const { port1: getterPort, port2: getterSender } = new MessageChannel(); +getterSender.postMessage(getters); +console.log("getter order", reads.join(",")); +getterPort.close(); diff --git a/tests/corpus/7141-comoving-loop-counters.ts b/tests/corpus/7141-comoving-loop-counters.ts new file mode 100644 index 000000000..a756b7a46 --- /dev/null +++ b/tests/corpus/7141-comoving-loop-counters.ts @@ -0,0 +1,144 @@ +// For loops with a second counter that steps beside the tested one +// (`i++, j += 4`): pixel strides over typed arrays, interleaving into number +// arrays, descending and inclusive loops, three counters, early exits, +// starts and limits that are fractions, negative zero, NaN, infinite or +// near 2^53, counters that live across a yield or an await, and counters a +// closure captures, the body writes or the condition reads. +function luminance(px: Uint8Array, count: number): number[] { + const out: number[] = []; + for (let i = 0, p = 0; i < count; i++, p += 4) { + out.push((px[p]! * 77 + px[p + 1]! * 150 + px[p + 2]! * 29) >> 8); + } + return out; +} +const px = new Uint8Array(32); +for (let k = 0; k < px.length; k++) px[k] = (k * 37 + 11) & 255; +console.log(luminance(px, 8).join(",")); +// Past the end, reads are undefined and the sums NaN, which `>> 8` makes 0. +console.log(luminance(px, 10).join(",")); +console.log(luminance(px, 0).length, luminance(px, -3).length, luminance(px, 2.5).join(",")); +console.log(luminance(px, NaN).length); + +function interleave(a: number[], b: number[]): number[] { + const out: number[] = new Array(a.length * 2).fill(-1); + const n = a.length; + for (let i = 0, j = 0; i < n; i++, j += 2) { + out[j] = a[i]!; + out[j + 1] = b[i]!; + } + return out; +} +console.log(interleave([1, 2, 3, 4], [10, 20, 30, 40]).join(",")); +console.log(interleave([], []).length); + +// The second counter's start is not proven: charCodeAt truncates its index, +// and the counter's own values keep JS semantics. +function codes(s: string, count: number, from: number, step: number): string { + const out: (number | string)[] = []; + if (step === 3) { + for (let i = 0, j = from; i < count; i++, j += 3) out.push(s.charCodeAt(j), j); + } else { + for (let i = 0, j = from; i < count; i++, j -= 2) out.push(s.charCodeAt(j), j); + } + return out.join(","); +} +const word = "abcdefghijklmnop"; +console.log(codes(word, 4, 0, 3), "|", codes(word, 4, 15, -2)); +console.log(codes(word, 4, 0.5, 3), "|", codes(word, 3, 9.75, -2)); +const negativeZero = -0; +console.log(codes(word, 2, negativeZero, 3), Object.is(negativeZero, -0)); +console.log(codes(word, 2, NaN, 3), "|", codes(word, 2, Infinity, -2), "|", codes(word, 2, -Infinity, 3)); +// Near 2^52 the run-time test passes or fails on the trip count; near 2^53 +// the double counter rounds (odd values above 2^53 are not representable). +console.log(codes(word, 4, 2 ** 52 - 16, 3)); +console.log(codes(word, 6, 2 ** 52 - 4, 3)); +console.log(codes(word, 6, 2 ** 53 - 10, 3)); +console.log(codes(word, 4, -(2 ** 53) + 3, -2)); +// A limit that is not finite or not an integer. +function capped(s: string, limit: number): string { + const out: number[] = []; + for (let i = 0, j = 1; i < limit; i++, j += 2) { + if (j >= s.length) break; + out.push(s.charCodeAt(j)); + } + return out.join(","); +} +console.log(capped(word, Infinity), "|", capped(word, 3.5), "|", capped(word, NaN), "|", capped(word, -Infinity)); + +// A descending driver with an ascending follower, inclusive bounds and +// larger steps. +function mirror(s: string): string { + const out: string[] = []; + for (let i = s.length - 1, j = 0; i >= 0; i--, j += 2) out.push(`${s.charCodeAt(i)}@${j}`); + return out.join(" "); +} +console.log(mirror("scriptc")); +function stepped(bytes: Uint8Array, last: number): string { + const out: number[] = []; + for (let i = 0, j = bytes.length - 1; i <= last; i += 3, j -= 5) + out.push(bytes[i]! | 0, bytes[j]! | 0, j); + return out.join(","); +} +console.log(stepped(px, 9), "|", stepped(px, 30)); + +// Three counters, continue and break. +function triple(a: Uint8Array, n: number): string { + const out: number[] = []; + for (let i = 0, j = 10, k = 100; i < n; i++, j -= 1, k += 7) { + if (i % 3 === 1) continue; + if (k > 150) break; + out.push(a[i]!, a[j]!, k); + } + return out.join(","); +} +console.log(triple(px, 12), "|", triple(px, 4)); + +// A counted limit with a known range and a follower used by a remainder. +let rotated = 0; +for (let i = 0, j = 5; i < 1000; i++, j += 3) rotated = (rotated * 31 + px[j % 32]!) % 1000003; +console.log(rotated); + +// The follower starting from a driver's start of unproven exactness. +function window(bytes: Uint8Array, from: number, to: number): string { + const out: number[] = []; + for (let i = from, j = 0; i < to; i++, j += 2) out.push(bytes[i]! | 0, bytes[j]! | 0, i, j); + return out.join(","); +} +console.log(window(px, 2, 5), "|", window(px, 1.5, 4), "|", window(px, -0, 2)); + +// Counters a closure captures keep one binding per iteration; a follower the +// body writes, one the condition reads, and a start that reads another +// counter keep their JS values. +const reads: (() => number)[] = []; +for (let i = 0, j = 0; i < 3; i++, j += 4) { + reads.push(() => j); + void px[j]; +} +console.log(reads.map((read) => read()).join(",")); +const written: number[] = []; +for (let i = 0, j = 0; i < 5; i++, j += 2) { + if (i === 2) j += 7; + written.push(px[j]!, j); +} +console.log(written.join(",")); +const chased: number[] = []; +for (let i = 0, j = 5; i < j; i += 2, j++) chased.push(px[i]!, i, j); +console.log(chased.join(",")); +const offset: number[] = []; +for (let i = 1, j = i + 1; i < 4; i++, j += 2) offset.push(px[j]!, j); +console.log(offset.join(",")); + +// Counters that live across a yield or an await. +function* strided(bytes: Uint8Array, n: number): Generator { + for (let i = 0, j = 1; i < n; i++, j += 3) yield bytes[j]! + i; +} +console.log([...strided(px, 6)].join(",")); +async function weighted(bytes: Uint8Array, n: number): Promise { + let sum = 0; + for (let i = 0, j = 2; i < n; i++, j += 5) { + await null; + sum += bytes[j]! * (i + 1); + } + return sum; +} +void (async () => console.log(await weighted(px, 6), await weighted(px, 3)))(); diff --git a/tests/corpus/7142-array-read-filled-prefix.ts b/tests/corpus/7142-array-read-filled-prefix.ts new file mode 100644 index 000000000..11cf2f675 --- /dev/null +++ b/tests/corpus/7142-array-read-filled-prefix.ts @@ -0,0 +1,72 @@ +// Element reads that may be undefined (`a[i]` as `T | undefined`, and the +// stores `a[x] = a[y]!` read through) on arrays whose hole-free prefix +// changes: holes from writes past the end and from a longer length, present +// undefined, shrinking and regrowing, shift and unshift, out-of-range and +// negative indices, and reads at a loop counter and at a computed index. +function show(a: (number | undefined)[]): string { + const out: string[] = []; + for (let i = -1; i <= a.length; i++) { + const v = a[i]; + out.push(v === undefined ? (i in a ? "u" : "_") : String(v)); + } + return out.join(","); +} +const a: (number | undefined)[] = [10, 11, 12, 13, 14, 15]; +console.log(show(a)); +a[8] = 18; +console.log(show(a), 7 in a); +a.length = 9; +console.log(show(a)); +a[7] = 17; +console.log(show(a)); +a.length = 3; +console.log(show(a)); +a.push(30, 31); +console.log(show(a)); +a.unshift(1); +console.log(show(a)); +a.shift(); +a.shift(); +console.log(show(a)); +const withUndefined: (number | undefined)[] = [1, undefined, 3]; +console.log(show(withUndefined)); + +// Copies through the read: a hole stores undefined, which `in` then sees. +function rotate(p: number[], r: number): void { + const first = p[0]!; + for (let i = 0; i < r; i++) p[i] = p[i + 1]!; + p[r] = first; +} +const p: number[] = [0, 1, 2, 3, 4]; +rotate(p, 4); +console.log(p.join(",")); +const holes: number[] = new Array(4); +holes[0] = 0; +holes[1] = 1; +holes[3] = 3; +rotate(holes, 3); +console.log(holes.length, 1 in holes, holes[1] === undefined, holes.join(",")); + +// Reads at a computed index and at an index beyond the capacity. +function pick(src: number[], idx: number[]): string { + const out: string[] = []; + for (const k of idx) { + const v = src[k * 2]; + out.push(v === undefined ? "-" : String(v)); + } + return out.join(","); +} +const big: number[] = []; +for (let k = 0; k < 40; k++) big.push(k * k); +console.log(pick(big, [0, 1, 5, 19, 20, 1000, -1, 2 ** 31])); +big.length = 10; +console.log(pick(big, [0, 4, 5, 6])); + +// Swaps at two counters, then reads of the swapped array. +const q: number[] = [5, 4, 3, 2, 1, 0]; +for (let lo = 0, hi = q.length - 1; lo < hi; lo++, hi--) { + const t = q[lo]!; + q[lo] = q[hi]!; + q[hi] = t; +} +console.log(q.join(","), show(q)); diff --git a/tests/corpus/7143-optional-read-integer-index.ts b/tests/corpus/7143-optional-read-integer-index.ts new file mode 100644 index 000000000..43fd59a6e --- /dev/null +++ b/tests/corpus/7143-optional-read-integer-index.ts @@ -0,0 +1,70 @@ +// Element reads that may be undefined, at indices with a proven integer +// range: loop counters with an unknown limit, `i | 0`, `x >>> 0`, negative +// counters, -0, indices past the length and the capacity, and copies +// `a[x] = b[y]!` that meet holes. +function copy(src: number[], n: number): number[] { + const out: number[] = new Array(n); + for (let i = 0; i < n; i++) out[i] = src[i]!; + return out; +} +const src: number[] = [1, 2, 3, 4]; +const copied = copy(src, 6); +console.log(copied.length, copied.join(","), 4 in copied, copied[5] === undefined); + +const holes: number[] = new Array(5); +holes[0] = 10; +holes[3] = 13; +const fromHoles = copy(holes, 5); +console.log(fromHoles.join(","), 1 in fromHoles, 3 in fromHoles); + +function show(a: (string | undefined)[], from: number, to: number): string { + const out: string[] = []; + for (let i = from; i < to; i++) { + const v = a[i]; + out.push(v === undefined ? "_" : v); + } + return out.join(","); +} +const words: (string | undefined)[] = ["a", undefined, "c"]; +words[5] = "f"; +console.log(show(words, -3, 8)); +console.log(show(words, 0, 0), show(words, 2, 1)); + +function masked(a: number[], keys: number[]): string { + const out: string[] = []; + for (const k of keys) { + const v = a[k | 0]; + const w = a[k >>> 0]; + out.push(`${v === undefined ? "-" : v}/${w === undefined ? "-" : w}`); + } + return out.join(" "); +} +const values: number[] = [5, 6, 7]; +console.log(masked(values, [0, 1.9, 2, 3, -1, -0, 4294967297, 2 ** 31])); + +const negativeZero = -0; +console.log(values[negativeZero], values[0 * -1], Object.is(negativeZero, -0)); + +// A counter that starts below zero and one that passes the capacity. +let total = 0; +for (let i = -2; i < values.length + 3; i++) total += values[i] ?? 100; +console.log(total); +const big: number[] = []; +for (let k = 0; k < 20; k++) big.push(k); +big.length = 10; +let seen = 0; +for (let i = 0; i < 40; i++) if (big[i] !== undefined) seen++; +console.log(seen, big.length); + +// Rotations through the read, with a hole that becomes undefined. +function rotate(p: number[], r: number): void { + const first = p[0]!; + for (let i = 0; i < r; i++) p[i] = p[i + 1]!; + p[r] = first; +} +const ring: number[] = new Array(4); +ring[0] = 0; +ring[1] = 1; +ring[3] = 3; +rotate(ring, 3); +console.log(ring.join(","), 1 in ring, ring[1] === undefined); diff --git a/tests/corpus/7150-cipher-legacy-modes.ts b/tests/corpus/7150-cipher-legacy-modes.ts new file mode 100644 index 000000000..80edfd029 --- /dev/null +++ b/tests/corpus/7150-cipher-legacy-modes.ts @@ -0,0 +1,74 @@ +// createCipheriv and createDecipheriv in the legacy modes: AES in ECB, +// CFB, CFB8, CFB1 and OFB, triple DES (three- and two-key) in CBC, ECB, +// CFB, CFB8, CFB1 and OFB, and bare chacha20. Fixed keys, IVs and inputs +// give Node's exact ciphertexts; chunked updates, string encodings, +// disabled padding and chacha20's 64-bit counter carry round-trip. +import { createCipheriv, createDecipheriv } from "node:crypto"; + +function bytes(length: number, seed: number): Buffer { + const out = Buffer.alloc(length); + for (let i = 0; i < length; i++) out[i] = (i * 29 + seed) & 0xff; + return out; +} + +const plaintext = Buffer.from("The five boxing wizards jump quickly; sphinx of black quartz, judge my vow."); + +function encrypt(name: string, key: Buffer, iv: Buffer | null, data: Buffer, chunk: number): Buffer { + const cipher = createCipheriv(name, key, iv); + const parts: Buffer[] = []; + for (let off = 0; off < data.length; off += chunk) parts.push(cipher.update(data.subarray(off, off + chunk))); + parts.push(cipher.final()); + return Buffer.concat(parts); +} + +function decrypt(name: string, key: Buffer, iv: Buffer | null, data: Buffer, chunk: number): Buffer { + const decipher = createDecipheriv(name, key, iv); + const parts: Buffer[] = []; + for (let off = 0; off < data.length; off += chunk) parts.push(decipher.update(data.subarray(off, off + chunk))); + parts.push(decipher.final()); + return Buffer.concat(parts); +} + +const cases: [string, number, number][] = []; +for (const bits of [128, 192, 256]) + for (const mode of ["ecb", "cfb", "cfb8", "cfb1", "ofb"]) cases.push([`aes-${bits}-${mode}`, bits / 8, mode === "ecb" ? 0 : 16]); +for (const name of ["des-ede3-cbc", "des3", "des-ede3", "des-ede3-ecb", "des-ede3-cfb", "des-ede3-cfb8", "des-ede3-cfb1", "des-ede3-ofb"]) + cases.push([name, 24, name === "des-ede3" || name === "des-ede3-ecb" ? 0 : 8]); +for (const name of ["des-ede-cbc", "des-ede", "des-ede-ecb", "des-ede-cfb", "des-ede-ofb"]) + cases.push([name, 16, name === "des-ede" || name === "des-ede-ecb" ? 0 : 8]); +cases.push(["chacha20", 32, 16]); + +for (const [name, keyLength, ivLength] of cases) { + const key = bytes(keyLength, keyLength + 3); + const iv = ivLength ? bytes(ivLength, 11) : null; + const sealed = encrypt(name, key, iv, plaintext, plaintext.length); + const chunked = encrypt(name, key, iv, plaintext, 7); + const opened = decrypt(name, key, iv, sealed, 5); + console.log(name.padEnd(14), sealed.length, sealed.toString("hex").slice(0, 48), chunked.equals(sealed), opened.equals(plaintext)); +} + +// String input and output encodings through a stream mode. +const ofb = createCipheriv("aes-128-ofb", bytes(16, 1), bytes(16, 2)); +const encoded = ofb.update("68656c6c6f20776f726c64", "hex", "base64") + ofb.final("base64"); +const unofb = createDecipheriv("aes-128-ofb", bytes(16, 1), bytes(16, 2)); +console.log(encoded, unofb.update(encoded, "base64", "utf8") + unofb.final("utf8")); + +// ECB and triple-DES CBC without padding over whole blocks. +for (const [name, keyLength, ivLength, block] of [["aes-256-ecb", 32, 0, 16], ["des-ede3-cbc", 24, 8, 8]] as const) { + const cipher = createCipheriv(name, bytes(keyLength, 5), ivLength ? bytes(ivLength, 6) : null); + cipher.setAutoPadding(false); + const sealed = Buffer.concat([cipher.update(bytes(block * 3, 7)), cipher.final()]); + const decipher = createDecipheriv(name, bytes(keyLength, 5), ivLength ? bytes(ivLength, 6) : null); + decipher.setAutoPadding(false); + const opened = Buffer.concat([decipher.update(sealed), decipher.final()]); + console.log(name, "unpadded", sealed.length, sealed.toString("hex").slice(0, 32), opened.equals(bytes(block * 3, 7))); +} + +// chacha20's counter is the IV's first 8 bytes, little-endian: the low +// word carries into the high word, which wraps. +const chachaKey = bytes(32, 9); +for (const counter of ["ffffffff00000000", "ffffffffffffffff", "fffffffe01000000"]) { + const iv = Buffer.from(counter + "0102030405060708", "hex"); + const stream = encrypt("chacha20", chachaKey, iv, Buffer.alloc(200), 50); + console.log("chacha20", counter, stream.toString("hex").slice(120, 152), stream.subarray(64, 96).toString("hex")); +} diff --git a/tests/corpus/7151-cipher-legacy-errors.cjs b/tests/corpus/7151-cipher-legacy-errors.cjs new file mode 100644 index 000000000..fe9c59bcc --- /dev/null +++ b/tests/corpus/7151-cipher-legacy-errors.cjs @@ -0,0 +1,83 @@ +// createCipheriv errors for the legacy modes, in Node's order: the IV +// length each mode takes (none for ECB), the key length, OpenSSL's +// "unsupported" for the ciphers its legacy provider holds, and the block +// modes' final-block and padding failures; the AEAD-only methods throw +// Node's invalid-state errors on the stream modes. +const crypto = require("crypto"); + +function attempt(label, run) { + try { + const value = run(); + console.log(label, "ok", Buffer.isBuffer(value) ? value.toString("hex") : value); + } catch (e) { + console.log(label, e.name, e.code, e.message, e.library, e.reason, JSON.stringify(e.opensslErrorStack)); + } +} + +const k16 = Buffer.alloc(16, 1), k24 = Buffer.alloc(24, 1), k32 = Buffer.alloc(32, 1); +attempt("ecb null iv", () => crypto.createCipheriv("aes-128-ecb", k16, null).final()); +attempt("ecb empty iv", () => crypto.createCipheriv("aes-128-ecb", k16, Buffer.alloc(0)).final()); +attempt("ecb 16-byte iv", () => crypto.createCipheriv("aes-128-ecb", k16, Buffer.alloc(16))); +attempt("cfb 15-byte iv", () => crypto.createCipheriv("aes-128-cfb", k16, Buffer.alloc(15))); +attempt("cfb null iv", () => crypto.createCipheriv("aes-128-cfb", k16, null)); +attempt("ofb key 15", () => crypto.createCipheriv("aes-128-ofb", Buffer.alloc(15), Buffer.alloc(16))); +attempt("des3 16-byte iv", () => crypto.createCipheriv("des-ede3-cbc", k24, Buffer.alloc(16))); +attempt("des3 16-byte key", () => crypto.createCipheriv("des-ede3-cbc", k16, Buffer.alloc(8))); +attempt("des-ede 24-byte key", () => crypto.createCipheriv("des-ede-cbc", k24, Buffer.alloc(8))); +attempt("des-ede3 ecb with iv", () => crypto.createCipheriv("des-ede3", k24, Buffer.alloc(8))); +attempt("chacha20 12-byte iv", () => crypto.createCipheriv("chacha20", k32, Buffer.alloc(12))); +attempt("chacha20 authTagLength ignored", () => crypto.createCipheriv("chacha20", k32, Buffer.alloc(16), { authTagLength: 16 }).update("x")); +attempt("upper-case name", () => crypto.createCipheriv("DES-EDE3-CBC", k24, Buffer.alloc(8)).final()); +attempt("des-cbc", () => crypto.createCipheriv("des-cbc", Buffer.alloc(8), Buffer.alloc(8))); +attempt("des-cbc bad iv", () => crypto.createCipheriv("des-cbc", Buffer.alloc(8), Buffer.alloc(3))); +attempt("des-cbc bad key", () => crypto.createCipheriv("des-cbc", Buffer.alloc(3), Buffer.alloc(8))); +attempt("bf-cbc", () => crypto.createDecipheriv("bf-cbc", k16, Buffer.alloc(8))); +attempt("rc4", () => crypto.createCipheriv("rc4", k16, null)); +attempt("rc4 with iv", () => crypto.createCipheriv("rc4", k16, Buffer.alloc(8))); +attempt("seed-ecb", () => crypto.createCipheriv("seed-ecb", k16, null)); +attempt("unknown cipher", () => crypto.createCipheriv("aes-128-xyz", k16, Buffer.alloc(16))); + +attempt("cfb getAuthTag", () => { + const c = crypto.createCipheriv("aes-128-cfb", k16, Buffer.alloc(16)); + c.update("x"); + c.final(); + return c.getAuthTag(); +}); +attempt("ofb setAAD", () => crypto.createCipheriv("aes-128-ofb", k16, Buffer.alloc(16)).setAAD(Buffer.alloc(1))); +attempt("chacha20 setAuthTag", () => crypto.createDecipheriv("chacha20", k32, Buffer.alloc(16)).setAuthTag(Buffer.alloc(16))); +attempt("cfb update sizes", () => { + const c = crypto.createCipheriv("aes-128-cfb", k16, Buffer.alloc(16)); + return [c.update("abc").length, c.update("defghijklmnopqrstu").length, c.final().length].join(","); +}); +attempt("cfb1 setAutoPadding(false)", () => { + const c = crypto.createCipheriv("aes-128-cfb1", k16, Buffer.alloc(16)); + c.setAutoPadding(false); + return Buffer.concat([c.update("abc"), c.final()]); +}); +attempt("ecb unpadded short", () => { + const c = crypto.createCipheriv("aes-128-ecb", k16, null); + c.setAutoPadding(false); + c.update(Buffer.alloc(31, 7)); + return c.final(); +}); +attempt("des3 unpadded short", () => { + const c = crypto.createCipheriv("des-ede3-cbc", k24, Buffer.alloc(8)); + c.setAutoPadding(false); + c.update(Buffer.alloc(7)); + return c.final(); +}); +attempt("des3 bad decrypt", () => { + const d = crypto.createDecipheriv("des-ede3-cbc", k24, Buffer.alloc(8)); + d.update(Buffer.alloc(16, 9)); + return d.final(); +}); +attempt("ecb decrypt 15 bytes", () => { + const d = crypto.createDecipheriv("aes-128-ecb", k16, null); + d.update(Buffer.alloc(15)); + return d.final(); +}); +attempt("ofb update after final", () => { + const c = crypto.createCipheriv("aes-128-ofb", k16, Buffer.alloc(16)); + c.final(); + return c.update("x"); +}); diff --git a/tests/corpus/7152-crypto-prime.ts b/tests/corpus/7152-crypto-prime.ts new file mode 100644 index 000000000..79edcc502 --- /dev/null +++ b/tests/corpus/7152-crypto-prime.ts @@ -0,0 +1,96 @@ +// checkPrimeSync, checkPrime, generatePrimeSync and generatePrime: known +// primes, composites and strong pseudoprimes as bigints, Buffers, typed +// arrays, ArrayBuffers and DataViews, the checks option, and generated +// primes' length, top bits, primality, residues and safety, as +// ArrayBuffers and bigints, synchronously and through the callbacks (whose +// error parameter, typed Error | null, receives null where Node passes +// undefined). The small sizes and the add and rem forms have one possible +// result. +import { checkPrime, checkPrimeSync, generatePrime, generatePrimeSync } from "node:crypto"; + +const mersenne61 = 2n ** 61n - 1n; +const mersenne127 = 2n ** 127n - 1n; +const mersenne521 = 2n ** 521n - 1n; +const known: [string, bigint][] = [ + ["0", 0n], + ["1", 1n], + ["2", 2n], + ["3", 3n], + ["4", 4n], + ["9", 9n], + ["17863", 17863n], + ["17881", 17881n], + ["561 (Carmichael)", 561n], + ["2047 (strong pseudoprime to 2)", 2047n], + ["3215031751 (strong pseudoprime to 2, 3, 5 and 7)", 3215031751n], + ["2^61 - 1", mersenne61], + ["2^61 + 1", mersenne61 + 2n], + ["2^127 - 1", mersenne127], + ["(2^61 - 1)(2^127 - 1)", mersenne61 * mersenne127], + ["2^521 - 1", mersenne521], + ["2^521 + 1", mersenne521 + 2n], +]; +for (const [label, value] of known) console.log(label, checkPrimeSync(value)); + +console.log("Buffer 13", checkPrimeSync(Buffer.from([0, 0, 13]))); +console.log("Uint8Array 15", checkPrimeSync(new Uint8Array([15]))); +const words = new ArrayBuffer(8); +new DataView(words).setBigUint64(0, mersenne61); +console.log("ArrayBuffer 2^61 - 1", checkPrimeSync(words)); +console.log("DataView 2^61 - 1", checkPrimeSync(new DataView(words))); +console.log("empty", checkPrimeSync(new Uint8Array(0))); +console.log("checks 1", checkPrimeSync(97n, { checks: 1 })); +console.log("checks 200", checkPrimeSync(3215031751n, { checks: 200 })); + +const bitLength = (n: bigint): number => n.toString(2).length; +const fromBuffer = (buffer: ArrayBuffer): bigint => BigInt("0x" + Buffer.from(buffer).toString("hex")); + +for (const bits of [2, 3, 4]) console.log("size", bits, generatePrimeSync(bits, { bigint: true })); +const five = generatePrimeSync(5, { bigint: true }); +console.log("size 5", five === 29n || five === 31n); +for (const bits of [8, 16, 31, 32, 33, 64, 127, 256, 512]) { + const p = generatePrimeSync(bits, { bigint: true }); + console.log("size", bits, bitLength(p) === bits, p >> BigInt(bits - 2), checkPrimeSync(p)); +} +const buffer = generatePrimeSync(96); +console.log("ArrayBuffer", buffer instanceof ArrayBuffer, buffer.byteLength, checkPrimeSync(buffer), bitLength(fromBuffer(buffer))); +console.log("bigint false", generatePrimeSync(40, { bigint: false }).byteLength); + +for (const bits of [3, 6, 7]) console.log("safe", bits, generatePrimeSync(bits, { safe: true, bigint: true })); +for (const bits of [16, 64, 128]) { + const p = generatePrimeSync(bits, { safe: true, bigint: true }); + console.log("safe", bits, bitLength(p) === bits, p >> BigInt(bits - 2), checkPrimeSync(p), checkPrimeSync((p - 1n) / 2n)); +} + +console.log("add 200 rem 1", generatePrimeSync(8, { add: 200n, rem: 1n, bigint: true })); +console.log("add 128", generatePrimeSync(8, { add: 128n, bigint: true })); +console.log("add 16 rem 3", generatePrimeSync(5, { add: 16n, rem: 3n, bigint: true })); +const safe4 = generatePrimeSync(5, { add: 4n, safe: true, bigint: true }); +console.log("add 4 safe", safe4 === 23n || safe4 === 47n); +for (const [label, add, rem] of [ + ["add 12 rem 11", 12n, 11n], + ["add 6", 6n, undefined], + ["add 1000 rem 7", 1000n, 7n], +] as const) { + const p = generatePrimeSync(48, rem === undefined ? { add, bigint: true } : { add, rem, bigint: true }); + console.log(label, p % add, checkPrimeSync(p), bitLength(p) >= 48); +} +const viaBuffer = generatePrimeSync(64, { add: Buffer.from([0x01, 0x00]), rem: new Uint8Array([0x0f]), bigint: true }); +console.log("add and rem as bytes", viaBuffer % 256n, checkPrimeSync(viaBuffer)); +const safeAdd = generatePrimeSync(64, { add: 24n, rem: 23n, safe: true, bigint: true }); +console.log("safe add 24 rem 23", safeAdd % 24n, checkPrimeSync((safeAdd - 1n) / 2n)); +console.log("rem without add", generatePrimeSync(16, { rem: 5n, bigint: true }) < 65536n); + +generatePrime(64, (err, prime) => { + console.log("callback", err ?? "no error", prime instanceof ArrayBuffer, prime.byteLength, checkPrimeSync(prime)); + generatePrime(128, { safe: true, bigint: true }, (err2, safe) => { + console.log("callback safe", err2 ?? "no error", bitLength(safe), checkPrimeSync((safe - 1n) / 2n)); + checkPrime(safe, (err3, result) => { + console.log("checkPrime", err3 ?? "no error", result); + checkPrime(Buffer.from([1, 1]), { checks: 3 }, (err4, result2) => { + console.log("checkPrime 257", err4 ?? "no error", result2); + }); + }); + }); +}); +console.log("sync done"); diff --git a/tests/corpus/7153-crypto-prime-errors.cjs b/tests/corpus/7153-crypto-prime-errors.cjs new file mode 100644 index 000000000..ff32e6e09 --- /dev/null +++ b/tests/corpus/7153-crypto-prime-errors.cjs @@ -0,0 +1,80 @@ +// checkPrime, checkPrimeSync, generatePrime and generatePrimeSync errors from +// JavaScript: argument types and ranges, the options bag, add and rem, and +// OpenSSL's generation failures, synchronously and through the callbacks. +const crypto = require("crypto"); + +function attempt(label, run) { + try { + const value = run(); + console.log(label, "ok", typeof value === "bigint" ? `${value}n` : value instanceof ArrayBuffer ? `ArrayBuffer(${value.byteLength})` : value); + } catch (e) { + console.log(label, e.name, e.code, e.message, JSON.stringify(Object.keys(e))); + } +} + +attempt("check string", () => crypto.checkPrimeSync("7")); +attempt("check number", () => crypto.checkPrimeSync(7)); +attempt("check negative", () => crypto.checkPrimeSync(-7n)); +attempt("check large negative", () => crypto.checkPrimeSync(-(2n ** 40n))); +attempt("check options null", () => crypto.checkPrimeSync(7n, null)); +attempt("check options array", () => crypto.checkPrimeSync(7n, [])); +attempt("check options string", () => crypto.checkPrimeSync(7n, "x")); +attempt("check checks string", () => crypto.checkPrimeSync(7n, { checks: "1" })); +attempt("check checks fraction", () => crypto.checkPrimeSync(7n, { checks: 1.5 })); +attempt("check checks -1", () => crypto.checkPrimeSync(7n, { checks: -1 })); +attempt("check checks 2^31", () => crypto.checkPrimeSync(7n, { checks: 2 ** 31 })); +attempt("check checks -0", () => crypto.checkPrimeSync(7n, { checks: -0 })); +attempt("check checks 10", () => crypto.checkPrimeSync(7n, { checks: 10 })); +attempt("check no callback", () => crypto.checkPrime(7n)); +attempt("check callback string", () => crypto.checkPrime(7n, {}, "cb")); +attempt("check async string", () => crypto.checkPrime("7", () => {})); +attempt("check async options null", () => crypto.checkPrime(7n, null, () => {})); + +attempt("size string", () => crypto.generatePrimeSync("8")); +attempt("size fraction", () => crypto.generatePrimeSync(8.5)); +attempt("size 0", () => crypto.generatePrimeSync(0)); +attempt("size 2^31", () => crypto.generatePrimeSync(2 ** 31)); +attempt("size NaN", () => crypto.generatePrimeSync(NaN)); +attempt("size 1", () => crypto.generatePrimeSync(1)); +attempt("size 2 safe", () => crypto.generatePrimeSync(2, { safe: true })); +attempt("size 4 safe", () => crypto.generatePrimeSync(4, { safe: true })); +attempt("size 5 safe", () => crypto.generatePrimeSync(5, { safe: true })); +attempt("options null", () => crypto.generatePrimeSync(8, null)); +attempt("options number", () => crypto.generatePrimeSync(8, 1)); +attempt("safe string", () => crypto.generatePrimeSync(8, { safe: "yes" })); +attempt("bigint number", () => crypto.generatePrimeSync(8, { bigint: 1 })); +attempt("add number", () => crypto.generatePrimeSync(8, { add: 6 })); +attempt("add string", () => crypto.generatePrimeSync(8, { add: "6" })); +attempt("add negative", () => crypto.generatePrimeSync(8, { add: -6n })); +attempt("rem number", () => crypto.generatePrimeSync(8, { add: 6n, rem: 1 })); +attempt("rem negative", () => crypto.generatePrimeSync(8, { add: 6n, rem: -1n })); +attempt("add too long", () => crypto.generatePrimeSync(8, { add: 1024n })); +attempt("add zero", () => crypto.generatePrimeSync(8, { add: 0n })); +attempt("add zero bytes", () => crypto.generatePrimeSync(8, { add: new Uint8Array(0) })); +attempt("rem equal add", () => crypto.generatePrimeSync(8, { add: 6n, rem: 6n })); +attempt("rem above add", () => crypto.generatePrimeSync(8, { add: 6n, rem: 7n })); +attempt("rem without add", () => crypto.generatePrimeSync(8, { rem: 1000n, bigint: true }) < 256n); +attempt("add 1 bigint", () => crypto.generatePrimeSync(8, { add: 1n, bigint: true }) < 256n); +attempt("gen no callback", () => crypto.generatePrime(8)); +attempt("gen options callback", () => crypto.generatePrime(8, {})); +attempt("gen size string", () => crypto.generatePrime("8", () => {})); +attempt("gen add too long", () => crypto.generatePrime(8, { add: 1024n }, () => {})); +attempt("gen options null", () => crypto.generatePrime(8, null, () => {})); + +// The callback forms' generation errors and results, one after another. +crypto.generatePrime(1, function (err, prime) { + console.log("gen 1 callback", arguments.length, err.name, err.code, err.message, JSON.stringify(Object.keys(err)), prime); + crypto.generatePrime(8, { add: 0n }, function (err2, prime2) { + console.log("gen add 0 callback", arguments.length, err2.message, prime2); + crypto.generatePrime(3, { safe: true, bigint: true }, function (err3, prime3) { + console.log("gen 3 safe callback", arguments.length, err3, prime3); + crypto.checkPrime(7n, function (err4, result) { + console.log("check 7 callback", arguments.length, err4, result); + crypto.checkPrime(new Uint8Array([0, 0, 9]), { checks: 3 }, function (err5, result2) { + console.log("check 9 callback", arguments.length, err5, result2); + }); + }); + }); + }); +}); +console.log("sync end"); diff --git a/tests/corpus/7180-generic-local-binding-early-uses.ts b/tests/corpus/7180-generic-local-binding-early-uses.ts new file mode 100644 index 000000000..f3f7816b5 --- /dev/null +++ b/tests/corpus/7180-generic-local-binding-early-uses.ts @@ -0,0 +1,69 @@ +// Generic arrow bindings declared inside functions, used by code that runs +// before or after the declaration: closures created above the declaration +// and hoisted function declarations read the binding like any const, so a +// use before the declaration throws a ReferenceError and a later one sees +// the function. +function describe(error: unknown): string { + return error instanceof Error ? `${error.name}: ${error.message}` : String(error); +} + +function make(): (x: number) => number { + const read = (): ((x: number) => number) => id; + const id: (x: number) => number = (x: T): T => x; + return read(); +} +console.log(make()(7)); + +function outer(flag: boolean): number { + if (flag) return helper(); + const id: (x: number) => number = (x: T): T => x; + return helper(); + + function helper(): number { + return id(1); + } +} +console.log(outer(false)); +try { + console.log(outer(true)); +} catch (error) { + console.log(describe(error)); +} + +function run(): void { + const early = (): number => id(2); + try { + early(); + } catch (error) { + console.log(describe(error)); + } + const id: (x: number) => number = (x: T): T => x; + console.log(early()); +} +run(); + +function counter(): () => number { + let total = 0; + const step = (): number => (total = add(total, 1)); + const add: (a: number, b: number) => number = (a: T, b: T): number => a + b; + step(); + step(); + return step; +} +console.log(counter()()); + +// Each evaluation of the declaration makes a new function object. +const first = make(); +console.log(first === make(), first === first, first(8)); +function looped(): string { + const seen: ((x: string) => string)[] = []; + for (let i = 0; i < 2; i++) { + const read = (): ((x: string) => string) => tag; + const tag: (x: string) => string = function (x: T): T { + return x; + }; + seen.push(read()); + } + return `${seen[0] === seen[1]} ${seen[1]!("p")}`; +} +console.log(looped()); diff --git a/tests/corpus/7181-generic-module-binding-tdz.ts b/tests/corpus/7181-generic-module-binding-tdz.ts new file mode 100644 index 000000000..d2d2915fb --- /dev/null +++ b/tests/corpus/7181-generic-module-binding-tdz.ts @@ -0,0 +1,49 @@ +// A module-scope generic arrow binding is in its temporal dead zone until +// its declaration runs: a hoisted function or an earlier closure that calls +// it during module evaluation throws a ReferenceError, and calls made after +// the declaration reach the function. A `var` binding is undefined until +// then: the call's arguments run, then it throws "is not a function". +function describe(error: unknown): string { + return error instanceof Error ? `${error.name}: ${error.message}` : String(error); +} + +function early(): number { + return id(1); +} +const before = (): string => wrap("b"); + +try { + console.log(early()); +} catch (error) { + console.log(describe(error)); +} +try { + console.log(before()); +} catch (error) { + console.log(describe(error)); +} + +const id = (x: T): T => x; +let wrap = (x: T): string => `[${String(x)}]`; + +console.log(early(), before(), id("direct"), wrap(2)); + +function later(): string { + return wrap(id(3)); +} +console.log(later()); + +function callMissing(): number { + return missing(log("argument")); +} +function log(text: string): number { + console.log(text); + return 1; +} +try { + console.log(callMissing()); +} catch (error) { + console.log(describe(error)); +} +var missing = (x: T): T => x; +console.log(callMissing(), missing(5)); diff --git a/tests/corpus/7182-generic-binding-direct-calls.ts b/tests/corpus/7182-generic-binding-direct-calls.ts new file mode 100644 index 000000000..c7b5397e1 --- /dev/null +++ b/tests/corpus/7182-generic-binding-direct-calls.ts @@ -0,0 +1,42 @@ +// Generic arrow bindings whose uses all run after the declaration: later +// statements, closures created after it, later declarators, recursion and +// function declarations that only later code calls. These calls go +// straight to the compiled instances. +const pair = (x: T): [T, T] => [x, x]; +const doubled = pair(2), labels = pair("a"); +console.log(doubled.join(","), labels.join(",")); + +function useLater(): string { + return pair(true).join(","); +} +console.log(useLater()); + +export function exported(n: number): number { + return pair(n)[0] + 1; +} +console.log(exported(4)); + +function local(): string { + var twice = (x: T): number => x * 2; + const call = (): number => twice(4); + const depth = (xs: T[], n: number): number => (n <= 0 ? xs.length : depth(xs, n - 1) + 1); + return `${twice(1)} ${call()} ${depth([1, 2], 3)} ${helper()}`; + + function helper(): string { + return pair("h").join(""); + } +} +console.log(local()); + +function loop(): string[] { + const out: string[] = []; + const later: (() => string)[] = []; + for (let i = 0; i < 3; i++) { + const tag = (x: T): string => `#${String(x)}`; + later.push(() => tag("late")); + out.push(tag(i * 10)); + } + for (const f of later) out.push(f()); + return out; +} +console.log(loop().join(" ")); diff --git a/tests/corpus/7183-local-class-heritage-effects.ts b/tests/corpus/7183-local-class-heritage-effects.ts new file mode 100644 index 000000000..514449fdb --- /dev/null +++ b/tests/corpus/7183-local-class-heritage-effects.ts @@ -0,0 +1,54 @@ +// A class defined inside a function evaluates its `extends` expression +// every time the definition runs, even when the base it names is fixed: +// calls in the heritage run in order, and a heritage call that throws +// stops the definition. +class Base { + tag(): string { + return "base"; + } +} +const log: string[] = []; +function select(note: string): typeof Base { + log.push(`select ${note}`); + return Base; +} + +function define(round: number): string { + class Local extends select(`declaration ${round}`) {} + return new Local().tag(); +} +for (let round = 0; round < 2; round++) log.push(define(round)); + +function expressionForm(): string { + const Made = class extends select("expression") {}; + return new Made().tag(); +} +log.push(expressionForm()); + +function nested(): string { + class Outer extends select("outer") {} + class Inner extends Outer {} + return new Inner().tag(); +} +log.push(nested()); + +function refuse(): typeof Base { + throw new Error("heritage failed"); +} +function failing(): void { + try { + class Never extends refuse() {} + log.push(new Never().tag()); + } catch (error) { + log.push((error as Error).message); + } +} +failing(); + +const arrow = (n: number): string => { + class InArrow extends select(`arrow ${n}`) {} + return new InArrow().tag(); +}; +log.push(arrow(1)); + +console.log(log.join("\n")); diff --git a/tests/corpus/7184-reduce-runtime-accumulator.ts b/tests/corpus/7184-reduce-runtime-accumulator.ts new file mode 100644 index 000000000..bd2c8e4d9 --- /dev/null +++ b/tests/corpus/7184-reduce-runtime-accumulator.ts @@ -0,0 +1,24 @@ +// Array reduce keeps the values its callback and initial value produce at +// run time: an initial value read from a missing element is undefined, a +// callback can produce another primitive through `??`, and a parenthesized +// callback widens like a bare one. +const noStrings: string[] = []; +const noNumbers: number[] = []; + +const fromMissingInit = ([] as number[]).reduce((_acc, _value) => "ok", noStrings[0]); +console.log(typeof fromMissingInit, fromMissingInit); + +const nonEmpty = [1, 2].reduce((acc, value) => acc + value, noNumbers[0]); +console.log(typeof nonEmpty, nonEmpty); + +const fallback = [1, 2].reduce((_acc, _value) => noNumbers[0] ?? "fallback"); +console.log(typeof fallback, fallback); + +const parenthesized = [1, 2].reduce((acc, x) => (x === 1 ? noStrings[0] : acc + "!"), ""); +console.log(parenthesized); + +const wrapped = [1, 2].reduce(((acc, x) => (x === 1 ? noStrings[0] : acc + "!")), ""); +console.log(wrapped); + +const right = ["a", "b"].reduceRight((acc, s) => acc + s, noStrings[0]); +console.log(right); diff --git a/tests/corpus/7185-array-callback-arguments-length.ts b/tests/corpus/7185-array-callback-arguments-length.ts new file mode 100644 index 000000000..ae5a8d847 --- /dev/null +++ b/tests/corpus/7185-array-callback-arguments-length.ts @@ -0,0 +1,42 @@ +// `arguments.length` in a function-expression callback counts every +// argument the array method passes: value, index and array, plus the +// accumulator for reduce. One stored in a fixed-arity function type counts +// that type's parameters, which every call passes. +const seen: number[] = []; +[10, 20].forEach(function (value) { + seen.push(arguments.length, value); +}); +console.log(seen.join(",")); + +console.log( + [1, 2] + .map(function (value) { + return `${value}:${arguments.length}`; + }) + .join(" "), +); + +console.log([5].filter(function () { + return arguments.length === 3; +}).length); + +console.log([1].reduce(function (acc, value) { + return acc + value + arguments.length; +}, 0)); + +console.log(["x", "y"].reduceRight(function (acc: string, value: string) { + return `${acc}${value}${arguments.length}`; +}, "")); + +console.log([3, 4].some(function (value) { + return arguments.length === 3 && value === 4; +})); + +const sum: (a: number, b: number) => number = function (a) { + return a + arguments.length; +}; +console.log(sum(1, 2)); + +console.log([3, 1, 2].sort(function (a, b) { + return arguments.length === 2 ? a - b : 0; +}).join(",")); diff --git a/tests/corpus/7240-objectmode-streams.ts b/tests/corpus/7240-objectmode-streams.ts new file mode 100644 index 000000000..47f799eee --- /dev/null +++ b/tests/corpus/7240-objectmode-streams.ts @@ -0,0 +1,161 @@ +// Typed object-mode streams: records through Readable.from, Transform +// and Writable in pipeline(), typed 'data' listeners, a Transform with +// readableObjectMode parsing bytes into records, an object-mode Duplex, +// a PassThrough's object-counted high-water mark, and Readable.from over +// a Map, a Set of records and an array mixing strings and Buffers, and +// byte-mode chunk parameters typed Buffer | string. +import { Duplex, PassThrough, Readable, Transform, Writable } from "node:stream"; +import { pipeline } from "node:stream/promises"; + +interface Row { + id: number; + name: string; +} + +interface Total { + count: number; + ids: number[]; +} + +async function records(): Promise { + const source = Readable.from([ + { id: 1, name: "ada" }, + { id: 2, name: "bo" }, + { id: 3, name: "cy" }, + ]); + const shout = new Transform({ + objectMode: true, + transform(row: Row, _enc: string, cb: (err: Error | null, out?: Row) => void) { + if (row.id === 2) { + cb(null); + return; + } + cb(null, { id: row.id * 10, name: row.name.toUpperCase() }); + }, + }); + const seen: Row[] = []; + await pipeline( + source, + shout, + new Writable({ + objectMode: true, + write(row: Row, enc: string | null | undefined, cb: () => void) { + seen.push(row); + console.log("write", row.id, enc); + cb(); + }, + }), + ); + console.log(seen.map((r) => `${r.id}:${r.name}`).join(" ")); +} + +function counters(): void { + const counter = new Readable({ objectMode: true, read() {} }); + console.log("hwm", counter.readableHighWaterMark, counter.readableObjectMode); + counter.on("data", (n: number) => console.log("data", n + 1)); + counter.on("end", () => console.log("counter end")); + counter.push(1); + counter.push(0); + counter.push(41); + counter.push(null); +} + +function sided(): void { + // bytes in, records out + const parse = new Transform({ + readableObjectMode: true, + transform(chunk: Buffer, _enc: string, cb: (err: Error | null, out?: Total) => void) { + const ids = chunk.toString().split(",").map((s) => Number(s)); + cb(null, { count: ids.length, ids }); + }, + }); + console.log( + "sided", + parse.readableObjectMode, + parse.writableObjectMode, + parse.readableHighWaterMark, + parse.writableHighWaterMark, + ); + parse.on("data", (t: Total) => console.log("total", t.count, t.ids.join("+"))); + parse.write("1,2,3"); + parse.end("4"); +} + +function duplex(): void { + const echo = new Duplex({ + objectMode: true, + read() {}, + write(chunk: Row, _enc: string, cb: () => void) { + this.push({ id: chunk.id + 1, name: chunk.name }); + cb(); + }, + final(cb: () => void) { + this.push(null); + cb(); + }, + }); + echo.on("data", (r: Row) => console.log("echo", r.id, r.name)); + echo.write({ id: 1, name: "x" }); + echo.end({ id: 5, name: "y" }); +} + +function passthrough(): void { + const pt = new PassThrough({ objectMode: true, highWaterMark: 2 }); + const ok1 = pt.write({ id: 1, name: "a" }); + const ok2 = pt.write({ id: 2, name: "b" }); + console.log("backpressure", ok1, ok2, pt.writableLength, pt.readableLength); + pt.on("data", (r: Row) => console.log("pt", r.name)); + pt.end(); +} + +async function collections(): Promise { + const prices = new Map([ + ["tea", 3], + ["cake", 5], + ]); + for await (const entry of Readable.from(prices)) console.log("entry", JSON.stringify(entry)); + const mixed: (string | Buffer)[] = ["text", Buffer.from("bytes")]; + for await (const chunk of Readable.from(mixed)) console.log("mixed", typeof chunk, String(chunk)); + const tags = new Set([{ tag: "a" }, { tag: "b" }]); + for await (const t of Readable.from(tags)) console.log("set", JSON.stringify(t)); +} + +// Byte-mode sides pass Buffers: a chunk parameter typed as a supertype +// of Buffer takes them, inline and as an underscore method, and +// super(undefined) leaves the stream in byte mode. +class Collector extends Writable { + constructor() { + super(undefined); + } + _write(chunk: Buffer | string, _encoding: BufferEncoding, cb: (err?: Error | null) => void): void { + console.log("collector", Buffer.isBuffer(chunk), typeof chunk === "string" ? chunk : chunk.toString()); + cb(); + } +} + +async function byteChunks(): Promise { + const inline = new Writable({ + write(chunk: Buffer | string, _encoding: BufferEncoding, cb: (err?: Error | null) => void): void { + console.log("inline", Buffer.isBuffer(chunk), typeof chunk === "string" ? chunk : chunk.toString()); + cb(); + }, + }); + inline.write("one"); + inline.end(Buffer.from("two")); + await new Promise((resolve) => inline.on("finish", () => resolve())); + const collector = new Collector(); + collector.end("three"); + await new Promise((resolve) => collector.on("finish", () => resolve())); +} + +async function main(): Promise { + await records(); + await collections(); + counters(); + sided(); + duplex(); + passthrough(); + await new Promise((resolve) => setTimeout(resolve, 5)); + await byteChunks(); +} +main(); diff --git a/tests/corpus/7241-objectmode-streams.mjs b/tests/corpus/7241-objectmode-streams.mjs new file mode 100644 index 000000000..6101930df --- /dev/null +++ b/tests/corpus/7241-objectmode-streams.mjs @@ -0,0 +1,155 @@ +// Object-mode streams in JavaScript: any value as a chunk through +// Readable, Writable, Duplex, Transform and PassThrough, pipe() and +// pipeline() between them, unshift(), the per-side modes and +// their high-water marks, and the encoding argument write() and end() +// hand to _write and _transform. +import { Duplex, PassThrough, Readable, Transform, Writable } from "node:stream"; +import { pipeline } from "node:stream/promises"; + +const show = (v) => (typeof v === "object" ? JSON.stringify(v) : `${typeof v}:${String(v)}`); + +async function values() { + const seen = []; + await pipeline( + Readable.from([1, "two", { three: 3 }, [4], true, 0, ""]), + new Transform({ + objectMode: true, + transform(chunk, enc, cb) { + cb(null, { wrapped: chunk }); + }, + }), + new Writable({ + objectMode: true, + write(chunk, enc, cb) { + seen.push(show(chunk.wrapped)); + cb(); + }, + }), + ); + console.log("values:", seen.join(" ")); +} + +function lines() { + let rest = ""; + const split = new Transform({ + readableObjectMode: true, + transform(chunk, enc, cb) { + const parts = (rest + chunk.toString()).split("\n"); + rest = parts.pop(); + for (const p of parts) this.push({ line: p, length: p.length }); + cb(); + }, + flush(cb) { + if (rest) this.push({ line: rest, length: rest.length }); + cb(); + }, + }); + console.log("split modes:", split.readableObjectMode, split.writableObjectMode); + split.on("data", (row) => console.log("line:", row.line, row.length)); + split.on("end", () => console.log("split end")); + split.write("alpha\nbe"); + split.write("ta\ngamma"); + split.end(); +} + +function encodings() { + const w = new Writable({ + objectMode: true, + write(chunk, enc, cb) { + console.log("write enc:", show(chunk), enc); + cb(); + }, + }); + w.write(1, () => console.log("write cb")); + w.write(2, null); + w.write(3, "utf8"); + w.write("four", "latin1"); + w.write(5, "anything"); + w.end(6, () => console.log("end cb")); + const t = new Transform({ + objectMode: true, + transform(chunk, enc, cb) { + console.log("transform enc:", show(chunk), enc); + cb(); + }, + }); + t.write(7); + t.end(8, "hex"); + const bytes = new Writable({ + write(chunk, enc, cb) { + console.log("byte write:", chunk.toString("hex"), enc); + cb(); + }, + }); + bytes.write("hi", "latin1"); + bytes.write("6869", "hex"); + try { + bytes.write("x", "bogus"); + } catch (e) { + console.log("byte encoding:", e.code); + } + bytes.end(); +} + +function unshiftFront() { + const r = new Readable({ objectMode: true, read() {} }); + r.push({ id: 1 }); + r.push({ id: 2 }); + r.push(null); + console.log("length:", r.readableLength, "hwm:", r.readableHighWaterMark); + r.unshift({ id: 0 }); + r.on("data", (v) => console.log("after unshift:", show(v))); + r.on("end", () => console.log("read end")); + // strings stay strings on an object-mode side, whatever the encoding + const strings = new Readable({ objectMode: true, read() {} }); + strings.push("b"); + strings.unshift("a"); + strings.push("6869", "hex"); + strings.push(null); + strings.on("data", (v) => console.log("string entry:", show(v))); +} + +function piped() { + const src = new PassThrough({ objectMode: true }); + const echo = new Duplex({ + objectMode: true, + read() {}, + write(chunk, enc, cb) { + this.push({ echoed: chunk }); + cb(); + }, + final(cb) { + this.push(null); + cb(); + }, + }); + src.pipe(echo).on("data", (v) => console.log("piped:", show(v))); + src.write({ n: 1 }); + src.write([2, 3]); + src.end("last"); +} + +function byteModeValues() { + const r = new Readable({ read() {} }); + r.on("error", (e) => console.log("byte push:", e.code)); + r.push(undefined); + r.push(42); +} + +async function forAwait() { + const pt = new PassThrough({ objectMode: true, highWaterMark: 2 }); + const ok = [pt.write(1), pt.write(2), pt.write(3)]; + console.log("backpressure:", ok.join(" "), pt.writableLength); + pt.end({ done: true }); + const got = []; + for await (const v of pt) got.push(show(v)); + console.log("for await:", got.join(" ")); +} + +await values(); +lines(); +encodings(); +unshiftFront(); +piped(); +byteModeValues(); +await forAwait(); diff --git a/tests/corpus/7242-objectmode-dynamic.cjs b/tests/corpus/7242-objectmode-dynamic.cjs new file mode 100644 index 000000000..fad06ad98 --- /dev/null +++ b/tests/corpus/7242-objectmode-dynamic.cjs @@ -0,0 +1,93 @@ +// Object-mode streams through dynamic values: options objects held in +// variables, constructor functions with util.inherits (Transform.call +// and Writable.call with objectMode), streams passed around as plain +// values, and Readable.from over values of mixed types. +const stream = require("stream"); +const util = require("util"); + +const show = (v) => (v !== null && typeof v === "object" ? JSON.stringify(v) : `${typeof v}:${String(v)}`); + +function Tagger(tag) { + stream.Transform.call(this, { objectMode: true }); + this.tag = tag; +} +util.inherits(Tagger, stream.Transform); +Tagger.prototype._transform = function (chunk, enc, cb) { + console.log("tagger enc:", enc); + if (chunk === 3) return cb(); + cb(null, { tag: this.tag, value: chunk }); +}; +Tagger.prototype._flush = function (cb) { + this.push({ tag: this.tag, value: "flushed" }); + cb(); +}; + +function Collector() { + stream.Writable.call(this, { objectMode: true, highWaterMark: 2 }); + this.items = []; +} +util.inherits(Collector, stream.Writable); +Collector.prototype._write = function (chunk, enc, cb) { + this.items.push(show(chunk)); + cb(); +}; + +function viaConstructors(next) { + const t = new Tagger("x"); + const c = new Collector(); + console.log("modes:", t.readableObjectMode, t.writableObjectMode, c.writableObjectMode, c.writableHighWaterMark); + t.pipe(c); + c.on("finish", () => { + console.log("collected:", c.items.join(" ")); + next(); + }); + t.write(1); + t.write("two", () => console.log("write cb")); + t.write(3); + t.end({ four: 4 }); +} + +function viaOptionObjects(next) { + const readableOpts = { objectMode: true, read() {} }; + const r = new stream.Readable(readableOpts); + const transformOpts = { + objectMode: true, + transform(chunk, enc, cb) { + cb(null, Array.isArray(chunk) ? chunk.length : chunk); + }, + }; + const t = new stream.Transform(transformOpts); + const seen = []; + const writableOpts = { + objectMode: true, + write(chunk, enc, cb) { + seen.push(show(chunk) + "/" + enc); + cb(); + }, + }; + const w = new stream.Writable(writableOpts); + stream.pipeline(r, t, w, (err) => { + console.log("option objects:", err === undefined ? "ok" : err, seen.join(" ")); + next(); + }); + r.push([1, 2, 3]); + r.push(false); + r.push({ k: "v" }); + r.push(null); +} + +async function viaFrom() { + const values = [0, "s", undefined, [1], { a: { b: 2 } }, 1.5]; + const out = []; + for await (const v of stream.Readable.from(values)) out.push(show(v)); + console.log("from:", out.join(" ")); + const pt = new stream.PassThrough({ objectMode: true }); + const passAlong = (s, v) => s.write(v); + passAlong(pt, { through: true }); + passAlong(pt, 7); + pt.end(); + pt.on("data", (v) => console.log("passed:", show(v))); + await new Promise((resolve) => pt.on("end", resolve)); +} + +viaConstructors(() => viaOptionObjects(() => viaFrom())); diff --git a/tests/corpus/7243-for-await-close-order.mjs b/tests/corpus/7243-for-await-close-order.mjs new file mode 100644 index 000000000..b3cc700be --- /dev/null +++ b/tests/corpus/7243-for-await-close-order.mjs @@ -0,0 +1,58 @@ +// for await over a stream completes through eos: a readable-only stream +// that will emit 'close' (autoDestroy and emitClose) ends the loop after +// 'close', a duplex after 'end', interleaved with other loops' ticks. +import { PassThrough, Readable } from "node:stream"; + +async function interleaved(objectMode) { + const log = []; + let on = true; + (async () => { + for (let i = 0; on && i < 30; i++) { + log.push("t" + i); + await null; + } + })(); + const nums = objectMode ? new PassThrough({ objectMode: true }) : new PassThrough({ highWaterMark: 4 }); + for (let k = 0; k < 6; k++) nums.write(objectMode ? k : "n" + k); + nums.end(); + nums.on("end", () => log.push("N-END")); + nums.on("close", () => log.push("N-CLOSE")); + nums.on("finish", () => log.push("N-FINISH")); + const fr = Readable.from(["a", "b", "c"]); + fr.on("end", () => log.push("F-END")); + fr.on("close", () => log.push("F-CLOSE")); + const a = (async () => { + for await (const n of nums) log.push("n" + String(n).length); + log.push("n-done"); + })(); + const b = (async () => { + for await (const v of fr) log.push("f" + v); + log.push("f-done"); + })(); + await Promise.all([a, b]); + on = false; + console.log(objectMode ? "object:" : "bytes:", log.join(" ")); +} + +async function closeBeforeDone() { + const log = []; + const r = new Readable({ objectMode: true, read() {} }); + r.on("end", () => log.push("end")); + r.on("close", () => log.push("close")); + r.push({ v: 1 }); + r.push(null); + for await (const v of r) log.push("v" + v.v); + log.push("done " + r.destroyed); + const keep = new Readable({ objectMode: true, autoDestroy: false, read() {} }); + keep.on("end", () => log.push("keep end")); + keep.on("close", () => log.push("keep close")); + keep.push(1); + keep.push(null); + for await (const v of keep) log.push("k" + v); + log.push("keep done " + keep.destroyed); + console.log("close order:", log.join(" ")); +} + +await interleaved(true); +await interleaved(false); +await closeBeforeDone(); diff --git a/tests/corpus/7244-objectmode-subclasses.ts b/tests/corpus/7244-objectmode-subclasses.ts new file mode 100644 index 000000000..5fcb05a24 --- /dev/null +++ b/tests/corpus/7244-objectmode-subclasses.ts @@ -0,0 +1,79 @@ +// Typed object-mode stream subclasses: Transform, Writable and Readable +// classes that pass objectMode to super(), _transform/_write/_read with +// record chunks, encoding parameters typed string | null | undefined, and +// push() of records and other values. +import { Readable, Transform, Writable } from "node:stream"; +import { pipeline } from "node:stream/promises"; + +interface Order { + id: number; + items: string[]; +} + +interface Summary { + id: number; + count: number; +} + +class Orders extends Readable { + private next = 1; + constructor() { + super({ objectMode: true }); + } + _read(): void { + if (this.next > 3) { + this.push(null); + return; + } + const id = this.next++; + this.push({ id, items: Array.from({ length: id }, (_, i) => `item${i}`) }); + } +} + +class Summarize extends Transform { + constructor() { + super({ objectMode: true }); + } + _transform( + order: Order, + encoding: string | null | undefined, + cb: (err: Error | null, data?: Summary) => void, + ): void { + console.log("summarize", order.id, encoding); + cb(null, { id: order.id, count: order.items.length }); + } +} + +class Report extends Writable { + lines: string[] = []; + constructor() { + super({ objectMode: true, highWaterMark: 1 }); + } + _write(s: Summary, _encoding: string, cb: (err?: Error | null) => void): void { + this.lines.push(`#${s.id}=${s.count}`); + cb(); + } +} + +async function main(): Promise { + const report = new Report(); + console.log("report", report.writableObjectMode, report.writableHighWaterMark); + await pipeline(new Orders(), new Summarize(), report); + console.log("lines", report.lines.join(" ")); + + const direct = new Summarize(); + direct.on("data", (s: Summary) => console.log("direct", s.id, s.count)); + direct.write({ id: 9, items: ["a"] }, "utf8"); + direct.write({ id: 10, items: [] }, () => console.log("written")); + direct.end(); + + const values = new Readable({ objectMode: true, read() {} }); + values.push(1.5); + values.push("text"); + values.push([1, 2]); + values.push(null); + const seen: string[] = []; + for await (const v of values) seen.push(JSON.stringify(v)); + console.log("values", seen.join(" ")); +} +main(); diff --git a/tests/corpus/7245-writable-callback-order.mjs b/tests/corpus/7245-writable-callback-order.mjs new file mode 100644 index 000000000..454e67fe0 --- /dev/null +++ b/tests/corpus/7245-writable-callback-order.mjs @@ -0,0 +1,71 @@ +// Writable callback and 'finish' timing: buffered writes completing +// inside clearBuffer keep their callback order, a deferred afterWrite +// with a user callback holds 'finish' for its own tick, a _final +// callback schedules 'finish' at once, and cork()/uncork() with +// callbacks. +import { PassThrough, Transform, Writable } from "node:stream"; + +function ticks(log, count) { + let n = 0; + const tick = () => { + log.push("t" + n); + if (++n < count) process.nextTick(tick); + }; + process.nextTick(tick); +} + +async function bufferedCallbacks() { + const log = []; + const nums = new PassThrough({ highWaterMark: 4 }); + for (let k = 0; k < 6; k++) log.push("w" + nums.write("n" + k, () => log.push("cb" + k))); + nums.end(() => log.push("end-cb")); + nums.on("finish", () => log.push("finish")); + nums.on("end", () => log.push("end")); + for await (const chunk of nums) log.push("r" + chunk.length); + log.push("done"); + console.log("buffered:", log.join(" ")); +} + +function finishTiming() { + return new Promise((resolve) => { + const log = []; + ticks(log, 10); + const plain = new Writable({ write(c, e, cb) { log.push("pw" + c); cb(); } }); + plain.write("1", () => log.push("pcb1")); + plain.write("2"); + plain.end("3", () => log.push("pend")); + plain.on("finish", () => log.push("pfinish")); + const withFinal = new Writable({ + write(c, e, cb) { log.push("fw" + c); cb(); }, + final(cb) { log.push("final"); cb(); }, + }); + withFinal.write("1", () => log.push("fcb1")); + withFinal.end(() => log.push("fend")); + withFinal.on("finish", () => log.push("ffinish")); + const corked = new Writable({ write(c, e, cb) { log.push("cw" + c); cb(); } }); + corked.cork(); + corked.write("a", () => log.push("ccb-a")); + corked.write("b", () => log.push("ccb-b")); + process.nextTick(() => { + corked.uncork(); + corked.end(() => log.push("cend")); + }); + corked.on("finish", () => log.push("cfinish")); + const t = new Transform({ + transform(c, e, cb) { cb(null, c); }, + flush(cb) { log.push("flush"); cb(); }, + }); + t.resume(); + t.write("q", () => log.push("tcb")); + t.end(() => log.push("tend")); + t.on("finish", () => log.push("tfinish")); + t.on("end", () => log.push("tread-end")); + setTimeout(() => { + console.log("timing:", log.join(" ")); + resolve(undefined); + }, 10); + }); +} + +await bufferedCallbacks(); +await finishTiming(); diff --git a/tests/corpus/7246-stream-construct.ts b/tests/corpus/7246-stream-construct.ts new file mode 100644 index 000000000..7cfb82e49 --- /dev/null +++ b/tests/corpus/7246-stream-construct.ts @@ -0,0 +1,156 @@ +// Deferred construction in typed code: the construct option and the +// _construct method on Readable, Writable, Duplex and Transform. Writes +// and reads wait for the callback, an error from it destroys the stream, +// a destroy while constructing reports both errors as an AggregateError, +// a throw inside construct is its error, and a second callback is +// ERR_MULTIPLE_CALLBACK. +import { EventEmitter } from "node:events"; +import { Duplex, Readable, Transform, Writable } from "node:stream"; + +const log: string[] = []; + +function ticks(count: number): void { + let i = 0; + const step = (): void => { + log.push("t" + i); + if (++i < count) process.nextTick(step); + }; + process.nextTick(step); +} + +class Store extends Writable { + private ready = false; + _construct(callback: (error?: Error | null) => void): void { + log.push("store construct"); + setTimeout(() => { + this.ready = true; + log.push("store ready"); + callback(); + }, 2); + } + _write(chunk: Buffer, _enc: string, cb: (error?: Error | null) => void): void { + log.push(`store write ${chunk.toString()} ready=${this.ready}`); + cb(); + } + _final(cb: (error?: Error | null) => void): void { + log.push("store final"); + cb(); + } +} + +class Pair extends Duplex { + constructor() { + super({ readableObjectMode: true }); + } + _construct(callback: (error?: Error | null) => void): void { + log.push("pair construct"); + process.nextTick(callback); + } + _read(): void {} + _write(chunk: Buffer, _enc: string, cb: (error?: Error | null) => void): void { + this.push({ got: chunk.toString() }); + cb(); + } + _final(cb: (error?: Error | null) => void): void { + this.push(null); + cb(); + } +} + +function closed(stream: EventEmitter): Promise { + return new Promise((resolve) => stream.on("close", () => resolve())); +} + +async function main(): Promise { + ticks(4); + const store = new Store(); + log.push("write " + store.write("a")); + store.end("b"); + store.on("finish", () => log.push("store finish")); + await closed(store); + + const source = new Readable({ + construct(cb: (error?: Error | null) => void) { + log.push("source construct"); + process.nextTick(cb); + }, + read() { + log.push("source read"); + this.push("x"); + this.push(null); + }, + }); + source.on("data", (c: Buffer) => log.push("source data " + c.toString())); + await closed(source); + + const pair = new Pair(); + pair.on("data", (v: { got: string }) => log.push("pair data " + v.got)); + pair.write("p"); + pair.end(); + await closed(pair); + + const upper = new Transform({ + construct(cb: (error?: Error | null) => void) { + log.push("upper construct"); + cb(); + }, + transform(c: Buffer, _e: string, cb: (error: Error | null, data?: Buffer) => void) { + cb(null, Buffer.from(c.toString().toUpperCase())); + }, + }); + upper.on("data", (c: Buffer) => log.push("upper " + c.toString())); + upper.end("shout"); + await closed(upper); + + const failing = new Writable({ + construct(cb: (error?: Error | null) => void) { + cb(new Error("no target")); + }, + write(_c: Buffer, _e: string, cb: (error?: Error | null) => void) { + cb(); + }, + }); + failing.on("error", (e: Error) => log.push("failing " + e.message)); + await closed(failing); + + const raced = new Writable({ + construct(cb: (error?: Error | null) => void) { + setTimeout(() => cb(new Error("late")), 2); + }, + write(_c: Buffer, _e: string, cb: (error?: Error | null) => void) { + cb(); + }, + destroy(err: Error | null, cb: (error?: Error | null) => void) { + log.push("raced destroy " + (err ? err.message : "none")); + cb(err); + }, + }); + raced.on("error", (e: Error) => log.push(`raced ${e.name} ${e.message}`)); + raced.destroy(new Error("early")); + await closed(raced); + + const thrown = new Writable({ + construct() { + throw new Error("thrown in construct"); + }, + write(_c: Buffer, _e: string, cb: (error?: Error | null) => void) { + cb(); + }, + }); + thrown.on("error", (e: Error) => log.push("thrown " + e.message)); + await closed(thrown); + + const twice = new Writable({ + construct(cb: (error?: Error | null) => void) { + cb(); + cb(); + }, + write(_c: Buffer, _e: string, cb: (error?: Error | null) => void) { + cb(); + }, + }); + twice.on("error", (e: Error) => log.push("twice " + (e as NodeJS.ErrnoException).code)); + await closed(twice); + console.log(log.join("\n")); +} +main(); diff --git a/tests/corpus/7247-stream-construct.mjs b/tests/corpus/7247-stream-construct.mjs new file mode 100644 index 000000000..355116fa7 --- /dev/null +++ b/tests/corpus/7247-stream-construct.mjs @@ -0,0 +1,101 @@ +// Deferred construction in JavaScript: construct in an options literal, +// in an options value read at run time, and _construct on a constructor +// function's prototype, with the write, read, error, destroy-while- +// constructing, throwing and double-callback paths. +import * as stream from "node:stream"; +import { Writable, Readable } from "node:stream"; +import * as util from "node:util"; +const log = []; +const tick = (n) => { let i = 0; const f = () => { log.push("t" + i); if (++i < n) process.nextTick(f); }; process.nextTick(f); }; +tick(4); +const wopts = { + construct(cb) { log.push("construct"); setTimeout(() => { log.push("constructed"); cb(); }, 2); }, + write(c, e, cb) { log.push("write " + c + "/" + e); cb(); }, + final(cb) { log.push("final"); cb(); }, +}; +const w = new Writable(dyn(wopts)); +log.push("write ret " + w.write("a")); +w.end("b"); +w.on("finish", () => log.push("finish")); +w.on("close", () => { log.push("close"); next(); }); +function next() { + const ropts = { construct(cb) { log.push("r construct"); process.nextTick(cb); }, read() { log.push("read"); r.push("x"); r.push(null); } }; + const r = new Readable(dyn(ropts)); + r.on("data", (c) => log.push("data " + c)); + r.on("end", () => { log.push("r end"); errs(); }); +} +function errs() { + const eo = { construct(cb) { cb(new Error("boom")); }, write(c, e2, cb) { cb(); } }; + const e = new Writable(dyn(eo)); + e.on("error", (err) => log.push("error " + err.message)); + e.on("close", () => { log.push("e close"); destroyDuring(); }); +} +function destroyDuring() { + const dopts = { construct(cb) { setTimeout(() => cb(new Error("late")), 2); }, write(c, e, cb) { cb(); }, destroy(err, cb) { log.push("destroy " + (err && err.message)); cb(err); } }; + const d = new Writable(dyn(dopts)); + d.on("error", (err) => log.push("d error " + err.name + " " + err.message + " " + (err.errors ? err.errors.map((x) => x.message).join("+") : ""))); + d.on("close", () => { log.push("d close"); throwing(); }); + d.destroy(new Error("early")); +} +function throwing() { + const to = { construct(cb) { throw new Error("thrown"); }, write(c, e, cb) { cb(); } }; + const t = new Writable(dyn(to)); + t.on("error", (err) => log.push("t error " + err.message)); + t.on("close", () => { log.push("t close"); twice(); }); +} +function twice() { + const o = { construct(cb) { cb(); cb(); }, write(c, e, cb) { cb(); } }; + const t = new Writable(dyn(o)); + t.on("error", (err) => log.push("twice error " + err.code)); + t.on("close", () => { log.push("twice close"); viaLiteral(); }); + setTimeout(() => t.destroy(), 5); +} +function dyn(o) { + return o; +} +function viaLiteral() { + const lit = new Writable({ + construct(cb) { + log.push("literal construct " + (this === lit)); + setImmediate(cb); + }, + write(chunk, enc, cb) { + log.push(`literal write ${chunk}/${enc}`); + cb(); + }, + }); + lit.end("z", () => { + log.push("literal end"); + viaConstructor(); + }); +} +function viaConstructor() { + function Bad() { + stream.Readable.call(this); + } + util.inherits(Bad, stream.Readable); + Bad.prototype._construct = function () { + throw new Error("ctor threw"); + }; + Bad.prototype._read = function () {}; + function Late(opts) { + stream.Writable.call(this, opts); + } + util.inherits(Late, stream.Writable); + Late.prototype._construct = function (cb) { + log.push("late construct " + (this instanceof Late)); + setTimeout(cb, 1); + }; + Late.prototype._write = function (chunk, enc, cb) { + log.push("late write " + chunk); + cb(); + }; + const late = new Late(); + late.write("q"); + late.end(() => { + log.push("late end"); + const bad = new Bad(); + bad.on("error", (e) => log.push("bad " + e.message)); + bad.on("close", () => console.log(log.join("\n"))); + }); +} diff --git a/tests/corpus/7248-stream-writev.ts b/tests/corpus/7248-stream-writev.ts new file mode 100644 index 000000000..2df298d6d --- /dev/null +++ b/tests/corpus/7248-stream-writev.ts @@ -0,0 +1,124 @@ +// Batched writes in typed code: the writev option and the _writev method +// on Writable and Duplex. Writes buffered behind a write in flight or a +// cork reach writev as one [{ chunk, encoding }] batch whose callback +// runs the writes' callbacks in order; a stream with only writev sends +// each lone write as a batch of one; a later `stream._writev = fn` +// takes over; an object-mode side batches its values. +import { EventEmitter } from "node:events"; +import { Duplex, Writable } from "node:stream"; + +interface Entry { + chunk: Buffer; + encoding: string; +} + +interface ValueEntry { + chunk: unknown; + encoding: string | undefined; +} + +const log: string[] = []; + +function finished(stream: EventEmitter): Promise { + return new Promise((resolve) => stream.on("finish", () => resolve())); +} + +class Batcher extends Writable { + _write(chunk: Buffer, _enc: string, cb: (error?: Error | null) => void): void { + log.push("batcher write " + chunk.toString()); + setTimeout(cb, 1); + } + _writev(chunks: Entry[], cb: (error?: Error | null) => void): void { + log.push(`batcher writev ${chunks.map((c) => c.chunk.toString() + "/" + c.encoding).join(",")}`); + setTimeout(cb, 1); + } +} + +class Echo extends Duplex { + _read(): void {} + _write(chunk: Buffer, _enc: string, cb: (error?: Error | null) => void): void { + this.push(chunk); + cb(); + } + _writev(chunks: Entry[], cb: (error?: Error | null) => void): void { + this.push(Buffer.concat(chunks.map((c) => c.chunk))); + cb(); + } + _final(cb: (error?: Error | null) => void): void { + this.push(null); + cb(); + } +} + +async function main(): Promise { + const batcher = new Batcher(); + batcher.write("a", () => log.push("a done")); + batcher.write("b", () => log.push("b done")); + batcher.write("c"); + batcher.write(Buffer.from("d"), () => log.push("d done")); + batcher.end(() => log.push("batcher end")); + await finished(batcher); + + const corked = new Writable({ + writev(chunks: Entry[], cb: (error?: Error | null) => void) { + log.push(`corked ${chunks.length}: ${chunks.map((c) => c.chunk.toString("hex")).join(" ")}`); + cb(); + }, + }); + corked.cork(); + corked.write("x"); + corked.write("ff", "hex"); + corked.write("y"); + corked.uncork(); + corked.write("z", () => log.push("z done")); + corked.end(); + await finished(corked); + + const late = new Writable({ + write(c: Buffer, _e: string, cb: () => void) { + log.push("late write " + c.toString()); + cb(); + }, + }); + late._writev = (chunks: Entry[], cb: (error?: Error | null) => void) => { + log.push("late writev " + chunks.length); + cb(); + }; + late.cork(); + late.write("1"); + late.write("2"); + late.uncork(); + late.end(); + await finished(late); + + const echo = new Echo(); + const echoed: string[] = []; + echo.on("data", (c: Buffer) => echoed.push(c.toString())); + echo.cork(); + echo.write("e1"); + echo.write("e2"); + process.nextTick(() => { + echo.uncork(); + echo.end("e3"); + }); + await new Promise((resolve) => echo.on("end", resolve)); + log.push("echoed " + echoed.join(",")); + + const values = new Writable({ + objectMode: true, + writev(chunks: ValueEntry[], cb: (error?: Error | null) => void) { + log.push( + "values " + chunks.map((c) => `${JSON.stringify(c.chunk)}/${String(c.encoding)}`).join(","), + ); + cb(); + }, + }); + values.cork(); + values.write({ n: 1 }); + values.write([2], "utf8"); + values.uncork(); + values.end(); + await finished(values); + console.log(log.join("\n")); +} +main(); diff --git a/tests/corpus/7249-buffer-index-of-candidates.ts b/tests/corpus/7249-buffer-index-of-candidates.ts new file mode 100644 index 000000000..ae6c2ae23 --- /dev/null +++ b/tests/corpus/7249-buffer-index-of-candidates.ts @@ -0,0 +1,27 @@ +// Buffer indexOf, lastIndexOf and includes with needles whose first byte +// recurs: a candidate whose later bytes differ is skipped, matches at the +// first and last positions are found, byteOffset clamps and counts from the +// end, and the search reads only the buffer's own window of its memory. +const text = Buffer.from("aab aaab aaaab ab\nab"); +console.log(text.indexOf("ab"), text.indexOf("aab"), text.indexOf("aaab"), text.indexOf("aaaab"), text.indexOf("aaaaab")); +console.log(text.lastIndexOf("ab"), text.lastIndexOf("aab"), text.lastIndexOf("aaab"), text.lastIndexOf("b\na")); +console.log(text.indexOf("ab", 2), text.indexOf("ab", -3), text.indexOf("ab", 100), text.indexOf("ab", -100)); +console.log(text.lastIndexOf("ab", 5), text.lastIndexOf("ab", -4), text.lastIndexOf("ab", 0), text.lastIndexOf("aa", 1)); +console.log(text.indexOf(10), text.indexOf(97, 3), text.lastIndexOf(98), text.lastIndexOf(97, -2), text.includes("b a")); +console.log(text.indexOf(""), text.indexOf("", 4), text.indexOf("", 100), text.lastIndexOf(""), text.indexOf("x")); +console.log(text.indexOf(Buffer.from("a\nab")), text.indexOf("ab\nab"), text.indexOf("ab\nabc"), text.lastIndexOf("aab", 4)); + +// A window into a larger buffer never sees the bytes outside it. +const whole = Buffer.from("xxneedlexx needle needlexx"); +const window = whole.subarray(3, 22); +console.log(window.toString(), window.indexOf("needle"), window.lastIndexOf("needle"), window.indexOf("xx"), window.includes("xne")); +console.log(window.indexOf("eedle", 1), window.lastIndexOf("eed"), window.indexOf("needlex"), window.lastIndexOf("n", 0)); + +// A long search with many first-byte candidates. +const long = Buffer.alloc(20000, "ab"); +long.write("abc", 19990); +console.log(long.indexOf("abc"), long.lastIndexOf("aba"), long.indexOf("abc", 19991), long.lastIndexOf("abc"), long.indexOf("bb")); +const lines: number[] = []; +const fasta = Buffer.from(">ONE\nACGT\nTTGA\n>TWO\nGGCC\n"); +for (let at = fasta.indexOf(10); at !== -1; at = fasta.indexOf(10, at + 1)) lines.push(at); +console.log(lines.join(","), fasta.indexOf(62, 1), fasta.lastIndexOf(62)); diff --git a/tests/corpus/7249-stream-writev.cjs b/tests/corpus/7249-stream-writev.cjs new file mode 100644 index 000000000..fb6d01960 --- /dev/null +++ b/tests/corpus/7249-stream-writev.cjs @@ -0,0 +1,126 @@ +// Batched writes in JavaScript: the writev option in a literal and in an +// options value, and _writev on a constructor function's prototype. The +// batch entries carry chunk, encoding and callback (Node's nop when the +// write passed none), allBuffers says whether every chunk is a Buffer, +// and a stream with only _writev sends a lone write as { chunk, encoding }. +const stream = require("node:stream"); +const util = require("node:util"); + +const log = []; +const describe = (chunks) => + chunks + .map((c) => { + const chunk = Buffer.isBuffer(c.chunk) ? "B:" + c.chunk.toString() : `${typeof c.chunk}:${c.chunk}`; + const callback = typeof c.callback === "function" ? c.callback.name || "fn" : String(c.callback); + return `${chunk}/${c.encoding}/${callback}`; + }) + .join(",") + + ` all=${chunks.allBuffers} keys=${Object.keys(chunks[0]).join(".")}`; + +function viaLiteral(next) { + const w = new stream.Writable({ + write(chunk, enc, cb) { + log.push("write " + chunk); + setTimeout(cb, 1); + }, + writev(chunks, cb) { + log.push("writev " + describe(chunks)); + setTimeout(cb, 1); + }, + }); + w.write("a", () => log.push("cb a")); + w.write("b", () => log.push("cb b")); + w.write("c"); + w.write(Buffer.from("d"), () => log.push("cb d")); + w.end(() => log.push("end")); + w.on("finish", () => { + log.push("finish"); + next(); + }); +} + +function dyn(value) { + return value; +} + +function viaValue(next) { + const options = { + writev(chunks, cb) { + log.push("value " + describe(chunks)); + cb(); + }, + }; + const v = new stream.Writable(dyn(options)); + v.cork(); + v.write("x"); + v.write("6869", "hex"); + v.uncork(); + v.write("z", () => log.push("z cb")); + v.end(); + v.on("finish", () => { + log.push("value finish"); + next(); + }); +} + +function Sink(opts) { + stream.Writable.call(this, opts); +} +util.inherits(Sink, stream.Writable); +Sink.prototype._writev = function (chunks, cb) { + log.push("sink " + (this instanceof Sink) + " " + describe(chunks)); + cb(); +}; + +function viaConstructor(next) { + const s = new Sink({ decodeStrings: false }); + s.cork(); + s.write("a"); + s.write("6869", "hex"); + s.write(Buffer.from("b")); + s.uncork(); + s.write("lone"); + s.end(() => { + log.push("sink end"); + next(); + }); +} + +// The writev option shadows the prototype's _writev: Node's constructor +// assigns it to the instance (this._writev = options.writev). +function viaOptionOverProto(next) { + function W(opts) { + stream.Writable.call(this, opts); + } + Object.setPrototypeOf(W.prototype, stream.Writable.prototype); + Object.setPrototypeOf(W, stream.Writable); + W.prototype._write = function (chunk, enc, cb) { + log.push("proto _write " + String(chunk)); + cb(); + }; + W.prototype._writev = function (chunks, cb) { + log.push("proto _writev " + chunks.length); + cb(); + }; + // (built without a second `new` of a constructor function) + const w = Object.create(W.prototype); + W.call(w, { + writev(chunks, cb) { + log.push("option writev " + chunks.map((c) => String(c.chunk)).join(",") + " " + (this === w)); + cb(); + }, + }); + log.push("own _writev " + Object.prototype.hasOwnProperty.call(w, "_writev")); + w.cork(); + w.write("a"); + w.write("b"); + w.uncork(); + w.end(() => { + log.push("option end"); + next(); + }); +} + +viaLiteral(() => + viaValue(() => viaConstructor(() => viaOptionOverProto(() => console.log(log.join("\n"))))), +); diff --git a/tests/corpus/7250-stream-decode-strings.ts b/tests/corpus/7250-stream-decode-strings.ts new file mode 100644 index 000000000..57e84aff2 --- /dev/null +++ b/tests/corpus/7250-stream-decode-strings.ts @@ -0,0 +1,89 @@ +// decodeStrings: false and the write-side default encoding in typed code: +// a string write reaches _write and _transform as the string with its +// encoding (its UTF-16 length counts toward writableLength), Buffers keep +// 'buffer', defaultEncoding decides how write(string) encodes (and the +// name _write sees when strings stay strings), and setDefaultEncoding() +// lowercases, validates and chains. +import { PassThrough, Transform, Writable } from "node:stream"; + +const log: string[] = []; + +function describe(chunk: string | Buffer, enc: string): string { + return typeof chunk === "string" ? `string:${chunk}/${enc}` : `B:${chunk.toString("hex")}/${enc}`; +} + +class Keeper extends Writable { + seen: string[] = []; + constructor() { + super({ decodeStrings: false, highWaterMark: 4 }); + } + _write(chunk: string | Buffer, enc: string, cb: (error?: Error | null) => void): void { + this.seen.push(describe(chunk, enc)); + setTimeout(cb, 1); + } +} + +async function main(): Promise { + const keeper = new Keeper(); + log.push("ret " + keeper.write("héllo")); + log.push("length " + keeper.writableLength); + keeper.write("6869", "hex"); + keeper.write(Buffer.from("zz")); + keeper.end("end", "latin1"); + await new Promise((resolve) => keeper.on("finish", resolve)); + log.push("keeper " + keeper.seen.join(" ")); + + const hex = new Writable({ + defaultEncoding: "hex", + write(chunk: Buffer, enc: string, cb: (error?: Error | null) => void) { + log.push(`hex ${chunk.toString()} ${enc}`); + cb(); + }, + }); + hex.write("6869"); + hex.write("41", "utf8"); + hex.setDefaultEncoding("BASE64").write("aGk="); + try { + hex.setDefaultEncoding("nope"); + } catch (e) { + log.push(`setDefaultEncoding ${(e as NodeJS.ErrnoException).code} ${(e as Error).message}`); + } + log.push("chains " + (hex.setDefaultEncoding("utf8") === hex)); + hex.end("ok"); + + const both = new Writable({ + decodeStrings: false, + defaultEncoding: "LATIN1", + write(chunk: string | Buffer, enc: string, cb: (error?: Error | null) => void) { + log.push("both " + describe(chunk, enc)); + cb(); + }, + }); + both.write("x"); + both.setDefaultEncoding("UTF-8"); + both.write("y"); + both.end(); + + const t = new Transform({ + decodeStrings: false, + transform(chunk: string | Buffer, enc: string, cb: (error: Error | null, data?: string | Buffer) => void) { + log.push("transform " + describe(chunk, enc)); + cb(null, chunk); + }, + }); + t.on("data", (c: Buffer) => log.push("transform out " + c.toString("hex"))); + t.write("abc"); + t.end("ff", "hex"); + + const p = new PassThrough({ decodeStrings: false }); + p.on("data", (c: Buffer) => log.push("pass " + c.toString())); + p.end("q"); + + try { + new Writable({ defaultEncoding: "bogus" }); + } catch (e) { + log.push("constructor " + (e as NodeJS.ErrnoException).code); + } + setTimeout(() => console.log(log.join("\n")), 10); +} +main(); diff --git a/tests/corpus/7251-stream-write-encodings.mjs b/tests/corpus/7251-stream-write-encodings.mjs new file mode 100644 index 000000000..5c4242ca8 --- /dev/null +++ b/tests/corpus/7251-stream-write-encodings.mjs @@ -0,0 +1,104 @@ +// Write encodings in JavaScript: decodeStrings: false and defaultEncoding +// in options literals and options values, setDefaultEncoding(), and +// strings written in other encodings to constructor-function streams. +import * as stream from "node:stream"; +import { PassThrough, Transform, Writable } from "node:stream"; +import * as util from "node:util"; + +const log = []; +const describe = (c, e) => `${Buffer.isBuffer(c) ? "B:" + c.toString("hex") : typeof c + ":" + c}/${e}`; +const dyn = (value) => value; + +const keep = new Writable({ decodeStrings: false, highWaterMark: 4, write(c, e, cb) { log.push("keep " + describe(c, e)); cb(); } }); +log.push("ret " + keep.write("héllo") + " length " + keep.writableLength); +keep.write("6869", "hex"); +keep.write(Buffer.from("zz")); +keep.end("end", "latin1"); + +const valueOpts = { decodeStrings: false, defaultEncoding: "HEX", write(c, e, cb) { log.push("value " + describe(c, e)); cb(); } }; +const fromValue = new Writable(dyn(valueOpts)); +fromValue.write("ab"); +fromValue.write(Buffer.from("c")); + +const hex = new Writable({ defaultEncoding: "hex", write(c, e, cb) { log.push("hex " + describe(c, e)); cb(); } }); +hex.write("6869"); +hex.write("41", "utf8"); +hex.setDefaultEncoding("BASE64"); +hex.write("aGk="); +try { + hex.setDefaultEncoding("nope"); +} catch (e) { + log.push("setDefaultEncoding " + e.code + " " + e.message); +} +log.push("chains " + (hex.setDefaultEncoding("utf8") === hex)); + +const t = new Transform({ decodeStrings: false, transform(c, e, cb) { log.push("t " + describe(c, e)); cb(null, c); } }); +t.on("data", (c) => log.push("t data " + describe(c, "-"))); +t.write("abc"); +t.write("ff", "hex"); +const p = new PassThrough({ decodeStrings: false }); +p.on("data", (c) => log.push("p data " + describe(c, "-"))); +p.write("q"); + +const om = new Writable({ objectMode: true, defaultEncoding: "hex", write(c, e, cb) { log.push("om " + describe(c, e)); cb(); } }); +om.write("s"); +try { + new Writable({ defaultEncoding: "bogus" }); +} catch (e) { + log.push("constructor " + e.code); +} + +function Sink() { + stream.Writable.call(this); +} +util.inherits(Sink, stream.Writable); +Sink.prototype._write = function (c, e, cb) { + log.push("sink " + describe(c, e)); + cb(); +}; +const sink = new Sink(); +sink.write("6869", "hex"); +sink.setDefaultEncoding("latin1"); +sink.write("é"); +sink.end("YQ==", "base64"); + +// A typed array or DataView chunk reaches _write and _writev as a Buffer +// over the same bytes (Stream._uint8ArrayToBuffer), also with +// decodeStrings: false; in object mode it stays as it is. +const views = new stream.Writable({ + decodeStrings: false, + write(c, e, cb) { + log.push(`view ${Buffer.isBuffer(c)} ${e} ${c.toString()}`); + cb(); + }, +}); +views.write(new Uint8Array([104, 105])); +views.write(new Uint16Array([0x6a6b])); +views.write(new DataView(new Uint8Array([108]).buffer)); +const batch = new stream.Writable({ + writev(chunks, cb) { + log.push(`view batch ${chunks.map((c) => `${Buffer.isBuffer(c.chunk)}:${c.encoding}:${c.chunk}`).join(" ")}`); + cb(); + }, +}); +batch.cork(); +batch.write(new Uint8Array([97])); +batch.write(new Uint8Array([98])); +batch.uncork(); +const source = new Uint8Array([1, 2]); +new stream.Writable({ + write(c, e, cb) { + log.push(`view plain ${Buffer.isBuffer(c)} ${e} ${c.buffer === source.buffer}`); + cb(); + }, +}).write(source); +new stream.Writable({ + objectMode: true, + write(c, e, cb) { + log.push(`view object ${Buffer.isBuffer(c)} ${c instanceof Uint8Array}`); + cb(); + }, +}).write(new Uint8Array([3])); +log.push(`view source ${Buffer.isBuffer(source)}`); + +setTimeout(() => console.log(log.join("\n")), 5); diff --git a/tests/corpus/7252-duplex-from-generator.ts b/tests/corpus/7252-duplex-from-generator.ts new file mode 100644 index 000000000..488748021 --- /dev/null +++ b/tests/corpus/7252-duplex-from-generator.ts @@ -0,0 +1,69 @@ +// Duplex.from over an async generator function in typed code: the +// generator reads what is written to the Duplex and its values are the +// readable side. Both sides are in object mode with a highWaterMark of +// 1; each write's callback runs once the generator asks for the next +// value, and end() reaches the generator as the end of its source. +import { Duplex } from "node:stream"; + +const log: string[] = []; + +async function* numbered(source: AsyncIterable): AsyncGenerator { + let n = 0; + for await (const chunk of source) { + n++; + log.push(`gen got ${String(chunk)}`); + yield `${n}:${String(chunk)}`; + } + log.push("gen done"); + yield `total ${n}`; +} + +async function collect(d: Duplex): Promise { + const out: string[] = []; + for await (const chunk of d) out.push(String(chunk)); + return out; +} + +async function basic(): Promise { + const d = Duplex.from(numbered); + log.push(`sides ${d.readable} ${d.writable}`); + log.push(`object mode ${d.readableObjectMode} ${d.writableObjectMode}`); + log.push(`hwm ${d.readableHighWaterMark} ${d.writableHighWaterMark}`); + d.write("a", () => log.push("write a done")); + d.write("b", () => log.push("write b done")); + d.end("c", () => log.push("end done")); + const out = await collect(d); + log.push(`read ${out.join(",")}`); + log.push(`after ${d.readableEnded} ${d.writableFinished} ${d.destroyed}`); +} + +async function values(): Promise { + // object-mode writes keep their values + const d = Duplex.from(async function* (source: AsyncIterable): AsyncGenerator { + for await (const v of source) yield typeof v + " " + JSON.stringify(v); + }); + d.write({ k: 1 }); + d.write([2, 3]); + d.write(4); + d.end(); + log.push(`values ${(await collect(d)).join(" | ")}`); +} + +async function earlyDestroy(): Promise { + const d = Duplex.from(numbered); + d.on("error", (e: Error) => log.push(`error ${e.message}`)); + d.on("close", () => log.push(`close ${d.destroyed}`)); + d.write("x"); + await new Promise((resolve) => setTimeout(resolve, 5)); + d.destroy(new Error("stop")); + await new Promise((resolve) => setTimeout(resolve, 5)); +} + +async function main(): Promise { + await basic(); + await values(); + await earlyDestroy(); + for (const line of log) console.log(line); +} + +void main(); diff --git a/tests/corpus/7253-duplex-from.mjs b/tests/corpus/7253-duplex-from.mjs new file mode 100644 index 000000000..14556348a --- /dev/null +++ b/tests/corpus/7253-duplex-from.mjs @@ -0,0 +1,48 @@ +// Duplex.from in JavaScript: an async generator function, an array, a +// generator object and an async generator object. Over an iterable the +// result is read-only (writable false); over a function it reads what is +// written. The log records the order of the write callbacks, the reads +// and the stream events against each other. +import { Duplex } from "node:stream"; + +const log = []; + +async function* echo(source) { + for await (const chunk of source) { + log.push(`echo ${chunk}`); + yield chunk.toUpperCase(); + } +} + +const fromFn = Duplex.from(echo); +fromFn.on("finish", () => log.push("fn finish")); +fromFn.on("end", () => log.push("fn end")); +fromFn.on("close", () => log.push("fn close")); +fromFn.write("one", () => log.push("fn write one cb")); +fromFn.write("two", () => log.push("fn write two cb")); +fromFn.end(() => log.push("fn end cb")); +for await (const chunk of fromFn) log.push(`fn read ${chunk}`); + +const fromArray = Duplex.from(["p", "q"]); +log.push(`array ${fromArray.readable} ${fromArray.writable} ${fromArray.readableObjectMode}`); +for await (const chunk of fromArray) log.push(`array ${chunk}`); + +function* gen() { + yield "g1"; + yield "g2"; +} +const fromGen = Duplex.from(gen()); +log.push(`gen ${fromGen.writable}`); +for await (const chunk of fromGen) log.push(`gen ${chunk}`); + +async function* agen() { + yield 1; + await null; + yield 2; +} +const fromAgen = Duplex.from(agen()); +fromAgen.on("data", (v) => log.push(`agen data ${v}`)); +await new Promise((resolve) => fromAgen.on("end", resolve)); +log.push(`agen ended ${fromAgen.readableEnded}`); + +console.log(log.join("\n")); diff --git a/tests/corpus/7254-compose-functions.ts b/tests/corpus/7254-compose-functions.ts new file mode 100644 index 000000000..4a2ba7189 --- /dev/null +++ b/tests/corpus/7254-compose-functions.ts @@ -0,0 +1,56 @@ +// stream.compose with async generator function stages in typed code: a +// function at either end becomes Duplex.from of it, functions between +// streams run as pipeline stages, and one stage is Duplex.from of it. +// The composed Duplex writes to the first stage and reads from the last; +// its object modes follow the first stage's writable side and the last +// stage's readable side. +import { Duplex, PassThrough, Transform, compose } from "node:stream"; + +const log: string[] = []; + +async function* upper(source: AsyncIterable): AsyncGenerator { + for await (const chunk of source) yield String(chunk).toUpperCase(); +} + +async function* numbered(source: AsyncIterable): AsyncGenerator { + let n = 0; + for await (const chunk of source) yield `${++n}.${String(chunk)}`; +} + +async function drain(name: string, d: Duplex, chunks: string[]): Promise { + log.push(`${name} r=${d.readable} w=${d.writable} ro=${d.readableObjectMode} wo=${d.writableObjectMode}`); + const out: string[] = []; + d.on("data", (c: unknown) => out.push(String(c))); + const ended = new Promise((resolve) => d.on("end", () => resolve())); + for (const c of chunks) d.write(c); + d.end(); + await ended; + log.push(`${name} ${out.join(" ")}`); +} + +async function main(): Promise { + // functions only: Duplex.from at both ends + await drain("fns", compose(upper, numbered), ["a", "b"]); + // a function between two object-mode streams + await drain( + "middle", + compose(new PassThrough({ objectMode: true }), upper, new PassThrough({ objectMode: true })), + ["c", "d"], + ); + // a byte stream before a function: the Duplex writes bytes + const bytes = compose(new PassThrough(), numbered); + await drain("bytes", bytes, ["e"]); + // a function before a Transform + const tail = new Transform({ + objectMode: true, + transform(chunk: unknown, _enc: string, cb: (err?: Error | null, data?: unknown) => void): void { + cb(null, `<${String(chunk)}>`); + }, + }); + await drain("transform", compose(upper, tail), ["f", "g"]); + // one stage + await drain("single", compose(numbered), ["h", "i", "j"]); + for (const line of log) console.log(line); +} + +void main(); diff --git a/tests/corpus/7255-compose-stages.mjs b/tests/corpus/7255-compose-stages.mjs new file mode 100644 index 000000000..ef6542ece --- /dev/null +++ b/tests/corpus/7255-compose-stages.mjs @@ -0,0 +1,55 @@ +// stream.compose in JavaScript with an iterable or generator first stage +// (the Duplex is not writable), a stage that throws (the Duplex errors), +// a destroyed composition (the stages see an AbortError), and compose() +// with no stages (ERR_MISSING_ARGS). +import { PassThrough, compose } from "node:stream"; + +const log = []; + +const double = async function* (source) { + for await (const n of source) yield n * 2; +}; + +const fromArray = compose([1, 2, 3], double); +log.push(`array r=${fromArray.readable} w=${fromArray.writable}`); +for await (const n of fromArray) log.push(`array ${n}`); + +function* counter() { + yield 10; + yield 20; +} +const fromGen = compose(counter(), double, async function* (source) { + for await (const n of source) yield `n=${n}`; +}); +for await (const s of fromGen) log.push(`gen ${s}`); + +const failing = compose(new PassThrough({ objectMode: true }), async function* (source) { + for await (const chunk of source) { + if (chunk === "stop") throw new Error("stage failed on " + chunk); + yield chunk; + } +}, new PassThrough({ objectMode: true })); +failing.on("data", (c) => log.push(`failing data ${c}`)); +failing.on("error", (e) => log.push(`failing error ${e.message}`)); +failing.on("close", () => log.push(`failing close ${failing.destroyed}`)); +failing.write("go"); +failing.write("stop"); +await new Promise((resolve) => failing.on("close", resolve)); + +const stopped = compose(new PassThrough({ objectMode: true }), double); +stopped.on("error", (e) => log.push(`stopped error ${e.name} ${e.code}`)); +stopped.on("close", () => log.push("stopped close")); +stopped.write(4); +stopped.once("data", (n) => { + log.push(`stopped data ${n}`); + stopped.destroy(); +}); +await new Promise((resolve) => stopped.on("close", resolve)); + +try { + compose(); +} catch (e) { + log.push(`empty ${e.code} ${e.message}`); +} + +console.log(log.join("\n")); diff --git a/tests/corpus/7256-readable-compose.mjs b/tests/corpus/7256-readable-compose.mjs new file mode 100644 index 000000000..a9622173e --- /dev/null +++ b/tests/corpus/7256-readable-compose.mjs @@ -0,0 +1,53 @@ +// readable.compose(stage, { signal }): compose(this, stage), with the +// signal aborting the composed Duplex. The stage may be an async +// generator function or a stream; the result reads like the stage's +// output and is not writable when the receiver heads it. +import { PassThrough, Readable, Transform } from "node:stream"; + +const log = []; + +const WORDS = ["alpha", "beta", "gamma"]; +const lengths = async function* (source) { + for await (const w of source) yield `${w}:${w.length}`; +}; + +const source = Readable.from(WORDS); +const viaFn = source.compose(lengths); +log.push(`fn r=${viaFn.readable} w=${viaFn.writable} ro=${viaFn.readableObjectMode}`); +for await (const s of viaFn) log.push(`fn ${s}`); + +const shout = new Transform({ + objectMode: true, + transform(chunk, _enc, cb) { + cb(null, chunk.toUpperCase()); + }, +}); +const source2 = Readable.from(WORDS); +const viaStream = source2.compose(shout); +log.push(`stream ${(await viaStream.toArray()).join(",")}`); + +const pass = new PassThrough({ objectMode: true }); +const chained = pass.compose(lengths).compose(async function* (source) { + for await (const s of source) yield `[${s}]`; +}); +chained.on("data", (s) => log.push(`chained ${s}`)); +pass.write("x"); +pass.end("yz"); +await new Promise((resolve) => chained.on("end", resolve)); + +const ac = new AbortController(); +const signal = ac.signal; +const slow = new Readable({ objectMode: true, read() {} }); +const aborted = slow.compose(lengths, { signal }); +aborted.on("data", (s) => log.push(`aborted data ${s}`)); +aborted.on("error", (e) => log.push(`aborted error ${e.name} ${e.code}`)); +aborted.on("close", () => log.push(`aborted close ${aborted.destroyed}`)); +slow.push("one"); +setTimeout(() => ac.abort(), 10); +await new Promise((resolve) => aborted.on("close", resolve)); + +const source3 = Readable.from(WORDS); +const unsignaled = source3.compose(lengths, undefined); +log.push(`undefined options ${(await unsignaled.toArray()).length}`); + +console.log(log.join("\n")); diff --git a/tests/corpus/7257-pipeline-generator-destination.mjs b/tests/corpus/7257-pipeline-generator-destination.mjs new file mode 100644 index 000000000..0996e06eb --- /dev/null +++ b/tests/corpus/7257-pipeline-generator-destination.mjs @@ -0,0 +1,61 @@ +// pipeline() whose destination is a function: an async generator +// destination is pumped into the object-mode PassThrough pipeline() +// returns, and an async function destination's resolved value is written +// to it (null and undefined are not). The callback runs with the error +// and the destination's value; a generator yielding null fails the +// pipeline with ERR_STREAM_NULL_VALUES. +import { Readable, pipeline } from "node:stream"; + +const log = []; + +const out = pipeline( + Readable.from(["a", "b", "c"]), + async function* (source) { + for await (const chunk of source) yield { chunk, at: log.length }; + }, + (err, value) => log.push(`gen cb ${err} ${value}`), +); +log.push(`gen out r=${out.readable} w=${out.writable} ro=${out.readableObjectMode} wo=${out.writableObjectMode}`); +for await (const item of out) log.push(`gen read ${JSON.stringify(item)}`); + +const summary = pipeline( + Readable.from([3, 4]), + async function* (source) { + for await (const n of source) yield n * n; + }, + async function (source) { + let total = 0; + for await (const n of source) total += n; + return { total }; + }, + (err, value) => log.push(`fn cb ${err} ${JSON.stringify(value)}`), +); +summary.on("data", (v) => log.push(`fn data ${JSON.stringify(v)}`)); +summary.on("end", () => log.push("fn end")); +await new Promise((resolve) => summary.on("close", resolve)); + +const nothing = pipeline( + Readable.from(["x"]), + async function (source) { + for await (const _ of source); + return undefined; + }, + (err) => log.push(`undefined cb ${err}`), +); +nothing.on("data", () => log.push("undefined data")); +nothing.on("end", () => log.push("undefined end")); +await new Promise((resolve) => nothing.on("close", resolve)); + +const bad = pipeline( + Readable.from(["g"]), + async function* (source) { + for await (const chunk of source) yield chunk; + yield null; + }, + (err) => log.push(`null cb ${err && err.code}`), +); +bad.on("data", (c) => log.push(`null data ${c}`)); +bad.on("error", (e) => log.push(`null error ${e.code}`)); +await new Promise((resolve) => bad.on("close", resolve)); + +console.log(log.join("\n")); diff --git a/tests/corpus/7258-pipeline-generator-destination.ts b/tests/corpus/7258-pipeline-generator-destination.ts new file mode 100644 index 000000000..b22b68dce --- /dev/null +++ b/tests/corpus/7258-pipeline-generator-destination.ts @@ -0,0 +1,47 @@ +// pipeline() with a function destination in typed code. @types/node and +// the fallback declarations type the result as the destination stream; +// for a function destination it is the object-mode PassThrough that +// pipeline() returns, read here as a PassThrough. +import { PassThrough, Readable, pipeline } from "node:stream"; + +const log: string[] = []; + +async function* tokens(source: AsyncIterable): AsyncGenerator { + for await (const line of source) { + for (const word of String(line).split(" ")) yield word; + } +} + +async function* tagged(source: AsyncIterable): AsyncGenerator<{ word: string; n: number }> { + let n = 0; + for await (const word of source) yield { word, n: ++n }; +} + +async function main(): Promise { + const out = pipeline(Readable.from(["to be", "or not"]), tokens, tagged, (err: Error | null) => { + log.push(`callback ${err === null || err === undefined ? "ok" : err.message}`); + }) as PassThrough; + log.push(`object mode ${out.readableObjectMode} ${out.writableObjectMode}`); + for await (const item of out) { + const entry = item as { word: string; n: number }; + log.push(`${entry.n} ${entry.word}`); + } + log.push(`ended ${out.readableEnded}`); + + const counted = pipeline( + Readable.from(["x", "y", "z"]), + async function (source: AsyncIterable): Promise { + let n = 0; + for await (const _ of source) n++; + return n; + }, + (err: Error | null) => log.push(`count callback ${err === null || err === undefined}`), + ) as PassThrough; + const values: unknown[] = []; + counted.on("data", (v: unknown) => values.push(v)); + await new Promise((resolve) => counted.on("end", () => resolve())); + log.push(`count values ${JSON.stringify(values)}`); + for (const line of log) console.log(line); +} + +void main(); diff --git a/tests/corpus/7259-promises-pipeline-stage-options.cjs b/tests/corpus/7259-promises-pipeline-stage-options.cjs new file mode 100644 index 000000000..a4a3ce396 --- /dev/null +++ b/tests/corpus/7259-promises-pipeline-stage-options.cjs @@ -0,0 +1,65 @@ +// stream/promises pipeline() with function stages or an iterable source +// and the options argument: end: false leaves the destination open, a +// signal aborts the pipeline (the stages see their own signal abort), an +// async function destination's value resolves the promise, and a value +// that is not an AbortSignal rejects with ERR_INVALID_ARG_TYPE. +const { PassThrough, Writable } = require("node:stream"); +const { pipeline } = require("node:stream/promises"); + +const log = []; + +const upper = async function* (source) { + for await (const chunk of source) yield String(chunk).toUpperCase(); +}; + +function sink(name) { + return new Writable({ + objectMode: true, + write(chunk, _enc, cb) { + log.push(`${name} got ${chunk}`); + cb(); + }, + }); +} + +async function main() { + const joined = await pipeline(["a", "b"], upper, async function (source) { + let s = ""; + for await (const c of source) s += c; + return s; + }, { end: true }); + log.push(`joined ${joined}`); + + const open = new PassThrough({ objectMode: true }); + await pipeline(["k"], upper, open, { end: false }); + log.push(`end false: ended ${open.writableEnded}`); + open.end("last"); + const rest = []; + for await (const c of open) rest.push(c); + log.push(`end false: read ${rest.join(",")}`); + + const ac = new AbortController(); + const slow = async function* (source, { signal }) { + signal.addEventListener("abort", () => log.push(`stage signal aborted ${signal.aborted}`)); + for await (const chunk of source) { + yield chunk; + await new Promise((resolve) => setTimeout(resolve, 30)); + } + }; + const aborting = pipeline(["s1", "s2", "s3"], slow, sink("abort"), { signal: ac.signal }); + setTimeout(() => ac.abort(), 10); + try { + await aborting; + } catch (e) { + log.push(`aborted ${e.name} ${e.code}`); + } + + try { + await pipeline(["v"], upper, sink("bad"), { signal: "nope" }); + } catch (e) { + log.push(`bad signal ${e.code}`); + } + console.log(log.join("\n")); +} + +main(); diff --git a/tests/corpus/7261-acyclic-result-builders.ts b/tests/corpus/7261-acyclic-result-builders.ts new file mode 100644 index 000000000..b6a98fce4 --- /dev/null +++ b/tests/corpus/7261-acyclic-result-builders.ts @@ -0,0 +1,86 @@ +// Records built by functions that return object literals, as tree and list +// builders are written. The backend gives such a function a result-slot +// entry that writes the literal's fields into a caller's frame storage, and +// those stores do not make the record's fields mutable: a type no store +// changes after construction stays acyclic and needs no cycle-collector +// header. This pins what such programs print: rebuilt trees, a shared +// subtree (a DAG), a builder whose result the caller only projects (so the +// entry runs), a list longer than the runtime's teardown depth budget, and +// a record type the program writes after construction, whose rings only +// the collector frees. The sanitized lane asserts every object is freed. + +interface Node { + value: number; + left: Node | null; + right: Node | null; +} + +function leaf(value: number): Node { + return { value, left: null, right: null }; +} + +function branch(value: number, left: Node | null, right: Node | null): Node { + return { value, left, right }; +} + +function tree(depth: number, value: number): Node { + return depth === 0 ? leaf(value) : branch(value, tree(depth - 1, value * 2), tree(depth - 1, value * 2 + 1)); +} + +function sum(node: Node | null): number { + return node === null ? 0 : node.value + sum(node.left) + sum(node.right); +} + +let total = 0; +for (let generation = 0; generation < 8; generation++) total += sum(tree(8, generation + 1)); +console.log("trees", total); + +// A subtree shared by both branches is released once. +const shared = tree(3, 1); +const dag = branch(0, shared, shared); +console.log("dag", sum(dag), JSON.stringify(branch(1, leaf(2), null))); + +// Only projected: the result lives in the caller's frame, which releases +// the subtree it holds. +const top = branch(5, tree(2, 1), null); +console.log("top", top.value, sum(top.left), top.right === null); + +interface Cell { + n: number; + next: Cell | null; +} + +function cons(n: number, next: Cell | null): Cell { + return { n, next }; +} + +let list: Cell | null = null; +for (let i = 0; i < 5000; i++) list = cons(i, list); +let length = 0; +let last = -1; +for (let c = list; c !== null; c = c.next) { + length++; + last = c.n; +} +console.log("list", length, last); +list = null; + +// A record type written after construction keeps its cycle-collector +// header: these rings are garbage only the collector can free. +interface Ring { + id: number; + next: Ring | null; +} + +function ring(id: number, next: Ring | null): Ring { + return { id, next }; +} + +let ids = 0; +for (let i = 0; i < 200; i++) { + const a = ring(i, null); + const b = ring(i + 1, a); + a.next = b; + ids += a.next.id + b.next!.id; +} +console.log("rings", ids); diff --git a/tests/corpus/7280-named-reads-hole-receivers.ts b/tests/corpus/7280-named-reads-hole-receivers.ts new file mode 100644 index 000000000..59f0c4820 --- /dev/null +++ b/tests/corpus/7280-named-reads-hole-receivers.ts @@ -0,0 +1,50 @@ +// Named reads and method calls through a parameter narrowed to one arm of a +// wide union, when an array hole reaches the narrowed branch. +type Bag = number | string | number[] | { a?: number; f?: () => string }; +function isBag(value: Bag): value is { a?: number; f?: () => string } { + return !Array.isArray(value) && typeof value !== "string" && typeof value !== "number"; +} +function peek(value: Bag): string { + if (isBag(value)) return typeof value.a; + return "-"; +} +function call(value: Bag): string { + if (isBag(value)) return value.f?.() ?? "none"; + return "-"; +} +class Shape { + side: number; + constructor(side: number) { + this.side = side; + } + area(): number { + return this.side * this.side; + } +} +type Item = Shape | string | number; +function area(item: Item): number { + if (item instanceof Shape || (typeof item !== "string" && typeof item !== "number")) return item.area(); + return 0; +} +const bags: Bag[] = [{ a: 1, f: () => "f" }, "s", [1]]; +bags.length = 4; +const items: Item[] = [new Shape(2), "x"]; +items.length = 3; +const out: string[] = []; +for (let i = 0; i < bags.length; i++) { + for (const which of [0, 1]) { + try { + out.push(which === 0 ? peek(bags[i]) : call(bags[i])); + } catch (e) { + out.push(e instanceof TypeError ? e.message : "other"); + } + } +} +for (let i = 0; i < items.length; i++) { + try { + out.push(String(area(items[i]))); + } catch (e) { + out.push(e instanceof TypeError ? e.message : "other"); + } +} +console.log(out.join("\n")); diff --git a/tests/corpus/7300-callback-captured-scalars.ts b/tests/corpus/7300-callback-captured-scalars.ts new file mode 100644 index 000000000..c8e8b28bd --- /dev/null +++ b/tests/corpus/7300-callback-captured-scalars.ts @@ -0,0 +1,147 @@ +// Callbacks that update captured `let` numbers and booleans from loops: typed +// array and array methods, an authored higher-order function called with one +// function at several calls and with two functions at one, closures of one +// function over different bindings, a callback that throws part way, nested +// callbacks, callbacks declared in the loop body, and reads after the loop. + +function each(values: number[], visit: (v: number, i: number) => void): void { + for (let i = 0; i < values.length; i++) visit(values[i]!, i); +} + +function until(limit: number, step: (i: number) => boolean): number { + let i = 0; + while (i < limit) { + if (!step(i)) break; + i++; + } + return i; +} + +function twice(values: Int16Array, f: (v: number) => void): void { + let i = 0; + do { + for (let j = 0; j < values.length; j++) f(values[j]!); + i++; + } while (i < 2); +} + +const ints = new Int32Array([5, -3, 8, 0, 12, -7, 4]); +let total = 0; +let negatives = 0; +let sawZero = false; +ints.forEach((v) => { + total = (total + v) | 0; + if (v < 0) negatives++; + if (v === 0) sawZero = true; +}); +console.log("forEach", total, negatives, sawZero); + +let max = -Infinity; +let maxAt = -1; +const floats = new Float64Array([0.5, 9.25, -2, 9.25, 3]); +floats.forEach((v, i) => { + if (v > max) { + max = v; + maxAt = i; + } +}); +console.log("max", max, maxAt); + +let calls = 0; +const doubled = ints.map((v) => { + calls++; + return v * 2 + calls; +}); +console.log("map", doubled.join(","), calls); + +let seen = 0; +const big = [3, 14, 15, 92, 65].filter((v) => { + seen += v; + return v > 10; +}); +console.log("filter", big.join(","), seen); + +let sum = 0; +let count = 0; +const summing = (v: number): void => { + sum += v; + count++; +}; +each([1, 2, 3], summing); +each([10, 20], summing); +console.log("each shared", sum, count); + +let a = 0; +let b = 0; +each([1, 2], (v) => { + a += v; +}); +each([1, 2], (v, i) => { + b += v * (i + 1); +}); +console.log("each two", a, b); + +const counters: (() => number)[] = []; +for (let k = 0; k < 3; k++) { + let local = k * 100; + each([1, 1, 1], () => { + local++; + }); + counters.push(() => local); +} +console.log("closures", counters.map((c) => c()).join(",")); + +let steps = 0; +console.log("until", until(10, (i) => (steps += i, steps < 12)), steps); + +let shorts = 0; +twice(new Int16Array([7, -8, 9]), (v) => { + shorts = shorts * 2 + v; +}); +console.log("twice", shorts); + +let partial = 0; +try { + floats.forEach((v) => { + if (v < 0) throw new RangeError(`at ${partial}`); + partial += v; + }); +} catch (error) { + console.log("throw", (error as Error).message, partial); +} + +let outer = 0; +let inner = 0; +[1, 2, 3].forEach((x) => { + outer += x; + ints.forEach((y) => { + if (y > x) inner++; + }); +}); +console.log("nested", outer, inner); + +let flag = false; +let flips = 0; +new Uint8Array([1, 0, 1, 1]).forEach((v) => { + if (v === 1) flag = !flag; + if (flag) flips++; +}); +console.log("bool", flag, flips); + +// Callbacks declared in the loop body: each iteration binds its own. +let strides = 0; +for (let i = 0; i < 10; i++) { + const bump = (): void => { + i += 2; + strides++; + }; + bump(); +} +let countdown = 0; +let k = 3; +while (k > 0) { + const tick = (n: number): number => (n > 0 ? tick(n - 1) + 1 : 0); + countdown += tick(k); + k--; +} +console.log("declared in loop", strides, countdown); diff --git a/tests/corpus/7301-running-extrema-branches.ts b/tests/corpus/7301-running-extrema-branches.ts new file mode 100644 index 000000000..9941ce538 --- /dev/null +++ b/tests/corpus/7301-running-extrema-branches.ts @@ -0,0 +1,169 @@ +// Running maximum and minimum scans over ascending, descending, alternating, +// pseudo-random and NaN-holding data: plain for, while, do-while and for-of +// loops, `<=` and `>=` ties, an argmax that records its index, typed array +// and array element reads, callbacks that update captured bindings, a scan +// nested in an outer loop, an update nested in another branch, and the clamp +// and saturating updates that are not running extrema. + +function shapes(n: number): [string, Float64Array][] { + const ascending = new Float64Array(n); + const descending = new Float64Array(n); + const alternating = new Float64Array(n); + const random = new Float64Array(n); + const holes = new Float64Array(n); + let x = 12345; + for (let i = 0; i < n; i++) { + ascending[i] = i; + descending[i] = n - i; + alternating[i] = i % 2 === 0 ? 0 : i; + x = (x * 1103515245 + 12345) % 2147483648; + random[i] = (x % 1000) - 500; + holes[i] = i % 7 === 3 ? NaN : (x % 97) - 48; + } + return [ + ["ascending", ascending], + ["descending", descending], + ["alternating", alternating], + ["random", random], + ["nan", holes], + ]; +} + +function argmax(a: Float64Array): string { + let max = -Infinity; + let at = -1; + for (let i = 0; i < a.length; i++) { + const v = a[i]!; + if (v > max) { + max = v; + at = i; + } + } + return `${max}@${at}`; +} + +function lastMin(a: Float64Array): string { + let min = Infinity; + let at = -1; + let i = 0; + while (i < a.length) { + if (a[i]! <= min) { + min = a[i]!; + at = i; + } + i++; + } + return `${min}@${at}`; +} + +function bothEnds(values: number[]): string { + let lo = Infinity; + let hi = -Infinity; + for (const v of values) { + if (lo > v) lo = v; + if (v >= hi) hi = v; + } + return `${lo}..${hi}`; +} + +function firstDrop(a: Float64Array): number { + let floor = a[0]!; + let i = 0; + do { + if (a[i]! < floor) floor = a[i]!; + i++; + } while (i < a.length); + return floor; +} + +function callbackPeak(a: Float64Array): string { + let max = -Infinity; + let at = -1; + a.forEach((v, i) => { + if (v > max) { + max = v; + at = i; + } + }); + return `${max}@${at}`; +} + +function arrayCallbackMin(values: number[]): number { + let min = Infinity; + values.forEach((v) => { + if (v < min) min = v; + }); + return min; +} + +function rowMaxima(a: Float64Array, width: number): string { + const out: number[] = []; + for (let row = 0; row * width < a.length; row++) { + let best = -Infinity; + for (let j = row * width; j < Math.min(a.length, (row + 1) * width); j++) { + if (a[j]! > best) best = a[j]!; + } + out.push(best); + } + return out.join(","); +} + +function longestNonNegativeRun(a: Float64Array): number { + let longest = 0; + let run = 0; + for (let i = 0; i < a.length; i++) { + if (a[i]! >= 0) { + run++; + if (run > longest) longest = run; + } else run = 0; + } + return longest; +} + +function clampSum(a: Float64Array, hi: number): number { + let s = 0; + for (let i = 0; i < a.length; i++) { + let v = a[i]!; + if (hi < v) v = hi; + s += v; + } + return s; +} + +function saturate(a: Float64Array, hi: number): number { + let v = 0; + for (let i = 0; i < a.length; i++) { + v += a[i]!; + if (hi < v) v = hi; + } + return v; +} + +for (const [name, a] of shapes(40)) { + const values = Array.from(a); + console.log( + name, + argmax(a), + lastMin(a), + bothEnds(values), + firstDrop(a), + callbackPeak(a), + arrayCallbackMin(values), + ); + console.log( + " rows", + rowMaxima(a, 7), + "run", + longestNonNegativeRun(a), + "clamp", + clampSum(a, 5), + "saturate", + saturate(a, 30), + ); +} + +const signed = new Float64Array([0, -0, 0, -0]); +let top = -Infinity; +for (let i = 0; i < signed.length; i++) if (signed[i]! >= top) top = signed[i]!; +console.log("signed zero", Object.is(top, -0), argmax(signed), lastMin(signed)); +console.log("empty", argmax(new Float64Array(0)), bothEnds([]), arrayCallbackMin([])); diff --git a/tests/corpus/7302-string-scan-loop-versions.ts b/tests/corpus/7302-string-scan-loop-versions.ts new file mode 100644 index 000000000..3408e048e --- /dev/null +++ b/tests/corpus/7302-string-scan-loop-versions.ts @@ -0,0 +1,192 @@ +// charCodeAt scans in counted for loops over ASCII strings, Latin-1 and BMP +// text, surrogate pairs and lone surrogates, empty strings, neighbors at +// i - 1 and i + 1, loops that stop early or read past the end, strings built +// by concatenation and slicing, a scan of a slice local, two strings read at +// one index, a string rebound inside or after the loop, nested scans, a +// module-level scan, and while loops over a counter below the length: word +// and identifier scans, peeks past the counter, a counter from a field, and +// reads at or past the end. + +function spaces(s: string): number { + let n = 0; + for (let i = 0; i < s.length; i++) if (s.charCodeAt(i) === 32) n++; + return n; +} + +function hash(s: string): number { + let h = 0; + for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) | 0; + return h; +} + +function rises(s: string): number { + let n = 0; + for (let i = 1; i < s.length; i++) if (s.charCodeAt(i) > s.charCodeAt(i - 1)) n++; + return n; +} + +function peaks(s: string): number { + let n = 0; + for (let i = 1; i < s.length - 1; i++) { + const c = s.charCodeAt(i); + if (c > s.charCodeAt(i - 1) && c > s.charCodeAt(i + 1)) n++; + } + return n; +} + +function firstDigit(s: string): number { + for (let i = 0; i < s.length; i++) { + const c = s.charCodeAt(i); + if (c >= 48 && c <= 57) return i; + } + return -1; +} + +function pastEnd(s: string): string { + let sum = 0; + for (let i = 0; i <= s.length; i++) sum += s.charCodeAt(i); + return String(sum); +} + +function sameAt(a: string, b: string): number { + let n = 0; + const end = Math.min(a.length, b.length); + for (let i = 0; i < end; i++) if (a.charCodeAt(i) === b.charCodeAt(i)) n++; + return n; +} + +function stepped(s: string): number { + let h = 7; + for (let i = s.length - 1; i >= 0; i -= 2) h = (h * 33) ^ s.charCodeAt(i); + return h; +} + +function slicedScan(s: string, from: number, to: number): number { + const piece = s.slice(from, to); + let n = piece.length; + for (let i = 0; i < piece.length; i++) n += piece.charCodeAt(i); + return n; +} + +function rebound(s: string): number { + let n = 0; + for (let i = 0; i < s.length; i++) { + n += s.charCodeAt(i); + if (i === 2) s = s.toUpperCase(); + } + return n; +} + +function words(s: string): number { + let pos = 0, + n = 0; + const end = s.length; + while (pos < end) { + while (pos < end && s.charCodeAt(pos) === 32) pos++; + if (pos >= end) break; + n++; + while (pos < end && s.charCodeAt(pos) !== 32) pos++; + } + return n; +} + +function identifiers(s: string): number { + let pos = 0, + total = 0; + while (pos < s.length) { + const c = s.charCodeAt(pos); + if (c >= 97 && c <= 122) { + const start = pos; + while (pos < s.length && s.charCodeAt(pos) >= 97 && s.charCodeAt(pos) <= 122) pos++; + total += pos - start; + } else pos = (pos + 1) | 0; + } + return total; +} + +function pairs(s: string): number { + let pos = 0, + n = 0; + while (pos < s.length) { + if (s.charCodeAt(pos) === s.charCodeAt(pos + 1)) n++; + pos += 1; + } + return n; +} + +function throughEnd(s: string): string { + let pos = 0, + sum = 0; + while (pos <= s.length) { + sum += s.charCodeAt(pos); + pos++; + } + return String(sum); +} + +class Cursor { + pos = 0; + src: string; + constructor(src: string) { + this.src = src; + } + skip(): number { + const src = this.src; + let pos = this.pos; + while (pos < src.length && src.charCodeAt(pos) !== 44) pos++; + this.pos = pos + 1; + return pos; + } +} + +function fields(s: string): string { + const cursor = new Cursor(s); + const ends: number[] = []; + while (cursor.pos < s.length) ends.push(cursor.skip()); + return ends.join(","); +} + +const samples = [ + "the quick brown fox jumps over the lazy dog", + "", + " ", + "abc123 def", + "café au lait", + "日本語のテキスト と 空白", + "emoji 😀 and 🎉 here", + "lone \uD800 surrogate \uDFFF end", + "zigzag azbycxdw", +]; +for (const s of samples) { + console.log( + JSON.stringify(s), + spaces(s), + hash(s), + rises(s), + peaks(s), + firstDigit(s), + pastEnd(s), + stepped(s), + rebound(s), + slicedScan(s, 2, 9), + ); + console.log(" ", words(s), identifiers(s), pairs(s), throughEnd(s), fields(s)); +} + +let built = ""; +for (let k = 0; k < 40; k++) built += String.fromCharCode(65 + (k % 26)) + (k % 3 === 0 ? " " : ""); +const sliced = built.slice(5, 30); +console.log("built", spaces(built), hash(built), rises(sliced), peaks(sliced), sameAt(built, sliced)); +console.log("pairs", sameAt("hello world", "help, world!"), sameAt("abc", ""), sameAt("é", "e")); + +let total = 0; +for (const s of samples) { + for (let i = 0; i < s.length; i++) total = (total + s.charCodeAt(i) * (i + 1)) | 0; +} +console.log("nested", total); + +let text = "module level scan, with commas, and spaces"; +let commas = 0; +for (let i = 0; i < text.length; i++) if (text.charCodeAt(i) === 44) commas++; +text = "rebound after the loop"; +console.log("module", commas, text.length, spaces(text)); diff --git a/tests/corpus/7303-string-char-loop-versions.ts b/tests/corpus/7303-string-char-loop-versions.ts new file mode 100644 index 000000000..f6c21fc59 --- /dev/null +++ b/tests/corpus/7303-string-char-loop-versions.ts @@ -0,0 +1,184 @@ +// s[i] and s.charAt(i) in counted for loops: equality and switch tests with +// one-unit literals, character locals compared with ranges of one-unit +// literals on either side, characters used as strings (pushed, concatenated, +// map keys, compared with each other), reads past the end, fractional, +// negative and -0 indices, ASCII, Latin-1, BMP, surrogate pairs and lone +// surrogates, empty strings, a character local with other uses, a local +// compared with a longer literal, a string rebound in the loop and a +// module-level loop. + +function spacesIndex(s: string): number { + let n = 0; + for (let i = 0; i < s.length; i++) if (s[i] === " ") n++; + return n; +} + +function nonSpaces(s: string): number { + let n = 0; + for (let i = 0; i < s.length; i++) if (s.charAt(i) !== " ") n++; + return n; +} + +function kinds(s: string): string { + let letters = 0, + digits = 0, + upper = 0, + other = 0; + for (let i = 0; i < s.length; i++) { + const c = s[i]; + if (c >= "a" && c <= "z") letters++; + else if ("0" <= c && "9" >= c) digits++; + else if (c > "@" && c < "[") upper++; + else other++; + } + return `${letters}/${digits}/${upper}/${other}`; +} + +function punctuation(s: string): number { + let n = 0; + for (let i = 0; i < s.length; i++) { + const c = s.charAt(i); + switch (c) { + case ".": + case ",": + n += 1; + break; + case "!": + n += 10; + break; + case "é": + n += 100; + break; + default: + if (c === "?") n += 1000; + } + } + return n; +} + +function switchIndex(s: string): number { + let n = 0; + for (let i = 0; i < s.length; i++) { + switch (s[i]) { + case "a": + n++; + break; + case "b": + n += 2; + break; + } + } + return n; +} + +function pastEnd(s: string): string { + let below = 0, + atMost = 0, + above = 0, + atLeast = 0; + for (let i = 0; i <= s.length + 1; i++) { + const c = s.charAt(i); + if (c < "a") below++; + if (c <= "z") atMost++; + if (c > " ") above++; + if (c >= "\0") atLeast++; + } + return `${below} ${atMost} ${above} ${atLeast}`; +} + +function oddIndices(s: string): string { + const out: string[] = []; + for (let i = -2; i < 3; i++) out.push(JSON.stringify(s.charAt(i + 0.5))); + out.push(JSON.stringify(s.charAt(-0)), JSON.stringify(s.charAt(NaN))); + const c = s.charAt(-1); + out.push(String(c < "a"), String(c >= "\0")); + return out.join(","); +} + +function chars(s: string): string { + const out: string[] = []; + for (let i = 0; i < s.length; i++) out.push(s.charAt(i)); + let reversed = ""; + for (let i = s.length - 1; i >= 0; i--) reversed += s[i]; + return `${out.join("|")} ${reversed}`; +} + +function counts(s: string): string { + const seen = new Map(); + for (let i = 0; i < s.length; i++) { + const c = s[i]; + seen.set(c, (seen.get(c) ?? 0) + 1); + } + return [...seen].map(([c, n]) => `${c}${n}`).join(""); +} + +function sameAt(a: string, b: string): number { + let n = 0; + const end = Math.min(a.length, b.length); + for (let i = 0; i < end; i++) if (a[i] === b[i]) n++; + return n; +} + +function words(s: string): string { + let n = 0; + let last = ""; + for (let i = 0; i < s.length; i++) { + const c = s[i]; + if (c === " ") n++; + last = c; + } + return `${n}:${last}`; +} + +function longer(s: string): number { + let n = 0; + for (let i = 0; i < s.length; i++) { + const c = s.charAt(i); + if (c === "ab" || c < "b") n++; + } + return n; +} + +function rebound(s: string): number { + let n = 0; + for (let i = 0; i < s.length; i++) { + if (s[i] === "x") n++; + if (i === 1) s = s + "xx"; + } + return n; +} + +const samples = [ + "the quick brown fox, jumps over the lazy dog!", + "", + " ", + "abc123 DEF? xyz", + "café, au lait.", + "日本語のテキスト と 空白", + "emoji 😀 and 🎉 here!", + "lone \uD800 surrogate \uDFFF end", + "aabbab ba", +]; +for (const s of samples) { + console.log( + JSON.stringify(s), + spacesIndex(s), + nonSpaces(s), + kinds(s), + punctuation(s), + switchIndex(s), + pastEnd(s), + oddIndices(s), + ); + console.log(" ", chars(s), counts(s), words(s), longer(s), rebound(s)); +} + +let built = ""; +for (let k = 0; k < 40; k++) built += String.fromCharCode(97 + (k % 26)) + (k % 4 === 0 ? " " : ""); +console.log("built", spacesIndex(built), kinds(built), sameAt(built, built.slice(3)), counts(built)); +console.log("pairs", sameAt("hello world", "help, world!"), sameAt("abc", ""), sameAt("é", "e")); + +const text = "module level: scan, with commas, and spaces"; +let commas = 0; +for (let i = 0; i < text.length; i++) if (text[i] === ",") commas++; +console.log("module", commas); diff --git a/tests/corpus/7320-array-dense-loop-invariant-limits.ts b/tests/corpus/7320-array-dense-loop-invariant-limits.ts new file mode 100644 index 000000000..878245e60 --- /dev/null +++ b/tests/corpus/7320-array-dense-loop-invariant-limits.ts @@ -0,0 +1,101 @@ +// Index loops bounded by an invariant limit other than the array's own length +// (a local copy of a length, a literal, an inclusive bound), over arrays the +// loop never resizes: class instances whose number and boolean fields the loop +// writes, and number arrays that are dense, short, holey or partially filled. + +class Body { + x: number; + v = 0; + hit = false; + next: Body | null = null; + + constructor(x: number) { + this.x = x; + } +} + +function pairs(bodies: Body[]): string { + const n = bodies.length; + for (let i = 0; i < n; i++) { + const bi = bodies[i]!; + let vi = bi.v; + for (let j = i + 1; j < n; j++) { + const bj = bodies[j]!; + const d = bi.x - bj.x; + const f = 1 / (d * d + 1); + vi -= d * f; + bj.v += d * f; + bj.hit = f > 0.1; + } + bi.v = vi; + } + return bodies.map((b) => `${b.v.toFixed(6)}${b.hit ? "*" : ""}`).join(" "); +} + +function firstThree(bodies: Body[]): number { + let s = 0; + for (let j = 0; j < 3; j++) s += bodies[j]!.x; + return s; +} + +function inclusive(bodies: Body[]): number { + const last = bodies.length - 1; + let s = 0; + for (let j = 1; j <= last; j++) s += bodies[j]!.x * j; + return s; +} + +function linked(bodies: Body[]): string { + const n = bodies.length; + // A reference field write: the loop keeps the ordinary copy. + for (let j = 0; j < n - 1; j++) bodies[j]!.next = bodies[j + 1]!; + let count = 0; + for (let b: Body | null = bodies[0]!; b !== null; b = b.next) count++; + return `${count}`; +} + +function sumTo(a: number[], limit: number): string { + const n = limit; + let s = 0; + let missing = 0; + for (let i = 0; i < n; i++) { + const v = a[i]; + if (v === undefined) missing++; + else s += v; + } + return `${s} ${missing}`; +} + +function scaleTo(a: number[], out: number[]): string { + const n = a.length; + for (let i = 0; i < n; i++) out[i] = a[i] * 2; + return `${out.length}:${out.join(",")}`; +} + +function window(a: number[]): number { + let s = 0; + for (let i = 2; i < 6; i++) s += a[i] * i; + return s; +} + +const bodies = [new Body(0), new Body(1.5), new Body(-2), new Body(4), new Body(0.25)]; +console.log(pairs(bodies)); +console.log(pairs(bodies)); +console.log(firstThree(bodies), inclusive(bodies), inclusive([new Body(7)])); +console.log(linked([new Body(1), new Body(2), new Body(3)])); + +const dense = [1, 2, 3, 4, 5, 6, 7, 8]; +console.log(sumTo(dense, 8), sumTo(dense, 5), sumTo(dense, 0), sumTo(dense, -3)); +// Limits past the length or the filled prefix take the checked loop. +console.log(sumTo(dense, 10), sumTo([], 2)); +const holey = [1]; +holey[3] = 4; +console.log(sumTo(holey, 4), sumTo(holey, 1)); +const shortened = [1, 2, 3, 4, 5, 6]; +shortened.length = 3; +shortened.length = 6; +console.log(sumTo(shortened, 6), sumTo(shortened, 3)); +console.log(scaleTo(dense, new Array(8).fill(0))); +console.log(scaleTo(dense, [9, 9])); +console.log(scaleTo([1, 2, 3], [])); +console.log(window(dense), window([1, 2, 3, 4, 5, 6])); diff --git a/tests/corpus/7321-speculative-loop-bail-sites.ts b/tests/corpus/7321-speculative-loop-bail-sites.ts new file mode 100644 index 000000000..460595feb --- /dev/null +++ b/tests/corpus/7321-speculative-loop-bail-sites.ts @@ -0,0 +1,111 @@ +// Speculative integer loops whose checks fail: on the first statement of +// every entry (fractional field data), after an effect earlier in the same +// iteration, before a `continue`, `break` or `return`, and on entries +// that alternate between integer and fractional data. A site that keeps +// failing stops trying its integer copy; every result is Node's. + +class Point { + x: number; + y: number; + w = 0; + + constructor(x: number, y: number) { + this.x = x; + this.y = y; + } +} + +function show(label: string, value: number): void { + console.log(label, Object.is(value, -0) ? "-0" : String(value)); +} + +// Each inner entry fails at its first statement when the fields hold +// fractions, and runs no iteration at all for the last point. +function pairs(points: Point[]): number { + let total = 0; + for (let i = 0; i < points.length; i++) { + const p = points[i]!; + let acc = p.w; + for (let j = i + 1; j < points.length; j++) { + const q = points[j]!; + const dx = p.x - q.x; + const dy = p.y - q.y; + const d2 = dx * dx + dy * dy; + acc += d2; + q.w += d2 * 0.5; + } + p.w = acc; + total += acc; + } + return total; +} + +const fractional = [ + new Point(0.5, 1), + new Point(1.25, -2), + new Point(3, 4.75), + new Point(-1.5, 0), +]; +const integral = [new Point(0, 1), new Point(2, -2), new Point(3, 4), new Point(-1, 0)]; +for (let round = 0; round < 12; round++) { + show(`pairs fractional ${round}`, pairs(fractional)); +} +// The same site, now with integer data after it stopped speculating. +show("pairs integral", pairs(integral)); +show("pairs integral again", pairs(integral)); + +// A field write comes before the failing statement: the iteration resumes +// after it and must not repeat it. +function afterEffect(points: Point[], scale: number): number { + let s = 0; + for (let i = 0; i < points.length; i++) { + const p = points[i]!; + p.w += 1; + const k = p.x * scale; + s += k * k; + } + return s; +} +const marks = [new Point(1, 0), new Point(2, 0), new Point(3, 0)]; +show("after effect 2", afterEffect(marks, 2)); +show("after effect 0.5", afterEffect(marks, 0.5)); +show("after effect 3", afterEffect(marks, 3)); +console.log(marks.map((p) => p.w).join(" ")); + +// The failing statement is followed by `continue`, `break` and `return`. +function control(n: number, step: number): number { + let acc = 0; + let i = 0; + while (i < n) { + const v = i * step; + i++; + if (v * v > 400) break; + if ((i & 1) === 0) continue; + acc += v * 3; + if (acc > 1000) return -acc; + } + return acc; +} +for (const step of [1, 0.5, 2, 0.75, 7, 1.5, 3, 0.25, 5, 1.75, 4]) { + show(`control ${step}`, control(40, step)); +} + +// do-while: the check fails part-way through, on some entries only. +function steps(start: number, factor: number): number { + let v = start; + let k = 0; + do { + v = v * factor - k; + k++; + } while (k < 6); + return v; +} +for (let r = 0; r < 20; r++) show(`steps ${r}`, steps(r % 3 === 0 ? r + 0.5 : r, 3)); + +// Overflow past 2^53 on later entries only. +function powers(base: number, n: number): number { + let p = 1; + for (let i = 0; i < n; i++) p = p * base; + return p; +} +for (const n of [3, 10, 40, 80, 5, 60, 2, 70, 1, 90, 0, 4]) show(`powers ${n}`, powers(3, n)); diff --git a/tests/corpus/7322-union-scalar-equality.ts b/tests/corpus/7322-union-scalar-equality.ts new file mode 100644 index 000000000..82e0564fc --- /dev/null +++ b/tests/corpus/7322-union-scalar-equality.ts @@ -0,0 +1,68 @@ +// Strict equality and inequality between a `number | undefined` or +// `boolean | undefined` value and a number or boolean: element reads of +// holes, past the end and of present undefined, NaN, -0 and +0, and +// Object.is, in branches, loops and expressions. + +function zeros(a: number[], at: number[]): string { + const hits: string[] = []; + for (const i of at) { + const v = a[i]; + hits.push(`${i}:${v === 0 ? "eq" : "ne"}${v !== 0 ? "!" : ""}${0 === v ? "r" : ""}`); + } + return hits.join(" "); +} + +const holey: number[] = [0, -0, 1]; +holey[5] = 0; +console.log(zeros(holey, [0, 1, 2, 3, 4, 5, 6, -1])); +console.log(zeros([NaN, 0.5, -1, 0], [0, 1, 2, 3])); + +function nanAndZeros(a: (number | undefined)[]): string { + return a + .map((v) => `${v === -0}${v === 0}${Object.is(v, -0)}${Object.is(v, 0)}${Object.is(v, NaN)}`) + .join(" "); +} +console.log(nanAndZeros([0, -0, NaN, undefined, 1])); + +function flags(a: (boolean | undefined)[]): string { + let t = 0; + let f = 0; + let notTrue = 0; + for (let i = 0; i < a.length + 2; i++) { + if (a[i] === true) t++; + if (a[i] === false) f++; + if (a[i] !== true) notTrue++; + } + return `${t} ${f} ${notTrue}`; +} +const bools: (boolean | undefined)[] = [true, false, undefined, true]; +bools[7] = false; +console.log(flags(bools)); + +// A permutation walk that stops at a zero element, as the flip loops of a +// counting benchmark do. +function walk(p: number[], start: number): number { + let steps = 0; + let at = start; + while (p[at] !== 0 && steps < 20) { + at = p[at]!; + steps++; + } + return steps; +} +console.log(walk([0, 3, 1, 2], 1), walk([1, 2, 3, 0], 0), walk([2, 2, 2], 0)); + +class Slot { + value: number | undefined = undefined; + on: boolean | undefined = undefined; +} +const slots = [new Slot(), new Slot(), new Slot()]; +slots[1]!.value = 0; +slots[1]!.on = true; +slots[2]!.value = -0; +slots[2]!.on = false; +console.log( + slots + .map((s) => `${s.value === 0}${s.value !== 0}${s.on === true}${s.on === false}${s.on !== false}`) + .join(" "), +); diff --git a/tests/corpus/7323-loop-bound-parameter-versions.ts b/tests/corpus/7323-loop-bound-parameter-versions.ts new file mode 100644 index 000000000..cdbb8cfc4 --- /dev/null +++ b/tests/corpus/7323-loop-bound-parameter-versions.ts @@ -0,0 +1,88 @@ +// Functions whose number parameters bound their loops, called with values +// no caller proves to be int32s: integers, fractions, NaN, -0, infinities, +// and integers past the int32 range. Every call prints Node's result, +// including -0 read back through 1 / n, a reassigned parameter, a thrown +// error, a void result and a function passed as a value. + +function show(label: string, value: number): void { + console.log(label, Object.is(value, -0) ? "-0" : String(value)); +} + +function sumTo(n: number): number { + let s = 0; + for (let i = 0; i < n; i++) s += i; + return s; +} + +function fill(n: number, out: number[]): void { + for (let i = 0; i < n; i++) out.push(i * 2); +} + +function sign(n: number): number { + let steps = 0; + for (let i = 0; i < n && steps < 4; i++) steps++; + return 1 / n + steps; +} + +function countdown(n: number, step: number): number { + let k = 0; + while (n > 0) { + n -= step; + k++; + if (k > 100) break; + } + return k * 1000 + n; +} + +function checked(n: number, limit: number): number { + let s = 0; + let over = -1; + for (let i = 0; i <= n; i++) { + if (i > limit && over < 0) over = i; + s += i; + } + if (over >= 0) throw new RangeError(`past ${limit} at ${over}`); + return s; +} + +function fillTo(n: number, out: number[]): number { + for (let i = 0; i < n; i++) out[i] = i * 3; + return out.length; +} + +function window2(a: number[], from: number, to: number): string { + const parts: string[] = []; + for (let i = from; i < to; i++) parts.push(String(a[i])); + return parts.join(","); +} + +// Values arrive as strings and JSON, so no caller proves them int32s. +const inputs: number[] = JSON.parse("[0, 1, 5, 7.5, -3, -0, 2147483647, 2147483648, -2147483649, 1e300]"); +inputs.push(NaN, Infinity, -Infinity, Number("12"), Number.parseFloat("3.25")); + +for (const n of inputs) { + const small = Math.abs(n) > 100 ? (n > 0 ? 3 : -3) : n; + show(`sumTo ${n}`, sumTo(small)); + show(`sign ${n}`, sign(n)); + show(`countdown ${n}`, countdown(small, 2)); + const out: number[] = []; + fill(small, out); + const dense: number[] = []; + const length = fillTo(small, dense); + console.log(`fill ${n}`, out.join(" "), length, dense.join(" ")); +} + +for (const n of [3, 4.5, 6]) { + try { + show(`checked ${n}`, checked(n, 4)); + } catch (e) { + console.log(`checked ${n} threw`, (e as Error).message); + } +} + +const data = [10, 20, 30, 40, 50]; +for (const [from, to] of JSON.parse("[[0, 2], [1.5, 4], [-1, 1], [3, 9], [2, 2]]") as [number, number][]) + console.log(`window ${from}..${to}`, window2(data, from, to)); + +const fns: ((n: number) => number)[] = [sumTo, (n) => sumTo(n) * 2]; +console.log(fns.map((f) => f(Number("4"))).join(" "), [1, 2.5, 3].map(sumTo).join(" ")); diff --git a/tests/corpus/7324-loop-bound-parameter-window-sums.ts b/tests/corpus/7324-loop-bound-parameter-window-sums.ts new file mode 100644 index 000000000..094e9848c --- /dev/null +++ b/tests/corpus/7324-loop-bound-parameter-window-sums.ts @@ -0,0 +1,33 @@ +// Sliding-window sums whose length and width are number parameters read +// from JSON, so no caller proves them int32s: int32 sizes run the +// function's int32 version, and a fractional width, a length past the +// int32 range, -0 and NaN run its ordinary body. + +function windowSums(n: number, width: number, values: number[], out: number[]): number { + let total = 0; + for (let i = 0; i + width <= n; i++) { + let s = 0; + for (let k = 0; k < width; k++) s += values[i + k]!; + out[i] = s; + total += s; + } + return total; +} + +const values: number[] = []; +for (let i = 0; i < 4000; i++) values.push((i * 37) % 101); + +const runs = JSON.parse( + "[[4000, 64, 3], [4000, 1, 2], [100, 2.5, 2], [10, 0, 1], [-0, 3, 1], [4000, 3000000000, 1], [3000000000, 4, 1], [12, 20, 1]]", +) as [number, number, number][]; +runs.push([NaN, 2, 1], [Number("250"), Number("8"), 2]); +for (const [n, width, rounds] of runs) { + const out: number[] = []; + const length = Math.min(Number.isFinite(n) ? n : 0, 4000); + for (let i = 0; i < length; i++) out.push(0); + let total = 0; + // A length past the values reads holes: keep that run within them. + const limit = n > 4000 ? 4000 : n; + for (let r = 0; r < rounds; r++) total += windowSums(limit, width, values, out); + console.log(`${n} ${width} ${rounds}:`, total, out.length, out.slice(0, 3).join(",")); +} diff --git a/tests/corpus/7360-worker-typed-records.ts b/tests/corpus/7360-worker-typed-records.ts new file mode 100644 index 000000000..6749398f3 --- /dev/null +++ b/tests/corpus/7360-worker-typed-records.ts @@ -0,0 +1,37 @@ +import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads"; + +// Typed records posted to a worker and back keep their keys, order and +// values, as in Node: records with optional fields, nested records and a +// record in workerData. +type Point = { x: number; y: number }; +type Job = { id: number; label: string; urgent: boolean; at: Point; note?: string }; +type Reply = { id: number; sum: number; label: string }; + +if (isMainThread) { + const start: Point = { x: 10, y: 20 }; + const worker = new Worker(new URL(import.meta.url), { workerData: start }); + const replies: string[] = []; + worker.on("message", (reply: Reply) => { + replies.push(`${JSON.stringify(reply)} ${Object.keys(reply).join(",")}`); + if (replies.length === 3) { + for (const line of replies) console.log(line); + void worker.terminate(); + } + }); + const jobs: Job[] = [ + { id: 1, label: "a", urgent: false, at: { x: 1, y: 2 } }, + { id: 2, label: "b", urgent: true, at: { x: 3, y: 4 }, note: "n" }, + { id: 3, label: "", urgent: false, at: { x: -1, y: 0.25 } }, + ]; + for (const job of jobs) worker.postMessage(job); +} else { + const origin = workerData as Point; + parentPort!.on("message", (job: Job) => { + const reply: Reply = { + id: job.id, + sum: job.at.x + job.at.y + origin.x + origin.y, + label: `${job.label}${job.urgent ? "!" : ""}${job.note ?? ""}`, + }; + parentPort!.postMessage(reply); + }); +} diff --git a/tests/corpus/7361-message-listeners-share-value.ts b/tests/corpus/7361-message-listeners-share-value.ts new file mode 100644 index 000000000..2a4e287df --- /dev/null +++ b/tests/corpus/7361-message-listeners-share-value.ts @@ -0,0 +1,45 @@ +import { MessageChannel, type MessagePort } from "node:worker_threads"; + +// Listeners of one message share its value, as in Node: a typed listener +// that runs after an untyped one sees the changes the untyped one made, +// and a listener on a discriminated union reads the arm its discriminator +// names. +type Item = { id: number; name: string }; +type Shape = { kind: "circle"; size: number } | { kind: "square"; size: number; corner: string }; + +const lines: string[] = []; +let pending = 0; +const ports: MessagePort[] = []; +function finish(): void { + if (--pending > 0) return; + for (const line of lines) console.log(line); + for (const port of ports) port.close(); +} + +const shared = new MessageChannel(); +ports.push(shared.port1); +shared.port1.on("message", (value: Item) => { + lines.push(`typed first ${value.id} ${value.name}`); +}); +shared.port1.on("message", (value: any) => { + value.id = value.id * 10; + value.name = `${value.name}!`; +}); +shared.port1.on("message", (value: Item) => { + lines.push(`typed after ${value.id} ${value.name}`); + finish(); +}); +pending += 2; +shared.port2.postMessage({ id: 1, name: "a" }); +shared.port2.postMessage({ id: 2, name: "b" }); + +const shapes = new MessageChannel(); +ports.push(shapes.port1); +shapes.port1.on("message", (shape: Shape) => { + if (shape.kind === "circle") lines.push(`circle ${shape.size}`); + else lines.push(`square ${shape.size} ${shape.corner}`); + finish(); +}); +pending += 2; +shapes.port2.postMessage({ kind: "circle", size: 3 }); +shapes.port2.postMessage({ kind: "square", size: 4, corner: "round" }); diff --git a/tests/corpus/7362-globalthis-intersection-singleton.ts b/tests/corpus/7362-globalthis-intersection-singleton.ts new file mode 100644 index 000000000..4c6eb997d --- /dev/null +++ b/tests/corpus/7362-globalthis-intersection-singleton.ts @@ -0,0 +1,46 @@ +// The global-singleton spelling: `globalThis as typeof globalThis & { key?: T }` +// names the global object itself (it also carries the global's own +// WebAssembly member), so a value stored through one view survives the +// call and is visible through every other view. +class Repository { + private items = new Map(); + add(name: string): number { + this.items.set(name, this.items.size + 1); + return this.items.size; + } + get size(): number { + return this.items.size; + } +} + +let constructed = 0; +const repoKey = "__exampleRepo"; +type WithRepo = typeof globalThis & { [repoKey]?: Repository }; + +function repo(): Repository { + const g = globalThis as WithRepo; + g[repoKey] ??= (constructed++, new Repository()); + return g[repoKey]; +} + +repo().add("keyboard"); +repo().add("mouse"); +console.log(constructed, repo().size, repo() === repo()); + +// a named member through a second spelling of the same intersection +const counters = globalThis as typeof globalThis & { exampleHits?: number; exampleLabel?: string }; +counters.exampleHits = 1; +counters.exampleHits += 2; +counters.exampleLabel = "ready"; +console.log( + (globalThis as typeof globalThis & { exampleHits?: number }).exampleHits, + (globalThis as unknown as { exampleLabel?: string }).exampleLabel, +); + +// the view is the global object +console.log(counters.globalThis === globalThis, (globalThis as WithRepo) === globalThis); + +// many reads of the global object in a loop see the same object +let same = 0; +for (let i = 0; i < 1000; i++) if ((globalThis as WithRepo)[repoKey] === repo()) same++; +console.log(same, constructed); diff --git a/tests/corpus/7363-json-stringify-live-capsules.ts b/tests/corpus/7363-json-stringify-live-capsules.ts new file mode 100644 index 000000000..5522ede5f --- /dev/null +++ b/tests/corpus/7363-json-stringify-live-capsules.ts @@ -0,0 +1,73 @@ +// JSON.stringify of typed records and arrays reached through `unknown`: +// members are read from the native values in key order, toJSON receives the +// member key (an index string inside arrays), undefined members drop out of +// objects and become null in arrays, and the key list is fixed before any +// toJSON runs. +interface Product { + id: string; + name: string; + priceCents: number; + tags: string[]; + note?: string; +} + +function stringify(value: unknown, space?: number): string { + return JSON.stringify(value, undefined, space); +} + +const products: Product[] = [ + { id: "p1", name: "Keyboard", priceCents: 12900, tags: ["hardware", "input"] }, + { id: "p2", name: "Quote \"and\" slash \\", priceCents: 0.5, tags: [], note: "café ☕" }, +]; +console.log(stringify({ products, count: products.length })); +console.log(stringify(products, 2)); +const second: Product = products[1]!; +delete second.note; +console.log(stringify(second)); + +class Money { + cents: number; + constructor(cents: number) { + this.cents = cents; + } + toJSON(key: string): string { + return `${key}:${(this.cents / 100).toFixed(2)}`; + } +} +const prices: Money[] = [new Money(100), new Money(2550)]; +console.log(stringify(prices), stringify({ total: new Money(5) })); + +const numbers: number[] = [1, -0, NaN, Infinity, 2.5, 1e21]; +console.log(stringify(numbers)); +const maybe: (string | undefined)[] = ["a", undefined, "c"]; +console.log(stringify(maybe), stringify({ maybe })); +const nested: number[][] = [[1, 2], [], [3]]; +console.log(stringify(nested, 1)); + +// a toJSON that deletes a later optional field: the field was present when +// the key list was taken, so its (now undefined) value is dropped +interface Order { + first: { toJSON(): string }; + note?: string; +} +const order: Order = { first: { toJSON: () => "x" }, note: "kept?" }; +order.first = { + toJSON: () => { + delete order.note; + return "first"; + }, +}; +console.log(stringify(order)); + +// circular structures through capsules report the path +interface Node { + name: string; + children: Node[]; +} +const root: Node = { name: "root", children: [] }; +root.children.push({ name: "leaf", children: [root] }); +try { + stringify(root); +} catch (error) { + console.log((error as Error).message); +} diff --git a/tests/corpus/7380-iterable-values.ts b/tests/corpus/7380-iterable-values.ts new file mode 100644 index 000000000..0c4284285 --- /dev/null +++ b/tests/corpus/7380-iterable-values.ts @@ -0,0 +1,122 @@ +// Iterable values: an array, Set, Map or string stays the same object +// (multi-pass, same identity, same inspection), and a generator or a +// Map/Set/array iterator stays single-pass. for-of, spread, Array.from and +// the Set/Map constructors consume every source. + +function sum(xs: Iterable): number { + let s = 0; + for (const x of xs) s += x; + return s; +} + +function* nums(): Generator { + yield 10; + yield 20; +} + +const arr = [1, 2, 3]; +const scores = new Map([ + ["a", 4], + ["b", 5], +]); +console.log(sum(arr), sum(new Set([1, 1, 2])), sum(scores.values()), sum(nums()), sum(arr.values())); + +// An array stays the same multi-pass object. +const it: Iterable = arr; +console.log(sum(it), sum(it), it === arr, typeof it, it); + +// A generator stays single-pass. +const once: Iterable = nums(); +console.log(sum(once), sum(once), typeof once); + +console.log([...it], Array.from(nums() as Iterable), new Set(it).size); + +// A function returning either a collection iterator or a fresh array. +function pick(rows: Map, ids: string[] | null): Iterable { + if (ids === null) return rows.values(); + const out: number[] = []; + for (const id of ids) out.push(rows.get(id) ?? 0); + return out; +} +let total = 0; +for (const v of pick(scores, null)) total += v; +for (const v of pick(scores, ["b", "b", "z"])) total += v; +console.log(total); + +// Strings iterate by code point; Maps iterate [key, value] entries. +function upper(s: Iterable): string[] { + const out: string[] = []; + for (const w of s) out.push(w.toUpperCase()); + return out; +} +console.log(upper("héllo😀"), upper(["a", "b"]), upper(new Set(["x"]))); +function pairs(p: Iterable<[string, number]>): string { + let out = ""; + for (const [k, v] of p) out += `${k}=${v};`; + return out; +} +console.log(pairs(scores), pairs([["x", 1]]), pairs(scores.entries()), pairs(new Set<[string, number]>([["s", 9]]))); + +// Constructors and Object.fromEntries take any Iterable. +function toMap(p: Iterable<[string, number]>): Map { + return new Map(p); +} +function toSet(xs: Iterable): Set { + return new Set(xs); +} +console.log(toMap([["a", 1], ["b", 2]]), toMap(scores), Object.fromEntries(toMap(new Set<[string, number]>([["c", 3]])))); +console.log(toSet([3, 3, 4]), toSet(new Set([9])), toSet(nums())); + +// Fields, generator functions declared to return Iterable, nested Iterables. +class Holder { + source: Iterable; + constructor(source: Iterable) { + this.source = source; + } + joined(): string { + let out = ""; + for (const s of this.source) out += s; + return out; + } +} +const holder = new Holder(["a", "b"]); +console.log(holder.joined(), holder.joined()); +holder.source = new Set(["x", "y"]); +console.log(holder.joined(), holder); + +function* range(n: number): Iterable { + for (let i = 0; i < n; i++) yield i; +} +console.log([...range(4)], sum(range(5))); + +const grid: Iterable[] = [[1, 2], new Set([3]), range(3)]; +let cells = 0; +for (const row of grid) for (const c of row) cells += c; +console.log(cells, grid.length); + +// A checked cast of an iterator value. +const entries = new Map([["k", 1]]).entries() as Iterable<[string, number]>; +console.log(toMap(entries)); + +// Optional Iterables narrow to the Iterable once proven present. +function totalOf(xs?: Iterable): number { + if (xs === undefined) return -1; + let s = 0; + for (const x of xs) s += x; + return s; +} +function orEmpty(xs: Iterable | null): number[] { + return xs === null ? [] : [...xs]; +} +console.log(totalOf(), totalOf([1, 2]), totalOf(new Set([5])), orEmpty(null), orEmpty(range(2))); +const byName = new Map>([ + ["a", [1, 2]], + ["b", new Set([3])], +]); +for (const k of ["a", "b", "c"]) { + const got = byName.get(k); + if (got !== undefined) console.log(k, [...got]); + else console.log(k, "none"); +} +const top = byName.get("a"); +console.log(top !== undefined ? [...top] : "none", byName); diff --git a/tests/corpus/7381-iterable-forof-semantics.ts b/tests/corpus/7381-iterable-forof-semantics.ts new file mode 100644 index 000000000..10f1d1d2f --- /dev/null +++ b/tests/corpus/7381-iterable-forof-semantics.ts @@ -0,0 +1,122 @@ +// for-of over Iterable keeps the semantics of the held source: an array +// is walked live, a generator is closed on break, return and throw (its +// finally blocks run) but not when it is exhausted or throws itself, and +// labels, closures, await and yield work in the loop body. + +function* noisy(tag: string): Generator { + try { + yield 1; + yield 2; + yield 3; + } finally { + console.log("closed", tag); + } +} + +const early: Iterable = noisy("break"); +for (const v of early) { + if (v === 2) break; + console.log("v", v); +} + +function firstOver(src: Iterable, n: number): number | undefined { + for (const x of src) if (x > n) return x; + return undefined; +} +console.log(firstOver([1, 5, 9], 4), firstOver(noisy("return"), 1), firstOver(noisy("exhausted"), 9)); + +try { + for (const v of noisy("throw") as Iterable) { + if (v === 1) throw new Error("boom"); + } +} catch (e) { + console.log("caught", (e as Error).message); +} + +function* failing(): Generator { + try { + yield 1; + throw new RangeError("generator failed"); + } finally { + console.log("failing finally"); + } +} +try { + for (const v of failing() as Iterable) console.log("got", v); +} catch (e) { + console.log(String(e)); +} + +// The array is read live: elements pushed during the walk are visited. +const grow: number[] = [1, 2]; +let visits = 0; +for (const v of grow as Iterable) { + if (grow.length < 5) grow.push(v * 10); + visits++; +} +console.log(visits, grow); + +// Holes read undefined when T holds it. +function show(xs: Iterable): string { + const out: string[] = []; + for (const x of xs) out.push(String(x)); + return out.join(","); +} +console.log(show([1, , 3]), show([undefined, 2])); + +// Labels, closures over the per-iteration binding, try/finally, a class +// declared in the body, and an existing binding as the loop target. +function run(src: Iterable, tag: string): void { + const fns: (() => number)[] = []; + let acc = 0; + outer: for (const x of src) { + fns.push(() => x * 10); + try { + if (x === 2) continue outer; + class Local { + v = x; + twice(): number { + return this.v * 2; + } + } + acc += new Local().twice(); + const inner = (y: number): number => y + x; + acc += inner(1); + } finally { + acc += 100; + } + } + console.log(tag, acc, fns.map((f) => f()).join(",")); +} +function* three(): Generator { + yield 1; + yield 2; + yield 3; +} +run([1, 2, 3], "array"); +run(three(), "generator"); +run(new Set([1, 2, 3]), "set"); + +let product = 0; +outer: for (const a of [1, 2, 3] as Iterable) { + for (const b of new Set([10, 20]) as Iterable) { + if (b === 20) continue outer; + if (a === 3) break outer; + product += a * b; + } +} +let target = 0; +for (target of [7, 8] as Iterable) { +} +console.log(product, target); + +// await and yield inside the loop body. +async function asyncSum(src: Iterable): Promise { + let s = 0; + for (const x of src) s += await Promise.resolve(x); + return s; +} +function* doubled(src: Iterable): Generator { + for (const x of src) yield x * 2; +} +asyncSum([4, 5]).then((v) => console.log("async", v, [...doubled([1, 2])], [...doubled(new Set([7]))])); diff --git a/tests/corpus/7382-iterable-generic-repository.ts b/tests/corpus/7382-iterable-generic-repository.ts new file mode 100644 index 000000000..3e9e62742 --- /dev/null +++ b/tests/corpus/7382-iterable-generic-repository.ts @@ -0,0 +1,57 @@ +// A generic repository whose query candidates are an Iterable: the +// live row map's values() iterator when nothing is indexed, or an array of +// index hits. Methods returning Iterable keep the class compilable. + +interface Row { + readonly id: string; + readonly tag: string; + readonly n: number; +} + +class Repository { + private readonly rows = new Map(); + private readonly index = new Map(); + + private readonly key: (row: T) => string; + + constructor(key: (row: T) => string) { + this.key = key; + } + + insert(row: T): void { + this.rows.set(row.id, row); + const k = this.key(row); + const ids = this.index.get(k); + if (ids === undefined) this.index.set(k, [row.id]); + else ids.push(row.id); + } + + all(): Iterable { + return this.rows.values(); + } + + candidates(key: string | null): Iterable { + if (key === null) return this.rows.values(); + const out: T[] = []; + for (const id of this.index.get(key) ?? []) { + const row = this.rows.get(id); + if (row !== undefined) out.push(row); + } + return out; + } + + query(key: string | null, where: (row: T) => boolean): T[] { + const matches: T[] = []; + for (const row of this.candidates(key)) if (where(row)) matches.push(row); + return matches; + } +} + +const repo = new Repository((row) => row.tag); +for (let i = 0; i < 12; i++) repo.insert({ id: `r${i}`, tag: i % 3 === 0 ? "red" : "blue", n: i * i }); +console.log(repo.query(null, (r) => r.n > 50).map((r) => r.id).join(",")); +console.log(repo.query("red", (r) => r.n % 2 === 0).map((r) => r.id).join(",")); +console.log(repo.query("green", () => true).length, [...repo.all()].length); +let sum = 0; +for (const row of repo.candidates("blue")) sum += row.n; +console.log(sum, Array.from(repo.candidates(null)).slice(0, 2)); diff --git a/tests/corpus/7383-iterable-union-sources.ts b/tests/corpus/7383-iterable-union-sources.ts new file mode 100644 index 000000000..3c393b256 --- /dev/null +++ b/tests/corpus/7383-iterable-union-sources.ts @@ -0,0 +1,51 @@ +// Iterable unions without an array arm, and optional or nullable Iterable +// slots that take a generator whose return channel is not void. + +function* evens(limit: number): Generator { + for (let i = 0; i <= limit; i += 2) yield i; +} + +// A union of a Set and a generator is an iterable union with no array arm: +// for-of walks every arm through the generator loop. +function total(src: Set | Generator): number { + let sum = 0; + for (const v of src) sum += v; + return sum; +} +console.log(total(new Set([1, 2, 3])), total(evens(6))); + +const labelled = (src: Set | Generator): string[] => { + const out: string[] = []; + outer: for (const v of src) { + if (v > 4) break outer; + out.push(`#${v}`); + } + return out; +}; +console.log(labelled(new Set([1, 3, 5])).join(" "), labelled(evens(10)).join(" ")); + +// A generator that returns a value: its return channel is dropped when it +// flows into an Iterable, required, optional or nullable alike. +function* countdown(from: number): Generator { + for (let i = from; i > 0; i--) yield i; + return "liftoff"; +} + +function joined(xs: Iterable): string { + return [...xs].join(","); +} + +function maybeJoined(xs?: Iterable): string { + return xs === undefined ? "none" : [...xs].join(","); +} + +function nullableJoined(xs: Iterable | null): string { + if (xs === null) return "null"; + let out = ""; + for (const x of xs) out += `${x};`; + return out; +} + +console.log(joined(countdown(3))); +console.log(maybeJoined(countdown(2)), maybeJoined(), maybeJoined(undefined), maybeJoined([7, 8])); +console.log(nullableJoined(countdown(4)), nullableJoined(null), nullableJoined(new Set([9]))); diff --git a/tests/corpus/7400-record-keyof-union-read.ts b/tests/corpus/7400-record-keyof-union-read.ts new file mode 100644 index 000000000..4a62a5067 --- /dev/null +++ b/tests/corpus/7400-record-keyof-union-read.ts @@ -0,0 +1,41 @@ +// Keyed reads of records whose fields have different types, with a key +// typed as `keyof` the record: the read is the union of the field types. +interface Book { + readonly id: string; + readonly title: string; + readonly year: number; + readonly tags: readonly string[]; + readonly available: boolean; +} +type BookPatch = Partial>; + +function changedKeys(current: Book, patch: BookPatch): string[] { + const changed: string[] = []; + for (const key of Object.keys(patch) as (keyof BookPatch)[]) { + const before = current[key]; + const after = patch[key]; + if (after === undefined) continue; + if (Array.isArray(before) && Array.isArray(after)) { + if (before.join("|") !== after.join("|")) changed.push(key); + } else if (before !== after) changed.push(key); + } + return changed; +} + +function describe(book: Book, key: keyof Book): string { + const value = book[key]; + if (typeof value === "string") return `${key}: string ${value}`; + if (typeof value === "number") return `${key}: number ${value.toFixed(1)}`; + if (typeof value === "boolean") return `${key}: boolean ${value ? "yes" : "no"}`; + return `${key}: list of ${value.length} [${value.join(", ")}]`; +} + +const book: Book = { id: "b1", title: "Atlas", year: 1999, tags: ["maps", "travel"], available: true }; +console.log(changedKeys(book, { title: "Atlas", year: 2001 })); +console.log(changedKeys(book, { tags: ["maps", "travel"], available: false })); +console.log(changedKeys(book, { tags: ["maps"], title: "Atlas II", year: undefined })); +for (const key of ["id", "title", "year", "tags", "available"] as const) console.log(describe(book, key)); +const keys: (keyof Book)[] = ["year", "tags"]; +const values = keys.map((k) => book[k]); +console.log(values, values.length); +console.log(JSON.stringify(Object.fromEntries(keys.map((k) => [k, book[k]])))); diff --git a/tests/corpus/7401-any-spread-into-typed-literal.ts b/tests/corpus/7401-any-spread-into-typed-literal.ts new file mode 100644 index 000000000..c159a813c --- /dev/null +++ b/tests/corpus/7401-any-spread-into-typed-literal.ts @@ -0,0 +1,32 @@ +// An object literal spreading an untyped (`any`) source into a typed slot +// copies the source's runtime properties, then checks the copy into the +// slot's type like any other `any` value. +interface Filter { + readonly genre?: string; + readonly sort: string; + readonly offset: number; + readonly limit: number; +} + +function untyped(text: string): any { + return JSON.parse(text); +} + +function describe(filter: Filter): string { + return `${filter.genre ?? "(any genre)"} sorted by ${filter.sort}, ${filter.offset}..${filter.offset + filter.limit}`; +} + +function main(): void { + const query = untyped('{"genre":"poetry","sort":"title","offset":20,"limit":10}'); + console.log(describe({ ...query, offset: 0, limit: 100 })); + console.log(describe({ offset: 5, ...query })); + const merged: Filter = { sort: "added", offset: 0, limit: 20, ...untyped('{"limit":3}') }; + console.log(merged.sort, merged.offset, merged.limit, merged.genre === undefined); + const copy: { a: number; b: string } = { ...untyped('{"a":1,"b":"x"}'), b: "y" }; + console.log(copy.a + 1, copy.b, JSON.stringify(copy)); + let latest: { a: number } = { a: 0 }; + latest = { ...untyped('{"a":4}') }; + console.log(latest.a); +} + +main(); diff --git a/tests/corpus/7401-program-lifetime-array-teardown.ts b/tests/corpus/7401-program-lifetime-array-teardown.ts new file mode 100644 index 000000000..64e23118a --- /dev/null +++ b/tests/corpus/7401-program-lifetime-array-teardown.ts @@ -0,0 +1,102 @@ +import type { ProgramLifetime } from "@scriptc/types"; + +// Arrays whose elements need no release when the array is destroyed: +// ProgramLifetime instances (plain and `| undefined` elements), numbers and +// booleans. They are created and dropped by literals, push, slice, filter, +// map, concat, splice, sort and spread, kept in fields, closures and maps, +// nested in other arrays, given holes and far indices, and +// mixed with arrays of ordinary objects, whose elements are released. + +class Node implements ProgramLifetime { + readonly id: number; + next: Node | undefined = undefined; + readonly kids: Node[] = []; + constructor(id: number) { + this.id = id; + } +} + +class Leaf extends Node { + weight = 2; +} + +class Temp { + readonly label: string; + constructor(label: string) { + this.label = label; + } +} + +const nodes: Node[] = []; +for (let i = 0; i < 40; i++) nodes.push(i % 3 === 0 ? new Leaf(i) : new Node(i)); +for (let i = 1; i < nodes.length; i++) nodes[i - 1]!.next = nodes[i]; +for (const n of nodes) for (let k = 1; k <= n.id % 4; k++) n.kids.push(nodes[(n.id + k) % 40]!); + +function ids(list: readonly (Node | undefined)[]): string { + return list.map((n) => (n === undefined ? "-" : String(n.id))).join(","); +} + +// Temporary arrays from every array operation, dropped at once. +let total = 0; +for (let round = 0; round < 200; round++) { + const picked = nodes.filter((n) => n.id % 7 === round % 7); + const mapped = picked.map((n) => n.next); + const joined = picked.concat(nodes.slice(round % 10, (round % 10) + 3)); + const spliced = joined.slice(); + spliced.splice(1, 2, nodes[round % 40]!); + const sorted = [...spliced].sort((a, b) => b.id - a.id); + const optional: (Node | undefined)[] = [nodes[round % 40], undefined, mapped[0]]; + total += picked.length + mapped.length + joined.length + sorted.length + optional.length; + if (round % 50 === 0) console.log(round, ids(sorted), ids(optional), ids(mapped)); +} +console.log("temporaries", total); + +// Numbers and booleans. +let sum = 0; +for (let round = 0; round < 100; round++) { + const values = [round, round * 2, round * 3]; + const flags = values.map((v) => v % 2 === 0); + sum += values.reduce((a, b) => a + b, 0) + flags.filter((f) => f).length; +} +console.log("scalars", sum); + +// Holes and far indices keep the full teardown. +const holey: Node[] = []; +holey[3] = nodes[3]!; +holey[0] = nodes[0]!; +const far: Node[] = [nodes[1]!]; +far[4_000_000_000] = nodes[2]!; +console.log("holey", holey.length, 1 in holey, ids([holey[0], holey[3]])); +console.log("far", far.length, far[4_000_000_000]?.id, far[0]?.id); + +// Kept arrays: a field, a closure, a map, an array of arrays. +class Holder { + items: Node[] = []; +} +const holder = new Holder(); +for (let i = 0; i < 5; i++) holder.items = nodes.slice(i, i + 4); +const later = ((kept: Node[]) => () => ids(kept))(nodes.filter((n) => n instanceof Leaf)); +const byKey = new Map(); +for (let i = 0; i < 10; i++) byKey.set(`k${i % 3}`, nodes.slice(i, i + 2)); +const nested: Node[][] = []; +for (let i = 0; i < 6; i++) nested.push(nodes.slice(i, i + i)); +nested.splice(2, 3); +console.log("field", ids(holder.items)); +console.log("closure", later()); +console.log("map", [...byKey].map(([k, v]) => `${k}:${ids(v)}`).join(" ")); +console.log("nested", nested.map((list) => ids(list)).join(" | ")); + +// Arrays of ordinary objects still release their elements. +let labels = ""; +for (let round = 0; round < 50; round++) { + const temps = [new Temp(`t${round}`), new Temp(`u${round}`)]; + const kept = temps.filter((t) => t.label.endsWith("0")); + labels += kept.map((t) => t.label).join(""); +} +console.log("objects", labels); + +// Kids lists reached through the graph. +let walked = 0; +for (let at: Node | undefined = nodes[0]; at !== undefined; at = at.next) + walked += at.kids.filter((k) => k.id > at!.id).length; +console.log("walked", walked, nodes[39]!.kids.length, (nodes[3] as Leaf).weight); diff --git a/tests/corpus/7420-for-await-close.ts b/tests/corpus/7420-for-await-close.ts new file mode 100644 index 000000000..52930a02c --- /dev/null +++ b/tests/corpus/7420-for-await-close.ts @@ -0,0 +1,100 @@ +// Leaving a for await loop over an async generator early closes it, as +// AsyncIteratorClose does: return, throw and break inside the body, a +// labeled continue to an outer loop, and a return() at a yield in the +// body all await the generator's return(), so its finally runs before the +// loop's caller continues. An exhausted generator and a rejected next() +// are not closed. After a throw, an error from closing is dropped; after +// a break or return it propagates. +const log: string[] = []; + +async function* numbers(tag: string, failClose = false): AsyncGenerator { + try { + yield 1; + yield 2; + yield 3; + } finally { + log.push(`${tag} finally`); + if (failClose) throw new Error(`${tag} close failed`); + } +} + +async function* slowClose(tag: string): AsyncGenerator { + try { + yield 1; + } finally { + await null; + log.push(`${tag} finally after await`); + } +} + +async function firstOf(tag: string): Promise { + for await (const n of numbers(tag)) return n * 10; + return -1; +} + +async function throwsInside(tag: string): Promise { + for await (const n of numbers(tag)) throw new Error(`${tag} body ${n}`); +} + +async function* takeOne(tag: string): AsyncGenerator { + for await (const n of numbers(tag)) { + yield n; + return; + } +} + +async function* rethrowing(tag: string): AsyncGenerator { + for await (const n of numbers(tag)) { + if (n === 2) throw new Error(`${tag} at ${n}`); + yield `${tag} ${n}`; + } +} + +async function main(): Promise { + log.push(`first ${await firstOf("return")}`); + try { + await throwsInside("throw"); + } catch (e) { + log.push(`caught ${(e as Error).message}`); + } + for await (const n of takeOne("generator-return")) log.push(`took ${n}`); + try { + for await (const s of rethrowing("generator-throw")) log.push(s); + } catch (e) { + log.push(`caught ${(e as Error).message}`); + } + const early = takeOne("consumer-return"); + for await (const n of early) { + log.push(`consumer got ${n}`); + break; + } + try { + for await (const n of numbers("break-close-fails", true)) { + log.push(`break at ${n}`); + break; + } + } catch (e) { + log.push(`caught ${(e as Error).message}`); + } + try { + for await (const n of numbers("throw-close-fails", true)) throw new Error(`body ${n}`); + } catch (e) { + log.push(`caught ${(e as Error).message}`); + } + void Promise.resolve().then(() => log.push("microtask")); + for await (const n of slowClose("slow")) { + log.push(`slow ${n}`); + break; + } + log.push("after slow"); + outer: for (const k of [1, 2]) { + for await (const n of numbers(`labeled ${k}`)) { + log.push(`labeled ${k} got ${n}`); + continue outer; + } + } + for await (const n of numbers("exhausted")) log.push(`exhausted ${n}`); + for (const line of log) console.log(line); +} + +void main(); diff --git a/tests/corpus/7421-for-await-close.mjs b/tests/corpus/7421-for-await-close.mjs new file mode 100644 index 000000000..c891a2084 --- /dev/null +++ b/tests/corpus/7421-for-await-close.mjs @@ -0,0 +1,53 @@ +// The same early exits in JavaScript: a for await loop that returns, +// throws or breaks closes its async generator, including one that reaches +// the loop as an untyped parameter, and a source whose return() is still +// running finishes before the code after the loop. +const log = []; + +async function* letters(tag) { + try { + yield "a"; + yield "b"; + } finally { + log.push(`${tag} finally`); + } +} + +async function firstLetter(source) { + for await (const c of source) return c; +} + +async function failOn(source, target) { + for await (const c of source) { + if (c === target) throw new Error(`failed on ${c}`); + log.push(`kept ${c}`); + } +} + +async function* upperUntil(source, stop) { + for await (const c of source) { + if (c === stop) return; + yield c.toUpperCase(); + } +} + +log.push(`first ${await firstLetter(letters("param-return"))}`); +try { + await failOn(letters("param-throw"), "b"); +} catch (e) { + log.push(`caught ${e.message}`); +} +for await (const c of upperUntil(letters("stage-return"), "b")) log.push(`upper ${c}`); +let ticks = 0; +const tick = () => { + log.push(`tick ${ticks}`); + if (++ticks < 4) process.nextTick(tick); +}; +process.nextTick(tick); +for await (const c of letters("break")) { + log.push(`break ${c}`); + break; +} +log.push("after break"); +await new Promise((resolve) => setTimeout(resolve, 1)); +console.log(log.join("\n")); diff --git a/tests/corpus/7422-for-await-untyped-streams.mjs b/tests/corpus/7422-for-await-untyped-streams.mjs new file mode 100644 index 000000000..b7dd21072 --- /dev/null +++ b/tests/corpus/7422-for-await-untyped-streams.mjs @@ -0,0 +1,38 @@ +// for await over a native stream that reaches the loop as an untyped +// value iterates it as a typed loop does, in the same tick order as Node: +// whole reads, an early return (the stream is destroyed), a break, an +// object-mode Transform and a stream error. +import { Readable, PassThrough, Transform } from "node:stream"; +const log = []; +async function readAll(s, tag) { + for await (const c of s) log.push(`${tag} ${typeof c} ${String(c)}`); + log.push(`${tag} done`); +} +async function first(s, tag) { + for await (const c of s) return `${tag} first ${String(c)}`; +} +async function breaks(s, tag) { + for await (const c of s) { log.push(`${tag} got ${String(c)}`); break; } +} +async function failing(s, tag) { + try { for await (const c of s) log.push(`${tag} ${c}`); } catch (e) { log.push(`${tag} caught ${e.message}`); } +} +let n = 0; +const ticker = () => { log.push(`tick ${n}`); if (++n < 6) process.nextTick(ticker); }; +process.nextTick(ticker); +await readAll(Readable.from(["a", "b"]), "arr"); +const r = Readable.from(["x", "y", "z"]); +r.on("close", () => log.push(`r close ${r.destroyed}`)); +log.push(await first(r, "r")); +const pt = new PassThrough(); +pt.on("close", () => log.push("pt close")); +pt.end("bytes"); +await breaks(pt, "pt"); +const t = new Transform({ objectMode: true, transform(c, e, cb) { cb(null, { v: c }); } }); +t.end(1); +await (async (s) => { for await (const c of s) log.push(`t ${JSON.stringify(c)}`); })(t); +const bad = new Readable({ read() { this.destroy(new Error("boom")); } }); +await failing(bad, "bad"); +await readAll(["plain", "array"], "dyn"); +await new Promise((res) => setTimeout(res, 5)); +console.log(log.join("\n")); diff --git a/tests/corpus/7423-stream-untyped-bindings.mjs b/tests/corpus/7423-stream-untyped-bindings.mjs new file mode 100644 index 000000000..23b9e1411 --- /dev/null +++ b/tests/corpus/7423-stream-untyped-bindings.mjs @@ -0,0 +1,33 @@ +// Streams held where the lowering keeps a checked-dynamic value: a +// module-level binding of a stream method's result on a value that a +// JavaScript function returns, an element read of an array of streams, +// and readable.compose on a stream whose function is typed with JSDoc. +import { PassThrough, Readable, Transform } from "node:stream"; + +const words = () => Readable.from(["alpha", "beta"]); +const shouted = words().map((w) => w.toUpperCase()); +console.log("shouted", shouted.readable, shouted.readableObjectMode); +for await (const w of shouted) console.log("shouted", w); + +const counted = words().filter((w) => w.length > 4); +counted.on("data", (w) => console.log("counted", w)); +await new Promise((resolve) => counted.on("end", resolve)); +console.log("counted ended", counted.readableEnded); + +const streams = [new PassThrough({ objectMode: true }), new Transform({ + objectMode: true, + transform(chunk, _enc, cb) { + cb(null, { wrapped: chunk }); + }, +})]; +streams[1].end(7); +for await (const v of streams[1]) console.log("element", JSON.stringify(v)); +streams[0].end("done"); +for await (const v of streams[0]) console.log("element", v); + +/** @returns {Readable} */ +const typedWords = () => Readable.from(["x", "yy"]); +const lengths = typedWords().compose(async function* (source) { + for await (const w of source) yield `${w}:${w.length}`; +}); +console.log("composed", (await lengths.toArray()).join(",")); diff --git a/tests/corpus/7424-duplex-from-streams.mjs b/tests/corpus/7424-duplex-from-streams.mjs new file mode 100644 index 000000000..6f5d43460 --- /dev/null +++ b/tests/corpus/7424-duplex-from-streams.mjs @@ -0,0 +1,47 @@ +// Duplex.from over a lone Readable, a lone Writable and a { readable, +// writable } pair, as duplexify.js's _duplexify wraps them: the Duplex +// reads through the Readable and writes through the Writable, takes each +// side's object mode from the stream behind it, and closes once both ends +// finish; destroying it without an error destroys the streams behind it. +import { Duplex, PassThrough, Readable, Writable } from "node:stream"; +const log = []; +const r = Readable.from(["a", "b"]); +const dr = Duplex.from(r); +log.push(`dr ${dr.readable} ${dr.writable} ${dr.readableObjectMode} ${dr.writableObjectMode}`); +dr.on("end", () => log.push("dr end")); +dr.on("close", () => log.push("dr close")); +for await (const c of dr) log.push(`dr ${c}`); +const got = []; +const w = new Writable({ write(c, e, cb) { got.push(String(c)); log.push(`w write ${c}`); cb(); } }); +const dw = Duplex.from(w); +log.push(`dw ${dw.readable} ${dw.writable} ${dw.writableObjectMode}`); +dw.on("finish", () => log.push("dw finish")); +dw.on("close", () => log.push("dw close")); +dw.write("x", () => log.push("dw cb x")); +dw.end("y", () => log.push("dw end cb")); +await new Promise((res) => dw.on("close", res)); +const inner = new PassThrough({ objectMode: true }); +const out = new PassThrough({ objectMode: true }); +const pair = Duplex.from({ readable: out, writable: inner }); +log.push(`pair ${pair.readable} ${pair.writable} ${pair.readableObjectMode} ${pair.writableObjectMode}`); +inner.on("data", (v) => { log.push(`inner ${JSON.stringify(v)}`); out.write({ echo: v }); }); +inner.on("finish", () => { log.push("inner finish"); out.end(); }); +pair.on("data", (v) => log.push(`pair data ${JSON.stringify(v)}`)); +pair.write({ n: 1 }); +pair.end({ n: 2 }); +await new Promise((res) => pair.on("close", res)); +log.push("pair closed"); +const killed = Duplex.from(new PassThrough()); +killed.on("error", (e) => log.push(`killed error ${e.name}`)); +killed.on("close", () => log.push(`killed close ${killed.destroyed}`)); +killed.destroy(); +await new Promise((res) => setTimeout(res, 5)); +// The pair's members are evaluated in source order; a pair still open at +// exit is left as it is. +const order = []; +const open = Duplex.from({ + writable: (order.push("writable"), new Writable({ write(c, e, cb) { cb(); } })), + readable: (order.push("readable"), Readable.from(["x"])), +}); +log.push(`pair order ${order.join(",")} ${open.readable} ${open.writable}`); +console.log(log.join("\n")); diff --git a/tests/corpus/7425-duplex-from-streams.ts b/tests/corpus/7425-duplex-from-streams.ts new file mode 100644 index 000000000..a9d85b797 --- /dev/null +++ b/tests/corpus/7425-duplex-from-streams.ts @@ -0,0 +1,72 @@ +// Duplex.from over streams in typed code: a Readable that fails destroys +// the Duplex with its error, a slow Writable's callbacks and the end +// callback follow its pace, a pair whose writable member is an async +// generator function's Duplex, compose() with an async function as its +// last stage, and a Duplex over a promise. +import { Duplex, PassThrough, Readable, Writable, compose } from "node:stream"; +const log: string[] = []; +async function main(): Promise { + const failing = new Readable({ read(): void { this.destroy(new Error("source failed")); } }); + const df = Duplex.from(failing); + df.on("error", (e: Error) => log.push(`df error ${e.message}`)); + df.on("close", () => log.push(`df close ${df.destroyed}`)); + df.resume(); + await new Promise((res) => df.on("close", res)); + const slow = new Writable({ + highWaterMark: 2, + write(c: Buffer, _e: string, cb: (err?: Error | null) => void): void { + log.push(`slow write ${c.toString()}`); + setTimeout(cb, 2); + }, + }); + const ds = Duplex.from(slow); + log.push(`write1 ${ds.write("aa", () => log.push("cb aa"))}`); + log.push(`write2 ${ds.write("bb", () => log.push("cb bb"))}`); + ds.on("drain", () => log.push("ds drain")); + ds.end(() => log.push("ds end cb")); + await new Promise((res) => ds.on("finish", res)); + log.push("ds finished"); + const upper = new PassThrough(); + const dp = Duplex.from({ + readable: Readable.from(["r1", "r2"]), + writable: async function* (source: AsyncIterable): AsyncGenerator { + for await (const c of source) log.push(`gen got ${String(c)}`); + yield "unused"; + }, + }); + dp.on("data", (c: unknown) => log.push(`dp data ${String(c)}`)); + dp.write("w1"); + dp.end(); + await new Promise((res) => dp.on("end", res)); + upper.end(); + await more(); + for (const line of log) console.log(line); +} +async function more(): Promise { + const sink = compose(new PassThrough({ objectMode: true }), async function (source: AsyncIterable): Promise { + for await (const c of source) log.push(`sink ${String(c)}`); + }); + log.push(`sink r=${sink.readable} w=${sink.writable}`); + sink.write("p"); + sink.end("q"); + await new Promise((res) => sink.on("finish", res)); + log.push("sink finished"); + const fromReadable: Duplex = Duplex.from(Readable.from([1, 2])); + const values: unknown[] = []; + for await (const v of fromReadable) values.push(v); + log.push(`readable ${JSON.stringify(values)}`); + const written: string[] = []; + const target = new Writable({ + write(c: Buffer, _e: string, cb: (err?: Error | null) => void): void { + written.push(c.toString()); + cb(); + }, + }); + const fromWritable: Duplex = Duplex.from(target); + fromWritable.end("only"); + await new Promise((res) => fromWritable.on("finish", res)); + log.push(`writable ${written.join(",")}`); + const value: Duplex = Duplex.from(Promise.resolve("resolved")); + for await (const v of value) log.push(`promise ${String(v)}`); +} +void main(); diff --git a/tests/corpus/7426-duplex-from-promise.mjs b/tests/corpus/7426-duplex-from-promise.mjs new file mode 100644 index 000000000..46d19586b --- /dev/null +++ b/tests/corpus/7426-duplex-from-promise.mjs @@ -0,0 +1,27 @@ +// Duplex.from over a promise: a Duplex that is not writable and reads the +// promise's value once it settles (nothing for null), then ends; a +// rejection destroys it with the reason. The events interleave with +// microtasks and nextTick callbacks as in Node. +import { Duplex } from "node:stream"; +const log = []; +const tick = (n) => { if (n < 5) { log.push(`tick ${n}`); process.nextTick(() => tick(n + 1)); } }; +const later = (v, ms) => new Promise((res) => setTimeout(() => res(v), ms)); +const a = Duplex.from(Promise.resolve({ answer: 42 })); +log.push(`a ${a.readable} ${a.writable} ${a.readableObjectMode}`); +a.on("data", (v) => log.push(`a data ${JSON.stringify(v)}`)); +a.on("end", () => log.push("a end")); +a.on("close", () => log.push("a close")); +Promise.resolve().then(() => log.push("microtask 1")).then(() => log.push("microtask 2")); +tick(0); +await new Promise((res) => a.on("close", res)); +const b = Duplex.from(later(null, 1)); +b.on("data", () => log.push("b data")); +b.on("end", () => log.push("b end")); +await new Promise((res) => b.on("close", res)); +const c = Duplex.from(Promise.reject(new Error("nope"))); +c.on("error", (e) => log.push(`c error ${e.message}`)); +c.on("close", () => log.push(`c close ${c.destroyed}`)); +await new Promise((res) => c.on("close", res)); +const d = Duplex.from(later("text", 1)); +for await (const v of d) log.push(`d ${v}`); +console.log(log.join("\n")); diff --git a/tests/corpus/7427-duplex-from-async-function.mjs b/tests/corpus/7427-duplex-from-async-function.mjs new file mode 100644 index 000000000..66ce35f9a --- /dev/null +++ b/tests/corpus/7427-duplex-from-async-function.mjs @@ -0,0 +1,40 @@ +// Duplex.from over an async function: a Duplex that is only writable, whose +// writes reach the function's source and whose end waits for the +// function's promise. A value other than null or undefined is +// ERR_INVALID_RETURN_VALUE, a return before the input is consumed aborts +// the Duplex, and a throw destroys it. +import { Duplex } from "node:stream"; +const log = []; +const sink = Duplex.from(async function (source) { + for await (const c of source) log.push(`sink got ${c}`); + log.push("sink done"); +}); +log.push(`sink ${sink.readable} ${sink.writable} ${sink.writableObjectMode}`); +sink.on("finish", () => log.push("sink finish")); +sink.on("close", () => log.push("sink close")); +sink.write("a", () => log.push("cb a")); +sink.end("b", () => log.push("end cb")); +await new Promise((res) => sink.on("close", res)); +const bad = Duplex.from(async function (source) { + for await (const c of source) log.push(`bad got ${c}`); + return 5; +}); +bad.on("error", (e) => log.push(`bad error ${e.code} ${e.message}`)); +bad.on("close", () => log.push("bad close")); +bad.end("x"); +await new Promise((res) => bad.on("close", res)); +const early = Duplex.from(async function (source) { + for await (const c of source) { log.push(`early got ${c}`); break; } +}); +early.on("error", (e) => log.push(`early error ${e.name}`)); +early.on("close", () => log.push(`early close ${early.destroyed}`)); +early.write("1"); +early.write("2"); +await new Promise((res) => early.on("close", res)); +const failing = Duplex.from(async function (source) { + for await (const c of source) throw new Error("fail " + c); +}); +failing.on("error", (e) => log.push(`failing error ${e.message}`)); +failing.write("z"); +await new Promise((res) => failing.on("close", res)); +console.log(log.join("\n")); diff --git a/tests/corpus/7428-web-stream-sources.mjs b/tests/corpus/7428-web-stream-sources.mjs new file mode 100644 index 000000000..72d98e5f8 --- /dev/null +++ b/tests/corpus/7428-web-stream-sources.mjs @@ -0,0 +1,41 @@ +// A web ReadableStream as an async iterable source: Readable.from reads +// its chunks through the stream's iterator (pull-based and start-based +// sources, Uint8Array chunks in byte mode, an error from the controller, +// and an early destroy that cancels the stream), and it heads compose() +// and pipeline() like any async iterable. +import { Readable, Writable, compose, pipeline } from "node:stream"; +const log = []; +let n = 0; +const pulled = new ReadableStream({ + pull(c) { n++; log.push(`pull ${n}`); if (n <= 3) c.enqueue(`p${n}`); else c.close(); }, + cancel(reason) { log.push(`cancel ${reason}`); }, +}); +for await (const c of Readable.from(pulled)) log.push(`got ${c}`); +const bytes = new ReadableStream({ start(c) { c.enqueue(new TextEncoder().encode("hi")); c.enqueue(new TextEncoder().encode("!")); c.close(); } }); +const br = Readable.from(bytes, { objectMode: false }); +br.on("data", (b) => log.push(`bytes ${Buffer.isBuffer(b)} ${b.toString()}`)); +await new Promise((res) => br.on("end", res)); +const failing = new ReadableStream({ start(c) { c.enqueue("ok"); c.error(new Error("web failed")); } }); +const fr = Readable.from(failing); +fr.on("data", (c) => log.push(`failing data ${c}`)); +fr.on("error", (e) => log.push(`failing error ${e.message}`)); +await new Promise((res) => fr.on("close", res)); +let m = 0; +const endless = new ReadableStream({ + pull(c) { c.enqueue(`e${++m}`); }, + cancel(reason) { log.push(`endless cancel ${reason === undefined ? "undefined" : reason}`); }, +}); +const er = Readable.from(endless); +er.once("data", (c) => { log.push(`endless ${c}`); er.destroy(); }); +await new Promise((res) => er.on("close", res)); +await new Promise((res) => setTimeout(res, 5)); +const head = compose(new ReadableStream({ start(c) { c.enqueue("c1"); c.enqueue("c2"); c.close(); } }), async function* (s) { for await (const c of s) yield `${c}!`; }); +log.push(`compose ${(await head.toArray()).join(",")}`); +await new Promise((resolve) => + pipeline( + new ReadableStream({ start(c) { c.enqueue("q1"); c.enqueue("q2"); c.close(); } }), + new Writable({ objectMode: true, write(c, e, cb) { log.push(`pipeline ${c}`); cb(); } }), + (err) => { log.push(`pipeline callback ${err}`); resolve(undefined); }, + ), +); +console.log(log.join("\n")); diff --git a/tests/corpus/7429-web-stream-sources.ts b/tests/corpus/7429-web-stream-sources.ts new file mode 100644 index 000000000..8243b6873 --- /dev/null +++ b/tests/corpus/7429-web-stream-sources.ts @@ -0,0 +1,42 @@ +// Web ReadableStreams as sources in typed code: Readable.from over a +// ReadableStream, interleaved with nextTick callbacks, and a +// ReadableStream heading compose() into an async generator. +import { Readable, compose } from "node:stream"; + +const log: string[] = []; + +function words(): ReadableStream { + return new ReadableStream({ + start(controller): void { + controller.enqueue("typed"); + controller.enqueue("web"); + controller.close(); + }, + }); +} + +async function main(): Promise { + let n = 0; + const tick = (): void => { + log.push(`tick ${n}`); + if (++n < 4) process.nextTick(tick); + }; + process.nextTick(tick); + const r = Readable.from(words()); + log.push(`object mode ${r.readableObjectMode}`); + for await (const c of r) log.push(`word ${String(c)}`); + const bytes = new ReadableStream({ + start(controller): void { + controller.enqueue(new TextEncoder().encode("ab")); + controller.enqueue(new TextEncoder().encode("cd")); + controller.close(); + }, + }); + const lengths = compose(bytes, async function* (source: AsyncIterable): AsyncGenerator { + for await (const chunk of source) yield `${chunk.length}`; + }); + log.push(`lengths ${(await lengths.toArray()).join(",")}`); + for (const line of log) console.log(line); +} + +void main(); diff --git a/tests/corpus/7430-readable-from-web.mjs b/tests/corpus/7430-readable-from-web.mjs new file mode 100644 index 000000000..017556f9d --- /dev/null +++ b/tests/corpus/7430-readable-from-web.mjs @@ -0,0 +1,42 @@ +// Readable.fromWeb: a Readable over a web ReadableStream's reader, in +// byte mode by default (Uint8Array chunks arrive as Buffers), in object +// mode, and with an encoding; an early destroy cancels the stream with +// null, and an error from the stream destroys the Readable. Duplex.from +// and compose() over a lone web ReadableStream read it the same way. +import { Duplex, Readable, compose } from "node:stream"; +const log = []; +const tick = (n) => { if (n < 6) { log.push(`tick ${n}`); process.nextTick(() => tick(n + 1)); } }; +const web = new ReadableStream({ start(c) { c.enqueue(new TextEncoder().encode("ab")); c.enqueue(new TextEncoder().encode("cd")); c.close(); } }); +const r = Readable.fromWeb(web); +log.push(`r ${r.readableObjectMode} ${r.readableHighWaterMark}`); +r.on("data", (b) => log.push(`data ${Buffer.isBuffer(b)} ${b.toString()}`)); +r.on("end", () => log.push("end")); +r.on("close", () => log.push("close")); +tick(0); +await new Promise((res) => r.on("close", res)); +const words = new ReadableStream({ start(c) { c.enqueue("x"); c.enqueue("y"); c.close(); } }); +const o = Readable.fromWeb(words, { objectMode: true, highWaterMark: 1 }); +for await (const v of o) log.push(`obj ${v}`); +const text = new ReadableStream({ start(c) { c.enqueue(new TextEncoder().encode("héllo")); c.close(); } }); +const t = Readable.fromWeb(text, { encoding: "utf8" }); +for await (const v of t) log.push(`text ${typeof v} ${v}`); +let m = 0; +const endless = new ReadableStream({ pull(c) { c.enqueue(new Uint8Array([++m])); }, cancel(reason) { log.push(`cancel ${reason && reason.name}`); } }); +const e = Readable.fromWeb(endless); +e.once("data", (b) => { log.push(`endless ${b[0]}`); e.destroy(); }); +e.on("close", () => log.push("endless close")); +await new Promise((res) => e.on("close", res)); +await new Promise((res) => setTimeout(res, 5)); +const failing = new ReadableStream({ start(c) { c.error(new Error("web broke")); } }); +const f = Readable.fromWeb(failing); +f.on("error", (err) => log.push(`failing error ${err.message}`)); +f.on("close", () => log.push("failing close")); +f.resume(); +await new Promise((res) => f.on("close", res)); +const d = Duplex.from(new ReadableStream({ start(c) { c.enqueue(new TextEncoder().encode("dx")); c.close(); } })); +log.push(`d ${d.readable} ${d.writable} ${d.readableObjectMode}`); +d.on("data", (b) => log.push(`d data ${b.toString()}`)); +await new Promise((res) => d.on("close", res)); +const one = compose(new ReadableStream({ start(c) { c.enqueue(new TextEncoder().encode("one")); c.close(); } })); +for await (const b of one) log.push(`one ${b.toString()}`); +console.log(log.join("\n")); diff --git a/tests/corpus/7431-readable-from-web.ts b/tests/corpus/7431-readable-from-web.ts new file mode 100644 index 000000000..23e7d2871 --- /dev/null +++ b/tests/corpus/7431-readable-from-web.ts @@ -0,0 +1,47 @@ +// Readable.fromWeb in typed code: a ReadableStream read as +// Buffers, a ReadableStream in object mode with a highWaterMark of +// 1, and an AbortSignal that destroys the Readable and cancels the stream. +import { Readable } from "node:stream"; + +const log: string[] = []; + +async function main(): Promise { + const bytes = new ReadableStream({ + start(controller): void { + controller.enqueue(new TextEncoder().encode("web")); + controller.enqueue(new TextEncoder().encode("bytes")); + controller.close(); + }, + }); + const r = Readable.fromWeb(bytes); + for await (const chunk of r) log.push(`bytes ${Buffer.isBuffer(chunk)} ${String(chunk)}`); + const words = new ReadableStream({ + start(controller): void { + controller.enqueue("alpha"); + controller.enqueue("beta"); + controller.close(); + }, + }); + const o = Readable.fromWeb(words, { objectMode: true, highWaterMark: 1 }); + log.push(`object mode ${o.readableObjectMode} ${o.readableHighWaterMark}`); + for await (const word of o) log.push(`word ${String(word)}`); + const ac = new AbortController(); + const signal = ac.signal; + let n = 0; + const endless = new ReadableStream({ + pull(controller): void { + controller.enqueue(new Uint8Array([++n])); + }, + cancel(reason: unknown): void { + log.push(`cancelled ${(reason as Error).name}`); + }, + }); + const a = Readable.fromWeb(endless, { signal }); + a.on("error", (e: Error) => log.push(`aborted ${e.name}`)); + a.once("data", () => ac.abort()); + await new Promise((resolve) => a.on("close", () => resolve())); + await new Promise((resolve) => setTimeout(resolve, 5)); + for (const line of log) console.log(line); +} + +void main(); diff --git a/tests/corpus/7432-readable-push-views.mjs b/tests/corpus/7432-readable-push-views.mjs new file mode 100644 index 000000000..9aca435b6 --- /dev/null +++ b/tests/corpus/7432-readable-push-views.mjs @@ -0,0 +1,16 @@ +// readable.push() in byte mode turns a Uint8Array or another typed array +// into a Buffer over the same bytes (Stream._uint8ArrayToBuffer); the +// pushed array itself is left as it was. +import { Readable } from "node:stream"; +const u = new Uint8Array([100, 101]); +const r = new Readable({ read() {} }); +r.push(u); r.push(new Uint16Array([0x6766])); r.push(null); +for await (const b of r) console.log(Buffer.isBuffer(b), b.toString(), b.length); +console.log("source still", Buffer.isBuffer(u)); +const r1 = new Readable({ read() {} }); +r1.push(new Uint8Array([97, 98])); +r1.push(null); +for await (const b of r1) console.log(Buffer.isBuffer(b), b.toString()); +const r2 = new Readable({ read() {} }); +r2.on("data", (b) => console.log("data", Buffer.isBuffer(b), b.toString())); +r2.push(new Uint8Array([99])); r2.push(null); diff --git a/tests/corpus/7433-readable-operator-signal.mjs b/tests/corpus/7433-readable-operator-signal.mjs new file mode 100644 index 000000000..0fc23c2d0 --- /dev/null +++ b/tests/corpus/7433-readable-operator-signal.mjs @@ -0,0 +1,41 @@ +// The Readable operators pass their callbacks { signal } as the second +// argument; map and filter's signal aborts when the options' signal +// does, reduce's signal is aborted once reduce settles, and map may +// return any value. +import { Readable } from "node:stream"; +const log = []; +log.push(JSON.stringify(await Readable.from([1, 2, 3]).map((n) => ({ n, sq: n * n })).toArray())); +log.push(JSON.stringify(await Readable.from(["a", "bb"]).map((s) => s.length).toArray())); +log.push(JSON.stringify(await Readable.from([1, 2]).map((n, { signal }) => `${n}:${signal.aborted}`).toArray())); +log.push(JSON.stringify(await Readable.from([1, 2, 3, 4]).filter(async (n, opts) => n % 2 === 0 && !opts.signal.aborted).toArray())); +log.push(String(await Readable.from([1, 2, 3]).reduce((acc, n, { signal }) => acc + n + (signal.aborted ? 100 : 0), 0))); +let kept; +await Readable.from([1]).reduce((acc, n, { signal }) => { kept = signal; return acc + n; }, 0); +log.push(`reduce signal after ${kept.aborted}`); +let mapKept; +await Readable.from([1]).map((n, { signal }) => { mapKept = signal; return n; }).toArray(); +log.push(`map signal after ${mapKept.aborted}`); +const ac = new AbortController(); +const events = []; +const p = Readable.from([1, 2, 3]).map(async (n, { signal }) => { + signal.addEventListener("abort", () => events.push(`abort ${n}`)); + await new Promise((r) => setTimeout(r, 10)); + return n; +}, { signal: ac.signal }).toArray(); +setTimeout(() => ac.abort(), 5); +try { await p; } catch (e) { log.push(`map aborted ${e.name}`); } +log.push(events.join(",")); +const dyn = [Readable.from([4, 5])][0]; +log.push(JSON.stringify(await dyn.map((n, { signal }) => n + Number(signal.aborted)).toArray())); +let seen = 0; +await Readable.from([5, 6]).forEach((n, { signal }) => { if (signal) seen++; }); +log.push(`forEach ${seen}`); +log.push(String(await Readable.from([1, 2, 3]).some((n, { signal }) => n > 2 && !signal.aborted))); +log.push(String(await Readable.from([1, 2, 3]).find((n, { signal }) => n > 1 && !signal.aborted))); +log.push(String(await Readable.from([1, 2, 3]).every((n, { signal }) => n > 0 && !signal.aborted))); +// A callback forwarded through an untyped parameter gets { signal } too. +const mapWith = (fn) => Readable.from([1, 2]).map(fn).toArray(); +log.push(JSON.stringify(await mapWith((n, { signal }) => `${n}:${signal.aborted}`))); +const reduceWith = (fn) => Readable.from([1, 2]).reduce(fn, 0); +log.push(String(await reduceWith((acc, n, { signal }) => acc + n + (signal.aborted ? 10 : 0)))); +console.log(log.join("\n")); diff --git a/tests/corpus/7434-readable-operator-values.ts b/tests/corpus/7434-readable-operator-values.ts new file mode 100644 index 000000000..49f7a0fa9 --- /dev/null +++ b/tests/corpus/7434-readable-operator-values.ts @@ -0,0 +1,32 @@ +// Typed Readable operators: map returns numbers and records, flatMap +// takes generator functions and sets, the callbacks may declare the +// { signal } argument, and read() on an object-mode stream answers the +// values pushed. +import { Readable } from "node:stream"; +async function* pair(n: number): AsyncGenerator { + yield n; + yield n * 100; +} +function* letters(s: string): Generator { + for (const c of s) yield c; +} +async function main(): Promise { + const squares = await Readable.from([1, 2, 3]).map((n: number) => n * n).toArray(); + const records = await Readable.from(["a", "bb"]).map((s: string) => ({ s, len: s.length })).toArray(); + const pairs = await Readable.from([1, 2]).flatMap(pair).toArray(); + const chars = await Readable.from(["hi"]).flatMap(letters).toArray(); + const sets = await Readable.from([7]).flatMap((n: number) => new Set([n, n + 1])).toArray(); + const signals = await Readable.from([1]).map((n: number, opts?: { signal?: AbortSignal }) => `${n}:${opts?.signal?.aborted}`).toArray(); + const total = await Readable.from([1, 2]).reduce((acc: number, n: number, opts?: { signal?: AbortSignal }) => acc + n + (opts?.signal?.aborted ? 1 : 0), 0); + console.log(JSON.stringify({ squares, records, pairs, chars, sets, signals, total })); + const r = new Readable({ objectMode: true, read(): void {} }); + r.push({ a: 1 }); + r.push(5); + r.push(null); + r.once("readable", () => { + const first: unknown = r.read(); + const second: unknown = r.read(); + console.log(JSON.stringify(first), second, r.read()); + }); +} +void main(); diff --git a/tests/corpus/7435-readable-flatmap-iterables.mjs b/tests/corpus/7435-readable-flatmap-iterables.mjs new file mode 100644 index 000000000..f0ee79b5a --- /dev/null +++ b/tests/corpus/7435-readable-flatmap-iterables.mjs @@ -0,0 +1,29 @@ +// flatMap over what the callback returns: async and sync generators, a +// Set, a Map, a Readable, and a value that is not iterable (V8's +// TypeError); the generator's steps interleave with process.nextTick as +// in Node, breaking out of the loop runs the inner generator's finally, +// and an inner throw rejects toArray(). +import { Readable } from "node:stream"; +const log = []; +log.push(JSON.stringify(await Readable.from(["x"]).flatMap(async function* (s) { yield s; yield s + s; }).toArray())); +log.push(JSON.stringify(await Readable.from([2]).flatMap(function* (n) { yield n; yield -n; }).toArray())); +log.push(JSON.stringify(await Readable.from([1, 2]).flatMap((n) => new Set([n, n])).toArray())); +log.push(JSON.stringify(await Readable.from(["p"]).flatMap((s) => Readable.from([s, s.toUpperCase()])).toArray())); +log.push(JSON.stringify(await Readable.from([3]).flatMap((n) => new Map([[n, "v"]])).toArray())); +log.push(JSON.stringify(await Readable.from([{ k: 1 }]).flatMap((o) => [o, { k: o.k + 1 }]).toArray())); +try { await Readable.from([1]).flatMap(() => 5).toArray(); } catch (e) { log.push(`${e.name} ${e.message}`); } +try { await Readable.from([1]).flatMap(() => null).toArray(); } catch (e) { log.push(`${e.name} ${e.message}`); } +const order = []; +let n = 0; +const tick = () => { order.push(`t${n}`); if (++n < 5) process.nextTick(tick); }; +process.nextTick(tick); +for await (const v of Readable.from([1]).flatMap(async function* (k) { order.push("gen start"); yield k; order.push("gen mid"); yield k + 1; })) order.push(`v${v}`); +log.push(order.join(" ")); +const closed = []; +const early = Readable.from([1, 2]).flatMap(async function* (k) { try { yield k; yield k * 10; } finally { closed.push(`finally ${k}`); } }); +for await (const v of early) { closed.push(`got ${v}`); break; } +log.push(closed.join(" ")); +const thrown = []; +try { await Readable.from([1]).flatMap(async function* () { yield 1; throw new Error("inner boom"); }).toArray(); } catch (e) { thrown.push(e.message); } +log.push(thrown.join(" ")); +console.log(log.join("\n")); diff --git a/tests/corpus/7436-readable-read-any-value.mjs b/tests/corpus/7436-readable-read-any-value.mjs new file mode 100644 index 000000000..5e19b16c8 --- /dev/null +++ b/tests/corpus/7436-readable-read-any-value.mjs @@ -0,0 +1,17 @@ +// readable.read() answers any value on an object-mode stream, and a +// Buffer or a string (with an encoding) in byte mode. +import { Readable, PassThrough } from "node:stream"; +const r = new Readable({ objectMode: true, read() {} }); +r.push({ a: 1 }); r.push(2); r.push("three"); r.push([4]); r.push(null); +r.once("readable", () => { let v; while ((v = r.read()) !== null) console.log("read", JSON.stringify(v)); }); +const p = new PassThrough({ objectMode: true }); +p.write([1, 2]); +p.end(); +p.once("readable", () => console.log("pt", JSON.stringify(p.read()), p.read())); +const b = new PassThrough(); +b.end("bytes!"); +b.once("readable", () => { const c = b.read(3); console.log("bytes", Buffer.isBuffer(c), String(c), String(b.read())); }); +const e = new PassThrough(); +e.setEncoding("utf8"); +e.end("text"); +e.once("readable", () => { const t = e.read(); console.log("encoded", typeof t, t); }); diff --git a/tests/corpus/7437-duplex-from-signal.mjs b/tests/corpus/7437-duplex-from-signal.mjs new file mode 100644 index 000000000..263225bbb --- /dev/null +++ b/tests/corpus/7437-duplex-from-signal.mjs @@ -0,0 +1,54 @@ +// A Duplex.from body may take { signal } (duplexify.js's fromAsyncGen): +// destroy aborts it with the destroy error, or with an AbortError when +// there is none, and compose passes it to its function stages. +import { Duplex, Readable, compose } from "node:stream"; +import { once } from "node:events"; + +const d = Duplex.from(async function* (source, { signal }) { + console.log("body", typeof signal, signal.aborted); + signal.addEventListener("abort", () => console.log("abort event", signal.aborted, signal.reason)); + for await (const chunk of source) yield String(chunk).toUpperCase(); + console.log("source ended"); +}); +d.on("data", (c) => console.log("data", c)); +d.write("a"); +d.write("b"); +await new Promise((r) => setTimeout(r, 10)); +d.destroy(); +await once(d, "close"); +console.log("closed d"); + +const seen = []; +const fin = Duplex.from(async function (source, { signal }) { + signal.addEventListener("abort", () => console.log("abort", seen.join(","))); + for await (const chunk of source) seen.push(String(chunk)); + console.log("done", signal.aborted); +}); +fin.on("finish", () => console.log("finish")); +fin.write("1"); +fin.write("2"); +fin.end(); +await once(fin, "close"); +console.log("closed fin"); + +const boom = new Error("boom"); +const e = Duplex.from(async function (source, { signal }) { + signal.addEventListener("abort", () => console.log("e abort", String(signal.reason), signal.reason === boom)); + await new Promise((r) => setTimeout(r, 50)); +}); +e.on("error", (err) => console.log("e error", err === boom)); +setTimeout(() => e.destroy(boom), 5); +await new Promise((r) => e.on("close", r)); +console.log("closed e"); + +const c = compose( + async function* (source, { signal }) { + for await (const chunk of source) yield `${chunk}!${signal.aborted}`; + }, + async function* (source, { signal }) { + for await (const chunk of source) yield chunk.toUpperCase(); + }, +); +Readable.from(["a", "b"]).pipe(c); +c.on("data", (x) => console.log("compose", String(x))); +c.on("end", () => console.log("compose end")); diff --git a/tests/corpus/7438-duplex-from-signal.ts b/tests/corpus/7438-duplex-from-signal.ts new file mode 100644 index 000000000..358bd3e68 --- /dev/null +++ b/tests/corpus/7438-duplex-from-signal.ts @@ -0,0 +1,26 @@ +// Typed Duplex.from bodies that declare the options argument: an async +// generator function and an async function. +import { Duplex } from "node:stream"; + +const d = Duplex.from(async function* (source: AsyncIterable, opts: { signal: AbortSignal }) { + opts.signal.addEventListener("abort", () => console.log("aborted", opts.signal.aborted)); + for await (const chunk of source) { + yield `<${chunk}>`; + } +}); +d.on("data", (c: string) => console.log("data", c)); +d.on("end", () => console.log("end")); +d.on("close", () => { + console.log("close"); + const w = Duplex.from(async function (source: AsyncIterable, { signal }: { signal: AbortSignal }): Promise { + let n = 0; + for await (const chunk of source) n += chunk.length; + console.log("total", n, signal.aborted); + }); + w.on("finish", () => console.log("finish")); + w.on("close", () => console.log("w close")); + w.write("abc"); + w.end("de"); +}); +d.write("x"); +d.end("y"); diff --git a/tests/corpus/7439-readable-read-string-chunks.ts b/tests/corpus/7439-readable-read-string-chunks.ts new file mode 100644 index 000000000..2fc5dbed6 --- /dev/null +++ b/tests/corpus/7439-readable-read-string-chunks.ts @@ -0,0 +1,17 @@ +// A typed read() answers the strings a stream holds: the first value a +// lazy Readable.from pull over a parsed array produces, and the decoded +// text once _read calls setEncoding(). +import { Readable } from "node:stream"; +const r = Readable.from(JSON.parse('["j1", "j2"]')); +const chunk = r.read(); +console.log("first", typeof chunk, chunk === null ? "null" : chunk.toString("hex")); +r.once("readable", () => console.log("later", JSON.stringify(r.read()))); +const e = new Readable({ + read() { + this.setEncoding("utf8"); + this.push(Buffer.from("ab")); + this.push(null); + }, +}); +const text = e.read(); +console.log("encoded", typeof text, text === null ? "null" : text.toString("hex")); diff --git a/tests/corpus/7440-fromentries-aliased-entries.ts b/tests/corpus/7440-fromentries-aliased-entries.ts new file mode 100644 index 000000000..f7c4c7e21 --- /dev/null +++ b/tests/corpus/7440-fromentries-aliased-entries.ts @@ -0,0 +1,12 @@ +// `Object.fromEntries(...) as T` over entries whose values are native +// arrays keeps their identity: both fields hold the one array the entries +// name, so a push through one is seen through the other and the original +// (corpus 6467 covers the scalar and checked-dynamic cases). +type Scores = { a: number[]; b: number[] }; +const shared = [10]; +const scores = Object.fromEntries([ + ["a", shared], + ["b", shared], +]) as Scores; +scores.a.push(11); +console.log(shared.length, scores.b.length); diff --git a/tests/corpus/7480-class-call-without-new.ts b/tests/corpus/7480-class-call-without-new.ts new file mode 100644 index 000000000..82b3b8452 --- /dev/null +++ b/tests/corpus/7480-class-call-without-new.ts @@ -0,0 +1,60 @@ +// Function.prototype.call and apply invoke a class constructor without +// `new`, which throws a TypeError naming the class after the arguments are +// evaluated. A declared static `call` answers instead. +class Base { + n = 1; +} +class Derived extends Base {} +class Pair { + left: string; + right: string; + constructor(left: string, right: string) { + this.left = left; + this.right = right; + } +} +class WithCall { + static call(value: number): number { + return value + 1; + } +} + +function report(label: string, run: () => unknown): void { + try { + run(); + console.log(label, "returned"); + } catch (error) { + console.log(label, error instanceof TypeError, (error as Error).message); + } +} + +const receiver = new Base(); +report("call", () => Base.call(receiver)); +report("apply", () => Base.apply(receiver, [])); +report("derived", () => Derived.call(new Derived())); +report("arguments", () => Pair.call(new Pair("a", "b"), "c", "d")); + +const order: string[] = []; +function effect(label: string, value: T): T { + order.push(label); + return value; +} +report("ordered", () => Pair.call(effect("this", new Pair("a", "b")), effect("left", "x"), effect("right", "y"))); +console.log(order.join(",")); + +function local(): void { + class Inner { + x = 2; + } + report("local", () => Inner.call(new Inner())); +} +local(); + +class Statics { + static run(): void { + report("static this", () => this.call(new Statics())); + } +} +Statics.run(); + +console.log(WithCall.call(4)); diff --git a/tests/corpus/7481-class-call-without-new.mjs b/tests/corpus/7481-class-call-without-new.mjs new file mode 100644 index 000000000..4734f0491 --- /dev/null +++ b/tests/corpus/7481-class-call-without-new.mjs @@ -0,0 +1,63 @@ +// An ES5 constructor that calls a class constructor as its base, and the +// other ways of calling a class without `new`, throw Node's TypeError. +class Base { + constructor() { + this.n = 1; + } +} + +function report(label, run) { + try { + run(); + console.log(label, "returned"); + } catch (error) { + console.log(label, error instanceof TypeError, error.message); + } +} + +function Sub() { + Base.call(this); + this.m = 2; +} +report("es5 subclass", () => new Sub()); + +function Applied() { + Base.apply(this, arguments); +} +report("es5 apply", () => new Applied(1, 2)); + +report("apply null", () => Base.apply(null, null)); +report("apply non-object", () => Base.apply(null, 5)); +report("apply array-like", () => Base.apply({}, { length: 1, 0: "a" })); + +const order = []; +function effect(label, value) { + order.push(label); + return value; +} +report("ordered", () => Base.call(effect("this", {}), effect("a", 1), effect("b", 2))); +console.log(order.join(",")); + +function viaValue(C) { + report("value " + C.name, () => C.call({})); +} +class Derived extends Base {} +viaValue(Base); +viaValue(Derived); + +class Configured {} +Configured.defaults = { size: 1 }; +function Wrapped() { + Configured.call(this, Configured.defaults); +} +report("expando statics", () => new Wrapped()); + +const Anonymous = class {}; +report("anonymous", () => Anonymous.call({})); + +class WithCall { + static call(value) { + return "own " + value; + } +} +console.log(WithCall.call(4)); diff --git a/tests/corpus/class-quoted-accessor-keys.mjs b/tests/corpus/class-quoted-accessor-keys.mjs new file mode 100644 index 000000000..637300b43 --- /dev/null +++ b/tests/corpus/class-quoted-accessor-keys.mjs @@ -0,0 +1,26 @@ +// Methods whose quoted names begin with "get:" or "set:", next to an +// accessor of the property after the prefix, read and called through +// untyped values. +class Quoted { + "get:size"() { + return "method get:size"; + } + "set:size"(value) { + return `method set:size ${value}`; + } + get size() { + return 3; + } +} +class Sized { + constructor() { + this.size = 5; + } +} +const values = [new Quoted(), new Sized(), { "get:size": () => "record get:size", size: 1 }]; +for (const value of values) { + const getter = value["get:size"]; + console.log(typeof getter, getter?.call(value)); + console.log(typeof value["set:size"], value.size); + if (value instanceof Quoted) console.log(value["get:size"](), value["set:size"](7)); +} diff --git a/tests/coverage-fixtures/blocked-signature-body.ts b/tests/coverage-fixtures/blocked-signature-body.ts new file mode 100644 index 000000000..2c37484e0 --- /dev/null +++ b/tests/coverage-fixtures/blocked-signature-body.ts @@ -0,0 +1,19 @@ +// Functions whose signatures cannot compile: the report still lists what +// their bodies would report. A use of the blocked parameter names the +// declaration; the body's own unsupported statement reports itself, with +// the reached diagnostics for a function the entry calls and as unreached +// for one nothing calls. +function measure(target: WeakRef, label: string): number { + const extra = new WeakRef({ label }); + console.log(target); + return label.length + (extra === undefined ? 0 : 1); +} +function unused(target: WeakRef): number { + const extra = new WeakRef({ target }); + return extra === undefined ? 0 : 1; +} +console.log(measure(new WeakRef({}), "abc")); +// A declared `this` parameter gives the body its receiver. +function described(this: { label: string }, target: WeakRef): string { + return this.label + String(target); +} diff --git a/tests/coverage-fixtures/startup-fences.js b/tests/coverage-fixtures/startup-fences.js new file mode 100644 index 000000000..22aad4e0a --- /dev/null +++ b/tests/coverage-fixtures/startup-fences.js @@ -0,0 +1,9 @@ +// Deferred fences in a module's top-level code run when the module loads; +// a fence inside a function runs when the function is called. +"use strict"; +var value = JSON.parse("{}"); +console.log(value instanceof Object); +function check(other) { + return other instanceof Object; +} +console.log(check([])); diff --git a/tests/coverage-fixtures/unreached-js-fence.js b/tests/coverage-fixtures/unreached-js-fence.js index 549e633d3..f900e5834 100644 --- a/tests/coverage-fixtures/unreached-js-fence.js +++ b/tests/coverage-fixtures/unreached-js-fence.js @@ -1,8 +1,8 @@ // An exported function nothing on the entry path calls: a statement in it -// that can only fence at runtime still reports its diagnostic, so no -// failed statement goes unexplained. +// that does not compile (a boolean pushed onto the numbers in `items`) +// still reports its diagnostic, so no failed statement goes unexplained. export function collect(values, flag) { - var out = { items: [] }; + var out = { items: [0] }; var x; out.items.push((x = +flag, x * 0 === 0) ? x : flag, !!flag); return out; diff --git a/tests/diagnostics/arguments-length-self-call.ts b/tests/diagnostics/arguments-length-self-call.ts new file mode 100644 index 000000000..3afc2cb33 --- /dev/null +++ b/tests/diagnostics/arguments-length-self-call.ts @@ -0,0 +1,8 @@ +// `arguments.length` in a function expression stored in a slot with more +// parameters counts that slot's arguments, but a call through the +// expression's own name passes only the declared ones: no constant answers +// both, so the read fences. +const count: (a: number, b: number) => number = function self(a: number): number { + return a > 0 ? self(a - 1) + arguments.length : arguments.length; +}; +console.log(count(2, 0)); diff --git a/tests/diagnostics/class-call-shadowed-static.ts b/tests/diagnostics/class-call-shadowed-static.ts new file mode 100644 index 000000000..53a5dc9ad --- /dev/null +++ b/tests/diagnostics/class-call-shadowed-static.ts @@ -0,0 +1,15 @@ +// Through a class value that may hold a subclass, `C.call(...)` reaches the +// subclass's own static `call` when it declares one, so the call is not the +// constructor call that throws Node's TypeError. +class Base { + n = 1; +} +class OwnCall extends Base { + static call(value: unknown): string { + return `own call ${typeof value}`; + } +} +function callThrough(C: typeof Base): unknown { + return C.call(new Base()); +} +console.log(callThrough(OwnCall)); diff --git a/tests/diagnostics/destructuring-fences.ts b/tests/diagnostics/destructuring-fences.ts index e42f8a07a..0ee60579d 100644 --- a/tests/diagnostics/destructuring-fences.ts +++ b/tests/diagnostics/destructuring-fences.ts @@ -38,12 +38,12 @@ interface E1 { } interface E2 { kind: "two"; - b: string; + b: number; label: string; } function fromUnion(u: E1 | E2): string { - const { b } = u; // union source: narrow first - return b; + const { b } = u; // union source whose arms type the field differently: narrow first + return String(b); } console.log(fromUnion({ kind: "one", b: "s", count: 1 })); diff --git a/tests/diagnostics/filter-narrow.ts b/tests/diagnostics/filter-narrow.ts deleted file mode 100644 index 45452e212..000000000 --- a/tests/diagnostics/filter-narrow.ts +++ /dev/null @@ -1,22 +0,0 @@ -// Narrowing filters re-tag ONLY what the runtime test proved: an inferred -// single-arm predicate or filter(Boolean). Everything else stays fenced — -// multi-arm targets (the re-tag doesn't exist), hand-written predicates -// (unchecked assertions), and predicate VALUES (their annotation is -// written by definition). -const xs: (string | number | undefined)[] = ["a", 1, undefined]; - -// Multi-arm narrowing: string | number is not a single arm. -const defined = xs.filter((x) => x !== undefined); -console.log(defined.length); - -// A hand-written predicate on an inline callback. -const ys: (string | undefined)[] = ["a", undefined]; -const strings = ys.filter((x): x is string => typeof x === "string"); -console.log(strings.length); - -// A predicate VALUE (declared function with a written predicate). -function isString(x: string | undefined): x is string { - return typeof x === "string"; -} -const viaValue = ys.filter(isString); -console.log(viaValue.length); diff --git a/tests/diagnostics/fromentries-aliased-entries.ts b/tests/diagnostics/fromentries-aliased-entries.ts deleted file mode 100644 index ee5cc5338..000000000 --- a/tests/diagnostics/fromentries-aliased-entries.ts +++ /dev/null @@ -1,13 +0,0 @@ -// `Object.fromEntries(...) as T` keeps the object only when the entries' -// values are scalars or checked-dynamic values. Native arrays and records -// in the entries would be copied, severing their identity, so the -// assertion keeps the exact-shape fence (corpus 6467 covers the cases that -// lower). -type Scores = { a: number[]; b: number[] }; -const shared = [10]; -const scores = Object.fromEntries([ - ["a", shared], - ["b", shared], -]) as Scores; -scores.a.push(11); -console.log(shared.length, scores.b.length); diff --git a/tests/diagnostics/generic-value-bindings.ts b/tests/diagnostics/generic-value-bindings.ts index a7de7aa1b..7c786c67c 100644 --- a/tests/diagnostics/generic-value-bindings.ts +++ b/tests/diagnostics/generic-value-bindings.ts @@ -60,3 +60,15 @@ function throughParam(a: Amb): void { console.log(a.m(4)); } throughParam(amb); + +// A `var` binding inside a function, declared in a branch and called from +// a closure: when the branch does not run, Node finds the binding undefined. +// The compiled instances have no per-call flag for that, so the call fences. +function branchVar(flag: boolean): number { + if (flag) { + var picked = (x: T): T => x; + } + const invoke = (): number => picked(1); + return invoke(); +} +console.log(branchVar(true)); diff --git a/tests/diagnostics/iterable-sources.ts b/tests/diagnostics/iterable-sources.ts new file mode 100644 index 000000000..c93029cce --- /dev/null +++ b/tests/diagnostics/iterable-sources.ts @@ -0,0 +1,17 @@ +// An Iterable value holds an array, Set, Map, string or iterator. A +// class instance with its own [Symbol.iterator] and a typed array have no +// representation there, so the conversion site reports them by name. +class Countdown implements Iterable { + *[Symbol.iterator](): Iterator { + yield 2; + yield 1; + } +} +function sum(xs: Iterable): number { + let s = 0; + for (const x of xs) s += x; + return s; +} +console.log(sum(new Countdown())); +console.log(sum(new Uint8Array([1, 2]))); +export const marker: number = 1; diff --git a/tests/diagnostics/iterator-slot-fences.ts b/tests/diagnostics/iterator-slot-fences.ts index 759929615..e82437d4d 100644 --- a/tests/diagnostics/iterator-slot-fences.ts +++ b/tests/diagnostics/iterator-slot-fences.ts @@ -1,6 +1,6 @@ // Iterator-typed slots hold generators and built-in collection iterators. -// A class implementing the iterator protocol stays a pointed fence there, -// and Iterable annotations have no lowering yet. +// A class implementing the iterator protocol stays a pointed fence there +// (Iterable values: corpus 7380-7383). class Countdown implements Iterator { n = 2; @@ -12,10 +12,3 @@ function firstOf(it: Iterator): void { console.log(it.next().value); } firstOf(new Countdown()); - -function total(values: Iterable): number { - let sum = 0; - for (const v of values) sum += v; - return sum; -} -console.log(total([1, 2])); diff --git a/tests/diagnostics/jsx-factory-mismatch/main.ts b/tests/diagnostics/jsx-factory-mismatch/main.ts new file mode 100644 index 000000000..47f9ff433 --- /dev/null +++ b/tests/diagnostics/jsx-factory-mismatch/main.ts @@ -0,0 +1,3 @@ +// The factory call a JSX element lowers to must type-check: h takes string children. +import { view } from "./view.js"; +console.log(view); diff --git a/tests/diagnostics/jsx-factory-mismatch/tsconfig.json b/tests/diagnostics/jsx-factory-mismatch/tsconfig.json new file mode 100644 index 000000000..4fcab4d21 --- /dev/null +++ b/tests/diagnostics/jsx-factory-mismatch/tsconfig.json @@ -0,0 +1 @@ +{ "compilerOptions": { "strict": true, "jsx": "react", "jsxFactory": "h" } } diff --git a/tests/diagnostics/jsx-factory-mismatch/view.tsx b/tests/diagnostics/jsx-factory-mismatch/view.tsx new file mode 100644 index 000000000..02bc0a95b --- /dev/null +++ b/tests/diagnostics/jsx-factory-mismatch/view.tsx @@ -0,0 +1,13 @@ +export function h(tag: string, props: object | null, ...children: string[]): string { + return `<${tag}>${children.join("")}`; +} +declare global { + namespace JSX { + type Element = string; + interface IntrinsicElements { + [name: string]: object; + } + } +} +const count = 3; +export const view =

    count: {count}

    ; diff --git a/tests/diagnostics/jsx-preserve/main.ts b/tests/diagnostics/jsx-preserve/main.ts new file mode 100644 index 000000000..1a5a8a0bc --- /dev/null +++ b/tests/diagnostics/jsx-preserve/main.ts @@ -0,0 +1,3 @@ +// "jsx": "preserve" emits JSX unchanged, so there is no call to compile. +import { view } from "./view.js"; +console.log(view); diff --git a/tests/diagnostics/jsx-preserve/tsconfig.json b/tests/diagnostics/jsx-preserve/tsconfig.json new file mode 100644 index 000000000..8bef9f7f4 --- /dev/null +++ b/tests/diagnostics/jsx-preserve/tsconfig.json @@ -0,0 +1 @@ +{ "compilerOptions": { "strict": true, "jsx": "preserve" } } diff --git a/tests/diagnostics/jsx-preserve/view.tsx b/tests/diagnostics/jsx-preserve/view.tsx new file mode 100644 index 000000000..48ce38147 --- /dev/null +++ b/tests/diagnostics/jsx-preserve/view.tsx @@ -0,0 +1,9 @@ +declare global { + namespace JSX { + type Element = string; + interface IntrinsicElements { + [name: string]: object; + } + } +} +export const view =

    kept as JSX

    ; diff --git a/tests/diagnostics/jsx-type-errors/main.ts b/tests/diagnostics/jsx-type-errors/main.ts new file mode 100644 index 000000000..00c4da53b --- /dev/null +++ b/tests/diagnostics/jsx-type-errors/main.ts @@ -0,0 +1,3 @@ +// TypeScript errors in JSX are reported with the positions of the file the program compiles. +import { view } from "./view.js"; +console.log(view); diff --git a/tests/diagnostics/jsx-type-errors/tsconfig.json b/tests/diagnostics/jsx-type-errors/tsconfig.json new file mode 100644 index 000000000..4fcab4d21 --- /dev/null +++ b/tests/diagnostics/jsx-type-errors/tsconfig.json @@ -0,0 +1 @@ +{ "compilerOptions": { "strict": true, "jsx": "react", "jsxFactory": "h" } } diff --git a/tests/diagnostics/jsx-type-errors/view.tsx b/tests/diagnostics/jsx-type-errors/view.tsx new file mode 100644 index 000000000..8a9be99ba --- /dev/null +++ b/tests/diagnostics/jsx-type-errors/view.tsx @@ -0,0 +1,15 @@ +export function h(tag: string | ((props: { count: number }) => string), props: object | null, ...children: string[]): string { + return typeof tag === "string" ? `<${tag}>${children.join("")}` : tag(props as { count: number }); +} +declare global { + namespace JSX { + type Element = string; + interface IntrinsicElements { + p: { title?: string }; + } + } +} +function Count(props: { count: number }): string { + return String(props.count); +} +export const view =

    text

    ; diff --git a/tests/diagnostics/local-class-boundaries.ts b/tests/diagnostics/local-class-boundaries.ts index 2c43e9900..ac1afb2c2 100644 --- a/tests/diagnostics/local-class-boundaries.ts +++ b/tests/diagnostics/local-class-boundaries.ts @@ -1,10 +1,8 @@ function privateBrand() { return class { #value = 1; has(other: object): boolean { return #value in other; } }; } -function selfName() { return class Local { copy() { return new Local(); } }; } class Base {} function derived() { return class extends Base {}; } function generic() { return class { read(value: T): T { return value; } }; } privateBrand(); -selfName(); derived(); generic(); // End of unsupported local-class forms. diff --git a/tests/diagnostics/retired-engine-1123-any-conditional-spread.ts b/tests/diagnostics/retired-engine-1123-any-conditional-spread.ts deleted file mode 100644 index 03043a32f..000000000 --- a/tests/diagnostics/retired-engine-1123-any-conditional-spread.ts +++ /dev/null @@ -1,49 +0,0 @@ -// The conditional-spread idiom inside `any`-typed object literals: -// `{ a, ...(c ? { k: v } : {}) }` builds one of two engine literals behind -// the test, so the key is truly ABSENT when the empty arm is taken — -// engine-exact (`typeof o.k` answers "undefined", JSON drops it), with the -// shared properties evaluating exactly once. - -function opts(aspect: string | undefined): any { - const o: any = { - mode: "M", - ...(aspect ? { cfg: { aspect } } : {}), - }; - return o; -} -const a = opts("1:1"); -console.log(`${a.mode} ${a.cfg.aspect} ${typeof a.cfg}`); -const b = opts(undefined); -console.log(`${b.mode} ${typeof b.cfg}`); - -// Multi-property carrier arms are fine in the island form. -function multi(on: boolean): any { - return { base: 1, ...(on ? { x: "X", y: "Y" } : {}) }; -} -const m1 = multi(true); -const m2 = multi(false); -console.log(`${m1.base} ${m1.x} ${m1.y}`); -console.log(`${m2.base} ${typeof m2.x} ${typeof m2.y}`); - -// Reversed orientation and string-literal keys. -function rev(quiet: boolean): any { - return { kind: "r", ...(quiet ? {} : { "log-level": "loud" }) }; -} -console.log(`${rev(false)["log-level"]}`); -console.log(`${typeof rev(true)["log-level"]}`); - -// The spread mid-literal: properties around it evaluate exactly once and -// land in engine key order. -let sides = 0; -function side(v: number): number { - sides++; - return v; -} -function ordered(flag: boolean): any { - const o: any = { first: side(1), ...(flag ? { mid: 2 } : {}), last: side(3) }; - return o; -} -const o1 = ordered(true); -const o2 = ordered(false); -console.log(`${o1.first} ${o1.mid} ${o1.last}`); -console.log(`${o2.first} ${typeof o2.mid} ${o2.last} ${sides}`); diff --git a/tests/diagnostics/stream-byte-mode-chunk-fences.ts b/tests/diagnostics/stream-byte-mode-chunk-fences.ts new file mode 100644 index 000000000..6afd1d794 --- /dev/null +++ b/tests/diagnostics/stream-byte-mode-chunk-fences.ts @@ -0,0 +1,36 @@ +// A byte-mode stream's write chunks are Buffers: an underscore method +// whose chunk parameter has another type is fenced, and super(undefined) +// passes no options, so the stream is in byte mode. A parameter that +// admits the Buffer (Buffer | string) is not fenced, inline or as a +// method. +import { Writable } from "node:stream"; + +class Numbers extends Writable { + constructor() { + super(undefined); + } + _write(chunk: number, _encoding: BufferEncoding, cb: (err?: Error | null) => void): void { + console.log(chunk); + cb(); + } +} +new Numbers().end("x"); + +const accepted = new Writable({ + write(chunk: Buffer | string, _encoding: BufferEncoding, cb: (err?: Error | null) => void): void { + console.log(typeof chunk === "string" ? chunk : chunk.toString()); + cb(); + }, +}); +accepted.end("z"); + +class Wide extends Writable { + constructor() { + super(undefined); + } + _write(chunk: Buffer | string, _encoding: BufferEncoding, cb: (err?: Error | null) => void): void { + console.log(typeof chunk === "string" ? chunk : chunk.toString()); + cb(); + } +} +new Wide().end("w"); diff --git a/tests/diagnostics/tls-socket-fences.ts b/tests/diagnostics/tls-socket-fences.ts new file mode 100644 index 000000000..948a8312a --- /dev/null +++ b/tests/diagnostics/tls-socket-fences.ts @@ -0,0 +1,20 @@ +// new tls.TLSSocket forms that have no lowering. +import { readFileSync } from "node:fs"; +import * as net from "node:net"; +import * as tls from "node:tls"; + +const cert = readFileSync("cert.pem"); +const key = readFileSync("key.pem"); +const context = tls.createSecureContext({ cert, key }); +function alpn(): string[] { + return ["h2"]; +} + +net.createServer((socket) => { + // The client mode: Node starts no handshake for it. + new tls.TLSSocket(socket, { cert, key }); + // A member after secureContext with side effects. + new tls.TLSSocket(socket, { isServer: true, secureContext: context, ALPNProtocols: alpn() }); + // A secureContext that is not a SecureContext. + new tls.TLSSocket(socket, { isServer: true, secureContext: { cert, key } }); +}); diff --git a/tests/diagnostics/webcrypto-refusals.ts b/tests/diagnostics/webcrypto-refusals.ts index d162872fb..030aa03c0 100644 --- a/tests/diagnostics/webcrypto-refusals.ts +++ b/tests/diagnostics/webcrypto-refusals.ts @@ -1,17 +1,8 @@ -// The native WebCrypto surface is HMAC importKey('raw'), sign and verify, -// and the SHA-1/SHA-2 digests, called directly on crypto.subtle. The 'jwk' -// key format and crypto.subtle or its methods taken as values are refused -// by name; the bundled declarations omit the other SubtleCrypto methods +// The native WebCrypto surface is crypto.subtle's secret-key slice and its +// ECDSA, Ed25519 and RSA algorithms, called directly on crypto.subtle. +// crypto.subtle or its methods taken as values are refused by name; the +// bundled declarations omit the other SubtleCrypto methods // (node-types/fenced.ts pins their fence under @types/node). -const fromJwk = await crypto.subtle.importKey( - "jwk", - { kty: "oct", k: "c2VjcmV0" }, - { name: "HMAC", hash: "SHA-256" }, - false, - ["sign"], -); -console.log(fromJwk.type); - const subtle = crypto.subtle; console.log(typeof subtle); diff --git a/tests/fixtures/node-types/dh.ts b/tests/fixtures/node-types/dh.ts new file mode 100644 index 000000000..0b20b1056 --- /dev/null +++ b/tests/fixtures/node-types/dh.ts @@ -0,0 +1,22 @@ +import { + type DiffieHellman, + type DiffieHellmanGroup, + createDiffieHellman, + createDiffieHellmanGroup, + getDiffieHellman, +} from "node:crypto"; + +const group: DiffieHellmanGroup = getDiffieHellman("modp2"); +const alice: DiffieHellman = createDiffieHellman(group.getPrime(), group.getGenerator()); +const bob: DiffieHellman = createDiffieHellman(group.getPrime("hex"), "hex", 2); +alice.setPrivateKey(Buffer.from("0a0b0c", "hex")); +bob.setPrivateKey("0d0e0f", "hex"); +const alicePublic: Buffer = alice.generateKeys(); +const bobPublic: string = bob.generateKeys("base64"); +const fromAlice: string = alice.computeSecret(bobPublic, "base64", "hex"); +const fromBob: Buffer = bob.computeSecret(alicePublic); +console.log(fromAlice === fromBob.toString("hex"), fromAlice.slice(0, 16), alice.verifyError); +const named: DiffieHellmanGroup = createDiffieHellmanGroup("modp5"); +console.log(named.getPrime().length, named.getGenerator("hex"), bob.getPrivateKey("hex")); +const generated: string = named.generateKeys("hex"); +console.log(generated.length <= 384, named.getPublicKey("hex") === generated); diff --git a/tests/fixtures/node-types/fenced.ts b/tests/fixtures/node-types/fenced.ts index 16a74081f..27e68a618 100644 --- a/tests/fixtures/node-types/fenced.ts +++ b/tests/fixtures/node-types/fenced.ts @@ -69,13 +69,13 @@ http2.createSecureServer({ http2.createSecureServer({ allowHTTP1: true, cert: "pem", key: "pem", streamResetBurst: 1 + 0 }); http2.connect("https://localhost"); /* The crypto surface beyond the lowered slice (randomness, the hash - * chain, the introspection statics): asymmetric-key operations name the - * missing public-key stack, symmetric ciphers the missing cipher stack, - * prime checks theirs, and setFips the FIPS truth (getFips() lowers to 0). */ -import { checkPrimeSync, createCipheriv, generateKeyPair, setFips } from "node:crypto"; -generateKeyPair("rsa", { modulusLength: 2048 }, () => {}); + * chain, the introspection statics): RSA encryption names the lowered + * asymmetric surface, symmetric ciphers the missing cipher stack, the + * secure heap the generic hint, and setFips the FIPS truth (getFips() lowers to 0). */ +import { createCipheriv, publicEncrypt, secureHeapUsed, setFips } from "node:crypto"; +publicEncrypt("key", Buffer.alloc(1)); createCipheriv("aes-128-ccm", Buffer.alloc(16), Buffer.alloc(12), { authTagLength: 16 }); -checkPrimeSync(7n); +secureHeapUsed(); setFips(false); fetch("https://example.invalid/", { integrity: "sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=", @@ -93,23 +93,25 @@ void inspectReadableStream; import { callbackify } from "node:util"; const callbackified = callbackify(async (n: number) => n); void callbackified; -/* Cipheriv values support update(), final(), setAAD(), setAutoPadding(), - * getAuthTag(), and setAuthTag(); the stream.Transform members are fenced. */ -const cipherStream = createCipheriv("aes-128-cbc", Buffer.alloc(16), Buffer.alloc(16)); -cipherStream.on("data", () => {}); /* ECDH on a curve Node knows but the runtime does not implement, and * computeSecret(view, encoding), which answers a Buffer where @types/node * declares a string. */ import { createECDH } from "node:crypto"; createECDH("sect163k1"); createECDH("prime256v1").computeSecret(Buffer.alloc(65), "hex"); -/* WebCrypto beyond the HMAC slice: @types/node declares the whole - * SubtleCrypto surface, and the methods outside importKey, sign, verify - * and digest fence by name. */ -async function encryptWithWebCrypto(key: import("node:crypto").webcrypto.CryptoKey): Promise { - await crypto.subtle.encrypt({ name: "AES-GCM", iv: new Uint8Array(12) }, key, new Uint8Array(1)); +/* DiffieHellman's Object.prototype members, and crypto.diffieHellman over + * asymmetric KeyObjects. */ +import { createDiffieHellman, diffieHellman, type KeyObject } from "node:crypto"; +createDiffieHellman(Buffer.from([23])).toString(); +declare const dhKey: KeyObject; +diffieHellman({ privateKey: dhKey, publicKey: dhKey }); +/* WebCrypto beyond the secret-key slice: @types/node declares the whole + * SubtleCrypto surface, and the methods outside the slice, such as + * getPublicKey, fence by name. */ +async function publicKeyWithWebCrypto(key: import("node:crypto").webcrypto.CryptoKey): Promise { + await crypto.subtle.getPublicKey(key, ["verify"]); } -void encryptWithWebCrypto; +void publicKeyWithWebCrypto; /* Node's navigator global: typeof navigator and navigator.userAgent * compile; the other members fence by name. */ const cores = navigator.hardwareConcurrency; diff --git a/tests/fixtures/node-types/keys.ts b/tests/fixtures/node-types/keys.ts new file mode 100644 index 000000000..ba91f5d18 --- /dev/null +++ b/tests/fixtures/node-types/keys.ts @@ -0,0 +1,43 @@ +import { + type KeyObject, + createPrivateKey, + createPublicKey, + createSign, + createVerify, + generateKeyPair, + generateKeyPairSync, + sign, + verify, +} from "node:crypto"; + +const { publicKey, privateKey } = generateKeyPairSync("ec", { namedCurve: "P-256" }); +const data = Buffer.from("typed keys"); +const signature: Buffer = sign("sha256", data, privateKey); +console.log(publicKey.type, privateKey.asymmetricKeyType, verify("sha256", data, publicKey, signature)); +const pem = privateKey.export({ type: "pkcs8", format: "pem" }); +const parsed: KeyObject = createPrivateKey(pem); +console.log(parsed.equals(privateKey), createPublicKey(parsed).equals(publicKey)); +const pems = generateKeyPairSync("rsa", { + modulusLength: 1024, + publicKeyEncoding: { type: "spki", format: "pem" }, + privateKeyEncoding: { type: "pkcs8", format: "pem" }, +}); +const signer = createSign("SHA256"); +signer.update("typed"); +const hex: string = signer.sign(pems.privateKey, "hex"); +const verifier = createVerify("SHA256"); +verifier.update("typed"); +console.log(pems.publicKey.split("\n")[0], verifier.verify(pems.publicKey, hex, "hex")); +const ed = generateKeyPairSync("ed25519"); +const edSignature: Buffer = sign(null, data, ed.privateKey); +console.log(ed.publicKey.asymmetricKeyType, edSignature.length, verify(null, data, ed.publicKey, edSignature)); +const edJwk = ed.publicKey.export({ format: "jwk" }); +console.log(edJwk.kty, edJwk.crv, createPublicKey({ key: edJwk, format: "jwk" }).equals(ed.publicKey)); +const edDer = generateKeyPairSync("ed25519", { + publicKeyEncoding: { type: "spki", format: "der" }, + privateKeyEncoding: { type: "pkcs8", format: "der" }, +}); +console.log(edDer.publicKey.length, edDer.privateKey.length); +generateKeyPair("rsa", { modulusLength: 1024 }, (err, rsaPublic, rsaPrivate) => { + console.log(err, rsaPublic.asymmetricKeyDetails?.modulusLength, rsaPrivate.type); +}); diff --git a/tests/fixtures/node-types/tls-socket-wrap.ts b/tests/fixtures/node-types/tls-socket-wrap.ts new file mode 100644 index 000000000..4f1272b33 --- /dev/null +++ b/tests/fixtures/node-types/tls-socket-wrap.ts @@ -0,0 +1,31 @@ +// Under @types/node: an http CONNECT handler terminates TLS on the tunnel +// socket with new tls.TLSSocket, and the client runs its handshake inside +// the tunnel with tls.connect({ socket }). +import { readFileSync } from "node:fs"; +import * as http from "node:http"; +import * as net from "node:net"; +import * as tls from "node:tls"; + +const ca = readFileSync("tests/fixtures/server/certs/ca.pem"); +const cert = readFileSync("tests/fixtures/server/certs/localhost.pem"); +const key = readFileSync("tests/fixtures/server/certs/localhost-key.pem"); + +const proxy = http.createServer(); +proxy.on("connect", (req: http.IncomingMessage, socket: net.Socket) => { + socket.write("HTTP/1.1 200 Connection Established\r\n\r\n"); + const secure = new tls.TLSSocket(socket, { isServer: true, cert, key, ALPNProtocols: ["http/1.1"] }); + secure.on("secure", () => console.log("proxy secure", req.url, secure.alpnProtocol)); + secure.on("data", (chunk: Buffer) => secure.end(`intercepted ${chunk.toString()}`)); + secure.on("close", () => proxy.close()); +}); +proxy.listen(0, "127.0.0.1", () => { + const port = (proxy.address() as net.AddressInfo).port; + const raw = net.connect(port, "127.0.0.1", () => raw.write("CONNECT example.test:443 HTTP/1.1\r\n\r\n")); + raw.once("data", () => { + const client = tls.connect({ socket: raw, ca, servername: "localhost", ALPNProtocols: ["http/1.1"] }, () => { + console.log("client secureConnect", client.authorized, client.alpnProtocol); + client.write("hello"); + }); + client.on("data", (data: Buffer) => console.log("client data", data.toString())); + }); +}); diff --git a/tests/fixtures/node-types/webcrypto-ecdsa.ts b/tests/fixtures/node-types/webcrypto-ecdsa.ts new file mode 100644 index 000000000..2ec7cc4a7 --- /dev/null +++ b/tests/fixtures/node-types/webcrypto-ecdsa.ts @@ -0,0 +1,34 @@ +/* WebCrypto ECDSA, Ed25519 and RSA under @types/node: generateKey, exportKey, + * importKey, sign and verify lower to the same native values as under the + * bundled declarations. */ +import type { webcrypto } from "node:crypto"; + +async function main(): Promise { + const data = new TextEncoder().encode("node-types"); + const params: webcrypto.EcKeyGenParams = { name: "ECDSA", namedCurve: "P-384" }; + const pair: webcrypto.CryptoKeyPair = await crypto.subtle.generateKey(params, true, ["sign", "verify"]); + const ecdsa: webcrypto.EcdsaParams = { name: "ECDSA", hash: "SHA-384" }; + const signature = await crypto.subtle.sign(ecdsa, pair.privateKey, data); + console.log(pair.privateKey.type, signature.byteLength, await crypto.subtle.verify(ecdsa, pair.publicKey, signature, data)); + const spki = await crypto.subtle.exportKey("spki", pair.publicKey); + const imported = await crypto.subtle.importKey("spki", spki, { name: "ECDSA", namedCurve: "P-384" }, false, ["verify"]); + const algorithm = imported.algorithm as webcrypto.EcKeyAlgorithm; + console.log(algorithm.name, algorithm.namedCurve, await crypto.subtle.verify(ecdsa, imported, signature, data)); + const jwk: webcrypto.JsonWebKey = await crypto.subtle.exportKey("jwk", pair.privateKey); + console.log(jwk.kty, jwk.crv, jwk.key_ops?.join(",")); + const rsa = await crypto.subtle.generateKey( + { name: "RSA-PSS", modulusLength: 1024, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" }, + false, + ["sign", "verify"], + ); + const pss: webcrypto.RsaPssParams = { name: "RSA-PSS", saltLength: 32 }; + const rsaSignature = await crypto.subtle.sign(pss, rsa.privateKey, data); + console.log(rsaSignature.byteLength, await crypto.subtle.verify(pss, rsa.publicKey, rsaSignature, data)); + const ed = (await crypto.subtle.generateKey("Ed25519", true, ["sign", "verify"])) as webcrypto.CryptoKeyPair; + const edSignature = await crypto.subtle.sign("Ed25519", ed.privateKey, data); + const raw = await crypto.subtle.exportKey("raw", ed.publicKey); + const edPublic = await crypto.subtle.importKey("raw", raw, "Ed25519", true, ["verify"]); + console.log(edPublic.algorithm.name, raw.byteLength, edSignature.byteLength, await crypto.subtle.verify("Ed25519", edPublic, edSignature, data)); +} + +void main(); diff --git a/tests/fixtures/node-types/webcrypto-keys.ts b/tests/fixtures/node-types/webcrypto-keys.ts new file mode 100644 index 000000000..be16271d8 --- /dev/null +++ b/tests/fixtures/node-types/webcrypto-keys.ts @@ -0,0 +1,32 @@ +/* WebCrypto secret keys under @types/node: generateKey, exportKey and + * importKey for HMAC and AES keys, and PBKDF2 key imports, lower to the + * same native values as under the bundled declarations. @types/node + * names the dictionary, key and JSON Web Key types in node:crypto's + * webcrypto namespace. */ +import type { webcrypto } from "node:crypto"; + +async function main(): Promise { + const hmacParams: webcrypto.HmacKeyGenParams = { name: "HMAC", hash: "SHA-256", length: 256 }; + const hmac: webcrypto.CryptoKey = await crypto.subtle.generateKey(hmacParams, true, ["sign", "verify"]); + const hmacAlgorithm = hmac.algorithm as webcrypto.HmacKeyAlgorithm; + console.log(hmac.type, hmacAlgorithm.name, hmacAlgorithm.length, hmacAlgorithm.hash.name, hmac.usages.join(",")); + const raw: ArrayBuffer = await crypto.subtle.exportKey("raw", hmac); + console.log(raw.byteLength); + + const aesParams: webcrypto.AesKeyGenParams = { name: "AES-GCM", length: 192 }; + const aes = await crypto.subtle.generateKey(aesParams, true, ["encrypt", "decrypt"]); + const aesAlgorithm = aes.algorithm as webcrypto.AesKeyAlgorithm; + console.log(aesAlgorithm.name, aesAlgorithm.length, aes.extractable); + const jwk: webcrypto.JsonWebKey = await crypto.subtle.exportKey("jwk", aes); + console.log(jwk.kty, jwk.alg, jwk.ext, jwk.key_ops?.join(","), jwk.k?.length); + const back = await crypto.subtle.importKey("jwk", jwk, "AES-GCM", false, ["decrypt"]); + console.log(back.algorithm.name, back.extractable, back.usages.join(",")); + + const fixed = new Uint8Array(16).fill(9); + const imported = await crypto.subtle.importKey("raw", fixed, { name: "AES-CBC" }, true, ["encrypt"]); + console.log(Buffer.from(await crypto.subtle.exportKey("raw", imported)).toString("hex")); + const password = await crypto.subtle.importKey("raw", new TextEncoder().encode("pw"), "PBKDF2", false, ["deriveBits"]); + console.log(password.algorithm.name, password.extractable, password.usages.join(",")); +} + +void main(); diff --git a/tests/fixtures/npm-static/js-yaml-cli.mjs b/tests/fixtures/npm-static/js-yaml-cli.mjs new file mode 100644 index 000000000..8c958cf80 --- /dev/null +++ b/tests/fixtures/npm-static/js-yaml-cli.mjs @@ -0,0 +1,63 @@ +// The published js-yaml package compiled as static modules: loading, dumping, +// schemas, custom types and the YAMLException errors it throws. +import yaml from "js-yaml"; +const text = ` +# config +name: demo +version: 1.2 +count: 0x1F +octal: 0o17 +neg: -12_000 +flt: 6.02e+23 +inf: .inf +nan: .NaN +on: yes +off: false +nil: ~ +date: 2001-12-14 +stamp: 2001-12-14t21:59:43.10-05:00 +str: "quoted \\u263A \\t tab" +single: 'it''s' +multi: | + line one + line two +folded: >- + folded + text +base: &base { a: 1, b: [x, y] } +derived: + <<: *base + c: 3 +list: + - one + - { k: v } + - [1, 2, 3] + - !!str 123 +set: !!set { a, b } +omap: !!omap [ { x: 1 }, { y: 2 } ] +binary: !!binary aGVsbG8= +`; +const doc = yaml.load(text); +console.log(JSON.stringify(doc, (k, v) => (v instanceof Uint8Array ? Array.from(v) : v))); +console.log(doc.stamp instanceof Date, doc.stamp.toISOString(), doc.date.toISOString(), Object.is(doc.nan, NaN) || Number.isNaN(doc.nan)); +const docs = yaml.loadAll("---\na: 1\n---\nb: 2\n...\n"); +console.log(JSON.stringify(docs)); +const items = []; +yaml.loadAll("--- 1\n--- two\n", (d) => items.push(d)); +console.log(items); +console.log(yaml.dump(doc, { sortKeys: true, lineWidth: 40, skipInvalid: true })); +console.log(yaml.dump({ a: "multi\nline\n", b: " lead", c: "yes", d: "123", e: null, f: [], g: {}, h: "x: y", i: -0, j: 1e21 }, { indent: 4 })); +console.log(yaml.dump([{ deep: { er: [1, { z: true }] } }], { flowLevel: 2 })); +console.log(yaml.dump({ s: "a'b\"c", u: "é☺", long: "word ".repeat(30).trim() }, { quotingType: '"', forceQuotes: true })); +for (const bad of ["a: [1", "a: b: c", "- a\nb: 1", "key: 'open", "a: !!int x", "? a\n? a\n", "&x a: *y"]) { + try { yaml.load(bad); console.log("no error", bad); } + catch (e) { console.log(e.name, "|", e.reason, "|", e.mark && e.mark.line, e.mark && e.mark.column, "|", e.message.split("\n")[0]); console.log(e.toString(true)); console.log(String(e).split("\n").length); } +} +try { yaml.load("a: 1\na: 2"); } catch (e) { console.log(e instanceof yaml.YAMLException, e instanceof Error, e.message); } +console.log(JSON.stringify(yaml.load("a: 1\na: 2", { json: true }))); +console.log(JSON.stringify(yaml.load("x: 1", { schema: yaml.JSON_SCHEMA })), JSON.stringify(yaml.load("x: yes", { schema: yaml.FAILSAFE_SCHEMA })), JSON.stringify(yaml.load("x: yes", { schema: yaml.CORE_SCHEMA }))); +const Point = new yaml.Type("!point", { kind: "sequence", construct: (d) => ({ x: d[0], y: d[1] }), instanceOf: Object, represent: (p) => [p.x, p.y] }); +const schema = yaml.DEFAULT_SCHEMA.extend([Point]); +console.log(JSON.stringify(yaml.load("p: !point [3, 4]", { schema }))); +try { yaml.dump({ f() {} }); } catch (e) { console.log(e.name, e.message); } +console.log(yaml.dump({ f() {}, u: undefined, k: 1 }, { skipInvalid: true })); diff --git a/tests/fixtures/npm-static/smol-toml-cli.mjs b/tests/fixtures/npm-static/smol-toml-cli.mjs new file mode 100644 index 000000000..453e16801 --- /dev/null +++ b/tests/fixtures/npm-static/smol-toml-cli.mjs @@ -0,0 +1,68 @@ +// The published smol-toml package compiled as static modules: parsing every +// value kind, the TomlDate subclass of Date, stringify and TomlError. +import { parse, stringify, TomlDate, TomlError } from "smol-toml"; +const text = ` +# a document +title = "TOML \\"example\\"" +int = +99 +neg = -17 +hex = 0xDEADBEEF +oct = 0o755 +bin = 0b1101 +under = 1_000_000 +float = 6.626e-34 +inf = inf +nan = nan +bool = true +odt1 = 1979-05-27T07:32:00Z +odt2 = 1979-05-27T00:32:00-07:00 +odt3 = 1979-05-27T00:32:00.999999-07:00 +ldt = 1979-05-27T07:32:00 +ld = 1979-05-27 +lt = 07:32:00.123 +space = 1979-05-27 07:32:00Z +literal = 'C:\\Users\\nodejs\\templates' +multi = """ +Roses are red +Violets are blue""" +lmulti = ''' +The first newline is +trimmed in raw strings.''' + +[owner] +name = "Tom" +"quoted key" = 1 +dotted.inner.key = "x" + +[database] +ports = [ 8000, 8001, 8002 ] +data = [ ["delta", "phi"], [3.14] ] +temp_targets = { cpu = 79.5, case = 72.0 } + +[[products]] +name = "Hammer" +sku = 738594937 + +[[products]] + +[[products]] +name = "Nail" +color = "gray" +`; +const doc = parse(text); +console.log(JSON.stringify(doc, null, 1)); +for (const key of ["odt1", "odt2", "odt3", "ldt", "ld", "lt", "space"]) { + const d = doc[key]; + console.log(key, d instanceof Date, d instanceof TomlDate, d.isDateTime(), d.isLocal(), d.isDate(), d.isTime(), d.isValid(), d.toISOString(), Number.isNaN(d.getTime()) ? "NaN" : d.getTime()); +} +console.log(Number.isNaN(doc.nan), doc.inf, typeof doc.hex, doc.under); +console.log(stringify(doc)); +console.log(stringify({ a: new Date(0), b: TomlDate.wrapAsLocalDate(new Date(86400000)), c: new TomlDate("10:20:30"), n: [1, [2, 3]], t: { u: { v: "w" } }, s: "quote\" and \\ backslash", f: 1.5, i: 2, big: 2n ** 40n })); +const d = new TomlDate("2020-02-29T12:00:00+01:00"); +console.log(d.toISOString(), JSON.stringify({ d }), String(d.getUTCHours()), d.valueOf()); +const bad = new TomlDate("not a date"); +console.log(bad.isValid(), Number.isNaN(bad.getTime())); +for (const src of ["a = ", "a = 1\na = 2", "[t]\n[t]", "x = [1,", "k = 1979-13-01", "s = \"unterminated", "= 1", "a = 25:00:00"]) { + try { parse(src); console.log("parsed", JSON.stringify(src)); } + catch (e) { console.log(e instanceof TomlError, e instanceof Error, e.name, e.line, e.column, e.message.split("\n")[0]); } +} diff --git a/tests/fixtures/npm/cases/chalk5-builder/main.ts b/tests/fixtures/npm/cases/chalk5-builder/main.ts new file mode 100644 index 000000000..2a4fff61b --- /dev/null +++ b/tests/fixtures/npm/cases/chalk5-builder/main.ts @@ -0,0 +1,48 @@ +// chalk 5 builders used as values (the package compiles from scriptc's +// built-in shim): builders in function slots and arrays, styles picked at +// run time, builders in record fields called with any number of arguments, +// visible at level 0, chalkStderr, and the root's own call. +import chalk, { Chalk, chalkStderr, type ChalkInstance, type ForegroundColorName } from "chalk"; + +const show = (label: string, value: string): void => { + console.log(label + " " + JSON.stringify(value)); +}; + +const c = new Chalk({ level: 1 }); +const paint: (text: string) => string = c.green; +show("slot", paint("go")); +const styles: ChalkInstance[] = [c.red, c.bold, c.underline.blue]; +show("array", styles.map((style) => style("x")).join("|")); +const byName = (name: ForegroundColorName): ChalkInstance => { + switch (name) { + case "red": + return c.red; + case "green": + return c.green; + default: + return c.white; + } +}; +show("picked", byName("red")("r") + byName("green")("g") + byName("cyan")("w")); +let chain: ChalkInstance = c; +for (const step of ["bold", "italic", "yellow"]) { + chain = step === "bold" ? chain.bold : step === "italic" ? chain.italic : chain.yellow; +} +show("built", chain("chain")); +show("cached", c.red === c.red ? "same" : "different"); +show("nested close", c.red("a" + c.blue("b") + "c" + c.red("d") + "e")); +show("bg nested", c.bgRed("a" + c.bgBlue("b") + "c")); + +const off = new Chalk({ level: 0 }); +show("visible off", off.visible("v") + "|" + off.red.visible("v") + "|" + off.red("plain")); +show("root call", c("a", 1, true) + "|" + c() + "|" + c(undefined) + "|" + c(null, "n")); +show("builder args", c.red(undefined) + "|" + c.red(null) + "|" + c.red(1, 2) + "|" + c.red()); +const theme = { error: c.red, note: c.bold.blue }; +show("field args", theme.error("a", "b") + "|" + theme.note("x", 1, true) + "|" + theme.error("one") + "|" + theme.error()); +show("multiline", c.cyan("one\r\ntwo\nthree")); +show("stderr level", String(chalkStderr.level >= 0)); +show("rgb levels", [1, 2, 3].map((level) => new Chalk({ level: level as 1 | 2 | 3 }).rgb(255, 136, 0)("o")).join("|")); +show("hex bg", new Chalk({ level: 2 }).bgHex("#abcdef")("h") + new Chalk({ level: 1 }).bgHex("123")("i")); +c.level = 0; +show("after level 0", paint("go") + "|" + c.red("r")); +show("default red", chalk.level >= 0 ? "ok" : "bad"); diff --git a/tests/fixtures/npm/cases/chalk5-builder/node_modules/chalk/license b/tests/fixtures/npm/cases/chalk5-builder/node_modules/chalk/license new file mode 100644 index 000000000..fa7ceba3e --- /dev/null +++ b/tests/fixtures/npm/cases/chalk5-builder/node_modules/chalk/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tests/fixtures/npm/cases/chalk5-builder/node_modules/chalk/package.json b/tests/fixtures/npm/cases/chalk5-builder/node_modules/chalk/package.json new file mode 100644 index 000000000..c9e0dc52b --- /dev/null +++ b/tests/fixtures/npm/cases/chalk5-builder/node_modules/chalk/package.json @@ -0,0 +1,83 @@ +{ + "name": "chalk", + "version": "5.6.2", + "description": "Terminal string styling done right", + "license": "MIT", + "repository": "chalk/chalk", + "funding": "https://github.com/chalk/chalk?sponsor=1", + "type": "module", + "main": "./source/index.js", + "exports": "./source/index.js", + "imports": { + "#ansi-styles": "./source/vendor/ansi-styles/index.js", + "#supports-color": { + "node": "./source/vendor/supports-color/index.js", + "default": "./source/vendor/supports-color/browser.js" + } + }, + "types": "./source/index.d.ts", + "sideEffects": false, + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "scripts": { + "test": "xo && c8 ava && tsd", + "bench": "matcha benchmark.js" + }, + "files": [ + "source", + "!source/index.test-d.ts" + ], + "keywords": [ + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "ansi", + "style", + "styles", + "tty", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "devDependencies": { + "@types/node": "^16.11.10", + "ava": "^3.15.0", + "c8": "^7.10.0", + "color-convert": "^2.0.1", + "execa": "^6.0.0", + "log-update": "^5.0.0", + "matcha": "^0.7.0", + "tsd": "^0.19.0", + "xo": "^0.57.0", + "yoctodelay": "^2.0.0" + }, + "xo": { + "rules": { + "unicorn/prefer-string-slice": "off", + "@typescript-eslint/consistent-type-imports": "off", + "@typescript-eslint/consistent-type-exports": "off", + "@typescript-eslint/consistent-type-definitions": "off", + "unicorn/expiring-todo-comments": "off" + } + }, + "c8": { + "reporter": [ + "text", + "lcov" + ], + "exclude": [ + "source/vendor" + ] + } +} diff --git a/tests/fixtures/npm/cases/chalk5-builder/node_modules/chalk/source/index.d.ts b/tests/fixtures/npm/cases/chalk5-builder/node_modules/chalk/source/index.d.ts new file mode 100644 index 000000000..8295d9252 --- /dev/null +++ b/tests/fixtures/npm/cases/chalk5-builder/node_modules/chalk/source/index.d.ts @@ -0,0 +1,325 @@ +// TODO: Make it this when TS suports that. +// import {ModifierName, ForegroundColor, BackgroundColor, ColorName} from '#ansi-styles'; +// import {ColorInfo, ColorSupportLevel} from '#supports-color'; +import { + ModifierName, + ForegroundColorName, + BackgroundColorName, + ColorName, +} from './vendor/ansi-styles/index.js'; +import {ColorInfo, ColorSupportLevel} from './vendor/supports-color/index.js'; + +export interface Options { + /** + Specify the color support for Chalk. + + By default, color support is automatically detected based on the environment. + + Levels: + - `0` - All colors disabled. + - `1` - Basic 16 colors support. + - `2` - ANSI 256 colors support. + - `3` - Truecolor 16 million colors support. + */ + readonly level?: ColorSupportLevel; +} + +/** +Return a new Chalk instance. +*/ +export const Chalk: new (options?: Options) => ChalkInstance; // eslint-disable-line @typescript-eslint/naming-convention + +export interface ChalkInstance { + (...text: unknown[]): string; + + /** + The color support for Chalk. + + By default, color support is automatically detected based on the environment. + + Levels: + - `0` - All colors disabled. + - `1` - Basic 16 colors support. + - `2` - ANSI 256 colors support. + - `3` - Truecolor 16 million colors support. + */ + level: ColorSupportLevel; + + /** + Use RGB values to set text color. + + @example + ``` + import chalk from 'chalk'; + + chalk.rgb(222, 173, 237); + ``` + */ + rgb: (red: number, green: number, blue: number) => this; + + /** + Use HEX value to set text color. + + @param color - Hexadecimal value representing the desired color. + + @example + ``` + import chalk from 'chalk'; + + chalk.hex('#DEADED'); + ``` + */ + hex: (color: string) => this; + + /** + Use an [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set text color. + + @example + ``` + import chalk from 'chalk'; + + chalk.ansi256(201); + ``` + */ + ansi256: (index: number) => this; + + /** + Use RGB values to set background color. + + @example + ``` + import chalk from 'chalk'; + + chalk.bgRgb(222, 173, 237); + ``` + */ + bgRgb: (red: number, green: number, blue: number) => this; + + /** + Use HEX value to set background color. + + @param color - Hexadecimal value representing the desired color. + + @example + ``` + import chalk from 'chalk'; + + chalk.bgHex('#DEADED'); + ``` + */ + bgHex: (color: string) => this; + + /** + Use a [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set background color. + + @example + ``` + import chalk from 'chalk'; + + chalk.bgAnsi256(201); + ``` + */ + bgAnsi256: (index: number) => this; + + /** + Modifier: Reset the current style. + */ + readonly reset: this; + + /** + Modifier: Make the text bold. + */ + readonly bold: this; + + /** + Modifier: Make the text have lower opacity. + */ + readonly dim: this; + + /** + Modifier: Make the text italic. *(Not widely supported)* + */ + readonly italic: this; + + /** + Modifier: Put a horizontal line below the text. *(Not widely supported)* + */ + readonly underline: this; + + /** + Modifier: Put a horizontal line above the text. *(Not widely supported)* + */ + readonly overline: this; + + /** + Modifier: Invert background and foreground colors. + */ + readonly inverse: this; + + /** + Modifier: Print the text but make it invisible. + */ + readonly hidden: this; + + /** + Modifier: Puts a horizontal line through the center of the text. *(Not widely supported)* + */ + readonly strikethrough: this; + + /** + Modifier: Print the text only when Chalk has a color level above zero. + + Can be useful for things that are purely cosmetic. + */ + readonly visible: this; + + readonly black: this; + readonly red: this; + readonly green: this; + readonly yellow: this; + readonly blue: this; + readonly magenta: this; + readonly cyan: this; + readonly white: this; + + /* + Alias for `blackBright`. + */ + readonly gray: this; + + /* + Alias for `blackBright`. + */ + readonly grey: this; + + readonly blackBright: this; + readonly redBright: this; + readonly greenBright: this; + readonly yellowBright: this; + readonly blueBright: this; + readonly magentaBright: this; + readonly cyanBright: this; + readonly whiteBright: this; + + readonly bgBlack: this; + readonly bgRed: this; + readonly bgGreen: this; + readonly bgYellow: this; + readonly bgBlue: this; + readonly bgMagenta: this; + readonly bgCyan: this; + readonly bgWhite: this; + + /* + Alias for `bgBlackBright`. + */ + readonly bgGray: this; + + /* + Alias for `bgBlackBright`. + */ + readonly bgGrey: this; + + readonly bgBlackBright: this; + readonly bgRedBright: this; + readonly bgGreenBright: this; + readonly bgYellowBright: this; + readonly bgBlueBright: this; + readonly bgMagentaBright: this; + readonly bgCyanBright: this; + readonly bgWhiteBright: this; +} + +/** +Main Chalk object that allows to chain styles together. + +Call the last one as a method with a string argument. + +Order doesn't matter, and later styles take precedent in case of a conflict. + +This simply means that `chalk.red.yellow.green` is equivalent to `chalk.green`. +*/ +declare const chalk: ChalkInstance; + +export const supportsColor: ColorInfo; + +export const chalkStderr: typeof chalk; +export const supportsColorStderr: typeof supportsColor; + +export { + ModifierName, ForegroundColorName, BackgroundColorName, ColorName, + modifierNames, foregroundColorNames, backgroundColorNames, colorNames, +// } from '#ansi-styles'; +} from './vendor/ansi-styles/index.js'; + +export { + ColorInfo, + ColorSupport, + ColorSupportLevel, +// } from '#supports-color'; +} from './vendor/supports-color/index.js'; + +// TODO: Remove these aliases in the next major version +/** +@deprecated Use `ModifierName` instead. + +Basic modifier names. +*/ +export type Modifiers = ModifierName; + +/** +@deprecated Use `ForegroundColorName` instead. + +Basic foreground color names. + +[More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support) +*/ +export type ForegroundColor = ForegroundColorName; + +/** +@deprecated Use `BackgroundColorName` instead. + +Basic background color names. + +[More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support) +*/ +export type BackgroundColor = BackgroundColorName; + +/** +@deprecated Use `ColorName` instead. + +Basic color names. The combination of foreground and background color names. + +[More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support) +*/ +export type Color = ColorName; + +/** +@deprecated Use `modifierNames` instead. + +Basic modifier names. +*/ +export const modifiers: readonly Modifiers[]; + +/** +@deprecated Use `foregroundColorNames` instead. + +Basic foreground color names. +*/ +export const foregroundColors: readonly ForegroundColor[]; + +/** +@deprecated Use `backgroundColorNames` instead. + +Basic background color names. +*/ +export const backgroundColors: readonly BackgroundColor[]; + +/** +@deprecated Use `colorNames` instead. + +Basic color names. The combination of foreground and background color names. +*/ +export const colors: readonly Color[]; + +export default chalk; diff --git a/tests/fixtures/npm/cases/chalk5-builder/node_modules/chalk/source/index.js b/tests/fixtures/npm/cases/chalk5-builder/node_modules/chalk/source/index.js new file mode 100644 index 000000000..8bc993da5 --- /dev/null +++ b/tests/fixtures/npm/cases/chalk5-builder/node_modules/chalk/source/index.js @@ -0,0 +1,225 @@ +import ansiStyles from '#ansi-styles'; +import supportsColor from '#supports-color'; +import { // eslint-disable-line import/order + stringReplaceAll, + stringEncaseCRLFWithFirstIndex, +} from './utilities.js'; + +const {stdout: stdoutColor, stderr: stderrColor} = supportsColor; + +const GENERATOR = Symbol('GENERATOR'); +const STYLER = Symbol('STYLER'); +const IS_EMPTY = Symbol('IS_EMPTY'); + +// `supportsColor.level` → `ansiStyles.color[name]` mapping +const levelMapping = [ + 'ansi', + 'ansi', + 'ansi256', + 'ansi16m', +]; + +const styles = Object.create(null); + +const applyOptions = (object, options = {}) => { + if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) { + throw new Error('The `level` option should be an integer from 0 to 3'); + } + + // Detect level if not set manually + const colorLevel = stdoutColor ? stdoutColor.level : 0; + object.level = options.level === undefined ? colorLevel : options.level; +}; + +export class Chalk { + constructor(options) { + // eslint-disable-next-line no-constructor-return + return chalkFactory(options); + } +} + +const chalkFactory = options => { + const chalk = (...strings) => strings.join(' '); + applyOptions(chalk, options); + + Object.setPrototypeOf(chalk, createChalk.prototype); + + return chalk; +}; + +function createChalk(options) { + return chalkFactory(options); +} + +Object.setPrototypeOf(createChalk.prototype, Function.prototype); + +for (const [styleName, style] of Object.entries(ansiStyles)) { + styles[styleName] = { + get() { + const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]); + Object.defineProperty(this, styleName, {value: builder}); + return builder; + }, + }; +} + +styles.visible = { + get() { + const builder = createBuilder(this, this[STYLER], true); + Object.defineProperty(this, 'visible', {value: builder}); + return builder; + }, +}; + +const getModelAnsi = (model, level, type, ...arguments_) => { + if (model === 'rgb') { + if (level === 'ansi16m') { + return ansiStyles[type].ansi16m(...arguments_); + } + + if (level === 'ansi256') { + return ansiStyles[type].ansi256(ansiStyles.rgbToAnsi256(...arguments_)); + } + + return ansiStyles[type].ansi(ansiStyles.rgbToAnsi(...arguments_)); + } + + if (model === 'hex') { + return getModelAnsi('rgb', level, type, ...ansiStyles.hexToRgb(...arguments_)); + } + + return ansiStyles[type][model](...arguments_); +}; + +const usedModels = ['rgb', 'hex', 'ansi256']; + +for (const model of usedModels) { + styles[model] = { + get() { + const {level} = this; + return function (...arguments_) { + const styler = createStyler(getModelAnsi(model, levelMapping[level], 'color', ...arguments_), ansiStyles.color.close, this[STYLER]); + return createBuilder(this, styler, this[IS_EMPTY]); + }; + }, + }; + + const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); + styles[bgModel] = { + get() { + const {level} = this; + return function (...arguments_) { + const styler = createStyler(getModelAnsi(model, levelMapping[level], 'bgColor', ...arguments_), ansiStyles.bgColor.close, this[STYLER]); + return createBuilder(this, styler, this[IS_EMPTY]); + }; + }, + }; +} + +const proto = Object.defineProperties(() => {}, { + ...styles, + level: { + enumerable: true, + get() { + return this[GENERATOR].level; + }, + set(level) { + this[GENERATOR].level = level; + }, + }, +}); + +const createStyler = (open, close, parent) => { + let openAll; + let closeAll; + if (parent === undefined) { + openAll = open; + closeAll = close; + } else { + openAll = parent.openAll + open; + closeAll = close + parent.closeAll; + } + + return { + open, + close, + openAll, + closeAll, + parent, + }; +}; + +const createBuilder = (self, _styler, _isEmpty) => { + // Single argument is hot path, implicit coercion is faster than anything + // eslint-disable-next-line no-implicit-coercion + const builder = (...arguments_) => applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' ')); + + // We alter the prototype because we must return a function, but there is + // no way to create a function with a different prototype + Object.setPrototypeOf(builder, proto); + + builder[GENERATOR] = self; + builder[STYLER] = _styler; + builder[IS_EMPTY] = _isEmpty; + + return builder; +}; + +const applyStyle = (self, string) => { + if (self.level <= 0 || !string) { + return self[IS_EMPTY] ? '' : string; + } + + let styler = self[STYLER]; + + if (styler === undefined) { + return string; + } + + const {openAll, closeAll} = styler; + if (string.includes('\u001B')) { + while (styler !== undefined) { + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + string = stringReplaceAll(string, styler.close, styler.open); + + styler = styler.parent; + } + } + + // We can move both next actions out of loop, because remaining actions in loop won't have + // any/visible effect on parts we add here. Close the styling before a linebreak and reopen + // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92 + const lfIndex = string.indexOf('\n'); + if (lfIndex !== -1) { + string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex); + } + + return openAll + string + closeAll; +}; + +Object.defineProperties(createChalk.prototype, styles); + +const chalk = createChalk(); +export const chalkStderr = createChalk({level: stderrColor ? stderrColor.level : 0}); + +export { + modifierNames, + foregroundColorNames, + backgroundColorNames, + colorNames, + + // TODO: Remove these aliases in the next major version + modifierNames as modifiers, + foregroundColorNames as foregroundColors, + backgroundColorNames as backgroundColors, + colorNames as colors, +} from './vendor/ansi-styles/index.js'; + +export { + stdoutColor as supportsColor, + stderrColor as supportsColorStderr, +}; + +export default chalk; diff --git a/tests/fixtures/npm/cases/chalk5-builder/node_modules/chalk/source/utilities.js b/tests/fixtures/npm/cases/chalk5-builder/node_modules/chalk/source/utilities.js new file mode 100644 index 000000000..4366dee0d --- /dev/null +++ b/tests/fixtures/npm/cases/chalk5-builder/node_modules/chalk/source/utilities.js @@ -0,0 +1,33 @@ +// TODO: When targeting Node.js 16, use `String.prototype.replaceAll`. +export function stringReplaceAll(string, substring, replacer) { + let index = string.indexOf(substring); + if (index === -1) { + return string; + } + + const substringLength = substring.length; + let endIndex = 0; + let returnValue = ''; + do { + returnValue += string.slice(endIndex, index) + substring + replacer; + endIndex = index + substringLength; + index = string.indexOf(substring, endIndex); + } while (index !== -1); + + returnValue += string.slice(endIndex); + return returnValue; +} + +export function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) { + let endIndex = 0; + let returnValue = ''; + do { + const gotCR = string[index - 1] === '\r'; + returnValue += string.slice(endIndex, (gotCR ? index - 1 : index)) + prefix + (gotCR ? '\r\n' : '\n') + postfix; + endIndex = index + 1; + index = string.indexOf('\n', endIndex); + } while (index !== -1); + + returnValue += string.slice(endIndex); + return returnValue; +} diff --git a/tests/fixtures/npm/cases/chalk5-builder/node_modules/chalk/source/vendor/ansi-styles/index.d.ts b/tests/fixtures/npm/cases/chalk5-builder/node_modules/chalk/source/vendor/ansi-styles/index.d.ts new file mode 100644 index 000000000..58f133abe --- /dev/null +++ b/tests/fixtures/npm/cases/chalk5-builder/node_modules/chalk/source/vendor/ansi-styles/index.d.ts @@ -0,0 +1,236 @@ +export interface CSPair { // eslint-disable-line @typescript-eslint/naming-convention + /** + The ANSI terminal control sequence for starting this style. + */ + readonly open: string; + + /** + The ANSI terminal control sequence for ending this style. + */ + readonly close: string; +} + +export interface ColorBase { + /** + The ANSI terminal control sequence for ending this color. + */ + readonly close: string; + + ansi(code: number): string; + + ansi256(code: number): string; + + ansi16m(red: number, green: number, blue: number): string; +} + +export interface Modifier { + /** + Resets the current color chain. + */ + readonly reset: CSPair; + + /** + Make text bold. + */ + readonly bold: CSPair; + + /** + Emitting only a small amount of light. + */ + readonly dim: CSPair; + + /** + Make text italic. (Not widely supported) + */ + readonly italic: CSPair; + + /** + Make text underline. (Not widely supported) + */ + readonly underline: CSPair; + + /** + Make text overline. + + Supported on VTE-based terminals, the GNOME terminal, mintty, and Git Bash. + */ + readonly overline: CSPair; + + /** + Inverse background and foreground colors. + */ + readonly inverse: CSPair; + + /** + Prints the text, but makes it invisible. + */ + readonly hidden: CSPair; + + /** + Puts a horizontal line through the center of the text. (Not widely supported) + */ + readonly strikethrough: CSPair; +} + +export interface ForegroundColor { + readonly black: CSPair; + readonly red: CSPair; + readonly green: CSPair; + readonly yellow: CSPair; + readonly blue: CSPair; + readonly cyan: CSPair; + readonly magenta: CSPair; + readonly white: CSPair; + + /** + Alias for `blackBright`. + */ + readonly gray: CSPair; + + /** + Alias for `blackBright`. + */ + readonly grey: CSPair; + + readonly blackBright: CSPair; + readonly redBright: CSPair; + readonly greenBright: CSPair; + readonly yellowBright: CSPair; + readonly blueBright: CSPair; + readonly cyanBright: CSPair; + readonly magentaBright: CSPair; + readonly whiteBright: CSPair; +} + +export interface BackgroundColor { + readonly bgBlack: CSPair; + readonly bgRed: CSPair; + readonly bgGreen: CSPair; + readonly bgYellow: CSPair; + readonly bgBlue: CSPair; + readonly bgCyan: CSPair; + readonly bgMagenta: CSPair; + readonly bgWhite: CSPair; + + /** + Alias for `bgBlackBright`. + */ + readonly bgGray: CSPair; + + /** + Alias for `bgBlackBright`. + */ + readonly bgGrey: CSPair; + + readonly bgBlackBright: CSPair; + readonly bgRedBright: CSPair; + readonly bgGreenBright: CSPair; + readonly bgYellowBright: CSPair; + readonly bgBlueBright: CSPair; + readonly bgCyanBright: CSPair; + readonly bgMagentaBright: CSPair; + readonly bgWhiteBright: CSPair; +} + +export interface ConvertColor { + /** + Convert from the RGB color space to the ANSI 256 color space. + + @param red - (`0...255`) + @param green - (`0...255`) + @param blue - (`0...255`) + */ + rgbToAnsi256(red: number, green: number, blue: number): number; + + /** + Convert from the RGB HEX color space to the RGB color space. + + @param hex - A hexadecimal string containing RGB data. + */ + hexToRgb(hex: string): [red: number, green: number, blue: number]; + + /** + Convert from the RGB HEX color space to the ANSI 256 color space. + + @param hex - A hexadecimal string containing RGB data. + */ + hexToAnsi256(hex: string): number; + + /** + Convert from the ANSI 256 color space to the ANSI 16 color space. + + @param code - A number representing the ANSI 256 color. + */ + ansi256ToAnsi(code: number): number; + + /** + Convert from the RGB color space to the ANSI 16 color space. + + @param red - (`0...255`) + @param green - (`0...255`) + @param blue - (`0...255`) + */ + rgbToAnsi(red: number, green: number, blue: number): number; + + /** + Convert from the RGB HEX color space to the ANSI 16 color space. + + @param hex - A hexadecimal string containing RGB data. + */ + hexToAnsi(hex: string): number; +} + +/** +Basic modifier names. +*/ +export type ModifierName = keyof Modifier; + +/** +Basic foreground color names. + +[More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support) +*/ +export type ForegroundColorName = keyof ForegroundColor; + +/** +Basic background color names. + +[More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support) +*/ +export type BackgroundColorName = keyof BackgroundColor; + +/** +Basic color names. The combination of foreground and background color names. + +[More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support) +*/ +export type ColorName = ForegroundColorName | BackgroundColorName; + +/** +Basic modifier names. +*/ +export const modifierNames: readonly ModifierName[]; + +/** +Basic foreground color names. +*/ +export const foregroundColorNames: readonly ForegroundColorName[]; + +/** +Basic background color names. +*/ +export const backgroundColorNames: readonly BackgroundColorName[]; + +/* +Basic color names. The combination of foreground and background color names. +*/ +export const colorNames: readonly ColorName[]; + +declare const ansiStyles: { + readonly modifier: Modifier; + readonly color: ColorBase & ForegroundColor; + readonly bgColor: ColorBase & BackgroundColor; + readonly codes: ReadonlyMap; +} & ForegroundColor & BackgroundColor & Modifier & ConvertColor; + +export default ansiStyles; diff --git a/tests/fixtures/npm/cases/chalk5-builder/node_modules/chalk/source/vendor/ansi-styles/index.js b/tests/fixtures/npm/cases/chalk5-builder/node_modules/chalk/source/vendor/ansi-styles/index.js new file mode 100644 index 000000000..eaa7bed6c --- /dev/null +++ b/tests/fixtures/npm/cases/chalk5-builder/node_modules/chalk/source/vendor/ansi-styles/index.js @@ -0,0 +1,223 @@ +const ANSI_BACKGROUND_OFFSET = 10; + +const wrapAnsi16 = (offset = 0) => code => `\u001B[${code + offset}m`; + +const wrapAnsi256 = (offset = 0) => code => `\u001B[${38 + offset};5;${code}m`; + +const wrapAnsi16m = (offset = 0) => (red, green, blue) => `\u001B[${38 + offset};2;${red};${green};${blue}m`; + +const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + overline: [53, 55], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29], + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + + // Bright color + blackBright: [90, 39], + gray: [90, 39], // Alias of `blackBright` + grey: [90, 39], // Alias of `blackBright` + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39], + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + + // Bright color + bgBlackBright: [100, 49], + bgGray: [100, 49], // Alias of `bgBlackBright` + bgGrey: [100, 49], // Alias of `bgBlackBright` + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49], + }, +}; + +export const modifierNames = Object.keys(styles.modifier); +export const foregroundColorNames = Object.keys(styles.color); +export const backgroundColorNames = Object.keys(styles.bgColor); +export const colorNames = [...foregroundColorNames, ...backgroundColorNames]; + +function assembleStyles() { + const codes = new Map(); + + for (const [groupName, group] of Object.entries(styles)) { + for (const [styleName, style] of Object.entries(group)) { + styles[styleName] = { + open: `\u001B[${style[0]}m`, + close: `\u001B[${style[1]}m`, + }; + + group[styleName] = styles[styleName]; + + codes.set(style[0], style[1]); + } + + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false, + }); + } + + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false, + }); + + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; + + styles.color.ansi = wrapAnsi16(); + styles.color.ansi256 = wrapAnsi256(); + styles.color.ansi16m = wrapAnsi16m(); + styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET); + styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET); + styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET); + + // From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js + Object.defineProperties(styles, { + rgbToAnsi256: { + value(red, green, blue) { + // We use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + if (red === green && green === blue) { + if (red < 8) { + return 16; + } + + if (red > 248) { + return 231; + } + + return Math.round(((red - 8) / 247) * 24) + 232; + } + + return 16 + + (36 * Math.round(red / 255 * 5)) + + (6 * Math.round(green / 255 * 5)) + + Math.round(blue / 255 * 5); + }, + enumerable: false, + }, + hexToRgb: { + value(hex) { + const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16)); + if (!matches) { + return [0, 0, 0]; + } + + let [colorString] = matches; + + if (colorString.length === 3) { + colorString = [...colorString].map(character => character + character).join(''); + } + + const integer = Number.parseInt(colorString, 16); + + return [ + /* eslint-disable no-bitwise */ + (integer >> 16) & 0xFF, + (integer >> 8) & 0xFF, + integer & 0xFF, + /* eslint-enable no-bitwise */ + ]; + }, + enumerable: false, + }, + hexToAnsi256: { + value: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)), + enumerable: false, + }, + ansi256ToAnsi: { + value(code) { + if (code < 8) { + return 30 + code; + } + + if (code < 16) { + return 90 + (code - 8); + } + + let red; + let green; + let blue; + + if (code >= 232) { + red = (((code - 232) * 10) + 8) / 255; + green = red; + blue = red; + } else { + code -= 16; + + const remainder = code % 36; + + red = Math.floor(code / 36) / 5; + green = Math.floor(remainder / 6) / 5; + blue = (remainder % 6) / 5; + } + + const value = Math.max(red, green, blue) * 2; + + if (value === 0) { + return 30; + } + + // eslint-disable-next-line no-bitwise + let result = 30 + ((Math.round(blue) << 2) | (Math.round(green) << 1) | Math.round(red)); + + if (value === 2) { + result += 60; + } + + return result; + }, + enumerable: false, + }, + rgbToAnsi: { + value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)), + enumerable: false, + }, + hexToAnsi: { + value: hex => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)), + enumerable: false, + }, + }); + + return styles; +} + +const ansiStyles = assembleStyles(); + +export default ansiStyles; diff --git a/tests/fixtures/npm/cases/chalk5-builder/node_modules/chalk/source/vendor/supports-color/browser.d.ts b/tests/fixtures/npm/cases/chalk5-builder/node_modules/chalk/source/vendor/supports-color/browser.d.ts new file mode 100644 index 000000000..0e8a9ccb8 --- /dev/null +++ b/tests/fixtures/npm/cases/chalk5-builder/node_modules/chalk/source/vendor/supports-color/browser.d.ts @@ -0,0 +1 @@ +export {default} from './index.js'; diff --git a/tests/fixtures/npm/cases/chalk5-builder/node_modules/chalk/source/vendor/supports-color/browser.js b/tests/fixtures/npm/cases/chalk5-builder/node_modules/chalk/source/vendor/supports-color/browser.js new file mode 100644 index 000000000..fbb6ce0fc --- /dev/null +++ b/tests/fixtures/npm/cases/chalk5-builder/node_modules/chalk/source/vendor/supports-color/browser.js @@ -0,0 +1,34 @@ +/* eslint-env browser */ + +const level = (() => { + if (!('navigator' in globalThis)) { + return 0; + } + + if (globalThis.navigator.userAgentData) { + const brand = navigator.userAgentData.brands.find(({brand}) => brand === 'Chromium'); + if (brand && brand.version > 93) { + return 3; + } + } + + if (/\b(Chrome|Chromium)\//.test(globalThis.navigator.userAgent)) { + return 1; + } + + return 0; +})(); + +const colorSupport = level !== 0 && { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3, +}; + +const supportsColor = { + stdout: colorSupport, + stderr: colorSupport, +}; + +export default supportsColor; diff --git a/tests/fixtures/npm/cases/chalk5-builder/node_modules/chalk/source/vendor/supports-color/index.d.ts b/tests/fixtures/npm/cases/chalk5-builder/node_modules/chalk/source/vendor/supports-color/index.d.ts new file mode 100644 index 000000000..db44a7851 --- /dev/null +++ b/tests/fixtures/npm/cases/chalk5-builder/node_modules/chalk/source/vendor/supports-color/index.d.ts @@ -0,0 +1,55 @@ +import type {WriteStream} from 'node:tty'; + +export type Options = { + /** + Whether `process.argv` should be sniffed for `--color` and `--no-color` flags. + + @default true + */ + readonly sniffFlags?: boolean; +}; + +/** +Levels: +- `0` - All colors disabled. +- `1` - Basic 16 colors support. +- `2` - ANSI 256 colors support. +- `3` - Truecolor 16 million colors support. +*/ +export type ColorSupportLevel = 0 | 1 | 2 | 3; + +/** +Detect whether the terminal supports color. +*/ +export type ColorSupport = { + /** + The color level. + */ + level: ColorSupportLevel; + + /** + Whether basic 16 colors are supported. + */ + hasBasic: boolean; + + /** + Whether ANSI 256 colors are supported. + */ + has256: boolean; + + /** + Whether Truecolor 16 million colors are supported. + */ + has16m: boolean; +}; + +export type ColorInfo = ColorSupport | false; + +export function createSupportsColor(stream?: WriteStream, options?: Options): ColorInfo; + +declare const supportsColor: { + stdout: ColorInfo; + stderr: ColorInfo; +}; + +export default supportsColor; diff --git a/tests/fixtures/npm/cases/chalk5-builder/node_modules/chalk/source/vendor/supports-color/index.js b/tests/fixtures/npm/cases/chalk5-builder/node_modules/chalk/source/vendor/supports-color/index.js new file mode 100644 index 000000000..265d7f858 --- /dev/null +++ b/tests/fixtures/npm/cases/chalk5-builder/node_modules/chalk/source/vendor/supports-color/index.js @@ -0,0 +1,190 @@ +import process from 'node:process'; +import os from 'node:os'; +import tty from 'node:tty'; + +// From: https://github.com/sindresorhus/has-flag/blob/main/index.js +/// function hasFlag(flag, argv = globalThis.Deno?.args ?? process.argv) { +function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process.argv) { + const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); + const position = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf('--'); + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); +} + +const {env} = process; + +let flagForceColor; +if ( + hasFlag('no-color') + || hasFlag('no-colors') + || hasFlag('color=false') + || hasFlag('color=never') +) { + flagForceColor = 0; +} else if ( + hasFlag('color') + || hasFlag('colors') + || hasFlag('color=true') + || hasFlag('color=always') +) { + flagForceColor = 1; +} + +function envForceColor() { + if ('FORCE_COLOR' in env) { + if (env.FORCE_COLOR === 'true') { + return 1; + } + + if (env.FORCE_COLOR === 'false') { + return 0; + } + + return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3); + } +} + +function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3, + }; +} + +function _supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) { + const noFlagForceColor = envForceColor(); + if (noFlagForceColor !== undefined) { + flagForceColor = noFlagForceColor; + } + + const forceColor = sniffFlags ? flagForceColor : noFlagForceColor; + + if (forceColor === 0) { + return 0; + } + + if (sniffFlags) { + if (hasFlag('color=16m') + || hasFlag('color=full') + || hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + } + + // Check for Azure DevOps pipelines. + // Has to be above the `!streamIsTTY` check. + if ('TF_BUILD' in env && 'AGENT_NAME' in env) { + return 1; + } + + if (haveStream && !streamIsTTY && forceColor === undefined) { + return 0; + } + + const min = forceColor || 0; + + if (env.TERM === 'dumb') { + return min; + } + + if (process.platform === 'win32') { + // Windows 10 build 10586 is the first Windows release that supports 256 colors. + // Windows 10 build 14931 is the first release that supports 16m/TrueColor. + const osRelease = os.release().split('.'); + if ( + Number(osRelease[0]) >= 10 + && Number(osRelease[2]) >= 10_586 + ) { + return Number(osRelease[2]) >= 14_931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env) { + if (['GITHUB_ACTIONS', 'GITEA_ACTIONS', 'CIRCLECI'].some(key => key in env)) { + return 3; + } + + if (['TRAVIS', 'APPVEYOR', 'GITLAB_CI', 'BUILDKITE', 'DRONE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } + + if (env.COLORTERM === 'truecolor') { + return 3; + } + + if (env.TERM === 'xterm-kitty') { + return 3; + } + + if (env.TERM === 'xterm-ghostty') { + return 3; + } + + if (env.TERM === 'wezterm') { + return 3; + } + + if ('TERM_PROGRAM' in env) { + const version = Number.parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env.TERM_PROGRAM) { + case 'iTerm.app': { + return version >= 3 ? 3 : 2; + } + + case 'Apple_Terminal': { + return 2; + } + // No default + } + } + + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + + if ('COLORTERM' in env) { + return 1; + } + + return min; +} + +export function createSupportsColor(stream, options = {}) { + const level = _supportsColor(stream, { + streamIsTTY: stream && stream.isTTY, + ...options, + }); + + return translateLevel(level); +} + +const supportsColor = { + stdout: createSupportsColor({isTTY: tty.isatty(1)}), + stderr: createSupportsColor({isTTY: tty.isatty(2)}), +}; + +export default supportsColor; diff --git a/tests/fixtures/npm/cases/chalk5-builder/package.json b/tests/fixtures/npm/cases/chalk5-builder/package.json new file mode 100644 index 000000000..3804daa8d --- /dev/null +++ b/tests/fixtures/npm/cases/chalk5-builder/package.json @@ -0,0 +1 @@ +{ "name": "chalk5-case", "private": true, "type": "module" } diff --git a/tests/fixtures/npm/cases/hot-shots-buffered/main.ts b/tests/fixtures/npm/cases/hot-shots-buffered/main.ts new file mode 100644 index 000000000..d17ce1167 --- /dev/null +++ b/tests/fixtures/npm/cases/hot-shots-buffered/main.ts @@ -0,0 +1,80 @@ +// The hot-shots StatsD client (compiled from scriptc's built-in shim) in +// buffered mode: metrics join one datagram until maxBufferSize, close +// flushes the rest, child clients share the buffer. Also explicit sample +// rates of 1, the telegraf line format, stat arrays with a callback, and +// suffixes. +import * as dgram from "node:dgram"; +import { StatsD } from "hot-shots"; + +const server = dgram.createSocket("udp4"); +const received: string[] = []; +let waiting: (() => void) | null = null; +let want = 0; +server.on("message", (msg) => { + received.push(msg.toString()); + if (waiting !== null && received.length >= want) { + const done = waiting; + waiting = null; + done(); + } +}); + +function datagrams(count: number): Promise { + want = count; + return new Promise((resolve) => { + if (received.length >= want) resolve(); + else waiting = resolve; + }); +} + +function flush(label: string): void { + console.log("--", label); + for (const line of received.splice(0)) console.log(JSON.stringify(line)); +} + +async function run(port: number): Promise { + const buffered = new StatsD({ + host: "127.0.0.1", + port, + maxBufferSize: 64, + bufferFlushInterval: 60000, + suffix: ".s", + globalTags: ["team:core"], + }); + buffered.increment("one"); + buffered.increment("two", 2); + buffered.gauge("three", 3); + buffered.histogram("four", 4, ["h:1"]); + const child = buffered.childClient({ prefix: "kid.", suffix: ".x" }); + child.increment("five"); + await new Promise((resolve) => buffered.close(() => resolve())); + await datagrams(2); + flush("buffered"); + + const telegraf = new StatsD({ host: "127.0.0.1", port, telegraf: true, globalTags: { region: "eu" } }); + telegraf.increment("hits", 1, 1, { route: "/x" }); + telegraf.timing("lat", 7, ["kind:a"]); + await datagrams(2); + flush("telegraf"); + + const plain = new StatsD({ host: "127.0.0.1", port, prefix: "p." }); + await new Promise((resolve) => { + plain.increment(["a", "b", "c"], 1, 1, ["t:1"], (err: unknown, bytes: unknown) => { + console.log("array sent", err, bytes); + resolve(); + }); + }); + plain.set("users", 42, 1); + plain.unique("visitors", "v1"); + plain.decrement("down", 3, ["d:1"]); + plain.decrement("gone"); + await datagrams(7); + flush("plain"); + await new Promise((resolve) => { + telegraf.close(() => plain.close(() => resolve())); + }); +} + +server.bind(0, "127.0.0.1", () => { + void run(server.address().port).then(() => server.close(() => console.log("server closed"))); +}); diff --git a/tests/fixtures/npm/cases/hot-shots-buffered/package.json b/tests/fixtures/npm/cases/hot-shots-buffered/package.json new file mode 100644 index 000000000..5ffd9800b --- /dev/null +++ b/tests/fixtures/npm/cases/hot-shots-buffered/package.json @@ -0,0 +1 @@ +{ "type": "module" } diff --git a/tests/fixtures/npm/cases/hot-shots-send-error/main.ts b/tests/fixtures/npm/cases/hot-shots-send-error/main.ts new file mode 100644 index 000000000..e829c5e33 --- /dev/null +++ b/tests/fixtures/npm/cases/hot-shots-send-error/main.ts @@ -0,0 +1,27 @@ +// The hot-shots StatsD client (compiled from scriptc's built-in shim) when a +// send fails: with a callback or an errorHandler the error goes there; with +// neither, the client logs it and emits it on the socket, where an 'error' +// event nobody listens for ends the process with status 1. +import { StatsD } from "hot-shots"; + +// A datagram larger than udp allows fails with EMSGSIZE before it leaves +// the host; port 9 keeps the message the same on every run. +const big = "x".repeat(70000); + +const withCallback = new StatsD({ host: "127.0.0.1", port: 9 }); +withCallback.increment(big, 1, 1, [], (err: Error | null | undefined) => { + console.log("callback:", err ? err.message : "no error"); + withCallback.close(); + + const withHandler = new StatsD({ + host: "127.0.0.1", + port: 9, + errorHandler: (error: Error) => { + console.log("errorHandler:", error.message); + withHandler.close(); + console.log("without a callback or errorHandler"); + new StatsD({ host: "127.0.0.1", port: 9 }).increment(big); + }, + }); + withHandler.increment(big); +}); diff --git a/tests/fixtures/npm/cases/hot-shots-send-error/package.json b/tests/fixtures/npm/cases/hot-shots-send-error/package.json new file mode 100644 index 000000000..5ffd9800b --- /dev/null +++ b/tests/fixtures/npm/cases/hot-shots-send-error/package.json @@ -0,0 +1 @@ +{ "type": "module" } diff --git a/tests/fixtures/npm/cases/hot-shots-tcp/main.ts b/tests/fixtures/npm/cases/hot-shots-tcp/main.ts new file mode 100644 index 000000000..0812c90f1 --- /dev/null +++ b/tests/fixtures/npm/cases/hot-shots-tcp/main.ts @@ -0,0 +1,33 @@ +// The hot-shots StatsD client over tcp (compiled from scriptc's built-in +// shim): a send completes once the socket has written its line, so close() +// waits for lines that a full socket buffer holds back, and the receiver +// gets every line before the connection ends. +import * as net from "node:net"; +import { StatsD } from "hot-shots"; + +const LINES = 20000; +const name = "m".repeat(1000); +let bytes = 0; +let ended: () => void = () => {}; +const serverDone = new Promise((resolve) => { + ended = resolve; +}); +const server = net.createServer((socket) => { + socket.pause(); + setTimeout(() => socket.resume(), 150); + socket.on("data", (chunk: Buffer) => { + bytes += chunk.length; + }); + socket.on("end", () => ended()); +}); + +server.listen(0, "127.0.0.1", () => { + const port = (server.address() as net.AddressInfo).port; + const client = new StatsD({ host: "127.0.0.1", port, protocol: "tcp" }); + for (let i = 0; i < LINES; i++) client.increment(name); + const closed = new Promise((resolve) => client.close(() => resolve())); + void Promise.all([closed, serverDone]).then(() => { + console.log("closed; received", bytes, "of", LINES * (name.length + 5), "bytes"); + server.close(() => console.log("server closed")); + }); +}); diff --git a/tests/fixtures/npm/cases/hot-shots-tcp/package.json b/tests/fixtures/npm/cases/hot-shots-tcp/package.json new file mode 100644 index 000000000..5ffd9800b --- /dev/null +++ b/tests/fixtures/npm/cases/hot-shots-tcp/package.json @@ -0,0 +1 @@ +{ "type": "module" } diff --git a/tests/fixtures/npm/cases/js-own-tostring/main.ts b/tests/fixtures/npm/cases/js-own-tostring/main.ts new file mode 100644 index 000000000..9793b2baa --- /dev/null +++ b/tests/fixtures/npm/cases/js-own-tostring/main.ts @@ -0,0 +1,16 @@ +// A JavaScript package (the TypeScript namespace downlevel zod uses) whose +// namespace object assigns its own `toString` returning string | undefined; +// Number.parseInt with one argument; and a `then` whose handler result the +// declared union types (zod's ParseStatus.mergeArray pattern). +import { check, direct, mergeLater, note, show, showRadix, wholePart } from "nsutil"; + +console.log(String(direct("a")), String(direct({ message: "b" })), String(direct(undefined))); +console.log(JSON.stringify(check(undefined)), JSON.stringify(check("m"))); +console.log(wholePart(1.23), wholePart(0.35), wholePart(-4.5), wholePart(12)); +const values: unknown[] = [12, "s", true, 1.5]; +console.log(values.map((value) => show(value)).join(" "), showRadix(5, 2), note.length); +async function main(): Promise { + console.log(JSON.stringify(await mergeLater([Promise.resolve(1), Promise.resolve("two")], { ok: true }))); + console.log(JSON.stringify(await mergeLater([Promise.resolve(3), Promise.resolve("four")], { ok: false }))); +} +void main(); diff --git a/tests/fixtures/npm/cases/js-own-tostring/node_modules/nsutil/dist/errorUtil.d.ts b/tests/fixtures/npm/cases/js-own-tostring/node_modules/nsutil/dist/errorUtil.d.ts new file mode 100644 index 000000000..bc9b033ff --- /dev/null +++ b/tests/fixtures/npm/cases/js-own-tostring/node_modules/nsutil/dist/errorUtil.d.ts @@ -0,0 +1,9 @@ +export declare namespace errorUtil { + type ErrMessage = string | { + message?: string | undefined; + }; + const errToObj: (message?: ErrMessage) => { + message?: string | undefined; + }; + const toString: (message?: ErrMessage) => string | undefined; +} diff --git a/tests/fixtures/npm/cases/js-own-tostring/node_modules/nsutil/dist/errorUtil.js b/tests/fixtures/npm/cases/js-own-tostring/node_modules/nsutil/dist/errorUtil.js new file mode 100644 index 000000000..1b48d927b --- /dev/null +++ b/tests/fixtures/npm/cases/js-own-tostring/node_modules/nsutil/dist/errorUtil.js @@ -0,0 +1,5 @@ +export var errorUtil; +(function (errorUtil) { + errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {}; + errorUtil.toString = (message) => typeof message === "string" ? message : message?.message; +})(errorUtil || (errorUtil = {})); diff --git a/tests/fixtures/npm/cases/js-own-tostring/node_modules/nsutil/dist/index.d.ts b/tests/fixtures/npm/cases/js-own-tostring/node_modules/nsutil/dist/index.d.ts new file mode 100644 index 000000000..18f135cad --- /dev/null +++ b/tests/fixtures/npm/cases/js-own-tostring/node_modules/nsutil/dist/index.d.ts @@ -0,0 +1,9 @@ +import { errorUtil } from "./errorUtil.js"; +export declare function check(message?: errorUtil.ErrMessage): { kind: "int"; message?: string }; +export declare function direct(message?: errorUtil.ErrMessage): string | undefined; +export declare function wholePart(value: number): number; +export type Merged = { status: "valid"; value: unknown[] } | { status: "aborted" }; +export declare function mergeLater(items: Promise[], status: { ok: boolean }): Promise; +export declare const note: string; +export declare function show(value: unknown): string; +export declare function showRadix(value: number, radix: number): string; diff --git a/tests/fixtures/npm/cases/js-own-tostring/node_modules/nsutil/dist/index.js b/tests/fixtures/npm/cases/js-own-tostring/node_modules/nsutil/dist/index.js new file mode 100644 index 000000000..105187f49 --- /dev/null +++ b/tests/fixtures/npm/cases/js-own-tostring/node_modules/nsutil/dist/index.js @@ -0,0 +1,28 @@ +import { errorUtil } from "./errorUtil.js"; +export function check(message) { + return { kind: "int", message: errorUtil.toString(message) }; +} +export function direct(message) { + return errorUtil.toString(message); +} +export function wholePart(value) { + return Number.parseInt(String(value).replace(".", "")) + Number.parseInt("0x1f"); +} +export function mergeLater(items, status) { + return Promise.all(items).then((results) => status.ok ? { status: "valid", value: results } : INVALID); +} +const INVALID = Object.freeze({ status: "aborted" }); +// Only an assignment to this binding's own toString counts: not this +// comment's value.toString = (x) => x, a string, or another function's +// parameter of the same name. +export const note = "value.toString = (x) => x"; +export function show(value) { + return value.toString(); +} +export function showRadix(value, radix) { + return value.toString(radix); +} +export function patch(value) { + value.toString = () => "patched"; + return value; +} diff --git a/tests/fixtures/npm/cases/js-own-tostring/node_modules/nsutil/package.json b/tests/fixtures/npm/cases/js-own-tostring/node_modules/nsutil/package.json new file mode 100644 index 000000000..a2757b8a1 --- /dev/null +++ b/tests/fixtures/npm/cases/js-own-tostring/node_modules/nsutil/package.json @@ -0,0 +1 @@ +{ "name": "nsutil", "version": "1.0.0", "type": "module", "main": "./dist/index.js", "types": "./dist/index.d.ts" } diff --git a/tests/fixtures/npm/cases/js-own-tostring/package.json b/tests/fixtures/npm/cases/js-own-tostring/package.json new file mode 100644 index 000000000..5ffd9800b --- /dev/null +++ b/tests/fixtures/npm/cases/js-own-tostring/package.json @@ -0,0 +1 @@ +{ "type": "module" } diff --git a/tests/fixtures/npm/cases/zod3-infer/main.ts b/tests/fixtures/npm/cases/zod3-infer/main.ts new file mode 100644 index 000000000..49029c38e --- /dev/null +++ b/tests/fixtures/npm/cases/zod3-infer/main.ts @@ -0,0 +1,118 @@ +// Types derived from zod 3.25 schemas (z.infer, z.input, z.output) used as +// ordinary typed data: field reads, spreads, interfaces extending inferred +// types, unions and discriminated unions narrowed by their tags, arrays, +// optional and nullable fields, transforms and defaults, and .extend. +import { z } from "zod"; + +const show = (label: string, value: unknown): void => { + console.log(label + " " + JSON.stringify(value)); +}; + +// Objects, and interfaces that extend an inferred type. +const ProductInput = z.object({ + name: z.string().min(1), + priceCents: z.number().int().nonnegative(), + tags: z.array(z.string()).default([]), +}); +type ProductInput = z.infer; +interface Product extends ProductInput { + id: string; +} + +function makeProduct(id: string, input: ProductInput): Product { + return { id, ...input }; +} +const parsed = ProductInput.parse({ name: "Keyboard", priceCents: 12900, tags: ["input"] }); +const product = makeProduct("p1", parsed); +show("product", product); +console.log("name", product.name, "price", product.priceCents, "tags", product.tags.join("|")); +const products: Product[] = [product, makeProduct("p2", ProductInput.parse({ name: "Cable", priceCents: 900 }))]; +console.log("tagged", products.filter((p) => p.tags.includes("input")).map((p) => p.name).join(",")); +let total = 0; +for (const p of products) total += p.priceCents; +console.log("total", total); + +// safeParse data spread into a record with more fields. +const OrderInput = z.object({ + productId: z.string(), + quantity: z.coerce.number().int().min(1), + email: z.string().email(), +}); +type OrderInput = z.infer; +interface Order extends OrderInput { + id: string; + totalCents: number; +} +function placeOrder(raw: unknown): Order | string { + const result = OrderInput.safeParse(raw); + if (!result.success) return result.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; "); + return { id: "o1", ...result.data, totalCents: result.data.quantity * 4900 }; +} +show("order", placeOrder({ productId: "p2", quantity: "3", email: "a@b.co" })); +show("bad order", placeOrder({ productId: "p2", quantity: "0", email: "nope" })); + +// Optional and nullable fields. +const Profile = z.object({ + handle: z.string(), + bio: z.string().optional(), + avatar: z.string().nullable(), + age: z.number().optional().nullable(), +}); +type Profile = z.infer; +function describe(p: Profile): string { + const bio = p.bio ?? "(no bio)"; + const avatar = p.avatar === null ? "(no avatar)" : p.avatar; + const age = p.age == null ? "?" : String(p.age); + return `${p.handle}: ${bio}, ${avatar}, ${age}`; +} +console.log(describe(Profile.parse({ handle: "ada", avatar: null }))); +console.log(describe(Profile.parse({ handle: "bob", bio: "hi", avatar: "b.png", age: 42 }))); + +// Unions and discriminated unions narrowed by their tag. +const Shape = z.discriminatedUnion("kind", [ + z.object({ kind: z.literal("circle"), radius: z.number() }), + z.object({ kind: z.literal("rect"), width: z.number(), height: z.number() }), +]); +type Shape = z.infer; +function area(s: Shape): number { + switch (s.kind) { + case "circle": + return Math.round(Math.PI * s.radius * s.radius); + case "rect": + return s.width * s.height; + } +} +const shapes: Shape[] = z.array(Shape).parse([ + { kind: "circle", radius: 2 }, + { kind: "rect", width: 3, height: 4 }, +]); +console.log("areas", shapes.map(area).join(",")); + +const IdOrName = z.union([z.number(), z.string()]); +type IdOrName = z.infer; +const label = (v: IdOrName): string => (typeof v === "number" ? `#${v}` : v.toUpperCase()); +console.log("labels", [IdOrName.parse(7), IdOrName.parse("x")].map(label).join(",")); + +// Transforms and defaults: input and output types differ. +const Settings = z.object({ + port: z.string().transform((s) => Number(s)), + mode: z.enum(["dev", "prod"]).default("dev"), +}); +type SettingsIn = z.input; +type SettingsOut = z.output; +const rawSettings: SettingsIn = { port: "8080" }; +const settings: SettingsOut = Settings.parse(rawSettings); +console.log("settings", settings.port + 1, settings.mode, typeof settings.port, rawSettings.port.length); + +// .extend and arrays of inferred records. +const Base = z.object({ id: z.string(), createdAt: z.string() }); +const User = Base.extend({ email: z.string().email(), roles: z.array(z.enum(["admin", "user"])) }); +type User = z.infer; +const users: User[] = z.array(User).parse([ + { id: "u1", createdAt: "2026-01-01", email: "a@b.co", roles: ["admin", "user"] }, + { id: "u2", createdAt: "2026-01-02", email: "c@d.co", roles: ["user"] }, +]); +const admins = users.filter((u) => u.roles.includes("admin")).map((u) => `${u.id}<${u.email}>`); +console.log("admins", admins.join(",")); +const renamed = users.map((u) => ({ ...u, id: u.id.toUpperCase() })); +show("renamed", renamed); diff --git a/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/LICENSE b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/LICENSE new file mode 100644 index 000000000..c06579627 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Colin McDonnell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/index.js b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/index.js new file mode 100644 index 000000000..8352ab713 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/index.js @@ -0,0 +1,3 @@ +import z3 from "./v3/index.js"; +export * from "./v3/index.js"; +export default z3; diff --git a/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/package.json b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/package.json new file mode 100644 index 000000000..aead43de3 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} \ No newline at end of file diff --git a/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/ZodError.js b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/ZodError.js new file mode 100644 index 000000000..c72ce5288 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/ZodError.js @@ -0,0 +1,132 @@ +import { util } from "./helpers/util.js"; +export const ZodIssueCode = util.arrayToEnum([ + "invalid_type", + "invalid_literal", + "custom", + "invalid_union", + "invalid_union_discriminator", + "invalid_enum_value", + "unrecognized_keys", + "invalid_arguments", + "invalid_return_type", + "invalid_date", + "invalid_string", + "too_small", + "too_big", + "invalid_intersection_types", + "not_multiple_of", + "not_finite", +]); +export const quotelessJson = (obj) => { + const json = JSON.stringify(obj, null, 2); + return json.replace(/"([^"]+)":/g, "$1:"); +}; +export class ZodError extends Error { + get errors() { + return this.issues; + } + constructor(issues) { + super(); + this.issues = []; + this.addIssue = (sub) => { + this.issues = [...this.issues, sub]; + }; + this.addIssues = (subs = []) => { + this.issues = [...this.issues, ...subs]; + }; + const actualProto = new.target.prototype; + if (Object.setPrototypeOf) { + // eslint-disable-next-line ban/ban + Object.setPrototypeOf(this, actualProto); + } + else { + this.__proto__ = actualProto; + } + this.name = "ZodError"; + this.issues = issues; + } + format(_mapper) { + const mapper = _mapper || + function (issue) { + return issue.message; + }; + const fieldErrors = { _errors: [] }; + const processError = (error) => { + for (const issue of error.issues) { + if (issue.code === "invalid_union") { + issue.unionErrors.map(processError); + } + else if (issue.code === "invalid_return_type") { + processError(issue.returnTypeError); + } + else if (issue.code === "invalid_arguments") { + processError(issue.argumentsError); + } + else if (issue.path.length === 0) { + fieldErrors._errors.push(mapper(issue)); + } + else { + let curr = fieldErrors; + let i = 0; + while (i < issue.path.length) { + const el = issue.path[i]; + const terminal = i === issue.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + // if (typeof el === "string") { + // curr[el] = curr[el] || { _errors: [] }; + // } else if (typeof el === "number") { + // const errorArray: any = []; + // errorArray._errors = []; + // curr[el] = curr[el] || errorArray; + // } + } + else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue)); + } + curr = curr[el]; + i++; + } + } + } + }; + processError(this); + return fieldErrors; + } + static assert(value) { + if (!(value instanceof ZodError)) { + throw new Error(`Not a ZodError: ${value}`); + } + } + toString() { + return this.message; + } + get message() { + return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); + } + get isEmpty() { + return this.issues.length === 0; + } + flatten(mapper = (issue) => issue.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of this.issues) { + if (sub.path.length > 0) { + fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; + fieldErrors[sub.path[0]].push(mapper(sub)); + } + else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; + } + get formErrors() { + return this.flatten(); + } +} +ZodError.create = (issues) => { + const error = new ZodError(issues); + return error; +}; diff --git a/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/errors.js b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/errors.js new file mode 100644 index 000000000..26fdf628a --- /dev/null +++ b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/errors.js @@ -0,0 +1,9 @@ +import defaultErrorMap from "./locales/en.js"; +let overrideErrorMap = defaultErrorMap; +export { defaultErrorMap }; +export function setErrorMap(map) { + overrideErrorMap = map; +} +export function getErrorMap() { + return overrideErrorMap; +} diff --git a/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/external.js b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/external.js new file mode 100644 index 000000000..f0a4be4c7 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/external.js @@ -0,0 +1,6 @@ +export * from "./errors.js"; +export * from "./helpers/parseUtil.js"; +export * from "./helpers/typeAliases.js"; +export * from "./helpers/util.js"; +export * from "./types.js"; +export * from "./ZodError.js"; diff --git a/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/helpers/enumUtil.js b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/helpers/enumUtil.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/helpers/enumUtil.js @@ -0,0 +1 @@ +export {}; diff --git a/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/helpers/errorUtil.js b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/helpers/errorUtil.js new file mode 100644 index 000000000..e1640d1a4 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/helpers/errorUtil.js @@ -0,0 +1,6 @@ +export var errorUtil; +(function (errorUtil) { + errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {}; + // biome-ignore lint: + errorUtil.toString = (message) => typeof message === "string" ? message : message?.message; +})(errorUtil || (errorUtil = {})); diff --git a/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/helpers/parseUtil.js b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/helpers/parseUtil.js new file mode 100644 index 000000000..91b2afb81 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/helpers/parseUtil.js @@ -0,0 +1,109 @@ +import { getErrorMap } from "../errors.js"; +import defaultErrorMap from "../locales/en.js"; +export const makeIssue = (params) => { + const { data, path, errorMaps, issueData } = params; + const fullPath = [...path, ...(issueData.path || [])]; + const fullIssue = { + ...issueData, + path: fullPath, + }; + if (issueData.message !== undefined) { + return { + ...issueData, + path: fullPath, + message: issueData.message, + }; + } + let errorMessage = ""; + const maps = errorMaps + .filter((m) => !!m) + .slice() + .reverse(); + for (const map of maps) { + errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; + } + return { + ...issueData, + path: fullPath, + message: errorMessage, + }; +}; +export const EMPTY_PATH = []; +export function addIssueToContext(ctx, issueData) { + const overrideMap = getErrorMap(); + const issue = makeIssue({ + issueData: issueData, + data: ctx.data, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, // contextual error map is first priority + ctx.schemaErrorMap, // then schema-bound map if available + overrideMap, // then global override map + overrideMap === defaultErrorMap ? undefined : defaultErrorMap, // then global default map + ].filter((x) => !!x), + }); + ctx.common.issues.push(issue); +} +export class ParseStatus { + constructor() { + this.value = "valid"; + } + dirty() { + if (this.value === "valid") + this.value = "dirty"; + } + abort() { + if (this.value !== "aborted") + this.value = "aborted"; + } + static mergeArray(status, results) { + const arrayValue = []; + for (const s of results) { + if (s.status === "aborted") + return INVALID; + if (s.status === "dirty") + status.dirty(); + arrayValue.push(s.value); + } + return { status: status.value, value: arrayValue }; + } + static async mergeObjectAsync(status, pairs) { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value, + }); + } + return ParseStatus.mergeObjectSync(status, syncPairs); + } + static mergeObjectSync(status, pairs) { + const finalObject = {}; + for (const pair of pairs) { + const { key, value } = pair; + if (key.status === "aborted") + return INVALID; + if (value.status === "aborted") + return INVALID; + if (key.status === "dirty") + status.dirty(); + if (value.status === "dirty") + status.dirty(); + if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { + finalObject[key.value] = value.value; + } + } + return { status: status.value, value: finalObject }; + } +} +export const INVALID = Object.freeze({ + status: "aborted", +}); +export const DIRTY = (value) => ({ status: "dirty", value }); +export const OK = (value) => ({ status: "valid", value }); +export const isAborted = (x) => x.status === "aborted"; +export const isDirty = (x) => x.status === "dirty"; +export const isValid = (x) => x.status === "valid"; +export const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; diff --git a/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/helpers/partialUtil.js b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/helpers/partialUtil.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/helpers/partialUtil.js @@ -0,0 +1 @@ +export {}; diff --git a/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/helpers/typeAliases.js b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/helpers/typeAliases.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/helpers/typeAliases.js @@ -0,0 +1 @@ +export {}; diff --git a/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/helpers/util.js b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/helpers/util.js new file mode 100644 index 000000000..b9641f29b --- /dev/null +++ b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/helpers/util.js @@ -0,0 +1,133 @@ +export var util; +(function (util) { + util.assertEqual = (_) => { }; + function assertIs(_arg) { } + util.assertIs = assertIs; + function assertNever(_x) { + throw new Error(); + } + util.assertNever = assertNever; + util.arrayToEnum = (items) => { + const obj = {}; + for (const item of items) { + obj[item] = item; + } + return obj; + }; + util.getValidEnumValues = (obj) => { + const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); + const filtered = {}; + for (const k of validKeys) { + filtered[k] = obj[k]; + } + return util.objectValues(filtered); + }; + util.objectValues = (obj) => { + return util.objectKeys(obj).map(function (e) { + return obj[e]; + }); + }; + util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban + ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban + : (object) => { + const keys = []; + for (const key in object) { + if (Object.prototype.hasOwnProperty.call(object, key)) { + keys.push(key); + } + } + return keys; + }; + util.find = (arr, checker) => { + for (const item of arr) { + if (checker(item)) + return item; + } + return undefined; + }; + util.isInteger = typeof Number.isInteger === "function" + ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban + : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; + function joinValues(array, separator = " | ") { + return array.map((val) => (typeof val === "string" ? `'${val}'` : val)).join(separator); + } + util.joinValues = joinValues; + util.jsonStringifyReplacer = (_, value) => { + if (typeof value === "bigint") { + return value.toString(); + } + return value; + }; +})(util || (util = {})); +export var objectUtil; +(function (objectUtil) { + objectUtil.mergeShapes = (first, second) => { + return { + ...first, + ...second, // second overwrites first + }; + }; +})(objectUtil || (objectUtil = {})); +export const ZodParsedType = util.arrayToEnum([ + "string", + "nan", + "number", + "integer", + "float", + "boolean", + "date", + "bigint", + "symbol", + "function", + "undefined", + "null", + "array", + "object", + "unknown", + "promise", + "void", + "never", + "map", + "set", +]); +export const getParsedType = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return ZodParsedType.undefined; + case "string": + return ZodParsedType.string; + case "number": + return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; + case "boolean": + return ZodParsedType.boolean; + case "function": + return ZodParsedType.function; + case "bigint": + return ZodParsedType.bigint; + case "symbol": + return ZodParsedType.symbol; + case "object": + if (Array.isArray(data)) { + return ZodParsedType.array; + } + if (data === null) { + return ZodParsedType.null; + } + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return ZodParsedType.promise; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return ZodParsedType.map; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return ZodParsedType.set; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return ZodParsedType.date; + } + return ZodParsedType.object; + default: + return ZodParsedType.unknown; + } +}; diff --git a/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/index.js b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/index.js new file mode 100644 index 000000000..a9dab5738 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/index.js @@ -0,0 +1,4 @@ +import * as z from "./external.js"; +export * from "./external.js"; +export { z }; +export default z; diff --git a/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/locales/en.js b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/locales/en.js new file mode 100644 index 000000000..3e97ad51a --- /dev/null +++ b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/locales/en.js @@ -0,0 +1,107 @@ +import { ZodIssueCode } from "../ZodError.js"; +import { util, ZodParsedType } from "../helpers/util.js"; +const errorMap = (issue, _ctx) => { + let message; + switch (issue.code) { + case ZodIssueCode.invalid_type: + if (issue.received === ZodParsedType.undefined) { + message = "Required"; + } + else { + message = `Expected ${issue.expected}, received ${issue.received}`; + } + break; + case ZodIssueCode.invalid_literal: + message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`; + break; + case ZodIssueCode.unrecognized_keys: + message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`; + break; + case ZodIssueCode.invalid_union: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_union_discriminator: + message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`; + break; + case ZodIssueCode.invalid_enum_value: + message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`; + break; + case ZodIssueCode.invalid_arguments: + message = `Invalid function arguments`; + break; + case ZodIssueCode.invalid_return_type: + message = `Invalid function return type`; + break; + case ZodIssueCode.invalid_date: + message = `Invalid date`; + break; + case ZodIssueCode.invalid_string: + if (typeof issue.validation === "object") { + if ("includes" in issue.validation) { + message = `Invalid input: must include "${issue.validation.includes}"`; + if (typeof issue.validation.position === "number") { + message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; + } + } + else if ("startsWith" in issue.validation) { + message = `Invalid input: must start with "${issue.validation.startsWith}"`; + } + else if ("endsWith" in issue.validation) { + message = `Invalid input: must end with "${issue.validation.endsWith}"`; + } + else { + util.assertNever(issue.validation); + } + } + else if (issue.validation !== "regex") { + message = `Invalid ${issue.validation}`; + } + else { + message = "Invalid"; + } + break; + case ZodIssueCode.too_small: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode.too_big: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; + else if (issue.type === "bigint") + message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode.custom: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_intersection_types: + message = `Intersection results could not be merged`; + break; + case ZodIssueCode.not_multiple_of: + message = `Number must be a multiple of ${issue.multipleOf}`; + break; + case ZodIssueCode.not_finite: + message = "Number must be finite"; + break; + default: + message = _ctx.defaultError; + util.assertNever(issue); + } + return { message }; +}; +export default errorMap; diff --git a/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/standard-schema.js b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/standard-schema.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/standard-schema.js @@ -0,0 +1 @@ +export {}; diff --git a/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/types.js b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/types.js new file mode 100644 index 000000000..de1e6213e --- /dev/null +++ b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/esm/v3/types.js @@ -0,0 +1,3691 @@ +import { ZodError, ZodIssueCode, } from "./ZodError.js"; +import { defaultErrorMap, getErrorMap } from "./errors.js"; +import { errorUtil } from "./helpers/errorUtil.js"; +import { DIRTY, INVALID, OK, ParseStatus, addIssueToContext, isAborted, isAsync, isDirty, isValid, makeIssue, } from "./helpers/parseUtil.js"; +import { util, ZodParsedType, getParsedType } from "./helpers/util.js"; +class ParseInputLazyPath { + constructor(parent, value, path, key) { + this._cachedPath = []; + this.parent = parent; + this.data = value; + this._path = path; + this._key = key; + } + get path() { + if (!this._cachedPath.length) { + if (Array.isArray(this._key)) { + this._cachedPath.push(...this._path, ...this._key); + } + else { + this._cachedPath.push(...this._path, this._key); + } + } + return this._cachedPath; + } +} +const handleResult = (ctx, result) => { + if (isValid(result)) { + return { success: true, data: result.value }; + } + else { + if (!ctx.common.issues.length) { + throw new Error("Validation failed but no issues detected."); + } + return { + success: false, + get error() { + if (this._error) + return this._error; + const error = new ZodError(ctx.common.issues); + this._error = error; + return this._error; + }, + }; + } +}; +function processCreateParams(params) { + if (!params) + return {}; + const { errorMap, invalid_type_error, required_error, description } = params; + if (errorMap && (invalid_type_error || required_error)) { + throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); + } + if (errorMap) + return { errorMap: errorMap, description }; + const customMap = (iss, ctx) => { + const { message } = params; + if (iss.code === "invalid_enum_value") { + return { message: message ?? ctx.defaultError }; + } + if (typeof ctx.data === "undefined") { + return { message: message ?? required_error ?? ctx.defaultError }; + } + if (iss.code !== "invalid_type") + return { message: ctx.defaultError }; + return { message: message ?? invalid_type_error ?? ctx.defaultError }; + }; + return { errorMap: customMap, description }; +} +export class ZodType { + get description() { + return this._def.description; + } + _getType(input) { + return getParsedType(input.data); + } + _getOrReturnCtx(input, ctx) { + return (ctx || { + common: input.parent.common, + data: input.data, + parsedType: getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent, + }); + } + _processInputParams(input) { + return { + status: new ParseStatus(), + ctx: { + common: input.parent.common, + data: input.data, + parsedType: getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent, + }, + }; + } + _parseSync(input) { + const result = this._parse(input); + if (isAsync(result)) { + throw new Error("Synchronous parse encountered promise."); + } + return result; + } + _parseAsync(input) { + const result = this._parse(input); + return Promise.resolve(result); + } + parse(data, params) { + const result = this.safeParse(data, params); + if (result.success) + return result.data; + throw result.error; + } + safeParse(data, params) { + const ctx = { + common: { + issues: [], + async: params?.async ?? false, + contextualErrorMap: params?.errorMap, + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data), + }; + const result = this._parseSync({ data, path: ctx.path, parent: ctx }); + return handleResult(ctx, result); + } + "~validate"(data) { + const ctx = { + common: { + issues: [], + async: !!this["~standard"].async, + }, + path: [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data), + }; + if (!this["~standard"].async) { + try { + const result = this._parseSync({ data, path: [], parent: ctx }); + return isValid(result) + ? { + value: result.value, + } + : { + issues: ctx.common.issues, + }; + } + catch (err) { + if (err?.message?.toLowerCase()?.includes("encountered")) { + this["~standard"].async = true; + } + ctx.common = { + issues: [], + async: true, + }; + } + } + return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) + ? { + value: result.value, + } + : { + issues: ctx.common.issues, + }); + } + async parseAsync(data, params) { + const result = await this.safeParseAsync(data, params); + if (result.success) + return result.data; + throw result.error; + } + async safeParseAsync(data, params) { + const ctx = { + common: { + issues: [], + contextualErrorMap: params?.errorMap, + async: true, + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data), + }; + const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); + const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); + return handleResult(ctx, result); + } + refine(check, message) { + const getIssueProperties = (val) => { + if (typeof message === "string" || typeof message === "undefined") { + return { message }; + } + else if (typeof message === "function") { + return message(val); + } + else { + return message; + } + }; + return this._refinement((val, ctx) => { + const result = check(val); + const setError = () => ctx.addIssue({ + code: ZodIssueCode.custom, + ...getIssueProperties(val), + }); + if (typeof Promise !== "undefined" && result instanceof Promise) { + return result.then((data) => { + if (!data) { + setError(); + return false; + } + else { + return true; + } + }); + } + if (!result) { + setError(); + return false; + } + else { + return true; + } + }); + } + refinement(check, refinementData) { + return this._refinement((val, ctx) => { + if (!check(val)) { + ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); + return false; + } + else { + return true; + } + }); + } + _refinement(refinement) { + return new ZodEffects({ + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "refinement", refinement }, + }); + } + superRefine(refinement) { + return this._refinement(refinement); + } + constructor(def) { + /** Alias of safeParseAsync */ + this.spa = this.safeParseAsync; + this._def = def; + this.parse = this.parse.bind(this); + this.safeParse = this.safeParse.bind(this); + this.parseAsync = this.parseAsync.bind(this); + this.safeParseAsync = this.safeParseAsync.bind(this); + this.spa = this.spa.bind(this); + this.refine = this.refine.bind(this); + this.refinement = this.refinement.bind(this); + this.superRefine = this.superRefine.bind(this); + this.optional = this.optional.bind(this); + this.nullable = this.nullable.bind(this); + this.nullish = this.nullish.bind(this); + this.array = this.array.bind(this); + this.promise = this.promise.bind(this); + this.or = this.or.bind(this); + this.and = this.and.bind(this); + this.transform = this.transform.bind(this); + this.brand = this.brand.bind(this); + this.default = this.default.bind(this); + this.catch = this.catch.bind(this); + this.describe = this.describe.bind(this); + this.pipe = this.pipe.bind(this); + this.readonly = this.readonly.bind(this); + this.isNullable = this.isNullable.bind(this); + this.isOptional = this.isOptional.bind(this); + this["~standard"] = { + version: 1, + vendor: "zod", + validate: (data) => this["~validate"](data), + }; + } + optional() { + return ZodOptional.create(this, this._def); + } + nullable() { + return ZodNullable.create(this, this._def); + } + nullish() { + return this.nullable().optional(); + } + array() { + return ZodArray.create(this); + } + promise() { + return ZodPromise.create(this, this._def); + } + or(option) { + return ZodUnion.create([this, option], this._def); + } + and(incoming) { + return ZodIntersection.create(this, incoming, this._def); + } + transform(transform) { + return new ZodEffects({ + ...processCreateParams(this._def), + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "transform", transform }, + }); + } + default(def) { + const defaultValueFunc = typeof def === "function" ? def : () => def; + return new ZodDefault({ + ...processCreateParams(this._def), + innerType: this, + defaultValue: defaultValueFunc, + typeName: ZodFirstPartyTypeKind.ZodDefault, + }); + } + brand() { + return new ZodBranded({ + typeName: ZodFirstPartyTypeKind.ZodBranded, + type: this, + ...processCreateParams(this._def), + }); + } + catch(def) { + const catchValueFunc = typeof def === "function" ? def : () => def; + return new ZodCatch({ + ...processCreateParams(this._def), + innerType: this, + catchValue: catchValueFunc, + typeName: ZodFirstPartyTypeKind.ZodCatch, + }); + } + describe(description) { + const This = this.constructor; + return new This({ + ...this._def, + description, + }); + } + pipe(target) { + return ZodPipeline.create(this, target); + } + readonly() { + return ZodReadonly.create(this); + } + isOptional() { + return this.safeParse(undefined).success; + } + isNullable() { + return this.safeParse(null).success; + } +} +const cuidRegex = /^c[^\s-]{8,}$/i; +const cuid2Regex = /^[0-9a-z]+$/; +const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; +// const uuidRegex = +// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i; +const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; +const nanoidRegex = /^[a-z0-9_-]{21}$/i; +const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; +const durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; +// from https://stackoverflow.com/a/46181/1550155 +// old version: too slow, didn't support unicode +// const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i; +//old email regex +// const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i; +// eslint-disable-next-line +// const emailRegex = +// /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/; +// const emailRegex = +// /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; +// const emailRegex = +// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i; +const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; +// const emailRegex = +// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i; +// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression +const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; +let emojiRegex; +// faster, simpler, safer +const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; +const ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; +// const ipv6Regex = +// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/; +const ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; +const ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript +const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; +// https://base64.guru/standards/base64url +const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; +// simple +// const dateRegexSource = `\\d{4}-\\d{2}-\\d{2}`; +// no leap year validation +// const dateRegexSource = `\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\d|2\\d))`; +// with leap year validation +const dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; +const dateRegex = new RegExp(`^${dateRegexSource}$`); +function timeRegexSource(args) { + let secondsRegexSource = `[0-5]\\d`; + if (args.precision) { + secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; + } + else if (args.precision == null) { + secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; + } + const secondsQuantifier = args.precision ? "+" : "?"; // require seconds if precision is nonzero + return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; +} +function timeRegex(args) { + return new RegExp(`^${timeRegexSource(args)}$`); +} +// Adapted from https://stackoverflow.com/a/3143231 +export function datetimeRegex(args) { + let regex = `${dateRegexSource}T${timeRegexSource(args)}`; + const opts = []; + opts.push(args.local ? `Z?` : `Z`); + if (args.offset) + opts.push(`([+-]\\d{2}:?\\d{2})`); + regex = `${regex}(${opts.join("|")})`; + return new RegExp(`^${regex}$`); +} +function isValidIP(ip, version) { + if ((version === "v4" || !version) && ipv4Regex.test(ip)) { + return true; + } + if ((version === "v6" || !version) && ipv6Regex.test(ip)) { + return true; + } + return false; +} +function isValidJWT(jwt, alg) { + if (!jwtRegex.test(jwt)) + return false; + try { + const [header] = jwt.split("."); + // Convert base64url to base64 + const base64 = header + .replace(/-/g, "+") + .replace(/_/g, "/") + .padEnd(header.length + ((4 - (header.length % 4)) % 4), "="); + const decoded = JSON.parse(atob(base64)); + if (typeof decoded !== "object" || decoded === null) + return false; + if ("typ" in decoded && decoded?.typ !== "JWT") + return false; + if (!decoded.alg) + return false; + if (alg && decoded.alg !== alg) + return false; + return true; + } + catch { + return false; + } +} +function isValidCidr(ip, version) { + if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) { + return true; + } + if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) { + return true; + } + return false; +} +export class ZodString extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = String(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.string) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.string, + received: ctx.parsedType, + }); + return INVALID; + } + const status = new ParseStatus(); + let ctx = undefined; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.length < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "max") { + if (input.data.length > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "length") { + const tooBig = input.data.length > check.value; + const tooSmall = input.data.length < check.value; + if (tooBig || tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + if (tooBig) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message, + }); + } + else if (tooSmall) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message, + }); + } + status.dirty(); + } + } + else if (check.kind === "email") { + if (!emailRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "email", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "emoji") { + if (!emojiRegex) { + emojiRegex = new RegExp(_emojiRegex, "u"); + } + if (!emojiRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "emoji", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "uuid") { + if (!uuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "uuid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "nanoid") { + if (!nanoidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "nanoid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "cuid") { + if (!cuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "cuid2") { + if (!cuid2Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid2", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "ulid") { + if (!ulidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ulid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "url") { + try { + new URL(input.data); + } + catch { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "url", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "regex") { + check.regex.lastIndex = 0; + const testResult = check.regex.test(input.data); + if (!testResult) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "regex", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "trim") { + input.data = input.data.trim(); + } + else if (check.kind === "includes") { + if (!input.data.includes(check.value, check.position)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { includes: check.value, position: check.position }, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "toLowerCase") { + input.data = input.data.toLowerCase(); + } + else if (check.kind === "toUpperCase") { + input.data = input.data.toUpperCase(); + } + else if (check.kind === "startsWith") { + if (!input.data.startsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { startsWith: check.value }, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "endsWith") { + if (!input.data.endsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { endsWith: check.value }, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "datetime") { + const regex = datetimeRegex(check); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "datetime", + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "date") { + const regex = dateRegex; + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "date", + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "time") { + const regex = timeRegex(check); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "time", + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "duration") { + if (!durationRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "duration", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "ip") { + if (!isValidIP(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ip", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "jwt") { + if (!isValidJWT(input.data, check.alg)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "jwt", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "cidr") { + if (!isValidCidr(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cidr", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "base64") { + if (!base64Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "base64", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "base64url") { + if (!base64urlRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "base64url", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else { + util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + _regex(regex, validation, message) { + return this.refinement((data) => regex.test(data), { + validation, + code: ZodIssueCode.invalid_string, + ...errorUtil.errToObj(message), + }); + } + _addCheck(check) { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + email(message) { + return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); + } + url(message) { + return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); + } + emoji(message) { + return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); + } + uuid(message) { + return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); + } + nanoid(message) { + return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); + } + cuid(message) { + return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); + } + cuid2(message) { + return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); + } + ulid(message) { + return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); + } + base64(message) { + return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); + } + base64url(message) { + // base64url encoding is a modification of base64 that can safely be used in URLs and filenames + return this._addCheck({ + kind: "base64url", + ...errorUtil.errToObj(message), + }); + } + jwt(options) { + return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); + } + ip(options) { + return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); + } + cidr(options) { + return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); + } + datetime(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "datetime", + precision: null, + offset: false, + local: false, + message: options, + }); + } + return this._addCheck({ + kind: "datetime", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + offset: options?.offset ?? false, + local: options?.local ?? false, + ...errorUtil.errToObj(options?.message), + }); + } + date(message) { + return this._addCheck({ kind: "date", message }); + } + time(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "time", + precision: null, + message: options, + }); + } + return this._addCheck({ + kind: "time", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + ...errorUtil.errToObj(options?.message), + }); + } + duration(message) { + return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); + } + regex(regex, message) { + return this._addCheck({ + kind: "regex", + regex: regex, + ...errorUtil.errToObj(message), + }); + } + includes(value, options) { + return this._addCheck({ + kind: "includes", + value: value, + position: options?.position, + ...errorUtil.errToObj(options?.message), + }); + } + startsWith(value, message) { + return this._addCheck({ + kind: "startsWith", + value: value, + ...errorUtil.errToObj(message), + }); + } + endsWith(value, message) { + return this._addCheck({ + kind: "endsWith", + value: value, + ...errorUtil.errToObj(message), + }); + } + min(minLength, message) { + return this._addCheck({ + kind: "min", + value: minLength, + ...errorUtil.errToObj(message), + }); + } + max(maxLength, message) { + return this._addCheck({ + kind: "max", + value: maxLength, + ...errorUtil.errToObj(message), + }); + } + length(len, message) { + return this._addCheck({ + kind: "length", + value: len, + ...errorUtil.errToObj(message), + }); + } + /** + * Equivalent to `.min(1)` + */ + nonempty(message) { + return this.min(1, errorUtil.errToObj(message)); + } + trim() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "trim" }], + }); + } + toLowerCase() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toLowerCase" }], + }); + } + toUpperCase() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toUpperCase" }], + }); + } + get isDatetime() { + return !!this._def.checks.find((ch) => ch.kind === "datetime"); + } + get isDate() { + return !!this._def.checks.find((ch) => ch.kind === "date"); + } + get isTime() { + return !!this._def.checks.find((ch) => ch.kind === "time"); + } + get isDuration() { + return !!this._def.checks.find((ch) => ch.kind === "duration"); + } + get isEmail() { + return !!this._def.checks.find((ch) => ch.kind === "email"); + } + get isURL() { + return !!this._def.checks.find((ch) => ch.kind === "url"); + } + get isEmoji() { + return !!this._def.checks.find((ch) => ch.kind === "emoji"); + } + get isUUID() { + return !!this._def.checks.find((ch) => ch.kind === "uuid"); + } + get isNANOID() { + return !!this._def.checks.find((ch) => ch.kind === "nanoid"); + } + get isCUID() { + return !!this._def.checks.find((ch) => ch.kind === "cuid"); + } + get isCUID2() { + return !!this._def.checks.find((ch) => ch.kind === "cuid2"); + } + get isULID() { + return !!this._def.checks.find((ch) => ch.kind === "ulid"); + } + get isIP() { + return !!this._def.checks.find((ch) => ch.kind === "ip"); + } + get isCIDR() { + return !!this._def.checks.find((ch) => ch.kind === "cidr"); + } + get isBase64() { + return !!this._def.checks.find((ch) => ch.kind === "base64"); + } + get isBase64url() { + // base64url encoding is a modification of base64 that can safely be used in URLs and filenames + return !!this._def.checks.find((ch) => ch.kind === "base64url"); + } + get minLength() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxLength() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } +} +ZodString.create = (params) => { + return new ZodString({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodString, + coerce: params?.coerce ?? false, + ...processCreateParams(params), + }); +}; +// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034 +function floatSafeRemainder(val, step) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); + return (valInt % stepInt) / 10 ** decCount; +} +export class ZodNumber extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + this.step = this.multipleOf; + } + _parse(input) { + if (this._def.coerce) { + input.data = Number(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.number) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.number, + received: ctx.parsedType, + }); + return INVALID; + } + let ctx = undefined; + const status = new ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "int") { + if (!util.isInteger(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: "integer", + received: "float", + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "min") { + const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "max") { + const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "multipleOf") { + if (floatSafeRemainder(input.data, check.value) !== 0) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "finite") { + if (!Number.isFinite(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_finite, + message: check.message, + }); + status.dirty(); + } + } + else { + util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new ZodNumber({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message), + }, + ], + }); + } + _addCheck(check) { + return new ZodNumber({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + int(message) { + return this._addCheck({ + kind: "int", + message: errorUtil.toString(message), + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: false, + message: errorUtil.toString(message), + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: false, + message: errorUtil.toString(message), + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: true, + message: errorUtil.toString(message), + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: true, + message: errorUtil.toString(message), + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value: value, + message: errorUtil.toString(message), + }); + } + finite(message) { + return this._addCheck({ + kind: "finite", + message: errorUtil.toString(message), + }); + } + safe(message) { + return this._addCheck({ + kind: "min", + inclusive: true, + value: Number.MIN_SAFE_INTEGER, + message: errorUtil.toString(message), + })._addCheck({ + kind: "max", + inclusive: true, + value: Number.MAX_SAFE_INTEGER, + message: errorUtil.toString(message), + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + get isInt() { + return !!this._def.checks.find((ch) => ch.kind === "int" || (ch.kind === "multipleOf" && util.isInteger(ch.value))); + } + get isFinite() { + let max = null; + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { + return true; + } + else if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + else if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return Number.isFinite(min) && Number.isFinite(max); + } +} +ZodNumber.create = (params) => { + return new ZodNumber({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodNumber, + coerce: params?.coerce || false, + ...processCreateParams(params), + }); +}; +export class ZodBigInt extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + } + _parse(input) { + if (this._def.coerce) { + try { + input.data = BigInt(input.data); + } + catch { + return this._getInvalidInput(input); + } + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.bigint) { + return this._getInvalidInput(input); + } + let ctx = undefined; + const status = new ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "min") { + const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + type: "bigint", + minimum: check.value, + inclusive: check.inclusive, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "max") { + const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + type: "bigint", + maximum: check.value, + inclusive: check.inclusive, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "multipleOf") { + if (input.data % check.value !== BigInt(0)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message, + }); + status.dirty(); + } + } + else { + util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + _getInvalidInput(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.bigint, + received: ctx.parsedType, + }); + return INVALID; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new ZodBigInt({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message), + }, + ], + }); + } + _addCheck(check) { + return new ZodBigInt({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message), + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message), + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message), + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message), + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message), + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } +} +ZodBigInt.create = (params) => { + return new ZodBigInt({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodBigInt, + coerce: params?.coerce ?? false, + ...processCreateParams(params), + }); +}; +export class ZodBoolean extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = Boolean(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.boolean) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.boolean, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } +} +ZodBoolean.create = (params) => { + return new ZodBoolean({ + typeName: ZodFirstPartyTypeKind.ZodBoolean, + coerce: params?.coerce || false, + ...processCreateParams(params), + }); +}; +export class ZodDate extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = new Date(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.date) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.date, + received: ctx.parsedType, + }); + return INVALID; + } + if (Number.isNaN(input.data.getTime())) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_date, + }); + return INVALID; + } + const status = new ParseStatus(); + let ctx = undefined; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.getTime() < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + message: check.message, + inclusive: true, + exact: false, + minimum: check.value, + type: "date", + }); + status.dirty(); + } + } + else if (check.kind === "max") { + if (input.data.getTime() > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + message: check.message, + inclusive: true, + exact: false, + maximum: check.value, + type: "date", + }); + status.dirty(); + } + } + else { + util.assertNever(check); + } + } + return { + status: status.value, + value: new Date(input.data.getTime()), + }; + } + _addCheck(check) { + return new ZodDate({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + min(minDate, message) { + return this._addCheck({ + kind: "min", + value: minDate.getTime(), + message: errorUtil.toString(message), + }); + } + max(maxDate, message) { + return this._addCheck({ + kind: "max", + value: maxDate.getTime(), + message: errorUtil.toString(message), + }); + } + get minDate() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min != null ? new Date(min) : null; + } + get maxDate() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max != null ? new Date(max) : null; + } +} +ZodDate.create = (params) => { + return new ZodDate({ + checks: [], + coerce: params?.coerce || false, + typeName: ZodFirstPartyTypeKind.ZodDate, + ...processCreateParams(params), + }); +}; +export class ZodSymbol extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.symbol) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.symbol, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } +} +ZodSymbol.create = (params) => { + return new ZodSymbol({ + typeName: ZodFirstPartyTypeKind.ZodSymbol, + ...processCreateParams(params), + }); +}; +export class ZodUndefined extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.undefined, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } +} +ZodUndefined.create = (params) => { + return new ZodUndefined({ + typeName: ZodFirstPartyTypeKind.ZodUndefined, + ...processCreateParams(params), + }); +}; +export class ZodNull extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.null) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.null, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } +} +ZodNull.create = (params) => { + return new ZodNull({ + typeName: ZodFirstPartyTypeKind.ZodNull, + ...processCreateParams(params), + }); +}; +export class ZodAny extends ZodType { + constructor() { + super(...arguments); + // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject. + this._any = true; + } + _parse(input) { + return OK(input.data); + } +} +ZodAny.create = (params) => { + return new ZodAny({ + typeName: ZodFirstPartyTypeKind.ZodAny, + ...processCreateParams(params), + }); +}; +export class ZodUnknown extends ZodType { + constructor() { + super(...arguments); + // required + this._unknown = true; + } + _parse(input) { + return OK(input.data); + } +} +ZodUnknown.create = (params) => { + return new ZodUnknown({ + typeName: ZodFirstPartyTypeKind.ZodUnknown, + ...processCreateParams(params), + }); +}; +export class ZodNever extends ZodType { + _parse(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.never, + received: ctx.parsedType, + }); + return INVALID; + } +} +ZodNever.create = (params) => { + return new ZodNever({ + typeName: ZodFirstPartyTypeKind.ZodNever, + ...processCreateParams(params), + }); +}; +export class ZodVoid extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.void, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } +} +ZodVoid.create = (params) => { + return new ZodVoid({ + typeName: ZodFirstPartyTypeKind.ZodVoid, + ...processCreateParams(params), + }); +}; +export class ZodArray extends ZodType { + _parse(input) { + const { ctx, status } = this._processInputParams(input); + const def = this._def; + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType, + }); + return INVALID; + } + if (def.exactLength !== null) { + const tooBig = ctx.data.length > def.exactLength.value; + const tooSmall = ctx.data.length < def.exactLength.value; + if (tooBig || tooSmall) { + addIssueToContext(ctx, { + code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, + minimum: (tooSmall ? def.exactLength.value : undefined), + maximum: (tooBig ? def.exactLength.value : undefined), + type: "array", + inclusive: true, + exact: true, + message: def.exactLength.message, + }); + status.dirty(); + } + } + if (def.minLength !== null) { + if (ctx.data.length < def.minLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.minLength.message, + }); + status.dirty(); + } + } + if (def.maxLength !== null) { + if (ctx.data.length > def.maxLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.maxLength.message, + }); + status.dirty(); + } + } + if (ctx.common.async) { + return Promise.all([...ctx.data].map((item, i) => { + return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + })).then((result) => { + return ParseStatus.mergeArray(status, result); + }); + } + const result = [...ctx.data].map((item, i) => { + return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + }); + return ParseStatus.mergeArray(status, result); + } + get element() { + return this._def.type; + } + min(minLength, message) { + return new ZodArray({ + ...this._def, + minLength: { value: minLength, message: errorUtil.toString(message) }, + }); + } + max(maxLength, message) { + return new ZodArray({ + ...this._def, + maxLength: { value: maxLength, message: errorUtil.toString(message) }, + }); + } + length(len, message) { + return new ZodArray({ + ...this._def, + exactLength: { value: len, message: errorUtil.toString(message) }, + }); + } + nonempty(message) { + return this.min(1, message); + } +} +ZodArray.create = (schema, params) => { + return new ZodArray({ + type: schema, + minLength: null, + maxLength: null, + exactLength: null, + typeName: ZodFirstPartyTypeKind.ZodArray, + ...processCreateParams(params), + }); +}; +function deepPartialify(schema) { + if (schema instanceof ZodObject) { + const newShape = {}; + for (const key in schema.shape) { + const fieldSchema = schema.shape[key]; + newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); + } + return new ZodObject({ + ...schema._def, + shape: () => newShape, + }); + } + else if (schema instanceof ZodArray) { + return new ZodArray({ + ...schema._def, + type: deepPartialify(schema.element), + }); + } + else if (schema instanceof ZodOptional) { + return ZodOptional.create(deepPartialify(schema.unwrap())); + } + else if (schema instanceof ZodNullable) { + return ZodNullable.create(deepPartialify(schema.unwrap())); + } + else if (schema instanceof ZodTuple) { + return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); + } + else { + return schema; + } +} +export class ZodObject extends ZodType { + constructor() { + super(...arguments); + this._cached = null; + /** + * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped. + * If you want to pass through unknown properties, use `.passthrough()` instead. + */ + this.nonstrict = this.passthrough; + // extend< + // Augmentation extends ZodRawShape, + // NewOutput extends util.flatten<{ + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }>, + // NewInput extends util.flatten<{ + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // }> + // >( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, + // UnknownKeys, + // Catchall, + // NewOutput, + // NewInput + // > { + // return new ZodObject({ + // ...this._def, + // shape: () => ({ + // ...this._def.shape(), + // ...augmentation, + // }), + // }) as any; + // } + /** + * @deprecated Use `.extend` instead + * */ + this.augment = this.extend; + } + _getCached() { + if (this._cached !== null) + return this._cached; + const shape = this._def.shape(); + const keys = util.objectKeys(shape); + this._cached = { shape, keys }; + return this._cached; + } + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.object) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType, + }); + return INVALID; + } + const { status, ctx } = this._processInputParams(input); + const { shape, keys: shapeKeys } = this._getCached(); + const extraKeys = []; + if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { + for (const key in ctx.data) { + if (!shapeKeys.includes(key)) { + extraKeys.push(key); + } + } + } + const pairs = []; + for (const key of shapeKeys) { + const keyValidator = shape[key]; + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data, + }); + } + if (this._def.catchall instanceof ZodNever) { + const unknownKeys = this._def.unknownKeys; + if (unknownKeys === "passthrough") { + for (const key of extraKeys) { + pairs.push({ + key: { status: "valid", value: key }, + value: { status: "valid", value: ctx.data[key] }, + }); + } + } + else if (unknownKeys === "strict") { + if (extraKeys.length > 0) { + addIssueToContext(ctx, { + code: ZodIssueCode.unrecognized_keys, + keys: extraKeys, + }); + status.dirty(); + } + } + else if (unknownKeys === "strip") { + } + else { + throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); + } + } + else { + // run catchall validation + const catchall = this._def.catchall; + for (const key of extraKeys) { + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value) + ), + alwaysSet: key in ctx.data, + }); + } + } + if (ctx.common.async) { + return Promise.resolve() + .then(async () => { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value, + alwaysSet: pair.alwaysSet, + }); + } + return syncPairs; + }) + .then((syncPairs) => { + return ParseStatus.mergeObjectSync(status, syncPairs); + }); + } + else { + return ParseStatus.mergeObjectSync(status, pairs); + } + } + get shape() { + return this._def.shape(); + } + strict(message) { + errorUtil.errToObj; + return new ZodObject({ + ...this._def, + unknownKeys: "strict", + ...(message !== undefined + ? { + errorMap: (issue, ctx) => { + const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError; + if (issue.code === "unrecognized_keys") + return { + message: errorUtil.errToObj(message).message ?? defaultError, + }; + return { + message: defaultError, + }; + }, + } + : {}), + }); + } + strip() { + return new ZodObject({ + ...this._def, + unknownKeys: "strip", + }); + } + passthrough() { + return new ZodObject({ + ...this._def, + unknownKeys: "passthrough", + }); + } + // const AugmentFactory = + // (def: Def) => + // ( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, Augmentation>, + // Def["unknownKeys"], + // Def["catchall"] + // > => { + // return new ZodObject({ + // ...def, + // shape: () => ({ + // ...def.shape(), + // ...augmentation, + // }), + // }) as any; + // }; + extend(augmentation) { + return new ZodObject({ + ...this._def, + shape: () => ({ + ...this._def.shape(), + ...augmentation, + }), + }); + } + /** + * Prior to zod@1.0.12 there was a bug in the + * inferred type of merged objects. Please + * upgrade if you are experiencing issues. + */ + merge(merging) { + const merged = new ZodObject({ + unknownKeys: merging._def.unknownKeys, + catchall: merging._def.catchall, + shape: () => ({ + ...this._def.shape(), + ...merging._def.shape(), + }), + typeName: ZodFirstPartyTypeKind.ZodObject, + }); + return merged; + } + // merge< + // Incoming extends AnyZodObject, + // Augmentation extends Incoming["shape"], + // NewOutput extends { + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }, + // NewInput extends { + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // } + // >( + // merging: Incoming + // ): ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"], + // NewOutput, + // NewInput + // > { + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + setKey(key, schema) { + return this.augment({ [key]: schema }); + } + // merge( + // merging: Incoming + // ): //ZodObject = (merging) => { + // ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"] + // > { + // // const mergedShape = objectUtil.mergeShapes( + // // this._def.shape(), + // // merging._def.shape() + // // ); + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + catchall(index) { + return new ZodObject({ + ...this._def, + catchall: index, + }); + } + pick(mask) { + const shape = {}; + for (const key of util.objectKeys(mask)) { + if (mask[key] && this.shape[key]) { + shape[key] = this.shape[key]; + } + } + return new ZodObject({ + ...this._def, + shape: () => shape, + }); + } + omit(mask) { + const shape = {}; + for (const key of util.objectKeys(this.shape)) { + if (!mask[key]) { + shape[key] = this.shape[key]; + } + } + return new ZodObject({ + ...this._def, + shape: () => shape, + }); + } + /** + * @deprecated + */ + deepPartial() { + return deepPartialify(this); + } + partial(mask) { + const newShape = {}; + for (const key of util.objectKeys(this.shape)) { + const fieldSchema = this.shape[key]; + if (mask && !mask[key]) { + newShape[key] = fieldSchema; + } + else { + newShape[key] = fieldSchema.optional(); + } + } + return new ZodObject({ + ...this._def, + shape: () => newShape, + }); + } + required(mask) { + const newShape = {}; + for (const key of util.objectKeys(this.shape)) { + if (mask && !mask[key]) { + newShape[key] = this.shape[key]; + } + else { + const fieldSchema = this.shape[key]; + let newField = fieldSchema; + while (newField instanceof ZodOptional) { + newField = newField._def.innerType; + } + newShape[key] = newField; + } + } + return new ZodObject({ + ...this._def, + shape: () => newShape, + }); + } + keyof() { + return createZodEnum(util.objectKeys(this.shape)); + } +} +ZodObject.create = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }); +}; +ZodObject.strictCreate = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strict", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }); +}; +ZodObject.lazycreate = (shape, params) => { + return new ZodObject({ + shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }); +}; +export class ZodUnion extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const options = this._def.options; + function handleResults(results) { + // return first issue-free validation if it exists + for (const result of results) { + if (result.result.status === "valid") { + return result.result; + } + } + for (const result of results) { + if (result.result.status === "dirty") { + // add issues from dirty option + ctx.common.issues.push(...result.ctx.common.issues); + return result.result; + } + } + // return invalid + const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors, + }); + return INVALID; + } + if (ctx.common.async) { + return Promise.all(options.map(async (option) => { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + parent: null, + }; + return { + result: await option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: childCtx, + }), + ctx: childCtx, + }; + })).then(handleResults); + } + else { + let dirty = undefined; + const issues = []; + for (const option of options) { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + parent: null, + }; + const result = option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: childCtx, + }); + if (result.status === "valid") { + return result; + } + else if (result.status === "dirty" && !dirty) { + dirty = { result, ctx: childCtx }; + } + if (childCtx.common.issues.length) { + issues.push(childCtx.common.issues); + } + } + if (dirty) { + ctx.common.issues.push(...dirty.ctx.common.issues); + return dirty.result; + } + const unionErrors = issues.map((issues) => new ZodError(issues)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors, + }); + return INVALID; + } + } + get options() { + return this._def.options; + } +} +ZodUnion.create = (types, params) => { + return new ZodUnion({ + options: types, + typeName: ZodFirstPartyTypeKind.ZodUnion, + ...processCreateParams(params), + }); +}; +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// +////////// ////////// +////////// ZodDiscriminatedUnion ////////// +////////// ////////// +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// +const getDiscriminator = (type) => { + if (type instanceof ZodLazy) { + return getDiscriminator(type.schema); + } + else if (type instanceof ZodEffects) { + return getDiscriminator(type.innerType()); + } + else if (type instanceof ZodLiteral) { + return [type.value]; + } + else if (type instanceof ZodEnum) { + return type.options; + } + else if (type instanceof ZodNativeEnum) { + // eslint-disable-next-line ban/ban + return util.objectValues(type.enum); + } + else if (type instanceof ZodDefault) { + return getDiscriminator(type._def.innerType); + } + else if (type instanceof ZodUndefined) { + return [undefined]; + } + else if (type instanceof ZodNull) { + return [null]; + } + else if (type instanceof ZodOptional) { + return [undefined, ...getDiscriminator(type.unwrap())]; + } + else if (type instanceof ZodNullable) { + return [null, ...getDiscriminator(type.unwrap())]; + } + else if (type instanceof ZodBranded) { + return getDiscriminator(type.unwrap()); + } + else if (type instanceof ZodReadonly) { + return getDiscriminator(type.unwrap()); + } + else if (type instanceof ZodCatch) { + return getDiscriminator(type._def.innerType); + } + else { + return []; + } +}; +export class ZodDiscriminatedUnion extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType, + }); + return INVALID; + } + const discriminator = this.discriminator; + const discriminatorValue = ctx.data[discriminator]; + const option = this.optionsMap.get(discriminatorValue); + if (!option) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union_discriminator, + options: Array.from(this.optionsMap.keys()), + path: [discriminator], + }); + return INVALID; + } + if (ctx.common.async) { + return option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + } + else { + return option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + } + } + get discriminator() { + return this._def.discriminator; + } + get options() { + return this._def.options; + } + get optionsMap() { + return this._def.optionsMap; + } + /** + * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. + * However, it only allows a union of objects, all of which need to share a discriminator property. This property must + * have a different value for each object in the union. + * @param discriminator the name of the discriminator property + * @param types an array of object schemas + * @param params + */ + static create(discriminator, options, params) { + // Get all the valid discriminator values + const optionsMap = new Map(); + // try { + for (const type of options) { + const discriminatorValues = getDiscriminator(type.shape[discriminator]); + if (!discriminatorValues.length) { + throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); + } + for (const value of discriminatorValues) { + if (optionsMap.has(value)) { + throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); + } + optionsMap.set(value, type); + } + } + return new ZodDiscriminatedUnion({ + typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, + discriminator, + options, + optionsMap, + ...processCreateParams(params), + }); + } +} +function mergeValues(a, b) { + const aType = getParsedType(a); + const bType = getParsedType(b); + if (a === b) { + return { valid: true, data: a }; + } + else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { + const bKeys = util.objectKeys(b); + const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b }; + for (const key of sharedKeys) { + const sharedValue = mergeValues(a[key], b[key]); + if (!sharedValue.valid) { + return { valid: false }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } + else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { + if (a.length !== b.length) { + return { valid: false }; + } + const newArray = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = mergeValues(itemA, itemB); + if (!sharedValue.valid) { + return { valid: false }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } + else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { + return { valid: true, data: a }; + } + else { + return { valid: false }; + } +} +export class ZodIntersection extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const handleParsed = (parsedLeft, parsedRight) => { + if (isAborted(parsedLeft) || isAborted(parsedRight)) { + return INVALID; + } + const merged = mergeValues(parsedLeft.value, parsedRight.value); + if (!merged.valid) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_intersection_types, + }); + return INVALID; + } + if (isDirty(parsedLeft) || isDirty(parsedRight)) { + status.dirty(); + } + return { status: status.value, value: merged.data }; + }; + if (ctx.common.async) { + return Promise.all([ + this._def.left._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), + this._def.right._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), + ]).then(([left, right]) => handleParsed(left, right)); + } + else { + return handleParsed(this._def.left._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), this._def.right._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + })); + } + } +} +ZodIntersection.create = (left, right, params) => { + return new ZodIntersection({ + left: left, + right: right, + typeName: ZodFirstPartyTypeKind.ZodIntersection, + ...processCreateParams(params), + }); +}; +// type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]]; +export class ZodTuple extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType, + }); + return INVALID; + } + if (ctx.data.length < this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: this._def.items.length, + inclusive: true, + exact: false, + type: "array", + }); + return INVALID; + } + const rest = this._def.rest; + if (!rest && ctx.data.length > this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: this._def.items.length, + inclusive: true, + exact: false, + type: "array", + }); + status.dirty(); + } + const items = [...ctx.data] + .map((item, itemIndex) => { + const schema = this._def.items[itemIndex] || this._def.rest; + if (!schema) + return null; + return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); + }) + .filter((x) => !!x); // filter nulls + if (ctx.common.async) { + return Promise.all(items).then((results) => { + return ParseStatus.mergeArray(status, results); + }); + } + else { + return ParseStatus.mergeArray(status, items); + } + } + get items() { + return this._def.items; + } + rest(rest) { + return new ZodTuple({ + ...this._def, + rest, + }); + } +} +ZodTuple.create = (schemas, params) => { + if (!Array.isArray(schemas)) { + throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); + } + return new ZodTuple({ + items: schemas, + typeName: ZodFirstPartyTypeKind.ZodTuple, + rest: null, + ...processCreateParams(params), + }); +}; +export class ZodRecord extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType, + }); + return INVALID; + } + const pairs = []; + const keyType = this._def.keyType; + const valueType = this._def.valueType; + for (const key in ctx.data) { + pairs.push({ + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), + value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), + alwaysSet: key in ctx.data, + }); + } + if (ctx.common.async) { + return ParseStatus.mergeObjectAsync(status, pairs); + } + else { + return ParseStatus.mergeObjectSync(status, pairs); + } + } + get element() { + return this._def.valueType; + } + static create(first, second, third) { + if (second instanceof ZodType) { + return new ZodRecord({ + keyType: first, + valueType: second, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(third), + }); + } + return new ZodRecord({ + keyType: ZodString.create(), + valueType: first, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(second), + }); + } +} +export class ZodMap extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.map) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.map, + received: ctx.parsedType, + }); + return INVALID; + } + const keyType = this._def.keyType; + const valueType = this._def.valueType; + const pairs = [...ctx.data.entries()].map(([key, value], index) => { + return { + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), + value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])), + }; + }); + if (ctx.common.async) { + const finalMap = new Map(); + return Promise.resolve().then(async () => { + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + }); + } + else { + const finalMap = new Map(); + for (const pair of pairs) { + const key = pair.key; + const value = pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + } + } +} +ZodMap.create = (keyType, valueType, params) => { + return new ZodMap({ + valueType, + keyType, + typeName: ZodFirstPartyTypeKind.ZodMap, + ...processCreateParams(params), + }); +}; +export class ZodSet extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.set) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.set, + received: ctx.parsedType, + }); + return INVALID; + } + const def = this._def; + if (def.minSize !== null) { + if (ctx.data.size < def.minSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.minSize.message, + }); + status.dirty(); + } + } + if (def.maxSize !== null) { + if (ctx.data.size > def.maxSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.maxSize.message, + }); + status.dirty(); + } + } + const valueType = this._def.valueType; + function finalizeSet(elements) { + const parsedSet = new Set(); + for (const element of elements) { + if (element.status === "aborted") + return INVALID; + if (element.status === "dirty") + status.dirty(); + parsedSet.add(element.value); + } + return { status: status.value, value: parsedSet }; + } + const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); + if (ctx.common.async) { + return Promise.all(elements).then((elements) => finalizeSet(elements)); + } + else { + return finalizeSet(elements); + } + } + min(minSize, message) { + return new ZodSet({ + ...this._def, + minSize: { value: minSize, message: errorUtil.toString(message) }, + }); + } + max(maxSize, message) { + return new ZodSet({ + ...this._def, + maxSize: { value: maxSize, message: errorUtil.toString(message) }, + }); + } + size(size, message) { + return this.min(size, message).max(size, message); + } + nonempty(message) { + return this.min(1, message); + } +} +ZodSet.create = (valueType, params) => { + return new ZodSet({ + valueType, + minSize: null, + maxSize: null, + typeName: ZodFirstPartyTypeKind.ZodSet, + ...processCreateParams(params), + }); +}; +export class ZodFunction extends ZodType { + constructor() { + super(...arguments); + this.validate = this.implement; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.function) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.function, + received: ctx.parsedType, + }); + return INVALID; + } + function makeArgsIssue(args, error) { + return makeIssue({ + data: args, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_arguments, + argumentsError: error, + }, + }); + } + function makeReturnsIssue(returns, error) { + return makeIssue({ + data: returns, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_return_type, + returnTypeError: error, + }, + }); + } + const params = { errorMap: ctx.common.contextualErrorMap }; + const fn = ctx.data; + if (this._def.returns instanceof ZodPromise) { + // Would love a way to avoid disabling this rule, but we need + // an alias (using an arrow function was what caused 2651). + // eslint-disable-next-line @typescript-eslint/no-this-alias + const me = this; + return OK(async function (...args) { + const error = new ZodError([]); + const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { + error.addIssue(makeArgsIssue(args, e)); + throw error; + }); + const result = await Reflect.apply(fn, this, parsedArgs); + const parsedReturns = await me._def.returns._def.type + .parseAsync(result, params) + .catch((e) => { + error.addIssue(makeReturnsIssue(result, e)); + throw error; + }); + return parsedReturns; + }); + } + else { + // Would love a way to avoid disabling this rule, but we need + // an alias (using an arrow function was what caused 2651). + // eslint-disable-next-line @typescript-eslint/no-this-alias + const me = this; + return OK(function (...args) { + const parsedArgs = me._def.args.safeParse(args, params); + if (!parsedArgs.success) { + throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); + } + const result = Reflect.apply(fn, this, parsedArgs.data); + const parsedReturns = me._def.returns.safeParse(result, params); + if (!parsedReturns.success) { + throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); + } + return parsedReturns.data; + }); + } + } + parameters() { + return this._def.args; + } + returnType() { + return this._def.returns; + } + args(...items) { + return new ZodFunction({ + ...this._def, + args: ZodTuple.create(items).rest(ZodUnknown.create()), + }); + } + returns(returnType) { + return new ZodFunction({ + ...this._def, + returns: returnType, + }); + } + implement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + strictImplement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + static create(args, returns, params) { + return new ZodFunction({ + args: (args ? args : ZodTuple.create([]).rest(ZodUnknown.create())), + returns: returns || ZodUnknown.create(), + typeName: ZodFirstPartyTypeKind.ZodFunction, + ...processCreateParams(params), + }); + } +} +export class ZodLazy extends ZodType { + get schema() { + return this._def.getter(); + } + _parse(input) { + const { ctx } = this._processInputParams(input); + const lazySchema = this._def.getter(); + return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); + } +} +ZodLazy.create = (getter, params) => { + return new ZodLazy({ + getter: getter, + typeName: ZodFirstPartyTypeKind.ZodLazy, + ...processCreateParams(params), + }); +}; +export class ZodLiteral extends ZodType { + _parse(input) { + if (input.data !== this._def.value) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_literal, + expected: this._def.value, + }); + return INVALID; + } + return { status: "valid", value: input.data }; + } + get value() { + return this._def.value; + } +} +ZodLiteral.create = (value, params) => { + return new ZodLiteral({ + value: value, + typeName: ZodFirstPartyTypeKind.ZodLiteral, + ...processCreateParams(params), + }); +}; +function createZodEnum(values, params) { + return new ZodEnum({ + values, + typeName: ZodFirstPartyTypeKind.ZodEnum, + ...processCreateParams(params), + }); +} +export class ZodEnum extends ZodType { + _parse(input) { + if (typeof input.data !== "string") { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type, + }); + return INVALID; + } + if (!this._cache) { + this._cache = new Set(this._def.values); + } + if (!this._cache.has(input.data)) { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues, + }); + return INVALID; + } + return OK(input.data); + } + get options() { + return this._def.values; + } + get enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + get Values() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + get Enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + extract(values, newDef = this._def) { + return ZodEnum.create(values, { + ...this._def, + ...newDef, + }); + } + exclude(values, newDef = this._def) { + return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { + ...this._def, + ...newDef, + }); + } +} +ZodEnum.create = createZodEnum; +export class ZodNativeEnum extends ZodType { + _parse(input) { + const nativeEnumValues = util.getValidEnumValues(this._def.values); + const ctx = this._getOrReturnCtx(input); + if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { + const expectedValues = util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type, + }); + return INVALID; + } + if (!this._cache) { + this._cache = new Set(util.getValidEnumValues(this._def.values)); + } + if (!this._cache.has(input.data)) { + const expectedValues = util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues, + }); + return INVALID; + } + return OK(input.data); + } + get enum() { + return this._def.values; + } +} +ZodNativeEnum.create = (values, params) => { + return new ZodNativeEnum({ + values: values, + typeName: ZodFirstPartyTypeKind.ZodNativeEnum, + ...processCreateParams(params), + }); +}; +export class ZodPromise extends ZodType { + unwrap() { + return this._def.type; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.promise, + received: ctx.parsedType, + }); + return INVALID; + } + const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); + return OK(promisified.then((data) => { + return this._def.type.parseAsync(data, { + path: ctx.path, + errorMap: ctx.common.contextualErrorMap, + }); + })); + } +} +ZodPromise.create = (schema, params) => { + return new ZodPromise({ + type: schema, + typeName: ZodFirstPartyTypeKind.ZodPromise, + ...processCreateParams(params), + }); +}; +export class ZodEffects extends ZodType { + innerType() { + return this._def.schema; + } + sourceType() { + return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects + ? this._def.schema.sourceType() + : this._def.schema; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const effect = this._def.effect || null; + const checkCtx = { + addIssue: (arg) => { + addIssueToContext(ctx, arg); + if (arg.fatal) { + status.abort(); + } + else { + status.dirty(); + } + }, + get path() { + return ctx.path; + }, + }; + checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); + if (effect.type === "preprocess") { + const processed = effect.transform(ctx.data, checkCtx); + if (ctx.common.async) { + return Promise.resolve(processed).then(async (processed) => { + if (status.value === "aborted") + return INVALID; + const result = await this._def.schema._parseAsync({ + data: processed, + path: ctx.path, + parent: ctx, + }); + if (result.status === "aborted") + return INVALID; + if (result.status === "dirty") + return DIRTY(result.value); + if (status.value === "dirty") + return DIRTY(result.value); + return result; + }); + } + else { + if (status.value === "aborted") + return INVALID; + const result = this._def.schema._parseSync({ + data: processed, + path: ctx.path, + parent: ctx, + }); + if (result.status === "aborted") + return INVALID; + if (result.status === "dirty") + return DIRTY(result.value); + if (status.value === "dirty") + return DIRTY(result.value); + return result; + } + } + if (effect.type === "refinement") { + const executeRefinement = (acc) => { + const result = effect.refinement(acc, checkCtx); + if (ctx.common.async) { + return Promise.resolve(result); + } + if (result instanceof Promise) { + throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); + } + return acc; + }; + if (ctx.common.async === false) { + const inner = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + // return value is ignored + executeRefinement(inner.value); + return { status: status.value, value: inner.value }; + } + else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + return executeRefinement(inner.value).then(() => { + return { status: status.value, value: inner.value }; + }); + }); + } + } + if (effect.type === "transform") { + if (ctx.common.async === false) { + const base = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (!isValid(base)) + return INVALID; + const result = effect.transform(base.value, checkCtx); + if (result instanceof Promise) { + throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); + } + return { status: status.value, value: result }; + } + else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { + if (!isValid(base)) + return INVALID; + return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ + status: status.value, + value: result, + })); + }); + } + } + util.assertNever(effect); + } +} +ZodEffects.create = (schema, effect, params) => { + return new ZodEffects({ + schema, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect, + ...processCreateParams(params), + }); +}; +ZodEffects.createWithPreprocess = (preprocess, schema, params) => { + return new ZodEffects({ + schema, + effect: { type: "preprocess", transform: preprocess }, + typeName: ZodFirstPartyTypeKind.ZodEffects, + ...processCreateParams(params), + }); +}; +export { ZodEffects as ZodTransformer }; +export class ZodOptional extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.undefined) { + return OK(undefined); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } +} +ZodOptional.create = (type, params) => { + return new ZodOptional({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodOptional, + ...processCreateParams(params), + }); +}; +export class ZodNullable extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.null) { + return OK(null); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } +} +ZodNullable.create = (type, params) => { + return new ZodNullable({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodNullable, + ...processCreateParams(params), + }); +}; +export class ZodDefault extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + let data = ctx.data; + if (ctx.parsedType === ZodParsedType.undefined) { + data = this._def.defaultValue(); + } + return this._def.innerType._parse({ + data, + path: ctx.path, + parent: ctx, + }); + } + removeDefault() { + return this._def.innerType; + } +} +ZodDefault.create = (type, params) => { + return new ZodDefault({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodDefault, + defaultValue: typeof params.default === "function" ? params.default : () => params.default, + ...processCreateParams(params), + }); +}; +export class ZodCatch extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + // newCtx is used to not collect issues from inner types in ctx + const newCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + }; + const result = this._def.innerType._parse({ + data: newCtx.data, + path: newCtx.path, + parent: { + ...newCtx, + }, + }); + if (isAsync(result)) { + return result.then((result) => { + return { + status: "valid", + value: result.status === "valid" + ? result.value + : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data, + }), + }; + }); + } + else { + return { + status: "valid", + value: result.status === "valid" + ? result.value + : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data, + }), + }; + } + } + removeCatch() { + return this._def.innerType; + } +} +ZodCatch.create = (type, params) => { + return new ZodCatch({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodCatch, + catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, + ...processCreateParams(params), + }); +}; +export class ZodNaN extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.nan) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.nan, + received: ctx.parsedType, + }); + return INVALID; + } + return { status: "valid", value: input.data }; + } +} +ZodNaN.create = (params) => { + return new ZodNaN({ + typeName: ZodFirstPartyTypeKind.ZodNaN, + ...processCreateParams(params), + }); +}; +export const BRAND = Symbol("zod_brand"); +export class ZodBranded extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const data = ctx.data; + return this._def.type._parse({ + data, + path: ctx.path, + parent: ctx, + }); + } + unwrap() { + return this._def.type; + } +} +export class ZodPipeline extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.common.async) { + const handleAsync = async () => { + const inResult = await this._def.in._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return DIRTY(inResult.value); + } + else { + return this._def.out._parseAsync({ + data: inResult.value, + path: ctx.path, + parent: ctx, + }); + } + }; + return handleAsync(); + } + else { + const inResult = this._def.in._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return { + status: "dirty", + value: inResult.value, + }; + } + else { + return this._def.out._parseSync({ + data: inResult.value, + path: ctx.path, + parent: ctx, + }); + } + } + } + static create(a, b) { + return new ZodPipeline({ + in: a, + out: b, + typeName: ZodFirstPartyTypeKind.ZodPipeline, + }); + } +} +export class ZodReadonly extends ZodType { + _parse(input) { + const result = this._def.innerType._parse(input); + const freeze = (data) => { + if (isValid(data)) { + data.value = Object.freeze(data.value); + } + return data; + }; + return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); + } + unwrap() { + return this._def.innerType; + } +} +ZodReadonly.create = (type, params) => { + return new ZodReadonly({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodReadonly, + ...processCreateParams(params), + }); +}; +//////////////////////////////////////// +//////////////////////////////////////// +////////// ////////// +////////// z.custom ////////// +////////// ////////// +//////////////////////////////////////// +//////////////////////////////////////// +function cleanParams(params, data) { + const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; + const p2 = typeof p === "string" ? { message: p } : p; + return p2; +} +export function custom(check, _params = {}, +/** + * @deprecated + * + * Pass `fatal` into the params object instead: + * + * ```ts + * z.string().custom((val) => val.length > 5, { fatal: false }) + * ``` + * + */ +fatal) { + if (check) + return ZodAny.create().superRefine((data, ctx) => { + const r = check(data); + if (r instanceof Promise) { + return r.then((r) => { + if (!r) { + const params = cleanParams(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + }); + } + if (!r) { + const params = cleanParams(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + return; + }); + return ZodAny.create(); +} +export { ZodType as Schema, ZodType as ZodSchema }; +export const late = { + object: ZodObject.lazycreate, +}; +export var ZodFirstPartyTypeKind; +(function (ZodFirstPartyTypeKind) { + ZodFirstPartyTypeKind["ZodString"] = "ZodString"; + ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber"; + ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN"; + ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt"; + ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean"; + ZodFirstPartyTypeKind["ZodDate"] = "ZodDate"; + ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol"; + ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined"; + ZodFirstPartyTypeKind["ZodNull"] = "ZodNull"; + ZodFirstPartyTypeKind["ZodAny"] = "ZodAny"; + ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown"; + ZodFirstPartyTypeKind["ZodNever"] = "ZodNever"; + ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid"; + ZodFirstPartyTypeKind["ZodArray"] = "ZodArray"; + ZodFirstPartyTypeKind["ZodObject"] = "ZodObject"; + ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion"; + ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; + ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection"; + ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple"; + ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord"; + ZodFirstPartyTypeKind["ZodMap"] = "ZodMap"; + ZodFirstPartyTypeKind["ZodSet"] = "ZodSet"; + ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction"; + ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy"; + ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral"; + ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum"; + ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects"; + ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum"; + ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional"; + ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable"; + ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault"; + ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch"; + ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise"; + ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded"; + ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline"; + ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly"; +})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); +// requires TS 4.4+ +class Class { + constructor(..._) { } +} +const instanceOfType = ( +// const instanceOfType = any>( +cls, params = { + message: `Input not instance of ${cls.name}`, +}) => custom((data) => data instanceof cls, params); +const stringType = ZodString.create; +const numberType = ZodNumber.create; +const nanType = ZodNaN.create; +const bigIntType = ZodBigInt.create; +const booleanType = ZodBoolean.create; +const dateType = ZodDate.create; +const symbolType = ZodSymbol.create; +const undefinedType = ZodUndefined.create; +const nullType = ZodNull.create; +const anyType = ZodAny.create; +const unknownType = ZodUnknown.create; +const neverType = ZodNever.create; +const voidType = ZodVoid.create; +const arrayType = ZodArray.create; +const objectType = ZodObject.create; +const strictObjectType = ZodObject.strictCreate; +const unionType = ZodUnion.create; +const discriminatedUnionType = ZodDiscriminatedUnion.create; +const intersectionType = ZodIntersection.create; +const tupleType = ZodTuple.create; +const recordType = ZodRecord.create; +const mapType = ZodMap.create; +const setType = ZodSet.create; +const functionType = ZodFunction.create; +const lazyType = ZodLazy.create; +const literalType = ZodLiteral.create; +const enumType = ZodEnum.create; +const nativeEnumType = ZodNativeEnum.create; +const promiseType = ZodPromise.create; +const effectsType = ZodEffects.create; +const optionalType = ZodOptional.create; +const nullableType = ZodNullable.create; +const preprocessType = ZodEffects.createWithPreprocess; +const pipelineType = ZodPipeline.create; +const ostring = () => stringType().optional(); +const onumber = () => numberType().optional(); +const oboolean = () => booleanType().optional(); +export const coerce = { + string: ((arg) => ZodString.create({ ...arg, coerce: true })), + number: ((arg) => ZodNumber.create({ ...arg, coerce: true })), + boolean: ((arg) => ZodBoolean.create({ + ...arg, + coerce: true, + })), + bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })), + date: ((arg) => ZodDate.create({ ...arg, coerce: true })), +}; +export { anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, dateType as date, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, instanceOfType as instanceof, intersectionType as intersection, lazyType as lazy, literalType as literal, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, recordType as record, setType as set, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, voidType as void, }; +export const NEVER = INVALID; diff --git a/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/index.d.ts b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/index.d.ts new file mode 100644 index 000000000..8352ab713 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/index.d.ts @@ -0,0 +1,3 @@ +import z3 from "./v3/index.js"; +export * from "./v3/index.js"; +export default z3; diff --git a/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/ZodError.d.ts b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/ZodError.d.ts new file mode 100644 index 000000000..4e71355a3 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/ZodError.d.ts @@ -0,0 +1,164 @@ +import type { Primitive } from "./helpers/typeAliases.js"; +import { util, type ZodParsedType } from "./helpers/util.js"; +import type { TypeOf, ZodType } from "./index.js"; +type allKeys = T extends any ? keyof T : never; +export type inferFlattenedErrors, U = string> = typeToFlattenedError, U>; +export type typeToFlattenedError = { + formErrors: U[]; + fieldErrors: { + [P in allKeys]?: U[]; + }; +}; +export declare const ZodIssueCode: { + invalid_type: "invalid_type"; + invalid_literal: "invalid_literal"; + custom: "custom"; + invalid_union: "invalid_union"; + invalid_union_discriminator: "invalid_union_discriminator"; + invalid_enum_value: "invalid_enum_value"; + unrecognized_keys: "unrecognized_keys"; + invalid_arguments: "invalid_arguments"; + invalid_return_type: "invalid_return_type"; + invalid_date: "invalid_date"; + invalid_string: "invalid_string"; + too_small: "too_small"; + too_big: "too_big"; + invalid_intersection_types: "invalid_intersection_types"; + not_multiple_of: "not_multiple_of"; + not_finite: "not_finite"; +}; +export type ZodIssueCode = keyof typeof ZodIssueCode; +export type ZodIssueBase = { + path: (string | number)[]; + message?: string | undefined; +}; +export interface ZodInvalidTypeIssue extends ZodIssueBase { + code: typeof ZodIssueCode.invalid_type; + expected: ZodParsedType; + received: ZodParsedType; +} +export interface ZodInvalidLiteralIssue extends ZodIssueBase { + code: typeof ZodIssueCode.invalid_literal; + expected: unknown; + received: unknown; +} +export interface ZodUnrecognizedKeysIssue extends ZodIssueBase { + code: typeof ZodIssueCode.unrecognized_keys; + keys: string[]; +} +export interface ZodInvalidUnionIssue extends ZodIssueBase { + code: typeof ZodIssueCode.invalid_union; + unionErrors: ZodError[]; +} +export interface ZodInvalidUnionDiscriminatorIssue extends ZodIssueBase { + code: typeof ZodIssueCode.invalid_union_discriminator; + options: Primitive[]; +} +export interface ZodInvalidEnumValueIssue extends ZodIssueBase { + received: string | number; + code: typeof ZodIssueCode.invalid_enum_value; + options: (string | number)[]; +} +export interface ZodInvalidArgumentsIssue extends ZodIssueBase { + code: typeof ZodIssueCode.invalid_arguments; + argumentsError: ZodError; +} +export interface ZodInvalidReturnTypeIssue extends ZodIssueBase { + code: typeof ZodIssueCode.invalid_return_type; + returnTypeError: ZodError; +} +export interface ZodInvalidDateIssue extends ZodIssueBase { + code: typeof ZodIssueCode.invalid_date; +} +export type StringValidation = "email" | "url" | "emoji" | "uuid" | "nanoid" | "regex" | "cuid" | "cuid2" | "ulid" | "datetime" | "date" | "time" | "duration" | "ip" | "cidr" | "base64" | "jwt" | "base64url" | { + includes: string; + position?: number | undefined; +} | { + startsWith: string; +} | { + endsWith: string; +}; +export interface ZodInvalidStringIssue extends ZodIssueBase { + code: typeof ZodIssueCode.invalid_string; + validation: StringValidation; +} +export interface ZodTooSmallIssue extends ZodIssueBase { + code: typeof ZodIssueCode.too_small; + minimum: number | bigint; + inclusive: boolean; + exact?: boolean; + type: "array" | "string" | "number" | "set" | "date" | "bigint"; +} +export interface ZodTooBigIssue extends ZodIssueBase { + code: typeof ZodIssueCode.too_big; + maximum: number | bigint; + inclusive: boolean; + exact?: boolean; + type: "array" | "string" | "number" | "set" | "date" | "bigint"; +} +export interface ZodInvalidIntersectionTypesIssue extends ZodIssueBase { + code: typeof ZodIssueCode.invalid_intersection_types; +} +export interface ZodNotMultipleOfIssue extends ZodIssueBase { + code: typeof ZodIssueCode.not_multiple_of; + multipleOf: number | bigint; +} +export interface ZodNotFiniteIssue extends ZodIssueBase { + code: typeof ZodIssueCode.not_finite; +} +export interface ZodCustomIssue extends ZodIssueBase { + code: typeof ZodIssueCode.custom; + params?: { + [k: string]: any; + }; +} +export type DenormalizedError = { + [k: string]: DenormalizedError | string[]; +}; +export type ZodIssueOptionalMessage = ZodInvalidTypeIssue | ZodInvalidLiteralIssue | ZodUnrecognizedKeysIssue | ZodInvalidUnionIssue | ZodInvalidUnionDiscriminatorIssue | ZodInvalidEnumValueIssue | ZodInvalidArgumentsIssue | ZodInvalidReturnTypeIssue | ZodInvalidDateIssue | ZodInvalidStringIssue | ZodTooSmallIssue | ZodTooBigIssue | ZodInvalidIntersectionTypesIssue | ZodNotMultipleOfIssue | ZodNotFiniteIssue | ZodCustomIssue; +export type ZodIssue = ZodIssueOptionalMessage & { + fatal?: boolean | undefined; + message: string; +}; +export declare const quotelessJson: (obj: any) => string; +type recursiveZodFormattedError = T extends [any, ...any[]] ? { + [K in keyof T]?: ZodFormattedError; +} : T extends any[] ? { + [k: number]: ZodFormattedError; +} : T extends object ? { + [K in keyof T]?: ZodFormattedError; +} : unknown; +export type ZodFormattedError = { + _errors: U[]; +} & recursiveZodFormattedError>; +export type inferFormattedError, U = string> = ZodFormattedError, U>; +export declare class ZodError extends Error { + issues: ZodIssue[]; + get errors(): ZodIssue[]; + constructor(issues: ZodIssue[]); + format(): ZodFormattedError; + format(mapper: (issue: ZodIssue) => U): ZodFormattedError; + static create: (issues: ZodIssue[]) => ZodError; + static assert(value: unknown): asserts value is ZodError; + toString(): string; + get message(): string; + get isEmpty(): boolean; + addIssue: (sub: ZodIssue) => void; + addIssues: (subs?: ZodIssue[]) => void; + flatten(): typeToFlattenedError; + flatten(mapper?: (issue: ZodIssue) => U): typeToFlattenedError; + get formErrors(): typeToFlattenedError; +} +type stripPath = T extends any ? util.OmitKeys : never; +export type IssueData = stripPath & { + path?: (string | number)[]; + fatal?: boolean | undefined; +}; +export type ErrorMapCtx = { + defaultError: string; + data: any; +}; +export type ZodErrorMap = (issue: ZodIssueOptionalMessage, _ctx: ErrorMapCtx) => { + message: string; +}; +export {}; diff --git a/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/errors.d.ts b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/errors.d.ts new file mode 100644 index 000000000..52eacf72e --- /dev/null +++ b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/errors.d.ts @@ -0,0 +1,5 @@ +import type { ZodErrorMap } from "./ZodError.js"; +import defaultErrorMap from "./locales/en.js"; +export { defaultErrorMap }; +export declare function setErrorMap(map: ZodErrorMap): void; +export declare function getErrorMap(): ZodErrorMap; diff --git a/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/external.d.ts b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/external.d.ts new file mode 100644 index 000000000..f0a4be4c7 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/external.d.ts @@ -0,0 +1,6 @@ +export * from "./errors.js"; +export * from "./helpers/parseUtil.js"; +export * from "./helpers/typeAliases.js"; +export * from "./helpers/util.js"; +export * from "./types.js"; +export * from "./ZodError.js"; diff --git a/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/helpers/enumUtil.d.ts b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/helpers/enumUtil.d.ts new file mode 100644 index 000000000..fad28a711 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/helpers/enumUtil.d.ts @@ -0,0 +1,8 @@ +export declare namespace enumUtil { + type UnionToIntersectionFn = (T extends unknown ? (k: () => T) => void : never) extends (k: infer Intersection) => void ? Intersection : never; + type GetUnionLast = UnionToIntersectionFn extends () => infer Last ? Last : never; + type UnionToTuple = [T] extends [never] ? Tuple : UnionToTuple>, [GetUnionLast, ...Tuple]>; + type CastToStringTuple = T extends [string, ...string[]] ? T : never; + export type UnionToTupleString = CastToStringTuple>; + export {}; +} diff --git a/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/helpers/errorUtil.d.ts b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/helpers/errorUtil.d.ts new file mode 100644 index 000000000..bc9b033ff --- /dev/null +++ b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/helpers/errorUtil.d.ts @@ -0,0 +1,9 @@ +export declare namespace errorUtil { + type ErrMessage = string | { + message?: string | undefined; + }; + const errToObj: (message?: ErrMessage) => { + message?: string | undefined; + }; + const toString: (message?: ErrMessage) => string | undefined; +} diff --git a/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/helpers/parseUtil.d.ts b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/helpers/parseUtil.d.ts new file mode 100644 index 000000000..e4dc1d7b3 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/helpers/parseUtil.d.ts @@ -0,0 +1,78 @@ +import type { IssueData, ZodErrorMap, ZodIssue } from "../ZodError.js"; +import type { ZodParsedType } from "./util.js"; +export declare const makeIssue: (params: { + data: any; + path: (string | number)[]; + errorMaps: ZodErrorMap[]; + issueData: IssueData; +}) => ZodIssue; +export type ParseParams = { + path: (string | number)[]; + errorMap: ZodErrorMap; + async: boolean; +}; +export type ParsePathComponent = string | number; +export type ParsePath = ParsePathComponent[]; +export declare const EMPTY_PATH: ParsePath; +export interface ParseContext { + readonly common: { + readonly issues: ZodIssue[]; + readonly contextualErrorMap?: ZodErrorMap | undefined; + readonly async: boolean; + }; + readonly path: ParsePath; + readonly schemaErrorMap?: ZodErrorMap | undefined; + readonly parent: ParseContext | null; + readonly data: any; + readonly parsedType: ZodParsedType; +} +export type ParseInput = { + data: any; + path: (string | number)[]; + parent: ParseContext; +}; +export declare function addIssueToContext(ctx: ParseContext, issueData: IssueData): void; +export type ObjectPair = { + key: SyncParseReturnType; + value: SyncParseReturnType; +}; +export declare class ParseStatus { + value: "aborted" | "dirty" | "valid"; + dirty(): void; + abort(): void; + static mergeArray(status: ParseStatus, results: SyncParseReturnType[]): SyncParseReturnType; + static mergeObjectAsync(status: ParseStatus, pairs: { + key: ParseReturnType; + value: ParseReturnType; + }[]): Promise>; + static mergeObjectSync(status: ParseStatus, pairs: { + key: SyncParseReturnType; + value: SyncParseReturnType; + alwaysSet?: boolean; + }[]): SyncParseReturnType; +} +export interface ParseResult { + status: "aborted" | "dirty" | "valid"; + data: any; +} +export type INVALID = { + status: "aborted"; +}; +export declare const INVALID: INVALID; +export type DIRTY = { + status: "dirty"; + value: T; +}; +export declare const DIRTY: (value: T) => DIRTY; +export type OK = { + status: "valid"; + value: T; +}; +export declare const OK: (value: T) => OK; +export type SyncParseReturnType = OK | DIRTY | INVALID; +export type AsyncParseReturnType = Promise>; +export type ParseReturnType = SyncParseReturnType | AsyncParseReturnType; +export declare const isAborted: (x: ParseReturnType) => x is INVALID; +export declare const isDirty: (x: ParseReturnType) => x is OK | DIRTY; +export declare const isValid: (x: ParseReturnType) => x is OK; +export declare const isAsync: (x: ParseReturnType) => x is AsyncParseReturnType; diff --git a/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/helpers/partialUtil.d.ts b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/helpers/partialUtil.d.ts new file mode 100644 index 000000000..d07657a25 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/helpers/partialUtil.d.ts @@ -0,0 +1,8 @@ +import type { ZodArray, ZodNullable, ZodObject, ZodOptional, ZodRawShape, ZodTuple, ZodTupleItems, ZodTypeAny } from "../types.js"; +export declare namespace partialUtil { + type DeepPartial = T extends ZodObject ? ZodObject<{ + [k in keyof T["shape"]]: ZodOptional>; + }, T["_def"]["unknownKeys"], T["_def"]["catchall"]> : T extends ZodArray ? ZodArray, Card> : T extends ZodOptional ? ZodOptional> : T extends ZodNullable ? ZodNullable> : T extends ZodTuple ? { + [k in keyof Items]: Items[k] extends ZodTypeAny ? DeepPartial : never; + } extends infer PI ? PI extends ZodTupleItems ? ZodTuple : never : never : T; +} diff --git a/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/helpers/typeAliases.d.ts b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/helpers/typeAliases.d.ts new file mode 100644 index 000000000..32df022ca --- /dev/null +++ b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/helpers/typeAliases.d.ts @@ -0,0 +1,2 @@ +export type Primitive = string | number | symbol | bigint | boolean | null | undefined; +export type Scalars = Primitive | Primitive[]; diff --git a/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/helpers/util.d.ts b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/helpers/util.d.ts new file mode 100644 index 000000000..eeaaeee1c --- /dev/null +++ b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/helpers/util.d.ts @@ -0,0 +1,85 @@ +export declare namespace util { + type AssertEqual = (() => V extends T ? 1 : 2) extends () => V extends U ? 1 : 2 ? true : false; + export type isAny = 0 extends 1 & T ? true : false; + export const assertEqual: (_: AssertEqual) => void; + export function assertIs(_arg: T): void; + export function assertNever(_x: never): never; + export type Omit = Pick>; + export type OmitKeys = Pick>; + export type MakePartial = Omit & Partial>; + export type Exactly = T & Record, never>; + export type InexactPartial = { + [k in keyof T]?: T[k] | undefined; + }; + export const arrayToEnum: (items: U) => { [k in U[number]]: k; }; + export const getValidEnumValues: (obj: any) => any[]; + export const objectValues: (obj: any) => any[]; + export const objectKeys: ObjectConstructor["keys"]; + export const find: (arr: T[], checker: (arg: T) => any) => T | undefined; + export type identity = objectUtil.identity; + export type flatten = objectUtil.flatten; + export type noUndefined = T extends undefined ? never : T; + export const isInteger: NumberConstructor["isInteger"]; + export function joinValues(array: T, separator?: string): string; + export const jsonStringifyReplacer: (_: string, value: any) => any; + export {}; +} +export declare namespace objectUtil { + export type MergeShapes = keyof U & keyof V extends never ? U & V : { + [k in Exclude]: U[k]; + } & V; + type optionalKeys = { + [k in keyof T]: undefined extends T[k] ? k : never; + }[keyof T]; + type requiredKeys = { + [k in keyof T]: undefined extends T[k] ? never : k; + }[keyof T]; + export type addQuestionMarks = { + [K in requiredKeys]: T[K]; + } & { + [K in optionalKeys]?: T[K]; + } & { + [k in keyof T]?: unknown; + }; + export type identity = T; + export type flatten = identity<{ + [k in keyof T]: T[k]; + }>; + export type noNeverKeys = { + [k in keyof T]: [T[k]] extends [never] ? never : k; + }[keyof T]; + export type noNever = identity<{ + [k in noNeverKeys]: k extends keyof T ? T[k] : never; + }>; + export const mergeShapes: (first: U, second: T) => T & U; + export type extendShape = keyof A & keyof B extends never ? A & B : { + [K in keyof A as K extends keyof B ? never : K]: A[K]; + } & { + [K in keyof B]: B[K]; + }; + export {}; +} +export declare const ZodParsedType: { + string: "string"; + nan: "nan"; + number: "number"; + integer: "integer"; + float: "float"; + boolean: "boolean"; + date: "date"; + bigint: "bigint"; + symbol: "symbol"; + function: "function"; + undefined: "undefined"; + null: "null"; + array: "array"; + object: "object"; + unknown: "unknown"; + promise: "promise"; + void: "void"; + never: "never"; + map: "map"; + set: "set"; +}; +export type ZodParsedType = keyof typeof ZodParsedType; +export declare const getParsedType: (data: any) => ZodParsedType; diff --git a/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/index.d.ts b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/index.d.ts new file mode 100644 index 000000000..a9dab5738 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/index.d.ts @@ -0,0 +1,4 @@ +import * as z from "./external.js"; +export * from "./external.js"; +export { z }; +export default z; diff --git a/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/locales/en.d.ts b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/locales/en.d.ts new file mode 100644 index 000000000..b2bea1ec4 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/locales/en.d.ts @@ -0,0 +1,3 @@ +import { type ZodErrorMap } from "../ZodError.js"; +declare const errorMap: ZodErrorMap; +export default errorMap; diff --git a/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/standard-schema.d.ts b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/standard-schema.d.ts new file mode 100644 index 000000000..7ddff3b7f --- /dev/null +++ b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/standard-schema.d.ts @@ -0,0 +1,102 @@ +/** + * The Standard Schema interface. + */ +export type StandardSchemaV1 = { + /** + * The Standard Schema properties. + */ + readonly "~standard": StandardSchemaV1.Props; +}; +export declare namespace StandardSchemaV1 { + /** + * The Standard Schema properties interface. + */ + export interface Props { + /** + * The version number of the standard. + */ + readonly version: 1; + /** + * The vendor name of the schema library. + */ + readonly vendor: string; + /** + * Validates unknown input values. + */ + readonly validate: (value: unknown) => Result | Promise>; + /** + * Inferred types associated with the schema. + */ + readonly types?: Types | undefined; + } + /** + * The result interface of the validate function. + */ + export type Result = SuccessResult | FailureResult; + /** + * The result interface if validation succeeds. + */ + export interface SuccessResult { + /** + * The typed output value. + */ + readonly value: Output; + /** + * The non-existent issues. + */ + readonly issues?: undefined; + } + /** + * The result interface if validation fails. + */ + export interface FailureResult { + /** + * The issues of failed validation. + */ + readonly issues: ReadonlyArray; + } + /** + * The issue interface of the failure output. + */ + export interface Issue { + /** + * The error message of the issue. + */ + readonly message: string; + /** + * The path of the issue, if any. + */ + readonly path?: ReadonlyArray | undefined; + } + /** + * The path segment interface of the issue. + */ + export interface PathSegment { + /** + * The key representing a path segment. + */ + readonly key: PropertyKey; + } + /** + * The Standard Schema types interface. + */ + export interface Types { + /** + * The input type of the schema. + */ + readonly input: Input; + /** + * The output type of the schema. + */ + readonly output: Output; + } + /** + * Infers the input type of a Standard Schema. + */ + export type InferInput = NonNullable["input"]; + /** + * Infers the output type of a Standard Schema. + */ + export type InferOutput = NonNullable["output"]; + export {}; +} diff --git a/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/types.d.ts b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/types.d.ts new file mode 100644 index 000000000..301e09128 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/dist/types/v3/types.d.ts @@ -0,0 +1,1031 @@ +import { type IssueData, type StringValidation, type ZodCustomIssue, ZodError, type ZodErrorMap } from "./ZodError.js"; +import type { enumUtil } from "./helpers/enumUtil.js"; +import { errorUtil } from "./helpers/errorUtil.js"; +import { type AsyncParseReturnType, INVALID, type ParseContext, type ParseInput, type ParseParams, type ParseReturnType, ParseStatus, type SyncParseReturnType } from "./helpers/parseUtil.js"; +import type { partialUtil } from "./helpers/partialUtil.js"; +import type { Primitive } from "./helpers/typeAliases.js"; +import { util, type objectUtil } from "./helpers/util.js"; +import type { StandardSchemaV1 } from "./standard-schema.js"; +export interface RefinementCtx { + addIssue: (arg: IssueData) => void; + path: (string | number)[]; +} +export type ZodRawShape = { + [k: string]: ZodTypeAny; +}; +export type ZodTypeAny = ZodType; +export type TypeOf> = T["_output"]; +export type input> = T["_input"]; +export type output> = T["_output"]; +export type { TypeOf as infer }; +export type CustomErrorParams = Partial>; +export interface ZodTypeDef { + errorMap?: ZodErrorMap | undefined; + description?: string | undefined; +} +export type RawCreateParams = { + errorMap?: ZodErrorMap | undefined; + invalid_type_error?: string | undefined; + required_error?: string | undefined; + message?: string | undefined; + description?: string | undefined; +} | undefined; +export type ProcessedCreateParams = { + errorMap?: ZodErrorMap | undefined; + description?: string | undefined; +}; +export type SafeParseSuccess = { + success: true; + data: Output; + error?: never; +}; +export type SafeParseError = { + success: false; + error: ZodError; + data?: never; +}; +export type SafeParseReturnType = SafeParseSuccess | SafeParseError; +export declare abstract class ZodType { + readonly _type: Output; + readonly _output: Output; + readonly _input: Input; + readonly _def: Def; + get description(): string | undefined; + "~standard": StandardSchemaV1.Props; + abstract _parse(input: ParseInput): ParseReturnType; + _getType(input: ParseInput): string; + _getOrReturnCtx(input: ParseInput, ctx?: ParseContext | undefined): ParseContext; + _processInputParams(input: ParseInput): { + status: ParseStatus; + ctx: ParseContext; + }; + _parseSync(input: ParseInput): SyncParseReturnType; + _parseAsync(input: ParseInput): AsyncParseReturnType; + parse(data: unknown, params?: util.InexactPartial): Output; + safeParse(data: unknown, params?: util.InexactPartial): SafeParseReturnType; + "~validate"(data: unknown): StandardSchemaV1.Result | Promise>; + parseAsync(data: unknown, params?: util.InexactPartial): Promise; + safeParseAsync(data: unknown, params?: util.InexactPartial): Promise>; + /** Alias of safeParseAsync */ + spa: (data: unknown, params?: util.InexactPartial) => Promise>; + refine(check: (arg: Output) => arg is RefinedOutput, message?: string | CustomErrorParams | ((arg: Output) => CustomErrorParams)): ZodEffects; + refine(check: (arg: Output) => unknown | Promise, message?: string | CustomErrorParams | ((arg: Output) => CustomErrorParams)): ZodEffects; + refinement(check: (arg: Output) => arg is RefinedOutput, refinementData: IssueData | ((arg: Output, ctx: RefinementCtx) => IssueData)): ZodEffects; + refinement(check: (arg: Output) => boolean, refinementData: IssueData | ((arg: Output, ctx: RefinementCtx) => IssueData)): ZodEffects; + _refinement(refinement: RefinementEffect["refinement"]): ZodEffects; + superRefine(refinement: (arg: Output, ctx: RefinementCtx) => arg is RefinedOutput): ZodEffects; + superRefine(refinement: (arg: Output, ctx: RefinementCtx) => void): ZodEffects; + superRefine(refinement: (arg: Output, ctx: RefinementCtx) => Promise): ZodEffects; + constructor(def: Def); + optional(): ZodOptional; + nullable(): ZodNullable; + nullish(): ZodOptional>; + array(): ZodArray; + promise(): ZodPromise; + or(option: T): ZodUnion<[this, T]>; + and(incoming: T): ZodIntersection; + transform(transform: (arg: Output, ctx: RefinementCtx) => NewOut | Promise): ZodEffects; + default(def: util.noUndefined): ZodDefault; + default(def: () => util.noUndefined): ZodDefault; + brand(brand?: B): ZodBranded; + catch(def: Output): ZodCatch; + catch(def: (ctx: { + error: ZodError; + input: Input; + }) => Output): ZodCatch; + describe(description: string): this; + pipe(target: T): ZodPipeline; + readonly(): ZodReadonly; + isOptional(): boolean; + isNullable(): boolean; +} +export type IpVersion = "v4" | "v6"; +export type ZodStringCheck = { + kind: "min"; + value: number; + message?: string | undefined; +} | { + kind: "max"; + value: number; + message?: string | undefined; +} | { + kind: "length"; + value: number; + message?: string | undefined; +} | { + kind: "email"; + message?: string | undefined; +} | { + kind: "url"; + message?: string | undefined; +} | { + kind: "emoji"; + message?: string | undefined; +} | { + kind: "uuid"; + message?: string | undefined; +} | { + kind: "nanoid"; + message?: string | undefined; +} | { + kind: "cuid"; + message?: string | undefined; +} | { + kind: "includes"; + value: string; + position?: number | undefined; + message?: string | undefined; +} | { + kind: "cuid2"; + message?: string | undefined; +} | { + kind: "ulid"; + message?: string | undefined; +} | { + kind: "startsWith"; + value: string; + message?: string | undefined; +} | { + kind: "endsWith"; + value: string; + message?: string | undefined; +} | { + kind: "regex"; + regex: RegExp; + message?: string | undefined; +} | { + kind: "trim"; + message?: string | undefined; +} | { + kind: "toLowerCase"; + message?: string | undefined; +} | { + kind: "toUpperCase"; + message?: string | undefined; +} | { + kind: "jwt"; + alg?: string; + message?: string | undefined; +} | { + kind: "datetime"; + offset: boolean; + local: boolean; + precision: number | null; + message?: string | undefined; +} | { + kind: "date"; + message?: string | undefined; +} | { + kind: "time"; + precision: number | null; + message?: string | undefined; +} | { + kind: "duration"; + message?: string | undefined; +} | { + kind: "ip"; + version?: IpVersion | undefined; + message?: string | undefined; +} | { + kind: "cidr"; + version?: IpVersion | undefined; + message?: string | undefined; +} | { + kind: "base64"; + message?: string | undefined; +} | { + kind: "base64url"; + message?: string | undefined; +}; +export interface ZodStringDef extends ZodTypeDef { + checks: ZodStringCheck[]; + typeName: ZodFirstPartyTypeKind.ZodString; + coerce: boolean; +} +export declare function datetimeRegex(args: { + precision?: number | null; + offset?: boolean; + local?: boolean; +}): RegExp; +export declare class ZodString extends ZodType { + _parse(input: ParseInput): ParseReturnType; + protected _regex(regex: RegExp, validation: StringValidation, message?: errorUtil.ErrMessage): ZodEffects; + _addCheck(check: ZodStringCheck): ZodString; + email(message?: errorUtil.ErrMessage): ZodString; + url(message?: errorUtil.ErrMessage): ZodString; + emoji(message?: errorUtil.ErrMessage): ZodString; + uuid(message?: errorUtil.ErrMessage): ZodString; + nanoid(message?: errorUtil.ErrMessage): ZodString; + cuid(message?: errorUtil.ErrMessage): ZodString; + cuid2(message?: errorUtil.ErrMessage): ZodString; + ulid(message?: errorUtil.ErrMessage): ZodString; + base64(message?: errorUtil.ErrMessage): ZodString; + base64url(message?: errorUtil.ErrMessage): ZodString; + jwt(options?: { + alg?: string; + message?: string | undefined; + }): ZodString; + ip(options?: string | { + version?: IpVersion; + message?: string | undefined; + }): ZodString; + cidr(options?: string | { + version?: IpVersion; + message?: string | undefined; + }): ZodString; + datetime(options?: string | { + message?: string | undefined; + precision?: number | null; + offset?: boolean; + local?: boolean; + }): ZodString; + date(message?: string): ZodString; + time(options?: string | { + message?: string | undefined; + precision?: number | null; + }): ZodString; + duration(message?: errorUtil.ErrMessage): ZodString; + regex(regex: RegExp, message?: errorUtil.ErrMessage): ZodString; + includes(value: string, options?: { + message?: string; + position?: number; + }): ZodString; + startsWith(value: string, message?: errorUtil.ErrMessage): ZodString; + endsWith(value: string, message?: errorUtil.ErrMessage): ZodString; + min(minLength: number, message?: errorUtil.ErrMessage): ZodString; + max(maxLength: number, message?: errorUtil.ErrMessage): ZodString; + length(len: number, message?: errorUtil.ErrMessage): ZodString; + /** + * Equivalent to `.min(1)` + */ + nonempty(message?: errorUtil.ErrMessage): ZodString; + trim(): ZodString; + toLowerCase(): ZodString; + toUpperCase(): ZodString; + get isDatetime(): boolean; + get isDate(): boolean; + get isTime(): boolean; + get isDuration(): boolean; + get isEmail(): boolean; + get isURL(): boolean; + get isEmoji(): boolean; + get isUUID(): boolean; + get isNANOID(): boolean; + get isCUID(): boolean; + get isCUID2(): boolean; + get isULID(): boolean; + get isIP(): boolean; + get isCIDR(): boolean; + get isBase64(): boolean; + get isBase64url(): boolean; + get minLength(): number | null; + get maxLength(): number | null; + static create: (params?: RawCreateParams & { + coerce?: true; + }) => ZodString; +} +export type ZodNumberCheck = { + kind: "min"; + value: number; + inclusive: boolean; + message?: string | undefined; +} | { + kind: "max"; + value: number; + inclusive: boolean; + message?: string | undefined; +} | { + kind: "int"; + message?: string | undefined; +} | { + kind: "multipleOf"; + value: number; + message?: string | undefined; +} | { + kind: "finite"; + message?: string | undefined; +}; +export interface ZodNumberDef extends ZodTypeDef { + checks: ZodNumberCheck[]; + typeName: ZodFirstPartyTypeKind.ZodNumber; + coerce: boolean; +} +export declare class ZodNumber extends ZodType { + _parse(input: ParseInput): ParseReturnType; + static create: (params?: RawCreateParams & { + coerce?: boolean; + }) => ZodNumber; + gte(value: number, message?: errorUtil.ErrMessage): ZodNumber; + min: (value: number, message?: errorUtil.ErrMessage) => ZodNumber; + gt(value: number, message?: errorUtil.ErrMessage): ZodNumber; + lte(value: number, message?: errorUtil.ErrMessage): ZodNumber; + max: (value: number, message?: errorUtil.ErrMessage) => ZodNumber; + lt(value: number, message?: errorUtil.ErrMessage): ZodNumber; + protected setLimit(kind: "min" | "max", value: number, inclusive: boolean, message?: string): ZodNumber; + _addCheck(check: ZodNumberCheck): ZodNumber; + int(message?: errorUtil.ErrMessage): ZodNumber; + positive(message?: errorUtil.ErrMessage): ZodNumber; + negative(message?: errorUtil.ErrMessage): ZodNumber; + nonpositive(message?: errorUtil.ErrMessage): ZodNumber; + nonnegative(message?: errorUtil.ErrMessage): ZodNumber; + multipleOf(value: number, message?: errorUtil.ErrMessage): ZodNumber; + step: (value: number, message?: errorUtil.ErrMessage) => ZodNumber; + finite(message?: errorUtil.ErrMessage): ZodNumber; + safe(message?: errorUtil.ErrMessage): ZodNumber; + get minValue(): number | null; + get maxValue(): number | null; + get isInt(): boolean; + get isFinite(): boolean; +} +export type ZodBigIntCheck = { + kind: "min"; + value: bigint; + inclusive: boolean; + message?: string | undefined; +} | { + kind: "max"; + value: bigint; + inclusive: boolean; + message?: string | undefined; +} | { + kind: "multipleOf"; + value: bigint; + message?: string | undefined; +}; +export interface ZodBigIntDef extends ZodTypeDef { + checks: ZodBigIntCheck[]; + typeName: ZodFirstPartyTypeKind.ZodBigInt; + coerce: boolean; +} +export declare class ZodBigInt extends ZodType { + _parse(input: ParseInput): ParseReturnType; + _getInvalidInput(input: ParseInput): INVALID; + static create: (params?: RawCreateParams & { + coerce?: boolean; + }) => ZodBigInt; + gte(value: bigint, message?: errorUtil.ErrMessage): ZodBigInt; + min: (value: bigint, message?: errorUtil.ErrMessage) => ZodBigInt; + gt(value: bigint, message?: errorUtil.ErrMessage): ZodBigInt; + lte(value: bigint, message?: errorUtil.ErrMessage): ZodBigInt; + max: (value: bigint, message?: errorUtil.ErrMessage) => ZodBigInt; + lt(value: bigint, message?: errorUtil.ErrMessage): ZodBigInt; + protected setLimit(kind: "min" | "max", value: bigint, inclusive: boolean, message?: string): ZodBigInt; + _addCheck(check: ZodBigIntCheck): ZodBigInt; + positive(message?: errorUtil.ErrMessage): ZodBigInt; + negative(message?: errorUtil.ErrMessage): ZodBigInt; + nonpositive(message?: errorUtil.ErrMessage): ZodBigInt; + nonnegative(message?: errorUtil.ErrMessage): ZodBigInt; + multipleOf(value: bigint, message?: errorUtil.ErrMessage): ZodBigInt; + get minValue(): bigint | null; + get maxValue(): bigint | null; +} +export interface ZodBooleanDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodBoolean; + coerce: boolean; +} +export declare class ZodBoolean extends ZodType { + _parse(input: ParseInput): ParseReturnType; + static create: (params?: RawCreateParams & { + coerce?: boolean; + }) => ZodBoolean; +} +export type ZodDateCheck = { + kind: "min"; + value: number; + message?: string | undefined; +} | { + kind: "max"; + value: number; + message?: string | undefined; +}; +export interface ZodDateDef extends ZodTypeDef { + checks: ZodDateCheck[]; + coerce: boolean; + typeName: ZodFirstPartyTypeKind.ZodDate; +} +export declare class ZodDate extends ZodType { + _parse(input: ParseInput): ParseReturnType; + _addCheck(check: ZodDateCheck): ZodDate; + min(minDate: Date, message?: errorUtil.ErrMessage): ZodDate; + max(maxDate: Date, message?: errorUtil.ErrMessage): ZodDate; + get minDate(): Date | null; + get maxDate(): Date | null; + static create: (params?: RawCreateParams & { + coerce?: boolean; + }) => ZodDate; +} +export interface ZodSymbolDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodSymbol; +} +export declare class ZodSymbol extends ZodType { + _parse(input: ParseInput): ParseReturnType; + static create: (params?: RawCreateParams) => ZodSymbol; +} +export interface ZodUndefinedDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodUndefined; +} +export declare class ZodUndefined extends ZodType { + _parse(input: ParseInput): ParseReturnType; + params?: RawCreateParams; + static create: (params?: RawCreateParams) => ZodUndefined; +} +export interface ZodNullDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodNull; +} +export declare class ZodNull extends ZodType { + _parse(input: ParseInput): ParseReturnType; + static create: (params?: RawCreateParams) => ZodNull; +} +export interface ZodAnyDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodAny; +} +export declare class ZodAny extends ZodType { + _any: true; + _parse(input: ParseInput): ParseReturnType; + static create: (params?: RawCreateParams) => ZodAny; +} +export interface ZodUnknownDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodUnknown; +} +export declare class ZodUnknown extends ZodType { + _unknown: true; + _parse(input: ParseInput): ParseReturnType; + static create: (params?: RawCreateParams) => ZodUnknown; +} +export interface ZodNeverDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodNever; +} +export declare class ZodNever extends ZodType { + _parse(input: ParseInput): ParseReturnType; + static create: (params?: RawCreateParams) => ZodNever; +} +export interface ZodVoidDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodVoid; +} +export declare class ZodVoid extends ZodType { + _parse(input: ParseInput): ParseReturnType; + static create: (params?: RawCreateParams) => ZodVoid; +} +export interface ZodArrayDef extends ZodTypeDef { + type: T; + typeName: ZodFirstPartyTypeKind.ZodArray; + exactLength: { + value: number; + message?: string | undefined; + } | null; + minLength: { + value: number; + message?: string | undefined; + } | null; + maxLength: { + value: number; + message?: string | undefined; + } | null; +} +export type ArrayCardinality = "many" | "atleastone"; +export type arrayOutputType = Cardinality extends "atleastone" ? [T["_output"], ...T["_output"][]] : T["_output"][]; +export declare class ZodArray extends ZodType, ZodArrayDef, Cardinality extends "atleastone" ? [T["_input"], ...T["_input"][]] : T["_input"][]> { + _parse(input: ParseInput): ParseReturnType; + get element(): T; + min(minLength: number, message?: errorUtil.ErrMessage): this; + max(maxLength: number, message?: errorUtil.ErrMessage): this; + length(len: number, message?: errorUtil.ErrMessage): this; + nonempty(message?: errorUtil.ErrMessage): ZodArray; + static create: (schema: El, params?: RawCreateParams) => ZodArray; +} +export type ZodNonEmptyArray = ZodArray; +export type UnknownKeysParam = "passthrough" | "strict" | "strip"; +export interface ZodObjectDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodObject; + shape: () => T; + catchall: Catchall; + unknownKeys: UnknownKeys; +} +export type mergeTypes = { + [k in keyof A | keyof B]: k extends keyof B ? B[k] : k extends keyof A ? A[k] : never; +}; +export type objectOutputType = objectUtil.flatten>> & CatchallOutput & PassthroughType; +export type baseObjectOutputType = { + [k in keyof Shape]: Shape[k]["_output"]; +}; +export type objectInputType = objectUtil.flatten> & CatchallInput & PassthroughType; +export type baseObjectInputType = objectUtil.addQuestionMarks<{ + [k in keyof Shape]: Shape[k]["_input"]; +}>; +export type CatchallOutput = ZodType extends T ? unknown : { + [k: string]: T["_output"]; +}; +export type CatchallInput = ZodType extends T ? unknown : { + [k: string]: T["_input"]; +}; +export type PassthroughType = T extends "passthrough" ? { + [k: string]: unknown; +} : unknown; +export type deoptional = T extends ZodOptional ? deoptional : T extends ZodNullable ? ZodNullable> : T; +export type SomeZodObject = ZodObject; +export type noUnrecognized = { + [k in keyof Obj]: k extends keyof Shape ? Obj[k] : never; +}; +export declare class ZodObject, Input = objectInputType> extends ZodType, Input> { + private _cached; + _getCached(): { + shape: T; + keys: string[]; + }; + _parse(input: ParseInput): ParseReturnType; + get shape(): T; + strict(message?: errorUtil.ErrMessage): ZodObject; + strip(): ZodObject; + passthrough(): ZodObject; + /** + * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped. + * If you want to pass through unknown properties, use `.passthrough()` instead. + */ + nonstrict: () => ZodObject; + extend(augmentation: Augmentation): ZodObject, UnknownKeys, Catchall>; + /** + * @deprecated Use `.extend` instead + * */ + augment: (augmentation: Augmentation) => ZodObject, UnknownKeys, Catchall>; + /** + * Prior to zod@1.0.12 there was a bug in the + * inferred type of merged objects. Please + * upgrade if you are experiencing issues. + */ + merge(merging: Incoming): ZodObject, Incoming["_def"]["unknownKeys"], Incoming["_def"]["catchall"]>; + setKey(key: Key, schema: Schema): ZodObject; + catchall(index: Index): ZodObject; + pick>(mask: Mask): ZodObject>, UnknownKeys, Catchall>; + omit>(mask: Mask): ZodObject, UnknownKeys, Catchall>; + /** + * @deprecated + */ + deepPartial(): partialUtil.DeepPartial; + partial(): ZodObject<{ + [k in keyof T]: ZodOptional; + }, UnknownKeys, Catchall>; + partial>(mask: Mask): ZodObject : T[k]; + }>, UnknownKeys, Catchall>; + required(): ZodObject<{ + [k in keyof T]: deoptional; + }, UnknownKeys, Catchall>; + required>(mask: Mask): ZodObject : T[k]; + }>, UnknownKeys, Catchall>; + keyof(): ZodEnum>; + static create: (shape: Shape, params?: RawCreateParams) => ZodObject, objectInputType>; + static strictCreate: (shape: Shape, params?: RawCreateParams) => ZodObject; + static lazycreate: (shape: () => Shape, params?: RawCreateParams) => ZodObject; +} +export type AnyZodObject = ZodObject; +export type ZodUnionOptions = Readonly<[ZodTypeAny, ...ZodTypeAny[]]>; +export interface ZodUnionDef> extends ZodTypeDef { + options: T; + typeName: ZodFirstPartyTypeKind.ZodUnion; +} +export declare class ZodUnion extends ZodType, T[number]["_input"]> { + _parse(input: ParseInput): ParseReturnType; + get options(): T; + static create: >(types: Options, params?: RawCreateParams) => ZodUnion; +} +export type ZodDiscriminatedUnionOption = ZodObject<{ + [key in Discriminator]: ZodTypeAny; +} & ZodRawShape, UnknownKeysParam, ZodTypeAny>; +export interface ZodDiscriminatedUnionDef[] = ZodDiscriminatedUnionOption[]> extends ZodTypeDef { + discriminator: Discriminator; + options: Options; + optionsMap: Map>; + typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion; +} +export declare class ZodDiscriminatedUnion[]> extends ZodType, ZodDiscriminatedUnionDef, input> { + _parse(input: ParseInput): ParseReturnType; + get discriminator(): Discriminator; + get options(): Options; + get optionsMap(): Map>; + /** + * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. + * However, it only allows a union of objects, all of which need to share a discriminator property. This property must + * have a different value for each object in the union. + * @param discriminator the name of the discriminator property + * @param types an array of object schemas + * @param params + */ + static create, + ...ZodDiscriminatedUnionOption[] + ]>(discriminator: Discriminator, options: Types, params?: RawCreateParams): ZodDiscriminatedUnion; +} +export interface ZodIntersectionDef extends ZodTypeDef { + left: T; + right: U; + typeName: ZodFirstPartyTypeKind.ZodIntersection; +} +export declare class ZodIntersection extends ZodType, T["_input"] & U["_input"]> { + _parse(input: ParseInput): ParseReturnType; + static create: (left: TSchema, right: USchema, params?: RawCreateParams) => ZodIntersection; +} +export type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]]; +export type AssertArray = T extends any[] ? T : never; +export type OutputTypeOfTuple = AssertArray<{ + [k in keyof T]: T[k] extends ZodType ? T[k]["_output"] : never; +}>; +export type OutputTypeOfTupleWithRest = Rest extends ZodTypeAny ? [...OutputTypeOfTuple, ...Rest["_output"][]] : OutputTypeOfTuple; +export type InputTypeOfTuple = AssertArray<{ + [k in keyof T]: T[k] extends ZodType ? T[k]["_input"] : never; +}>; +export type InputTypeOfTupleWithRest = Rest extends ZodTypeAny ? [...InputTypeOfTuple, ...Rest["_input"][]] : InputTypeOfTuple; +export interface ZodTupleDef extends ZodTypeDef { + items: T; + rest: Rest; + typeName: ZodFirstPartyTypeKind.ZodTuple; +} +export type AnyZodTuple = ZodTuple<[ZodTypeAny, ...ZodTypeAny[]] | [], ZodTypeAny | null>; +export declare class ZodTuple extends ZodType, ZodTupleDef, InputTypeOfTupleWithRest> { + _parse(input: ParseInput): ParseReturnType; + get items(): T; + rest(rest: RestSchema): ZodTuple; + static create: (schemas: Items, params?: RawCreateParams) => ZodTuple; +} +export interface ZodRecordDef extends ZodTypeDef { + valueType: Value; + keyType: Key; + typeName: ZodFirstPartyTypeKind.ZodRecord; +} +export type KeySchema = ZodType; +export type RecordType = [string] extends [K] ? Record : [number] extends [K] ? Record : [symbol] extends [K] ? Record : [BRAND] extends [K] ? Record : Partial>; +export declare class ZodRecord extends ZodType, ZodRecordDef, RecordType> { + get keySchema(): Key; + get valueSchema(): Value; + _parse(input: ParseInput): ParseReturnType; + get element(): Value; + static create(valueType: Value, params?: RawCreateParams): ZodRecord; + static create(keySchema: Keys, valueType: Value, params?: RawCreateParams): ZodRecord; +} +export interface ZodMapDef extends ZodTypeDef { + valueType: Value; + keyType: Key; + typeName: ZodFirstPartyTypeKind.ZodMap; +} +export declare class ZodMap extends ZodType, ZodMapDef, Map> { + get keySchema(): Key; + get valueSchema(): Value; + _parse(input: ParseInput): ParseReturnType; + static create: (keyType: KeySchema, valueType: ValueSchema, params?: RawCreateParams) => ZodMap; +} +export interface ZodSetDef extends ZodTypeDef { + valueType: Value; + typeName: ZodFirstPartyTypeKind.ZodSet; + minSize: { + value: number; + message?: string | undefined; + } | null; + maxSize: { + value: number; + message?: string | undefined; + } | null; +} +export declare class ZodSet extends ZodType, ZodSetDef, Set> { + _parse(input: ParseInput): ParseReturnType; + min(minSize: number, message?: errorUtil.ErrMessage): this; + max(maxSize: number, message?: errorUtil.ErrMessage): this; + size(size: number, message?: errorUtil.ErrMessage): this; + nonempty(message?: errorUtil.ErrMessage): ZodSet; + static create: (valueType: ValueSchema, params?: RawCreateParams) => ZodSet; +} +export interface ZodFunctionDef = ZodTuple, Returns extends ZodTypeAny = ZodTypeAny> extends ZodTypeDef { + args: Args; + returns: Returns; + typeName: ZodFirstPartyTypeKind.ZodFunction; +} +export type OuterTypeOfFunction, Returns extends ZodTypeAny> = Args["_input"] extends Array ? (...args: Args["_input"]) => Returns["_output"] : never; +export type InnerTypeOfFunction, Returns extends ZodTypeAny> = Args["_output"] extends Array ? (...args: Args["_output"]) => Returns["_input"] : never; +export declare class ZodFunction, Returns extends ZodTypeAny> extends ZodType, ZodFunctionDef, InnerTypeOfFunction> { + _parse(input: ParseInput): ParseReturnType; + parameters(): Args; + returnType(): Returns; + args[0]>(...items: Items): ZodFunction, Returns>; + returns>(returnType: NewReturnType): ZodFunction; + implement>(func: F): ReturnType extends Returns["_output"] ? (...args: Args["_input"]) => ReturnType : OuterTypeOfFunction; + strictImplement(func: InnerTypeOfFunction): InnerTypeOfFunction; + validate: >(func: F) => ReturnType extends Returns["_output"] ? (...args: Args["_input"]) => ReturnType : OuterTypeOfFunction; + static create(): ZodFunction, ZodUnknown>; + static create>(args: T): ZodFunction; + static create(args: T, returns: U): ZodFunction; + static create, U extends ZodTypeAny = ZodUnknown>(args: T, returns: U, params?: RawCreateParams): ZodFunction; +} +export interface ZodLazyDef extends ZodTypeDef { + getter: () => T; + typeName: ZodFirstPartyTypeKind.ZodLazy; +} +export declare class ZodLazy extends ZodType, ZodLazyDef, input> { + get schema(): T; + _parse(input: ParseInput): ParseReturnType; + static create: (getter: () => Inner, params?: RawCreateParams) => ZodLazy; +} +export interface ZodLiteralDef extends ZodTypeDef { + value: T; + typeName: ZodFirstPartyTypeKind.ZodLiteral; +} +export declare class ZodLiteral extends ZodType, T> { + _parse(input: ParseInput): ParseReturnType; + get value(): T; + static create: (value: Value, params?: RawCreateParams) => ZodLiteral; +} +export type ArrayKeys = keyof any[]; +export type Indices = Exclude; +export type EnumValues = readonly [T, ...T[]]; +export type Values = { + [k in T[number]]: k; +}; +export interface ZodEnumDef extends ZodTypeDef { + values: T; + typeName: ZodFirstPartyTypeKind.ZodEnum; +} +export type Writeable = { + -readonly [P in keyof T]: T[P]; +}; +export type FilterEnum = Values extends [] ? [] : Values extends [infer Head, ...infer Rest] ? Head extends ToExclude ? FilterEnum : [Head, ...FilterEnum] : never; +export type typecast = A extends T ? A : never; +declare function createZodEnum>(values: T, params?: RawCreateParams): ZodEnum>; +declare function createZodEnum(values: T, params?: RawCreateParams): ZodEnum; +export declare class ZodEnum extends ZodType, T[number]> { + _cache: Set | undefined; + _parse(input: ParseInput): ParseReturnType; + get options(): T; + get enum(): Values; + get Values(): Values; + get Enum(): Values; + extract(values: ToExtract, newDef?: RawCreateParams): ZodEnum>; + exclude(values: ToExclude, newDef?: RawCreateParams): ZodEnum>, [string, ...string[]]>>; + static create: typeof createZodEnum; +} +export interface ZodNativeEnumDef extends ZodTypeDef { + values: T; + typeName: ZodFirstPartyTypeKind.ZodNativeEnum; +} +export type EnumLike = { + [k: string]: string | number; + [nu: number]: string; +}; +export declare class ZodNativeEnum extends ZodType, T[keyof T]> { + _cache: Set | undefined; + _parse(input: ParseInput): ParseReturnType; + get enum(): T; + static create: (values: Elements, params?: RawCreateParams) => ZodNativeEnum; +} +export interface ZodPromiseDef extends ZodTypeDef { + type: T; + typeName: ZodFirstPartyTypeKind.ZodPromise; +} +export declare class ZodPromise extends ZodType, ZodPromiseDef, Promise> { + unwrap(): T; + _parse(input: ParseInput): ParseReturnType; + static create: (schema: Inner, params?: RawCreateParams) => ZodPromise; +} +export type Refinement = (arg: T, ctx: RefinementCtx) => any; +export type SuperRefinement = (arg: T, ctx: RefinementCtx) => void | Promise; +export type RefinementEffect = { + type: "refinement"; + refinement: (arg: T, ctx: RefinementCtx) => any; +}; +export type TransformEffect = { + type: "transform"; + transform: (arg: T, ctx: RefinementCtx) => any; +}; +export type PreprocessEffect = { + type: "preprocess"; + transform: (arg: T, ctx: RefinementCtx) => any; +}; +export type Effect = RefinementEffect | TransformEffect | PreprocessEffect; +export interface ZodEffectsDef extends ZodTypeDef { + schema: T; + typeName: ZodFirstPartyTypeKind.ZodEffects; + effect: Effect; +} +export declare class ZodEffects, Input = input> extends ZodType, Input> { + innerType(): T; + sourceType(): T; + _parse(input: ParseInput): ParseReturnType; + static create: (schema: I, effect: Effect, params?: RawCreateParams) => ZodEffects; + static createWithPreprocess: (preprocess: (arg: unknown, ctx: RefinementCtx) => unknown, schema: I, params?: RawCreateParams) => ZodEffects; +} +export { ZodEffects as ZodTransformer }; +export interface ZodOptionalDef extends ZodTypeDef { + innerType: T; + typeName: ZodFirstPartyTypeKind.ZodOptional; +} +export type ZodOptionalType = ZodOptional; +export declare class ZodOptional extends ZodType, T["_input"] | undefined> { + _parse(input: ParseInput): ParseReturnType; + unwrap(): T; + static create: (type: Inner, params?: RawCreateParams) => ZodOptional; +} +export interface ZodNullableDef extends ZodTypeDef { + innerType: T; + typeName: ZodFirstPartyTypeKind.ZodNullable; +} +export type ZodNullableType = ZodNullable; +export declare class ZodNullable extends ZodType, T["_input"] | null> { + _parse(input: ParseInput): ParseReturnType; + unwrap(): T; + static create: (type: Inner, params?: RawCreateParams) => ZodNullable; +} +export interface ZodDefaultDef extends ZodTypeDef { + innerType: T; + defaultValue: () => util.noUndefined; + typeName: ZodFirstPartyTypeKind.ZodDefault; +} +export declare class ZodDefault extends ZodType, ZodDefaultDef, T["_input"] | undefined> { + _parse(input: ParseInput): ParseReturnType; + removeDefault(): T; + static create: (type: Inner, params: RawCreateParams & { + default: Inner["_input"] | (() => util.noUndefined); + }) => ZodDefault; +} +export interface ZodCatchDef extends ZodTypeDef { + innerType: T; + catchValue: (ctx: { + error: ZodError; + input: unknown; + }) => T["_input"]; + typeName: ZodFirstPartyTypeKind.ZodCatch; +} +export declare class ZodCatch extends ZodType, unknown> { + _parse(input: ParseInput): ParseReturnType; + removeCatch(): T; + static create: (type: Inner, params: RawCreateParams & { + catch: Inner["_output"] | (() => Inner["_output"]); + }) => ZodCatch; +} +export interface ZodNaNDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodNaN; +} +export declare class ZodNaN extends ZodType { + _parse(input: ParseInput): ParseReturnType; + static create: (params?: RawCreateParams) => ZodNaN; +} +export interface ZodBrandedDef extends ZodTypeDef { + type: T; + typeName: ZodFirstPartyTypeKind.ZodBranded; +} +export declare const BRAND: unique symbol; +export type BRAND = { + [BRAND]: { + [k in T]: true; + }; +}; +export declare class ZodBranded extends ZodType, ZodBrandedDef, T["_input"]> { + _parse(input: ParseInput): ParseReturnType; + unwrap(): T; +} +export interface ZodPipelineDef extends ZodTypeDef { + in: A; + out: B; + typeName: ZodFirstPartyTypeKind.ZodPipeline; +} +export declare class ZodPipeline extends ZodType, A["_input"]> { + _parse(input: ParseInput): ParseReturnType; + static create(a: ASchema, b: BSchema): ZodPipeline; +} +type BuiltIn = (((...args: any[]) => any) | (new (...args: any[]) => any)) | { + readonly [Symbol.toStringTag]: string; +} | Date | Error | Generator | Promise | RegExp; +type MakeReadonly = T extends Map ? ReadonlyMap : T extends Set ? ReadonlySet : T extends [infer Head, ...infer Tail] ? readonly [Head, ...Tail] : T extends Array ? ReadonlyArray : T extends BuiltIn ? T : Readonly; +export interface ZodReadonlyDef extends ZodTypeDef { + innerType: T; + typeName: ZodFirstPartyTypeKind.ZodReadonly; +} +export declare class ZodReadonly extends ZodType, ZodReadonlyDef, MakeReadonly> { + _parse(input: ParseInput): ParseReturnType; + static create: (type: Inner, params?: RawCreateParams) => ZodReadonly; + unwrap(): T; +} +type CustomParams = CustomErrorParams & { + fatal?: boolean; +}; +export declare function custom(check?: (data: any) => any, _params?: string | CustomParams | ((input: any) => CustomParams), +/** + * @deprecated + * + * Pass `fatal` into the params object instead: + * + * ```ts + * z.string().custom((val) => val.length > 5, { fatal: false }) + * ``` + * + */ +fatal?: boolean): ZodType; +export { ZodType as Schema, ZodType as ZodSchema }; +export declare const late: { + object: (shape: () => Shape, params?: RawCreateParams) => ZodObject; +}; +export declare enum ZodFirstPartyTypeKind { + ZodString = "ZodString", + ZodNumber = "ZodNumber", + ZodNaN = "ZodNaN", + ZodBigInt = "ZodBigInt", + ZodBoolean = "ZodBoolean", + ZodDate = "ZodDate", + ZodSymbol = "ZodSymbol", + ZodUndefined = "ZodUndefined", + ZodNull = "ZodNull", + ZodAny = "ZodAny", + ZodUnknown = "ZodUnknown", + ZodNever = "ZodNever", + ZodVoid = "ZodVoid", + ZodArray = "ZodArray", + ZodObject = "ZodObject", + ZodUnion = "ZodUnion", + ZodDiscriminatedUnion = "ZodDiscriminatedUnion", + ZodIntersection = "ZodIntersection", + ZodTuple = "ZodTuple", + ZodRecord = "ZodRecord", + ZodMap = "ZodMap", + ZodSet = "ZodSet", + ZodFunction = "ZodFunction", + ZodLazy = "ZodLazy", + ZodLiteral = "ZodLiteral", + ZodEnum = "ZodEnum", + ZodEffects = "ZodEffects", + ZodNativeEnum = "ZodNativeEnum", + ZodOptional = "ZodOptional", + ZodNullable = "ZodNullable", + ZodDefault = "ZodDefault", + ZodCatch = "ZodCatch", + ZodPromise = "ZodPromise", + ZodBranded = "ZodBranded", + ZodPipeline = "ZodPipeline", + ZodReadonly = "ZodReadonly" +} +export type ZodFirstPartySchemaTypes = ZodString | ZodNumber | ZodNaN | ZodBigInt | ZodBoolean | ZodDate | ZodUndefined | ZodNull | ZodAny | ZodUnknown | ZodNever | ZodVoid | ZodArray | ZodObject | ZodUnion | ZodDiscriminatedUnion | ZodIntersection | ZodTuple | ZodRecord | ZodMap | ZodSet | ZodFunction | ZodLazy | ZodLiteral | ZodEnum | ZodEffects | ZodNativeEnum | ZodOptional | ZodNullable | ZodDefault | ZodCatch | ZodPromise | ZodBranded | ZodPipeline | ZodReadonly | ZodSymbol; +declare abstract class Class { + constructor(..._: any[]); +} +declare const instanceOfType: (cls: T, params?: CustomParams) => ZodType, ZodTypeDef, InstanceType>; +declare const stringType: (params?: RawCreateParams & { + coerce?: true; +}) => ZodString; +declare const numberType: (params?: RawCreateParams & { + coerce?: boolean; +}) => ZodNumber; +declare const nanType: (params?: RawCreateParams) => ZodNaN; +declare const bigIntType: (params?: RawCreateParams & { + coerce?: boolean; +}) => ZodBigInt; +declare const booleanType: (params?: RawCreateParams & { + coerce?: boolean; +}) => ZodBoolean; +declare const dateType: (params?: RawCreateParams & { + coerce?: boolean; +}) => ZodDate; +declare const symbolType: (params?: RawCreateParams) => ZodSymbol; +declare const undefinedType: (params?: RawCreateParams) => ZodUndefined; +declare const nullType: (params?: RawCreateParams) => ZodNull; +declare const anyType: (params?: RawCreateParams) => ZodAny; +declare const unknownType: (params?: RawCreateParams) => ZodUnknown; +declare const neverType: (params?: RawCreateParams) => ZodNever; +declare const voidType: (params?: RawCreateParams) => ZodVoid; +declare const arrayType: (schema: El, params?: RawCreateParams) => ZodArray; +declare const objectType: (shape: Shape, params?: RawCreateParams) => ZodObject, objectInputType>; +declare const strictObjectType: (shape: Shape, params?: RawCreateParams) => ZodObject; +declare const unionType: >(types: Options, params?: RawCreateParams) => ZodUnion; +declare const discriminatedUnionType: typeof ZodDiscriminatedUnion.create; +declare const intersectionType: (left: TSchema, right: USchema, params?: RawCreateParams) => ZodIntersection; +declare const tupleType: (schemas: Items, params?: RawCreateParams) => ZodTuple; +declare const recordType: typeof ZodRecord.create; +declare const mapType: (keyType: KeySchema, valueType: ValueSchema, params?: RawCreateParams) => ZodMap; +declare const setType: (valueType: ValueSchema, params?: RawCreateParams) => ZodSet; +declare const functionType: typeof ZodFunction.create; +declare const lazyType: (getter: () => Inner, params?: RawCreateParams) => ZodLazy; +declare const literalType: (value: Value, params?: RawCreateParams) => ZodLiteral; +declare const enumType: typeof createZodEnum; +declare const nativeEnumType: (values: Elements, params?: RawCreateParams) => ZodNativeEnum; +declare const promiseType: (schema: Inner, params?: RawCreateParams) => ZodPromise; +declare const effectsType: (schema: I, effect: Effect, params?: RawCreateParams) => ZodEffects; +declare const optionalType: (type: Inner, params?: RawCreateParams) => ZodOptional; +declare const nullableType: (type: Inner, params?: RawCreateParams) => ZodNullable; +declare const preprocessType: (preprocess: (arg: unknown, ctx: RefinementCtx) => unknown, schema: I, params?: RawCreateParams) => ZodEffects; +declare const pipelineType: typeof ZodPipeline.create; +declare const ostring: () => ZodOptional; +declare const onumber: () => ZodOptional; +declare const oboolean: () => ZodOptional; +export declare const coerce: { + string: (typeof ZodString)["create"]; + number: (typeof ZodNumber)["create"]; + boolean: (typeof ZodBoolean)["create"]; + bigint: (typeof ZodBigInt)["create"]; + date: (typeof ZodDate)["create"]; +}; +export { anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, dateType as date, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, instanceOfType as instanceof, intersectionType as intersection, lazyType as lazy, literalType as literal, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, recordType as record, setType as set, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, voidType as void, }; +export declare const NEVER: never; diff --git a/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/package.json b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/package.json new file mode 100644 index 000000000..e02b87614 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3-infer/node_modules/zod/package.json @@ -0,0 +1,120 @@ +{ + "name": "zod", + "version": "3.25.67", + "type": "module", + "author": "Colin McDonnell ", + "description": "TypeScript-first schema declaration and validation library with static type inference", + "files": ["dist", "v3", "v4", "v4-mini"], + "funding": "https://github.com/sponsors/colinhacks", + "homepage": "https://zod.dev", + "keywords": ["typescript", "schema", "validation", "type", "inference"], + "license": "MIT", + "sideEffects": false, + "main": "./dist/cjs/index.js", + "types": "./dist/types/index.d.ts", + "module": "./dist/esm/index.js", + "exports": { + ".": { + "import": { + "@zod/source": "./src/index.ts", + "types": "./dist/types/index.d.ts", + "default": "./dist/esm/index.js" + }, + "require": { + "@zod/source": "./src/index.ts", + "types": "./dist/types/index.d.ts", + "default": "./dist/cjs/index.js" + } + }, + "./v3": { + "import": { + "@zod/source": "./src/index.ts", + "types": "./dist/types/index.d.ts", + "default": "./dist/esm/index.js" + }, + "require": { + "@zod/source": "./src/index.ts", + "types": "./dist/types/index.d.ts", + "default": "./dist/cjs/index.js" + } + }, + "./v4": { + "import": { + "@zod/source": "./src/v4/index.ts", + "types": "./dist/types/v4/index.d.ts", + "default": "./dist/esm/v4/index.js" + }, + "require": { + "@zod/source": "./src/v4/index.ts", + "types": "./dist/types/v4/index.d.ts", + "default": "./dist/cjs/v4/index.js" + } + }, + "./v4-mini": { + "@zod/source": "./src/v4/mini/index.ts", + "types": "./dist/types/v4/mini/index.d.ts", + "import": "./dist/esm/v4/mini/index.js", + "require": "./dist/cjs/v4/mini/index.js" + }, + "./v4/mini": { + "@zod/source": "./src/v4/mini/index.ts", + "types": "./dist/types/v4/mini/index.d.ts", + "import": "./dist/esm/v4/mini/index.js", + "require": "./dist/cjs/v4/mini/index.js" + }, + "./v4/core": { + "@zod/source": "./src/v4/core/index.ts", + "types": "./dist/types/v4/core/index.d.ts", + "import": "./dist/esm/v4/core/index.js", + "require": "./dist/cjs/v4/core/index.js" + }, + "./v4/locales": { + "@zod/source": "./src/v4/locales/index.ts", + "types": "./dist/types/v4/locales/index.d.ts", + "import": "./dist/esm/v4/locales/index.js", + "require": "./dist/cjs/v4/locales/index.js" + }, + "./v4/locales/*": { + "@zod/source": "./src/v4/locales/*", + "types": "./dist/types/v4/locales/*", + "import": "./dist/esm/v4/locales/*", + "require": "./dist/cjs/v4/locales/*" + }, + "./package.json": "./package.json" + }, + "tshy": { + "exports": { + "./package.json": "./package.json", + ".": "./src/index.ts", + "./v3": "./src/v3/index.ts", + "./v4": "./src/v4/index.ts", + "./v4-mini": "./src/v4/mini/index.ts", + "./v4/core": "./src/v4/core/index.ts", + "./v4/locales": "./src/v4/locales/index.ts", + "./v4/locales/*": "./src/v4/locales/*" + }, + "sourceDialects": ["@zod/source"], + "exclude": ["./src/**/*.test.ts"] + }, + "repository": { + "type": "git", + "url": "git+https://github.com/colinhacks/zod.git" + }, + "bugs": { + "url": "https://github.com/colinhacks/zod/issues" + }, + "support": { + "backing": { + "npm-funding": true + } + }, + "scripts": { + "clean": "rm -rf dist", + "build": "tsx ./build.mts", + "postbuild": "pnpm biome check --write .", + "test:watch": "pnpm vitest", + "test": "pnpm vitest run", + "bump:beta": "pnpm version \"v$(pnpm pkg get version | jq -r)-beta.$(date +%Y%m%dT%H%M%S)\"", + "pub:beta": "pnpm bump:beta && pnpm publish --tag next --publish-branch v4 --no-git-checks --dry-run" + } +} diff --git a/tests/fixtures/npm/cases/zod3-infer/package.json b/tests/fixtures/npm/cases/zod3-infer/package.json new file mode 100644 index 000000000..ccfb8101b --- /dev/null +++ b/tests/fixtures/npm/cases/zod3-infer/package.json @@ -0,0 +1 @@ +{ "name": "zod3-infer-case", "private": true, "type": "module" } diff --git a/tests/fixtures/npm/cases/zod3/main.ts b/tests/fixtures/npm/cases/zod3/main.ts new file mode 100644 index 000000000..d7f1a433a --- /dev/null +++ b/tests/fixtures/npm/cases/zod3/main.ts @@ -0,0 +1,115 @@ +// zod 3.25 (the real package, trimmed to its v3 ESM build and types) compiled +// natively: schemas built at module top level, parse and safeParse across the +// common schema kinds, number checks, issue paths, codes and messages, and +// async refinements through parseAsync/safeParseAsync. +import { z } from "zod"; + +const show = (label: string, value: unknown): void => { + console.log(label + " " + JSON.stringify(value)); +}; +const issues = (result: z.SafeParseReturnType): string => + result.success + ? "ok" + : result.error.issues.map((i) => `${i.path.join(".")}:${i.code}:${i.message}`).join(" | "); + +const Region = z.enum(["east", "west", "north"]); +const Job = z.object({ + id: z.string().min(3).max(32), + region: Region, + attempts: z.number().int().nonnegative().default(0), + tags: z.record(z.string()).optional(), + files: z.array(z.object({ path: z.string(), mode: z.number() })), + kind: z.union([z.literal("static"), z.literal("worker")]), + meta: z.object({ owner: z.string().nullable() }).partial(), +}); +type Job = z.infer; + +const job: Job = Job.parse({ + id: "job_1", + region: "east", + files: [{ path: "a.js", mode: 420 }], + kind: "worker", + meta: { owner: null }, +}); +show("job", job); +show("bad job", issues(Job.safeParse({ id: "x", region: "south", files: [{ path: 1 }], kind: "edge" }))); + +// The common schema kinds. +show("number", z.number().parse(3)); +show("default", z.number().default(0).parse(undefined)); +show("optional", z.string().optional().parse(undefined) ?? "undefined"); +show("nullable", z.string().nullable().parse(null)); +show("record", z.record(z.string()).parse({ a: "b" })); +show("array", z.array(z.string()).parse(["a"])); +show("union", z.union([z.literal("a"), z.literal("b")]).parse("b")); +show("partial", z.object({ a: z.string() }).partial().parse({})); +show("discriminated", z.discriminatedUnion("t", [z.object({ t: z.literal("x") })]).parse({ t: "x" })); +show("transform", z.string().transform((s) => s.length).parse("abc")); +show("wrong type", issues(z.object({ a: z.number() }).safeParse({ a: "x" }))); +show("email", issues(z.string().email().safeParse("nope"))); +show("boolean", z.boolean().parse(true)); +show("strict", issues(z.object({ a: z.string() }).strict().safeParse({ a: "x", b: 1 }))); +show("regex", z.string().regex(/^a/).parse("abc")); +show("coerce", z.coerce.number().parse("4")); +show("extend", z.object({ a: z.string() }).extend({ b: z.number() }).parse({ a: "x", b: 1 })); +show("refine", issues(z.string().refine((s) => s.length > 1, "short").safeParse("a"))); +show("enum", z.enum(["a", "b"]).parse("a")); +show("literal", z.literal("q").parse("q")); + +// Number checks, passing and failing, with and without messages. +show("int", z.number().int().parse(3)); +show("int fail", issues(z.number().int().safeParse(1.5))); +show("int message", issues(z.number().int("whole numbers only").safeParse(2.5))); +show("min", z.number().min(1).parse(3)); +show("min fail", issues(z.number().min(1, "too low").safeParse(0))); +show("max fail", issues(z.number().max(10).safeParse(11))); +show("gt lt", issues(z.number().gt(0).lt(5).safeParse(5))); +show("positive", issues(z.number().positive().safeParse(0))); +show("nonnegative", issues(z.number().nonnegative().safeParse(-1))); +show("multipleOf", z.number().multipleOf(2).parse(4)); +show("multipleOf fail", issues(z.number().multipleOf(0.1).safeParse(0.35))); +show("multipleOf float", z.number().multipleOf(0.01).parse(1.23)); +show("step", issues(z.number().step(3).safeParse(10))); +show("finite", issues(z.number().finite().safeParse(Infinity))); +show("safe", issues(z.number().safe().safeParse(2 ** 60))); +show("bounds", [z.number().min(2).max(9).minValue, z.number().min(2).max(9).maxValue, z.number().int().isInt]); + +try { + Job.parse({}); +} catch (error) { + show("thrown", error instanceof z.ZodError ? error.issues.length : "other"); +} + +// Async refinements. +const Unique = z.string().refine(async (name) => name !== "taken", { message: "name is taken" }); +const Account = z.object({ + name: Unique, + age: z.number().int().min(18), +}); + +async function main(): Promise { + show("async ok", await Account.parseAsync({ name: "free", age: 30 })); + show("async fail", issues(await Account.safeParseAsync({ name: "taken", age: 12.5 }))); + try { + await Unique.parseAsync("taken"); + } catch (error) { + show("async thrown", error instanceof z.ZodError ? error.issues[0]!.message : "other"); + } + try { + Unique.parse("free"); + } catch (error) { + show("sync on async", (error as Error).message); + } + const Slow = z.number().superRefine(async (n, ctx) => { + await new Promise((resolve) => setTimeout(resolve, 1)); + if (n % 2 !== 0) ctx.addIssue({ code: z.ZodIssueCode.custom, message: "odd" }); + }); + show("superRefine", issues(await Slow.safeParseAsync(3))); + show("transform async", await z.string().transform(async (s) => s.toUpperCase()).parseAsync("up")); + show("array async", issues(await z.array(Unique).safeParseAsync(["a", "taken", "b"]))); + show("array async ok", await z.array(Unique).parseAsync(["x", "y"])); + show("tuple async", issues(await z.tuple([z.string(), Unique]).safeParseAsync(["a", "taken"]))); + show("tuple async ok", await z.tuple([z.number(), Unique]).parseAsync([1, "z"])); +} + +void main(); diff --git a/tests/fixtures/npm/cases/zod3/node_modules/zod/LICENSE b/tests/fixtures/npm/cases/zod3/node_modules/zod/LICENSE new file mode 100644 index 000000000..c06579627 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3/node_modules/zod/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Colin McDonnell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/index.js b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/index.js new file mode 100644 index 000000000..8352ab713 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/index.js @@ -0,0 +1,3 @@ +import z3 from "./v3/index.js"; +export * from "./v3/index.js"; +export default z3; diff --git a/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/package.json b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/package.json new file mode 100644 index 000000000..aead43de3 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} \ No newline at end of file diff --git a/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/ZodError.js b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/ZodError.js new file mode 100644 index 000000000..c72ce5288 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/ZodError.js @@ -0,0 +1,132 @@ +import { util } from "./helpers/util.js"; +export const ZodIssueCode = util.arrayToEnum([ + "invalid_type", + "invalid_literal", + "custom", + "invalid_union", + "invalid_union_discriminator", + "invalid_enum_value", + "unrecognized_keys", + "invalid_arguments", + "invalid_return_type", + "invalid_date", + "invalid_string", + "too_small", + "too_big", + "invalid_intersection_types", + "not_multiple_of", + "not_finite", +]); +export const quotelessJson = (obj) => { + const json = JSON.stringify(obj, null, 2); + return json.replace(/"([^"]+)":/g, "$1:"); +}; +export class ZodError extends Error { + get errors() { + return this.issues; + } + constructor(issues) { + super(); + this.issues = []; + this.addIssue = (sub) => { + this.issues = [...this.issues, sub]; + }; + this.addIssues = (subs = []) => { + this.issues = [...this.issues, ...subs]; + }; + const actualProto = new.target.prototype; + if (Object.setPrototypeOf) { + // eslint-disable-next-line ban/ban + Object.setPrototypeOf(this, actualProto); + } + else { + this.__proto__ = actualProto; + } + this.name = "ZodError"; + this.issues = issues; + } + format(_mapper) { + const mapper = _mapper || + function (issue) { + return issue.message; + }; + const fieldErrors = { _errors: [] }; + const processError = (error) => { + for (const issue of error.issues) { + if (issue.code === "invalid_union") { + issue.unionErrors.map(processError); + } + else if (issue.code === "invalid_return_type") { + processError(issue.returnTypeError); + } + else if (issue.code === "invalid_arguments") { + processError(issue.argumentsError); + } + else if (issue.path.length === 0) { + fieldErrors._errors.push(mapper(issue)); + } + else { + let curr = fieldErrors; + let i = 0; + while (i < issue.path.length) { + const el = issue.path[i]; + const terminal = i === issue.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + // if (typeof el === "string") { + // curr[el] = curr[el] || { _errors: [] }; + // } else if (typeof el === "number") { + // const errorArray: any = []; + // errorArray._errors = []; + // curr[el] = curr[el] || errorArray; + // } + } + else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue)); + } + curr = curr[el]; + i++; + } + } + } + }; + processError(this); + return fieldErrors; + } + static assert(value) { + if (!(value instanceof ZodError)) { + throw new Error(`Not a ZodError: ${value}`); + } + } + toString() { + return this.message; + } + get message() { + return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); + } + get isEmpty() { + return this.issues.length === 0; + } + flatten(mapper = (issue) => issue.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of this.issues) { + if (sub.path.length > 0) { + fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; + fieldErrors[sub.path[0]].push(mapper(sub)); + } + else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; + } + get formErrors() { + return this.flatten(); + } +} +ZodError.create = (issues) => { + const error = new ZodError(issues); + return error; +}; diff --git a/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/errors.js b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/errors.js new file mode 100644 index 000000000..26fdf628a --- /dev/null +++ b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/errors.js @@ -0,0 +1,9 @@ +import defaultErrorMap from "./locales/en.js"; +let overrideErrorMap = defaultErrorMap; +export { defaultErrorMap }; +export function setErrorMap(map) { + overrideErrorMap = map; +} +export function getErrorMap() { + return overrideErrorMap; +} diff --git a/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/external.js b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/external.js new file mode 100644 index 000000000..f0a4be4c7 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/external.js @@ -0,0 +1,6 @@ +export * from "./errors.js"; +export * from "./helpers/parseUtil.js"; +export * from "./helpers/typeAliases.js"; +export * from "./helpers/util.js"; +export * from "./types.js"; +export * from "./ZodError.js"; diff --git a/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/helpers/enumUtil.js b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/helpers/enumUtil.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/helpers/enumUtil.js @@ -0,0 +1 @@ +export {}; diff --git a/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/helpers/errorUtil.js b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/helpers/errorUtil.js new file mode 100644 index 000000000..e1640d1a4 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/helpers/errorUtil.js @@ -0,0 +1,6 @@ +export var errorUtil; +(function (errorUtil) { + errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {}; + // biome-ignore lint: + errorUtil.toString = (message) => typeof message === "string" ? message : message?.message; +})(errorUtil || (errorUtil = {})); diff --git a/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/helpers/parseUtil.js b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/helpers/parseUtil.js new file mode 100644 index 000000000..91b2afb81 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/helpers/parseUtil.js @@ -0,0 +1,109 @@ +import { getErrorMap } from "../errors.js"; +import defaultErrorMap from "../locales/en.js"; +export const makeIssue = (params) => { + const { data, path, errorMaps, issueData } = params; + const fullPath = [...path, ...(issueData.path || [])]; + const fullIssue = { + ...issueData, + path: fullPath, + }; + if (issueData.message !== undefined) { + return { + ...issueData, + path: fullPath, + message: issueData.message, + }; + } + let errorMessage = ""; + const maps = errorMaps + .filter((m) => !!m) + .slice() + .reverse(); + for (const map of maps) { + errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; + } + return { + ...issueData, + path: fullPath, + message: errorMessage, + }; +}; +export const EMPTY_PATH = []; +export function addIssueToContext(ctx, issueData) { + const overrideMap = getErrorMap(); + const issue = makeIssue({ + issueData: issueData, + data: ctx.data, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, // contextual error map is first priority + ctx.schemaErrorMap, // then schema-bound map if available + overrideMap, // then global override map + overrideMap === defaultErrorMap ? undefined : defaultErrorMap, // then global default map + ].filter((x) => !!x), + }); + ctx.common.issues.push(issue); +} +export class ParseStatus { + constructor() { + this.value = "valid"; + } + dirty() { + if (this.value === "valid") + this.value = "dirty"; + } + abort() { + if (this.value !== "aborted") + this.value = "aborted"; + } + static mergeArray(status, results) { + const arrayValue = []; + for (const s of results) { + if (s.status === "aborted") + return INVALID; + if (s.status === "dirty") + status.dirty(); + arrayValue.push(s.value); + } + return { status: status.value, value: arrayValue }; + } + static async mergeObjectAsync(status, pairs) { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value, + }); + } + return ParseStatus.mergeObjectSync(status, syncPairs); + } + static mergeObjectSync(status, pairs) { + const finalObject = {}; + for (const pair of pairs) { + const { key, value } = pair; + if (key.status === "aborted") + return INVALID; + if (value.status === "aborted") + return INVALID; + if (key.status === "dirty") + status.dirty(); + if (value.status === "dirty") + status.dirty(); + if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { + finalObject[key.value] = value.value; + } + } + return { status: status.value, value: finalObject }; + } +} +export const INVALID = Object.freeze({ + status: "aborted", +}); +export const DIRTY = (value) => ({ status: "dirty", value }); +export const OK = (value) => ({ status: "valid", value }); +export const isAborted = (x) => x.status === "aborted"; +export const isDirty = (x) => x.status === "dirty"; +export const isValid = (x) => x.status === "valid"; +export const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; diff --git a/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/helpers/partialUtil.js b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/helpers/partialUtil.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/helpers/partialUtil.js @@ -0,0 +1 @@ +export {}; diff --git a/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/helpers/typeAliases.js b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/helpers/typeAliases.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/helpers/typeAliases.js @@ -0,0 +1 @@ +export {}; diff --git a/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/helpers/util.js b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/helpers/util.js new file mode 100644 index 000000000..b9641f29b --- /dev/null +++ b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/helpers/util.js @@ -0,0 +1,133 @@ +export var util; +(function (util) { + util.assertEqual = (_) => { }; + function assertIs(_arg) { } + util.assertIs = assertIs; + function assertNever(_x) { + throw new Error(); + } + util.assertNever = assertNever; + util.arrayToEnum = (items) => { + const obj = {}; + for (const item of items) { + obj[item] = item; + } + return obj; + }; + util.getValidEnumValues = (obj) => { + const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); + const filtered = {}; + for (const k of validKeys) { + filtered[k] = obj[k]; + } + return util.objectValues(filtered); + }; + util.objectValues = (obj) => { + return util.objectKeys(obj).map(function (e) { + return obj[e]; + }); + }; + util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban + ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban + : (object) => { + const keys = []; + for (const key in object) { + if (Object.prototype.hasOwnProperty.call(object, key)) { + keys.push(key); + } + } + return keys; + }; + util.find = (arr, checker) => { + for (const item of arr) { + if (checker(item)) + return item; + } + return undefined; + }; + util.isInteger = typeof Number.isInteger === "function" + ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban + : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; + function joinValues(array, separator = " | ") { + return array.map((val) => (typeof val === "string" ? `'${val}'` : val)).join(separator); + } + util.joinValues = joinValues; + util.jsonStringifyReplacer = (_, value) => { + if (typeof value === "bigint") { + return value.toString(); + } + return value; + }; +})(util || (util = {})); +export var objectUtil; +(function (objectUtil) { + objectUtil.mergeShapes = (first, second) => { + return { + ...first, + ...second, // second overwrites first + }; + }; +})(objectUtil || (objectUtil = {})); +export const ZodParsedType = util.arrayToEnum([ + "string", + "nan", + "number", + "integer", + "float", + "boolean", + "date", + "bigint", + "symbol", + "function", + "undefined", + "null", + "array", + "object", + "unknown", + "promise", + "void", + "never", + "map", + "set", +]); +export const getParsedType = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return ZodParsedType.undefined; + case "string": + return ZodParsedType.string; + case "number": + return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; + case "boolean": + return ZodParsedType.boolean; + case "function": + return ZodParsedType.function; + case "bigint": + return ZodParsedType.bigint; + case "symbol": + return ZodParsedType.symbol; + case "object": + if (Array.isArray(data)) { + return ZodParsedType.array; + } + if (data === null) { + return ZodParsedType.null; + } + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return ZodParsedType.promise; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return ZodParsedType.map; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return ZodParsedType.set; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return ZodParsedType.date; + } + return ZodParsedType.object; + default: + return ZodParsedType.unknown; + } +}; diff --git a/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/index.js b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/index.js new file mode 100644 index 000000000..a9dab5738 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/index.js @@ -0,0 +1,4 @@ +import * as z from "./external.js"; +export * from "./external.js"; +export { z }; +export default z; diff --git a/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/locales/en.js b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/locales/en.js new file mode 100644 index 000000000..3e97ad51a --- /dev/null +++ b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/locales/en.js @@ -0,0 +1,107 @@ +import { ZodIssueCode } from "../ZodError.js"; +import { util, ZodParsedType } from "../helpers/util.js"; +const errorMap = (issue, _ctx) => { + let message; + switch (issue.code) { + case ZodIssueCode.invalid_type: + if (issue.received === ZodParsedType.undefined) { + message = "Required"; + } + else { + message = `Expected ${issue.expected}, received ${issue.received}`; + } + break; + case ZodIssueCode.invalid_literal: + message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`; + break; + case ZodIssueCode.unrecognized_keys: + message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`; + break; + case ZodIssueCode.invalid_union: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_union_discriminator: + message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`; + break; + case ZodIssueCode.invalid_enum_value: + message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`; + break; + case ZodIssueCode.invalid_arguments: + message = `Invalid function arguments`; + break; + case ZodIssueCode.invalid_return_type: + message = `Invalid function return type`; + break; + case ZodIssueCode.invalid_date: + message = `Invalid date`; + break; + case ZodIssueCode.invalid_string: + if (typeof issue.validation === "object") { + if ("includes" in issue.validation) { + message = `Invalid input: must include "${issue.validation.includes}"`; + if (typeof issue.validation.position === "number") { + message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; + } + } + else if ("startsWith" in issue.validation) { + message = `Invalid input: must start with "${issue.validation.startsWith}"`; + } + else if ("endsWith" in issue.validation) { + message = `Invalid input: must end with "${issue.validation.endsWith}"`; + } + else { + util.assertNever(issue.validation); + } + } + else if (issue.validation !== "regex") { + message = `Invalid ${issue.validation}`; + } + else { + message = "Invalid"; + } + break; + case ZodIssueCode.too_small: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode.too_big: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; + else if (issue.type === "bigint") + message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode.custom: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_intersection_types: + message = `Intersection results could not be merged`; + break; + case ZodIssueCode.not_multiple_of: + message = `Number must be a multiple of ${issue.multipleOf}`; + break; + case ZodIssueCode.not_finite: + message = "Number must be finite"; + break; + default: + message = _ctx.defaultError; + util.assertNever(issue); + } + return { message }; +}; +export default errorMap; diff --git a/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/standard-schema.js b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/standard-schema.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/standard-schema.js @@ -0,0 +1 @@ +export {}; diff --git a/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/types.js b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/types.js new file mode 100644 index 000000000..de1e6213e --- /dev/null +++ b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/esm/v3/types.js @@ -0,0 +1,3691 @@ +import { ZodError, ZodIssueCode, } from "./ZodError.js"; +import { defaultErrorMap, getErrorMap } from "./errors.js"; +import { errorUtil } from "./helpers/errorUtil.js"; +import { DIRTY, INVALID, OK, ParseStatus, addIssueToContext, isAborted, isAsync, isDirty, isValid, makeIssue, } from "./helpers/parseUtil.js"; +import { util, ZodParsedType, getParsedType } from "./helpers/util.js"; +class ParseInputLazyPath { + constructor(parent, value, path, key) { + this._cachedPath = []; + this.parent = parent; + this.data = value; + this._path = path; + this._key = key; + } + get path() { + if (!this._cachedPath.length) { + if (Array.isArray(this._key)) { + this._cachedPath.push(...this._path, ...this._key); + } + else { + this._cachedPath.push(...this._path, this._key); + } + } + return this._cachedPath; + } +} +const handleResult = (ctx, result) => { + if (isValid(result)) { + return { success: true, data: result.value }; + } + else { + if (!ctx.common.issues.length) { + throw new Error("Validation failed but no issues detected."); + } + return { + success: false, + get error() { + if (this._error) + return this._error; + const error = new ZodError(ctx.common.issues); + this._error = error; + return this._error; + }, + }; + } +}; +function processCreateParams(params) { + if (!params) + return {}; + const { errorMap, invalid_type_error, required_error, description } = params; + if (errorMap && (invalid_type_error || required_error)) { + throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); + } + if (errorMap) + return { errorMap: errorMap, description }; + const customMap = (iss, ctx) => { + const { message } = params; + if (iss.code === "invalid_enum_value") { + return { message: message ?? ctx.defaultError }; + } + if (typeof ctx.data === "undefined") { + return { message: message ?? required_error ?? ctx.defaultError }; + } + if (iss.code !== "invalid_type") + return { message: ctx.defaultError }; + return { message: message ?? invalid_type_error ?? ctx.defaultError }; + }; + return { errorMap: customMap, description }; +} +export class ZodType { + get description() { + return this._def.description; + } + _getType(input) { + return getParsedType(input.data); + } + _getOrReturnCtx(input, ctx) { + return (ctx || { + common: input.parent.common, + data: input.data, + parsedType: getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent, + }); + } + _processInputParams(input) { + return { + status: new ParseStatus(), + ctx: { + common: input.parent.common, + data: input.data, + parsedType: getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent, + }, + }; + } + _parseSync(input) { + const result = this._parse(input); + if (isAsync(result)) { + throw new Error("Synchronous parse encountered promise."); + } + return result; + } + _parseAsync(input) { + const result = this._parse(input); + return Promise.resolve(result); + } + parse(data, params) { + const result = this.safeParse(data, params); + if (result.success) + return result.data; + throw result.error; + } + safeParse(data, params) { + const ctx = { + common: { + issues: [], + async: params?.async ?? false, + contextualErrorMap: params?.errorMap, + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data), + }; + const result = this._parseSync({ data, path: ctx.path, parent: ctx }); + return handleResult(ctx, result); + } + "~validate"(data) { + const ctx = { + common: { + issues: [], + async: !!this["~standard"].async, + }, + path: [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data), + }; + if (!this["~standard"].async) { + try { + const result = this._parseSync({ data, path: [], parent: ctx }); + return isValid(result) + ? { + value: result.value, + } + : { + issues: ctx.common.issues, + }; + } + catch (err) { + if (err?.message?.toLowerCase()?.includes("encountered")) { + this["~standard"].async = true; + } + ctx.common = { + issues: [], + async: true, + }; + } + } + return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) + ? { + value: result.value, + } + : { + issues: ctx.common.issues, + }); + } + async parseAsync(data, params) { + const result = await this.safeParseAsync(data, params); + if (result.success) + return result.data; + throw result.error; + } + async safeParseAsync(data, params) { + const ctx = { + common: { + issues: [], + contextualErrorMap: params?.errorMap, + async: true, + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data), + }; + const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); + const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); + return handleResult(ctx, result); + } + refine(check, message) { + const getIssueProperties = (val) => { + if (typeof message === "string" || typeof message === "undefined") { + return { message }; + } + else if (typeof message === "function") { + return message(val); + } + else { + return message; + } + }; + return this._refinement((val, ctx) => { + const result = check(val); + const setError = () => ctx.addIssue({ + code: ZodIssueCode.custom, + ...getIssueProperties(val), + }); + if (typeof Promise !== "undefined" && result instanceof Promise) { + return result.then((data) => { + if (!data) { + setError(); + return false; + } + else { + return true; + } + }); + } + if (!result) { + setError(); + return false; + } + else { + return true; + } + }); + } + refinement(check, refinementData) { + return this._refinement((val, ctx) => { + if (!check(val)) { + ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); + return false; + } + else { + return true; + } + }); + } + _refinement(refinement) { + return new ZodEffects({ + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "refinement", refinement }, + }); + } + superRefine(refinement) { + return this._refinement(refinement); + } + constructor(def) { + /** Alias of safeParseAsync */ + this.spa = this.safeParseAsync; + this._def = def; + this.parse = this.parse.bind(this); + this.safeParse = this.safeParse.bind(this); + this.parseAsync = this.parseAsync.bind(this); + this.safeParseAsync = this.safeParseAsync.bind(this); + this.spa = this.spa.bind(this); + this.refine = this.refine.bind(this); + this.refinement = this.refinement.bind(this); + this.superRefine = this.superRefine.bind(this); + this.optional = this.optional.bind(this); + this.nullable = this.nullable.bind(this); + this.nullish = this.nullish.bind(this); + this.array = this.array.bind(this); + this.promise = this.promise.bind(this); + this.or = this.or.bind(this); + this.and = this.and.bind(this); + this.transform = this.transform.bind(this); + this.brand = this.brand.bind(this); + this.default = this.default.bind(this); + this.catch = this.catch.bind(this); + this.describe = this.describe.bind(this); + this.pipe = this.pipe.bind(this); + this.readonly = this.readonly.bind(this); + this.isNullable = this.isNullable.bind(this); + this.isOptional = this.isOptional.bind(this); + this["~standard"] = { + version: 1, + vendor: "zod", + validate: (data) => this["~validate"](data), + }; + } + optional() { + return ZodOptional.create(this, this._def); + } + nullable() { + return ZodNullable.create(this, this._def); + } + nullish() { + return this.nullable().optional(); + } + array() { + return ZodArray.create(this); + } + promise() { + return ZodPromise.create(this, this._def); + } + or(option) { + return ZodUnion.create([this, option], this._def); + } + and(incoming) { + return ZodIntersection.create(this, incoming, this._def); + } + transform(transform) { + return new ZodEffects({ + ...processCreateParams(this._def), + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "transform", transform }, + }); + } + default(def) { + const defaultValueFunc = typeof def === "function" ? def : () => def; + return new ZodDefault({ + ...processCreateParams(this._def), + innerType: this, + defaultValue: defaultValueFunc, + typeName: ZodFirstPartyTypeKind.ZodDefault, + }); + } + brand() { + return new ZodBranded({ + typeName: ZodFirstPartyTypeKind.ZodBranded, + type: this, + ...processCreateParams(this._def), + }); + } + catch(def) { + const catchValueFunc = typeof def === "function" ? def : () => def; + return new ZodCatch({ + ...processCreateParams(this._def), + innerType: this, + catchValue: catchValueFunc, + typeName: ZodFirstPartyTypeKind.ZodCatch, + }); + } + describe(description) { + const This = this.constructor; + return new This({ + ...this._def, + description, + }); + } + pipe(target) { + return ZodPipeline.create(this, target); + } + readonly() { + return ZodReadonly.create(this); + } + isOptional() { + return this.safeParse(undefined).success; + } + isNullable() { + return this.safeParse(null).success; + } +} +const cuidRegex = /^c[^\s-]{8,}$/i; +const cuid2Regex = /^[0-9a-z]+$/; +const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; +// const uuidRegex = +// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i; +const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; +const nanoidRegex = /^[a-z0-9_-]{21}$/i; +const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; +const durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; +// from https://stackoverflow.com/a/46181/1550155 +// old version: too slow, didn't support unicode +// const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i; +//old email regex +// const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i; +// eslint-disable-next-line +// const emailRegex = +// /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/; +// const emailRegex = +// /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; +// const emailRegex = +// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i; +const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; +// const emailRegex = +// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i; +// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression +const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; +let emojiRegex; +// faster, simpler, safer +const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; +const ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; +// const ipv6Regex = +// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/; +const ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; +const ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript +const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; +// https://base64.guru/standards/base64url +const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; +// simple +// const dateRegexSource = `\\d{4}-\\d{2}-\\d{2}`; +// no leap year validation +// const dateRegexSource = `\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\d|2\\d))`; +// with leap year validation +const dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; +const dateRegex = new RegExp(`^${dateRegexSource}$`); +function timeRegexSource(args) { + let secondsRegexSource = `[0-5]\\d`; + if (args.precision) { + secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; + } + else if (args.precision == null) { + secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; + } + const secondsQuantifier = args.precision ? "+" : "?"; // require seconds if precision is nonzero + return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; +} +function timeRegex(args) { + return new RegExp(`^${timeRegexSource(args)}$`); +} +// Adapted from https://stackoverflow.com/a/3143231 +export function datetimeRegex(args) { + let regex = `${dateRegexSource}T${timeRegexSource(args)}`; + const opts = []; + opts.push(args.local ? `Z?` : `Z`); + if (args.offset) + opts.push(`([+-]\\d{2}:?\\d{2})`); + regex = `${regex}(${opts.join("|")})`; + return new RegExp(`^${regex}$`); +} +function isValidIP(ip, version) { + if ((version === "v4" || !version) && ipv4Regex.test(ip)) { + return true; + } + if ((version === "v6" || !version) && ipv6Regex.test(ip)) { + return true; + } + return false; +} +function isValidJWT(jwt, alg) { + if (!jwtRegex.test(jwt)) + return false; + try { + const [header] = jwt.split("."); + // Convert base64url to base64 + const base64 = header + .replace(/-/g, "+") + .replace(/_/g, "/") + .padEnd(header.length + ((4 - (header.length % 4)) % 4), "="); + const decoded = JSON.parse(atob(base64)); + if (typeof decoded !== "object" || decoded === null) + return false; + if ("typ" in decoded && decoded?.typ !== "JWT") + return false; + if (!decoded.alg) + return false; + if (alg && decoded.alg !== alg) + return false; + return true; + } + catch { + return false; + } +} +function isValidCidr(ip, version) { + if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) { + return true; + } + if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) { + return true; + } + return false; +} +export class ZodString extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = String(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.string) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.string, + received: ctx.parsedType, + }); + return INVALID; + } + const status = new ParseStatus(); + let ctx = undefined; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.length < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "max") { + if (input.data.length > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "length") { + const tooBig = input.data.length > check.value; + const tooSmall = input.data.length < check.value; + if (tooBig || tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + if (tooBig) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message, + }); + } + else if (tooSmall) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message, + }); + } + status.dirty(); + } + } + else if (check.kind === "email") { + if (!emailRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "email", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "emoji") { + if (!emojiRegex) { + emojiRegex = new RegExp(_emojiRegex, "u"); + } + if (!emojiRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "emoji", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "uuid") { + if (!uuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "uuid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "nanoid") { + if (!nanoidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "nanoid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "cuid") { + if (!cuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "cuid2") { + if (!cuid2Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid2", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "ulid") { + if (!ulidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ulid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "url") { + try { + new URL(input.data); + } + catch { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "url", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "regex") { + check.regex.lastIndex = 0; + const testResult = check.regex.test(input.data); + if (!testResult) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "regex", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "trim") { + input.data = input.data.trim(); + } + else if (check.kind === "includes") { + if (!input.data.includes(check.value, check.position)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { includes: check.value, position: check.position }, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "toLowerCase") { + input.data = input.data.toLowerCase(); + } + else if (check.kind === "toUpperCase") { + input.data = input.data.toUpperCase(); + } + else if (check.kind === "startsWith") { + if (!input.data.startsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { startsWith: check.value }, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "endsWith") { + if (!input.data.endsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { endsWith: check.value }, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "datetime") { + const regex = datetimeRegex(check); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "datetime", + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "date") { + const regex = dateRegex; + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "date", + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "time") { + const regex = timeRegex(check); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "time", + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "duration") { + if (!durationRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "duration", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "ip") { + if (!isValidIP(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ip", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "jwt") { + if (!isValidJWT(input.data, check.alg)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "jwt", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "cidr") { + if (!isValidCidr(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cidr", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "base64") { + if (!base64Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "base64", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "base64url") { + if (!base64urlRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "base64url", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else { + util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + _regex(regex, validation, message) { + return this.refinement((data) => regex.test(data), { + validation, + code: ZodIssueCode.invalid_string, + ...errorUtil.errToObj(message), + }); + } + _addCheck(check) { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + email(message) { + return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); + } + url(message) { + return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); + } + emoji(message) { + return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); + } + uuid(message) { + return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); + } + nanoid(message) { + return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); + } + cuid(message) { + return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); + } + cuid2(message) { + return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); + } + ulid(message) { + return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); + } + base64(message) { + return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); + } + base64url(message) { + // base64url encoding is a modification of base64 that can safely be used in URLs and filenames + return this._addCheck({ + kind: "base64url", + ...errorUtil.errToObj(message), + }); + } + jwt(options) { + return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); + } + ip(options) { + return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); + } + cidr(options) { + return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); + } + datetime(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "datetime", + precision: null, + offset: false, + local: false, + message: options, + }); + } + return this._addCheck({ + kind: "datetime", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + offset: options?.offset ?? false, + local: options?.local ?? false, + ...errorUtil.errToObj(options?.message), + }); + } + date(message) { + return this._addCheck({ kind: "date", message }); + } + time(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "time", + precision: null, + message: options, + }); + } + return this._addCheck({ + kind: "time", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + ...errorUtil.errToObj(options?.message), + }); + } + duration(message) { + return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); + } + regex(regex, message) { + return this._addCheck({ + kind: "regex", + regex: regex, + ...errorUtil.errToObj(message), + }); + } + includes(value, options) { + return this._addCheck({ + kind: "includes", + value: value, + position: options?.position, + ...errorUtil.errToObj(options?.message), + }); + } + startsWith(value, message) { + return this._addCheck({ + kind: "startsWith", + value: value, + ...errorUtil.errToObj(message), + }); + } + endsWith(value, message) { + return this._addCheck({ + kind: "endsWith", + value: value, + ...errorUtil.errToObj(message), + }); + } + min(minLength, message) { + return this._addCheck({ + kind: "min", + value: minLength, + ...errorUtil.errToObj(message), + }); + } + max(maxLength, message) { + return this._addCheck({ + kind: "max", + value: maxLength, + ...errorUtil.errToObj(message), + }); + } + length(len, message) { + return this._addCheck({ + kind: "length", + value: len, + ...errorUtil.errToObj(message), + }); + } + /** + * Equivalent to `.min(1)` + */ + nonempty(message) { + return this.min(1, errorUtil.errToObj(message)); + } + trim() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "trim" }], + }); + } + toLowerCase() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toLowerCase" }], + }); + } + toUpperCase() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toUpperCase" }], + }); + } + get isDatetime() { + return !!this._def.checks.find((ch) => ch.kind === "datetime"); + } + get isDate() { + return !!this._def.checks.find((ch) => ch.kind === "date"); + } + get isTime() { + return !!this._def.checks.find((ch) => ch.kind === "time"); + } + get isDuration() { + return !!this._def.checks.find((ch) => ch.kind === "duration"); + } + get isEmail() { + return !!this._def.checks.find((ch) => ch.kind === "email"); + } + get isURL() { + return !!this._def.checks.find((ch) => ch.kind === "url"); + } + get isEmoji() { + return !!this._def.checks.find((ch) => ch.kind === "emoji"); + } + get isUUID() { + return !!this._def.checks.find((ch) => ch.kind === "uuid"); + } + get isNANOID() { + return !!this._def.checks.find((ch) => ch.kind === "nanoid"); + } + get isCUID() { + return !!this._def.checks.find((ch) => ch.kind === "cuid"); + } + get isCUID2() { + return !!this._def.checks.find((ch) => ch.kind === "cuid2"); + } + get isULID() { + return !!this._def.checks.find((ch) => ch.kind === "ulid"); + } + get isIP() { + return !!this._def.checks.find((ch) => ch.kind === "ip"); + } + get isCIDR() { + return !!this._def.checks.find((ch) => ch.kind === "cidr"); + } + get isBase64() { + return !!this._def.checks.find((ch) => ch.kind === "base64"); + } + get isBase64url() { + // base64url encoding is a modification of base64 that can safely be used in URLs and filenames + return !!this._def.checks.find((ch) => ch.kind === "base64url"); + } + get minLength() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxLength() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } +} +ZodString.create = (params) => { + return new ZodString({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodString, + coerce: params?.coerce ?? false, + ...processCreateParams(params), + }); +}; +// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034 +function floatSafeRemainder(val, step) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); + return (valInt % stepInt) / 10 ** decCount; +} +export class ZodNumber extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + this.step = this.multipleOf; + } + _parse(input) { + if (this._def.coerce) { + input.data = Number(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.number) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.number, + received: ctx.parsedType, + }); + return INVALID; + } + let ctx = undefined; + const status = new ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "int") { + if (!util.isInteger(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: "integer", + received: "float", + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "min") { + const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "max") { + const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "multipleOf") { + if (floatSafeRemainder(input.data, check.value) !== 0) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "finite") { + if (!Number.isFinite(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_finite, + message: check.message, + }); + status.dirty(); + } + } + else { + util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new ZodNumber({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message), + }, + ], + }); + } + _addCheck(check) { + return new ZodNumber({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + int(message) { + return this._addCheck({ + kind: "int", + message: errorUtil.toString(message), + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: false, + message: errorUtil.toString(message), + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: false, + message: errorUtil.toString(message), + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: true, + message: errorUtil.toString(message), + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: true, + message: errorUtil.toString(message), + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value: value, + message: errorUtil.toString(message), + }); + } + finite(message) { + return this._addCheck({ + kind: "finite", + message: errorUtil.toString(message), + }); + } + safe(message) { + return this._addCheck({ + kind: "min", + inclusive: true, + value: Number.MIN_SAFE_INTEGER, + message: errorUtil.toString(message), + })._addCheck({ + kind: "max", + inclusive: true, + value: Number.MAX_SAFE_INTEGER, + message: errorUtil.toString(message), + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + get isInt() { + return !!this._def.checks.find((ch) => ch.kind === "int" || (ch.kind === "multipleOf" && util.isInteger(ch.value))); + } + get isFinite() { + let max = null; + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { + return true; + } + else if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + else if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return Number.isFinite(min) && Number.isFinite(max); + } +} +ZodNumber.create = (params) => { + return new ZodNumber({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodNumber, + coerce: params?.coerce || false, + ...processCreateParams(params), + }); +}; +export class ZodBigInt extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + } + _parse(input) { + if (this._def.coerce) { + try { + input.data = BigInt(input.data); + } + catch { + return this._getInvalidInput(input); + } + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.bigint) { + return this._getInvalidInput(input); + } + let ctx = undefined; + const status = new ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "min") { + const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + type: "bigint", + minimum: check.value, + inclusive: check.inclusive, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "max") { + const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + type: "bigint", + maximum: check.value, + inclusive: check.inclusive, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "multipleOf") { + if (input.data % check.value !== BigInt(0)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message, + }); + status.dirty(); + } + } + else { + util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + _getInvalidInput(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.bigint, + received: ctx.parsedType, + }); + return INVALID; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new ZodBigInt({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message), + }, + ], + }); + } + _addCheck(check) { + return new ZodBigInt({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message), + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message), + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message), + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message), + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message), + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } +} +ZodBigInt.create = (params) => { + return new ZodBigInt({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodBigInt, + coerce: params?.coerce ?? false, + ...processCreateParams(params), + }); +}; +export class ZodBoolean extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = Boolean(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.boolean) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.boolean, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } +} +ZodBoolean.create = (params) => { + return new ZodBoolean({ + typeName: ZodFirstPartyTypeKind.ZodBoolean, + coerce: params?.coerce || false, + ...processCreateParams(params), + }); +}; +export class ZodDate extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = new Date(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.date) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.date, + received: ctx.parsedType, + }); + return INVALID; + } + if (Number.isNaN(input.data.getTime())) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_date, + }); + return INVALID; + } + const status = new ParseStatus(); + let ctx = undefined; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.getTime() < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + message: check.message, + inclusive: true, + exact: false, + minimum: check.value, + type: "date", + }); + status.dirty(); + } + } + else if (check.kind === "max") { + if (input.data.getTime() > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + message: check.message, + inclusive: true, + exact: false, + maximum: check.value, + type: "date", + }); + status.dirty(); + } + } + else { + util.assertNever(check); + } + } + return { + status: status.value, + value: new Date(input.data.getTime()), + }; + } + _addCheck(check) { + return new ZodDate({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + min(minDate, message) { + return this._addCheck({ + kind: "min", + value: minDate.getTime(), + message: errorUtil.toString(message), + }); + } + max(maxDate, message) { + return this._addCheck({ + kind: "max", + value: maxDate.getTime(), + message: errorUtil.toString(message), + }); + } + get minDate() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min != null ? new Date(min) : null; + } + get maxDate() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max != null ? new Date(max) : null; + } +} +ZodDate.create = (params) => { + return new ZodDate({ + checks: [], + coerce: params?.coerce || false, + typeName: ZodFirstPartyTypeKind.ZodDate, + ...processCreateParams(params), + }); +}; +export class ZodSymbol extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.symbol) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.symbol, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } +} +ZodSymbol.create = (params) => { + return new ZodSymbol({ + typeName: ZodFirstPartyTypeKind.ZodSymbol, + ...processCreateParams(params), + }); +}; +export class ZodUndefined extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.undefined, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } +} +ZodUndefined.create = (params) => { + return new ZodUndefined({ + typeName: ZodFirstPartyTypeKind.ZodUndefined, + ...processCreateParams(params), + }); +}; +export class ZodNull extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.null) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.null, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } +} +ZodNull.create = (params) => { + return new ZodNull({ + typeName: ZodFirstPartyTypeKind.ZodNull, + ...processCreateParams(params), + }); +}; +export class ZodAny extends ZodType { + constructor() { + super(...arguments); + // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject. + this._any = true; + } + _parse(input) { + return OK(input.data); + } +} +ZodAny.create = (params) => { + return new ZodAny({ + typeName: ZodFirstPartyTypeKind.ZodAny, + ...processCreateParams(params), + }); +}; +export class ZodUnknown extends ZodType { + constructor() { + super(...arguments); + // required + this._unknown = true; + } + _parse(input) { + return OK(input.data); + } +} +ZodUnknown.create = (params) => { + return new ZodUnknown({ + typeName: ZodFirstPartyTypeKind.ZodUnknown, + ...processCreateParams(params), + }); +}; +export class ZodNever extends ZodType { + _parse(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.never, + received: ctx.parsedType, + }); + return INVALID; + } +} +ZodNever.create = (params) => { + return new ZodNever({ + typeName: ZodFirstPartyTypeKind.ZodNever, + ...processCreateParams(params), + }); +}; +export class ZodVoid extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.void, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } +} +ZodVoid.create = (params) => { + return new ZodVoid({ + typeName: ZodFirstPartyTypeKind.ZodVoid, + ...processCreateParams(params), + }); +}; +export class ZodArray extends ZodType { + _parse(input) { + const { ctx, status } = this._processInputParams(input); + const def = this._def; + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType, + }); + return INVALID; + } + if (def.exactLength !== null) { + const tooBig = ctx.data.length > def.exactLength.value; + const tooSmall = ctx.data.length < def.exactLength.value; + if (tooBig || tooSmall) { + addIssueToContext(ctx, { + code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, + minimum: (tooSmall ? def.exactLength.value : undefined), + maximum: (tooBig ? def.exactLength.value : undefined), + type: "array", + inclusive: true, + exact: true, + message: def.exactLength.message, + }); + status.dirty(); + } + } + if (def.minLength !== null) { + if (ctx.data.length < def.minLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.minLength.message, + }); + status.dirty(); + } + } + if (def.maxLength !== null) { + if (ctx.data.length > def.maxLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.maxLength.message, + }); + status.dirty(); + } + } + if (ctx.common.async) { + return Promise.all([...ctx.data].map((item, i) => { + return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + })).then((result) => { + return ParseStatus.mergeArray(status, result); + }); + } + const result = [...ctx.data].map((item, i) => { + return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + }); + return ParseStatus.mergeArray(status, result); + } + get element() { + return this._def.type; + } + min(minLength, message) { + return new ZodArray({ + ...this._def, + minLength: { value: minLength, message: errorUtil.toString(message) }, + }); + } + max(maxLength, message) { + return new ZodArray({ + ...this._def, + maxLength: { value: maxLength, message: errorUtil.toString(message) }, + }); + } + length(len, message) { + return new ZodArray({ + ...this._def, + exactLength: { value: len, message: errorUtil.toString(message) }, + }); + } + nonempty(message) { + return this.min(1, message); + } +} +ZodArray.create = (schema, params) => { + return new ZodArray({ + type: schema, + minLength: null, + maxLength: null, + exactLength: null, + typeName: ZodFirstPartyTypeKind.ZodArray, + ...processCreateParams(params), + }); +}; +function deepPartialify(schema) { + if (schema instanceof ZodObject) { + const newShape = {}; + for (const key in schema.shape) { + const fieldSchema = schema.shape[key]; + newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); + } + return new ZodObject({ + ...schema._def, + shape: () => newShape, + }); + } + else if (schema instanceof ZodArray) { + return new ZodArray({ + ...schema._def, + type: deepPartialify(schema.element), + }); + } + else if (schema instanceof ZodOptional) { + return ZodOptional.create(deepPartialify(schema.unwrap())); + } + else if (schema instanceof ZodNullable) { + return ZodNullable.create(deepPartialify(schema.unwrap())); + } + else if (schema instanceof ZodTuple) { + return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); + } + else { + return schema; + } +} +export class ZodObject extends ZodType { + constructor() { + super(...arguments); + this._cached = null; + /** + * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped. + * If you want to pass through unknown properties, use `.passthrough()` instead. + */ + this.nonstrict = this.passthrough; + // extend< + // Augmentation extends ZodRawShape, + // NewOutput extends util.flatten<{ + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }>, + // NewInput extends util.flatten<{ + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // }> + // >( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, + // UnknownKeys, + // Catchall, + // NewOutput, + // NewInput + // > { + // return new ZodObject({ + // ...this._def, + // shape: () => ({ + // ...this._def.shape(), + // ...augmentation, + // }), + // }) as any; + // } + /** + * @deprecated Use `.extend` instead + * */ + this.augment = this.extend; + } + _getCached() { + if (this._cached !== null) + return this._cached; + const shape = this._def.shape(); + const keys = util.objectKeys(shape); + this._cached = { shape, keys }; + return this._cached; + } + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.object) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType, + }); + return INVALID; + } + const { status, ctx } = this._processInputParams(input); + const { shape, keys: shapeKeys } = this._getCached(); + const extraKeys = []; + if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { + for (const key in ctx.data) { + if (!shapeKeys.includes(key)) { + extraKeys.push(key); + } + } + } + const pairs = []; + for (const key of shapeKeys) { + const keyValidator = shape[key]; + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data, + }); + } + if (this._def.catchall instanceof ZodNever) { + const unknownKeys = this._def.unknownKeys; + if (unknownKeys === "passthrough") { + for (const key of extraKeys) { + pairs.push({ + key: { status: "valid", value: key }, + value: { status: "valid", value: ctx.data[key] }, + }); + } + } + else if (unknownKeys === "strict") { + if (extraKeys.length > 0) { + addIssueToContext(ctx, { + code: ZodIssueCode.unrecognized_keys, + keys: extraKeys, + }); + status.dirty(); + } + } + else if (unknownKeys === "strip") { + } + else { + throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); + } + } + else { + // run catchall validation + const catchall = this._def.catchall; + for (const key of extraKeys) { + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value) + ), + alwaysSet: key in ctx.data, + }); + } + } + if (ctx.common.async) { + return Promise.resolve() + .then(async () => { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value, + alwaysSet: pair.alwaysSet, + }); + } + return syncPairs; + }) + .then((syncPairs) => { + return ParseStatus.mergeObjectSync(status, syncPairs); + }); + } + else { + return ParseStatus.mergeObjectSync(status, pairs); + } + } + get shape() { + return this._def.shape(); + } + strict(message) { + errorUtil.errToObj; + return new ZodObject({ + ...this._def, + unknownKeys: "strict", + ...(message !== undefined + ? { + errorMap: (issue, ctx) => { + const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError; + if (issue.code === "unrecognized_keys") + return { + message: errorUtil.errToObj(message).message ?? defaultError, + }; + return { + message: defaultError, + }; + }, + } + : {}), + }); + } + strip() { + return new ZodObject({ + ...this._def, + unknownKeys: "strip", + }); + } + passthrough() { + return new ZodObject({ + ...this._def, + unknownKeys: "passthrough", + }); + } + // const AugmentFactory = + // (def: Def) => + // ( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, Augmentation>, + // Def["unknownKeys"], + // Def["catchall"] + // > => { + // return new ZodObject({ + // ...def, + // shape: () => ({ + // ...def.shape(), + // ...augmentation, + // }), + // }) as any; + // }; + extend(augmentation) { + return new ZodObject({ + ...this._def, + shape: () => ({ + ...this._def.shape(), + ...augmentation, + }), + }); + } + /** + * Prior to zod@1.0.12 there was a bug in the + * inferred type of merged objects. Please + * upgrade if you are experiencing issues. + */ + merge(merging) { + const merged = new ZodObject({ + unknownKeys: merging._def.unknownKeys, + catchall: merging._def.catchall, + shape: () => ({ + ...this._def.shape(), + ...merging._def.shape(), + }), + typeName: ZodFirstPartyTypeKind.ZodObject, + }); + return merged; + } + // merge< + // Incoming extends AnyZodObject, + // Augmentation extends Incoming["shape"], + // NewOutput extends { + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }, + // NewInput extends { + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // } + // >( + // merging: Incoming + // ): ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"], + // NewOutput, + // NewInput + // > { + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + setKey(key, schema) { + return this.augment({ [key]: schema }); + } + // merge( + // merging: Incoming + // ): //ZodObject = (merging) => { + // ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"] + // > { + // // const mergedShape = objectUtil.mergeShapes( + // // this._def.shape(), + // // merging._def.shape() + // // ); + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + catchall(index) { + return new ZodObject({ + ...this._def, + catchall: index, + }); + } + pick(mask) { + const shape = {}; + for (const key of util.objectKeys(mask)) { + if (mask[key] && this.shape[key]) { + shape[key] = this.shape[key]; + } + } + return new ZodObject({ + ...this._def, + shape: () => shape, + }); + } + omit(mask) { + const shape = {}; + for (const key of util.objectKeys(this.shape)) { + if (!mask[key]) { + shape[key] = this.shape[key]; + } + } + return new ZodObject({ + ...this._def, + shape: () => shape, + }); + } + /** + * @deprecated + */ + deepPartial() { + return deepPartialify(this); + } + partial(mask) { + const newShape = {}; + for (const key of util.objectKeys(this.shape)) { + const fieldSchema = this.shape[key]; + if (mask && !mask[key]) { + newShape[key] = fieldSchema; + } + else { + newShape[key] = fieldSchema.optional(); + } + } + return new ZodObject({ + ...this._def, + shape: () => newShape, + }); + } + required(mask) { + const newShape = {}; + for (const key of util.objectKeys(this.shape)) { + if (mask && !mask[key]) { + newShape[key] = this.shape[key]; + } + else { + const fieldSchema = this.shape[key]; + let newField = fieldSchema; + while (newField instanceof ZodOptional) { + newField = newField._def.innerType; + } + newShape[key] = newField; + } + } + return new ZodObject({ + ...this._def, + shape: () => newShape, + }); + } + keyof() { + return createZodEnum(util.objectKeys(this.shape)); + } +} +ZodObject.create = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }); +}; +ZodObject.strictCreate = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strict", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }); +}; +ZodObject.lazycreate = (shape, params) => { + return new ZodObject({ + shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }); +}; +export class ZodUnion extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const options = this._def.options; + function handleResults(results) { + // return first issue-free validation if it exists + for (const result of results) { + if (result.result.status === "valid") { + return result.result; + } + } + for (const result of results) { + if (result.result.status === "dirty") { + // add issues from dirty option + ctx.common.issues.push(...result.ctx.common.issues); + return result.result; + } + } + // return invalid + const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors, + }); + return INVALID; + } + if (ctx.common.async) { + return Promise.all(options.map(async (option) => { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + parent: null, + }; + return { + result: await option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: childCtx, + }), + ctx: childCtx, + }; + })).then(handleResults); + } + else { + let dirty = undefined; + const issues = []; + for (const option of options) { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + parent: null, + }; + const result = option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: childCtx, + }); + if (result.status === "valid") { + return result; + } + else if (result.status === "dirty" && !dirty) { + dirty = { result, ctx: childCtx }; + } + if (childCtx.common.issues.length) { + issues.push(childCtx.common.issues); + } + } + if (dirty) { + ctx.common.issues.push(...dirty.ctx.common.issues); + return dirty.result; + } + const unionErrors = issues.map((issues) => new ZodError(issues)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors, + }); + return INVALID; + } + } + get options() { + return this._def.options; + } +} +ZodUnion.create = (types, params) => { + return new ZodUnion({ + options: types, + typeName: ZodFirstPartyTypeKind.ZodUnion, + ...processCreateParams(params), + }); +}; +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// +////////// ////////// +////////// ZodDiscriminatedUnion ////////// +////////// ////////// +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// +const getDiscriminator = (type) => { + if (type instanceof ZodLazy) { + return getDiscriminator(type.schema); + } + else if (type instanceof ZodEffects) { + return getDiscriminator(type.innerType()); + } + else if (type instanceof ZodLiteral) { + return [type.value]; + } + else if (type instanceof ZodEnum) { + return type.options; + } + else if (type instanceof ZodNativeEnum) { + // eslint-disable-next-line ban/ban + return util.objectValues(type.enum); + } + else if (type instanceof ZodDefault) { + return getDiscriminator(type._def.innerType); + } + else if (type instanceof ZodUndefined) { + return [undefined]; + } + else if (type instanceof ZodNull) { + return [null]; + } + else if (type instanceof ZodOptional) { + return [undefined, ...getDiscriminator(type.unwrap())]; + } + else if (type instanceof ZodNullable) { + return [null, ...getDiscriminator(type.unwrap())]; + } + else if (type instanceof ZodBranded) { + return getDiscriminator(type.unwrap()); + } + else if (type instanceof ZodReadonly) { + return getDiscriminator(type.unwrap()); + } + else if (type instanceof ZodCatch) { + return getDiscriminator(type._def.innerType); + } + else { + return []; + } +}; +export class ZodDiscriminatedUnion extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType, + }); + return INVALID; + } + const discriminator = this.discriminator; + const discriminatorValue = ctx.data[discriminator]; + const option = this.optionsMap.get(discriminatorValue); + if (!option) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union_discriminator, + options: Array.from(this.optionsMap.keys()), + path: [discriminator], + }); + return INVALID; + } + if (ctx.common.async) { + return option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + } + else { + return option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + } + } + get discriminator() { + return this._def.discriminator; + } + get options() { + return this._def.options; + } + get optionsMap() { + return this._def.optionsMap; + } + /** + * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. + * However, it only allows a union of objects, all of which need to share a discriminator property. This property must + * have a different value for each object in the union. + * @param discriminator the name of the discriminator property + * @param types an array of object schemas + * @param params + */ + static create(discriminator, options, params) { + // Get all the valid discriminator values + const optionsMap = new Map(); + // try { + for (const type of options) { + const discriminatorValues = getDiscriminator(type.shape[discriminator]); + if (!discriminatorValues.length) { + throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); + } + for (const value of discriminatorValues) { + if (optionsMap.has(value)) { + throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); + } + optionsMap.set(value, type); + } + } + return new ZodDiscriminatedUnion({ + typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, + discriminator, + options, + optionsMap, + ...processCreateParams(params), + }); + } +} +function mergeValues(a, b) { + const aType = getParsedType(a); + const bType = getParsedType(b); + if (a === b) { + return { valid: true, data: a }; + } + else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { + const bKeys = util.objectKeys(b); + const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b }; + for (const key of sharedKeys) { + const sharedValue = mergeValues(a[key], b[key]); + if (!sharedValue.valid) { + return { valid: false }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } + else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { + if (a.length !== b.length) { + return { valid: false }; + } + const newArray = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = mergeValues(itemA, itemB); + if (!sharedValue.valid) { + return { valid: false }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } + else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { + return { valid: true, data: a }; + } + else { + return { valid: false }; + } +} +export class ZodIntersection extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const handleParsed = (parsedLeft, parsedRight) => { + if (isAborted(parsedLeft) || isAborted(parsedRight)) { + return INVALID; + } + const merged = mergeValues(parsedLeft.value, parsedRight.value); + if (!merged.valid) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_intersection_types, + }); + return INVALID; + } + if (isDirty(parsedLeft) || isDirty(parsedRight)) { + status.dirty(); + } + return { status: status.value, value: merged.data }; + }; + if (ctx.common.async) { + return Promise.all([ + this._def.left._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), + this._def.right._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), + ]).then(([left, right]) => handleParsed(left, right)); + } + else { + return handleParsed(this._def.left._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), this._def.right._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + })); + } + } +} +ZodIntersection.create = (left, right, params) => { + return new ZodIntersection({ + left: left, + right: right, + typeName: ZodFirstPartyTypeKind.ZodIntersection, + ...processCreateParams(params), + }); +}; +// type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]]; +export class ZodTuple extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType, + }); + return INVALID; + } + if (ctx.data.length < this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: this._def.items.length, + inclusive: true, + exact: false, + type: "array", + }); + return INVALID; + } + const rest = this._def.rest; + if (!rest && ctx.data.length > this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: this._def.items.length, + inclusive: true, + exact: false, + type: "array", + }); + status.dirty(); + } + const items = [...ctx.data] + .map((item, itemIndex) => { + const schema = this._def.items[itemIndex] || this._def.rest; + if (!schema) + return null; + return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); + }) + .filter((x) => !!x); // filter nulls + if (ctx.common.async) { + return Promise.all(items).then((results) => { + return ParseStatus.mergeArray(status, results); + }); + } + else { + return ParseStatus.mergeArray(status, items); + } + } + get items() { + return this._def.items; + } + rest(rest) { + return new ZodTuple({ + ...this._def, + rest, + }); + } +} +ZodTuple.create = (schemas, params) => { + if (!Array.isArray(schemas)) { + throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); + } + return new ZodTuple({ + items: schemas, + typeName: ZodFirstPartyTypeKind.ZodTuple, + rest: null, + ...processCreateParams(params), + }); +}; +export class ZodRecord extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType, + }); + return INVALID; + } + const pairs = []; + const keyType = this._def.keyType; + const valueType = this._def.valueType; + for (const key in ctx.data) { + pairs.push({ + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), + value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), + alwaysSet: key in ctx.data, + }); + } + if (ctx.common.async) { + return ParseStatus.mergeObjectAsync(status, pairs); + } + else { + return ParseStatus.mergeObjectSync(status, pairs); + } + } + get element() { + return this._def.valueType; + } + static create(first, second, third) { + if (second instanceof ZodType) { + return new ZodRecord({ + keyType: first, + valueType: second, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(third), + }); + } + return new ZodRecord({ + keyType: ZodString.create(), + valueType: first, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(second), + }); + } +} +export class ZodMap extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.map) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.map, + received: ctx.parsedType, + }); + return INVALID; + } + const keyType = this._def.keyType; + const valueType = this._def.valueType; + const pairs = [...ctx.data.entries()].map(([key, value], index) => { + return { + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), + value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])), + }; + }); + if (ctx.common.async) { + const finalMap = new Map(); + return Promise.resolve().then(async () => { + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + }); + } + else { + const finalMap = new Map(); + for (const pair of pairs) { + const key = pair.key; + const value = pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + } + } +} +ZodMap.create = (keyType, valueType, params) => { + return new ZodMap({ + valueType, + keyType, + typeName: ZodFirstPartyTypeKind.ZodMap, + ...processCreateParams(params), + }); +}; +export class ZodSet extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.set) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.set, + received: ctx.parsedType, + }); + return INVALID; + } + const def = this._def; + if (def.minSize !== null) { + if (ctx.data.size < def.minSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.minSize.message, + }); + status.dirty(); + } + } + if (def.maxSize !== null) { + if (ctx.data.size > def.maxSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.maxSize.message, + }); + status.dirty(); + } + } + const valueType = this._def.valueType; + function finalizeSet(elements) { + const parsedSet = new Set(); + for (const element of elements) { + if (element.status === "aborted") + return INVALID; + if (element.status === "dirty") + status.dirty(); + parsedSet.add(element.value); + } + return { status: status.value, value: parsedSet }; + } + const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); + if (ctx.common.async) { + return Promise.all(elements).then((elements) => finalizeSet(elements)); + } + else { + return finalizeSet(elements); + } + } + min(minSize, message) { + return new ZodSet({ + ...this._def, + minSize: { value: minSize, message: errorUtil.toString(message) }, + }); + } + max(maxSize, message) { + return new ZodSet({ + ...this._def, + maxSize: { value: maxSize, message: errorUtil.toString(message) }, + }); + } + size(size, message) { + return this.min(size, message).max(size, message); + } + nonempty(message) { + return this.min(1, message); + } +} +ZodSet.create = (valueType, params) => { + return new ZodSet({ + valueType, + minSize: null, + maxSize: null, + typeName: ZodFirstPartyTypeKind.ZodSet, + ...processCreateParams(params), + }); +}; +export class ZodFunction extends ZodType { + constructor() { + super(...arguments); + this.validate = this.implement; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.function) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.function, + received: ctx.parsedType, + }); + return INVALID; + } + function makeArgsIssue(args, error) { + return makeIssue({ + data: args, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_arguments, + argumentsError: error, + }, + }); + } + function makeReturnsIssue(returns, error) { + return makeIssue({ + data: returns, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_return_type, + returnTypeError: error, + }, + }); + } + const params = { errorMap: ctx.common.contextualErrorMap }; + const fn = ctx.data; + if (this._def.returns instanceof ZodPromise) { + // Would love a way to avoid disabling this rule, but we need + // an alias (using an arrow function was what caused 2651). + // eslint-disable-next-line @typescript-eslint/no-this-alias + const me = this; + return OK(async function (...args) { + const error = new ZodError([]); + const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { + error.addIssue(makeArgsIssue(args, e)); + throw error; + }); + const result = await Reflect.apply(fn, this, parsedArgs); + const parsedReturns = await me._def.returns._def.type + .parseAsync(result, params) + .catch((e) => { + error.addIssue(makeReturnsIssue(result, e)); + throw error; + }); + return parsedReturns; + }); + } + else { + // Would love a way to avoid disabling this rule, but we need + // an alias (using an arrow function was what caused 2651). + // eslint-disable-next-line @typescript-eslint/no-this-alias + const me = this; + return OK(function (...args) { + const parsedArgs = me._def.args.safeParse(args, params); + if (!parsedArgs.success) { + throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); + } + const result = Reflect.apply(fn, this, parsedArgs.data); + const parsedReturns = me._def.returns.safeParse(result, params); + if (!parsedReturns.success) { + throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); + } + return parsedReturns.data; + }); + } + } + parameters() { + return this._def.args; + } + returnType() { + return this._def.returns; + } + args(...items) { + return new ZodFunction({ + ...this._def, + args: ZodTuple.create(items).rest(ZodUnknown.create()), + }); + } + returns(returnType) { + return new ZodFunction({ + ...this._def, + returns: returnType, + }); + } + implement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + strictImplement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + static create(args, returns, params) { + return new ZodFunction({ + args: (args ? args : ZodTuple.create([]).rest(ZodUnknown.create())), + returns: returns || ZodUnknown.create(), + typeName: ZodFirstPartyTypeKind.ZodFunction, + ...processCreateParams(params), + }); + } +} +export class ZodLazy extends ZodType { + get schema() { + return this._def.getter(); + } + _parse(input) { + const { ctx } = this._processInputParams(input); + const lazySchema = this._def.getter(); + return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); + } +} +ZodLazy.create = (getter, params) => { + return new ZodLazy({ + getter: getter, + typeName: ZodFirstPartyTypeKind.ZodLazy, + ...processCreateParams(params), + }); +}; +export class ZodLiteral extends ZodType { + _parse(input) { + if (input.data !== this._def.value) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_literal, + expected: this._def.value, + }); + return INVALID; + } + return { status: "valid", value: input.data }; + } + get value() { + return this._def.value; + } +} +ZodLiteral.create = (value, params) => { + return new ZodLiteral({ + value: value, + typeName: ZodFirstPartyTypeKind.ZodLiteral, + ...processCreateParams(params), + }); +}; +function createZodEnum(values, params) { + return new ZodEnum({ + values, + typeName: ZodFirstPartyTypeKind.ZodEnum, + ...processCreateParams(params), + }); +} +export class ZodEnum extends ZodType { + _parse(input) { + if (typeof input.data !== "string") { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type, + }); + return INVALID; + } + if (!this._cache) { + this._cache = new Set(this._def.values); + } + if (!this._cache.has(input.data)) { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues, + }); + return INVALID; + } + return OK(input.data); + } + get options() { + return this._def.values; + } + get enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + get Values() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + get Enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + extract(values, newDef = this._def) { + return ZodEnum.create(values, { + ...this._def, + ...newDef, + }); + } + exclude(values, newDef = this._def) { + return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { + ...this._def, + ...newDef, + }); + } +} +ZodEnum.create = createZodEnum; +export class ZodNativeEnum extends ZodType { + _parse(input) { + const nativeEnumValues = util.getValidEnumValues(this._def.values); + const ctx = this._getOrReturnCtx(input); + if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { + const expectedValues = util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type, + }); + return INVALID; + } + if (!this._cache) { + this._cache = new Set(util.getValidEnumValues(this._def.values)); + } + if (!this._cache.has(input.data)) { + const expectedValues = util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues, + }); + return INVALID; + } + return OK(input.data); + } + get enum() { + return this._def.values; + } +} +ZodNativeEnum.create = (values, params) => { + return new ZodNativeEnum({ + values: values, + typeName: ZodFirstPartyTypeKind.ZodNativeEnum, + ...processCreateParams(params), + }); +}; +export class ZodPromise extends ZodType { + unwrap() { + return this._def.type; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.promise, + received: ctx.parsedType, + }); + return INVALID; + } + const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); + return OK(promisified.then((data) => { + return this._def.type.parseAsync(data, { + path: ctx.path, + errorMap: ctx.common.contextualErrorMap, + }); + })); + } +} +ZodPromise.create = (schema, params) => { + return new ZodPromise({ + type: schema, + typeName: ZodFirstPartyTypeKind.ZodPromise, + ...processCreateParams(params), + }); +}; +export class ZodEffects extends ZodType { + innerType() { + return this._def.schema; + } + sourceType() { + return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects + ? this._def.schema.sourceType() + : this._def.schema; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const effect = this._def.effect || null; + const checkCtx = { + addIssue: (arg) => { + addIssueToContext(ctx, arg); + if (arg.fatal) { + status.abort(); + } + else { + status.dirty(); + } + }, + get path() { + return ctx.path; + }, + }; + checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); + if (effect.type === "preprocess") { + const processed = effect.transform(ctx.data, checkCtx); + if (ctx.common.async) { + return Promise.resolve(processed).then(async (processed) => { + if (status.value === "aborted") + return INVALID; + const result = await this._def.schema._parseAsync({ + data: processed, + path: ctx.path, + parent: ctx, + }); + if (result.status === "aborted") + return INVALID; + if (result.status === "dirty") + return DIRTY(result.value); + if (status.value === "dirty") + return DIRTY(result.value); + return result; + }); + } + else { + if (status.value === "aborted") + return INVALID; + const result = this._def.schema._parseSync({ + data: processed, + path: ctx.path, + parent: ctx, + }); + if (result.status === "aborted") + return INVALID; + if (result.status === "dirty") + return DIRTY(result.value); + if (status.value === "dirty") + return DIRTY(result.value); + return result; + } + } + if (effect.type === "refinement") { + const executeRefinement = (acc) => { + const result = effect.refinement(acc, checkCtx); + if (ctx.common.async) { + return Promise.resolve(result); + } + if (result instanceof Promise) { + throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); + } + return acc; + }; + if (ctx.common.async === false) { + const inner = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + // return value is ignored + executeRefinement(inner.value); + return { status: status.value, value: inner.value }; + } + else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + return executeRefinement(inner.value).then(() => { + return { status: status.value, value: inner.value }; + }); + }); + } + } + if (effect.type === "transform") { + if (ctx.common.async === false) { + const base = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (!isValid(base)) + return INVALID; + const result = effect.transform(base.value, checkCtx); + if (result instanceof Promise) { + throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); + } + return { status: status.value, value: result }; + } + else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { + if (!isValid(base)) + return INVALID; + return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ + status: status.value, + value: result, + })); + }); + } + } + util.assertNever(effect); + } +} +ZodEffects.create = (schema, effect, params) => { + return new ZodEffects({ + schema, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect, + ...processCreateParams(params), + }); +}; +ZodEffects.createWithPreprocess = (preprocess, schema, params) => { + return new ZodEffects({ + schema, + effect: { type: "preprocess", transform: preprocess }, + typeName: ZodFirstPartyTypeKind.ZodEffects, + ...processCreateParams(params), + }); +}; +export { ZodEffects as ZodTransformer }; +export class ZodOptional extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.undefined) { + return OK(undefined); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } +} +ZodOptional.create = (type, params) => { + return new ZodOptional({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodOptional, + ...processCreateParams(params), + }); +}; +export class ZodNullable extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.null) { + return OK(null); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } +} +ZodNullable.create = (type, params) => { + return new ZodNullable({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodNullable, + ...processCreateParams(params), + }); +}; +export class ZodDefault extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + let data = ctx.data; + if (ctx.parsedType === ZodParsedType.undefined) { + data = this._def.defaultValue(); + } + return this._def.innerType._parse({ + data, + path: ctx.path, + parent: ctx, + }); + } + removeDefault() { + return this._def.innerType; + } +} +ZodDefault.create = (type, params) => { + return new ZodDefault({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodDefault, + defaultValue: typeof params.default === "function" ? params.default : () => params.default, + ...processCreateParams(params), + }); +}; +export class ZodCatch extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + // newCtx is used to not collect issues from inner types in ctx + const newCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + }; + const result = this._def.innerType._parse({ + data: newCtx.data, + path: newCtx.path, + parent: { + ...newCtx, + }, + }); + if (isAsync(result)) { + return result.then((result) => { + return { + status: "valid", + value: result.status === "valid" + ? result.value + : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data, + }), + }; + }); + } + else { + return { + status: "valid", + value: result.status === "valid" + ? result.value + : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data, + }), + }; + } + } + removeCatch() { + return this._def.innerType; + } +} +ZodCatch.create = (type, params) => { + return new ZodCatch({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodCatch, + catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, + ...processCreateParams(params), + }); +}; +export class ZodNaN extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.nan) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.nan, + received: ctx.parsedType, + }); + return INVALID; + } + return { status: "valid", value: input.data }; + } +} +ZodNaN.create = (params) => { + return new ZodNaN({ + typeName: ZodFirstPartyTypeKind.ZodNaN, + ...processCreateParams(params), + }); +}; +export const BRAND = Symbol("zod_brand"); +export class ZodBranded extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const data = ctx.data; + return this._def.type._parse({ + data, + path: ctx.path, + parent: ctx, + }); + } + unwrap() { + return this._def.type; + } +} +export class ZodPipeline extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.common.async) { + const handleAsync = async () => { + const inResult = await this._def.in._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return DIRTY(inResult.value); + } + else { + return this._def.out._parseAsync({ + data: inResult.value, + path: ctx.path, + parent: ctx, + }); + } + }; + return handleAsync(); + } + else { + const inResult = this._def.in._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return { + status: "dirty", + value: inResult.value, + }; + } + else { + return this._def.out._parseSync({ + data: inResult.value, + path: ctx.path, + parent: ctx, + }); + } + } + } + static create(a, b) { + return new ZodPipeline({ + in: a, + out: b, + typeName: ZodFirstPartyTypeKind.ZodPipeline, + }); + } +} +export class ZodReadonly extends ZodType { + _parse(input) { + const result = this._def.innerType._parse(input); + const freeze = (data) => { + if (isValid(data)) { + data.value = Object.freeze(data.value); + } + return data; + }; + return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); + } + unwrap() { + return this._def.innerType; + } +} +ZodReadonly.create = (type, params) => { + return new ZodReadonly({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodReadonly, + ...processCreateParams(params), + }); +}; +//////////////////////////////////////// +//////////////////////////////////////// +////////// ////////// +////////// z.custom ////////// +////////// ////////// +//////////////////////////////////////// +//////////////////////////////////////// +function cleanParams(params, data) { + const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; + const p2 = typeof p === "string" ? { message: p } : p; + return p2; +} +export function custom(check, _params = {}, +/** + * @deprecated + * + * Pass `fatal` into the params object instead: + * + * ```ts + * z.string().custom((val) => val.length > 5, { fatal: false }) + * ``` + * + */ +fatal) { + if (check) + return ZodAny.create().superRefine((data, ctx) => { + const r = check(data); + if (r instanceof Promise) { + return r.then((r) => { + if (!r) { + const params = cleanParams(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + }); + } + if (!r) { + const params = cleanParams(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + return; + }); + return ZodAny.create(); +} +export { ZodType as Schema, ZodType as ZodSchema }; +export const late = { + object: ZodObject.lazycreate, +}; +export var ZodFirstPartyTypeKind; +(function (ZodFirstPartyTypeKind) { + ZodFirstPartyTypeKind["ZodString"] = "ZodString"; + ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber"; + ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN"; + ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt"; + ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean"; + ZodFirstPartyTypeKind["ZodDate"] = "ZodDate"; + ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol"; + ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined"; + ZodFirstPartyTypeKind["ZodNull"] = "ZodNull"; + ZodFirstPartyTypeKind["ZodAny"] = "ZodAny"; + ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown"; + ZodFirstPartyTypeKind["ZodNever"] = "ZodNever"; + ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid"; + ZodFirstPartyTypeKind["ZodArray"] = "ZodArray"; + ZodFirstPartyTypeKind["ZodObject"] = "ZodObject"; + ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion"; + ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; + ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection"; + ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple"; + ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord"; + ZodFirstPartyTypeKind["ZodMap"] = "ZodMap"; + ZodFirstPartyTypeKind["ZodSet"] = "ZodSet"; + ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction"; + ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy"; + ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral"; + ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum"; + ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects"; + ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum"; + ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional"; + ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable"; + ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault"; + ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch"; + ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise"; + ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded"; + ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline"; + ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly"; +})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); +// requires TS 4.4+ +class Class { + constructor(..._) { } +} +const instanceOfType = ( +// const instanceOfType = any>( +cls, params = { + message: `Input not instance of ${cls.name}`, +}) => custom((data) => data instanceof cls, params); +const stringType = ZodString.create; +const numberType = ZodNumber.create; +const nanType = ZodNaN.create; +const bigIntType = ZodBigInt.create; +const booleanType = ZodBoolean.create; +const dateType = ZodDate.create; +const symbolType = ZodSymbol.create; +const undefinedType = ZodUndefined.create; +const nullType = ZodNull.create; +const anyType = ZodAny.create; +const unknownType = ZodUnknown.create; +const neverType = ZodNever.create; +const voidType = ZodVoid.create; +const arrayType = ZodArray.create; +const objectType = ZodObject.create; +const strictObjectType = ZodObject.strictCreate; +const unionType = ZodUnion.create; +const discriminatedUnionType = ZodDiscriminatedUnion.create; +const intersectionType = ZodIntersection.create; +const tupleType = ZodTuple.create; +const recordType = ZodRecord.create; +const mapType = ZodMap.create; +const setType = ZodSet.create; +const functionType = ZodFunction.create; +const lazyType = ZodLazy.create; +const literalType = ZodLiteral.create; +const enumType = ZodEnum.create; +const nativeEnumType = ZodNativeEnum.create; +const promiseType = ZodPromise.create; +const effectsType = ZodEffects.create; +const optionalType = ZodOptional.create; +const nullableType = ZodNullable.create; +const preprocessType = ZodEffects.createWithPreprocess; +const pipelineType = ZodPipeline.create; +const ostring = () => stringType().optional(); +const onumber = () => numberType().optional(); +const oboolean = () => booleanType().optional(); +export const coerce = { + string: ((arg) => ZodString.create({ ...arg, coerce: true })), + number: ((arg) => ZodNumber.create({ ...arg, coerce: true })), + boolean: ((arg) => ZodBoolean.create({ + ...arg, + coerce: true, + })), + bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })), + date: ((arg) => ZodDate.create({ ...arg, coerce: true })), +}; +export { anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, dateType as date, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, instanceOfType as instanceof, intersectionType as intersection, lazyType as lazy, literalType as literal, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, recordType as record, setType as set, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, voidType as void, }; +export const NEVER = INVALID; diff --git a/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/index.d.ts b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/index.d.ts new file mode 100644 index 000000000..8352ab713 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/index.d.ts @@ -0,0 +1,3 @@ +import z3 from "./v3/index.js"; +export * from "./v3/index.js"; +export default z3; diff --git a/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/ZodError.d.ts b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/ZodError.d.ts new file mode 100644 index 000000000..4e71355a3 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/ZodError.d.ts @@ -0,0 +1,164 @@ +import type { Primitive } from "./helpers/typeAliases.js"; +import { util, type ZodParsedType } from "./helpers/util.js"; +import type { TypeOf, ZodType } from "./index.js"; +type allKeys = T extends any ? keyof T : never; +export type inferFlattenedErrors, U = string> = typeToFlattenedError, U>; +export type typeToFlattenedError = { + formErrors: U[]; + fieldErrors: { + [P in allKeys]?: U[]; + }; +}; +export declare const ZodIssueCode: { + invalid_type: "invalid_type"; + invalid_literal: "invalid_literal"; + custom: "custom"; + invalid_union: "invalid_union"; + invalid_union_discriminator: "invalid_union_discriminator"; + invalid_enum_value: "invalid_enum_value"; + unrecognized_keys: "unrecognized_keys"; + invalid_arguments: "invalid_arguments"; + invalid_return_type: "invalid_return_type"; + invalid_date: "invalid_date"; + invalid_string: "invalid_string"; + too_small: "too_small"; + too_big: "too_big"; + invalid_intersection_types: "invalid_intersection_types"; + not_multiple_of: "not_multiple_of"; + not_finite: "not_finite"; +}; +export type ZodIssueCode = keyof typeof ZodIssueCode; +export type ZodIssueBase = { + path: (string | number)[]; + message?: string | undefined; +}; +export interface ZodInvalidTypeIssue extends ZodIssueBase { + code: typeof ZodIssueCode.invalid_type; + expected: ZodParsedType; + received: ZodParsedType; +} +export interface ZodInvalidLiteralIssue extends ZodIssueBase { + code: typeof ZodIssueCode.invalid_literal; + expected: unknown; + received: unknown; +} +export interface ZodUnrecognizedKeysIssue extends ZodIssueBase { + code: typeof ZodIssueCode.unrecognized_keys; + keys: string[]; +} +export interface ZodInvalidUnionIssue extends ZodIssueBase { + code: typeof ZodIssueCode.invalid_union; + unionErrors: ZodError[]; +} +export interface ZodInvalidUnionDiscriminatorIssue extends ZodIssueBase { + code: typeof ZodIssueCode.invalid_union_discriminator; + options: Primitive[]; +} +export interface ZodInvalidEnumValueIssue extends ZodIssueBase { + received: string | number; + code: typeof ZodIssueCode.invalid_enum_value; + options: (string | number)[]; +} +export interface ZodInvalidArgumentsIssue extends ZodIssueBase { + code: typeof ZodIssueCode.invalid_arguments; + argumentsError: ZodError; +} +export interface ZodInvalidReturnTypeIssue extends ZodIssueBase { + code: typeof ZodIssueCode.invalid_return_type; + returnTypeError: ZodError; +} +export interface ZodInvalidDateIssue extends ZodIssueBase { + code: typeof ZodIssueCode.invalid_date; +} +export type StringValidation = "email" | "url" | "emoji" | "uuid" | "nanoid" | "regex" | "cuid" | "cuid2" | "ulid" | "datetime" | "date" | "time" | "duration" | "ip" | "cidr" | "base64" | "jwt" | "base64url" | { + includes: string; + position?: number | undefined; +} | { + startsWith: string; +} | { + endsWith: string; +}; +export interface ZodInvalidStringIssue extends ZodIssueBase { + code: typeof ZodIssueCode.invalid_string; + validation: StringValidation; +} +export interface ZodTooSmallIssue extends ZodIssueBase { + code: typeof ZodIssueCode.too_small; + minimum: number | bigint; + inclusive: boolean; + exact?: boolean; + type: "array" | "string" | "number" | "set" | "date" | "bigint"; +} +export interface ZodTooBigIssue extends ZodIssueBase { + code: typeof ZodIssueCode.too_big; + maximum: number | bigint; + inclusive: boolean; + exact?: boolean; + type: "array" | "string" | "number" | "set" | "date" | "bigint"; +} +export interface ZodInvalidIntersectionTypesIssue extends ZodIssueBase { + code: typeof ZodIssueCode.invalid_intersection_types; +} +export interface ZodNotMultipleOfIssue extends ZodIssueBase { + code: typeof ZodIssueCode.not_multiple_of; + multipleOf: number | bigint; +} +export interface ZodNotFiniteIssue extends ZodIssueBase { + code: typeof ZodIssueCode.not_finite; +} +export interface ZodCustomIssue extends ZodIssueBase { + code: typeof ZodIssueCode.custom; + params?: { + [k: string]: any; + }; +} +export type DenormalizedError = { + [k: string]: DenormalizedError | string[]; +}; +export type ZodIssueOptionalMessage = ZodInvalidTypeIssue | ZodInvalidLiteralIssue | ZodUnrecognizedKeysIssue | ZodInvalidUnionIssue | ZodInvalidUnionDiscriminatorIssue | ZodInvalidEnumValueIssue | ZodInvalidArgumentsIssue | ZodInvalidReturnTypeIssue | ZodInvalidDateIssue | ZodInvalidStringIssue | ZodTooSmallIssue | ZodTooBigIssue | ZodInvalidIntersectionTypesIssue | ZodNotMultipleOfIssue | ZodNotFiniteIssue | ZodCustomIssue; +export type ZodIssue = ZodIssueOptionalMessage & { + fatal?: boolean | undefined; + message: string; +}; +export declare const quotelessJson: (obj: any) => string; +type recursiveZodFormattedError = T extends [any, ...any[]] ? { + [K in keyof T]?: ZodFormattedError; +} : T extends any[] ? { + [k: number]: ZodFormattedError; +} : T extends object ? { + [K in keyof T]?: ZodFormattedError; +} : unknown; +export type ZodFormattedError = { + _errors: U[]; +} & recursiveZodFormattedError>; +export type inferFormattedError, U = string> = ZodFormattedError, U>; +export declare class ZodError extends Error { + issues: ZodIssue[]; + get errors(): ZodIssue[]; + constructor(issues: ZodIssue[]); + format(): ZodFormattedError; + format(mapper: (issue: ZodIssue) => U): ZodFormattedError; + static create: (issues: ZodIssue[]) => ZodError; + static assert(value: unknown): asserts value is ZodError; + toString(): string; + get message(): string; + get isEmpty(): boolean; + addIssue: (sub: ZodIssue) => void; + addIssues: (subs?: ZodIssue[]) => void; + flatten(): typeToFlattenedError; + flatten(mapper?: (issue: ZodIssue) => U): typeToFlattenedError; + get formErrors(): typeToFlattenedError; +} +type stripPath = T extends any ? util.OmitKeys : never; +export type IssueData = stripPath & { + path?: (string | number)[]; + fatal?: boolean | undefined; +}; +export type ErrorMapCtx = { + defaultError: string; + data: any; +}; +export type ZodErrorMap = (issue: ZodIssueOptionalMessage, _ctx: ErrorMapCtx) => { + message: string; +}; +export {}; diff --git a/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/errors.d.ts b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/errors.d.ts new file mode 100644 index 000000000..52eacf72e --- /dev/null +++ b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/errors.d.ts @@ -0,0 +1,5 @@ +import type { ZodErrorMap } from "./ZodError.js"; +import defaultErrorMap from "./locales/en.js"; +export { defaultErrorMap }; +export declare function setErrorMap(map: ZodErrorMap): void; +export declare function getErrorMap(): ZodErrorMap; diff --git a/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/external.d.ts b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/external.d.ts new file mode 100644 index 000000000..f0a4be4c7 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/external.d.ts @@ -0,0 +1,6 @@ +export * from "./errors.js"; +export * from "./helpers/parseUtil.js"; +export * from "./helpers/typeAliases.js"; +export * from "./helpers/util.js"; +export * from "./types.js"; +export * from "./ZodError.js"; diff --git a/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/helpers/enumUtil.d.ts b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/helpers/enumUtil.d.ts new file mode 100644 index 000000000..fad28a711 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/helpers/enumUtil.d.ts @@ -0,0 +1,8 @@ +export declare namespace enumUtil { + type UnionToIntersectionFn = (T extends unknown ? (k: () => T) => void : never) extends (k: infer Intersection) => void ? Intersection : never; + type GetUnionLast = UnionToIntersectionFn extends () => infer Last ? Last : never; + type UnionToTuple = [T] extends [never] ? Tuple : UnionToTuple>, [GetUnionLast, ...Tuple]>; + type CastToStringTuple = T extends [string, ...string[]] ? T : never; + export type UnionToTupleString = CastToStringTuple>; + export {}; +} diff --git a/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/helpers/errorUtil.d.ts b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/helpers/errorUtil.d.ts new file mode 100644 index 000000000..bc9b033ff --- /dev/null +++ b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/helpers/errorUtil.d.ts @@ -0,0 +1,9 @@ +export declare namespace errorUtil { + type ErrMessage = string | { + message?: string | undefined; + }; + const errToObj: (message?: ErrMessage) => { + message?: string | undefined; + }; + const toString: (message?: ErrMessage) => string | undefined; +} diff --git a/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/helpers/parseUtil.d.ts b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/helpers/parseUtil.d.ts new file mode 100644 index 000000000..e4dc1d7b3 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/helpers/parseUtil.d.ts @@ -0,0 +1,78 @@ +import type { IssueData, ZodErrorMap, ZodIssue } from "../ZodError.js"; +import type { ZodParsedType } from "./util.js"; +export declare const makeIssue: (params: { + data: any; + path: (string | number)[]; + errorMaps: ZodErrorMap[]; + issueData: IssueData; +}) => ZodIssue; +export type ParseParams = { + path: (string | number)[]; + errorMap: ZodErrorMap; + async: boolean; +}; +export type ParsePathComponent = string | number; +export type ParsePath = ParsePathComponent[]; +export declare const EMPTY_PATH: ParsePath; +export interface ParseContext { + readonly common: { + readonly issues: ZodIssue[]; + readonly contextualErrorMap?: ZodErrorMap | undefined; + readonly async: boolean; + }; + readonly path: ParsePath; + readonly schemaErrorMap?: ZodErrorMap | undefined; + readonly parent: ParseContext | null; + readonly data: any; + readonly parsedType: ZodParsedType; +} +export type ParseInput = { + data: any; + path: (string | number)[]; + parent: ParseContext; +}; +export declare function addIssueToContext(ctx: ParseContext, issueData: IssueData): void; +export type ObjectPair = { + key: SyncParseReturnType; + value: SyncParseReturnType; +}; +export declare class ParseStatus { + value: "aborted" | "dirty" | "valid"; + dirty(): void; + abort(): void; + static mergeArray(status: ParseStatus, results: SyncParseReturnType[]): SyncParseReturnType; + static mergeObjectAsync(status: ParseStatus, pairs: { + key: ParseReturnType; + value: ParseReturnType; + }[]): Promise>; + static mergeObjectSync(status: ParseStatus, pairs: { + key: SyncParseReturnType; + value: SyncParseReturnType; + alwaysSet?: boolean; + }[]): SyncParseReturnType; +} +export interface ParseResult { + status: "aborted" | "dirty" | "valid"; + data: any; +} +export type INVALID = { + status: "aborted"; +}; +export declare const INVALID: INVALID; +export type DIRTY = { + status: "dirty"; + value: T; +}; +export declare const DIRTY: (value: T) => DIRTY; +export type OK = { + status: "valid"; + value: T; +}; +export declare const OK: (value: T) => OK; +export type SyncParseReturnType = OK | DIRTY | INVALID; +export type AsyncParseReturnType = Promise>; +export type ParseReturnType = SyncParseReturnType | AsyncParseReturnType; +export declare const isAborted: (x: ParseReturnType) => x is INVALID; +export declare const isDirty: (x: ParseReturnType) => x is OK | DIRTY; +export declare const isValid: (x: ParseReturnType) => x is OK; +export declare const isAsync: (x: ParseReturnType) => x is AsyncParseReturnType; diff --git a/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/helpers/partialUtil.d.ts b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/helpers/partialUtil.d.ts new file mode 100644 index 000000000..d07657a25 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/helpers/partialUtil.d.ts @@ -0,0 +1,8 @@ +import type { ZodArray, ZodNullable, ZodObject, ZodOptional, ZodRawShape, ZodTuple, ZodTupleItems, ZodTypeAny } from "../types.js"; +export declare namespace partialUtil { + type DeepPartial = T extends ZodObject ? ZodObject<{ + [k in keyof T["shape"]]: ZodOptional>; + }, T["_def"]["unknownKeys"], T["_def"]["catchall"]> : T extends ZodArray ? ZodArray, Card> : T extends ZodOptional ? ZodOptional> : T extends ZodNullable ? ZodNullable> : T extends ZodTuple ? { + [k in keyof Items]: Items[k] extends ZodTypeAny ? DeepPartial : never; + } extends infer PI ? PI extends ZodTupleItems ? ZodTuple : never : never : T; +} diff --git a/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/helpers/typeAliases.d.ts b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/helpers/typeAliases.d.ts new file mode 100644 index 000000000..32df022ca --- /dev/null +++ b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/helpers/typeAliases.d.ts @@ -0,0 +1,2 @@ +export type Primitive = string | number | symbol | bigint | boolean | null | undefined; +export type Scalars = Primitive | Primitive[]; diff --git a/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/helpers/util.d.ts b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/helpers/util.d.ts new file mode 100644 index 000000000..eeaaeee1c --- /dev/null +++ b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/helpers/util.d.ts @@ -0,0 +1,85 @@ +export declare namespace util { + type AssertEqual = (() => V extends T ? 1 : 2) extends () => V extends U ? 1 : 2 ? true : false; + export type isAny = 0 extends 1 & T ? true : false; + export const assertEqual: (_: AssertEqual) => void; + export function assertIs(_arg: T): void; + export function assertNever(_x: never): never; + export type Omit = Pick>; + export type OmitKeys = Pick>; + export type MakePartial = Omit & Partial>; + export type Exactly = T & Record, never>; + export type InexactPartial = { + [k in keyof T]?: T[k] | undefined; + }; + export const arrayToEnum: (items: U) => { [k in U[number]]: k; }; + export const getValidEnumValues: (obj: any) => any[]; + export const objectValues: (obj: any) => any[]; + export const objectKeys: ObjectConstructor["keys"]; + export const find: (arr: T[], checker: (arg: T) => any) => T | undefined; + export type identity = objectUtil.identity; + export type flatten = objectUtil.flatten; + export type noUndefined = T extends undefined ? never : T; + export const isInteger: NumberConstructor["isInteger"]; + export function joinValues(array: T, separator?: string): string; + export const jsonStringifyReplacer: (_: string, value: any) => any; + export {}; +} +export declare namespace objectUtil { + export type MergeShapes = keyof U & keyof V extends never ? U & V : { + [k in Exclude]: U[k]; + } & V; + type optionalKeys = { + [k in keyof T]: undefined extends T[k] ? k : never; + }[keyof T]; + type requiredKeys = { + [k in keyof T]: undefined extends T[k] ? never : k; + }[keyof T]; + export type addQuestionMarks = { + [K in requiredKeys]: T[K]; + } & { + [K in optionalKeys]?: T[K]; + } & { + [k in keyof T]?: unknown; + }; + export type identity = T; + export type flatten = identity<{ + [k in keyof T]: T[k]; + }>; + export type noNeverKeys = { + [k in keyof T]: [T[k]] extends [never] ? never : k; + }[keyof T]; + export type noNever = identity<{ + [k in noNeverKeys]: k extends keyof T ? T[k] : never; + }>; + export const mergeShapes: (first: U, second: T) => T & U; + export type extendShape = keyof A & keyof B extends never ? A & B : { + [K in keyof A as K extends keyof B ? never : K]: A[K]; + } & { + [K in keyof B]: B[K]; + }; + export {}; +} +export declare const ZodParsedType: { + string: "string"; + nan: "nan"; + number: "number"; + integer: "integer"; + float: "float"; + boolean: "boolean"; + date: "date"; + bigint: "bigint"; + symbol: "symbol"; + function: "function"; + undefined: "undefined"; + null: "null"; + array: "array"; + object: "object"; + unknown: "unknown"; + promise: "promise"; + void: "void"; + never: "never"; + map: "map"; + set: "set"; +}; +export type ZodParsedType = keyof typeof ZodParsedType; +export declare const getParsedType: (data: any) => ZodParsedType; diff --git a/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/index.d.ts b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/index.d.ts new file mode 100644 index 000000000..a9dab5738 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/index.d.ts @@ -0,0 +1,4 @@ +import * as z from "./external.js"; +export * from "./external.js"; +export { z }; +export default z; diff --git a/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/locales/en.d.ts b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/locales/en.d.ts new file mode 100644 index 000000000..b2bea1ec4 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/locales/en.d.ts @@ -0,0 +1,3 @@ +import { type ZodErrorMap } from "../ZodError.js"; +declare const errorMap: ZodErrorMap; +export default errorMap; diff --git a/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/standard-schema.d.ts b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/standard-schema.d.ts new file mode 100644 index 000000000..7ddff3b7f --- /dev/null +++ b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/standard-schema.d.ts @@ -0,0 +1,102 @@ +/** + * The Standard Schema interface. + */ +export type StandardSchemaV1 = { + /** + * The Standard Schema properties. + */ + readonly "~standard": StandardSchemaV1.Props; +}; +export declare namespace StandardSchemaV1 { + /** + * The Standard Schema properties interface. + */ + export interface Props { + /** + * The version number of the standard. + */ + readonly version: 1; + /** + * The vendor name of the schema library. + */ + readonly vendor: string; + /** + * Validates unknown input values. + */ + readonly validate: (value: unknown) => Result | Promise>; + /** + * Inferred types associated with the schema. + */ + readonly types?: Types | undefined; + } + /** + * The result interface of the validate function. + */ + export type Result = SuccessResult | FailureResult; + /** + * The result interface if validation succeeds. + */ + export interface SuccessResult { + /** + * The typed output value. + */ + readonly value: Output; + /** + * The non-existent issues. + */ + readonly issues?: undefined; + } + /** + * The result interface if validation fails. + */ + export interface FailureResult { + /** + * The issues of failed validation. + */ + readonly issues: ReadonlyArray; + } + /** + * The issue interface of the failure output. + */ + export interface Issue { + /** + * The error message of the issue. + */ + readonly message: string; + /** + * The path of the issue, if any. + */ + readonly path?: ReadonlyArray | undefined; + } + /** + * The path segment interface of the issue. + */ + export interface PathSegment { + /** + * The key representing a path segment. + */ + readonly key: PropertyKey; + } + /** + * The Standard Schema types interface. + */ + export interface Types { + /** + * The input type of the schema. + */ + readonly input: Input; + /** + * The output type of the schema. + */ + readonly output: Output; + } + /** + * Infers the input type of a Standard Schema. + */ + export type InferInput = NonNullable["input"]; + /** + * Infers the output type of a Standard Schema. + */ + export type InferOutput = NonNullable["output"]; + export {}; +} diff --git a/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/types.d.ts b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/types.d.ts new file mode 100644 index 000000000..301e09128 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3/node_modules/zod/dist/types/v3/types.d.ts @@ -0,0 +1,1031 @@ +import { type IssueData, type StringValidation, type ZodCustomIssue, ZodError, type ZodErrorMap } from "./ZodError.js"; +import type { enumUtil } from "./helpers/enumUtil.js"; +import { errorUtil } from "./helpers/errorUtil.js"; +import { type AsyncParseReturnType, INVALID, type ParseContext, type ParseInput, type ParseParams, type ParseReturnType, ParseStatus, type SyncParseReturnType } from "./helpers/parseUtil.js"; +import type { partialUtil } from "./helpers/partialUtil.js"; +import type { Primitive } from "./helpers/typeAliases.js"; +import { util, type objectUtil } from "./helpers/util.js"; +import type { StandardSchemaV1 } from "./standard-schema.js"; +export interface RefinementCtx { + addIssue: (arg: IssueData) => void; + path: (string | number)[]; +} +export type ZodRawShape = { + [k: string]: ZodTypeAny; +}; +export type ZodTypeAny = ZodType; +export type TypeOf> = T["_output"]; +export type input> = T["_input"]; +export type output> = T["_output"]; +export type { TypeOf as infer }; +export type CustomErrorParams = Partial>; +export interface ZodTypeDef { + errorMap?: ZodErrorMap | undefined; + description?: string | undefined; +} +export type RawCreateParams = { + errorMap?: ZodErrorMap | undefined; + invalid_type_error?: string | undefined; + required_error?: string | undefined; + message?: string | undefined; + description?: string | undefined; +} | undefined; +export type ProcessedCreateParams = { + errorMap?: ZodErrorMap | undefined; + description?: string | undefined; +}; +export type SafeParseSuccess = { + success: true; + data: Output; + error?: never; +}; +export type SafeParseError = { + success: false; + error: ZodError; + data?: never; +}; +export type SafeParseReturnType = SafeParseSuccess | SafeParseError; +export declare abstract class ZodType { + readonly _type: Output; + readonly _output: Output; + readonly _input: Input; + readonly _def: Def; + get description(): string | undefined; + "~standard": StandardSchemaV1.Props; + abstract _parse(input: ParseInput): ParseReturnType; + _getType(input: ParseInput): string; + _getOrReturnCtx(input: ParseInput, ctx?: ParseContext | undefined): ParseContext; + _processInputParams(input: ParseInput): { + status: ParseStatus; + ctx: ParseContext; + }; + _parseSync(input: ParseInput): SyncParseReturnType; + _parseAsync(input: ParseInput): AsyncParseReturnType; + parse(data: unknown, params?: util.InexactPartial): Output; + safeParse(data: unknown, params?: util.InexactPartial): SafeParseReturnType; + "~validate"(data: unknown): StandardSchemaV1.Result | Promise>; + parseAsync(data: unknown, params?: util.InexactPartial): Promise; + safeParseAsync(data: unknown, params?: util.InexactPartial): Promise>; + /** Alias of safeParseAsync */ + spa: (data: unknown, params?: util.InexactPartial) => Promise>; + refine(check: (arg: Output) => arg is RefinedOutput, message?: string | CustomErrorParams | ((arg: Output) => CustomErrorParams)): ZodEffects; + refine(check: (arg: Output) => unknown | Promise, message?: string | CustomErrorParams | ((arg: Output) => CustomErrorParams)): ZodEffects; + refinement(check: (arg: Output) => arg is RefinedOutput, refinementData: IssueData | ((arg: Output, ctx: RefinementCtx) => IssueData)): ZodEffects; + refinement(check: (arg: Output) => boolean, refinementData: IssueData | ((arg: Output, ctx: RefinementCtx) => IssueData)): ZodEffects; + _refinement(refinement: RefinementEffect["refinement"]): ZodEffects; + superRefine(refinement: (arg: Output, ctx: RefinementCtx) => arg is RefinedOutput): ZodEffects; + superRefine(refinement: (arg: Output, ctx: RefinementCtx) => void): ZodEffects; + superRefine(refinement: (arg: Output, ctx: RefinementCtx) => Promise): ZodEffects; + constructor(def: Def); + optional(): ZodOptional; + nullable(): ZodNullable; + nullish(): ZodOptional>; + array(): ZodArray; + promise(): ZodPromise; + or(option: T): ZodUnion<[this, T]>; + and(incoming: T): ZodIntersection; + transform(transform: (arg: Output, ctx: RefinementCtx) => NewOut | Promise): ZodEffects; + default(def: util.noUndefined): ZodDefault; + default(def: () => util.noUndefined): ZodDefault; + brand(brand?: B): ZodBranded; + catch(def: Output): ZodCatch; + catch(def: (ctx: { + error: ZodError; + input: Input; + }) => Output): ZodCatch; + describe(description: string): this; + pipe(target: T): ZodPipeline; + readonly(): ZodReadonly; + isOptional(): boolean; + isNullable(): boolean; +} +export type IpVersion = "v4" | "v6"; +export type ZodStringCheck = { + kind: "min"; + value: number; + message?: string | undefined; +} | { + kind: "max"; + value: number; + message?: string | undefined; +} | { + kind: "length"; + value: number; + message?: string | undefined; +} | { + kind: "email"; + message?: string | undefined; +} | { + kind: "url"; + message?: string | undefined; +} | { + kind: "emoji"; + message?: string | undefined; +} | { + kind: "uuid"; + message?: string | undefined; +} | { + kind: "nanoid"; + message?: string | undefined; +} | { + kind: "cuid"; + message?: string | undefined; +} | { + kind: "includes"; + value: string; + position?: number | undefined; + message?: string | undefined; +} | { + kind: "cuid2"; + message?: string | undefined; +} | { + kind: "ulid"; + message?: string | undefined; +} | { + kind: "startsWith"; + value: string; + message?: string | undefined; +} | { + kind: "endsWith"; + value: string; + message?: string | undefined; +} | { + kind: "regex"; + regex: RegExp; + message?: string | undefined; +} | { + kind: "trim"; + message?: string | undefined; +} | { + kind: "toLowerCase"; + message?: string | undefined; +} | { + kind: "toUpperCase"; + message?: string | undefined; +} | { + kind: "jwt"; + alg?: string; + message?: string | undefined; +} | { + kind: "datetime"; + offset: boolean; + local: boolean; + precision: number | null; + message?: string | undefined; +} | { + kind: "date"; + message?: string | undefined; +} | { + kind: "time"; + precision: number | null; + message?: string | undefined; +} | { + kind: "duration"; + message?: string | undefined; +} | { + kind: "ip"; + version?: IpVersion | undefined; + message?: string | undefined; +} | { + kind: "cidr"; + version?: IpVersion | undefined; + message?: string | undefined; +} | { + kind: "base64"; + message?: string | undefined; +} | { + kind: "base64url"; + message?: string | undefined; +}; +export interface ZodStringDef extends ZodTypeDef { + checks: ZodStringCheck[]; + typeName: ZodFirstPartyTypeKind.ZodString; + coerce: boolean; +} +export declare function datetimeRegex(args: { + precision?: number | null; + offset?: boolean; + local?: boolean; +}): RegExp; +export declare class ZodString extends ZodType { + _parse(input: ParseInput): ParseReturnType; + protected _regex(regex: RegExp, validation: StringValidation, message?: errorUtil.ErrMessage): ZodEffects; + _addCheck(check: ZodStringCheck): ZodString; + email(message?: errorUtil.ErrMessage): ZodString; + url(message?: errorUtil.ErrMessage): ZodString; + emoji(message?: errorUtil.ErrMessage): ZodString; + uuid(message?: errorUtil.ErrMessage): ZodString; + nanoid(message?: errorUtil.ErrMessage): ZodString; + cuid(message?: errorUtil.ErrMessage): ZodString; + cuid2(message?: errorUtil.ErrMessage): ZodString; + ulid(message?: errorUtil.ErrMessage): ZodString; + base64(message?: errorUtil.ErrMessage): ZodString; + base64url(message?: errorUtil.ErrMessage): ZodString; + jwt(options?: { + alg?: string; + message?: string | undefined; + }): ZodString; + ip(options?: string | { + version?: IpVersion; + message?: string | undefined; + }): ZodString; + cidr(options?: string | { + version?: IpVersion; + message?: string | undefined; + }): ZodString; + datetime(options?: string | { + message?: string | undefined; + precision?: number | null; + offset?: boolean; + local?: boolean; + }): ZodString; + date(message?: string): ZodString; + time(options?: string | { + message?: string | undefined; + precision?: number | null; + }): ZodString; + duration(message?: errorUtil.ErrMessage): ZodString; + regex(regex: RegExp, message?: errorUtil.ErrMessage): ZodString; + includes(value: string, options?: { + message?: string; + position?: number; + }): ZodString; + startsWith(value: string, message?: errorUtil.ErrMessage): ZodString; + endsWith(value: string, message?: errorUtil.ErrMessage): ZodString; + min(minLength: number, message?: errorUtil.ErrMessage): ZodString; + max(maxLength: number, message?: errorUtil.ErrMessage): ZodString; + length(len: number, message?: errorUtil.ErrMessage): ZodString; + /** + * Equivalent to `.min(1)` + */ + nonempty(message?: errorUtil.ErrMessage): ZodString; + trim(): ZodString; + toLowerCase(): ZodString; + toUpperCase(): ZodString; + get isDatetime(): boolean; + get isDate(): boolean; + get isTime(): boolean; + get isDuration(): boolean; + get isEmail(): boolean; + get isURL(): boolean; + get isEmoji(): boolean; + get isUUID(): boolean; + get isNANOID(): boolean; + get isCUID(): boolean; + get isCUID2(): boolean; + get isULID(): boolean; + get isIP(): boolean; + get isCIDR(): boolean; + get isBase64(): boolean; + get isBase64url(): boolean; + get minLength(): number | null; + get maxLength(): number | null; + static create: (params?: RawCreateParams & { + coerce?: true; + }) => ZodString; +} +export type ZodNumberCheck = { + kind: "min"; + value: number; + inclusive: boolean; + message?: string | undefined; +} | { + kind: "max"; + value: number; + inclusive: boolean; + message?: string | undefined; +} | { + kind: "int"; + message?: string | undefined; +} | { + kind: "multipleOf"; + value: number; + message?: string | undefined; +} | { + kind: "finite"; + message?: string | undefined; +}; +export interface ZodNumberDef extends ZodTypeDef { + checks: ZodNumberCheck[]; + typeName: ZodFirstPartyTypeKind.ZodNumber; + coerce: boolean; +} +export declare class ZodNumber extends ZodType { + _parse(input: ParseInput): ParseReturnType; + static create: (params?: RawCreateParams & { + coerce?: boolean; + }) => ZodNumber; + gte(value: number, message?: errorUtil.ErrMessage): ZodNumber; + min: (value: number, message?: errorUtil.ErrMessage) => ZodNumber; + gt(value: number, message?: errorUtil.ErrMessage): ZodNumber; + lte(value: number, message?: errorUtil.ErrMessage): ZodNumber; + max: (value: number, message?: errorUtil.ErrMessage) => ZodNumber; + lt(value: number, message?: errorUtil.ErrMessage): ZodNumber; + protected setLimit(kind: "min" | "max", value: number, inclusive: boolean, message?: string): ZodNumber; + _addCheck(check: ZodNumberCheck): ZodNumber; + int(message?: errorUtil.ErrMessage): ZodNumber; + positive(message?: errorUtil.ErrMessage): ZodNumber; + negative(message?: errorUtil.ErrMessage): ZodNumber; + nonpositive(message?: errorUtil.ErrMessage): ZodNumber; + nonnegative(message?: errorUtil.ErrMessage): ZodNumber; + multipleOf(value: number, message?: errorUtil.ErrMessage): ZodNumber; + step: (value: number, message?: errorUtil.ErrMessage) => ZodNumber; + finite(message?: errorUtil.ErrMessage): ZodNumber; + safe(message?: errorUtil.ErrMessage): ZodNumber; + get minValue(): number | null; + get maxValue(): number | null; + get isInt(): boolean; + get isFinite(): boolean; +} +export type ZodBigIntCheck = { + kind: "min"; + value: bigint; + inclusive: boolean; + message?: string | undefined; +} | { + kind: "max"; + value: bigint; + inclusive: boolean; + message?: string | undefined; +} | { + kind: "multipleOf"; + value: bigint; + message?: string | undefined; +}; +export interface ZodBigIntDef extends ZodTypeDef { + checks: ZodBigIntCheck[]; + typeName: ZodFirstPartyTypeKind.ZodBigInt; + coerce: boolean; +} +export declare class ZodBigInt extends ZodType { + _parse(input: ParseInput): ParseReturnType; + _getInvalidInput(input: ParseInput): INVALID; + static create: (params?: RawCreateParams & { + coerce?: boolean; + }) => ZodBigInt; + gte(value: bigint, message?: errorUtil.ErrMessage): ZodBigInt; + min: (value: bigint, message?: errorUtil.ErrMessage) => ZodBigInt; + gt(value: bigint, message?: errorUtil.ErrMessage): ZodBigInt; + lte(value: bigint, message?: errorUtil.ErrMessage): ZodBigInt; + max: (value: bigint, message?: errorUtil.ErrMessage) => ZodBigInt; + lt(value: bigint, message?: errorUtil.ErrMessage): ZodBigInt; + protected setLimit(kind: "min" | "max", value: bigint, inclusive: boolean, message?: string): ZodBigInt; + _addCheck(check: ZodBigIntCheck): ZodBigInt; + positive(message?: errorUtil.ErrMessage): ZodBigInt; + negative(message?: errorUtil.ErrMessage): ZodBigInt; + nonpositive(message?: errorUtil.ErrMessage): ZodBigInt; + nonnegative(message?: errorUtil.ErrMessage): ZodBigInt; + multipleOf(value: bigint, message?: errorUtil.ErrMessage): ZodBigInt; + get minValue(): bigint | null; + get maxValue(): bigint | null; +} +export interface ZodBooleanDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodBoolean; + coerce: boolean; +} +export declare class ZodBoolean extends ZodType { + _parse(input: ParseInput): ParseReturnType; + static create: (params?: RawCreateParams & { + coerce?: boolean; + }) => ZodBoolean; +} +export type ZodDateCheck = { + kind: "min"; + value: number; + message?: string | undefined; +} | { + kind: "max"; + value: number; + message?: string | undefined; +}; +export interface ZodDateDef extends ZodTypeDef { + checks: ZodDateCheck[]; + coerce: boolean; + typeName: ZodFirstPartyTypeKind.ZodDate; +} +export declare class ZodDate extends ZodType { + _parse(input: ParseInput): ParseReturnType; + _addCheck(check: ZodDateCheck): ZodDate; + min(minDate: Date, message?: errorUtil.ErrMessage): ZodDate; + max(maxDate: Date, message?: errorUtil.ErrMessage): ZodDate; + get minDate(): Date | null; + get maxDate(): Date | null; + static create: (params?: RawCreateParams & { + coerce?: boolean; + }) => ZodDate; +} +export interface ZodSymbolDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodSymbol; +} +export declare class ZodSymbol extends ZodType { + _parse(input: ParseInput): ParseReturnType; + static create: (params?: RawCreateParams) => ZodSymbol; +} +export interface ZodUndefinedDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodUndefined; +} +export declare class ZodUndefined extends ZodType { + _parse(input: ParseInput): ParseReturnType; + params?: RawCreateParams; + static create: (params?: RawCreateParams) => ZodUndefined; +} +export interface ZodNullDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodNull; +} +export declare class ZodNull extends ZodType { + _parse(input: ParseInput): ParseReturnType; + static create: (params?: RawCreateParams) => ZodNull; +} +export interface ZodAnyDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodAny; +} +export declare class ZodAny extends ZodType { + _any: true; + _parse(input: ParseInput): ParseReturnType; + static create: (params?: RawCreateParams) => ZodAny; +} +export interface ZodUnknownDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodUnknown; +} +export declare class ZodUnknown extends ZodType { + _unknown: true; + _parse(input: ParseInput): ParseReturnType; + static create: (params?: RawCreateParams) => ZodUnknown; +} +export interface ZodNeverDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodNever; +} +export declare class ZodNever extends ZodType { + _parse(input: ParseInput): ParseReturnType; + static create: (params?: RawCreateParams) => ZodNever; +} +export interface ZodVoidDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodVoid; +} +export declare class ZodVoid extends ZodType { + _parse(input: ParseInput): ParseReturnType; + static create: (params?: RawCreateParams) => ZodVoid; +} +export interface ZodArrayDef extends ZodTypeDef { + type: T; + typeName: ZodFirstPartyTypeKind.ZodArray; + exactLength: { + value: number; + message?: string | undefined; + } | null; + minLength: { + value: number; + message?: string | undefined; + } | null; + maxLength: { + value: number; + message?: string | undefined; + } | null; +} +export type ArrayCardinality = "many" | "atleastone"; +export type arrayOutputType = Cardinality extends "atleastone" ? [T["_output"], ...T["_output"][]] : T["_output"][]; +export declare class ZodArray extends ZodType, ZodArrayDef, Cardinality extends "atleastone" ? [T["_input"], ...T["_input"][]] : T["_input"][]> { + _parse(input: ParseInput): ParseReturnType; + get element(): T; + min(minLength: number, message?: errorUtil.ErrMessage): this; + max(maxLength: number, message?: errorUtil.ErrMessage): this; + length(len: number, message?: errorUtil.ErrMessage): this; + nonempty(message?: errorUtil.ErrMessage): ZodArray; + static create: (schema: El, params?: RawCreateParams) => ZodArray; +} +export type ZodNonEmptyArray = ZodArray; +export type UnknownKeysParam = "passthrough" | "strict" | "strip"; +export interface ZodObjectDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodObject; + shape: () => T; + catchall: Catchall; + unknownKeys: UnknownKeys; +} +export type mergeTypes = { + [k in keyof A | keyof B]: k extends keyof B ? B[k] : k extends keyof A ? A[k] : never; +}; +export type objectOutputType = objectUtil.flatten>> & CatchallOutput & PassthroughType; +export type baseObjectOutputType = { + [k in keyof Shape]: Shape[k]["_output"]; +}; +export type objectInputType = objectUtil.flatten> & CatchallInput & PassthroughType; +export type baseObjectInputType = objectUtil.addQuestionMarks<{ + [k in keyof Shape]: Shape[k]["_input"]; +}>; +export type CatchallOutput = ZodType extends T ? unknown : { + [k: string]: T["_output"]; +}; +export type CatchallInput = ZodType extends T ? unknown : { + [k: string]: T["_input"]; +}; +export type PassthroughType = T extends "passthrough" ? { + [k: string]: unknown; +} : unknown; +export type deoptional = T extends ZodOptional ? deoptional : T extends ZodNullable ? ZodNullable> : T; +export type SomeZodObject = ZodObject; +export type noUnrecognized = { + [k in keyof Obj]: k extends keyof Shape ? Obj[k] : never; +}; +export declare class ZodObject, Input = objectInputType> extends ZodType, Input> { + private _cached; + _getCached(): { + shape: T; + keys: string[]; + }; + _parse(input: ParseInput): ParseReturnType; + get shape(): T; + strict(message?: errorUtil.ErrMessage): ZodObject; + strip(): ZodObject; + passthrough(): ZodObject; + /** + * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped. + * If you want to pass through unknown properties, use `.passthrough()` instead. + */ + nonstrict: () => ZodObject; + extend(augmentation: Augmentation): ZodObject, UnknownKeys, Catchall>; + /** + * @deprecated Use `.extend` instead + * */ + augment: (augmentation: Augmentation) => ZodObject, UnknownKeys, Catchall>; + /** + * Prior to zod@1.0.12 there was a bug in the + * inferred type of merged objects. Please + * upgrade if you are experiencing issues. + */ + merge(merging: Incoming): ZodObject, Incoming["_def"]["unknownKeys"], Incoming["_def"]["catchall"]>; + setKey(key: Key, schema: Schema): ZodObject; + catchall(index: Index): ZodObject; + pick>(mask: Mask): ZodObject>, UnknownKeys, Catchall>; + omit>(mask: Mask): ZodObject, UnknownKeys, Catchall>; + /** + * @deprecated + */ + deepPartial(): partialUtil.DeepPartial; + partial(): ZodObject<{ + [k in keyof T]: ZodOptional; + }, UnknownKeys, Catchall>; + partial>(mask: Mask): ZodObject : T[k]; + }>, UnknownKeys, Catchall>; + required(): ZodObject<{ + [k in keyof T]: deoptional; + }, UnknownKeys, Catchall>; + required>(mask: Mask): ZodObject : T[k]; + }>, UnknownKeys, Catchall>; + keyof(): ZodEnum>; + static create: (shape: Shape, params?: RawCreateParams) => ZodObject, objectInputType>; + static strictCreate: (shape: Shape, params?: RawCreateParams) => ZodObject; + static lazycreate: (shape: () => Shape, params?: RawCreateParams) => ZodObject; +} +export type AnyZodObject = ZodObject; +export type ZodUnionOptions = Readonly<[ZodTypeAny, ...ZodTypeAny[]]>; +export interface ZodUnionDef> extends ZodTypeDef { + options: T; + typeName: ZodFirstPartyTypeKind.ZodUnion; +} +export declare class ZodUnion extends ZodType, T[number]["_input"]> { + _parse(input: ParseInput): ParseReturnType; + get options(): T; + static create: >(types: Options, params?: RawCreateParams) => ZodUnion; +} +export type ZodDiscriminatedUnionOption = ZodObject<{ + [key in Discriminator]: ZodTypeAny; +} & ZodRawShape, UnknownKeysParam, ZodTypeAny>; +export interface ZodDiscriminatedUnionDef[] = ZodDiscriminatedUnionOption[]> extends ZodTypeDef { + discriminator: Discriminator; + options: Options; + optionsMap: Map>; + typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion; +} +export declare class ZodDiscriminatedUnion[]> extends ZodType, ZodDiscriminatedUnionDef, input> { + _parse(input: ParseInput): ParseReturnType; + get discriminator(): Discriminator; + get options(): Options; + get optionsMap(): Map>; + /** + * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. + * However, it only allows a union of objects, all of which need to share a discriminator property. This property must + * have a different value for each object in the union. + * @param discriminator the name of the discriminator property + * @param types an array of object schemas + * @param params + */ + static create, + ...ZodDiscriminatedUnionOption[] + ]>(discriminator: Discriminator, options: Types, params?: RawCreateParams): ZodDiscriminatedUnion; +} +export interface ZodIntersectionDef extends ZodTypeDef { + left: T; + right: U; + typeName: ZodFirstPartyTypeKind.ZodIntersection; +} +export declare class ZodIntersection extends ZodType, T["_input"] & U["_input"]> { + _parse(input: ParseInput): ParseReturnType; + static create: (left: TSchema, right: USchema, params?: RawCreateParams) => ZodIntersection; +} +export type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]]; +export type AssertArray = T extends any[] ? T : never; +export type OutputTypeOfTuple = AssertArray<{ + [k in keyof T]: T[k] extends ZodType ? T[k]["_output"] : never; +}>; +export type OutputTypeOfTupleWithRest = Rest extends ZodTypeAny ? [...OutputTypeOfTuple, ...Rest["_output"][]] : OutputTypeOfTuple; +export type InputTypeOfTuple = AssertArray<{ + [k in keyof T]: T[k] extends ZodType ? T[k]["_input"] : never; +}>; +export type InputTypeOfTupleWithRest = Rest extends ZodTypeAny ? [...InputTypeOfTuple, ...Rest["_input"][]] : InputTypeOfTuple; +export interface ZodTupleDef extends ZodTypeDef { + items: T; + rest: Rest; + typeName: ZodFirstPartyTypeKind.ZodTuple; +} +export type AnyZodTuple = ZodTuple<[ZodTypeAny, ...ZodTypeAny[]] | [], ZodTypeAny | null>; +export declare class ZodTuple extends ZodType, ZodTupleDef, InputTypeOfTupleWithRest> { + _parse(input: ParseInput): ParseReturnType; + get items(): T; + rest(rest: RestSchema): ZodTuple; + static create: (schemas: Items, params?: RawCreateParams) => ZodTuple; +} +export interface ZodRecordDef extends ZodTypeDef { + valueType: Value; + keyType: Key; + typeName: ZodFirstPartyTypeKind.ZodRecord; +} +export type KeySchema = ZodType; +export type RecordType = [string] extends [K] ? Record : [number] extends [K] ? Record : [symbol] extends [K] ? Record : [BRAND] extends [K] ? Record : Partial>; +export declare class ZodRecord extends ZodType, ZodRecordDef, RecordType> { + get keySchema(): Key; + get valueSchema(): Value; + _parse(input: ParseInput): ParseReturnType; + get element(): Value; + static create(valueType: Value, params?: RawCreateParams): ZodRecord; + static create(keySchema: Keys, valueType: Value, params?: RawCreateParams): ZodRecord; +} +export interface ZodMapDef extends ZodTypeDef { + valueType: Value; + keyType: Key; + typeName: ZodFirstPartyTypeKind.ZodMap; +} +export declare class ZodMap extends ZodType, ZodMapDef, Map> { + get keySchema(): Key; + get valueSchema(): Value; + _parse(input: ParseInput): ParseReturnType; + static create: (keyType: KeySchema, valueType: ValueSchema, params?: RawCreateParams) => ZodMap; +} +export interface ZodSetDef extends ZodTypeDef { + valueType: Value; + typeName: ZodFirstPartyTypeKind.ZodSet; + minSize: { + value: number; + message?: string | undefined; + } | null; + maxSize: { + value: number; + message?: string | undefined; + } | null; +} +export declare class ZodSet extends ZodType, ZodSetDef, Set> { + _parse(input: ParseInput): ParseReturnType; + min(minSize: number, message?: errorUtil.ErrMessage): this; + max(maxSize: number, message?: errorUtil.ErrMessage): this; + size(size: number, message?: errorUtil.ErrMessage): this; + nonempty(message?: errorUtil.ErrMessage): ZodSet; + static create: (valueType: ValueSchema, params?: RawCreateParams) => ZodSet; +} +export interface ZodFunctionDef = ZodTuple, Returns extends ZodTypeAny = ZodTypeAny> extends ZodTypeDef { + args: Args; + returns: Returns; + typeName: ZodFirstPartyTypeKind.ZodFunction; +} +export type OuterTypeOfFunction, Returns extends ZodTypeAny> = Args["_input"] extends Array ? (...args: Args["_input"]) => Returns["_output"] : never; +export type InnerTypeOfFunction, Returns extends ZodTypeAny> = Args["_output"] extends Array ? (...args: Args["_output"]) => Returns["_input"] : never; +export declare class ZodFunction, Returns extends ZodTypeAny> extends ZodType, ZodFunctionDef, InnerTypeOfFunction> { + _parse(input: ParseInput): ParseReturnType; + parameters(): Args; + returnType(): Returns; + args[0]>(...items: Items): ZodFunction, Returns>; + returns>(returnType: NewReturnType): ZodFunction; + implement>(func: F): ReturnType extends Returns["_output"] ? (...args: Args["_input"]) => ReturnType : OuterTypeOfFunction; + strictImplement(func: InnerTypeOfFunction): InnerTypeOfFunction; + validate: >(func: F) => ReturnType extends Returns["_output"] ? (...args: Args["_input"]) => ReturnType : OuterTypeOfFunction; + static create(): ZodFunction, ZodUnknown>; + static create>(args: T): ZodFunction; + static create(args: T, returns: U): ZodFunction; + static create, U extends ZodTypeAny = ZodUnknown>(args: T, returns: U, params?: RawCreateParams): ZodFunction; +} +export interface ZodLazyDef extends ZodTypeDef { + getter: () => T; + typeName: ZodFirstPartyTypeKind.ZodLazy; +} +export declare class ZodLazy extends ZodType, ZodLazyDef, input> { + get schema(): T; + _parse(input: ParseInput): ParseReturnType; + static create: (getter: () => Inner, params?: RawCreateParams) => ZodLazy; +} +export interface ZodLiteralDef extends ZodTypeDef { + value: T; + typeName: ZodFirstPartyTypeKind.ZodLiteral; +} +export declare class ZodLiteral extends ZodType, T> { + _parse(input: ParseInput): ParseReturnType; + get value(): T; + static create: (value: Value, params?: RawCreateParams) => ZodLiteral; +} +export type ArrayKeys = keyof any[]; +export type Indices = Exclude; +export type EnumValues = readonly [T, ...T[]]; +export type Values = { + [k in T[number]]: k; +}; +export interface ZodEnumDef extends ZodTypeDef { + values: T; + typeName: ZodFirstPartyTypeKind.ZodEnum; +} +export type Writeable = { + -readonly [P in keyof T]: T[P]; +}; +export type FilterEnum = Values extends [] ? [] : Values extends [infer Head, ...infer Rest] ? Head extends ToExclude ? FilterEnum : [Head, ...FilterEnum] : never; +export type typecast = A extends T ? A : never; +declare function createZodEnum>(values: T, params?: RawCreateParams): ZodEnum>; +declare function createZodEnum(values: T, params?: RawCreateParams): ZodEnum; +export declare class ZodEnum extends ZodType, T[number]> { + _cache: Set | undefined; + _parse(input: ParseInput): ParseReturnType; + get options(): T; + get enum(): Values; + get Values(): Values; + get Enum(): Values; + extract(values: ToExtract, newDef?: RawCreateParams): ZodEnum>; + exclude(values: ToExclude, newDef?: RawCreateParams): ZodEnum>, [string, ...string[]]>>; + static create: typeof createZodEnum; +} +export interface ZodNativeEnumDef extends ZodTypeDef { + values: T; + typeName: ZodFirstPartyTypeKind.ZodNativeEnum; +} +export type EnumLike = { + [k: string]: string | number; + [nu: number]: string; +}; +export declare class ZodNativeEnum extends ZodType, T[keyof T]> { + _cache: Set | undefined; + _parse(input: ParseInput): ParseReturnType; + get enum(): T; + static create: (values: Elements, params?: RawCreateParams) => ZodNativeEnum; +} +export interface ZodPromiseDef extends ZodTypeDef { + type: T; + typeName: ZodFirstPartyTypeKind.ZodPromise; +} +export declare class ZodPromise extends ZodType, ZodPromiseDef, Promise> { + unwrap(): T; + _parse(input: ParseInput): ParseReturnType; + static create: (schema: Inner, params?: RawCreateParams) => ZodPromise; +} +export type Refinement = (arg: T, ctx: RefinementCtx) => any; +export type SuperRefinement = (arg: T, ctx: RefinementCtx) => void | Promise; +export type RefinementEffect = { + type: "refinement"; + refinement: (arg: T, ctx: RefinementCtx) => any; +}; +export type TransformEffect = { + type: "transform"; + transform: (arg: T, ctx: RefinementCtx) => any; +}; +export type PreprocessEffect = { + type: "preprocess"; + transform: (arg: T, ctx: RefinementCtx) => any; +}; +export type Effect = RefinementEffect | TransformEffect | PreprocessEffect; +export interface ZodEffectsDef extends ZodTypeDef { + schema: T; + typeName: ZodFirstPartyTypeKind.ZodEffects; + effect: Effect; +} +export declare class ZodEffects, Input = input> extends ZodType, Input> { + innerType(): T; + sourceType(): T; + _parse(input: ParseInput): ParseReturnType; + static create: (schema: I, effect: Effect, params?: RawCreateParams) => ZodEffects; + static createWithPreprocess: (preprocess: (arg: unknown, ctx: RefinementCtx) => unknown, schema: I, params?: RawCreateParams) => ZodEffects; +} +export { ZodEffects as ZodTransformer }; +export interface ZodOptionalDef extends ZodTypeDef { + innerType: T; + typeName: ZodFirstPartyTypeKind.ZodOptional; +} +export type ZodOptionalType = ZodOptional; +export declare class ZodOptional extends ZodType, T["_input"] | undefined> { + _parse(input: ParseInput): ParseReturnType; + unwrap(): T; + static create: (type: Inner, params?: RawCreateParams) => ZodOptional; +} +export interface ZodNullableDef extends ZodTypeDef { + innerType: T; + typeName: ZodFirstPartyTypeKind.ZodNullable; +} +export type ZodNullableType = ZodNullable; +export declare class ZodNullable extends ZodType, T["_input"] | null> { + _parse(input: ParseInput): ParseReturnType; + unwrap(): T; + static create: (type: Inner, params?: RawCreateParams) => ZodNullable; +} +export interface ZodDefaultDef extends ZodTypeDef { + innerType: T; + defaultValue: () => util.noUndefined; + typeName: ZodFirstPartyTypeKind.ZodDefault; +} +export declare class ZodDefault extends ZodType, ZodDefaultDef, T["_input"] | undefined> { + _parse(input: ParseInput): ParseReturnType; + removeDefault(): T; + static create: (type: Inner, params: RawCreateParams & { + default: Inner["_input"] | (() => util.noUndefined); + }) => ZodDefault; +} +export interface ZodCatchDef extends ZodTypeDef { + innerType: T; + catchValue: (ctx: { + error: ZodError; + input: unknown; + }) => T["_input"]; + typeName: ZodFirstPartyTypeKind.ZodCatch; +} +export declare class ZodCatch extends ZodType, unknown> { + _parse(input: ParseInput): ParseReturnType; + removeCatch(): T; + static create: (type: Inner, params: RawCreateParams & { + catch: Inner["_output"] | (() => Inner["_output"]); + }) => ZodCatch; +} +export interface ZodNaNDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodNaN; +} +export declare class ZodNaN extends ZodType { + _parse(input: ParseInput): ParseReturnType; + static create: (params?: RawCreateParams) => ZodNaN; +} +export interface ZodBrandedDef extends ZodTypeDef { + type: T; + typeName: ZodFirstPartyTypeKind.ZodBranded; +} +export declare const BRAND: unique symbol; +export type BRAND = { + [BRAND]: { + [k in T]: true; + }; +}; +export declare class ZodBranded extends ZodType, ZodBrandedDef, T["_input"]> { + _parse(input: ParseInput): ParseReturnType; + unwrap(): T; +} +export interface ZodPipelineDef extends ZodTypeDef { + in: A; + out: B; + typeName: ZodFirstPartyTypeKind.ZodPipeline; +} +export declare class ZodPipeline extends ZodType, A["_input"]> { + _parse(input: ParseInput): ParseReturnType; + static create(a: ASchema, b: BSchema): ZodPipeline; +} +type BuiltIn = (((...args: any[]) => any) | (new (...args: any[]) => any)) | { + readonly [Symbol.toStringTag]: string; +} | Date | Error | Generator | Promise | RegExp; +type MakeReadonly = T extends Map ? ReadonlyMap : T extends Set ? ReadonlySet : T extends [infer Head, ...infer Tail] ? readonly [Head, ...Tail] : T extends Array ? ReadonlyArray : T extends BuiltIn ? T : Readonly; +export interface ZodReadonlyDef extends ZodTypeDef { + innerType: T; + typeName: ZodFirstPartyTypeKind.ZodReadonly; +} +export declare class ZodReadonly extends ZodType, ZodReadonlyDef, MakeReadonly> { + _parse(input: ParseInput): ParseReturnType; + static create: (type: Inner, params?: RawCreateParams) => ZodReadonly; + unwrap(): T; +} +type CustomParams = CustomErrorParams & { + fatal?: boolean; +}; +export declare function custom(check?: (data: any) => any, _params?: string | CustomParams | ((input: any) => CustomParams), +/** + * @deprecated + * + * Pass `fatal` into the params object instead: + * + * ```ts + * z.string().custom((val) => val.length > 5, { fatal: false }) + * ``` + * + */ +fatal?: boolean): ZodType; +export { ZodType as Schema, ZodType as ZodSchema }; +export declare const late: { + object: (shape: () => Shape, params?: RawCreateParams) => ZodObject; +}; +export declare enum ZodFirstPartyTypeKind { + ZodString = "ZodString", + ZodNumber = "ZodNumber", + ZodNaN = "ZodNaN", + ZodBigInt = "ZodBigInt", + ZodBoolean = "ZodBoolean", + ZodDate = "ZodDate", + ZodSymbol = "ZodSymbol", + ZodUndefined = "ZodUndefined", + ZodNull = "ZodNull", + ZodAny = "ZodAny", + ZodUnknown = "ZodUnknown", + ZodNever = "ZodNever", + ZodVoid = "ZodVoid", + ZodArray = "ZodArray", + ZodObject = "ZodObject", + ZodUnion = "ZodUnion", + ZodDiscriminatedUnion = "ZodDiscriminatedUnion", + ZodIntersection = "ZodIntersection", + ZodTuple = "ZodTuple", + ZodRecord = "ZodRecord", + ZodMap = "ZodMap", + ZodSet = "ZodSet", + ZodFunction = "ZodFunction", + ZodLazy = "ZodLazy", + ZodLiteral = "ZodLiteral", + ZodEnum = "ZodEnum", + ZodEffects = "ZodEffects", + ZodNativeEnum = "ZodNativeEnum", + ZodOptional = "ZodOptional", + ZodNullable = "ZodNullable", + ZodDefault = "ZodDefault", + ZodCatch = "ZodCatch", + ZodPromise = "ZodPromise", + ZodBranded = "ZodBranded", + ZodPipeline = "ZodPipeline", + ZodReadonly = "ZodReadonly" +} +export type ZodFirstPartySchemaTypes = ZodString | ZodNumber | ZodNaN | ZodBigInt | ZodBoolean | ZodDate | ZodUndefined | ZodNull | ZodAny | ZodUnknown | ZodNever | ZodVoid | ZodArray | ZodObject | ZodUnion | ZodDiscriminatedUnion | ZodIntersection | ZodTuple | ZodRecord | ZodMap | ZodSet | ZodFunction | ZodLazy | ZodLiteral | ZodEnum | ZodEffects | ZodNativeEnum | ZodOptional | ZodNullable | ZodDefault | ZodCatch | ZodPromise | ZodBranded | ZodPipeline | ZodReadonly | ZodSymbol; +declare abstract class Class { + constructor(..._: any[]); +} +declare const instanceOfType: (cls: T, params?: CustomParams) => ZodType, ZodTypeDef, InstanceType>; +declare const stringType: (params?: RawCreateParams & { + coerce?: true; +}) => ZodString; +declare const numberType: (params?: RawCreateParams & { + coerce?: boolean; +}) => ZodNumber; +declare const nanType: (params?: RawCreateParams) => ZodNaN; +declare const bigIntType: (params?: RawCreateParams & { + coerce?: boolean; +}) => ZodBigInt; +declare const booleanType: (params?: RawCreateParams & { + coerce?: boolean; +}) => ZodBoolean; +declare const dateType: (params?: RawCreateParams & { + coerce?: boolean; +}) => ZodDate; +declare const symbolType: (params?: RawCreateParams) => ZodSymbol; +declare const undefinedType: (params?: RawCreateParams) => ZodUndefined; +declare const nullType: (params?: RawCreateParams) => ZodNull; +declare const anyType: (params?: RawCreateParams) => ZodAny; +declare const unknownType: (params?: RawCreateParams) => ZodUnknown; +declare const neverType: (params?: RawCreateParams) => ZodNever; +declare const voidType: (params?: RawCreateParams) => ZodVoid; +declare const arrayType: (schema: El, params?: RawCreateParams) => ZodArray; +declare const objectType: (shape: Shape, params?: RawCreateParams) => ZodObject, objectInputType>; +declare const strictObjectType: (shape: Shape, params?: RawCreateParams) => ZodObject; +declare const unionType: >(types: Options, params?: RawCreateParams) => ZodUnion; +declare const discriminatedUnionType: typeof ZodDiscriminatedUnion.create; +declare const intersectionType: (left: TSchema, right: USchema, params?: RawCreateParams) => ZodIntersection; +declare const tupleType: (schemas: Items, params?: RawCreateParams) => ZodTuple; +declare const recordType: typeof ZodRecord.create; +declare const mapType: (keyType: KeySchema, valueType: ValueSchema, params?: RawCreateParams) => ZodMap; +declare const setType: (valueType: ValueSchema, params?: RawCreateParams) => ZodSet; +declare const functionType: typeof ZodFunction.create; +declare const lazyType: (getter: () => Inner, params?: RawCreateParams) => ZodLazy; +declare const literalType: (value: Value, params?: RawCreateParams) => ZodLiteral; +declare const enumType: typeof createZodEnum; +declare const nativeEnumType: (values: Elements, params?: RawCreateParams) => ZodNativeEnum; +declare const promiseType: (schema: Inner, params?: RawCreateParams) => ZodPromise; +declare const effectsType: (schema: I, effect: Effect, params?: RawCreateParams) => ZodEffects; +declare const optionalType: (type: Inner, params?: RawCreateParams) => ZodOptional; +declare const nullableType: (type: Inner, params?: RawCreateParams) => ZodNullable; +declare const preprocessType: (preprocess: (arg: unknown, ctx: RefinementCtx) => unknown, schema: I, params?: RawCreateParams) => ZodEffects; +declare const pipelineType: typeof ZodPipeline.create; +declare const ostring: () => ZodOptional; +declare const onumber: () => ZodOptional; +declare const oboolean: () => ZodOptional; +export declare const coerce: { + string: (typeof ZodString)["create"]; + number: (typeof ZodNumber)["create"]; + boolean: (typeof ZodBoolean)["create"]; + bigint: (typeof ZodBigInt)["create"]; + date: (typeof ZodDate)["create"]; +}; +export { anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, dateType as date, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, instanceOfType as instanceof, intersectionType as intersection, lazyType as lazy, literalType as literal, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, recordType as record, setType as set, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, voidType as void, }; +export declare const NEVER: never; diff --git a/tests/fixtures/npm/cases/zod3/node_modules/zod/package.json b/tests/fixtures/npm/cases/zod3/node_modules/zod/package.json new file mode 100644 index 000000000..e02b87614 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3/node_modules/zod/package.json @@ -0,0 +1,120 @@ +{ + "name": "zod", + "version": "3.25.67", + "type": "module", + "author": "Colin McDonnell ", + "description": "TypeScript-first schema declaration and validation library with static type inference", + "files": ["dist", "v3", "v4", "v4-mini"], + "funding": "https://github.com/sponsors/colinhacks", + "homepage": "https://zod.dev", + "keywords": ["typescript", "schema", "validation", "type", "inference"], + "license": "MIT", + "sideEffects": false, + "main": "./dist/cjs/index.js", + "types": "./dist/types/index.d.ts", + "module": "./dist/esm/index.js", + "exports": { + ".": { + "import": { + "@zod/source": "./src/index.ts", + "types": "./dist/types/index.d.ts", + "default": "./dist/esm/index.js" + }, + "require": { + "@zod/source": "./src/index.ts", + "types": "./dist/types/index.d.ts", + "default": "./dist/cjs/index.js" + } + }, + "./v3": { + "import": { + "@zod/source": "./src/index.ts", + "types": "./dist/types/index.d.ts", + "default": "./dist/esm/index.js" + }, + "require": { + "@zod/source": "./src/index.ts", + "types": "./dist/types/index.d.ts", + "default": "./dist/cjs/index.js" + } + }, + "./v4": { + "import": { + "@zod/source": "./src/v4/index.ts", + "types": "./dist/types/v4/index.d.ts", + "default": "./dist/esm/v4/index.js" + }, + "require": { + "@zod/source": "./src/v4/index.ts", + "types": "./dist/types/v4/index.d.ts", + "default": "./dist/cjs/v4/index.js" + } + }, + "./v4-mini": { + "@zod/source": "./src/v4/mini/index.ts", + "types": "./dist/types/v4/mini/index.d.ts", + "import": "./dist/esm/v4/mini/index.js", + "require": "./dist/cjs/v4/mini/index.js" + }, + "./v4/mini": { + "@zod/source": "./src/v4/mini/index.ts", + "types": "./dist/types/v4/mini/index.d.ts", + "import": "./dist/esm/v4/mini/index.js", + "require": "./dist/cjs/v4/mini/index.js" + }, + "./v4/core": { + "@zod/source": "./src/v4/core/index.ts", + "types": "./dist/types/v4/core/index.d.ts", + "import": "./dist/esm/v4/core/index.js", + "require": "./dist/cjs/v4/core/index.js" + }, + "./v4/locales": { + "@zod/source": "./src/v4/locales/index.ts", + "types": "./dist/types/v4/locales/index.d.ts", + "import": "./dist/esm/v4/locales/index.js", + "require": "./dist/cjs/v4/locales/index.js" + }, + "./v4/locales/*": { + "@zod/source": "./src/v4/locales/*", + "types": "./dist/types/v4/locales/*", + "import": "./dist/esm/v4/locales/*", + "require": "./dist/cjs/v4/locales/*" + }, + "./package.json": "./package.json" + }, + "tshy": { + "exports": { + "./package.json": "./package.json", + ".": "./src/index.ts", + "./v3": "./src/v3/index.ts", + "./v4": "./src/v4/index.ts", + "./v4-mini": "./src/v4/mini/index.ts", + "./v4/core": "./src/v4/core/index.ts", + "./v4/locales": "./src/v4/locales/index.ts", + "./v4/locales/*": "./src/v4/locales/*" + }, + "sourceDialects": ["@zod/source"], + "exclude": ["./src/**/*.test.ts"] + }, + "repository": { + "type": "git", + "url": "git+https://github.com/colinhacks/zod.git" + }, + "bugs": { + "url": "https://github.com/colinhacks/zod/issues" + }, + "support": { + "backing": { + "npm-funding": true + } + }, + "scripts": { + "clean": "rm -rf dist", + "build": "tsx ./build.mts", + "postbuild": "pnpm biome check --write .", + "test:watch": "pnpm vitest", + "test": "pnpm vitest run", + "bump:beta": "pnpm version \"v$(pnpm pkg get version | jq -r)-beta.$(date +%Y%m%dT%H%M%S)\"", + "pub:beta": "pnpm bump:beta && pnpm publish --tag next --publish-branch v4 --no-git-checks --dry-run" + } +} diff --git a/tests/fixtures/npm/cases/zod3/package.json b/tests/fixtures/npm/cases/zod3/package.json new file mode 100644 index 000000000..cda6a6168 --- /dev/null +++ b/tests/fixtures/npm/cases/zod3/package.json @@ -0,0 +1 @@ +{ "name": "zod3-case", "private": true, "type": "module" } diff --git a/tests/fixtures/split-tools/symlink/outside/linked.ts b/tests/fixtures/split-tools/symlink/outside/linked.ts new file mode 100644 index 000000000..7e551bf2e --- /dev/null +++ b/tests/fixtures/split-tools/symlink/outside/linked.ts @@ -0,0 +1,2 @@ +// A file outside the checkout that the split tools must not read or write. +export const outside = 1; diff --git a/tests/fixtures/split-tools/symlink/repo/src/host.ts b/tests/fixtures/split-tools/symlink/repo/src/host.ts new file mode 100644 index 000000000..4bf39c941 --- /dev/null +++ b/tests/fixtures/split-tools/symlink/repo/src/host.ts @@ -0,0 +1,6 @@ +export class Host { + count = 0; + moved(): number { + return this.count + 1; + } +} diff --git a/tests/fixtures/split-tools/symlink/repo/src/linked.ts b/tests/fixtures/split-tools/symlink/repo/src/linked.ts new file mode 120000 index 000000000..3a9e39fbe --- /dev/null +++ b/tests/fixtures/split-tools/symlink/repo/src/linked.ts @@ -0,0 +1 @@ +../../outside/linked.ts \ No newline at end of file diff --git a/tests/harness/__snapshots__/arguments-length-self-call.ts.txt b/tests/harness/__snapshots__/arguments-length-self-call.ts.txt new file mode 100644 index 000000000..7e94b56c6 --- /dev/null +++ b/tests/harness/__snapshots__/arguments-length-self-call.ts.txt @@ -0,0 +1,6 @@ +arguments-length-self-call.ts:6:32 - error SC1090: 'arguments.length' in a function expression that is called both through its own name and through a function type with more parameters (the count varies per call) are not supported yet + + 5 | const count: (a: number, b: number) => number = function self(a: number): number { + 6 | return a > 0 ? self(a - 1) + arguments.length : arguments.length; + | ^~~~~~~~~~~~~~~~ + 7 | }; \ No newline at end of file diff --git a/tests/harness/__snapshots__/child-process.ts.txt b/tests/harness/__snapshots__/child-process.ts.txt index f5f9f8f86..a1f2999b7 100644 --- a/tests/harness/__snapshots__/child-process.ts.txt +++ b/tests/harness/__snapshots__/child-process.ts.txt @@ -14,7 +14,7 @@ child-process.ts:27:14 - error SC1090: listeners returning a value (make the cal | ^~~~~~~~~~~~~~~ 28 | // Methods have no bound-value form — call on directly. -child-process.ts:29:7 - error SC2007: values of type '{ (event: "spawn", listener: () => void): void; (event: "exit", listener: (code: number | null, signal: string | null) => void): void; (event: "close", listener: (code: number | null, signal: string | null) => void): void; (event: "error", listener: (err: Error) => void): void; (event: "message", listener: (message:...' cannot be compiled: the type declares multiple call signatures (overloads), and a compiled function value is always one concrete signature +child-process.ts:29:7 - error SC2007: values of type '{ (event: "spawn", listener: () => void): ChildProcess; (event: "exit", listener: (code: number | null, signal: string | null) => void): ChildProcess; (event: "close", listener: (code: number | null, signal: string | null) => void): ChildProcess; (event: "error", listener: (err: Error) => void): ChildProcess; (event...' cannot be compiled: the type declares multiple call signatures (overloads), and a compiled function value is always one concrete signature 28 | // Methods have no bound-value form — call on directly. 29 | const f = c.on; diff --git a/tests/harness/__snapshots__/class-call-shadowed-static.ts.txt b/tests/harness/__snapshots__/class-call-shadowed-static.ts.txt new file mode 100644 index 000000000..e04c8423a --- /dev/null +++ b/tests/harness/__snapshots__/class-call-shadowed-static.ts.txt @@ -0,0 +1,8 @@ +class-call-shadowed-static.ts:13:10 - error SC2020: 'typeof Base.call' is part of the standard library types but has no scriptc lowering yet + + 12 | function callThrough(C: typeof Base): unknown { + 13 | return C.call(new Base()); + | ^~~~~~ + 14 | } + + hint: the type checker sees the full standard library, but only the supported surface compiles (https://scriptc.dev/limitations) \ No newline at end of file diff --git a/tests/harness/__snapshots__/coverage-js-builtin-callable-alias.txt b/tests/harness/__snapshots__/coverage-js-builtin-callable-alias.txt index 53eac6c3c..6291c291f 100644 --- a/tests/harness/__snapshots__/coverage-js-builtin-callable-alias.txt +++ b/tests/harness/__snapshots__/coverage-js-builtin-callable-alias.txt @@ -3,7 +3,7 @@ scriptc coverage tests/coverage-fixtures/js-builtin-callable-alias.js statements analyzed 3 compile statically 2 (66%) - deferred to runtime 1 site (JS statements that throw their fence if executed) + runs at startup 1 site (JS statements in module top-level code, which runs when the module loads) ×1 SC1090 a builtin function alias as an escaping value (call 'ext' directly) at tests/coverage-fixtures/js-builtin-callable-alias.js:8:13 hint: this form is valid TypeScript but does not compile yet — rewrite it with a supported equivalent of the construct the message names (https://scriptc.dev/limitations lists the boundary) diff --git a/tests/harness/__snapshots__/destructuring-fences.ts.txt b/tests/harness/__snapshots__/destructuring-fences.ts.txt index 743bb5657..41026a7c8 100644 --- a/tests/harness/__snapshots__/destructuring-fences.ts.txt +++ b/tests/harness/__snapshots__/destructuring-fences.ts.txt @@ -19,18 +19,18 @@ destructuring-fences.ts:31:9 - error SC1090: reading a property that has only a | ^~~~~~ 32 | console.log(onlyIn); -destructuring-fences.ts:45:9 - error SC1031: object destructuring of non-record values (the source is union-typed) are not supported yet +destructuring-fences.ts:45:11 - error SC1031: destructuring 'b' from a union whose arms type it differently (every arm must be a record or class with a same-typed field 'b' — narrow first: check a discriminant field, or compare with '!== undefined'/'!== null' for unit arms) is not supported yet 44 | function fromUnion(u: E1 | E2): string { - 45 | const { b } = u; // union source: narrow first - | ^~~~~ - 46 | return b; + 45 | const { b } = u; // union source whose arms type the field differently: narrow first + | ^ + 46 | return String(b); -destructuring-fences.ts:46:10 - error SC2004: uses of 'b' inherit the blocker on its declaration +destructuring-fences.ts:46:17 - error SC2004: uses of 'b' inherit the blocker on its declaration - 45 | const { b } = u; // union source: narrow first - 46 | return b; - | ^ + 45 | const { b } = u; // union source whose arms type the field differently: narrow first + 46 | return String(b); + | ^ 47 | } hint: the declaration of 'b' did not compile — fix the diagnostic reported there and these sites clear with it diff --git a/tests/harness/__snapshots__/filter-narrow.ts.txt b/tests/harness/__snapshots__/filter-narrow.ts.txt deleted file mode 100644 index bc5180219..000000000 --- a/tests/harness/__snapshots__/filter-narrow.ts.txt +++ /dev/null @@ -1,20 +0,0 @@ -filter-narrow.ts:9:17 - error SC1090: '.filter' narrowing 'number | string | undefined' elements to the multi-arm 'number | string' (only a SINGLE arm re-tags — keep the receiver's element type instead — annotate the callback's return ': boolean' (the checker then skips the predicate) or annotate the result with the receiver's own element type — and narrow the elements after) is not supported yet - - 8 | // Multi-arm narrowing: string | number is not a single arm. - 9 | const defined = xs.filter((x) => x !== undefined); - | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - 10 | console.log(defined.length); - -filter-narrow.ts:14:27 - error SC1090: narrowing '.filter' with a hand-written type predicate (a written 'x is T' is an unchecked assertion nothing validates at runtime — keep the receiver's element type instead — annotate the callback's return ': boolean' (the checker then skips the predicate) or annotate the result with the receiver's own element type — and narrow the elements after) is not supported yet - - 13 | const ys: (string | undefined)[] = ["a", undefined]; - 14 | const strings = ys.filter((x): x is string => typeof x === "string"); - | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - 15 | console.log(strings.length); - -filter-narrow.ts:21:28 - error SC1090: narrowing '.filter' through a callback VALUE (only an inline callback whose predicate the checker inferred can re-tag — keep the receiver's element type instead — annotate the callback's return ': boolean' (the checker then skips the predicate) or annotate the result with the receiver's own element type — and narrow the elements after) is not supported yet - - 20 | } - 21 | const viaValue = ys.filter(isString); - | ^~~~~~~~ - 22 | console.log(viaValue.length); \ No newline at end of file diff --git a/tests/harness/__snapshots__/fromentries-aliased-entries.ts.txt b/tests/harness/__snapshots__/fromentries-aliased-entries.ts.txt deleted file mode 100644 index 7b0f02266..000000000 --- a/tests/harness/__snapshots__/fromentries-aliased-entries.ts.txt +++ /dev/null @@ -1,8 +0,0 @@ -fromentries-aliased-entries.ts:8:16 - error SC2002: record shapes must match exactly or width-coerce: expected '{ a: number[]; b: number[] }', got '{ [key: string]: number[] }' — 'a' is not a declared field of the source, and the source's index signature could hold it at runtime (a completed undefined would drop that value) - - 7 | const shared = [10]; - 8 | const scores = Object.fromEntries([ - | ^~~~~~~~~~~~~~~~~~~~ - 9 | ["a", shared], - - hint: width subtyping compiles as a copy (each expected field copied off the source; extra fields drop) — this pair is outside the copy's rules; build a literal with exactly the expected fields instead \ No newline at end of file diff --git a/tests/harness/__snapshots__/generic-value-bindings.ts.txt b/tests/harness/__snapshots__/generic-value-bindings.ts.txt index 04fa9d069..835b84fa7 100644 --- a/tests/harness/__snapshots__/generic-value-bindings.ts.txt +++ b/tests/harness/__snapshots__/generic-value-bindings.ts.txt @@ -92,4 +92,11 @@ generic-value-bindings.ts:60:15 - error SC1090: calls of the generic method 'm' 59 | function throughParam(a: Amb): void { 60 | console.log(a.m(4)); | ^~~~~~ - 61 | } \ No newline at end of file + 61 | } + +generic-value-bindings.ts:71:32 - error SC1090: generic arrow/function-expression bindings declared inside functions that code can call before their declaration runs (the binding 'picked' is a 'var' in a branch or block, or is called from a place that can run first — declare it with const before its uses) are not supported yet + + 70 | } + 71 | const invoke = (): number => picked(1); + | ^~~~~~ + 72 | return invoke(); \ No newline at end of file diff --git a/tests/harness/__snapshots__/iterable-sources.ts.txt b/tests/harness/__snapshots__/iterable-sources.ts.txt new file mode 100644 index 000000000..cac17a49e --- /dev/null +++ b/tests/harness/__snapshots__/iterable-sources.ts.txt @@ -0,0 +1,13 @@ +iterable-sources.ts:15:17 - error SC1090: an Iterable holding a 'Countdown' (an Iterable value holds an array, Set, Map, string, or iterator) is not supported yet + + 14 | } + 15 | console.log(sum(new Countdown())); + | ^~~~~~~~~~~~~~~ + 16 | console.log(sum(new Uint8Array([1, 2]))); + +iterable-sources.ts:16:17 - error SC1090: an Iterable holding a 'Uint8Array' (an Iterable value holds an array, Set, Map, string, or iterator) is not supported yet + + 15 | console.log(sum(new Countdown())); + 16 | console.log(sum(new Uint8Array([1, 2]))); + | ^~~~~~~~~~~~~~~~~~~~~~ + 17 | export const marker: number = 1; \ No newline at end of file diff --git a/tests/harness/__snapshots__/iterator-slot-fences.ts.txt b/tests/harness/__snapshots__/iterator-slot-fences.ts.txt index fd244e8fd..a29b4b186 100644 --- a/tests/harness/__snapshots__/iterator-slot-fences.ts.txt +++ b/tests/harness/__snapshots__/iterator-slot-fences.ts.txt @@ -3,22 +3,4 @@ iterator-slot-fences.ts:14:9 - error SC1090: 'Countdown' values in an iterator-t 13 | } 14 | firstOf(new Countdown()); | ^~~~~~~~~~~~~~~ - 15 | - -iterator-slot-fences.ts:16:16 - error SC2020: 'Iterable' is part of the standard library types but has no scriptc lowering yet - - 15 | - 16 | function total(values: Iterable): number { - | ^~~~~~ - 17 | let sum = 0; - - hint: the type checker sees the full standard library, but only the supported surface compiles (https://scriptc.dev/limitations) - -iterator-slot-fences.ts:21:13 - error SC2004: uses of 'total' inherit the blocker on its declaration - - 20 | } - 21 | console.log(total([1, 2])); - | ^~~~~ - 22 | - - hint: the declaration of 'total' did not compile — fix the diagnostic reported there and these sites clear with it \ No newline at end of file + 15 | \ No newline at end of file diff --git a/tests/harness/__snapshots__/jsx-factory-mismatch/main.ts.txt b/tests/harness/__snapshots__/jsx-factory-mismatch/main.ts.txt new file mode 100644 index 000000000..e0a19b654 --- /dev/null +++ b/tests/harness/__snapshots__/jsx-factory-mismatch/main.ts.txt @@ -0,0 +1,6 @@ +jsx-factory-mismatch/view.tsx:13:45 - error SC0001: Argument of type 'number' is not assignable to parameter of type 'string'. (in the call this JSX lowers to) + + 12 | const count = 3; + 13 | export const view = h("p", null, "count: ", count); + | ^~~~~ + 14 | \ No newline at end of file diff --git a/tests/harness/__snapshots__/jsx-preserve/main.ts.txt b/tests/harness/__snapshots__/jsx-preserve/main.ts.txt new file mode 100644 index 000000000..9e0239088 --- /dev/null +++ b/tests/harness/__snapshots__/jsx-preserve/main.ts.txt @@ -0,0 +1,8 @@ +jsx-preserve/view.tsx:9:21 - error SC1090: JSX with "jsx": "preserve" is not supported: that setting keeps JSX in the output instead of lowering it to calls + + 8 | } + 9 | export const view =

    kept as JSX

    ; + | ^~~~~~~~~~~~~~~~~~ + 10 | + + hint: set "jsx" to "react", "react-jsx" or "react-jsxdev" in the project tsconfig \ No newline at end of file diff --git a/tests/harness/__snapshots__/jsx-type-errors/main.ts.txt b/tests/harness/__snapshots__/jsx-type-errors/main.ts.txt new file mode 100644 index 000000000..c87c719a8 --- /dev/null +++ b/tests/harness/__snapshots__/jsx-type-errors/main.ts.txt @@ -0,0 +1,13 @@ +jsx-type-errors/view.tsx:15:30 - error SC0001: Type 'number' is not assignable to type 'string'. + + 14 | } + 15 | export const view = h("p", { title: 1 }, "text ", h(Count, { count: "two" })); + | ^~~~~~~ + 16 | + +jsx-type-errors/view.tsx:15:62 - error SC0001: Type 'string' is not assignable to type 'number'. + + 14 | } + 15 | export const view = h("p", { title: 1 }, "text ", h(Count, { count: "two" })); + | ^~~~~~~ + 16 | \ No newline at end of file diff --git a/tests/harness/__snapshots__/local-class-boundaries.ts.txt b/tests/harness/__snapshots__/local-class-boundaries.ts.txt index 6706a1278..697b1b8ed 100644 --- a/tests/harness/__snapshots__/local-class-boundaries.ts.txt +++ b/tests/harness/__snapshots__/local-class-boundaries.ts.txt @@ -2,18 +2,11 @@ local-class-boundaries.ts:1:34 - error SC1090: function-local classes with priva 1 | function privateBrand() { return class { #value = 1; has(other: object): boolean { return #value in other; } }; } | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - 2 | function selfName() { return class Local { copy() { return new Local(); } }; } + 2 | class Base {} -local-class-boundaries.ts:2:64 - error SC1090: named self references inside function-local classes are not supported yet +local-class-boundaries.ts:4:29 - error SC1090: function-local classes with statics, decorators, or generic members are not supported yet - 1 | function privateBrand() { return class { #value = 1; has(other: object): boolean { return #value in other; } }; } - 2 | function selfName() { return class Local { copy() { return new Local(); } }; } - | ^~~~~ - 3 | class Base {} - -local-class-boundaries.ts:5:29 - error SC1090: function-local classes with statics, decorators, or generic members are not supported yet - - 4 | function derived() { return class extends Base {}; } - 5 | function generic() { return class { read(value: T): T { return value; } }; } + 3 | function derived() { return class extends Base {}; } + 4 | function generic() { return class { read(value: T): T { return value; } }; } | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - 6 | privateBrand(); \ No newline at end of file + 5 | privateBrand(); \ No newline at end of file diff --git a/tests/harness/__snapshots__/node-types-fenced.txt b/tests/harness/__snapshots__/node-types-fenced.txt index 0bd13963d..cabce49c4 100644 --- a/tests/harness/__snapshots__/node-types-fenced.txt +++ b/tests/harness/__snapshots__/node-types-fenced.txt @@ -115,36 +115,36 @@ fenced.ts:69:71 - error SC2020: 'createSecureServer option 'streamResetBurst' wi hint: h2 session-tuning options are accepted with literal values but are not applied yet -fenced.ts:76:1 - error SC2020: 'crypto.generateKeyPair' is typed by @types/node but has no scriptc lowering yet +fenced.ts:76:1 - error SC2020: 'crypto.publicEncrypt' is typed by @types/node but has no scriptc lowering yet - 75 | import { checkPrimeSync, createCipheriv, generateKeyPair, setFips } from "node:crypto"; - 76 | generateKeyPair("rsa", { modulusLength: 2048 }, () => {}); - | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + 75 | import { createCipheriv, publicEncrypt, secureHeapUsed, setFips } from "node:crypto"; + 76 | publicEncrypt("key", Buffer.alloc(1)); + | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 77 | createCipheriv("aes-128-ccm", Buffer.alloc(16), Buffer.alloc(12), { authTagLength: 16 }); - hint: asymmetric-key operations need a public-key stack (bignum, RSA/EC/EdDSA math) and public and private KeyObjects — neither exists in the static runtime, so no faithful lowering can be small; the lowered crypto surface is hashing, randomness, secret KeyObjects, and the introspection statics + hint: RSA encryption has no lowering — the asymmetric crypto surface is RSA and EC KeyObjects (generateKeyPair, createPrivateKey, createPublicKey), sign, verify, createSign, createVerify, createECDH, and createDiffieHellman fenced.ts:77:16 - error SC2020: 'crypto.createCipheriv with cipher 'aes-128-ccm'' is part of the standard library types but has no scriptc lowering yet - 76 | generateKeyPair("rsa", { modulusLength: 2048 }, () => {}); + 76 | publicEncrypt("key", Buffer.alloc(1)); 77 | createCipheriv("aes-128-ccm", Buffer.alloc(16), Buffer.alloc(12), { authTagLength: 16 }); | ^~~~~~~~~~~~~ - 78 | checkPrimeSync(7n); + 78 | secureHeapUsed(); - hint: the supported ciphers are aes-128-cbc, aes-192-cbc, aes-256-cbc, aes-128-ctr, aes-192-ctr, aes-256-ctr, aes-128-gcm, aes-192-gcm, aes-256-gcm, and chacha20-poly1305 + hint: the supported ciphers are aes-128, aes-192 and aes-256 in cbc, ctr, gcm, ecb, cfb, cfb8, cfb1 and ofb modes, des-ede3 in cbc, ecb, cfb, cfb8, cfb1 and ofb modes, des-ede in cbc, ecb, cfb and ofb modes, chacha20, and chacha20-poly1305 -fenced.ts:78:1 - error SC2020: 'crypto.checkPrimeSync' is typed by @types/node but has no scriptc lowering yet +fenced.ts:78:1 - error SC2020: 'crypto.secureHeapUsed' is typed by @types/node but has no scriptc lowering yet 77 | createCipheriv("aes-128-ccm", Buffer.alloc(16), Buffer.alloc(12), { authTagLength: 16 }); - 78 | checkPrimeSync(7n); - | ^~~~~~~~~~~~~~~~~~ + 78 | secureHeapUsed(); + | ^~~~~~~~~~~~~~~~ 79 | setFips(false); hint: the type checker sees everything @types/node declares, but only the supported surface compiles (https://scriptc.dev/limitations) fenced.ts:79:1 - error SC2020: 'crypto.setFips' is typed by @types/node but has no scriptc lowering yet - 78 | checkPrimeSync(7n); + 78 | secureHeapUsed(); 79 | setFips(false); | ^~~~~~~~~~~~~~ 80 | fetch("https://example.invalid/", { @@ -205,47 +205,56 @@ fenced.ts:94:23 - error SC2020: 'util.callbackify into a callback whose error pa hint: Node calls back with a null error on success; type the binding's callback as (err: NodeJS.ErrnoException | null, ...) => void -fenced.ts:99:1 - error SC2020: 'Cipheriv/Decipheriv.on' is part of the standard library types but has no scriptc lowering yet +fenced.ts:100:12 - error SC2020: 'crypto.createECDH with curve 'sect163k1'' is part of the standard library types but has no scriptc lowering yet - 98 | const cipherStream = createCipheriv("aes-128-cbc", Buffer.alloc(16), Buffer.alloc(16)); - 99 | cipherStream.on("data", () => {}); - | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - 100 | /* ECDH on a curve Node knows but the runtime does not implement, and - - hint: update(), final(), setAAD(), setAutoPadding(), getAuthTag(), and setAuthTag() are supported; cipher streams are not - -fenced.ts:104:12 - error SC2020: 'crypto.createECDH with curve 'sect163k1'' is part of the standard library types but has no scriptc lowering yet - - 103 | import { createECDH } from "node:crypto"; - 104 | createECDH("sect163k1"); + 99 | import { createECDH } from "node:crypto"; + 100 | createECDH("sect163k1"); | ^~~~~~~~~~~ - 105 | createECDH("prime256v1").computeSecret(Buffer.alloc(65), "hex"); + 101 | createECDH("prime256v1").computeSecret(Buffer.alloc(65), "hex"); hint: the supported curves are prime192v1, secp224r1, prime256v1, secp384r1, secp521r1, secp192k1, secp224k1, secp256k1, brainpoolP256r1, brainpoolP384r1, and brainpoolP512r1 -fenced.ts:105:1 - error SC2020: 'ECDH.computeSecret(key, encoding) with a Buffer or view key' is part of the standard library types but has no scriptc lowering yet +fenced.ts:101:1 - error SC2020: 'ECDH.computeSecret(key, encoding) with a Buffer or view key' is part of the standard library types but has no scriptc lowering yet - 104 | createECDH("sect163k1"); - 105 | createECDH("prime256v1").computeSecret(Buffer.alloc(65), "hex"); + 100 | createECDH("sect163k1"); + 101 | createECDH("prime256v1").computeSecret(Buffer.alloc(65), "hex"); | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - 106 | /* WebCrypto beyond the HMAC slice: @types/node declares the whole + 102 | /* DiffieHellman's Object.prototype members, and crypto.diffieHellman over hint: Node reads the second argument as the key's input encoding and answers a Buffer; pass the output encoding third: computeSecret(key, undefined, encoding) -fenced.ts:110:9 - error SC2020: 'crypto.subtle.encrypt' is part of the standard library types but has no scriptc lowering yet +fenced.ts:105:1 - error SC2020: 'DiffieHellman.toString' is part of the standard library types but has no scriptc lowering yet - 109 | async function encryptWithWebCrypto(key: import("node:crypto").webcrypto.CryptoKey): Promise { - 110 | await crypto.subtle.encrypt({ name: "AES-GCM", iv: new Uint8Array(12) }, key, new Uint8Array(1)); - | ^~~~~~~~~~~~~~~~~~~~~ - 111 | } + 104 | import { createDiffieHellman, diffieHellman, type KeyObject } from "node:crypto"; + 105 | createDiffieHellman(Buffer.from([23])).toString(); + | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + 106 | declare const dhKey: KeyObject; - hint: the native WebCrypto surface is crypto.subtle.importKey('raw', ...) for HMAC keys, sign and verify with HMAC, and digest with SHA-1, SHA-256, SHA-384 or SHA-512, each called directly on crypto.subtle + hint: generateKeys(), computeSecret(), getPrime(), getGenerator(), getPublicKey(), getPrivateKey(), setPublicKey(), setPrivateKey() and verifyError are supported -fenced.ts:115:15 - error SC2020: 'navigator.hardwareConcurrency' is typed by @types/node but has no scriptc lowering yet +fenced.ts:107:1 - error SC2020: 'crypto.diffieHellman' is typed by @types/node but has no scriptc lowering yet - 114 | * compile; the other members fence by name. */ - 115 | const cores = navigator.hardwareConcurrency; + 106 | declare const dhKey: KeyObject; + 107 | diffieHellman({ privateKey: dhKey, publicKey: dhKey }); + | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + 108 | /* WebCrypto beyond the secret-key slice: @types/node declares the whole + + hint: crypto.diffieHellman takes DH, EC or X25519 KeyObjects and has no lowering; the objects of createDiffieHellman, getDiffieHellman and createECDH compute shared secrets + +fenced.ts:112:9 - error SC2020: 'crypto.subtle.getPublicKey' is part of the standard library types but has no scriptc lowering yet + + 111 | async function publicKeyWithWebCrypto(key: import("node:crypto").webcrypto.CryptoKey): Promise { + 112 | await crypto.subtle.getPublicKey(key, ["verify"]); + | ^~~~~~~~~~~~~~~~~~~~~~~~~~ + 113 | } + + hint: the native WebCrypto surface is crypto.subtle's importKey, generateKey and exportKey for HMAC and AES keys (importKey also for PBKDF2 and HKDF keys), encrypt and decrypt with AES-GCM, AES-CBC or AES-CTR, wrapKey and unwrapKey of secret keys with AES-KW or those ciphers, deriveBits and deriveKey with PBKDF2 or HKDF, sign and verify with HMAC, generateKey, importKey, exportKey, sign and verify for ECDSA, Ed25519, RSASSA-PKCS1-v1_5 and RSA-PSS, and digest with SHA-1, SHA-256, SHA-384 or SHA-512, each called directly on crypto.subtle + +fenced.ts:117:15 - error SC2020: 'navigator.hardwareConcurrency' is typed by @types/node but has no scriptc lowering yet + + 116 | * compile; the other members fence by name. */ + 117 | const cores = navigator.hardwareConcurrency; | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - 116 | void cores; + 118 | void cores; hint: of Node's navigator global only typeof navigator and navigator.userAgent compile \ No newline at end of file diff --git a/tests/harness/__snapshots__/retired-engine-1123-any-conditional-spread.ts.txt b/tests/harness/__snapshots__/retired-engine-1123-any-conditional-spread.ts.txt deleted file mode 100644 index 707d1dfd9..000000000 --- a/tests/harness/__snapshots__/retired-engine-1123-any-conditional-spread.ts.txt +++ /dev/null @@ -1,6 +0,0 @@ -retired-engine-1123-any-conditional-spread.ts:21:21 - error SC1090: conditional spreads beyond `...(c ? { field: v } : {})` (exactly one property against an empty arm — spell other shapes as optional fields) is not supported yet - - 20 | function multi(on: boolean): any { - 21 | return { base: 1, ...(on ? { x: "X", y: "Y" } : {}) }; - | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - 22 | } \ No newline at end of file diff --git a/tests/harness/__snapshots__/spread-fences.ts.txt b/tests/harness/__snapshots__/spread-fences.ts.txt index 56f8b81ee..eaced4979 100644 --- a/tests/harness/__snapshots__/spread-fences.ts.txt +++ b/tests/harness/__snapshots__/spread-fences.ts.txt @@ -1,4 +1,4 @@ -spread-fences.ts:14:21 - error SC1090: conditional spreads beyond `...(c ? { field: v } : {})` (exactly one property against an empty arm — spell other shapes as optional fields) is not supported yet +spread-fences.ts:14:21 - error SC1090: conditional spreads beyond `...(c ? { field: v } : {})` and `...(c ? record : {})` (one arm must be empty — spell other shapes as optional fields) is not supported yet 13 | const cond = true; 14 | const s1: Shape = { ...(cond ? { x: 1, y: 2 } : { x: 3, y: 4 }) }; diff --git a/tests/harness/__snapshots__/stream-byte-mode-chunk-fences.ts.txt b/tests/harness/__snapshots__/stream-byte-mode-chunk-fences.ts.txt new file mode 100644 index 000000000..39a06dfd7 --- /dev/null +++ b/tests/harness/__snapshots__/stream-byte-mode-chunk-fences.ts.txt @@ -0,0 +1,8 @@ +stream-byte-mode-chunk-fences.ts:10:5 - error SC2020: 'a '_write' method whose parameter 0 is 'number' where Node passes 'Uint8Array'' is part of the standard library types but has no scriptc lowering yet + + 9 | constructor() { + 10 | super(undefined); + | ^~~~~~~~~~~~~~~~ + 11 | } + + hint: annotate the parameter with the Node signature's type or a supertype of it (chunks are Buffers here) \ No newline at end of file diff --git a/tests/harness/__snapshots__/tls-socket-fences.ts.txt b/tests/harness/__snapshots__/tls-socket-fences.ts.txt new file mode 100644 index 000000000..e912b7649 --- /dev/null +++ b/tests/harness/__snapshots__/tls-socket-fences.ts.txt @@ -0,0 +1,26 @@ +tls-socket-fences.ts:15:29 - error SC2020: 'new tls.TLSSocket in client mode' is part of the standard library types but has no scriptc lowering yet + + 14 | // The client mode: Node starts no handshake for it. + 15 | new tls.TLSSocket(socket, { cert, key }); + | ^~~~~~~~~~~~~ + 16 | // A member after secureContext with side effects. + + hint: Node starts no handshake for a client-mode TLSSocket — pass isServer: true for the server side; tls.connect makes client sockets + +tls-socket-fences.ts:17:71 - error SC2020: 'a new tls.TLSSocket options literal with side effects after secureContext' is part of the standard library types but has no scriptc lowering yet + + 16 | // A member after secureContext with side effects. + 17 | new tls.TLSSocket(socket, { isServer: true, secureContext: context, ALPNProtocols: alpn() }); + | ^~~~~~~~~~~~~~~~~~~~~ + 18 | // A secureContext that is not a SecureContext. + + hint: secureContext is read after the other members — move it to the end of the object + +tls-socket-fences.ts:19:62 - error SC2020: 'a '{ cert: Uint8Array; key: Uint8Array }' secureContext' is part of the standard library types but has no scriptc lowering yet + + 18 | // A secureContext that is not a SecureContext. + 19 | new tls.TLSSocket(socket, { isServer: true, secureContext: { cert, key } }); + | ^~~~~~~~~~~~~ + 20 | }); + + hint: pass a tls.createSecureContext({ cert, key }) result \ No newline at end of file diff --git a/tests/harness/__snapshots__/webcrypto-refusals.ts.txt b/tests/harness/__snapshots__/webcrypto-refusals.ts.txt index 521edff3c..7242d2966 100644 --- a/tests/harness/__snapshots__/webcrypto-refusals.ts.txt +++ b/tests/harness/__snapshots__/webcrypto-refusals.ts.txt @@ -1,26 +1,17 @@ -webcrypto-refusals.ts:7:3 - error SC2020: 'crypto.subtle.importKey with the 'jwk' key format' is part of the standard library types but has no scriptc lowering yet +webcrypto-refusals.ts:6:16 - error SC2020: 'crypto.subtle as a value' is part of the standard library types but has no scriptc lowering yet - 6 | const fromJwk = await crypto.subtle.importKey( - 7 | "jwk", - | ^~~~~ - 8 | { kty: "oct", k: "c2VjcmV0" }, + 5 | // (node-types/fenced.ts pins their fence under @types/node). + 6 | const subtle = crypto.subtle; + | ^~~~~~~~~~~~~ + 7 | console.log(typeof subtle); - hint: the native WebCrypto surface is crypto.subtle.importKey('raw', ...) for HMAC keys, sign and verify with HMAC, and digest with SHA-1, SHA-256, SHA-384 or SHA-512, each called directly on crypto.subtle + hint: the native WebCrypto surface is crypto.subtle's importKey, generateKey and exportKey for HMAC and AES keys (importKey also for PBKDF2 and HKDF keys), encrypt and decrypt with AES-GCM, AES-CBC or AES-CTR, wrapKey and unwrapKey of secret keys with AES-KW or those ciphers, deriveBits and deriveKey with PBKDF2 or HKDF, sign and verify with HMAC, generateKey, importKey, exportKey, sign and verify for ECDSA, Ed25519, RSASSA-PKCS1-v1_5 and RSA-PSS, and digest with SHA-1, SHA-256, SHA-384 or SHA-512, each called directly on crypto.subtle -webcrypto-refusals.ts:15:16 - error SC2020: 'crypto.subtle as a value' is part of the standard library types but has no scriptc lowering yet +webcrypto-refusals.ts:9:20 - error SC2020: 'crypto.subtle.sign as a value' is part of the standard library types but has no scriptc lowering yet - 14 | - 15 | const subtle = crypto.subtle; - | ^~~~~~~~~~~~~ - 16 | console.log(typeof subtle); - - hint: the native WebCrypto surface is crypto.subtle.importKey('raw', ...) for HMAC keys, sign and verify with HMAC, and digest with SHA-1, SHA-256, SHA-384 or SHA-512, each called directly on crypto.subtle - -webcrypto-refusals.ts:18:20 - error SC2020: 'crypto.subtle.sign as a value' is part of the standard library types but has no scriptc lowering yet - - 17 | - 18 | console.log(typeof crypto.subtle.sign); + 8 | + 9 | console.log(typeof crypto.subtle.sign); | ^~~~~~~~~~~~~~~~~~ - 19 | + 10 | - hint: the native WebCrypto surface is crypto.subtle.importKey('raw', ...) for HMAC keys, sign and verify with HMAC, and digest with SHA-1, SHA-256, SHA-384 or SHA-512, each called directly on crypto.subtle \ No newline at end of file + hint: the native WebCrypto surface is crypto.subtle's importKey, generateKey and exportKey for HMAC and AES keys (importKey also for PBKDF2 and HKDF keys), encrypt and decrypt with AES-GCM, AES-CBC or AES-CTR, wrapKey and unwrapKey of secret keys with AES-KW or those ciphers, deriveBits and deriveKey with PBKDF2 or HKDF, sign and verify with HMAC, generateKey, importKey, exportKey, sign and verify for ECDSA, Ed25519, RSASSA-PKCS1-v1_5 and RSA-PSS, and digest with SHA-1, SHA-256, SHA-384 or SHA-512, each called directly on crypto.subtle \ No newline at end of file diff --git a/tests/harness/bootstrap-seed.test.ts b/tests/harness/bootstrap-seed.test.ts index 2e8b3bad9..76b1f6de5 100644 --- a/tests/harness/bootstrap-seed.test.ts +++ b/tests/harness/bootstrap-seed.test.ts @@ -78,6 +78,10 @@ test("CI restores each seed only into its matching instrumented bootstrap lane", const execute = checks.steps.find((step) => step.run?.split("\n").includes("node scripts/ci-native-bootstrap.mjs"), )!; + // The sanitized seed's build needs more memory than the runner has: swap backs it. + const swap = seed.steps.findIndex((step) => step.run?.includes("swapon /mnt/swapfile")); + expect(seed.steps[swap]?.if).toBe("matrix.flavor == 'san'"); + expect(swap).toBeLessThan(seed.steps.indexOf(prepare)); expect(prepare.env?.SCRIPTC_BOOTSTRAP_SEED_DIRECTORY).toBe("${{ runner.temp }}/native-bootstrap"); expect(execute.env?.SCRIPTC_BOOTSTRAP_SEED_DIRECTORY).toBe( prepare.env?.SCRIPTC_BOOTSTRAP_SEED_DIRECTORY, diff --git a/tests/harness/corpus-costs/4638-contract-program-lifetime-arrays.ts.json b/tests/harness/corpus-costs/4638-contract-program-lifetime-arrays.ts.json new file mode 100644 index 000000000..8512b117c --- /dev/null +++ b/tests/harness/corpus-costs/4638-contract-program-lifetime-arrays.ts.json @@ -0,0 +1 @@ +{ "plain": 2800, "san": 4600 } diff --git a/tests/harness/corpus-costs/4639-contract-program-lifetime-maps.ts.json b/tests/harness/corpus-costs/4639-contract-program-lifetime-maps.ts.json new file mode 100644 index 000000000..d12d0c3a4 --- /dev/null +++ b/tests/harness/corpus-costs/4639-contract-program-lifetime-maps.ts.json @@ -0,0 +1 @@ +{ "plain": 2500, "san": 3600 } diff --git a/tests/harness/corpus-costs/4814-integer-or-nan-indexes.ts.json b/tests/harness/corpus-costs/4814-integer-or-nan-indexes.ts.json new file mode 100644 index 000000000..23f4b5b65 --- /dev/null +++ b/tests/harness/corpus-costs/4814-integer-or-nan-indexes.ts.json @@ -0,0 +1 @@ +{"plain":3473,"san":4706} diff --git a/tests/harness/corpus-costs/4815-touint32-wide-magnitudes.ts.json b/tests/harness/corpus-costs/4815-touint32-wide-magnitudes.ts.json new file mode 100644 index 000000000..ee076af6b --- /dev/null +++ b/tests/harness/corpus-costs/4815-touint32-wide-magnitudes.ts.json @@ -0,0 +1 @@ +{"plain":2871,"san":4039} diff --git a/tests/harness/corpus-costs/6706-dh-groups.ts.json b/tests/harness/corpus-costs/6706-dh-groups.ts.json new file mode 100644 index 000000000..b051df274 --- /dev/null +++ b/tests/harness/corpus-costs/6706-dh-groups.ts.json @@ -0,0 +1 @@ +{ "plain": 4855, "san": 8228 } diff --git a/tests/harness/corpus-costs/6707-dh-explicit-params.ts.json b/tests/harness/corpus-costs/6707-dh-explicit-params.ts.json new file mode 100644 index 000000000..95ab0f1b2 --- /dev/null +++ b/tests/harness/corpus-costs/6707-dh-explicit-params.ts.json @@ -0,0 +1 @@ +{ "plain": 6328, "san": 10420 } diff --git a/tests/harness/corpus-costs/6708-dh-errors.js.json b/tests/harness/corpus-costs/6708-dh-errors.js.json new file mode 100644 index 000000000..743216cb9 --- /dev/null +++ b/tests/harness/corpus-costs/6708-dh-errors.js.json @@ -0,0 +1 @@ +{ "plain": 8044, "san": 10499 } diff --git a/tests/harness/corpus-costs/6709-dh-generate.ts.json b/tests/harness/corpus-costs/6709-dh-generate.ts.json new file mode 100644 index 000000000..1e00ad64d --- /dev/null +++ b/tests/harness/corpus-costs/6709-dh-generate.ts.json @@ -0,0 +1 @@ +{ "plain": 6999, "san": 9388 } diff --git a/tests/harness/corpus-costs/6710-dh-encodings.cjs.json b/tests/harness/corpus-costs/6710-dh-encodings.cjs.json new file mode 100644 index 000000000..15e5385e0 --- /dev/null +++ b/tests/harness/corpus-costs/6710-dh-encodings.cjs.json @@ -0,0 +1 @@ +{ "plain": 6048, "san": 8117 } diff --git a/tests/harness/corpus-costs/6711-dh-handles.ts.json b/tests/harness/corpus-costs/6711-dh-handles.ts.json new file mode 100644 index 000000000..ecf09ecb1 --- /dev/null +++ b/tests/harness/corpus-costs/6711-dh-handles.ts.json @@ -0,0 +1 @@ +{ "plain": 5664, "san": 7161 } diff --git a/tests/harness/corpus-costs/6712-dh-peer-keys.js.json b/tests/harness/corpus-costs/6712-dh-peer-keys.js.json new file mode 100644 index 000000000..429593dc5 --- /dev/null +++ b/tests/harness/corpus-costs/6712-dh-peer-keys.js.json @@ -0,0 +1 @@ +{ "plain": 9427, "san": 12410 } diff --git a/tests/harness/corpus-costs/6822-jsx-classic-runtime/main.ts.json b/tests/harness/corpus-costs/6822-jsx-classic-runtime/main.ts.json new file mode 100644 index 000000000..dbc0fa779 --- /dev/null +++ b/tests/harness/corpus-costs/6822-jsx-classic-runtime/main.ts.json @@ -0,0 +1 @@ +{ "plain": 3400, "san": 2900 } diff --git a/tests/harness/corpus-costs/6824-jsx-automatic-runtime/main.ts.json b/tests/harness/corpus-costs/6824-jsx-automatic-runtime/main.ts.json new file mode 100644 index 000000000..2a685047e --- /dev/null +++ b/tests/harness/corpus-costs/6824-jsx-automatic-runtime/main.ts.json @@ -0,0 +1 @@ +{ "plain": 3600, "san": 3000 } diff --git a/tests/harness/corpus-costs/6825-jsx-automatic-development/main.ts.json b/tests/harness/corpus-costs/6825-jsx-automatic-development/main.ts.json new file mode 100644 index 000000000..79e32d960 --- /dev/null +++ b/tests/harness/corpus-costs/6825-jsx-automatic-development/main.ts.json @@ -0,0 +1 @@ +{ "plain": 3000, "san": 2500 } diff --git a/tests/harness/corpus-costs/6826-map-primitive-constructors.ts.json b/tests/harness/corpus-costs/6826-map-primitive-constructors.ts.json new file mode 100644 index 000000000..d2c795829 --- /dev/null +++ b/tests/harness/corpus-costs/6826-map-primitive-constructors.ts.json @@ -0,0 +1 @@ +{ "plain": 3700, "san": 3500 } diff --git a/tests/harness/corpus-costs/6827-recursive-union-nested-literals.ts.json b/tests/harness/corpus-costs/6827-recursive-union-nested-literals.ts.json new file mode 100644 index 000000000..f44e89d4f --- /dev/null +++ b/tests/harness/corpus-costs/6827-recursive-union-nested-literals.ts.json @@ -0,0 +1 @@ +{ "plain": 3500, "san": 3400 } diff --git a/tests/harness/corpus-costs/6828-recursive-union-object-walkers.ts.json b/tests/harness/corpus-costs/6828-recursive-union-object-walkers.ts.json new file mode 100644 index 000000000..77ddc81f8 --- /dev/null +++ b/tests/harness/corpus-costs/6828-recursive-union-object-walkers.ts.json @@ -0,0 +1 @@ +{ "plain": 4200, "san": 5800 } diff --git a/tests/harness/corpus-costs/6862-readline-chained-listeners.cjs.json b/tests/harness/corpus-costs/6862-readline-chained-listeners.cjs.json new file mode 100644 index 000000000..5c8f4dafd --- /dev/null +++ b/tests/harness/corpus-costs/6862-readline-chained-listeners.cjs.json @@ -0,0 +1 @@ +{ "plain": 1930, "san": 4280 } diff --git a/tests/harness/corpus-costs/6865-number-parseint-default-radix.ts.json b/tests/harness/corpus-costs/6865-number-parseint-default-radix.ts.json new file mode 100644 index 000000000..ad095e0af --- /dev/null +++ b/tests/harness/corpus-costs/6865-number-parseint-default-radix.ts.json @@ -0,0 +1 @@ +{ "plain": 1940, "san": 4550 } diff --git a/tests/harness/corpus-costs/6866-number-parseint-untyped.js.json b/tests/harness/corpus-costs/6866-number-parseint-untyped.js.json new file mode 100644 index 000000000..03bfc0b22 --- /dev/null +++ b/tests/harness/corpus-costs/6866-number-parseint-untyped.js.json @@ -0,0 +1 @@ +{ "plain": 1830, "san": 3890 } diff --git a/tests/harness/corpus-costs/6867-string-match-optional-regexp.js.json b/tests/harness/corpus-costs/6867-string-match-optional-regexp.js.json new file mode 100644 index 000000000..f6a23dfa9 --- /dev/null +++ b/tests/harness/corpus-costs/6867-string-match-optional-regexp.js.json @@ -0,0 +1 @@ +{ "plain": 1960, "san": 4170 } diff --git a/tests/harness/corpus-costs/6868-buffer-from-untyped-array-buffer.cjs.json b/tests/harness/corpus-costs/6868-buffer-from-untyped-array-buffer.cjs.json new file mode 100644 index 000000000..a1967e528 --- /dev/null +++ b/tests/harness/corpus-costs/6868-buffer-from-untyped-array-buffer.cjs.json @@ -0,0 +1 @@ +{ "plain": 2070, "san": 4110 } diff --git a/tests/harness/corpus-costs/6869-atomics-untyped-arrays.cjs.json b/tests/harness/corpus-costs/6869-atomics-untyped-arrays.cjs.json new file mode 100644 index 000000000..114626b53 --- /dev/null +++ b/tests/harness/corpus-costs/6869-atomics-untyped-arrays.cjs.json @@ -0,0 +1 @@ +{ "plain": 2500, "san": 4710 } diff --git a/tests/harness/corpus-costs/6870-error-constructor-values.js.json b/tests/harness/corpus-costs/6870-error-constructor-values.js.json new file mode 100644 index 000000000..c608ce33a --- /dev/null +++ b/tests/harness/corpus-costs/6870-error-constructor-values.js.json @@ -0,0 +1 @@ +{ "plain": 1200, "san": 3400 } diff --git a/tests/harness/corpus-costs/6871-worker-data-destructuring.cjs.json b/tests/harness/corpus-costs/6871-worker-data-destructuring.cjs.json new file mode 100644 index 000000000..d6c0cb9ee --- /dev/null +++ b/tests/harness/corpus-costs/6871-worker-data-destructuring.cjs.json @@ -0,0 +1 @@ +{ "plain": 1300, "san": 3490 } diff --git a/tests/harness/corpus-costs/6872-regex-start-filter.ts.json b/tests/harness/corpus-costs/6872-regex-start-filter.ts.json new file mode 100644 index 000000000..c9d5dd264 --- /dev/null +++ b/tests/harness/corpus-costs/6872-regex-start-filter.ts.json @@ -0,0 +1 @@ +{ "plain": 2430, "san": 8860 } diff --git a/tests/harness/corpus-costs/6912-extend-factory-local-class.ts.json b/tests/harness/corpus-costs/6912-extend-factory-local-class.ts.json new file mode 100644 index 000000000..a44d195f2 --- /dev/null +++ b/tests/harness/corpus-costs/6912-extend-factory-local-class.ts.json @@ -0,0 +1 @@ +{ "plain": 3633, "san": 5578 } diff --git a/tests/harness/corpus-costs/6913-builtin-constructor-shorthand.ts.json b/tests/harness/corpus-costs/6913-builtin-constructor-shorthand.ts.json new file mode 100644 index 000000000..3c9170116 --- /dev/null +++ b/tests/harness/corpus-costs/6913-builtin-constructor-shorthand.ts.json @@ -0,0 +1 @@ +{ "plain": 3202, "san": 4630 } diff --git a/tests/harness/corpus-costs/6914-dynamic-builtin-construct.ts.json b/tests/harness/corpus-costs/6914-dynamic-builtin-construct.ts.json new file mode 100644 index 000000000..a3f53b09c --- /dev/null +++ b/tests/harness/corpus-costs/6914-dynamic-builtin-construct.ts.json @@ -0,0 +1 @@ +{ "plain": 3064, "san": 5586 } diff --git a/tests/harness/corpus-costs/6915-dynamic-builtin-construct.mjs.json b/tests/harness/corpus-costs/6915-dynamic-builtin-construct.mjs.json new file mode 100644 index 000000000..0c65d046c --- /dev/null +++ b/tests/harness/corpus-costs/6915-dynamic-builtin-construct.mjs.json @@ -0,0 +1 @@ +{ "plain": 2821, "san": 4440 } diff --git a/tests/harness/corpus-costs/6915-key-order-narrowed-throw.ts.json b/tests/harness/corpus-costs/6915-key-order-narrowed-throw.ts.json new file mode 100644 index 000000000..fae2adeb4 --- /dev/null +++ b/tests/harness/corpus-costs/6915-key-order-narrowed-throw.ts.json @@ -0,0 +1 @@ +{ "plain": 1500, "san": 9000 } diff --git a/tests/harness/corpus-costs/6916-index-record-spread-overrides.ts.json b/tests/harness/corpus-costs/6916-index-record-spread-overrides.ts.json new file mode 100644 index 000000000..fae2adeb4 --- /dev/null +++ b/tests/harness/corpus-costs/6916-index-record-spread-overrides.ts.json @@ -0,0 +1 @@ +{ "plain": 1500, "san": 9000 } diff --git a/tests/harness/corpus-costs/6916-local-class-static-self-reference.mjs.json b/tests/harness/corpus-costs/6916-local-class-static-self-reference.mjs.json new file mode 100644 index 000000000..0d9aa6b13 --- /dev/null +++ b/tests/harness/corpus-costs/6916-local-class-static-self-reference.mjs.json @@ -0,0 +1 @@ +{ "plain": 3135, "san": 4365 } diff --git a/tests/harness/corpus-costs/6917-local-class-expression-self-reference.ts.json b/tests/harness/corpus-costs/6917-local-class-expression-self-reference.ts.json new file mode 100644 index 000000000..2769f5b72 --- /dev/null +++ b/tests/harness/corpus-costs/6917-local-class-expression-self-reference.ts.json @@ -0,0 +1 @@ +{ "plain": 3074, "san": 4624 } diff --git a/tests/harness/corpus-costs/6918-local-class-expression-self-reference.mjs.json b/tests/harness/corpus-costs/6918-local-class-expression-self-reference.mjs.json new file mode 100644 index 000000000..04f903d8a --- /dev/null +++ b/tests/harness/corpus-costs/6918-local-class-expression-self-reference.mjs.json @@ -0,0 +1 @@ +{ "plain": 3050, "san": 4393 } diff --git a/tests/harness/corpus-costs/6919-local-class-inspect-name.mjs.json b/tests/harness/corpus-costs/6919-local-class-inspect-name.mjs.json new file mode 100644 index 000000000..78aea9163 --- /dev/null +++ b/tests/harness/corpus-costs/6919-local-class-inspect-name.mjs.json @@ -0,0 +1 @@ +{ "plain": 3058, "san": 4846 } diff --git a/tests/harness/corpus-costs/6921-local-subclass-override-dispatch.ts.json b/tests/harness/corpus-costs/6921-local-subclass-override-dispatch.ts.json new file mode 100644 index 000000000..0dd7e966b --- /dev/null +++ b/tests/harness/corpus-costs/6921-local-subclass-override-dispatch.ts.json @@ -0,0 +1 @@ +{ "plain": 2459, "san": 4630 } diff --git a/tests/harness/corpus-costs/6922-local-subclass-override-dispatch.mjs.json b/tests/harness/corpus-costs/6922-local-subclass-override-dispatch.mjs.json new file mode 100644 index 000000000..f2ba6c139 --- /dev/null +++ b/tests/harness/corpus-costs/6922-local-subclass-override-dispatch.mjs.json @@ -0,0 +1 @@ +{ "plain": 3216, "san": 5042 } diff --git a/tests/harness/corpus-costs/6926-dynamic-collection-seeds.mjs.json b/tests/harness/corpus-costs/6926-dynamic-collection-seeds.mjs.json new file mode 100644 index 000000000..b4a56f5c5 --- /dev/null +++ b/tests/harness/corpus-costs/6926-dynamic-collection-seeds.mjs.json @@ -0,0 +1 @@ +{ "plain": 3813, "san": 3374 } diff --git a/tests/harness/corpus-costs/6927-dynamic-collection-seeds.ts.json b/tests/harness/corpus-costs/6927-dynamic-collection-seeds.ts.json new file mode 100644 index 000000000..93da087d2 --- /dev/null +++ b/tests/harness/corpus-costs/6927-dynamic-collection-seeds.ts.json @@ -0,0 +1 @@ +{ "plain": 2436, "san": 2273 } diff --git a/tests/harness/corpus-costs/6996-typed-array-index-temps.ts.json b/tests/harness/corpus-costs/6996-typed-array-index-temps.ts.json new file mode 100644 index 000000000..4dc6b88cb --- /dev/null +++ b/tests/harness/corpus-costs/6996-typed-array-index-temps.ts.json @@ -0,0 +1 @@ +{ "plain": 3500, "san": 4600 } diff --git a/tests/harness/corpus-costs/6997-typed-array-invariant-index-terms.ts.json b/tests/harness/corpus-costs/6997-typed-array-invariant-index-terms.ts.json new file mode 100644 index 000000000..ed05a3c5d --- /dev/null +++ b/tests/harness/corpus-costs/6997-typed-array-invariant-index-terms.ts.json @@ -0,0 +1 @@ +{ "plain": 3400, "san": 4800 } diff --git a/tests/harness/corpus-costs/6998-typed-array-while-loop-versions.ts.json b/tests/harness/corpus-costs/6998-typed-array-while-loop-versions.ts.json new file mode 100644 index 000000000..204a01a83 --- /dev/null +++ b/tests/harness/corpus-costs/6998-typed-array-while-loop-versions.ts.json @@ -0,0 +1 @@ +{ "plain": 3700, "san": 5000 } diff --git a/tests/harness/corpus-costs/6999-typed-array-callback-loops.ts.json b/tests/harness/corpus-costs/6999-typed-array-callback-loops.ts.json new file mode 100644 index 000000000..63d9448b4 --- /dev/null +++ b/tests/harness/corpus-costs/6999-typed-array-callback-loops.ts.json @@ -0,0 +1 @@ +{ "plain": 4400, "san": 5000 } diff --git a/tests/harness/corpus-costs/7002-empty-array-contextual-slots/main.ts.json b/tests/harness/corpus-costs/7002-empty-array-contextual-slots/main.ts.json new file mode 100644 index 000000000..9495bb65c --- /dev/null +++ b/tests/harness/corpus-costs/7002-empty-array-contextual-slots/main.ts.json @@ -0,0 +1 @@ +{ "plain": 2282, "san": 1173 } diff --git a/tests/harness/corpus-costs/7005-dyn-constructor-instanceof/main.ts.json b/tests/harness/corpus-costs/7005-dyn-constructor-instanceof/main.ts.json new file mode 100644 index 000000000..f84e21437 --- /dev/null +++ b/tests/harness/corpus-costs/7005-dyn-constructor-instanceof/main.ts.json @@ -0,0 +1 @@ +{ "plain": 2308, "san": 955 } diff --git a/tests/harness/corpus-costs/7006-evolving-array-aliases.ts.json b/tests/harness/corpus-costs/7006-evolving-array-aliases.ts.json new file mode 100644 index 000000000..f34efd332 --- /dev/null +++ b/tests/harness/corpus-costs/7006-evolving-array-aliases.ts.json @@ -0,0 +1 @@ +{ "plain": 2292, "san": 3445 } diff --git a/tests/harness/corpus-costs/7007-filter-written-type-predicates.ts.json b/tests/harness/corpus-costs/7007-filter-written-type-predicates.ts.json new file mode 100644 index 000000000..188fa7fab --- /dev/null +++ b/tests/harness/corpus-costs/7007-filter-written-type-predicates.ts.json @@ -0,0 +1 @@ +{ "plain": 3510, "san": 2873 } diff --git a/tests/harness/corpus-costs/7008-js-unit-initialized-properties/main.ts.json b/tests/harness/corpus-costs/7008-js-unit-initialized-properties/main.ts.json new file mode 100644 index 000000000..3a6df58d2 --- /dev/null +++ b/tests/harness/corpus-costs/7008-js-unit-initialized-properties/main.ts.json @@ -0,0 +1 @@ +{ "plain": 3065, "san": 2623 } diff --git a/tests/harness/corpus-costs/7009-finalization-registry-wasm-loader/main.ts.json b/tests/harness/corpus-costs/7009-finalization-registry-wasm-loader/main.ts.json new file mode 100644 index 000000000..db9fc4168 --- /dev/null +++ b/tests/harness/corpus-costs/7009-finalization-registry-wasm-loader/main.ts.json @@ -0,0 +1 @@ +{ "plain": 4351, "san": 2333 } diff --git a/tests/harness/corpus-costs/7011-for-in-dictionary-deletes.ts.json b/tests/harness/corpus-costs/7011-for-in-dictionary-deletes.ts.json new file mode 100644 index 000000000..e172eed8a --- /dev/null +++ b/tests/harness/corpus-costs/7011-for-in-dictionary-deletes.ts.json @@ -0,0 +1 @@ +{ "plain": 1527, "san": 2135 } diff --git a/tests/harness/corpus-costs/7014-js-never-array-literal-fields/main.ts.json b/tests/harness/corpus-costs/7014-js-never-array-literal-fields/main.ts.json new file mode 100644 index 000000000..c5bf12c38 --- /dev/null +++ b/tests/harness/corpus-costs/7014-js-never-array-literal-fields/main.ts.json @@ -0,0 +1 @@ +{ "plain": 3004, "san": 3359 } diff --git a/tests/harness/corpus-costs/7020-conditional-spread-fields.ts.json b/tests/harness/corpus-costs/7020-conditional-spread-fields.ts.json new file mode 100644 index 000000000..ee564e79f --- /dev/null +++ b/tests/harness/corpus-costs/7020-conditional-spread-fields.ts.json @@ -0,0 +1 @@ +{ "plain": 3640, "san": 5580 } diff --git a/tests/harness/corpus-costs/7021-promise-all-uniform-tuple.ts.json b/tests/harness/corpus-costs/7021-promise-all-uniform-tuple.ts.json new file mode 100644 index 000000000..fba6fd530 --- /dev/null +++ b/tests/harness/corpus-costs/7021-promise-all-uniform-tuple.ts.json @@ -0,0 +1 @@ +{ "plain": 2510, "san": 3630 } diff --git a/tests/harness/corpus-costs/7022-promise-all-dynamic-arrays.ts.json b/tests/harness/corpus-costs/7022-promise-all-dynamic-arrays.ts.json new file mode 100644 index 000000000..c59bb483b --- /dev/null +++ b/tests/harness/corpus-costs/7022-promise-all-dynamic-arrays.ts.json @@ -0,0 +1 @@ +{ "plain": 3330, "san": 4690 } diff --git a/tests/harness/corpus-costs/7023-union-object-patterns.ts.json b/tests/harness/corpus-costs/7023-union-object-patterns.ts.json new file mode 100644 index 000000000..3f0a047e7 --- /dev/null +++ b/tests/harness/corpus-costs/7023-union-object-patterns.ts.json @@ -0,0 +1 @@ +{ "plain": 2440, "san": 3670 } diff --git a/tests/harness/corpus-costs/7024-async-return-fresh-collections.ts.json b/tests/harness/corpus-costs/7024-async-return-fresh-collections.ts.json new file mode 100644 index 000000000..6285a25c5 --- /dev/null +++ b/tests/harness/corpus-costs/7024-async-return-fresh-collections.ts.json @@ -0,0 +1 @@ +{ "plain": 2570, "san": 4360 } diff --git a/tests/harness/corpus-costs/7025-child-listener-chaining.ts.json b/tests/harness/corpus-costs/7025-child-listener-chaining.ts.json new file mode 100644 index 000000000..44843dc06 --- /dev/null +++ b/tests/harness/corpus-costs/7025-child-listener-chaining.ts.json @@ -0,0 +1 @@ +{ "plain": 2510, "san": 3950 } diff --git a/tests/harness/corpus-costs/7026-url-object-patterns.ts.json b/tests/harness/corpus-costs/7026-url-object-patterns.ts.json new file mode 100644 index 000000000..9d3f28ab1 --- /dev/null +++ b/tests/harness/corpus-costs/7026-url-object-patterns.ts.json @@ -0,0 +1 @@ +{ "plain": 2520, "san": 4000 } diff --git a/tests/harness/corpus-costs/7027-search-params-conditional-init.ts.json b/tests/harness/corpus-costs/7027-search-params-conditional-init.ts.json new file mode 100644 index 000000000..56c46a74b --- /dev/null +++ b/tests/harness/corpus-costs/7027-search-params-conditional-init.ts.json @@ -0,0 +1 @@ +{ "plain": 2240, "san": 3440 } diff --git a/tests/harness/corpus-costs/7028-non-empty-rest-tuples.ts.json b/tests/harness/corpus-costs/7028-non-empty-rest-tuples.ts.json new file mode 100644 index 000000000..147f70b9a --- /dev/null +++ b/tests/harness/corpus-costs/7028-non-empty-rest-tuples.ts.json @@ -0,0 +1 @@ +{ "plain": 2520, "san": 4030 } diff --git a/tests/harness/corpus-costs/7029-flatmap-union-results.ts.json b/tests/harness/corpus-costs/7029-flatmap-union-results.ts.json new file mode 100644 index 000000000..7efdd91bf --- /dev/null +++ b/tests/harness/corpus-costs/7029-flatmap-union-results.ts.json @@ -0,0 +1 @@ +{ "plain": 2640, "san": 4710 } diff --git a/tests/harness/corpus-costs/7030-spawn-sync-env.ts.json b/tests/harness/corpus-costs/7030-spawn-sync-env.ts.json new file mode 100644 index 000000000..cf8ef4d26 --- /dev/null +++ b/tests/harness/corpus-costs/7030-spawn-sync-env.ts.json @@ -0,0 +1 @@ +{ "plain": 2460, "san": 4060 } diff --git a/tests/harness/corpus-costs/7033-any-fields-into-declared-records.ts.json b/tests/harness/corpus-costs/7033-any-fields-into-declared-records.ts.json new file mode 100644 index 000000000..1fd3ee053 --- /dev/null +++ b/tests/harness/corpus-costs/7033-any-fields-into-declared-records.ts.json @@ -0,0 +1 @@ +{ "plain": 2640, "san": 3950 } diff --git a/tests/harness/corpus-costs/7034-optional-field-union-routes.ts.json b/tests/harness/corpus-costs/7034-optional-field-union-routes.ts.json new file mode 100644 index 000000000..7e342cfd0 --- /dev/null +++ b/tests/harness/corpus-costs/7034-optional-field-union-routes.ts.json @@ -0,0 +1 @@ +{ "plain": 2420, "san": 3640 } diff --git a/tests/harness/corpus-costs/7036-child-env-path-lookup.ts.json b/tests/harness/corpus-costs/7036-child-env-path-lookup.ts.json new file mode 100644 index 000000000..f9bfce7d9 --- /dev/null +++ b/tests/harness/corpus-costs/7036-child-env-path-lookup.ts.json @@ -0,0 +1 @@ +{ "plain": 2570, "san": 4110 } diff --git a/tests/harness/corpus-costs/7040-es5-error-constructor.mjs.json b/tests/harness/corpus-costs/7040-es5-error-constructor.mjs.json new file mode 100644 index 000000000..40dc942dc --- /dev/null +++ b/tests/harness/corpus-costs/7040-es5-error-constructor.mjs.json @@ -0,0 +1 @@ +{ "plain": 3648, "san": 32315 } diff --git a/tests/harness/corpus-costs/7041-error-called-without-new.mjs.json b/tests/harness/corpus-costs/7041-error-called-without-new.mjs.json new file mode 100644 index 000000000..d5a7a927c --- /dev/null +++ b/tests/harness/corpus-costs/7041-error-called-without-new.mjs.json @@ -0,0 +1 @@ +{ "plain": 2293, "san": 3259 } diff --git a/tests/harness/corpus-costs/7042-string-method-names-on-objects.mjs.json b/tests/harness/corpus-costs/7042-string-method-names-on-objects.mjs.json new file mode 100644 index 000000000..e85a6cc3e --- /dev/null +++ b/tests/harness/corpus-costs/7042-string-method-names-on-objects.mjs.json @@ -0,0 +1 @@ +{ "plain": 2776, "san": 20012 } diff --git a/tests/harness/corpus-costs/7043-date-set-time.mjs.json b/tests/harness/corpus-costs/7043-date-set-time.mjs.json new file mode 100644 index 000000000..cdb4d4f92 --- /dev/null +++ b/tests/harness/corpus-costs/7043-date-set-time.mjs.json @@ -0,0 +1 @@ +{ "plain": 2423, "san": 3371 } diff --git a/tests/harness/corpus-costs/7044-nested-empty-object-maps.mjs.json b/tests/harness/corpus-costs/7044-nested-empty-object-maps.mjs.json new file mode 100644 index 000000000..a7951b37e --- /dev/null +++ b/tests/harness/corpus-costs/7044-nested-empty-object-maps.mjs.json @@ -0,0 +1 @@ +{ "plain": 2671, "san": 3931 } diff --git a/tests/harness/corpus-costs/7045-instanceof-constructor-values.mjs.json b/tests/harness/corpus-costs/7045-instanceof-constructor-values.mjs.json new file mode 100644 index 000000000..1776c882d --- /dev/null +++ b/tests/harness/corpus-costs/7045-instanceof-constructor-values.mjs.json @@ -0,0 +1 @@ +{ "plain": 2726, "san": 4330 } diff --git a/tests/harness/corpus-costs/7046-parse-float-extra-arguments.mjs.json b/tests/harness/corpus-costs/7046-parse-float-extra-arguments.mjs.json new file mode 100644 index 000000000..2e8f43953 --- /dev/null +++ b/tests/harness/corpus-costs/7046-parse-float-extra-arguments.mjs.json @@ -0,0 +1 @@ +{ "plain": 2204, "san": 3269 } diff --git a/tests/harness/corpus-costs/7047-dynamic-string-index.mjs.json b/tests/harness/corpus-costs/7047-dynamic-string-index.mjs.json new file mode 100644 index 000000000..d73f3cccc --- /dev/null +++ b/tests/harness/corpus-costs/7047-dynamic-string-index.mjs.json @@ -0,0 +1 @@ +{ "plain": 2451, "san": 3411 } diff --git a/tests/harness/corpus-costs/7048-unary-number-coercions.mjs.json b/tests/harness/corpus-costs/7048-unary-number-coercions.mjs.json new file mode 100644 index 000000000..710783451 --- /dev/null +++ b/tests/harness/corpus-costs/7048-unary-number-coercions.mjs.json @@ -0,0 +1 @@ +{ "plain": 2478, "san": 3675 } diff --git a/tests/harness/corpus-costs/7049-member-assignment-values.mjs.json b/tests/harness/corpus-costs/7049-member-assignment-values.mjs.json new file mode 100644 index 000000000..551cfbf7b --- /dev/null +++ b/tests/harness/corpus-costs/7049-member-assignment-values.mjs.json @@ -0,0 +1 @@ +{ "plain": 2456, "san": 3617 } diff --git a/tests/harness/corpus-costs/7050-date-subclass.mjs.json b/tests/harness/corpus-costs/7050-date-subclass.mjs.json new file mode 100644 index 000000000..e21289735 --- /dev/null +++ b/tests/harness/corpus-costs/7050-date-subclass.mjs.json @@ -0,0 +1 @@ +{ "plain": 2932, "san": 3727 } diff --git a/tests/harness/corpus-costs/7051-date-subclass-typed.ts.json b/tests/harness/corpus-costs/7051-date-subclass-typed.ts.json new file mode 100644 index 000000000..fad282486 --- /dev/null +++ b/tests/harness/corpus-costs/7051-date-subclass-typed.ts.json @@ -0,0 +1 @@ +{ "plain": 2533, "san": 3429 } diff --git a/tests/harness/corpus-costs/7052-date-subclass-dynamic.mjs.json b/tests/harness/corpus-costs/7052-date-subclass-dynamic.mjs.json new file mode 100644 index 000000000..cabbe475e --- /dev/null +++ b/tests/harness/corpus-costs/7052-date-subclass-dynamic.mjs.json @@ -0,0 +1 @@ +{ "plain": 2740, "san": 3689 } diff --git a/tests/harness/corpus-costs/7053-private-fields-untyped-receivers.mjs.json b/tests/harness/corpus-costs/7053-private-fields-untyped-receivers.mjs.json new file mode 100644 index 000000000..8ebe6846a --- /dev/null +++ b/tests/harness/corpus-costs/7053-private-fields-untyped-receivers.mjs.json @@ -0,0 +1 @@ +{ "plain": 2415, "san": 3338 } diff --git a/tests/harness/corpus-costs/7054-let-bindings-with-null-writes.mjs.json b/tests/harness/corpus-costs/7054-let-bindings-with-null-writes.mjs.json new file mode 100644 index 000000000..d313a64f1 --- /dev/null +++ b/tests/harness/corpus-costs/7054-let-bindings-with-null-writes.mjs.json @@ -0,0 +1 @@ +{ "plain": 2293, "san": 3012 } diff --git a/tests/harness/corpus-costs/7055-cipher-streams.ts.json b/tests/harness/corpus-costs/7055-cipher-streams.ts.json new file mode 100644 index 000000000..7dda3fe10 --- /dev/null +++ b/tests/harness/corpus-costs/7055-cipher-streams.ts.json @@ -0,0 +1 @@ +{ "plain": 4395, "san": 6600 } diff --git a/tests/harness/corpus-costs/7056-cipher-stream-errors.ts.json b/tests/harness/corpus-costs/7056-cipher-stream-errors.ts.json new file mode 100644 index 000000000..b3e89de2a --- /dev/null +++ b/tests/harness/corpus-costs/7056-cipher-stream-errors.ts.json @@ -0,0 +1 @@ +{ "plain": 2558, "san": 4456 } diff --git a/tests/harness/corpus-costs/7057-cipher-streams.mjs.json b/tests/harness/corpus-costs/7057-cipher-streams.mjs.json new file mode 100644 index 000000000..1edb6e866 --- /dev/null +++ b/tests/harness/corpus-costs/7057-cipher-streams.mjs.json @@ -0,0 +1 @@ +{ "plain": 2780, "san": 5329 } diff --git a/tests/harness/corpus-costs/7058-pipeline-function-stages.mjs.json b/tests/harness/corpus-costs/7058-pipeline-function-stages.mjs.json new file mode 100644 index 000000000..d4709c5d6 --- /dev/null +++ b/tests/harness/corpus-costs/7058-pipeline-function-stages.mjs.json @@ -0,0 +1 @@ +{ "plain": 3703, "san": 7279 } diff --git a/tests/harness/corpus-costs/7059-transform-backpressure.ts.json b/tests/harness/corpus-costs/7059-transform-backpressure.ts.json new file mode 100644 index 000000000..cc34bea0e --- /dev/null +++ b/tests/harness/corpus-costs/7059-transform-backpressure.ts.json @@ -0,0 +1 @@ +{ "plain": 2394, "san": 5656 } diff --git a/tests/harness/corpus-costs/7080-crypto-ed25519.mjs.json b/tests/harness/corpus-costs/7080-crypto-ed25519.mjs.json new file mode 100644 index 000000000..8a1e96b68 --- /dev/null +++ b/tests/harness/corpus-costs/7080-crypto-ed25519.mjs.json @@ -0,0 +1 @@ +{ "plain": 4906, "san": 50709 } diff --git a/tests/harness/corpus-costs/7081-webcrypto-ed25519.mjs.json b/tests/harness/corpus-costs/7081-webcrypto-ed25519.mjs.json new file mode 100644 index 000000000..47b28eca2 --- /dev/null +++ b/tests/harness/corpus-costs/7081-webcrypto-ed25519.mjs.json @@ -0,0 +1 @@ +{ "plain": 7958, "san": 51204 } diff --git a/tests/harness/corpus-costs/7082-crypto-key-objects.ts.json b/tests/harness/corpus-costs/7082-crypto-key-objects.ts.json new file mode 100644 index 000000000..b0d8e50c9 --- /dev/null +++ b/tests/harness/corpus-costs/7082-crypto-key-objects.ts.json @@ -0,0 +1 @@ +{ "plain": 4405, "san": 7280 } diff --git a/tests/harness/corpus-costs/7083-crypto-sign-verify.ts.json b/tests/harness/corpus-costs/7083-crypto-sign-verify.ts.json new file mode 100644 index 000000000..650393982 --- /dev/null +++ b/tests/harness/corpus-costs/7083-crypto-sign-verify.ts.json @@ -0,0 +1 @@ +{ "plain": 3631, "san": 5127 } diff --git a/tests/harness/corpus-costs/7084-crypto-key-pairs.cjs.json b/tests/harness/corpus-costs/7084-crypto-key-pairs.cjs.json new file mode 100644 index 000000000..363a8de39 --- /dev/null +++ b/tests/harness/corpus-costs/7084-crypto-key-pairs.cjs.json @@ -0,0 +1 @@ +{ "plain": 6267, "san": 19680 } diff --git a/tests/harness/corpus-costs/7085-webcrypto-ecdsa-rsa.ts.json b/tests/harness/corpus-costs/7085-webcrypto-ecdsa-rsa.ts.json new file mode 100644 index 000000000..73c07085d --- /dev/null +++ b/tests/harness/corpus-costs/7085-webcrypto-ecdsa-rsa.ts.json @@ -0,0 +1 @@ +{ "plain": 5184, "san": 40791 } diff --git a/tests/harness/corpus-costs/7086-webcrypto-ecdsa-rsa-errors.mjs.json b/tests/harness/corpus-costs/7086-webcrypto-ecdsa-rsa-errors.mjs.json new file mode 100644 index 000000000..a74af7ae1 --- /dev/null +++ b/tests/harness/corpus-costs/7086-webcrypto-ecdsa-rsa-errors.mjs.json @@ -0,0 +1 @@ +{ "plain": 8513, "san": 13054 } diff --git a/tests/harness/corpus-costs/7087-tls-socket-wrap.ts.json b/tests/harness/corpus-costs/7087-tls-socket-wrap.ts.json new file mode 100644 index 000000000..b4372e38c --- /dev/null +++ b/tests/harness/corpus-costs/7087-tls-socket-wrap.ts.json @@ -0,0 +1 @@ +{ "plain": 4491, "san": 82505 } diff --git a/tests/harness/corpus-costs/7088-tls-socket-connect-tunnel.ts.json b/tests/harness/corpus-costs/7088-tls-socket-connect-tunnel.ts.json new file mode 100644 index 000000000..8e6e4a3d0 --- /dev/null +++ b/tests/harness/corpus-costs/7088-tls-socket-connect-tunnel.ts.json @@ -0,0 +1 @@ +{ "plain": 4100, "san": 56643 } diff --git a/tests/harness/corpus-costs/7089-http-host-header-tunnels.ts.json b/tests/harness/corpus-costs/7089-http-host-header-tunnels.ts.json new file mode 100644 index 000000000..349a68037 --- /dev/null +++ b/tests/harness/corpus-costs/7089-http-host-header-tunnels.ts.json @@ -0,0 +1 @@ +{ "plain": 3401, "san": 48875 } diff --git a/tests/harness/corpus-costs/7094-tls-socket-failed-handshakes.ts.json b/tests/harness/corpus-costs/7094-tls-socket-failed-handshakes.ts.json new file mode 100644 index 000000000..ec5193be7 --- /dev/null +++ b/tests/harness/corpus-costs/7094-tls-socket-failed-handshakes.ts.json @@ -0,0 +1 @@ +{ "plain": 2618, "san": 3905 } diff --git a/tests/harness/corpus-costs/7106-async-prefix-enter-with.ts.json b/tests/harness/corpus-costs/7106-async-prefix-enter-with.ts.json new file mode 100644 index 000000000..74a3101e8 --- /dev/null +++ b/tests/harness/corpus-costs/7106-async-prefix-enter-with.ts.json @@ -0,0 +1 @@ +{ "plain": 3100, "san": 4000 } diff --git a/tests/harness/corpus-costs/7107-for-await-context.ts.json b/tests/harness/corpus-costs/7107-for-await-context.ts.json new file mode 100644 index 000000000..111fd2885 --- /dev/null +++ b/tests/harness/corpus-costs/7107-for-await-context.ts.json @@ -0,0 +1 @@ +{ "plain": 2200, "san": 3000 } diff --git a/tests/harness/corpus-costs/7108-generator-step-context.ts.json b/tests/harness/corpus-costs/7108-generator-step-context.ts.json new file mode 100644 index 000000000..a5e618da8 --- /dev/null +++ b/tests/harness/corpus-costs/7108-generator-step-context.ts.json @@ -0,0 +1 @@ +{ "plain": 2400, "san": 3100 } diff --git a/tests/harness/corpus-costs/7109-uninitialized-let-assignment-expressions.ts.json b/tests/harness/corpus-costs/7109-uninitialized-let-assignment-expressions.ts.json new file mode 100644 index 000000000..46c7f7832 --- /dev/null +++ b/tests/harness/corpus-costs/7109-uninitialized-let-assignment-expressions.ts.json @@ -0,0 +1 @@ +{ "plain": 3300, "san": 4500 } diff --git a/tests/harness/corpus-costs/7120-webcrypto-random-uuid.ts.json b/tests/harness/corpus-costs/7120-webcrypto-random-uuid.ts.json new file mode 100644 index 000000000..ce52548ca --- /dev/null +++ b/tests/harness/corpus-costs/7120-webcrypto-random-uuid.ts.json @@ -0,0 +1 @@ +{ "plain": 4431, "san": 4365 } diff --git a/tests/harness/corpus-costs/7121-webcrypto-crypto-object.mjs.json b/tests/harness/corpus-costs/7121-webcrypto-crypto-object.mjs.json new file mode 100644 index 000000000..db431c2ca --- /dev/null +++ b/tests/harness/corpus-costs/7121-webcrypto-crypto-object.mjs.json @@ -0,0 +1 @@ +{ "plain": 5043, "san": 4705 } diff --git a/tests/harness/corpus-costs/7122-webcrypto-node-crypto.ts.json b/tests/harness/corpus-costs/7122-webcrypto-node-crypto.ts.json new file mode 100644 index 000000000..46469f2a9 --- /dev/null +++ b/tests/harness/corpus-costs/7122-webcrypto-node-crypto.ts.json @@ -0,0 +1 @@ +{ "plain": 4805, "san": 6923 } diff --git a/tests/harness/corpus-costs/7123-webcrypto-node-crypto.cjs.json b/tests/harness/corpus-costs/7123-webcrypto-node-crypto.cjs.json new file mode 100644 index 000000000..682ba704a --- /dev/null +++ b/tests/harness/corpus-costs/7123-webcrypto-node-crypto.cjs.json @@ -0,0 +1 @@ +{ "plain": 4728, "san": 6725 } diff --git a/tests/harness/corpus-costs/7124-webcrypto-secret-keys.ts.json b/tests/harness/corpus-costs/7124-webcrypto-secret-keys.ts.json new file mode 100644 index 000000000..73f1ce847 --- /dev/null +++ b/tests/harness/corpus-costs/7124-webcrypto-secret-keys.ts.json @@ -0,0 +1 @@ +{ "plain": 5860, "san": 9241 } diff --git a/tests/harness/corpus-costs/7125-webcrypto-key-errors.mjs.json b/tests/harness/corpus-costs/7125-webcrypto-key-errors.mjs.json new file mode 100644 index 000000000..ceff344eb --- /dev/null +++ b/tests/harness/corpus-costs/7125-webcrypto-key-errors.mjs.json @@ -0,0 +1 @@ +{ "plain": 6582, "san": 9054 } diff --git a/tests/harness/corpus-costs/7126-webcrypto-aes.ts.json b/tests/harness/corpus-costs/7126-webcrypto-aes.ts.json new file mode 100644 index 000000000..b1680985c --- /dev/null +++ b/tests/harness/corpus-costs/7126-webcrypto-aes.ts.json @@ -0,0 +1 @@ +{ "plain": 4563, "san": 6500 } diff --git a/tests/harness/corpus-costs/7127-webcrypto-aes-errors.mjs.json b/tests/harness/corpus-costs/7127-webcrypto-aes-errors.mjs.json new file mode 100644 index 000000000..1ebb743b0 --- /dev/null +++ b/tests/harness/corpus-costs/7127-webcrypto-aes-errors.mjs.json @@ -0,0 +1 @@ +{ "plain": 4385, "san": 8939 } diff --git a/tests/harness/corpus-costs/7128-webcrypto-derive.ts.json b/tests/harness/corpus-costs/7128-webcrypto-derive.ts.json new file mode 100644 index 000000000..2888d22eb --- /dev/null +++ b/tests/harness/corpus-costs/7128-webcrypto-derive.ts.json @@ -0,0 +1 @@ +{ "plain": 5042, "san": 9143 } diff --git a/tests/harness/corpus-costs/7129-webcrypto-derive-errors.mjs.json b/tests/harness/corpus-costs/7129-webcrypto-derive-errors.mjs.json new file mode 100644 index 000000000..b2f70bf57 --- /dev/null +++ b/tests/harness/corpus-costs/7129-webcrypto-derive-errors.mjs.json @@ -0,0 +1 @@ +{ "plain": 5549, "san": 7441 } diff --git a/tests/harness/corpus-costs/7130-typed-message-listeners.ts.json b/tests/harness/corpus-costs/7130-typed-message-listeners.ts.json new file mode 100644 index 000000000..bf7b0d199 --- /dev/null +++ b/tests/harness/corpus-costs/7130-typed-message-listeners.ts.json @@ -0,0 +1 @@ +{ "plain": 2200, "san": 2200 } diff --git a/tests/harness/corpus-costs/7130-webcrypto-wrap-key.ts.json b/tests/harness/corpus-costs/7130-webcrypto-wrap-key.ts.json new file mode 100644 index 000000000..56b3458ca --- /dev/null +++ b/tests/harness/corpus-costs/7130-webcrypto-wrap-key.ts.json @@ -0,0 +1 @@ +{ "plain": 5334, "san": 8182 } diff --git a/tests/harness/corpus-costs/7131-typed-worker-messages.ts.json b/tests/harness/corpus-costs/7131-typed-worker-messages.ts.json new file mode 100644 index 000000000..953e2af8f --- /dev/null +++ b/tests/harness/corpus-costs/7131-typed-worker-messages.ts.json @@ -0,0 +1 @@ +{ "plain": 1700, "san": 1600 } diff --git a/tests/harness/corpus-costs/7131-webcrypto-wrap-key-errors.mjs.json b/tests/harness/corpus-costs/7131-webcrypto-wrap-key-errors.mjs.json new file mode 100644 index 000000000..5cb958a53 --- /dev/null +++ b/tests/harness/corpus-costs/7131-webcrypto-wrap-key-errors.mjs.json @@ -0,0 +1 @@ +{ "plain": 5838, "san": 8032 } diff --git a/tests/harness/corpus-costs/7132-jose-pbes2/main.mjs.json b/tests/harness/corpus-costs/7132-jose-pbes2/main.mjs.json new file mode 100644 index 000000000..3ad38d83d --- /dev/null +++ b/tests/harness/corpus-costs/7132-jose-pbes2/main.mjs.json @@ -0,0 +1 @@ +{ "plain": 30866, "san": 122276 } diff --git a/tests/harness/corpus-costs/7139-message-typed-records.ts.json b/tests/harness/corpus-costs/7139-message-typed-records.ts.json new file mode 100644 index 000000000..f0ed6cbc2 --- /dev/null +++ b/tests/harness/corpus-costs/7139-message-typed-records.ts.json @@ -0,0 +1 @@ +{ "plain": 4300, "san": 4400 } diff --git a/tests/harness/corpus-costs/7141-comoving-loop-counters.ts.json b/tests/harness/corpus-costs/7141-comoving-loop-counters.ts.json new file mode 100644 index 000000000..7c0606885 --- /dev/null +++ b/tests/harness/corpus-costs/7141-comoving-loop-counters.ts.json @@ -0,0 +1 @@ +{ "plain": 4260, "san": 6600 } diff --git a/tests/harness/corpus-costs/7142-array-read-filled-prefix.ts.json b/tests/harness/corpus-costs/7142-array-read-filled-prefix.ts.json new file mode 100644 index 000000000..c7b8ddd23 --- /dev/null +++ b/tests/harness/corpus-costs/7142-array-read-filled-prefix.ts.json @@ -0,0 +1 @@ +{ "plain": 3600, "san": 5600 } diff --git a/tests/harness/corpus-costs/7143-optional-read-integer-index.ts.json b/tests/harness/corpus-costs/7143-optional-read-integer-index.ts.json new file mode 100644 index 000000000..16148d8ce --- /dev/null +++ b/tests/harness/corpus-costs/7143-optional-read-integer-index.ts.json @@ -0,0 +1 @@ +{ "plain": 3500, "san": 5400 } diff --git a/tests/harness/corpus-costs/7150-cipher-legacy-modes.ts.json b/tests/harness/corpus-costs/7150-cipher-legacy-modes.ts.json new file mode 100644 index 000000000..40196decf --- /dev/null +++ b/tests/harness/corpus-costs/7150-cipher-legacy-modes.ts.json @@ -0,0 +1 @@ +{ "plain": 6099, "san": 8251 } diff --git a/tests/harness/corpus-costs/7151-cipher-legacy-errors.cjs.json b/tests/harness/corpus-costs/7151-cipher-legacy-errors.cjs.json new file mode 100644 index 000000000..6a82dd081 --- /dev/null +++ b/tests/harness/corpus-costs/7151-cipher-legacy-errors.cjs.json @@ -0,0 +1 @@ +{ "plain": 7845, "san": 9581 } diff --git a/tests/harness/corpus-costs/7152-crypto-prime.ts.json b/tests/harness/corpus-costs/7152-crypto-prime.ts.json new file mode 100644 index 000000000..4df2be436 --- /dev/null +++ b/tests/harness/corpus-costs/7152-crypto-prime.ts.json @@ -0,0 +1 @@ +{ "plain": 7273, "san": 10284 } diff --git a/tests/harness/corpus-costs/7153-crypto-prime-errors.cjs.json b/tests/harness/corpus-costs/7153-crypto-prime-errors.cjs.json new file mode 100644 index 000000000..d20dc198a --- /dev/null +++ b/tests/harness/corpus-costs/7153-crypto-prime-errors.cjs.json @@ -0,0 +1 @@ +{ "plain": 5893, "san": 5691 } diff --git a/tests/harness/corpus-costs/7180-generic-local-binding-early-uses.ts.json b/tests/harness/corpus-costs/7180-generic-local-binding-early-uses.ts.json new file mode 100644 index 000000000..929b49d23 --- /dev/null +++ b/tests/harness/corpus-costs/7180-generic-local-binding-early-uses.ts.json @@ -0,0 +1 @@ +{ "plain": 2542, "san": 2911 } diff --git a/tests/harness/corpus-costs/7181-generic-module-binding-tdz.ts.json b/tests/harness/corpus-costs/7181-generic-module-binding-tdz.ts.json new file mode 100644 index 000000000..321663d8b --- /dev/null +++ b/tests/harness/corpus-costs/7181-generic-module-binding-tdz.ts.json @@ -0,0 +1 @@ +{ "plain": 2500, "san": 2870 } diff --git a/tests/harness/corpus-costs/7182-generic-binding-direct-calls.ts.json b/tests/harness/corpus-costs/7182-generic-binding-direct-calls.ts.json new file mode 100644 index 000000000..e9da8d46e --- /dev/null +++ b/tests/harness/corpus-costs/7182-generic-binding-direct-calls.ts.json @@ -0,0 +1 @@ +{ "plain": 2686, "san": 3069 } diff --git a/tests/harness/corpus-costs/7183-local-class-heritage-effects.ts.json b/tests/harness/corpus-costs/7183-local-class-heritage-effects.ts.json new file mode 100644 index 000000000..6bcb3bc35 --- /dev/null +++ b/tests/harness/corpus-costs/7183-local-class-heritage-effects.ts.json @@ -0,0 +1 @@ +{ "plain": 2573, "san": 3208 } diff --git a/tests/harness/corpus-costs/7184-reduce-runtime-accumulator.ts.json b/tests/harness/corpus-costs/7184-reduce-runtime-accumulator.ts.json new file mode 100644 index 000000000..c480bea3f --- /dev/null +++ b/tests/harness/corpus-costs/7184-reduce-runtime-accumulator.ts.json @@ -0,0 +1 @@ +{ "plain": 2541, "san": 3260 } diff --git a/tests/harness/corpus-costs/7185-array-callback-arguments-length.ts.json b/tests/harness/corpus-costs/7185-array-callback-arguments-length.ts.json new file mode 100644 index 000000000..b86a9e70a --- /dev/null +++ b/tests/harness/corpus-costs/7185-array-callback-arguments-length.ts.json @@ -0,0 +1 @@ +{ "plain": 2528, "san": 3201 } diff --git a/tests/harness/corpus-costs/7240-objectmode-streams.ts.json b/tests/harness/corpus-costs/7240-objectmode-streams.ts.json new file mode 100644 index 000000000..2695df1a4 --- /dev/null +++ b/tests/harness/corpus-costs/7240-objectmode-streams.ts.json @@ -0,0 +1 @@ +{ "plain": 2084, "san": 2980 } diff --git a/tests/harness/corpus-costs/7241-objectmode-streams.mjs.json b/tests/harness/corpus-costs/7241-objectmode-streams.mjs.json new file mode 100644 index 000000000..bd04ea049 --- /dev/null +++ b/tests/harness/corpus-costs/7241-objectmode-streams.mjs.json @@ -0,0 +1 @@ +{ "plain": 2190, "san": 3093 } diff --git a/tests/harness/corpus-costs/7242-objectmode-dynamic.cjs.json b/tests/harness/corpus-costs/7242-objectmode-dynamic.cjs.json new file mode 100644 index 000000000..3bc4d9211 --- /dev/null +++ b/tests/harness/corpus-costs/7242-objectmode-dynamic.cjs.json @@ -0,0 +1 @@ +{ "plain": 2430, "san": 3287 } diff --git a/tests/harness/corpus-costs/7243-for-await-close-order.mjs.json b/tests/harness/corpus-costs/7243-for-await-close-order.mjs.json new file mode 100644 index 000000000..e5826334d --- /dev/null +++ b/tests/harness/corpus-costs/7243-for-await-close-order.mjs.json @@ -0,0 +1 @@ +{ "plain": 2402, "san": 3174 } diff --git a/tests/harness/corpus-costs/7244-objectmode-subclasses.ts.json b/tests/harness/corpus-costs/7244-objectmode-subclasses.ts.json new file mode 100644 index 000000000..d555a94ab --- /dev/null +++ b/tests/harness/corpus-costs/7244-objectmode-subclasses.ts.json @@ -0,0 +1 @@ +{ "plain": 1917, "san": 2782 } diff --git a/tests/harness/corpus-costs/7245-writable-callback-order.mjs.json b/tests/harness/corpus-costs/7245-writable-callback-order.mjs.json new file mode 100644 index 000000000..0226cbb35 --- /dev/null +++ b/tests/harness/corpus-costs/7245-writable-callback-order.mjs.json @@ -0,0 +1 @@ +{ "plain": 2144, "san": 2747 } diff --git a/tests/harness/corpus-costs/7246-stream-construct.ts.json b/tests/harness/corpus-costs/7246-stream-construct.ts.json new file mode 100644 index 000000000..d94320c7e --- /dev/null +++ b/tests/harness/corpus-costs/7246-stream-construct.ts.json @@ -0,0 +1 @@ +{ "plain": 2327, "san": 3064 } diff --git a/tests/harness/corpus-costs/7247-stream-construct.mjs.json b/tests/harness/corpus-costs/7247-stream-construct.mjs.json new file mode 100644 index 000000000..a74da86c8 --- /dev/null +++ b/tests/harness/corpus-costs/7247-stream-construct.mjs.json @@ -0,0 +1 @@ +{ "plain": 2834, "san": 3538 } diff --git a/tests/harness/corpus-costs/7248-stream-writev.ts.json b/tests/harness/corpus-costs/7248-stream-writev.ts.json new file mode 100644 index 000000000..83ccdb03d --- /dev/null +++ b/tests/harness/corpus-costs/7248-stream-writev.ts.json @@ -0,0 +1 @@ +{ "plain": 2294, "san": 3026 } diff --git a/tests/harness/corpus-costs/7249-buffer-index-of-candidates.ts.json b/tests/harness/corpus-costs/7249-buffer-index-of-candidates.ts.json new file mode 100644 index 000000000..5c265ea01 --- /dev/null +++ b/tests/harness/corpus-costs/7249-buffer-index-of-candidates.ts.json @@ -0,0 +1 @@ +{ "plain": 2870, "san": 3656 } diff --git a/tests/harness/corpus-costs/7249-stream-writev.cjs.json b/tests/harness/corpus-costs/7249-stream-writev.cjs.json new file mode 100644 index 000000000..2fc75720e --- /dev/null +++ b/tests/harness/corpus-costs/7249-stream-writev.cjs.json @@ -0,0 +1 @@ +{ "plain": 2640, "san": 2765 } diff --git a/tests/harness/corpus-costs/7250-stream-decode-strings.ts.json b/tests/harness/corpus-costs/7250-stream-decode-strings.ts.json new file mode 100644 index 000000000..b6c0a39a0 --- /dev/null +++ b/tests/harness/corpus-costs/7250-stream-decode-strings.ts.json @@ -0,0 +1 @@ +{ "plain": 2016, "san": 2519 } diff --git a/tests/harness/corpus-costs/7251-stream-write-encodings.mjs.json b/tests/harness/corpus-costs/7251-stream-write-encodings.mjs.json new file mode 100644 index 000000000..7e459d978 --- /dev/null +++ b/tests/harness/corpus-costs/7251-stream-write-encodings.mjs.json @@ -0,0 +1 @@ +{ "plain": 2161, "san": 2661 } diff --git a/tests/harness/corpus-costs/7252-duplex-from-generator.ts.json b/tests/harness/corpus-costs/7252-duplex-from-generator.ts.json new file mode 100644 index 000000000..47f7b9ed9 --- /dev/null +++ b/tests/harness/corpus-costs/7252-duplex-from-generator.ts.json @@ -0,0 +1 @@ +{ "plain": 2522, "san": 3330 } diff --git a/tests/harness/corpus-costs/7253-duplex-from.mjs.json b/tests/harness/corpus-costs/7253-duplex-from.mjs.json new file mode 100644 index 000000000..7743ca7c8 --- /dev/null +++ b/tests/harness/corpus-costs/7253-duplex-from.mjs.json @@ -0,0 +1 @@ +{ "plain": 1849, "san": 2440 } diff --git a/tests/harness/corpus-costs/7254-compose-functions.ts.json b/tests/harness/corpus-costs/7254-compose-functions.ts.json new file mode 100644 index 000000000..19d896024 --- /dev/null +++ b/tests/harness/corpus-costs/7254-compose-functions.ts.json @@ -0,0 +1 @@ +{ "plain": 1782, "san": 2350 } diff --git a/tests/harness/corpus-costs/7255-compose-stages.mjs.json b/tests/harness/corpus-costs/7255-compose-stages.mjs.json new file mode 100644 index 000000000..e8e0ab3d1 --- /dev/null +++ b/tests/harness/corpus-costs/7255-compose-stages.mjs.json @@ -0,0 +1 @@ +{ "plain": 2033, "san": 2680 } diff --git a/tests/harness/corpus-costs/7256-readable-compose.mjs.json b/tests/harness/corpus-costs/7256-readable-compose.mjs.json new file mode 100644 index 000000000..fe1307a1f --- /dev/null +++ b/tests/harness/corpus-costs/7256-readable-compose.mjs.json @@ -0,0 +1 @@ +{ "plain": 2146, "san": 2830 } diff --git a/tests/harness/corpus-costs/7257-pipeline-generator-destination.mjs.json b/tests/harness/corpus-costs/7257-pipeline-generator-destination.mjs.json new file mode 100644 index 000000000..ebaa9214c --- /dev/null +++ b/tests/harness/corpus-costs/7257-pipeline-generator-destination.mjs.json @@ -0,0 +1 @@ +{ "plain": 2008, "san": 2731 } diff --git a/tests/harness/corpus-costs/7258-pipeline-generator-destination.ts.json b/tests/harness/corpus-costs/7258-pipeline-generator-destination.ts.json new file mode 100644 index 000000000..15ff27f21 --- /dev/null +++ b/tests/harness/corpus-costs/7258-pipeline-generator-destination.ts.json @@ -0,0 +1 @@ +{ "plain": 1751, "san": 2442 } diff --git a/tests/harness/corpus-costs/7259-promises-pipeline-stage-options.cjs.json b/tests/harness/corpus-costs/7259-promises-pipeline-stage-options.cjs.json new file mode 100644 index 000000000..6bda6d818 --- /dev/null +++ b/tests/harness/corpus-costs/7259-promises-pipeline-stage-options.cjs.json @@ -0,0 +1 @@ +{ "plain": 2504, "san": 3707 } diff --git a/tests/harness/corpus-costs/7261-acyclic-result-builders.ts.json b/tests/harness/corpus-costs/7261-acyclic-result-builders.ts.json new file mode 100644 index 000000000..30b7c116f --- /dev/null +++ b/tests/harness/corpus-costs/7261-acyclic-result-builders.ts.json @@ -0,0 +1 @@ +{ "plain": 3336, "san": 4712 } diff --git a/tests/harness/corpus-costs/7280-named-reads-hole-receivers.ts.json b/tests/harness/corpus-costs/7280-named-reads-hole-receivers.ts.json new file mode 100644 index 000000000..db9f23551 --- /dev/null +++ b/tests/harness/corpus-costs/7280-named-reads-hole-receivers.ts.json @@ -0,0 +1 @@ +{ "plain": 4700, "san": 2400 } diff --git a/tests/harness/corpus-costs/7300-callback-captured-scalars.ts.json b/tests/harness/corpus-costs/7300-callback-captured-scalars.ts.json new file mode 100644 index 000000000..18495cd4e --- /dev/null +++ b/tests/harness/corpus-costs/7300-callback-captured-scalars.ts.json @@ -0,0 +1 @@ +{ "plain": 6000, "san": 7900 } diff --git a/tests/harness/corpus-costs/7301-running-extrema-branches.ts.json b/tests/harness/corpus-costs/7301-running-extrema-branches.ts.json new file mode 100644 index 000000000..74df88f0c --- /dev/null +++ b/tests/harness/corpus-costs/7301-running-extrema-branches.ts.json @@ -0,0 +1 @@ +{ "plain": 5300, "san": 5800 } diff --git a/tests/harness/corpus-costs/7302-string-scan-loop-versions.ts.json b/tests/harness/corpus-costs/7302-string-scan-loop-versions.ts.json new file mode 100644 index 000000000..793171eba --- /dev/null +++ b/tests/harness/corpus-costs/7302-string-scan-loop-versions.ts.json @@ -0,0 +1 @@ +{ "plain": 4000, "san": 6300 } diff --git a/tests/harness/corpus-costs/7303-string-char-loop-versions.ts.json b/tests/harness/corpus-costs/7303-string-char-loop-versions.ts.json new file mode 100644 index 000000000..0c31a05f7 --- /dev/null +++ b/tests/harness/corpus-costs/7303-string-char-loop-versions.ts.json @@ -0,0 +1 @@ +{ "plain": 3000, "san": 4000 } diff --git a/tests/harness/corpus-costs/7320-array-dense-loop-invariant-limits.ts.json b/tests/harness/corpus-costs/7320-array-dense-loop-invariant-limits.ts.json new file mode 100644 index 000000000..2ea93101c --- /dev/null +++ b/tests/harness/corpus-costs/7320-array-dense-loop-invariant-limits.ts.json @@ -0,0 +1 @@ +{ "plain": 2600, "san": 31600 } diff --git a/tests/harness/corpus-costs/7321-speculative-loop-bail-sites.ts.json b/tests/harness/corpus-costs/7321-speculative-loop-bail-sites.ts.json new file mode 100644 index 000000000..1e5609a66 --- /dev/null +++ b/tests/harness/corpus-costs/7321-speculative-loop-bail-sites.ts.json @@ -0,0 +1 @@ +{ "plain": 2000, "san": 2600 } diff --git a/tests/harness/corpus-costs/7322-union-scalar-equality.ts.json b/tests/harness/corpus-costs/7322-union-scalar-equality.ts.json new file mode 100644 index 000000000..2df20a0ed --- /dev/null +++ b/tests/harness/corpus-costs/7322-union-scalar-equality.ts.json @@ -0,0 +1 @@ +{ "plain": 2100, "san": 2800 } diff --git a/tests/harness/corpus-costs/7323-loop-bound-parameter-versions.ts.json b/tests/harness/corpus-costs/7323-loop-bound-parameter-versions.ts.json new file mode 100644 index 000000000..ee18f5f11 --- /dev/null +++ b/tests/harness/corpus-costs/7323-loop-bound-parameter-versions.ts.json @@ -0,0 +1 @@ +{ "plain": 2000, "san": 2800 } diff --git a/tests/harness/corpus-costs/7324-loop-bound-parameter-window-sums.ts.json b/tests/harness/corpus-costs/7324-loop-bound-parameter-window-sums.ts.json new file mode 100644 index 000000000..9622c5beb --- /dev/null +++ b/tests/harness/corpus-costs/7324-loop-bound-parameter-window-sums.ts.json @@ -0,0 +1 @@ +{ "plain": 2000, "san": 3000 } diff --git a/tests/harness/corpus-costs/7360-worker-typed-records.ts.json b/tests/harness/corpus-costs/7360-worker-typed-records.ts.json new file mode 100644 index 000000000..cf0403d1d --- /dev/null +++ b/tests/harness/corpus-costs/7360-worker-typed-records.ts.json @@ -0,0 +1 @@ +{ "plain": 2700, "san": 2900 } diff --git a/tests/harness/corpus-costs/7361-message-listeners-share-value.ts.json b/tests/harness/corpus-costs/7361-message-listeners-share-value.ts.json new file mode 100644 index 000000000..c428eb8f1 --- /dev/null +++ b/tests/harness/corpus-costs/7361-message-listeners-share-value.ts.json @@ -0,0 +1 @@ +{ "plain": 3000, "san": 4600 } diff --git a/tests/harness/corpus-costs/7362-globalthis-intersection-singleton.ts.json b/tests/harness/corpus-costs/7362-globalthis-intersection-singleton.ts.json new file mode 100644 index 000000000..27b641ffe --- /dev/null +++ b/tests/harness/corpus-costs/7362-globalthis-intersection-singleton.ts.json @@ -0,0 +1 @@ +{ "plain": 2900, "san": 3200 } diff --git a/tests/harness/corpus-costs/7363-json-stringify-live-capsules.ts.json b/tests/harness/corpus-costs/7363-json-stringify-live-capsules.ts.json new file mode 100644 index 000000000..27b641ffe --- /dev/null +++ b/tests/harness/corpus-costs/7363-json-stringify-live-capsules.ts.json @@ -0,0 +1 @@ +{ "plain": 2900, "san": 3200 } diff --git a/tests/harness/corpus-costs/7380-iterable-values.ts.json b/tests/harness/corpus-costs/7380-iterable-values.ts.json new file mode 100644 index 000000000..87569618d --- /dev/null +++ b/tests/harness/corpus-costs/7380-iterable-values.ts.json @@ -0,0 +1 @@ +{ "plain": 4000, "san": 6000 } diff --git a/tests/harness/corpus-costs/7381-iterable-forof-semantics.ts.json b/tests/harness/corpus-costs/7381-iterable-forof-semantics.ts.json new file mode 100644 index 000000000..87569618d --- /dev/null +++ b/tests/harness/corpus-costs/7381-iterable-forof-semantics.ts.json @@ -0,0 +1 @@ +{ "plain": 4000, "san": 6000 } diff --git a/tests/harness/corpus-costs/7382-iterable-generic-repository.ts.json b/tests/harness/corpus-costs/7382-iterable-generic-repository.ts.json new file mode 100644 index 000000000..87569618d --- /dev/null +++ b/tests/harness/corpus-costs/7382-iterable-generic-repository.ts.json @@ -0,0 +1 @@ +{ "plain": 4000, "san": 6000 } diff --git a/tests/harness/corpus-costs/7383-iterable-union-sources.ts.json b/tests/harness/corpus-costs/7383-iterable-union-sources.ts.json new file mode 100644 index 000000000..87569618d --- /dev/null +++ b/tests/harness/corpus-costs/7383-iterable-union-sources.ts.json @@ -0,0 +1 @@ +{ "plain": 4000, "san": 6000 } diff --git a/tests/harness/corpus-costs/7400-record-keyof-union-read.ts.json b/tests/harness/corpus-costs/7400-record-keyof-union-read.ts.json new file mode 100644 index 000000000..9b72eaf8d --- /dev/null +++ b/tests/harness/corpus-costs/7400-record-keyof-union-read.ts.json @@ -0,0 +1 @@ +{ "plain": 2600, "san": 20500 } diff --git a/tests/harness/corpus-costs/7401-any-spread-into-typed-literal.ts.json b/tests/harness/corpus-costs/7401-any-spread-into-typed-literal.ts.json new file mode 100644 index 000000000..9eb118813 --- /dev/null +++ b/tests/harness/corpus-costs/7401-any-spread-into-typed-literal.ts.json @@ -0,0 +1 @@ +{ "plain": 2600, "san": 20000 } diff --git a/tests/harness/corpus-costs/7401-program-lifetime-array-teardown.ts.json b/tests/harness/corpus-costs/7401-program-lifetime-array-teardown.ts.json new file mode 100644 index 000000000..2741c4d83 --- /dev/null +++ b/tests/harness/corpus-costs/7401-program-lifetime-array-teardown.ts.json @@ -0,0 +1 @@ +{ "plain": 3103, "san": 4147 } diff --git a/tests/harness/corpus-costs/7420-for-await-close.ts.json b/tests/harness/corpus-costs/7420-for-await-close.ts.json new file mode 100644 index 000000000..2df20a0ed --- /dev/null +++ b/tests/harness/corpus-costs/7420-for-await-close.ts.json @@ -0,0 +1 @@ +{ "plain": 2100, "san": 2800 } diff --git a/tests/harness/corpus-costs/7421-for-await-close.mjs.json b/tests/harness/corpus-costs/7421-for-await-close.mjs.json new file mode 100644 index 000000000..cb701dc93 --- /dev/null +++ b/tests/harness/corpus-costs/7421-for-await-close.mjs.json @@ -0,0 +1 @@ +{ "plain": 1900, "san": 2600 } diff --git a/tests/harness/corpus-costs/7422-for-await-untyped-streams.mjs.json b/tests/harness/corpus-costs/7422-for-await-untyped-streams.mjs.json new file mode 100644 index 000000000..cb701dc93 --- /dev/null +++ b/tests/harness/corpus-costs/7422-for-await-untyped-streams.mjs.json @@ -0,0 +1 @@ +{ "plain": 1900, "san": 2600 } diff --git a/tests/harness/corpus-costs/7423-stream-untyped-bindings.mjs.json b/tests/harness/corpus-costs/7423-stream-untyped-bindings.mjs.json new file mode 100644 index 000000000..d2ac5db99 --- /dev/null +++ b/tests/harness/corpus-costs/7423-stream-untyped-bindings.mjs.json @@ -0,0 +1 @@ +{ "plain": 4900, "san": 6454 } diff --git a/tests/harness/corpus-costs/7424-duplex-from-streams.mjs.json b/tests/harness/corpus-costs/7424-duplex-from-streams.mjs.json new file mode 100644 index 000000000..14a2052b9 --- /dev/null +++ b/tests/harness/corpus-costs/7424-duplex-from-streams.mjs.json @@ -0,0 +1 @@ +{ "plain": 2607, "san": 3440 } diff --git a/tests/harness/corpus-costs/7425-duplex-from-streams.ts.json b/tests/harness/corpus-costs/7425-duplex-from-streams.ts.json new file mode 100644 index 000000000..9dde8d70e --- /dev/null +++ b/tests/harness/corpus-costs/7425-duplex-from-streams.ts.json @@ -0,0 +1 @@ +{ "plain": 2009, "san": 2743 } diff --git a/tests/harness/corpus-costs/7426-duplex-from-promise.mjs.json b/tests/harness/corpus-costs/7426-duplex-from-promise.mjs.json new file mode 100644 index 000000000..9195268ab --- /dev/null +++ b/tests/harness/corpus-costs/7426-duplex-from-promise.mjs.json @@ -0,0 +1 @@ +{ "plain": 1877, "san": 2357 } diff --git a/tests/harness/corpus-costs/7427-duplex-from-async-function.mjs.json b/tests/harness/corpus-costs/7427-duplex-from-async-function.mjs.json new file mode 100644 index 000000000..c572d9930 --- /dev/null +++ b/tests/harness/corpus-costs/7427-duplex-from-async-function.mjs.json @@ -0,0 +1 @@ +{ "plain": 1811, "san": 2417 } diff --git a/tests/harness/corpus-costs/7428-web-stream-sources.mjs.json b/tests/harness/corpus-costs/7428-web-stream-sources.mjs.json new file mode 100644 index 000000000..e95faaa64 --- /dev/null +++ b/tests/harness/corpus-costs/7428-web-stream-sources.mjs.json @@ -0,0 +1 @@ +{ "plain": 1829, "san": 2414 } diff --git a/tests/harness/corpus-costs/7429-web-stream-sources.ts.json b/tests/harness/corpus-costs/7429-web-stream-sources.ts.json new file mode 100644 index 000000000..6b14e36cc --- /dev/null +++ b/tests/harness/corpus-costs/7429-web-stream-sources.ts.json @@ -0,0 +1 @@ +{ "plain": 1250, "san": 3013 } diff --git a/tests/harness/corpus-costs/7430-readable-from-web.mjs.json b/tests/harness/corpus-costs/7430-readable-from-web.mjs.json new file mode 100644 index 000000000..2266382b4 --- /dev/null +++ b/tests/harness/corpus-costs/7430-readable-from-web.mjs.json @@ -0,0 +1 @@ +{ "plain": 3342, "san": 4411 } diff --git a/tests/harness/corpus-costs/7431-readable-from-web.ts.json b/tests/harness/corpus-costs/7431-readable-from-web.ts.json new file mode 100644 index 000000000..05fab8e59 --- /dev/null +++ b/tests/harness/corpus-costs/7431-readable-from-web.ts.json @@ -0,0 +1 @@ +{ "plain": 1956, "san": 2929 } diff --git a/tests/harness/corpus-costs/7432-readable-push-views.mjs.json b/tests/harness/corpus-costs/7432-readable-push-views.mjs.json new file mode 100644 index 000000000..8a2f5280e --- /dev/null +++ b/tests/harness/corpus-costs/7432-readable-push-views.mjs.json @@ -0,0 +1 @@ +{ "plain": 1582, "san": 2088 } diff --git a/tests/harness/corpus-costs/7433-readable-operator-signal.mjs.json b/tests/harness/corpus-costs/7433-readable-operator-signal.mjs.json new file mode 100644 index 000000000..3ef40f751 --- /dev/null +++ b/tests/harness/corpus-costs/7433-readable-operator-signal.mjs.json @@ -0,0 +1 @@ +{ "plain": 3885, "san": 5128 } diff --git a/tests/harness/corpus-costs/7434-readable-operator-values.ts.json b/tests/harness/corpus-costs/7434-readable-operator-values.ts.json new file mode 100644 index 000000000..fdbfd8cde --- /dev/null +++ b/tests/harness/corpus-costs/7434-readable-operator-values.ts.json @@ -0,0 +1 @@ +{ "plain": 2465, "san": 2933 } diff --git a/tests/harness/corpus-costs/7435-readable-flatmap-iterables.mjs.json b/tests/harness/corpus-costs/7435-readable-flatmap-iterables.mjs.json new file mode 100644 index 000000000..8c31cc905 --- /dev/null +++ b/tests/harness/corpus-costs/7435-readable-flatmap-iterables.mjs.json @@ -0,0 +1 @@ +{ "plain": 2265, "san": 2990 } diff --git a/tests/harness/corpus-costs/7436-readable-read-any-value.mjs.json b/tests/harness/corpus-costs/7436-readable-read-any-value.mjs.json new file mode 100644 index 000000000..c4a7cbc84 --- /dev/null +++ b/tests/harness/corpus-costs/7436-readable-read-any-value.mjs.json @@ -0,0 +1 @@ +{ "plain": 1675, "san": 2211 } diff --git a/tests/harness/corpus-costs/7437-duplex-from-signal.mjs.json b/tests/harness/corpus-costs/7437-duplex-from-signal.mjs.json new file mode 100644 index 000000000..dfbf933f4 --- /dev/null +++ b/tests/harness/corpus-costs/7437-duplex-from-signal.mjs.json @@ -0,0 +1 @@ +{ "plain": 2383, "san": 3146 } diff --git a/tests/harness/corpus-costs/7438-duplex-from-signal.ts.json b/tests/harness/corpus-costs/7438-duplex-from-signal.ts.json new file mode 100644 index 000000000..13b6f4240 --- /dev/null +++ b/tests/harness/corpus-costs/7438-duplex-from-signal.ts.json @@ -0,0 +1 @@ +{ "plain": 1777, "san": 2722 } diff --git a/tests/harness/corpus-costs/7439-readable-read-string-chunks.ts.json b/tests/harness/corpus-costs/7439-readable-read-string-chunks.ts.json new file mode 100644 index 000000000..a93aa2e95 --- /dev/null +++ b/tests/harness/corpus-costs/7439-readable-read-string-chunks.ts.json @@ -0,0 +1 @@ +{ "plain": 2578, "san": 3403 } diff --git a/tests/harness/corpus-costs/7440-fromentries-aliased-entries.ts.json b/tests/harness/corpus-costs/7440-fromentries-aliased-entries.ts.json new file mode 100644 index 000000000..87569618d --- /dev/null +++ b/tests/harness/corpus-costs/7440-fromentries-aliased-entries.ts.json @@ -0,0 +1 @@ +{ "plain": 4000, "san": 6000 } diff --git a/tests/harness/corpus-costs/7480-class-call-without-new.ts.json b/tests/harness/corpus-costs/7480-class-call-without-new.ts.json new file mode 100644 index 000000000..f14d666a4 --- /dev/null +++ b/tests/harness/corpus-costs/7480-class-call-without-new.ts.json @@ -0,0 +1 @@ +{ "plain": 3114, "san": 2571 } diff --git a/tests/harness/corpus-costs/7481-class-call-without-new.mjs.json b/tests/harness/corpus-costs/7481-class-call-without-new.mjs.json new file mode 100644 index 000000000..cecf59f78 --- /dev/null +++ b/tests/harness/corpus-costs/7481-class-call-without-new.mjs.json @@ -0,0 +1 @@ +{ "plain": 2315, "san": 2145 } diff --git a/tests/harness/corpus-costs/class-quoted-accessor-keys.mjs.json b/tests/harness/corpus-costs/class-quoted-accessor-keys.mjs.json new file mode 100644 index 000000000..81da85b90 --- /dev/null +++ b/tests/harness/corpus-costs/class-quoted-accessor-keys.mjs.json @@ -0,0 +1 @@ +{ "plain": 3900, "san": 4000 } diff --git a/tests/harness/coverage.test.ts b/tests/harness/coverage.test.ts index 86d202b46..3ed562aea 100644 --- a/tests/harness/coverage.test.ts +++ b/tests/harness/coverage.test.ts @@ -182,6 +182,57 @@ test("statements of a signature-blocked function count as not static", () => { expect(coverage.stats.statementsFailed + (un?.statementsFailed ?? 0)).toBe(5); }); +test("the body of a signature-blocked function reports its diagnostics", () => { + const { coverage } = analyze(fixture("blocked-signature-body.ts")); + const sites = (diags: readonly { code: string; message: string }[]) => + diags.map((d) => `${d.code} ${d.message}`).sort(); + // measure is called: its body's diagnostics join the reached ones. + expect(sites(coverage.diagnostics)).toEqual([ + "SC2004 uses of 'extra' inherit the blocker on its declaration", + "SC2004 uses of 'measure' inherit the blocker on its declaration", + "SC2004 uses of 'target' inherit the blocker on its declaration", + "SC2020 'WeakRef' is part of the standard library types but has no scriptc lowering yet", + "SC2020 'new WeakRef' is part of the standard library types but has no scriptc lowering yet", + ]); + // Nothing calls unused or described: their signatures and bodies report + // as unreached. described's declared `this` is its receiver, so + // `this.label` reports nothing. + expect(sites(coverage.unreached?.diagnostics ?? [])).toEqual([ + "SC2004 uses of 'extra' inherit the blocker on its declaration", + "SC2004 uses of 'target' inherit the blocker on its declaration", + "SC2020 'WeakRef' is part of the standard library types but has no scriptc lowering yet", + "SC2020 'WeakRef' is part of the standard library types but has no scriptc lowering yet", + "SC2020 'new WeakRef' is part of the standard library types but has no scriptc lowering yet", + ]); + // The bodies' statements still count once each, as not static. + const un = coverage.unreached?.stats; + expect(coverage.stats.functionsSkipped + (un?.functionsSkipped ?? 0)).toBe(3); + expect(coverage.stats.statementsTotal + (un?.statementsTotal ?? 0)).toBe(7); + expect(coverage.stats.statementsFailed + (un?.statementsFailed ?? 0)).toBe(7); +}); + +test("deferred fences in a module's top-level code report as running at startup", () => { + const { coverage, sourceTexts } = analyze(fixture("startup-fences.js")); + expect( + (coverage.runtimeFences ?? []).map((d) => [d.code, d.loc.start, d.startup === true]), + ).toEqual([ + ["SC1090", expect.any(Number), true], + ["SC1090", expect.any(Number), false], + ]); + const out = report(fixture("startup-fences.js")); + expect(out).toMatch( + /runs at startup {3}1 site .*\n.*instanceof against this native constructor\n\s+at tests\/coverage-fixtures\/startup-fences\.js:5:13/, + ); + expect(out).toMatch( + /deferred to runtime {3}1 site .*\n.*instanceof against this native constructor\n\s+at tests\/coverage-fixtures\/startup-fences\.js:7:10/, + ); + const envelope = coverageEnvelope(coverage, { compilerVersion: "test", sourceTexts }); + expect(envelope.diagnostics.map((d) => [d.scope, d.line, d.startup])).toEqual([ + ["deferred", 5, true], + ["deferred", 7, undefined], + ]); +}); + test("a failed unreached JavaScript statement is always explained", () => { const { coverage } = analyze(fixture("unreached-js-fence.js")); const failed = diff --git a/tests/harness/differential.test.ts b/tests/harness/differential.test.ts index b70e59c86..905f648dd 100644 --- a/tests/harness/differential.test.ts +++ b/tests/harness/differential.test.ts @@ -23,6 +23,7 @@ import ts5 from "typescript"; import { compile } from "@scriptc/compiler"; import { corpusSelect, shardSuffix } from "./shard.js"; import { oracleEnvKey } from "./oracle-env.js"; +import { tscJsxOracleEntry, wantsTscJsx } from "./jsx-oracle.js"; const execFileAsync = promisify(execFile); const repoRoot = join(import.meta.dirname, "../.."); @@ -122,6 +123,7 @@ function wantsTscDecorators(file: string): boolean { * test cache — a pure function of the program bytes and the typescript * version (both in the oracle cache key). */ function nodeOracleFile(file: string): string { + if (wantsTscJsx(directiveHead(file))) return tscJsxOracleEntry(file, cacheDir); if (!wantsTscDecorators(file)) return file; const src = readFileSync(file, "utf8"); const out = ts5.transpileModule(src, { @@ -241,7 +243,7 @@ const comptimeShim = pathToFileURL(join(import.meta.dirname, "comptime-shim.mjs" function programInputs(file: string): string[] { if (!/\/main\.(ts|js|mjs|cjs)$/.test(file)) return [file]; return [ - ...ENTRY_EXTS.flatMap((ext) => globSync(join(file, `../**/*.${ext}`))), + ...[...ENTRY_EXTS, "tsx", "jsx"].flatMap((ext) => globSync(join(file, `../**/*.${ext}`))), ...globSync(join(file, "../**/tsconfig.json")), ...globSync(join(file, "../**/package.json")), ].sort(); diff --git a/tests/harness/errors.test.ts b/tests/harness/errors.test.ts index 38749c168..6afa1780d 100644 --- a/tests/harness/errors.test.ts +++ b/tests/harness/errors.test.ts @@ -847,14 +847,110 @@ try { expect(r.exitCode).toBe(0); expect(r.stdout).toBe( "Error SC2020 The cipher 'aes-128-ccm' has no native implementation; the supported ciphers are " + - "aes-128-cbc, aes-192-cbc, aes-256-cbc, aes-128-ctr, aes-192-ctr, aes-256-ctr, aes-128-gcm, " + - "aes-192-gcm, aes-256-gcm and chacha20-poly1305\n" + + "aes-128, aes-192 and aes-256 in cbc, ctr, gcm, ecb, cfb, cfb8, cfb1 and ofb modes, des-ede3 in " + + "cbc, ecb, cfb, cfb8, cfb1 and ofb modes, des-ede in cbc, ecb, cfb and ofb modes, chacha20 and " + + "chacha20-poly1305\n" + "Error ERR_CRYPTO_UNKNOWN_CIPHER Unknown cipher\n", ); expect(r.stderr).toBe(""); }); }); +// new tls.TLSSocket reads a runtime options record: the client mode, whose +// handshake Node never starts, and members without a lowering throw the +// fence, as do sockets it cannot take over (a second wrap, and +// tls.connect({ socket }) over a socket that is still dialing). +describe("tls.TLSSocket runtime fences", () => { + test("client mode, unlowered members and sockets that cannot be taken over throw", async () => { + const r = await compileAndRun( + "tls-socket-fences", + `import { readFileSync } from "node:fs"; +import * as net from "node:net"; +import * as tls from "node:tls"; +const certs = "tests/fixtures/server/certs"; +const cert = readFileSync(\`\${certs}/localhost.pem\`); +const key = readFileSync(\`\${certs}/localhost-key.pem\`); +function report(label: string, run: () => void): void { + try { + run(); + console.log(label, "no error"); + } catch (error) { + console.log(label, (error as Error).message); + } +} +const client: Record = { cert, key }; +const session: Record = { isServer: true, cert, key, session: Buffer.alloc(1) }; +const server: Record = { isServer: true, cert, key }; +const listener = net.createServer((raw) => { + report("client mode", () => new tls.TLSSocket(raw, client)); + report("session", () => new tls.TLSSocket(raw, session)); + const wrapped = new tls.TLSSocket(raw, server); + report("twice", () => new tls.TLSSocket(raw, server)); + wrapped.destroy(); + listener.close(); +}); +listener.listen(0, () => { + const c = net.connect((listener.address() as net.AddressInfo).port, "localhost"); + report("dialing", () => tls.connect({ socket: c })); + c.on("error", () => {}); +}); +`, + ); + expect(r.stderr).toBe(""); + expect(r.stdout).toBe( + "dialing tls.connect over a socket that is not connected, or is already wrapped, is not supported yet\n" + + "client mode new tls.TLSSocket option 'isServer' has no static lowering — Node starts no handshake for a client-mode TLSSocket; tls.connect({ socket }) runs the client handshake over an open socket\n" + + "session new tls.TLSSocket option 'session' has no static lowering — isServer, cert, key, secureContext, ALPNProtocols, minVersion and maxVersion are the implemented members\n" + + "twice new tls.TLSSocket over a socket that is not connected, or is already wrapped, is not supported yet\n", + ); + }); +}); + +// With a secureContext, the TLSSocket's own options still apply: a truthy +// requestCert, which asks for client certificates this runtime does not +// verify, and SNICallback throw the fence instead of being dropped. +describe("tls.TLSSocket socket options beside a secureContext", () => { + test("requestCert and SNICallback throw the fence", async () => { + const r = await compileAndRun( + "tls-socket-context-fences", + `import { readFileSync } from "node:fs"; +import * as net from "node:net"; +import * as tls from "node:tls"; +const certs = "tests/fixtures/server/certs"; +const cert = readFileSync(\`\${certs}/localhost.pem\`); +const key = readFileSync(\`\${certs}/localhost-key.pem\`); +const context = tls.createSecureContext({ cert, key }); +function report(label: string, run: () => void): void { + try { + run(); + console.log(label, "no error"); + } catch (error) { + console.log(label, (error as Error).message); + } +} +const listener = net.createServer((raw) => { + report("requestCert", () => new tls.TLSSocket(raw, { isServer: true, secureContext: context, requestCert: true, rejectUnauthorized: true })); + report("SNICallback", () => new tls.TLSSocket(raw, { isServer: true, secureContext: context, SNICallback: (name: string, cb: (err: Error | null, ctx?: tls.SecureContext) => void) => cb(null, context) })); + report("requestCert false", () => new tls.TLSSocket(raw, { isServer: true, secureContext: context, requestCert: false, rejectUnauthorized: true }).destroy()); + listener.close(); +}); +listener.listen(0, () => { + const c = net.connect((listener.address() as net.AddressInfo).port, "localhost"); + c.on("error", () => {}); + c.on("close", () => console.log("client closed")); +}); +`, + ); + expect(r.stderr).toBe(""); + expect(r.stdout).toBe( + "requestCert new tls.TLSSocket option 'requestCert' has no static lowering — client-certificate handshakes are not modeled (SEMANTICS.md divergence 55) — requestCert stays at Node's false default\n" + + "SNICallback new tls.TLSSocket option 'SNICallback' has no static lowering — isServer, cert, key, secureContext, ALPNProtocols, minVersion and maxVersion are the implemented members\n" + + "requestCert false no error\n" + + "client closed\n", + ); + }); +}); + // A curve Node lists in crypto.getCurves() but the runtime does not // implement throws a coded SC2020 error naming the curve when the name is // computed; literal names are refused at compile time (node-types-fenced). @@ -918,6 +1014,53 @@ for (const run of [() => ecdh.getPublicKey.name, () => { ecdh.custom = 1; }]) { }); }); +// DiffieHellman primes past mbedTLS's 8192-bit limit throw a coded SC2020 +// error, as do property reads other than verifyError, property writes, and +// Object.prototype method calls on an untyped DiffieHellman. +describe("DiffieHellman runtime refusals", () => { + test("primes longer than 8192 bits throw SC2020", async () => { + const r = await compileAndRun( + "dh-long-prime", + `import { createDiffieHellman } from "node:crypto"; +const prime = Buffer.alloc(1025, 0xff); +for (const run of [() => createDiffieHellman(prime), () => createDiffieHellman(8193)]) { + try { + run(); + } catch (error) { + const e = error as Error & { code?: string }; + console.log(e.name, e.code, e.message); + } +} +console.log(createDiffieHellman(Buffer.alloc(1024, 0xff)).verifyError); +`, + ); + expect(r.exitCode).toBe(0); + const message = "DiffieHellman primes longer than 8192 bits have no native implementation"; + expect(r.stdout).toBe(`Error SC2020 ${message}\nError SC2020 ${message}\n1\n`); + expect(r.stderr).toBe(""); + }); + + test("DiffieHellman property reads, writes and Object.prototype calls throw SC2020", async () => { + const r = await compileAndRun( + "dh-properties", + `const crypto = require("node:crypto"); +const dh = crypto.getDiffieHellman("modp1"); +console.log(dh.verifyError); +for (const run of [() => dh.getPrime.name, () => { dh.verifyError = 1; }, () => dh.hasOwnProperty("verifyError")]) { + try { + run(); + } catch (e) { + console.log(e.name, e.code); + } +} +`, + "cjs", + ); + expect(r.exitCode).toBe(0); + expect(r.stdout).toBe("0\nError SC2020\nError SC2020\nError SC2020\n"); + }); +}); + // Node formats an unknown output encoding with %s, which prints a // function's source text and calls a toString the encoding's class // defines. The cipher runtime has neither, so both throw a coded SC2020 @@ -1634,14 +1777,15 @@ console.log(typeof promisePrototype, typeof promisePrototype.then, promiseProtot }); }); -// WebCrypto's native slice is HMAC importKey('raw'), sign and verify, and -// the SHA-1/SHA-2 digests. Algorithms Node recognizes outside that slice -// reject with a coded SC2020 Error instead of a Node-shaped success, and a -// JavaScript call with the 'jwk' format meets its named fence when it runs. +// WebCrypto's native slice is crypto.subtle's secret-key methods and its +// ECDSA, Ed25519 and RSA algorithms. Algorithms Node recognizes outside +// that slice reject with a coded SC2020 +// Error instead of a Node-shaped success, and a JavaScript call of a +// method outside it meets its named fence when it runs. // Node's own rejections (unknown names, bad usages) are corpus-pinned // (6292, 6294); these refusals have no Node twin, so they live here. describe("WebCrypto refusals (JS lane)", () => { - test("recognized algorithms outside the HMAC slice reject with SC2020", async () => { + test("recognized algorithms outside the lowered ones reject with SC2020", async () => { const r = await compileAndRun( "webcrypto-unsupported-algorithms", `const bytes = new TextEncoder().encode("secret"); @@ -1653,18 +1797,25 @@ async function attempt(label, run) { console.log(label, e.name, e.code, e.message); } } -await attempt("rsa", () => - crypto.subtle.importKey("raw", bytes, { name: "RSA-PSS", hash: "SHA-256" }, false, ["verify"]), -); const key = await crypto.subtle.importKey("raw", bytes, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]); -await attempt("ecdsa", () => crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, key, bytes)); +await attempt("ed448", () => crypto.subtle.sign({ name: "Ed448" }, key, bytes)); +await attempt("ecdsa with an hmac key", () => crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, key, bytes)); await attempt("sha3", () => crypto.subtle.digest("SHA3-256", bytes)); await attempt("sha3 hmac", () => crypto.subtle.importKey("raw", bytes, { name: "HMAC", hash: "SHA3-256" }, false, ["sign"]), ); -const format = JSON.parse('"jwk"'); -await attempt("computed jwk", () => - crypto.subtle.importKey(format, { kty: "oct", k: "c2VjcmV0" }, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]), +const aes = await crypto.subtle.generateKey({ name: "AES-GCM", length: 128 }, false, ["encrypt"]); +await attempt("aes-ocb", () => crypto.subtle.encrypt({ name: "AES-OCB", iv: new Uint8Array(12) }, aes, bytes)); +await attempt("ecdh bits", () => crypto.subtle.deriveBits({ name: "ECDH" }, key, 256)); +await attempt("rsa-oaep wrap", () => crypto.subtle.wrapKey("raw", key, key, { name: "RSA-OAEP" })); +const pair = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign", "verify"]); +const kw = await crypto.subtle.generateKey({ name: "AES-KW", length: 128 }, false, ["wrapKey", "unwrapKey"]); +await attempt("wrap an ecdsa key", () => crypto.subtle.wrapKey("spki", pair.publicKey, kw, "AES-KW")); +await attempt("wrap with an ecdsa key", () => crypto.subtle.wrapKey("raw", aes, pair.privateKey, "AES-KW")); +await attempt("unwrap an ecdsa key", () => + crypto.subtle.unwrapKey("spki", new Uint8Array(24), kw, "AES-KW", { name: "ECDSA", namedCurve: "P-256" }, true, [ + "verify", + ]), ); `, "mjs", @@ -1672,26 +1823,83 @@ await attempt("computed jwk", () => expect(r.exitCode).toBe(0); expect(r.stderr).toBe(""); expect(r.stdout).toBe( - "rsa Error SC2020 crypto.subtle.importKey with the RSA-PSS algorithm is not supported yet\n" + - "ecdsa Error SC2020 crypto.subtle.sign with the ECDSA algorithm is not supported yet\n" + + "ed448 Error SC2020 crypto.subtle.sign with the Ed448 algorithm is not supported yet\n" + + "ecdsa with an hmac key InvalidAccessError 15 Key algorithm mismatch\n" + "sha3 Error SC2020 crypto.subtle.digest with the SHA3-256 algorithm is not supported yet\n" + "sha3 hmac Error SC2020 crypto.subtle.importKey with the SHA3-256 algorithm is not supported yet\n" + - "computed jwk Error SC2020 crypto.subtle.importKey with the 'jwk' key format is not supported yet\n", + "aes-ocb Error SC2020 crypto.subtle.encrypt with the AES-OCB algorithm is not supported yet\n" + + "ecdh bits Error SC2020 crypto.subtle.deriveBits with the ECDH algorithm is not supported yet\n" + + "rsa-oaep wrap Error SC2020 crypto.subtle.wrapKey with the RSA-OAEP algorithm is not supported yet\n" + + "wrap an ecdsa key Error SC2020 crypto.subtle.wrapKey with an ECDSA, Ed25519 or RSA key is not supported yet\n" + + "wrap with an ecdsa key InvalidAccessError 15 Key algorithm mismatch\n" + + "unwrap an ecdsa key Error SC2020 crypto.subtle.unwrapKey with the ECDSA algorithm is not supported yet\n", ); }); - test("a literal 'jwk' import is a named fence where it runs", async () => { + test("a method outside the slice is a named fence where it runs", async () => { const r = await compileAndRun( - "webcrypto-jwk-literal", + "webcrypto-get-public-key", `console.log("before"); -await crypto.subtle.importKey("jwk", { kty: "oct", k: "c2VjcmV0" }, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]); +const key = await crypto.subtle.generateKey({ name: "HMAC", hash: "SHA-256" }, true, ["sign"]); +await crypto.subtle.getPublicKey(key, ["verify"]); `, "mjs", ); expect(r.exitCode).toBe(1); expect(r.stdout).toBe("before\n"); expect(r.stderr).toMatch( - /^Uncaught Error: 'crypto\.subtle\.importKey with the 'jwk' key format' is part of the standard library types but has no scriptc lowering yet.*\n$/, + /^Uncaught Error: 'crypto\.subtle\.getPublicKey' is part of the standard library types but has no scriptc lowering yet.*\n$/, + ); + }); +}); + +// The Ed25519 arithmetic (scr_ed25519.c) links only into programs whose +// string literals name Ed25519. Without it, an Ed25519 public key still +// imports and exports, while private-key parsing, signing and verification +// reject with a coded SC2020 Error where Node answers; there is no Node +// twin, so this lives here. The corpus (7080, 7081) pins the linked path. +describe("Ed25519 without the Ed25519 unit (JS lane)", () => { + test("a program that never names Ed25519 refuses its arithmetic with SC2020", async () => { + const r = await compileAndRun( + "ed25519-unit-not-linked", + `import * as c from "node:crypto"; +const spki = Buffer.from("302a300506032b6570032100d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a", "hex"); +const pkcs8 = Buffer.from("302e020100300506032b6570042204209d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", "hex"); +const pub = c.createPublicKey({ key: spki, format: "der", type: "spki" }); +console.log(pub.asymmetricKeyType, pub.export({ format: "jwk" }).x); +async function attempt(label, run) { + try { + await run(); + console.log(label, "resolved"); + } catch (e) { + console.log(label, e.name, e.code, e.message); + } +} +await attempt("pkcs8", () => c.createPrivateKey({ key: pkcs8, format: "der", type: "pkcs8" })); +await attempt("verify", () => c.verify(null, Buffer.from("x"), pub, Buffer.alloc(64))); +// ECDSA links the WebCrypto key unit; the Ed25519 name is built at run time. +const ecdsa = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, false, ["sign"]); +console.log(ecdsa.privateKey.type); +const name = ["Ed", "25519"].join(""); +await attempt("generateKey", () => crypto.subtle.generateKey(name, false, ["sign", "verify"])); +await attempt("importKey", () => crypto.subtle.importKey("pkcs8", pkcs8, name, false, ["sign"])); +const raw = await crypto.subtle.importKey("raw", spki.subarray(12), name, false, ["verify"]); +await attempt("subtle verify", () => crypto.subtle.verify(name, raw, new Uint8Array(64), new Uint8Array(1))); +`, + "mjs", + ); + const refusal = + "Error SC2020 Ed25519 keys are supported when a string literal in the program names 'ed25519'"; + expect(r.exitCode).toBe(0); + expect(r.stderr).toBe(""); + expect(r.stdout).toBe( + "ed25519 11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo\n" + + `pkcs8 ${refusal}\n` + + `verify ${refusal}\n` + + "private\n" + + `generateKey ${refusal}\n` + + `importKey ${refusal}\n` + + `subtle verify ${refusal}\n`, ); }); }); diff --git a/tests/harness/executable-cache-shared-output.test.ts b/tests/harness/executable-cache-shared-output.test.ts new file mode 100644 index 000000000..bf9e7353c --- /dev/null +++ b/tests/harness/executable-cache-shared-output.test.ts @@ -0,0 +1,102 @@ +/* Two programs whose entries share a name (main.ts) built into one output + * directory share the kept `main.ll` beside their executables. Each build + * must still compile, link and cache its own translation unit: a later + * build that restores either program from the executable cache, or relinks + * it from the cached translation unit, gets that program back. + * + * The overlap is made deterministic with a linker wrapper that rewrites the + * kept `main.ll` with the other program's text while the first build links, + * which is what a concurrent build of the other program does when it writes + * its kept LLVM in that window. A caller-selected linker never publishes the + * final executable, so every cache hit relinks from the cached translation + * unit. Both builds also run concurrently. */ +import { execFile, execFileSync } from "node:child_process"; +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { promisify } from "node:util"; +import { afterAll, beforeAll, describe, expect, test } from "vitest"; + +const execFileAsync = promisify(execFile); +const repoRoot = join(import.meta.dirname, "../.."); +const cli = join(repoRoot, "packages/cli/dist/main.js"); +const windows = process.platform === "win32"; + +let directory = ""; + +beforeAll(() => { + directory = mkdtempSync(join(windows ? tmpdir() : "/tmp", "scriptc-shared-output-")); + for (const name of ["first", "second"]) { + mkdirSync(join(directory, name)); + writeFileSync(join(directory, name, "main.ts"), `console.log("${name} program");\n`); + } + mkdirSync(join(directory, "out")); +}); + +afterAll(() => { + if (directory !== "") rmSync(directory, { recursive: true, force: true }); +}); + +function outPath(name: string): string { + return join(directory, "out", name + (windows ? ".exe" : "")); +} + +async function build(name: string, env: NodeJS.ProcessEnv = {}): Promise { + await execFileAsync( + process.execPath, + [cli, "build", join(directory, name, "main.ts"), "-o", outPath(name)], + { + cwd: repoRoot, + env: { ...process.env, SCRIPTC_CACHE_DIR: join(directory, "cache"), ...env }, + maxBuffer: 1 << 24, + }, + ); +} + +function run(name: string): string { + return execFileSync(outPath(name), { encoding: "utf8" }); +} + +describe.skipIf(windows)("executables built into one output directory", () => { + test( + "keep their own translation units when their builds overlap", + { timeout: 600_000 }, + async () => { + const keptLlvm = join(directory, "out", "main.ll"); + // The second program's kept LLVM, for the wrapper to write while the + // first program links. + await build("second"); + const secondLlvm = join(directory, "second.ll"); + writeFileSync(secondLlvm, readFileSync(keptLlvm)); + const linker = join(directory, "linker.sh"); + writeFileSync( + linker, + [ + "#!/bin/sh", + `if [ -n "$SCRIPTC_TEST_OVERLAP" ]; then cp "${secondLlvm}" "${keptLlvm}"; fi`, + 'exec clang "$@"', + "", + ].join("\n"), + ); + chmodSync(linker, 0o755); + + await build("first", { SCRIPTC_LINKER: linker, SCRIPTC_TEST_OVERLAP: "1" }); + expect(run("first")).toBe("first program\n"); + expect(readFileSync(keptLlvm, "utf8")).toContain("first program"); + // A cache hit relinks from the translation unit the build cached. + rmSync(outPath("first")); + await build("first", { SCRIPTC_LINKER: linker }); + expect(run("first")).toBe("first program\n"); + expect(readFileSync(keptLlvm, "utf8")).toContain("first program"); + + // Both programs at once, cold and then from the cache. + for (const round of [0, 1]) { + if (round === 1) for (const name of ["first", "second"]) rmSync(outPath(name)); + const env = { SCRIPTC_CACHE_DIR: join(directory, "cache-both"), SCRIPTC_LINKER: linker }; + await Promise.all([build("first", env), build("second", env)]); + expect(run("first")).toBe("first program\n"); + expect(run("second")).toBe("second program\n"); + } + }, + ); +}); diff --git a/tests/harness/jsx-oracle.ts b/tests/harness/jsx-oracle.ts new file mode 100644 index 000000000..ba7a49946 --- /dev/null +++ b/tests/harness/jsx-oracle.ts @@ -0,0 +1,120 @@ +import { createHash } from "node:crypto"; +import { + copyFileSync, + existsSync, + mkdirSync, + readFileSync, + readdirSync, + renameSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { dirname, join, relative } from "node:path"; +import ts5 from "typescript"; + +/** `// @tsc-jsx` in a directory program's main.ts head: Node cannot run + * .tsx or .jsx modules, so the oracle runs TypeScript's own emit of the + * program. Every .ts, .tsx, .js and .jsx file of the directory is transpiled + * (target ES2022, ES modules) with the jsx options of the directory's + * tsconfig.json, .ts, .tsx and .jsx files becoming .js, and package.json import + * and export targets renamed alike; other files are copied. + * The result lives in a directory under the test cache keyed by the program + * bytes and the typescript version. */ +export function wantsTscJsx(head: readonly string[]): boolean { + return head.some((line) => /^\/\/ @tsc-jsx\s*$/.test(line)); +} + +/** The oracle entry (`main.js` of the transpiled program) for `file`. */ +export function tscJsxOracleEntry(file: string, cacheDir: string): string { + const root = dirname(file); + const files = listFiles(root); + const hash = createHash("sha256").update(ts5.version); + for (const path of files) + hash.update("\0").update(relative(root, path)).update("\0").update(readFileSync(path)); + const dir = join(cacheDir, `jsx-oracle-${hash.digest("hex").slice(0, 16)}`); + const entry = join(dir, "main.js"); + if (existsSync(entry)) return entry; + const configPath = join(root, "tsconfig.json"); + const config = existsSync(configPath) + ? ts5.parseJsonConfigFileContent( + ts5.readConfigFile(configPath, ts5.sys.readFile).config ?? {}, + ts5.sys, + root, + ).options + : {}; + const compilerOptions: ts5.CompilerOptions = { + target: ts5.ScriptTarget.ES2022, + module: ts5.ModuleKind.ESNext, + jsx: config.jsx, + jsxFactory: config.jsxFactory, + jsxFragmentFactory: config.jsxFragmentFactory, + jsxImportSource: config.jsxImportSource, + reactNamespace: config.reactNamespace, + }; + // Atomic publish: build beside the final directory, then rename it into + // place; a concurrent suite that wins the rename leaves the same content. + const staging = `${dir}.${process.pid}.tmp`; + rmSync(staging, { recursive: true, force: true }); + for (const path of files) { + const target = join(staging, relative(root, path)); + mkdirSync(dirname(target), { recursive: true }); + if (/\.(?:[cm]?ts|tsx|jsx?|[cm]js)$/.test(path) && !/\.d\.[cm]?ts$/.test(path)) { + const output = ts5.transpileModule(readFileSync(path, "utf8"), { + compilerOptions, + fileName: path, + }).outputText; + writeFileSync( + target + .replace(/\.(?:ts|tsx|jsx)$/, ".js") + .replace(/\.mts$/, ".mjs") + .replace(/\.cts$/, ".cjs"), + output, + ); + } else if (/(^|\/)package\.json$/.test(path)) { + // Import and export targets follow their files: .ts, .tsx and .jsx + // become .js. + const renamed = (value: unknown): unknown => + typeof value === "string" + ? /\.d\.[cm]?ts$/.test(value) + ? value + : value + .replace(/\.(?:ts|tsx|jsx)$/, ".js") + .replace(/\.mts$/, ".mjs") + .replace(/\.cts$/, ".cjs") + : Array.isArray(value) + ? value.map(renamed) + : value !== null && typeof value === "object" + ? Object.fromEntries(Object.entries(value).map(([key, item]) => [key, renamed(item)])) + : value; + writeFileSync( + target, + `${JSON.stringify(renamed(JSON.parse(readFileSync(path, "utf8"))), null, 2)}\n`, + ); + } else { + copyFileSync(path, target); + } + } + if (!existsSync(join(staging, "package.json"))) + writeFileSync(join(staging, "package.json"), '{ "type": "module" }\n'); + try { + renameSync(staging, dir); + } catch { + rmSync(staging, { recursive: true, force: true }); + } + return entry; +} + +function listFiles(root: string): string[] { + const out: string[] = []; + const visit = (dir: string): void => { + for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => + a.name < b.name ? -1 : a.name > b.name ? 1 : 0, + )) { + const path = join(dir, entry.name); + if (entry.isDirectory()) visit(path); + else if (entry.isFile()) out.push(path); + } + }; + visit(root); + return out; +} diff --git a/tests/harness/library-asyncfree.test.ts b/tests/harness/library-asyncfree.test.ts index 7c4d029cc..d924f26d1 100644 --- a/tests/harness/library-asyncfree.test.ts +++ b/tests/harness/library-asyncfree.test.ts @@ -97,6 +97,15 @@ describe("async_free detection over the IR", () => { ).toContain("child_process"); }); + test("asymmetric keys and signatures refuse", async () => { + expect( + await surfaceOf( + "pki", + `import * as crypto from "node:crypto";\nconst { privateKey } = crypto.generateKeyPairSync("ec", { namedCurve: "P-256" });\nconsole.log(crypto.sign("sha256", Buffer.from("x"), privateKey).length > 0);\n`, + ), + ).toContain("asymmetric KeyObjects"); + }); + test("process signal listeners refuse", async () => { expect( await surfaceOf( diff --git a/tests/harness/library-mode.test.ts b/tests/harness/library-mode.test.ts index ffd42bd8e..0d4052952 100644 --- a/tests/harness/library-mode.test.ts +++ b/tests/harness/library-mode.test.ts @@ -351,6 +351,7 @@ bump: 1 2 note: 1 2 indexed: 72100 recall: a,b +globals: undefined fenced `; test("K4: three init sessions are byte-identical", async () => { diff --git a/tests/harness/library-profile.test.ts b/tests/harness/library-profile.test.ts index 2b28a6cd0..b39daefa1 100644 --- a/tests/harness/library-profile.test.ts +++ b/tests/harness/library-profile.test.ts @@ -8,7 +8,12 @@ import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterAll, describe, expect, test } from "vitest"; -import { loadLibraryProfile, profileRemediation, profileTeaching } from "@scriptc/compiler"; +import { + loadLibraryProfile, + profileRemediation, + profileTeaching, + resolveLibraryFences, +} from "@scriptc/compiler"; const dir = mkdtempSync(join(tmpdir(), "scriptc-lib-profile-")); afterAll(() => rmSync(dir, { recursive: true, force: true })); @@ -475,6 +480,13 @@ describe("library profile fences", () => { }); test("a fence remediation feeds the trap-remediation lookup through covered codes", () => { + // A crypto member that still refuses with SC2020, read from the + // manifest: members leave that set as they gain lowerings. + const builtins = resolveLibraryFences([{ path: "fences[0]", prefix: "node-builtin.crypto." }]); + expect(builtins.ok).toBe(true); + if (!builtins.ok) return; + const unlowered = builtins.fences[0]!.surfaces.find((s) => s.code === "SC2020"); + expect(unlowered).toBeDefined(); const r = loadLibraryProfile( writeProfile({ ...good, @@ -482,7 +494,7 @@ describe("library profile fences", () => { remediations: { SC2012: "the explicit map key wins" }, fences: [ { id: "diagnostic.sc2012", remediation: "request it as an effect" }, - { id: "node-builtin.crypto.createSign", remediation: "signatures come from the host" }, + { id: unlowered!.id, remediation: "the host provides it" }, ], }, }), @@ -492,9 +504,9 @@ describe("library profile fences", () => { // Explicit remediations keys win over fence-supplied text. expect(profileRemediation(r.profile, "SC2012")).toBe("the explicit map key wins"); // A fence's remediation answers for its covered entries' codes - // (crypto.createSign is SC2020) — spec §3's "in a fence entry or a - // remediations map", one lookup either way. - expect(profileRemediation(r.profile, "SC2020")).toBe("signatures come from the host"); + // (SC2020 here) — spec §3's "in a fence entry or a remediations map", + // one lookup either way. + expect(profileRemediation(r.profile, "SC2020")).toBe("the host provides it"); expect(profileRemediation(r.profile, "SC4014")).toBeUndefined(); }); diff --git a/tests/harness/linux-differential.test.ts b/tests/harness/linux-differential.test.ts index 9730623cd..9da5199d3 100644 --- a/tests/harness/linux-differential.test.ts +++ b/tests/harness/linux-differential.test.ts @@ -9,6 +9,7 @@ import { compile } from "@scriptc/compiler"; import { npmCases } from "./npm-cases.js"; import { normalizeNodeTestOutput } from "./node-test-normalize.js"; import { eventLoopCases, type StdinScript } from "./event-loop-cases.js"; +import { tscJsxOracleEntry, wantsTscJsx } from "./jsx-oracle.js"; const execFileAsync = promisify(execFile); const enabled = process.env["SCRIPTC_LINUX"] === "1"; @@ -55,6 +56,7 @@ function wantsTscDecorators(file: string): boolean { * programs) its deterministic ES2022 downlevel — differential.test.ts's * nodeOracleFile, with the identical transform and cache key. */ function nodeOracleFile(file: string): string { + if (wantsTscJsx(directiveHead(file))) return tscJsxOracleEntry(file, cacheDir); if (!wantsTscDecorators(file)) return file; const src = readFileSync(file, "utf8"); const out = ts5.transpileModule(src, { @@ -212,7 +214,7 @@ async function runLinuxNode(file: string): Promise { function programInputs(file: string): string[] { if (!/\/main\.(ts|js|mjs|cjs)$/.test(file)) return [file]; return [ - ...ENTRY_EXTS.flatMap((ext) => globSync(join(file, `../**/*.${ext}`))), + ...[...ENTRY_EXTS, "tsx", "jsx"].flatMap((ext) => globSync(join(file, `../**/*.${ext}`))), ...globSync(join(file, "../**/tsconfig.json")), ...globSync(join(file, "../**/package.json")), ].sort(); diff --git a/tests/harness/llvm-differential.test.ts b/tests/harness/llvm-differential.test.ts index 792fdb1d2..15b7e7c0e 100644 --- a/tests/harness/llvm-differential.test.ts +++ b/tests/harness/llvm-differential.test.ts @@ -11,6 +11,7 @@ import { describe, expect, test } from "vitest"; import ts5 from "typescript"; import { compile } from "@scriptc/compiler"; import { corpusSelect, shardSuffix } from "./shard.js"; +import { tscJsxOracleEntry, wantsTscJsx } from "./jsx-oracle.js"; const execFileAsync = promisify(execFile); const repoRoot = join(import.meta.dirname, "../.."); @@ -120,6 +121,7 @@ function wantsTscDecorators(file: string): boolean { } function nodeOracleFile(file: string): string { + if (wantsTscJsx(directiveHead(file))) return tscJsxOracleEntry(file, cacheDir); if (!wantsTscDecorators(file)) return file; const src = readFileSync(file, "utf8"); const out = ts5.transpileModule(src, { @@ -165,7 +167,7 @@ function nodeOracleArgs(file: string): string[] { function programInputs(file: string): string[] { if (!/\/main\.(ts|js|mjs|cjs)$/.test(file)) return [file]; return [ - ...ENTRY_EXTS.flatMap((ext) => globSync(join(file, `../**/*.${ext}`))), + ...[...ENTRY_EXTS, "tsx", "jsx"].flatMap((ext) => globSync(join(file, `../**/*.${ext}`))), ...globSync(join(file, "../**/tsconfig.json")), ...globSync(join(file, "../**/package.json")), ].sort(); diff --git a/tests/harness/npm-static-costs.json b/tests/harness/npm-static-costs.json index 2f1cdde1e..1546f8d57 100644 --- a/tests/harness/npm-static-costs.json +++ b/tests/harness/npm-static-costs.json @@ -84,6 +84,8 @@ "the published Effect Function subpath initializes and runs statically": 9097, "the published Effect generator has deterministic native results": 105577, "the published Effect generator logs and completes statically": 112814, + "the published js-yaml loads, dumps and reports errors statically and matches Node": 12728, + "the published smol-toml parses and stringifies statically and matches Node": 11649, "untyped package methods preserve virtual overrides (llvm)": 3065 }, "san": { @@ -171,6 +173,8 @@ "the published Effect Function subpath initializes and runs statically": 8280, "the published Effect generator has deterministic native results": 136502, "the published Effect generator logs and completes statically": 181378, + "the published js-yaml loads, dumps and reports errors statically and matches Node": 35621, + "the published smol-toml parses and stringifies statically and matches Node": 25130, "untyped package methods preserve virtual overrides (llvm)": 2730 } } diff --git a/tests/harness/npm-static.test.ts b/tests/harness/npm-static.test.ts index df82efbcf..7ee76307f 100644 --- a/tests/harness/npm-static.test.ts +++ b/tests/harness/npm-static.test.ts @@ -1175,6 +1175,38 @@ describe(`npm-static pilots${sanitize ? " (sanitized)" : ""}`, () => { effectBuildTimeout, ); + test("the published js-yaml loads, dumps and reports errors statically and matches Node", async () => { + const entry = join(pilotRoot, "js-yaml-cli.mjs"); + const { coverage } = analyze(entry, { npmStatic: ["js-yaml"] }); + expect(coverage.npmStatic).toEqual([{ package: "js-yaml", status: "static" }]); + expect(coverage.diagnostics).toHaveLength(0); + const binary = await buildStatic(entry, ["js-yaml"]); + const [reference, native] = await Promise.all([ + runBinary(process.execPath, [entry]), + runBinary(binary, []), + ]); + expect(native.stdout.toString()).toBe(reference.stdout.toString()); + expect(comparableStderr(native.stderr)).toEqual(reference.stderr); + expect(native.exitCode).toBe(reference.exitCode); + expect(native.exitCode).toBe(0); + }, 300_000); + + test("the published smol-toml parses and stringifies statically and matches Node", async () => { + const entry = join(pilotRoot, "smol-toml-cli.mjs"); + const { coverage } = analyze(entry, { npmStatic: ["smol-toml"] }); + expect(coverage.npmStatic).toEqual([{ package: "smol-toml", status: "static" }]); + expect(coverage.diagnostics).toHaveLength(0); + const binary = await buildStatic(entry, ["smol-toml"]); + const [reference, native] = await Promise.all([ + runBinary(process.execPath, [entry]), + runBinary(binary, []), + ]); + expect(native.stdout.toString()).toBe(reference.stdout.toString()); + expect(comparableStderr(native.stderr)).toEqual(reference.stderr); + expect(native.exitCode).toBe(reference.exitCode); + expect(native.exitCode).toBe(0); + }, 300_000); + test("inferred variadic factories preserve checked callable results", async () => { const entry = join(pilotRoot, "variadic-factory-cli.ts"); const binary = await buildStatic(entry, ["variadic-factory"]); diff --git a/tests/harness/npm.test.ts b/tests/harness/npm.test.ts index 2df0d87ef..795e42846 100644 --- a/tests/harness/npm.test.ts +++ b/tests/harness/npm.test.ts @@ -112,9 +112,10 @@ const KNOWN: Record = { const cases = shardSelect(npmCases(fixturesRoot), (c) => c.name); /** Per-case timeouts past the default 120 s: the undici cases compile the - * built-in undici implementation's module graph, which a sanitized build - * on a CI runner takes minutes to compile. */ -const TIMEOUTS: Record = { undici5: 600_000, undici7: 600_000 }; + * built-in undici implementation's module graph, and zod3 compiles zod 3's + * 3,700-line types module. A sanitized build of either takes minutes on a + * CI runner. */ +const TIMEOUTS: Record = { undici5: 600_000, undici7: 600_000, zod3: 600_000 }; interface RunResult { stdout: Buffer; diff --git a/tests/harness/project-config.test.ts b/tests/harness/project-config.test.ts index dabb9b0bf..4676499eb 100644 --- a/tests/harness/project-config.test.ts +++ b/tests/harness/project-config.test.ts @@ -307,6 +307,24 @@ test("node-types: TLSSocket.isSessionReused and keyed ??= timings under @types/n expect(comparableStderr(native.stderr)).toBe(node.stderr); }); +test("node-types: new tls.TLSSocket and tls.connect({ socket }) under @types/node", async () => { + const outDir = outDirFor("tls-socket-wrap"); + const entry = join(nodeTypesDir, "tls-socket-wrap.ts"); + const result = await compile(entry, { + outPath: join(outDir, process.platform === "win32" ? "tls-socket-wrap.exe" : "tls-socket-wrap"), + outDir, + sanitize, + }); + expect(result.ok, !result.ok ? JSON.stringify(result.diagnostics, null, 2) : "").toBe(true); + if (!result.ok) return; + const [native, node] = await Promise.all([ + execFileAsync(result.binaryPath), + execFileAsync(process.execPath, ["--disable-warning=MODULE_TYPELESS_PACKAGE_JSON", entry]), + ]); + expect(native.stdout).toBe(node.stdout); + expect(comparableStderr(native.stderr)).toBe(node.stderr); +}); + test("node-types: net.SocketAddress and net.BlockList under @types/node", async () => { const outDir = outDirFor("net-blocklist"); const entry = join(nodeTypesDir, "net-blocklist.ts"); @@ -1114,6 +1132,52 @@ test("node-types: ECDH matches Node under @types/node", async () => { expect(comparableStderr(native.stderr)).toBe(node.stderr); }); +test("node-types: DiffieHellman matches Node under @types/node", async () => { + const outDir = outDirFor("node-dh"); + const entry = join(nodeTypesDir, "dh.ts"); + const result = await compile(entry, { outPath: join(outDir, "dh"), outDir, sanitize }); + expect(result.ok, !result.ok ? JSON.stringify(result.diagnostics, null, 2) : "").toBe(true); + if (!result.ok) return; + const [native, node] = await Promise.all([ + execFileAsync(result.binaryPath), + execFileAsync(process.execPath, ["--disable-warning=MODULE_TYPELESS_PACKAGE_JSON", entry]), + ]); + expect(native.stdout).toBe(node.stdout); + expect(comparableStderr(native.stderr)).toBe(node.stderr); +}); + +test("node-types: asymmetric keys and signatures match Node under @types/node", async () => { + const outDir = outDirFor("node-keys"); + const entry = join(nodeTypesDir, "keys.ts"); + const result = await compile(entry, { outPath: join(outDir, "keys"), outDir, sanitize }); + expect(result.ok, !result.ok ? JSON.stringify(result.diagnostics, null, 2) : "").toBe(true); + if (!result.ok) return; + const [native, node] = await Promise.all([ + execFileAsync(result.binaryPath), + execFileAsync(process.execPath, ["--disable-warning=MODULE_TYPELESS_PACKAGE_JSON", entry]), + ]); + expect(native.stdout).toBe(node.stdout); + expect(comparableStderr(native.stderr)).toBe(node.stderr); +}); + +test("node-types: WebCrypto ECDSA, Ed25519 and RSA match Node under @types/node", async () => { + const outDir = outDirFor("node-webcrypto-ecdsa"); + const entry = join(nodeTypesDir, "webcrypto-ecdsa.ts"); + const result = await compile(entry, { + outPath: join(outDir, "webcrypto-ecdsa"), + outDir, + sanitize, + }); + expect(result.ok, !result.ok ? JSON.stringify(result.diagnostics, null, 2) : "").toBe(true); + if (!result.ok) return; + const [native, node] = await Promise.all([ + execFileAsync(result.binaryPath), + execFileAsync(process.execPath, ["--disable-warning=MODULE_TYPELESS_PACKAGE_JSON", entry]), + ]); + expect(native.stdout).toBe(node.stdout); + expect(comparableStderr(native.stderr)).toBe(node.stderr); +}); + test("node-types: WebCrypto HMAC matches Node under @types/node", async () => { const outDir = outDirFor("node-webcrypto-hmac"); const entry = join(nodeTypesDir, "webcrypto-hmac.ts"); @@ -1132,6 +1196,24 @@ test("node-types: WebCrypto HMAC matches Node under @types/node", async () => { expect(comparableStderr(native.stderr)).toBe(node.stderr); }); +test("node-types: WebCrypto secret keys match Node under @types/node", async () => { + const outDir = outDirFor("node-webcrypto-keys"); + const entry = join(nodeTypesDir, "webcrypto-keys.ts"); + const result = await compile(entry, { + outPath: join(outDir, "webcrypto-keys"), + outDir, + sanitize, + }); + expect(result.ok, !result.ok ? JSON.stringify(result.diagnostics, null, 2) : "").toBe(true); + if (!result.ok) return; + const [native, node] = await Promise.all([ + execFileAsync(result.binaryPath), + execFileAsync(process.execPath, ["--disable-warning=MODULE_TYPELESS_PACKAGE_JSON", entry]), + ]); + expect(native.stdout).toBe(node.stdout); + expect(comparableStderr(native.stderr)).toBe(node.stderr); +}); + test("node-types: the navigator global's runtime probe matches Node under @types/node", async () => { const outDir = outDirFor("node-navigator"); const entry = join(nodeTypesDir, "navigator.ts"); diff --git a/tests/harness/self-hosting-llvm-emitter.test.ts b/tests/harness/self-hosting-llvm-emitter.test.ts index 9c24d50cb..cb9cd69c4 100644 --- a/tests/harness/self-hosting-llvm-emitter.test.ts +++ b/tests/harness/self-hosting-llvm-emitter.test.ts @@ -161,7 +161,7 @@ for (const backend of ["llvm"] as const) { name: string, request = llvmEmitterRequest(), ): Promise => { - writeFileSync(input, serializeModule(mod)); + writeFileSync(input, serializeModule(mod, true)); writeFileSync(config, JSON.stringify(request)); const result = await execFileAsync(stage, [input, output, config], { ...runOptions, @@ -195,7 +195,7 @@ for (const backend of ["llvm"] as const) { loc: { file: rejected.sourceFile, start: 0, end: 0 }, }, ]; - writeFileSync(input, serializeModule(rejected)); + writeFileSync(input, serializeModule(rejected, true)); writeFileSync(config, JSON.stringify(llvmEmitterRequest())); writeFileSync(output, "untouched"); const args = [input, output, config]; diff --git a/tests/harness/self-hosting-native-toolchain.test.ts b/tests/harness/self-hosting-native-toolchain.test.ts index 7da7626b7..4d5546ab6 100644 --- a/tests/harness/self-hosting-native-toolchain.test.ts +++ b/tests/harness/self-hosting-native-toolchain.test.ts @@ -48,6 +48,9 @@ const features: NativeLinkFeatures = { tlsCa: false, cipher: false, ecdh: false, + dh: false, + pki: false, + ed25519: false, webcrypto: false, perfLoop: false, }; @@ -105,7 +108,7 @@ for (const backend of ["llvm"] as const) { object_format: target.objectFormat, minimum_os: target.minimumOs, }, - runtime_abi: { version: 24, marker: "scr_runtime_abi_v24" }, + runtime_abi: { version: 33, marker: "scr_runtime_abi_v33" }, compiler: { command: "fixture", identity: "fixture", target: target.llvmTriple }, macros: { executable: [], excluded: [], sanitizer: "external-toolchain-required" }, flavors: { diff --git a/tests/harness/self-hosting-runtime-pack.test.ts b/tests/harness/self-hosting-runtime-pack.test.ts index f4fde795c..57857d642 100644 --- a/tests/harness/self-hosting-runtime-pack.test.ts +++ b/tests/harness/self-hosting-runtime-pack.test.ts @@ -49,6 +49,9 @@ const base: NativeLinkFeatures = { tlsCa: false, cipher: false, ecdh: false, + dh: false, + pki: false, + ed25519: false, webcrypto: false, perfLoop: false, }; diff --git a/tests/harness/split-tools.test.ts b/tests/harness/split-tools.test.ts new file mode 100644 index 000000000..8bdefdf0e --- /dev/null +++ b/tests/harness/split-tools.test.ts @@ -0,0 +1,296 @@ +import { execFileSync, spawnSync } from "node:child_process"; +import { + cpSync, + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + symlinkSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import ts from "typescript"; +import { afterEach, expect, test } from "vitest"; + +// The repository root supplies typescript and oxfmt to the split tools. +const root = fileURLToPath(new URL("../..", import.meta.url)); +const tool = (name: string): string => join(root, "scripts/split", name); +const dirs: string[] = []; + +afterEach(() => { + for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +const compilerOptions = { + strict: true, + noEmit: true, + target: "ES2022", + module: "ESNext", + moduleResolution: "Bundler", +}; + +/** A checkout holding `files` (paths relative to its root) and a tsconfig. */ +function checkout(files: Record): string { + const dir = mkdtempSync(join(tmpdir(), "split-tools-")); + dirs.push(dir); + const all = { ...files, "tsconfig.json": JSON.stringify({ compilerOptions }) }; + for (const [path, text] of Object.entries(all)) { + mkdirSync(dirname(join(dir, path)), { recursive: true }); + writeFileSync(join(dir, path), text); + } + return dir; +} + +function run(script: string, args: string[], repo: string): void { + execFileSync(process.execPath, [tool(script), ...args, "--repo", repo, "--tools", root], { + cwd: repo, + stdio: "pipe", + }); +} + +/** Type errors in the checkout's files. */ +function diagnostics(dir: string): string[] { + const parsed = ts.getParsedCommandLineOfConfigFile( + join(dir, "tsconfig.json"), + {}, + { + ...ts.sys, + onUnRecoverableConfigFileDiagnostic: () => {}, + }, + ); + const program = ts.createProgram(parsed!.fileNames, parsed!.options); + return ts + .getPreEmitDiagnostics(program) + .map((d) => ts.flattenDiagnosticMessageText(d.messageText, "\n")); +} + +test("split-methods keeps an import a staying method uses as a shorthand property", () => { + const dir = checkout({ + "src/helper.ts": "export const helper = 2;\n", + "src/host.ts": [ + 'import { helper } from "./helper.js";', + "", + "export class Host {", + " value = 1;", + " keep(): { helper: number } {", + " return { helper };", + " }", + " moved(): number {", + " return this.value + 1;", + " }", + "}", + "", + ].join("\n"), + "split.json": JSON.stringify({ + module: "src/host.ts", + class: "Host", + methods: { "moved.ts": ["moved"] }, + }), + }); + run("split-methods.mjs", ["apply", join(dir, "split.json")], dir); + expect(readFileSync(join(dir, "src/host.ts"), "utf8")).toContain( + 'import { helper } from "./helper.js";', + ); + expect(diagnostics(dir)).toEqual([]); +}); + +/** An oxfmt.config.ts that records it ran by writing `marker`. */ +const recordingConfig = (marker: string): string => + [ + 'import { writeFileSync } from "node:fs";', + `writeFileSync(${JSON.stringify(marker)}, "ran");`, + "export default {};", + "", + ].join("\n"); + +test("split-methods formats with the tools checkout's configuration, not the branch's", () => { + const dir = checkout({ + "src/host.ts": [ + "export class Host {", + " value = 1;", + " moved(): number {", + " return this.value + 1;", + " }", + "}", + "", + ].join("\n"), + "split.json": JSON.stringify({ + module: "src/host.ts", + class: "Host", + methods: { "moved.ts": ["moved"] }, + }), + }); + const markers = [join(dir, "root-config-ran"), join(dir, "nested-config-ran")]; + writeFileSync(join(dir, "oxfmt.config.ts"), recordingConfig(markers[0]!)); + writeFileSync(join(dir, "src/oxfmt.config.ts"), recordingConfig(markers[1]!)); + run("split-methods.mjs", ["apply", join(dir, "split.json")], dir); + expect(readFileSync(join(dir, "src/moved.ts"), "utf8")).toContain("export function moved"); + for (const marker of markers) expect(existsSync(marker)).toBe(false); +}); + +test("move-state formats with the tools checkout's configuration, not the branch's", () => { + const dir = checkout({ + "src/host.ts": + "export class Host {\n count = 0;\n moved(): number {\n return this.count + 1;\n }\n}\n", + "state.template": "", + "split.json": JSON.stringify({ + module: "src/host.ts", + class: "Host", + dir: "src", + create: { "host-state.ts": "state.template" }, + groups: [ + { file: "host-state.ts", key: "COUNTS", interfaceName: "Counts", fields: ["count"] }, + ], + }), + }); + const markers = [join(dir, "root-config-ran"), join(dir, "nested-config-ran")]; + writeFileSync(join(dir, "oxfmt.config.ts"), recordingConfig(markers[0]!)); + writeFileSync(join(dir, "src/oxfmt.config.ts"), recordingConfig(markers[1]!)); + run("move-state.mjs", ["apply", join(dir, "split.json")], dir); + expect(readFileSync(join(dir, "src/host.ts"), "utf8")).toContain("COUNTS.of(this).count"); + for (const marker of markers) expect(existsSync(marker)).toBe(false); +}); + +test("split-module imports a moved class's local base class as a value", () => { + const dir = checkout({ + "src/shapes.ts": [ + "export class Base {", + " x = 1;", + "}", + "", + "export class Derived extends Base {", + " y = 2;", + "}", + "", + "export function base(): Base {", + " return new Base();", + "}", + "", + ].join("\n"), + "split.json": JSON.stringify({ + tsconfig: "tsconfig.json", + module: "src/shapes.ts", + seeds: { "derived.ts": ["Derived"] }, + manifest: "manifest.json", + }), + }); + const config = join(dir, "split.json"); + run("split-module.mjs", ["plan", config], dir); + run("split-module.mjs", ["apply", config], dir); + expect(readFileSync(join(dir, "src/derived.ts"), "utf8")).toContain( + 'import { Base } from "./shapes.js";', + ); + expect(diagnostics(dir)).toEqual([]); +}); + +/* A copy of tests/fixtures/split-tools/symlink: `repo/` is the checkout the + * tools rewrite, and its committed `src/linked.ts` links to `outside/linked.ts` + * next to it. */ +const symlinkFixture = fileURLToPath(new URL("../fixtures/split-tools/symlink", import.meta.url)); +const outsideText = readFileSync(join(symlinkFixture, "outside/linked.ts"), "utf8"); + +function symlinkCheckout(): { dir: string; repo: string } { + const dir = mkdtempSync(join(tmpdir(), "split-tools-")); + dirs.push(dir); + cpSync(symlinkFixture, dir, { recursive: true, verbatimSymlinks: true }); + return { dir, repo: join(dir, "repo") }; +} + +/** Runs a tool that must refuse; answers its stderr. */ +function refused(script: string, config: object, dir: string, repo: string): string { + const path = join(dir, "split.json"); + writeFileSync(path, JSON.stringify(config)); + const result = spawnSync( + process.execPath, + [tool(script), "apply", path, "--repo", repo, "--tools", root], + { cwd: repo, encoding: "utf8" }, + ); + expect(result.status).not.toBe(0); + return result.stderr; +} + +test("split-methods refuses to write a new file through a symlink that leaves the checkout", () => { + const { dir, repo } = symlinkCheckout(); + // A link to a file that doesn't exist yet: writing through it would create the file. + symlinkSync("../../outside/created.ts", join(repo, "src/moved.ts")); + const stderr = refused( + "split-methods.mjs", + { module: "src/host.ts", class: "Host", methods: { "moved.ts": ["moved"] } }, + dir, + repo, + ); + expect(stderr).toContain("refusing"); + expect(existsSync(join(dir, "outside/created.ts"))).toBe(false); +}); + +test("split-methods refuses a module that links outside the checkout", () => { + const { dir, repo } = symlinkCheckout(); + const stderr = refused( + "split-methods.mjs", + { module: "src/linked.ts", class: "Host", methods: { "moved.ts": ["moved"] } }, + dir, + repo, + ); + expect(stderr).toContain("refusing"); +}); + +test("split-module refuses a module that links outside the checkout", () => { + const { dir, repo } = symlinkCheckout(); + writeFileSync(join(repo, "tsconfig.json"), JSON.stringify({ compilerOptions })); + writeFileSync(join(dir, "manifest.json"), JSON.stringify({ "moved.ts": ["outside"] })); + const stderr = refused( + "split-module.mjs", + { tsconfig: "tsconfig.json", module: "src/linked.ts", manifest: "manifest.json" }, + dir, + repo, + ); + expect(stderr).toContain("refusing"); +}); + +test("move-state refuses a state file that a branch commits as a link outside the checkout", () => { + const { dir, repo } = symlinkCheckout(); + // The group file is listed under `create` and already exists as a link, so + // creation skips it and the move would append the state through the link. + symlinkSync("../../outside/linked.ts", join(repo, "src/host-state.ts")); + writeFileSync(join(dir, "state.template"), ""); + const stderr = refused( + "move-state.mjs", + { + module: "src/host.ts", + class: "Host", + dir: "src", + create: { "host-state.ts": "state.template" }, + groups: [ + { file: "host-state.ts", key: "COUNTS", interfaceName: "Counts", fields: ["count"] }, + ], + }, + dir, + repo, + ); + expect(stderr).toContain("refusing"); + expect(readFileSync(join(dir, "outside/linked.ts"), "utf8")).toBe(outsideText); +}); + +test("move-state refuses to rewrite a file that links outside the checkout", () => { + const { dir, repo } = symlinkCheckout(); + writeFileSync(join(repo, "src/host-state.ts"), ""); + const stderr = refused( + "move-state.mjs", + { + module: "src/host.ts", + class: "Host", + dir: "src", + groups: [ + { file: "host-state.ts", key: "COUNTS", interfaceName: "Counts", fields: ["count"] }, + ], + replacements: [{ file: "linked.ts", find: "export const outside = 1;", replace: "" }], + }, + dir, + repo, + ); + expect(stderr).toContain("refusing"); + expect(readFileSync(join(dir, "outside/linked.ts"), "utf8")).toBe(outsideText); +}); diff --git a/tests/harness/stream-entry-kinds.test.ts b/tests/harness/stream-entry-kinds.test.ts index f7333b298..b0aa52294 100644 --- a/tests/harness/stream-entry-kinds.test.ts +++ b/tests/harness/stream-entry-kinds.test.ts @@ -1,14 +1,9 @@ /* Stream chunk kinds Node cannot oracle — scriptc-only. * - * A typed read() answers `Buffer | null`. When the read itself makes the - * stream hold strings (the first string a lazy Readable.from pull over a - * dynamic array produces, or setEncoding() inside _read), Node returns - * the string, which the typed result cannot hold, so the read throws the - * encoding fence instead (caught here, so the program exits normally). - * These pins keep that refusal exact and, under - * SCRIPTC_SAN=1 (ASan and the RC audit, like every harness lane), prove - * no string reaches Buffer code. The Node-observable cases are corpus - * programs (stream-dynamic-entry-kinds.*). + * Under SCRIPTC_SAN=1 (ASan and the RC audit, like every harness lane) + * these pins prove no string reaches Buffer code. The Node-observable + * cases are corpus programs (stream-dynamic-entry-kinds.*, and + * 7439-readable-read-string-chunks for read() of strings). */ import { execFile } from "node:child_process"; import { createHash } from "node:crypto"; @@ -73,72 +68,8 @@ function stripAsanFiberWarning(s: string): string { ); } -const READ_FENCE_MESSAGE = - "read() on a stream with an encoding set is not supported yet (consume 'data' events, which deliver strings)"; - describe(`typed stream reads of string chunks (scriptc-only${sanitize ? ", sanitized" : ""})`, () => { - test("a typed read() whose lazy pull yields the first string throws the encoding fence", async () => { - const r = await compileAndRun( - "typed-read-json-string", - `import { Readable } from "node:stream"; -const r = Readable.from(JSON.parse('["j1", "j2"]')); -try { - const chunk = r.read(); - console.log("hex", chunk === null ? "null" : chunk.toString("hex")); -} catch (err) { - console.log("caught", (err as Error).message); -} -`, - ); - expect(r.exitCode).toBe(0); - expect(r.stdout).toBe(`caught ${READ_FENCE_MESSAGE}\n`); - }); - - test("a typed read() whose _read calls setEncoding() throws the encoding fence", async () => { - const r = await compileAndRun( - "typed-read-encoding-in-read", - `import { Readable } from "node:stream"; -const r = new Readable({ - read() { - this.setEncoding("utf8"); - this.push(Buffer.from("ab")); - this.push(null); - }, -}); -try { - const chunk = r.read(); - console.log("hex", chunk === null ? "null" : chunk.toString("hex")); -} catch (err) { - console.log("caught", (err as Error).message); -} -`, - ); - expect(r.exitCode).toBe(0); - expect(r.stdout).toBe(`caught ${READ_FENCE_MESSAGE}\n`); - }); - - test("the JavaScript lane's read() on a JSON source throws the same fence", async () => { - const r = await compileAndRun( - "js-read-json-string", - `'use strict'; -const { Readable } = require('node:stream'); -const r = Readable.from(JSON.parse('["j1"]')); -r.once('readable', () => { - try { - const chunk = r.read(); - console.log('got', chunk === null ? 'null' : chunk.length); - } catch (err) { - console.log('caught', err.message); - } -}); -`, - "cjs", - ); - expect(r.exitCode).toBe(0); - expect(r.stdout).toBe(`caught ${READ_FENCE_MESSAGE}\n`); - }); - - test("a dynamic source that mixes Buffers and strings without a decoder is destroyed", async () => { + test("a dynamic source that mixes Buffers and strings yields each as it is, as Node does", async () => { const r = await compileAndRun( "mixed-dynamic-source", `import { Readable } from "node:stream"; @@ -151,8 +82,6 @@ r.on("close", () => console.log("close")); `, ); expect(r.exitCode).toBe(0); - expect(r.stdout).toBe( - "data true b1\nerror a Readable.from source that mixes strings and Buffers is not supported yet\nclose\n", - ); + expect(r.stdout).toBe("data true b1\ndata false s1\nclose\n"); }); }); diff --git a/tests/harness/tls-socket-leaks.test.ts b/tests/harness/tls-socket-leaks.test.ts new file mode 100644 index 000000000..64edfac25 --- /dev/null +++ b/tests/harness/tls-socket-leaks.test.ts @@ -0,0 +1,68 @@ +/* new tls.TLSSocket under LeakSanitizer. A TLS socket's transport holds + * its 'secure' and 'session' listeners, which often capture the socket; + * every socket that closes, including one whose handshake fails, must drop + * them. The sanitized lanes otherwise run with detect_leaks=0, so this runs + * the TLSSocket programs with LeakSanitizer explicitly on. 7094's + * handshakes all fail. Linux only (Apple's ASan has no LeakSanitizer); + * runs in the SCRIPTC_SAN=1 lane. */ +import { execFile } from "node:child_process"; +import { createHash } from "node:crypto"; +import { mkdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { promisify } from "node:util"; +import { describe, expect, test } from "vitest"; +import { compile } from "@scriptc/compiler"; + +const execFileAsync = promisify(execFile); +const repoRoot = join(import.meta.dirname, "../.."); +const cacheDir = join(repoRoot, "node_modules/.cache/scriptc-tests"); +const sanitize = process.env["SCRIPTC_SAN"] === "1"; + +const programs = [ + "tests/corpus/7087-tls-socket-wrap.ts", + "tests/corpus/7088-tls-socket-connect-tunnel.ts", + "tests/corpus/7094-tls-socket-failed-handshakes.ts", +]; + +describe.skipIf(!sanitize || process.platform !== "linux")( + "tls.TLSSocket under LeakSanitizer", + () => { + test.each(programs)("%s reports no leaks", { timeout: 300_000 }, async (program) => { + const file = join(repoRoot, program); + const key = createHash("sha256") + .update(file) + .update(readFileSync(file)) + .update("san") + .digest("hex") + .slice(0, 16); + const outDir = join(cacheDir, `tls-socket-leaks-${key}`); + mkdirSync(outDir, { recursive: true }); + const result = await compile(file, { + outPath: join(outDir, "program"), + outDir, + sanitize: true, + backend: "llvm", + }); + if (!result.ok) { + throw new Error( + "program failed to compile:\n" + + result.diagnostics.map((d) => `${d.code}: ${d.message}`).join("\n"), + ); + } + const run = await execFileAsync(result.binaryPath, [], { + env: { ...process.env, ASAN_OPTIONS: "detect_leaks=1" }, + maxBuffer: 16 * 1024 * 1024, + }).catch((error: { code?: number; stdout?: string; stderr?: string }) => error); + expect(run.stderr).toBe(""); + expect("code" in run ? run.code : 0).toBe(0); + const expected = await execFileAsync( + process.execPath, + ["--no-warnings", "--experimental-strip-types", file], + { + maxBuffer: 16 * 1024 * 1024, + }, + ); + expect(run.stdout).toBe(expected.stdout); + }); + }, +); diff --git a/tests/harness/windows-differential.test.ts b/tests/harness/windows-differential.test.ts index 366820420..8d25d9b07 100644 --- a/tests/harness/windows-differential.test.ts +++ b/tests/harness/windows-differential.test.ts @@ -47,11 +47,12 @@ import { writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; -import { basename, join } from "node:path"; +import { basename, dirname, join } from "node:path"; import { promisify } from "node:util"; import { afterAll, beforeAll, describe, expect, test } from "vitest"; import ts5 from "typescript"; import { compile } from "@scriptc/compiler"; +import { tscJsxOracleEntry, wantsTscJsx } from "./jsx-oracle.js"; const execFileAsync = promisify(execFile); const enabled = process.env["SCRIPTC_WIN"] === "1"; @@ -343,11 +344,13 @@ async function scpToLane(paths: string[]): Promise { * type-strips .ts natively (same pinned version as the macOS lanes). */ async function runWindowsNode(file: string): Promise { const name = laneName(file); - const entry = wantsTscDecorators(file) - ? decOracleName(file) - : name === basename(file) - ? name - : `${name}\\${basename(file)}`; + const entry = wantsTscJsx(directiveHead(file)) + ? `${basename(dirname(tscJsxOracleEntry(file, cacheDir)))}\\main.js` + : wantsTscDecorators(file) + ? decOracleName(file) + : name === basename(file) + ? name + : `${name}\\${basename(file)}`; const transform = wantsTransformTypes(file) ? "--experimental-transform-types --disable-warning=ExperimentalWarning " : ""; @@ -366,7 +369,7 @@ async function runWindowsNode(file: string): Promise { function programInputs(file: string): string[] { if (!/\/main\.(ts|js|mjs|cjs)$/.test(file)) return [file]; return [ - ...ENTRY_EXTS.flatMap((ext) => globSync(join(file, `../**/*.${ext}`))), + ...[...ENTRY_EXTS, "tsx", "jsx"].flatMap((ext) => globSync(join(file, `../**/*.${ext}`))), ...globSync(join(file, "../**/tsconfig.json")), ...globSync(join(file, "../**/package.json")), ].sort(); @@ -403,7 +406,11 @@ async function shipProgram(file: string): Promise { const programRoot = /\/main\.(ts|js|mjs|cjs)$/.test(file) ? join(file, "..") : file; // Decorator programs additionally ship the tsc downlevel the oracle // executes (the compiler still eats the real source above). - const oracleExtra = wantsTscDecorators(file) ? [decOraclePath(file)] : []; + const oracleExtra = wantsTscJsx(directiveHead(file)) + ? [dirname(tscJsxOracleEntry(file, cacheDir))] + : wantsTscDecorators(file) + ? [decOraclePath(file)] + : []; await scpToLane([binary, programRoot, ...oracleExtra]); } diff --git a/tests/library-mode/reinit/lib.ts b/tests/library-mode/reinit/lib.ts index dad54090a..73e466f70 100644 --- a/tests/library-mode/reinit/lib.ts +++ b/tests/library-mode/reinit/lib.ts @@ -29,4 +29,22 @@ export function indexedUnicode(): number { return s.length + s.charCodeAt(n) + s.slice(n - 1, n + 2).length; } +// A symbol-keyed global access creates the global object before any read of +// `globalThis` in a session: the builtin names must still be fenced on the +// stored global object, in every session. +const probeKey = Symbol.for("scriptc.reinit"); +function stored(global: typeof globalThis): any { + return global; +} +export function globalFences(): string { + // @ts-expect-error: globalThis has no symbol index signature + const before: unknown = globalThis[probeKey]; + const view = stored(globalThis); + try { + return `${typeof before} ${typeof view.Reflect}`; + } catch { + return `${typeof before} fenced`; + } +} + console.log(`session start counter=${counter}`); diff --git a/tests/library-mode/reinit/probe.c b/tests/library-mode/reinit/probe.c index 8cd17be1e..409766d0d 100644 --- a/tests/library-mode/reinit/probe.c +++ b/tests/library-mode/reinit/probe.c @@ -12,6 +12,7 @@ extern double kr_bump(void); extern double kr_note(const uint8_t *p, size_t len); extern double kr_indexed_unicode(void); extern void kr_recall(const uint8_t **out, size_t *out_len); +extern void kr_global_fences(const uint8_t **out, size_t *out_len); static void sink(void *ctx, const uint8_t *msg, size_t len, uint64_t addr) { (void)ctx; (void)addr; @@ -30,6 +31,8 @@ static void session(void) { const uint8_t *s; size_t n; kr_recall(&s, &n); printf("recall: %.*s\n", (int)n, s); + kr_global_fences(&s, &n); + printf("globals: %.*s\n", (int)n, s); } int main(void) { diff --git a/tests/library-mode/reinit/profile.json b/tests/library-mode/reinit/profile.json index 620150db1..cfcfebc9a 100644 --- a/tests/library-mode/reinit/profile.json +++ b/tests/library-mode/reinit/profile.json @@ -14,6 +14,7 @@ { "export": "bump", "symbol": "kr_bump", "params": [], "returns": "f64" }, { "export": "note", "symbol": "kr_note", "params": ["string"], "returns": "f64" }, { "export": "recall", "symbol": "kr_recall", "params": [], "returns": "string" }, - { "export": "indexedUnicode", "symbol": "kr_indexed_unicode", "params": [], "returns": "f64" } + { "export": "indexedUnicode", "symbol": "kr_indexed_unicode", "params": [], "returns": "f64" }, + { "export": "globalFences", "symbol": "kr_global_fences", "params": [], "returns": "string" } ] }